youtube-dl 112 KB

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