youtube-dl 142 KB

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