youtube-dl 103 KB

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