youtube-dl 36 KB

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