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.

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