PageRenderTime 188ms CodeModel.GetById 12ms RepoModel.GetById 0ms app.codeStats 1ms

/external/youtube-dl/youtube-dl

http://echo-nest-remix.googlecode.com/
#! | 3001 lines | 2559 code | 442 blank | 0 comment | 0 complexity | 21244e50e2f1f86210dba26274891286 MD5 | raw file
Possible License(s): BSD-3-Clause
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # Author: Ricardo Garcia Gonzalez
  4. # Author: Danny Colligan
  5. # Author: Benjamin Johnson
  6. # Author: Vasyl' Vavrychuk
  7. # Author: Witold Baryluk
  8. # Author: Pawe?‚ Paprota
  9. # Author: Gergely Imreh
  10. # License: Public domain code
  11. import cookielib
  12. import ctypes
  13. import datetime
  14. import email.utils
  15. import gzip
  16. import htmlentitydefs
  17. import httplib
  18. import locale
  19. import math
  20. import netrc
  21. import os
  22. import os.path
  23. import re
  24. import socket
  25. import string
  26. import StringIO
  27. import subprocess
  28. import sys
  29. import time
  30. import urllib
  31. import urllib2
  32. import zlib
  33. # parse_qs was moved from the cgi module to the urlparse module recently.
  34. try:
  35. from urlparse import parse_qs
  36. except ImportError:
  37. from cgi import parse_qs
  38. std_headers = {
  39. 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:2.0b11) Gecko/20100101 Firefox/4.0b11',
  40. 'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
  41. 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
  42. 'Accept-Encoding': 'gzip, deflate',
  43. 'Accept-Language': 'en-us,en;q=0.5',
  44. }
  45. simple_title_chars = string.ascii_letters.decode('ascii') + string.digits.decode('ascii')
  46. def preferredencoding():
  47. """Get preferred encoding.
  48. Returns the best encoding scheme for the system, based on
  49. locale.getpreferredencoding() and some further tweaks.
  50. """
  51. def yield_preferredencoding():
  52. try:
  53. pref = locale.getpreferredencoding()
  54. u'TEST'.encode(pref)
  55. except:
  56. pref = 'UTF-8'
  57. while True:
  58. yield pref
  59. return yield_preferredencoding().next()
  60. def htmlentity_transform(matchobj):
  61. """Transforms an HTML entity to a Unicode character.
  62. This function receives a match object and is intended to be used with
  63. the re.sub() function.
  64. """
  65. entity = matchobj.group(1)
  66. # Known non-numeric HTML entity
  67. if entity in htmlentitydefs.name2codepoint:
  68. return unichr(htmlentitydefs.name2codepoint[entity])
  69. # Unicode character
  70. mobj = re.match(ur'(?u)#(x?\d+)', entity)
  71. if mobj is not None:
  72. numstr = mobj.group(1)
  73. if numstr.startswith(u'x'):
  74. base = 16
  75. numstr = u'0%s' % numstr
  76. else:
  77. base = 10
  78. return unichr(long(numstr, base))
  79. # Unknown entity in name, return its literal representation
  80. return (u'&%s;' % entity)
  81. def sanitize_title(utitle):
  82. """Sanitizes a video title so it could be used as part of a filename."""
  83. utitle = re.sub(ur'(?u)&(.+?);', htmlentity_transform, utitle)
  84. return utitle.replace(unicode(os.sep), u'%')
  85. def sanitize_open(filename, open_mode):
  86. """Try to open the given filename, and slightly tweak it if this fails.
  87. Attempts to open the given filename. If this fails, it tries to change
  88. the filename slightly, step by step, until it's either able to open it
  89. or it fails and raises a final exception, like the standard open()
  90. function.
  91. It returns the tuple (stream, definitive_file_name).
  92. """
  93. try:
  94. if filename == u'-':
  95. if sys.platform == 'win32':
  96. import msvcrt
  97. msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
  98. return (sys.stdout, filename)
  99. stream = open(filename, open_mode)
  100. return (stream, filename)
  101. except (IOError, OSError), err:
  102. # In case of error, try to remove win32 forbidden chars
  103. filename = re.sub(ur'[/<>:"\|\?\*]', u'#', filename)
  104. # An exception here should be caught in the caller
  105. stream = open(filename, open_mode)
  106. return (stream, filename)
  107. def timeconvert(timestr):
  108. """Convert RFC 2822 defined time string into system timestamp"""
  109. timestamp = None
  110. timetuple = email.utils.parsedate_tz(timestr)
  111. if timetuple is not None:
  112. timestamp = email.utils.mktime_tz(timetuple)
  113. return timestamp
  114. class DownloadError(Exception):
  115. """Download Error exception.
  116. This exception may be thrown by FileDownloader objects if they are not
  117. configured to continue on errors. They will contain the appropriate
  118. error message.
  119. """
  120. pass
  121. class SameFileError(Exception):
  122. """Same File exception.
  123. This exception will be thrown by FileDownloader objects if they detect
  124. multiple files would have to be downloaded to the same file on disk.
  125. """
  126. pass
  127. class PostProcessingError(Exception):
  128. """Post Processing exception.
  129. This exception may be raised by PostProcessor's .run() method to
  130. indicate an error in the postprocessing task.
  131. """
  132. pass
  133. class UnavailableVideoError(Exception):
  134. """Unavailable Format exception.
  135. This exception will be thrown when a video is requested
  136. in a format that is not available for that video.
  137. """
  138. pass
  139. class ContentTooShortError(Exception):
  140. """Content Too Short exception.
  141. This exception may be raised by FileDownloader objects when a file they
  142. download is too small for what the server announced first, indicating
  143. the connection was probably interrupted.
  144. """
  145. # Both in bytes
  146. downloaded = None
  147. expected = None
  148. def __init__(self, downloaded, expected):
  149. self.downloaded = downloaded
  150. self.expected = expected
  151. class YoutubeDLHandler(urllib2.HTTPHandler):
  152. """Handler for HTTP requests and responses.
  153. This class, when installed with an OpenerDirector, automatically adds
  154. the standard headers to every HTTP request and handles gzipped and
  155. deflated responses from web servers. If compression is to be avoided in
  156. a particular request, the original request in the program code only has
  157. to include the HTTP header "Youtubedl-No-Compression", which will be
  158. removed before making the real request.
  159. Part of this code was copied from:
  160. http://techknack.net/python-urllib2-handlers/
  161. Andrew Rowls, the author of that code, agreed to release it to the
  162. public domain.
  163. """
  164. @staticmethod
  165. def deflate(data):
  166. try:
  167. return zlib.decompress(data, -zlib.MAX_WBITS)
  168. except zlib.error:
  169. return zlib.decompress(data)
  170. @staticmethod
  171. def addinfourl_wrapper(stream, headers, url, code):
  172. if hasattr(urllib2.addinfourl, 'getcode'):
  173. return urllib2.addinfourl(stream, headers, url, code)
  174. ret = urllib2.addinfourl(stream, headers, url)
  175. ret.code = code
  176. return ret
  177. def http_request(self, req):
  178. for h in std_headers:
  179. if h in req.headers:
  180. del req.headers[h]
  181. req.add_header(h, std_headers[h])
  182. if 'Youtubedl-no-compression' in req.headers:
  183. if 'Accept-encoding' in req.headers:
  184. del req.headers['Accept-encoding']
  185. del req.headers['Youtubedl-no-compression']
  186. return req
  187. def http_response(self, req, resp):
  188. old_resp = resp
  189. # gzip
  190. if resp.headers.get('Content-encoding', '') == 'gzip':
  191. gz = gzip.GzipFile(fileobj=StringIO.StringIO(resp.read()), mode='r')
  192. resp = self.addinfourl_wrapper(gz, old_resp.headers, old_resp.url, old_resp.code)
  193. resp.msg = old_resp.msg
  194. # deflate
  195. if resp.headers.get('Content-encoding', '') == 'deflate':
  196. gz = StringIO.StringIO(self.deflate(resp.read()))
  197. resp = self.addinfourl_wrapper(gz, old_resp.headers, old_resp.url, old_resp.code)
  198. resp.msg = old_resp.msg
  199. return resp
  200. class FileDownloader(object):
  201. """File Downloader class.
  202. File downloader objects are the ones responsible of downloading the
  203. actual video file and writing it to disk if the user has requested
  204. it, among some other tasks. In most cases there should be one per
  205. program. As, given a video URL, the downloader doesn't know how to
  206. extract all the needed information, task that InfoExtractors do, it
  207. has to pass the URL to one of them.
  208. For this, file downloader objects have a method that allows
  209. InfoExtractors to be registered in a given order. When it is passed
  210. a URL, the file downloader handles it to the first InfoExtractor it
  211. finds that reports being able to handle it. The InfoExtractor extracts
  212. all the information about the video or videos the URL refers to, and
  213. asks the FileDownloader to process the video information, possibly
  214. downloading the video.
  215. File downloaders accept a lot of parameters. In order not to saturate
  216. the object constructor with arguments, it receives a dictionary of
  217. options instead. These options are available through the params
  218. attribute for the InfoExtractors to use. The FileDownloader also
  219. registers itself as the downloader in charge for the InfoExtractors
  220. that are added to it, so this is a "mutual registration".
  221. Available options:
  222. username: Username for authentication purposes.
  223. password: Password for authentication purposes.
  224. usenetrc: Use netrc for authentication instead.
  225. quiet: Do not print messages to stdout.
  226. forceurl: Force printing final URL.
  227. forcetitle: Force printing title.
  228. forcethumbnail: Force printing thumbnail URL.
  229. forcedescription: Force printing description.
  230. forcefilename: Force printing final filename.
  231. simulate: Do not download the video files.
  232. format: Video format code.
  233. format_limit: Highest quality format to try.
  234. outtmpl: Template for output names.
  235. ignoreerrors: Do not stop on download errors.
  236. ratelimit: Download speed limit, in bytes/sec.
  237. nooverwrites: Prevent overwriting files.
  238. retries: Number of times to retry for HTTP error 5xx
  239. continuedl: Try to continue downloads if possible.
  240. noprogress: Do not print the progress bar.
  241. playliststart: Playlist item to start at.
  242. playlistend: Playlist item to end at.
  243. logtostderr: Log messages to stderr instead of stdout.
  244. consoletitle: Display progress in console window's titlebar.
  245. nopart: Do not use temporary .part files.
  246. updatetime: Use the Last-modified header to set output file timestamps.
  247. """
  248. params = None
  249. _ies = []
  250. _pps = []
  251. _download_retcode = None
  252. _num_downloads = None
  253. _screen_file = None
  254. def __init__(self, params):
  255. """Create a FileDownloader object with the given options."""
  256. self._ies = []
  257. self._pps = []
  258. self._download_retcode = 0
  259. self._num_downloads = 0
  260. self._screen_file = [sys.stdout, sys.stderr][params.get('logtostderr', False)]
  261. self.params = params
  262. @staticmethod
  263. def pmkdir(filename):
  264. """Create directory components in filename. Similar to Unix "mkdir -p"."""
  265. components = filename.split(os.sep)
  266. aggregate = [os.sep.join(components[0:x]) for x in xrange(1, len(components))]
  267. aggregate = ['%s%s' % (x, os.sep) for x in aggregate] # Finish names with separator
  268. for dir in aggregate:
  269. if not os.path.exists(dir):
  270. os.mkdir(dir)
  271. @staticmethod
  272. def format_bytes(bytes):
  273. if bytes is None:
  274. return 'N/A'
  275. if type(bytes) is str:
  276. bytes = float(bytes)
  277. if bytes == 0.0:
  278. exponent = 0
  279. else:
  280. exponent = long(math.log(bytes, 1024.0))
  281. suffix = 'bkMGTPEZY'[exponent]
  282. converted = float(bytes) / float(1024**exponent)
  283. return '%.2f%s' % (converted, suffix)
  284. @staticmethod
  285. def calc_percent(byte_counter, data_len):
  286. if data_len is None:
  287. return '---.-%'
  288. return '%6s' % ('%3.1f%%' % (float(byte_counter) / float(data_len) * 100.0))
  289. @staticmethod
  290. def calc_eta(start, now, total, current):
  291. if total is None:
  292. return '--:--'
  293. dif = now - start
  294. if current == 0 or dif < 0.001: # One millisecond
  295. return '--:--'
  296. rate = float(current) / dif
  297. eta = long((float(total) - float(current)) / rate)
  298. (eta_mins, eta_secs) = divmod(eta, 60)
  299. if eta_mins > 99:
  300. return '--:--'
  301. return '%02d:%02d' % (eta_mins, eta_secs)
  302. @staticmethod
  303. def calc_speed(start, now, bytes):
  304. dif = now - start
  305. if bytes == 0 or dif < 0.001: # One millisecond
  306. return '%10s' % '---b/s'
  307. return '%10s' % ('%s/s' % FileDownloader.format_bytes(float(bytes) / dif))
  308. @staticmethod
  309. def best_block_size(elapsed_time, bytes):
  310. new_min = max(bytes / 2.0, 1.0)
  311. new_max = min(max(bytes * 2.0, 1.0), 4194304) # Do not surpass 4 MB
  312. if elapsed_time < 0.001:
  313. return long(new_max)
  314. rate = bytes / elapsed_time
  315. if rate > new_max:
  316. return long(new_max)
  317. if rate < new_min:
  318. return long(new_min)
  319. return long(rate)
  320. @staticmethod
  321. def parse_bytes(bytestr):
  322. """Parse a string indicating a byte quantity into a long integer."""
  323. matchobj = re.match(r'(?i)^(\d+(?:\.\d+)?)([kMGTPEZY]?)$', bytestr)
  324. if matchobj is None:
  325. return None
  326. number = float(matchobj.group(1))
  327. multiplier = 1024.0 ** 'bkmgtpezy'.index(matchobj.group(2).lower())
  328. return long(round(number * multiplier))
  329. def add_info_extractor(self, ie):
  330. """Add an InfoExtractor object to the end of the list."""
  331. self._ies.append(ie)
  332. ie.set_downloader(self)
  333. def add_post_processor(self, pp):
  334. """Add a PostProcessor object to the end of the chain."""
  335. self._pps.append(pp)
  336. pp.set_downloader(self)
  337. def to_screen(self, message, skip_eol=False, ignore_encoding_errors=False):
  338. """Print message to stdout if not in quiet mode."""
  339. try:
  340. if not self.params.get('quiet', False):
  341. terminator = [u'\n', u''][skip_eol]
  342. print >>self._screen_file, (u'%s%s' % (message, terminator)).encode(preferredencoding()),
  343. self._screen_file.flush()
  344. except (UnicodeEncodeError), err:
  345. if not ignore_encoding_errors:
  346. raise
  347. def to_stderr(self, message):
  348. """Print message to stderr."""
  349. print >>sys.stderr, message.encode(preferredencoding())
  350. def to_cons_title(self, message):
  351. """Set console/terminal window title to message."""
  352. if not self.params.get('consoletitle', False):
  353. return
  354. if os.name == 'nt' and ctypes.windll.kernel32.GetConsoleWindow():
  355. # c_wchar_p() might not be necessary if `message` is
  356. # already of type unicode()
  357. ctypes.windll.kernel32.SetConsoleTitleW(ctypes.c_wchar_p(message))
  358. elif 'TERM' in os.environ:
  359. sys.stderr.write('\033]0;%s\007' % message.encode(preferredencoding()))
  360. def fixed_template(self):
  361. """Checks if the output template is fixed."""
  362. return (re.search(ur'(?u)%\(.+?\)s', self.params['outtmpl']) is None)
  363. def trouble(self, message=None):
  364. """Determine action to take when a download problem appears.
  365. Depending on if the downloader has been configured to ignore
  366. download errors or not, this method may throw an exception or
  367. not when errors are found, after printing the message.
  368. """
  369. if message is not None:
  370. self.to_stderr(message)
  371. if not self.params.get('ignoreerrors', False):
  372. raise DownloadError(message)
  373. self._download_retcode = 1
  374. def slow_down(self, start_time, byte_counter):
  375. """Sleep if the download speed is over the rate limit."""
  376. rate_limit = self.params.get('ratelimit', None)
  377. if rate_limit is None or byte_counter == 0:
  378. return
  379. now = time.time()
  380. elapsed = now - start_time
  381. if elapsed <= 0.0:
  382. return
  383. speed = float(byte_counter) / elapsed
  384. if speed > rate_limit:
  385. time.sleep((byte_counter - rate_limit * (now - start_time)) / rate_limit)
  386. def temp_name(self, filename):
  387. """Returns a temporary filename for the given filename."""
  388. if self.params.get('nopart', False) or filename == u'-' or \
  389. (os.path.exists(filename) and not os.path.isfile(filename)):
  390. return filename
  391. return filename + u'.part'
  392. def undo_temp_name(self, filename):
  393. if filename.endswith(u'.part'):
  394. return filename[:-len(u'.part')]
  395. return filename
  396. def try_rename(self, old_filename, new_filename):
  397. try:
  398. if old_filename == new_filename:
  399. return
  400. os.rename(old_filename, new_filename)
  401. except (IOError, OSError), err:
  402. self.trouble(u'ERROR: unable to rename file')
  403. def try_utime(self, filename, last_modified_hdr):
  404. """Try to set the last-modified time of the given file."""
  405. if last_modified_hdr is None:
  406. return
  407. if not os.path.isfile(filename):
  408. return
  409. timestr = last_modified_hdr
  410. if timestr is None:
  411. return
  412. filetime = timeconvert(timestr)
  413. if filetime is None:
  414. return
  415. try:
  416. os.utime(filename,(time.time(), filetime))
  417. except:
  418. pass
  419. def report_destination(self, filename):
  420. """Report destination filename."""
  421. self.to_screen(u'[download] Destination: %s' % filename, ignore_encoding_errors=True)
  422. def report_progress(self, percent_str, data_len_str, speed_str, eta_str):
  423. """Report download progress."""
  424. if self.params.get('noprogress', False):
  425. return
  426. self.to_screen(u'\r[download] %s of %s at %s ETA %s' %
  427. (percent_str, data_len_str, speed_str, eta_str), skip_eol=True)
  428. self.to_cons_title(u'youtube-dl - %s of %s at %s ETA %s' %
  429. (percent_str.strip(), data_len_str.strip(), speed_str.strip(), eta_str.strip()))
  430. def report_resuming_byte(self, resume_len):
  431. """Report attempt to resume at given byte."""
  432. self.to_screen(u'[download] Resuming download at byte %s' % resume_len)
  433. def report_retry(self, count, retries):
  434. """Report retry in case of HTTP error 5xx"""
  435. self.to_screen(u'[download] Got server HTTP error. Retrying (attempt %d of %d)...' % (count, retries))
  436. def report_file_already_downloaded(self, file_name):
  437. """Report file has already been fully downloaded."""
  438. try:
  439. self.to_screen(u'[download] %s has already been downloaded' % file_name)
  440. except (UnicodeEncodeError), err:
  441. self.to_screen(u'[download] The file has already been downloaded')
  442. def report_unable_to_resume(self):
  443. """Report it was impossible to resume download."""
  444. self.to_screen(u'[download] Unable to resume')
  445. def report_finish(self):
  446. """Report download finished."""
  447. if self.params.get('noprogress', False):
  448. self.to_screen(u'[download] Download completed')
  449. else:
  450. self.to_screen(u'')
  451. def increment_downloads(self):
  452. """Increment the ordinal that assigns a number to each file."""
  453. self._num_downloads += 1
  454. def prepare_filename(self, info_dict):
  455. """Generate the output filename."""
  456. try:
  457. template_dict = dict(info_dict)
  458. template_dict['epoch'] = unicode(long(time.time()))
  459. template_dict['autonumber'] = unicode('%05d' % self._num_downloads)
  460. filename = self.params['outtmpl'] % template_dict
  461. return filename
  462. except (ValueError, KeyError), err:
  463. self.trouble(u'ERROR: invalid system charset or erroneous output template')
  464. return None
  465. def process_info(self, info_dict):
  466. """Process a single dictionary returned by an InfoExtractor."""
  467. filename = self.prepare_filename(info_dict)
  468. # Do nothing else if in simulate mode
  469. if self.params.get('simulate', False):
  470. # Forced printings
  471. if self.params.get('forcetitle', False):
  472. print info_dict['title'].encode(preferredencoding(), 'xmlcharrefreplace')
  473. if self.params.get('forceurl', False):
  474. print info_dict['url'].encode(preferredencoding(), 'xmlcharrefreplace')
  475. if self.params.get('forcethumbnail', False) and 'thumbnail' in info_dict:
  476. print info_dict['thumbnail'].encode(preferredencoding(), 'xmlcharrefreplace')
  477. if self.params.get('forcedescription', False) and 'description' in info_dict:
  478. print info_dict['description'].encode(preferredencoding(), 'xmlcharrefreplace')
  479. if self.params.get('forcefilename', False) and filename is not None:
  480. print filename.encode(preferredencoding(), 'xmlcharrefreplace')
  481. return
  482. if filename is None:
  483. return
  484. if self.params.get('nooverwrites', False) and os.path.exists(filename):
  485. self.to_stderr(u'WARNING: file exists and will be skipped')
  486. return
  487. try:
  488. self.pmkdir(filename)
  489. except (OSError, IOError), err:
  490. self.trouble(u'ERROR: unable to create directories: %s' % str(err))
  491. return
  492. try:
  493. success = self._do_download(filename, info_dict['url'].encode('utf-8'), info_dict.get('player_url', None))
  494. except (OSError, IOError), err:
  495. raise UnavailableVideoError
  496. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  497. self.trouble(u'ERROR: unable to download video data: %s' % str(err))
  498. return
  499. except (ContentTooShortError, ), err:
  500. self.trouble(u'ERROR: content too short (expected %s bytes and served %s)' % (err.expected, err.downloaded))
  501. return
  502. if success:
  503. try:
  504. self.post_process(filename, info_dict)
  505. except (PostProcessingError), err:
  506. self.trouble(u'ERROR: postprocessing: %s' % str(err))
  507. return
  508. def download(self, url_list):
  509. """Download a given list of URLs."""
  510. if len(url_list) > 1 and self.fixed_template():
  511. raise SameFileError(self.params['outtmpl'])
  512. for url in url_list:
  513. suitable_found = False
  514. for ie in self._ies:
  515. # Go to next InfoExtractor if not suitable
  516. if not ie.suitable(url):
  517. continue
  518. # Suitable InfoExtractor found
  519. suitable_found = True
  520. # Extract information from URL and process it
  521. ie.extract(url)
  522. # Suitable InfoExtractor had been found; go to next URL
  523. break
  524. if not suitable_found:
  525. self.trouble(u'ERROR: no suitable InfoExtractor: %s' % url)
  526. return self._download_retcode
  527. def post_process(self, filename, ie_info):
  528. """Run the postprocessing chain on the given file."""
  529. info = dict(ie_info)
  530. info['filepath'] = filename
  531. for pp in self._pps:
  532. info = pp.run(info)
  533. if info is None:
  534. break
  535. def _download_with_rtmpdump(self, filename, url, player_url):
  536. self.report_destination(filename)
  537. tmpfilename = self.temp_name(filename)
  538. # Check for rtmpdump first
  539. try:
  540. subprocess.call(['rtmpdump', '-h'], stdout=(file(os.path.devnull, 'w')), stderr=subprocess.STDOUT)
  541. except (OSError, IOError):
  542. self.trouble(u'ERROR: RTMP download detected but "rtmpdump" could not be run')
  543. return False
  544. # Download using rtmpdump. rtmpdump returns exit code 2 when
  545. # the connection was interrumpted and resuming appears to be
  546. # possible. This is part of rtmpdump's normal usage, AFAIK.
  547. basic_args = ['rtmpdump', '-q'] + [[], ['-W', player_url]][player_url is not None] + ['-r', url, '-o', tmpfilename]
  548. retval = subprocess.call(basic_args + [[], ['-e', '-k', '1']][self.params.get('continuedl', False)])
  549. while retval == 2 or retval == 1:
  550. prevsize = os.path.getsize(tmpfilename)
  551. self.to_screen(u'\r[rtmpdump] %s bytes' % prevsize, skip_eol=True)
  552. time.sleep(5.0) # This seems to be needed
  553. retval = subprocess.call(basic_args + ['-e'] + [[], ['-k', '1']][retval == 1])
  554. cursize = os.path.getsize(tmpfilename)
  555. if prevsize == cursize and retval == 1:
  556. break
  557. if retval == 0:
  558. self.to_screen(u'\r[rtmpdump] %s bytes' % os.path.getsize(tmpfilename))
  559. self.try_rename(tmpfilename, filename)
  560. return True
  561. else:
  562. self.trouble(u'\nERROR: rtmpdump exited with code %d' % retval)
  563. return False
  564. def _do_download(self, filename, url, player_url):
  565. # Check file already present
  566. if self.params.get('continuedl', False) and os.path.isfile(filename) and not self.params.get('nopart', False):
  567. self.report_file_already_downloaded(filename)
  568. return True
  569. # Attempt to download using rtmpdump
  570. if url.startswith('rtmp'):
  571. return self._download_with_rtmpdump(filename, url, player_url)
  572. tmpfilename = self.temp_name(filename)
  573. stream = None
  574. open_mode = 'wb'
  575. # Do not include the Accept-Encoding header
  576. headers = {'Youtubedl-no-compression': 'True'}
  577. basic_request = urllib2.Request(url, None, headers)
  578. request = urllib2.Request(url, None, headers)
  579. # Establish possible resume length
  580. if os.path.isfile(tmpfilename):
  581. resume_len = os.path.getsize(tmpfilename)
  582. else:
  583. resume_len = 0
  584. # Request parameters in case of being able to resume
  585. if self.params.get('continuedl', False) and resume_len != 0:
  586. self.report_resuming_byte(resume_len)
  587. request.add_header('Range','bytes=%d-' % resume_len)
  588. open_mode = 'ab'
  589. count = 0
  590. retries = self.params.get('retries', 0)
  591. while count <= retries:
  592. # Establish connection
  593. try:
  594. data = urllib2.urlopen(request)
  595. break
  596. except (urllib2.HTTPError, ), err:
  597. if (err.code < 500 or err.code >= 600) and err.code != 416:
  598. # Unexpected HTTP error
  599. raise
  600. elif err.code == 416:
  601. # Unable to resume (requested range not satisfiable)
  602. try:
  603. # Open the connection again without the range header
  604. data = urllib2.urlopen(basic_request)
  605. content_length = data.info()['Content-Length']
  606. except (urllib2.HTTPError, ), err:
  607. if err.code < 500 or err.code >= 600:
  608. raise
  609. else:
  610. # Examine the reported length
  611. if (content_length is not None and
  612. (resume_len - 100 < long(content_length) < resume_len + 100)):
  613. # The file had already been fully downloaded.
  614. # Explanation to the above condition: in issue #175 it was revealed that
  615. # YouTube sometimes adds or removes a few bytes from the end of the file,
  616. # changing the file size slightly and causing problems for some users. So
  617. # I decided to implement a suggested change and consider the file
  618. # completely downloaded if the file size differs less than 100 bytes from
  619. # the one in the hard drive.
  620. self.report_file_already_downloaded(filename)
  621. self.try_rename(tmpfilename, filename)
  622. return True
  623. else:
  624. # The length does not match, we start the download over
  625. self.report_unable_to_resume()
  626. open_mode = 'wb'
  627. break
  628. # Retry
  629. count += 1
  630. if count <= retries:
  631. self.report_retry(count, retries)
  632. if count > retries:
  633. self.trouble(u'ERROR: giving up after %s retries' % retries)
  634. return False
  635. data_len = data.info().get('Content-length', None)
  636. if data_len is not None:
  637. data_len = long(data_len) + resume_len
  638. data_len_str = self.format_bytes(data_len)
  639. byte_counter = 0 + resume_len
  640. block_size = 1024
  641. start = time.time()
  642. while True:
  643. # Download and write
  644. before = time.time()
  645. data_block = data.read(block_size)
  646. after = time.time()
  647. if len(data_block) == 0:
  648. break
  649. byte_counter += len(data_block)
  650. # Open file just in time
  651. if stream is None:
  652. try:
  653. (stream, tmpfilename) = sanitize_open(tmpfilename, open_mode)
  654. filename = self.undo_temp_name(tmpfilename)
  655. self.report_destination(filename)
  656. except (OSError, IOError), err:
  657. self.trouble(u'ERROR: unable to open for writing: %s' % str(err))
  658. return False
  659. try:
  660. stream.write(data_block)
  661. except (IOError, OSError), err:
  662. self.trouble(u'\nERROR: unable to write data: %s' % str(err))
  663. return False
  664. block_size = self.best_block_size(after - before, len(data_block))
  665. # Progress message
  666. percent_str = self.calc_percent(byte_counter, data_len)
  667. eta_str = self.calc_eta(start, time.time(), data_len - resume_len, byte_counter - resume_len)
  668. speed_str = self.calc_speed(start, time.time(), byte_counter - resume_len)
  669. self.report_progress(percent_str, data_len_str, speed_str, eta_str)
  670. # Apply rate limit
  671. self.slow_down(start, byte_counter - resume_len)
  672. stream.close()
  673. self.report_finish()
  674. if data_len is not None and byte_counter != data_len:
  675. raise ContentTooShortError(byte_counter, long(data_len))
  676. self.try_rename(tmpfilename, filename)
  677. # Update file modification time
  678. if self.params.get('updatetime', True):
  679. self.try_utime(filename, data.info().get('last-modified', None))
  680. return True
  681. class InfoExtractor(object):
  682. """Information Extractor class.
  683. Information extractors are the classes that, given a URL, extract
  684. information from the video (or videos) the URL refers to. This
  685. information includes the real video URL, the video title and simplified
  686. title, author and others. The information is stored in a dictionary
  687. which is then passed to the FileDownloader. The FileDownloader
  688. processes this information possibly downloading the video to the file
  689. system, among other possible outcomes. The dictionaries must include
  690. the following fields:
  691. id: Video identifier.
  692. url: Final video URL.
  693. uploader: Nickname of the video uploader.
  694. title: Literal title.
  695. stitle: Simplified title.
  696. ext: Video filename extension.
  697. format: Video format.
  698. player_url: SWF Player URL (may be None).
  699. The following fields are optional. Their primary purpose is to allow
  700. youtube-dl to serve as the backend for a video search function, such
  701. as the one in youtube2mp3. They are only used when their respective
  702. forced printing functions are called:
  703. thumbnail: Full URL to a video thumbnail image.
  704. description: One-line video description.
  705. Subclasses of this one should re-define the _real_initialize() and
  706. _real_extract() methods, as well as the suitable() static method.
  707. Probably, they should also be instantiated and added to the main
  708. downloader.
  709. """
  710. _ready = False
  711. _downloader = None
  712. def __init__(self, downloader=None):
  713. """Constructor. Receives an optional downloader."""
  714. self._ready = False
  715. self.set_downloader(downloader)
  716. @staticmethod
  717. def suitable(url):
  718. """Receives a URL and returns True if suitable for this IE."""
  719. return False
  720. def initialize(self):
  721. """Initializes an instance (authentication, etc)."""
  722. if not self._ready:
  723. self._real_initialize()
  724. self._ready = True
  725. def extract(self, url):
  726. """Extracts URL information and returns it in list of dicts."""
  727. self.initialize()
  728. return self._real_extract(url)
  729. def set_downloader(self, downloader):
  730. """Sets the downloader for this IE."""
  731. self._downloader = downloader
  732. def _real_initialize(self):
  733. """Real initialization process. Redefine in subclasses."""
  734. pass
  735. def _real_extract(self, url):
  736. """Real extraction process. Redefine in subclasses."""
  737. pass
  738. class YoutubeIE(InfoExtractor):
  739. """Information extractor for youtube.com."""
  740. _VALID_URL = r'^((?:https?://)?(?:youtu\.be/|(?:\w+\.)?youtube(?:-nocookie)?\.com/)(?:(?:(?:v|embed|e)/)|(?:(?:watch(?:_popup)?(?:\.php)?)?(?:\?|#!?)(?:.+&)?v=)))?([0-9A-Za-z_-]+)(?(1).+)?$'
  741. _LANG_URL = r'http://www.youtube.com/?hl=en&persist_hl=1&gl=US&persist_gl=1&opt_out_ackd=1'
  742. _LOGIN_URL = 'https://www.youtube.com/signup?next=/&gl=US&hl=en'
  743. _AGE_URL = 'http://www.youtube.com/verify_age?next_url=/&gl=US&hl=en'
  744. _NETRC_MACHINE = 'youtube'
  745. # Listed in order of quality
  746. _available_formats = ['38', '37', '22', '45', '35', '34', '43', '18', '6', '5', '17', '13']
  747. _video_extensions = {
  748. '13': '3gp',
  749. '17': 'mp4',
  750. '18': 'mp4',
  751. '22': 'mp4',
  752. '37': 'mp4',
  753. '38': 'video', # You actually don't know if this will be MOV, AVI or whatever
  754. '43': 'webm',
  755. '45': 'webm',
  756. }
  757. @staticmethod
  758. def suitable(url):
  759. return (re.match(YoutubeIE._VALID_URL, url) is not None)
  760. def report_lang(self):
  761. """Report attempt to set language."""
  762. self._downloader.to_screen(u'[youtube] Setting language')
  763. def report_login(self):
  764. """Report attempt to log in."""
  765. self._downloader.to_screen(u'[youtube] Logging in')
  766. def report_age_confirmation(self):
  767. """Report attempt to confirm age."""
  768. self._downloader.to_screen(u'[youtube] Confirming age')
  769. def report_video_webpage_download(self, video_id):
  770. """Report attempt to download video webpage."""
  771. self._downloader.to_screen(u'[youtube] %s: Downloading video webpage' % video_id)
  772. def report_video_info_webpage_download(self, video_id):
  773. """Report attempt to download video info webpage."""
  774. self._downloader.to_screen(u'[youtube] %s: Downloading video info webpage' % video_id)
  775. def report_information_extraction(self, video_id):
  776. """Report attempt to extract video information."""
  777. self._downloader.to_screen(u'[youtube] %s: Extracting video information' % video_id)
  778. def report_unavailable_format(self, video_id, format):
  779. """Report extracted video URL."""
  780. self._downloader.to_screen(u'[youtube] %s: Format %s not available' % (video_id, format))
  781. def report_rtmp_download(self):
  782. """Indicate the download will use the RTMP protocol."""
  783. self._downloader.to_screen(u'[youtube] RTMP download detected')
  784. def _real_initialize(self):
  785. if self._downloader is None:
  786. return
  787. username = None
  788. password = None
  789. downloader_params = self._downloader.params
  790. # Attempt to use provided username and password or .netrc data
  791. if downloader_params.get('username', None) is not None:
  792. username = downloader_params['username']
  793. password = downloader_params['password']
  794. elif downloader_params.get('usenetrc', False):
  795. try:
  796. info = netrc.netrc().authenticators(self._NETRC_MACHINE)
  797. if info is not None:
  798. username = info[0]
  799. password = info[2]
  800. else:
  801. raise netrc.NetrcParseError('No authenticators for %s' % self._NETRC_MACHINE)
  802. except (IOError, netrc.NetrcParseError), err:
  803. self._downloader.to_stderr(u'WARNING: parsing .netrc: %s' % str(err))
  804. return
  805. # Set language
  806. request = urllib2.Request(self._LANG_URL)
  807. try:
  808. self.report_lang()
  809. urllib2.urlopen(request).read()
  810. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  811. self._downloader.to_stderr(u'WARNING: unable to set language: %s' % str(err))
  812. return
  813. # No authentication to be performed
  814. if username is None:
  815. return
  816. # Log in
  817. login_form = {
  818. 'current_form': 'loginForm',
  819. 'next': '/',
  820. 'action_login': 'Log In',
  821. 'username': username,
  822. 'password': password,
  823. }
  824. request = urllib2.Request(self._LOGIN_URL, urllib.urlencode(login_form))
  825. try:
  826. self.report_login()
  827. login_results = urllib2.urlopen(request).read()
  828. if re.search(r'(?i)<form[^>]* name="loginForm"', login_results) is not None:
  829. self._downloader.to_stderr(u'WARNING: unable to log in: bad username or password')
  830. return
  831. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  832. self._downloader.to_stderr(u'WARNING: unable to log in: %s' % str(err))
  833. return
  834. # Confirm age
  835. age_form = {
  836. 'next_url': '/',
  837. 'action_confirm': 'Confirm',
  838. }
  839. request = urllib2.Request(self._AGE_URL, urllib.urlencode(age_form))
  840. try:
  841. self.report_age_confirmation()
  842. age_results = urllib2.urlopen(request).read()
  843. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  844. self._downloader.trouble(u'ERROR: unable to confirm age: %s' % str(err))
  845. return
  846. def _real_extract(self, url):
  847. # Extract video id from URL
  848. mobj = re.match(self._VALID_URL, url)
  849. if mobj is None:
  850. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  851. return
  852. video_id = mobj.group(2)
  853. # Get video webpage
  854. self.report_video_webpage_download(video_id)
  855. request = urllib2.Request('http://www.youtube.com/watch?v=%s&gl=US&hl=en&amp;has_verified=1' % video_id)
  856. try:
  857. video_webpage = urllib2.urlopen(request).read()
  858. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  859. self._downloader.trouble(u'ERROR: unable to download video webpage: %s' % str(err))
  860. return
  861. # Attempt to extract SWF player URL
  862. mobj = re.search(r'swfConfig.*?"(http:\\/\\/.*?watch.*?-.*?\.swf)"', video_webpage)
  863. if mobj is not None:
  864. player_url = re.sub(r'\\(.)', r'\1', mobj.group(1))
  865. else:
  866. player_url = None
  867. # Get video info
  868. self.report_video_info_webpage_download(video_id)
  869. for el_type in ['&el=embedded', '&el=detailpage', '&el=vevo', '']:
  870. video_info_url = ('http://www.youtube.com/get_video_info?&video_id=%s%s&ps=default&eurl=&gl=US&hl=en'
  871. % (video_id, el_type))
  872. request = urllib2.Request(video_info_url)
  873. try:
  874. video_info_webpage = urllib2.urlopen(request).read()
  875. video_info = parse_qs(video_info_webpage)
  876. if 'token' in video_info:
  877. break
  878. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  879. self._downloader.trouble(u'ERROR: unable to download video info webpage: %s' % str(err))
  880. return
  881. if 'token' not in video_info:
  882. if 'reason' in video_info:
  883. self._downloader.trouble(u'ERROR: YouTube said: %s' % video_info['reason'][0].decode('utf-8'))
  884. else:
  885. self._downloader.trouble(u'ERROR: "token" parameter not in video info for unknown reason')
  886. return
  887. # Start extracting information
  888. self.report_information_extraction(video_id)
  889. # uploader
  890. if 'author' not in video_info:
  891. self._downloader.trouble(u'ERROR: unable to extract uploader nickname')
  892. return
  893. video_uploader = urllib.unquote_plus(video_info['author'][0])
  894. # title
  895. if 'title' not in video_info:
  896. self._downloader.trouble(u'ERROR: unable to extract video title')
  897. return
  898. video_title = urllib.unquote_plus(video_info['title'][0])
  899. video_title = video_title.decode('utf-8')
  900. video_title = sanitize_title(video_title)
  901. # simplified title
  902. simple_title = re.sub(ur'(?u)([^%s]+)' % simple_title_chars, ur'_', video_title)
  903. simple_title = simple_title.strip(ur'_')
  904. # thumbnail image
  905. if 'thumbnail_url' not in video_info:
  906. self._downloader.trouble(u'WARNING: unable to extract video thumbnail')
  907. video_thumbnail = ''
  908. else: # don't panic if we can't find it
  909. video_thumbnail = urllib.unquote_plus(video_info['thumbnail_url'][0])
  910. # upload date
  911. upload_date = u'NA'
  912. mobj = re.search(r'id="eow-date.*?>(.*?)</span>', video_webpage, re.DOTALL)
  913. if mobj is not None:
  914. upload_date = ' '.join(re.sub(r'[/,-]', r' ', mobj.group(1)).split())
  915. format_expressions = ['%d %B %Y', '%B %d %Y', '%b %d %Y']
  916. for expression in format_expressions:
  917. try:
  918. upload_date = datetime.datetime.strptime(upload_date, expression).strftime('%Y%m%d')
  919. except:
  920. pass
  921. # description
  922. video_description = 'No description available.'
  923. if self._downloader.params.get('forcedescription', False):
  924. mobj = re.search(r'<meta name="description" content="(.*)"(?:\s*/)?>', video_webpage)
  925. if mobj is not None:
  926. video_description = mobj.group(1)
  927. # token
  928. video_token = urllib.unquote_plus(video_info['token'][0])
  929. # Decide which formats to download
  930. req_format = self._downloader.params.get('format', None)
  931. if 'fmt_url_map' in video_info and len(video_info['fmt_url_map']) >= 1 and ',' in video_info['fmt_url_map'][0]:
  932. url_map = dict(tuple(pair.split('|')) for pair in video_info['fmt_url_map'][0].split(','))
  933. format_limit = self._downloader.params.get('format_limit', None)
  934. if format_limit is not None and format_limit in self._available_formats:
  935. format_list = self._available_formats[self._available_formats.index(format_limit):]
  936. else:
  937. format_list = self._available_formats
  938. existing_formats = [x for x in format_list if x in url_map]
  939. if len(existing_formats) == 0:
  940. self._downloader.trouble(u'ERROR: no known formats available for video')
  941. return
  942. if req_format is None:
  943. video_url_list = [(existing_formats[0], url_map[existing_formats[0]])] # Best quality
  944. elif req_format == '-1':
  945. video_url_list = [(f, url_map[f]) for f in existing_formats] # All formats
  946. else:
  947. # Specific format
  948. if req_format not in url_map:
  949. self._downloader.trouble(u'ERROR: requested format not available')
  950. return
  951. video_url_list = [(req_format, url_map[req_format])] # Specific format
  952. elif 'conn' in video_info and video_info['conn'][0].startswith('rtmp'):
  953. self.report_rtmp_download()
  954. video_url_list = [(None, video_info['conn'][0])]
  955. else:
  956. self._downloader.trouble(u'ERROR: no fmt_url_map or conn information found in video info')
  957. return
  958. for format_param, video_real_url in video_url_list:
  959. # At this point we have a new video
  960. self._downloader.increment_downloads()
  961. # Extension
  962. video_extension = self._video_extensions.get(format_param, 'flv')
  963. # Find the video URL in fmt_url_map or conn paramters
  964. try:
  965. # Process video information
  966. self._downloader.process_info({
  967. 'id': video_id.decode('utf-8'),
  968. 'url': video_real_url.decode('utf-8'),
  969. 'uploader': video_uploader.decode('utf-8'),
  970. 'upload_date': upload_date,
  971. 'title': video_title,
  972. 'stitle': simple_title,
  973. 'ext': video_extension.decode('utf-8'),
  974. 'format': (format_param is None and u'NA' or format_param.decode('utf-8')),
  975. 'thumbnail': video_thumbnail.decode('utf-8'),
  976. 'description': video_description.decode('utf-8'),
  977. 'player_url': player_url,
  978. })
  979. except UnavailableVideoError, err:
  980. self._downloader.trouble(u'\nERROR: unable to download video')
  981. class MetacafeIE(InfoExtractor):
  982. """Information Extractor for metacafe.com."""
  983. _VALID_URL = r'(?:http://)?(?:www\.)?metacafe\.com/watch/([^/]+)/([^/]+)/.*'
  984. _DISCLAIMER = 'http://www.metacafe.com/family_filter/'
  985. _FILTER_POST = 'http://www.metacafe.com/f/index.php?inputType=filter&controllerGroup=user'
  986. _youtube_ie = None
  987. def __init__(self, youtube_ie, downloader=None):
  988. InfoExtractor.__init__(self, downloader)
  989. self._youtube_ie = youtube_ie
  990. @staticmethod
  991. def suitable(url):
  992. return (re.match(MetacafeIE._VALID_URL, url) is not None)
  993. def report_disclaimer(self):
  994. """Report disclaimer retrieval."""
  995. self._downloader.to_screen(u'[metacafe] Retrieving disclaimer')
  996. def report_age_confirmation(self):
  997. """Report attempt to confirm age."""
  998. self._downloader.to_screen(u'[metacafe] Confirming age')
  999. def report_download_webpage(self, video_id):
  1000. """Report webpage download."""
  1001. self._downloader.to_screen(u'[metacafe] %s: Downloading webpage' % video_id)
  1002. def report_extraction(self, video_id):
  1003. """Report information extraction."""
  1004. self._downloader.to_screen(u'[metacafe] %s: Extracting information' % video_id)
  1005. def _real_initialize(self):
  1006. # Retrieve disclaimer
  1007. request = urllib2.Request(self._DISCLAIMER)
  1008. try:
  1009. self.report_disclaimer()
  1010. disclaimer = urllib2.urlopen(request).read()
  1011. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1012. self._downloader.trouble(u'ERROR: unable to retrieve disclaimer: %s' % str(err))
  1013. return
  1014. # Confirm age
  1015. disclaimer_form = {
  1016. 'filters': '0',
  1017. 'submit': "Continue - I'm over 18",
  1018. }
  1019. request = urllib2.Request(self._FILTER_POST, urllib.urlencode(disclaimer_form))
  1020. try:
  1021. self.report_age_confirmation()
  1022. disclaimer = urllib2.urlopen(request).read()
  1023. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1024. self._downloader.trouble(u'ERROR: unable to confirm age: %s' % str(err))
  1025. return
  1026. def _real_extract(self, url):
  1027. # Extract id and simplified title from URL
  1028. mobj = re.match(self._VALID_URL, url)
  1029. if mobj is None:
  1030. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  1031. return
  1032. video_id = mobj.group(1)
  1033. # Check if video comes from YouTube
  1034. mobj2 = re.match(r'^yt-(.*)$', video_id)
  1035. if mobj2 is not None:
  1036. self._youtube_ie.extract('http://www.youtube.com/watch?v=%s' % mobj2.group(1))
  1037. return
  1038. # At this point we have a new video
  1039. self._downloader.increment_downloads()
  1040. simple_title = mobj.group(2).decode('utf-8')
  1041. # Retrieve video webpage to extract further information
  1042. request = urllib2.Request('http://www.metacafe.com/watch/%s/' % video_id)
  1043. try:
  1044. self.report_download_webpage(video_id)
  1045. webpage = urllib2.urlopen(request).read()
  1046. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1047. self._downloader.trouble(u'ERROR: unable retrieve video webpage: %s' % str(err))
  1048. return
  1049. # Extract URL, uploader and title from webpage
  1050. self.report_extraction(video_id)
  1051. mobj = re.search(r'(?m)&mediaURL=([^&]+)', webpage)
  1052. if mobj is not None:
  1053. mediaURL = urllib.unquote(mobj.group(1))
  1054. video_extension = mediaURL[-3:]
  1055. # Extract gdaKey if available
  1056. mobj = re.search(r'(?m)&gdaKey=(.*?)&', webpage)
  1057. if mobj is None:
  1058. video_url = mediaURL
  1059. else:
  1060. gdaKey = mobj.group(1)
  1061. video_url = '%s?__gda__=%s' % (mediaURL, gdaKey)
  1062. else:
  1063. mobj = re.search(r' name="flashvars" value="(.*?)"', webpage)
  1064. if mobj is None:
  1065. self._downloader.trouble(u'ERROR: unable to extract media URL')
  1066. return
  1067. vardict = parse_qs(mobj.group(1))
  1068. if 'mediaData' not in vardict:
  1069. self._downloader.trouble(u'ERROR: unable to extract media URL')
  1070. return
  1071. mobj = re.search(r'"mediaURL":"(http.*?)","key":"(.*?)"', vardict['mediaData'][0])
  1072. if mobj is None:
  1073. self._downloader.trouble(u'ERROR: unable to extract media URL')
  1074. return
  1075. mediaURL = mobj.group(1).replace('\\/', '/')
  1076. video_extension = mediaURL[-3:]
  1077. video_url = '%s?__gda__=%s' % (mediaURL, mobj.group(2))
  1078. mobj = re.search(r'(?im)<title>(.*) - Video</title>', webpage)
  1079. if mobj is None:
  1080. self._downloader.trouble(u'ERROR: unable to extract title')
  1081. return
  1082. video_title = mobj.group(1).decode('utf-8')
  1083. video_title = sanitize_title(video_title)
  1084. mobj = re.search(r'(?ms)By:\s*<a .*?>(.+?)<', webpage)
  1085. if mobj is None:
  1086. self._downloader.trouble(u'ERROR: unable to extract uploader nickname')
  1087. return
  1088. video_uploader = mobj.group(1)
  1089. try:
  1090. # Process video information
  1091. self._downloader.process_info({
  1092. 'id': video_id.decode('utf-8'),
  1093. 'url': video_url.decode('utf-8'),
  1094. 'uploader': video_uploader.decode('utf-8'),
  1095. 'upload_date': u'NA',
  1096. 'title': video_title,
  1097. 'stitle': simple_title,
  1098. 'ext': video_extension.decode('utf-8'),
  1099. 'format': u'NA',
  1100. 'player_url': None,
  1101. })
  1102. except UnavailableVideoError:
  1103. self._downloader.trouble(u'\nERROR: unable to download video')
  1104. class DailymotionIE(InfoExtractor):
  1105. """Information Extractor for Dailymotion"""
  1106. _VALID_URL = r'(?i)(?:https?://)?(?:www\.)?dailymotion\.[a-z]{2,3}/video/([^_/]+)_([^/]+)'
  1107. def __init__(self, downloader=None):
  1108. InfoExtractor.__init__(self, downloader)
  1109. @staticmethod
  1110. def suitable(url):
  1111. return (re.match(DailymotionIE._VALID_URL, url) is not None)
  1112. def report_download_webpage(self, video_id):
  1113. """Report webpage download."""
  1114. self._downloader.to_screen(u'[dailymotion] %s: Downloading webpage' % video_id)
  1115. def report_extraction(self, video_id):
  1116. """Report information extraction."""
  1117. self._downloader.to_screen(u'[dailymotion] %s: Extracting information' % video_id)
  1118. def _real_initialize(self):
  1119. return
  1120. def _real_extract(self, url):
  1121. # Extract id and simplified title from URL
  1122. mobj = re.match(self._VALID_URL, url)
  1123. if mobj is None:
  1124. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  1125. return
  1126. # At this point we have a new video
  1127. self._downloader.increment_downloads()
  1128. video_id = mobj.group(1)
  1129. simple_title = mobj.group(2).decode('utf-8')
  1130. video_extension = 'flv'
  1131. # Retrieve video webpage to extract further information
  1132. request = urllib2.Request(url)
  1133. try:
  1134. self.report_download_webpage(video_id)
  1135. webpage = urllib2.urlopen(request).read()
  1136. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1137. self._downloader.trouble(u'ERROR: unable retrieve video webpage: %s' % str(err))
  1138. return
  1139. # Extract URL, uploader and title from webpage
  1140. self.report_extraction(video_id)
  1141. mobj = re.search(r'(?i)addVariable\(\"video\"\s*,\s*\"([^\"]*)\"\)', webpage)
  1142. if mobj is None:
  1143. self._downloader.trouble(u'ERROR: unable to extract media URL')
  1144. return
  1145. mediaURL = urllib.unquote(mobj.group(1))
  1146. # if needed add http://www.dailymotion.com/ if relative URL
  1147. video_url = mediaURL
  1148. # '<meta\s+name="title"\s+content="Dailymotion\s*[:\-]\s*(.*?)"\s*\/\s*>'
  1149. mobj = re.search(r'(?im)<title>Dailymotion\s*[\-:]\s*(.+?)</title>', webpage)
  1150. if mobj is None:
  1151. self._downloader.trouble(u'ERROR: unable to extract title')
  1152. return
  1153. video_title = mobj.group(1).decode('utf-8')
  1154. video_title = sanitize_title(video_title)
  1155. mobj = re.search(r'(?im)<Attribute name="owner">(.+?)</Attribute>', webpage)
  1156. if mobj is None:
  1157. self._downloader.trouble(u'ERROR: unable to extract uploader nickname')
  1158. return
  1159. video_uploader = mobj.group(1)
  1160. try:
  1161. # Process video information
  1162. self._downloader.process_info({
  1163. 'id': video_id.decode('utf-8'),
  1164. 'url': video_url.decode('utf-8'),
  1165. 'uploader': video_uploader.decode('utf-8'),
  1166. 'upload_date': u'NA',
  1167. 'title': video_title,
  1168. 'stitle': simple_title,
  1169. 'ext': video_extension.decode('utf-8'),
  1170. 'format': u'NA',
  1171. 'player_url': None,
  1172. })
  1173. except UnavailableVideoError:
  1174. self._downloader.trouble(u'\nERROR: unable to download video')
  1175. class GoogleIE(InfoExtractor):
  1176. """Information extractor for video.google.com."""
  1177. _VALID_URL = r'(?:http://)?video\.google\.(?:com(?:\.au)?|co\.(?:uk|jp|kr|cr)|ca|de|es|fr|it|nl|pl)/videoplay\?docid=([^\&]+).*'
  1178. def __init__(self, downloader=None):
  1179. InfoExtractor.__init__(self, downloader)
  1180. @staticmethod
  1181. def suitable(url):
  1182. return (re.match(GoogleIE._VALID_URL, url) is not None)
  1183. def report_download_webpage(self, video_id):
  1184. """Report webpage download."""
  1185. self._downloader.to_screen(u'[video.google] %s: Downloading webpage' % video_id)
  1186. def report_extraction(self, video_id):
  1187. """Report information extraction."""
  1188. self._downloader.to_screen(u'[video.google] %s: Extracting information' % video_id)
  1189. def _real_initialize(self):
  1190. return
  1191. def _real_extract(self, url):
  1192. # Extract id from URL
  1193. mobj = re.match(self._VALID_URL, url)
  1194. if mobj is None:
  1195. self._downloader.trouble(u'ERROR: Invalid URL: %s' % url)
  1196. return
  1197. # At this point we have a new video
  1198. self._downloader.increment_downloads()
  1199. video_id = mobj.group(1)
  1200. video_extension = 'mp4'
  1201. # Retrieve video webpage to extract further information
  1202. request = urllib2.Request('http://video.google.com/videoplay?docid=%s&hl=en&oe=utf-8' % video_id)
  1203. try:
  1204. self.report_download_webpage(video_id)
  1205. webpage = urllib2.urlopen(request).read()
  1206. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1207. self._downloader.trouble(u'ERROR: Unable to retrieve video webpage: %s' % str(err))
  1208. return
  1209. # Extract URL, uploader, and title from webpage
  1210. self.report_extraction(video_id)
  1211. mobj = re.search(r"download_url:'([^']+)'", webpage)
  1212. if mobj is None:
  1213. video_extension = 'flv'
  1214. mobj = re.search(r"(?i)videoUrl\\x3d(.+?)\\x26", webpage)
  1215. if mobj is None:
  1216. self._downloader.trouble(u'ERROR: unable to extract media URL')
  1217. return
  1218. mediaURL = urllib.unquote(mobj.group(1))
  1219. mediaURL = mediaURL.replace('\\x3d', '\x3d')
  1220. mediaURL = mediaURL.replace('\\x26', '\x26')
  1221. video_url = mediaURL
  1222. mobj = re.search(r'<title>(.*)</title>', webpage)
  1223. if mobj is None:
  1224. self._downloader.trouble(u'ERROR: unable to extract title')
  1225. return
  1226. video_title = mobj.group(1).decode('utf-8')
  1227. video_title = sanitize_title(video_title)
  1228. simple_title = re.sub(ur'(?u)([^%s]+)' % simple_title_chars, ur'_', video_title)
  1229. # Extract video description
  1230. mobj = re.search(r'<span id=short-desc-content>([^<]*)</span>', webpage)
  1231. if mobj is None:
  1232. self._downloader.trouble(u'ERROR: unable to extract video description')
  1233. return
  1234. video_description = mobj.group(1).decode('utf-8')
  1235. if not video_description:
  1236. video_description = 'No description available.'
  1237. # Extract video thumbnail
  1238. if self._downloader.params.get('forcethumbnail', False):
  1239. request = urllib2.Request('http://video.google.com/videosearch?q=%s+site:video.google.com&hl=en' % abs(int(video_id)))
  1240. try:
  1241. webpage = urllib2.urlopen(request).read()
  1242. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1243. self._downloader.trouble(u'ERROR: Unable to retrieve video webpage: %s' % str(err))
  1244. return
  1245. mobj = re.search(r'<img class=thumbnail-img (?:.* )?src=(http.*)>', webpage)
  1246. if mobj is None:
  1247. self._downloader.trouble(u'ERROR: unable to extract video thumbnail')
  1248. return
  1249. video_thumbnail = mobj.group(1)
  1250. else: # we need something to pass to process_info
  1251. video_thumbnail = ''
  1252. try:
  1253. # Process video information
  1254. self._downloader.process_info({
  1255. 'id': video_id.decode('utf-8'),
  1256. 'url': video_url.decode('utf-8'),
  1257. 'uploader': u'NA',
  1258. 'upload_date': u'NA',
  1259. 'title': video_title,
  1260. 'stitle': simple_title,
  1261. 'ext': video_extension.decode('utf-8'),
  1262. 'format': u'NA',
  1263. 'player_url': None,
  1264. })
  1265. except UnavailableVideoError:
  1266. self._downloader.trouble(u'\nERROR: unable to download video')
  1267. class PhotobucketIE(InfoExtractor):
  1268. """Information extractor for photobucket.com."""
  1269. _VALID_URL = r'(?:http://)?(?:[a-z0-9]+\.)?photobucket\.com/.*[\?\&]current=(.*\.flv)'
  1270. def __init__(self, downloader=None):
  1271. InfoExtractor.__init__(self, downloader)
  1272. @staticmethod
  1273. def suitable(url):
  1274. return (re.match(PhotobucketIE._VALID_URL, url) is not None)
  1275. def report_download_webpage(self, video_id):
  1276. """Report webpage download."""
  1277. self._downloader.to_screen(u'[photobucket] %s: Downloading webpage' % video_id)
  1278. def report_extraction(self, video_id):
  1279. """Report information extraction."""
  1280. self._downloader.to_screen(u'[photobucket] %s: Extracting information' % video_id)
  1281. def _real_initialize(self):
  1282. return
  1283. def _real_extract(self, url):
  1284. # Extract id from URL
  1285. mobj = re.match(self._VALID_URL, url)
  1286. if mobj is None:
  1287. self._downloader.trouble(u'ERROR: Invalid URL: %s' % url)
  1288. return
  1289. # At this point we have a new video
  1290. self._downloader.increment_downloads()
  1291. video_id = mobj.group(1)
  1292. video_extension = 'flv'
  1293. # Retrieve video webpage to extract further information
  1294. request = urllib2.Request(url)
  1295. try:
  1296. self.report_download_webpage(video_id)
  1297. webpage = urllib2.urlopen(request).read()
  1298. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1299. self._downloader.trouble(u'ERROR: Unable to retrieve video webpage: %s' % str(err))
  1300. return
  1301. # Extract URL, uploader, and title from webpage
  1302. self.report_extraction(video_id)
  1303. mobj = re.search(r'<link rel="video_src" href=".*\?file=([^"]+)" />', webpage)
  1304. if mobj is None:
  1305. self._downloader.trouble(u'ERROR: unable to extract media URL')
  1306. return
  1307. mediaURL = urllib.unquote(mobj.group(1))
  1308. video_url = mediaURL
  1309. mobj = re.search(r'<title>(.*) video by (.*) - Photobucket</title>', webpage)
  1310. if mobj is None:
  1311. self._downloader.trouble(u'ERROR: unable to extract title')
  1312. return
  1313. video_title = mobj.group(1).decode('utf-8')
  1314. video_title = sanitize_title(video_title)
  1315. simple_title = re.sub(ur'(?u)([^%s]+)' % simple_title_chars, ur'_', video_title)
  1316. video_uploader = mobj.group(2).decode('utf-8')
  1317. try:
  1318. # Process video information
  1319. self._downloader.process_info({
  1320. 'id': video_id.decode('utf-8'),
  1321. 'url': video_url.decode('utf-8'),
  1322. 'uploader': video_uploader,
  1323. 'upload_date': u'NA',
  1324. 'title': video_title,
  1325. 'stitle': simple_title,
  1326. 'ext': video_extension.decode('utf-8'),
  1327. 'format': u'NA',
  1328. 'player_url': None,
  1329. })
  1330. except UnavailableVideoError:
  1331. self._downloader.trouble(u'\nERROR: unable to download video')
  1332. class YahooIE(InfoExtractor):
  1333. """Information extractor for video.yahoo.com."""
  1334. # _VALID_URL matches all Yahoo! Video URLs
  1335. # _VPAGE_URL matches only the extractable '/watch/' URLs
  1336. _VALID_URL = r'(?:http://)?(?:[a-z]+\.)?video\.yahoo\.com/(?:watch|network)/([0-9]+)(?:/|\?v=)([0-9]+)(?:[#\?].*)?'
  1337. _VPAGE_URL = r'(?:http://)?video\.yahoo\.com/watch/([0-9]+)/([0-9]+)(?:[#\?].*)?'
  1338. def __init__(self, downloader=None):
  1339. InfoExtractor.__init__(self, downloader)
  1340. @staticmethod
  1341. def suitable(url):
  1342. return (re.match(YahooIE._VALID_URL, url) is not None)
  1343. def report_download_webpage(self, video_id):
  1344. """Report webpage download."""
  1345. self._downloader.to_screen(u'[video.yahoo] %s: Downloading webpage' % video_id)
  1346. def report_extraction(self, video_id):
  1347. """Report information extraction."""
  1348. self._downloader.to_screen(u'[video.yahoo] %s: Extracting information' % video_id)
  1349. def _real_initialize(self):
  1350. return
  1351. def _real_extract(self, url, new_video=True):
  1352. # Extract ID from URL
  1353. mobj = re.match(self._VALID_URL, url)
  1354. if mobj is None:
  1355. self._downloader.trouble(u'ERROR: Invalid URL: %s' % url)
  1356. return
  1357. # At this point we have a new video
  1358. self._downloader.increment_downloads()
  1359. video_id = mobj.group(2)
  1360. video_extension = 'flv'
  1361. # Rewrite valid but non-extractable URLs as
  1362. # extractable English language /watch/ URLs
  1363. if re.match(self._VPAGE_URL, url) is None:
  1364. request = urllib2.Request(url)
  1365. try:
  1366. webpage = urllib2.urlopen(request).read()
  1367. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1368. self._downloader.trouble(u'ERROR: Unable to retrieve video webpage: %s' % str(err))
  1369. return
  1370. mobj = re.search(r'\("id", "([0-9]+)"\);', webpage)
  1371. if mobj is None:
  1372. self._downloader.trouble(u'ERROR: Unable to extract id field')
  1373. return
  1374. yahoo_id = mobj.group(1)
  1375. mobj = re.search(r'\("vid", "([0-9]+)"\);', webpage)
  1376. if mobj is None:
  1377. self._downloader.trouble(u'ERROR: Unable to extract vid field')
  1378. return
  1379. yahoo_vid = mobj.group(1)
  1380. url = 'http://video.yahoo.com/watch/%s/%s' % (yahoo_vid, yahoo_id)
  1381. return self._real_extract(url, new_video=False)
  1382. # Retrieve video webpage to extract further information
  1383. request = urllib2.Request(url)
  1384. try:
  1385. self.report_download_webpage(video_id)
  1386. webpage = urllib2.urlopen(request).read()
  1387. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1388. self._downloader.trouble(u'ERROR: Unable to retrieve video webpage: %s' % str(err))
  1389. return
  1390. # Extract uploader and title from webpage
  1391. self.report_extraction(video_id)
  1392. mobj = re.search(r'<meta name="title" content="(.*)" />', webpage)
  1393. if mobj is None:
  1394. self._downloader.trouble(u'ERROR: unable to extract video title')
  1395. return
  1396. video_title = mobj.group(1).decode('utf-8')
  1397. simple_title = re.sub(ur'(?u)([^%s]+)' % simple_title_chars, ur'_', video_title)
  1398. mobj = re.search(r'<h2 class="ti-5"><a href="http://video\.yahoo\.com/(people|profile)/[0-9]+" beacon=".*">(.*)</a></h2>', webpage)
  1399. if mobj is None:
  1400. self._downloader.trouble(u'ERROR: unable to extract video uploader')
  1401. return
  1402. video_uploader = mobj.group(1).decode('utf-8')
  1403. # Extract video thumbnail
  1404. mobj = re.search(r'<link rel="image_src" href="(.*)" />', webpage)
  1405. if mobj is None:
  1406. self._downloader.trouble(u'ERROR: unable to extract video thumbnail')
  1407. return
  1408. video_thumbnail = mobj.group(1).decode('utf-8')
  1409. # Extract video description
  1410. mobj = re.search(r'<meta name="description" content="(.*)" />', webpage)
  1411. if mobj is None:
  1412. self._downloader.trouble(u'ERROR: unable to extract video description')
  1413. return
  1414. video_description = mobj.group(1).decode('utf-8')
  1415. if not video_description: video_description = 'No description available.'
  1416. # Extract video height and width
  1417. mobj = re.search(r'<meta name="video_height" content="([0-9]+)" />', webpage)
  1418. if mobj is None:
  1419. self._downloader.trouble(u'ERROR: unable to extract video height')
  1420. return
  1421. yv_video_height = mobj.group(1)
  1422. mobj = re.search(r'<meta name="video_width" content="([0-9]+)" />', webpage)
  1423. if mobj is None:
  1424. self._downloader.trouble(u'ERROR: unable to extract video width')
  1425. return
  1426. yv_video_width = mobj.group(1)
  1427. # Retrieve video playlist to extract media URL
  1428. # I'm not completely sure what all these options are, but we
  1429. # seem to need most of them, otherwise the server sends a 401.
  1430. yv_lg = 'R0xx6idZnW2zlrKP8xxAIR' # not sure what this represents
  1431. yv_bitrate = '700' # according to Wikipedia this is hard-coded
  1432. request = urllib2.Request('http://cosmos.bcst.yahoo.com/up/yep/process/getPlaylistFOP.php?node_id=' + video_id +
  1433. '&tech=flash&mode=playlist&lg=' + yv_lg + '&bitrate=' + yv_bitrate + '&vidH=' + yv_video_height +
  1434. '&vidW=' + yv_video_width + '&swf=as3&rd=video.yahoo.com&tk=null&adsupported=v1,v2,&eventid=1301797')
  1435. try:
  1436. self.report_download_webpage(video_id)
  1437. webpage = urllib2.urlopen(request).read()
  1438. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1439. self._downloader.trouble(u'ERROR: Unable to retrieve video webpage: %s' % str(err))
  1440. return
  1441. # Extract media URL from playlist XML
  1442. mobj = re.search(r'<STREAM APP="(http://.*)" FULLPATH="/?(/.*\.flv\?[^"]*)"', webpage)
  1443. if mobj is None:
  1444. self._downloader.trouble(u'ERROR: Unable to extract media URL')
  1445. return
  1446. video_url = urllib.unquote(mobj.group(1) + mobj.group(2)).decode('utf-8')
  1447. video_url = re.sub(r'(?u)&(.+?);', htmlentity_transform, video_url)
  1448. try:
  1449. # Process video information
  1450. self._downloader.process_info({
  1451. 'id': video_id.decode('utf-8'),
  1452. 'url': video_url,
  1453. 'uploader': video_uploader,
  1454. 'upload_date': u'NA',
  1455. 'title': video_title,
  1456. 'stitle': simple_title,
  1457. 'ext': video_extension.decode('utf-8'),
  1458. 'thumbnail': video_thumbnail.decode('utf-8'),
  1459. 'description': video_description,
  1460. 'thumbnail': video_thumbnail,
  1461. 'description': video_description,
  1462. 'player_url': None,
  1463. })
  1464. except UnavailableVideoError:
  1465. self._downloader.trouble(u'\nERROR: unable to download video')
  1466. class GenericIE(InfoExtractor):
  1467. """Generic last-resort information extractor."""
  1468. def __init__(self, downloader=None):
  1469. InfoExtractor.__init__(self, downloader)
  1470. @staticmethod
  1471. def suitable(url):
  1472. return True
  1473. def report_download_webpage(self, video_id):
  1474. """Report webpage download."""
  1475. self._downloader.to_screen(u'WARNING: Falling back on generic information extractor.')
  1476. self._downloader.to_screen(u'[generic] %s: Downloading webpage' % video_id)
  1477. def report_extraction(self, video_id):
  1478. """Report information extraction."""
  1479. self._downloader.to_screen(u'[generic] %s: Extracting information' % video_id)
  1480. def _real_initialize(self):
  1481. return
  1482. def _real_extract(self, url):
  1483. # At this point we have a new video
  1484. self._downloader.increment_downloads()
  1485. video_id = url.split('/')[-1]
  1486. request = urllib2.Request(url)
  1487. try:
  1488. self.report_download_webpage(video_id)
  1489. webpage = urllib2.urlopen(request).read()
  1490. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1491. self._downloader.trouble(u'ERROR: Unable to retrieve video webpage: %s' % str(err))
  1492. return
  1493. except ValueError, err:
  1494. # since this is the last-resort InfoExtractor, if
  1495. # this error is thrown, it'll be thrown here
  1496. self._downloader.trouble(u'ERROR: Invalid URL: %s' % url)
  1497. return
  1498. self.report_extraction(video_id)
  1499. # Start with something easy: JW Player in SWFObject
  1500. mobj = re.search(r'flashvars: [\'"](?:.*&)?file=(http[^\'"&]*)', webpage)
  1501. if mobj is None:
  1502. # Broaden the search a little bit
  1503. mobj = re.search(r'[^A-Za-z0-9]?(?:file|source)=(http[^\'"&]*)', webpage)
  1504. if mobj is None:
  1505. self._downloader.trouble(u'ERROR: Invalid URL: %s' % url)
  1506. return
  1507. # It's possible that one of the regexes
  1508. # matched, but returned an empty group:
  1509. if mobj.group(1) is None:
  1510. self._downloader.trouble(u'ERROR: Invalid URL: %s' % url)
  1511. return
  1512. video_url = urllib.unquote(mobj.group(1))
  1513. video_id = os.path.basename(video_url)
  1514. # here's a fun little line of code for you:
  1515. video_extension = os.path.splitext(video_id)[1][1:]
  1516. video_id = os.path.splitext(video_id)[0]
  1517. # it's tempting to parse this further, but you would
  1518. # have to take into account all the variations like
  1519. # Video Title - Site Name
  1520. # Site Name | Video Title
  1521. # Video Title - Tagline | Site Name
  1522. # and so on and so forth; it's just not practical
  1523. mobj = re.search(r'<title>(.*)</title>', webpage)
  1524. if mobj is None:
  1525. self._downloader.trouble(u'ERROR: unable to extract title')
  1526. return
  1527. video_title = mobj.group(1).decode('utf-8')
  1528. video_title = sanitize_title(video_title)
  1529. simple_title = re.sub(ur'(?u)([^%s]+)' % simple_title_chars, ur'_', video_title)
  1530. # video uploader is domain name
  1531. mobj = re.match(r'(?:https?://)?([^/]*)/.*', url)
  1532. if mobj is None:
  1533. self._downloader.trouble(u'ERROR: unable to extract title')
  1534. return
  1535. video_uploader = mobj.group(1).decode('utf-8')
  1536. try:
  1537. # Process video information
  1538. self._downloader.process_info({
  1539. 'id': video_id.decode('utf-8'),
  1540. 'url': video_url.decode('utf-8'),
  1541. 'uploader': video_uploader,
  1542. 'upload_date': u'NA',
  1543. 'title': video_title,
  1544. 'stitle': simple_title,
  1545. 'ext': video_extension.decode('utf-8'),
  1546. 'format': u'NA',
  1547. 'player_url': None,
  1548. })
  1549. except UnavailableVideoError, err:
  1550. self._downloader.trouble(u'\nERROR: unable to download video')
  1551. class YoutubeSearchIE(InfoExtractor):
  1552. """Information Extractor for YouTube search queries."""
  1553. _VALID_QUERY = r'ytsearch(\d+|all)?:[\s\S]+'
  1554. _TEMPLATE_URL = 'http://www.youtube.com/results?search_query=%s&page=%s&gl=US&hl=en'
  1555. _VIDEO_INDICATOR = r'href="/watch\?v=.+?"'
  1556. _MORE_PAGES_INDICATOR = r'(?m)>\s*Next\s*</a>'
  1557. _youtube_ie = None
  1558. _max_youtube_results = 1000
  1559. def __init__(self, youtube_ie, downloader=None):
  1560. InfoExtractor.__init__(self, downloader)
  1561. self._youtube_ie = youtube_ie
  1562. @staticmethod
  1563. def suitable(url):
  1564. return (re.match(YoutubeSearchIE._VALID_QUERY, url) is not None)
  1565. def report_download_page(self, query, pagenum):
  1566. """Report attempt to download playlist page with given number."""
  1567. query = query.decode(preferredencoding())
  1568. self._downloader.to_screen(u'[youtube] query "%s": Downloading page %s' % (query, pagenum))
  1569. def _real_initialize(self):
  1570. self._youtube_ie.initialize()
  1571. def _real_extract(self, query):
  1572. mobj = re.match(self._VALID_QUERY, query)
  1573. if mobj is None:
  1574. self._downloader.trouble(u'ERROR: invalid search query "%s"' % query)
  1575. return
  1576. prefix, query = query.split(':')
  1577. prefix = prefix[8:]
  1578. query = query.encode('utf-8')
  1579. if prefix == '':
  1580. self._download_n_results(query, 1)
  1581. return
  1582. elif prefix == 'all':
  1583. self._download_n_results(query, self._max_youtube_results)
  1584. return
  1585. else:
  1586. try:
  1587. n = long(prefix)
  1588. if n <= 0:
  1589. self._downloader.trouble(u'ERROR: invalid download number %s for query "%s"' % (n, query))
  1590. return
  1591. elif n > self._max_youtube_results:
  1592. self._downloader.to_stderr(u'WARNING: ytsearch returns max %i results (you requested %i)' % (self._max_youtube_results, n))
  1593. n = self._max_youtube_results
  1594. self._download_n_results(query, n)
  1595. return
  1596. except ValueError: # parsing prefix as integer fails
  1597. self._download_n_results(query, 1)
  1598. return
  1599. def _download_n_results(self, query, n):
  1600. """Downloads a specified number of results for a query"""
  1601. video_ids = []
  1602. already_seen = set()
  1603. pagenum = 1
  1604. while True:
  1605. self.report_download_page(query, pagenum)
  1606. result_url = self._TEMPLATE_URL % (urllib.quote_plus(query), pagenum)
  1607. request = urllib2.Request(result_url)
  1608. try:
  1609. page = urllib2.urlopen(request).read()
  1610. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1611. self._downloader.trouble(u'ERROR: unable to download webpage: %s' % str(err))
  1612. return
  1613. # Extract video identifiers
  1614. for mobj in re.finditer(self._VIDEO_INDICATOR, page):
  1615. video_id = page[mobj.span()[0]:mobj.span()[1]].split('=')[2][:-1]
  1616. if video_id not in already_seen:
  1617. video_ids.append(video_id)
  1618. already_seen.add(video_id)
  1619. if len(video_ids) == n:
  1620. # Specified n videos reached
  1621. for id in video_ids:
  1622. self._youtube_ie.extract('http://www.youtube.com/watch?v=%s' % id)
  1623. return
  1624. if re.search(self._MORE_PAGES_INDICATOR, page) is None:
  1625. for id in video_ids:
  1626. self._youtube_ie.extract('http://www.youtube.com/watch?v=%s' % id)
  1627. return
  1628. pagenum = pagenum + 1
  1629. class GoogleSearchIE(InfoExtractor):
  1630. """Information Extractor for Google Video search queries."""
  1631. _VALID_QUERY = r'gvsearch(\d+|all)?:[\s\S]+'
  1632. _TEMPLATE_URL = 'http://video.google.com/videosearch?q=%s+site:video.google.com&start=%s&hl=en'
  1633. _VIDEO_INDICATOR = r'videoplay\?docid=([^\&>]+)\&'
  1634. _MORE_PAGES_INDICATOR = r'<span>Next</span>'
  1635. _google_ie = None
  1636. _max_google_results = 1000
  1637. def __init__(self, google_ie, downloader=None):
  1638. InfoExtractor.__init__(self, downloader)
  1639. self._google_ie = google_ie
  1640. @staticmethod
  1641. def suitable(url):
  1642. return (re.match(GoogleSearchIE._VALID_QUERY, url) is not None)
  1643. def report_download_page(self, query, pagenum):
  1644. """Report attempt to download playlist page with given number."""
  1645. query = query.decode(preferredencoding())
  1646. self._downloader.to_screen(u'[video.google] query "%s": Downloading page %s' % (query, pagenum))
  1647. def _real_initialize(self):
  1648. self._google_ie.initialize()
  1649. def _real_extract(self, query):
  1650. mobj = re.match(self._VALID_QUERY, query)
  1651. if mobj is None:
  1652. self._downloader.trouble(u'ERROR: invalid search query "%s"' % query)
  1653. return
  1654. prefix, query = query.split(':')
  1655. prefix = prefix[8:]
  1656. query = query.encode('utf-8')
  1657. if prefix == '':
  1658. self._download_n_results(query, 1)
  1659. return
  1660. elif prefix == 'all':
  1661. self._download_n_results(query, self._max_google_results)
  1662. return
  1663. else:
  1664. try:
  1665. n = long(prefix)
  1666. if n <= 0:
  1667. self._downloader.trouble(u'ERROR: invalid download number %s for query "%s"' % (n, query))
  1668. return
  1669. elif n > self._max_google_results:
  1670. self._downloader.to_stderr(u'WARNING: gvsearch returns max %i results (you requested %i)' % (self._max_google_results, n))
  1671. n = self._max_google_results
  1672. self._download_n_results(query, n)
  1673. return
  1674. except ValueError: # parsing prefix as integer fails
  1675. self._download_n_results(query, 1)
  1676. return
  1677. def _download_n_results(self, query, n):
  1678. """Downloads a specified number of results for a query"""
  1679. video_ids = []
  1680. already_seen = set()
  1681. pagenum = 1
  1682. while True:
  1683. self.report_download_page(query, pagenum)
  1684. result_url = self._TEMPLATE_URL % (urllib.quote_plus(query), pagenum)
  1685. request = urllib2.Request(result_url)
  1686. try:
  1687. page = urllib2.urlopen(request).read()
  1688. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1689. self._downloader.trouble(u'ERROR: unable to download webpage: %s' % str(err))
  1690. return
  1691. # Extract video identifiers
  1692. for mobj in re.finditer(self._VIDEO_INDICATOR, page):
  1693. video_id = mobj.group(1)
  1694. if video_id not in already_seen:
  1695. video_ids.append(video_id)
  1696. already_seen.add(video_id)
  1697. if len(video_ids) == n:
  1698. # Specified n videos reached
  1699. for id in video_ids:
  1700. self._google_ie.extract('http://video.google.com/videoplay?docid=%s' % id)
  1701. return
  1702. if re.search(self._MORE_PAGES_INDICATOR, page) is None:
  1703. for id in video_ids:
  1704. self._google_ie.extract('http://video.google.com/videoplay?docid=%s' % id)
  1705. return
  1706. pagenum = pagenum + 1
  1707. class YahooSearchIE(InfoExtractor):
  1708. """Information Extractor for Yahoo! Video search queries."""
  1709. _VALID_QUERY = r'yvsearch(\d+|all)?:[\s\S]+'
  1710. _TEMPLATE_URL = 'http://video.yahoo.com/search/?p=%s&o=%s'
  1711. _VIDEO_INDICATOR = r'href="http://video\.yahoo\.com/watch/([0-9]+/[0-9]+)"'
  1712. _MORE_PAGES_INDICATOR = r'\s*Next'
  1713. _yahoo_ie = None
  1714. _max_yahoo_results = 1000
  1715. def __init__(self, yahoo_ie, downloader=None):
  1716. InfoExtractor.__init__(self, downloader)
  1717. self._yahoo_ie = yahoo_ie
  1718. @staticmethod
  1719. def suitable(url):
  1720. return (re.match(YahooSearchIE._VALID_QUERY, url) is not None)
  1721. def report_download_page(self, query, pagenum):
  1722. """Report attempt to download playlist page with given number."""
  1723. query = query.decode(preferredencoding())
  1724. self._downloader.to_screen(u'[video.yahoo] query "%s": Downloading page %s' % (query, pagenum))
  1725. def _real_initialize(self):
  1726. self._yahoo_ie.initialize()
  1727. def _real_extract(self, query):
  1728. mobj = re.match(self._VALID_QUERY, query)
  1729. if mobj is None:
  1730. self._downloader.trouble(u'ERROR: invalid search query "%s"' % query)
  1731. return
  1732. prefix, query = query.split(':')
  1733. prefix = prefix[8:]
  1734. query = query.encode('utf-8')
  1735. if prefix == '':
  1736. self._download_n_results(query, 1)
  1737. return
  1738. elif prefix == 'all':
  1739. self._download_n_results(query, self._max_yahoo_results)
  1740. return
  1741. else:
  1742. try:
  1743. n = long(prefix)
  1744. if n <= 0:
  1745. self._downloader.trouble(u'ERROR: invalid download number %s for query "%s"' % (n, query))
  1746. return
  1747. elif n > self._max_yahoo_results:
  1748. self._downloader.to_stderr(u'WARNING: yvsearch returns max %i results (you requested %i)' % (self._max_yahoo_results, n))
  1749. n = self._max_yahoo_results
  1750. self._download_n_results(query, n)
  1751. return
  1752. except ValueError: # parsing prefix as integer fails
  1753. self._download_n_results(query, 1)
  1754. return
  1755. def _download_n_results(self, query, n):
  1756. """Downloads a specified number of results for a query"""
  1757. video_ids = []
  1758. already_seen = set()
  1759. pagenum = 1
  1760. while True:
  1761. self.report_download_page(query, pagenum)
  1762. result_url = self._TEMPLATE_URL % (urllib.quote_plus(query), pagenum)
  1763. request = urllib2.Request(result_url)
  1764. try:
  1765. page = urllib2.urlopen(request).read()
  1766. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1767. self._downloader.trouble(u'ERROR: unable to download webpage: %s' % str(err))
  1768. return
  1769. # Extract video identifiers
  1770. for mobj in re.finditer(self._VIDEO_INDICATOR, page):
  1771. video_id = mobj.group(1)
  1772. if video_id not in already_seen:
  1773. video_ids.append(video_id)
  1774. already_seen.add(video_id)
  1775. if len(video_ids) == n:
  1776. # Specified n videos reached
  1777. for id in video_ids:
  1778. self._yahoo_ie.extract('http://video.yahoo.com/watch/%s' % id)
  1779. return
  1780. if re.search(self._MORE_PAGES_INDICATOR, page) is None:
  1781. for id in video_ids:
  1782. self._yahoo_ie.extract('http://video.yahoo.com/watch/%s' % id)
  1783. return
  1784. pagenum = pagenum + 1
  1785. class YoutubePlaylistIE(InfoExtractor):
  1786. """Information Extractor for YouTube playlists."""
  1787. _VALID_URL = r'(?:http://)?(?:\w+\.)?youtube.com/(?:(?:view_play_list|my_playlists|artist)\?.*?(p|a)=|user/.*?/user/|p/|user/.*?#[pg]/c/)([0-9A-Za-z]+)(?:/.*?/([0-9A-Za-z_-]+))?.*'
  1788. _TEMPLATE_URL = 'http://www.youtube.com/%s?%s=%s&page=%s&gl=US&hl=en'
  1789. _VIDEO_INDICATOR = r'/watch\?v=(.+?)&'
  1790. _MORE_PAGES_INDICATOR = r'(?m)>\s*Next\s*</a>'
  1791. _youtube_ie = None
  1792. def __init__(self, youtube_ie, downloader=None):
  1793. InfoExtractor.__init__(self, downloader)
  1794. self._youtube_ie = youtube_ie
  1795. @staticmethod
  1796. def suitable(url):
  1797. return (re.match(YoutubePlaylistIE._VALID_URL, url) is not None)
  1798. def report_download_page(self, playlist_id, pagenum):
  1799. """Report attempt to download playlist page with given number."""
  1800. self._downloader.to_screen(u'[youtube] PL %s: Downloading page #%s' % (playlist_id, pagenum))
  1801. def _real_initialize(self):
  1802. self._youtube_ie.initialize()
  1803. def _real_extract(self, url):
  1804. # Extract playlist id
  1805. mobj = re.match(self._VALID_URL, url)
  1806. if mobj is None:
  1807. self._downloader.trouble(u'ERROR: invalid url: %s' % url)
  1808. return
  1809. # Single video case
  1810. if mobj.group(3) is not None:
  1811. self._youtube_ie.extract(mobj.group(3))
  1812. return
  1813. # Download playlist pages
  1814. # prefix is 'p' as default for playlists but there are other types that need extra care
  1815. playlist_prefix = mobj.group(1)
  1816. if playlist_prefix == 'a':
  1817. playlist_access = 'artist'
  1818. else:
  1819. playlist_prefix = 'p'
  1820. playlist_access = 'view_play_list'
  1821. playlist_id = mobj.group(2)
  1822. video_ids = []
  1823. pagenum = 1
  1824. while True:
  1825. self.report_download_page(playlist_id, pagenum)
  1826. request = urllib2.Request(self._TEMPLATE_URL % (playlist_access, playlist_prefix, playlist_id, pagenum))
  1827. try:
  1828. page = urllib2.urlopen(request).read()
  1829. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1830. self._downloader.trouble(u'ERROR: unable to download webpage: %s' % str(err))
  1831. return
  1832. # Extract video identifiers
  1833. ids_in_page = []
  1834. for mobj in re.finditer(self._VIDEO_INDICATOR, page):
  1835. if mobj.group(1) not in ids_in_page:
  1836. ids_in_page.append(mobj.group(1))
  1837. video_ids.extend(ids_in_page)
  1838. if re.search(self._MORE_PAGES_INDICATOR, page) is None:
  1839. break
  1840. pagenum = pagenum + 1
  1841. playliststart = self._downloader.params.get('playliststart', 1) - 1
  1842. playlistend = self._downloader.params.get('playlistend', -1)
  1843. video_ids = video_ids[playliststart:playlistend]
  1844. for id in video_ids:
  1845. self._youtube_ie.extract('http://www.youtube.com/watch?v=%s' % id)
  1846. return
  1847. class YoutubeUserIE(InfoExtractor):
  1848. """Information Extractor for YouTube users."""
  1849. _VALID_URL = r'(?:(?:(?:http://)?(?:\w+\.)?youtube.com/user/)|ytuser:)([A-Za-z0-9_-]+)'
  1850. _TEMPLATE_URL = 'http://gdata.youtube.com/feeds/api/users/%s'
  1851. _GDATA_PAGE_SIZE = 50
  1852. _GDATA_URL = 'http://gdata.youtube.com/feeds/api/users/%s/uploads?max-results=%d&start-index=%d'
  1853. _VIDEO_INDICATOR = r'/watch\?v=(.+?)&'
  1854. _youtube_ie = None
  1855. def __init__(self, youtube_ie, downloader=None):
  1856. InfoExtractor.__init__(self, downloader)
  1857. self._youtube_ie = youtube_ie
  1858. @staticmethod
  1859. def suitable(url):
  1860. return (re.match(YoutubeUserIE._VALID_URL, url) is not None)
  1861. def report_download_page(self, username, start_index):
  1862. """Report attempt to download user page."""
  1863. self._downloader.to_screen(u'[youtube] user %s: Downloading video ids from %d to %d' %
  1864. (username, start_index, start_index + self._GDATA_PAGE_SIZE))
  1865. def _real_initialize(self):
  1866. self._youtube_ie.initialize()
  1867. def _real_extract(self, url):
  1868. # Extract username
  1869. mobj = re.match(self._VALID_URL, url)
  1870. if mobj is None:
  1871. self._downloader.trouble(u'ERROR: invalid url: %s' % url)
  1872. return
  1873. username = mobj.group(1)
  1874. # Download video ids using YouTube Data API. Result size per
  1875. # query is limited (currently to 50 videos) so we need to query
  1876. # page by page until there are no video ids - it means we got
  1877. # all of them.
  1878. video_ids = []
  1879. pagenum = 0
  1880. while True:
  1881. start_index = pagenum * self._GDATA_PAGE_SIZE + 1
  1882. self.report_download_page(username, start_index)
  1883. request = urllib2.Request(self._GDATA_URL % (username, self._GDATA_PAGE_SIZE, start_index))
  1884. try:
  1885. page = urllib2.urlopen(request).read()
  1886. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1887. self._downloader.trouble(u'ERROR: unable to download webpage: %s' % str(err))
  1888. return
  1889. # Extract video identifiers
  1890. ids_in_page = []
  1891. for mobj in re.finditer(self._VIDEO_INDICATOR, page):
  1892. if mobj.group(1) not in ids_in_page:
  1893. ids_in_page.append(mobj.group(1))
  1894. video_ids.extend(ids_in_page)
  1895. # A little optimization - if current page is not
  1896. # "full", ie. does not contain PAGE_SIZE video ids then
  1897. # we can assume that this page is the last one - there
  1898. # are no more ids on further pages - no need to query
  1899. # again.
  1900. if len(ids_in_page) < self._GDATA_PAGE_SIZE:
  1901. break
  1902. pagenum += 1
  1903. all_ids_count = len(video_ids)
  1904. playliststart = self._downloader.params.get('playliststart', 1) - 1
  1905. playlistend = self._downloader.params.get('playlistend', -1)
  1906. if playlistend == -1:
  1907. video_ids = video_ids[playliststart:]
  1908. else:
  1909. video_ids = video_ids[playliststart:playlistend]
  1910. self._downloader.to_screen("[youtube] user %s: Collected %d video ids (downloading %d of them)" %
  1911. (username, all_ids_count, len(video_ids)))
  1912. for video_id in video_ids:
  1913. self._youtube_ie.extract('http://www.youtube.com/watch?v=%s' % video_id)
  1914. class DepositFilesIE(InfoExtractor):
  1915. """Information extractor for depositfiles.com"""
  1916. _VALID_URL = r'(?:http://)?(?:\w+\.)?depositfiles.com/(?:../(?#locale))?files/(.+)'
  1917. def __init__(self, downloader=None):
  1918. InfoExtractor.__init__(self, downloader)
  1919. @staticmethod
  1920. def suitable(url):
  1921. return (re.match(DepositFilesIE._VALID_URL, url) is not None)
  1922. def report_download_webpage(self, file_id):
  1923. """Report webpage download."""
  1924. self._downloader.to_screen(u'[DepositFiles] %s: Downloading webpage' % file_id)
  1925. def report_extraction(self, file_id):
  1926. """Report information extraction."""
  1927. self._downloader.to_screen(u'[DepositFiles] %s: Extracting information' % file_id)
  1928. def _real_initialize(self):
  1929. return
  1930. def _real_extract(self, url):
  1931. # At this point we have a new file
  1932. self._downloader.increment_downloads()
  1933. file_id = url.split('/')[-1]
  1934. # Rebuild url in english locale
  1935. url = 'http://depositfiles.com/en/files/' + file_id
  1936. # Retrieve file webpage with 'Free download' button pressed
  1937. free_download_indication = { 'gateway_result' : '1' }
  1938. request = urllib2.Request(url, urllib.urlencode(free_download_indication))
  1939. try:
  1940. self.report_download_webpage(file_id)
  1941. webpage = urllib2.urlopen(request).read()
  1942. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1943. self._downloader.trouble(u'ERROR: Unable to retrieve file webpage: %s' % str(err))
  1944. return
  1945. # Search for the real file URL
  1946. mobj = re.search(r'<form action="(http://fileshare.+?)"', webpage)
  1947. if (mobj is None) or (mobj.group(1) is None):
  1948. # Try to figure out reason of the error.
  1949. mobj = re.search(r'<strong>(Attention.*?)</strong>', webpage, re.DOTALL)
  1950. if (mobj is not None) and (mobj.group(1) is not None):
  1951. restriction_message = re.sub('\s+', ' ', mobj.group(1)).strip()
  1952. self._downloader.trouble(u'ERROR: %s' % restriction_message)
  1953. else:
  1954. self._downloader.trouble(u'ERROR: unable to extract download URL from: %s' % url)
  1955. return
  1956. file_url = mobj.group(1)
  1957. file_extension = os.path.splitext(file_url)[1][1:]
  1958. # Search for file title
  1959. mobj = re.search(r'<b title="(.*?)">', webpage)
  1960. if mobj is None:
  1961. self._downloader.trouble(u'ERROR: unable to extract title')
  1962. return
  1963. file_title = mobj.group(1).decode('utf-8')
  1964. try:
  1965. # Process file information
  1966. self._downloader.process_info({
  1967. 'id': file_id.decode('utf-8'),
  1968. 'url': file_url.decode('utf-8'),
  1969. 'uploader': u'NA',
  1970. 'upload_date': u'NA',
  1971. 'title': file_title,
  1972. 'stitle': file_title,
  1973. 'ext': file_extension.decode('utf-8'),
  1974. 'format': u'NA',
  1975. 'player_url': None,
  1976. })
  1977. except UnavailableVideoError, err:
  1978. self._downloader.trouble(u'ERROR: unable to download file')
  1979. class FacebookIE(InfoExtractor):
  1980. """Information Extractor for Facebook"""
  1981. _VALID_URL = r'^(?:https?://)?(?:\w+\.)?facebook.com/video/video.php\?(?:.*?)v=(?P<ID>\d+)(?:.*)'
  1982. _LOGIN_URL = 'https://login.facebook.com/login.php?m&next=http%3A%2F%2Fm.facebook.com%2Fhome.php&'
  1983. _NETRC_MACHINE = 'facebook'
  1984. _available_formats = ['highqual', 'lowqual']
  1985. _video_extensions = {
  1986. 'highqual': 'mp4',
  1987. 'lowqual': 'mp4',
  1988. }
  1989. def __init__(self, downloader=None):
  1990. InfoExtractor.__init__(self, downloader)
  1991. @staticmethod
  1992. def suitable(url):
  1993. return (re.match(FacebookIE._VALID_URL, url) is not None)
  1994. def _reporter(self, message):
  1995. """Add header and report message."""
  1996. self._downloader.to_screen(u'[facebook] %s' % message)
  1997. def report_login(self):
  1998. """Report attempt to log in."""
  1999. self._reporter(u'Logging in')
  2000. def report_video_webpage_download(self, video_id):
  2001. """Report attempt to download video webpage."""
  2002. self._reporter(u'%s: Downloading video webpage' % video_id)
  2003. def report_information_extraction(self, video_id):
  2004. """Report attempt to extract video information."""
  2005. self._reporter(u'%s: Extracting video information' % video_id)
  2006. def _parse_page(self, video_webpage):
  2007. """Extract video information from page"""
  2008. # General data
  2009. data = {'title': r'class="video_title datawrap">(.*?)</',
  2010. 'description': r'<div class="datawrap">(.*?)</div>',
  2011. 'owner': r'\("video_owner_name", "(.*?)"\)',
  2012. 'upload_date': r'data-date="(.*?)"',
  2013. 'thumbnail': r'\("thumb_url", "(?P<THUMB>.*?)"\)',
  2014. }
  2015. video_info = {}
  2016. for piece in data.keys():
  2017. mobj = re.search(data[piece], video_webpage)
  2018. if mobj is not None:
  2019. video_info[piece] = urllib.unquote_plus(mobj.group(1).decode("unicode_escape"))
  2020. # Video urls
  2021. video_urls = {}
  2022. for fmt in self._available_formats:
  2023. mobj = re.search(r'\("%s_src\", "(.+?)"\)' % fmt, video_webpage)
  2024. if mobj is not None:
  2025. # URL is in a Javascript segment inside an escaped Unicode format within
  2026. # the generally utf-8 page
  2027. video_urls[fmt] = urllib.unquote_plus(mobj.group(1).decode("unicode_escape"))
  2028. video_info['video_urls'] = video_urls
  2029. return video_info
  2030. def _real_initialize(self):
  2031. if self._downloader is None:
  2032. return
  2033. useremail = None
  2034. password = None
  2035. downloader_params = self._downloader.params
  2036. # Attempt to use provided username and password or .netrc data
  2037. if downloader_params.get('username', None) is not None:
  2038. useremail = downloader_params['username']
  2039. password = downloader_params['password']
  2040. elif downloader_params.get('usenetrc', False):
  2041. try:
  2042. info = netrc.netrc().authenticators(self._NETRC_MACHINE)
  2043. if info is not None:
  2044. useremail = info[0]
  2045. password = info[2]
  2046. else:
  2047. raise netrc.NetrcParseError('No authenticators for %s' % self._NETRC_MACHINE)
  2048. except (IOError, netrc.NetrcParseError), err:
  2049. self._downloader.to_stderr(u'WARNING: parsing .netrc: %s' % str(err))
  2050. return
  2051. if useremail is None:
  2052. return
  2053. # Log in
  2054. login_form = {
  2055. 'email': useremail,
  2056. 'pass': password,
  2057. 'login': 'Log+In'
  2058. }
  2059. request = urllib2.Request(self._LOGIN_URL, urllib.urlencode(login_form))
  2060. try:
  2061. self.report_login()
  2062. login_results = urllib2.urlopen(request).read()
  2063. if re.search(r'<form(.*)name="login"(.*)</form>', login_results) is not None:
  2064. self._downloader.to_stderr(u'WARNING: unable to log in: bad username/password, or exceded login rate limit (~3/min). Check credentials or wait.')
  2065. return
  2066. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  2067. self._downloader.to_stderr(u'WARNING: unable to log in: %s' % str(err))
  2068. return
  2069. def _real_extract(self, url):
  2070. mobj = re.match(self._VALID_URL, url)
  2071. if mobj is None:
  2072. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  2073. return
  2074. video_id = mobj.group('ID')
  2075. # Get video webpage
  2076. self.report_video_webpage_download(video_id)
  2077. request = urllib2.Request('https://www.facebook.com/video/video.php?v=%s' % video_id)
  2078. try:
  2079. page = urllib2.urlopen(request)
  2080. video_webpage = page.read()
  2081. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  2082. self._downloader.trouble(u'ERROR: unable to download video webpage: %s' % str(err))
  2083. return
  2084. # Start extracting information
  2085. self.report_information_extraction(video_id)
  2086. # Extract information
  2087. video_info = self._parse_page(video_webpage)
  2088. # uploader
  2089. if 'owner' not in video_info:
  2090. self._downloader.trouble(u'ERROR: unable to extract uploader nickname')
  2091. return
  2092. video_uploader = video_info['owner']
  2093. # title
  2094. if 'title' not in video_info:
  2095. self._downloader.trouble(u'ERROR: unable to extract video title')
  2096. return
  2097. video_title = video_info['title']
  2098. video_title = video_title.decode('utf-8')
  2099. video_title = sanitize_title(video_title)
  2100. # simplified title
  2101. simple_title = re.sub(ur'(?u)([^%s]+)' % simple_title_chars, ur'_', video_title)
  2102. simple_title = simple_title.strip(ur'_')
  2103. # thumbnail image
  2104. if 'thumbnail' not in video_info:
  2105. self._downloader.trouble(u'WARNING: unable to extract video thumbnail')
  2106. video_thumbnail = ''
  2107. else:
  2108. video_thumbnail = video_info['thumbnail']
  2109. # upload date
  2110. upload_date = u'NA'
  2111. if 'upload_date' in video_info:
  2112. upload_time = video_info['upload_date']
  2113. timetuple = email.utils.parsedate_tz(upload_time)
  2114. if timetuple is not None:
  2115. try:
  2116. upload_date = time.strftime('%Y%m%d', timetuple[0:9])
  2117. except:
  2118. pass
  2119. # description
  2120. video_description = 'No description available.'
  2121. if (self._downloader.params.get('forcedescription', False) and
  2122. 'description' in video_info):
  2123. video_description = video_info['description']
  2124. url_map = video_info['video_urls']
  2125. if len(url_map.keys()) > 0:
  2126. # Decide which formats to download
  2127. req_format = self._downloader.params.get('format', None)
  2128. format_limit = self._downloader.params.get('format_limit', None)
  2129. if format_limit is not None and format_limit in self._available_formats:
  2130. format_list = self._available_formats[self._available_formats.index(format_limit):]
  2131. else:
  2132. format_list = self._available_formats
  2133. existing_formats = [x for x in format_list if x in url_map]
  2134. if len(existing_formats) == 0:
  2135. self._downloader.trouble(u'ERROR: no known formats available for video')
  2136. return
  2137. if req_format is None:
  2138. video_url_list = [(existing_formats[0], url_map[existing_formats[0]])] # Best quality
  2139. elif req_format == '-1':
  2140. video_url_list = [(f, url_map[f]) for f in existing_formats] # All formats
  2141. else:
  2142. # Specific format
  2143. if req_format not in url_map:
  2144. self._downloader.trouble(u'ERROR: requested format not available')
  2145. return
  2146. video_url_list = [(req_format, url_map[req_format])] # Specific format
  2147. for format_param, video_real_url in video_url_list:
  2148. # At this point we have a new video
  2149. self._downloader.increment_downloads()
  2150. # Extension
  2151. video_extension = self._video_extensions.get(format_param, 'mp4')
  2152. # Find the video URL in fmt_url_map or conn paramters
  2153. try:
  2154. # Process video information
  2155. self._downloader.process_info({
  2156. 'id': video_id.decode('utf-8'),
  2157. 'url': video_real_url.decode('utf-8'),
  2158. 'uploader': video_uploader.decode('utf-8'),
  2159. 'upload_date': upload_date,
  2160. 'title': video_title,
  2161. 'stitle': simple_title,
  2162. 'ext': video_extension.decode('utf-8'),
  2163. 'format': (format_param is None and u'NA' or format_param.decode('utf-8')),
  2164. 'thumbnail': video_thumbnail.decode('utf-8'),
  2165. 'description': video_description.decode('utf-8'),
  2166. 'player_url': None,
  2167. })
  2168. except UnavailableVideoError, err:
  2169. self._downloader.trouble(u'\nERROR: unable to download video')
  2170. class PostProcessor(object):
  2171. """Post Processor class.
  2172. PostProcessor objects can be added to downloaders with their
  2173. add_post_processor() method. When the downloader has finished a
  2174. successful download, it will take its internal chain of PostProcessors
  2175. and start calling the run() method on each one of them, first with
  2176. an initial argument and then with the returned value of the previous
  2177. PostProcessor.
  2178. The chain will be stopped if one of them ever returns None or the end
  2179. of the chain is reached.
  2180. PostProcessor objects follow a "mutual registration" process similar
  2181. to InfoExtractor objects.
  2182. """
  2183. _downloader = None
  2184. def __init__(self, downloader=None):
  2185. self._downloader = downloader
  2186. def set_downloader(self, downloader):
  2187. """Sets the downloader for this PP."""
  2188. self._downloader = downloader
  2189. def run(self, information):
  2190. """Run the PostProcessor.
  2191. The "information" argument is a dictionary like the ones
  2192. composed by InfoExtractors. The only difference is that this
  2193. one has an extra field called "filepath" that points to the
  2194. downloaded file.
  2195. When this method returns None, the postprocessing chain is
  2196. stopped. However, this method may return an information
  2197. dictionary that will be passed to the next postprocessing
  2198. object in the chain. It can be the one it received after
  2199. changing some fields.
  2200. In addition, this method may raise a PostProcessingError
  2201. exception that will be taken into account by the downloader
  2202. it was called from.
  2203. """
  2204. return information # by default, do nothing
  2205. class FFmpegExtractAudioPP(PostProcessor):
  2206. def __init__(self, downloader=None, preferredcodec=None):
  2207. PostProcessor.__init__(self, downloader)
  2208. if preferredcodec is None:
  2209. preferredcodec = 'best'
  2210. self._preferredcodec = preferredcodec
  2211. @staticmethod
  2212. def get_audio_codec(path):
  2213. try:
  2214. cmd = ['ffprobe', '-show_streams', '--', path]
  2215. handle = subprocess.Popen(cmd, stderr=file(os.path.devnull, 'w'), stdout=subprocess.PIPE)
  2216. output = handle.communicate()[0]
  2217. if handle.wait() != 0:
  2218. return None
  2219. except (IOError, OSError):
  2220. return None
  2221. audio_codec = None
  2222. for line in output.split('\n'):
  2223. if line.startswith('codec_name='):
  2224. audio_codec = line.split('=')[1].strip()
  2225. elif line.strip() == 'codec_type=audio' and audio_codec is not None:
  2226. return audio_codec
  2227. return None
  2228. @staticmethod
  2229. def run_ffmpeg(path, out_path, codec, more_opts):
  2230. try:
  2231. cmd = ['ffmpeg', '-y', '-i', path, '-vn', '-acodec', codec] + more_opts + ['--', out_path]
  2232. ret = subprocess.call(cmd, stdout=file(os.path.devnull, 'w'), stderr=subprocess.STDOUT)
  2233. return (ret == 0)
  2234. except (IOError, OSError):
  2235. return False
  2236. def run(self, information):
  2237. path = information['filepath']
  2238. filecodec = self.get_audio_codec(path)
  2239. if filecodec is None:
  2240. self._downloader.to_stderr(u'WARNING: unable to obtain file audio codec with ffprobe')
  2241. return None
  2242. more_opts = []
  2243. if self._preferredcodec == 'best' or self._preferredcodec == filecodec:
  2244. if filecodec == 'aac' or filecodec == 'mp3':
  2245. # Lossless if possible
  2246. acodec = 'copy'
  2247. extension = filecodec
  2248. if filecodec == 'aac':
  2249. more_opts = ['-f', 'adts']
  2250. else:
  2251. # MP3 otherwise.
  2252. acodec = 'libmp3lame'
  2253. extension = 'mp3'
  2254. more_opts = ['-ab', '128k']
  2255. else:
  2256. # We convert the audio (lossy)
  2257. acodec = {'mp3': 'libmp3lame', 'aac': 'aac'}[self._preferredcodec]
  2258. extension = self._preferredcodec
  2259. more_opts = ['-ab', '128k']
  2260. if self._preferredcodec == 'aac':
  2261. more_opts += ['-f', 'adts']
  2262. (prefix, ext) = os.path.splitext(path)
  2263. new_path = prefix + '.' + extension
  2264. self._downloader.to_screen(u'[ffmpeg] Destination: %s' % new_path)
  2265. status = self.run_ffmpeg(path, new_path, acodec, more_opts)
  2266. if not status:
  2267. self._downloader.to_stderr(u'WARNING: error running ffmpeg')
  2268. return None
  2269. try:
  2270. os.remove(path)
  2271. except (IOError, OSError):
  2272. self._downloader.to_stderr(u'WARNING: Unable to remove downloaded video file')
  2273. return None
  2274. information['filepath'] = new_path
  2275. return information
  2276. ### MAIN PROGRAM ###
  2277. if __name__ == '__main__':
  2278. try:
  2279. # Modules needed only when running the main program
  2280. import getpass
  2281. import optparse
  2282. # Function to update the program file with the latest version from the repository.
  2283. def update_self(downloader, filename):
  2284. # Note: downloader only used for options
  2285. if not os.access(filename, os.W_OK):
  2286. sys.exit('ERROR: no write permissions on %s' % filename)
  2287. downloader.to_screen('Updating to latest stable version...')
  2288. try:
  2289. latest_url = 'http://github.com/rg3/youtube-dl/raw/master/LATEST_VERSION'
  2290. latest_version = urllib.urlopen(latest_url).read().strip()
  2291. prog_url = 'http://github.com/rg3/youtube-dl/raw/%s/youtube-dl' % latest_version
  2292. newcontent = urllib.urlopen(prog_url).read()
  2293. except (IOError, OSError), err:
  2294. sys.exit('ERROR: unable to download latest version')
  2295. try:
  2296. stream = open(filename, 'w')
  2297. stream.write(newcontent)
  2298. stream.close()
  2299. except (IOError, OSError), err:
  2300. sys.exit('ERROR: unable to overwrite current version')
  2301. downloader.to_screen('Updated to version %s' % latest_version)
  2302. # Parse command line
  2303. parser = optparse.OptionParser(
  2304. usage='Usage: %prog [options] url...',
  2305. version='2011.03.29',
  2306. conflict_handler='resolve',
  2307. )
  2308. parser.add_option('-h', '--help',
  2309. action='help', help='print this help text and exit')
  2310. parser.add_option('-v', '--version',
  2311. action='version', help='print program version and exit')
  2312. parser.add_option('-U', '--update',
  2313. action='store_true', dest='update_self', help='update this program to latest stable version')
  2314. parser.add_option('-i', '--ignore-errors',
  2315. action='store_true', dest='ignoreerrors', help='continue on download errors', default=False)
  2316. parser.add_option('-r', '--rate-limit',
  2317. dest='ratelimit', metavar='LIMIT', help='download rate limit (e.g. 50k or 44.6m)')
  2318. parser.add_option('-R', '--retries',
  2319. dest='retries', metavar='RETRIES', help='number of retries (default is 10)', default=10)
  2320. parser.add_option('--playlist-start',
  2321. dest='playliststart', metavar='NUMBER', help='playlist video to start at (default is 1)', default=1)
  2322. parser.add_option('--playlist-end',
  2323. dest='playlistend', metavar='NUMBER', help='playlist video to end at (default is last)', default=-1)
  2324. parser.add_option('--dump-user-agent',
  2325. action='store_true', dest='dump_user_agent',
  2326. help='display the current browser identification', default=False)
  2327. authentication = optparse.OptionGroup(parser, 'Authentication Options')
  2328. authentication.add_option('-u', '--username',
  2329. dest='username', metavar='USERNAME', help='account username')
  2330. authentication.add_option('-p', '--password',
  2331. dest='password', metavar='PASSWORD', help='account password')
  2332. authentication.add_option('-n', '--netrc',
  2333. action='store_true', dest='usenetrc', help='use .netrc authentication data', default=False)
  2334. parser.add_option_group(authentication)
  2335. video_format = optparse.OptionGroup(parser, 'Video Format Options')
  2336. video_format.add_option('-f', '--format',
  2337. action='store', dest='format', metavar='FORMAT', help='video format code')
  2338. video_format.add_option('--all-formats',
  2339. action='store_const', dest='format', help='download all available video formats', const='-1')
  2340. video_format.add_option('--max-quality',
  2341. action='store', dest='format_limit', metavar='FORMAT', help='highest quality format to download')
  2342. parser.add_option_group(video_format)
  2343. verbosity = optparse.OptionGroup(parser, 'Verbosity / Simulation Options')
  2344. verbosity.add_option('-q', '--quiet',
  2345. action='store_true', dest='quiet', help='activates quiet mode', default=False)
  2346. verbosity.add_option('-s', '--simulate',
  2347. action='store_true', dest='simulate', help='do not download video', default=False)
  2348. verbosity.add_option('-g', '--get-url',
  2349. action='store_true', dest='geturl', help='simulate, quiet but print URL', default=False)
  2350. verbosity.add_option('-e', '--get-title',
  2351. action='store_true', dest='gettitle', help='simulate, quiet but print title', default=False)
  2352. verbosity.add_option('--get-thumbnail',
  2353. action='store_true', dest='getthumbnail',
  2354. help='simulate, quiet but print thumbnail URL', default=False)
  2355. verbosity.add_option('--get-description',
  2356. action='store_true', dest='getdescription',
  2357. help='simulate, quiet but print video description', default=False)
  2358. verbosity.add_option('--get-filename',
  2359. action='store_true', dest='getfilename',
  2360. help='simulate, quiet but print output filename', default=False)
  2361. verbosity.add_option('--no-progress',
  2362. action='store_true', dest='noprogress', help='do not print progress bar', default=False)
  2363. verbosity.add_option('--console-title',
  2364. action='store_true', dest='consoletitle',
  2365. help='display progress in console titlebar', default=False)
  2366. parser.add_option_group(verbosity)
  2367. filesystem = optparse.OptionGroup(parser, 'Filesystem Options')
  2368. filesystem.add_option('-t', '--title',
  2369. action='store_true', dest='usetitle', help='use title in file name', default=False)
  2370. filesystem.add_option('-l', '--literal',
  2371. action='store_true', dest='useliteral', help='use literal title in file name', default=False)
  2372. filesystem.add_option('-A', '--auto-number',
  2373. action='store_true', dest='autonumber',
  2374. help='number downloaded files starting from 00000', default=False)
  2375. filesystem.add_option('-o', '--output',
  2376. dest='outtmpl', metavar='TEMPLATE', help='output filename template')
  2377. filesystem.add_option('-a', '--batch-file',
  2378. dest='batchfile', metavar='FILE', help='file containing URLs to download (\'-\' for stdin)')
  2379. filesystem.add_option('-w', '--no-overwrites',
  2380. action='store_true', dest='nooverwrites', help='do not overwrite files', default=False)
  2381. filesystem.add_option('-c', '--continue',
  2382. action='store_true', dest='continue_dl', help='resume partially downloaded files', default=False)
  2383. filesystem.add_option('--cookies',
  2384. dest='cookiefile', metavar='FILE', help='file to dump cookie jar to')
  2385. filesystem.add_option('--no-part',
  2386. action='store_true', dest='nopart', help='do not use .part files', default=False)
  2387. filesystem.add_option('--no-mtime',
  2388. action='store_false', dest='updatetime',
  2389. help='do not use the Last-modified header to set the file modification time', default=True)
  2390. parser.add_option_group(filesystem)
  2391. postproc = optparse.OptionGroup(parser, 'Post-processing Options')
  2392. postproc.add_option('--extract-audio', action='store_true', dest='extractaudio', default=False,
  2393. help='convert video files to audio-only files (requires ffmpeg and ffprobe)')
  2394. postproc.add_option('--audio-format', metavar='FORMAT', dest='audioformat', default='best',
  2395. help='"best", "aac" or "mp3"; best by default')
  2396. parser.add_option_group(postproc)
  2397. (opts, args) = parser.parse_args()
  2398. # Open appropriate CookieJar
  2399. if opts.cookiefile is None:
  2400. jar = cookielib.CookieJar()
  2401. else:
  2402. try:
  2403. jar = cookielib.MozillaCookieJar(opts.cookiefile)
  2404. if os.path.isfile(opts.cookiefile) and os.access(opts.cookiefile, os.R_OK):
  2405. jar.load()
  2406. except (IOError, OSError), err:
  2407. sys.exit(u'ERROR: unable to open cookie file')
  2408. # Dump user agent
  2409. if opts.dump_user_agent:
  2410. print std_headers['User-Agent']
  2411. sys.exit(0)
  2412. # General configuration
  2413. cookie_processor = urllib2.HTTPCookieProcessor(jar)
  2414. urllib2.install_opener(urllib2.build_opener(urllib2.ProxyHandler(), cookie_processor, YoutubeDLHandler()))
  2415. socket.setdefaulttimeout(300) # 5 minutes should be enough (famous last words)
  2416. # Batch file verification
  2417. batchurls = []
  2418. if opts.batchfile is not None:
  2419. try:
  2420. if opts.batchfile == '-':
  2421. batchfd = sys.stdin
  2422. else:
  2423. batchfd = open(opts.batchfile, 'r')
  2424. batchurls = batchfd.readlines()
  2425. batchurls = [x.strip() for x in batchurls]
  2426. batchurls = [x for x in batchurls if len(x) > 0 and not re.search(r'^[#/;]', x)]
  2427. except IOError:
  2428. sys.exit(u'ERROR: batch file could not be read')
  2429. all_urls = batchurls + args
  2430. # Conflicting, missing and erroneous options
  2431. if opts.usenetrc and (opts.username is not None or opts.password is not None):
  2432. parser.error(u'using .netrc conflicts with giving username/password')
  2433. if opts.password is not None and opts.username is None:
  2434. parser.error(u'account username missing')
  2435. if opts.outtmpl is not None and (opts.useliteral or opts.usetitle or opts.autonumber):
  2436. parser.error(u'using output template conflicts with using title, literal title or auto number')
  2437. if opts.usetitle and opts.useliteral:
  2438. parser.error(u'using title conflicts with using literal title')
  2439. if opts.username is not None and opts.password is None:
  2440. opts.password = getpass.getpass(u'Type account password and press return:')
  2441. if opts.ratelimit is not None:
  2442. numeric_limit = FileDownloader.parse_bytes(opts.ratelimit)
  2443. if numeric_limit is None:
  2444. parser.error(u'invalid rate limit specified')
  2445. opts.ratelimit = numeric_limit
  2446. if opts.retries is not None:
  2447. try:
  2448. opts.retries = long(opts.retries)
  2449. except (TypeError, ValueError), err:
  2450. parser.error(u'invalid retry count specified')
  2451. try:
  2452. opts.playliststart = long(opts.playliststart)
  2453. if opts.playliststart <= 0:
  2454. raise ValueError
  2455. except (TypeError, ValueError), err:
  2456. parser.error(u'invalid playlist start number specified')
  2457. try:
  2458. opts.playlistend = long(opts.playlistend)
  2459. if opts.playlistend != -1 and (opts.playlistend <= 0 or opts.playlistend < opts.playliststart):
  2460. raise ValueError
  2461. except (TypeError, ValueError), err:
  2462. parser.error(u'invalid playlist end number specified')
  2463. if opts.extractaudio:
  2464. if opts.audioformat not in ['best', 'aac', 'mp3']:
  2465. parser.error(u'invalid audio format specified')
  2466. # Information extractors
  2467. youtube_ie = YoutubeIE()
  2468. metacafe_ie = MetacafeIE(youtube_ie)
  2469. dailymotion_ie = DailymotionIE()
  2470. youtube_pl_ie = YoutubePlaylistIE(youtube_ie)
  2471. youtube_user_ie = YoutubeUserIE(youtube_ie)
  2472. youtube_search_ie = YoutubeSearchIE(youtube_ie)
  2473. google_ie = GoogleIE()
  2474. google_search_ie = GoogleSearchIE(google_ie)
  2475. photobucket_ie = PhotobucketIE()
  2476. yahoo_ie = YahooIE()
  2477. yahoo_search_ie = YahooSearchIE(yahoo_ie)
  2478. deposit_files_ie = DepositFilesIE()
  2479. facebook_ie = FacebookIE()
  2480. generic_ie = GenericIE()
  2481. # File downloader
  2482. fd = FileDownloader({
  2483. 'usenetrc': opts.usenetrc,
  2484. 'username': opts.username,
  2485. 'password': opts.password,
  2486. 'quiet': (opts.quiet or opts.geturl or opts.gettitle or opts.getthumbnail or opts.getdescription or opts.getfilename),
  2487. 'forceurl': opts.geturl,
  2488. 'forcetitle': opts.gettitle,
  2489. 'forcethumbnail': opts.getthumbnail,
  2490. 'forcedescription': opts.getdescription,
  2491. 'forcefilename': opts.getfilename,
  2492. 'simulate': (opts.simulate or opts.geturl or opts.gettitle or opts.getthumbnail or opts.getdescription or opts.getfilename),
  2493. 'format': opts.format,
  2494. 'format_limit': opts.format_limit,
  2495. 'outtmpl': ((opts.outtmpl is not None and opts.outtmpl.decode(preferredencoding()))
  2496. or (opts.format == '-1' and opts.usetitle and u'%(stitle)s-%(id)s-%(format)s.%(ext)s')
  2497. or (opts.format == '-1' and opts.useliteral and u'%(title)s-%(id)s-%(format)s.%(ext)s')
  2498. or (opts.format == '-1' and u'%(id)s-%(format)s.%(ext)s')
  2499. or (opts.usetitle and opts.autonumber and u'%(autonumber)s-%(stitle)s-%(id)s.%(ext)s')
  2500. or (opts.useliteral and opts.autonumber and u'%(autonumber)s-%(title)s-%(id)s.%(ext)s')
  2501. or (opts.usetitle and u'%(stitle)s-%(id)s.%(ext)s')
  2502. or (opts.useliteral and u'%(title)s-%(id)s.%(ext)s')
  2503. or (opts.autonumber and u'%(autonumber)s-%(id)s.%(ext)s')
  2504. or u'%(id)s.%(ext)s'),
  2505. 'ignoreerrors': opts.ignoreerrors,
  2506. 'ratelimit': opts.ratelimit,
  2507. 'nooverwrites': opts.nooverwrites,
  2508. 'retries': opts.retries,
  2509. 'continuedl': opts.continue_dl,
  2510. 'noprogress': opts.noprogress,
  2511. 'playliststart': opts.playliststart,
  2512. 'playlistend': opts.playlistend,
  2513. 'logtostderr': opts.outtmpl == '-',
  2514. 'consoletitle': opts.consoletitle,
  2515. 'nopart': opts.nopart,
  2516. 'updatetime': opts.updatetime,
  2517. })
  2518. fd.add_info_extractor(youtube_search_ie)
  2519. fd.add_info_extractor(youtube_pl_ie)
  2520. fd.add_info_extractor(youtube_user_ie)
  2521. fd.add_info_extractor(metacafe_ie)
  2522. fd.add_info_extractor(dailymotion_ie)
  2523. fd.add_info_extractor(youtube_ie)
  2524. fd.add_info_extractor(google_ie)
  2525. fd.add_info_extractor(google_search_ie)
  2526. fd.add_info_extractor(photobucket_ie)
  2527. fd.add_info_extractor(yahoo_ie)
  2528. fd.add_info_extractor(yahoo_search_ie)
  2529. fd.add_info_extractor(deposit_files_ie)
  2530. fd.add_info_extractor(facebook_ie)
  2531. # This must come last since it's the
  2532. # fallback if none of the others work
  2533. fd.add_info_extractor(generic_ie)
  2534. # PostProcessors
  2535. if opts.extractaudio:
  2536. fd.add_post_processor(FFmpegExtractAudioPP(preferredcodec=opts.audioformat))
  2537. # Update version
  2538. if opts.update_self:
  2539. update_self(fd, sys.argv[0])
  2540. # Maybe do nothing
  2541. if len(all_urls) < 1:
  2542. if not opts.update_self:
  2543. parser.error(u'you must provide at least one URL')
  2544. else:
  2545. sys.exit()
  2546. retcode = fd.download(all_urls)
  2547. # Dump cookie jar if requested
  2548. if opts.cookiefile is not None:
  2549. try:
  2550. jar.save()
  2551. except (IOError, OSError), err:
  2552. sys.exit(u'ERROR: unable to save cookie jar')
  2553. sys.exit(retcode)
  2554. except DownloadError:
  2555. sys.exit(1)
  2556. except SameFileError:
  2557. sys.exit(u'ERROR: fixed output name but more than one file to download')
  2558. except KeyboardInterrupt:
  2559. sys.exit(u'\nERROR: Interrupted by user')