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.

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