youtube-dl 107 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # Author: Ricardo Garcia Gonzalez
  4. # Author: Danny Colligan
  5. # Author: Benjamin Johnson
  6. # Author: Vasyl' Vavrychuk
  7. # Author: Witold Baryluk
  8. # Author: Paweł Paprota
  9. # Author: Gergely Imreh
  10. # License: Public domain code
  11. from __future__ import with_statement
  12. import contextlib
  13. import cookielib
  14. import ctypes
  15. import datetime
  16. import email.utils
  17. import gzip
  18. import htmlentitydefs
  19. import httplib
  20. import locale
  21. import math
  22. import netrc
  23. import os
  24. import os.path
  25. import re
  26. import socket
  27. import string
  28. import subprocess
  29. import sys
  30. import time
  31. import urllib
  32. import urllib2
  33. import warnings
  34. import zlib
  35. try:
  36. import json
  37. except ImportError:
  38. warnings.warn('No JSON support (TODO: insert trivialjson here)')
  39. try:
  40. import cStringIO as StringIO
  41. except ImportError:
  42. import StringIO
  43. # parse_qs was moved from the cgi module to the urlparse module recently.
  44. try:
  45. from urlparse import parse_qs
  46. except ImportError:
  47. from cgi import parse_qs
  48. try:
  49. import lxml.etree
  50. except ImportError: # Python < 2.6
  51. pass # Handled below
  52. std_headers = {
  53. 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:2.0b11) Gecko/20100101 Firefox/4.0b11',
  54. 'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
  55. 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
  56. 'Accept-Encoding': 'gzip, deflate',
  57. 'Accept-Language': 'en-us,en;q=0.5',
  58. }
  59. simple_title_chars = string.ascii_letters.decode('ascii') + string.digits.decode('ascii')
  60. def preferredencoding():
  61. """Get preferred encoding.
  62. Returns the best encoding scheme for the system, based on
  63. locale.getpreferredencoding() and some further tweaks.
  64. """
  65. def yield_preferredencoding():
  66. try:
  67. pref = locale.getpreferredencoding()
  68. u'TEST'.encode(pref)
  69. except:
  70. pref = 'UTF-8'
  71. while True:
  72. yield pref
  73. return yield_preferredencoding().next()
  74. def htmlentity_transform(matchobj):
  75. """Transforms an HTML entity to a Unicode character.
  76. This function receives a match object and is intended to be used with
  77. the re.sub() function.
  78. """
  79. entity = matchobj.group(1)
  80. # Known non-numeric HTML entity
  81. if entity in htmlentitydefs.name2codepoint:
  82. return unichr(htmlentitydefs.name2codepoint[entity])
  83. # Unicode character
  84. mobj = re.match(ur'(?u)#(x?\d+)', entity)
  85. if mobj is not None:
  86. numstr = mobj.group(1)
  87. if numstr.startswith(u'x'):
  88. base = 16
  89. numstr = u'0%s' % numstr
  90. else:
  91. base = 10
  92. return unichr(long(numstr, base))
  93. # Unknown entity in name, return its literal representation
  94. return (u'&%s;' % entity)
  95. def sanitize_title(utitle):
  96. """Sanitizes a video title so it could be used as part of a filename."""
  97. utitle = re.sub(ur'(?u)&(.+?);', htmlentity_transform, utitle)
  98. return utitle.replace(unicode(os.sep), u'%')
  99. def sanitize_open(filename, open_mode):
  100. """Try to open the given filename, and slightly tweak it if this fails.
  101. Attempts to open the given filename. If this fails, it tries to change
  102. the filename slightly, step by step, until it's either able to open it
  103. or it fails and raises a final exception, like the standard open()
  104. function.
  105. It returns the tuple (stream, definitive_file_name).
  106. """
  107. try:
  108. if filename == u'-':
  109. if sys.platform == 'win32':
  110. import msvcrt
  111. msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
  112. return (sys.stdout, filename)
  113. stream = open(filename, open_mode)
  114. return (stream, filename)
  115. except (IOError, OSError), err:
  116. # In case of error, try to remove win32 forbidden chars
  117. filename = re.sub(ur'[/<>:"\|\?\*]', u'#', filename)
  118. # An exception here should be caught in the caller
  119. stream = open(filename, open_mode)
  120. return (stream, filename)
  121. def timeconvert(timestr):
  122. """Convert RFC 2822 defined time string into system timestamp"""
  123. timestamp = None
  124. timetuple = email.utils.parsedate_tz(timestr)
  125. if timetuple is not None:
  126. timestamp = email.utils.mktime_tz(timetuple)
  127. return timestamp
  128. class DownloadError(Exception):
  129. """Download Error exception.
  130. This exception may be thrown by FileDownloader objects if they are not
  131. configured to continue on errors. They will contain the appropriate
  132. error message.
  133. """
  134. pass
  135. class SameFileError(Exception):
  136. """Same File exception.
  137. This exception will be thrown by FileDownloader objects if they detect
  138. multiple files would have to be downloaded to the same file on disk.
  139. """
  140. pass
  141. class PostProcessingError(Exception):
  142. """Post Processing exception.
  143. This exception may be raised by PostProcessor's .run() method to
  144. indicate an error in the postprocessing task.
  145. """
  146. pass
  147. class UnavailableVideoError(Exception):
  148. """Unavailable Format exception.
  149. This exception will be thrown when a video is requested
  150. in a format that is not available for that video.
  151. """
  152. pass
  153. class ContentTooShortError(Exception):
  154. """Content Too Short exception.
  155. This exception may be raised by FileDownloader objects when a file they
  156. download is too small for what the server announced first, indicating
  157. the connection was probably interrupted.
  158. """
  159. # Both in bytes
  160. downloaded = None
  161. expected = None
  162. def __init__(self, downloaded, expected):
  163. self.downloaded = downloaded
  164. self.expected = expected
  165. class YoutubeDLHandler(urllib2.HTTPHandler):
  166. """Handler for HTTP requests and responses.
  167. This class, when installed with an OpenerDirector, automatically adds
  168. the standard headers to every HTTP request and handles gzipped and
  169. deflated responses from web servers. If compression is to be avoided in
  170. a particular request, the original request in the program code only has
  171. to include the HTTP header "Youtubedl-No-Compression", which will be
  172. removed before making the real request.
  173. Part of this code was copied from:
  174. http://techknack.net/python-urllib2-handlers/
  175. Andrew Rowls, the author of that code, agreed to release it to the
  176. public domain.
  177. """
  178. @staticmethod
  179. def deflate(data):
  180. try:
  181. return zlib.decompress(data, -zlib.MAX_WBITS)
  182. except zlib.error:
  183. return zlib.decompress(data)
  184. @staticmethod
  185. def addinfourl_wrapper(stream, headers, url, code):
  186. if hasattr(urllib2.addinfourl, 'getcode'):
  187. return urllib2.addinfourl(stream, headers, url, code)
  188. ret = urllib2.addinfourl(stream, headers, url)
  189. ret.code = code
  190. return ret
  191. def http_request(self, req):
  192. for h in std_headers:
  193. if h in req.headers:
  194. del req.headers[h]
  195. req.add_header(h, std_headers[h])
  196. if 'Youtubedl-no-compression' in req.headers:
  197. if 'Accept-encoding' in req.headers:
  198. del req.headers['Accept-encoding']
  199. del req.headers['Youtubedl-no-compression']
  200. return req
  201. def http_response(self, req, resp):
  202. old_resp = resp
  203. # gzip
  204. if resp.headers.get('Content-encoding', '') == 'gzip':
  205. gz = gzip.GzipFile(fileobj=StringIO.StringIO(resp.read()), mode='r')
  206. resp = self.addinfourl_wrapper(gz, old_resp.headers, old_resp.url, old_resp.code)
  207. resp.msg = old_resp.msg
  208. # deflate
  209. if resp.headers.get('Content-encoding', '') == 'deflate':
  210. gz = StringIO.StringIO(self.deflate(resp.read()))
  211. resp = self.addinfourl_wrapper(gz, old_resp.headers, old_resp.url, old_resp.code)
  212. resp.msg = old_resp.msg
  213. return resp
  214. class FileDownloader(object):
  215. """File Downloader class.
  216. File downloader objects are the ones responsible of downloading the
  217. actual video file and writing it to disk if the user has requested
  218. it, among some other tasks. In most cases there should be one per
  219. program. As, given a video URL, the downloader doesn't know how to
  220. extract all the needed information, task that InfoExtractors do, it
  221. has to pass the URL to one of them.
  222. For this, file downloader objects have a method that allows
  223. InfoExtractors to be registered in a given order. When it is passed
  224. a URL, the file downloader handles it to the first InfoExtractor it
  225. finds that reports being able to handle it. The InfoExtractor extracts
  226. all the information about the video or videos the URL refers to, and
  227. asks the FileDownloader to process the video information, possibly
  228. downloading the video.
  229. File downloaders accept a lot of parameters. In order not to saturate
  230. the object constructor with arguments, it receives a dictionary of
  231. options instead. These options are available through the params
  232. attribute for the InfoExtractors to use. The FileDownloader also
  233. registers itself as the downloader in charge for the InfoExtractors
  234. that are added to it, so this is a "mutual registration".
  235. Available options:
  236. username: Username for authentication purposes.
  237. password: Password for authentication purposes.
  238. usenetrc: Use netrc for authentication instead.
  239. quiet: Do not print messages to stdout.
  240. forceurl: Force printing final URL.
  241. forcetitle: Force printing title.
  242. forcethumbnail: Force printing thumbnail URL.
  243. forcedescription: Force printing description.
  244. forcefilename: Force printing final filename.
  245. simulate: Do not download the video files.
  246. format: Video format code.
  247. format_limit: Highest quality format to try.
  248. outtmpl: Template for output names.
  249. ignoreerrors: Do not stop on download errors.
  250. ratelimit: Download speed limit, in bytes/sec.
  251. nooverwrites: Prevent overwriting files.
  252. retries: Number of times to retry for HTTP error 5xx
  253. continuedl: Try to continue downloads if possible.
  254. noprogress: Do not print the progress bar.
  255. playliststart: Playlist item to start at.
  256. playlistend: Playlist item to end at.
  257. logtostderr: Log messages to stderr instead of stdout.
  258. consoletitle: Display progress in console window's titlebar.
  259. nopart: Do not use temporary .part files.
  260. updatetime: Use the Last-modified header to set output file timestamps.
  261. writedescription: Write the video description to a .description file
  262. """
  263. params = None
  264. _ies = []
  265. _pps = []
  266. _download_retcode = None
  267. _num_downloads = None
  268. _screen_file = None
  269. def __init__(self, params):
  270. """Create a FileDownloader object with the given options."""
  271. self._ies = []
  272. self._pps = []
  273. self._download_retcode = 0
  274. self._num_downloads = 0
  275. self._screen_file = [sys.stdout, sys.stderr][params.get('logtostderr', False)]
  276. self.params = params
  277. @staticmethod
  278. def pmkdir(filename):
  279. """Create directory components in filename. Similar to Unix "mkdir -p"."""
  280. components = filename.split(os.sep)
  281. aggregate = [os.sep.join(components[0:x]) for x in xrange(1, len(components))]
  282. aggregate = ['%s%s' % (x, os.sep) for x in aggregate] # Finish names with separator
  283. for dir in aggregate:
  284. if not os.path.exists(dir):
  285. os.mkdir(dir)
  286. @staticmethod
  287. def format_bytes(bytes):
  288. if bytes is None:
  289. return 'N/A'
  290. if type(bytes) is str:
  291. bytes = float(bytes)
  292. if bytes == 0.0:
  293. exponent = 0
  294. else:
  295. exponent = long(math.log(bytes, 1024.0))
  296. suffix = 'bkMGTPEZY'[exponent]
  297. converted = float(bytes) / float(1024**exponent)
  298. return '%.2f%s' % (converted, suffix)
  299. @staticmethod
  300. def calc_percent(byte_counter, data_len):
  301. if data_len is None:
  302. return '---.-%'
  303. return '%6s' % ('%3.1f%%' % (float(byte_counter) / float(data_len) * 100.0))
  304. @staticmethod
  305. def calc_eta(start, now, total, current):
  306. if total is None:
  307. return '--:--'
  308. dif = now - start
  309. if current == 0 or dif < 0.001: # One millisecond
  310. return '--:--'
  311. rate = float(current) / dif
  312. eta = long((float(total) - float(current)) / rate)
  313. (eta_mins, eta_secs) = divmod(eta, 60)
  314. if eta_mins > 99:
  315. return '--:--'
  316. return '%02d:%02d' % (eta_mins, eta_secs)
  317. @staticmethod
  318. def calc_speed(start, now, bytes):
  319. dif = now - start
  320. if bytes == 0 or dif < 0.001: # One millisecond
  321. return '%10s' % '---b/s'
  322. return '%10s' % ('%s/s' % FileDownloader.format_bytes(float(bytes) / dif))
  323. @staticmethod
  324. def best_block_size(elapsed_time, bytes):
  325. new_min = max(bytes / 2.0, 1.0)
  326. new_max = min(max(bytes * 2.0, 1.0), 4194304) # Do not surpass 4 MB
  327. if elapsed_time < 0.001:
  328. return long(new_max)
  329. rate = bytes / elapsed_time
  330. if rate > new_max:
  331. return long(new_max)
  332. if rate < new_min:
  333. return long(new_min)
  334. return long(rate)
  335. @staticmethod
  336. def parse_bytes(bytestr):
  337. """Parse a string indicating a byte quantity into a long integer."""
  338. matchobj = re.match(r'(?i)^(\d+(?:\.\d+)?)([kMGTPEZY]?)$', bytestr)
  339. if matchobj is None:
  340. return None
  341. number = float(matchobj.group(1))
  342. multiplier = 1024.0 ** 'bkmgtpezy'.index(matchobj.group(2).lower())
  343. return long(round(number * multiplier))
  344. def add_info_extractor(self, ie):
  345. """Add an InfoExtractor object to the end of the list."""
  346. self._ies.append(ie)
  347. ie.set_downloader(self)
  348. def add_post_processor(self, pp):
  349. """Add a PostProcessor object to the end of the chain."""
  350. self._pps.append(pp)
  351. pp.set_downloader(self)
  352. def to_screen(self, message, skip_eol=False, ignore_encoding_errors=False):
  353. """Print message to stdout if not in quiet mode."""
  354. try:
  355. if not self.params.get('quiet', False):
  356. terminator = [u'\n', u''][skip_eol]
  357. print >>self._screen_file, (u'%s%s' % (message, terminator)).encode(preferredencoding()),
  358. self._screen_file.flush()
  359. except (UnicodeEncodeError), err:
  360. if not ignore_encoding_errors:
  361. raise
  362. def to_stderr(self, message):
  363. """Print message to stderr."""
  364. print >>sys.stderr, message.encode(preferredencoding())
  365. def to_cons_title(self, message):
  366. """Set console/terminal window title to message."""
  367. if not self.params.get('consoletitle', False):
  368. return
  369. if os.name == 'nt' and ctypes.windll.kernel32.GetConsoleWindow():
  370. # c_wchar_p() might not be necessary if `message` is
  371. # already of type unicode()
  372. ctypes.windll.kernel32.SetConsoleTitleW(ctypes.c_wchar_p(message))
  373. elif 'TERM' in os.environ:
  374. sys.stderr.write('\033]0;%s\007' % message.encode(preferredencoding()))
  375. def fixed_template(self):
  376. """Checks if the output template is fixed."""
  377. return (re.search(ur'(?u)%\(.+?\)s', self.params['outtmpl']) is None)
  378. def trouble(self, message=None):
  379. """Determine action to take when a download problem appears.
  380. Depending on if the downloader has been configured to ignore
  381. download errors or not, this method may throw an exception or
  382. not when errors are found, after printing the message.
  383. """
  384. if message is not None:
  385. self.to_stderr(message)
  386. if not self.params.get('ignoreerrors', False):
  387. raise DownloadError(message)
  388. self._download_retcode = 1
  389. def slow_down(self, start_time, byte_counter):
  390. """Sleep if the download speed is over the rate limit."""
  391. rate_limit = self.params.get('ratelimit', None)
  392. if rate_limit is None or byte_counter == 0:
  393. return
  394. now = time.time()
  395. elapsed = now - start_time
  396. if elapsed <= 0.0:
  397. return
  398. speed = float(byte_counter) / elapsed
  399. if speed > rate_limit:
  400. time.sleep((byte_counter - rate_limit * (now - start_time)) / rate_limit)
  401. def temp_name(self, filename):
  402. """Returns a temporary filename for the given filename."""
  403. if self.params.get('nopart', False) or filename == u'-' or \
  404. (os.path.exists(filename) and not os.path.isfile(filename)):
  405. return filename
  406. return filename + u'.part'
  407. def undo_temp_name(self, filename):
  408. if filename.endswith(u'.part'):
  409. return filename[:-len(u'.part')]
  410. return filename
  411. def try_rename(self, old_filename, new_filename):
  412. try:
  413. if old_filename == new_filename:
  414. return
  415. os.rename(old_filename, new_filename)
  416. except (IOError, OSError), err:
  417. self.trouble(u'ERROR: unable to rename file')
  418. def try_utime(self, filename, last_modified_hdr):
  419. """Try to set the last-modified time of the given file."""
  420. if last_modified_hdr is None:
  421. return
  422. if not os.path.isfile(filename):
  423. return
  424. timestr = last_modified_hdr
  425. if timestr is None:
  426. return
  427. filetime = timeconvert(timestr)
  428. if filetime is None:
  429. return
  430. try:
  431. os.utime(filename,(time.time(), filetime))
  432. except:
  433. pass
  434. def report_writedescription(self, descfn):
  435. """ Report that the description file has been written """
  436. self.to_screen(u'[info] Video description written to: %s' % descfn, ignore_encoding_errors=True)
  437. def report_destination(self, filename):
  438. """Report destination filename."""
  439. self.to_screen(u'[download] Destination: %s' % filename, ignore_encoding_errors=True)
  440. def report_progress(self, percent_str, data_len_str, speed_str, eta_str):
  441. """Report download progress."""
  442. if self.params.get('noprogress', False):
  443. return
  444. self.to_screen(u'\r[download] %s of %s at %s ETA %s' %
  445. (percent_str, data_len_str, speed_str, eta_str), skip_eol=True)
  446. self.to_cons_title(u'youtube-dl - %s of %s at %s ETA %s' %
  447. (percent_str.strip(), data_len_str.strip(), speed_str.strip(), eta_str.strip()))
  448. def report_resuming_byte(self, resume_len):
  449. """Report attempt to resume at given byte."""
  450. self.to_screen(u'[download] Resuming download at byte %s' % resume_len)
  451. def report_retry(self, count, retries):
  452. """Report retry in case of HTTP error 5xx"""
  453. self.to_screen(u'[download] Got server HTTP error. Retrying (attempt %d of %d)...' % (count, retries))
  454. def report_file_already_downloaded(self, file_name):
  455. """Report file has already been fully downloaded."""
  456. try:
  457. self.to_screen(u'[download] %s has already been downloaded' % file_name)
  458. except (UnicodeEncodeError), err:
  459. self.to_screen(u'[download] The file has already been downloaded')
  460. def report_unable_to_resume(self):
  461. """Report it was impossible to resume download."""
  462. self.to_screen(u'[download] Unable to resume')
  463. def report_finish(self):
  464. """Report download finished."""
  465. if self.params.get('noprogress', False):
  466. self.to_screen(u'[download] Download completed')
  467. else:
  468. self.to_screen(u'')
  469. def increment_downloads(self):
  470. """Increment the ordinal that assigns a number to each file."""
  471. self._num_downloads += 1
  472. def prepare_filename(self, info_dict):
  473. """Generate the output filename."""
  474. try:
  475. template_dict = dict(info_dict)
  476. template_dict['epoch'] = unicode(long(time.time()))
  477. template_dict['autonumber'] = unicode('%05d' % self._num_downloads)
  478. filename = self.params['outtmpl'] % template_dict
  479. return filename
  480. except (ValueError, KeyError), err:
  481. self.trouble(u'ERROR: invalid system charset or erroneous output template')
  482. return None
  483. def process_info(self, info_dict):
  484. """Process a single dictionary returned by an InfoExtractor."""
  485. filename = self.prepare_filename(info_dict)
  486. # Do nothing else if in simulate mode
  487. if self.params.get('simulate', False):
  488. # Forced printings
  489. if self.params.get('forcetitle', False):
  490. print info_dict['title'].encode(preferredencoding(), 'xmlcharrefreplace')
  491. if self.params.get('forceurl', False):
  492. print info_dict['url'].encode(preferredencoding(), 'xmlcharrefreplace')
  493. if self.params.get('forcethumbnail', False) and 'thumbnail' in info_dict:
  494. print info_dict['thumbnail'].encode(preferredencoding(), 'xmlcharrefreplace')
  495. if self.params.get('forcedescription', False) and 'description' in info_dict:
  496. print info_dict['description'].encode(preferredencoding(), 'xmlcharrefreplace')
  497. if self.params.get('forcefilename', False) and filename is not None:
  498. print filename.encode(preferredencoding(), 'xmlcharrefreplace')
  499. return
  500. if filename is None:
  501. return
  502. if self.params.get('nooverwrites', False) and os.path.exists(filename):
  503. self.to_stderr(u'WARNING: file exists and will be skipped')
  504. return
  505. try:
  506. self.pmkdir(filename)
  507. except (OSError, IOError), err:
  508. self.trouble(u'ERROR: unable to create directories: %s' % str(err))
  509. return
  510. if self.params.get('writedescription', False):
  511. try:
  512. descfn = filename + '.description'
  513. with contextlib.closing(open(descfn, 'wb')) as descfile:
  514. descfile.write(info_dict['description'].encode('utf-8'))
  515. self.report_writedescription(descfn)
  516. except (OSError, IOError):
  517. self.trouble(u'ERROR: Cannot write description file: %s' % str(descfn))
  518. return
  519. try:
  520. success = self._do_download(filename, info_dict['url'].encode('utf-8'), info_dict.get('player_url', None))
  521. except (OSError, IOError), err:
  522. raise UnavailableVideoError
  523. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  524. self.trouble(u'ERROR: unable to download video data: %s' % str(err))
  525. return
  526. except (ContentTooShortError, ), err:
  527. self.trouble(u'ERROR: content too short (expected %s bytes and served %s)' % (err.expected, err.downloaded))
  528. return
  529. if success:
  530. try:
  531. self.post_process(filename, info_dict)
  532. except (PostProcessingError), err:
  533. self.trouble(u'ERROR: postprocessing: %s' % str(err))
  534. return
  535. def download(self, url_list):
  536. """Download a given list of URLs."""
  537. if len(url_list) > 1 and self.fixed_template():
  538. raise SameFileError(self.params['outtmpl'])
  539. for url in url_list:
  540. suitable_found = False
  541. for ie in self._ies:
  542. # Go to next InfoExtractor if not suitable
  543. if not ie.suitable(url):
  544. continue
  545. # Suitable InfoExtractor found
  546. suitable_found = True
  547. # Extract information from URL and process it
  548. ie.extract(url)
  549. # Suitable InfoExtractor had been found; go to next URL
  550. break
  551. if not suitable_found:
  552. self.trouble(u'ERROR: no suitable InfoExtractor: %s' % url)
  553. return self._download_retcode
  554. def post_process(self, filename, ie_info):
  555. """Run the postprocessing chain on the given file."""
  556. info = dict(ie_info)
  557. info['filepath'] = filename
  558. for pp in self._pps:
  559. info = pp.run(info)
  560. if info is None:
  561. break
  562. def _download_with_rtmpdump(self, filename, url, player_url):
  563. self.report_destination(filename)
  564. tmpfilename = self.temp_name(filename)
  565. # Check for rtmpdump first
  566. try:
  567. subprocess.call(['rtmpdump', '-h'], stdout=(file(os.path.devnull, 'w')), stderr=subprocess.STDOUT)
  568. except (OSError, IOError):
  569. self.trouble(u'ERROR: RTMP download detected but "rtmpdump" could not be run')
  570. return False
  571. # Download using rtmpdump. rtmpdump returns exit code 2 when
  572. # the connection was interrumpted and resuming appears to be
  573. # possible. This is part of rtmpdump's normal usage, AFAIK.
  574. basic_args = ['rtmpdump', '-q'] + [[], ['-W', player_url]][player_url is not None] + ['-r', url, '-o', tmpfilename]
  575. retval = subprocess.call(basic_args + [[], ['-e', '-k', '1']][self.params.get('continuedl', False)])
  576. while retval == 2 or retval == 1:
  577. prevsize = os.path.getsize(tmpfilename)
  578. self.to_screen(u'\r[rtmpdump] %s bytes' % prevsize, skip_eol=True)
  579. time.sleep(5.0) # This seems to be needed
  580. retval = subprocess.call(basic_args + ['-e'] + [[], ['-k', '1']][retval == 1])
  581. cursize = os.path.getsize(tmpfilename)
  582. if prevsize == cursize and retval == 1:
  583. break
  584. if retval == 0:
  585. self.to_screen(u'\r[rtmpdump] %s bytes' % os.path.getsize(tmpfilename))
  586. self.try_rename(tmpfilename, filename)
  587. return True
  588. else:
  589. self.trouble(u'\nERROR: rtmpdump exited with code %d' % retval)
  590. return False
  591. def _do_download(self, filename, url, player_url):
  592. # Check file already present
  593. if self.params.get('continuedl', False) and os.path.isfile(filename) and not self.params.get('nopart', False):
  594. self.report_file_already_downloaded(filename)
  595. return True
  596. # Attempt to download using rtmpdump
  597. if url.startswith('rtmp'):
  598. return self._download_with_rtmpdump(filename, url, player_url)
  599. tmpfilename = self.temp_name(filename)
  600. stream = None
  601. open_mode = 'wb'
  602. # Do not include the Accept-Encoding header
  603. headers = {'Youtubedl-no-compression': 'True'}
  604. basic_request = urllib2.Request(url, None, headers)
  605. request = urllib2.Request(url, None, headers)
  606. # Establish possible resume length
  607. if os.path.isfile(tmpfilename):
  608. resume_len = os.path.getsize(tmpfilename)
  609. else:
  610. resume_len = 0
  611. # Request parameters in case of being able to resume
  612. if self.params.get('continuedl', False) and resume_len != 0:
  613. self.report_resuming_byte(resume_len)
  614. request.add_header('Range','bytes=%d-' % resume_len)
  615. open_mode = 'ab'
  616. count = 0
  617. retries = self.params.get('retries', 0)
  618. while count <= retries:
  619. # Establish connection
  620. try:
  621. data = urllib2.urlopen(request)
  622. break
  623. except (urllib2.HTTPError, ), err:
  624. if (err.code < 500 or err.code >= 600) and err.code != 416:
  625. # Unexpected HTTP error
  626. raise
  627. elif err.code == 416:
  628. # Unable to resume (requested range not satisfiable)
  629. try:
  630. # Open the connection again without the range header
  631. data = urllib2.urlopen(basic_request)
  632. content_length = data.info()['Content-Length']
  633. except (urllib2.HTTPError, ), err:
  634. if err.code < 500 or err.code >= 600:
  635. raise
  636. else:
  637. # Examine the reported length
  638. if (content_length is not None and
  639. (resume_len - 100 < long(content_length) < resume_len + 100)):
  640. # The file had already been fully downloaded.
  641. # Explanation to the above condition: in issue #175 it was revealed that
  642. # YouTube sometimes adds or removes a few bytes from the end of the file,
  643. # changing the file size slightly and causing problems for some users. So
  644. # I decided to implement a suggested change and consider the file
  645. # completely downloaded if the file size differs less than 100 bytes from
  646. # the one in the hard drive.
  647. self.report_file_already_downloaded(filename)
  648. self.try_rename(tmpfilename, filename)
  649. return True
  650. else:
  651. # The length does not match, we start the download over
  652. self.report_unable_to_resume()
  653. open_mode = 'wb'
  654. break
  655. # Retry
  656. count += 1
  657. if count <= retries:
  658. self.report_retry(count, retries)
  659. if count > retries:
  660. self.trouble(u'ERROR: giving up after %s retries' % retries)
  661. return False
  662. data_len = data.info().get('Content-length', None)
  663. if data_len is not None:
  664. data_len = long(data_len) + resume_len
  665. data_len_str = self.format_bytes(data_len)
  666. byte_counter = 0 + resume_len
  667. block_size = 1024
  668. start = time.time()
  669. while True:
  670. # Download and write
  671. before = time.time()
  672. data_block = data.read(block_size)
  673. after = time.time()
  674. if len(data_block) == 0:
  675. break
  676. byte_counter += len(data_block)
  677. # Open file just in time
  678. if stream is None:
  679. try:
  680. (stream, tmpfilename) = sanitize_open(tmpfilename, open_mode)
  681. filename = self.undo_temp_name(tmpfilename)
  682. self.report_destination(filename)
  683. except (OSError, IOError), err:
  684. self.trouble(u'ERROR: unable to open for writing: %s' % str(err))
  685. return False
  686. try:
  687. stream.write(data_block)
  688. except (IOError, OSError), err:
  689. self.trouble(u'\nERROR: unable to write data: %s' % str(err))
  690. return False
  691. block_size = self.best_block_size(after - before, len(data_block))
  692. # Progress message
  693. percent_str = self.calc_percent(byte_counter, data_len)
  694. eta_str = self.calc_eta(start, time.time(), data_len - resume_len, byte_counter - resume_len)
  695. speed_str = self.calc_speed(start, time.time(), byte_counter - resume_len)
  696. self.report_progress(percent_str, data_len_str, speed_str, eta_str)
  697. # Apply rate limit
  698. self.slow_down(start, byte_counter - resume_len)
  699. stream.close()
  700. self.report_finish()
  701. if data_len is not None and byte_counter != data_len:
  702. raise ContentTooShortError(byte_counter, long(data_len))
  703. self.try_rename(tmpfilename, filename)
  704. # Update file modification time
  705. if self.params.get('updatetime', True):
  706. self.try_utime(filename, data.info().get('last-modified', None))
  707. return True
  708. class InfoExtractor(object):
  709. """Information Extractor class.
  710. Information extractors are the classes that, given a URL, extract
  711. information from the video (or videos) the URL refers to. This
  712. information includes the real video URL, the video title and simplified
  713. title, author and others. The information is stored in a dictionary
  714. which is then passed to the FileDownloader. The FileDownloader
  715. processes this information possibly downloading the video to the file
  716. system, among other possible outcomes. The dictionaries must include
  717. the following fields:
  718. id: Video identifier.
  719. url: Final video URL.
  720. uploader: Nickname of the video uploader.
  721. title: Literal title.
  722. stitle: Simplified title.
  723. ext: Video filename extension.
  724. format: Video format.
  725. player_url: SWF Player URL (may be None).
  726. The following fields are optional. Their primary purpose is to allow
  727. youtube-dl to serve as the backend for a video search function, such
  728. as the one in youtube2mp3. They are only used when their respective
  729. forced printing functions are called:
  730. thumbnail: Full URL to a video thumbnail image.
  731. description: One-line video description.
  732. Subclasses of this one should re-define the _real_initialize() and
  733. _real_extract() methods, as well as the suitable() static method.
  734. Probably, they should also be instantiated and added to the main
  735. downloader.
  736. """
  737. _ready = False
  738. _downloader = None
  739. def __init__(self, downloader=None):
  740. """Constructor. Receives an optional downloader."""
  741. self._ready = False
  742. self.set_downloader(downloader)
  743. @staticmethod
  744. def suitable(url):
  745. """Receives a URL and returns True if suitable for this IE."""
  746. return False
  747. def initialize(self):
  748. """Initializes an instance (authentication, etc)."""
  749. if not self._ready:
  750. self._real_initialize()
  751. self._ready = True
  752. def extract(self, url):
  753. """Extracts URL information and returns it in list of dicts."""
  754. self.initialize()
  755. return self._real_extract(url)
  756. def set_downloader(self, downloader):
  757. """Sets the downloader for this IE."""
  758. self._downloader = downloader
  759. def _real_initialize(self):
  760. """Real initialization process. Redefine in subclasses."""
  761. pass
  762. def _real_extract(self, url):
  763. """Real extraction process. Redefine in subclasses."""
  764. pass
  765. class YoutubeIE(InfoExtractor):
  766. """Information extractor for youtube.com."""
  767. _VALID_URL = r'^((?:https?://)?(?:youtu\.be/|(?:\w+\.)?youtube(?:-nocookie)?\.com/)(?:(?:(?:v|embed|e)/)|(?:(?:watch(?:_popup)?(?:\.php)?)?(?:\?|#!?)(?:.+&)?v=)))?([0-9A-Za-z_-]+)(?(1).+)?$'
  768. _LANG_URL = r'http://www.youtube.com/?hl=en&persist_hl=1&gl=US&persist_gl=1&opt_out_ackd=1'
  769. _LOGIN_URL = 'https://www.youtube.com/signup?next=/&gl=US&hl=en'
  770. _AGE_URL = 'http://www.youtube.com/verify_age?next_url=/&gl=US&hl=en'
  771. _NETRC_MACHINE = 'youtube'
  772. # Listed in order of quality
  773. _available_formats = ['38', '37', '22', '45', '35', '34', '43', '18', '6', '5', '17', '13']
  774. _video_extensions = {
  775. '13': '3gp',
  776. '17': 'mp4',
  777. '18': 'mp4',
  778. '22': 'mp4',
  779. '37': 'mp4',
  780. '38': 'video', # You actually don't know if this will be MOV, AVI or whatever
  781. '43': 'webm',
  782. '45': 'webm',
  783. }
  784. @staticmethod
  785. def suitable(url):
  786. return (re.match(YoutubeIE._VALID_URL, url) is not None)
  787. def report_lang(self):
  788. """Report attempt to set language."""
  789. self._downloader.to_screen(u'[youtube] Setting language')
  790. def report_login(self):
  791. """Report attempt to log in."""
  792. self._downloader.to_screen(u'[youtube] Logging in')
  793. def report_age_confirmation(self):
  794. """Report attempt to confirm age."""
  795. self._downloader.to_screen(u'[youtube] Confirming age')
  796. def report_video_webpage_download(self, video_id):
  797. """Report attempt to download video webpage."""
  798. self._downloader.to_screen(u'[youtube] %s: Downloading video webpage' % video_id)
  799. def report_video_info_webpage_download(self, video_id):
  800. """Report attempt to download video info webpage."""
  801. self._downloader.to_screen(u'[youtube] %s: Downloading video info webpage' % video_id)
  802. def report_information_extraction(self, video_id):
  803. """Report attempt to extract video information."""
  804. self._downloader.to_screen(u'[youtube] %s: Extracting video information' % video_id)
  805. def report_unavailable_format(self, video_id, format):
  806. """Report extracted video URL."""
  807. self._downloader.to_screen(u'[youtube] %s: Format %s not available' % (video_id, format))
  808. def report_rtmp_download(self):
  809. """Indicate the download will use the RTMP protocol."""
  810. self._downloader.to_screen(u'[youtube] RTMP download detected')
  811. def _real_initialize(self):
  812. if self._downloader is None:
  813. return
  814. username = None
  815. password = None
  816. downloader_params = self._downloader.params
  817. # Attempt to use provided username and password or .netrc data
  818. if downloader_params.get('username', None) is not None:
  819. username = downloader_params['username']
  820. password = downloader_params['password']
  821. elif downloader_params.get('usenetrc', False):
  822. try:
  823. info = netrc.netrc().authenticators(self._NETRC_MACHINE)
  824. if info is not None:
  825. username = info[0]
  826. password = info[2]
  827. else:
  828. raise netrc.NetrcParseError('No authenticators for %s' % self._NETRC_MACHINE)
  829. except (IOError, netrc.NetrcParseError), err:
  830. self._downloader.to_stderr(u'WARNING: parsing .netrc: %s' % str(err))
  831. return
  832. # Set language
  833. request = urllib2.Request(self._LANG_URL)
  834. try:
  835. self.report_lang()
  836. urllib2.urlopen(request).read()
  837. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  838. self._downloader.to_stderr(u'WARNING: unable to set language: %s' % str(err))
  839. return
  840. # No authentication to be performed
  841. if username is None:
  842. return
  843. # Log in
  844. login_form = {
  845. 'current_form': 'loginForm',
  846. 'next': '/',
  847. 'action_login': 'Log In',
  848. 'username': username,
  849. 'password': password,
  850. }
  851. request = urllib2.Request(self._LOGIN_URL, urllib.urlencode(login_form))
  852. try:
  853. self.report_login()
  854. login_results = urllib2.urlopen(request).read()
  855. if re.search(r'(?i)<form[^>]* name="loginForm"', login_results) is not None:
  856. self._downloader.to_stderr(u'WARNING: unable to log in: bad username or password')
  857. return
  858. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  859. self._downloader.to_stderr(u'WARNING: unable to log in: %s' % str(err))
  860. return
  861. # Confirm age
  862. age_form = {
  863. 'next_url': '/',
  864. 'action_confirm': 'Confirm',
  865. }
  866. request = urllib2.Request(self._AGE_URL, urllib.urlencode(age_form))
  867. try:
  868. self.report_age_confirmation()
  869. age_results = urllib2.urlopen(request).read()
  870. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  871. self._downloader.trouble(u'ERROR: unable to confirm age: %s' % str(err))
  872. return
  873. def _real_extract(self, url):
  874. # Extract video id from URL
  875. mobj = re.match(self._VALID_URL, url)
  876. if mobj is None:
  877. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  878. return
  879. video_id = mobj.group(2)
  880. # Get video webpage
  881. self.report_video_webpage_download(video_id)
  882. request = urllib2.Request('http://www.youtube.com/watch?v=%s&gl=US&hl=en&amp;has_verified=1' % video_id)
  883. try:
  884. video_webpage = urllib2.urlopen(request).read()
  885. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  886. self._downloader.trouble(u'ERROR: unable to download video webpage: %s' % str(err))
  887. return
  888. # Attempt to extract SWF player URL
  889. mobj = re.search(r'swfConfig.*?"(http:\\/\\/.*?watch.*?-.*?\.swf)"', video_webpage)
  890. if mobj is not None:
  891. player_url = re.sub(r'\\(.)', r'\1', mobj.group(1))
  892. else:
  893. player_url = None
  894. # Get video info
  895. self.report_video_info_webpage_download(video_id)
  896. for el_type in ['&el=embedded', '&el=detailpage', '&el=vevo', '']:
  897. video_info_url = ('http://www.youtube.com/get_video_info?&video_id=%s%s&ps=default&eurl=&gl=US&hl=en'
  898. % (video_id, el_type))
  899. request = urllib2.Request(video_info_url)
  900. try:
  901. video_info_webpage = urllib2.urlopen(request).read()
  902. video_info = parse_qs(video_info_webpage)
  903. if 'token' in video_info:
  904. break
  905. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  906. self._downloader.trouble(u'ERROR: unable to download video info webpage: %s' % str(err))
  907. return
  908. if 'token' not in video_info:
  909. if 'reason' in video_info:
  910. self._downloader.trouble(u'ERROR: YouTube said: %s' % video_info['reason'][0].decode('utf-8'))
  911. else:
  912. self._downloader.trouble(u'ERROR: "token" parameter not in video info for unknown reason')
  913. return
  914. # Start extracting information
  915. self.report_information_extraction(video_id)
  916. # uploader
  917. if 'author' not in video_info:
  918. self._downloader.trouble(u'ERROR: unable to extract uploader nickname')
  919. return
  920. video_uploader = urllib.unquote_plus(video_info['author'][0])
  921. # title
  922. if 'title' not in video_info:
  923. self._downloader.trouble(u'ERROR: unable to extract video title')
  924. return
  925. video_title = urllib.unquote_plus(video_info['title'][0])
  926. video_title = video_title.decode('utf-8')
  927. video_title = sanitize_title(video_title)
  928. # simplified title
  929. simple_title = re.sub(ur'(?u)([^%s]+)' % simple_title_chars, ur'_', video_title)
  930. simple_title = simple_title.strip(ur'_')
  931. # thumbnail image
  932. if 'thumbnail_url' not in video_info:
  933. self._downloader.trouble(u'WARNING: unable to extract video thumbnail')
  934. video_thumbnail = ''
  935. else: # don't panic if we can't find it
  936. video_thumbnail = urllib.unquote_plus(video_info['thumbnail_url'][0])
  937. # upload date
  938. upload_date = u'NA'
  939. mobj = re.search(r'id="eow-date.*?>(.*?)</span>', video_webpage, re.DOTALL)
  940. if mobj is not None:
  941. upload_date = ' '.join(re.sub(r'[/,-]', r' ', mobj.group(1)).split())
  942. format_expressions = ['%d %B %Y', '%B %d %Y', '%b %d %Y']
  943. for expression in format_expressions:
  944. try:
  945. upload_date = datetime.datetime.strptime(upload_date, expression).strftime('%Y%m%d')
  946. except:
  947. pass
  948. # description
  949. try:
  950. lxml.etree
  951. except NameError:
  952. video_description = u'No description available.'
  953. if self._downloader.params.get('forcedescription', False) or self._downloader.params.get('writedescription', False):
  954. warnings.warn(u'You are using an old Python version, install Python 2.6+ or lxml. Falling back to old video description extractor.')
  955. mobj = re.search(r'<meta name="description" content="(.*)"(?:\s*/)?>', video_webpage)
  956. if mobj is not None:
  957. video_description = mobj.group(1).decode('utf-8')
  958. else:
  959. html_parser = lxml.etree.HTMLParser(encoding='utf-8')
  960. vwebpage_doc = lxml.etree.parse(StringIO.StringIO(video_webpage), html_parser)
  961. video_description = u''.join(vwebpage_doc.xpath('id("eow-description")//text()'))
  962. # token
  963. video_token = urllib.unquote_plus(video_info['token'][0])
  964. # Decide which formats to download
  965. req_format = self._downloader.params.get('format', None)
  966. if 'fmt_url_map' in video_info and len(video_info['fmt_url_map']) >= 1 and ',' in video_info['fmt_url_map'][0]:
  967. url_map = dict(tuple(pair.split('|')) for pair in video_info['fmt_url_map'][0].split(','))
  968. format_limit = self._downloader.params.get('format_limit', None)
  969. if format_limit is not None and format_limit in self._available_formats:
  970. format_list = self._available_formats[self._available_formats.index(format_limit):]
  971. else:
  972. format_list = self._available_formats
  973. existing_formats = [x for x in format_list if x in url_map]
  974. if len(existing_formats) == 0:
  975. self._downloader.trouble(u'ERROR: no known formats available for video')
  976. return
  977. if req_format is None:
  978. video_url_list = [(existing_formats[0], url_map[existing_formats[0]])] # Best quality
  979. elif req_format == '-1':
  980. video_url_list = [(f, url_map[f]) for f in existing_formats] # All formats
  981. else:
  982. # Specific format
  983. if req_format not in url_map:
  984. self._downloader.trouble(u'ERROR: requested format not available')
  985. return
  986. video_url_list = [(req_format, url_map[req_format])] # Specific format
  987. elif 'conn' in video_info and video_info['conn'][0].startswith('rtmp'):
  988. self.report_rtmp_download()
  989. video_url_list = [(None, video_info['conn'][0])]
  990. else:
  991. self._downloader.trouble(u'ERROR: no fmt_url_map or conn information found in video info')
  992. return
  993. for format_param, video_real_url in video_url_list:
  994. # At this point we have a new video
  995. self._downloader.increment_downloads()
  996. # Extension
  997. video_extension = self._video_extensions.get(format_param, 'flv')
  998. # Find the video URL in fmt_url_map or conn paramters
  999. try:
  1000. # Process video information
  1001. self._downloader.process_info({
  1002. 'id': video_id.decode('utf-8'),
  1003. 'url': video_real_url.decode('utf-8'),
  1004. 'uploader': video_uploader.decode('utf-8'),
  1005. 'upload_date': upload_date,
  1006. 'title': video_title,
  1007. 'stitle': simple_title,
  1008. 'ext': video_extension.decode('utf-8'),
  1009. 'format': (format_param is None and u'NA' or format_param.decode('utf-8')),
  1010. 'thumbnail': video_thumbnail.decode('utf-8'),
  1011. 'description': video_description,
  1012. 'player_url': player_url,
  1013. })
  1014. except UnavailableVideoError, err:
  1015. self._downloader.trouble(u'\nERROR: unable to download video')
  1016. class MetacafeIE(InfoExtractor):
  1017. """Information Extractor for metacafe.com."""
  1018. _VALID_URL = r'(?:http://)?(?:www\.)?metacafe\.com/watch/([^/]+)/([^/]+)/.*'
  1019. _DISCLAIMER = 'http://www.metacafe.com/family_filter/'
  1020. _FILTER_POST = 'http://www.metacafe.com/f/index.php?inputType=filter&controllerGroup=user'
  1021. _youtube_ie = None
  1022. def __init__(self, youtube_ie, downloader=None):
  1023. InfoExtractor.__init__(self, downloader)
  1024. self._youtube_ie = youtube_ie
  1025. @staticmethod
  1026. def suitable(url):
  1027. return (re.match(MetacafeIE._VALID_URL, url) is not None)
  1028. def report_disclaimer(self):
  1029. """Report disclaimer retrieval."""
  1030. self._downloader.to_screen(u'[metacafe] Retrieving disclaimer')
  1031. def report_age_confirmation(self):
  1032. """Report attempt to confirm age."""
  1033. self._downloader.to_screen(u'[metacafe] Confirming age')
  1034. def report_download_webpage(self, video_id):
  1035. """Report webpage download."""
  1036. self._downloader.to_screen(u'[metacafe] %s: Downloading webpage' % video_id)
  1037. def report_extraction(self, video_id):
  1038. """Report information extraction."""
  1039. self._downloader.to_screen(u'[metacafe] %s: Extracting information' % video_id)
  1040. def _real_initialize(self):
  1041. # Retrieve disclaimer
  1042. request = urllib2.Request(self._DISCLAIMER)
  1043. try:
  1044. self.report_disclaimer()
  1045. disclaimer = urllib2.urlopen(request).read()
  1046. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1047. self._downloader.trouble(u'ERROR: unable to retrieve disclaimer: %s' % str(err))
  1048. return
  1049. # Confirm age
  1050. disclaimer_form = {
  1051. 'filters': '0',
  1052. 'submit': "Continue - I'm over 18",
  1053. }
  1054. request = urllib2.Request(self._FILTER_POST, urllib.urlencode(disclaimer_form))
  1055. try:
  1056. self.report_age_confirmation()
  1057. disclaimer = urllib2.urlopen(request).read()
  1058. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1059. self._downloader.trouble(u'ERROR: unable to confirm age: %s' % str(err))
  1060. return
  1061. def _real_extract(self, url):
  1062. # Extract id and simplified title from URL
  1063. mobj = re.match(self._VALID_URL, url)
  1064. if mobj is None:
  1065. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  1066. return
  1067. video_id = mobj.group(1)
  1068. # Check if video comes from YouTube
  1069. mobj2 = re.match(r'^yt-(.*)$', video_id)
  1070. if mobj2 is not None:
  1071. self._youtube_ie.extract('http://www.youtube.com/watch?v=%s' % mobj2.group(1))
  1072. return
  1073. # At this point we have a new video
  1074. self._downloader.increment_downloads()
  1075. simple_title = mobj.group(2).decode('utf-8')
  1076. # Retrieve video webpage to extract further information
  1077. request = urllib2.Request('http://www.metacafe.com/watch/%s/' % 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 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'(?m)&mediaURL=([^&]+)', webpage)
  1087. if mobj is not None:
  1088. mediaURL = urllib.unquote(mobj.group(1))
  1089. video_extension = mediaURL[-3:]
  1090. # Extract gdaKey if available
  1091. mobj = re.search(r'(?m)&gdaKey=(.*?)&', webpage)
  1092. if mobj is None:
  1093. video_url = mediaURL
  1094. else:
  1095. gdaKey = mobj.group(1)
  1096. video_url = '%s?__gda__=%s' % (mediaURL, gdaKey)
  1097. else:
  1098. mobj = re.search(r' name="flashvars" value="(.*?)"', webpage)
  1099. if mobj is None:
  1100. self._downloader.trouble(u'ERROR: unable to extract media URL')
  1101. return
  1102. vardict = parse_qs(mobj.group(1))
  1103. if 'mediaData' not in vardict:
  1104. self._downloader.trouble(u'ERROR: unable to extract media URL')
  1105. return
  1106. mobj = re.search(r'"mediaURL":"(http.*?)","key":"(.*?)"', vardict['mediaData'][0])
  1107. if mobj is None:
  1108. self._downloader.trouble(u'ERROR: unable to extract media URL')
  1109. return
  1110. mediaURL = mobj.group(1).replace('\\/', '/')
  1111. video_extension = mediaURL[-3:]
  1112. video_url = '%s?__gda__=%s' % (mediaURL, mobj.group(2))
  1113. mobj = re.search(r'(?im)<title>(.*) - Video</title>', webpage)
  1114. if mobj is None:
  1115. self._downloader.trouble(u'ERROR: unable to extract title')
  1116. return
  1117. video_title = mobj.group(1).decode('utf-8')
  1118. video_title = sanitize_title(video_title)
  1119. mobj = re.search(r'(?ms)By:\s*<a .*?>(.+?)<', webpage)
  1120. if mobj is None:
  1121. self._downloader.trouble(u'ERROR: unable to extract uploader nickname')
  1122. return
  1123. video_uploader = mobj.group(1)
  1124. try:
  1125. # Process video information
  1126. self._downloader.process_info({
  1127. 'id': video_id.decode('utf-8'),
  1128. 'url': video_url.decode('utf-8'),
  1129. 'uploader': video_uploader.decode('utf-8'),
  1130. 'upload_date': u'NA',
  1131. 'title': video_title,
  1132. 'stitle': simple_title,
  1133. 'ext': video_extension.decode('utf-8'),
  1134. 'format': u'NA',
  1135. 'player_url': None,
  1136. })
  1137. except UnavailableVideoError:
  1138. self._downloader.trouble(u'\nERROR: unable to download video')
  1139. class DailymotionIE(InfoExtractor):
  1140. """Information Extractor for Dailymotion"""
  1141. _VALID_URL = r'(?i)(?:https?://)?(?:www\.)?dailymotion\.[a-z]{2,3}/video/([^_/]+)_([^/]+)'
  1142. def __init__(self, downloader=None):
  1143. InfoExtractor.__init__(self, downloader)
  1144. @staticmethod
  1145. def suitable(url):
  1146. return (re.match(DailymotionIE._VALID_URL, url) is not None)
  1147. def report_download_webpage(self, video_id):
  1148. """Report webpage download."""
  1149. self._downloader.to_screen(u'[dailymotion] %s: Downloading webpage' % video_id)
  1150. def report_extraction(self, video_id):
  1151. """Report information extraction."""
  1152. self._downloader.to_screen(u'[dailymotion] %s: Extracting information' % video_id)
  1153. def _real_initialize(self):
  1154. return
  1155. def _real_extract(self, url):
  1156. # Extract id and simplified title from URL
  1157. mobj = re.match(self._VALID_URL, url)
  1158. if mobj is None:
  1159. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  1160. return
  1161. # At this point we have a new video
  1162. self._downloader.increment_downloads()
  1163. video_id = mobj.group(1)
  1164. simple_title = mobj.group(2).decode('utf-8')
  1165. video_extension = 'flv'
  1166. # Retrieve video webpage to extract further information
  1167. request = urllib2.Request(url)
  1168. try:
  1169. self.report_download_webpage(video_id)
  1170. webpage = urllib2.urlopen(request).read()
  1171. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1172. self._downloader.trouble(u'ERROR: unable retrieve video webpage: %s' % str(err))
  1173. return
  1174. # Extract URL, uploader and title from webpage
  1175. self.report_extraction(video_id)
  1176. mobj = re.search(r'(?i)addVariable\(\"video\"\s*,\s*\"([^\"]*)\"\)', webpage)
  1177. if mobj is None:
  1178. self._downloader.trouble(u'ERROR: unable to extract media URL')
  1179. return
  1180. mediaURL = urllib.unquote(mobj.group(1))
  1181. # if needed add http://www.dailymotion.com/ if relative URL
  1182. video_url = mediaURL
  1183. # '<meta\s+name="title"\s+content="Dailymotion\s*[:\-]\s*(.*?)"\s*\/\s*>'
  1184. mobj = re.search(r'(?im)<title>Dailymotion\s*[\-:]\s*(.+?)</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. mobj = re.search(r'(?im)<Attribute name="owner">(.+?)</Attribute>', webpage)
  1191. if mobj is None:
  1192. self._downloader.trouble(u'ERROR: unable to extract uploader nickname')
  1193. return
  1194. video_uploader = mobj.group(1)
  1195. try:
  1196. # Process video information
  1197. self._downloader.process_info({
  1198. 'id': video_id.decode('utf-8'),
  1199. 'url': video_url.decode('utf-8'),
  1200. 'uploader': video_uploader.decode('utf-8'),
  1201. 'upload_date': u'NA',
  1202. 'title': video_title,
  1203. 'stitle': simple_title,
  1204. 'ext': video_extension.decode('utf-8'),
  1205. 'format': u'NA',
  1206. 'player_url': None,
  1207. })
  1208. except UnavailableVideoError:
  1209. self._downloader.trouble(u'\nERROR: unable to download video')
  1210. class GoogleIE(InfoExtractor):
  1211. """Information extractor for video.google.com."""
  1212. _VALID_URL = r'(?:http://)?video\.google\.(?:com(?:\.au)?|co\.(?:uk|jp|kr|cr)|ca|de|es|fr|it|nl|pl)/videoplay\?docid=([^\&]+).*'
  1213. def __init__(self, downloader=None):
  1214. InfoExtractor.__init__(self, downloader)
  1215. @staticmethod
  1216. def suitable(url):
  1217. return (re.match(GoogleIE._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.google] %s: Downloading webpage' % video_id)
  1221. def report_extraction(self, video_id):
  1222. """Report information extraction."""
  1223. self._downloader.to_screen(u'[video.google] %s: Extracting information' % video_id)
  1224. def _real_initialize(self):
  1225. return
  1226. def _real_extract(self, url):
  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(1)
  1235. video_extension = 'mp4'
  1236. # Retrieve video webpage to extract further information
  1237. request = urllib2.Request('http://video.google.com/videoplay?docid=%s&hl=en&oe=utf-8' % video_id)
  1238. try:
  1239. self.report_download_webpage(video_id)
  1240. webpage = urllib2.urlopen(request).read()
  1241. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1242. self._downloader.trouble(u'ERROR: Unable to retrieve video webpage: %s' % str(err))
  1243. return
  1244. # Extract URL, uploader, and title from webpage
  1245. self.report_extraction(video_id)
  1246. mobj = re.search(r"download_url:'([^']+)'", webpage)
  1247. if mobj is None:
  1248. video_extension = 'flv'
  1249. mobj = re.search(r"(?i)videoUrl\\x3d(.+?)\\x26", webpage)
  1250. if mobj is None:
  1251. self._downloader.trouble(u'ERROR: unable to extract media URL')
  1252. return
  1253. mediaURL = urllib.unquote(mobj.group(1))
  1254. mediaURL = mediaURL.replace('\\x3d', '\x3d')
  1255. mediaURL = mediaURL.replace('\\x26', '\x26')
  1256. video_url = mediaURL
  1257. mobj = re.search(r'<title>(.*)</title>', webpage)
  1258. if mobj is None:
  1259. self._downloader.trouble(u'ERROR: unable to extract title')
  1260. return
  1261. video_title = mobj.group(1).decode('utf-8')
  1262. video_title = sanitize_title(video_title)
  1263. simple_title = re.sub(ur'(?u)([^%s]+)' % simple_title_chars, ur'_', video_title)
  1264. # Extract video description
  1265. mobj = re.search(r'<span id=short-desc-content>([^<]*)</span>', webpage)
  1266. if mobj is None:
  1267. self._downloader.trouble(u'ERROR: unable to extract video description')
  1268. return
  1269. video_description = mobj.group(1).decode('utf-8')
  1270. if not video_description:
  1271. video_description = 'No description available.'
  1272. # Extract video thumbnail
  1273. if self._downloader.params.get('forcethumbnail', False):
  1274. request = urllib2.Request('http://video.google.com/videosearch?q=%s+site:video.google.com&hl=en' % abs(int(video_id)))
  1275. try:
  1276. webpage = urllib2.urlopen(request).read()
  1277. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1278. self._downloader.trouble(u'ERROR: Unable to retrieve video webpage: %s' % str(err))
  1279. return
  1280. mobj = re.search(r'<img class=thumbnail-img (?:.* )?src=(http.*)>', webpage)
  1281. if mobj is None:
  1282. self._downloader.trouble(u'ERROR: unable to extract video thumbnail')
  1283. return
  1284. video_thumbnail = mobj.group(1)
  1285. else: # we need something to pass to process_info
  1286. video_thumbnail = ''
  1287. try:
  1288. # Process video information
  1289. self._downloader.process_info({
  1290. 'id': video_id.decode('utf-8'),
  1291. 'url': video_url.decode('utf-8'),
  1292. 'uploader': u'NA',
  1293. 'upload_date': u'NA',
  1294. 'title': video_title,
  1295. 'stitle': simple_title,
  1296. 'ext': video_extension.decode('utf-8'),
  1297. 'format': u'NA',
  1298. 'player_url': None,
  1299. })
  1300. except UnavailableVideoError:
  1301. self._downloader.trouble(u'\nERROR: unable to download video')
  1302. class PhotobucketIE(InfoExtractor):
  1303. """Information extractor for photobucket.com."""
  1304. _VALID_URL = r'(?:http://)?(?:[a-z0-9]+\.)?photobucket\.com/.*[\?\&]current=(.*\.flv)'
  1305. def __init__(self, downloader=None):
  1306. InfoExtractor.__init__(self, downloader)
  1307. @staticmethod
  1308. def suitable(url):
  1309. return (re.match(PhotobucketIE._VALID_URL, url) is not None)
  1310. def report_download_webpage(self, video_id):
  1311. """Report webpage download."""
  1312. self._downloader.to_screen(u'[photobucket] %s: Downloading webpage' % video_id)
  1313. def report_extraction(self, video_id):
  1314. """Report information extraction."""
  1315. self._downloader.to_screen(u'[photobucket] %s: Extracting information' % video_id)
  1316. def _real_initialize(self):
  1317. return
  1318. def _real_extract(self, url):
  1319. # Extract id from URL
  1320. mobj = re.match(self._VALID_URL, url)
  1321. if mobj is None:
  1322. self._downloader.trouble(u'ERROR: Invalid URL: %s' % url)
  1323. return
  1324. # At this point we have a new video
  1325. self._downloader.increment_downloads()
  1326. video_id = mobj.group(1)
  1327. video_extension = 'flv'
  1328. # Retrieve video webpage to extract further information
  1329. request = urllib2.Request(url)
  1330. try:
  1331. self.report_download_webpage(video_id)
  1332. webpage = urllib2.urlopen(request).read()
  1333. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1334. self._downloader.trouble(u'ERROR: Unable to retrieve video webpage: %s' % str(err))
  1335. return
  1336. # Extract URL, uploader, and title from webpage
  1337. self.report_extraction(video_id)
  1338. mobj = re.search(r'<link rel="video_src" href=".*\?file=([^"]+)" />', webpage)
  1339. if mobj is None:
  1340. self._downloader.trouble(u'ERROR: unable to extract media URL')
  1341. return
  1342. mediaURL = urllib.unquote(mobj.group(1))
  1343. video_url = mediaURL
  1344. mobj = re.search(r'<title>(.*) video by (.*) - Photobucket</title>', webpage)
  1345. if mobj is None:
  1346. self._downloader.trouble(u'ERROR: unable to extract title')
  1347. return
  1348. video_title = mobj.group(1).decode('utf-8')
  1349. video_title = sanitize_title(video_title)
  1350. simple_title = re.sub(ur'(?u)([^%s]+)' % simple_title_chars, ur'_', video_title)
  1351. video_uploader = mobj.group(2).decode('utf-8')
  1352. try:
  1353. # Process video information
  1354. self._downloader.process_info({
  1355. 'id': video_id.decode('utf-8'),
  1356. 'url': video_url.decode('utf-8'),
  1357. 'uploader': video_uploader,
  1358. 'upload_date': u'NA',
  1359. 'title': video_title,
  1360. 'stitle': simple_title,
  1361. 'ext': video_extension.decode('utf-8'),
  1362. 'format': u'NA',
  1363. 'player_url': None,
  1364. })
  1365. except UnavailableVideoError:
  1366. self._downloader.trouble(u'\nERROR: unable to download video')
  1367. class YahooIE(InfoExtractor):
  1368. """Information extractor for video.yahoo.com."""
  1369. # _VALID_URL matches all Yahoo! Video URLs
  1370. # _VPAGE_URL matches only the extractable '/watch/' URLs
  1371. _VALID_URL = r'(?:http://)?(?:[a-z]+\.)?video\.yahoo\.com/(?:watch|network)/([0-9]+)(?:/|\?v=)([0-9]+)(?:[#\?].*)?'
  1372. _VPAGE_URL = r'(?:http://)?video\.yahoo\.com/watch/([0-9]+)/([0-9]+)(?:[#\?].*)?'
  1373. def __init__(self, downloader=None):
  1374. InfoExtractor.__init__(self, downloader)
  1375. @staticmethod
  1376. def suitable(url):
  1377. return (re.match(YahooIE._VALID_URL, url) is not None)
  1378. def report_download_webpage(self, video_id):
  1379. """Report webpage download."""
  1380. self._downloader.to_screen(u'[video.yahoo] %s: Downloading webpage' % video_id)
  1381. def report_extraction(self, video_id):
  1382. """Report information extraction."""
  1383. self._downloader.to_screen(u'[video.yahoo] %s: Extracting information' % video_id)
  1384. def _real_initialize(self):
  1385. return
  1386. def _real_extract(self, url, new_video=True):
  1387. # Extract ID from URL
  1388. mobj = re.match(self._VALID_URL, url)
  1389. if mobj is None:
  1390. self._downloader.trouble(u'ERROR: Invalid URL: %s' % url)
  1391. return
  1392. # At this point we have a new video
  1393. self._downloader.increment_downloads()
  1394. video_id = mobj.group(2)
  1395. video_extension = 'flv'
  1396. # Rewrite valid but non-extractable URLs as
  1397. # extractable English language /watch/ URLs
  1398. if re.match(self._VPAGE_URL, url) is None:
  1399. request = urllib2.Request(url)
  1400. try:
  1401. webpage = urllib2.urlopen(request).read()
  1402. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1403. self._downloader.trouble(u'ERROR: Unable to retrieve video webpage: %s' % str(err))
  1404. return
  1405. mobj = re.search(r'\("id", "([0-9]+)"\);', webpage)
  1406. if mobj is None:
  1407. self._downloader.trouble(u'ERROR: Unable to extract id field')
  1408. return
  1409. yahoo_id = mobj.group(1)
  1410. mobj = re.search(r'\("vid", "([0-9]+)"\);', webpage)
  1411. if mobj is None:
  1412. self._downloader.trouble(u'ERROR: Unable to extract vid field')
  1413. return
  1414. yahoo_vid = mobj.group(1)
  1415. url = 'http://video.yahoo.com/watch/%s/%s' % (yahoo_vid, yahoo_id)
  1416. return self._real_extract(url, new_video=False)
  1417. # Retrieve video webpage to extract further information
  1418. request = urllib2.Request(url)
  1419. try:
  1420. self.report_download_webpage(video_id)
  1421. webpage = urllib2.urlopen(request).read()
  1422. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1423. self._downloader.trouble(u'ERROR: Unable to retrieve video webpage: %s' % str(err))
  1424. return
  1425. # Extract uploader and title from webpage
  1426. self.report_extraction(video_id)
  1427. mobj = re.search(r'<meta name="title" content="(.*)" />', webpage)
  1428. if mobj is None:
  1429. self._downloader.trouble(u'ERROR: unable to extract video title')
  1430. return
  1431. video_title = mobj.group(1).decode('utf-8')
  1432. simple_title = re.sub(ur'(?u)([^%s]+)' % simple_title_chars, ur'_', video_title)
  1433. mobj = re.search(r'<h2 class="ti-5"><a href="http://video\.yahoo\.com/(people|profile)/[0-9]+" beacon=".*">(.*)</a></h2>', webpage)
  1434. if mobj is None:
  1435. self._downloader.trouble(u'ERROR: unable to extract video uploader')
  1436. return
  1437. video_uploader = mobj.group(1).decode('utf-8')
  1438. # Extract video thumbnail
  1439. mobj = re.search(r'<link rel="image_src" href="(.*)" />', webpage)
  1440. if mobj is None:
  1441. self._downloader.trouble(u'ERROR: unable to extract video thumbnail')
  1442. return
  1443. video_thumbnail = mobj.group(1).decode('utf-8')
  1444. # Extract video description
  1445. mobj = re.search(r'<meta name="description" content="(.*)" />', webpage)
  1446. if mobj is None:
  1447. self._downloader.trouble(u'ERROR: unable to extract video description')
  1448. return
  1449. video_description = mobj.group(1).decode('utf-8')
  1450. if not video_description: video_description = 'No description available.'
  1451. # Extract video height and width
  1452. mobj = re.search(r'<meta name="video_height" content="([0-9]+)" />', webpage)
  1453. if mobj is None:
  1454. self._downloader.trouble(u'ERROR: unable to extract video height')
  1455. return
  1456. yv_video_height = mobj.group(1)
  1457. mobj = re.search(r'<meta name="video_width" content="([0-9]+)" />', webpage)
  1458. if mobj is None:
  1459. self._downloader.trouble(u'ERROR: unable to extract video width')
  1460. return
  1461. yv_video_width = mobj.group(1)
  1462. # Retrieve video playlist to extract media URL
  1463. # I'm not completely sure what all these options are, but we
  1464. # seem to need most of them, otherwise the server sends a 401.
  1465. yv_lg = 'R0xx6idZnW2zlrKP8xxAIR' # not sure what this represents
  1466. yv_bitrate = '700' # according to Wikipedia this is hard-coded
  1467. request = urllib2.Request('http://cosmos.bcst.yahoo.com/up/yep/process/getPlaylistFOP.php?node_id=' + video_id +
  1468. '&tech=flash&mode=playlist&lg=' + yv_lg + '&bitrate=' + yv_bitrate + '&vidH=' + yv_video_height +
  1469. '&vidW=' + yv_video_width + '&swf=as3&rd=video.yahoo.com&tk=null&adsupported=v1,v2,&eventid=1301797')
  1470. try:
  1471. self.report_download_webpage(video_id)
  1472. webpage = urllib2.urlopen(request).read()
  1473. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1474. self._downloader.trouble(u'ERROR: Unable to retrieve video webpage: %s' % str(err))
  1475. return
  1476. # Extract media URL from playlist XML
  1477. mobj = re.search(r'<STREAM APP="(http://.*)" FULLPATH="/?(/.*\.flv\?[^"]*)"', webpage)
  1478. if mobj is None:
  1479. self._downloader.trouble(u'ERROR: Unable to extract media URL')
  1480. return
  1481. video_url = urllib.unquote(mobj.group(1) + mobj.group(2)).decode('utf-8')
  1482. video_url = re.sub(r'(?u)&(.+?);', htmlentity_transform, video_url)
  1483. try:
  1484. # Process video information
  1485. self._downloader.process_info({
  1486. 'id': video_id.decode('utf-8'),
  1487. 'url': video_url,
  1488. 'uploader': video_uploader,
  1489. 'upload_date': u'NA',
  1490. 'title': video_title,
  1491. 'stitle': simple_title,
  1492. 'ext': video_extension.decode('utf-8'),
  1493. 'thumbnail': video_thumbnail.decode('utf-8'),
  1494. 'description': video_description,
  1495. 'thumbnail': video_thumbnail,
  1496. 'description': video_description,
  1497. 'player_url': None,
  1498. })
  1499. except UnavailableVideoError:
  1500. self._downloader.trouble(u'\nERROR: unable to download video')
  1501. class GenericIE(InfoExtractor):
  1502. """Generic last-resort information extractor."""
  1503. def __init__(self, downloader=None):
  1504. InfoExtractor.__init__(self, downloader)
  1505. @staticmethod
  1506. def suitable(url):
  1507. return True
  1508. def report_download_webpage(self, video_id):
  1509. """Report webpage download."""
  1510. self._downloader.to_screen(u'WARNING: Falling back on generic information extractor.')
  1511. self._downloader.to_screen(u'[generic] %s: Downloading webpage' % video_id)
  1512. def report_extraction(self, video_id):
  1513. """Report information extraction."""
  1514. self._downloader.to_screen(u'[generic] %s: Extracting information' % video_id)
  1515. def _real_initialize(self):
  1516. return
  1517. def _real_extract(self, url):
  1518. # At this point we have a new video
  1519. self._downloader.increment_downloads()
  1520. video_id = url.split('/')[-1]
  1521. request = urllib2.Request(url)
  1522. try:
  1523. self.report_download_webpage(video_id)
  1524. webpage = urllib2.urlopen(request).read()
  1525. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1526. self._downloader.trouble(u'ERROR: Unable to retrieve video webpage: %s' % str(err))
  1527. return
  1528. except ValueError, err:
  1529. # since this is the last-resort InfoExtractor, if
  1530. # this error is thrown, it'll be thrown here
  1531. self._downloader.trouble(u'ERROR: Invalid URL: %s' % url)
  1532. return
  1533. self.report_extraction(video_id)
  1534. # Start with something easy: JW Player in SWFObject
  1535. mobj = re.search(r'flashvars: [\'"](?:.*&)?file=(http[^\'"&]*)', webpage)
  1536. if mobj is None:
  1537. # Broaden the search a little bit
  1538. mobj = re.search(r'[^A-Za-z0-9]?(?:file|source)=(http[^\'"&]*)', webpage)
  1539. if mobj is None:
  1540. self._downloader.trouble(u'ERROR: Invalid URL: %s' % url)
  1541. return
  1542. # It's possible that one of the regexes
  1543. # matched, but returned an empty group:
  1544. if mobj.group(1) is None:
  1545. self._downloader.trouble(u'ERROR: Invalid URL: %s' % url)
  1546. return
  1547. video_url = urllib.unquote(mobj.group(1))
  1548. video_id = os.path.basename(video_url)
  1549. # here's a fun little line of code for you:
  1550. video_extension = os.path.splitext(video_id)[1][1:]
  1551. video_id = os.path.splitext(video_id)[0]
  1552. # it's tempting to parse this further, but you would
  1553. # have to take into account all the variations like
  1554. # Video Title - Site Name
  1555. # Site Name | Video Title
  1556. # Video Title - Tagline | Site Name
  1557. # and so on and so forth; it's just not practical
  1558. mobj = re.search(r'<title>(.*)</title>', webpage)
  1559. if mobj is None:
  1560. self._downloader.trouble(u'ERROR: unable to extract title')
  1561. return
  1562. video_title = mobj.group(1).decode('utf-8')
  1563. video_title = sanitize_title(video_title)
  1564. simple_title = re.sub(ur'(?u)([^%s]+)' % simple_title_chars, ur'_', video_title)
  1565. # video uploader is domain name
  1566. mobj = re.match(r'(?:https?://)?([^/]*)/.*', url)
  1567. if mobj is None:
  1568. self._downloader.trouble(u'ERROR: unable to extract title')
  1569. return
  1570. video_uploader = mobj.group(1).decode('utf-8')
  1571. try:
  1572. # Process video information
  1573. self._downloader.process_info({
  1574. 'id': video_id.decode('utf-8'),
  1575. 'url': video_url.decode('utf-8'),
  1576. 'uploader': video_uploader,
  1577. 'upload_date': u'NA',
  1578. 'title': video_title,
  1579. 'stitle': simple_title,
  1580. 'ext': video_extension.decode('utf-8'),
  1581. 'format': u'NA',
  1582. 'player_url': None,
  1583. })
  1584. except UnavailableVideoError, err:
  1585. self._downloader.trouble(u'\nERROR: unable to download video')
  1586. class YoutubeSearchIE(InfoExtractor):
  1587. """Information Extractor for YouTube search queries."""
  1588. _VALID_QUERY = r'ytsearch(\d+|all)?:[\s\S]+'
  1589. _TEMPLATE_URL = 'http://www.youtube.com/results?search_query=%s&page=%s&gl=US&hl=en'
  1590. _VIDEO_INDICATOR = r'href="/watch\?v=.+?"'
  1591. _MORE_PAGES_INDICATOR = r'(?m)>\s*Next\s*</a>'
  1592. _youtube_ie = None
  1593. _max_youtube_results = 1000
  1594. def __init__(self, youtube_ie, downloader=None):
  1595. InfoExtractor.__init__(self, downloader)
  1596. self._youtube_ie = youtube_ie
  1597. @staticmethod
  1598. def suitable(url):
  1599. return (re.match(YoutubeSearchIE._VALID_QUERY, url) is not None)
  1600. def report_download_page(self, query, pagenum):
  1601. """Report attempt to download playlist page with given number."""
  1602. query = query.decode(preferredencoding())
  1603. self._downloader.to_screen(u'[youtube] query "%s": Downloading page %s' % (query, pagenum))
  1604. def _real_initialize(self):
  1605. self._youtube_ie.initialize()
  1606. def _real_extract(self, query):
  1607. mobj = re.match(self._VALID_QUERY, query)
  1608. if mobj is None:
  1609. self._downloader.trouble(u'ERROR: invalid search query "%s"' % query)
  1610. return
  1611. prefix, query = query.split(':')
  1612. prefix = prefix[8:]
  1613. query = query.encode('utf-8')
  1614. if prefix == '':
  1615. self._download_n_results(query, 1)
  1616. return
  1617. elif prefix == 'all':
  1618. self._download_n_results(query, self._max_youtube_results)
  1619. return
  1620. else:
  1621. try:
  1622. n = long(prefix)
  1623. if n <= 0:
  1624. self._downloader.trouble(u'ERROR: invalid download number %s for query "%s"' % (n, query))
  1625. return
  1626. elif n > self._max_youtube_results:
  1627. self._downloader.to_stderr(u'WARNING: ytsearch returns max %i results (you requested %i)' % (self._max_youtube_results, n))
  1628. n = self._max_youtube_results
  1629. self._download_n_results(query, n)
  1630. return
  1631. except ValueError: # parsing prefix as integer fails
  1632. self._download_n_results(query, 1)
  1633. return
  1634. def _download_n_results(self, query, n):
  1635. """Downloads a specified number of results for a query"""
  1636. video_ids = []
  1637. already_seen = set()
  1638. pagenum = 1
  1639. while True:
  1640. self.report_download_page(query, pagenum)
  1641. result_url = self._TEMPLATE_URL % (urllib.quote_plus(query), pagenum)
  1642. request = urllib2.Request(result_url)
  1643. try:
  1644. page = urllib2.urlopen(request).read()
  1645. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1646. self._downloader.trouble(u'ERROR: unable to download webpage: %s' % str(err))
  1647. return
  1648. # Extract video identifiers
  1649. for mobj in re.finditer(self._VIDEO_INDICATOR, page):
  1650. video_id = page[mobj.span()[0]:mobj.span()[1]].split('=')[2][:-1]
  1651. if video_id not in already_seen:
  1652. video_ids.append(video_id)
  1653. already_seen.add(video_id)
  1654. if len(video_ids) == n:
  1655. # Specified n videos reached
  1656. for id in video_ids:
  1657. self._youtube_ie.extract('http://www.youtube.com/watch?v=%s' % id)
  1658. return
  1659. if re.search(self._MORE_PAGES_INDICATOR, page) is None:
  1660. for id in video_ids:
  1661. self._youtube_ie.extract('http://www.youtube.com/watch?v=%s' % id)
  1662. return
  1663. pagenum = pagenum + 1
  1664. class GoogleSearchIE(InfoExtractor):
  1665. """Information Extractor for Google Video search queries."""
  1666. _VALID_QUERY = r'gvsearch(\d+|all)?:[\s\S]+'
  1667. _TEMPLATE_URL = 'http://video.google.com/videosearch?q=%s+site:video.google.com&start=%s&hl=en'
  1668. _VIDEO_INDICATOR = r'videoplay\?docid=([^\&>]+)\&'
  1669. _MORE_PAGES_INDICATOR = r'<span>Next</span>'
  1670. _google_ie = None
  1671. _max_google_results = 1000
  1672. def __init__(self, google_ie, downloader=None):
  1673. InfoExtractor.__init__(self, downloader)
  1674. self._google_ie = google_ie
  1675. @staticmethod
  1676. def suitable(url):
  1677. return (re.match(GoogleSearchIE._VALID_QUERY, url) is not None)
  1678. def report_download_page(self, query, pagenum):
  1679. """Report attempt to download playlist page with given number."""
  1680. query = query.decode(preferredencoding())
  1681. self._downloader.to_screen(u'[video.google] query "%s": Downloading page %s' % (query, pagenum))
  1682. def _real_initialize(self):
  1683. self._google_ie.initialize()
  1684. def _real_extract(self, query):
  1685. mobj = re.match(self._VALID_QUERY, query)
  1686. if mobj is None:
  1687. self._downloader.trouble(u'ERROR: invalid search query "%s"' % query)
  1688. return
  1689. prefix, query = query.split(':')
  1690. prefix = prefix[8:]
  1691. query = query.encode('utf-8')
  1692. if prefix == '':
  1693. self._download_n_results(query, 1)
  1694. return
  1695. elif prefix == 'all':
  1696. self._download_n_results(query, self._max_google_results)
  1697. return
  1698. else:
  1699. try:
  1700. n = long(prefix)
  1701. if n <= 0:
  1702. self._downloader.trouble(u'ERROR: invalid download number %s for query "%s"' % (n, query))
  1703. return
  1704. elif n > self._max_google_results:
  1705. self._downloader.to_stderr(u'WARNING: gvsearch returns max %i results (you requested %i)' % (self._max_google_results, n))
  1706. n = self._max_google_results
  1707. self._download_n_results(query, n)
  1708. return
  1709. except ValueError: # parsing prefix as integer fails
  1710. self._download_n_results(query, 1)
  1711. return
  1712. def _download_n_results(self, query, n):
  1713. """Downloads a specified number of results for a query"""
  1714. video_ids = []
  1715. already_seen = set()
  1716. pagenum = 1
  1717. while True:
  1718. self.report_download_page(query, pagenum)
  1719. result_url = self._TEMPLATE_URL % (urllib.quote_plus(query), pagenum)
  1720. request = urllib2.Request(result_url)
  1721. try:
  1722. page = urllib2.urlopen(request).read()
  1723. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1724. self._downloader.trouble(u'ERROR: unable to download webpage: %s' % str(err))
  1725. return
  1726. # Extract video identifiers
  1727. for mobj in re.finditer(self._VIDEO_INDICATOR, page):
  1728. video_id = mobj.group(1)
  1729. if video_id not in already_seen:
  1730. video_ids.append(video_id)
  1731. already_seen.add(video_id)
  1732. if len(video_ids) == n:
  1733. # Specified n videos reached
  1734. for id in video_ids:
  1735. self._google_ie.extract('http://video.google.com/videoplay?docid=%s' % id)
  1736. return
  1737. if re.search(self._MORE_PAGES_INDICATOR, page) is None:
  1738. for id in video_ids:
  1739. self._google_ie.extract('http://video.google.com/videoplay?docid=%s' % id)
  1740. return
  1741. pagenum = pagenum + 1
  1742. class YahooSearchIE(InfoExtractor):
  1743. """Information Extractor for Yahoo! Video search queries."""
  1744. _VALID_QUERY = r'yvsearch(\d+|all)?:[\s\S]+'
  1745. _TEMPLATE_URL = 'http://video.yahoo.com/search/?p=%s&o=%s'
  1746. _VIDEO_INDICATOR = r'href="http://video\.yahoo\.com/watch/([0-9]+/[0-9]+)"'
  1747. _MORE_PAGES_INDICATOR = r'\s*Next'
  1748. _yahoo_ie = None
  1749. _max_yahoo_results = 1000
  1750. def __init__(self, yahoo_ie, downloader=None):
  1751. InfoExtractor.__init__(self, downloader)
  1752. self._yahoo_ie = yahoo_ie
  1753. @staticmethod
  1754. def suitable(url):
  1755. return (re.match(YahooSearchIE._VALID_QUERY, url) is not None)
  1756. def report_download_page(self, query, pagenum):
  1757. """Report attempt to download playlist page with given number."""
  1758. query = query.decode(preferredencoding())
  1759. self._downloader.to_screen(u'[video.yahoo] query "%s": Downloading page %s' % (query, pagenum))
  1760. def _real_initialize(self):
  1761. self._yahoo_ie.initialize()
  1762. def _real_extract(self, query):
  1763. mobj = re.match(self._VALID_QUERY, query)
  1764. if mobj is None:
  1765. self._downloader.trouble(u'ERROR: invalid search query "%s"' % query)
  1766. return
  1767. prefix, query = query.split(':')
  1768. prefix = prefix[8:]
  1769. query = query.encode('utf-8')
  1770. if prefix == '':
  1771. self._download_n_results(query, 1)
  1772. return
  1773. elif prefix == 'all':
  1774. self._download_n_results(query, self._max_yahoo_results)
  1775. return
  1776. else:
  1777. try:
  1778. n = long(prefix)
  1779. if n <= 0:
  1780. self._downloader.trouble(u'ERROR: invalid download number %s for query "%s"' % (n, query))
  1781. return
  1782. elif n > self._max_yahoo_results:
  1783. self._downloader.to_stderr(u'WARNING: yvsearch returns max %i results (you requested %i)' % (self._max_yahoo_results, n))
  1784. n = self._max_yahoo_results
  1785. self._download_n_results(query, n)
  1786. return
  1787. except ValueError: # parsing prefix as integer fails
  1788. self._download_n_results(query, 1)
  1789. return
  1790. def _download_n_results(self, query, n):
  1791. """Downloads a specified number of results for a query"""
  1792. video_ids = []
  1793. already_seen = set()
  1794. pagenum = 1
  1795. while True:
  1796. self.report_download_page(query, pagenum)
  1797. result_url = self._TEMPLATE_URL % (urllib.quote_plus(query), pagenum)
  1798. request = urllib2.Request(result_url)
  1799. try:
  1800. page = urllib2.urlopen(request).read()
  1801. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1802. self._downloader.trouble(u'ERROR: unable to download webpage: %s' % str(err))
  1803. return
  1804. # Extract video identifiers
  1805. for mobj in re.finditer(self._VIDEO_INDICATOR, page):
  1806. video_id = mobj.group(1)
  1807. if video_id not in already_seen:
  1808. video_ids.append(video_id)
  1809. already_seen.add(video_id)
  1810. if len(video_ids) == n:
  1811. # Specified n videos reached
  1812. for id in video_ids:
  1813. self._yahoo_ie.extract('http://video.yahoo.com/watch/%s' % id)
  1814. return
  1815. if re.search(self._MORE_PAGES_INDICATOR, page) is None:
  1816. for id in video_ids:
  1817. self._yahoo_ie.extract('http://video.yahoo.com/watch/%s' % id)
  1818. return
  1819. pagenum = pagenum + 1
  1820. class YoutubePlaylistIE(InfoExtractor):
  1821. """Information Extractor for YouTube playlists."""
  1822. _VALID_URL = r'(?:http://)?(?:\w+\.)?youtube.com/(?:(?:view_play_list|my_playlists|artist)\?.*?(p|a)=|user/.*?/user/|p/|user/.*?#[pg]/c/)([0-9A-Za-z]+)(?:/.*?/([0-9A-Za-z_-]+))?.*'
  1823. _TEMPLATE_URL = 'http://www.youtube.com/%s?%s=%s&page=%s&gl=US&hl=en'
  1824. _VIDEO_INDICATOR = r'/watch\?v=(.+?)&'
  1825. _MORE_PAGES_INDICATOR = r'(?m)>\s*Next\s*</a>'
  1826. _youtube_ie = None
  1827. def __init__(self, youtube_ie, downloader=None):
  1828. InfoExtractor.__init__(self, downloader)
  1829. self._youtube_ie = youtube_ie
  1830. @staticmethod
  1831. def suitable(url):
  1832. return (re.match(YoutubePlaylistIE._VALID_URL, url) is not None)
  1833. def report_download_page(self, playlist_id, pagenum):
  1834. """Report attempt to download playlist page with given number."""
  1835. self._downloader.to_screen(u'[youtube] PL %s: Downloading page #%s' % (playlist_id, pagenum))
  1836. def _real_initialize(self):
  1837. self._youtube_ie.initialize()
  1838. def _real_extract(self, url):
  1839. # Extract playlist id
  1840. mobj = re.match(self._VALID_URL, url)
  1841. if mobj is None:
  1842. self._downloader.trouble(u'ERROR: invalid url: %s' % url)
  1843. return
  1844. # Single video case
  1845. if mobj.group(3) is not None:
  1846. self._youtube_ie.extract(mobj.group(3))
  1847. return
  1848. # Download playlist pages
  1849. # prefix is 'p' as default for playlists but there are other types that need extra care
  1850. playlist_prefix = mobj.group(1)
  1851. if playlist_prefix == 'a':
  1852. playlist_access = 'artist'
  1853. else:
  1854. playlist_prefix = 'p'
  1855. playlist_access = 'view_play_list'
  1856. playlist_id = mobj.group(2)
  1857. video_ids = []
  1858. pagenum = 1
  1859. while True:
  1860. self.report_download_page(playlist_id, pagenum)
  1861. request = urllib2.Request(self._TEMPLATE_URL % (playlist_access, playlist_prefix, playlist_id, pagenum))
  1862. try:
  1863. page = urllib2.urlopen(request).read()
  1864. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1865. self._downloader.trouble(u'ERROR: unable to download webpage: %s' % str(err))
  1866. return
  1867. # Extract video identifiers
  1868. ids_in_page = []
  1869. for mobj in re.finditer(self._VIDEO_INDICATOR, page):
  1870. if mobj.group(1) not in ids_in_page:
  1871. ids_in_page.append(mobj.group(1))
  1872. video_ids.extend(ids_in_page)
  1873. if re.search(self._MORE_PAGES_INDICATOR, page) is None:
  1874. break
  1875. pagenum = pagenum + 1
  1876. playliststart = self._downloader.params.get('playliststart', 1) - 1
  1877. playlistend = self._downloader.params.get('playlistend', -1)
  1878. video_ids = video_ids[playliststart:playlistend]
  1879. for id in video_ids:
  1880. self._youtube_ie.extract('http://www.youtube.com/watch?v=%s' % id)
  1881. return
  1882. class YoutubeUserIE(InfoExtractor):
  1883. """Information Extractor for YouTube users."""
  1884. _VALID_URL = r'(?:(?:(?:http://)?(?:\w+\.)?youtube.com/user/)|ytuser:)([A-Za-z0-9_-]+)'
  1885. _TEMPLATE_URL = 'http://gdata.youtube.com/feeds/api/users/%s'
  1886. _GDATA_PAGE_SIZE = 50
  1887. _GDATA_URL = 'http://gdata.youtube.com/feeds/api/users/%s/uploads?max-results=%d&start-index=%d'
  1888. _VIDEO_INDICATOR = r'/watch\?v=(.+?)&'
  1889. _youtube_ie = None
  1890. def __init__(self, youtube_ie, downloader=None):
  1891. InfoExtractor.__init__(self, downloader)
  1892. self._youtube_ie = youtube_ie
  1893. @staticmethod
  1894. def suitable(url):
  1895. return (re.match(YoutubeUserIE._VALID_URL, url) is not None)
  1896. def report_download_page(self, username, start_index):
  1897. """Report attempt to download user page."""
  1898. self._downloader.to_screen(u'[youtube] user %s: Downloading video ids from %d to %d' %
  1899. (username, start_index, start_index + self._GDATA_PAGE_SIZE))
  1900. def _real_initialize(self):
  1901. self._youtube_ie.initialize()
  1902. def _real_extract(self, url):
  1903. # Extract username
  1904. mobj = re.match(self._VALID_URL, url)
  1905. if mobj is None:
  1906. self._downloader.trouble(u'ERROR: invalid url: %s' % url)
  1907. return
  1908. username = mobj.group(1)
  1909. # Download video ids using YouTube Data API. Result size per
  1910. # query is limited (currently to 50 videos) so we need to query
  1911. # page by page until there are no video ids - it means we got
  1912. # all of them.
  1913. video_ids = []
  1914. pagenum = 0
  1915. while True:
  1916. start_index = pagenum * self._GDATA_PAGE_SIZE + 1
  1917. self.report_download_page(username, start_index)
  1918. request = urllib2.Request(self._GDATA_URL % (username, self._GDATA_PAGE_SIZE, start_index))
  1919. try:
  1920. page = urllib2.urlopen(request).read()
  1921. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1922. self._downloader.trouble(u'ERROR: unable to download webpage: %s' % str(err))
  1923. return
  1924. # Extract video identifiers
  1925. ids_in_page = []
  1926. for mobj in re.finditer(self._VIDEO_INDICATOR, page):
  1927. if mobj.group(1) not in ids_in_page:
  1928. ids_in_page.append(mobj.group(1))
  1929. video_ids.extend(ids_in_page)
  1930. # A little optimization - if current page is not
  1931. # "full", ie. does not contain PAGE_SIZE video ids then
  1932. # we can assume that this page is the last one - there
  1933. # are no more ids on further pages - no need to query
  1934. # again.
  1935. if len(ids_in_page) < self._GDATA_PAGE_SIZE:
  1936. break
  1937. pagenum += 1
  1938. all_ids_count = len(video_ids)
  1939. playliststart = self._downloader.params.get('playliststart', 1) - 1
  1940. playlistend = self._downloader.params.get('playlistend', -1)
  1941. if playlistend == -1:
  1942. video_ids = video_ids[playliststart:]
  1943. else:
  1944. video_ids = video_ids[playliststart:playlistend]
  1945. self._downloader.to_screen("[youtube] user %s: Collected %d video ids (downloading %d of them)" %
  1946. (username, all_ids_count, len(video_ids)))
  1947. for video_id in video_ids:
  1948. self._youtube_ie.extract('http://www.youtube.com/watch?v=%s' % video_id)
  1949. class DepositFilesIE(InfoExtractor):
  1950. """Information extractor for depositfiles.com"""
  1951. _VALID_URL = r'(?:http://)?(?:\w+\.)?depositfiles.com/(?:../(?#locale))?files/(.+)'
  1952. def __init__(self, downloader=None):
  1953. InfoExtractor.__init__(self, downloader)
  1954. @staticmethod
  1955. def suitable(url):
  1956. return (re.match(DepositFilesIE._VALID_URL, url) is not None)
  1957. def report_download_webpage(self, file_id):
  1958. """Report webpage download."""
  1959. self._downloader.to_screen(u'[DepositFiles] %s: Downloading webpage' % file_id)
  1960. def report_extraction(self, file_id):
  1961. """Report information extraction."""
  1962. self._downloader.to_screen(u'[DepositFiles] %s: Extracting information' % file_id)
  1963. def _real_initialize(self):
  1964. return
  1965. def _real_extract(self, url):
  1966. # At this point we have a new file
  1967. self._downloader.increment_downloads()
  1968. file_id = url.split('/')[-1]
  1969. # Rebuild url in english locale
  1970. url = 'http://depositfiles.com/en/files/' + file_id
  1971. # Retrieve file webpage with 'Free download' button pressed
  1972. free_download_indication = { 'gateway_result' : '1' }
  1973. request = urllib2.Request(url, urllib.urlencode(free_download_indication))
  1974. try:
  1975. self.report_download_webpage(file_id)
  1976. webpage = urllib2.urlopen(request).read()
  1977. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1978. self._downloader.trouble(u'ERROR: Unable to retrieve file webpage: %s' % str(err))
  1979. return
  1980. # Search for the real file URL
  1981. mobj = re.search(r'<form action="(http://fileshare.+?)"', webpage)
  1982. if (mobj is None) or (mobj.group(1) is None):
  1983. # Try to figure out reason of the error.
  1984. mobj = re.search(r'<strong>(Attention.*?)</strong>', webpage, re.DOTALL)
  1985. if (mobj is not None) and (mobj.group(1) is not None):
  1986. restriction_message = re.sub('\s+', ' ', mobj.group(1)).strip()
  1987. self._downloader.trouble(u'ERROR: %s' % restriction_message)
  1988. else:
  1989. self._downloader.trouble(u'ERROR: unable to extract download URL from: %s' % url)
  1990. return
  1991. file_url = mobj.group(1)
  1992. file_extension = os.path.splitext(file_url)[1][1:]
  1993. # Search for file title
  1994. mobj = re.search(r'<b title="(.*?)">', webpage)
  1995. if mobj is None:
  1996. self._downloader.trouble(u'ERROR: unable to extract title')
  1997. return
  1998. file_title = mobj.group(1).decode('utf-8')
  1999. try:
  2000. # Process file information
  2001. self._downloader.process_info({
  2002. 'id': file_id.decode('utf-8'),
  2003. 'url': file_url.decode('utf-8'),
  2004. 'uploader': u'NA',
  2005. 'upload_date': u'NA',
  2006. 'title': file_title,
  2007. 'stitle': file_title,
  2008. 'ext': file_extension.decode('utf-8'),
  2009. 'format': u'NA',
  2010. 'player_url': None,
  2011. })
  2012. except UnavailableVideoError, err:
  2013. self._downloader.trouble(u'ERROR: unable to download file')
  2014. class FacebookIE(InfoExtractor):
  2015. """Information Extractor for Facebook"""
  2016. _VALID_URL = r'^(?:https?://)?(?:\w+\.)?facebook.com/video/video.php\?(?:.*?)v=(?P<ID>\d+)(?:.*)'
  2017. _LOGIN_URL = 'https://login.facebook.com/login.php?m&next=http%3A%2F%2Fm.facebook.com%2Fhome.php&'
  2018. _NETRC_MACHINE = 'facebook'
  2019. _available_formats = ['highqual', 'lowqual']
  2020. _video_extensions = {
  2021. 'highqual': 'mp4',
  2022. 'lowqual': 'mp4',
  2023. }
  2024. def __init__(self, downloader=None):
  2025. InfoExtractor.__init__(self, downloader)
  2026. @staticmethod
  2027. def suitable(url):
  2028. return (re.match(FacebookIE._VALID_URL, url) is not None)
  2029. def _reporter(self, message):
  2030. """Add header and report message."""
  2031. self._downloader.to_screen(u'[facebook] %s' % message)
  2032. def report_login(self):
  2033. """Report attempt to log in."""
  2034. self._reporter(u'Logging in')
  2035. def report_video_webpage_download(self, video_id):
  2036. """Report attempt to download video webpage."""
  2037. self._reporter(u'%s: Downloading video webpage' % video_id)
  2038. def report_information_extraction(self, video_id):
  2039. """Report attempt to extract video information."""
  2040. self._reporter(u'%s: Extracting video information' % video_id)
  2041. def _parse_page(self, video_webpage):
  2042. """Extract video information from page"""
  2043. # General data
  2044. data = {'title': r'class="video_title datawrap">(.*?)</',
  2045. 'description': r'<div class="datawrap">(.*?)</div>',
  2046. 'owner': r'\("video_owner_name", "(.*?)"\)',
  2047. 'upload_date': r'data-date="(.*?)"',
  2048. 'thumbnail': r'\("thumb_url", "(?P<THUMB>.*?)"\)',
  2049. }
  2050. video_info = {}
  2051. for piece in data.keys():
  2052. mobj = re.search(data[piece], video_webpage)
  2053. if mobj is not None:
  2054. video_info[piece] = urllib.unquote_plus(mobj.group(1).decode("unicode_escape"))
  2055. # Video urls
  2056. video_urls = {}
  2057. for fmt in self._available_formats:
  2058. mobj = re.search(r'\("%s_src\", "(.+?)"\)' % fmt, video_webpage)
  2059. if mobj is not None:
  2060. # URL is in a Javascript segment inside an escaped Unicode format within
  2061. # the generally utf-8 page
  2062. video_urls[fmt] = urllib.unquote_plus(mobj.group(1).decode("unicode_escape"))
  2063. video_info['video_urls'] = video_urls
  2064. return video_info
  2065. def _real_initialize(self):
  2066. if self._downloader is None:
  2067. return
  2068. useremail = None
  2069. password = None
  2070. downloader_params = self._downloader.params
  2071. # Attempt to use provided username and password or .netrc data
  2072. if downloader_params.get('username', None) is not None:
  2073. useremail = downloader_params['username']
  2074. password = downloader_params['password']
  2075. elif downloader_params.get('usenetrc', False):
  2076. try:
  2077. info = netrc.netrc().authenticators(self._NETRC_MACHINE)
  2078. if info is not None:
  2079. useremail = info[0]
  2080. password = info[2]
  2081. else:
  2082. raise netrc.NetrcParseError('No authenticators for %s' % self._NETRC_MACHINE)
  2083. except (IOError, netrc.NetrcParseError), err:
  2084. self._downloader.to_stderr(u'WARNING: parsing .netrc: %s' % str(err))
  2085. return
  2086. if useremail is None:
  2087. return
  2088. # Log in
  2089. login_form = {
  2090. 'email': useremail,
  2091. 'pass': password,
  2092. 'login': 'Log+In'
  2093. }
  2094. request = urllib2.Request(self._LOGIN_URL, urllib.urlencode(login_form))
  2095. try:
  2096. self.report_login()
  2097. login_results = urllib2.urlopen(request).read()
  2098. if re.search(r'<form(.*)name="login"(.*)</form>', login_results) is not None:
  2099. self._downloader.to_stderr(u'WARNING: unable to log in: bad username/password, or exceded login rate limit (~3/min). Check credentials or wait.')
  2100. return
  2101. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  2102. self._downloader.to_stderr(u'WARNING: unable to log in: %s' % str(err))
  2103. return
  2104. def _real_extract(self, url):
  2105. mobj = re.match(self._VALID_URL, url)
  2106. if mobj is None:
  2107. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  2108. return
  2109. video_id = mobj.group('ID')
  2110. # Get video webpage
  2111. self.report_video_webpage_download(video_id)
  2112. request = urllib2.Request('https://www.facebook.com/video/video.php?v=%s' % video_id)
  2113. try:
  2114. page = urllib2.urlopen(request)
  2115. video_webpage = page.read()
  2116. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  2117. self._downloader.trouble(u'ERROR: unable to download video webpage: %s' % str(err))
  2118. return
  2119. # Start extracting information
  2120. self.report_information_extraction(video_id)
  2121. # Extract information
  2122. video_info = self._parse_page(video_webpage)
  2123. # uploader
  2124. if 'owner' not in video_info:
  2125. self._downloader.trouble(u'ERROR: unable to extract uploader nickname')
  2126. return
  2127. video_uploader = video_info['owner']
  2128. # title
  2129. if 'title' not in video_info:
  2130. self._downloader.trouble(u'ERROR: unable to extract video title')
  2131. return
  2132. video_title = video_info['title']
  2133. video_title = video_title.decode('utf-8')
  2134. video_title = sanitize_title(video_title)
  2135. # simplified title
  2136. simple_title = re.sub(ur'(?u)([^%s]+)' % simple_title_chars, ur'_', video_title)
  2137. simple_title = simple_title.strip(ur'_')
  2138. # thumbnail image
  2139. if 'thumbnail' not in video_info:
  2140. self._downloader.trouble(u'WARNING: unable to extract video thumbnail')
  2141. video_thumbnail = ''
  2142. else:
  2143. video_thumbnail = video_info['thumbnail']
  2144. # upload date
  2145. upload_date = u'NA'
  2146. if 'upload_date' in video_info:
  2147. upload_time = video_info['upload_date']
  2148. timetuple = email.utils.parsedate_tz(upload_time)
  2149. if timetuple is not None:
  2150. try:
  2151. upload_date = time.strftime('%Y%m%d', timetuple[0:9])
  2152. except:
  2153. pass
  2154. # description
  2155. video_description = video_info.get('description', 'No description available.')
  2156. url_map = video_info['video_urls']
  2157. if len(url_map.keys()) > 0:
  2158. # Decide which formats to download
  2159. req_format = self._downloader.params.get('format', None)
  2160. format_limit = self._downloader.params.get('format_limit', None)
  2161. if format_limit is not None and format_limit in self._available_formats:
  2162. format_list = self._available_formats[self._available_formats.index(format_limit):]
  2163. else:
  2164. format_list = self._available_formats
  2165. existing_formats = [x for x in format_list if x in url_map]
  2166. if len(existing_formats) == 0:
  2167. self._downloader.trouble(u'ERROR: no known formats available for video')
  2168. return
  2169. if req_format is None:
  2170. video_url_list = [(existing_formats[0], url_map[existing_formats[0]])] # Best quality
  2171. elif req_format == '-1':
  2172. video_url_list = [(f, url_map[f]) for f in existing_formats] # All formats
  2173. else:
  2174. # Specific format
  2175. if req_format not in url_map:
  2176. self._downloader.trouble(u'ERROR: requested format not available')
  2177. return
  2178. video_url_list = [(req_format, url_map[req_format])] # Specific format
  2179. for format_param, video_real_url in video_url_list:
  2180. # At this point we have a new video
  2181. self._downloader.increment_downloads()
  2182. # Extension
  2183. video_extension = self._video_extensions.get(format_param, 'mp4')
  2184. # Find the video URL in fmt_url_map or conn paramters
  2185. try:
  2186. # Process video information
  2187. self._downloader.process_info({
  2188. 'id': video_id.decode('utf-8'),
  2189. 'url': video_real_url.decode('utf-8'),
  2190. 'uploader': video_uploader.decode('utf-8'),
  2191. 'upload_date': upload_date,
  2192. 'title': video_title,
  2193. 'stitle': simple_title,
  2194. 'ext': video_extension.decode('utf-8'),
  2195. 'format': (format_param is None and u'NA' or format_param.decode('utf-8')),
  2196. 'thumbnail': video_thumbnail.decode('utf-8'),
  2197. 'description': video_description.decode('utf-8'),
  2198. 'player_url': None,
  2199. })
  2200. except UnavailableVideoError, err:
  2201. self._downloader.trouble(u'\nERROR: unable to download video')
  2202. class BlipTVIE(InfoExtractor):
  2203. """Information extractor for blip.tv"""
  2204. _VALID_URL = r'^(?:https?://)?(?:\w+\.)?blip.tv(/.+)$'
  2205. _URL_EXT = r'^.*\.([a-z0-9]+)$'
  2206. @staticmethod
  2207. def suitable(url):
  2208. return (re.match(BlipTVIE._VALID_URL, url) is not None)
  2209. def report_extraction(self, file_id):
  2210. """Report information extraction."""
  2211. self._downloader.to_screen(u'[blip.tv] %s: Extracting information' % file_id)
  2212. def _simplify_title(self, title):
  2213. res = re.sub(ur'(?u)([^%s]+)' % simple_title_chars, ur'_', title)
  2214. res = res.strip(ur'_')
  2215. return res
  2216. def _real_extract(self, url):
  2217. mobj = re.match(self._VALID_URL, url)
  2218. if mobj is None:
  2219. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  2220. return
  2221. json_url = url + ('&' if '?' in url else '?') + 'skin=json&version=2&no_wrap=1'
  2222. request = urllib2.Request(json_url)
  2223. self.report_extraction(mobj.group(1))
  2224. try:
  2225. json_code = urllib2.urlopen(request).read()
  2226. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  2227. self._downloader.trouble(u'ERROR: unable to download video info webpage: %s' % str(err))
  2228. return
  2229. try:
  2230. json_data = json.loads(json_code)
  2231. data = json_data['Post'] if 'Post' in json_data else json_data
  2232. upload_date = datetime.datetime.strptime(data['datestamp'], '%m-%d-%y %H:%M%p').strftime('%Y%m%d')
  2233. video_url = data['media']['url']
  2234. umobj = re.match(self._URL_EXT, video_url)
  2235. if umobj is None:
  2236. raise ValueError('Can not determine filename extension')
  2237. ext = umobj.group(1)
  2238. self._downloader.increment_downloads()
  2239. info = {
  2240. 'id': data['item_id'],
  2241. 'url': video_url,
  2242. 'uploader': data['display_name'],
  2243. 'upload_date': upload_date,
  2244. 'title': data['title'],
  2245. 'stitle': self._simplify_title(data['title']),
  2246. 'ext': ext,
  2247. 'format': data['media']['mimeType'],
  2248. 'thumbnail': data['thumbnailUrl'],
  2249. 'description': data['description'],
  2250. 'player_url': data['embedUrl']
  2251. }
  2252. except (ValueError,KeyError), err:
  2253. self._downloader.trouble(u'ERROR: unable to parse video information: %s' % repr(err))
  2254. return
  2255. try:
  2256. self._downloader.process_info(info)
  2257. except UnavailableVideoError, err:
  2258. self._downloader.trouble(u'\nERROR: unable to download video')
  2259. class PostProcessor(object):
  2260. """Post Processor class.
  2261. PostProcessor objects can be added to downloaders with their
  2262. add_post_processor() method. When the downloader has finished a
  2263. successful download, it will take its internal chain of PostProcessors
  2264. and start calling the run() method on each one of them, first with
  2265. an initial argument and then with the returned value of the previous
  2266. PostProcessor.
  2267. The chain will be stopped if one of them ever returns None or the end
  2268. of the chain is reached.
  2269. PostProcessor objects follow a "mutual registration" process similar
  2270. to InfoExtractor objects.
  2271. """
  2272. _downloader = None
  2273. def __init__(self, downloader=None):
  2274. self._downloader = downloader
  2275. def set_downloader(self, downloader):
  2276. """Sets the downloader for this PP."""
  2277. self._downloader = downloader
  2278. def run(self, information):
  2279. """Run the PostProcessor.
  2280. The "information" argument is a dictionary like the ones
  2281. composed by InfoExtractors. The only difference is that this
  2282. one has an extra field called "filepath" that points to the
  2283. downloaded file.
  2284. When this method returns None, the postprocessing chain is
  2285. stopped. However, this method may return an information
  2286. dictionary that will be passed to the next postprocessing
  2287. object in the chain. It can be the one it received after
  2288. changing some fields.
  2289. In addition, this method may raise a PostProcessingError
  2290. exception that will be taken into account by the downloader
  2291. it was called from.
  2292. """
  2293. return information # by default, do nothing
  2294. class FFmpegExtractAudioPP(PostProcessor):
  2295. def __init__(self, downloader=None, preferredcodec=None):
  2296. PostProcessor.__init__(self, downloader)
  2297. if preferredcodec is None:
  2298. preferredcodec = 'best'
  2299. self._preferredcodec = preferredcodec
  2300. @staticmethod
  2301. def get_audio_codec(path):
  2302. try:
  2303. cmd = ['ffprobe', '-show_streams', '--', path]
  2304. handle = subprocess.Popen(cmd, stderr=file(os.path.devnull, 'w'), stdout=subprocess.PIPE)
  2305. output = handle.communicate()[0]
  2306. if handle.wait() != 0:
  2307. return None
  2308. except (IOError, OSError):
  2309. return None
  2310. audio_codec = None
  2311. for line in output.split('\n'):
  2312. if line.startswith('codec_name='):
  2313. audio_codec = line.split('=')[1].strip()
  2314. elif line.strip() == 'codec_type=audio' and audio_codec is not None:
  2315. return audio_codec
  2316. return None
  2317. @staticmethod
  2318. def run_ffmpeg(path, out_path, codec, more_opts):
  2319. try:
  2320. cmd = ['ffmpeg', '-y', '-i', path, '-vn', '-acodec', codec] + more_opts + ['--', out_path]
  2321. ret = subprocess.call(cmd, stdout=file(os.path.devnull, 'w'), stderr=subprocess.STDOUT)
  2322. return (ret == 0)
  2323. except (IOError, OSError):
  2324. return False
  2325. def run(self, information):
  2326. path = information['filepath']
  2327. filecodec = self.get_audio_codec(path)
  2328. if filecodec is None:
  2329. self._downloader.to_stderr(u'WARNING: unable to obtain file audio codec with ffprobe')
  2330. return None
  2331. more_opts = []
  2332. if self._preferredcodec == 'best' or self._preferredcodec == filecodec:
  2333. if filecodec == 'aac' or filecodec == 'mp3':
  2334. # Lossless if possible
  2335. acodec = 'copy'
  2336. extension = filecodec
  2337. if filecodec == 'aac':
  2338. more_opts = ['-f', 'adts']
  2339. else:
  2340. # MP3 otherwise.
  2341. acodec = 'libmp3lame'
  2342. extension = 'mp3'
  2343. more_opts = ['-ab', '128k']
  2344. else:
  2345. # We convert the audio (lossy)
  2346. acodec = {'mp3': 'libmp3lame', 'aac': 'aac'}[self._preferredcodec]
  2347. extension = self._preferredcodec
  2348. more_opts = ['-ab', '128k']
  2349. if self._preferredcodec == 'aac':
  2350. more_opts += ['-f', 'adts']
  2351. (prefix, ext) = os.path.splitext(path)
  2352. new_path = prefix + '.' + extension
  2353. self._downloader.to_screen(u'[ffmpeg] Destination: %s' % new_path)
  2354. status = self.run_ffmpeg(path, new_path, acodec, more_opts)
  2355. if not status:
  2356. self._downloader.to_stderr(u'WARNING: error running ffmpeg')
  2357. return None
  2358. try:
  2359. os.remove(path)
  2360. except (IOError, OSError):
  2361. self._downloader.to_stderr(u'WARNING: Unable to remove downloaded video file')
  2362. return None
  2363. information['filepath'] = new_path
  2364. return information
  2365. ### MAIN PROGRAM ###
  2366. if __name__ == '__main__':
  2367. try:
  2368. # Modules needed only when running the main program
  2369. import getpass
  2370. import optparse
  2371. # Function to update the program file with the latest version from the repository.
  2372. def update_self(downloader, filename):
  2373. # Note: downloader only used for options
  2374. if not os.access(filename, os.W_OK):
  2375. sys.exit('ERROR: no write permissions on %s' % filename)
  2376. downloader.to_screen('Updating to latest stable version...')
  2377. try:
  2378. latest_url = 'http://github.com/rg3/youtube-dl/raw/master/LATEST_VERSION'
  2379. latest_version = urllib.urlopen(latest_url).read().strip()
  2380. prog_url = 'http://github.com/rg3/youtube-dl/raw/%s/youtube-dl' % latest_version
  2381. newcontent = urllib.urlopen(prog_url).read()
  2382. except (IOError, OSError), err:
  2383. sys.exit('ERROR: unable to download latest version')
  2384. try:
  2385. stream = open(filename, 'w')
  2386. stream.write(newcontent)
  2387. stream.close()
  2388. except (IOError, OSError), err:
  2389. sys.exit('ERROR: unable to overwrite current version')
  2390. downloader.to_screen('Updated to version %s' % latest_version)
  2391. # Parse command line
  2392. parser = optparse.OptionParser(
  2393. usage='Usage: %prog [options] url...',
  2394. version='2011.03.29',
  2395. conflict_handler='resolve',
  2396. )
  2397. parser.add_option('-h', '--help',
  2398. action='help', help='print this help text and exit')
  2399. parser.add_option('-v', '--version',
  2400. action='version', help='print program version and exit')
  2401. parser.add_option('-U', '--update',
  2402. action='store_true', dest='update_self', help='update this program to latest stable version')
  2403. parser.add_option('-i', '--ignore-errors',
  2404. action='store_true', dest='ignoreerrors', help='continue on download errors', default=False)
  2405. parser.add_option('-r', '--rate-limit',
  2406. dest='ratelimit', metavar='LIMIT', help='download rate limit (e.g. 50k or 44.6m)')
  2407. parser.add_option('-R', '--retries',
  2408. dest='retries', metavar='RETRIES', help='number of retries (default is 10)', default=10)
  2409. parser.add_option('--playlist-start',
  2410. dest='playliststart', metavar='NUMBER', help='playlist video to start at (default is 1)', default=1)
  2411. parser.add_option('--playlist-end',
  2412. dest='playlistend', metavar='NUMBER', help='playlist video to end at (default is last)', default=-1)
  2413. parser.add_option('--dump-user-agent',
  2414. action='store_true', dest='dump_user_agent',
  2415. help='display the current browser identification', default=False)
  2416. authentication = optparse.OptionGroup(parser, 'Authentication Options')
  2417. authentication.add_option('-u', '--username',
  2418. dest='username', metavar='USERNAME', help='account username')
  2419. authentication.add_option('-p', '--password',
  2420. dest='password', metavar='PASSWORD', help='account password')
  2421. authentication.add_option('-n', '--netrc',
  2422. action='store_true', dest='usenetrc', help='use .netrc authentication data', default=False)
  2423. parser.add_option_group(authentication)
  2424. video_format = optparse.OptionGroup(parser, 'Video Format Options')
  2425. video_format.add_option('-f', '--format',
  2426. action='store', dest='format', metavar='FORMAT', help='video format code')
  2427. video_format.add_option('--all-formats',
  2428. action='store_const', dest='format', help='download all available video formats', const='-1')
  2429. video_format.add_option('--max-quality',
  2430. action='store', dest='format_limit', metavar='FORMAT', help='highest quality format to download')
  2431. parser.add_option_group(video_format)
  2432. verbosity = optparse.OptionGroup(parser, 'Verbosity / Simulation Options')
  2433. verbosity.add_option('-q', '--quiet',
  2434. action='store_true', dest='quiet', help='activates quiet mode', default=False)
  2435. verbosity.add_option('-s', '--simulate',
  2436. action='store_true', dest='simulate', help='do not download video', default=False)
  2437. verbosity.add_option('-g', '--get-url',
  2438. action='store_true', dest='geturl', help='simulate, quiet but print URL', default=False)
  2439. verbosity.add_option('-e', '--get-title',
  2440. action='store_true', dest='gettitle', help='simulate, quiet but print title', default=False)
  2441. verbosity.add_option('--get-thumbnail',
  2442. action='store_true', dest='getthumbnail',
  2443. help='simulate, quiet but print thumbnail URL', default=False)
  2444. verbosity.add_option('--get-description',
  2445. action='store_true', dest='getdescription',
  2446. help='simulate, quiet but print video description', default=False)
  2447. verbosity.add_option('--get-filename',
  2448. action='store_true', dest='getfilename',
  2449. help='simulate, quiet but print output filename', default=False)
  2450. verbosity.add_option('--no-progress',
  2451. action='store_true', dest='noprogress', help='do not print progress bar', default=False)
  2452. verbosity.add_option('--console-title',
  2453. action='store_true', dest='consoletitle',
  2454. help='display progress in console titlebar', default=False)
  2455. parser.add_option_group(verbosity)
  2456. filesystem = optparse.OptionGroup(parser, 'Filesystem Options')
  2457. filesystem.add_option('-t', '--title',
  2458. action='store_true', dest='usetitle', help='use title in file name', default=False)
  2459. filesystem.add_option('-l', '--literal',
  2460. action='store_true', dest='useliteral', help='use literal title in file name', default=False)
  2461. filesystem.add_option('-A', '--auto-number',
  2462. action='store_true', dest='autonumber',
  2463. help='number downloaded files starting from 00000', default=False)
  2464. filesystem.add_option('-o', '--output',
  2465. dest='outtmpl', metavar='TEMPLATE', help='output filename template')
  2466. filesystem.add_option('-a', '--batch-file',
  2467. dest='batchfile', metavar='FILE', help='file containing URLs to download (\'-\' for stdin)')
  2468. filesystem.add_option('-w', '--no-overwrites',
  2469. action='store_true', dest='nooverwrites', help='do not overwrite files', default=False)
  2470. filesystem.add_option('-c', '--continue',
  2471. action='store_true', dest='continue_dl', help='resume partially downloaded files', default=False)
  2472. filesystem.add_option('--cookies',
  2473. dest='cookiefile', metavar='FILE', help='file to dump cookie jar to')
  2474. filesystem.add_option('--no-part',
  2475. action='store_true', dest='nopart', help='do not use .part files', default=False)
  2476. filesystem.add_option('--no-mtime',
  2477. action='store_false', dest='updatetime',
  2478. help='do not use the Last-modified header to set the file modification time', default=True)
  2479. filesystem.add_option('--write-description',
  2480. action='store_true', dest='writedescription',
  2481. help='write video description to a .description file', default=False)
  2482. parser.add_option_group(filesystem)
  2483. postproc = optparse.OptionGroup(parser, 'Post-processing Options')
  2484. postproc.add_option('--extract-audio', action='store_true', dest='extractaudio', default=False,
  2485. help='convert video files to audio-only files (requires ffmpeg and ffprobe)')
  2486. postproc.add_option('--audio-format', metavar='FORMAT', dest='audioformat', default='best',
  2487. help='"best", "aac" or "mp3"; best by default')
  2488. parser.add_option_group(postproc)
  2489. (opts, args) = parser.parse_args()
  2490. # Open appropriate CookieJar
  2491. if opts.cookiefile is None:
  2492. jar = cookielib.CookieJar()
  2493. else:
  2494. try:
  2495. jar = cookielib.MozillaCookieJar(opts.cookiefile)
  2496. if os.path.isfile(opts.cookiefile) and os.access(opts.cookiefile, os.R_OK):
  2497. jar.load()
  2498. except (IOError, OSError), err:
  2499. sys.exit(u'ERROR: unable to open cookie file')
  2500. # Dump user agent
  2501. if opts.dump_user_agent:
  2502. print std_headers['User-Agent']
  2503. sys.exit(0)
  2504. # General configuration
  2505. cookie_processor = urllib2.HTTPCookieProcessor(jar)
  2506. urllib2.install_opener(urllib2.build_opener(urllib2.ProxyHandler(), cookie_processor, YoutubeDLHandler()))
  2507. socket.setdefaulttimeout(300) # 5 minutes should be enough (famous last words)
  2508. # Batch file verification
  2509. batchurls = []
  2510. if opts.batchfile is not None:
  2511. try:
  2512. if opts.batchfile == '-':
  2513. batchfd = sys.stdin
  2514. else:
  2515. batchfd = open(opts.batchfile, 'r')
  2516. batchurls = batchfd.readlines()
  2517. batchurls = [x.strip() for x in batchurls]
  2518. batchurls = [x for x in batchurls if len(x) > 0 and not re.search(r'^[#/;]', x)]
  2519. except IOError:
  2520. sys.exit(u'ERROR: batch file could not be read')
  2521. all_urls = batchurls + args
  2522. # Conflicting, missing and erroneous options
  2523. if opts.usenetrc and (opts.username is not None or opts.password is not None):
  2524. parser.error(u'using .netrc conflicts with giving username/password')
  2525. if opts.password is not None and opts.username is None:
  2526. parser.error(u'account username missing')
  2527. if opts.outtmpl is not None and (opts.useliteral or opts.usetitle or opts.autonumber):
  2528. parser.error(u'using output template conflicts with using title, literal title or auto number')
  2529. if opts.usetitle and opts.useliteral:
  2530. parser.error(u'using title conflicts with using literal title')
  2531. if opts.username is not None and opts.password is None:
  2532. opts.password = getpass.getpass(u'Type account password and press return:')
  2533. if opts.ratelimit is not None:
  2534. numeric_limit = FileDownloader.parse_bytes(opts.ratelimit)
  2535. if numeric_limit is None:
  2536. parser.error(u'invalid rate limit specified')
  2537. opts.ratelimit = numeric_limit
  2538. if opts.retries is not None:
  2539. try:
  2540. opts.retries = long(opts.retries)
  2541. except (TypeError, ValueError), err:
  2542. parser.error(u'invalid retry count specified')
  2543. try:
  2544. opts.playliststart = long(opts.playliststart)
  2545. if opts.playliststart <= 0:
  2546. raise ValueError
  2547. except (TypeError, ValueError), err:
  2548. parser.error(u'invalid playlist start number specified')
  2549. try:
  2550. opts.playlistend = long(opts.playlistend)
  2551. if opts.playlistend != -1 and (opts.playlistend <= 0 or opts.playlistend < opts.playliststart):
  2552. raise ValueError
  2553. except (TypeError, ValueError), err:
  2554. parser.error(u'invalid playlist end number specified')
  2555. if opts.extractaudio:
  2556. if opts.audioformat not in ['best', 'aac', 'mp3']:
  2557. parser.error(u'invalid audio format specified')
  2558. # Information extractors
  2559. youtube_ie = YoutubeIE()
  2560. metacafe_ie = MetacafeIE(youtube_ie)
  2561. dailymotion_ie = DailymotionIE()
  2562. youtube_pl_ie = YoutubePlaylistIE(youtube_ie)
  2563. youtube_user_ie = YoutubeUserIE(youtube_ie)
  2564. youtube_search_ie = YoutubeSearchIE(youtube_ie)
  2565. google_ie = GoogleIE()
  2566. google_search_ie = GoogleSearchIE(google_ie)
  2567. photobucket_ie = PhotobucketIE()
  2568. yahoo_ie = YahooIE()
  2569. yahoo_search_ie = YahooSearchIE(yahoo_ie)
  2570. deposit_files_ie = DepositFilesIE()
  2571. facebook_ie = FacebookIE()
  2572. bliptv_ie = BlipTVIE()
  2573. generic_ie = GenericIE()
  2574. # File downloader
  2575. fd = FileDownloader({
  2576. 'usenetrc': opts.usenetrc,
  2577. 'username': opts.username,
  2578. 'password': opts.password,
  2579. 'quiet': (opts.quiet or opts.geturl or opts.gettitle or opts.getthumbnail or opts.getdescription or opts.getfilename),
  2580. 'forceurl': opts.geturl,
  2581. 'forcetitle': opts.gettitle,
  2582. 'forcethumbnail': opts.getthumbnail,
  2583. 'forcedescription': opts.getdescription,
  2584. 'forcefilename': opts.getfilename,
  2585. 'simulate': (opts.simulate or opts.geturl or opts.gettitle or opts.getthumbnail or opts.getdescription or opts.getfilename),
  2586. 'format': opts.format,
  2587. 'format_limit': opts.format_limit,
  2588. 'outtmpl': ((opts.outtmpl is not None and opts.outtmpl.decode(preferredencoding()))
  2589. or (opts.format == '-1' and opts.usetitle and u'%(stitle)s-%(id)s-%(format)s.%(ext)s')
  2590. or (opts.format == '-1' and opts.useliteral and u'%(title)s-%(id)s-%(format)s.%(ext)s')
  2591. or (opts.format == '-1' and u'%(id)s-%(format)s.%(ext)s')
  2592. or (opts.usetitle and opts.autonumber and u'%(autonumber)s-%(stitle)s-%(id)s.%(ext)s')
  2593. or (opts.useliteral and opts.autonumber and u'%(autonumber)s-%(title)s-%(id)s.%(ext)s')
  2594. or (opts.usetitle and u'%(stitle)s-%(id)s.%(ext)s')
  2595. or (opts.useliteral and u'%(title)s-%(id)s.%(ext)s')
  2596. or (opts.autonumber and u'%(autonumber)s-%(id)s.%(ext)s')
  2597. or u'%(id)s.%(ext)s'),
  2598. 'ignoreerrors': opts.ignoreerrors,
  2599. 'ratelimit': opts.ratelimit,
  2600. 'nooverwrites': opts.nooverwrites,
  2601. 'retries': opts.retries,
  2602. 'continuedl': opts.continue_dl,
  2603. 'noprogress': opts.noprogress,
  2604. 'playliststart': opts.playliststart,
  2605. 'playlistend': opts.playlistend,
  2606. 'logtostderr': opts.outtmpl == '-',
  2607. 'consoletitle': opts.consoletitle,
  2608. 'nopart': opts.nopart,
  2609. 'updatetime': opts.updatetime,
  2610. 'writedescription': opts.writedescription,
  2611. })
  2612. fd.add_info_extractor(youtube_search_ie)
  2613. fd.add_info_extractor(youtube_pl_ie)
  2614. fd.add_info_extractor(youtube_user_ie)
  2615. fd.add_info_extractor(metacafe_ie)
  2616. fd.add_info_extractor(dailymotion_ie)
  2617. fd.add_info_extractor(youtube_ie)
  2618. fd.add_info_extractor(google_ie)
  2619. fd.add_info_extractor(google_search_ie)
  2620. fd.add_info_extractor(photobucket_ie)
  2621. fd.add_info_extractor(yahoo_ie)
  2622. fd.add_info_extractor(yahoo_search_ie)
  2623. fd.add_info_extractor(deposit_files_ie)
  2624. fd.add_info_extractor(facebook_ie)
  2625. fd.add_info_extractor(bliptv_ie)
  2626. # This must come last since it's the
  2627. # fallback if none of the others work
  2628. fd.add_info_extractor(generic_ie)
  2629. # PostProcessors
  2630. if opts.extractaudio:
  2631. fd.add_post_processor(FFmpegExtractAudioPP(preferredcodec=opts.audioformat))
  2632. # Update version
  2633. if opts.update_self:
  2634. update_self(fd, sys.argv[0])
  2635. # Maybe do nothing
  2636. if len(all_urls) < 1:
  2637. if not opts.update_self:
  2638. parser.error(u'you must provide at least one URL')
  2639. else:
  2640. sys.exit()
  2641. retcode = fd.download(all_urls)
  2642. # Dump cookie jar if requested
  2643. if opts.cookiefile is not None:
  2644. try:
  2645. jar.save()
  2646. except (IOError, OSError), err:
  2647. sys.exit(u'ERROR: unable to save cookie jar')
  2648. sys.exit(retcode)
  2649. except DownloadError:
  2650. sys.exit(1)
  2651. except SameFileError:
  2652. sys.exit(u'ERROR: fixed output name but more than one file to download')
  2653. except KeyboardInterrupt:
  2654. sys.exit(u'\nERROR: Interrupted by user')