__init__.py 162 KB

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