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