You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

4223 lines
142 KiB

13 years ago
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. __author__ = (
  4. 'Ricardo Garcia Gonzalez',
  5. 'Danny Colligan',
  6. 'Benjamin Johnson',
  7. 'Vasyl\' Vavrychuk',
  8. 'Witold Baryluk',
  9. 'Paweł Paprota',
  10. 'Gergely Imreh',
  11. 'Rogério Brito',
  12. 'Philipp Hagemeister',
  13. 'Sören Schulze',
  14. 'Kevin Ngo',
  15. 'Ori Avtalion',
  16. )
  17. __license__ = 'Public Domain'
  18. __version__ = '2011.10.19'
  19. UPDATE_URL = 'https://raw.github.com/rg3/youtube-dl/master/youtube-dl'
  20. import cookielib
  21. import datetime
  22. import gzip
  23. import htmlentitydefs
  24. import HTMLParser
  25. import httplib
  26. import locale
  27. import math
  28. import netrc
  29. import os
  30. import os.path
  31. import re
  32. import socket
  33. import string
  34. import subprocess
  35. import sys
  36. import time
  37. import urllib
  38. import urllib2
  39. import warnings
  40. import zlib
  41. if os.name == 'nt':
  42. import ctypes
  43. try:
  44. import email.utils
  45. except ImportError: # Python 2.4
  46. import email.Utils
  47. try:
  48. import cStringIO as StringIO
  49. except ImportError:
  50. import StringIO
  51. # parse_qs was moved from the cgi module to the urlparse module recently.
  52. try:
  53. from urlparse import parse_qs
  54. except ImportError:
  55. from cgi import parse_qs
  56. try:
  57. import lxml.etree
  58. except ImportError:
  59. pass # Handled below
  60. try:
  61. import xml.etree.ElementTree
  62. except ImportError: # Python<2.5: Not officially supported, but let it slip
  63. warnings.warn('xml.etree.ElementTree support is missing. Consider upgrading to Python >= 2.5 if you get related errors.')
  64. std_headers = {
  65. 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:5.0.1) Gecko/20100101 Firefox/5.0.1',
  66. 'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
  67. 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
  68. 'Accept-Encoding': 'gzip, deflate',
  69. 'Accept-Language': 'en-us,en;q=0.5',
  70. }
  71. simple_title_chars = string.ascii_letters.decode('ascii') + string.digits.decode('ascii')
  72. try:
  73. import json
  74. except ImportError: # Python <2.6, use trivialjson (https://github.com/phihag/trivialjson):
  75. import re
  76. class json(object):
  77. @staticmethod
  78. def loads(s):
  79. s = s.decode('UTF-8')
  80. def raiseError(msg, i):
  81. raise ValueError(msg + ' at position ' + str(i) + ' of ' + repr(s) + ': ' + repr(s[i:]))
  82. def skipSpace(i, expectMore=True):
  83. while i < len(s) and s[i] in ' \t\r\n':
  84. i += 1
  85. if expectMore:
  86. if i >= len(s):
  87. raiseError('Premature end', i)
  88. return i
  89. def decodeEscape(match):
  90. esc = match.group(1)
  91. _STATIC = {
  92. '"': '"',
  93. '\\': '\\',
  94. '/': '/',
  95. 'b': unichr(0x8),
  96. 'f': unichr(0xc),
  97. 'n': '\n',
  98. 'r': '\r',
  99. 't': '\t',
  100. }
  101. if esc in _STATIC:
  102. return _STATIC[esc]
  103. if esc[0] == 'u':
  104. if len(esc) == 1+4:
  105. return unichr(int(esc[1:5], 16))
  106. if len(esc) == 5+6 and esc[5:7] == '\\u':
  107. hi = int(esc[1:5], 16)
  108. low = int(esc[7:11], 16)
  109. return unichr((hi - 0xd800) * 0x400 + low - 0xdc00 + 0x10000)
  110. raise ValueError('Unknown escape ' + str(esc))
  111. def parseString(i):
  112. i += 1
  113. e = i
  114. while True:
  115. e = s.index('"', e)
  116. bslashes = 0
  117. while s[e-bslashes-1] == '\\':
  118. bslashes += 1
  119. if bslashes % 2 == 1:
  120. e += 1
  121. continue
  122. break
  123. rexp = re.compile(r'\\(u[dD][89aAbB][0-9a-fA-F]{2}\\u[0-9a-fA-F]{4}|u[0-9a-fA-F]{4}|.|$)')
  124. stri = rexp.sub(decodeEscape, s[i:e])
  125. return (e+1,stri)
  126. def parseObj(i):
  127. i += 1
  128. res = {}
  129. i = skipSpace(i)
  130. if s[i] == '}': # Empty dictionary
  131. return (i+1,res)
  132. while True:
  133. if s[i] != '"':
  134. raiseError('Expected a string object key', i)
  135. i,key = parseString(i)
  136. i = skipSpace(i)
  137. if i >= len(s) or s[i] != ':':
  138. raiseError('Expected a colon', i)
  139. i,val = parse(i+1)
  140. res[key] = val
  141. i = skipSpace(i)
  142. if s[i] == '}':
  143. return (i+1, res)
  144. if s[i] != ',':
  145. raiseError('Expected comma or closing curly brace', i)
  146. i = skipSpace(i+1)
  147. def parseArray(i):
  148. res = []
  149. i = skipSpace(i+1)
  150. if s[i] == ']': # Empty array
  151. return (i+1,res)
  152. while True:
  153. i,val = parse(i)
  154. res.append(val)
  155. i = skipSpace(i) # Raise exception if premature end
  156. if s[i] == ']':
  157. return (i+1, res)
  158. if s[i] != ',':
  159. raiseError('Expected a comma or closing bracket', i)
  160. i = skipSpace(i+1)
  161. def parseDiscrete(i):
  162. for k,v in {'true': True, 'false': False, 'null': None}.items():
  163. if s.startswith(k, i):
  164. return (i+len(k), v)
  165. raiseError('Not a boolean (or null)', i)
  166. def parseNumber(i):
  167. mobj = re.match('^(-?(0|[1-9][0-9]*)(\.[0-9]*)?([eE][+-]?[0-9]+)?)', s[i:])
  168. if mobj is None:
  169. raiseError('Not a number', i)
  170. nums = mobj.group(1)
  171. if '.' in nums or 'e' in nums or 'E' in nums:
  172. return (i+len(nums), float(nums))
  173. return (i+len(nums), int(nums))
  174. CHARMAP = {'{': parseObj, '[': parseArray, '"': parseString, 't': parseDiscrete, 'f': parseDiscrete, 'n': parseDiscrete}
  175. def parse(i):
  176. i = skipSpace(i)
  177. i,res = CHARMAP.get(s[i], parseNumber)(i)
  178. i = skipSpace(i, False)
  179. return (i,res)
  180. i,res = parse(0)
  181. if i < len(s):
  182. raise ValueError('Extra data at end of input (index ' + str(i) + ' of ' + repr(s) + ': ' + repr(s[i:]) + ')')
  183. return res
  184. def preferredencoding():
  185. """Get preferred encoding.
  186. Returns the best encoding scheme for the system, based on
  187. locale.getpreferredencoding() and some further tweaks.
  188. """
  189. def yield_preferredencoding():
  190. try:
  191. pref = locale.getpreferredencoding()
  192. u'TEST'.encode(pref)
  193. except:
  194. pref = 'UTF-8'
  195. while True:
  196. yield pref
  197. return yield_preferredencoding().next()
  198. def htmlentity_transform(matchobj):
  199. """Transforms an HTML entity to a Unicode character.
  200. This function receives a match object and is intended to be used with
  201. the re.sub() function.
  202. """
  203. entity = matchobj.group(1)
  204. # Known non-numeric HTML entity
  205. if entity in htmlentitydefs.name2codepoint:
  206. return unichr(htmlentitydefs.name2codepoint[entity])
  207. # Unicode character
  208. mobj = re.match(ur'(?u)#(x?\d+)', entity)
  209. if mobj is not None:
  210. numstr = mobj.group(1)
  211. if numstr.startswith(u'x'):
  212. base = 16
  213. numstr = u'0%s' % numstr
  214. else:
  215. base = 10
  216. return unichr(long(numstr, base))
  217. # Unknown entity in name, return its literal representation
  218. return (u'&%s;' % entity)
  219. def sanitize_title(utitle):
  220. """Sanitizes a video title so it could be used as part of a filename."""
  221. utitle = re.sub(ur'(?u)&(.+?);', htmlentity_transform, utitle)
  222. return utitle.replace(unicode(os.sep), u'%')
  223. def sanitize_open(filename, open_mode):
  224. """Try to open the given filename, and slightly tweak it if this fails.
  225. Attempts to open the given filename. If this fails, it tries to change
  226. the filename slightly, step by step, until it's either able to open it
  227. or it fails and raises a final exception, like the standard open()
  228. function.
  229. It returns the tuple (stream, definitive_file_name).
  230. """
  231. try:
  232. if filename == u'-':
  233. if sys.platform == 'win32':
  234. import msvcrt
  235. msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
  236. return (sys.stdout, filename)
  237. stream = open(filename, open_mode)
  238. return (stream, filename)
  239. except (IOError, OSError), err:
  240. # In case of error, try to remove win32 forbidden chars
  241. filename = re.sub(ur'[/<>:"\|\?\*]', u'#', filename)
  242. # An exception here should be caught in the caller
  243. stream = open(filename, open_mode)
  244. return (stream, filename)
  245. def timeconvert(timestr):
  246. """Convert RFC 2822 defined time string into system timestamp"""
  247. timestamp = None
  248. timetuple = email.utils.parsedate_tz(timestr)
  249. if timetuple is not None:
  250. timestamp = email.utils.mktime_tz(timetuple)
  251. return timestamp
  252. def _simplify_title(title):
  253. return re.sub(ur'[^\w\d_\-]+', u'_', title)
  254. class DownloadError(Exception):
  255. """Download Error exception.
  256. This exception may be thrown by FileDownloader objects if they are not
  257. configured to continue on errors. They will contain the appropriate
  258. error message.
  259. """
  260. pass
  261. class SameFileError(Exception):
  262. """Same File exception.
  263. This exception will be thrown by FileDownloader objects if they detect
  264. multiple files would have to be downloaded to the same file on disk.
  265. """
  266. pass
  267. class PostProcessingError(Exception):
  268. """Post Processing exception.
  269. This exception may be raised by PostProcessor's .run() method to
  270. indicate an error in the postprocessing task.
  271. """
  272. pass
  273. class UnavailableVideoError(Exception):
  274. """Unavailable Format exception.
  275. This exception will be thrown when a video is requested
  276. in a format that is not available for that video.
  277. """
  278. pass
  279. class ContentTooShortError(Exception):
  280. """Content Too Short exception.
  281. This exception may be raised by FileDownloader objects when a file they
  282. download is too small for what the server announced first, indicating
  283. the connection was probably interrupted.
  284. """
  285. # Both in bytes
  286. downloaded = None
  287. expected = None
  288. def __init__(self, downloaded, expected):
  289. self.downloaded = downloaded
  290. self.expected = expected
  291. class YoutubeDLHandler(urllib2.HTTPHandler):
  292. """Handler for HTTP requests and responses.
  293. This class, when installed with an OpenerDirector, automatically adds
  294. the standard headers to every HTTP request and handles gzipped and
  295. deflated responses from web servers. If compression is to be avoided in
  296. a particular request, the original request in the program code only has
  297. to include the HTTP header "Youtubedl-No-Compression", which will be
  298. removed before making the real request.
  299. Part of this code was copied from:
  300. http://techknack.net/python-urllib2-handlers/
  301. Andrew Rowls, the author of that code, agreed to release it to the
  302. public domain.
  303. """
  304. @staticmethod
  305. def deflate(data):
  306. try:
  307. return zlib.decompress(data, -zlib.MAX_WBITS)
  308. except zlib.error:
  309. return zlib.decompress(data)
  310. @staticmethod
  311. def addinfourl_wrapper(stream, headers, url, code):
  312. if hasattr(urllib2.addinfourl, 'getcode'):
  313. return urllib2.addinfourl(stream, headers, url, code)
  314. ret = urllib2.addinfourl(stream, headers, url)
  315. ret.code = code
  316. return ret
  317. def http_request(self, req):
  318. for h in std_headers:
  319. if h in req.headers:
  320. del req.headers[h]
  321. req.add_header(h, std_headers[h])
  322. if 'Youtubedl-no-compression' in req.headers:
  323. if 'Accept-encoding' in req.headers:
  324. del req.headers['Accept-encoding']
  325. del req.headers['Youtubedl-no-compression']
  326. return req
  327. def http_response(self, req, resp):
  328. old_resp = resp
  329. # gzip
  330. if resp.headers.get('Content-encoding', '') == 'gzip':
  331. gz = gzip.GzipFile(fileobj=StringIO.StringIO(resp.read()), mode='r')
  332. resp = self.addinfourl_wrapper(gz, old_resp.headers, old_resp.url, old_resp.code)
  333. resp.msg = old_resp.msg
  334. # deflate
  335. if resp.headers.get('Content-encoding', '') == 'deflate':
  336. gz = StringIO.StringIO(self.deflate(resp.read()))
  337. resp = self.addinfourl_wrapper(gz, old_resp.headers, old_resp.url, old_resp.code)
  338. resp.msg = old_resp.msg
  339. return resp
  340. class FileDownloader(object):
  341. """File Downloader class.
  342. File downloader objects are the ones responsible of downloading the
  343. actual video file and writing it to disk if the user has requested
  344. it, among some other tasks. In most cases there should be one per
  345. program. As, given a video URL, the downloader doesn't know how to
  346. extract all the needed information, task that InfoExtractors do, it
  347. has to pass the URL to one of them.
  348. For this, file downloader objects have a method that allows
  349. InfoExtractors to be registered in a given order. When it is passed
  350. a URL, the file downloader handles it to the first InfoExtractor it
  351. finds that reports being able to handle it. The InfoExtractor extracts
  352. all the information about the video or videos the URL refers to, and
  353. asks the FileDownloader to process the video information, possibly
  354. downloading the video.
  355. File downloaders accept a lot of parameters. In order not to saturate
  356. the object constructor with arguments, it receives a dictionary of
  357. options instead. These options are available through the params
  358. attribute for the InfoExtractors to use. The FileDownloader also
  359. registers itself as the downloader in charge for the InfoExtractors
  360. that are added to it, so this is a "mutual registration".
  361. Available options:
  362. username: Username for authentication purposes.
  363. password: Password for authentication purposes.
  364. usenetrc: Use netrc for authentication instead.
  365. quiet: Do not print messages to stdout.
  366. forceurl: Force printing final URL.
  367. forcetitle: Force printing title.
  368. forcethumbnail: Force printing thumbnail URL.
  369. forcedescription: Force printing description.
  370. forcefilename: Force printing final filename.
  371. simulate: Do not download the video files.
  372. format: Video format code.
  373. format_limit: Highest quality format to try.
  374. outtmpl: Template for output names.
  375. ignoreerrors: Do not stop on download errors.
  376. ratelimit: Download speed limit, in bytes/sec.
  377. nooverwrites: Prevent overwriting files.
  378. retries: Number of times to retry for HTTP error 5xx
  379. continuedl: Try to continue downloads if possible.
  380. noprogress: Do not print the progress bar.
  381. playliststart: Playlist item to start at.
  382. playlistend: Playlist item to end at.
  383. matchtitle: Download only matching titles.
  384. rejecttitle: Reject downloads for matching titles.
  385. logtostderr: Log messages to stderr instead of stdout.
  386. consoletitle: Display progress in console window's titlebar.
  387. nopart: Do not use temporary .part files.
  388. updatetime: Use the Last-modified header to set output file timestamps.
  389. writedescription: Write the video description to a .description file
  390. writeinfojson: Write the video description to a .info.json file
  391. """
  392. params = None
  393. _ies = []
  394. _pps = []
  395. _download_retcode = None
  396. _num_downloads = None
  397. _screen_file = None
  398. def __init__(self, params):
  399. """Create a FileDownloader object with the given options."""
  400. self._ies = []
  401. self._pps = []
  402. self._download_retcode = 0
  403. self._num_downloads = 0
  404. self._screen_file = [sys.stdout, sys.stderr][params.get('logtostderr', False)]
  405. self.params = params
  406. @staticmethod
  407. def format_bytes(bytes):
  408. if bytes is None:
  409. return 'N/A'
  410. if type(bytes) is str:
  411. bytes = float(bytes)
  412. if bytes == 0.0:
  413. exponent = 0
  414. else:
  415. exponent = long(math.log(bytes, 1024.0))
  416. suffix = 'bkMGTPEZY'[exponent]
  417. converted = float(bytes) / float(1024 ** exponent)
  418. return '%.2f%s' % (converted, suffix)
  419. @staticmethod
  420. def calc_percent(byte_counter, data_len):
  421. if data_len is None:
  422. return '---.-%'
  423. return '%6s' % ('%3.1f%%' % (float(byte_counter) / float(data_len) * 100.0))
  424. @staticmethod
  425. def calc_eta(start, now, total, current):
  426. if total is None:
  427. return '--:--'
  428. dif = now - start
  429. if current == 0 or dif < 0.001: # One millisecond
  430. return '--:--'
  431. rate = float(current) / dif
  432. eta = long((float(total) - float(current)) / rate)
  433. (eta_mins, eta_secs) = divmod(eta, 60)
  434. if eta_mins > 99:
  435. return '--:--'
  436. return '%02d:%02d' % (eta_mins, eta_secs)
  437. @staticmethod
  438. def calc_speed(start, now, bytes):
  439. dif = now - start
  440. if bytes == 0 or dif < 0.001: # One millisecond
  441. return '%10s' % '---b/s'
  442. return '%10s' % ('%s/s' % FileDownloader.format_bytes(float(bytes) / dif))
  443. @staticmethod
  444. def best_block_size(elapsed_time, bytes):
  445. new_min = max(bytes / 2.0, 1.0)
  446. new_max = min(max(bytes * 2.0, 1.0), 4194304) # Do not surpass 4 MB
  447. if elapsed_time < 0.001:
  448. return long(new_max)
  449. rate = bytes / elapsed_time
  450. if rate > new_max:
  451. return long(new_max)
  452. if rate < new_min:
  453. return long(new_min)
  454. return long(rate)
  455. @staticmethod
  456. def parse_bytes(bytestr):
  457. """Parse a string indicating a byte quantity into a long integer."""
  458. matchobj = re.match(r'(?i)^(\d+(?:\.\d+)?)([kMGTPEZY]?)$', bytestr)
  459. if matchobj is None:
  460. return None
  461. number = float(matchobj.group(1))
  462. multiplier = 1024.0 ** 'bkmgtpezy'.index(matchobj.group(2).lower())
  463. return long(round(number * multiplier))
  464. def add_info_extractor(self, ie):
  465. """Add an InfoExtractor object to the end of the list."""
  466. self._ies.append(ie)
  467. ie.set_downloader(self)
  468. def add_post_processor(self, pp):
  469. """Add a PostProcessor object to the end of the chain."""
  470. self._pps.append(pp)
  471. pp.set_downloader(self)
  472. def to_screen(self, message, skip_eol=False, ignore_encoding_errors=False):
  473. """Print message to stdout if not in quiet mode."""
  474. try:
  475. if not self.params.get('quiet', False):
  476. terminator = [u'\n', u''][skip_eol]
  477. print >>self._screen_file, (u'%s%s' % (message, terminator)).encode(preferredencoding()),
  478. self._screen_file.flush()
  479. except (UnicodeEncodeError), err:
  480. if not ignore_encoding_errors:
  481. raise
  482. def to_stderr(self, message):
  483. """Print message to stderr."""
  484. print >>sys.stderr, message.encode(preferredencoding())
  485. def to_cons_title(self, message):
  486. """Set console/terminal window title to message."""
  487. if not self.params.get('consoletitle', False):
  488. return
  489. if os.name == 'nt' and ctypes.windll.kernel32.GetConsoleWindow():
  490. # c_wchar_p() might not be necessary if `message` is
  491. # already of type unicode()
  492. ctypes.windll.kernel32.SetConsoleTitleW(ctypes.c_wchar_p(message))
  493. elif 'TERM' in os.environ:
  494. sys.stderr.write('\033]0;%s\007' % message.encode(preferredencoding()))
  495. def fixed_template(self):
  496. """Checks if the output template is fixed."""
  497. return (re.search(ur'(?u)%\(.+?\)s', self.params['outtmpl']) is None)
  498. def trouble(self, message=None):
  499. """Determine action to take when a download problem appears.
  500. Depending on if the downloader has been configured to ignore
  501. download errors or not, this method may throw an exception or
  502. not when errors are found, after printing the message.
  503. """
  504. if message is not None:
  505. self.to_stderr(message)
  506. if not self.params.get('ignoreerrors', False):
  507. raise DownloadError(message)
  508. self._download_retcode = 1
  509. def slow_down(self, start_time, byte_counter):
  510. """Sleep if the download speed is over the rate limit."""
  511. rate_limit = self.params.get('ratelimit', None)
  512. if rate_limit is None or byte_counter == 0:
  513. return
  514. now = time.time()
  515. elapsed = now - start_time
  516. if elapsed <= 0.0:
  517. return
  518. speed = float(byte_counter) / elapsed
  519. if speed > rate_limit:
  520. time.sleep((byte_counter - rate_limit * (now - start_time)) / rate_limit)
  521. def temp_name(self, filename):
  522. """Returns a temporary filename for the given filename."""
  523. if self.params.get('nopart', False) or filename == u'-' or \
  524. (os.path.exists(filename) and not os.path.isfile(filename)):
  525. return filename
  526. return filename + u'.part'
  527. def undo_temp_name(self, filename):
  528. if filename.endswith(u'.part'):
  529. return filename[:-len(u'.part')]
  530. return filename
  531. def try_rename(self, old_filename, new_filename):
  532. try:
  533. if old_filename == new_filename:
  534. return
  535. os.rename(old_filename, new_filename)
  536. except (IOError, OSError), err:
  537. self.trouble(u'ERROR: unable to rename file')
  538. def try_utime(self, filename, last_modified_hdr):
  539. """Try to set the last-modified time of the given file."""
  540. if last_modified_hdr is None:
  541. return
  542. if not os.path.isfile(filename):
  543. return
  544. timestr = last_modified_hdr
  545. if timestr is None:
  546. return
  547. filetime = timeconvert(timestr)
  548. if filetime is None:
  549. return filetime
  550. try:
  551. os.utime(filename, (time.time(), filetime))
  552. except:
  553. pass
  554. return filetime
  555. def report_writedescription(self, descfn):
  556. """ Report that the description file is being written """
  557. self.to_screen(u'[info] Writing video description to: %s' % descfn, ignore_encoding_errors=True)
  558. def report_writeinfojson(self, infofn):
  559. """ Report that the metadata file has been written """
  560. self.to_screen(u'[info] Video description metadata as JSON to: %s' % infofn, ignore_encoding_errors=True)
  561. def report_destination(self, filename):
  562. """Report destination filename."""
  563. self.to_screen(u'[download] Destination: %s' % filename, ignore_encoding_errors=True)
  564. def report_progress(self, percent_str, data_len_str, speed_str, eta_str):
  565. """Report download progress."""
  566. if self.params.get('noprogress', False):
  567. return
  568. self.to_screen(u'\r[download] %s of %s at %s ETA %s' %
  569. (percent_str, data_len_str, speed_str, eta_str), skip_eol=True)
  570. self.to_cons_title(u'youtube-dl - %s of %s at %s ETA %s' %
  571. (percent_str.strip(), data_len_str.strip(), speed_str.strip(), eta_str.strip()))
  572. def report_resuming_byte(self, resume_len):
  573. """Report attempt to resume at given byte."""
  574. self.to_screen(u'[download] Resuming download at byte %s' % resume_len)
  575. def report_retry(self, count, retries):
  576. """Report retry in case of HTTP error 5xx"""
  577. self.to_screen(u'[download] Got server HTTP error. Retrying (attempt %d of %d)...' % (count, retries))
  578. def report_file_already_downloaded(self, file_name):
  579. """Report file has already been fully downloaded."""
  580. try:
  581. self.to_screen(u'[download] %s has already been downloaded' % file_name)
  582. except (UnicodeEncodeError), err:
  583. self.to_screen(u'[download] The file has already been downloaded')
  584. def report_unable_to_resume(self):
  585. """Report it was impossible to resume download."""
  586. self.to_screen(u'[download] Unable to resume')
  587. def report_finish(self):
  588. """Report download finished."""
  589. if self.params.get('noprogress', False):
  590. self.to_screen(u'[download] Download completed')
  591. else:
  592. self.to_screen(u'')
  593. def increment_downloads(self):
  594. """Increment the ordinal that assigns a number to each file."""
  595. self._num_downloads += 1
  596. def prepare_filename(self, info_dict):
  597. """Generate the output filename."""
  598. try:
  599. template_dict = dict(info_dict)
  600. template_dict['epoch'] = unicode(long(time.time()))
  601. template_dict['autonumber'] = unicode('%05d' % self._num_downloads)
  602. filename = self.params['outtmpl'] % template_dict
  603. return filename
  604. except (ValueError, KeyError), err:
  605. self.trouble(u'ERROR: invalid system charset or erroneous output template')
  606. return None
  607. def process_info(self, info_dict):
  608. """Process a single dictionary returned by an InfoExtractor."""
  609. filename = self.prepare_filename(info_dict)
  610. # Forced printings
  611. if self.params.get('forcetitle', False):
  612. print info_dict['title'].encode(preferredencoding(), 'xmlcharrefreplace')
  613. if self.params.get('forceurl', False):
  614. print info_dict['url'].encode(preferredencoding(), 'xmlcharrefreplace')
  615. if self.params.get('forcethumbnail', False) and 'thumbnail' in info_dict:
  616. print info_dict['thumbnail'].encode(preferredencoding(), 'xmlcharrefreplace')
  617. if self.params.get('forcedescription', False) and 'description' in info_dict:
  618. print info_dict['description'].encode(preferredencoding(), 'xmlcharrefreplace')
  619. if self.params.get('forcefilename', False) and filename is not None:
  620. print filename.encode(preferredencoding(), 'xmlcharrefreplace')
  621. if self.params.get('forceformat', False):
  622. print info_dict['format'].encode(preferredencoding(), 'xmlcharrefreplace')
  623. # Do nothing else if in simulate mode
  624. if self.params.get('simulate', False):
  625. return
  626. if filename is None:
  627. return
  628. matchtitle=self.params.get('matchtitle',False)
  629. rejecttitle=self.params.get('rejecttitle',False)
  630. title=info_dict['title'].encode(preferredencoding(), 'xmlcharrefreplace')
  631. if matchtitle and not re.search(matchtitle, title, re.IGNORECASE):
  632. self.to_screen(u'[download] "%s" title did not match pattern "%s"' % (title, matchtitle))
  633. return
  634. if rejecttitle and re.search(rejecttitle, title, re.IGNORECASE):
  635. self.to_screen(u'[download] "%s" title matched reject pattern "%s"' % (title, rejecttitle))
  636. return
  637. if self.params.get('nooverwrites', False) and os.path.exists(filename):
  638. self.to_stderr(u'WARNING: file exists and will be skipped')
  639. return
  640. try:
  641. dn = os.path.dirname(filename)
  642. if dn != '' and not os.path.exists(dn):
  643. os.makedirs(dn)
  644. except (OSError, IOError), err:
  645. self.trouble(u'ERROR: unable to create directory ' + unicode(err))
  646. return
  647. if self.params.get('writedescription', False):
  648. try:
  649. descfn = filename + '.description'
  650. self.report_writedescription(descfn)
  651. descfile = open(descfn, 'wb')
  652. try:
  653. descfile.write(info_dict['description'].encode('utf-8'))
  654. finally:
  655. descfile.close()
  656. except (OSError, IOError):
  657. self.trouble(u'ERROR: Cannot write description file ' + descfn)
  658. return
  659. if self.params.get('writeinfojson', False):
  660. infofn = filename + '.info.json'
  661. self.report_writeinfojson(infofn)
  662. try:
  663. json.dump
  664. except (NameError,AttributeError):
  665. self.trouble(u'ERROR: No JSON encoder found. Update to Python 2.6+, setup a json module, or leave out --write-info-json.')
  666. return
  667. try:
  668. infof = open(infofn, 'wb')
  669. try:
  670. json_info_dict = dict((k,v) for k,v in info_dict.iteritems() if not k in ('urlhandle',))
  671. json.dump(json_info_dict, infof)
  672. finally:
  673. infof.close()
  674. except (OSError, IOError):
  675. self.trouble(u'ERROR: Cannot write metadata to JSON file ' + infofn)
  676. return
  677. if not self.params.get('skip_download', False):
  678. try:
  679. success = self._do_download(filename, info_dict)
  680. except (OSError, IOError), err:
  681. raise UnavailableVideoError
  682. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  683. self.trouble(u'ERROR: unable to download video data: %s' % str(err))
  684. return
  685. except (ContentTooShortError, ), err:
  686. self.trouble(u'ERROR: content too short (expected %s bytes and served %s)' % (err.expected, err.downloaded))
  687. return
  688. if success:
  689. try:
  690. self.post_process(filename, info_dict)
  691. except (PostProcessingError), err:
  692. self.trouble(u'ERROR: postprocessing: %s' % str(err))
  693. return
  694. def download(self, url_list):
  695. """Download a given list of URLs."""
  696. if len(url_list) > 1 and self.fixed_template():
  697. raise SameFileError(self.params['outtmpl'])
  698. for url in url_list:
  699. suitable_found = False
  700. for ie in self._ies:
  701. # Go to next InfoExtractor if not suitable
  702. if not ie.suitable(url):
  703. continue
  704. # Suitable InfoExtractor found
  705. suitable_found = True
  706. # Extract information from URL and process it
  707. ie.extract(url)
  708. # Suitable InfoExtractor had been found; go to next URL
  709. break
  710. if not suitable_found:
  711. self.trouble(u'ERROR: no suitable InfoExtractor: %s' % url)
  712. return self._download_retcode
  713. def post_process(self, filename, ie_info):
  714. """Run the postprocessing chain on the given file."""
  715. info = dict(ie_info)
  716. info['filepath'] = filename
  717. for pp in self._pps:
  718. info = pp.run(info)
  719. if info is None:
  720. break
  721. def _download_with_rtmpdump(self, filename, url, player_url):
  722. self.report_destination(filename)
  723. tmpfilename = self.temp_name(filename)
  724. # Check for rtmpdump first
  725. try:
  726. subprocess.call(['rtmpdump', '-h'], stdout=(file(os.path.devnull, 'w')), stderr=subprocess.STDOUT)
  727. except (OSError, IOError):
  728. self.trouble(u'ERROR: RTMP download detected but "rtmpdump" could not be run')
  729. return False
  730. # Download using rtmpdump. rtmpdump returns exit code 2 when
  731. # the connection was interrumpted and resuming appears to be
  732. # possible. This is part of rtmpdump's normal usage, AFAIK.
  733. basic_args = ['rtmpdump', '-q'] + [[], ['-W', player_url]][player_url is not None] + ['-r', url, '-o', tmpfilename]
  734. retval = subprocess.call(basic_args + [[], ['-e', '-k', '1']][self.params.get('continuedl', False)])
  735. while retval == 2 or retval == 1:
  736. prevsize = os.path.getsize(tmpfilename)
  737. self.to_screen(u'\r[rtmpdump] %s bytes' % prevsize, skip_eol=True)
  738. time.sleep(5.0) # This seems to be needed
  739. retval = subprocess.call(basic_args + ['-e'] + [[], ['-k', '1']][retval == 1])
  740. cursize = os.path.getsize(tmpfilename)
  741. if prevsize == cursize and retval == 1:
  742. break
  743. # Some rtmp streams seem abort after ~ 99.8%. Don't complain for those
  744. if prevsize == cursize and retval == 2 and cursize > 1024:
  745. self.to_screen(u'\r[rtmpdump] Could not download the whole video. This can happen for some advertisements.')
  746. retval = 0
  747. break
  748. if retval == 0:
  749. self.to_screen(u'\r[rtmpdump] %s bytes' % os.path.getsize(tmpfilename))
  750. self.try_rename(tmpfilename, filename)
  751. return True
  752. else:
  753. self.trouble(u'\nERROR: rtmpdump exited with code %d' % retval)
  754. return False
  755. def _do_download(self, filename, info_dict):
  756. url = info_dict['url']
  757. player_url = info_dict.get('player_url', None)
  758. # Check file already present
  759. if self.params.get('continuedl', False) and os.path.isfile(filename) and not self.params.get('nopart', False):
  760. self.report_file_already_downloaded(filename)
  761. return True
  762. # Attempt to download using rtmpdump
  763. if url.startswith('rtmp'):
  764. return self._download_with_rtmpdump(filename, url, player_url)
  765. tmpfilename = self.temp_name(filename)
  766. stream = None
  767. # Do not include the Accept-Encoding header
  768. headers = {'Youtubedl-no-compression': 'True'}
  769. basic_request = urllib2.Request(url, None, headers)
  770. request = urllib2.Request(url, None, headers)
  771. # Establish possible resume length
  772. if os.path.isfile(tmpfilename):
  773. resume_len = os.path.getsize(tmpfilename)
  774. else:
  775. resume_len = 0
  776. open_mode = 'wb'
  777. if resume_len != 0:
  778. if self.params.get('continuedl', False):
  779. self.report_resuming_byte(resume_len)
  780. request.add_header('Range','bytes=%d-' % resume_len)
  781. open_mode = 'ab'
  782. else:
  783. resume_len = 0
  784. count = 0
  785. retries = self.params.get('retries', 0)
  786. while count <= retries:
  787. # Establish connection
  788. try:
  789. if count == 0 and 'urlhandle' in info_dict:
  790. data = info_dict['urlhandle']
  791. data = urllib2.urlopen(request)
  792. break
  793. except (urllib2.HTTPError, ), err:
  794. if (err.code < 500 or err.code >= 600) and err.code != 416:
  795. # Unexpected HTTP error
  796. raise
  797. elif err.code == 416:
  798. # Unable to resume (requested range not satisfiable)
  799. try:
  800. # Open the connection again without the range header
  801. data = urllib2.urlopen(basic_request)
  802. content_length = data.info()['Content-Length']
  803. except (urllib2.HTTPError, ), err:
  804. if err.code < 500 or err.code >= 600:
  805. raise
  806. else:
  807. # Examine the reported length
  808. if (content_length is not None and
  809. (resume_len - 100 < long(content_length) < resume_len + 100)):
  810. # The file had already been fully downloaded.
  811. # Explanation to the above condition: in issue #175 it was revealed that
  812. # YouTube sometimes adds or removes a few bytes from the end of the file,
  813. # changing the file size slightly and causing problems for some users. So
  814. # I decided to implement a suggested change and consider the file
  815. # completely downloaded if the file size differs less than 100 bytes from
  816. # the one in the hard drive.
  817. self.report_file_already_downloaded(filename)
  818. self.try_rename(tmpfilename, filename)
  819. return True
  820. else:
  821. # The length does not match, we start the download over
  822. self.report_unable_to_resume()
  823. open_mode = 'wb'
  824. break
  825. # Retry
  826. count += 1
  827. if count <= retries:
  828. self.report_retry(count, retries)
  829. if count > retries:
  830. self.trouble(u'ERROR: giving up after %s retries' % retries)
  831. return False
  832. data_len = data.info().get('Content-length', None)
  833. if data_len is not None:
  834. data_len = long(data_len) + resume_len
  835. data_len_str = self.format_bytes(data_len)
  836. byte_counter = 0 + resume_len
  837. block_size = 1024
  838. start = time.time()
  839. while True:
  840. # Download and write
  841. before = time.time()
  842. data_block = data.read(block_size)
  843. after = time.time()
  844. if len(data_block) == 0:
  845. break
  846. byte_counter += len(data_block)
  847. # Open file just in time
  848. if stream is None:
  849. try:
  850. (stream, tmpfilename) = sanitize_open(tmpfilename, open_mode)
  851. assert stream is not None
  852. filename = self.undo_temp_name(tmpfilename)
  853. self.report_destination(filename)
  854. except (OSError, IOError), err:
  855. self.trouble(u'ERROR: unable to open for writing: %s' % str(err))
  856. return False
  857. try:
  858. stream.write(data_block)
  859. except (IOError, OSError), err:
  860. self.trouble(u'\nERROR: unable to write data: %s' % str(err))
  861. return False
  862. block_size = self.best_block_size(after - before, len(data_block))
  863. # Progress message
  864. speed_str = self.calc_speed(start, time.time(), byte_counter - resume_len)
  865. if data_len is None:
  866. self.report_progress('Unknown %', data_len_str, speed_str, 'Unknown ETA')
  867. else:
  868. percent_str = self.calc_percent(byte_counter, data_len)
  869. eta_str = self.calc_eta(start, time.time(), data_len - resume_len, byte_counter - resume_len)
  870. self.report_progress(percent_str, data_len_str, speed_str, eta_str)
  871. # Apply rate limit
  872. self.slow_down(start, byte_counter - resume_len)
  873. if stream is None:
  874. self.trouble(u'\nERROR: Did not get any data blocks')
  875. return False
  876. stream.close()
  877. self.report_finish()
  878. if data_len is not None and byte_counter != data_len:
  879. raise ContentTooShortError(byte_counter, long(data_len))
  880. self.try_rename(tmpfilename, filename)
  881. # Update file modification time
  882. if self.params.get('updatetime', True):
  883. info_dict['filetime'] = self.try_utime(filename, data.info().get('last-modified', None))
  884. return True
  885. class InfoExtractor(object):
  886. """Information Extractor class.
  887. Information extractors are the classes that, given a URL, extract
  888. information from the video (or videos) the URL refers to. This
  889. information includes the real video URL, the video title and simplified
  890. title, author and others. The information is stored in a dictionary
  891. which is then passed to the FileDownloader. The FileDownloader
  892. processes this information possibly downloading the video to the file
  893. system, among other possible outcomes. The dictionaries must include
  894. the following fields:
  895. id: Video identifier.
  896. url: Final video URL.
  897. uploader: Nickname of the video uploader.
  898. title: Literal title.
  899. stitle: Simplified title.
  900. ext: Video filename extension.
  901. format: Video format.
  902. player_url: SWF Player URL (may be None).
  903. The following fields are optional. Their primary purpose is to allow
  904. youtube-dl to serve as the backend for a video search function, such
  905. as the one in youtube2mp3. They are only used when their respective
  906. forced printing functions are called:
  907. thumbnail: Full URL to a video thumbnail image.
  908. description: One-line video description.
  909. Subclasses of this one should re-define the _real_initialize() and
  910. _real_extract() methods and define a _VALID_URL regexp.
  911. Probably, they should also be added to the list of extractors.
  912. """
  913. _ready = False
  914. _downloader = None
  915. def __init__(self, downloader=None):
  916. """Constructor. Receives an optional downloader."""
  917. self._ready = False
  918. self.set_downloader(downloader)
  919. def suitable(self, url):
  920. """Receives a URL and returns True if suitable for this IE."""
  921. return re.match(self._VALID_URL, url) is not None
  922. def initialize(self):
  923. """Initializes an instance (authentication, etc)."""
  924. if not self._ready:
  925. self._real_initialize()
  926. self._ready = True
  927. def extract(self, url):
  928. """Extracts URL information and returns it in list of dicts."""
  929. self.initialize()
  930. return self._real_extract(url)
  931. def set_downloader(self, downloader):
  932. """Sets the downloader for this IE."""
  933. self._downloader = downloader
  934. def _real_initialize(self):
  935. """Real initialization process. Redefine in subclasses."""
  936. pass
  937. def _real_extract(self, url):
  938. """Real extraction process. Redefine in subclasses."""
  939. pass
  940. class YoutubeIE(InfoExtractor):
  941. """Information extractor for youtube.com."""
  942. _VALID_URL = r'^((?:https?://)?(?:youtu\.be/|(?:\w+\.)?youtube(?:-nocookie)?\.com/)(?!view_play_list|my_playlists|artist|playlist)(?:(?:(?:v|embed|e)/)|(?:(?:watch(?:_popup)?(?:\.php)?)?(?:\?|#!?)(?:.+&)?v=))?)?([0-9A-Za-z_-]+)(?(1).+)?$'
  943. _LANG_URL = r'http://www.youtube.com/?hl=en&persist_hl=1&gl=US&persist_gl=1&opt_out_ackd=1'
  944. _LOGIN_URL = 'https://www.youtube.com/signup?next=/&gl=US&hl=en'
  945. _AGE_URL = 'http://www.youtube.com/verify_age?next_url=/&gl=US&hl=en'
  946. _NETRC_MACHINE = 'youtube'
  947. # Listed in order of quality
  948. _available_formats = ['38', '37', '22', '45', '35', '44', '34', '18', '43', '6', '5', '17', '13']
  949. _video_extensions = {
  950. '13': '3gp',
  951. '17': 'mp4',
  952. '18': 'mp4',
  953. '22': 'mp4',
  954. '37': 'mp4',
  955. '38': 'video', # You actually don't know if this will be MOV, AVI or whatever
  956. '43': 'webm',
  957. '44': 'webm',
  958. '45': 'webm',
  959. }
  960. _video_dimensions = {
  961. '5': '240x400',
  962. '6': '???',
  963. '13': '???',
  964. '17': '144x176',
  965. '18': '360x640',
  966. '22': '720x1280',
  967. '34': '360x640',
  968. '35': '480x854',
  969. '37': '1080x1920',
  970. '38': '3072x4096',
  971. '43': '360x640',
  972. '44': '480x854',
  973. '45': '720x1280',
  974. }
  975. IE_NAME = u'youtube'
  976. def report_lang(self):
  977. """Report attempt to set language."""
  978. self._downloader.to_screen(u'[youtube] Setting language')
  979. def report_login(self):
  980. """Report attempt to log in."""
  981. self._downloader.to_screen(u'[youtube] Logging in')
  982. def report_age_confirmation(self):
  983. """Report attempt to confirm age."""
  984. self._downloader.to_screen(u'[youtube] Confirming age')
  985. def report_video_webpage_download(self, video_id):
  986. """Report attempt to download video webpage."""
  987. self._downloader.to_screen(u'[youtube] %s: Downloading video webpage' % video_id)
  988. def report_video_info_webpage_download(self, video_id):
  989. """Report attempt to download video info webpage."""
  990. self._downloader.to_screen(u'[youtube] %s: Downloading video info webpage' % video_id)
  991. def report_information_extraction(self, video_id):
  992. """Report attempt to extract video information."""
  993. self._downloader.to_screen(u'[youtube] %s: Extracting video information' % video_id)
  994. def report_unavailable_format(self, video_id, format):
  995. """Report extracted video URL."""
  996. self._downloader.to_screen(u'[youtube] %s: Format %s not available' % (video_id, format))
  997. def report_rtmp_download(self):
  998. """Indicate the download will use the RTMP protocol."""
  999. self._downloader.to_screen(u'[youtube] RTMP download detected')
  1000. def _print_formats(self, formats):
  1001. print 'Available formats:'
  1002. for x in formats:
  1003. print '%s\t:\t%s\t[%s]' %(x, self._video_extensions.get(x, 'flv'), self._video_dimensions.get(x, '???'))
  1004. def _real_initialize(self):
  1005. if self._downloader is None:
  1006. return
  1007. username = None
  1008. password = None
  1009. downloader_params = self._downloader.params
  1010. # Attempt to use provided username and password or .netrc data
  1011. if downloader_params.get('username', None) is not None:
  1012. username = downloader_params['username']
  1013. password = downloader_params['password']
  1014. elif downloader_params.get('usenetrc', False):
  1015. try:
  1016. info = netrc.netrc().authenticators(self._NETRC_MACHINE)
  1017. if info is not None:
  1018. username = info[0]
  1019. password = info[2]
  1020. else:
  1021. raise netrc.NetrcParseError('No authenticators for %s' % self._NETRC_MACHINE)
  1022. except (IOError, netrc.NetrcParseError), err:
  1023. self._downloader.to_stderr(u'WARNING: parsing .netrc: %s' % str(err))
  1024. return
  1025. # Set language
  1026. request = urllib2.Request(self._LANG_URL)
  1027. try:
  1028. self.report_lang()
  1029. urllib2.urlopen(request).read()
  1030. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1031. self._downloader.to_stderr(u'WARNING: unable to set language: %s' % str(err))
  1032. return
  1033. # No authentication to be performed
  1034. if username is None:
  1035. return
  1036. # Log in
  1037. login_form = {
  1038. 'current_form': 'loginForm',
  1039. 'next': '/',
  1040. 'action_login': 'Log In',
  1041. 'username': username,
  1042. 'password': password,
  1043. }
  1044. request = urllib2.Request(self._LOGIN_URL, urllib.urlencode(login_form))
  1045. try:
  1046. self.report_login()
  1047. login_results = urllib2.urlopen(request).read()
  1048. if re.search(r'(?i)<form[^>]* name="loginForm"', login_results) is not None:
  1049. self._downloader.to_stderr(u'WARNING: unable to log in: bad username or password')
  1050. return
  1051. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1052. self._downloader.to_stderr(u'WARNING: unable to log in: %s' % str(err))
  1053. return
  1054. # Confirm age
  1055. age_form = {
  1056. 'next_url': '/',
  1057. 'action_confirm': 'Confirm',
  1058. }
  1059. request = urllib2.Request(self._AGE_URL, urllib.urlencode(age_form))
  1060. try:
  1061. self.report_age_confirmation()
  1062. age_results = urllib2.urlopen(request).read()
  1063. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1064. self._downloader.trouble(u'ERROR: unable to confirm age: %s' % str(err))
  1065. return
  1066. def _real_extract(self, url):
  1067. # Extract video id from URL
  1068. mobj = re.match(self._VALID_URL, url)
  1069. if mobj is None:
  1070. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  1071. return
  1072. video_id = mobj.group(2)
  1073. # Get video webpage
  1074. self.report_video_webpage_download(video_id)
  1075. request = urllib2.Request('http://www.youtube.com/watch?v=%s&gl=US&hl=en&has_verified=1' % video_id)
  1076. try:
  1077. video_webpage = urllib2.urlopen(request).read()
  1078. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1079. self._downloader.trouble(u'ERROR: unable to download video webpage: %s' % str(err))
  1080. return
  1081. # Attempt to extract SWF player URL
  1082. mobj = re.search(r'swfConfig.*?"(http:\\/\\/.*?watch.*?-.*?\.swf)"', video_webpage)
  1083. if mobj is not None:
  1084. player_url = re.sub(r'\\(.)', r'\1', mobj.group(1))
  1085. else:
  1086. player_url = None
  1087. # Get video info
  1088. self.report_video_info_webpage_download(video_id)
  1089. for el_type in ['&el=embedded', '&el=detailpage', '&el=vevo', '']:
  1090. video_info_url = ('http://www.youtube.com/get_video_info?&video_id=%s%s&ps=default&eurl=&gl=US&hl=en'
  1091. % (video_id, el_type))
  1092. request = urllib2.Request(video_info_url)
  1093. try:
  1094. video_info_webpage = urllib2.urlopen(request).read()
  1095. video_info = parse_qs(video_info_webpage)
  1096. if 'token' in video_info:
  1097. break
  1098. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1099. self._downloader.trouble(u'ERROR: unable to download video info webpage: %s' % str(err))
  1100. return
  1101. if 'token' not in video_info:
  1102. if 'reason' in video_info:
  1103. self._downloader.trouble(u'ERROR: YouTube said: %s' % video_info['reason'][0].decode('utf-8'))
  1104. else:
  1105. self._downloader.trouble(u'ERROR: "token" parameter not in video info for unknown reason')
  1106. return
  1107. # Start extracting information
  1108. self.report_information_extraction(video_id)
  1109. # uploader
  1110. if 'author' not in video_info:
  1111. self._downloader.trouble(u'ERROR: unable to extract uploader nickname')
  1112. return
  1113. video_uploader = urllib.unquote_plus(video_info['author'][0])
  1114. # title
  1115. if 'title' not in video_info:
  1116. self._downloader.trouble(u'ERROR: unable to extract video title')
  1117. return
  1118. video_title = urllib.unquote_plus(video_info['title'][0])
  1119. video_title = video_title.decode('utf-8')
  1120. video_title = sanitize_title(video_title)
  1121. # simplified title
  1122. simple_title = re.sub(ur'(?u)([^%s]+)' % simple_title_chars, ur'_', video_title)
  1123. simple_title = simple_title.strip(ur'_')
  1124. # thumbnail image
  1125. if 'thumbnail_url' not in video_info:
  1126. self._downloader.trouble(u'WARNING: unable to extract video thumbnail')
  1127. video_thumbnail = ''
  1128. else: # don't panic if we can't find it
  1129. video_thumbnail = urllib.unquote_plus(video_info['thumbnail_url'][0])
  1130. # upload date
  1131. upload_date = u'NA'
  1132. mobj = re.search(r'id="eow-date.*?>(.*?)</span>', video_webpage, re.DOTALL)
  1133. if mobj is not None:
  1134. upload_date = ' '.join(re.sub(r'[/,-]', r' ', mobj.group(1)).split())
  1135. format_expressions = ['%d %B %Y', '%B %d %Y', '%b %d %Y']
  1136. for expression in format_expressions:
  1137. try:
  1138. upload_date = datetime.datetime.strptime(upload_date, expression).strftime('%Y%m%d')
  1139. except:
  1140. pass
  1141. # description
  1142. try:
  1143. lxml.etree
  1144. except NameError:
  1145. video_description = u'No description available.'
  1146. if self._downloader.params.get('forcedescription', False) or self._downloader.params.get('writedescription', False):
  1147. mobj = re.search(r'<meta name="description" content="(.*)"(?:\s*/)?>', video_webpage)
  1148. if mobj is not None:
  1149. video_description = mobj.group(1).decode('utf-8')
  1150. else:
  1151. html_parser = lxml.etree.HTMLParser(encoding='utf-8')
  1152. vwebpage_doc = lxml.etree.parse(StringIO.StringIO(video_webpage), html_parser)
  1153. video_description = u''.join(vwebpage_doc.xpath('id("eow-description")//text()'))
  1154. # TODO use another parser
  1155. # token
  1156. video_token = urllib.unquote_plus(video_info['token'][0])
  1157. # Decide which formats to download
  1158. req_format = self._downloader.params.get('format', None)
  1159. if 'conn' in video_info and video_info['conn'][0].startswith('rtmp'):
  1160. self.report_rtmp_download()
  1161. video_url_list = [(None, video_info['conn'][0])]
  1162. elif 'url_encoded_fmt_stream_map' in video_info and len(video_info['url_encoded_fmt_stream_map']) >= 1:
  1163. url_data_strs = video_info['url_encoded_fmt_stream_map'][0].split(',')
  1164. url_data = [parse_qs(uds) for uds in url_data_strs]
  1165. url_data = filter(lambda ud: 'itag' in ud and 'url' in ud, url_data)
  1166. url_map = dict((ud['itag'][0], ud['url'][0]) for ud in url_data)
  1167. format_limit = self._downloader.params.get('format_limit', None)
  1168. if format_limit is not None and format_limit in self._available_formats:
  1169. format_list = self._available_formats[self._available_formats.index(format_limit):]
  1170. else:
  1171. format_list = self._available_formats
  1172. existing_formats = [x for x in format_list if x in url_map]
  1173. if len(existing_formats) == 0:
  1174. self._downloader.trouble(u'ERROR: no known formats available for video')
  1175. return
  1176. if self._downloader.params.get('listformats', None):
  1177. self._print_formats(existing_formats)
  1178. return
  1179. if req_format is None or req_format == 'best':
  1180. video_url_list = [(existing_formats[0], url_map[existing_formats[0]])] # Best quality
  1181. elif req_format == 'worst':
  1182. video_url_list = [(existing_formats[len(existing_formats)-1], url_map[existing_formats[len(existing_formats)-1]])] # worst quality
  1183. elif req_format in ('-1', 'all'):
  1184. video_url_list = [(f, url_map[f]) for f in existing_formats] # All formats
  1185. else:
  1186. # Specific formats. We pick the first in a slash-delimeted sequence.
  1187. # For example, if '1/2/3/4' is requested and '2' and '4' are available, we pick '2'.
  1188. req_formats = req_format.split('/')
  1189. video_url_list = None
  1190. for rf in req_formats:
  1191. if rf in url_map:
  1192. video_url_list = [(rf, url_map[rf])]
  1193. break
  1194. if video_url_list is None:
  1195. self._downloader.trouble(u'ERROR: requested format not available')
  1196. return
  1197. else:
  1198. self._downloader.trouble(u'ERROR: no conn or url_encoded_fmt_stream_map information found in video info')
  1199. return
  1200. for format_param, video_real_url in video_url_list:
  1201. # At this point we have a new video
  1202. self._downloader.increment_downloads()
  1203. # Extension
  1204. video_extension = self._video_extensions.get(format_param, 'flv')
  1205. try:
  1206. # Process video information
  1207. self._downloader.process_info({
  1208. 'id': video_id.decode('utf-8'),
  1209. 'url': video_real_url.decode('utf-8'),
  1210. 'uploader': video_uploader.decode('utf-8'),
  1211. 'upload_date': upload_date,
  1212. 'title': video_title,
  1213. 'stitle': simple_title,
  1214. 'ext': video_extension.decode('utf-8'),
  1215. 'format': (format_param is None and u'NA' or format_param.decode('utf-8')),
  1216. 'thumbnail': video_thumbnail.decode('utf-8'),
  1217. 'description': video_description,
  1218. 'player_url': player_url,
  1219. })
  1220. except UnavailableVideoError, err:
  1221. self._downloader.trouble(u'\nERROR: unable to download video')
  1222. class MetacafeIE(InfoExtractor):
  1223. """Information Extractor for metacafe.com."""
  1224. _VALID_URL = r'(?:http://)?(?:www\.)?metacafe\.com/watch/([^/]+)/([^/]+)/.*'
  1225. _DISCLAIMER = 'http://www.metacafe.com/family_filter/'
  1226. _FILTER_POST = 'http://www.metacafe.com/f/index.php?inputType=filter&controllerGroup=user'
  1227. _youtube_ie = None
  1228. IE_NAME = u'metacafe'
  1229. def __init__(self, youtube_ie, downloader=None):
  1230. InfoExtractor.__init__(self, downloader)
  1231. self._youtube_ie = youtube_ie
  1232. def report_disclaimer(self):
  1233. """Report disclaimer retrieval."""
  1234. self._downloader.to_screen(u'[metacafe] Retrieving disclaimer')
  1235. def report_age_confirmation(self):
  1236. """Report attempt to confirm age."""
  1237. self._downloader.to_screen(u'[metacafe] Confirming age')
  1238. def report_download_webpage(self, video_id):
  1239. """Report webpage download."""
  1240. self._downloader.to_screen(u'[metacafe] %s: Downloading webpage' % video_id)
  1241. def report_extraction(self, video_id):
  1242. """Report information extraction."""
  1243. self._downloader.to_screen(u'[metacafe] %s: Extracting information' % video_id)
  1244. def _real_initialize(self):
  1245. # Retrieve disclaimer
  1246. request = urllib2.Request(self._DISCLAIMER)
  1247. try:
  1248. self.report_disclaimer()
  1249. disclaimer = urllib2.urlopen(request).read()
  1250. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1251. self._downloader.trouble(u'ERROR: unable to retrieve disclaimer: %s' % str(err))
  1252. return
  1253. # Confirm age
  1254. disclaimer_form = {
  1255. 'filters': '0',
  1256. 'submit': "Continue - I'm over 18",
  1257. }
  1258. request = urllib2.Request(self._FILTER_POST, urllib.urlencode(disclaimer_form))
  1259. try:
  1260. self.report_age_confirmation()
  1261. disclaimer = urllib2.urlopen(request).read()
  1262. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1263. self._downloader.trouble(u'ERROR: unable to confirm age: %s' % str(err))
  1264. return
  1265. def _real_extract(self, url):
  1266. # Extract id and simplified title from URL
  1267. mobj = re.match(self._VALID_URL, url)
  1268. if mobj is None:
  1269. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  1270. return
  1271. video_id = mobj.group(1)
  1272. # Check if video comes from YouTube
  1273. mobj2 = re.match(r'^yt-(.*)$', video_id)
  1274. if mobj2 is not None:
  1275. self._youtube_ie.extract('http://www.youtube.com/watch?v=%s' % mobj2.group(1))
  1276. return
  1277. # At this point we have a new video
  1278. self._downloader.increment_downloads()
  1279. simple_title = mobj.group(2).decode('utf-8')
  1280. # Retrieve video webpage to extract further information
  1281. request = urllib2.Request('http://www.metacafe.com/watch/%s/' % video_id)
  1282. try:
  1283. self.report_download_webpage(video_id)
  1284. webpage = urllib2.urlopen(request).read()
  1285. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1286. self._downloader.trouble(u'ERROR: unable retrieve video webpage: %s' % str(err))
  1287. return
  1288. # Extract URL, uploader and title from webpage
  1289. self.report_extraction(video_id)
  1290. mobj = re.search(r'(?m)&mediaURL=([^&]+)', webpage)
  1291. if mobj is not None:
  1292. mediaURL = urllib.unquote(mobj.group(1))
  1293. video_extension = mediaURL[-3:]
  1294. # Extract gdaKey if available
  1295. mobj = re.search(r'(?m)&gdaKey=(.*?)&', webpage)
  1296. if mobj is None:
  1297. video_url = mediaURL
  1298. else:
  1299. gdaKey = mobj.group(1)
  1300. video_url = '%s?__gda__=%s' % (mediaURL, gdaKey)
  1301. else:
  1302. mobj = re.search(r' name="flashvars" value="(.*?)"', webpage)
  1303. if mobj is None:
  1304. self._downloader.trouble(u'ERROR: unable to extract media URL')
  1305. return
  1306. vardict = parse_qs(mobj.group(1))
  1307. if 'mediaData' not in vardict:
  1308. self._downloader.trouble(u'ERROR: unable to extract media URL')
  1309. return
  1310. mobj = re.search(r'"mediaURL":"(http.*?)","key":"(.*?)"', vardict['mediaData'][0])
  1311. if mobj is None:
  1312. self._downloader.trouble(u'ERROR: unable to extract media URL')
  1313. return
  1314. mediaURL = mobj.group(1).replace('\\/', '/')
  1315. video_extension = mediaURL[-3:]
  1316. video_url = '%s?__gda__=%s' % (mediaURL, mobj.group(2))
  1317. mobj = re.search(r'(?im)<title>(.*) - Video</title>', webpage)
  1318. if mobj is None:
  1319. self._downloader.trouble(u'ERROR: unable to extract title')
  1320. return
  1321. video_title = mobj.group(1).decode('utf-8')
  1322. video_title = sanitize_title(video_title)
  1323. mobj = re.search(r'(?ms)By:\s*<a .*?>(.+?)<', webpage)
  1324. if mobj is None:
  1325. self._downloader.trouble(u'ERROR: unable to extract uploader nickname')
  1326. return
  1327. video_uploader = mobj.group(1)
  1328. try:
  1329. # Process video information
  1330. self._downloader.process_info({
  1331. 'id': video_id.decode('utf-8'),
  1332. 'url': video_url.decode('utf-8'),
  1333. 'uploader': video_uploader.decode('utf-8'),
  1334. 'upload_date': u'NA',
  1335. 'title': video_title,
  1336. 'stitle': simple_title,
  1337. 'ext': video_extension.decode('utf-8'),
  1338. 'format': u'NA',
  1339. 'player_url': None,
  1340. })
  1341. except UnavailableVideoError:
  1342. self._downloader.trouble(u'\nERROR: unable to download video')
  1343. class DailymotionIE(InfoExtractor):
  1344. """Information Extractor for Dailymotion"""
  1345. _VALID_URL = r'(?i)(?:https?://)?(?:www\.)?dailymotion\.[a-z]{2,3}/video/([^_/]+)_([^/]+)'
  1346. IE_NAME = u'dailymotion'
  1347. def __init__(self, downloader=None):
  1348. InfoExtractor.__init__(self, downloader)
  1349. def report_download_webpage(self, video_id):
  1350. """Report webpage download."""
  1351. self._downloader.to_screen(u'[dailymotion] %s: Downloading webpage' % video_id)
  1352. def report_extraction(self, video_id):
  1353. """Report information extraction."""
  1354. self._downloader.to_screen(u'[dailymotion] %s: Extracting information' % video_id)
  1355. def _real_extract(self, url):
  1356. # Extract id and simplified title from URL
  1357. mobj = re.match(self._VALID_URL, url)
  1358. if mobj is None:
  1359. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  1360. return
  1361. # At this point we have a new video
  1362. self._downloader.increment_downloads()
  1363. video_id = mobj.group(1)
  1364. simple_title = mobj.group(2).decode('utf-8')
  1365. video_extension = 'flv'
  1366. # Retrieve video webpage to extract further information
  1367. request = urllib2.Request(url)
  1368. request.add_header('Cookie', 'family_filter=off')
  1369. try:
  1370. self.report_download_webpage(video_id)
  1371. webpage = urllib2.urlopen(request).read()
  1372. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1373. self._downloader.trouble(u'ERROR: unable retrieve video webpage: %s' % str(err))
  1374. return
  1375. # Extract URL, uploader and title from webpage
  1376. self.report_extraction(video_id)
  1377. mobj = re.search(r'(?i)addVariable\(\"sequence\"\s*,\s*\"([^\"]+?)\"\)', webpage)
  1378. if mobj is None:
  1379. self._downloader.trouble(u'ERROR: unable to extract media URL')
  1380. return
  1381. sequence = urllib.unquote(mobj.group(1))
  1382. mobj = re.search(r',\"sdURL\"\:\"([^\"]+?)\",', sequence)
  1383. if mobj is None:
  1384. self._downloader.trouble(u'ERROR: unable to extract media URL')
  1385. return
  1386. mediaURL = urllib.unquote(mobj.group(1)).replace('\\', '')
  1387. # if needed add http://www.dailymotion.com/ if relative URL
  1388. video_url = mediaURL
  1389. mobj = re.search(r'(?im)<title>Dailymotion\s*-\s*(.+)\s*-\s*[^<]+?</title>', webpage)
  1390. if mobj is None:
  1391. self._downloader.trouble(u'ERROR: unable to extract title')
  1392. return
  1393. video_title = mobj.group(1).decode('utf-8')
  1394. video_title = sanitize_title(video_title)
  1395. mobj = re.search(r'(?im)<span class="owner[^\"]+?">[^<]+?<a [^>]+?>([^<]+?)</a></span>', webpage)
  1396. if mobj is None:
  1397. self._downloader.trouble(u'ERROR: unable to extract uploader nickname')
  1398. return
  1399. video_uploader = mobj.group(1)
  1400. try:
  1401. # Process video information
  1402. self._downloader.process_info({
  1403. 'id': video_id.decode('utf-8'),
  1404. 'url': video_url.decode('utf-8'),
  1405. 'uploader': video_uploader.decode('utf-8'),
  1406. 'upload_date': u'NA',
  1407. 'title': video_title,
  1408. 'stitle': simple_title,
  1409. 'ext': video_extension.decode('utf-8'),
  1410. 'format': u'NA',
  1411. 'player_url': None,
  1412. })
  1413. except UnavailableVideoError:
  1414. self._downloader.trouble(u'\nERROR: unable to download video')
  1415. class GoogleIE(InfoExtractor):
  1416. """Information extractor for video.google.com."""
  1417. _VALID_URL = r'(?:http://)?video\.google\.(?:com(?:\.au)?|co\.(?:uk|jp|kr|cr)|ca|de|es|fr|it|nl|pl)/videoplay\?docid=([^\&]+).*'
  1418. IE_NAME = u'video.google'
  1419. def __init__(self, downloader=None):
  1420. InfoExtractor.__init__(self, downloader)
  1421. def report_download_webpage(self, video_id):
  1422. """Report webpage download."""
  1423. self._downloader.to_screen(u'[video.google] %s: Downloading webpage' % video_id)
  1424. def report_extraction(self, video_id):
  1425. """Report information extraction."""
  1426. self._downloader.to_screen(u'[video.google] %s: Extracting information' % video_id)
  1427. def _real_extract(self, url):
  1428. # Extract id from URL
  1429. mobj = re.match(self._VALID_URL, url)
  1430. if mobj is None:
  1431. self._downloader.trouble(u'ERROR: Invalid URL: %s' % url)
  1432. return
  1433. # At this point we have a new video
  1434. self._downloader.increment_downloads()
  1435. video_id = mobj.group(1)
  1436. video_extension = 'mp4'
  1437. # Retrieve video webpage to extract further information
  1438. request = urllib2.Request('http://video.google.com/videoplay?docid=%s&hl=en&oe=utf-8' % video_id)
  1439. try:
  1440. self.report_download_webpage(video_id)
  1441. webpage = urllib2.urlopen(request).read()
  1442. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1443. self._downloader.trouble(u'ERROR: Unable to retrieve video webpage: %s' % str(err))
  1444. return
  1445. # Extract URL, uploader, and title from webpage
  1446. self.report_extraction(video_id)
  1447. mobj = re.search(r"download_url:'([^']+)'", webpage)
  1448. if mobj is None:
  1449. video_extension = 'flv'
  1450. mobj = re.search(r"(?i)videoUrl\\x3d(.+?)\\x26", webpage)
  1451. if mobj is None:
  1452. self._downloader.trouble(u'ERROR: unable to extract media URL')
  1453. return
  1454. mediaURL = urllib.unquote(mobj.group(1))
  1455. mediaURL = mediaURL.replace('\\x3d', '\x3d')
  1456. mediaURL = mediaURL.replace('\\x26', '\x26')
  1457. video_url = mediaURL
  1458. mobj = re.search(r'<title>(.*)</title>', webpage)
  1459. if mobj is None:
  1460. self._downloader.trouble(u'ERROR: unable to extract title')
  1461. return
  1462. video_title = mobj.group(1).decode('utf-8')
  1463. video_title = sanitize_title(video_title)
  1464. simple_title = re.sub(ur'(?u)([^%s]+)' % simple_title_chars, ur'_', video_title)
  1465. # Extract video description
  1466. mobj = re.search(r'<span id=short-desc-content>([^<]*)</span>', webpage)
  1467. if mobj is None:
  1468. self._downloader.trouble(u'ERROR: unable to extract video description')
  1469. return
  1470. video_description = mobj.group(1).decode('utf-8')
  1471. if not video_description:
  1472. video_description = 'No description available.'
  1473. # Extract video thumbnail
  1474. if self._downloader.params.get('forcethumbnail', False):
  1475. request = urllib2.Request('http://video.google.com/videosearch?q=%s+site:video.google.com&hl=en' % abs(int(video_id)))
  1476. try:
  1477. webpage = urllib2.urlopen(request).read()
  1478. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1479. self._downloader.trouble(u'ERROR: Unable to retrieve video webpage: %s' % str(err))
  1480. return
  1481. mobj = re.search(r'<img class=thumbnail-img (?:.* )?src=(http.*)>', webpage)
  1482. if mobj is None:
  1483. self._downloader.trouble(u'ERROR: unable to extract video thumbnail')
  1484. return
  1485. video_thumbnail = mobj.group(1)
  1486. else: # we need something to pass to process_info
  1487. video_thumbnail = ''
  1488. try:
  1489. # Process video information
  1490. self._downloader.process_info({
  1491. 'id': video_id.decode('utf-8'),
  1492. 'url': video_url.decode('utf-8'),
  1493. 'uploader': u'NA',
  1494. 'upload_date': u'NA',
  1495. 'title': video_title,
  1496. 'stitle': simple_title,
  1497. 'ext': video_extension.decode('utf-8'),
  1498. 'format': u'NA',
  1499. 'player_url': None,
  1500. })
  1501. except UnavailableVideoError:
  1502. self._downloader.trouble(u'\nERROR: unable to download video')
  1503. class PhotobucketIE(InfoExtractor):
  1504. """Information extractor for photobucket.com."""
  1505. _VALID_URL = r'(?:http://)?(?:[a-z0-9]+\.)?photobucket\.com/.*[\?\&]current=(.*\.flv)'
  1506. IE_NAME = u'photobucket'
  1507. def __init__(self, downloader=None):
  1508. InfoExtractor.__init__(self, downloader)
  1509. def report_download_webpage(self, video_id):
  1510. """Report webpage download."""
  1511. self._downloader.to_screen(u'[photobucket] %s: Downloading webpage' % video_id)
  1512. def report_extraction(self, video_id):
  1513. """Report information extraction."""
  1514. self._downloader.to_screen(u'[photobucket] %s: Extracting information' % video_id)
  1515. def _real_extract(self, url):
  1516. # Extract id from URL
  1517. mobj = re.match(self._VALID_URL, url)
  1518. if mobj is None:
  1519. self._downloader.trouble(u'ERROR: Invalid URL: %s' % url)
  1520. return
  1521. # At this point we have a new video
  1522. self._downloader.increment_downloads()
  1523. video_id = mobj.group(1)
  1524. video_extension = 'flv'
  1525. # Retrieve video webpage to extract further information
  1526. request = urllib2.Request(url)
  1527. try:
  1528. self.report_download_webpage(video_id)
  1529. webpage = urllib2.urlopen(request).read()
  1530. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1531. self._downloader.trouble(u'ERROR: Unable to retrieve video webpage: %s' % str(err))
  1532. return
  1533. # Extract URL, uploader, and title from webpage
  1534. self.report_extraction(video_id)
  1535. mobj = re.search(r'<link rel="video_src" href=".*\?file=([^"]+)" />', webpage)
  1536. if mobj is None:
  1537. self._downloader.trouble(u'ERROR: unable to extract media URL')
  1538. return
  1539. mediaURL = urllib.unquote(mobj.group(1))
  1540. video_url = mediaURL
  1541. mobj = re.search(r'<title>(.*) video by (.*) - Photobucket</title>', webpage)
  1542. if mobj is None:
  1543. self._downloader.trouble(u'ERROR: unable to extract title')
  1544. return
  1545. video_title = mobj.group(1).decode('utf-8')
  1546. video_title = sanitize_title(video_title)
  1547. simple_title = re.sub(ur'(?u)([^%s]+)' % simple_title_chars, ur'_', video_title)
  1548. video_uploader = mobj.group(2).decode('utf-8')
  1549. try:
  1550. # Process video information
  1551. self._downloader.process_info({
  1552. 'id': video_id.decode('utf-8'),
  1553. 'url': video_url.decode('utf-8'),
  1554. 'uploader': video_uploader,
  1555. 'upload_date': u'NA',
  1556. 'title': video_title,
  1557. 'stitle': simple_title,
  1558. 'ext': video_extension.decode('utf-8'),
  1559. 'format': u'NA',
  1560. 'player_url': None,
  1561. })
  1562. except UnavailableVideoError:
  1563. self._downloader.trouble(u'\nERROR: unable to download video')
  1564. class YahooIE(InfoExtractor):
  1565. """Information extractor for video.yahoo.com."""
  1566. # _VALID_URL matches all Yahoo! Video URLs
  1567. # _VPAGE_URL matches only the extractable '/watch/' URLs
  1568. _VALID_URL = r'(?:http://)?(?:[a-z]+\.)?video\.yahoo\.com/(?:watch|network)/([0-9]+)(?:/|\?v=)([0-9]+)(?:[#\?].*)?'
  1569. _VPAGE_URL = r'(?:http://)?video\.yahoo\.com/watch/([0-9]+)/([0-9]+)(?:[#\?].*)?'
  1570. IE_NAME = u'video.yahoo'
  1571. def __init__(self, downloader=None):
  1572. InfoExtractor.__init__(self, downloader)
  1573. def report_download_webpage(self, video_id):
  1574. """Report webpage download."""
  1575. self._downloader.to_screen(u'[video.yahoo] %s: Downloading webpage' % video_id)
  1576. def report_extraction(self, video_id):
  1577. """Report information extraction."""
  1578. self._downloader.to_screen(u'[video.yahoo] %s: Extracting information' % video_id)
  1579. def _real_extract(self, url, new_video=True):
  1580. # Extract ID from URL
  1581. mobj = re.match(self._VALID_URL, url)
  1582. if mobj is None:
  1583. self._downloader.trouble(u'ERROR: Invalid URL: %s' % url)
  1584. return
  1585. # At this point we have a new video
  1586. self._downloader.increment_downloads()
  1587. video_id = mobj.group(2)
  1588. video_extension = 'flv'
  1589. # Rewrite valid but non-extractable URLs as
  1590. # extractable English language /watch/ URLs
  1591. if re.match(self._VPAGE_URL, url) is None:
  1592. request = urllib2.Request(url)
  1593. try:
  1594. webpage = urllib2.urlopen(request).read()
  1595. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1596. self._downloader.trouble(u'ERROR: Unable to retrieve video webpage: %s' % str(err))
  1597. return
  1598. mobj = re.search(r'\("id", "([0-9]+)"\);', webpage)
  1599. if mobj is None:
  1600. self._downloader.trouble(u'ERROR: Unable to extract id field')
  1601. return
  1602. yahoo_id = mobj.group(1)
  1603. mobj = re.search(r'\("vid", "([0-9]+)"\);', webpage)
  1604. if mobj is None:
  1605. self._downloader.trouble(u'ERROR: Unable to extract vid field')
  1606. return
  1607. yahoo_vid = mobj.group(1)
  1608. url = 'http://video.yahoo.com/watch/%s/%s' % (yahoo_vid, yahoo_id)
  1609. return self._real_extract(url, new_video=False)
  1610. # Retrieve video webpage to extract further information
  1611. request = urllib2.Request(url)
  1612. try:
  1613. self.report_download_webpage(video_id)
  1614. webpage = urllib2.urlopen(request).read()
  1615. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1616. self._downloader.trouble(u'ERROR: Unable to retrieve video webpage: %s' % str(err))
  1617. return
  1618. # Extract uploader and title from webpage
  1619. self.report_extraction(video_id)
  1620. mobj = re.search(r'<meta name="title" content="(.*)" />', webpage)
  1621. if mobj is None:
  1622. self._downloader.trouble(u'ERROR: unable to extract video title')
  1623. return
  1624. video_title = mobj.group(1).decode('utf-8')
  1625. simple_title = re.sub(ur'(?u)([^%s]+)' % simple_title_chars, ur'_', video_title)
  1626. mobj = re.search(r'<h2 class="ti-5"><a href="http://video\.yahoo\.com/(people|profile)/[0-9]+" beacon=".*">(.*)</a></h2>', webpage)
  1627. if mobj is None:
  1628. self._downloader.trouble(u'ERROR: unable to extract video uploader')
  1629. return
  1630. video_uploader = mobj.group(1).decode('utf-8')
  1631. # Extract video thumbnail
  1632. mobj = re.search(r'<link rel="image_src" href="(.*)" />', webpage)
  1633. if mobj is None:
  1634. self._downloader.trouble(u'ERROR: unable to extract video thumbnail')
  1635. return
  1636. video_thumbnail = mobj.group(1).decode('utf-8')
  1637. # Extract video description
  1638. mobj = re.search(r'<meta name="description" content="(.*)" />', webpage)
  1639. if mobj is None:
  1640. self._downloader.trouble(u'ERROR: unable to extract video description')
  1641. return
  1642. video_description = mobj.group(1).decode('utf-8')
  1643. if not video_description:
  1644. video_description = 'No description available.'
  1645. # Extract video height and width
  1646. mobj = re.search(r'<meta name="video_height" content="([0-9]+)" />', webpage)
  1647. if mobj is None:
  1648. self._downloader.trouble(u'ERROR: unable to extract video height')
  1649. return
  1650. yv_video_height = mobj.group(1)
  1651. mobj = re.search(r'<meta name="video_width" content="([0-9]+)" />', webpage)
  1652. if mobj is None:
  1653. self._downloader.trouble(u'ERROR: unable to extract video width')
  1654. return
  1655. yv_video_width = mobj.group(1)
  1656. # Retrieve video playlist to extract media URL
  1657. # I'm not completely sure what all these options are, but we
  1658. # seem to need most of them, otherwise the server sends a 401.
  1659. yv_lg = 'R0xx6idZnW2zlrKP8xxAIR' # not sure what this represents
  1660. yv_bitrate = '700' # according to Wikipedia this is hard-coded
  1661. request = urllib2.Request('http://cosmos.bcst.yahoo.com/up/yep/process/getPlaylistFOP.php?node_id=' + video_id +
  1662. '&tech=flash&mode=playlist&lg=' + yv_lg + '&bitrate=' + yv_bitrate + '&vidH=' + yv_video_height +
  1663. '&vidW=' + yv_video_width + '&swf=as3&rd=video.yahoo.com&tk=null&adsupported=v1,v2,&eventid=1301797')
  1664. try:
  1665. self.report_download_webpage(video_id)
  1666. webpage = urllib2.urlopen(request).read()
  1667. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1668. self._downloader.trouble(u'ERROR: Unable to retrieve video webpage: %s' % str(err))
  1669. return
  1670. # Extract media URL from playlist XML
  1671. mobj = re.search(r'<STREAM APP="(http://.*)" FULLPATH="/?(/.*\.flv\?[^"]*)"', webpage)
  1672. if mobj is None:
  1673. self._downloader.trouble(u'ERROR: Unable to extract media URL')
  1674. return
  1675. video_url = urllib.unquote(mobj.group(1) + mobj.group(2)).decode('utf-8')
  1676. video_url = re.sub(r'(?u)&(.+?);', htmlentity_transform, video_url)
  1677. try:
  1678. # Process video information
  1679. self._downloader.process_info({
  1680. 'id': video_id.decode('utf-8'),
  1681. 'url': video_url,
  1682. 'uploader': video_uploader,
  1683. 'upload_date': u'NA',
  1684. 'title': video_title,
  1685. 'stitle': simple_title,
  1686. 'ext': video_extension.decode('utf-8'),
  1687. 'thumbnail': video_thumbnail.decode('utf-8'),
  1688. 'description': video_description,
  1689. 'thumbnail': video_thumbnail,
  1690. 'player_url': None,
  1691. })
  1692. except UnavailableVideoError:
  1693. self._downloader.trouble(u'\nERROR: unable to download video')
  1694. class VimeoIE(InfoExtractor):
  1695. """Information extractor for vimeo.com."""
  1696. # _VALID_URL matches Vimeo URLs
  1697. _VALID_URL = r'(?:https?://)?(?:(?:www|player).)?vimeo\.com/(?:groups/[^/]+/)?(?:videos?/)?([0-9]+)'
  1698. IE_NAME = u'vimeo'
  1699. def __init__(self, downloader=None):
  1700. InfoExtractor.__init__(self, downloader)
  1701. def report_download_webpage(self, video_id):
  1702. """Report webpage download."""
  1703. self._downloader.to_screen(u'[vimeo] %s: Downloading webpage' % video_id)
  1704. def report_extraction(self, video_id):
  1705. """Report information extraction."""
  1706. self._downloader.to_screen(u'[vimeo] %s: Extracting information' % video_id)
  1707. def _real_extract(self, url, new_video=True):
  1708. # Extract ID from URL
  1709. mobj = re.match(self._VALID_URL, url)
  1710. if mobj is None:
  1711. self._downloader.trouble(u'ERROR: Invalid URL: %s' % url)
  1712. return
  1713. # At this point we have a new video
  1714. self._downloader.increment_downloads()
  1715. video_id = mobj.group(1)
  1716. # Retrieve video webpage to extract further information
  1717. request = urllib2.Request("http://vimeo.com/moogaloop/load/clip:%s" % video_id, None, std_headers)
  1718. try:
  1719. self.report_download_webpage(video_id)
  1720. webpage = urllib2.urlopen(request).read()
  1721. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1722. self._downloader.trouble(u'ERROR: Unable to retrieve video webpage: %s' % str(err))
  1723. return
  1724. # Now we begin extracting as much information as we can from what we
  1725. # retrieved. First we extract the information common to all extractors,
  1726. # and latter we extract those that are Vimeo specific.
  1727. self.report_extraction(video_id)
  1728. # Extract title
  1729. mobj = re.search(r'<caption>(.*?)</caption>', webpage)
  1730. if mobj is None:
  1731. self._downloader.trouble(u'ERROR: unable to extract video title')
  1732. return
  1733. video_title = mobj.group(1).decode('utf-8')
  1734. simple_title = re.sub(ur'(?u)([^%s]+)' % simple_title_chars, ur'_', video_title)
  1735. # Extract uploader
  1736. mobj = re.search(r'<uploader_url>http://vimeo.com/(.*?)</uploader_url>', webpage)
  1737. if mobj is None:
  1738. self._downloader.trouble(u'ERROR: unable to extract video uploader')
  1739. return
  1740. video_uploader = mobj.group(1).decode('utf-8')
  1741. # Extract video thumbnail
  1742. mobj = re.search(r'<thumbnail>(.*?)</thumbnail>', webpage)
  1743. if mobj is None:
  1744. self._downloader.trouble(u'ERROR: unable to extract video thumbnail')
  1745. return
  1746. video_thumbnail = mobj.group(1).decode('utf-8')
  1747. # # Extract video description
  1748. # mobj = re.search(r'<meta property="og:description" content="(.*)" />', webpage)
  1749. # if mobj is None:
  1750. # self._downloader.trouble(u'ERROR: unable to extract video description')
  1751. # return
  1752. # video_description = mobj.group(1).decode('utf-8')
  1753. # if not video_description: video_description = 'No description available.'
  1754. video_description = 'Foo.'
  1755. # Vimeo specific: extract request signature
  1756. mobj = re.search(r'<request_signature>(.*?)</request_signature>', webpage)
  1757. if mobj is None:
  1758. self._downloader.trouble(u'ERROR: unable to extract request signature')
  1759. return
  1760. sig = mobj.group(1).decode('utf-8')
  1761. # Vimeo specific: extract video quality information
  1762. mobj = re.search(r'<isHD>(\d+)</isHD>', webpage)
  1763. if mobj is None:
  1764. self._downloader.trouble(u'ERROR: unable to extract video quality information')
  1765. return
  1766. quality = mobj.group(1).decode('utf-8')
  1767. if int(quality) == 1:
  1768. quality = 'hd'
  1769. else:
  1770. quality = 'sd'
  1771. # Vimeo specific: Extract request signature expiration
  1772. mobj = re.search(r'<request_signature_expires>(.*?)</request_signature_expires>', webpage)
  1773. if mobj is None:
  1774. self._downloader.trouble(u'ERROR: unable to extract request signature expiration')
  1775. return
  1776. sig_exp = mobj.group(1).decode('utf-8')
  1777. video_url = "http://vimeo.com/moogaloop/play/clip:%s/%s/%s/?q=%s" % (video_id, sig, sig_exp, quality)
  1778. try:
  1779. # Process video information
  1780. self._downloader.process_info({
  1781. 'id': video_id.decode('utf-8'),
  1782. 'url': video_url,
  1783. 'uploader': video_uploader,
  1784. 'upload_date': u'NA',
  1785. 'title': video_title,
  1786. 'stitle': simple_title,
  1787. 'ext': u'mp4',
  1788. 'thumbnail': video_thumbnail.decode('utf-8'),
  1789. 'description': video_description,
  1790. 'thumbnail': video_thumbnail,
  1791. 'description': video_description,
  1792. 'player_url': None,
  1793. })
  1794. except UnavailableVideoError:
  1795. self._downloader.trouble(u'ERROR: unable to download video')
  1796. class GenericIE(InfoExtractor):
  1797. """Generic last-resort information extractor."""
  1798. _VALID_URL = r'.*'
  1799. IE_NAME = u'generic'
  1800. def __init__(self, downloader=None):
  1801. InfoExtractor.__init__(self, downloader)
  1802. def report_download_webpage(self, video_id):
  1803. """Report webpage download."""
  1804. self._downloader.to_screen(u'WARNING: Falling back on generic information extractor.')
  1805. self._downloader.to_screen(u'[generic] %s: Downloading webpage' % video_id)
  1806. def report_extraction(self, video_id):
  1807. """Report information extraction."""
  1808. self._downloader.to_screen(u'[generic] %s: Extracting information' % video_id)
  1809. def _real_extract(self, url):
  1810. # At this point we have a new video
  1811. self._downloader.increment_downloads()
  1812. video_id = url.split('/')[-1]
  1813. request = urllib2.Request(url)
  1814. try:
  1815. self.report_download_webpage(video_id)
  1816. webpage = urllib2.urlopen(request).read()
  1817. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1818. self._downloader.trouble(u'ERROR: Unable to retrieve video webpage: %s' % str(err))
  1819. return
  1820. except ValueError, err:
  1821. # since this is the last-resort InfoExtractor, if
  1822. # this error is thrown, it'll be thrown here
  1823. self._downloader.trouble(u'ERROR: Invalid URL: %s' % url)
  1824. return
  1825. self.report_extraction(video_id)
  1826. # Start with something easy: JW Player in SWFObject
  1827. mobj = re.search(r'flashvars: [\'"](?:.*&)?file=(http[^\'"&]*)', webpage)
  1828. if mobj is None:
  1829. # Broaden the search a little bit
  1830. mobj = re.search(r'[^A-Za-z0-9]?(?:file|source)=(http[^\'"&]*)', webpage)
  1831. if mobj is None:
  1832. self._downloader.trouble(u'ERROR: Invalid URL: %s' % url)
  1833. return
  1834. # It's possible that one of the regexes
  1835. # matched, but returned an empty group:
  1836. if mobj.group(1) is None:
  1837. self._downloader.trouble(u'ERROR: Invalid URL: %s' % url)
  1838. return
  1839. video_url = urllib.unquote(mobj.group(1))
  1840. video_id = os.path.basename(video_url)
  1841. # here's a fun little line of code for you:
  1842. video_extension = os.path.splitext(video_id)[1][1:]
  1843. video_id = os.path.splitext(video_id)[0]
  1844. # it's tempting to parse this further, but you would
  1845. # have to take into account all the variations like
  1846. # Video Title - Site Name
  1847. # Site Name | Video Title
  1848. # Video Title - Tagline | Site Name
  1849. # and so on and so forth; it's just not practical
  1850. mobj = re.search(r'<title>(.*)</title>', webpage)
  1851. if mobj is None:
  1852. self._downloader.trouble(u'ERROR: unable to extract title')
  1853. return
  1854. video_title = mobj.group(1).decode('utf-8')
  1855. video_title = sanitize_title(video_title)
  1856. simple_title = re.sub(ur'(?u)([^%s]+)' % simple_title_chars, ur'_', video_title)
  1857. # video uploader is domain name
  1858. mobj = re.match(r'(?:https?://)?([^/]*)/.*', url)
  1859. if mobj is None:
  1860. self._downloader.trouble(u'ERROR: unable to extract title')
  1861. return
  1862. video_uploader = mobj.group(1).decode('utf-8')
  1863. try:
  1864. # Process video information
  1865. self._downloader.process_info({
  1866. 'id': video_id.decode('utf-8'),
  1867. 'url': video_url.decode('utf-8'),
  1868. 'uploader': video_uploader,
  1869. 'upload_date': u'NA',
  1870. 'title': video_title,
  1871. 'stitle': simple_title,
  1872. 'ext': video_extension.decode('utf-8'),
  1873. 'format': u'NA',
  1874. 'player_url': None,
  1875. })
  1876. except UnavailableVideoError, err:
  1877. self._downloader.trouble(u'\nERROR: unable to download video')
  1878. class YoutubeSearchIE(InfoExtractor):
  1879. """Information Extractor for YouTube search queries."""
  1880. _VALID_URL = r'ytsearch(\d+|all)?:[\s\S]+'
  1881. _TEMPLATE_URL = 'http://www.youtube.com/results?search_query=%s&page=%s&gl=US&hl=en'
  1882. _VIDEO_INDICATOR = r'href="/watch\?v=.+?"'
  1883. _MORE_PAGES_INDICATOR = r'(?m)>\s*Next\s*</a>'
  1884. _youtube_ie = None
  1885. _max_youtube_results = 1000
  1886. IE_NAME = u'youtube:search'
  1887. def __init__(self, youtube_ie, downloader=None):
  1888. InfoExtractor.__init__(self, downloader)
  1889. self._youtube_ie = youtube_ie
  1890. def report_download_page(self, query, pagenum):
  1891. """Report attempt to download playlist page with given number."""
  1892. query = query.decode(preferredencoding())
  1893. self._downloader.to_screen(u'[youtube] query "%s": Downloading page %s' % (query, pagenum))
  1894. def _real_initialize(self):
  1895. self._youtube_ie.initialize()
  1896. def _real_extract(self, query):
  1897. mobj = re.match(self._VALID_URL, query)
  1898. if mobj is None:
  1899. self._downloader.trouble(u'ERROR: invalid search query "%s"' % query)
  1900. return
  1901. prefix, query = query.split(':')
  1902. prefix = prefix[8:]
  1903. query = query.encode('utf-8')
  1904. if prefix == '':
  1905. self._download_n_results(query, 1)
  1906. return
  1907. elif prefix == 'all':
  1908. self._download_n_results(query, self._max_youtube_results)
  1909. return
  1910. else:
  1911. try:
  1912. n = long(prefix)
  1913. if n <= 0:
  1914. self._downloader.trouble(u'ERROR: invalid download number %s for query "%s"' % (n, query))
  1915. return
  1916. elif n > self._max_youtube_results:
  1917. self._downloader.to_stderr(u'WARNING: ytsearch returns max %i results (you requested %i)' % (self._max_youtube_results, n))
  1918. n = self._max_youtube_results
  1919. self._download_n_results(query, n)
  1920. return
  1921. except ValueError: # parsing prefix as integer fails
  1922. self._download_n_results(query, 1)
  1923. return
  1924. def _download_n_results(self, query, n):
  1925. """Downloads a specified number of results for a query"""
  1926. video_ids = []
  1927. already_seen = set()
  1928. pagenum = 1
  1929. while True:
  1930. self.report_download_page(query, pagenum)
  1931. result_url = self._TEMPLATE_URL % (urllib.quote_plus(query), pagenum)
  1932. request = urllib2.Request(result_url)
  1933. try:
  1934. page = urllib2.urlopen(request).read()
  1935. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1936. self._downloader.trouble(u'ERROR: unable to download webpage: %s' % str(err))
  1937. return
  1938. # Extract video identifiers
  1939. for mobj in re.finditer(self._VIDEO_INDICATOR, page):
  1940. video_id = page[mobj.span()[0]:mobj.span()[1]].split('=')[2][:-1]
  1941. if video_id not in already_seen:
  1942. video_ids.append(video_id)
  1943. already_seen.add(video_id)
  1944. if len(video_ids) == n:
  1945. # Specified n videos reached
  1946. for id in video_ids:
  1947. self._youtube_ie.extract('http://www.youtube.com/watch?v=%s' % id)
  1948. return
  1949. if re.search(self._MORE_PAGES_INDICATOR, page) is None:
  1950. for id in video_ids:
  1951. self._youtube_ie.extract('http://www.youtube.com/watch?v=%s' % id)
  1952. return
  1953. pagenum = pagenum + 1
  1954. class GoogleSearchIE(InfoExtractor):
  1955. """Information Extractor for Google Video search queries."""
  1956. _VALID_URL = r'gvsearch(\d+|all)?:[\s\S]+'
  1957. _TEMPLATE_URL = 'http://video.google.com/videosearch?q=%s+site:video.google.com&start=%s&hl=en'
  1958. _VIDEO_INDICATOR = r'videoplay\?docid=([^\&>]+)\&'
  1959. _MORE_PAGES_INDICATOR = r'<span>Next</span>'
  1960. _google_ie = None
  1961. _max_google_results = 1000
  1962. IE_NAME = u'video.google:search'
  1963. def __init__(self, google_ie, downloader=None):
  1964. InfoExtractor.__init__(self, downloader)
  1965. self._google_ie = google_ie
  1966. def report_download_page(self, query, pagenum):
  1967. """Report attempt to download playlist page with given number."""
  1968. query = query.decode(preferredencoding())
  1969. self._downloader.to_screen(u'[video.google] query "%s": Downloading page %s' % (query, pagenum))
  1970. def _real_initialize(self):
  1971. self._google_ie.initialize()
  1972. def _real_extract(self, query):
  1973. mobj = re.match(self._VALID_URL, query)
  1974. if mobj is None:
  1975. self._downloader.trouble(u'ERROR: invalid search query "%s"' % query)
  1976. return
  1977. prefix, query = query.split(':')
  1978. prefix = prefix[8:]
  1979. query = query.encode('utf-8')
  1980. if prefix == '':
  1981. self._download_n_results(query, 1)
  1982. return
  1983. elif prefix == 'all':
  1984. self._download_n_results(query, self._max_google_results)
  1985. return
  1986. else:
  1987. try:
  1988. n = long(prefix)
  1989. if n <= 0:
  1990. self._downloader.trouble(u'ERROR: invalid download number %s for query "%s"' % (n, query))
  1991. return
  1992. elif n > self._max_google_results:
  1993. self._downloader.to_stderr(u'WARNING: gvsearch returns max %i results (you requested %i)' % (self._max_google_results, n))
  1994. n = self._max_google_results
  1995. self._download_n_results(query, n)
  1996. return
  1997. except ValueError: # parsing prefix as integer fails
  1998. self._download_n_results(query, 1)
  1999. return
  2000. def _download_n_results(self, query, n):
  2001. """Downloads a specified number of results for a query"""
  2002. video_ids = []
  2003. already_seen = set()
  2004. pagenum = 1
  2005. while True:
  2006. self.report_download_page(query, pagenum)
  2007. result_url = self._TEMPLATE_URL % (urllib.quote_plus(query), pagenum)
  2008. request = urllib2.Request(result_url)
  2009. try:
  2010. page = urllib2.urlopen(request).read()
  2011. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  2012. self._downloader.trouble(u'ERROR: unable to download webpage: %s' % str(err))
  2013. return
  2014. # Extract video identifiers
  2015. for mobj in re.finditer(self._VIDEO_INDICATOR, page):
  2016. video_id = mobj.group(1)
  2017. if video_id not in already_seen:
  2018. video_ids.append(video_id)
  2019. already_seen.add(video_id)
  2020. if len(video_ids) == n:
  2021. # Specified n videos reached
  2022. for id in video_ids:
  2023. self._google_ie.extract('http://video.google.com/videoplay?docid=%s' % id)
  2024. return
  2025. if re.search(self._MORE_PAGES_INDICATOR, page) is None:
  2026. for id in video_ids:
  2027. self._google_ie.extract('http://video.google.com/videoplay?docid=%s' % id)
  2028. return
  2029. pagenum = pagenum + 1
  2030. class YahooSearchIE(InfoExtractor):
  2031. """Information Extractor for Yahoo! Video search queries."""
  2032. _VALID_URL = r'yvsearch(\d+|all)?:[\s\S]+'
  2033. _TEMPLATE_URL = 'http://video.yahoo.com/search/?p=%s&o=%s'
  2034. _VIDEO_INDICATOR = r'href="http://video\.yahoo\.com/watch/([0-9]+/[0-9]+)"'
  2035. _MORE_PAGES_INDICATOR = r'\s*Next'
  2036. _yahoo_ie = None
  2037. _max_yahoo_results = 1000
  2038. IE_NAME = u'video.yahoo:search'
  2039. def __init__(self, yahoo_ie, downloader=None):
  2040. InfoExtractor.__init__(self, downloader)
  2041. self._yahoo_ie = yahoo_ie
  2042. def report_download_page(self, query, pagenum):
  2043. """Report attempt to download playlist page with given number."""
  2044. query = query.decode(preferredencoding())
  2045. self._downloader.to_screen(u'[video.yahoo] query "%s": Downloading page %s' % (query, pagenum))
  2046. def _real_initialize(self):
  2047. self._yahoo_ie.initialize()
  2048. def _real_extract(self, query):
  2049. mobj = re.match(self._VALID_URL, query)
  2050. if mobj is None:
  2051. self._downloader.trouble(u'ERROR: invalid search query "%s"' % query)
  2052. return
  2053. prefix, query = query.split(':')
  2054. prefix = prefix[8:]
  2055. query = query.encode('utf-8')
  2056. if prefix == '':
  2057. self._download_n_results(query, 1)
  2058. return
  2059. elif prefix == 'all':
  2060. self._download_n_results(query, self._max_yahoo_results)
  2061. return
  2062. else:
  2063. try:
  2064. n = long(prefix)
  2065. if n <= 0:
  2066. self._downloader.trouble(u'ERROR: invalid download number %s for query "%s"' % (n, query))
  2067. return
  2068. elif n > self._max_yahoo_results:
  2069. self._downloader.to_stderr(u'WARNING: yvsearch returns max %i results (you requested %i)' % (self._max_yahoo_results, n))
  2070. n = self._max_yahoo_results
  2071. self._download_n_results(query, n)
  2072. return
  2073. except ValueError: # parsing prefix as integer fails
  2074. self._download_n_results(query, 1)
  2075. return
  2076. def _download_n_results(self, query, n):
  2077. """Downloads a specified number of results for a query"""
  2078. video_ids = []
  2079. already_seen = set()
  2080. pagenum = 1
  2081. while True:
  2082. self.report_download_page(query, pagenum)
  2083. result_url = self._TEMPLATE_URL % (urllib.quote_plus(query), pagenum)
  2084. request = urllib2.Request(result_url)
  2085. try:
  2086. page = urllib2.urlopen(request).read()
  2087. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  2088. self._downloader.trouble(u'ERROR: unable to download webpage: %s' % str(err))
  2089. return
  2090. # Extract video identifiers
  2091. for mobj in re.finditer(self._VIDEO_INDICATOR, page):
  2092. video_id = mobj.group(1)
  2093. if video_id not in already_seen:
  2094. video_ids.append(video_id)
  2095. already_seen.add(video_id)
  2096. if len(video_ids) == n:
  2097. # Specified n videos reached
  2098. for id in video_ids:
  2099. self._yahoo_ie.extract('http://video.yahoo.com/watch/%s' % id)
  2100. return
  2101. if re.search(self._MORE_PAGES_INDICATOR, page) is None:
  2102. for id in video_ids:
  2103. self._yahoo_ie.extract('http://video.yahoo.com/watch/%s' % id)
  2104. return
  2105. pagenum = pagenum + 1
  2106. class YoutubePlaylistIE(InfoExtractor):
  2107. """Information Extractor for YouTube playlists."""
  2108. _VALID_URL = r'(?:https?://)?(?:\w+\.)?youtube\.com/(?:(?:course|view_play_list|my_playlists|artist|playlist)\?.*?(p|a|list)=|user/.*?/user/|p/|user/.*?#[pg]/c/)(?:PL)?([0-9A-Za-z-_]+)(?:/.*?/([0-9A-Za-z_-]+))?.*'
  2109. _TEMPLATE_URL = 'http://www.youtube.com/%s?%s=%s&page=%s&gl=US&hl=en'
  2110. _VIDEO_INDICATOR = r'/watch\?v=(.+?)&'
  2111. _MORE_PAGES_INDICATOR = r'(?m)>\s*Next\s*</a>'
  2112. _youtube_ie = None
  2113. IE_NAME = u'youtube:playlist'
  2114. def __init__(self, youtube_ie, downloader=None):
  2115. InfoExtractor.__init__(self, downloader)
  2116. self._youtube_ie = youtube_ie
  2117. def report_download_page(self, playlist_id, pagenum):
  2118. """Report attempt to download playlist page with given number."""
  2119. self._downloader.to_screen(u'[youtube] PL %s: Downloading page #%s' % (playlist_id, pagenum))
  2120. def _real_initialize(self):
  2121. self._youtube_ie.initialize()
  2122. def _real_extract(self, url):
  2123. # Extract playlist id
  2124. mobj = re.match(self._VALID_URL, url)
  2125. if mobj is None:
  2126. self._downloader.trouble(u'ERROR: invalid url: %s' % url)
  2127. return
  2128. # Single video case
  2129. if mobj.group(3) is not None:
  2130. self._youtube_ie.extract(mobj.group(3))
  2131. return
  2132. # Download playlist pages
  2133. # prefix is 'p' as default for playlists but there are other types that need extra care
  2134. playlist_prefix = mobj.group(1)
  2135. if playlist_prefix == 'a':
  2136. playlist_access = 'artist'
  2137. else:
  2138. playlist_prefix = 'p'
  2139. playlist_access = 'view_play_list'
  2140. playlist_id = mobj.group(2)
  2141. video_ids = []
  2142. pagenum = 1
  2143. while True:
  2144. self.report_download_page(playlist_id, pagenum)
  2145. url = self._TEMPLATE_URL % (playlist_access, playlist_prefix, playlist_id, pagenum)
  2146. request = urllib2.Request(url)
  2147. try:
  2148. page = urllib2.urlopen(request).read()
  2149. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  2150. self._downloader.trouble(u'ERROR: unable to download webpage: %s' % str(err))
  2151. return
  2152. # Extract video identifiers
  2153. ids_in_page = []
  2154. for mobj in re.finditer(self._VIDEO_INDICATOR, page):
  2155. if mobj.group(1) not in ids_in_page:
  2156. ids_in_page.append(mobj.group(1))
  2157. video_ids.extend(ids_in_page)
  2158. if re.search(self._MORE_PAGES_INDICATOR, page) is None:
  2159. break
  2160. pagenum = pagenum + 1
  2161. playliststart = self._downloader.params.get('playliststart', 1) - 1
  2162. playlistend = self._downloader.params.get('playlistend', -1)
  2163. video_ids = video_ids[playliststart:playlistend]
  2164. for id in video_ids:
  2165. self._youtube_ie.extract('http://www.youtube.com/watch?v=%s' % id)
  2166. return
  2167. class YoutubeUserIE(InfoExtractor):
  2168. """Information Extractor for YouTube users."""
  2169. _VALID_URL = r'(?:(?:(?:https?://)?(?:\w+\.)?youtube\.com/user/)|ytuser:)([A-Za-z0-9_-]+)'
  2170. _TEMPLATE_URL = 'http://gdata.youtube.com/feeds/api/users/%s'
  2171. _GDATA_PAGE_SIZE = 50
  2172. _GDATA_URL = 'http://gdata.youtube.com/feeds/api/users/%s/uploads?max-results=%d&start-index=%d'
  2173. _VIDEO_INDICATOR = r'/watch\?v=(.+?)[\<&]'
  2174. _youtube_ie = None
  2175. IE_NAME = u'youtube:user'
  2176. def __init__(self, youtube_ie, downloader=None):
  2177. InfoExtractor.__init__(self, downloader)
  2178. self._youtube_ie = youtube_ie
  2179. def report_download_page(self, username, start_index):
  2180. """Report attempt to download user page."""
  2181. self._downloader.to_screen(u'[youtube] user %s: Downloading video ids from %d to %d' %
  2182. (username, start_index, start_index + self._GDATA_PAGE_SIZE))
  2183. def _real_initialize(self):
  2184. self._youtube_ie.initialize()
  2185. def _real_extract(self, url):
  2186. # Extract username
  2187. mobj = re.match(self._VALID_URL, url)
  2188. if mobj is None:
  2189. self._downloader.trouble(u'ERROR: invalid url: %s' % url)
  2190. return
  2191. username = mobj.group(1)
  2192. # Download video ids using YouTube Data API. Result size per
  2193. # query is limited (currently to 50 videos) so we need to query
  2194. # page by page until there are no video ids - it means we got
  2195. # all of them.
  2196. video_ids = []
  2197. pagenum = 0
  2198. while True:
  2199. start_index = pagenum * self._GDATA_PAGE_SIZE + 1
  2200. self.report_download_page(username, start_index)
  2201. request = urllib2.Request(self._GDATA_URL % (username, self._GDATA_PAGE_SIZE, start_index))
  2202. try:
  2203. page = urllib2.urlopen(request).read()
  2204. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  2205. self._downloader.trouble(u'ERROR: unable to download webpage: %s' % str(err))
  2206. return
  2207. # Extract video identifiers
  2208. ids_in_page = []
  2209. for mobj in re.finditer(self._VIDEO_INDICATOR, page):
  2210. if mobj.group(1) not in ids_in_page:
  2211. ids_in_page.append(mobj.group(1))
  2212. video_ids.extend(ids_in_page)
  2213. # A little optimization - if current page is not
  2214. # "full", ie. does not contain PAGE_SIZE video ids then
  2215. # we can assume that this page is the last one - there
  2216. # are no more ids on further pages - no need to query
  2217. # again.
  2218. if len(ids_in_page) < self._GDATA_PAGE_SIZE:
  2219. break
  2220. pagenum += 1
  2221. all_ids_count = len(video_ids)
  2222. playliststart = self._downloader.params.get('playliststart', 1) - 1
  2223. playlistend = self._downloader.params.get('playlistend', -1)
  2224. if playlistend == -1:
  2225. video_ids = video_ids[playliststart:]
  2226. else:
  2227. video_ids = video_ids[playliststart:playlistend]
  2228. self._downloader.to_screen("[youtube] user %s: Collected %d video ids (downloading %d of them)" %
  2229. (username, all_ids_count, len(video_ids)))
  2230. for video_id in video_ids:
  2231. self._youtube_ie.extract('http://www.youtube.com/watch?v=%s' % video_id)
  2232. class DepositFilesIE(InfoExtractor):
  2233. """Information extractor for depositfiles.com"""
  2234. _VALID_URL = r'(?:http://)?(?:\w+\.)?depositfiles\.com/(?:../(?#locale))?files/(.+)'
  2235. IE_NAME = u'DepositFiles'
  2236. def __init__(self, downloader=None):
  2237. InfoExtractor.__init__(self, downloader)
  2238. def report_download_webpage(self, file_id):
  2239. """Report webpage download."""
  2240. self._downloader.to_screen(u'[DepositFiles] %s: Downloading webpage' % file_id)
  2241. def report_extraction(self, file_id):
  2242. """Report information extraction."""
  2243. self._downloader.to_screen(u'[DepositFiles] %s: Extracting information' % file_id)
  2244. def _real_extract(self, url):
  2245. # At this point we have a new file
  2246. self._downloader.increment_downloads()
  2247. file_id = url.split('/')[-1]
  2248. # Rebuild url in english locale
  2249. url = 'http://depositfiles.com/en/files/' + file_id
  2250. # Retrieve file webpage with 'Free download' button pressed
  2251. free_download_indication = { 'gateway_result' : '1' }
  2252. request = urllib2.Request(url, urllib.urlencode(free_download_indication))
  2253. try:
  2254. self.report_download_webpage(file_id)
  2255. webpage = urllib2.urlopen(request).read()
  2256. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  2257. self._downloader.trouble(u'ERROR: Unable to retrieve file webpage: %s' % str(err))
  2258. return
  2259. # Search for the real file URL
  2260. mobj = re.search(r'<form action="(http://fileshare.+?)"', webpage)
  2261. if (mobj is None) or (mobj.group(1) is None):
  2262. # Try to figure out reason of the error.
  2263. mobj = re.search(r'<strong>(Attention.*?)</strong>', webpage, re.DOTALL)
  2264. if (mobj is not None) and (mobj.group(1) is not None):
  2265. restriction_message = re.sub('\s+', ' ', mobj.group(1)).strip()
  2266. self._downloader.trouble(u'ERROR: %s' % restriction_message)
  2267. else:
  2268. self._downloader.trouble(u'ERROR: unable to extract download URL from: %s' % url)
  2269. return
  2270. file_url = mobj.group(1)
  2271. file_extension = os.path.splitext(file_url)[1][1:]
  2272. # Search for file title
  2273. mobj = re.search(r'<b title="(.*?)">', webpage)
  2274. if mobj is None:
  2275. self._downloader.trouble(u'ERROR: unable to extract title')
  2276. return
  2277. file_title = mobj.group(1).decode('utf-8')
  2278. try:
  2279. # Process file information
  2280. self._downloader.process_info({
  2281. 'id': file_id.decode('utf-8'),
  2282. 'url': file_url.decode('utf-8'),
  2283. 'uploader': u'NA',
  2284. 'upload_date': u'NA',
  2285. 'title': file_title,
  2286. 'stitle': file_title,
  2287. 'ext': file_extension.decode('utf-8'),
  2288. 'format': u'NA',
  2289. 'player_url': None,
  2290. })
  2291. except UnavailableVideoError, err:
  2292. self._downloader.trouble(u'ERROR: unable to download file')
  2293. class FacebookIE(InfoExtractor):
  2294. """Information Extractor for Facebook"""
  2295. _VALID_URL = r'^(?:https?://)?(?:\w+\.)?facebook\.com/(?:video/video|photo)\.php\?(?:.*?)v=(?P<ID>\d+)(?:.*)'
  2296. _LOGIN_URL = 'https://login.facebook.com/login.php?m&next=http%3A%2F%2Fm.facebook.com%2Fhome.php&'
  2297. _NETRC_MACHINE = 'facebook'
  2298. _available_formats = ['video', 'highqual', 'lowqual']
  2299. _video_extensions = {
  2300. 'video': 'mp4',
  2301. 'highqual': 'mp4',
  2302. 'lowqual': 'mp4',
  2303. }
  2304. IE_NAME = u'facebook'
  2305. def __init__(self, downloader=None):
  2306. InfoExtractor.__init__(self, downloader)
  2307. def _reporter(self, message):
  2308. """Add header and report message."""
  2309. self._downloader.to_screen(u'[facebook] %s' % message)
  2310. def report_login(self):
  2311. """Report attempt to log in."""
  2312. self._reporter(u'Logging in')
  2313. def report_video_webpage_download(self, video_id):
  2314. """Report attempt to download video webpage."""
  2315. self._reporter(u'%s: Downloading video webpage' % video_id)
  2316. def report_information_extraction(self, video_id):
  2317. """Report attempt to extract video information."""
  2318. self._reporter(u'%s: Extracting video information' % video_id)
  2319. def _parse_page(self, video_webpage):
  2320. """Extract video information from page"""
  2321. # General data
  2322. data = {'title': r'\("video_title", "(.*?)"\)',
  2323. 'description': r'<div class="datawrap">(.*?)</div>',
  2324. 'owner': r'\("video_owner_name", "(.*?)"\)',
  2325. 'thumbnail': r'\("thumb_url", "(?P<THUMB>.*?)"\)',
  2326. }
  2327. video_info = {}
  2328. for piece in data.keys():
  2329. mobj = re.search(data[piece], video_webpage)
  2330. if mobj is not None:
  2331. video_info[piece] = urllib.unquote_plus(mobj.group(1).decode("unicode_escape"))
  2332. # Video urls
  2333. video_urls = {}
  2334. for fmt in self._available_formats:
  2335. mobj = re.search(r'\("%s_src\", "(.+?)"\)' % fmt, video_webpage)
  2336. if mobj is not None:
  2337. # URL is in a Javascript segment inside an escaped Unicode format within
  2338. # the generally utf-8 page
  2339. video_urls[fmt] = urllib.unquote_plus(mobj.group(1).decode("unicode_escape"))
  2340. video_info['video_urls'] = video_urls
  2341. return video_info
  2342. def _real_initialize(self):
  2343. if self._downloader is None:
  2344. return
  2345. useremail = None
  2346. password = None
  2347. downloader_params = self._downloader.params
  2348. # Attempt to use provided username and password or .netrc data
  2349. if downloader_params.get('username', None) is not None:
  2350. useremail = downloader_params['username']
  2351. password = downloader_params['password']
  2352. elif downloader_params.get('usenetrc', False):
  2353. try:
  2354. info = netrc.netrc().authenticators(self._NETRC_MACHINE)
  2355. if info is not None:
  2356. useremail = info[0]
  2357. password = info[2]
  2358. else:
  2359. raise netrc.NetrcParseError('No authenticators for %s' % self._NETRC_MACHINE)
  2360. except (IOError, netrc.NetrcParseError), err:
  2361. self._downloader.to_stderr(u'WARNING: parsing .netrc: %s' % str(err))
  2362. return
  2363. if useremail is None:
  2364. return
  2365. # Log in
  2366. login_form = {
  2367. 'email': useremail,
  2368. 'pass': password,
  2369. 'login': 'Log+In'
  2370. }
  2371. request = urllib2.Request(self._LOGIN_URL, urllib.urlencode(login_form))
  2372. try:
  2373. self.report_login()
  2374. login_results = urllib2.urlopen(request).read()
  2375. if re.search(r'<form(.*)name="login"(.*)</form>', login_results) is not None:
  2376. self._downloader.to_stderr(u'WARNING: unable to log in: bad username/password, or exceded login rate limit (~3/min). Check credentials or wait.')
  2377. return
  2378. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  2379. self._downloader.to_stderr(u'WARNING: unable to log in: %s' % str(err))
  2380. return
  2381. def _real_extract(self, url):
  2382. mobj = re.match(self._VALID_URL, url)
  2383. if mobj is None:
  2384. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  2385. return
  2386. video_id = mobj.group('ID')
  2387. # Get video webpage
  2388. self.report_video_webpage_download(video_id)
  2389. request = urllib2.Request('https://www.facebook.com/video/video.php?v=%s' % video_id)
  2390. try:
  2391. page = urllib2.urlopen(request)
  2392. video_webpage = page.read()
  2393. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  2394. self._downloader.trouble(u'ERROR: unable to download video webpage: %s' % str(err))
  2395. return
  2396. # Start extracting information
  2397. self.report_information_extraction(video_id)
  2398. # Extract information
  2399. video_info = self._parse_page(video_webpage)
  2400. # uploader
  2401. if 'owner' not in video_info:
  2402. self._downloader.trouble(u'ERROR: unable to extract uploader nickname')
  2403. return
  2404. video_uploader = video_info['owner']
  2405. # title
  2406. if 'title' not in video_info:
  2407. self._downloader.trouble(u'ERROR: unable to extract video title')
  2408. return
  2409. video_title = video_info['title']
  2410. video_title = video_title.decode('utf-8')
  2411. video_title = sanitize_title(video_title)
  2412. # simplified title
  2413. simple_title = re.sub(ur'(?u)([^%s]+)' % simple_title_chars, ur'_', video_title)
  2414. simple_title = simple_title.strip(ur'_')
  2415. # thumbnail image
  2416. if 'thumbnail' not in video_info:
  2417. self._downloader.trouble(u'WARNING: unable to extract video thumbnail')
  2418. video_thumbnail = ''
  2419. else:
  2420. video_thumbnail = video_info['thumbnail']
  2421. # upload date
  2422. upload_date = u'NA'
  2423. if 'upload_date' in video_info:
  2424. upload_time = video_info['upload_date']
  2425. timetuple = email.utils.parsedate_tz(upload_time)
  2426. if timetuple is not None:
  2427. try:
  2428. upload_date = time.strftime('%Y%m%d', timetuple[0:9])
  2429. except:
  2430. pass
  2431. # description
  2432. video_description = video_info.get('description', 'No description available.')
  2433. url_map = video_info['video_urls']
  2434. if len(url_map.keys()) > 0:
  2435. # Decide which formats to download
  2436. req_format = self._downloader.params.get('format', None)
  2437. format_limit = self._downloader.params.get('format_limit', None)
  2438. if format_limit is not None and format_limit in self._available_formats:
  2439. format_list = self._available_formats[self._available_formats.index(format_limit):]
  2440. else:
  2441. format_list = self._available_formats
  2442. existing_formats = [x for x in format_list if x in url_map]
  2443. if len(existing_formats) == 0:
  2444. self._downloader.trouble(u'ERROR: no known formats available for video')
  2445. return
  2446. if req_format is None:
  2447. video_url_list = [(existing_formats[0], url_map[existing_formats[0]])] # Best quality
  2448. elif req_format == 'worst':
  2449. video_url_list = [(existing_formats[len(existing_formats)-1], url_map[existing_formats[len(existing_formats)-1]])] # worst quality
  2450. elif req_format == '-1':
  2451. video_url_list = [(f, url_map[f]) for f in existing_formats] # All formats
  2452. else:
  2453. # Specific format
  2454. if req_format not in url_map:
  2455. self._downloader.trouble(u'ERROR: requested format not available')
  2456. return
  2457. video_url_list = [(req_format, url_map[req_format])] # Specific format
  2458. for format_param, video_real_url in video_url_list:
  2459. # At this point we have a new video
  2460. self._downloader.increment_downloads()
  2461. # Extension
  2462. video_extension = self._video_extensions.get(format_param, 'mp4')
  2463. try:
  2464. # Process video information
  2465. self._downloader.process_info({
  2466. 'id': video_id.decode('utf-8'),
  2467. 'url': video_real_url.decode('utf-8'),
  2468. 'uploader': video_uploader.decode('utf-8'),
  2469. 'upload_date': upload_date,
  2470. 'title': video_title,
  2471. 'stitle': simple_title,
  2472. 'ext': video_extension.decode('utf-8'),
  2473. 'format': (format_param is None and u'NA' or format_param.decode('utf-8')),
  2474. 'thumbnail': video_thumbnail.decode('utf-8'),
  2475. 'description': video_description.decode('utf-8'),
  2476. 'player_url': None,
  2477. })
  2478. except UnavailableVideoError, err:
  2479. self._downloader.trouble(u'\nERROR: unable to download video')
  2480. class BlipTVIE(InfoExtractor):
  2481. """Information extractor for blip.tv"""
  2482. _VALID_URL = r'^(?:https?://)?(?:\w+\.)?blip\.tv(/.+)$'
  2483. _URL_EXT = r'^.*\.([a-z0-9]+)$'
  2484. IE_NAME = u'blip.tv'
  2485. def report_extraction(self, file_id):
  2486. """Report information extraction."""
  2487. self._downloader.to_screen(u'[%s] %s: Extracting information' % (self.IE_NAME, file_id))
  2488. def report_direct_download(self, title):
  2489. """Report information extraction."""
  2490. self._downloader.to_screen(u'[%s] %s: Direct download detected' % (self.IE_NAME, title))
  2491. def _simplify_title(self, title):
  2492. res = re.sub(ur'(?u)([^%s]+)' % simple_title_chars, ur'_', title)
  2493. res = res.strip(ur'_')
  2494. return res
  2495. def _real_extract(self, url):
  2496. mobj = re.match(self._VALID_URL, url)
  2497. if mobj is None:
  2498. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  2499. return
  2500. if '?' in url:
  2501. cchar = '&'
  2502. else:
  2503. cchar = '?'
  2504. json_url = url + cchar + 'skin=json&version=2&no_wrap=1'
  2505. request = urllib2.Request(json_url)
  2506. self.report_extraction(mobj.group(1))
  2507. info = None
  2508. try:
  2509. urlh = urllib2.urlopen(request)
  2510. if urlh.headers.get('Content-Type', '').startswith('video/'): # Direct download
  2511. basename = url.split('/')[-1]
  2512. title,ext = os.path.splitext(basename)
  2513. ext = ext.replace('.', '')
  2514. self.report_direct_download(title)
  2515. info = {
  2516. 'id': title,
  2517. 'url': url,
  2518. 'title': title,
  2519. 'stitle': self._simplify_title(title),
  2520. 'ext': ext,
  2521. 'urlhandle': urlh
  2522. }
  2523. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  2524. self._downloader.trouble(u'ERROR: unable to download video info webpage: %s' % str(err))
  2525. return
  2526. if info is None: # Regular URL
  2527. try:
  2528. json_code = urlh.read()
  2529. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  2530. self._downloader.trouble(u'ERROR: unable to read video info webpage: %s' % str(err))
  2531. return
  2532. try:
  2533. json_data = json.loads(json_code)
  2534. if 'Post' in json_data:
  2535. data = json_data['Post']
  2536. else:
  2537. data = json_data
  2538. upload_date = datetime.datetime.strptime(data['datestamp'], '%m-%d-%y %H:%M%p').strftime('%Y%m%d')
  2539. video_url = data['media']['url']
  2540. umobj = re.match(self._URL_EXT, video_url)
  2541. if umobj is None:
  2542. raise ValueError('Can not determine filename extension')
  2543. ext = umobj.group(1)
  2544. info = {
  2545. 'id': data['item_id'],
  2546. 'url': video_url,
  2547. 'uploader': data['display_name'],
  2548. 'upload_date': upload_date,
  2549. 'title': data['title'],
  2550. 'stitle': self._simplify_title(data['title']),
  2551. 'ext': ext,
  2552. 'format': data['media']['mimeType'],
  2553. 'thumbnail': data['thumbnailUrl'],
  2554. 'description': data['description'],
  2555. 'player_url': data['embedUrl']
  2556. }
  2557. except (ValueError,KeyError), err:
  2558. self._downloader.trouble(u'ERROR: unable to parse video information: %s' % repr(err))
  2559. return
  2560. self._downloader.increment_downloads()
  2561. try:
  2562. self._downloader.process_info(info)
  2563. except UnavailableVideoError, err:
  2564. self._downloader.trouble(u'\nERROR: unable to download video')
  2565. class MyVideoIE(InfoExtractor):
  2566. """Information Extractor for myvideo.de."""
  2567. _VALID_URL = r'(?:http://)?(?:www\.)?myvideo\.de/watch/([0-9]+)/([^?/]+).*'
  2568. IE_NAME = u'myvideo'
  2569. def __init__(self, downloader=None):
  2570. InfoExtractor.__init__(self, downloader)
  2571. def report_download_webpage(self, video_id):
  2572. """Report webpage download."""
  2573. self._downloader.to_screen(u'[myvideo] %s: Downloading webpage' % video_id)
  2574. def report_extraction(self, video_id):
  2575. """Report information extraction."""
  2576. self._downloader.to_screen(u'[myvideo] %s: Extracting information' % video_id)
  2577. def _real_extract(self,url):
  2578. mobj = re.match(self._VALID_URL, url)
  2579. if mobj is None:
  2580. self._download.trouble(u'ERROR: invalid URL: %s' % url)
  2581. return
  2582. video_id = mobj.group(1)
  2583. simple_title = mobj.group(2).decode('utf-8')
  2584. # should actually not be necessary
  2585. simple_title = sanitize_title(simple_title)
  2586. simple_title = re.sub(ur'(?u)([^%s]+)' % simple_title_chars, ur'_', simple_title)
  2587. # Get video webpage
  2588. request = urllib2.Request('http://www.myvideo.de/watch/%s' % video_id)
  2589. try:
  2590. self.report_download_webpage(video_id)
  2591. webpage = urllib2.urlopen(request).read()
  2592. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  2593. self._downloader.trouble(u'ERROR: Unable to retrieve video webpage: %s' % str(err))
  2594. return
  2595. self.report_extraction(video_id)
  2596. mobj = re.search(r'<link rel=\'image_src\' href=\'(http://is[0-9].myvideo\.de/de/movie[0-9]+/[a-f0-9]+)/thumbs/[^.]+\.jpg\' />',
  2597. webpage)
  2598. if mobj is None:
  2599. self._downloader.trouble(u'ERROR: unable to extract media URL')
  2600. return
  2601. video_url = mobj.group(1) + ('/%s.flv' % video_id)
  2602. mobj = re.search('<title>([^<]+)</title>', webpage)
  2603. if mobj is None:
  2604. self._downloader.trouble(u'ERROR: unable to extract title')
  2605. return
  2606. video_title = mobj.group(1)
  2607. video_title = sanitize_title(video_title)
  2608. try:
  2609. self._downloader.process_info({
  2610. 'id': video_id,
  2611. 'url': video_url,
  2612. 'uploader': u'NA',
  2613. 'upload_date': u'NA',
  2614. 'title': video_title,
  2615. 'stitle': simple_title,
  2616. 'ext': u'flv',
  2617. 'format': u'NA',
  2618. 'player_url': None,
  2619. })
  2620. except UnavailableVideoError:
  2621. self._downloader.trouble(u'\nERROR: Unable to download video')
  2622. class ComedyCentralIE(InfoExtractor):
  2623. """Information extractor for The Daily Show and Colbert Report """
  2624. _VALID_URL = r'^(:(?P<shortname>tds|thedailyshow|cr|colbert|colbertnation|colbertreport))|(https?://)?(www\.)?(?P<showname>thedailyshow|colbertnation)\.com/full-episodes/(?P<episode>.*)$'
  2625. IE_NAME = u'comedycentral'
  2626. def report_extraction(self, episode_id):
  2627. self._downloader.to_screen(u'[comedycentral] %s: Extracting information' % episode_id)
  2628. def report_config_download(self, episode_id):
  2629. self._downloader.to_screen(u'[comedycentral] %s: Downloading configuration' % episode_id)
  2630. def report_index_download(self, episode_id):
  2631. self._downloader.to_screen(u'[comedycentral] %s: Downloading show index' % episode_id)
  2632. def report_player_url(self, episode_id):
  2633. self._downloader.to_screen(u'[comedycentral] %s: Determining player URL' % episode_id)
  2634. def _simplify_title(self, title):
  2635. res = re.sub(ur'(?u)([^%s]+)' % simple_title_chars, ur'_', title)
  2636. res = res.strip(ur'_')
  2637. return res
  2638. def _real_extract(self, url):
  2639. mobj = re.match(self._VALID_URL, url)
  2640. if mobj is None:
  2641. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  2642. return
  2643. if mobj.group('shortname'):
  2644. if mobj.group('shortname') in ('tds', 'thedailyshow'):
  2645. url = 'http://www.thedailyshow.com/full-episodes/'
  2646. else:
  2647. url = 'http://www.colbertnation.com/full-episodes/'
  2648. mobj = re.match(self._VALID_URL, url)
  2649. assert mobj is not None
  2650. dlNewest = not mobj.group('episode')
  2651. if dlNewest:
  2652. epTitle = mobj.group('showname')
  2653. else:
  2654. epTitle = mobj.group('episode')
  2655. req = urllib2.Request(url)
  2656. self.report_extraction(epTitle)
  2657. try:
  2658. htmlHandle = urllib2.urlopen(req)
  2659. html = htmlHandle.read()
  2660. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  2661. self._downloader.trouble(u'ERROR: unable to download webpage: %s' % unicode(err))
  2662. return
  2663. if dlNewest:
  2664. url = htmlHandle.geturl()
  2665. mobj = re.match(self._VALID_URL, url)
  2666. if mobj is None:
  2667. self._downloader.trouble(u'ERROR: Invalid redirected URL: ' + url)
  2668. return
  2669. if mobj.group('episode') == '':
  2670. self._downloader.trouble(u'ERROR: Redirected URL is still not specific: ' + url)
  2671. return
  2672. epTitle = mobj.group('episode')
  2673. mMovieParams = re.findall('<param name="movie" value="(http://media.mtvnservices.com/([^"]*episode.*?:.*?))"/>', html)
  2674. if len(mMovieParams) == 0:
  2675. self._downloader.trouble(u'ERROR: unable to find Flash URL in webpage ' + url)
  2676. return
  2677. playerUrl_raw = mMovieParams[0][0]
  2678. self.report_player_url(epTitle)
  2679. try:
  2680. urlHandle = urllib2.urlopen(playerUrl_raw)
  2681. playerUrl = urlHandle.geturl()
  2682. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  2683. self._downloader.trouble(u'ERROR: unable to find out player URL: ' + unicode(err))
  2684. return
  2685. uri = mMovieParams[0][1]
  2686. indexUrl = 'http://shadow.comedycentral.com/feeds/video_player/mrss/?' + urllib.urlencode({'uri': uri})
  2687. self.report_index_download(epTitle)
  2688. try:
  2689. indexXml = urllib2.urlopen(indexUrl).read()
  2690. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  2691. self._downloader.trouble(u'ERROR: unable to download episode index: ' + unicode(err))
  2692. return
  2693. idoc = xml.etree.ElementTree.fromstring(indexXml)
  2694. itemEls = idoc.findall('.//item')
  2695. for itemEl in itemEls:
  2696. mediaId = itemEl.findall('./guid')[0].text
  2697. shortMediaId = mediaId.split(':')[-1]
  2698. showId = mediaId.split(':')[-2].replace('.com', '')
  2699. officialTitle = itemEl.findall('./title')[0].text
  2700. officialDate = itemEl.findall('./pubDate')[0].text
  2701. configUrl = ('http://www.comedycentral.com/global/feeds/entertainment/media/mediaGenEntertainment.jhtml?' +
  2702. urllib.urlencode({'uri': mediaId}))
  2703. configReq = urllib2.Request(configUrl)
  2704. self.report_config_download(epTitle)
  2705. try:
  2706. configXml = urllib2.urlopen(configReq).read()
  2707. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  2708. self._downloader.trouble(u'ERROR: unable to download webpage: %s' % unicode(err))
  2709. return
  2710. cdoc = xml.etree.ElementTree.fromstring(configXml)
  2711. turls = []
  2712. for rendition in cdoc.findall('.//rendition'):
  2713. finfo = (rendition.attrib['bitrate'], rendition.findall('./src')[0].text)
  2714. turls.append(finfo)
  2715. if len(turls) == 0:
  2716. self._downloader.trouble(u'\nERROR: unable to download ' + mediaId + ': No videos found')
  2717. continue
  2718. # For now, just pick the highest bitrate
  2719. format,video_url = turls[-1]
  2720. self._downloader.increment_downloads()
  2721. effTitle = showId + '-' + epTitle
  2722. info = {
  2723. 'id': shortMediaId,
  2724. 'url': video_url,
  2725. 'uploader': showId,
  2726. 'upload_date': officialDate,
  2727. 'title': effTitle,
  2728. 'stitle': self._simplify_title(effTitle),
  2729. 'ext': 'mp4',
  2730. 'format': format,
  2731. 'thumbnail': None,
  2732. 'description': officialTitle,
  2733. 'player_url': playerUrl
  2734. }
  2735. try:
  2736. self._downloader.process_info(info)
  2737. except UnavailableVideoError, err:
  2738. self._downloader.trouble(u'\nERROR: unable to download ' + mediaId)
  2739. continue
  2740. class EscapistIE(InfoExtractor):
  2741. """Information extractor for The Escapist """
  2742. _VALID_URL = r'^(https?://)?(www\.)?escapistmagazine\.com/videos/view/(?P<showname>[^/]+)/(?P<episode>[^/?]+)[/?]?.*$'
  2743. IE_NAME = u'escapist'
  2744. def report_extraction(self, showName):
  2745. self._downloader.to_screen(u'[escapist] %s: Extracting information' % showName)
  2746. def report_config_download(self, showName):
  2747. self._downloader.to_screen(u'[escapist] %s: Downloading configuration' % showName)
  2748. def _simplify_title(self, title):
  2749. res = re.sub(ur'(?u)([^%s]+)' % simple_title_chars, ur'_', title)
  2750. res = res.strip(ur'_')
  2751. return res
  2752. def _real_extract(self, url):
  2753. htmlParser = HTMLParser.HTMLParser()
  2754. mobj = re.match(self._VALID_URL, url)
  2755. if mobj is None:
  2756. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  2757. return
  2758. showName = mobj.group('showname')
  2759. videoId = mobj.group('episode')
  2760. self.report_extraction(showName)
  2761. try:
  2762. webPage = urllib2.urlopen(url).read()
  2763. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  2764. self._downloader.trouble(u'ERROR: unable to download webpage: ' + unicode(err))
  2765. return
  2766. descMatch = re.search('<meta name="description" content="([^"]*)"', webPage)
  2767. description = htmlParser.unescape(descMatch.group(1))
  2768. imgMatch = re.search('<meta property="og:image" content="([^"]*)"', webPage)
  2769. imgUrl = htmlParser.unescape(imgMatch.group(1))
  2770. playerUrlMatch = re.search('<meta property="og:video" content="([^"]*)"', webPage)
  2771. playerUrl = htmlParser.unescape(playerUrlMatch.group(1))
  2772. configUrlMatch = re.search('config=(.*)$', playerUrl)
  2773. configUrl = urllib2.unquote(configUrlMatch.group(1))
  2774. self.report_config_download(showName)
  2775. try:
  2776. configJSON = urllib2.urlopen(configUrl).read()
  2777. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  2778. self._downloader.trouble(u'ERROR: unable to download configuration: ' + unicode(err))
  2779. return
  2780. # Technically, it's JavaScript, not JSON
  2781. configJSON = configJSON.replace("'", '"')
  2782. try:
  2783. config = json.loads(configJSON)
  2784. except (ValueError,), err:
  2785. self._downloader.trouble(u'ERROR: Invalid JSON in configuration file: ' + unicode(err))
  2786. return
  2787. playlist = config['playlist']
  2788. videoUrl = playlist[1]['url']
  2789. self._downloader.increment_downloads()
  2790. info = {
  2791. 'id': videoId,
  2792. 'url': videoUrl,
  2793. 'uploader': showName,
  2794. 'upload_date': None,
  2795. 'title': showName,
  2796. 'stitle': self._simplify_title(showName),
  2797. 'ext': 'flv',
  2798. 'format': 'flv',
  2799. 'thumbnail': imgUrl,
  2800. 'description': description,
  2801. 'player_url': playerUrl,
  2802. }
  2803. try:
  2804. self._downloader.process_info(info)
  2805. except UnavailableVideoError, err:
  2806. self._downloader.trouble(u'\nERROR: unable to download ' + videoId)
  2807. class CollegeHumorIE(InfoExtractor):
  2808. """Information extractor for collegehumor.com"""
  2809. _VALID_URL = r'^(?:https?://)?(?:www\.)?collegehumor\.com/video/(?P<videoid>[0-9]+)/(?P<shorttitle>.*)$'
  2810. IE_NAME = u'collegehumor'
  2811. def report_webpage(self, video_id):
  2812. """Report information extraction."""
  2813. self._downloader.to_screen(u'[%s] %s: Downloading webpage' % (self.IE_NAME, video_id))
  2814. def report_extraction(self, video_id):
  2815. """Report information extraction."""
  2816. self._downloader.to_screen(u'[%s] %s: Extracting information' % (self.IE_NAME, video_id))
  2817. def _simplify_title(self, title):
  2818. res = re.sub(ur'(?u)([^%s]+)' % simple_title_chars, ur'_', title)
  2819. res = res.strip(ur'_')
  2820. return res
  2821. def _real_extract(self, url):
  2822. htmlParser = HTMLParser.HTMLParser()
  2823. mobj = re.match(self._VALID_URL, url)
  2824. if mobj is None:
  2825. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  2826. return
  2827. video_id = mobj.group('videoid')
  2828. self.report_webpage(video_id)
  2829. request = urllib2.Request(url)
  2830. try:
  2831. webpage = urllib2.urlopen(request).read()
  2832. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  2833. self._downloader.trouble(u'ERROR: unable to download video webpage: %s' % str(err))
  2834. return
  2835. m = re.search(r'id="video:(?P<internalvideoid>[0-9]+)"', webpage)
  2836. if m is None:
  2837. self._downloader.trouble(u'ERROR: Cannot extract internal video ID')
  2838. return
  2839. internal_video_id = m.group('internalvideoid')
  2840. info = {
  2841. 'id': video_id,
  2842. 'internal_id': internal_video_id,
  2843. }
  2844. self.report_extraction(video_id)
  2845. xmlUrl = 'http://www.collegehumor.com/moogaloop/video:' + internal_video_id
  2846. try:
  2847. metaXml = urllib2.urlopen(xmlUrl).read()
  2848. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  2849. self._downloader.trouble(u'ERROR: unable to download video info XML: %s' % str(err))
  2850. return
  2851. mdoc = xml.etree.ElementTree.fromstring(metaXml)
  2852. try:
  2853. videoNode = mdoc.findall('./video')[0]
  2854. info['description'] = videoNode.findall('./description')[0].text
  2855. info['title'] = videoNode.findall('./caption')[0].text
  2856. info['stitle'] = self._simplify_title(info['title'])
  2857. info['url'] = videoNode.findall('./file')[0].text
  2858. info['thumbnail'] = videoNode.findall('./thumbnail')[0].text
  2859. info['ext'] = info['url'].rpartition('.')[2]
  2860. info['format'] = info['ext']
  2861. except IndexError:
  2862. self._downloader.trouble(u'\nERROR: Invalid metadata XML file')
  2863. return
  2864. self._downloader.increment_downloads()
  2865. try:
  2866. self._downloader.process_info(info)
  2867. except UnavailableVideoError, err:
  2868. self._downloader.trouble(u'\nERROR: unable to download video')
  2869. class XVideosIE(InfoExtractor):
  2870. """Information extractor for xvideos.com"""
  2871. _VALID_URL = r'^(?:https?://)?(?:www\.)?xvideos\.com/video([0-9]+)(?:.*)'
  2872. IE_NAME = u'xvideos'
  2873. def report_webpage(self, video_id):
  2874. """Report information extraction."""
  2875. self._downloader.to_screen(u'[%s] %s: Downloading webpage' % (self.IE_NAME, video_id))
  2876. def report_extraction(self, video_id):
  2877. """Report information extraction."""
  2878. self._downloader.to_screen(u'[%s] %s: Extracting information' % (self.IE_NAME, video_id))
  2879. def _simplify_title(self, title):
  2880. res = re.sub(ur'(?u)([^%s]+)' % simple_title_chars, ur'_', title)
  2881. res = res.strip(ur'_')
  2882. return res
  2883. def _real_extract(self, url):
  2884. htmlParser = HTMLParser.HTMLParser()
  2885. mobj = re.match(self._VALID_URL, url)
  2886. if mobj is None:
  2887. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  2888. return
  2889. video_id = mobj.group(1).decode('utf-8')
  2890. self.report_webpage(video_id)
  2891. request = urllib2.Request(r'http://www.xvideos.com/video' + video_id)
  2892. try:
  2893. webpage = urllib2.urlopen(request).read()
  2894. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  2895. self._downloader.trouble(u'ERROR: unable to download video webpage: %s' % str(err))
  2896. return
  2897. self.report_extraction(video_id)
  2898. # Extract video URL
  2899. mobj = re.search(r'flv_url=(.+?)&', webpage)
  2900. if mobj is None:
  2901. self._downloader.trouble(u'ERROR: unable to extract video url')
  2902. return
  2903. video_url = urllib2.unquote(mobj.group(1).decode('utf-8'))
  2904. # Extract title
  2905. mobj = re.search(r'<title>(.*?)\s+-\s+XVID', webpage)
  2906. if mobj is None:
  2907. self._downloader.trouble(u'ERROR: unable to extract video title')
  2908. return
  2909. video_title = mobj.group(1).decode('utf-8')
  2910. # Extract video thumbnail
  2911. mobj = re.search(r'http://(?:img.*?\.)xvideos.com/videos/thumbs/[a-fA-F0-9]/[a-fA-F0-9]/[a-fA-F0-9]/([a-fA-F0-9.]+jpg)', webpage)
  2912. if mobj is None:
  2913. self._downloader.trouble(u'ERROR: unable to extract video thumbnail')
  2914. return
  2915. video_thumbnail = mobj.group(1).decode('utf-8')
  2916. self._downloader.increment_downloads()
  2917. info = {
  2918. 'id': video_id,
  2919. 'url': video_url,
  2920. 'uploader': None,
  2921. 'upload_date': None,
  2922. 'title': video_title,
  2923. 'stitle': self._simplify_title(video_title),
  2924. 'ext': 'flv',
  2925. 'format': 'flv',
  2926. 'thumbnail': video_thumbnail,
  2927. 'description': None,
  2928. 'player_url': None,
  2929. }
  2930. try:
  2931. self._downloader.process_info(info)
  2932. except UnavailableVideoError, err:
  2933. self._downloader.trouble(u'\nERROR: unable to download ' + video_id)
  2934. class SoundcloudIE(InfoExtractor):
  2935. """Information extractor for soundcloud.com
  2936. To access the media, the uid of the song and a stream token
  2937. must be extracted from the page source and the script must make
  2938. a request to media.soundcloud.com/crossdomain.xml. Then
  2939. the media can be grabbed by requesting from an url composed
  2940. of the stream token and uid
  2941. """
  2942. _VALID_URL = r'^(?:https?://)?(?:www\.)?soundcloud\.com/([\w\d-]+)/([\w\d-]+)'
  2943. IE_NAME = u'soundcloud'
  2944. def __init__(self, downloader=None):
  2945. InfoExtractor.__init__(self, downloader)
  2946. def report_webpage(self, video_id):
  2947. """Report information extraction."""
  2948. self._downloader.to_screen(u'[%s] %s: Downloading webpage' % (self.IE_NAME, video_id))
  2949. def report_extraction(self, video_id):
  2950. """Report information extraction."""
  2951. self._downloader.to_screen(u'[%s] %s: Extracting information' % (self.IE_NAME, video_id))
  2952. def _real_extract(self, url):
  2953. htmlParser = HTMLParser.HTMLParser()
  2954. mobj = re.match(self._VALID_URL, url)
  2955. if mobj is None:
  2956. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  2957. return
  2958. # extract uploader (which is in the url)
  2959. uploader = mobj.group(1).decode('utf-8')
  2960. # extract simple title (uploader + slug of song title)
  2961. slug_title = mobj.group(2).decode('utf-8')
  2962. simple_title = uploader + '-' + slug_title
  2963. self.report_webpage('%s/%s' % (uploader, slug_title))
  2964. request = urllib2.Request('http://soundcloud.com/%s/%s' % (uploader, slug_title))
  2965. try:
  2966. webpage = urllib2.urlopen(request).read()
  2967. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  2968. self._downloader.trouble(u'ERROR: unable to download video webpage: %s' % str(err))
  2969. return
  2970. self.report_extraction('%s/%s' % (uploader, slug_title))
  2971. # extract uid and stream token that soundcloud hands out for access
  2972. mobj = re.search('"uid":"([\w\d]+?)".*?stream_token=([\w\d]+)', webpage)
  2973. if mobj:
  2974. video_id = mobj.group(1)
  2975. stream_token = mobj.group(2)
  2976. # extract unsimplified title
  2977. mobj = re.search('"title":"(.*?)",', webpage)
  2978. if mobj:
  2979. title = mobj.group(1)
  2980. # construct media url (with uid/token)
  2981. mediaURL = "http://media.soundcloud.com/stream/%s?stream_token=%s"
  2982. mediaURL = mediaURL % (video_id, stream_token)
  2983. # description
  2984. description = u'No description available'
  2985. mobj = re.search('track-description-value"><p>(.*?)</p>', webpage)
  2986. if mobj:
  2987. description = mobj.group(1)
  2988. # upload date
  2989. upload_date = None
  2990. mobj = re.search("pretty-date'>on ([\w]+ [\d]+, [\d]+ \d+:\d+)</abbr></h2>", webpage)
  2991. if mobj:
  2992. try:
  2993. upload_date = datetime.datetime.strptime(mobj.group(1), '%B %d, %Y %H:%M').strftime('%Y%m%d')
  2994. except Exception as e:
  2995. print str(e)
  2996. # for soundcloud, a request to a cross domain is required for cookies
  2997. request = urllib2.Request('http://media.soundcloud.com/crossdomain.xml', std_headers)
  2998. try:
  2999. self._downloader.process_info({
  3000. 'id': video_id.decode('utf-8'),
  3001. 'url': mediaURL,
  3002. 'uploader': uploader.decode('utf-8'),
  3003. 'upload_date': upload_date,
  3004. 'title': simple_title.decode('utf-8'),
  3005. 'stitle': simple_title.decode('utf-8'),
  3006. 'ext': u'mp3',
  3007. 'format': u'NA',
  3008. 'player_url': None,
  3009. 'description': description.decode('utf-8')
  3010. })
  3011. except UnavailableVideoError:
  3012. self._downloader.trouble(u'\nERROR: unable to download video')
  3013. class InfoQIE(InfoExtractor):
  3014. """Information extractor for infoq.com"""
  3015. _VALID_URL = r'^(?:https?://)?(?:www\.)?infoq\.com/[^/]+/[^/]+$'
  3016. IE_NAME = u'infoq'
  3017. def report_webpage(self, video_id):
  3018. """Report information extraction."""
  3019. self._downloader.to_screen(u'[%s] %s: Downloading webpage' % (self.IE_NAME, video_id))
  3020. def report_extraction(self, video_id):
  3021. """Report information extraction."""
  3022. self._downloader.to_screen(u'[%s] %s: Extracting information' % (self.IE_NAME, video_id))
  3023. def _simplify_title(self, title):
  3024. res = re.sub(ur'(?u)([^%s]+)' % simple_title_chars, ur'_', title)
  3025. res = res.strip(ur'_')
  3026. return res
  3027. def _real_extract(self, url):
  3028. htmlParser = HTMLParser.HTMLParser()
  3029. mobj = re.match(self._VALID_URL, url)
  3030. if mobj is None:
  3031. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  3032. return
  3033. self.report_webpage(url)
  3034. request = urllib2.Request(url)
  3035. try:
  3036. webpage = urllib2.urlopen(request).read()
  3037. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  3038. self._downloader.trouble(u'ERROR: unable to download video webpage: %s' % str(err))
  3039. return
  3040. self.report_extraction(url)
  3041. # Extract video URL
  3042. mobj = re.search(r"jsclassref='([^']*)'", webpage)
  3043. if mobj is None:
  3044. self._downloader.trouble(u'ERROR: unable to extract video url')
  3045. return
  3046. video_url = 'rtmpe://video.infoq.com/cfx/st/' + urllib2.unquote(mobj.group(1).decode('base64'))
  3047. # Extract title
  3048. mobj = re.search(r'contentTitle = "(.*?)";', webpage)
  3049. if mobj is None:
  3050. self._downloader.trouble(u'ERROR: unable to extract video title')
  3051. return
  3052. video_title = mobj.group(1).decode('utf-8')
  3053. # Extract description
  3054. video_description = u'No description available.'
  3055. mobj = re.search(r'<meta name="description" content="(.*)"(?:\s*/)?>', webpage)
  3056. if mobj is not None:
  3057. video_description = mobj.group(1).decode('utf-8')
  3058. video_filename = video_url.split('/')[-1]
  3059. video_id, extension = video_filename.split('.')
  3060. self._downloader.increment_downloads()
  3061. info = {
  3062. 'id': video_id,
  3063. 'url': video_url,
  3064. 'uploader': None,
  3065. 'upload_date': None,
  3066. 'title': video_title,
  3067. 'stitle': self._simplify_title(video_title),
  3068. 'ext': extension,
  3069. 'format': extension, # Extension is always(?) mp4, but seems to be flv
  3070. 'thumbnail': None,
  3071. 'description': video_description,
  3072. 'player_url': None,
  3073. }
  3074. try:
  3075. self._downloader.process_info(info)
  3076. except UnavailableVideoError, err:
  3077. self._downloader.trouble(u'\nERROR: unable to download ' + video_url)
  3078. class PostProcessor(object):
  3079. """Post Processor class.
  3080. PostProcessor objects can be added to downloaders with their
  3081. add_post_processor() method. When the downloader has finished a
  3082. successful download, it will take its internal chain of PostProcessors
  3083. and start calling the run() method on each one of them, first with
  3084. an initial argument and then with the returned value of the previous
  3085. PostProcessor.
  3086. The chain will be stopped if one of them ever returns None or the end
  3087. of the chain is reached.
  3088. PostProcessor objects follow a "mutual registration" process similar
  3089. to InfoExtractor objects.
  3090. """
  3091. _downloader = None
  3092. def __init__(self, downloader=None):
  3093. self._downloader = downloader
  3094. def set_downloader(self, downloader):
  3095. """Sets the downloader for this PP."""
  3096. self._downloader = downloader
  3097. def run(self, information):
  3098. """Run the PostProcessor.
  3099. The "information" argument is a dictionary like the ones
  3100. composed by InfoExtractors. The only difference is that this
  3101. one has an extra field called "filepath" that points to the
  3102. downloaded file.
  3103. When this method returns None, the postprocessing chain is
  3104. stopped. However, this method may return an information
  3105. dictionary that will be passed to the next postprocessing
  3106. object in the chain. It can be the one it received after
  3107. changing some fields.
  3108. In addition, this method may raise a PostProcessingError
  3109. exception that will be taken into account by the downloader
  3110. it was called from.
  3111. """
  3112. return information # by default, do nothing
  3113. class FFmpegExtractAudioPP(PostProcessor):
  3114. def __init__(self, downloader=None, preferredcodec=None, preferredquality=None, keepvideo=False):
  3115. PostProcessor.__init__(self, downloader)
  3116. if preferredcodec is None:
  3117. preferredcodec = 'best'
  3118. self._preferredcodec = preferredcodec
  3119. self._preferredquality = preferredquality
  3120. self._keepvideo = keepvideo
  3121. @staticmethod
  3122. def get_audio_codec(path):
  3123. try:
  3124. cmd = ['ffprobe', '-show_streams', '--', path]
  3125. handle = subprocess.Popen(cmd, stderr=file(os.path.devnull, 'w'), stdout=subprocess.PIPE)
  3126. output = handle.communicate()[0]
  3127. if handle.wait() != 0:
  3128. return None
  3129. except (IOError, OSError):
  3130. return None
  3131. audio_codec = None
  3132. for line in output.split('\n'):
  3133. if line.startswith('codec_name='):
  3134. audio_codec = line.split('=')[1].strip()
  3135. elif line.strip() == 'codec_type=audio' and audio_codec is not None:
  3136. return audio_codec
  3137. return None
  3138. @staticmethod
  3139. def run_ffmpeg(path, out_path, codec, more_opts):
  3140. try:
  3141. cmd = ['ffmpeg', '-y', '-i', path, '-vn', '-acodec', codec] + more_opts + ['--', out_path]
  3142. ret = subprocess.call(cmd, stdout=file(os.path.devnull, 'w'), stderr=subprocess.STDOUT)
  3143. return (ret == 0)
  3144. except (IOError, OSError):
  3145. return False
  3146. def run(self, information):
  3147. path = information['filepath']
  3148. filecodec = self.get_audio_codec(path)
  3149. if filecodec is None:
  3150. self._downloader.to_stderr(u'WARNING: unable to obtain file audio codec with ffprobe')
  3151. return None
  3152. more_opts = []
  3153. if self._preferredcodec == 'best' or self._preferredcodec == filecodec:
  3154. if filecodec in ['aac', 'mp3', 'vorbis']:
  3155. # Lossless if possible
  3156. acodec = 'copy'
  3157. extension = filecodec
  3158. if filecodec == 'aac':
  3159. more_opts = ['-f', 'adts']
  3160. if filecodec == 'vorbis':
  3161. extension = 'ogg'
  3162. else:
  3163. # MP3 otherwise.
  3164. acodec = 'libmp3lame'
  3165. extension = 'mp3'
  3166. more_opts = []
  3167. if self._preferredquality is not None:
  3168. more_opts += ['-ab', self._preferredquality]
  3169. else:
  3170. # We convert the audio (lossy)
  3171. acodec = {'mp3': 'libmp3lame', 'aac': 'aac', 'vorbis': 'libvorbis'}[self._preferredcodec]
  3172. extension = self._preferredcodec
  3173. more_opts = []
  3174. if self._preferredquality is not None:
  3175. more_opts += ['-ab', self._preferredquality]
  3176. if self._preferredcodec == 'aac':
  3177. more_opts += ['-f', 'adts']
  3178. if self._preferredcodec == 'vorbis':
  3179. extension = 'ogg'
  3180. (prefix, ext) = os.path.splitext(path)
  3181. new_path = prefix + '.' + extension
  3182. self._downloader.to_screen(u'[ffmpeg] Destination: %s' % new_path)
  3183. status = self.run_ffmpeg(path, new_path, acodec, more_opts)
  3184. if not status:
  3185. self._downloader.to_stderr(u'WARNING: error running ffmpeg')
  3186. return None
  3187. # Try to update the date time for extracted audio file.
  3188. if information.get('filetime') is not None:
  3189. try:
  3190. os.utime(new_path, (time.time(), information['filetime']))
  3191. except:
  3192. self._downloader.to_stderr(u'WARNING: Cannot update utime of audio file')
  3193. if not self._keepvideo:
  3194. try:
  3195. os.remove(path)
  3196. except (IOError, OSError):
  3197. self._downloader.to_stderr(u'WARNING: Unable to remove downloaded video file')
  3198. return None
  3199. information['filepath'] = new_path
  3200. return information
  3201. def updateSelf(downloader, filename):
  3202. ''' Update the program file with the latest version from the repository '''
  3203. # Note: downloader only used for options
  3204. if not os.access(filename, os.W_OK):
  3205. sys.exit('ERROR: no write permissions on %s' % filename)
  3206. downloader.to_screen('Updating to latest version...')
  3207. try:
  3208. try:
  3209. urlh = urllib.urlopen(UPDATE_URL)
  3210. newcontent = urlh.read()
  3211. vmatch = re.search("__version__ = '([^']+)'", newcontent)
  3212. if vmatch is not None and vmatch.group(1) == __version__:
  3213. downloader.to_screen('youtube-dl is up-to-date (' + __version__ + ')')
  3214. return
  3215. finally:
  3216. urlh.close()
  3217. except (IOError, OSError), err:
  3218. sys.exit('ERROR: unable to download latest version')
  3219. try:
  3220. outf = open(filename, 'wb')
  3221. try:
  3222. outf.write(newcontent)
  3223. finally:
  3224. outf.close()
  3225. except (IOError, OSError), err:
  3226. sys.exit('ERROR: unable to overwrite current version')
  3227. downloader.to_screen('Updated youtube-dl. Restart youtube-dl to use the new version.')
  3228. def parseOpts():
  3229. # Deferred imports
  3230. import getpass
  3231. import optparse
  3232. def _format_option_string(option):
  3233. ''' ('-o', '--option') -> -o, --format METAVAR'''
  3234. opts = []
  3235. if option._short_opts: opts.append(option._short_opts[0])
  3236. if option._long_opts: opts.append(option._long_opts[0])
  3237. if len(opts) > 1: opts.insert(1, ', ')
  3238. if option.takes_value(): opts.append(' %s' % option.metavar)
  3239. return "".join(opts)
  3240. def _find_term_columns():
  3241. columns = os.environ.get('COLUMNS', None)
  3242. if columns:
  3243. return int(columns)
  3244. try:
  3245. sp = subprocess.Popen(['stty', 'size'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  3246. out,err = sp.communicate()
  3247. return int(out.split()[1])
  3248. except:
  3249. pass
  3250. return None
  3251. max_width = 80
  3252. max_help_position = 80
  3253. # No need to wrap help messages if we're on a wide console
  3254. columns = _find_term_columns()
  3255. if columns: max_width = columns
  3256. fmt = optparse.IndentedHelpFormatter(width=max_width, max_help_position=max_help_position)
  3257. fmt.format_option_strings = _format_option_string
  3258. kw = {
  3259. 'version' : __version__,
  3260. 'formatter' : fmt,
  3261. 'usage' : '%prog [options] url [url...]',
  3262. 'conflict_handler' : 'resolve',
  3263. }
  3264. parser = optparse.OptionParser(**kw)
  3265. # option groups
  3266. general = optparse.OptionGroup(parser, 'General Options')
  3267. selection = optparse.OptionGroup(parser, 'Video Selection')
  3268. authentication = optparse.OptionGroup(parser, 'Authentication Options')
  3269. video_format = optparse.OptionGroup(parser, 'Video Format Options')
  3270. postproc = optparse.OptionGroup(parser, 'Post-processing Options')
  3271. filesystem = optparse.OptionGroup(parser, 'Filesystem Options')
  3272. verbosity = optparse.OptionGroup(parser, 'Verbosity / Simulation Options')
  3273. general.add_option('-h', '--help',
  3274. action='help', help='print this help text and exit')
  3275. general.add_option('-v', '--version',
  3276. action='version', help='print program version and exit')
  3277. general.add_option('-U', '--update',
  3278. action='store_true', dest='update_self', help='update this program to latest version')
  3279. general.add_option('-i', '--ignore-errors',
  3280. action='store_true', dest='ignoreerrors', help='continue on download errors', default=False)
  3281. general.add_option('-r', '--rate-limit',
  3282. dest='ratelimit', metavar='LIMIT', help='download rate limit (e.g. 50k or 44.6m)')
  3283. general.add_option('-R', '--retries',
  3284. dest='retries', metavar='RETRIES', help='number of retries (default is 10)', default=10)
  3285. general.add_option('--dump-user-agent',
  3286. action='store_true', dest='dump_user_agent',
  3287. help='display the current browser identification', default=False)
  3288. general.add_option('--list-extractors',
  3289. action='store_true', dest='list_extractors',
  3290. help='List all supported extractors and the URLs they would handle', default=False)
  3291. selection.add_option('--playlist-start',
  3292. dest='playliststart', metavar='NUMBER', help='playlist video to start at (default is 1)', default=1)
  3293. selection.add_option('--playlist-end',
  3294. dest='playlistend', metavar='NUMBER', help='playlist video to end at (default is last)', default=-1)
  3295. selection.add_option('--match-title', dest='matchtitle', metavar='REGEX',help='download only matching titles (regex or caseless sub-string)')
  3296. selection.add_option('--reject-title', dest='rejecttitle', metavar='REGEX',help='skip download for matching titles (regex or caseless sub-string)')
  3297. authentication.add_option('-u', '--username',
  3298. dest='username', metavar='USERNAME', help='account username')
  3299. authentication.add_option('-p', '--password',
  3300. dest='password', metavar='PASSWORD', help='account password')
  3301. authentication.add_option('-n', '--netrc',
  3302. action='store_true', dest='usenetrc', help='use .netrc authentication data', default=False)
  3303. video_format.add_option('-f', '--format',
  3304. action='store', dest='format', metavar='FORMAT', help='video format code')
  3305. video_format.add_option('--all-formats',
  3306. action='store_const', dest='format', help='download all available video formats', const='all')
  3307. video_format.add_option('--max-quality',
  3308. action='store', dest='format_limit', metavar='FORMAT', help='highest quality format to download')
  3309. video_format.add_option('-F', '--list-formats',
  3310. action='store_true', dest='listformats', help='list all available formats (currently youtube only)')
  3311. verbosity.add_option('-q', '--quiet',
  3312. action='store_true', dest='quiet', help='activates quiet mode', default=False)
  3313. verbosity.add_option('-s', '--simulate',
  3314. action='store_true', dest='simulate', help='do not download the video and do not write anything to disk', default=False)
  3315. verbosity.add_option('--skip-download',
  3316. action='store_true', dest='skip_download', help='do not download the video', default=False)
  3317. verbosity.add_option('-g', '--get-url',
  3318. action='store_true', dest='geturl', help='simulate, quiet but print URL', default=False)
  3319. verbosity.add_option('-e', '--get-title',
  3320. action='store_true', dest='gettitle', help='simulate, quiet but print title', default=False)
  3321. verbosity.add_option('--get-thumbnail',
  3322. action='store_true', dest='getthumbnail',
  3323. help='simulate, quiet but print thumbnail URL', default=False)
  3324. verbosity.add_option('--get-description',
  3325. action='store_true', dest='getdescription',
  3326. help='simulate, quiet but print video description', default=False)
  3327. verbosity.add_option('--get-filename',
  3328. action='store_true', dest='getfilename',
  3329. help='simulate, quiet but print output filename', default=False)
  3330. verbosity.add_option('--get-format',
  3331. action='store_true', dest='getformat',
  3332. help='simulate, quiet but print output format', default=False)
  3333. verbosity.add_option('--no-progress',
  3334. action='store_true', dest='noprogress', help='do not print progress bar', default=False)
  3335. verbosity.add_option('--console-title',
  3336. action='store_true', dest='consoletitle',
  3337. help='display progress in console titlebar', default=False)
  3338. filesystem.add_option('-t', '--title',
  3339. action='store_true', dest='usetitle', help='use title in file name', default=False)
  3340. filesystem.add_option('-l', '--literal',
  3341. action='store_true', dest='useliteral', help='use literal title in file name', default=False)
  3342. filesystem.add_option('-A', '--auto-number',
  3343. action='store_true', dest='autonumber',
  3344. help='number downloaded files starting from 00000', default=False)
  3345. filesystem.add_option('-o', '--output',
  3346. dest='outtmpl', metavar='TEMPLATE', help='output filename template. Use %(stitle)s to get the title, %(uploader)s for the uploader name, %(autonumber)s to get an automatically incremented number, %(ext)s for the filename extension, and %% for a literal percent')
  3347. filesystem.add_option('-a', '--batch-file',
  3348. dest='batchfile', metavar='FILE', help='file containing URLs to download (\'-\' for stdin)')
  3349. filesystem.add_option('-w', '--no-overwrites',
  3350. action='store_true', dest='nooverwrites', help='do not overwrite files', default=False)
  3351. filesystem.add_option('-c', '--continue',
  3352. action='store_true', dest='continue_dl', help='resume partially downloaded files', default=False)
  3353. filesystem.add_option('--no-continue',
  3354. action='store_false', dest='continue_dl',
  3355. help='do not resume partially downloaded files (restart from beginning)')
  3356. filesystem.add_option('--cookies',
  3357. dest='cookiefile', metavar='FILE', help='file to read cookies from and dump cookie jar in')
  3358. filesystem.add_option('--no-part',
  3359. action='store_true', dest='nopart', help='do not use .part files', default=False)
  3360. filesystem.add_option('--no-mtime',
  3361. action='store_false', dest='updatetime',
  3362. help='do not use the Last-modified header to set the file modification time', default=True)
  3363. filesystem.add_option('--write-description',
  3364. action='store_true', dest='writedescription',
  3365. help='write video description to a .description file', default=False)
  3366. filesystem.add_option('--write-info-json',
  3367. action='store_true', dest='writeinfojson',
  3368. help='write video metadata to a .info.json file', default=False)
  3369. postproc.add_option('--extract-audio', action='store_true', dest='extractaudio', default=False,
  3370. help='convert video files to audio-only files (requires ffmpeg and ffprobe)')
  3371. postproc.add_option('--audio-format', metavar='FORMAT', dest='audioformat', default='best',
  3372. help='"best", "aac", "vorbis" or "mp3"; best by default')
  3373. postproc.add_option('--audio-quality', metavar='QUALITY', dest='audioquality', default='128K',
  3374. help='ffmpeg audio bitrate specification, 128k by default')
  3375. postproc.add_option('-k', '--keep-video', action='store_true', dest='keepvideo', default=False,
  3376. help='keeps the video file on disk after the post-processing; the video is erased by default')
  3377. parser.add_option_group(general)
  3378. parser.add_option_group(selection)
  3379. parser.add_option_group(filesystem)
  3380. parser.add_option_group(verbosity)
  3381. parser.add_option_group(video_format)
  3382. parser.add_option_group(authentication)
  3383. parser.add_option_group(postproc)
  3384. opts, args = parser.parse_args()
  3385. return parser, opts, args
  3386. def gen_extractors():
  3387. """ Return a list of an instance of every supported extractor.
  3388. The order does matter; the first extractor matched is the one handling the URL.
  3389. """
  3390. youtube_ie = YoutubeIE()
  3391. google_ie = GoogleIE()
  3392. yahoo_ie = YahooIE()
  3393. return [
  3394. YoutubePlaylistIE(youtube_ie),
  3395. YoutubeUserIE(youtube_ie),
  3396. YoutubeSearchIE(youtube_ie),
  3397. youtube_ie,
  3398. MetacafeIE(youtube_ie),
  3399. DailymotionIE(),
  3400. google_ie,
  3401. GoogleSearchIE(google_ie),
  3402. PhotobucketIE(),
  3403. yahoo_ie,
  3404. YahooSearchIE(yahoo_ie),
  3405. DepositFilesIE(),
  3406. FacebookIE(),
  3407. BlipTVIE(),
  3408. VimeoIE(),
  3409. MyVideoIE(),
  3410. ComedyCentralIE(),
  3411. EscapistIE(),
  3412. CollegeHumorIE(),
  3413. XVideosIE(),
  3414. SoundcloudIE(),
  3415. InfoQIE(),
  3416. GenericIE()
  3417. ]
  3418. def _real_main():
  3419. parser, opts, args = parseOpts()
  3420. # Open appropriate CookieJar
  3421. if opts.cookiefile is None:
  3422. jar = cookielib.CookieJar()
  3423. else:
  3424. try:
  3425. jar = cookielib.MozillaCookieJar(opts.cookiefile)
  3426. if os.path.isfile(opts.cookiefile) and os.access(opts.cookiefile, os.R_OK):
  3427. jar.load()
  3428. except (IOError, OSError), err:
  3429. sys.exit(u'ERROR: unable to open cookie file')
  3430. # Dump user agent
  3431. if opts.dump_user_agent:
  3432. print std_headers['User-Agent']
  3433. sys.exit(0)
  3434. # Batch file verification
  3435. batchurls = []
  3436. if opts.batchfile is not None:
  3437. try:
  3438. if opts.batchfile == '-':
  3439. batchfd = sys.stdin
  3440. else:
  3441. batchfd = open(opts.batchfile, 'r')
  3442. batchurls = batchfd.readlines()
  3443. batchurls = [x.strip() for x in batchurls]
  3444. batchurls = [x for x in batchurls if len(x) > 0 and not re.search(r'^[#/;]', x)]
  3445. except IOError:
  3446. sys.exit(u'ERROR: batch file could not be read')
  3447. all_urls = batchurls + args
  3448. # General configuration
  3449. cookie_processor = urllib2.HTTPCookieProcessor(jar)
  3450. opener = urllib2.build_opener(urllib2.ProxyHandler(), cookie_processor, YoutubeDLHandler())
  3451. urllib2.install_opener(opener)
  3452. socket.setdefaulttimeout(300) # 5 minutes should be enough (famous last words)
  3453. extractors = gen_extractors()
  3454. if opts.list_extractors:
  3455. for ie in extractors:
  3456. print(ie.IE_NAME)
  3457. matchedUrls = filter(lambda url: ie.suitable(url), all_urls)
  3458. all_urls = filter(lambda url: url not in matchedUrls, all_urls)
  3459. for mu in matchedUrls:
  3460. print(u' ' + mu)
  3461. sys.exit(0)
  3462. # Conflicting, missing and erroneous options
  3463. if opts.usenetrc and (opts.username is not None or opts.password is not None):
  3464. parser.error(u'using .netrc conflicts with giving username/password')
  3465. if opts.password is not None and opts.username is None:
  3466. parser.error(u'account username missing')
  3467. if opts.outtmpl is not None and (opts.useliteral or opts.usetitle or opts.autonumber):
  3468. parser.error(u'using output template conflicts with using title, literal title or auto number')
  3469. if opts.usetitle and opts.useliteral:
  3470. parser.error(u'using title conflicts with using literal title')
  3471. if opts.username is not None and opts.password is None:
  3472. opts.password = getpass.getpass(u'Type account password and press return:')
  3473. if opts.ratelimit is not None:
  3474. numeric_limit = FileDownloader.parse_bytes(opts.ratelimit)
  3475. if numeric_limit is None:
  3476. parser.error(u'invalid rate limit specified')
  3477. opts.ratelimit = numeric_limit
  3478. if opts.retries is not None:
  3479. try:
  3480. opts.retries = long(opts.retries)
  3481. except (TypeError, ValueError), err:
  3482. parser.error(u'invalid retry count specified')
  3483. try:
  3484. opts.playliststart = int(opts.playliststart)
  3485. if opts.playliststart <= 0:
  3486. raise ValueError(u'Playlist start must be positive')
  3487. except (TypeError, ValueError), err:
  3488. parser.error(u'invalid playlist start number specified')
  3489. try:
  3490. opts.playlistend = int(opts.playlistend)
  3491. if opts.playlistend != -1 and (opts.playlistend <= 0 or opts.playlistend < opts.playliststart):
  3492. raise ValueError(u'Playlist end must be greater than playlist start')
  3493. except (TypeError, ValueError), err:
  3494. parser.error(u'invalid playlist end number specified')
  3495. if opts.extractaudio:
  3496. if opts.audioformat not in ['best', 'aac', 'mp3', 'vorbis']:
  3497. parser.error(u'invalid audio format specified')
  3498. # File downloader
  3499. fd = FileDownloader({
  3500. 'usenetrc': opts.usenetrc,
  3501. 'username': opts.username,
  3502. 'password': opts.password,
  3503. 'quiet': (opts.quiet or opts.geturl or opts.gettitle or opts.getthumbnail or opts.getdescription or opts.getfilename or opts.getformat),
  3504. 'forceurl': opts.geturl,
  3505. 'forcetitle': opts.gettitle,
  3506. 'forcethumbnail': opts.getthumbnail,
  3507. 'forcedescription': opts.getdescription,
  3508. 'forcefilename': opts.getfilename,
  3509. 'forceformat': opts.getformat,
  3510. 'simulate': opts.simulate,
  3511. 'skip_download': (opts.skip_download or opts.simulate or opts.geturl or opts.gettitle or opts.getthumbnail or opts.getdescription or opts.getfilename or opts.getformat),
  3512. 'format': opts.format,
  3513. 'format_limit': opts.format_limit,
  3514. 'listformats': opts.listformats,
  3515. 'outtmpl': ((opts.outtmpl is not None and opts.outtmpl.decode(preferredencoding()))
  3516. or (opts.format == '-1' and opts.usetitle and u'%(stitle)s-%(id)s-%(format)s.%(ext)s')
  3517. or (opts.format == '-1' and opts.useliteral and u'%(title)s-%(id)s-%(format)s.%(ext)s')
  3518. or (opts.format == '-1' and u'%(id)s-%(format)s.%(ext)s')
  3519. or (opts.usetitle and opts.autonumber and u'%(autonumber)s-%(stitle)s-%(id)s.%(ext)s')
  3520. or (opts.useliteral and opts.autonumber and u'%(autonumber)s-%(title)s-%(id)s.%(ext)s')
  3521. or (opts.usetitle and u'%(stitle)s-%(id)s.%(ext)s')
  3522. or (opts.useliteral and u'%(title)s-%(id)s.%(ext)s')
  3523. or (opts.autonumber and u'%(autonumber)s-%(id)s.%(ext)s')
  3524. or u'%(id)s.%(ext)s'),
  3525. 'ignoreerrors': opts.ignoreerrors,
  3526. 'ratelimit': opts.ratelimit,
  3527. 'nooverwrites': opts.nooverwrites,
  3528. 'retries': opts.retries,
  3529. 'continuedl': opts.continue_dl,
  3530. 'noprogress': opts.noprogress,
  3531. 'playliststart': opts.playliststart,
  3532. 'playlistend': opts.playlistend,
  3533. 'logtostderr': opts.outtmpl == '-',
  3534. 'consoletitle': opts.consoletitle,
  3535. 'nopart': opts.nopart,
  3536. 'updatetime': opts.updatetime,
  3537. 'writedescription': opts.writedescription,
  3538. 'writeinfojson': opts.writeinfojson,
  3539. 'matchtitle': opts.matchtitle,
  3540. 'rejecttitle': opts.rejecttitle,
  3541. })
  3542. for extractor in extractors:
  3543. fd.add_info_extractor(extractor)
  3544. # PostProcessors
  3545. if opts.extractaudio:
  3546. fd.add_post_processor(FFmpegExtractAudioPP(preferredcodec=opts.audioformat, preferredquality=opts.audioquality, keepvideo=opts.keepvideo))
  3547. # Update version
  3548. if opts.update_self:
  3549. updateSelf(fd, sys.argv[0])
  3550. # Maybe do nothing
  3551. if len(all_urls) < 1:
  3552. if not opts.update_self:
  3553. parser.error(u'you must provide at least one URL')
  3554. else:
  3555. sys.exit()
  3556. retcode = fd.download(all_urls)
  3557. # Dump cookie jar if requested
  3558. if opts.cookiefile is not None:
  3559. try:
  3560. jar.save()
  3561. except (IOError, OSError), err:
  3562. sys.exit(u'ERROR: unable to save cookie jar')
  3563. sys.exit(retcode)
  3564. def main():
  3565. try:
  3566. _real_main()
  3567. except DownloadError:
  3568. sys.exit(1)
  3569. except SameFileError:
  3570. sys.exit(u'ERROR: fixed output name but more than one file to download')
  3571. except KeyboardInterrupt:
  3572. sys.exit(u'\nERROR: Interrupted by user')
  3573. if __name__ == '__main__':
  3574. main()
  3575. # vim: set ts=4 sw=4 sts=4 noet ai si filetype=python: