youtube-dl 35 KB

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