__init__.py 156 KB

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