youtube-dl 160 KB

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