youtube-dl 82 KB

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