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.

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