__init__.py 156 KB

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