__init__.py 156 KB

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