youtube-dl 136 KB

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