youtube-dl 38 KB

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