__init__.py 160 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728
  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 _real_extract(self, url):
  1933. # At this point we have a new video
  1934. self._downloader.increment_downloads()
  1935. video_id = url.split('/')[-1]
  1936. request = urllib2.Request(url)
  1937. try:
  1938. self.report_download_webpage(video_id)
  1939. webpage = urllib2.urlopen(request).read()
  1940. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1941. self._downloader.trouble(u'ERROR: Unable to retrieve video webpage: %s' % str(err))
  1942. return
  1943. except ValueError, err:
  1944. # since this is the last-resort InfoExtractor, if
  1945. # this error is thrown, it'll be thrown here
  1946. self._downloader.trouble(u'ERROR: Invalid URL: %s' % url)
  1947. return
  1948. self.report_extraction(video_id)
  1949. # Start with something easy: JW Player in SWFObject
  1950. mobj = re.search(r'flashvars: [\'"](?:.*&)?file=(http[^\'"&]*)', webpage)
  1951. if mobj is None:
  1952. # Broaden the search a little bit
  1953. mobj = re.search(r'[^A-Za-z0-9]?(?:file|source)=(http[^\'"&]*)', webpage)
  1954. if mobj is None:
  1955. self._downloader.trouble(u'ERROR: Invalid URL: %s' % url)
  1956. return
  1957. # It's possible that one of the regexes
  1958. # matched, but returned an empty group:
  1959. if mobj.group(1) is None:
  1960. self._downloader.trouble(u'ERROR: Invalid URL: %s' % url)
  1961. return
  1962. video_url = urllib.unquote(mobj.group(1))
  1963. video_id = os.path.basename(video_url)
  1964. # here's a fun little line of code for you:
  1965. video_extension = os.path.splitext(video_id)[1][1:]
  1966. video_id = os.path.splitext(video_id)[0]
  1967. # it's tempting to parse this further, but you would
  1968. # have to take into account all the variations like
  1969. # Video Title - Site Name
  1970. # Site Name | Video Title
  1971. # Video Title - Tagline | Site Name
  1972. # and so on and so forth; it's just not practical
  1973. mobj = re.search(r'<title>(.*)</title>', webpage)
  1974. if mobj is None:
  1975. self._downloader.trouble(u'ERROR: unable to extract title')
  1976. return
  1977. video_title = mobj.group(1).decode('utf-8')
  1978. video_title = sanitize_title(video_title)
  1979. simple_title = _simplify_title(video_title)
  1980. # video uploader is domain name
  1981. mobj = re.match(r'(?:https?://)?([^/]*)/.*', url)
  1982. if mobj is None:
  1983. self._downloader.trouble(u'ERROR: unable to extract title')
  1984. return
  1985. video_uploader = mobj.group(1).decode('utf-8')
  1986. try:
  1987. # Process video information
  1988. self._downloader.process_info({
  1989. 'id': video_id.decode('utf-8'),
  1990. 'url': video_url.decode('utf-8'),
  1991. 'uploader': video_uploader,
  1992. 'upload_date': u'NA',
  1993. 'title': video_title,
  1994. 'stitle': simple_title,
  1995. 'ext': video_extension.decode('utf-8'),
  1996. 'format': u'NA',
  1997. 'player_url': None,
  1998. })
  1999. except UnavailableVideoError, err:
  2000. self._downloader.trouble(u'\nERROR: unable to download video')
  2001. class YoutubeSearchIE(InfoExtractor):
  2002. """Information Extractor for YouTube search queries."""
  2003. _VALID_URL = r'ytsearch(\d+|all)?:[\s\S]+'
  2004. _API_URL = 'https://gdata.youtube.com/feeds/api/videos?q=%s&start-index=%i&max-results=50&v=2&alt=jsonc'
  2005. _youtube_ie = None
  2006. _max_youtube_results = 1000
  2007. IE_NAME = u'youtube:search'
  2008. def __init__(self, youtube_ie, downloader=None):
  2009. InfoExtractor.__init__(self, downloader)
  2010. self._youtube_ie = youtube_ie
  2011. def report_download_page(self, query, pagenum):
  2012. """Report attempt to download playlist page with given number."""
  2013. query = query.decode(preferredencoding())
  2014. self._downloader.to_screen(u'[youtube] query "%s": Downloading page %s' % (query, pagenum))
  2015. def _real_initialize(self):
  2016. self._youtube_ie.initialize()
  2017. def _real_extract(self, query):
  2018. mobj = re.match(self._VALID_URL, query)
  2019. if mobj is None:
  2020. self._downloader.trouble(u'ERROR: invalid search query "%s"' % query)
  2021. return
  2022. prefix, query = query.split(':')
  2023. prefix = prefix[8:]
  2024. query = query.encode('utf-8')
  2025. if prefix == '':
  2026. self._download_n_results(query, 1)
  2027. return
  2028. elif prefix == 'all':
  2029. self._download_n_results(query, self._max_youtube_results)
  2030. return
  2031. else:
  2032. try:
  2033. n = long(prefix)
  2034. if n <= 0:
  2035. self._downloader.trouble(u'ERROR: invalid download number %s for query "%s"' % (n, query))
  2036. return
  2037. elif n > self._max_youtube_results:
  2038. self._downloader.to_stderr(u'WARNING: ytsearch returns max %i results (you requested %i)' % (self._max_youtube_results, n))
  2039. n = self._max_youtube_results
  2040. self._download_n_results(query, n)
  2041. return
  2042. except ValueError: # parsing prefix as integer fails
  2043. self._download_n_results(query, 1)
  2044. return
  2045. def _download_n_results(self, query, n):
  2046. """Downloads a specified number of results for a query"""
  2047. video_ids = []
  2048. pagenum = 0
  2049. limit = n
  2050. while (50 * pagenum) < limit:
  2051. self.report_download_page(query, pagenum+1)
  2052. result_url = self._API_URL % (urllib.quote_plus(query), (50*pagenum)+1)
  2053. request = urllib2.Request(result_url)
  2054. try:
  2055. data = urllib2.urlopen(request).read()
  2056. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  2057. self._downloader.trouble(u'ERROR: unable to download API page: %s' % str(err))
  2058. return
  2059. api_response = json.loads(data)['data']
  2060. new_ids = list(video['id'] for video in api_response['items'])
  2061. video_ids += new_ids
  2062. limit = min(n, api_response['totalItems'])
  2063. pagenum += 1
  2064. if len(video_ids) > n:
  2065. video_ids = video_ids[:n]
  2066. for id in video_ids:
  2067. self._youtube_ie.extract('http://www.youtube.com/watch?v=%s' % id)
  2068. return
  2069. class GoogleSearchIE(InfoExtractor):
  2070. """Information Extractor for Google Video search queries."""
  2071. _VALID_URL = r'gvsearch(\d+|all)?:[\s\S]+'
  2072. _TEMPLATE_URL = 'http://video.google.com/videosearch?q=%s+site:video.google.com&start=%s&hl=en'
  2073. _VIDEO_INDICATOR = r'<a href="http://video\.google\.com/videoplay\?docid=([^"\&]+)'
  2074. _MORE_PAGES_INDICATOR = r'class="pn" id="pnnext"'
  2075. _google_ie = None
  2076. _max_google_results = 1000
  2077. IE_NAME = u'video.google:search'
  2078. def __init__(self, google_ie, downloader=None):
  2079. InfoExtractor.__init__(self, downloader)
  2080. self._google_ie = google_ie
  2081. def report_download_page(self, query, pagenum):
  2082. """Report attempt to download playlist page with given number."""
  2083. query = query.decode(preferredencoding())
  2084. self._downloader.to_screen(u'[video.google] query "%s": Downloading page %s' % (query, pagenum))
  2085. def _real_initialize(self):
  2086. self._google_ie.initialize()
  2087. def _real_extract(self, query):
  2088. mobj = re.match(self._VALID_URL, query)
  2089. if mobj is None:
  2090. self._downloader.trouble(u'ERROR: invalid search query "%s"' % query)
  2091. return
  2092. prefix, query = query.split(':')
  2093. prefix = prefix[8:]
  2094. query = query.encode('utf-8')
  2095. if prefix == '':
  2096. self._download_n_results(query, 1)
  2097. return
  2098. elif prefix == 'all':
  2099. self._download_n_results(query, self._max_google_results)
  2100. return
  2101. else:
  2102. try:
  2103. n = long(prefix)
  2104. if n <= 0:
  2105. self._downloader.trouble(u'ERROR: invalid download number %s for query "%s"' % (n, query))
  2106. return
  2107. elif n > self._max_google_results:
  2108. self._downloader.to_stderr(u'WARNING: gvsearch returns max %i results (you requested %i)' % (self._max_google_results, n))
  2109. n = self._max_google_results
  2110. self._download_n_results(query, n)
  2111. return
  2112. except ValueError: # parsing prefix as integer fails
  2113. self._download_n_results(query, 1)
  2114. return
  2115. def _download_n_results(self, query, n):
  2116. """Downloads a specified number of results for a query"""
  2117. video_ids = []
  2118. pagenum = 0
  2119. while True:
  2120. self.report_download_page(query, pagenum)
  2121. result_url = self._TEMPLATE_URL % (urllib.quote_plus(query), pagenum*10)
  2122. request = urllib2.Request(result_url)
  2123. try:
  2124. page = urllib2.urlopen(request).read()
  2125. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  2126. self._downloader.trouble(u'ERROR: unable to download webpage: %s' % str(err))
  2127. return
  2128. # Extract video identifiers
  2129. for mobj in re.finditer(self._VIDEO_INDICATOR, page):
  2130. video_id = mobj.group(1)
  2131. if video_id not in video_ids:
  2132. video_ids.append(video_id)
  2133. if len(video_ids) == n:
  2134. # Specified n videos reached
  2135. for id in video_ids:
  2136. self._google_ie.extract('http://video.google.com/videoplay?docid=%s' % id)
  2137. return
  2138. if re.search(self._MORE_PAGES_INDICATOR, page) is None:
  2139. for id in video_ids:
  2140. self._google_ie.extract('http://video.google.com/videoplay?docid=%s' % id)
  2141. return
  2142. pagenum = pagenum + 1
  2143. class YahooSearchIE(InfoExtractor):
  2144. """Information Extractor for Yahoo! Video search queries."""
  2145. _VALID_URL = r'yvsearch(\d+|all)?:[\s\S]+'
  2146. _TEMPLATE_URL = 'http://video.yahoo.com/search/?p=%s&o=%s'
  2147. _VIDEO_INDICATOR = r'href="http://video\.yahoo\.com/watch/([0-9]+/[0-9]+)"'
  2148. _MORE_PAGES_INDICATOR = r'\s*Next'
  2149. _yahoo_ie = None
  2150. _max_yahoo_results = 1000
  2151. IE_NAME = u'video.yahoo:search'
  2152. def __init__(self, yahoo_ie, downloader=None):
  2153. InfoExtractor.__init__(self, downloader)
  2154. self._yahoo_ie = yahoo_ie
  2155. def report_download_page(self, query, pagenum):
  2156. """Report attempt to download playlist page with given number."""
  2157. query = query.decode(preferredencoding())
  2158. self._downloader.to_screen(u'[video.yahoo] query "%s": Downloading page %s' % (query, pagenum))
  2159. def _real_initialize(self):
  2160. self._yahoo_ie.initialize()
  2161. def _real_extract(self, query):
  2162. mobj = re.match(self._VALID_URL, query)
  2163. if mobj is None:
  2164. self._downloader.trouble(u'ERROR: invalid search query "%s"' % query)
  2165. return
  2166. prefix, query = query.split(':')
  2167. prefix = prefix[8:]
  2168. query = query.encode('utf-8')
  2169. if prefix == '':
  2170. self._download_n_results(query, 1)
  2171. return
  2172. elif prefix == 'all':
  2173. self._download_n_results(query, self._max_yahoo_results)
  2174. return
  2175. else:
  2176. try:
  2177. n = long(prefix)
  2178. if n <= 0:
  2179. self._downloader.trouble(u'ERROR: invalid download number %s for query "%s"' % (n, query))
  2180. return
  2181. elif n > self._max_yahoo_results:
  2182. self._downloader.to_stderr(u'WARNING: yvsearch returns max %i results (you requested %i)' % (self._max_yahoo_results, n))
  2183. n = self._max_yahoo_results
  2184. self._download_n_results(query, n)
  2185. return
  2186. except ValueError: # parsing prefix as integer fails
  2187. self._download_n_results(query, 1)
  2188. return
  2189. def _download_n_results(self, query, n):
  2190. """Downloads a specified number of results for a query"""
  2191. video_ids = []
  2192. already_seen = set()
  2193. pagenum = 1
  2194. while True:
  2195. self.report_download_page(query, pagenum)
  2196. result_url = self._TEMPLATE_URL % (urllib.quote_plus(query), pagenum)
  2197. request = urllib2.Request(result_url)
  2198. try:
  2199. page = urllib2.urlopen(request).read()
  2200. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  2201. self._downloader.trouble(u'ERROR: unable to download webpage: %s' % str(err))
  2202. return
  2203. # Extract video identifiers
  2204. for mobj in re.finditer(self._VIDEO_INDICATOR, page):
  2205. video_id = mobj.group(1)
  2206. if video_id not in already_seen:
  2207. video_ids.append(video_id)
  2208. already_seen.add(video_id)
  2209. if len(video_ids) == n:
  2210. # Specified n videos reached
  2211. for id in video_ids:
  2212. self._yahoo_ie.extract('http://video.yahoo.com/watch/%s' % id)
  2213. return
  2214. if re.search(self._MORE_PAGES_INDICATOR, page) is None:
  2215. for id in video_ids:
  2216. self._yahoo_ie.extract('http://video.yahoo.com/watch/%s' % id)
  2217. return
  2218. pagenum = pagenum + 1
  2219. class YoutubePlaylistIE(InfoExtractor):
  2220. """Information Extractor for YouTube playlists."""
  2221. _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_-]+))?.*'
  2222. _TEMPLATE_URL = 'http://www.youtube.com/%s?%s=%s&page=%s&gl=US&hl=en'
  2223. _VIDEO_INDICATOR_TEMPLATE = r'/watch\?v=(.+?)&amp;list=PL%s&'
  2224. _MORE_PAGES_INDICATOR = r'(?m)>\s*Next\s*</a>'
  2225. _youtube_ie = None
  2226. IE_NAME = u'youtube:playlist'
  2227. def __init__(self, youtube_ie, downloader=None):
  2228. InfoExtractor.__init__(self, downloader)
  2229. self._youtube_ie = youtube_ie
  2230. def report_download_page(self, playlist_id, pagenum):
  2231. """Report attempt to download playlist page with given number."""
  2232. self._downloader.to_screen(u'[youtube] PL %s: Downloading page #%s' % (playlist_id, pagenum))
  2233. def _real_initialize(self):
  2234. self._youtube_ie.initialize()
  2235. def _real_extract(self, url):
  2236. # Extract playlist id
  2237. mobj = re.match(self._VALID_URL, url)
  2238. if mobj is None:
  2239. self._downloader.trouble(u'ERROR: invalid url: %s' % url)
  2240. return
  2241. # Single video case
  2242. if mobj.group(3) is not None:
  2243. self._youtube_ie.extract(mobj.group(3))
  2244. return
  2245. # Download playlist pages
  2246. # prefix is 'p' as default for playlists but there are other types that need extra care
  2247. playlist_prefix = mobj.group(1)
  2248. if playlist_prefix == 'a':
  2249. playlist_access = 'artist'
  2250. else:
  2251. playlist_prefix = 'p'
  2252. playlist_access = 'view_play_list'
  2253. playlist_id = mobj.group(2)
  2254. video_ids = []
  2255. pagenum = 1
  2256. while True:
  2257. self.report_download_page(playlist_id, pagenum)
  2258. url = self._TEMPLATE_URL % (playlist_access, playlist_prefix, playlist_id, pagenum)
  2259. request = urllib2.Request(url)
  2260. try:
  2261. page = urllib2.urlopen(request).read()
  2262. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  2263. self._downloader.trouble(u'ERROR: unable to download webpage: %s' % str(err))
  2264. return
  2265. # Extract video identifiers
  2266. ids_in_page = []
  2267. for mobj in re.finditer(self._VIDEO_INDICATOR_TEMPLATE % playlist_id, page):
  2268. if mobj.group(1) not in ids_in_page:
  2269. ids_in_page.append(mobj.group(1))
  2270. video_ids.extend(ids_in_page)
  2271. if re.search(self._MORE_PAGES_INDICATOR, page) is None:
  2272. break
  2273. pagenum = pagenum + 1
  2274. playliststart = self._downloader.params.get('playliststart', 1) - 1
  2275. playlistend = self._downloader.params.get('playlistend', -1)
  2276. if playlistend == -1:
  2277. video_ids = video_ids[playliststart:]
  2278. else:
  2279. video_ids = video_ids[playliststart:playlistend]
  2280. for id in video_ids:
  2281. self._youtube_ie.extract('http://www.youtube.com/watch?v=%s' % id)
  2282. return
  2283. class YoutubeUserIE(InfoExtractor):
  2284. """Information Extractor for YouTube users."""
  2285. _VALID_URL = r'(?:(?:(?:https?://)?(?:\w+\.)?youtube\.com/user/)|ytuser:)([A-Za-z0-9_-]+)'
  2286. _TEMPLATE_URL = 'http://gdata.youtube.com/feeds/api/users/%s'
  2287. _GDATA_PAGE_SIZE = 50
  2288. _GDATA_URL = 'http://gdata.youtube.com/feeds/api/users/%s/uploads?max-results=%d&start-index=%d'
  2289. _VIDEO_INDICATOR = r'/watch\?v=(.+?)[\<&]'
  2290. _youtube_ie = None
  2291. IE_NAME = u'youtube:user'
  2292. def __init__(self, youtube_ie, downloader=None):
  2293. InfoExtractor.__init__(self, downloader)
  2294. self._youtube_ie = youtube_ie
  2295. def report_download_page(self, username, start_index):
  2296. """Report attempt to download user page."""
  2297. self._downloader.to_screen(u'[youtube] user %s: Downloading video ids from %d to %d' %
  2298. (username, start_index, start_index + self._GDATA_PAGE_SIZE))
  2299. def _real_initialize(self):
  2300. self._youtube_ie.initialize()
  2301. def _real_extract(self, url):
  2302. # Extract username
  2303. mobj = re.match(self._VALID_URL, url)
  2304. if mobj is None:
  2305. self._downloader.trouble(u'ERROR: invalid url: %s' % url)
  2306. return
  2307. username = mobj.group(1)
  2308. # Download video ids using YouTube Data API. Result size per
  2309. # query is limited (currently to 50 videos) so we need to query
  2310. # page by page until there are no video ids - it means we got
  2311. # all of them.
  2312. video_ids = []
  2313. pagenum = 0
  2314. while True:
  2315. start_index = pagenum * self._GDATA_PAGE_SIZE + 1
  2316. self.report_download_page(username, start_index)
  2317. request = urllib2.Request(self._GDATA_URL % (username, self._GDATA_PAGE_SIZE, start_index))
  2318. try:
  2319. page = urllib2.urlopen(request).read()
  2320. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  2321. self._downloader.trouble(u'ERROR: unable to download webpage: %s' % str(err))
  2322. return
  2323. # Extract video identifiers
  2324. ids_in_page = []
  2325. for mobj in re.finditer(self._VIDEO_INDICATOR, page):
  2326. if mobj.group(1) not in ids_in_page:
  2327. ids_in_page.append(mobj.group(1))
  2328. video_ids.extend(ids_in_page)
  2329. # A little optimization - if current page is not
  2330. # "full", ie. does not contain PAGE_SIZE video ids then
  2331. # we can assume that this page is the last one - there
  2332. # are no more ids on further pages - no need to query
  2333. # again.
  2334. if len(ids_in_page) < self._GDATA_PAGE_SIZE:
  2335. break
  2336. pagenum += 1
  2337. all_ids_count = len(video_ids)
  2338. playliststart = self._downloader.params.get('playliststart', 1) - 1
  2339. playlistend = self._downloader.params.get('playlistend', -1)
  2340. if playlistend == -1:
  2341. video_ids = video_ids[playliststart:]
  2342. else:
  2343. video_ids = video_ids[playliststart:playlistend]
  2344. self._downloader.to_screen(u"[youtube] user %s: Collected %d video ids (downloading %d of them)" %
  2345. (username, all_ids_count, len(video_ids)))
  2346. for video_id in video_ids:
  2347. self._youtube_ie.extract('http://www.youtube.com/watch?v=%s' % video_id)
  2348. class DepositFilesIE(InfoExtractor):
  2349. """Information extractor for depositfiles.com"""
  2350. _VALID_URL = r'(?:http://)?(?:\w+\.)?depositfiles\.com/(?:../(?#locale))?files/(.+)'
  2351. IE_NAME = u'DepositFiles'
  2352. def __init__(self, downloader=None):
  2353. InfoExtractor.__init__(self, downloader)
  2354. def report_download_webpage(self, file_id):
  2355. """Report webpage download."""
  2356. self._downloader.to_screen(u'[DepositFiles] %s: Downloading webpage' % file_id)
  2357. def report_extraction(self, file_id):
  2358. """Report information extraction."""
  2359. self._downloader.to_screen(u'[DepositFiles] %s: Extracting information' % file_id)
  2360. def _real_extract(self, url):
  2361. # At this point we have a new file
  2362. self._downloader.increment_downloads()
  2363. file_id = url.split('/')[-1]
  2364. # Rebuild url in english locale
  2365. url = 'http://depositfiles.com/en/files/' + file_id
  2366. # Retrieve file webpage with 'Free download' button pressed
  2367. free_download_indication = { 'gateway_result' : '1' }
  2368. request = urllib2.Request(url, urllib.urlencode(free_download_indication))
  2369. try:
  2370. self.report_download_webpage(file_id)
  2371. webpage = urllib2.urlopen(request).read()
  2372. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  2373. self._downloader.trouble(u'ERROR: Unable to retrieve file webpage: %s' % str(err))
  2374. return
  2375. # Search for the real file URL
  2376. mobj = re.search(r'<form action="(http://fileshare.+?)"', webpage)
  2377. if (mobj is None) or (mobj.group(1) is None):
  2378. # Try to figure out reason of the error.
  2379. mobj = re.search(r'<strong>(Attention.*?)</strong>', webpage, re.DOTALL)
  2380. if (mobj is not None) and (mobj.group(1) is not None):
  2381. restriction_message = re.sub('\s+', ' ', mobj.group(1)).strip()
  2382. self._downloader.trouble(u'ERROR: %s' % restriction_message)
  2383. else:
  2384. self._downloader.trouble(u'ERROR: unable to extract download URL from: %s' % url)
  2385. return
  2386. file_url = mobj.group(1)
  2387. file_extension = os.path.splitext(file_url)[1][1:]
  2388. # Search for file title
  2389. mobj = re.search(r'<b title="(.*?)">', webpage)
  2390. if mobj is None:
  2391. self._downloader.trouble(u'ERROR: unable to extract title')
  2392. return
  2393. file_title = mobj.group(1).decode('utf-8')
  2394. try:
  2395. # Process file information
  2396. self._downloader.process_info({
  2397. 'id': file_id.decode('utf-8'),
  2398. 'url': file_url.decode('utf-8'),
  2399. 'uploader': u'NA',
  2400. 'upload_date': u'NA',
  2401. 'title': file_title,
  2402. 'stitle': file_title,
  2403. 'ext': file_extension.decode('utf-8'),
  2404. 'format': u'NA',
  2405. 'player_url': None,
  2406. })
  2407. except UnavailableVideoError, err:
  2408. self._downloader.trouble(u'ERROR: unable to download file')
  2409. class FacebookIE(InfoExtractor):
  2410. """Information Extractor for Facebook"""
  2411. _VALID_URL = r'^(?:https?://)?(?:\w+\.)?facebook\.com/(?:video/video|photo)\.php\?(?:.*?)v=(?P<ID>\d+)(?:.*)'
  2412. _LOGIN_URL = 'https://login.facebook.com/login.php?m&next=http%3A%2F%2Fm.facebook.com%2Fhome.php&'
  2413. _NETRC_MACHINE = 'facebook'
  2414. _available_formats = ['video', 'highqual', 'lowqual']
  2415. _video_extensions = {
  2416. 'video': 'mp4',
  2417. 'highqual': 'mp4',
  2418. 'lowqual': 'mp4',
  2419. }
  2420. IE_NAME = u'facebook'
  2421. def __init__(self, downloader=None):
  2422. InfoExtractor.__init__(self, downloader)
  2423. def _reporter(self, message):
  2424. """Add header and report message."""
  2425. self._downloader.to_screen(u'[facebook] %s' % message)
  2426. def report_login(self):
  2427. """Report attempt to log in."""
  2428. self._reporter(u'Logging in')
  2429. def report_video_webpage_download(self, video_id):
  2430. """Report attempt to download video webpage."""
  2431. self._reporter(u'%s: Downloading video webpage' % video_id)
  2432. def report_information_extraction(self, video_id):
  2433. """Report attempt to extract video information."""
  2434. self._reporter(u'%s: Extracting video information' % video_id)
  2435. def _parse_page(self, video_webpage):
  2436. """Extract video information from page"""
  2437. # General data
  2438. data = {'title': r'\("video_title", "(.*?)"\)',
  2439. 'description': r'<div class="datawrap">(.*?)</div>',
  2440. 'owner': r'\("video_owner_name", "(.*?)"\)',
  2441. 'thumbnail': r'\("thumb_url", "(?P<THUMB>.*?)"\)',
  2442. }
  2443. video_info = {}
  2444. for piece in data.keys():
  2445. mobj = re.search(data[piece], video_webpage)
  2446. if mobj is not None:
  2447. video_info[piece] = urllib.unquote_plus(mobj.group(1).decode("unicode_escape"))
  2448. # Video urls
  2449. video_urls = {}
  2450. for fmt in self._available_formats:
  2451. mobj = re.search(r'\("%s_src\", "(.+?)"\)' % fmt, video_webpage)
  2452. if mobj is not None:
  2453. # URL is in a Javascript segment inside an escaped Unicode format within
  2454. # the generally utf-8 page
  2455. video_urls[fmt] = urllib.unquote_plus(mobj.group(1).decode("unicode_escape"))
  2456. video_info['video_urls'] = video_urls
  2457. return video_info
  2458. def _real_initialize(self):
  2459. if self._downloader is None:
  2460. return
  2461. useremail = None
  2462. password = None
  2463. downloader_params = self._downloader.params
  2464. # Attempt to use provided username and password or .netrc data
  2465. if downloader_params.get('username', None) is not None:
  2466. useremail = downloader_params['username']
  2467. password = downloader_params['password']
  2468. elif downloader_params.get('usenetrc', False):
  2469. try:
  2470. info = netrc.netrc().authenticators(self._NETRC_MACHINE)
  2471. if info is not None:
  2472. useremail = info[0]
  2473. password = info[2]
  2474. else:
  2475. raise netrc.NetrcParseError('No authenticators for %s' % self._NETRC_MACHINE)
  2476. except (IOError, netrc.NetrcParseError), err:
  2477. self._downloader.to_stderr(u'WARNING: parsing .netrc: %s' % str(err))
  2478. return
  2479. if useremail is None:
  2480. return
  2481. # Log in
  2482. login_form = {
  2483. 'email': useremail,
  2484. 'pass': password,
  2485. 'login': 'Log+In'
  2486. }
  2487. request = urllib2.Request(self._LOGIN_URL, urllib.urlencode(login_form))
  2488. try:
  2489. self.report_login()
  2490. login_results = urllib2.urlopen(request).read()
  2491. if re.search(r'<form(.*)name="login"(.*)</form>', login_results) is not None:
  2492. self._downloader.to_stderr(u'WARNING: unable to log in: bad username/password, or exceded login rate limit (~3/min). Check credentials or wait.')
  2493. return
  2494. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  2495. self._downloader.to_stderr(u'WARNING: unable to log in: %s' % str(err))
  2496. return
  2497. def _real_extract(self, url):
  2498. mobj = re.match(self._VALID_URL, url)
  2499. if mobj is None:
  2500. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  2501. return
  2502. video_id = mobj.group('ID')
  2503. # Get video webpage
  2504. self.report_video_webpage_download(video_id)
  2505. request = urllib2.Request('https://www.facebook.com/video/video.php?v=%s' % video_id)
  2506. try:
  2507. page = urllib2.urlopen(request)
  2508. video_webpage = page.read()
  2509. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  2510. self._downloader.trouble(u'ERROR: unable to download video webpage: %s' % str(err))
  2511. return
  2512. # Start extracting information
  2513. self.report_information_extraction(video_id)
  2514. # Extract information
  2515. video_info = self._parse_page(video_webpage)
  2516. # uploader
  2517. if 'owner' not in video_info:
  2518. self._downloader.trouble(u'ERROR: unable to extract uploader nickname')
  2519. return
  2520. video_uploader = video_info['owner']
  2521. # title
  2522. if 'title' not in video_info:
  2523. self._downloader.trouble(u'ERROR: unable to extract video title')
  2524. return
  2525. video_title = video_info['title']
  2526. video_title = video_title.decode('utf-8')
  2527. video_title = sanitize_title(video_title)
  2528. simple_title = _simplify_title(video_title)
  2529. # thumbnail image
  2530. if 'thumbnail' not in video_info:
  2531. self._downloader.trouble(u'WARNING: unable to extract video thumbnail')
  2532. video_thumbnail = ''
  2533. else:
  2534. video_thumbnail = video_info['thumbnail']
  2535. # upload date
  2536. upload_date = u'NA'
  2537. if 'upload_date' in video_info:
  2538. upload_time = video_info['upload_date']
  2539. timetuple = email.utils.parsedate_tz(upload_time)
  2540. if timetuple is not None:
  2541. try:
  2542. upload_date = time.strftime('%Y%m%d', timetuple[0:9])
  2543. except:
  2544. pass
  2545. # description
  2546. video_description = video_info.get('description', 'No description available.')
  2547. url_map = video_info['video_urls']
  2548. if len(url_map.keys()) > 0:
  2549. # Decide which formats to download
  2550. req_format = self._downloader.params.get('format', None)
  2551. format_limit = self._downloader.params.get('format_limit', None)
  2552. if format_limit is not None and format_limit in self._available_formats:
  2553. format_list = self._available_formats[self._available_formats.index(format_limit):]
  2554. else:
  2555. format_list = self._available_formats
  2556. existing_formats = [x for x in format_list if x in url_map]
  2557. if len(existing_formats) == 0:
  2558. self._downloader.trouble(u'ERROR: no known formats available for video')
  2559. return
  2560. if req_format is None:
  2561. video_url_list = [(existing_formats[0], url_map[existing_formats[0]])] # Best quality
  2562. elif req_format == 'worst':
  2563. video_url_list = [(existing_formats[len(existing_formats)-1], url_map[existing_formats[len(existing_formats)-1]])] # worst quality
  2564. elif req_format == '-1':
  2565. video_url_list = [(f, url_map[f]) for f in existing_formats] # All formats
  2566. else:
  2567. # Specific format
  2568. if req_format not in url_map:
  2569. self._downloader.trouble(u'ERROR: requested format not available')
  2570. return
  2571. video_url_list = [(req_format, url_map[req_format])] # Specific format
  2572. for format_param, video_real_url in video_url_list:
  2573. # At this point we have a new video
  2574. self._downloader.increment_downloads()
  2575. # Extension
  2576. video_extension = self._video_extensions.get(format_param, 'mp4')
  2577. try:
  2578. # Process video information
  2579. self._downloader.process_info({
  2580. 'id': video_id.decode('utf-8'),
  2581. 'url': video_real_url.decode('utf-8'),
  2582. 'uploader': video_uploader.decode('utf-8'),
  2583. 'upload_date': upload_date,
  2584. 'title': video_title,
  2585. 'stitle': simple_title,
  2586. 'ext': video_extension.decode('utf-8'),
  2587. 'format': (format_param is None and u'NA' or format_param.decode('utf-8')),
  2588. 'thumbnail': video_thumbnail.decode('utf-8'),
  2589. 'description': video_description.decode('utf-8'),
  2590. 'player_url': None,
  2591. })
  2592. except UnavailableVideoError, err:
  2593. self._downloader.trouble(u'\nERROR: unable to download video')
  2594. class BlipTVIE(InfoExtractor):
  2595. """Information extractor for blip.tv"""
  2596. _VALID_URL = r'^(?:https?://)?(?:\w+\.)?blip\.tv(/.+)$'
  2597. _URL_EXT = r'^.*\.([a-z0-9]+)$'
  2598. IE_NAME = u'blip.tv'
  2599. def report_extraction(self, file_id):
  2600. """Report information extraction."""
  2601. self._downloader.to_screen(u'[%s] %s: Extracting information' % (self.IE_NAME, file_id))
  2602. def report_direct_download(self, title):
  2603. """Report information extraction."""
  2604. self._downloader.to_screen(u'[%s] %s: Direct download detected' % (self.IE_NAME, title))
  2605. def _real_extract(self, url):
  2606. mobj = re.match(self._VALID_URL, url)
  2607. if mobj is None:
  2608. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  2609. return
  2610. if '?' in url:
  2611. cchar = '&'
  2612. else:
  2613. cchar = '?'
  2614. json_url = url + cchar + 'skin=json&version=2&no_wrap=1'
  2615. request = urllib2.Request(json_url)
  2616. self.report_extraction(mobj.group(1))
  2617. info = None
  2618. try:
  2619. urlh = urllib2.urlopen(request)
  2620. if urlh.headers.get('Content-Type', '').startswith('video/'): # Direct download
  2621. basename = url.split('/')[-1]
  2622. title,ext = os.path.splitext(basename)
  2623. title = title.decode('UTF-8')
  2624. ext = ext.replace('.', '')
  2625. self.report_direct_download(title)
  2626. info = {
  2627. 'id': title,
  2628. 'url': url,
  2629. 'title': title,
  2630. 'stitle': _simplify_title(title),
  2631. 'ext': ext,
  2632. 'urlhandle': urlh
  2633. }
  2634. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  2635. self._downloader.trouble(u'ERROR: unable to download video info webpage: %s' % str(err))
  2636. return
  2637. if info is None: # Regular URL
  2638. try:
  2639. json_code = urlh.read()
  2640. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  2641. self._downloader.trouble(u'ERROR: unable to read video info webpage: %s' % str(err))
  2642. return
  2643. try:
  2644. json_data = json.loads(json_code)
  2645. if 'Post' in json_data:
  2646. data = json_data['Post']
  2647. else:
  2648. data = json_data
  2649. upload_date = datetime.datetime.strptime(data['datestamp'], '%m-%d-%y %H:%M%p').strftime('%Y%m%d')
  2650. video_url = data['media']['url']
  2651. umobj = re.match(self._URL_EXT, video_url)
  2652. if umobj is None:
  2653. raise ValueError('Can not determine filename extension')
  2654. ext = umobj.group(1)
  2655. info = {
  2656. 'id': data['item_id'],
  2657. 'url': video_url,
  2658. 'uploader': data['display_name'],
  2659. 'upload_date': upload_date,
  2660. 'title': data['title'],
  2661. 'stitle': _simplify_title(data['title']),
  2662. 'ext': ext,
  2663. 'format': data['media']['mimeType'],
  2664. 'thumbnail': data['thumbnailUrl'],
  2665. 'description': data['description'],
  2666. 'player_url': data['embedUrl']
  2667. }
  2668. except (ValueError,KeyError), err:
  2669. self._downloader.trouble(u'ERROR: unable to parse video information: %s' % repr(err))
  2670. return
  2671. self._downloader.increment_downloads()
  2672. try:
  2673. self._downloader.process_info(info)
  2674. except UnavailableVideoError, err:
  2675. self._downloader.trouble(u'\nERROR: unable to download video')
  2676. class MyVideoIE(InfoExtractor):
  2677. """Information Extractor for myvideo.de."""
  2678. _VALID_URL = r'(?:http://)?(?:www\.)?myvideo\.de/watch/([0-9]+)/([^?/]+).*'
  2679. IE_NAME = u'myvideo'
  2680. def __init__(self, downloader=None):
  2681. InfoExtractor.__init__(self, downloader)
  2682. def report_download_webpage(self, video_id):
  2683. """Report webpage download."""
  2684. self._downloader.to_screen(u'[myvideo] %s: Downloading webpage' % video_id)
  2685. def report_extraction(self, video_id):
  2686. """Report information extraction."""
  2687. self._downloader.to_screen(u'[myvideo] %s: Extracting information' % video_id)
  2688. def _real_extract(self,url):
  2689. mobj = re.match(self._VALID_URL, url)
  2690. if mobj is None:
  2691. self._download.trouble(u'ERROR: invalid URL: %s' % url)
  2692. return
  2693. video_id = mobj.group(1)
  2694. # Get video webpage
  2695. request = urllib2.Request('http://www.myvideo.de/watch/%s' % video_id)
  2696. try:
  2697. self.report_download_webpage(video_id)
  2698. webpage = urllib2.urlopen(request).read()
  2699. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  2700. self._downloader.trouble(u'ERROR: Unable to retrieve video webpage: %s' % str(err))
  2701. return
  2702. self.report_extraction(video_id)
  2703. mobj = re.search(r'<link rel=\'image_src\' href=\'(http://is[0-9].myvideo\.de/de/movie[0-9]+/[a-f0-9]+)/thumbs/[^.]+\.jpg\' />',
  2704. webpage)
  2705. if mobj is None:
  2706. self._downloader.trouble(u'ERROR: unable to extract media URL')
  2707. return
  2708. video_url = mobj.group(1) + ('/%s.flv' % video_id)
  2709. mobj = re.search('<title>([^<]+)</title>', webpage)
  2710. if mobj is None:
  2711. self._downloader.trouble(u'ERROR: unable to extract title')
  2712. return
  2713. video_title = mobj.group(1)
  2714. video_title = sanitize_title(video_title)
  2715. simple_title = _simplify_title(video_title)
  2716. try:
  2717. self._downloader.process_info({
  2718. 'id': video_id,
  2719. 'url': video_url,
  2720. 'uploader': u'NA',
  2721. 'upload_date': u'NA',
  2722. 'title': video_title,
  2723. 'stitle': simple_title,
  2724. 'ext': u'flv',
  2725. 'format': u'NA',
  2726. 'player_url': None,
  2727. })
  2728. except UnavailableVideoError:
  2729. self._downloader.trouble(u'\nERROR: Unable to download video')
  2730. class ComedyCentralIE(InfoExtractor):
  2731. """Information extractor for The Daily Show and Colbert Report """
  2732. _VALID_URL = r'^(:(?P<shortname>tds|thedailyshow|cr|colbert|colbertnation|colbertreport))|(https?://)?(www\.)?(?P<showname>thedailyshow|colbertnation)\.com/full-episodes/(?P<episode>.*)$'
  2733. IE_NAME = u'comedycentral'
  2734. def report_extraction(self, episode_id):
  2735. self._downloader.to_screen(u'[comedycentral] %s: Extracting information' % episode_id)
  2736. def report_config_download(self, episode_id):
  2737. self._downloader.to_screen(u'[comedycentral] %s: Downloading configuration' % episode_id)
  2738. def report_index_download(self, episode_id):
  2739. self._downloader.to_screen(u'[comedycentral] %s: Downloading show index' % episode_id)
  2740. def report_player_url(self, episode_id):
  2741. self._downloader.to_screen(u'[comedycentral] %s: Determining player URL' % episode_id)
  2742. def _real_extract(self, url):
  2743. mobj = re.match(self._VALID_URL, url)
  2744. if mobj is None:
  2745. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  2746. return
  2747. if mobj.group('shortname'):
  2748. if mobj.group('shortname') in ('tds', 'thedailyshow'):
  2749. url = u'http://www.thedailyshow.com/full-episodes/'
  2750. else:
  2751. url = u'http://www.colbertnation.com/full-episodes/'
  2752. mobj = re.match(self._VALID_URL, url)
  2753. assert mobj is not None
  2754. dlNewest = not mobj.group('episode')
  2755. if dlNewest:
  2756. epTitle = mobj.group('showname')
  2757. else:
  2758. epTitle = mobj.group('episode')
  2759. req = urllib2.Request(url)
  2760. self.report_extraction(epTitle)
  2761. try:
  2762. htmlHandle = urllib2.urlopen(req)
  2763. html = htmlHandle.read()
  2764. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  2765. self._downloader.trouble(u'ERROR: unable to download webpage: %s' % unicode(err))
  2766. return
  2767. if dlNewest:
  2768. url = htmlHandle.geturl()
  2769. mobj = re.match(self._VALID_URL, url)
  2770. if mobj is None:
  2771. self._downloader.trouble(u'ERROR: Invalid redirected URL: ' + url)
  2772. return
  2773. if mobj.group('episode') == '':
  2774. self._downloader.trouble(u'ERROR: Redirected URL is still not specific: ' + url)
  2775. return
  2776. epTitle = mobj.group('episode')
  2777. mMovieParams = re.findall('(?:<param name="movie" value="|var url = ")(http://media.mtvnservices.com/([^"]*episode.*?:.*?))"', html)
  2778. if len(mMovieParams) == 0:
  2779. self._downloader.trouble(u'ERROR: unable to find Flash URL in webpage ' + url)
  2780. return
  2781. playerUrl_raw = mMovieParams[0][0]
  2782. self.report_player_url(epTitle)
  2783. try:
  2784. urlHandle = urllib2.urlopen(playerUrl_raw)
  2785. playerUrl = urlHandle.geturl()
  2786. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  2787. self._downloader.trouble(u'ERROR: unable to find out player URL: ' + unicode(err))
  2788. return
  2789. uri = mMovieParams[0][1]
  2790. indexUrl = 'http://shadow.comedycentral.com/feeds/video_player/mrss/?' + urllib.urlencode({'uri': uri})
  2791. self.report_index_download(epTitle)
  2792. try:
  2793. indexXml = urllib2.urlopen(indexUrl).read()
  2794. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  2795. self._downloader.trouble(u'ERROR: unable to download episode index: ' + unicode(err))
  2796. return
  2797. idoc = xml.etree.ElementTree.fromstring(indexXml)
  2798. itemEls = idoc.findall('.//item')
  2799. for itemEl in itemEls:
  2800. mediaId = itemEl.findall('./guid')[0].text
  2801. shortMediaId = mediaId.split(':')[-1]
  2802. showId = mediaId.split(':')[-2].replace('.com', '')
  2803. officialTitle = itemEl.findall('./title')[0].text
  2804. officialDate = itemEl.findall('./pubDate')[0].text
  2805. configUrl = ('http://www.comedycentral.com/global/feeds/entertainment/media/mediaGenEntertainment.jhtml?' +
  2806. urllib.urlencode({'uri': mediaId}))
  2807. configReq = urllib2.Request(configUrl)
  2808. self.report_config_download(epTitle)
  2809. try:
  2810. configXml = urllib2.urlopen(configReq).read()
  2811. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  2812. self._downloader.trouble(u'ERROR: unable to download webpage: %s' % unicode(err))
  2813. return
  2814. cdoc = xml.etree.ElementTree.fromstring(configXml)
  2815. turls = []
  2816. for rendition in cdoc.findall('.//rendition'):
  2817. finfo = (rendition.attrib['bitrate'], rendition.findall('./src')[0].text)
  2818. turls.append(finfo)
  2819. if len(turls) == 0:
  2820. self._downloader.trouble(u'\nERROR: unable to download ' + mediaId + ': No videos found')
  2821. continue
  2822. # For now, just pick the highest bitrate
  2823. format,video_url = turls[-1]
  2824. self._downloader.increment_downloads()
  2825. effTitle = showId + u'-' + epTitle
  2826. info = {
  2827. 'id': shortMediaId,
  2828. 'url': video_url,
  2829. 'uploader': showId,
  2830. 'upload_date': officialDate,
  2831. 'title': effTitle,
  2832. 'stitle': _simplify_title(effTitle),
  2833. 'ext': 'mp4',
  2834. 'format': format,
  2835. 'thumbnail': None,
  2836. 'description': officialTitle,
  2837. 'player_url': playerUrl
  2838. }
  2839. try:
  2840. self._downloader.process_info(info)
  2841. except UnavailableVideoError, err:
  2842. self._downloader.trouble(u'\nERROR: unable to download ' + mediaId)
  2843. continue
  2844. class EscapistIE(InfoExtractor):
  2845. """Information extractor for The Escapist """
  2846. _VALID_URL = r'^(https?://)?(www\.)?escapistmagazine\.com/videos/view/(?P<showname>[^/]+)/(?P<episode>[^/?]+)[/?]?.*$'
  2847. IE_NAME = u'escapist'
  2848. def report_extraction(self, showName):
  2849. self._downloader.to_screen(u'[escapist] %s: Extracting information' % showName)
  2850. def report_config_download(self, showName):
  2851. self._downloader.to_screen(u'[escapist] %s: Downloading configuration' % showName)
  2852. def _real_extract(self, url):
  2853. htmlParser = HTMLParser.HTMLParser()
  2854. mobj = re.match(self._VALID_URL, url)
  2855. if mobj is None:
  2856. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  2857. return
  2858. showName = mobj.group('showname')
  2859. videoId = mobj.group('episode')
  2860. self.report_extraction(showName)
  2861. try:
  2862. webPage = urllib2.urlopen(url).read()
  2863. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  2864. self._downloader.trouble(u'ERROR: unable to download webpage: ' + unicode(err))
  2865. return
  2866. descMatch = re.search('<meta name="description" content="([^"]*)"', webPage)
  2867. description = htmlParser.unescape(descMatch.group(1))
  2868. imgMatch = re.search('<meta property="og:image" content="([^"]*)"', webPage)
  2869. imgUrl = htmlParser.unescape(imgMatch.group(1))
  2870. playerUrlMatch = re.search('<meta property="og:video" content="([^"]*)"', webPage)
  2871. playerUrl = htmlParser.unescape(playerUrlMatch.group(1))
  2872. configUrlMatch = re.search('config=(.*)$', playerUrl)
  2873. configUrl = urllib2.unquote(configUrlMatch.group(1))
  2874. self.report_config_download(showName)
  2875. try:
  2876. configJSON = urllib2.urlopen(configUrl).read()
  2877. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  2878. self._downloader.trouble(u'ERROR: unable to download configuration: ' + unicode(err))
  2879. return
  2880. # Technically, it's JavaScript, not JSON
  2881. configJSON = configJSON.replace("'", '"')
  2882. try:
  2883. config = json.loads(configJSON)
  2884. except (ValueError,), err:
  2885. self._downloader.trouble(u'ERROR: Invalid JSON in configuration file: ' + unicode(err))
  2886. return
  2887. playlist = config['playlist']
  2888. videoUrl = playlist[1]['url']
  2889. self._downloader.increment_downloads()
  2890. info = {
  2891. 'id': videoId,
  2892. 'url': videoUrl,
  2893. 'uploader': showName,
  2894. 'upload_date': None,
  2895. 'title': showName,
  2896. 'stitle': _simplify_title(showName),
  2897. 'ext': 'flv',
  2898. 'format': 'flv',
  2899. 'thumbnail': imgUrl,
  2900. 'description': description,
  2901. 'player_url': playerUrl,
  2902. }
  2903. try:
  2904. self._downloader.process_info(info)
  2905. except UnavailableVideoError, err:
  2906. self._downloader.trouble(u'\nERROR: unable to download ' + videoId)
  2907. class CollegeHumorIE(InfoExtractor):
  2908. """Information extractor for collegehumor.com"""
  2909. _VALID_URL = r'^(?:https?://)?(?:www\.)?collegehumor\.com/video/(?P<videoid>[0-9]+)/(?P<shorttitle>.*)$'
  2910. IE_NAME = u'collegehumor'
  2911. def report_webpage(self, video_id):
  2912. """Report information extraction."""
  2913. self._downloader.to_screen(u'[%s] %s: Downloading webpage' % (self.IE_NAME, video_id))
  2914. def report_extraction(self, video_id):
  2915. """Report information extraction."""
  2916. self._downloader.to_screen(u'[%s] %s: Extracting information' % (self.IE_NAME, video_id))
  2917. def _real_extract(self, url):
  2918. htmlParser = HTMLParser.HTMLParser()
  2919. mobj = re.match(self._VALID_URL, url)
  2920. if mobj is None:
  2921. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  2922. return
  2923. video_id = mobj.group('videoid')
  2924. self.report_webpage(video_id)
  2925. request = urllib2.Request(url)
  2926. try:
  2927. webpage = urllib2.urlopen(request).read()
  2928. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  2929. self._downloader.trouble(u'ERROR: unable to download video webpage: %s' % str(err))
  2930. return
  2931. m = re.search(r'id="video:(?P<internalvideoid>[0-9]+)"', webpage)
  2932. if m is None:
  2933. self._downloader.trouble(u'ERROR: Cannot extract internal video ID')
  2934. return
  2935. internal_video_id = m.group('internalvideoid')
  2936. info = {
  2937. 'id': video_id,
  2938. 'internal_id': internal_video_id,
  2939. }
  2940. self.report_extraction(video_id)
  2941. xmlUrl = 'http://www.collegehumor.com/moogaloop/video:' + internal_video_id
  2942. try:
  2943. metaXml = urllib2.urlopen(xmlUrl).read()
  2944. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  2945. self._downloader.trouble(u'ERROR: unable to download video info XML: %s' % str(err))
  2946. return
  2947. mdoc = xml.etree.ElementTree.fromstring(metaXml)
  2948. try:
  2949. videoNode = mdoc.findall('./video')[0]
  2950. info['description'] = videoNode.findall('./description')[0].text
  2951. info['title'] = videoNode.findall('./caption')[0].text
  2952. info['stitle'] = _simplify_title(info['title'])
  2953. info['url'] = videoNode.findall('./file')[0].text
  2954. info['thumbnail'] = videoNode.findall('./thumbnail')[0].text
  2955. info['ext'] = info['url'].rpartition('.')[2]
  2956. info['format'] = info['ext']
  2957. except IndexError:
  2958. self._downloader.trouble(u'\nERROR: Invalid metadata XML file')
  2959. return
  2960. self._downloader.increment_downloads()
  2961. try:
  2962. self._downloader.process_info(info)
  2963. except UnavailableVideoError, err:
  2964. self._downloader.trouble(u'\nERROR: unable to download video')
  2965. class XVideosIE(InfoExtractor):
  2966. """Information extractor for xvideos.com"""
  2967. _VALID_URL = r'^(?:https?://)?(?:www\.)?xvideos\.com/video([0-9]+)(?:.*)'
  2968. IE_NAME = u'xvideos'
  2969. def report_webpage(self, video_id):
  2970. """Report information extraction."""
  2971. self._downloader.to_screen(u'[%s] %s: Downloading webpage' % (self.IE_NAME, video_id))
  2972. def report_extraction(self, video_id):
  2973. """Report information extraction."""
  2974. self._downloader.to_screen(u'[%s] %s: Extracting information' % (self.IE_NAME, video_id))
  2975. def _real_extract(self, url):
  2976. htmlParser = HTMLParser.HTMLParser()
  2977. mobj = re.match(self._VALID_URL, url)
  2978. if mobj is None:
  2979. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  2980. return
  2981. video_id = mobj.group(1).decode('utf-8')
  2982. self.report_webpage(video_id)
  2983. request = urllib2.Request(r'http://www.xvideos.com/video' + video_id)
  2984. try:
  2985. webpage = urllib2.urlopen(request).read()
  2986. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  2987. self._downloader.trouble(u'ERROR: unable to download video webpage: %s' % str(err))
  2988. return
  2989. self.report_extraction(video_id)
  2990. # Extract video URL
  2991. mobj = re.search(r'flv_url=(.+?)&', webpage)
  2992. if mobj is None:
  2993. self._downloader.trouble(u'ERROR: unable to extract video url')
  2994. return
  2995. video_url = urllib2.unquote(mobj.group(1).decode('utf-8'))
  2996. # Extract title
  2997. mobj = re.search(r'<title>(.*?)\s+-\s+XVID', webpage)
  2998. if mobj is None:
  2999. self._downloader.trouble(u'ERROR: unable to extract video title')
  3000. return
  3001. video_title = mobj.group(1).decode('utf-8')
  3002. # Extract video thumbnail
  3003. 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)
  3004. if mobj is None:
  3005. self._downloader.trouble(u'ERROR: unable to extract video thumbnail')
  3006. return
  3007. video_thumbnail = mobj.group(1).decode('utf-8')
  3008. self._downloader.increment_downloads()
  3009. info = {
  3010. 'id': video_id,
  3011. 'url': video_url,
  3012. 'uploader': None,
  3013. 'upload_date': None,
  3014. 'title': video_title,
  3015. 'stitle': _simplify_title(video_title),
  3016. 'ext': 'flv',
  3017. 'format': 'flv',
  3018. 'thumbnail': video_thumbnail,
  3019. 'description': None,
  3020. 'player_url': None,
  3021. }
  3022. try:
  3023. self._downloader.process_info(info)
  3024. except UnavailableVideoError, err:
  3025. self._downloader.trouble(u'\nERROR: unable to download ' + video_id)
  3026. class SoundcloudIE(InfoExtractor):
  3027. """Information extractor for soundcloud.com
  3028. To access the media, the uid of the song and a stream token
  3029. must be extracted from the page source and the script must make
  3030. a request to media.soundcloud.com/crossdomain.xml. Then
  3031. the media can be grabbed by requesting from an url composed
  3032. of the stream token and uid
  3033. """
  3034. _VALID_URL = r'^(?:https?://)?(?:www\.)?soundcloud\.com/([\w\d-]+)/([\w\d-]+)'
  3035. IE_NAME = u'soundcloud'
  3036. def __init__(self, downloader=None):
  3037. InfoExtractor.__init__(self, downloader)
  3038. def report_webpage(self, video_id):
  3039. """Report information extraction."""
  3040. self._downloader.to_screen(u'[%s] %s: Downloading webpage' % (self.IE_NAME, video_id))
  3041. def report_extraction(self, video_id):
  3042. """Report information extraction."""
  3043. self._downloader.to_screen(u'[%s] %s: Extracting information' % (self.IE_NAME, video_id))
  3044. def _real_extract(self, url):
  3045. htmlParser = HTMLParser.HTMLParser()
  3046. mobj = re.match(self._VALID_URL, url)
  3047. if mobj is None:
  3048. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  3049. return
  3050. # extract uploader (which is in the url)
  3051. uploader = mobj.group(1).decode('utf-8')
  3052. # extract simple title (uploader + slug of song title)
  3053. slug_title = mobj.group(2).decode('utf-8')
  3054. simple_title = uploader + '-' + slug_title
  3055. self.report_webpage('%s/%s' % (uploader, slug_title))
  3056. request = urllib2.Request('http://soundcloud.com/%s/%s' % (uploader, slug_title))
  3057. try:
  3058. webpage = urllib2.urlopen(request).read()
  3059. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  3060. self._downloader.trouble(u'ERROR: unable to download video webpage: %s' % str(err))
  3061. return
  3062. self.report_extraction('%s/%s' % (uploader, slug_title))
  3063. # extract uid and stream token that soundcloud hands out for access
  3064. mobj = re.search('"uid":"([\w\d]+?)".*?stream_token=([\w\d]+)', webpage)
  3065. if mobj:
  3066. video_id = mobj.group(1)
  3067. stream_token = mobj.group(2)
  3068. # extract unsimplified title
  3069. mobj = re.search('"title":"(.*?)",', webpage)
  3070. if mobj:
  3071. title = mobj.group(1)
  3072. # construct media url (with uid/token)
  3073. mediaURL = "http://media.soundcloud.com/stream/%s?stream_token=%s"
  3074. mediaURL = mediaURL % (video_id, stream_token)
  3075. # description
  3076. description = u'No description available'
  3077. mobj = re.search('track-description-value"><p>(.*?)</p>', webpage)
  3078. if mobj:
  3079. description = mobj.group(1)
  3080. # upload date
  3081. upload_date = None
  3082. mobj = re.search("pretty-date'>on ([\w]+ [\d]+, [\d]+ \d+:\d+)</abbr></h2>", webpage)
  3083. if mobj:
  3084. try:
  3085. upload_date = datetime.datetime.strptime(mobj.group(1), '%B %d, %Y %H:%M').strftime('%Y%m%d')
  3086. except Exception, e:
  3087. print str(e)
  3088. # for soundcloud, a request to a cross domain is required for cookies
  3089. request = urllib2.Request('http://media.soundcloud.com/crossdomain.xml', std_headers)
  3090. try:
  3091. self._downloader.process_info({
  3092. 'id': video_id.decode('utf-8'),
  3093. 'url': mediaURL,
  3094. 'uploader': uploader.decode('utf-8'),
  3095. 'upload_date': upload_date,
  3096. 'title': simple_title.decode('utf-8'),
  3097. 'stitle': simple_title.decode('utf-8'),
  3098. 'ext': u'mp3',
  3099. 'format': u'NA',
  3100. 'player_url': None,
  3101. 'description': description.decode('utf-8')
  3102. })
  3103. except UnavailableVideoError:
  3104. self._downloader.trouble(u'\nERROR: unable to download video')
  3105. class InfoQIE(InfoExtractor):
  3106. """Information extractor for infoq.com"""
  3107. _VALID_URL = r'^(?:https?://)?(?:www\.)?infoq\.com/[^/]+/[^/]+$'
  3108. IE_NAME = u'infoq'
  3109. def report_webpage(self, video_id):
  3110. """Report information extraction."""
  3111. self._downloader.to_screen(u'[%s] %s: Downloading webpage' % (self.IE_NAME, video_id))
  3112. def report_extraction(self, video_id):
  3113. """Report information extraction."""
  3114. self._downloader.to_screen(u'[%s] %s: Extracting information' % (self.IE_NAME, video_id))
  3115. def _real_extract(self, url):
  3116. htmlParser = HTMLParser.HTMLParser()
  3117. mobj = re.match(self._VALID_URL, url)
  3118. if mobj is None:
  3119. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  3120. return
  3121. self.report_webpage(url)
  3122. request = urllib2.Request(url)
  3123. try:
  3124. webpage = urllib2.urlopen(request).read()
  3125. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  3126. self._downloader.trouble(u'ERROR: unable to download video webpage: %s' % str(err))
  3127. return
  3128. self.report_extraction(url)
  3129. # Extract video URL
  3130. mobj = re.search(r"jsclassref='([^']*)'", webpage)
  3131. if mobj is None:
  3132. self._downloader.trouble(u'ERROR: unable to extract video url')
  3133. return
  3134. video_url = 'rtmpe://video.infoq.com/cfx/st/' + urllib2.unquote(mobj.group(1).decode('base64'))
  3135. # Extract title
  3136. mobj = re.search(r'contentTitle = "(.*?)";', webpage)
  3137. if mobj is None:
  3138. self._downloader.trouble(u'ERROR: unable to extract video title')
  3139. return
  3140. video_title = mobj.group(1).decode('utf-8')
  3141. # Extract description
  3142. video_description = u'No description available.'
  3143. mobj = re.search(r'<meta name="description" content="(.*)"(?:\s*/)?>', webpage)
  3144. if mobj is not None:
  3145. video_description = mobj.group(1).decode('utf-8')
  3146. video_filename = video_url.split('/')[-1]
  3147. video_id, extension = video_filename.split('.')
  3148. self._downloader.increment_downloads()
  3149. info = {
  3150. 'id': video_id,
  3151. 'url': video_url,
  3152. 'uploader': None,
  3153. 'upload_date': None,
  3154. 'title': video_title,
  3155. 'stitle': _simplify_title(video_title),
  3156. 'ext': extension,
  3157. 'format': extension, # Extension is always(?) mp4, but seems to be flv
  3158. 'thumbnail': None,
  3159. 'description': video_description,
  3160. 'player_url': None,
  3161. }
  3162. try:
  3163. self._downloader.process_info(info)
  3164. except UnavailableVideoError, err:
  3165. self._downloader.trouble(u'\nERROR: unable to download ' + video_url)
  3166. class MixcloudIE(InfoExtractor):
  3167. """Information extractor for www.mixcloud.com"""
  3168. _VALID_URL = r'^(?:https?://)?(?:www\.)?mixcloud\.com/([\w\d-]+)/([\w\d-]+)'
  3169. IE_NAME = u'mixcloud'
  3170. def __init__(self, downloader=None):
  3171. InfoExtractor.__init__(self, downloader)
  3172. def report_download_json(self, file_id):
  3173. """Report JSON download."""
  3174. self._downloader.to_screen(u'[%s] Downloading json' % self.IE_NAME)
  3175. def report_extraction(self, file_id):
  3176. """Report information extraction."""
  3177. self._downloader.to_screen(u'[%s] %s: Extracting information' % (self.IE_NAME, file_id))
  3178. def get_urls(self, jsonData, fmt, bitrate='best'):
  3179. """Get urls from 'audio_formats' section in json"""
  3180. file_url = None
  3181. try:
  3182. bitrate_list = jsonData[fmt]
  3183. if bitrate is None or bitrate == 'best' or bitrate not in bitrate_list:
  3184. bitrate = max(bitrate_list) # select highest
  3185. url_list = jsonData[fmt][bitrate]
  3186. except TypeError: # we have no bitrate info.
  3187. url_list = jsonData[fmt]
  3188. return url_list
  3189. def check_urls(self, url_list):
  3190. """Returns 1st active url from list"""
  3191. for url in url_list:
  3192. try:
  3193. urllib2.urlopen(url)
  3194. return url
  3195. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  3196. url = None
  3197. return None
  3198. def _print_formats(self, formats):
  3199. print 'Available formats:'
  3200. for fmt in formats.keys():
  3201. for b in formats[fmt]:
  3202. try:
  3203. ext = formats[fmt][b][0]
  3204. print '%s\t%s\t[%s]' % (fmt, b, ext.split('.')[-1])
  3205. except TypeError: # we have no bitrate info
  3206. ext = formats[fmt][0]
  3207. print '%s\t%s\t[%s]' % (fmt, '??', ext.split('.')[-1])
  3208. break
  3209. def _real_extract(self, url):
  3210. mobj = re.match(self._VALID_URL, url)
  3211. if mobj is None:
  3212. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  3213. return
  3214. # extract uploader & filename from url
  3215. uploader = mobj.group(1).decode('utf-8')
  3216. file_id = uploader + "-" + mobj.group(2).decode('utf-8')
  3217. # construct API request
  3218. file_url = 'http://www.mixcloud.com/api/1/cloudcast/' + '/'.join(url.split('/')[-3:-1]) + '.json'
  3219. # retrieve .json file with links to files
  3220. request = urllib2.Request(file_url)
  3221. try:
  3222. self.report_download_json(file_url)
  3223. jsonData = urllib2.urlopen(request).read()
  3224. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  3225. self._downloader.trouble(u'ERROR: Unable to retrieve file: %s' % str(err))
  3226. return
  3227. # parse JSON
  3228. json_data = json.loads(jsonData)
  3229. player_url = json_data['player_swf_url']
  3230. formats = dict(json_data['audio_formats'])
  3231. req_format = self._downloader.params.get('format', None)
  3232. bitrate = None
  3233. if self._downloader.params.get('listformats', None):
  3234. self._print_formats(formats)
  3235. return
  3236. if req_format is None or req_format == 'best':
  3237. for format_param in formats.keys():
  3238. url_list = self.get_urls(formats, format_param)
  3239. # check urls
  3240. file_url = self.check_urls(url_list)
  3241. if file_url is not None:
  3242. break # got it!
  3243. else:
  3244. if req_format not in formats.keys():
  3245. self._downloader.trouble(u'ERROR: format is not available')
  3246. return
  3247. url_list = self.get_urls(formats, req_format)
  3248. file_url = self.check_urls(url_list)
  3249. format_param = req_format
  3250. # We have audio
  3251. self._downloader.increment_downloads()
  3252. try:
  3253. # Process file information
  3254. self._downloader.process_info({
  3255. 'id': file_id.decode('utf-8'),
  3256. 'url': file_url.decode('utf-8'),
  3257. 'uploader': uploader.decode('utf-8'),
  3258. 'upload_date': u'NA',
  3259. 'title': json_data['name'],
  3260. 'stitle': _simplify_title(json_data['name']),
  3261. 'ext': file_url.split('.')[-1].decode('utf-8'),
  3262. 'format': (format_param is None and u'NA' or format_param.decode('utf-8')),
  3263. 'thumbnail': json_data['thumbnail_url'],
  3264. 'description': json_data['description'],
  3265. 'player_url': player_url.decode('utf-8'),
  3266. })
  3267. except UnavailableVideoError, err:
  3268. self._downloader.trouble(u'ERROR: unable to download file')
  3269. class StanfordOpenClassroomIE(InfoExtractor):
  3270. """Information extractor for Stanford's Open ClassRoom"""
  3271. _VALID_URL = r'^(?:https?://)?openclassroom.stanford.edu(?P<path>/?|(/MainFolder/(?:HomePage|CoursePage|VideoPage)\.php([?]course=(?P<course>[^&]+)(&video=(?P<video>[^&]+))?(&.*)?)?))$'
  3272. IE_NAME = u'stanfordoc'
  3273. def report_download_webpage(self, objid):
  3274. """Report information extraction."""
  3275. self._downloader.to_screen(u'[%s] %s: Downloading webpage' % (self.IE_NAME, objid))
  3276. def report_extraction(self, video_id):
  3277. """Report information extraction."""
  3278. self._downloader.to_screen(u'[%s] %s: Extracting information' % (self.IE_NAME, video_id))
  3279. def _real_extract(self, url):
  3280. mobj = re.match(self._VALID_URL, url)
  3281. if mobj is None:
  3282. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  3283. return
  3284. if mobj.group('course') and mobj.group('video'): # A specific video
  3285. course = mobj.group('course')
  3286. video = mobj.group('video')
  3287. info = {
  3288. 'id': _simplify_title(course + '_' + video),
  3289. }
  3290. self.report_extraction(info['id'])
  3291. baseUrl = 'http://openclassroom.stanford.edu/MainFolder/courses/' + course + '/videos/'
  3292. xmlUrl = baseUrl + video + '.xml'
  3293. try:
  3294. metaXml = urllib2.urlopen(xmlUrl).read()
  3295. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  3296. self._downloader.trouble(u'ERROR: unable to download video info XML: %s' % unicode(err))
  3297. return
  3298. mdoc = xml.etree.ElementTree.fromstring(metaXml)
  3299. try:
  3300. info['title'] = mdoc.findall('./title')[0].text
  3301. info['url'] = baseUrl + mdoc.findall('./videoFile')[0].text
  3302. except IndexError:
  3303. self._downloader.trouble(u'\nERROR: Invalid metadata XML file')
  3304. return
  3305. info['stitle'] = _simplify_title(info['title'])
  3306. info['ext'] = info['url'].rpartition('.')[2]
  3307. info['format'] = info['ext']
  3308. self._downloader.increment_downloads()
  3309. try:
  3310. self._downloader.process_info(info)
  3311. except UnavailableVideoError, err:
  3312. self._downloader.trouble(u'\nERROR: unable to download video')
  3313. elif mobj.group('course'): # A course page
  3314. unescapeHTML = HTMLParser.HTMLParser().unescape
  3315. course = mobj.group('course')
  3316. info = {
  3317. 'id': _simplify_title(course),
  3318. 'type': 'playlist',
  3319. }
  3320. self.report_download_webpage(info['id'])
  3321. try:
  3322. coursepage = urllib2.urlopen(url).read()
  3323. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  3324. self._downloader.trouble(u'ERROR: unable to download course info page: ' + unicode(err))
  3325. return
  3326. m = re.search('<h1>([^<]+)</h1>', coursepage)
  3327. if m:
  3328. info['title'] = unescapeHTML(m.group(1))
  3329. else:
  3330. info['title'] = info['id']
  3331. info['stitle'] = _simplify_title(info['title'])
  3332. m = re.search('<description>([^<]+)</description>', coursepage)
  3333. if m:
  3334. info['description'] = unescapeHTML(m.group(1))
  3335. links = _orderedSet(re.findall('<a href="(VideoPage.php\?[^"]+)">', coursepage))
  3336. info['list'] = [
  3337. {
  3338. 'type': 'reference',
  3339. 'url': 'http://openclassroom.stanford.edu/MainFolder/' + unescapeHTML(vpage),
  3340. }
  3341. for vpage in links]
  3342. for entry in info['list']:
  3343. assert entry['type'] == 'reference'
  3344. self.extract(entry['url'])
  3345. else: # Root page
  3346. unescapeHTML = HTMLParser.HTMLParser().unescape
  3347. info = {
  3348. 'id': 'Stanford OpenClassroom',
  3349. 'type': 'playlist',
  3350. }
  3351. self.report_download_webpage(info['id'])
  3352. rootURL = 'http://openclassroom.stanford.edu/MainFolder/HomePage.php'
  3353. try:
  3354. rootpage = urllib2.urlopen(rootURL).read()
  3355. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  3356. self._downloader.trouble(u'ERROR: unable to download course info page: ' + unicode(err))
  3357. return
  3358. info['title'] = info['id']
  3359. info['stitle'] = _simplify_title(info['title'])
  3360. links = _orderedSet(re.findall('<a href="(CoursePage.php\?[^"]+)">', rootpage))
  3361. info['list'] = [
  3362. {
  3363. 'type': 'reference',
  3364. 'url': 'http://openclassroom.stanford.edu/MainFolder/' + unescapeHTML(cpage),
  3365. }
  3366. for cpage in links]
  3367. for entry in info['list']:
  3368. assert entry['type'] == 'reference'
  3369. self.extract(entry['url'])
  3370. class MTVIE(InfoExtractor):
  3371. """Information extractor for MTV.com"""
  3372. _VALID_URL = r'^(?P<proto>https?://)?(?:www\.)?mtv\.com/videos/[^/]+/(?P<videoid>[0-9]+)/[^/]+$'
  3373. IE_NAME = u'mtv'
  3374. def report_webpage(self, video_id):
  3375. """Report information extraction."""
  3376. self._downloader.to_screen(u'[%s] %s: Downloading webpage' % (self.IE_NAME, video_id))
  3377. def report_extraction(self, video_id):
  3378. """Report information extraction."""
  3379. self._downloader.to_screen(u'[%s] %s: Extracting information' % (self.IE_NAME, video_id))
  3380. def _real_extract(self, url):
  3381. mobj = re.match(self._VALID_URL, url)
  3382. if mobj is None:
  3383. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  3384. return
  3385. if not mobj.group('proto'):
  3386. url = 'http://' + url
  3387. video_id = mobj.group('videoid')
  3388. self.report_webpage(video_id)
  3389. request = urllib2.Request(url)
  3390. try:
  3391. webpage = urllib2.urlopen(request).read()
  3392. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  3393. self._downloader.trouble(u'ERROR: unable to download video webpage: %s' % str(err))
  3394. return
  3395. mobj = re.search(r'<meta name="mtv_vt" content="([^"]+)"/>', webpage)
  3396. if mobj is None:
  3397. self._downloader.trouble(u'ERROR: unable to extract song name')
  3398. return
  3399. song_name = _unescapeHTML(mobj.group(1).decode('iso-8859-1'))
  3400. mobj = re.search(r'<meta name="mtv_an" content="([^"]+)"/>', webpage)
  3401. if mobj is None:
  3402. self._downloader.trouble(u'ERROR: unable to extract performer')
  3403. return
  3404. performer = _unescapeHTML(mobj.group(1).decode('iso-8859-1'))
  3405. video_title = performer + ' - ' + song_name
  3406. mobj = re.search(r'<meta name="mtvn_uri" content="([^"]+)"/>', webpage)
  3407. if mobj is None:
  3408. self._downloader.trouble(u'ERROR: unable to mtvn_uri')
  3409. return
  3410. mtvn_uri = mobj.group(1)
  3411. mobj = re.search(r'MTVN.Player.defaultPlaylistId = ([0-9]+);', webpage)
  3412. if mobj is None:
  3413. self._downloader.trouble(u'ERROR: unable to extract content id')
  3414. return
  3415. content_id = mobj.group(1)
  3416. 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
  3417. self.report_extraction(video_id)
  3418. request = urllib2.Request(videogen_url)
  3419. try:
  3420. metadataXml = urllib2.urlopen(request).read()
  3421. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  3422. self._downloader.trouble(u'ERROR: unable to download video metadata: %s' % str(err))
  3423. return
  3424. mdoc = xml.etree.ElementTree.fromstring(metadataXml)
  3425. renditions = mdoc.findall('.//rendition')
  3426. # For now, always pick the highest quality.
  3427. rendition = renditions[-1]
  3428. try:
  3429. _,_,ext = rendition.attrib['type'].partition('/')
  3430. format = ext + '-' + rendition.attrib['width'] + 'x' + rendition.attrib['height'] + '_' + rendition.attrib['bitrate']
  3431. video_url = rendition.find('./src').text
  3432. except KeyError:
  3433. self._downloader.trouble('Invalid rendition field.')
  3434. return
  3435. self._downloader.increment_downloads()
  3436. info = {
  3437. 'id': video_id,
  3438. 'url': video_url,
  3439. 'uploader': performer,
  3440. 'title': video_title,
  3441. 'stitle': _simplify_title(video_title),
  3442. 'ext': ext,
  3443. 'format': format,
  3444. }
  3445. try:
  3446. self._downloader.process_info(info)
  3447. except UnavailableVideoError, err:
  3448. self._downloader.trouble(u'\nERROR: unable to download ' + video_id)
  3449. class PostProcessor(object):
  3450. """Post Processor class.
  3451. PostProcessor objects can be added to downloaders with their
  3452. add_post_processor() method. When the downloader has finished a
  3453. successful download, it will take its internal chain of PostProcessors
  3454. and start calling the run() method on each one of them, first with
  3455. an initial argument and then with the returned value of the previous
  3456. PostProcessor.
  3457. The chain will be stopped if one of them ever returns None or the end
  3458. of the chain is reached.
  3459. PostProcessor objects follow a "mutual registration" process similar
  3460. to InfoExtractor objects.
  3461. """
  3462. _downloader = None
  3463. def __init__(self, downloader=None):
  3464. self._downloader = downloader
  3465. def set_downloader(self, downloader):
  3466. """Sets the downloader for this PP."""
  3467. self._downloader = downloader
  3468. def run(self, information):
  3469. """Run the PostProcessor.
  3470. The "information" argument is a dictionary like the ones
  3471. composed by InfoExtractors. The only difference is that this
  3472. one has an extra field called "filepath" that points to the
  3473. downloaded file.
  3474. When this method returns None, the postprocessing chain is
  3475. stopped. However, this method may return an information
  3476. dictionary that will be passed to the next postprocessing
  3477. object in the chain. It can be the one it received after
  3478. changing some fields.
  3479. In addition, this method may raise a PostProcessingError
  3480. exception that will be taken into account by the downloader
  3481. it was called from.
  3482. """
  3483. return information # by default, do nothing
  3484. class AudioConversionError(BaseException):
  3485. def __init__(self, message):
  3486. self.message = message
  3487. class FFmpegExtractAudioPP(PostProcessor):
  3488. def __init__(self, downloader=None, preferredcodec=None, preferredquality=None, keepvideo=False):
  3489. PostProcessor.__init__(self, downloader)
  3490. if preferredcodec is None:
  3491. preferredcodec = 'best'
  3492. self._preferredcodec = preferredcodec
  3493. self._preferredquality = preferredquality
  3494. self._keepvideo = keepvideo
  3495. @staticmethod
  3496. def get_audio_codec(path):
  3497. try:
  3498. cmd = ['ffprobe', '-show_streams', '--', _encodeFilename(path)]
  3499. handle = subprocess.Popen(cmd, stderr=file(os.path.devnull, 'w'), stdout=subprocess.PIPE)
  3500. output = handle.communicate()[0]
  3501. if handle.wait() != 0:
  3502. return None
  3503. except (IOError, OSError):
  3504. return None
  3505. audio_codec = None
  3506. for line in output.split('\n'):
  3507. if line.startswith('codec_name='):
  3508. audio_codec = line.split('=')[1].strip()
  3509. elif line.strip() == 'codec_type=audio' and audio_codec is not None:
  3510. return audio_codec
  3511. return None
  3512. @staticmethod
  3513. def run_ffmpeg(path, out_path, codec, more_opts):
  3514. if codec is None:
  3515. acodec_opts = []
  3516. else:
  3517. acodec_opts = ['-acodec', codec]
  3518. cmd = ['ffmpeg', '-y', '-i', _encodeFilename(path), '-vn'] + acodec_opts + more_opts + ['--', _encodeFilename(out_path)]
  3519. try:
  3520. p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  3521. stdout,stderr = p.communicate()
  3522. except (IOError, OSError):
  3523. e = sys.exc_info()[1]
  3524. if isinstance(e, OSError) and e.errno == 2:
  3525. raise AudioConversionError('ffmpeg not found. Please install ffmpeg.')
  3526. else:
  3527. raise e
  3528. if p.returncode != 0:
  3529. msg = stderr.strip().split('\n')[-1]
  3530. raise AudioConversionError(msg)
  3531. def run(self, information):
  3532. path = information['filepath']
  3533. filecodec = self.get_audio_codec(path)
  3534. if filecodec is None:
  3535. self._downloader.to_stderr(u'WARNING: unable to obtain file audio codec with ffprobe')
  3536. return None
  3537. more_opts = []
  3538. if self._preferredcodec == 'best' or self._preferredcodec == filecodec or (self._preferredcodec == 'm4a' and filecodec == 'aac'):
  3539. if self._preferredcodec == 'm4a' and filecodec == 'aac':
  3540. # Lossless, but in another container
  3541. acodec = 'copy'
  3542. extension = self._preferredcodec
  3543. more_opts = ['-absf', 'aac_adtstoasc']
  3544. elif filecodec in ['aac', 'mp3', 'vorbis']:
  3545. # Lossless if possible
  3546. acodec = 'copy'
  3547. extension = filecodec
  3548. if filecodec == 'aac':
  3549. more_opts = ['-f', 'adts']
  3550. if filecodec == 'vorbis':
  3551. extension = 'ogg'
  3552. else:
  3553. # MP3 otherwise.
  3554. acodec = 'libmp3lame'
  3555. extension = 'mp3'
  3556. more_opts = []
  3557. if self._preferredquality is not None:
  3558. more_opts += ['-ab', self._preferredquality]
  3559. else:
  3560. # We convert the audio (lossy)
  3561. acodec = {'mp3': 'libmp3lame', 'aac': 'aac', 'm4a': 'aac', 'vorbis': 'libvorbis', 'wav': None}[self._preferredcodec]
  3562. extension = self._preferredcodec
  3563. more_opts = []
  3564. if self._preferredquality is not None:
  3565. more_opts += ['-ab', self._preferredquality]
  3566. if self._preferredcodec == 'aac':
  3567. more_opts += ['-f', 'adts']
  3568. if self._preferredcodec == 'm4a':
  3569. more_opts += ['-absf', 'aac_adtstoasc']
  3570. if self._preferredcodec == 'vorbis':
  3571. extension = 'ogg'
  3572. if self._preferredcodec == 'wav':
  3573. extension = 'wav'
  3574. more_opts += ['-f', 'wav']
  3575. prefix, sep, ext = path.rpartition(u'.') # not os.path.splitext, since the latter does not work on unicode in all setups
  3576. new_path = prefix + sep + extension
  3577. self._downloader.to_screen(u'[ffmpeg] Destination: ' + new_path)
  3578. try:
  3579. self.run_ffmpeg(path, new_path, acodec, more_opts)
  3580. except:
  3581. etype,e,tb = sys.exc_info()
  3582. if isinstance(e, AudioConversionError):
  3583. self._downloader.to_stderr(u'ERROR: audio conversion failed: ' + e.message)
  3584. else:
  3585. self._downloader.to_stderr(u'ERROR: error running ffmpeg')
  3586. return None
  3587. # Try to update the date time for extracted audio file.
  3588. if information.get('filetime') is not None:
  3589. try:
  3590. os.utime(_encodeFilename(new_path), (time.time(), information['filetime']))
  3591. except:
  3592. self._downloader.to_stderr(u'WARNING: Cannot update utime of audio file')
  3593. if not self._keepvideo:
  3594. try:
  3595. os.remove(_encodeFilename(path))
  3596. except (IOError, OSError):
  3597. self._downloader.to_stderr(u'WARNING: Unable to remove downloaded video file')
  3598. return None
  3599. information['filepath'] = new_path
  3600. return information
  3601. def updateSelf(downloader, filename):
  3602. ''' Update the program file with the latest version from the repository '''
  3603. # Note: downloader only used for options
  3604. if not os.access(filename, os.W_OK):
  3605. sys.exit('ERROR: no write permissions on %s' % filename)
  3606. downloader.to_screen(u'Updating to latest version...')
  3607. try:
  3608. try:
  3609. urlh = urllib.urlopen(UPDATE_URL)
  3610. newcontent = urlh.read()
  3611. vmatch = re.search("__version__ = '([^']+)'", newcontent)
  3612. if vmatch is not None and vmatch.group(1) == __version__:
  3613. downloader.to_screen(u'youtube-dl is up-to-date (' + __version__ + ')')
  3614. return
  3615. finally:
  3616. urlh.close()
  3617. except (IOError, OSError), err:
  3618. sys.exit('ERROR: unable to download latest version')
  3619. try:
  3620. outf = open(filename, 'wb')
  3621. try:
  3622. outf.write(newcontent)
  3623. finally:
  3624. outf.close()
  3625. except (IOError, OSError), err:
  3626. sys.exit('ERROR: unable to overwrite current version')
  3627. downloader.to_screen(u'Updated youtube-dl. Restart youtube-dl to use the new version.')
  3628. def parseOpts():
  3629. def _readOptions(filename_bytes):
  3630. try:
  3631. optionf = open(filename_bytes)
  3632. except IOError:
  3633. return [] # silently skip if file is not present
  3634. try:
  3635. res = []
  3636. for l in optionf:
  3637. res += shlex.split(l, comments=True)
  3638. finally:
  3639. optionf.close()
  3640. return res
  3641. def _format_option_string(option):
  3642. ''' ('-o', '--option') -> -o, --format METAVAR'''
  3643. opts = []
  3644. if option._short_opts: opts.append(option._short_opts[0])
  3645. if option._long_opts: opts.append(option._long_opts[0])
  3646. if len(opts) > 1: opts.insert(1, ', ')
  3647. if option.takes_value(): opts.append(' %s' % option.metavar)
  3648. return "".join(opts)
  3649. def _find_term_columns():
  3650. columns = os.environ.get('COLUMNS', None)
  3651. if columns:
  3652. return int(columns)
  3653. try:
  3654. sp = subprocess.Popen(['stty', 'size'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  3655. out,err = sp.communicate()
  3656. return int(out.split()[1])
  3657. except:
  3658. pass
  3659. return None
  3660. max_width = 80
  3661. max_help_position = 80
  3662. # No need to wrap help messages if we're on a wide console
  3663. columns = _find_term_columns()
  3664. if columns: max_width = columns
  3665. fmt = optparse.IndentedHelpFormatter(width=max_width, max_help_position=max_help_position)
  3666. fmt.format_option_strings = _format_option_string
  3667. kw = {
  3668. 'version' : __version__,
  3669. 'formatter' : fmt,
  3670. 'usage' : '%prog [options] url [url...]',
  3671. 'conflict_handler' : 'resolve',
  3672. }
  3673. parser = optparse.OptionParser(**kw)
  3674. # option groups
  3675. general = optparse.OptionGroup(parser, 'General Options')
  3676. selection = optparse.OptionGroup(parser, 'Video Selection')
  3677. authentication = optparse.OptionGroup(parser, 'Authentication Options')
  3678. video_format = optparse.OptionGroup(parser, 'Video Format Options')
  3679. postproc = optparse.OptionGroup(parser, 'Post-processing Options')
  3680. filesystem = optparse.OptionGroup(parser, 'Filesystem Options')
  3681. verbosity = optparse.OptionGroup(parser, 'Verbosity / Simulation Options')
  3682. general.add_option('-h', '--help',
  3683. action='help', help='print this help text and exit')
  3684. general.add_option('-v', '--version',
  3685. action='version', help='print program version and exit')
  3686. general.add_option('-U', '--update',
  3687. action='store_true', dest='update_self', help='update this program to latest version')
  3688. general.add_option('-i', '--ignore-errors',
  3689. action='store_true', dest='ignoreerrors', help='continue on download errors', default=False)
  3690. general.add_option('-r', '--rate-limit',
  3691. dest='ratelimit', metavar='LIMIT', help='download rate limit (e.g. 50k or 44.6m)')
  3692. general.add_option('-R', '--retries',
  3693. dest='retries', metavar='RETRIES', help='number of retries (default is 10)', default=10)
  3694. general.add_option('--dump-user-agent',
  3695. action='store_true', dest='dump_user_agent',
  3696. help='display the current browser identification', default=False)
  3697. general.add_option('--list-extractors',
  3698. action='store_true', dest='list_extractors',
  3699. help='List all supported extractors and the URLs they would handle', default=False)
  3700. selection.add_option('--playlist-start',
  3701. dest='playliststart', metavar='NUMBER', help='playlist video to start at (default is 1)', default=1)
  3702. selection.add_option('--playlist-end',
  3703. dest='playlistend', metavar='NUMBER', help='playlist video to end at (default is last)', default=-1)
  3704. selection.add_option('--match-title', dest='matchtitle', metavar='REGEX',help='download only matching titles (regex or caseless sub-string)')
  3705. selection.add_option('--reject-title', dest='rejecttitle', metavar='REGEX',help='skip download for matching titles (regex or caseless sub-string)')
  3706. selection.add_option('--max-downloads', metavar='NUMBER', dest='max_downloads', help='Abort after downloading NUMBER files', default=None)
  3707. authentication.add_option('-u', '--username',
  3708. dest='username', metavar='USERNAME', help='account username')
  3709. authentication.add_option('-p', '--password',
  3710. dest='password', metavar='PASSWORD', help='account password')
  3711. authentication.add_option('-n', '--netrc',
  3712. action='store_true', dest='usenetrc', help='use .netrc authentication data', default=False)
  3713. video_format.add_option('-f', '--format',
  3714. action='store', dest='format', metavar='FORMAT', help='video format code')
  3715. video_format.add_option('--all-formats',
  3716. action='store_const', dest='format', help='download all available video formats', const='all')
  3717. video_format.add_option('--prefer-free-formats',
  3718. action='store_true', dest='prefer_free_formats', default=False, help='prefer free video formats unless a specific one is requested')
  3719. video_format.add_option('--max-quality',
  3720. action='store', dest='format_limit', metavar='FORMAT', help='highest quality format to download')
  3721. video_format.add_option('-F', '--list-formats',
  3722. action='store_true', dest='listformats', help='list all available formats (currently youtube only)')
  3723. video_format.add_option('--write-srt',
  3724. action='store_true', dest='writesubtitles',
  3725. help='write video closed captions to a .srt file (currently youtube only)', default=False)
  3726. video_format.add_option('--srt-lang',
  3727. action='store', dest='subtitleslang', metavar='LANG',
  3728. help='language of the closed captions to download (optional) use IETF language tags like \'en\'')
  3729. verbosity.add_option('-q', '--quiet',
  3730. action='store_true', dest='quiet', help='activates quiet mode', default=False)
  3731. verbosity.add_option('-s', '--simulate',
  3732. action='store_true', dest='simulate', help='do not download the video and do not write anything to disk', default=False)
  3733. verbosity.add_option('--skip-download',
  3734. action='store_true', dest='skip_download', help='do not download the video', default=False)
  3735. verbosity.add_option('-g', '--get-url',
  3736. action='store_true', dest='geturl', help='simulate, quiet but print URL', default=False)
  3737. verbosity.add_option('-e', '--get-title',
  3738. action='store_true', dest='gettitle', help='simulate, quiet but print title', default=False)
  3739. verbosity.add_option('--get-thumbnail',
  3740. action='store_true', dest='getthumbnail',
  3741. help='simulate, quiet but print thumbnail URL', default=False)
  3742. verbosity.add_option('--get-description',
  3743. action='store_true', dest='getdescription',
  3744. help='simulate, quiet but print video description', default=False)
  3745. verbosity.add_option('--get-filename',
  3746. action='store_true', dest='getfilename',
  3747. help='simulate, quiet but print output filename', default=False)
  3748. verbosity.add_option('--get-format',
  3749. action='store_true', dest='getformat',
  3750. help='simulate, quiet but print output format', default=False)
  3751. verbosity.add_option('--no-progress',
  3752. action='store_true', dest='noprogress', help='do not print progress bar', default=False)
  3753. verbosity.add_option('--console-title',
  3754. action='store_true', dest='consoletitle',
  3755. help='display progress in console titlebar', default=False)
  3756. verbosity.add_option('-v', '--verbose',
  3757. action='store_true', dest='verbose', help='print various debugging information', default=False)
  3758. filesystem.add_option('-t', '--title',
  3759. action='store_true', dest='usetitle', help='use title in file name', default=False)
  3760. filesystem.add_option('-l', '--literal',
  3761. action='store_true', dest='useliteral', help='use literal title in file name', default=False)
  3762. filesystem.add_option('-A', '--auto-number',
  3763. action='store_true', dest='autonumber',
  3764. help='number downloaded files starting from 00000', default=False)
  3765. filesystem.add_option('-o', '--output',
  3766. 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.')
  3767. filesystem.add_option('-a', '--batch-file',
  3768. dest='batchfile', metavar='FILE', help='file containing URLs to download (\'-\' for stdin)')
  3769. filesystem.add_option('-w', '--no-overwrites',
  3770. action='store_true', dest='nooverwrites', help='do not overwrite files', default=False)
  3771. filesystem.add_option('-c', '--continue',
  3772. action='store_true', dest='continue_dl', help='resume partially downloaded files', default=True)
  3773. filesystem.add_option('--no-continue',
  3774. action='store_false', dest='continue_dl',
  3775. help='do not resume partially downloaded files (restart from beginning)')
  3776. filesystem.add_option('--cookies',
  3777. dest='cookiefile', metavar='FILE', help='file to read cookies from and dump cookie jar in')
  3778. filesystem.add_option('--no-part',
  3779. action='store_true', dest='nopart', help='do not use .part files', default=False)
  3780. filesystem.add_option('--no-mtime',
  3781. action='store_false', dest='updatetime',
  3782. help='do not use the Last-modified header to set the file modification time', default=True)
  3783. filesystem.add_option('--write-description',
  3784. action='store_true', dest='writedescription',
  3785. help='write video description to a .description file', default=False)
  3786. filesystem.add_option('--write-info-json',
  3787. action='store_true', dest='writeinfojson',
  3788. help='write video metadata to a .info.json file', default=False)
  3789. postproc.add_option('--extract-audio', action='store_true', dest='extractaudio', default=False,
  3790. help='convert video files to audio-only files (requires ffmpeg and ffprobe)')
  3791. postproc.add_option('--audio-format', metavar='FORMAT', dest='audioformat', default='best',
  3792. help='"best", "aac", "vorbis", "mp3", "m4a", or "wav"; best by default')
  3793. postproc.add_option('--audio-quality', metavar='QUALITY', dest='audioquality', default='128K',
  3794. help='ffmpeg audio bitrate specification, 128k by default')
  3795. postproc.add_option('-k', '--keep-video', action='store_true', dest='keepvideo', default=False,
  3796. help='keeps the video file on disk after the post-processing; the video is erased by default')
  3797. parser.add_option_group(general)
  3798. parser.add_option_group(selection)
  3799. parser.add_option_group(filesystem)
  3800. parser.add_option_group(verbosity)
  3801. parser.add_option_group(video_format)
  3802. parser.add_option_group(authentication)
  3803. parser.add_option_group(postproc)
  3804. xdg_config_home = os.environ.get('XDG_CONFIG_HOME')
  3805. if xdg_config_home:
  3806. userConf = os.path.join(xdg_config_home, 'youtube-dl.conf')
  3807. else:
  3808. userConf = os.path.join(os.path.expanduser('~'), '.config', 'youtube-dl.conf')
  3809. argv = _readOptions('/etc/youtube-dl.conf') + _readOptions(userConf) + sys.argv[1:]
  3810. opts, args = parser.parse_args(argv)
  3811. return parser, opts, args
  3812. def gen_extractors():
  3813. """ Return a list of an instance of every supported extractor.
  3814. The order does matter; the first extractor matched is the one handling the URL.
  3815. """
  3816. youtube_ie = YoutubeIE()
  3817. google_ie = GoogleIE()
  3818. yahoo_ie = YahooIE()
  3819. return [
  3820. YoutubePlaylistIE(youtube_ie),
  3821. YoutubeUserIE(youtube_ie),
  3822. YoutubeSearchIE(youtube_ie),
  3823. youtube_ie,
  3824. MetacafeIE(youtube_ie),
  3825. DailymotionIE(),
  3826. google_ie,
  3827. GoogleSearchIE(google_ie),
  3828. PhotobucketIE(),
  3829. yahoo_ie,
  3830. YahooSearchIE(yahoo_ie),
  3831. DepositFilesIE(),
  3832. FacebookIE(),
  3833. BlipTVIE(),
  3834. VimeoIE(),
  3835. MyVideoIE(),
  3836. ComedyCentralIE(),
  3837. EscapistIE(),
  3838. CollegeHumorIE(),
  3839. XVideosIE(),
  3840. SoundcloudIE(),
  3841. InfoQIE(),
  3842. MixcloudIE(),
  3843. StanfordOpenClassroomIE(),
  3844. MTVIE(),
  3845. GenericIE()
  3846. ]
  3847. def _real_main():
  3848. parser, opts, args = parseOpts()
  3849. # Open appropriate CookieJar
  3850. if opts.cookiefile is None:
  3851. jar = cookielib.CookieJar()
  3852. else:
  3853. try:
  3854. jar = cookielib.MozillaCookieJar(opts.cookiefile)
  3855. if os.path.isfile(opts.cookiefile) and os.access(opts.cookiefile, os.R_OK):
  3856. jar.load()
  3857. except (IOError, OSError), err:
  3858. sys.exit(u'ERROR: unable to open cookie file')
  3859. # Dump user agent
  3860. if opts.dump_user_agent:
  3861. print std_headers['User-Agent']
  3862. sys.exit(0)
  3863. # Batch file verification
  3864. batchurls = []
  3865. if opts.batchfile is not None:
  3866. try:
  3867. if opts.batchfile == '-':
  3868. batchfd = sys.stdin
  3869. else:
  3870. batchfd = open(opts.batchfile, 'r')
  3871. batchurls = batchfd.readlines()
  3872. batchurls = [x.strip() for x in batchurls]
  3873. batchurls = [x for x in batchurls if len(x) > 0 and not re.search(r'^[#/;]', x)]
  3874. except IOError:
  3875. sys.exit(u'ERROR: batch file could not be read')
  3876. all_urls = batchurls + args
  3877. all_urls = map(lambda url: url.strip(), all_urls)
  3878. # General configuration
  3879. cookie_processor = urllib2.HTTPCookieProcessor(jar)
  3880. proxy_handler = urllib2.ProxyHandler()
  3881. opener = urllib2.build_opener(proxy_handler, cookie_processor, YoutubeDLHandler())
  3882. urllib2.install_opener(opener)
  3883. socket.setdefaulttimeout(300) # 5 minutes should be enough (famous last words)
  3884. if opts.verbose:
  3885. print(u'[debug] Proxy map: ' + str(proxy_handler.proxies))
  3886. extractors = gen_extractors()
  3887. if opts.list_extractors:
  3888. for ie in extractors:
  3889. print(ie.IE_NAME)
  3890. matchedUrls = filter(lambda url: ie.suitable(url), all_urls)
  3891. all_urls = filter(lambda url: url not in matchedUrls, all_urls)
  3892. for mu in matchedUrls:
  3893. print(u' ' + mu)
  3894. sys.exit(0)
  3895. # Conflicting, missing and erroneous options
  3896. if opts.usenetrc and (opts.username is not None or opts.password is not None):
  3897. parser.error(u'using .netrc conflicts with giving username/password')
  3898. if opts.password is not None and opts.username is None:
  3899. parser.error(u'account username missing')
  3900. if opts.outtmpl is not None and (opts.useliteral or opts.usetitle or opts.autonumber):
  3901. parser.error(u'using output template conflicts with using title, literal title or auto number')
  3902. if opts.usetitle and opts.useliteral:
  3903. parser.error(u'using title conflicts with using literal title')
  3904. if opts.username is not None and opts.password is None:
  3905. opts.password = getpass.getpass(u'Type account password and press return:')
  3906. if opts.ratelimit is not None:
  3907. numeric_limit = FileDownloader.parse_bytes(opts.ratelimit)
  3908. if numeric_limit is None:
  3909. parser.error(u'invalid rate limit specified')
  3910. opts.ratelimit = numeric_limit
  3911. if opts.retries is not None:
  3912. try:
  3913. opts.retries = long(opts.retries)
  3914. except (TypeError, ValueError), err:
  3915. parser.error(u'invalid retry count specified')
  3916. try:
  3917. opts.playliststart = int(opts.playliststart)
  3918. if opts.playliststart <= 0:
  3919. raise ValueError(u'Playlist start must be positive')
  3920. except (TypeError, ValueError), err:
  3921. parser.error(u'invalid playlist start number specified')
  3922. try:
  3923. opts.playlistend = int(opts.playlistend)
  3924. if opts.playlistend != -1 and (opts.playlistend <= 0 or opts.playlistend < opts.playliststart):
  3925. raise ValueError(u'Playlist end must be greater than playlist start')
  3926. except (TypeError, ValueError), err:
  3927. parser.error(u'invalid playlist end number specified')
  3928. if opts.extractaudio:
  3929. if opts.audioformat not in ['best', 'aac', 'mp3', 'vorbis', 'm4a', 'wav']:
  3930. parser.error(u'invalid audio format specified')
  3931. # File downloader
  3932. fd = FileDownloader({
  3933. 'usenetrc': opts.usenetrc,
  3934. 'username': opts.username,
  3935. 'password': opts.password,
  3936. 'quiet': (opts.quiet or opts.geturl or opts.gettitle or opts.getthumbnail or opts.getdescription or opts.getfilename or opts.getformat),
  3937. 'forceurl': opts.geturl,
  3938. 'forcetitle': opts.gettitle,
  3939. 'forcethumbnail': opts.getthumbnail,
  3940. 'forcedescription': opts.getdescription,
  3941. 'forcefilename': opts.getfilename,
  3942. 'forceformat': opts.getformat,
  3943. 'simulate': opts.simulate,
  3944. '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),
  3945. 'format': opts.format,
  3946. 'format_limit': opts.format_limit,
  3947. 'listformats': opts.listformats,
  3948. 'outtmpl': ((opts.outtmpl is not None and opts.outtmpl.decode(preferredencoding()))
  3949. or (opts.format == '-1' and opts.usetitle and u'%(stitle)s-%(id)s-%(format)s.%(ext)s')
  3950. or (opts.format == '-1' and opts.useliteral and u'%(title)s-%(id)s-%(format)s.%(ext)s')
  3951. or (opts.format == '-1' and u'%(id)s-%(format)s.%(ext)s')
  3952. or (opts.usetitle and opts.autonumber and u'%(autonumber)s-%(stitle)s-%(id)s.%(ext)s')
  3953. or (opts.useliteral and opts.autonumber and u'%(autonumber)s-%(title)s-%(id)s.%(ext)s')
  3954. or (opts.usetitle and u'%(stitle)s-%(id)s.%(ext)s')
  3955. or (opts.useliteral and u'%(title)s-%(id)s.%(ext)s')
  3956. or (opts.autonumber and u'%(autonumber)s-%(id)s.%(ext)s')
  3957. or u'%(id)s.%(ext)s'),
  3958. 'ignoreerrors': opts.ignoreerrors,
  3959. 'ratelimit': opts.ratelimit,
  3960. 'nooverwrites': opts.nooverwrites,
  3961. 'retries': opts.retries,
  3962. 'continuedl': opts.continue_dl,
  3963. 'noprogress': opts.noprogress,
  3964. 'playliststart': opts.playliststart,
  3965. 'playlistend': opts.playlistend,
  3966. 'logtostderr': opts.outtmpl == '-',
  3967. 'consoletitle': opts.consoletitle,
  3968. 'nopart': opts.nopart,
  3969. 'updatetime': opts.updatetime,
  3970. 'writedescription': opts.writedescription,
  3971. 'writeinfojson': opts.writeinfojson,
  3972. 'writesubtitles': opts.writesubtitles,
  3973. 'subtitleslang': opts.subtitleslang,
  3974. 'matchtitle': opts.matchtitle,
  3975. 'rejecttitle': opts.rejecttitle,
  3976. 'max_downloads': opts.max_downloads,
  3977. 'prefer_free_formats': opts.prefer_free_formats,
  3978. 'verbose': opts.verbose,
  3979. })
  3980. for extractor in extractors:
  3981. fd.add_info_extractor(extractor)
  3982. # PostProcessors
  3983. if opts.extractaudio:
  3984. fd.add_post_processor(FFmpegExtractAudioPP(preferredcodec=opts.audioformat, preferredquality=opts.audioquality, keepvideo=opts.keepvideo))
  3985. # Update version
  3986. if opts.update_self:
  3987. updateSelf(fd, sys.argv[0])
  3988. # Maybe do nothing
  3989. if len(all_urls) < 1:
  3990. if not opts.update_self:
  3991. parser.error(u'you must provide at least one URL')
  3992. else:
  3993. sys.exit()
  3994. try:
  3995. retcode = fd.download(all_urls)
  3996. except MaxDownloadsReached:
  3997. fd.to_screen(u'--max-download limit reached, aborting.')
  3998. retcode = 101
  3999. # Dump cookie jar if requested
  4000. if opts.cookiefile is not None:
  4001. try:
  4002. jar.save()
  4003. except (IOError, OSError), err:
  4004. sys.exit(u'ERROR: unable to save cookie jar')
  4005. sys.exit(retcode)
  4006. def main():
  4007. try:
  4008. _real_main()
  4009. except DownloadError:
  4010. sys.exit(1)
  4011. except SameFileError:
  4012. sys.exit(u'ERROR: fixed output name but more than one file to download')
  4013. except KeyboardInterrupt:
  4014. sys.exit(u'\nERROR: Interrupted by user')
  4015. if __name__ == '__main__':
  4016. main()
  4017. # vim: set ts=4 sw=4 sts=4 noet ai si filetype=python: