youtube-dl 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # Author: Ricardo Garcia Gonzalez
  4. # Author: Danny Colligan
  5. # License: Public domain code
  6. import htmlentitydefs
  7. import httplib
  8. import locale
  9. import math
  10. import netrc
  11. import os
  12. import os.path
  13. import re
  14. import socket
  15. import string
  16. import sys
  17. import time
  18. import urllib
  19. import urllib2
  20. std_headers = {
  21. 'User-Agent': 'Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.0.8) Gecko/2009032609 Firefox/3.0.8',
  22. 'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
  23. 'Accept': 'text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5',
  24. 'Accept-Language': 'en-us,en;q=0.5',
  25. }
  26. simple_title_chars = string.ascii_letters.decode('ascii') + string.digits.decode('ascii')
  27. class DownloadError(Exception):
  28. """Download Error exception.
  29. This exception may be thrown by FileDownloader objects if they are not
  30. configured to continue on errors. They will contain the appropriate
  31. error message.
  32. """
  33. pass
  34. class SameFileError(Exception):
  35. """Same File exception.
  36. This exception will be thrown by FileDownloader objects if they detect
  37. multiple files would have to be downloaded to the same file on disk.
  38. """
  39. pass
  40. class PostProcessingError(Exception):
  41. """Post Processing exception.
  42. This exception may be raised by PostProcessor's .run() method to
  43. indicate an error in the postprocessing task.
  44. """
  45. pass
  46. class UnavailableFormatError(Exception):
  47. """Unavailable Format exception.
  48. This exception will be thrown when a video is requested
  49. in a format that is not available for that video.
  50. """
  51. class FileDownloader(object):
  52. """File Downloader class.
  53. File downloader objects are the ones responsible of downloading the
  54. actual video file and writing it to disk if the user has requested
  55. it, among some other tasks. In most cases there should be one per
  56. program. As, given a video URL, the downloader doesn't know how to
  57. extract all the needed information, task that InfoExtractors do, it
  58. has to pass the URL to one of them.
  59. For this, file downloader objects have a method that allows
  60. InfoExtractors to be registered in a given order. When it is passed
  61. a URL, the file downloader handles it to the first InfoExtractor it
  62. finds that reports being able to handle it. The InfoExtractor extracts
  63. all the information about the video or videos the URL refers to, and
  64. asks the FileDownloader to process the video information, possibly
  65. downloading the video.
  66. File downloaders accept a lot of parameters. In order not to saturate
  67. the object constructor with arguments, it receives a dictionary of
  68. options instead. These options are available through the params
  69. attribute for the InfoExtractors to use. The FileDownloader also
  70. registers itself as the downloader in charge for the InfoExtractors
  71. that are added to it, so this is a "mutual registration".
  72. Available options:
  73. username: Username for authentication purposes.
  74. password: Password for authentication purposes.
  75. usenetrc: Use netrc for authentication instead.
  76. quiet: Do not print messages to stdout.
  77. forceurl: Force printing final URL.
  78. forcetitle: Force printing title.
  79. simulate: Do not download the video files.
  80. format: Video format code.
  81. outtmpl: Template for output names.
  82. ignoreerrors: Do not stop on download errors.
  83. ratelimit: Download speed limit, in bytes/sec.
  84. nooverwrites: Prevent overwriting files.
  85. """
  86. params = None
  87. _ies = []
  88. _pps = []
  89. _download_retcode = None
  90. def __init__(self, params):
  91. """Create a FileDownloader object with the given options."""
  92. self._ies = []
  93. self._pps = []
  94. self._download_retcode = 0
  95. self.params = params
  96. @staticmethod
  97. def pmkdir(filename):
  98. """Create directory components in filename. Similar to Unix "mkdir -p"."""
  99. components = filename.split(os.sep)
  100. aggregate = [os.sep.join(components[0:x]) for x in xrange(1, len(components))]
  101. aggregate = ['%s%s' % (x, os.sep) for x in aggregate] # Finish names with separator
  102. for dir in aggregate:
  103. if not os.path.exists(dir):
  104. os.mkdir(dir)
  105. @staticmethod
  106. def format_bytes(bytes):
  107. if bytes is None:
  108. return 'N/A'
  109. if bytes == 0:
  110. exponent = 0
  111. else:
  112. exponent = long(math.log(float(bytes), 1024.0))
  113. suffix = 'bkMGTPEZY'[exponent]
  114. converted = float(bytes) / float(1024**exponent)
  115. return '%.2f%s' % (converted, suffix)
  116. @staticmethod
  117. def calc_percent(byte_counter, data_len):
  118. if data_len is None:
  119. return '---.-%'
  120. return '%6s' % ('%3.1f%%' % (float(byte_counter) / float(data_len) * 100.0))
  121. @staticmethod
  122. def calc_eta(start, now, total, current):
  123. if total is None:
  124. return '--:--'
  125. dif = now - start
  126. if current == 0 or dif < 0.001: # One millisecond
  127. return '--:--'
  128. rate = float(current) / dif
  129. eta = long((float(total) - float(current)) / rate)
  130. (eta_mins, eta_secs) = divmod(eta, 60)
  131. if eta_mins > 99:
  132. return '--:--'
  133. return '%02d:%02d' % (eta_mins, eta_secs)
  134. @staticmethod
  135. def calc_speed(start, now, bytes):
  136. dif = now - start
  137. if bytes == 0 or dif < 0.001: # One millisecond
  138. return '%10s' % '---b/s'
  139. return '%10s' % ('%s/s' % FileDownloader.format_bytes(float(bytes) / dif))
  140. @staticmethod
  141. def best_block_size(elapsed_time, bytes):
  142. new_min = max(bytes / 2.0, 1.0)
  143. new_max = min(max(bytes * 2.0, 1.0), 4194304) # Do not surpass 4 MB
  144. if elapsed_time < 0.001:
  145. return int(new_max)
  146. rate = bytes / elapsed_time
  147. if rate > new_max:
  148. return int(new_max)
  149. if rate < new_min:
  150. return int(new_min)
  151. return int(rate)
  152. @staticmethod
  153. def parse_bytes(bytestr):
  154. """Parse a string indicating a byte quantity into a long integer."""
  155. matchobj = re.match(r'(?i)^(\d+(?:\.\d+)?)([kMGTPEZY]?)$', bytestr)
  156. if matchobj is None:
  157. return None
  158. number = float(matchobj.group(1))
  159. multiplier = 1024.0 ** 'bkmgtpezy'.index(matchobj.group(2).lower())
  160. return long(round(number * multiplier))
  161. def add_info_extractor(self, ie):
  162. """Add an InfoExtractor object to the end of the list."""
  163. self._ies.append(ie)
  164. ie.set_downloader(self)
  165. def add_post_processor(self, pp):
  166. """Add a PostProcessor object to the end of the chain."""
  167. self._pps.append(pp)
  168. pp.set_downloader(self)
  169. def to_stdout(self, message, skip_eol=False):
  170. """Print message to stdout if not in quiet mode."""
  171. if not self.params.get('quiet', False):
  172. print (u'%s%s' % (message, [u'\n', u''][skip_eol])).encode(locale.getpreferredencoding()),
  173. sys.stdout.flush()
  174. def to_stderr(self, message):
  175. """Print message to stderr."""
  176. print >>sys.stderr, message
  177. def fixed_template(self):
  178. """Checks if the output template is fixed."""
  179. return (re.search(ur'(?u)%\(.+?\)s', self.params['outtmpl']) is None)
  180. def trouble(self, message=None):
  181. """Determine action to take when a download problem appears.
  182. Depending on if the downloader has been configured to ignore
  183. download errors or not, this method may throw an exception or
  184. not when errors are found, after printing the message.
  185. """
  186. if message is not None:
  187. self.to_stderr(message)
  188. if not self.params.get('ignoreerrors', False):
  189. raise DownloadError(message)
  190. self._download_retcode = 1
  191. def slow_down(self, start_time, byte_counter):
  192. """Sleep if the download speed is over the rate limit."""
  193. rate_limit = self.params.get('ratelimit', None)
  194. if rate_limit is None or byte_counter == 0:
  195. return
  196. now = time.time()
  197. elapsed = now - start_time
  198. if elapsed <= 0.0:
  199. return
  200. speed = float(byte_counter) / elapsed
  201. if speed > rate_limit:
  202. time.sleep((byte_counter - rate_limit * (now - start_time)) / rate_limit)
  203. def report_destination(self, filename):
  204. """Report destination filename."""
  205. self.to_stdout(u'[download] Destination: %s' % filename)
  206. def report_progress(self, percent_str, data_len_str, speed_str, eta_str):
  207. """Report download progress."""
  208. self.to_stdout(u'\r[download] %s of %s at %s ETA %s' %
  209. (percent_str, data_len_str, speed_str, eta_str), skip_eol=True)
  210. def report_finish(self):
  211. """Report download finished."""
  212. self.to_stdout(u'')
  213. def process_info(self, info_dict):
  214. """Process a single dictionary returned by an InfoExtractor."""
  215. # Forced printings
  216. if self.params.get('forcetitle', False):
  217. print info_dict['title'].encode(locale.getpreferredencoding())
  218. if self.params.get('forceurl', False):
  219. print info_dict['url'].encode(locale.getpreferredencoding())
  220. # Do nothing else if in simulate mode
  221. if self.params.get('simulate', False):
  222. return
  223. try:
  224. template_dict = dict(info_dict)
  225. template_dict['epoch'] = unicode(long(time.time()))
  226. filename = self.params['outtmpl'] % template_dict
  227. self.report_destination(filename)
  228. except (ValueError, KeyError), err:
  229. self.trouble('ERROR: invalid output template or system charset: %s' % str(err))
  230. if self.params['nooverwrites'] and os.path.exists(filename):
  231. self.to_stderr('WARNING: file exists: %s; skipping' % filename)
  232. return
  233. try:
  234. self.pmkdir(filename)
  235. except (OSError, IOError), err:
  236. self.trouble('ERROR: unable to create directories: %s' % str(err))
  237. return
  238. try:
  239. outstream = open(filename, 'wb')
  240. except (OSError, IOError), err:
  241. self.trouble('ERROR: unable to open for writing: %s' % str(err))
  242. return
  243. try:
  244. self._do_download(outstream, info_dict['url'])
  245. outstream.close()
  246. except (OSError, IOError), err:
  247. os.remove(filename)
  248. raise UnavailableFormatError
  249. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  250. self.trouble('ERROR: unable to download video data: %s' % str(err))
  251. return
  252. try:
  253. self.post_process(filename, info_dict)
  254. except (PostProcessingError), err:
  255. self.trouble('ERROR: postprocessing: %s' % str(err))
  256. return
  257. def download(self, url_list):
  258. """Download a given list of URLs."""
  259. if len(url_list) > 1 and self.fixed_template():
  260. raise SameFileError(self.params['outtmpl'])
  261. for url in url_list:
  262. suitable_found = False
  263. for ie in self._ies:
  264. # Go to next InfoExtractor if not suitable
  265. if not ie.suitable(url):
  266. continue
  267. # Suitable InfoExtractor found
  268. suitable_found = True
  269. # Extract information from URL and process it
  270. ie.extract(url)
  271. # Suitable InfoExtractor had been found; go to next URL
  272. break
  273. if not suitable_found:
  274. self.trouble('ERROR: no suitable InfoExtractor: %s' % url)
  275. return self._download_retcode
  276. def post_process(self, filename, ie_info):
  277. """Run the postprocessing chain on the given file."""
  278. info = dict(ie_info)
  279. info['filepath'] = filename
  280. for pp in self._pps:
  281. info = pp.run(info)
  282. if info is None:
  283. break
  284. def _do_download(self, stream, url):
  285. request = urllib2.Request(url, None, std_headers)
  286. data = urllib2.urlopen(request)
  287. data_len = data.info().get('Content-length', None)
  288. data_len_str = self.format_bytes(data_len)
  289. byte_counter = 0
  290. block_size = 1024
  291. start = time.time()
  292. while True:
  293. # Progress message
  294. percent_str = self.calc_percent(byte_counter, data_len)
  295. eta_str = self.calc_eta(start, time.time(), data_len, byte_counter)
  296. speed_str = self.calc_speed(start, time.time(), byte_counter)
  297. self.report_progress(percent_str, data_len_str, speed_str, eta_str)
  298. # Download and write
  299. before = time.time()
  300. data_block = data.read(block_size)
  301. after = time.time()
  302. data_block_len = len(data_block)
  303. if data_block_len == 0:
  304. break
  305. byte_counter += data_block_len
  306. stream.write(data_block)
  307. block_size = self.best_block_size(after - before, data_block_len)
  308. # Apply rate limit
  309. self.slow_down(start, byte_counter)
  310. self.report_finish()
  311. if data_len is not None and str(byte_counter) != data_len:
  312. raise ValueError('Content too short: %s/%s bytes' % (byte_counter, data_len))
  313. class InfoExtractor(object):
  314. """Information Extractor class.
  315. Information extractors are the classes that, given a URL, extract
  316. information from the video (or videos) the URL refers to. This
  317. information includes the real video URL, the video title and simplified
  318. title, author and others. The information is stored in a dictionary
  319. which is then passed to the FileDownloader. The FileDownloader
  320. processes this information possibly downloading the video to the file
  321. system, among other possible outcomes. The dictionaries must include
  322. the following fields:
  323. id: Video identifier.
  324. url: Final video URL.
  325. uploader: Nickname of the video uploader.
  326. title: Literal title.
  327. stitle: Simplified title.
  328. ext: Video filename extension.
  329. Subclasses of this one should re-define the _real_initialize() and
  330. _real_extract() methods, as well as the suitable() static method.
  331. Probably, they should also be instantiated and added to the main
  332. downloader.
  333. """
  334. _ready = False
  335. _downloader = None
  336. def __init__(self, downloader=None):
  337. """Constructor. Receives an optional downloader."""
  338. self._ready = False
  339. self.set_downloader(downloader)
  340. @staticmethod
  341. def suitable(url):
  342. """Receives a URL and returns True if suitable for this IE."""
  343. return False
  344. def initialize(self):
  345. """Initializes an instance (authentication, etc)."""
  346. if not self._ready:
  347. self._real_initialize()
  348. self._ready = True
  349. def extract(self, url):
  350. """Extracts URL information and returns it in list of dicts."""
  351. self.initialize()
  352. return self._real_extract(url)
  353. def set_downloader(self, downloader):
  354. """Sets the downloader for this IE."""
  355. self._downloader = downloader
  356. def _real_initialize(self):
  357. """Real initialization process. Redefine in subclasses."""
  358. pass
  359. def _real_extract(self, url):
  360. """Real extraction process. Redefine in subclasses."""
  361. pass
  362. class YoutubeIE(InfoExtractor):
  363. """Information extractor for youtube.com."""
  364. _VALID_URL = r'^((?:http://)?(?:\w+\.)?youtube\.com/(?:(?:v/)|(?:(?:watch(?:\.php)?)?\?(?:.+&)?v=)))?([0-9A-Za-z_-]+)(?(1).+)?$'
  365. _LANG_URL = r'http://uk.youtube.com/?hl=en&persist_hl=1&gl=US&persist_gl=1&opt_out_ackd=1'
  366. _LOGIN_URL = 'http://www.youtube.com/signup?next=/&gl=US&hl=en'
  367. _AGE_URL = 'http://www.youtube.com/verify_age?next_url=/&gl=US&hl=en'
  368. _NETRC_MACHINE = 'youtube'
  369. _available_formats = ['22', '35', '18', '17', '13'] # listed in order of priority for -b flag
  370. _video_extensions = {
  371. '13': '3gp',
  372. '17': 'mp4',
  373. '18': 'mp4',
  374. '22': 'mp4',
  375. }
  376. @staticmethod
  377. def suitable(url):
  378. return (re.match(YoutubeIE._VALID_URL, url) is not None)
  379. @staticmethod
  380. def htmlentity_transform(matchobj):
  381. """Transforms an HTML entity to a Unicode character."""
  382. entity = matchobj.group(1)
  383. # Known non-numeric HTML entity
  384. if entity in htmlentitydefs.name2codepoint:
  385. return unichr(htmlentitydefs.name2codepoint[entity])
  386. # Unicode character
  387. mobj = re.match(ur'(?u)#(x?\d+)', entity)
  388. if mobj is not None:
  389. numstr = mobj.group(1)
  390. if numstr.startswith(u'x'):
  391. base = 16
  392. numstr = u'0%s' % numstr
  393. else:
  394. base = 10
  395. return unichr(long(numstr, base))
  396. # Unknown entity in name, return its literal representation
  397. return (u'&%s;' % entity)
  398. def report_lang(self):
  399. """Report attempt to set language."""
  400. self._downloader.to_stdout(u'[youtube] Setting language')
  401. def report_login(self):
  402. """Report attempt to log in."""
  403. self._downloader.to_stdout(u'[youtube] Logging in')
  404. def report_age_confirmation(self):
  405. """Report attempt to confirm age."""
  406. self._downloader.to_stdout(u'[youtube] Confirming age')
  407. def report_webpage_download(self, video_id):
  408. """Report attempt to download webpage."""
  409. self._downloader.to_stdout(u'[youtube] %s: Downloading video webpage' % video_id)
  410. def report_information_extraction(self, video_id):
  411. """Report attempt to extract video information."""
  412. self._downloader.to_stdout(u'[youtube] %s: Extracting video information' % video_id)
  413. def report_video_url(self, video_id, video_real_url):
  414. """Report extracted video URL."""
  415. self._downloader.to_stdout(u'[youtube] %s: URL: %s' % (video_id, video_real_url))
  416. def report_unavailable_format(self, video_id, format):
  417. """Report extracted video URL."""
  418. self._downloader.to_stdout(u'[youtube] %s: Format %s not available' % (video_id, format))
  419. def _real_initialize(self):
  420. if self._downloader is None:
  421. return
  422. username = None
  423. password = None
  424. downloader_params = self._downloader.params
  425. # Attempt to use provided username and password or .netrc data
  426. if downloader_params.get('username', None) is not None:
  427. username = downloader_params['username']
  428. password = downloader_params['password']
  429. elif downloader_params.get('usenetrc', False):
  430. try:
  431. info = netrc.netrc().authenticators(self._NETRC_MACHINE)
  432. if info is not None:
  433. username = info[0]
  434. password = info[2]
  435. else:
  436. raise netrc.NetrcParseError('No authenticators for %s' % self._NETRC_MACHINE)
  437. except (IOError, netrc.NetrcParseError), err:
  438. self._downloader.to_stderr(u'WARNING: parsing .netrc: %s' % str(err))
  439. return
  440. # Set language
  441. request = urllib2.Request(self._LANG_URL, None, std_headers)
  442. try:
  443. self.report_lang()
  444. urllib2.urlopen(request).read()
  445. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  446. self._downloader.to_stderr(u'WARNING: unable to set language: %s' % str(err))
  447. return
  448. # No authentication to be performed
  449. if username is None:
  450. return
  451. # Log in
  452. login_form = {
  453. 'current_form': 'loginForm',
  454. 'next': '/',
  455. 'action_login': 'Log In',
  456. 'username': username,
  457. 'password': password,
  458. }
  459. request = urllib2.Request(self._LOGIN_URL, urllib.urlencode(login_form), std_headers)
  460. try:
  461. self.report_login()
  462. login_results = urllib2.urlopen(request).read()
  463. if re.search(r'(?i)<form[^>]* name="loginForm"', login_results) is not None:
  464. self._downloader.to_stderr(u'WARNING: unable to log in: bad username or password')
  465. return
  466. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  467. self._downloader.to_stderr(u'WARNING: unable to log in: %s' % str(err))
  468. return
  469. # Confirm age
  470. age_form = {
  471. 'next_url': '/',
  472. 'action_confirm': 'Confirm',
  473. }
  474. request = urllib2.Request(self._AGE_URL, urllib.urlencode(age_form), std_headers)
  475. try:
  476. self.report_age_confirmation()
  477. age_results = urllib2.urlopen(request).read()
  478. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  479. self._downloader.trouble(u'ERROR: unable to confirm age: %s' % str(err))
  480. return
  481. def _real_extract(self, url):
  482. # Extract video id from URL
  483. mobj = re.match(self._VALID_URL, url)
  484. if mobj is None:
  485. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  486. return
  487. video_id = mobj.group(2)
  488. # Downloader parameters
  489. best_quality = False
  490. format_param = None
  491. quality_index = 0
  492. if self._downloader is not None:
  493. params = self._downloader.params
  494. format_param = params.get('format', None)
  495. if format_param == '0':
  496. format_param = self._available_formats[quality_index]
  497. best_quality = True
  498. while True:
  499. try:
  500. # Extension
  501. video_extension = self._video_extensions.get(format_param, 'flv')
  502. # Normalize URL, including format
  503. normalized_url = 'http://www.youtube.com/watch?v=%s&gl=US&hl=en' % video_id
  504. if format_param is not None:
  505. normalized_url = '%s&fmt=%s' % (normalized_url, format_param)
  506. request = urllib2.Request(normalized_url, None, std_headers)
  507. try:
  508. self.report_webpage_download(video_id)
  509. video_webpage = urllib2.urlopen(request).read()
  510. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  511. self._downloader.trouble(u'ERROR: unable to download video webpage: %s' % str(err))
  512. return
  513. self.report_information_extraction(video_id)
  514. # "t" param
  515. mobj = re.search(r', "t": "([^"]+)"', video_webpage)
  516. if mobj is None:
  517. self._downloader.trouble(u'ERROR: unable to extract "t" parameter')
  518. return
  519. video_real_url = 'http://www.youtube.com/get_video?video_id=%s&t=%s&el=detailpage&ps=' % (video_id, mobj.group(1))
  520. if format_param is not None:
  521. video_real_url = '%s&fmt=%s' % (video_real_url, format_param)
  522. self.report_video_url(video_id, video_real_url)
  523. # uploader
  524. mobj = re.search(r"var watchUsername = '([^']+)';", video_webpage)
  525. if mobj is None:
  526. self._downloader.trouble(u'ERROR: unable to extract uploader nickname')
  527. return
  528. video_uploader = mobj.group(1)
  529. # title
  530. mobj = re.search(r'(?im)<title>YouTube - ([^<]*)</title>', video_webpage)
  531. if mobj is None:
  532. self._downloader.trouble(u'ERROR: unable to extract video title')
  533. return
  534. video_title = mobj.group(1).decode('utf-8')
  535. video_title = re.sub(ur'(?u)&(.+?);', self.htmlentity_transform, video_title)
  536. video_title = video_title.replace(os.sep, u'%')
  537. # simplified title
  538. simple_title = re.sub(ur'(?u)([^%s]+)' % simple_title_chars, ur'_', video_title)
  539. simple_title = simple_title.strip(ur'_')
  540. # Process video information
  541. self._downloader.process_info({
  542. 'id': video_id.decode('utf-8'),
  543. 'url': video_real_url.decode('utf-8'),
  544. 'uploader': video_uploader.decode('utf-8'),
  545. 'title': video_title,
  546. 'stitle': simple_title,
  547. 'ext': video_extension.decode('utf-8'),
  548. })
  549. return
  550. except UnavailableFormatError, err:
  551. if best_quality:
  552. if quality_index == len(self._available_formats) - 1:
  553. # I don't ever expect this to happen
  554. self._downloader.trouble(u'ERROR: no known formats available for video')
  555. return
  556. else:
  557. self.report_unavailable_format(video_id, format_param)
  558. quality_index += 1
  559. format_param = self._available_formats[quality_index]
  560. continue
  561. else:
  562. self._downloader.trouble('ERROR: format not available for video')
  563. return
  564. class MetacafeIE(InfoExtractor):
  565. """Information Extractor for metacafe.com."""
  566. _VALID_URL = r'(?:http://)?(?:www\.)?metacafe\.com/watch/([^/]+)/([^/]+)/.*'
  567. _DISCLAIMER = 'http://www.metacafe.com/family_filter/'
  568. _FILTER_POST = 'http://www.metacafe.com/f/index.php?inputType=filter&controllerGroup=user'
  569. _youtube_ie = None
  570. def __init__(self, youtube_ie, downloader=None):
  571. InfoExtractor.__init__(self, downloader)
  572. self._youtube_ie = youtube_ie
  573. @staticmethod
  574. def suitable(url):
  575. return (re.match(MetacafeIE._VALID_URL, url) is not None)
  576. def report_disclaimer(self):
  577. """Report disclaimer retrieval."""
  578. self._downloader.to_stdout(u'[metacafe] Retrieving disclaimer')
  579. def report_age_confirmation(self):
  580. """Report attempt to confirm age."""
  581. self._downloader.to_stdout(u'[metacafe] Confirming age')
  582. def report_download_webpage(self, video_id):
  583. """Report webpage download."""
  584. self._downloader.to_stdout(u'[metacafe] %s: Downloading webpage' % video_id)
  585. def report_extraction(self, video_id):
  586. """Report information extraction."""
  587. self._downloader.to_stdout(u'[metacafe] %s: Extracting information' % video_id)
  588. def _real_initialize(self):
  589. # Retrieve disclaimer
  590. request = urllib2.Request(self._DISCLAIMER, None, std_headers)
  591. try:
  592. self.report_disclaimer()
  593. disclaimer = urllib2.urlopen(request).read()
  594. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  595. self._downloader.trouble(u'ERROR: unable to retrieve disclaimer: %s' % str(err))
  596. return
  597. # Confirm age
  598. disclaimer_form = {
  599. 'filters': '0',
  600. 'submit': "Continue - I'm over 18",
  601. }
  602. request = urllib2.Request(self._FILTER_POST, urllib.urlencode(disclaimer_form), std_headers)
  603. try:
  604. self.report_age_confirmation()
  605. disclaimer = urllib2.urlopen(request).read()
  606. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  607. self._downloader.trouble(u'ERROR: unable to confirm age: %s' % str(err))
  608. return
  609. def _real_extract(self, url):
  610. # Extract id and simplified title from URL
  611. mobj = re.match(self._VALID_URL, url)
  612. if mobj is None:
  613. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  614. return
  615. video_id = mobj.group(1)
  616. # Check if video comes from YouTube
  617. mobj2 = re.match(r'^yt-(.*)$', video_id)
  618. if mobj2 is not None:
  619. self._youtube_ie.extract('http://www.youtube.com/watch?v=%s' % mobj2.group(1))
  620. return
  621. simple_title = mobj.group(2).decode('utf-8')
  622. video_extension = 'flv'
  623. # Retrieve video webpage to extract further information
  624. request = urllib2.Request('http://www.metacafe.com/watch/%s/' % video_id)
  625. try:
  626. self.report_download_webpage(video_id)
  627. webpage = urllib2.urlopen(request).read()
  628. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  629. self._downloader.trouble(u'ERROR: unable retrieve video webpage: %s' % str(err))
  630. return
  631. # Extract URL, uploader and title from webpage
  632. self.report_extraction(video_id)
  633. mobj = re.search(r'(?m)&mediaURL=(http.*?\.flv)', webpage)
  634. if mobj is None:
  635. self._downloader.trouble(u'ERROR: unable to extract media URL')
  636. return
  637. mediaURL = urllib.unquote(mobj.group(1))
  638. mobj = re.search(r'(?m)&gdaKey=(.*?)&', webpage)
  639. if mobj is None:
  640. self._downloader.trouble(u'ERROR: unable to extract gdaKey')
  641. return
  642. gdaKey = mobj.group(1)
  643. video_url = '%s?__gda__=%s' % (mediaURL, gdaKey)
  644. mobj = re.search(r'(?im)<title>(.*) - Video</title>', webpage)
  645. if mobj is None:
  646. self._downloader.trouble(u'ERROR: unable to extract title')
  647. return
  648. video_title = mobj.group(1).decode('utf-8')
  649. mobj = re.search(r'(?ms)<li id="ChnlUsr">.*?Submitter:.*?<a .*?>(.*?)<', webpage)
  650. if mobj is None:
  651. self._downloader.trouble(u'ERROR: unable to extract uploader nickname')
  652. return
  653. video_uploader = mobj.group(1)
  654. try:
  655. # Process video information
  656. self._downloader.process_info({
  657. 'id': video_id.decode('utf-8'),
  658. 'url': video_url.decode('utf-8'),
  659. 'uploader': video_uploader.decode('utf-8'),
  660. 'title': video_title,
  661. 'stitle': simple_title,
  662. 'ext': video_extension.decode('utf-8'),
  663. })
  664. except UnavailableFormatError:
  665. self._downloader.trouble(u'ERROR: format not available for video')
  666. class YoutubeSearchIE(InfoExtractor):
  667. """Information Extractor for YouTube search queries."""
  668. _VALID_QUERY = r'ytsearch(\d+|all)?:[\s\S]+'
  669. _TEMPLATE_URL = 'http://www.youtube.com/results?search_query=%s&page=%s&gl=US&hl=en'
  670. _VIDEO_INDICATOR = r'href="/watch\?v=.+?"'
  671. _MORE_PAGES_INDICATOR = r'>Next</a>'
  672. _youtube_ie = None
  673. _max_youtube_results = 1000
  674. def __init__(self, youtube_ie, downloader=None):
  675. InfoExtractor.__init__(self, downloader)
  676. self._youtube_ie = youtube_ie
  677. @staticmethod
  678. def suitable(url):
  679. return (re.match(YoutubeSearchIE._VALID_QUERY, url) is not None)
  680. def report_download_page(self, query, pagenum):
  681. """Report attempt to download playlist page with given number."""
  682. self._downloader.to_stdout(u'[youtube] query "%s": Downloading page %s' % (query, pagenum))
  683. def _real_initialize(self):
  684. self._youtube_ie.initialize()
  685. def _real_extract(self, query):
  686. mobj = re.match(self._VALID_QUERY, query)
  687. if mobj is None:
  688. self._downloader.trouble(u'ERROR: invalid search query "%s"' % query)
  689. return
  690. prefix, query = query.split(':')
  691. prefix = prefix[8:]
  692. if prefix == '':
  693. self._download_n_results(query, 1)
  694. return
  695. elif prefix == 'all':
  696. self._download_n_results(query, self._max_youtube_results)
  697. return
  698. else:
  699. try:
  700. n = int(prefix)
  701. if n <= 0:
  702. self._downloader.trouble(u'ERROR: invalid download number %s for query "%s"' % (n, query))
  703. return
  704. elif n > self._max_youtube_results:
  705. self._downloader.to_stderr(u'WARNING: ytsearch returns max %i results (you requested %i)' % (self._max_youtube_results, n))
  706. n = self._max_youtube_results
  707. self._download_n_results(query, n)
  708. return
  709. except ValueError: # parsing prefix as int fails
  710. self._download_n_results(query, 1)
  711. return
  712. def _download_n_results(self, query, n):
  713. """Downloads a specified number of results for a query"""
  714. video_ids = []
  715. already_seen = set()
  716. pagenum = 1
  717. while True:
  718. self.report_download_page(query, pagenum)
  719. result_url = self._TEMPLATE_URL % (urllib.quote_plus(query), pagenum)
  720. request = urllib2.Request(result_url, None, std_headers)
  721. try:
  722. page = urllib2.urlopen(request).read()
  723. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  724. self._downloader.trouble(u'ERROR: unable to download webpage: %s' % str(err))
  725. return
  726. # Extract video identifiers
  727. for mobj in re.finditer(self._VIDEO_INDICATOR, page):
  728. video_id = page[mobj.span()[0]:mobj.span()[1]].split('=')[2][:-1]
  729. if video_id not in already_seen:
  730. video_ids.append(video_id)
  731. already_seen.add(video_id)
  732. if len(video_ids) == n:
  733. # Specified n videos reached
  734. for id in video_ids:
  735. self._youtube_ie.extract('http://www.youtube.com/watch?v=%s' % id)
  736. return
  737. if self._MORE_PAGES_INDICATOR not in page:
  738. for id in video_ids:
  739. self._youtube_ie.extract('http://www.youtube.com/watch?v=%s' % id)
  740. return
  741. pagenum = pagenum + 1
  742. class YoutubePlaylistIE(InfoExtractor):
  743. """Information Extractor for YouTube playlists."""
  744. _VALID_URL = r'(?:http://)?(?:\w+\.)?youtube.com/view_play_list\?p=(.+)'
  745. _TEMPLATE_URL = 'http://www.youtube.com/view_play_list?p=%s&page=%s&gl=US&hl=en'
  746. _VIDEO_INDICATOR = r'/watch\?v=(.+?)&'
  747. _MORE_PAGES_INDICATOR = r'/view_play_list?p=%s&amp;page=%s'
  748. _youtube_ie = None
  749. def __init__(self, youtube_ie, downloader=None):
  750. InfoExtractor.__init__(self, downloader)
  751. self._youtube_ie = youtube_ie
  752. @staticmethod
  753. def suitable(url):
  754. return (re.match(YoutubePlaylistIE._VALID_URL, url) is not None)
  755. def report_download_page(self, playlist_id, pagenum):
  756. """Report attempt to download playlist page with given number."""
  757. self._downloader.to_stdout(u'[youtube] PL %s: Downloading page #%s' % (playlist_id, pagenum))
  758. def _real_initialize(self):
  759. self._youtube_ie.initialize()
  760. def _real_extract(self, url):
  761. # Extract playlist id
  762. mobj = re.match(self._VALID_URL, url)
  763. if mobj is None:
  764. self._downloader.trouble(u'ERROR: invalid url: %s' % url)
  765. return
  766. # Download playlist pages
  767. playlist_id = mobj.group(1)
  768. video_ids = []
  769. pagenum = 1
  770. while True:
  771. self.report_download_page(playlist_id, pagenum)
  772. request = urllib2.Request(self._TEMPLATE_URL % (playlist_id, pagenum), None, std_headers)
  773. try:
  774. page = urllib2.urlopen(request).read()
  775. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  776. self._downloader.trouble(u'ERROR: unable to download webpage: %s' % str(err))
  777. return
  778. # Extract video identifiers
  779. ids_in_page = []
  780. for mobj in re.finditer(self._VIDEO_INDICATOR, page):
  781. if mobj.group(1) not in ids_in_page:
  782. ids_in_page.append(mobj.group(1))
  783. video_ids.extend(ids_in_page)
  784. if (self._MORE_PAGES_INDICATOR % (playlist_id, pagenum + 1)) not in page:
  785. break
  786. pagenum = pagenum + 1
  787. for id in video_ids:
  788. self._youtube_ie.extract('http://www.youtube.com/watch?v=%s' % id)
  789. return
  790. class PostProcessor(object):
  791. """Post Processor class.
  792. PostProcessor objects can be added to downloaders with their
  793. add_post_processor() method. When the downloader has finished a
  794. successful download, it will take its internal chain of PostProcessors
  795. and start calling the run() method on each one of them, first with
  796. an initial argument and then with the returned value of the previous
  797. PostProcessor.
  798. The chain will be stopped if one of them ever returns None or the end
  799. of the chain is reached.
  800. PostProcessor objects follow a "mutual registration" process similar
  801. to InfoExtractor objects.
  802. """
  803. _downloader = None
  804. def __init__(self, downloader=None):
  805. self._downloader = downloader
  806. def set_downloader(self, downloader):
  807. """Sets the downloader for this PP."""
  808. self._downloader = downloader
  809. def run(self, information):
  810. """Run the PostProcessor.
  811. The "information" argument is a dictionary like the ones
  812. composed by InfoExtractors. The only difference is that this
  813. one has an extra field called "filepath" that points to the
  814. downloaded file.
  815. When this method returns None, the postprocessing chain is
  816. stopped. However, this method may return an information
  817. dictionary that will be passed to the next postprocessing
  818. object in the chain. It can be the one it received after
  819. changing some fields.
  820. In addition, this method may raise a PostProcessingError
  821. exception that will be taken into account by the downloader
  822. it was called from.
  823. """
  824. return information # by default, do nothing
  825. ### MAIN PROGRAM ###
  826. if __name__ == '__main__':
  827. try:
  828. # Modules needed only when running the main program
  829. import getpass
  830. import optparse
  831. # General configuration
  832. urllib2.install_opener(urllib2.build_opener(urllib2.ProxyHandler()))
  833. urllib2.install_opener(urllib2.build_opener(urllib2.HTTPCookieProcessor()))
  834. socket.setdefaulttimeout(300) # 5 minutes should be enough (famous last words)
  835. # Parse command line
  836. parser = optparse.OptionParser(
  837. usage='Usage: %prog [options] url...',
  838. version='2009.05.11',
  839. conflict_handler='resolve',
  840. )
  841. parser.add_option('-h', '--help',
  842. action='help', help='print this help text and exit')
  843. parser.add_option('-v', '--version',
  844. action='version', help='print program version and exit')
  845. parser.add_option('-i', '--ignore-errors',
  846. action='store_true', dest='ignoreerrors', help='continue on download errors', default=False)
  847. parser.add_option('-r', '--rate-limit',
  848. dest='ratelimit', metavar='L', help='download rate limit (e.g. 50k or 44.6m)')
  849. authentication = optparse.OptionGroup(parser, 'Authentication Options')
  850. authentication.add_option('-u', '--username',
  851. dest='username', metavar='UN', help='account username')
  852. authentication.add_option('-p', '--password',
  853. dest='password', metavar='PW', help='account password')
  854. authentication.add_option('-n', '--netrc',
  855. action='store_true', dest='usenetrc', help='use .netrc authentication data', default=False)
  856. parser.add_option_group(authentication)
  857. video_format = optparse.OptionGroup(parser, 'Video Format Options')
  858. video_format.add_option('-f', '--format',
  859. action='append', dest='format', metavar='FMT', help='video format code')
  860. video_format.add_option('-b', '--best-quality',
  861. action='append_const', dest='format', help='download the best quality video possible', const='0')
  862. video_format.add_option('-m', '--mobile-version',
  863. action='append_const', dest='format', help='alias for -f 17', const='17')
  864. video_format.add_option('-d', '--high-def',
  865. action='append_const', dest='format', help='alias for -f 22', const='22')
  866. parser.add_option_group(video_format)
  867. verbosity = optparse.OptionGroup(parser, 'Verbosity / Simulation Options')
  868. verbosity.add_option('-q', '--quiet',
  869. action='store_true', dest='quiet', help='activates quiet mode', default=False)
  870. verbosity.add_option('-s', '--simulate',
  871. action='store_true', dest='simulate', help='do not download video', default=False)
  872. verbosity.add_option('-g', '--get-url',
  873. action='store_true', dest='geturl', help='simulate, quiet but print URL', default=False)
  874. verbosity.add_option('-e', '--get-title',
  875. action='store_true', dest='gettitle', help='simulate, quiet but print title', default=False)
  876. parser.add_option_group(verbosity)
  877. filesystem = optparse.OptionGroup(parser, 'Filesystem Options')
  878. filesystem.add_option('-t', '--title',
  879. action='store_true', dest='usetitle', help='use title in file name', default=False)
  880. filesystem.add_option('-l', '--literal',
  881. action='store_true', dest='useliteral', help='use literal title in file name', default=False)
  882. filesystem.add_option('-o', '--output',
  883. dest='outtmpl', metavar='TPL', help='output filename template')
  884. filesystem.add_option('-a', '--batch-file',
  885. dest='batchfile', metavar='F', help='file containing URLs to download')
  886. filesystem.add_option('-w', '--no-overwrites',
  887. action='store_true', dest='nooverwrites', help='do not overwrite files', default=False)
  888. parser.add_option_group(filesystem)
  889. (opts, args) = parser.parse_args()
  890. # Batch file verification
  891. batchurls = []
  892. if opts.batchfile is not None:
  893. try:
  894. batchurls = open(opts.batchfile, 'r').readlines()
  895. batchurls = [x.strip() for x in batchurls]
  896. batchurls = [x for x in batchurls if len(x) > 0]
  897. except IOError:
  898. sys.exit(u'ERROR: batch file could not be read')
  899. all_urls = batchurls + args
  900. # Conflicting, missing and erroneous options
  901. if len(all_urls) < 1:
  902. parser.error(u'you must provide at least one URL')
  903. if opts.usenetrc and (opts.username is not None or opts.password is not None):
  904. parser.error(u'using .netrc conflicts with giving username/password')
  905. if opts.password is not None and opts.username is None:
  906. parser.error(u'account username missing')
  907. if opts.outtmpl is not None and (opts.useliteral or opts.usetitle):
  908. parser.error(u'using output template conflicts with using title or literal title')
  909. if opts.usetitle and opts.useliteral:
  910. parser.error(u'using title conflicts with using literal title')
  911. if opts.username is not None and opts.password is None:
  912. opts.password = getpass.getpass(u'Type account password and press return:')
  913. if opts.ratelimit is not None:
  914. numeric_limit = FileDownloader.parse_bytes(opts.ratelimit)
  915. if numeric_limit is None:
  916. parser.error(u'invalid rate limit specified')
  917. opts.ratelimit = numeric_limit
  918. if opts.format is not None and len(opts.format) > 1:
  919. parser.error(u'pass at most one of the video format option flags (-f, -b, -m, -d)')
  920. if opts.format is None:
  921. real_format = None
  922. else:
  923. real_format = opts.format[0]
  924. # Information extractors
  925. youtube_ie = YoutubeIE()
  926. metacafe_ie = MetacafeIE(youtube_ie)
  927. youtube_pl_ie = YoutubePlaylistIE(youtube_ie)
  928. youtube_search_ie = YoutubeSearchIE(youtube_ie)
  929. # File downloader
  930. fd = FileDownloader({
  931. 'usenetrc': opts.usenetrc,
  932. 'username': opts.username,
  933. 'password': opts.password,
  934. 'quiet': (opts.quiet or opts.geturl or opts.gettitle),
  935. 'forceurl': opts.geturl,
  936. 'forcetitle': opts.gettitle,
  937. 'simulate': (opts.simulate or opts.geturl or opts.gettitle),
  938. 'format': real_format,
  939. 'outtmpl': ((opts.outtmpl is not None and opts.outtmpl.decode(locale.getpreferredencoding()))
  940. or (opts.usetitle and u'%(stitle)s-%(id)s.%(ext)s')
  941. or (opts.useliteral and u'%(title)s-%(id)s.%(ext)s')
  942. or u'%(id)s.%(ext)s'),
  943. 'ignoreerrors': opts.ignoreerrors,
  944. 'ratelimit': opts.ratelimit,
  945. 'nooverwrites': opts.nooverwrites,
  946. })
  947. fd.add_info_extractor(youtube_search_ie)
  948. fd.add_info_extractor(youtube_pl_ie)
  949. fd.add_info_extractor(metacafe_ie)
  950. fd.add_info_extractor(youtube_ie)
  951. retcode = fd.download(all_urls)
  952. sys.exit(retcode)
  953. except DownloadError:
  954. sys.exit(1)
  955. except SameFileError:
  956. sys.exit(u'ERROR: fixed output name but more than one file to download')
  957. except KeyboardInterrupt:
  958. sys.exit(u'\nERROR: Interrupted by user')