youtube-dl 82 KB

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