youtube-dl 72 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # Author: Ricardo Garcia Gonzalez
  4. # Author: Danny Colligan
  5. # Author: Benjamin Johnson
  6. # License: Public domain code
  7. import htmlentitydefs
  8. import httplib
  9. import locale
  10. import math
  11. import netrc
  12. import os
  13. import os.path
  14. import re
  15. import socket
  16. import string
  17. import subprocess
  18. import sys
  19. import time
  20. import urllib
  21. import urllib2
  22. # parse_qs was moved from the cgi module to the urlparse module recently.
  23. try:
  24. from urlparse import parse_qs
  25. except ImportError:
  26. from cgi import parse_qs
  27. std_headers = {
  28. 'User-Agent': 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2) Gecko/20100115 Firefox/3.6',
  29. 'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
  30. 'Accept': 'text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5',
  31. 'Accept-Language': 'en-us,en;q=0.5',
  32. }
  33. simple_title_chars = string.ascii_letters.decode('ascii') + string.digits.decode('ascii')
  34. def preferredencoding():
  35. """Get preferred encoding.
  36. Returns the best encoding scheme for the system, based on
  37. locale.getpreferredencoding() and some further tweaks.
  38. """
  39. def yield_preferredencoding():
  40. try:
  41. pref = locale.getpreferredencoding()
  42. u'TEST'.encode(pref)
  43. except:
  44. pref = 'UTF-8'
  45. while True:
  46. yield pref
  47. return yield_preferredencoding().next()
  48. def htmlentity_transform(matchobj):
  49. """Transforms an HTML entity to a Unicode character.
  50. This function receives a match object and is intended to be used with
  51. the re.sub() function.
  52. """
  53. entity = matchobj.group(1)
  54. # Known non-numeric HTML entity
  55. if entity in htmlentitydefs.name2codepoint:
  56. return unichr(htmlentitydefs.name2codepoint[entity])
  57. # Unicode character
  58. mobj = re.match(ur'(?u)#(x?\d+)', entity)
  59. if mobj is not None:
  60. numstr = mobj.group(1)
  61. if numstr.startswith(u'x'):
  62. base = 16
  63. numstr = u'0%s' % numstr
  64. else:
  65. base = 10
  66. return unichr(long(numstr, base))
  67. # Unknown entity in name, return its literal representation
  68. return (u'&%s;' % entity)
  69. def sanitize_title(utitle):
  70. """Sanitizes a video title so it could be used as part of a filename."""
  71. utitle = re.sub(ur'(?u)&(.+?);', htmlentity_transform, utitle)
  72. return utitle.replace(unicode(os.sep), u'%')
  73. def sanitize_open(filename, open_mode):
  74. """Try to open the given filename, and slightly tweak it if this fails.
  75. Attempts to open the given filename. If this fails, it tries to change
  76. the filename slightly, step by step, until it's either able to open it
  77. or it fails and raises a final exception, like the standard open()
  78. function.
  79. It returns the tuple (stream, definitive_file_name).
  80. """
  81. try:
  82. if filename == u'-':
  83. return (sys.stdout, filename)
  84. stream = open(filename, open_mode)
  85. return (stream, filename)
  86. except (IOError, OSError), err:
  87. # In case of error, try to remove win32 forbidden chars
  88. filename = re.sub(ur'[<>:"\|\?\*]', u'#', filename)
  89. # An exception here should be caught in the caller
  90. stream = open(filename, open_mode)
  91. return (stream, filename)
  92. class DownloadError(Exception):
  93. """Download Error exception.
  94. This exception may be thrown by FileDownloader objects if they are not
  95. configured to continue on errors. They will contain the appropriate
  96. error message.
  97. """
  98. pass
  99. class SameFileError(Exception):
  100. """Same File exception.
  101. This exception will be thrown by FileDownloader objects if they detect
  102. multiple files would have to be downloaded to the same file on disk.
  103. """
  104. pass
  105. class PostProcessingError(Exception):
  106. """Post Processing exception.
  107. This exception may be raised by PostProcessor's .run() method to
  108. indicate an error in the postprocessing task.
  109. """
  110. pass
  111. class UnavailableFormatError(Exception):
  112. """Unavailable Format exception.
  113. This exception will be thrown when a video is requested
  114. in a format that is not available for that video.
  115. """
  116. pass
  117. class ContentTooShortError(Exception):
  118. """Content Too Short exception.
  119. This exception may be raised by FileDownloader objects when a file they
  120. download is too small for what the server announced first, indicating
  121. the connection was probably interrupted.
  122. """
  123. # Both in bytes
  124. downloaded = None
  125. expected = None
  126. def __init__(self, downloaded, expected):
  127. self.downloaded = downloaded
  128. self.expected = expected
  129. class FileDownloader(object):
  130. """File Downloader class.
  131. File downloader objects are the ones responsible of downloading the
  132. actual video file and writing it to disk if the user has requested
  133. it, among some other tasks. In most cases there should be one per
  134. program. As, given a video URL, the downloader doesn't know how to
  135. extract all the needed information, task that InfoExtractors do, it
  136. has to pass the URL to one of them.
  137. For this, file downloader objects have a method that allows
  138. InfoExtractors to be registered in a given order. When it is passed
  139. a URL, the file downloader handles it to the first InfoExtractor it
  140. finds that reports being able to handle it. The InfoExtractor extracts
  141. all the information about the video or videos the URL refers to, and
  142. asks the FileDownloader to process the video information, possibly
  143. downloading the video.
  144. File downloaders accept a lot of parameters. In order not to saturate
  145. the object constructor with arguments, it receives a dictionary of
  146. options instead. These options are available through the params
  147. attribute for the InfoExtractors to use. The FileDownloader also
  148. registers itself as the downloader in charge for the InfoExtractors
  149. that are added to it, so this is a "mutual registration".
  150. Available options:
  151. username: Username for authentication purposes.
  152. password: Password for authentication purposes.
  153. usenetrc: Use netrc for authentication instead.
  154. quiet: Do not print messages to stdout.
  155. forceurl: Force printing final URL.
  156. forcetitle: Force printing title.
  157. simulate: Do not download the video files.
  158. format: Video format code.
  159. outtmpl: Template for output names.
  160. ignoreerrors: Do not stop on download errors.
  161. ratelimit: Download speed limit, in bytes/sec.
  162. nooverwrites: Prevent overwriting files.
  163. continuedl: Try to continue downloads if possible.
  164. noprogress: Do not print the progress bar.
  165. """
  166. params = None
  167. _ies = []
  168. _pps = []
  169. _download_retcode = None
  170. _num_downloads = None
  171. def __init__(self, params):
  172. """Create a FileDownloader object with the given options."""
  173. self._ies = []
  174. self._pps = []
  175. self._download_retcode = 0
  176. self._num_downloads = 0
  177. self.params = params
  178. @staticmethod
  179. def pmkdir(filename):
  180. """Create directory components in filename. Similar to Unix "mkdir -p"."""
  181. components = filename.split(os.sep)
  182. aggregate = [os.sep.join(components[0:x]) for x in xrange(1, len(components))]
  183. aggregate = ['%s%s' % (x, os.sep) for x in aggregate] # Finish names with separator
  184. for dir in aggregate:
  185. if not os.path.exists(dir):
  186. os.mkdir(dir)
  187. @staticmethod
  188. def format_bytes(bytes):
  189. if bytes is None:
  190. return 'N/A'
  191. if type(bytes) is str:
  192. bytes = float(bytes)
  193. if bytes == 0.0:
  194. exponent = 0
  195. else:
  196. exponent = long(math.log(bytes, 1024.0))
  197. suffix = 'bkMGTPEZY'[exponent]
  198. converted = float(bytes) / float(1024**exponent)
  199. return '%.2f%s' % (converted, suffix)
  200. @staticmethod
  201. def calc_percent(byte_counter, data_len):
  202. if data_len is None:
  203. return '---.-%'
  204. return '%6s' % ('%3.1f%%' % (float(byte_counter) / float(data_len) * 100.0))
  205. @staticmethod
  206. def calc_eta(start, now, total, current):
  207. if total is None:
  208. return '--:--'
  209. dif = now - start
  210. if current == 0 or dif < 0.001: # One millisecond
  211. return '--:--'
  212. rate = float(current) / dif
  213. eta = long((float(total) - float(current)) / rate)
  214. (eta_mins, eta_secs) = divmod(eta, 60)
  215. if eta_mins > 99:
  216. return '--:--'
  217. return '%02d:%02d' % (eta_mins, eta_secs)
  218. @staticmethod
  219. def calc_speed(start, now, bytes):
  220. dif = now - start
  221. if bytes == 0 or dif < 0.001: # One millisecond
  222. return '%10s' % '---b/s'
  223. return '%10s' % ('%s/s' % FileDownloader.format_bytes(float(bytes) / dif))
  224. @staticmethod
  225. def best_block_size(elapsed_time, bytes):
  226. new_min = max(bytes / 2.0, 1.0)
  227. new_max = min(max(bytes * 2.0, 1.0), 4194304) # Do not surpass 4 MB
  228. if elapsed_time < 0.001:
  229. return long(new_max)
  230. rate = bytes / elapsed_time
  231. if rate > new_max:
  232. return long(new_max)
  233. if rate < new_min:
  234. return long(new_min)
  235. return long(rate)
  236. @staticmethod
  237. def parse_bytes(bytestr):
  238. """Parse a string indicating a byte quantity into a long integer."""
  239. matchobj = re.match(r'(?i)^(\d+(?:\.\d+)?)([kMGTPEZY]?)$', bytestr)
  240. if matchobj is None:
  241. return None
  242. number = float(matchobj.group(1))
  243. multiplier = 1024.0 ** 'bkmgtpezy'.index(matchobj.group(2).lower())
  244. return long(round(number * multiplier))
  245. @staticmethod
  246. def verify_url(url):
  247. """Verify a URL is valid and data could be downloaded. Return real data URL."""
  248. request = urllib2.Request(url, None, std_headers)
  249. data = urllib2.urlopen(request)
  250. data.read(1)
  251. url = data.geturl()
  252. data.close()
  253. return url
  254. def add_info_extractor(self, ie):
  255. """Add an InfoExtractor object to the end of the list."""
  256. self._ies.append(ie)
  257. ie.set_downloader(self)
  258. def add_post_processor(self, pp):
  259. """Add a PostProcessor object to the end of the chain."""
  260. self._pps.append(pp)
  261. pp.set_downloader(self)
  262. def to_stdout(self, message, skip_eol=False, ignore_encoding_errors=False):
  263. """Print message to stdout if not in quiet mode."""
  264. try:
  265. if not self.params.get('quiet', False):
  266. print (u'%s%s' % (message, [u'\n', u''][skip_eol])).encode(preferredencoding()),
  267. sys.stdout.flush()
  268. except (UnicodeEncodeError), err:
  269. if not ignore_encoding_errors:
  270. raise
  271. def to_stderr(self, message):
  272. """Print message to stderr."""
  273. print >>sys.stderr, message.encode(preferredencoding())
  274. def fixed_template(self):
  275. """Checks if the output template is fixed."""
  276. return (re.search(ur'(?u)%\(.+?\)s', self.params['outtmpl']) is None)
  277. def trouble(self, message=None):
  278. """Determine action to take when a download problem appears.
  279. Depending on if the downloader has been configured to ignore
  280. download errors or not, this method may throw an exception or
  281. not when errors are found, after printing the message.
  282. """
  283. if message is not None:
  284. self.to_stderr(message)
  285. if not self.params.get('ignoreerrors', False):
  286. raise DownloadError(message)
  287. self._download_retcode = 1
  288. def slow_down(self, start_time, byte_counter):
  289. """Sleep if the download speed is over the rate limit."""
  290. rate_limit = self.params.get('ratelimit', None)
  291. if rate_limit is None or byte_counter == 0:
  292. return
  293. now = time.time()
  294. elapsed = now - start_time
  295. if elapsed <= 0.0:
  296. return
  297. speed = float(byte_counter) / elapsed
  298. if speed > rate_limit:
  299. time.sleep((byte_counter - rate_limit * (now - start_time)) / rate_limit)
  300. def report_destination(self, filename):
  301. """Report destination filename."""
  302. self.to_stdout(u'[download] Destination: %s' % filename, ignore_encoding_errors=True)
  303. def report_progress(self, percent_str, data_len_str, speed_str, eta_str):
  304. """Report download progress."""
  305. if self.params.get('noprogress', False):
  306. return
  307. self.to_stdout(u'\r[download] %s of %s at %s ETA %s' %
  308. (percent_str, data_len_str, speed_str, eta_str), skip_eol=True)
  309. def report_resuming_byte(self, resume_len):
  310. """Report attemtp to resume at given byte."""
  311. self.to_stdout(u'[download] Resuming download at byte %s' % resume_len)
  312. def report_file_already_downloaded(self, file_name):
  313. """Report file has already been fully downloaded."""
  314. try:
  315. self.to_stdout(u'[download] %s has already been downloaded' % file_name)
  316. except (UnicodeEncodeError), err:
  317. self.to_stdout(u'[download] The file has already been downloaded')
  318. def report_unable_to_resume(self):
  319. """Report it was impossible to resume download."""
  320. self.to_stdout(u'[download] Unable to resume')
  321. def report_finish(self):
  322. """Report download finished."""
  323. if self.params.get('noprogress', False):
  324. self.to_stdout(u'[download] Download completed')
  325. else:
  326. self.to_stdout(u'')
  327. def process_info(self, info_dict):
  328. """Process a single dictionary returned by an InfoExtractor."""
  329. # Do nothing else if in simulate mode
  330. if self.params.get('simulate', False):
  331. # Verify URL if it's an HTTP one
  332. if info_dict['url'].startswith('http'):
  333. try:
  334. self.verify_url(info_dict['url'].encode('utf-8')).decode('utf-8')
  335. except (OSError, IOError, urllib2.URLError, httplib.HTTPException, socket.error), err:
  336. raise UnavailableFormatError
  337. # Forced printings
  338. if self.params.get('forcetitle', False):
  339. print info_dict['title'].encode(preferredencoding(), 'xmlcharrefreplace')
  340. if self.params.get('forceurl', False):
  341. print info_dict['url'].encode(preferredencoding(), 'xmlcharrefreplace')
  342. if self.params.get('forcethumbnail', False) and 'thumbnail' in info_dict:
  343. print info_dict['thumbnail'].encode(preferredencoding(), 'xmlcharrefreplace')
  344. if self.params.get('forcedescription', False) and 'description' in info_dict:
  345. print info_dict['description'].encode(preferredencoding(), 'xmlcharrefreplace')
  346. return
  347. try:
  348. template_dict = dict(info_dict)
  349. template_dict['epoch'] = unicode(long(time.time()))
  350. template_dict['ord'] = unicode('%05d' % self._num_downloads)
  351. filename = self.params['outtmpl'] % template_dict
  352. except (ValueError, KeyError), err:
  353. self.trouble('ERROR: invalid output template or system charset: %s' % str(err))
  354. if self.params.get('nooverwrites', False) and os.path.exists(filename):
  355. self.to_stderr(u'WARNING: file exists: %s; skipping' % filename)
  356. return
  357. try:
  358. self.pmkdir(filename)
  359. except (OSError, IOError), err:
  360. self.trouble('ERROR: unable to create directories: %s' % str(err))
  361. return
  362. try:
  363. success = self._do_download(filename, info_dict['url'].encode('utf-8'))
  364. except (OSError, IOError), err:
  365. raise UnavailableFormatError
  366. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  367. self.trouble('ERROR: unable to download video data: %s' % str(err))
  368. return
  369. except (ContentTooShortError, ), err:
  370. self.trouble('ERROR: content too short (expected %s bytes and served %s)' % (err.expected, err.downloaded))
  371. return
  372. if success:
  373. try:
  374. self.post_process(filename, info_dict)
  375. except (PostProcessingError), err:
  376. self.trouble('ERROR: postprocessing: %s' % str(err))
  377. return
  378. def download(self, url_list):
  379. """Download a given list of URLs."""
  380. if len(url_list) > 1 and self.fixed_template():
  381. raise SameFileError(self.params['outtmpl'])
  382. for url in url_list:
  383. suitable_found = False
  384. for ie in self._ies:
  385. # Go to next InfoExtractor if not suitable
  386. if not ie.suitable(url):
  387. continue
  388. # Suitable InfoExtractor found
  389. suitable_found = True
  390. # Extract information from URL and process it
  391. ie.extract(url)
  392. # Suitable InfoExtractor had been found; go to next URL
  393. break
  394. if not suitable_found:
  395. self.trouble('ERROR: no suitable InfoExtractor: %s' % url)
  396. return self._download_retcode
  397. def post_process(self, filename, ie_info):
  398. """Run the postprocessing chain on the given file."""
  399. info = dict(ie_info)
  400. info['filepath'] = filename
  401. for pp in self._pps:
  402. info = pp.run(info)
  403. if info is None:
  404. break
  405. def _download_with_rtmpdump(self, filename, url):
  406. self.report_destination(filename)
  407. # Check for rtmpdump first
  408. try:
  409. subprocess.call(['rtmpdump', '-h'], stdout=(file(os.path.devnull, 'w')), stderr=subprocess.STDOUT)
  410. except (OSError, IOError):
  411. self.trouble(u'ERROR: RTMP download detected but "rtmpdump" could not be run')
  412. return False
  413. # Download using rtmpdump. rtmpdump returns exit code 2 when
  414. # the connection was interrumpted and resuming appears to be
  415. # possible. This is part of rtmpdump's normal usage, AFAIK.
  416. basic_args = ['rtmpdump', '-q', '-r', url, '-o', filename]
  417. retval = subprocess.call(basic_args + [[], ['-e', '-k', '1']][self.params.get('continuedl', False)])
  418. while retval == 2 or retval == 1:
  419. self.to_stdout(u'\r[rtmpdump] %s bytes' % os.path.getsize(filename), skip_eol=True)
  420. time.sleep(2.0) # This seems to be needed
  421. retval = subprocess.call(basic_args + ['-e'] + [[], ['-k', '1']][retval == 1])
  422. if retval == 0:
  423. self.to_stdout(u'\r[rtmpdump] %s bytes' % os.path.getsize(filename))
  424. return True
  425. else:
  426. self.trouble('\nERROR: rtmpdump exited with code %d' % retval)
  427. return False
  428. def _do_download(self, filename, url):
  429. # Attempt to download using rtmpdump
  430. if url.startswith('rtmp'):
  431. return self._download_with_rtmpdump(filename, url)
  432. stream = None
  433. open_mode = 'wb'
  434. basic_request = urllib2.Request(url, None, std_headers)
  435. request = urllib2.Request(url, None, std_headers)
  436. # Establish possible resume length
  437. if os.path.isfile(filename):
  438. resume_len = os.path.getsize(filename)
  439. else:
  440. resume_len = 0
  441. # Request parameters in case of being able to resume
  442. if self.params.get('continuedl', False) and resume_len != 0:
  443. self.report_resuming_byte(resume_len)
  444. request.add_header('Range','bytes=%d-' % resume_len)
  445. open_mode = 'ab'
  446. # Establish connection
  447. try:
  448. data = urllib2.urlopen(request)
  449. except (urllib2.HTTPError, ), err:
  450. if err.code != 416: # 416 is 'Requested range not satisfiable'
  451. raise
  452. # Unable to resume
  453. data = urllib2.urlopen(basic_request)
  454. content_length = data.info()['Content-Length']
  455. if content_length is not None and long(content_length) == resume_len:
  456. # Because the file had already been fully downloaded
  457. self.report_file_already_downloaded(filename)
  458. self._num_downloads += 1
  459. return True
  460. else:
  461. # Because the server didn't let us
  462. self.report_unable_to_resume()
  463. open_mode = 'wb'
  464. data_len = data.info().get('Content-length', None)
  465. data_len_str = self.format_bytes(data_len)
  466. byte_counter = 0
  467. block_size = 1024
  468. start = time.time()
  469. while True:
  470. # Download and write
  471. before = time.time()
  472. data_block = data.read(block_size)
  473. after = time.time()
  474. data_block_len = len(data_block)
  475. if data_block_len == 0:
  476. break
  477. byte_counter += data_block_len
  478. # Open file just in time
  479. if stream is None:
  480. try:
  481. (stream, filename) = sanitize_open(filename, open_mode)
  482. self.report_destination(filename)
  483. self._num_downloads += 1
  484. except (OSError, IOError), err:
  485. self.trouble('ERROR: unable to open for writing: %s' % str(err))
  486. return False
  487. try:
  488. stream.write(data_block)
  489. except (IOError, OSError), err:
  490. self.trouble('\nERROR: unable to write data: %s' % str(err))
  491. block_size = self.best_block_size(after - before, data_block_len)
  492. # Progress message
  493. percent_str = self.calc_percent(byte_counter, data_len)
  494. eta_str = self.calc_eta(start, time.time(), data_len, byte_counter)
  495. speed_str = self.calc_speed(start, time.time(), byte_counter)
  496. self.report_progress(percent_str, data_len_str, speed_str, eta_str)
  497. # Apply rate limit
  498. self.slow_down(start, byte_counter)
  499. self.report_finish()
  500. if data_len is not None and str(byte_counter) != data_len:
  501. raise ContentTooShortError(byte_counter, long(data_len))
  502. return True
  503. class InfoExtractor(object):
  504. """Information Extractor class.
  505. Information extractors are the classes that, given a URL, extract
  506. information from the video (or videos) the URL refers to. This
  507. information includes the real video URL, the video title and simplified
  508. title, author and others. The information is stored in a dictionary
  509. which is then passed to the FileDownloader. The FileDownloader
  510. processes this information possibly downloading the video to the file
  511. system, among other possible outcomes. The dictionaries must include
  512. the following fields:
  513. id: Video identifier.
  514. url: Final video URL.
  515. uploader: Nickname of the video uploader.
  516. title: Literal title.
  517. stitle: Simplified title.
  518. ext: Video filename extension.
  519. format: Video format.
  520. The following fields are optional. Their primary purpose is to allow
  521. youtube-dl to serve as the backend for a video search function, such
  522. as the one in youtube2mp3. They are only used when their respective
  523. forced printing functions are called:
  524. thumbnail: Full URL to a video thumbnail image.
  525. description: One-line video description.
  526. Subclasses of this one should re-define the _real_initialize() and
  527. _real_extract() methods, as well as the suitable() static method.
  528. Probably, they should also be instantiated and added to the main
  529. downloader.
  530. """
  531. _ready = False
  532. _downloader = None
  533. def __init__(self, downloader=None):
  534. """Constructor. Receives an optional downloader."""
  535. self._ready = False
  536. self.set_downloader(downloader)
  537. @staticmethod
  538. def suitable(url):
  539. """Receives a URL and returns True if suitable for this IE."""
  540. return False
  541. def initialize(self):
  542. """Initializes an instance (authentication, etc)."""
  543. if not self._ready:
  544. self._real_initialize()
  545. self._ready = True
  546. def extract(self, url):
  547. """Extracts URL information and returns it in list of dicts."""
  548. self.initialize()
  549. return self._real_extract(url)
  550. def set_downloader(self, downloader):
  551. """Sets the downloader for this IE."""
  552. self._downloader = downloader
  553. def _real_initialize(self):
  554. """Real initialization process. Redefine in subclasses."""
  555. pass
  556. def _real_extract(self, url):
  557. """Real extraction process. Redefine in subclasses."""
  558. pass
  559. class YoutubeIE(InfoExtractor):
  560. """Information extractor for youtube.com."""
  561. _VALID_URL = r'^((?:http://)?(?:\w+\.)?youtube\.com/(?:(?:v/)|(?:(?:watch(?:\.php)?)?[\?#](?:.+&)?v=)))?([0-9A-Za-z_-]+)(?(1).+)?$'
  562. _LANG_URL = r'http://uk.youtube.com/?hl=en&persist_hl=1&gl=US&persist_gl=1&opt_out_ackd=1'
  563. _LOGIN_URL = 'http://www.youtube.com/signup?next=/&gl=US&hl=en'
  564. _AGE_URL = 'http://www.youtube.com/verify_age?next_url=/&gl=US&hl=en'
  565. _NETRC_MACHINE = 'youtube'
  566. _available_formats = ['37', '22', '35', '18', '34', '5', '17', '13', None] # listed in order of priority for -b flag
  567. _video_extensions = {
  568. '13': '3gp',
  569. '17': 'mp4',
  570. '18': 'mp4',
  571. '22': 'mp4',
  572. '37': 'mp4',
  573. }
  574. @staticmethod
  575. def suitable(url):
  576. return (re.match(YoutubeIE._VALID_URL, url) is not None)
  577. def report_lang(self):
  578. """Report attempt to set language."""
  579. self._downloader.to_stdout(u'[youtube] Setting language')
  580. def report_login(self):
  581. """Report attempt to log in."""
  582. self._downloader.to_stdout(u'[youtube] Logging in')
  583. def report_age_confirmation(self):
  584. """Report attempt to confirm age."""
  585. self._downloader.to_stdout(u'[youtube] Confirming age')
  586. def report_video_info_webpage_download(self, video_id):
  587. """Report attempt to download video info webpage."""
  588. self._downloader.to_stdout(u'[youtube] %s: Downloading video info webpage' % video_id)
  589. def report_information_extraction(self, video_id):
  590. """Report attempt to extract video information."""
  591. self._downloader.to_stdout(u'[youtube] %s: Extracting video information' % video_id)
  592. def report_unavailable_format(self, video_id, format):
  593. """Report extracted video URL."""
  594. self._downloader.to_stdout(u'[youtube] %s: Format %s not available' % (video_id, format))
  595. def report_rtmp_download(self):
  596. """Indicate the download will use the RTMP protocol."""
  597. self._downloader.to_stdout(u'[youtube] RTMP download detected')
  598. def _real_initialize(self):
  599. if self._downloader is None:
  600. return
  601. username = None
  602. password = None
  603. downloader_params = self._downloader.params
  604. # Attempt to use provided username and password or .netrc data
  605. if downloader_params.get('username', None) is not None:
  606. username = downloader_params['username']
  607. password = downloader_params['password']
  608. elif downloader_params.get('usenetrc', False):
  609. try:
  610. info = netrc.netrc().authenticators(self._NETRC_MACHINE)
  611. if info is not None:
  612. username = info[0]
  613. password = info[2]
  614. else:
  615. raise netrc.NetrcParseError('No authenticators for %s' % self._NETRC_MACHINE)
  616. except (IOError, netrc.NetrcParseError), err:
  617. self._downloader.to_stderr(u'WARNING: parsing .netrc: %s' % str(err))
  618. return
  619. # Set language
  620. request = urllib2.Request(self._LANG_URL, None, std_headers)
  621. try:
  622. self.report_lang()
  623. urllib2.urlopen(request).read()
  624. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  625. self._downloader.to_stderr(u'WARNING: unable to set language: %s' % str(err))
  626. return
  627. # No authentication to be performed
  628. if username is None:
  629. return
  630. # Log in
  631. login_form = {
  632. 'current_form': 'loginForm',
  633. 'next': '/',
  634. 'action_login': 'Log In',
  635. 'username': username,
  636. 'password': password,
  637. }
  638. request = urllib2.Request(self._LOGIN_URL, urllib.urlencode(login_form), std_headers)
  639. try:
  640. self.report_login()
  641. login_results = urllib2.urlopen(request).read()
  642. if re.search(r'(?i)<form[^>]* name="loginForm"', login_results) is not None:
  643. self._downloader.to_stderr(u'WARNING: unable to log in: bad username or password')
  644. return
  645. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  646. self._downloader.to_stderr(u'WARNING: unable to log in: %s' % str(err))
  647. return
  648. # Confirm age
  649. age_form = {
  650. 'next_url': '/',
  651. 'action_confirm': 'Confirm',
  652. }
  653. request = urllib2.Request(self._AGE_URL, urllib.urlencode(age_form), std_headers)
  654. try:
  655. self.report_age_confirmation()
  656. age_results = urllib2.urlopen(request).read()
  657. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  658. self._downloader.trouble(u'ERROR: unable to confirm age: %s' % str(err))
  659. return
  660. def _real_extract(self, url):
  661. # Extract video id from URL
  662. mobj = re.match(self._VALID_URL, url)
  663. if mobj is None:
  664. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  665. return
  666. video_id = mobj.group(2)
  667. # Downloader parameters
  668. best_quality = False
  669. all_formats = False
  670. format_param = None
  671. quality_index = 0
  672. if self._downloader is not None:
  673. params = self._downloader.params
  674. format_param = params.get('format', None)
  675. if format_param == '0':
  676. format_param = self._available_formats[quality_index]
  677. best_quality = True
  678. elif format_param == '-1':
  679. format_param = self._available_formats[quality_index]
  680. all_formats = True
  681. while True:
  682. # Extension
  683. video_extension = self._video_extensions.get(format_param, 'flv')
  684. # Get video info
  685. self.report_video_info_webpage_download(video_id)
  686. for el_type in ['&el=embedded', '&el=detailpage', '&el=vevo', '']:
  687. video_info_url = ('http://www.youtube.com/get_video_info?&video_id=%s%s&ps=default&eurl=&gl=US&hl=en'
  688. % (video_id, el_type))
  689. request = urllib2.Request(video_info_url, None, std_headers)
  690. try:
  691. video_info_webpage = urllib2.urlopen(request).read()
  692. video_info = parse_qs(video_info_webpage)
  693. if 'token' in video_info:
  694. break
  695. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  696. self._downloader.trouble(u'ERROR: unable to download video info webpage: %s' % str(err))
  697. return
  698. self.report_information_extraction(video_id)
  699. # "t" param
  700. if 'token' not in video_info:
  701. # Attempt to see if YouTube has issued an error message
  702. if 'reason' not in video_info:
  703. self._downloader.trouble(u'ERROR: unable to extract "t" parameter for unknown reason')
  704. stream = open('reportme-ydl-%s.dat' % time.time(), 'wb')
  705. stream.write(video_info_webpage)
  706. stream.close()
  707. else:
  708. reason = urllib.unquote_plus(video_info['reason'][0])
  709. self._downloader.trouble(u'ERROR: YouTube said: %s' % reason.decode('utf-8'))
  710. return
  711. token = urllib.unquote_plus(video_info['token'][0])
  712. video_real_url = 'http://www.youtube.com/get_video?video_id=%s&t=%s&eurl=&el=detailpage&ps=default&gl=US&hl=en' % (video_id, token)
  713. if format_param is not None:
  714. video_real_url = '%s&fmt=%s' % (video_real_url, format_param)
  715. # Check possible RTMP download
  716. if 'conn' in video_info and video_info['conn'][0].startswith('rtmp'):
  717. self.report_rtmp_download()
  718. video_real_url = video_info['conn'][0]
  719. # uploader
  720. if 'author' not in video_info:
  721. self._downloader.trouble(u'ERROR: unable to extract uploader nickname')
  722. return
  723. video_uploader = urllib.unquote_plus(video_info['author'][0])
  724. # title
  725. if 'title' not in video_info:
  726. self._downloader.trouble(u'ERROR: unable to extract video title')
  727. return
  728. video_title = urllib.unquote_plus(video_info['title'][0])
  729. video_title = video_title.decode('utf-8')
  730. video_title = sanitize_title(video_title)
  731. # simplified title
  732. simple_title = re.sub(ur'(?u)([^%s]+)' % simple_title_chars, ur'_', video_title)
  733. simple_title = simple_title.strip(ur'_')
  734. # thumbnail image
  735. if 'thumbnail_url' not in video_info:
  736. self._downloader.trouble(u'WARNING: unable to extract video thumbnail')
  737. video_thumbnail = ''
  738. else: # don't panic if we can't find it
  739. video_thumbnail = urllib.unquote_plus(video_info['thumbnail_url'][0])
  740. # get video description
  741. video_description = 'No description available.' # we need something to pass to self._downloader
  742. # this requires an additional HTTP request and a little
  743. # more time, so don't do it unless absolutely necessary
  744. if self._downloader.params.get('forcedescription', False):
  745. video_page_url = 'http://www.youtube.com/watch?v=' + video_id
  746. request = urllib2.Request(video_page_url, None, std_headers)
  747. try:
  748. video_page_webpage = urllib2.urlopen(request).read()
  749. mobj = re.search(r'<meta name="description" content="(.*)"(?:\s*/)?>', video_page_webpage)
  750. if mobj is not None:
  751. video_description = mobj.group(1)
  752. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  753. pass # don't panic if we can't find it
  754. try:
  755. # Process video information
  756. self._downloader.process_info({
  757. 'id': video_id.decode('utf-8'),
  758. 'url': video_real_url.decode('utf-8'),
  759. 'uploader': video_uploader.decode('utf-8'),
  760. 'title': video_title,
  761. 'stitle': simple_title,
  762. 'ext': video_extension.decode('utf-8'),
  763. 'format': (format_param is None and u'NA' or format_param.decode('utf-8')),
  764. 'thumbnail': video_thumbnail.decode('utf-8'),
  765. 'description': video_description.decode('utf-8'),
  766. })
  767. if all_formats:
  768. if quality_index == len(self._available_formats):
  769. # None left to get
  770. return
  771. else:
  772. quality_index += 1
  773. format_param = self._available_formats[quality_index]
  774. continue
  775. return
  776. except UnavailableFormatError, err:
  777. if best_quality or all_formats:
  778. if quality_index == len(self._available_formats):
  779. # I don't ever expect this to happen
  780. if not all_formats:
  781. self._downloader.trouble(u'ERROR: no known formats available for video')
  782. return
  783. else:
  784. self.report_unavailable_format(video_id, format_param)
  785. quality_index += 1
  786. format_param = self._available_formats[quality_index]
  787. continue
  788. else:
  789. self._downloader.trouble('ERROR: format not available for video')
  790. return
  791. class MetacafeIE(InfoExtractor):
  792. """Information Extractor for metacafe.com."""
  793. _VALID_URL = r'(?:http://)?(?:www\.)?metacafe\.com/watch/([^/]+)/([^/]+)/.*'
  794. _DISCLAIMER = 'http://www.metacafe.com/family_filter/'
  795. _FILTER_POST = 'http://www.metacafe.com/f/index.php?inputType=filter&controllerGroup=user'
  796. _youtube_ie = None
  797. def __init__(self, youtube_ie, downloader=None):
  798. InfoExtractor.__init__(self, downloader)
  799. self._youtube_ie = youtube_ie
  800. @staticmethod
  801. def suitable(url):
  802. return (re.match(MetacafeIE._VALID_URL, url) is not None)
  803. def report_disclaimer(self):
  804. """Report disclaimer retrieval."""
  805. self._downloader.to_stdout(u'[metacafe] Retrieving disclaimer')
  806. def report_age_confirmation(self):
  807. """Report attempt to confirm age."""
  808. self._downloader.to_stdout(u'[metacafe] Confirming age')
  809. def report_download_webpage(self, video_id):
  810. """Report webpage download."""
  811. self._downloader.to_stdout(u'[metacafe] %s: Downloading webpage' % video_id)
  812. def report_extraction(self, video_id):
  813. """Report information extraction."""
  814. self._downloader.to_stdout(u'[metacafe] %s: Extracting information' % video_id)
  815. def _real_initialize(self):
  816. # Retrieve disclaimer
  817. request = urllib2.Request(self._DISCLAIMER, None, std_headers)
  818. try:
  819. self.report_disclaimer()
  820. disclaimer = urllib2.urlopen(request).read()
  821. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  822. self._downloader.trouble(u'ERROR: unable to retrieve disclaimer: %s' % str(err))
  823. return
  824. # Confirm age
  825. disclaimer_form = {
  826. 'filters': '0',
  827. 'submit': "Continue - I'm over 18",
  828. }
  829. request = urllib2.Request(self._FILTER_POST, urllib.urlencode(disclaimer_form), std_headers)
  830. try:
  831. self.report_age_confirmation()
  832. disclaimer = urllib2.urlopen(request).read()
  833. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  834. self._downloader.trouble(u'ERROR: unable to confirm age: %s' % str(err))
  835. return
  836. def _real_extract(self, url):
  837. # Extract id and simplified title from URL
  838. mobj = re.match(self._VALID_URL, url)
  839. if mobj is None:
  840. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  841. return
  842. video_id = mobj.group(1)
  843. # Check if video comes from YouTube
  844. mobj2 = re.match(r'^yt-(.*)$', video_id)
  845. if mobj2 is not None:
  846. self._youtube_ie.extract('http://www.youtube.com/watch?v=%s' % mobj2.group(1))
  847. return
  848. simple_title = mobj.group(2).decode('utf-8')
  849. video_extension = 'flv'
  850. # Retrieve video webpage to extract further information
  851. request = urllib2.Request('http://www.metacafe.com/watch/%s/' % video_id)
  852. try:
  853. self.report_download_webpage(video_id)
  854. webpage = urllib2.urlopen(request).read()
  855. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  856. self._downloader.trouble(u'ERROR: unable retrieve video webpage: %s' % str(err))
  857. return
  858. # Extract URL, uploader and title from webpage
  859. self.report_extraction(video_id)
  860. mobj = re.search(r'(?m)&mediaURL=([^&]+)', webpage)
  861. if mobj is None:
  862. self._downloader.trouble(u'ERROR: unable to extract media URL')
  863. return
  864. mediaURL = urllib.unquote(mobj.group(1))
  865. #mobj = re.search(r'(?m)&gdaKey=(.*?)&', webpage)
  866. #if mobj is None:
  867. # self._downloader.trouble(u'ERROR: unable to extract gdaKey')
  868. # return
  869. #gdaKey = mobj.group(1)
  870. #
  871. #video_url = '%s?__gda__=%s' % (mediaURL, gdaKey)
  872. video_url = mediaURL
  873. mobj = re.search(r'(?im)<title>(.*) - Video</title>', webpage)
  874. if mobj is None:
  875. self._downloader.trouble(u'ERROR: unable to extract title')
  876. return
  877. video_title = mobj.group(1).decode('utf-8')
  878. video_title = sanitize_title(video_title)
  879. mobj = re.search(r'(?ms)By:\s*<a .*?>(.+?)<', webpage)
  880. if mobj is None:
  881. self._downloader.trouble(u'ERROR: unable to extract uploader nickname')
  882. return
  883. video_uploader = mobj.group(1)
  884. try:
  885. # Process video information
  886. self._downloader.process_info({
  887. 'id': video_id.decode('utf-8'),
  888. 'url': video_url.decode('utf-8'),
  889. 'uploader': video_uploader.decode('utf-8'),
  890. 'title': video_title,
  891. 'stitle': simple_title,
  892. 'ext': video_extension.decode('utf-8'),
  893. 'format': u'NA',
  894. })
  895. except UnavailableFormatError:
  896. self._downloader.trouble(u'ERROR: format not available for video')
  897. class GoogleIE(InfoExtractor):
  898. """Information extractor for video.google.com."""
  899. _VALID_URL = r'(?:http://)?video\.google\.(?:com(?:\.au)?|co\.(?:uk|jp|kr|cr)|ca|de|es|fr|it|nl|pl)/videoplay\?docid=([^\&]+).*'
  900. def __init__(self, downloader=None):
  901. InfoExtractor.__init__(self, downloader)
  902. @staticmethod
  903. def suitable(url):
  904. return (re.match(GoogleIE._VALID_URL, url) is not None)
  905. def report_download_webpage(self, video_id):
  906. """Report webpage download."""
  907. self._downloader.to_stdout(u'[video.google] %s: Downloading webpage' % video_id)
  908. def report_extraction(self, video_id):
  909. """Report information extraction."""
  910. self._downloader.to_stdout(u'[video.google] %s: Extracting information' % video_id)
  911. def _real_initialize(self):
  912. return
  913. def _real_extract(self, url):
  914. # Extract id from URL
  915. mobj = re.match(self._VALID_URL, url)
  916. if mobj is None:
  917. self._downloader.trouble(u'ERROR: Invalid URL: %s' % url)
  918. return
  919. video_id = mobj.group(1)
  920. video_extension = 'mp4'
  921. # Retrieve video webpage to extract further information
  922. request = urllib2.Request('http://video.google.com/videoplay?docid=%s&hl=en&oe=utf-8' % video_id)
  923. try:
  924. self.report_download_webpage(video_id)
  925. webpage = urllib2.urlopen(request).read()
  926. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  927. self._downloader.trouble(u'ERROR: Unable to retrieve video webpage: %s' % str(err))
  928. return
  929. # Extract URL, uploader, and title from webpage
  930. self.report_extraction(video_id)
  931. mobj = re.search(r"download_url:'([^']+)'", webpage)
  932. if mobj is None:
  933. video_extension = 'flv'
  934. mobj = re.search(r"(?i)videoUrl\\x3d(.+?)\\x26", webpage)
  935. if mobj is None:
  936. self._downloader.trouble(u'ERROR: unable to extract media URL')
  937. return
  938. mediaURL = urllib.unquote(mobj.group(1))
  939. mediaURL = mediaURL.replace('\\x3d', '\x3d')
  940. mediaURL = mediaURL.replace('\\x26', '\x26')
  941. video_url = mediaURL
  942. mobj = re.search(r'<title>(.*)</title>', webpage)
  943. if mobj is None:
  944. self._downloader.trouble(u'ERROR: unable to extract title')
  945. return
  946. video_title = mobj.group(1).decode('utf-8')
  947. video_title = sanitize_title(video_title)
  948. simple_title = re.sub(ur'(?u)([^%s]+)' % simple_title_chars, ur'_', video_title)
  949. # Extract video description
  950. mobj = re.search(r'<span id=short-desc-content>([^<]*)</span>', webpage)
  951. if mobj is None:
  952. self._downloader.trouble(u'ERROR: unable to extract video description')
  953. return
  954. video_description = mobj.group(1).decode('utf-8')
  955. if not video_description:
  956. video_description = 'No description available.'
  957. # Extract video thumbnail
  958. if self._downloader.params.get('forcethumbnail', False):
  959. request = urllib2.Request('http://video.google.com/videosearch?q=%s+site:video.google.com&hl=en' % abs(int(video_id)))
  960. try:
  961. webpage = urllib2.urlopen(request).read()
  962. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  963. self._downloader.trouble(u'ERROR: Unable to retrieve video webpage: %s' % str(err))
  964. return
  965. mobj = re.search(r'<img class=thumbnail-img (?:.* )?src=(http.*)>', webpage)
  966. if mobj is None:
  967. self._downloader.trouble(u'ERROR: unable to extract video thumbnail')
  968. return
  969. video_thumbnail = mobj.group(1)
  970. else: # we need something to pass to process_info
  971. video_thumbnail = ''
  972. try:
  973. # Process video information
  974. self._downloader.process_info({
  975. 'id': video_id.decode('utf-8'),
  976. 'url': video_url.decode('utf-8'),
  977. 'uploader': u'NA',
  978. 'title': video_title,
  979. 'stitle': simple_title,
  980. 'ext': video_extension.decode('utf-8'),
  981. 'format': u'NA',
  982. })
  983. except UnavailableFormatError:
  984. self._downloader.trouble(u'ERROR: format not available for video')
  985. class PhotobucketIE(InfoExtractor):
  986. """Information extractor for photobucket.com."""
  987. _VALID_URL = r'(?:http://)?(?:[a-z0-9]+\.)?photobucket\.com/.*[\?\&]current=(.*\.flv)'
  988. def __init__(self, downloader=None):
  989. InfoExtractor.__init__(self, downloader)
  990. @staticmethod
  991. def suitable(url):
  992. return (re.match(PhotobucketIE._VALID_URL, url) is not None)
  993. def report_download_webpage(self, video_id):
  994. """Report webpage download."""
  995. self._downloader.to_stdout(u'[photobucket] %s: Downloading webpage' % video_id)
  996. def report_extraction(self, video_id):
  997. """Report information extraction."""
  998. self._downloader.to_stdout(u'[photobucket] %s: Extracting information' % video_id)
  999. def _real_initialize(self):
  1000. return
  1001. def _real_extract(self, url):
  1002. # Extract id from URL
  1003. mobj = re.match(self._VALID_URL, url)
  1004. if mobj is None:
  1005. self._downloader.trouble(u'ERROR: Invalid URL: %s' % url)
  1006. return
  1007. video_id = mobj.group(1)
  1008. video_extension = 'flv'
  1009. # Retrieve video webpage to extract further information
  1010. request = urllib2.Request(url)
  1011. try:
  1012. self.report_download_webpage(video_id)
  1013. webpage = urllib2.urlopen(request).read()
  1014. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1015. self._downloader.trouble(u'ERROR: Unable to retrieve video webpage: %s' % str(err))
  1016. return
  1017. # Extract URL, uploader, and title from webpage
  1018. self.report_extraction(video_id)
  1019. mobj = re.search(r'<link rel="video_src" href=".*\?file=([^"]+)" />', webpage)
  1020. if mobj is None:
  1021. self._downloader.trouble(u'ERROR: unable to extract media URL')
  1022. return
  1023. mediaURL = urllib.unquote(mobj.group(1))
  1024. video_url = mediaURL
  1025. mobj = re.search(r'<title>(.*) video by (.*) - Photobucket</title>', webpage)
  1026. if mobj is None:
  1027. self._downloader.trouble(u'ERROR: unable to extract title')
  1028. return
  1029. video_title = mobj.group(1).decode('utf-8')
  1030. video_title = sanitize_title(video_title)
  1031. simple_title = re.sub(ur'(?u)([^%s]+)' % simple_title_chars, ur'_', video_title)
  1032. video_uploader = mobj.group(2).decode('utf-8')
  1033. try:
  1034. # Process video information
  1035. self._downloader.process_info({
  1036. 'id': video_id.decode('utf-8'),
  1037. 'url': video_url.decode('utf-8'),
  1038. 'uploader': video_uploader,
  1039. 'title': video_title,
  1040. 'stitle': simple_title,
  1041. 'ext': video_extension.decode('utf-8'),
  1042. 'format': u'NA',
  1043. })
  1044. except UnavailableFormatError:
  1045. self._downloader.trouble(u'ERROR: format not available for video')
  1046. class YahooIE(InfoExtractor):
  1047. """Information extractor for video.yahoo.com."""
  1048. # _VALID_URL matches all Yahoo! Video URLs
  1049. # _VPAGE_URL matches only the extractable '/watch/' URLs
  1050. _VALID_URL = r'(?:http://)?(?:[a-z]+\.)?video\.yahoo\.com/(?:watch|network)/([0-9]+)(?:/|\?v=)([0-9]+)(?:[#\?].*)?'
  1051. _VPAGE_URL = r'(?:http://)?video\.yahoo\.com/watch/([0-9]+)/([0-9]+)(?:[#\?].*)?'
  1052. def __init__(self, downloader=None):
  1053. InfoExtractor.__init__(self, downloader)
  1054. @staticmethod
  1055. def suitable(url):
  1056. return (re.match(YahooIE._VALID_URL, url) is not None)
  1057. def report_download_webpage(self, video_id):
  1058. """Report webpage download."""
  1059. self._downloader.to_stdout(u'[video.yahoo] %s: Downloading webpage' % video_id)
  1060. def report_extraction(self, video_id):
  1061. """Report information extraction."""
  1062. self._downloader.to_stdout(u'[video.yahoo] %s: Extracting information' % video_id)
  1063. def _real_initialize(self):
  1064. return
  1065. def _real_extract(self, url):
  1066. # Extract ID from URL
  1067. mobj = re.match(self._VALID_URL, url)
  1068. if mobj is None:
  1069. self._downloader.trouble(u'ERROR: Invalid URL: %s' % url)
  1070. return
  1071. video_id = mobj.group(2)
  1072. video_extension = 'flv'
  1073. # Rewrite valid but non-extractable URLs as
  1074. # extractable English language /watch/ URLs
  1075. if re.match(self._VPAGE_URL, url) is None:
  1076. request = urllib2.Request(url)
  1077. try:
  1078. webpage = urllib2.urlopen(request).read()
  1079. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1080. self._downloader.trouble(u'ERROR: Unable to retrieve video webpage: %s' % str(err))
  1081. return
  1082. mobj = re.search(r'\("id", "([0-9]+)"\);', webpage)
  1083. if mobj is None:
  1084. self._downloader.trouble(u'ERROR: Unable to extract id field')
  1085. return
  1086. yahoo_id = mobj.group(1)
  1087. mobj = re.search(r'\("vid", "([0-9]+)"\);', webpage)
  1088. if mobj is None:
  1089. self._downloader.trouble(u'ERROR: Unable to extract vid field')
  1090. return
  1091. yahoo_vid = mobj.group(1)
  1092. url = 'http://video.yahoo.com/watch/%s/%s' % (yahoo_vid, yahoo_id)
  1093. return self._real_extract(url)
  1094. # Retrieve video webpage to extract further information
  1095. request = urllib2.Request(url)
  1096. try:
  1097. self.report_download_webpage(video_id)
  1098. webpage = urllib2.urlopen(request).read()
  1099. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1100. self._downloader.trouble(u'ERROR: Unable to retrieve video webpage: %s' % str(err))
  1101. return
  1102. # Extract uploader and title from webpage
  1103. self.report_extraction(video_id)
  1104. mobj = re.search(r'<meta name="title" content="(.*)" />', webpage)
  1105. if mobj is None:
  1106. self._downloader.trouble(u'ERROR: unable to extract video title')
  1107. return
  1108. video_title = mobj.group(1).decode('utf-8')
  1109. simple_title = re.sub(ur'(?u)([^%s]+)' % simple_title_chars, ur'_', video_title)
  1110. mobj = re.search(r'<h2 class="ti-5"><a href="http://video\.yahoo\.com/(people|profile)/[0-9]+" beacon=".*">(.*)</a></h2>', webpage)
  1111. if mobj is None:
  1112. self._downloader.trouble(u'ERROR: unable to extract video uploader')
  1113. return
  1114. video_uploader = mobj.group(1).decode('utf-8')
  1115. # Extract video thumbnail
  1116. mobj = re.search(r'<link rel="image_src" href="(.*)" />', webpage)
  1117. if mobj is None:
  1118. self._downloader.trouble(u'ERROR: unable to extract video thumbnail')
  1119. return
  1120. video_thumbnail = mobj.group(1).decode('utf-8')
  1121. # Extract video description
  1122. mobj = re.search(r'<meta name="description" content="(.*)" />', webpage)
  1123. if mobj is None:
  1124. self._downloader.trouble(u'ERROR: unable to extract video description')
  1125. return
  1126. video_description = mobj.group(1).decode('utf-8')
  1127. if not video_description: video_description = 'No description available.'
  1128. # Extract video height and width
  1129. mobj = re.search(r'<meta name="video_height" content="([0-9]+)" />', webpage)
  1130. if mobj is None:
  1131. self._downloader.trouble(u'ERROR: unable to extract video height')
  1132. return
  1133. yv_video_height = mobj.group(1)
  1134. mobj = re.search(r'<meta name="video_width" content="([0-9]+)" />', webpage)
  1135. if mobj is None:
  1136. self._downloader.trouble(u'ERROR: unable to extract video width')
  1137. return
  1138. yv_video_width = mobj.group(1)
  1139. # Retrieve video playlist to extract media URL
  1140. # I'm not completely sure what all these options are, but we
  1141. # seem to need most of them, otherwise the server sends a 401.
  1142. yv_lg = 'R0xx6idZnW2zlrKP8xxAIR' # not sure what this represents
  1143. yv_bitrate = '700' # according to Wikipedia this is hard-coded
  1144. request = urllib2.Request('http://cosmos.bcst.yahoo.com/up/yep/process/getPlaylistFOP.php?node_id=' + video_id +
  1145. '&tech=flash&mode=playlist&lg=' + yv_lg + '&bitrate=' + yv_bitrate + '&vidH=' + yv_video_height +
  1146. '&vidW=' + yv_video_width + '&swf=as3&rd=video.yahoo.com&tk=null&adsupported=v1,v2,&eventid=1301797')
  1147. try:
  1148. self.report_download_webpage(video_id)
  1149. webpage = urllib2.urlopen(request).read()
  1150. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1151. self._downloader.trouble(u'ERROR: Unable to retrieve video webpage: %s' % str(err))
  1152. return
  1153. # Extract media URL from playlist XML
  1154. mobj = re.search(r'<STREAM APP="(http://.*)" FULLPATH="/?(/.*\.flv\?[^"]*)"', webpage)
  1155. if mobj is None:
  1156. self._downloader.trouble(u'ERROR: Unable to extract media URL')
  1157. return
  1158. video_url = urllib.unquote(mobj.group(1) + mobj.group(2)).decode('utf-8')
  1159. video_url = re.sub(r'(?u)&(.+?);', htmlentity_transform, video_url)
  1160. try:
  1161. # Process video information
  1162. self._downloader.process_info({
  1163. 'id': video_id.decode('utf-8'),
  1164. 'url': video_url,
  1165. 'uploader': video_uploader,
  1166. 'title': video_title,
  1167. 'stitle': simple_title,
  1168. 'ext': video_extension.decode('utf-8'),
  1169. 'thumbnail': video_thumbnail.decode('utf-8'),
  1170. 'description': video_description,
  1171. 'thumbnail': video_thumbnail,
  1172. 'description': video_description,
  1173. })
  1174. except UnavailableFormatError:
  1175. self._downloader.trouble(u'ERROR: format not available for video')
  1176. class GenericIE(InfoExtractor):
  1177. """Generic last-resort information extractor."""
  1178. def __init__(self, downloader=None):
  1179. InfoExtractor.__init__(self, downloader)
  1180. @staticmethod
  1181. def suitable(url):
  1182. return True
  1183. def report_download_webpage(self, video_id):
  1184. """Report webpage download."""
  1185. self._downloader.to_stdout(u'WARNING: Falling back on generic information extractor.')
  1186. self._downloader.to_stdout(u'[generic] %s: Downloading webpage' % video_id)
  1187. def report_extraction(self, video_id):
  1188. """Report information extraction."""
  1189. self._downloader.to_stdout(u'[generic] %s: Extracting information' % video_id)
  1190. def _real_initialize(self):
  1191. return
  1192. def _real_extract(self, url):
  1193. video_id = url.split('/')[-1]
  1194. request = urllib2.Request(url)
  1195. try:
  1196. self.report_download_webpage(video_id)
  1197. webpage = urllib2.urlopen(request).read()
  1198. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1199. self._downloader.trouble(u'ERROR: Unable to retrieve video webpage: %s' % str(err))
  1200. return
  1201. except ValueError, err:
  1202. # since this is the last-resort InfoExtractor, if
  1203. # this error is thrown, it'll be thrown here
  1204. self._downloader.trouble(u'ERROR: Invalid URL: %s' % url)
  1205. return
  1206. # Start with something easy: JW Player in SWFObject
  1207. mobj = re.search(r'flashvars: [\'"](?:.*&)?file=(http[^\'"&]*)', webpage)
  1208. if mobj is None:
  1209. # Broaden the search a little bit
  1210. mobj = re.search(r'[^A-Za-z0-9]?(?:file|source)=(http[^\'"&]*)', webpage)
  1211. if mobj is None:
  1212. self._downloader.trouble(u'ERROR: Invalid URL: %s' % url)
  1213. return
  1214. # It's possible that one of the regexes
  1215. # matched, but returned an empty group:
  1216. if mobj.group(1) is None:
  1217. self._downloader.trouble(u'ERROR: Invalid URL: %s' % url)
  1218. return
  1219. video_url = urllib.unquote(mobj.group(1))
  1220. video_id = os.path.basename(video_url)
  1221. # here's a fun little line of code for you:
  1222. video_extension = os.path.splitext(video_id)[1][1:]
  1223. video_id = os.path.splitext(video_id)[0]
  1224. # it's tempting to parse this further, but you would
  1225. # have to take into account all the variations like
  1226. # Video Title - Site Name
  1227. # Site Name | Video Title
  1228. # Video Title - Tagline | Site Name
  1229. # and so on and so forth; it's just not practical
  1230. mobj = re.search(r'<title>(.*)</title>', webpage)
  1231. if mobj is None:
  1232. self._downloader.trouble(u'ERROR: unable to extract title')
  1233. return
  1234. video_title = mobj.group(1).decode('utf-8')
  1235. video_title = sanitize_title(video_title)
  1236. simple_title = re.sub(ur'(?u)([^%s]+)' % simple_title_chars, ur'_', video_title)
  1237. # video uploader is domain name
  1238. mobj = re.match(r'(?:https?://)?([^/]*)/.*', url)
  1239. if mobj is None:
  1240. self._downloader.trouble(u'ERROR: unable to extract title')
  1241. return
  1242. video_uploader = mobj.group(1).decode('utf-8')
  1243. try:
  1244. # Process video information
  1245. self._downloader.process_info({
  1246. 'id': video_id.decode('utf-8'),
  1247. 'url': video_url.decode('utf-8'),
  1248. 'uploader': video_uploader,
  1249. 'title': video_title,
  1250. 'stitle': simple_title,
  1251. 'ext': video_extension.decode('utf-8'),
  1252. 'format': u'NA',
  1253. })
  1254. except UnavailableFormatError:
  1255. self._downloader.trouble(u'ERROR: format not available for video')
  1256. class YoutubeSearchIE(InfoExtractor):
  1257. """Information Extractor for YouTube search queries."""
  1258. _VALID_QUERY = r'ytsearch(\d+|all)?:[\s\S]+'
  1259. _TEMPLATE_URL = 'http://www.youtube.com/results?search_query=%s&page=%s&gl=US&hl=en'
  1260. _VIDEO_INDICATOR = r'href="/watch\?v=.+?"'
  1261. _MORE_PAGES_INDICATOR = r'(?m)>\s*Next\s*</a>'
  1262. _youtube_ie = None
  1263. _max_youtube_results = 1000
  1264. def __init__(self, youtube_ie, downloader=None):
  1265. InfoExtractor.__init__(self, downloader)
  1266. self._youtube_ie = youtube_ie
  1267. @staticmethod
  1268. def suitable(url):
  1269. return (re.match(YoutubeSearchIE._VALID_QUERY, url) is not None)
  1270. def report_download_page(self, query, pagenum):
  1271. """Report attempt to download playlist page with given number."""
  1272. query = query.decode(preferredencoding())
  1273. self._downloader.to_stdout(u'[youtube] query "%s": Downloading page %s' % (query, pagenum))
  1274. def _real_initialize(self):
  1275. self._youtube_ie.initialize()
  1276. def _real_extract(self, query):
  1277. mobj = re.match(self._VALID_QUERY, query)
  1278. if mobj is None:
  1279. self._downloader.trouble(u'ERROR: invalid search query "%s"' % query)
  1280. return
  1281. prefix, query = query.split(':')
  1282. prefix = prefix[8:]
  1283. query = query.encode('utf-8')
  1284. if prefix == '':
  1285. self._download_n_results(query, 1)
  1286. return
  1287. elif prefix == 'all':
  1288. self._download_n_results(query, self._max_youtube_results)
  1289. return
  1290. else:
  1291. try:
  1292. n = long(prefix)
  1293. if n <= 0:
  1294. self._downloader.trouble(u'ERROR: invalid download number %s for query "%s"' % (n, query))
  1295. return
  1296. elif n > self._max_youtube_results:
  1297. self._downloader.to_stderr(u'WARNING: ytsearch returns max %i results (you requested %i)' % (self._max_youtube_results, n))
  1298. n = self._max_youtube_results
  1299. self._download_n_results(query, n)
  1300. return
  1301. except ValueError: # parsing prefix as integer fails
  1302. self._download_n_results(query, 1)
  1303. return
  1304. def _download_n_results(self, query, n):
  1305. """Downloads a specified number of results for a query"""
  1306. video_ids = []
  1307. already_seen = set()
  1308. pagenum = 1
  1309. while True:
  1310. self.report_download_page(query, pagenum)
  1311. result_url = self._TEMPLATE_URL % (urllib.quote_plus(query), pagenum)
  1312. request = urllib2.Request(result_url, None, std_headers)
  1313. try:
  1314. page = urllib2.urlopen(request).read()
  1315. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1316. self._downloader.trouble(u'ERROR: unable to download webpage: %s' % str(err))
  1317. return
  1318. # Extract video identifiers
  1319. for mobj in re.finditer(self._VIDEO_INDICATOR, page):
  1320. video_id = page[mobj.span()[0]:mobj.span()[1]].split('=')[2][:-1]
  1321. if video_id not in already_seen:
  1322. video_ids.append(video_id)
  1323. already_seen.add(video_id)
  1324. if len(video_ids) == n:
  1325. # Specified n videos reached
  1326. for id in video_ids:
  1327. self._youtube_ie.extract('http://www.youtube.com/watch?v=%s' % id)
  1328. return
  1329. if re.search(self._MORE_PAGES_INDICATOR, page) is None:
  1330. for id in video_ids:
  1331. self._youtube_ie.extract('http://www.youtube.com/watch?v=%s' % id)
  1332. return
  1333. pagenum = pagenum + 1
  1334. class GoogleSearchIE(InfoExtractor):
  1335. """Information Extractor for Google Video search queries."""
  1336. _VALID_QUERY = r'gvsearch(\d+|all)?:[\s\S]+'
  1337. _TEMPLATE_URL = 'http://video.google.com/videosearch?q=%s+site:video.google.com&start=%s&hl=en'
  1338. _VIDEO_INDICATOR = r'videoplay\?docid=([^\&>]+)\&'
  1339. _MORE_PAGES_INDICATOR = r'<span>Next</span>'
  1340. _google_ie = None
  1341. _max_google_results = 1000
  1342. def __init__(self, google_ie, downloader=None):
  1343. InfoExtractor.__init__(self, downloader)
  1344. self._google_ie = google_ie
  1345. @staticmethod
  1346. def suitable(url):
  1347. return (re.match(GoogleSearchIE._VALID_QUERY, url) is not None)
  1348. def report_download_page(self, query, pagenum):
  1349. """Report attempt to download playlist page with given number."""
  1350. query = query.decode(preferredencoding())
  1351. self._downloader.to_stdout(u'[video.google] query "%s": Downloading page %s' % (query, pagenum))
  1352. def _real_initialize(self):
  1353. self._google_ie.initialize()
  1354. def _real_extract(self, query):
  1355. mobj = re.match(self._VALID_QUERY, query)
  1356. if mobj is None:
  1357. self._downloader.trouble(u'ERROR: invalid search query "%s"' % query)
  1358. return
  1359. prefix, query = query.split(':')
  1360. prefix = prefix[8:]
  1361. query = query.encode('utf-8')
  1362. if prefix == '':
  1363. self._download_n_results(query, 1)
  1364. return
  1365. elif prefix == 'all':
  1366. self._download_n_results(query, self._max_google_results)
  1367. return
  1368. else:
  1369. try:
  1370. n = long(prefix)
  1371. if n <= 0:
  1372. self._downloader.trouble(u'ERROR: invalid download number %s for query "%s"' % (n, query))
  1373. return
  1374. elif n > self._max_google_results:
  1375. self._downloader.to_stderr(u'WARNING: gvsearch returns max %i results (you requested %i)' % (self._max_google_results, n))
  1376. n = self._max_google_results
  1377. self._download_n_results(query, n)
  1378. return
  1379. except ValueError: # parsing prefix as integer fails
  1380. self._download_n_results(query, 1)
  1381. return
  1382. def _download_n_results(self, query, n):
  1383. """Downloads a specified number of results for a query"""
  1384. video_ids = []
  1385. already_seen = set()
  1386. pagenum = 1
  1387. while True:
  1388. self.report_download_page(query, pagenum)
  1389. result_url = self._TEMPLATE_URL % (urllib.quote_plus(query), pagenum)
  1390. request = urllib2.Request(result_url, None, std_headers)
  1391. try:
  1392. page = urllib2.urlopen(request).read()
  1393. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1394. self._downloader.trouble(u'ERROR: unable to download webpage: %s' % str(err))
  1395. return
  1396. # Extract video identifiers
  1397. for mobj in re.finditer(self._VIDEO_INDICATOR, page):
  1398. video_id = mobj.group(1)
  1399. if video_id not in already_seen:
  1400. video_ids.append(video_id)
  1401. already_seen.add(video_id)
  1402. if len(video_ids) == n:
  1403. # Specified n videos reached
  1404. for id in video_ids:
  1405. self._google_ie.extract('http://video.google.com/videoplay?docid=%s' % id)
  1406. return
  1407. if re.search(self._MORE_PAGES_INDICATOR, page) is None:
  1408. for id in video_ids:
  1409. self._google_ie.extract('http://video.google.com/videoplay?docid=%s' % id)
  1410. return
  1411. pagenum = pagenum + 1
  1412. class YahooSearchIE(InfoExtractor):
  1413. """Information Extractor for Yahoo! Video search queries."""
  1414. _VALID_QUERY = r'yvsearch(\d+|all)?:[\s\S]+'
  1415. _TEMPLATE_URL = 'http://video.yahoo.com/search/?p=%s&o=%s'
  1416. _VIDEO_INDICATOR = r'href="http://video\.yahoo\.com/watch/([0-9]+/[0-9]+)"'
  1417. _MORE_PAGES_INDICATOR = r'\s*Next'
  1418. _yahoo_ie = None
  1419. _max_yahoo_results = 1000
  1420. def __init__(self, yahoo_ie, downloader=None):
  1421. InfoExtractor.__init__(self, downloader)
  1422. self._yahoo_ie = yahoo_ie
  1423. @staticmethod
  1424. def suitable(url):
  1425. return (re.match(YahooSearchIE._VALID_QUERY, url) is not None)
  1426. def report_download_page(self, query, pagenum):
  1427. """Report attempt to download playlist page with given number."""
  1428. query = query.decode(preferredencoding())
  1429. self._downloader.to_stdout(u'[video.yahoo] query "%s": Downloading page %s' % (query, pagenum))
  1430. def _real_initialize(self):
  1431. self._yahoo_ie.initialize()
  1432. def _real_extract(self, query):
  1433. mobj = re.match(self._VALID_QUERY, query)
  1434. if mobj is None:
  1435. self._downloader.trouble(u'ERROR: invalid search query "%s"' % query)
  1436. return
  1437. prefix, query = query.split(':')
  1438. prefix = prefix[8:]
  1439. query = query.encode('utf-8')
  1440. if prefix == '':
  1441. self._download_n_results(query, 1)
  1442. return
  1443. elif prefix == 'all':
  1444. self._download_n_results(query, self._max_yahoo_results)
  1445. return
  1446. else:
  1447. try:
  1448. n = long(prefix)
  1449. if n <= 0:
  1450. self._downloader.trouble(u'ERROR: invalid download number %s for query "%s"' % (n, query))
  1451. return
  1452. elif n > self._max_yahoo_results:
  1453. self._downloader.to_stderr(u'WARNING: yvsearch returns max %i results (you requested %i)' % (self._max_yahoo_results, n))
  1454. n = self._max_yahoo_results
  1455. self._download_n_results(query, n)
  1456. return
  1457. except ValueError: # parsing prefix as integer fails
  1458. self._download_n_results(query, 1)
  1459. return
  1460. def _download_n_results(self, query, n):
  1461. """Downloads a specified number of results for a query"""
  1462. video_ids = []
  1463. already_seen = set()
  1464. pagenum = 1
  1465. while True:
  1466. self.report_download_page(query, pagenum)
  1467. result_url = self._TEMPLATE_URL % (urllib.quote_plus(query), pagenum)
  1468. request = urllib2.Request(result_url, None, std_headers)
  1469. try:
  1470. page = urllib2.urlopen(request).read()
  1471. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1472. self._downloader.trouble(u'ERROR: unable to download webpage: %s' % str(err))
  1473. return
  1474. # Extract video identifiers
  1475. for mobj in re.finditer(self._VIDEO_INDICATOR, page):
  1476. video_id = mobj.group(1)
  1477. if video_id not in already_seen:
  1478. video_ids.append(video_id)
  1479. already_seen.add(video_id)
  1480. if len(video_ids) == n:
  1481. # Specified n videos reached
  1482. for id in video_ids:
  1483. self._yahoo_ie.extract('http://video.yahoo.com/watch/%s' % id)
  1484. return
  1485. if re.search(self._MORE_PAGES_INDICATOR, page) is None:
  1486. for id in video_ids:
  1487. self._yahoo_ie.extract('http://video.yahoo.com/watch/%s' % id)
  1488. return
  1489. pagenum = pagenum + 1
  1490. class YoutubePlaylistIE(InfoExtractor):
  1491. """Information Extractor for YouTube playlists."""
  1492. _VALID_URL = r'(?:http://)?(?:\w+\.)?youtube.com/(?:(?:view_play_list|my_playlists)\?.*?p=|user/.*?/user/)([^&]+).*'
  1493. _TEMPLATE_URL = 'http://www.youtube.com/view_play_list?p=%s&page=%s&gl=US&hl=en'
  1494. _VIDEO_INDICATOR = r'/watch\?v=(.+?)&'
  1495. _MORE_PAGES_INDICATOR = r'(?m)>\s*Next\s*</a>'
  1496. _youtube_ie = None
  1497. def __init__(self, youtube_ie, downloader=None):
  1498. InfoExtractor.__init__(self, downloader)
  1499. self._youtube_ie = youtube_ie
  1500. @staticmethod
  1501. def suitable(url):
  1502. return (re.match(YoutubePlaylistIE._VALID_URL, url) is not None)
  1503. def report_download_page(self, playlist_id, pagenum):
  1504. """Report attempt to download playlist page with given number."""
  1505. self._downloader.to_stdout(u'[youtube] PL %s: Downloading page #%s' % (playlist_id, pagenum))
  1506. def _real_initialize(self):
  1507. self._youtube_ie.initialize()
  1508. def _real_extract(self, url):
  1509. # Extract playlist id
  1510. mobj = re.match(self._VALID_URL, url)
  1511. if mobj is None:
  1512. self._downloader.trouble(u'ERROR: invalid url: %s' % url)
  1513. return
  1514. # Download playlist pages
  1515. playlist_id = mobj.group(1)
  1516. video_ids = []
  1517. pagenum = 1
  1518. while True:
  1519. self.report_download_page(playlist_id, pagenum)
  1520. request = urllib2.Request(self._TEMPLATE_URL % (playlist_id, pagenum), None, std_headers)
  1521. try:
  1522. page = urllib2.urlopen(request).read()
  1523. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1524. self._downloader.trouble(u'ERROR: unable to download webpage: %s' % str(err))
  1525. return
  1526. # Extract video identifiers
  1527. ids_in_page = []
  1528. for mobj in re.finditer(self._VIDEO_INDICATOR, page):
  1529. if mobj.group(1) not in ids_in_page:
  1530. ids_in_page.append(mobj.group(1))
  1531. video_ids.extend(ids_in_page)
  1532. if re.search(self._MORE_PAGES_INDICATOR, page) is None:
  1533. break
  1534. pagenum = pagenum + 1
  1535. for id in video_ids:
  1536. self._youtube_ie.extract('http://www.youtube.com/watch?v=%s' % id)
  1537. return
  1538. class YoutubeUserIE(InfoExtractor):
  1539. """Information Extractor for YouTube users."""
  1540. _VALID_URL = r'(?:http://)?(?:\w+\.)?youtube.com/user/(.*)'
  1541. _TEMPLATE_URL = 'http://gdata.youtube.com/feeds/api/users/%s'
  1542. _VIDEO_INDICATOR = r'http://gdata.youtube.com/feeds/api/videos/(.*)' # XXX Fix this.
  1543. _youtube_ie = None
  1544. def __init__(self, youtube_ie, downloader=None):
  1545. InfoExtractor.__init__(self, downloader)
  1546. self._youtube_ie = youtube_ie
  1547. @staticmethod
  1548. def suitable(url):
  1549. return (re.match(YoutubeUserIE._VALID_URL, url) is not None)
  1550. def report_download_page(self, username):
  1551. """Report attempt to download user page."""
  1552. self._downloader.to_stdout(u'[youtube] user %s: Downloading page ' % (username))
  1553. def _real_initialize(self):
  1554. self._youtube_ie.initialize()
  1555. def _real_extract(self, url):
  1556. # Extract username
  1557. mobj = re.match(self._VALID_URL, url)
  1558. if mobj is None:
  1559. self._downloader.trouble(u'ERROR: invalid url: %s' % url)
  1560. return
  1561. # Download user page
  1562. username = mobj.group(1)
  1563. video_ids = []
  1564. pagenum = 1
  1565. self.report_download_page(username)
  1566. request = urllib2.Request(self._TEMPLATE_URL % (username), None, std_headers)
  1567. try:
  1568. page = urllib2.urlopen(request).read()
  1569. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1570. self._downloader.trouble(u'ERROR: unable to download webpage: %s' % str(err))
  1571. return
  1572. # Extract video identifiers
  1573. ids_in_page = []
  1574. for mobj in re.finditer(self._VIDEO_INDICATOR, page):
  1575. if mobj.group(1) not in ids_in_page:
  1576. ids_in_page.append(mobj.group(1))
  1577. video_ids.extend(ids_in_page)
  1578. for id in video_ids:
  1579. self._youtube_ie.extract('http://www.youtube.com/watch?v=%s' % id)
  1580. return
  1581. class PostProcessor(object):
  1582. """Post Processor class.
  1583. PostProcessor objects can be added to downloaders with their
  1584. add_post_processor() method. When the downloader has finished a
  1585. successful download, it will take its internal chain of PostProcessors
  1586. and start calling the run() method on each one of them, first with
  1587. an initial argument and then with the returned value of the previous
  1588. PostProcessor.
  1589. The chain will be stopped if one of them ever returns None or the end
  1590. of the chain is reached.
  1591. PostProcessor objects follow a "mutual registration" process similar
  1592. to InfoExtractor objects.
  1593. """
  1594. _downloader = None
  1595. def __init__(self, downloader=None):
  1596. self._downloader = downloader
  1597. def set_downloader(self, downloader):
  1598. """Sets the downloader for this PP."""
  1599. self._downloader = downloader
  1600. def run(self, information):
  1601. """Run the PostProcessor.
  1602. The "information" argument is a dictionary like the ones
  1603. composed by InfoExtractors. The only difference is that this
  1604. one has an extra field called "filepath" that points to the
  1605. downloaded file.
  1606. When this method returns None, the postprocessing chain is
  1607. stopped. However, this method may return an information
  1608. dictionary that will be passed to the next postprocessing
  1609. object in the chain. It can be the one it received after
  1610. changing some fields.
  1611. In addition, this method may raise a PostProcessingError
  1612. exception that will be taken into account by the downloader
  1613. it was called from.
  1614. """
  1615. return information # by default, do nothing
  1616. ### MAIN PROGRAM ###
  1617. if __name__ == '__main__':
  1618. try:
  1619. # Modules needed only when running the main program
  1620. import getpass
  1621. import optparse
  1622. # Function to update the program file with the latest version from bitbucket.org
  1623. def update_self(downloader, filename):
  1624. # Note: downloader only used for options
  1625. if not os.access (filename, os.W_OK):
  1626. sys.exit('ERROR: no write permissions on %s' % filename)
  1627. downloader.to_stdout('Updating to latest stable version...')
  1628. latest_url = 'http://bitbucket.org/rg3/youtube-dl/raw/tip/LATEST_VERSION'
  1629. latest_version = urllib.urlopen(latest_url).read().strip()
  1630. prog_url = 'http://bitbucket.org/rg3/youtube-dl/raw/%s/youtube-dl' % latest_version
  1631. newcontent = urllib.urlopen(prog_url).read()
  1632. stream = open(filename, 'w')
  1633. stream.write(newcontent)
  1634. stream.close()
  1635. downloader.to_stdout('Updated to version %s' % latest_version)
  1636. # General configuration
  1637. urllib2.install_opener(urllib2.build_opener(urllib2.ProxyHandler()))
  1638. urllib2.install_opener(urllib2.build_opener(urllib2.HTTPCookieProcessor()))
  1639. socket.setdefaulttimeout(300) # 5 minutes should be enough (famous last words)
  1640. # Parse command line
  1641. parser = optparse.OptionParser(
  1642. usage='Usage: %prog [options] url...',
  1643. version='2010.04.04',
  1644. conflict_handler='resolve',
  1645. )
  1646. parser.add_option('-h', '--help',
  1647. action='help', help='print this help text and exit')
  1648. parser.add_option('-v', '--version',
  1649. action='version', help='print program version and exit')
  1650. parser.add_option('-U', '--update',
  1651. action='store_true', dest='update_self', help='update this program to latest stable version')
  1652. parser.add_option('-i', '--ignore-errors',
  1653. action='store_true', dest='ignoreerrors', help='continue on download errors', default=False)
  1654. parser.add_option('-r', '--rate-limit',
  1655. dest='ratelimit', metavar='L', help='download rate limit (e.g. 50k or 44.6m)')
  1656. authentication = optparse.OptionGroup(parser, 'Authentication Options')
  1657. authentication.add_option('-u', '--username',
  1658. dest='username', metavar='UN', help='account username')
  1659. authentication.add_option('-p', '--password',
  1660. dest='password', metavar='PW', help='account password')
  1661. authentication.add_option('-n', '--netrc',
  1662. action='store_true', dest='usenetrc', help='use .netrc authentication data', default=False)
  1663. parser.add_option_group(authentication)
  1664. video_format = optparse.OptionGroup(parser, 'Video Format Options')
  1665. video_format.add_option('-f', '--format',
  1666. action='store', dest='format', metavar='FMT', help='video format code')
  1667. video_format.add_option('-b', '--best-quality',
  1668. action='store_const', dest='format', help='download the best quality video possible', const='0')
  1669. video_format.add_option('-m', '--mobile-version',
  1670. action='store_const', dest='format', help='alias for -f 17', const='17')
  1671. video_format.add_option('-d', '--high-def',
  1672. action='store_const', dest='format', help='alias for -f 22', const='22')
  1673. video_format.add_option('--all-formats',
  1674. action='store_const', dest='format', help='download all available video formats', const='-1')
  1675. parser.add_option_group(video_format)
  1676. verbosity = optparse.OptionGroup(parser, 'Verbosity / Simulation Options')
  1677. verbosity.add_option('-q', '--quiet',
  1678. action='store_true', dest='quiet', help='activates quiet mode', default=False)
  1679. verbosity.add_option('-s', '--simulate',
  1680. action='store_true', dest='simulate', help='do not download video', default=False)
  1681. verbosity.add_option('-g', '--get-url',
  1682. action='store_true', dest='geturl', help='simulate, quiet but print URL', default=False)
  1683. verbosity.add_option('-e', '--get-title',
  1684. action='store_true', dest='gettitle', help='simulate, quiet but print title', default=False)
  1685. verbosity.add_option('--get-thumbnail',
  1686. action='store_true', dest='getthumbnail', help='simulate, quiet but print thumbnail URL', default=False)
  1687. verbosity.add_option('--get-description',
  1688. action='store_true', dest='getdescription', help='simulate, quiet but print video description', default=False)
  1689. verbosity.add_option('--no-progress',
  1690. action='store_true', dest='noprogress', help='do not print progress bar', default=False)
  1691. parser.add_option_group(verbosity)
  1692. filesystem = optparse.OptionGroup(parser, 'Filesystem Options')
  1693. filesystem.add_option('-t', '--title',
  1694. action='store_true', dest='usetitle', help='use title in file name', default=False)
  1695. filesystem.add_option('-l', '--literal',
  1696. action='store_true', dest='useliteral', help='use literal title in file name', default=False)
  1697. filesystem.add_option('-o', '--output',
  1698. dest='outtmpl', metavar='TPL', help='output filename template')
  1699. filesystem.add_option('-a', '--batch-file',
  1700. dest='batchfile', metavar='F', help='file containing URLs to download')
  1701. filesystem.add_option('-w', '--no-overwrites',
  1702. action='store_true', dest='nooverwrites', help='do not overwrite files', default=False)
  1703. filesystem.add_option('-c', '--continue',
  1704. action='store_true', dest='continue_dl', help='resume partially downloaded files', default=False)
  1705. parser.add_option_group(filesystem)
  1706. (opts, args) = parser.parse_args()
  1707. # Batch file verification
  1708. batchurls = []
  1709. if opts.batchfile is not None:
  1710. try:
  1711. batchurls = open(opts.batchfile, 'r').readlines()
  1712. batchurls = [x.strip() for x in batchurls]
  1713. batchurls = [x for x in batchurls if len(x) > 0]
  1714. except IOError:
  1715. sys.exit(u'ERROR: batch file could not be read')
  1716. all_urls = batchurls + args
  1717. # Conflicting, missing and erroneous options
  1718. if opts.usenetrc and (opts.username is not None or opts.password is not None):
  1719. parser.error(u'using .netrc conflicts with giving username/password')
  1720. if opts.password is not None and opts.username is None:
  1721. parser.error(u'account username missing')
  1722. if opts.outtmpl is not None and (opts.useliteral or opts.usetitle):
  1723. parser.error(u'using output template conflicts with using title or literal title')
  1724. if opts.usetitle and opts.useliteral:
  1725. parser.error(u'using title conflicts with using literal title')
  1726. if opts.username is not None and opts.password is None:
  1727. opts.password = getpass.getpass(u'Type account password and press return:')
  1728. if opts.ratelimit is not None:
  1729. numeric_limit = FileDownloader.parse_bytes(opts.ratelimit)
  1730. if numeric_limit is None:
  1731. parser.error(u'invalid rate limit specified')
  1732. opts.ratelimit = numeric_limit
  1733. # Information extractors
  1734. youtube_ie = YoutubeIE()
  1735. metacafe_ie = MetacafeIE(youtube_ie)
  1736. youtube_pl_ie = YoutubePlaylistIE(youtube_ie)
  1737. youtube_user_ie = YoutubeUserIE(youtube_ie)
  1738. youtube_search_ie = YoutubeSearchIE(youtube_ie)
  1739. google_ie = GoogleIE()
  1740. google_search_ie = GoogleSearchIE(google_ie)
  1741. photobucket_ie = PhotobucketIE()
  1742. yahoo_ie = YahooIE()
  1743. yahoo_search_ie = YahooSearchIE(yahoo_ie)
  1744. generic_ie = GenericIE()
  1745. # File downloader
  1746. fd = FileDownloader({
  1747. 'usenetrc': opts.usenetrc,
  1748. 'username': opts.username,
  1749. 'password': opts.password,
  1750. 'quiet': (opts.quiet or opts.geturl or opts.gettitle or opts.getthumbnail or opts.getdescription),
  1751. 'forceurl': opts.geturl,
  1752. 'forcetitle': opts.gettitle,
  1753. 'forcethumbnail': opts.getthumbnail,
  1754. 'forcedescription': opts.getdescription,
  1755. 'simulate': (opts.simulate or opts.geturl or opts.gettitle or opts.getthumbnail or opts.getdescription),
  1756. 'format': opts.format,
  1757. 'outtmpl': ((opts.outtmpl is not None and opts.outtmpl.decode(preferredencoding()))
  1758. or (opts.format == '-1' and opts.usetitle and u'%(stitle)s-%(id)s-%(format)s.%(ext)s')
  1759. or (opts.format == '-1' and opts.useliteral and u'%(title)s-%(id)s-%(format)s.%(ext)s')
  1760. or (opts.format == '-1' and u'%(id)s-%(format)s.%(ext)s')
  1761. or (opts.usetitle and u'%(stitle)s-%(id)s.%(ext)s')
  1762. or (opts.useliteral and u'%(title)s-%(id)s.%(ext)s')
  1763. or u'%(id)s.%(ext)s'),
  1764. 'ignoreerrors': opts.ignoreerrors,
  1765. 'ratelimit': opts.ratelimit,
  1766. 'nooverwrites': opts.nooverwrites,
  1767. 'continuedl': opts.continue_dl,
  1768. 'noprogress': opts.noprogress,
  1769. })
  1770. fd.add_info_extractor(youtube_search_ie)
  1771. fd.add_info_extractor(youtube_pl_ie)
  1772. fd.add_info_extractor(youtube_user_ie)
  1773. fd.add_info_extractor(metacafe_ie)
  1774. fd.add_info_extractor(youtube_ie)
  1775. fd.add_info_extractor(google_ie)
  1776. fd.add_info_extractor(google_search_ie)
  1777. fd.add_info_extractor(photobucket_ie)
  1778. fd.add_info_extractor(yahoo_ie)
  1779. fd.add_info_extractor(yahoo_search_ie)
  1780. # This must come last since it's the
  1781. # fallback if none of the others work
  1782. fd.add_info_extractor(generic_ie)
  1783. # Update version
  1784. if opts.update_self:
  1785. update_self(fd, sys.argv[0])
  1786. # Maybe do nothing
  1787. if len(all_urls) < 1:
  1788. if not opts.update_self:
  1789. parser.error(u'you must provide at least one URL')
  1790. else:
  1791. sys.exit()
  1792. retcode = fd.download(all_urls)
  1793. sys.exit(retcode)
  1794. except DownloadError:
  1795. sys.exit(1)
  1796. except SameFileError:
  1797. sys.exit(u'ERROR: fixed output name but more than one file to download')
  1798. except KeyboardInterrupt:
  1799. sys.exit(u'\nERROR: Interrupted by user')