__init__.py 144 KB

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