__init__.py 151 KB

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