__init__.py 159 KB

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