youtube-dl 127 KB

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