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.

4639 lines
156 KiB

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