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.

4320 lines
145 KiB

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