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.

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