youtube-dl 129 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821
  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.18'
  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.dump(info_dict, infof)
  667. finally:
  668. infof.close()
  669. except (OSError, IOError):
  670. self.trouble(u'ERROR: Cannot write metadata to JSON file ' + infofn)
  671. return
  672. if not self.params.get('skip_download', False):
  673. try:
  674. success = self._do_download(filename, info_dict)
  675. except (OSError, IOError), err:
  676. raise UnavailableVideoError
  677. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  678. self.trouble(u'ERROR: unable to download video data: %s' % str(err))
  679. return
  680. except (ContentTooShortError, ), err:
  681. self.trouble(u'ERROR: content too short (expected %s bytes and served %s)' % (err.expected, err.downloaded))
  682. return
  683. if success:
  684. try:
  685. self.post_process(filename, info_dict)
  686. except (PostProcessingError), err:
  687. self.trouble(u'ERROR: postprocessing: %s' % str(err))
  688. return
  689. def download(self, url_list):
  690. """Download a given list of URLs."""
  691. if len(url_list) > 1 and self.fixed_template():
  692. raise SameFileError(self.params['outtmpl'])
  693. for url in url_list:
  694. suitable_found = False
  695. for ie in self._ies:
  696. # Go to next InfoExtractor if not suitable
  697. if not ie.suitable(url):
  698. continue
  699. # Suitable InfoExtractor found
  700. suitable_found = True
  701. # Extract information from URL and process it
  702. ie.extract(url)
  703. # Suitable InfoExtractor had been found; go to next URL
  704. break
  705. if not suitable_found:
  706. self.trouble(u'ERROR: no suitable InfoExtractor: %s' % url)
  707. return self._download_retcode
  708. def post_process(self, filename, ie_info):
  709. """Run the postprocessing chain on the given file."""
  710. info = dict(ie_info)
  711. info['filepath'] = filename
  712. for pp in self._pps:
  713. info = pp.run(info)
  714. if info is None:
  715. break
  716. def _download_with_rtmpdump(self, filename, url, player_url):
  717. self.report_destination(filename)
  718. tmpfilename = self.temp_name(filename)
  719. # Check for rtmpdump first
  720. try:
  721. subprocess.call(['rtmpdump', '-h'], stdout=(file(os.path.devnull, 'w')), stderr=subprocess.STDOUT)
  722. except (OSError, IOError):
  723. self.trouble(u'ERROR: RTMP download detected but "rtmpdump" could not be run')
  724. return False
  725. # Download using rtmpdump. rtmpdump returns exit code 2 when
  726. # the connection was interrumpted and resuming appears to be
  727. # possible. This is part of rtmpdump's normal usage, AFAIK.
  728. basic_args = ['rtmpdump', '-q'] + [[], ['-W', player_url]][player_url is not None] + ['-r', url, '-o', tmpfilename]
  729. retval = subprocess.call(basic_args + [[], ['-e', '-k', '1']][self.params.get('continuedl', False)])
  730. while retval == 2 or retval == 1:
  731. prevsize = os.path.getsize(tmpfilename)
  732. self.to_screen(u'\r[rtmpdump] %s bytes' % prevsize, skip_eol=True)
  733. time.sleep(5.0) # This seems to be needed
  734. retval = subprocess.call(basic_args + ['-e'] + [[], ['-k', '1']][retval == 1])
  735. cursize = os.path.getsize(tmpfilename)
  736. if prevsize == cursize and retval == 1:
  737. break
  738. # Some rtmp streams seem abort after ~ 99.8%. Don't complain for those
  739. if prevsize == cursize and retval == 2 and cursize > 1024:
  740. self.to_screen(u'\r[rtmpdump] Could not download the whole video. This can happen for some advertisements.')
  741. retval = 0
  742. break
  743. if retval == 0:
  744. self.to_screen(u'\r[rtmpdump] %s bytes' % os.path.getsize(tmpfilename))
  745. self.try_rename(tmpfilename, filename)
  746. return True
  747. else:
  748. self.trouble(u'\nERROR: rtmpdump exited with code %d' % retval)
  749. return False
  750. def _do_download(self, filename, info_dict):
  751. url = info_dict['url']
  752. player_url = info_dict.get('player_url', None)
  753. # Check file already present
  754. if self.params.get('continuedl', False) and os.path.isfile(filename) and not self.params.get('nopart', False):
  755. self.report_file_already_downloaded(filename)
  756. return True
  757. # Attempt to download using rtmpdump
  758. if url.startswith('rtmp'):
  759. return self._download_with_rtmpdump(filename, url, player_url)
  760. tmpfilename = self.temp_name(filename)
  761. stream = None
  762. # Do not include the Accept-Encoding header
  763. headers = {'Youtubedl-no-compression': 'True'}
  764. basic_request = urllib2.Request(url, None, headers)
  765. request = urllib2.Request(url, None, headers)
  766. # Establish possible resume length
  767. if os.path.isfile(tmpfilename):
  768. resume_len = os.path.getsize(tmpfilename)
  769. else:
  770. resume_len = 0
  771. open_mode = 'wb'
  772. if resume_len != 0:
  773. if self.params.get('continuedl', False):
  774. self.report_resuming_byte(resume_len)
  775. request.add_header('Range','bytes=%d-' % resume_len)
  776. open_mode = 'ab'
  777. else:
  778. resume_len = 0
  779. count = 0
  780. retries = self.params.get('retries', 0)
  781. while count <= retries:
  782. # Establish connection
  783. try:
  784. data = urllib2.urlopen(request)
  785. break
  786. except (urllib2.HTTPError, ), err:
  787. if (err.code < 500 or err.code >= 600) and err.code != 416:
  788. # Unexpected HTTP error
  789. raise
  790. elif err.code == 416:
  791. # Unable to resume (requested range not satisfiable)
  792. try:
  793. # Open the connection again without the range header
  794. data = urllib2.urlopen(basic_request)
  795. content_length = data.info()['Content-Length']
  796. except (urllib2.HTTPError, ), err:
  797. if err.code < 500 or err.code >= 600:
  798. raise
  799. else:
  800. # Examine the reported length
  801. if (content_length is not None and
  802. (resume_len - 100 < long(content_length) < resume_len + 100)):
  803. # The file had already been fully downloaded.
  804. # Explanation to the above condition: in issue #175 it was revealed that
  805. # YouTube sometimes adds or removes a few bytes from the end of the file,
  806. # changing the file size slightly and causing problems for some users. So
  807. # I decided to implement a suggested change and consider the file
  808. # completely downloaded if the file size differs less than 100 bytes from
  809. # the one in the hard drive.
  810. self.report_file_already_downloaded(filename)
  811. self.try_rename(tmpfilename, filename)
  812. return True
  813. else:
  814. # The length does not match, we start the download over
  815. self.report_unable_to_resume()
  816. open_mode = 'wb'
  817. break
  818. # Retry
  819. count += 1
  820. if count <= retries:
  821. self.report_retry(count, retries)
  822. if count > retries:
  823. self.trouble(u'ERROR: giving up after %s retries' % retries)
  824. return False
  825. data_len = data.info().get('Content-length', None)
  826. if data_len is not None:
  827. data_len = long(data_len) + resume_len
  828. data_len_str = self.format_bytes(data_len)
  829. byte_counter = 0 + resume_len
  830. block_size = 1024
  831. start = time.time()
  832. while True:
  833. # Download and write
  834. before = time.time()
  835. data_block = data.read(block_size)
  836. after = time.time()
  837. if len(data_block) == 0:
  838. break
  839. byte_counter += len(data_block)
  840. # Open file just in time
  841. if stream is None:
  842. try:
  843. (stream, tmpfilename) = sanitize_open(tmpfilename, open_mode)
  844. assert stream is not None
  845. filename = self.undo_temp_name(tmpfilename)
  846. self.report_destination(filename)
  847. except (OSError, IOError), err:
  848. self.trouble(u'ERROR: unable to open for writing: %s' % str(err))
  849. return False
  850. try:
  851. stream.write(data_block)
  852. except (IOError, OSError), err:
  853. self.trouble(u'\nERROR: unable to write data: %s' % str(err))
  854. return False
  855. block_size = self.best_block_size(after - before, len(data_block))
  856. # Progress message
  857. speed_str = self.calc_speed(start, time.time(), byte_counter - resume_len)
  858. if data_len is None:
  859. self.report_progress('Unknown %', data_len_str, speed_str, 'Unknown ETA')
  860. else:
  861. percent_str = self.calc_percent(byte_counter, data_len)
  862. eta_str = self.calc_eta(start, time.time(), data_len - resume_len, byte_counter - resume_len)
  863. self.report_progress(percent_str, data_len_str, speed_str, eta_str)
  864. # Apply rate limit
  865. self.slow_down(start, byte_counter - resume_len)
  866. if stream is None:
  867. self.trouble(u'\nERROR: Did not get any data blocks')
  868. return False
  869. stream.close()
  870. self.report_finish()
  871. if data_len is not None and byte_counter != data_len:
  872. raise ContentTooShortError(byte_counter, long(data_len))
  873. self.try_rename(tmpfilename, filename)
  874. # Update file modification time
  875. if self.params.get('updatetime', True):
  876. info_dict['filetime'] = self.try_utime(filename, data.info().get('last-modified', None))
  877. return True
  878. class InfoExtractor(object):
  879. """Information Extractor class.
  880. Information extractors are the classes that, given a URL, extract
  881. information from the video (or videos) the URL refers to. This
  882. information includes the real video URL, the video title and simplified
  883. title, author and others. The information is stored in a dictionary
  884. which is then passed to the FileDownloader. The FileDownloader
  885. processes this information possibly downloading the video to the file
  886. system, among other possible outcomes. The dictionaries must include
  887. the following fields:
  888. id: Video identifier.
  889. url: Final video URL.
  890. uploader: Nickname of the video uploader.
  891. title: Literal title.
  892. stitle: Simplified title.
  893. ext: Video filename extension.
  894. format: Video format.
  895. player_url: SWF Player URL (may be None).
  896. The following fields are optional. Their primary purpose is to allow
  897. youtube-dl to serve as the backend for a video search function, such
  898. as the one in youtube2mp3. They are only used when their respective
  899. forced printing functions are called:
  900. thumbnail: Full URL to a video thumbnail image.
  901. description: One-line video description.
  902. Subclasses of this one should re-define the _real_initialize() and
  903. _real_extract() methods and define a _VALID_URL regexp.
  904. Probably, they should also be added to the list of extractors.
  905. """
  906. _ready = False
  907. _downloader = None
  908. def __init__(self, downloader=None):
  909. """Constructor. Receives an optional downloader."""
  910. self._ready = False
  911. self.set_downloader(downloader)
  912. def suitable(self, url):
  913. """Receives a URL and returns True if suitable for this IE."""
  914. return re.match(self._VALID_URL, url) is not None
  915. def initialize(self):
  916. """Initializes an instance (authentication, etc)."""
  917. if not self._ready:
  918. self._real_initialize()
  919. self._ready = True
  920. def extract(self, url):
  921. """Extracts URL information and returns it in list of dicts."""
  922. self.initialize()
  923. return self._real_extract(url)
  924. def set_downloader(self, downloader):
  925. """Sets the downloader for this IE."""
  926. self._downloader = downloader
  927. def _real_initialize(self):
  928. """Real initialization process. Redefine in subclasses."""
  929. pass
  930. def _real_extract(self, url):
  931. """Real extraction process. Redefine in subclasses."""
  932. pass
  933. class YoutubeIE(InfoExtractor):
  934. """Information extractor for youtube.com."""
  935. _VALID_URL = r'^((?:https?://)?(?:youtu\.be/|(?:\w+\.)?youtube(?:-nocookie)?\.com/)(?:(?:(?:v|embed|e)/)|(?:(?:watch(?:_popup)?(?:\.php)?)?(?:\?|#!?)(?:.+&)?v=))?)?([0-9A-Za-z_-]+)(?(1).+)?$'
  936. _LANG_URL = r'http://www.youtube.com/?hl=en&persist_hl=1&gl=US&persist_gl=1&opt_out_ackd=1'
  937. _LOGIN_URL = 'https://www.youtube.com/signup?next=/&gl=US&hl=en'
  938. _AGE_URL = 'http://www.youtube.com/verify_age?next_url=/&gl=US&hl=en'
  939. _NETRC_MACHINE = 'youtube'
  940. # Listed in order of quality
  941. _available_formats = ['38', '37', '45', '22', '43', '35', '34', '18', '6', '5', '17', '13']
  942. _video_extensions = {
  943. '13': '3gp',
  944. '17': 'mp4',
  945. '18': 'mp4',
  946. '22': 'mp4',
  947. '37': 'mp4',
  948. '38': 'video', # You actually don't know if this will be MOV, AVI or whatever
  949. '43': 'webm',
  950. '45': 'webm',
  951. }
  952. IE_NAME = u'youtube'
  953. def report_lang(self):
  954. """Report attempt to set language."""
  955. self._downloader.to_screen(u'[youtube] Setting language')
  956. def report_login(self):
  957. """Report attempt to log in."""
  958. self._downloader.to_screen(u'[youtube] Logging in')
  959. def report_age_confirmation(self):
  960. """Report attempt to confirm age."""
  961. self._downloader.to_screen(u'[youtube] Confirming age')
  962. def report_video_webpage_download(self, video_id):
  963. """Report attempt to download video webpage."""
  964. self._downloader.to_screen(u'[youtube] %s: Downloading video webpage' % video_id)
  965. def report_video_info_webpage_download(self, video_id):
  966. """Report attempt to download video info webpage."""
  967. self._downloader.to_screen(u'[youtube] %s: Downloading video info webpage' % video_id)
  968. def report_information_extraction(self, video_id):
  969. """Report attempt to extract video information."""
  970. self._downloader.to_screen(u'[youtube] %s: Extracting video information' % video_id)
  971. def report_unavailable_format(self, video_id, format):
  972. """Report extracted video URL."""
  973. self._downloader.to_screen(u'[youtube] %s: Format %s not available' % (video_id, format))
  974. def report_rtmp_download(self):
  975. """Indicate the download will use the RTMP protocol."""
  976. self._downloader.to_screen(u'[youtube] RTMP download detected')
  977. def _real_initialize(self):
  978. if self._downloader is None:
  979. return
  980. username = None
  981. password = None
  982. downloader_params = self._downloader.params
  983. # Attempt to use provided username and password or .netrc data
  984. if downloader_params.get('username', None) is not None:
  985. username = downloader_params['username']
  986. password = downloader_params['password']
  987. elif downloader_params.get('usenetrc', False):
  988. try:
  989. info = netrc.netrc().authenticators(self._NETRC_MACHINE)
  990. if info is not None:
  991. username = info[0]
  992. password = info[2]
  993. else:
  994. raise netrc.NetrcParseError('No authenticators for %s' % self._NETRC_MACHINE)
  995. except (IOError, netrc.NetrcParseError), err:
  996. self._downloader.to_stderr(u'WARNING: parsing .netrc: %s' % str(err))
  997. return
  998. # Set language
  999. request = urllib2.Request(self._LANG_URL)
  1000. try:
  1001. self.report_lang()
  1002. urllib2.urlopen(request).read()
  1003. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1004. self._downloader.to_stderr(u'WARNING: unable to set language: %s' % str(err))
  1005. return
  1006. # No authentication to be performed
  1007. if username is None:
  1008. return
  1009. # Log in
  1010. login_form = {
  1011. 'current_form': 'loginForm',
  1012. 'next': '/',
  1013. 'action_login': 'Log In',
  1014. 'username': username,
  1015. 'password': password,
  1016. }
  1017. request = urllib2.Request(self._LOGIN_URL, urllib.urlencode(login_form))
  1018. try:
  1019. self.report_login()
  1020. login_results = urllib2.urlopen(request).read()
  1021. if re.search(r'(?i)<form[^>]* name="loginForm"', login_results) is not None:
  1022. self._downloader.to_stderr(u'WARNING: unable to log in: bad username or password')
  1023. return
  1024. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1025. self._downloader.to_stderr(u'WARNING: unable to log in: %s' % str(err))
  1026. return
  1027. # Confirm age
  1028. age_form = {
  1029. 'next_url': '/',
  1030. 'action_confirm': 'Confirm',
  1031. }
  1032. request = urllib2.Request(self._AGE_URL, urllib.urlencode(age_form))
  1033. try:
  1034. self.report_age_confirmation()
  1035. age_results = urllib2.urlopen(request).read()
  1036. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1037. self._downloader.trouble(u'ERROR: unable to confirm age: %s' % str(err))
  1038. return
  1039. def _real_extract(self, url):
  1040. # Extract video id from URL
  1041. mobj = re.match(self._VALID_URL, url)
  1042. if mobj is None:
  1043. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  1044. return
  1045. video_id = mobj.group(2)
  1046. # Get video webpage
  1047. self.report_video_webpage_download(video_id)
  1048. request = urllib2.Request('http://www.youtube.com/watch?v=%s&gl=US&hl=en&amp;has_verified=1' % video_id)
  1049. try:
  1050. video_webpage = urllib2.urlopen(request).read()
  1051. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1052. self._downloader.trouble(u'ERROR: unable to download video webpage: %s' % str(err))
  1053. return
  1054. # Attempt to extract SWF player URL
  1055. mobj = re.search(r'swfConfig.*?"(http:\\/\\/.*?watch.*?-.*?\.swf)"', video_webpage)
  1056. if mobj is not None:
  1057. player_url = re.sub(r'\\(.)', r'\1', mobj.group(1))
  1058. else:
  1059. player_url = None
  1060. # Get video info
  1061. self.report_video_info_webpage_download(video_id)
  1062. for el_type in ['&el=embedded', '&el=detailpage', '&el=vevo', '']:
  1063. video_info_url = ('http://www.youtube.com/get_video_info?&video_id=%s%s&ps=default&eurl=&gl=US&hl=en'
  1064. % (video_id, el_type))
  1065. request = urllib2.Request(video_info_url)
  1066. try:
  1067. video_info_webpage = urllib2.urlopen(request).read()
  1068. video_info = parse_qs(video_info_webpage)
  1069. if 'token' in video_info:
  1070. break
  1071. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1072. self._downloader.trouble(u'ERROR: unable to download video info webpage: %s' % str(err))
  1073. return
  1074. if 'token' not in video_info:
  1075. if 'reason' in video_info:
  1076. self._downloader.trouble(u'ERROR: YouTube said: %s' % video_info['reason'][0].decode('utf-8'))
  1077. else:
  1078. self._downloader.trouble(u'ERROR: "token" parameter not in video info for unknown reason')
  1079. return
  1080. # Start extracting information
  1081. self.report_information_extraction(video_id)
  1082. # uploader
  1083. if 'author' not in video_info:
  1084. self._downloader.trouble(u'ERROR: unable to extract uploader nickname')
  1085. return
  1086. video_uploader = urllib.unquote_plus(video_info['author'][0])
  1087. # title
  1088. if 'title' not in video_info:
  1089. self._downloader.trouble(u'ERROR: unable to extract video title')
  1090. return
  1091. video_title = urllib.unquote_plus(video_info['title'][0])
  1092. video_title = video_title.decode('utf-8')
  1093. video_title = sanitize_title(video_title)
  1094. # simplified title
  1095. simple_title = re.sub(ur'(?u)([^%s]+)' % simple_title_chars, ur'_', video_title)
  1096. simple_title = simple_title.strip(ur'_')
  1097. # thumbnail image
  1098. if 'thumbnail_url' not in video_info:
  1099. self._downloader.trouble(u'WARNING: unable to extract video thumbnail')
  1100. video_thumbnail = ''
  1101. else: # don't panic if we can't find it
  1102. video_thumbnail = urllib.unquote_plus(video_info['thumbnail_url'][0])
  1103. # upload date
  1104. upload_date = u'NA'
  1105. mobj = re.search(r'id="eow-date.*?>(.*?)</span>', video_webpage, re.DOTALL)
  1106. if mobj is not None:
  1107. upload_date = ' '.join(re.sub(r'[/,-]', r' ', mobj.group(1)).split())
  1108. format_expressions = ['%d %B %Y', '%B %d %Y', '%b %d %Y']
  1109. for expression in format_expressions:
  1110. try:
  1111. upload_date = datetime.datetime.strptime(upload_date, expression).strftime('%Y%m%d')
  1112. except:
  1113. pass
  1114. # description
  1115. try:
  1116. lxml.etree
  1117. except NameError:
  1118. video_description = u'No description available.'
  1119. if self._downloader.params.get('forcedescription', False) or self._downloader.params.get('writedescription', False):
  1120. mobj = re.search(r'<meta name="description" content="(.*)"(?:\s*/)?>', video_webpage)
  1121. if mobj is not None:
  1122. video_description = mobj.group(1).decode('utf-8')
  1123. else:
  1124. html_parser = lxml.etree.HTMLParser(encoding='utf-8')
  1125. vwebpage_doc = lxml.etree.parse(StringIO.StringIO(video_webpage), html_parser)
  1126. video_description = u''.join(vwebpage_doc.xpath('id("eow-description")//text()'))
  1127. # TODO use another parser
  1128. # token
  1129. video_token = urllib.unquote_plus(video_info['token'][0])
  1130. # Decide which formats to download
  1131. req_format = self._downloader.params.get('format', None)
  1132. if 'conn' in video_info and video_info['conn'][0].startswith('rtmp'):
  1133. self.report_rtmp_download()
  1134. video_url_list = [(None, video_info['conn'][0])]
  1135. elif 'url_encoded_fmt_stream_map' in video_info and len(video_info['url_encoded_fmt_stream_map']) >= 1:
  1136. url_data_strs = video_info['url_encoded_fmt_stream_map'][0].split(',')
  1137. url_data = [parse_qs(uds) for uds in url_data_strs]
  1138. url_data = filter(lambda ud: 'itag' in ud and 'url' in ud, url_data)
  1139. url_map = dict((ud['itag'][0], ud['url'][0]) for ud in url_data)
  1140. format_limit = self._downloader.params.get('format_limit', None)
  1141. if format_limit is not None and format_limit in self._available_formats:
  1142. format_list = self._available_formats[self._available_formats.index(format_limit):]
  1143. else:
  1144. format_list = self._available_formats
  1145. existing_formats = [x for x in format_list if x in url_map]
  1146. if len(existing_formats) == 0:
  1147. self._downloader.trouble(u'ERROR: no known formats available for video')
  1148. return
  1149. if req_format is None or req_format == 'best':
  1150. video_url_list = [(existing_formats[0], url_map[existing_formats[0]])] # Best quality
  1151. elif req_format == 'worst':
  1152. video_url_list = [(existing_formats[len(existing_formats)-1], url_map[existing_formats[len(existing_formats)-1]])] # worst quality
  1153. elif req_format in ('-1', 'all'):
  1154. video_url_list = [(f, url_map[f]) for f in existing_formats] # All formats
  1155. else:
  1156. # Specific formats. We pick the first in a slash-delimeted sequence.
  1157. # For example, if '1/2/3/4' is requested and '2' and '4' are available, we pick '2'.
  1158. req_formats = req_format.split('/')
  1159. video_url_list = None
  1160. for rf in req_formats:
  1161. if rf in url_map:
  1162. video_url_list = [(rf, url_map[rf])]
  1163. break
  1164. if video_url_list is None:
  1165. self._downloader.trouble(u'ERROR: requested format not available')
  1166. return
  1167. else:
  1168. self._downloader.trouble(u'ERROR: no conn or url_encoded_fmt_stream_map information found in video info')
  1169. return
  1170. for format_param, video_real_url in video_url_list:
  1171. # At this point we have a new video
  1172. self._downloader.increment_downloads()
  1173. # Extension
  1174. video_extension = self._video_extensions.get(format_param, 'flv')
  1175. try:
  1176. # Process video information
  1177. self._downloader.process_info({
  1178. 'id': video_id.decode('utf-8'),
  1179. 'url': video_real_url.decode('utf-8'),
  1180. 'uploader': video_uploader.decode('utf-8'),
  1181. 'upload_date': upload_date,
  1182. 'title': video_title,
  1183. 'stitle': simple_title,
  1184. 'ext': video_extension.decode('utf-8'),
  1185. 'format': (format_param is None and u'NA' or format_param.decode('utf-8')),
  1186. 'thumbnail': video_thumbnail.decode('utf-8'),
  1187. 'description': video_description,
  1188. 'player_url': player_url,
  1189. })
  1190. except UnavailableVideoError, err:
  1191. self._downloader.trouble(u'\nERROR: unable to download video')
  1192. class MetacafeIE(InfoExtractor):
  1193. """Information Extractor for metacafe.com."""
  1194. _VALID_URL = r'(?:http://)?(?:www\.)?metacafe\.com/watch/([^/]+)/([^/]+)/.*'
  1195. _DISCLAIMER = 'http://www.metacafe.com/family_filter/'
  1196. _FILTER_POST = 'http://www.metacafe.com/f/index.php?inputType=filter&controllerGroup=user'
  1197. _youtube_ie = None
  1198. IE_NAME = u'metacafe'
  1199. def __init__(self, youtube_ie, downloader=None):
  1200. InfoExtractor.__init__(self, downloader)
  1201. self._youtube_ie = youtube_ie
  1202. def report_disclaimer(self):
  1203. """Report disclaimer retrieval."""
  1204. self._downloader.to_screen(u'[metacafe] Retrieving disclaimer')
  1205. def report_age_confirmation(self):
  1206. """Report attempt to confirm age."""
  1207. self._downloader.to_screen(u'[metacafe] Confirming age')
  1208. def report_download_webpage(self, video_id):
  1209. """Report webpage download."""
  1210. self._downloader.to_screen(u'[metacafe] %s: Downloading webpage' % video_id)
  1211. def report_extraction(self, video_id):
  1212. """Report information extraction."""
  1213. self._downloader.to_screen(u'[metacafe] %s: Extracting information' % video_id)
  1214. def _real_initialize(self):
  1215. # Retrieve disclaimer
  1216. request = urllib2.Request(self._DISCLAIMER)
  1217. try:
  1218. self.report_disclaimer()
  1219. disclaimer = urllib2.urlopen(request).read()
  1220. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1221. self._downloader.trouble(u'ERROR: unable to retrieve disclaimer: %s' % str(err))
  1222. return
  1223. # Confirm age
  1224. disclaimer_form = {
  1225. 'filters': '0',
  1226. 'submit': "Continue - I'm over 18",
  1227. }
  1228. request = urllib2.Request(self._FILTER_POST, urllib.urlencode(disclaimer_form))
  1229. try:
  1230. self.report_age_confirmation()
  1231. disclaimer = urllib2.urlopen(request).read()
  1232. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1233. self._downloader.trouble(u'ERROR: unable to confirm age: %s' % str(err))
  1234. return
  1235. def _real_extract(self, url):
  1236. # Extract id and simplified title from URL
  1237. mobj = re.match(self._VALID_URL, url)
  1238. if mobj is None:
  1239. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  1240. return
  1241. video_id = mobj.group(1)
  1242. # Check if video comes from YouTube
  1243. mobj2 = re.match(r'^yt-(.*)$', video_id)
  1244. if mobj2 is not None:
  1245. self._youtube_ie.extract('http://www.youtube.com/watch?v=%s' % mobj2.group(1))
  1246. return
  1247. # At this point we have a new video
  1248. self._downloader.increment_downloads()
  1249. simple_title = mobj.group(2).decode('utf-8')
  1250. # Retrieve video webpage to extract further information
  1251. request = urllib2.Request('http://www.metacafe.com/watch/%s/' % video_id)
  1252. try:
  1253. self.report_download_webpage(video_id)
  1254. webpage = urllib2.urlopen(request).read()
  1255. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1256. self._downloader.trouble(u'ERROR: unable retrieve video webpage: %s' % str(err))
  1257. return
  1258. # Extract URL, uploader and title from webpage
  1259. self.report_extraction(video_id)
  1260. mobj = re.search(r'(?m)&mediaURL=([^&]+)', webpage)
  1261. if mobj is not None:
  1262. mediaURL = urllib.unquote(mobj.group(1))
  1263. video_extension = mediaURL[-3:]
  1264. # Extract gdaKey if available
  1265. mobj = re.search(r'(?m)&gdaKey=(.*?)&', webpage)
  1266. if mobj is None:
  1267. video_url = mediaURL
  1268. else:
  1269. gdaKey = mobj.group(1)
  1270. video_url = '%s?__gda__=%s' % (mediaURL, gdaKey)
  1271. else:
  1272. mobj = re.search(r' name="flashvars" value="(.*?)"', webpage)
  1273. if mobj is None:
  1274. self._downloader.trouble(u'ERROR: unable to extract media URL')
  1275. return
  1276. vardict = parse_qs(mobj.group(1))
  1277. if 'mediaData' not in vardict:
  1278. self._downloader.trouble(u'ERROR: unable to extract media URL')
  1279. return
  1280. mobj = re.search(r'"mediaURL":"(http.*?)","key":"(.*?)"', vardict['mediaData'][0])
  1281. if mobj is None:
  1282. self._downloader.trouble(u'ERROR: unable to extract media URL')
  1283. return
  1284. mediaURL = mobj.group(1).replace('\\/', '/')
  1285. video_extension = mediaURL[-3:]
  1286. video_url = '%s?__gda__=%s' % (mediaURL, mobj.group(2))
  1287. mobj = re.search(r'(?im)<title>(.*) - Video</title>', webpage)
  1288. if mobj is None:
  1289. self._downloader.trouble(u'ERROR: unable to extract title')
  1290. return
  1291. video_title = mobj.group(1).decode('utf-8')
  1292. video_title = sanitize_title(video_title)
  1293. mobj = re.search(r'(?ms)By:\s*<a .*?>(.+?)<', webpage)
  1294. if mobj is None:
  1295. self._downloader.trouble(u'ERROR: unable to extract uploader nickname')
  1296. return
  1297. video_uploader = mobj.group(1)
  1298. try:
  1299. # Process video information
  1300. self._downloader.process_info({
  1301. 'id': video_id.decode('utf-8'),
  1302. 'url': video_url.decode('utf-8'),
  1303. 'uploader': video_uploader.decode('utf-8'),
  1304. 'upload_date': u'NA',
  1305. 'title': video_title,
  1306. 'stitle': simple_title,
  1307. 'ext': video_extension.decode('utf-8'),
  1308. 'format': u'NA',
  1309. 'player_url': None,
  1310. })
  1311. except UnavailableVideoError:
  1312. self._downloader.trouble(u'\nERROR: unable to download video')
  1313. class DailymotionIE(InfoExtractor):
  1314. """Information Extractor for Dailymotion"""
  1315. _VALID_URL = r'(?i)(?:https?://)?(?:www\.)?dailymotion\.[a-z]{2,3}/video/([^_/]+)_([^/]+)'
  1316. IE_NAME = u'dailymotion'
  1317. def __init__(self, downloader=None):
  1318. InfoExtractor.__init__(self, downloader)
  1319. def report_download_webpage(self, video_id):
  1320. """Report webpage download."""
  1321. self._downloader.to_screen(u'[dailymotion] %s: Downloading webpage' % video_id)
  1322. def report_extraction(self, video_id):
  1323. """Report information extraction."""
  1324. self._downloader.to_screen(u'[dailymotion] %s: Extracting information' % video_id)
  1325. def _real_initialize(self):
  1326. return
  1327. def _real_extract(self, url):
  1328. # Extract id and simplified title from URL
  1329. mobj = re.match(self._VALID_URL, url)
  1330. if mobj is None:
  1331. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  1332. return
  1333. # At this point we have a new video
  1334. self._downloader.increment_downloads()
  1335. video_id = mobj.group(1)
  1336. simple_title = mobj.group(2).decode('utf-8')
  1337. video_extension = 'flv'
  1338. # Retrieve video webpage to extract further information
  1339. request = urllib2.Request(url)
  1340. request.add_header('Cookie', 'family_filter=off')
  1341. try:
  1342. self.report_download_webpage(video_id)
  1343. webpage = urllib2.urlopen(request).read()
  1344. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1345. self._downloader.trouble(u'ERROR: unable retrieve video webpage: %s' % str(err))
  1346. return
  1347. # Extract URL, uploader and title from webpage
  1348. self.report_extraction(video_id)
  1349. mobj = re.search(r'(?i)addVariable\(\"sequence\"\s*,\s*\"([^\"]+?)\"\)', webpage)
  1350. if mobj is None:
  1351. self._downloader.trouble(u'ERROR: unable to extract media URL')
  1352. return
  1353. sequence = urllib.unquote(mobj.group(1))
  1354. mobj = re.search(r',\"sdURL\"\:\"([^\"]+?)\",', sequence)
  1355. if mobj is None:
  1356. self._downloader.trouble(u'ERROR: unable to extract media URL')
  1357. return
  1358. mediaURL = urllib.unquote(mobj.group(1)).replace('\\', '')
  1359. # if needed add http://www.dailymotion.com/ if relative URL
  1360. video_url = mediaURL
  1361. mobj = re.search(r'(?im)<title>Dailymotion\s*-\s*(.+)\s*-\s*[^<]+?</title>', webpage)
  1362. if mobj is None:
  1363. self._downloader.trouble(u'ERROR: unable to extract title')
  1364. return
  1365. video_title = mobj.group(1).decode('utf-8')
  1366. video_title = sanitize_title(video_title)
  1367. mobj = re.search(r'(?im)<span class="owner[^\"]+?">[^<]+?<a [^>]+?>([^<]+?)</a></span>', webpage)
  1368. if mobj is None:
  1369. self._downloader.trouble(u'ERROR: unable to extract uploader nickname')
  1370. return
  1371. video_uploader = mobj.group(1)
  1372. try:
  1373. # Process video information
  1374. self._downloader.process_info({
  1375. 'id': video_id.decode('utf-8'),
  1376. 'url': video_url.decode('utf-8'),
  1377. 'uploader': video_uploader.decode('utf-8'),
  1378. 'upload_date': u'NA',
  1379. 'title': video_title,
  1380. 'stitle': simple_title,
  1381. 'ext': video_extension.decode('utf-8'),
  1382. 'format': u'NA',
  1383. 'player_url': None,
  1384. })
  1385. except UnavailableVideoError:
  1386. self._downloader.trouble(u'\nERROR: unable to download video')
  1387. class GoogleIE(InfoExtractor):
  1388. """Information extractor for video.google.com."""
  1389. _VALID_URL = r'(?:http://)?video\.google\.(?:com(?:\.au)?|co\.(?:uk|jp|kr|cr)|ca|de|es|fr|it|nl|pl)/videoplay\?docid=([^\&]+).*'
  1390. IE_NAME = u'video.google'
  1391. def __init__(self, downloader=None):
  1392. InfoExtractor.__init__(self, downloader)
  1393. def report_download_webpage(self, video_id):
  1394. """Report webpage download."""
  1395. self._downloader.to_screen(u'[video.google] %s: Downloading webpage' % video_id)
  1396. def report_extraction(self, video_id):
  1397. """Report information extraction."""
  1398. self._downloader.to_screen(u'[video.google] %s: Extracting information' % video_id)
  1399. def _real_initialize(self):
  1400. return
  1401. def _real_extract(self, url):
  1402. # Extract id from URL
  1403. mobj = re.match(self._VALID_URL, url)
  1404. if mobj is None:
  1405. self._downloader.trouble(u'ERROR: Invalid URL: %s' % url)
  1406. return
  1407. # At this point we have a new video
  1408. self._downloader.increment_downloads()
  1409. video_id = mobj.group(1)
  1410. video_extension = 'mp4'
  1411. # Retrieve video webpage to extract further information
  1412. request = urllib2.Request('http://video.google.com/videoplay?docid=%s&hl=en&oe=utf-8' % video_id)
  1413. try:
  1414. self.report_download_webpage(video_id)
  1415. webpage = urllib2.urlopen(request).read()
  1416. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1417. self._downloader.trouble(u'ERROR: Unable to retrieve video webpage: %s' % str(err))
  1418. return
  1419. # Extract URL, uploader, and title from webpage
  1420. self.report_extraction(video_id)
  1421. mobj = re.search(r"download_url:'([^']+)'", webpage)
  1422. if mobj is None:
  1423. video_extension = 'flv'
  1424. mobj = re.search(r"(?i)videoUrl\\x3d(.+?)\\x26", webpage)
  1425. if mobj is None:
  1426. self._downloader.trouble(u'ERROR: unable to extract media URL')
  1427. return
  1428. mediaURL = urllib.unquote(mobj.group(1))
  1429. mediaURL = mediaURL.replace('\\x3d', '\x3d')
  1430. mediaURL = mediaURL.replace('\\x26', '\x26')
  1431. video_url = mediaURL
  1432. mobj = re.search(r'<title>(.*)</title>', webpage)
  1433. if mobj is None:
  1434. self._downloader.trouble(u'ERROR: unable to extract title')
  1435. return
  1436. video_title = mobj.group(1).decode('utf-8')
  1437. video_title = sanitize_title(video_title)
  1438. simple_title = re.sub(ur'(?u)([^%s]+)' % simple_title_chars, ur'_', video_title)
  1439. # Extract video description
  1440. mobj = re.search(r'<span id=short-desc-content>([^<]*)</span>', webpage)
  1441. if mobj is None:
  1442. self._downloader.trouble(u'ERROR: unable to extract video description')
  1443. return
  1444. video_description = mobj.group(1).decode('utf-8')
  1445. if not video_description:
  1446. video_description = 'No description available.'
  1447. # Extract video thumbnail
  1448. if self._downloader.params.get('forcethumbnail', False):
  1449. request = urllib2.Request('http://video.google.com/videosearch?q=%s+site:video.google.com&hl=en' % abs(int(video_id)))
  1450. try:
  1451. webpage = urllib2.urlopen(request).read()
  1452. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1453. self._downloader.trouble(u'ERROR: Unable to retrieve video webpage: %s' % str(err))
  1454. return
  1455. mobj = re.search(r'<img class=thumbnail-img (?:.* )?src=(http.*)>', webpage)
  1456. if mobj is None:
  1457. self._downloader.trouble(u'ERROR: unable to extract video thumbnail')
  1458. return
  1459. video_thumbnail = mobj.group(1)
  1460. else: # we need something to pass to process_info
  1461. video_thumbnail = ''
  1462. try:
  1463. # Process video information
  1464. self._downloader.process_info({
  1465. 'id': video_id.decode('utf-8'),
  1466. 'url': video_url.decode('utf-8'),
  1467. 'uploader': u'NA',
  1468. 'upload_date': u'NA',
  1469. 'title': video_title,
  1470. 'stitle': simple_title,
  1471. 'ext': video_extension.decode('utf-8'),
  1472. 'format': u'NA',
  1473. 'player_url': None,
  1474. })
  1475. except UnavailableVideoError:
  1476. self._downloader.trouble(u'\nERROR: unable to download video')
  1477. class PhotobucketIE(InfoExtractor):
  1478. """Information extractor for photobucket.com."""
  1479. _VALID_URL = r'(?:http://)?(?:[a-z0-9]+\.)?photobucket\.com/.*[\?\&]current=(.*\.flv)'
  1480. IE_NAME = u'photobucket'
  1481. def __init__(self, downloader=None):
  1482. InfoExtractor.__init__(self, downloader)
  1483. def report_download_webpage(self, video_id):
  1484. """Report webpage download."""
  1485. self._downloader.to_screen(u'[photobucket] %s: Downloading webpage' % video_id)
  1486. def report_extraction(self, video_id):
  1487. """Report information extraction."""
  1488. self._downloader.to_screen(u'[photobucket] %s: Extracting information' % video_id)
  1489. def _real_initialize(self):
  1490. return
  1491. def _real_extract(self, url):
  1492. # Extract id from URL
  1493. mobj = re.match(self._VALID_URL, url)
  1494. if mobj is None:
  1495. self._downloader.trouble(u'ERROR: Invalid URL: %s' % url)
  1496. return
  1497. # At this point we have a new video
  1498. self._downloader.increment_downloads()
  1499. video_id = mobj.group(1)
  1500. video_extension = 'flv'
  1501. # Retrieve video webpage to extract further information
  1502. request = urllib2.Request(url)
  1503. try:
  1504. self.report_download_webpage(video_id)
  1505. webpage = urllib2.urlopen(request).read()
  1506. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1507. self._downloader.trouble(u'ERROR: Unable to retrieve video webpage: %s' % str(err))
  1508. return
  1509. # Extract URL, uploader, and title from webpage
  1510. self.report_extraction(video_id)
  1511. mobj = re.search(r'<link rel="video_src" href=".*\?file=([^"]+)" />', webpage)
  1512. if mobj is None:
  1513. self._downloader.trouble(u'ERROR: unable to extract media URL')
  1514. return
  1515. mediaURL = urllib.unquote(mobj.group(1))
  1516. video_url = mediaURL
  1517. mobj = re.search(r'<title>(.*) video by (.*) - Photobucket</title>', webpage)
  1518. if mobj is None:
  1519. self._downloader.trouble(u'ERROR: unable to extract title')
  1520. return
  1521. video_title = mobj.group(1).decode('utf-8')
  1522. video_title = sanitize_title(video_title)
  1523. simple_title = re.sub(ur'(?u)([^%s]+)' % simple_title_chars, ur'_', video_title)
  1524. video_uploader = mobj.group(2).decode('utf-8')
  1525. try:
  1526. # Process video information
  1527. self._downloader.process_info({
  1528. 'id': video_id.decode('utf-8'),
  1529. 'url': video_url.decode('utf-8'),
  1530. 'uploader': video_uploader,
  1531. 'upload_date': u'NA',
  1532. 'title': video_title,
  1533. 'stitle': simple_title,
  1534. 'ext': video_extension.decode('utf-8'),
  1535. 'format': u'NA',
  1536. 'player_url': None,
  1537. })
  1538. except UnavailableVideoError:
  1539. self._downloader.trouble(u'\nERROR: unable to download video')
  1540. class YahooIE(InfoExtractor):
  1541. """Information extractor for video.yahoo.com."""
  1542. # _VALID_URL matches all Yahoo! Video URLs
  1543. # _VPAGE_URL matches only the extractable '/watch/' URLs
  1544. _VALID_URL = r'(?:http://)?(?:[a-z]+\.)?video\.yahoo\.com/(?:watch|network)/([0-9]+)(?:/|\?v=)([0-9]+)(?:[#\?].*)?'
  1545. _VPAGE_URL = r'(?:http://)?video\.yahoo\.com/watch/([0-9]+)/([0-9]+)(?:[#\?].*)?'
  1546. IE_NAME = u'video.yahoo'
  1547. def __init__(self, downloader=None):
  1548. InfoExtractor.__init__(self, downloader)
  1549. def report_download_webpage(self, video_id):
  1550. """Report webpage download."""
  1551. self._downloader.to_screen(u'[video.yahoo] %s: Downloading webpage' % video_id)
  1552. def report_extraction(self, video_id):
  1553. """Report information extraction."""
  1554. self._downloader.to_screen(u'[video.yahoo] %s: Extracting information' % video_id)
  1555. def _real_initialize(self):
  1556. return
  1557. def _real_extract(self, url, new_video=True):
  1558. # Extract ID from URL
  1559. mobj = re.match(self._VALID_URL, url)
  1560. if mobj is None:
  1561. self._downloader.trouble(u'ERROR: Invalid URL: %s' % url)
  1562. return
  1563. # At this point we have a new video
  1564. self._downloader.increment_downloads()
  1565. video_id = mobj.group(2)
  1566. video_extension = 'flv'
  1567. # Rewrite valid but non-extractable URLs as
  1568. # extractable English language /watch/ URLs
  1569. if re.match(self._VPAGE_URL, url) is None:
  1570. request = urllib2.Request(url)
  1571. try:
  1572. webpage = urllib2.urlopen(request).read()
  1573. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1574. self._downloader.trouble(u'ERROR: Unable to retrieve video webpage: %s' % str(err))
  1575. return
  1576. mobj = re.search(r'\("id", "([0-9]+)"\);', webpage)
  1577. if mobj is None:
  1578. self._downloader.trouble(u'ERROR: Unable to extract id field')
  1579. return
  1580. yahoo_id = mobj.group(1)
  1581. mobj = re.search(r'\("vid", "([0-9]+)"\);', webpage)
  1582. if mobj is None:
  1583. self._downloader.trouble(u'ERROR: Unable to extract vid field')
  1584. return
  1585. yahoo_vid = mobj.group(1)
  1586. url = 'http://video.yahoo.com/watch/%s/%s' % (yahoo_vid, yahoo_id)
  1587. return self._real_extract(url, new_video=False)
  1588. # Retrieve video webpage to extract further information
  1589. request = urllib2.Request(url)
  1590. try:
  1591. self.report_download_webpage(video_id)
  1592. webpage = urllib2.urlopen(request).read()
  1593. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1594. self._downloader.trouble(u'ERROR: Unable to retrieve video webpage: %s' % str(err))
  1595. return
  1596. # Extract uploader and title from webpage
  1597. self.report_extraction(video_id)
  1598. mobj = re.search(r'<meta name="title" content="(.*)" />', webpage)
  1599. if mobj is None:
  1600. self._downloader.trouble(u'ERROR: unable to extract video title')
  1601. return
  1602. video_title = mobj.group(1).decode('utf-8')
  1603. simple_title = re.sub(ur'(?u)([^%s]+)' % simple_title_chars, ur'_', video_title)
  1604. mobj = re.search(r'<h2 class="ti-5"><a href="http://video\.yahoo\.com/(people|profile)/[0-9]+" beacon=".*">(.*)</a></h2>', webpage)
  1605. if mobj is None:
  1606. self._downloader.trouble(u'ERROR: unable to extract video uploader')
  1607. return
  1608. video_uploader = mobj.group(1).decode('utf-8')
  1609. # Extract video thumbnail
  1610. mobj = re.search(r'<link rel="image_src" href="(.*)" />', webpage)
  1611. if mobj is None:
  1612. self._downloader.trouble(u'ERROR: unable to extract video thumbnail')
  1613. return
  1614. video_thumbnail = mobj.group(1).decode('utf-8')
  1615. # Extract video description
  1616. mobj = re.search(r'<meta name="description" content="(.*)" />', webpage)
  1617. if mobj is None:
  1618. self._downloader.trouble(u'ERROR: unable to extract video description')
  1619. return
  1620. video_description = mobj.group(1).decode('utf-8')
  1621. if not video_description:
  1622. video_description = 'No description available.'
  1623. # Extract video height and width
  1624. mobj = re.search(r'<meta name="video_height" content="([0-9]+)" />', webpage)
  1625. if mobj is None:
  1626. self._downloader.trouble(u'ERROR: unable to extract video height')
  1627. return
  1628. yv_video_height = mobj.group(1)
  1629. mobj = re.search(r'<meta name="video_width" content="([0-9]+)" />', webpage)
  1630. if mobj is None:
  1631. self._downloader.trouble(u'ERROR: unable to extract video width')
  1632. return
  1633. yv_video_width = mobj.group(1)
  1634. # Retrieve video playlist to extract media URL
  1635. # I'm not completely sure what all these options are, but we
  1636. # seem to need most of them, otherwise the server sends a 401.
  1637. yv_lg = 'R0xx6idZnW2zlrKP8xxAIR' # not sure what this represents
  1638. yv_bitrate = '700' # according to Wikipedia this is hard-coded
  1639. request = urllib2.Request('http://cosmos.bcst.yahoo.com/up/yep/process/getPlaylistFOP.php?node_id=' + video_id +
  1640. '&tech=flash&mode=playlist&lg=' + yv_lg + '&bitrate=' + yv_bitrate + '&vidH=' + yv_video_height +
  1641. '&vidW=' + yv_video_width + '&swf=as3&rd=video.yahoo.com&tk=null&adsupported=v1,v2,&eventid=1301797')
  1642. try:
  1643. self.report_download_webpage(video_id)
  1644. webpage = urllib2.urlopen(request).read()
  1645. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1646. self._downloader.trouble(u'ERROR: Unable to retrieve video webpage: %s' % str(err))
  1647. return
  1648. # Extract media URL from playlist XML
  1649. mobj = re.search(r'<STREAM APP="(http://.*)" FULLPATH="/?(/.*\.flv\?[^"]*)"', webpage)
  1650. if mobj is None:
  1651. self._downloader.trouble(u'ERROR: Unable to extract media URL')
  1652. return
  1653. video_url = urllib.unquote(mobj.group(1) + mobj.group(2)).decode('utf-8')
  1654. video_url = re.sub(r'(?u)&(.+?);', htmlentity_transform, video_url)
  1655. try:
  1656. # Process video information
  1657. self._downloader.process_info({
  1658. 'id': video_id.decode('utf-8'),
  1659. 'url': video_url,
  1660. 'uploader': video_uploader,
  1661. 'upload_date': u'NA',
  1662. 'title': video_title,
  1663. 'stitle': simple_title,
  1664. 'ext': video_extension.decode('utf-8'),
  1665. 'thumbnail': video_thumbnail.decode('utf-8'),
  1666. 'description': video_description,
  1667. 'thumbnail': video_thumbnail,
  1668. 'player_url': None,
  1669. })
  1670. except UnavailableVideoError:
  1671. self._downloader.trouble(u'\nERROR: unable to download video')
  1672. class VimeoIE(InfoExtractor):
  1673. """Information extractor for vimeo.com."""
  1674. # _VALID_URL matches Vimeo URLs
  1675. _VALID_URL = r'(?:https?://)?(?:(?:www|player).)?vimeo\.com/(?:groups/[^/]+/)?(?:videos?/)?([0-9]+)'
  1676. IE_NAME = u'vimeo'
  1677. def __init__(self, downloader=None):
  1678. InfoExtractor.__init__(self, downloader)
  1679. def report_download_webpage(self, video_id):
  1680. """Report webpage download."""
  1681. self._downloader.to_screen(u'[vimeo] %s: Downloading webpage' % video_id)
  1682. def report_extraction(self, video_id):
  1683. """Report information extraction."""
  1684. self._downloader.to_screen(u'[vimeo] %s: Extracting information' % video_id)
  1685. def _real_initialize(self):
  1686. return
  1687. def _real_extract(self, url, new_video=True):
  1688. # Extract ID from URL
  1689. mobj = re.match(self._VALID_URL, url)
  1690. if mobj is None:
  1691. self._downloader.trouble(u'ERROR: Invalid URL: %s' % url)
  1692. return
  1693. # At this point we have a new video
  1694. self._downloader.increment_downloads()
  1695. video_id = mobj.group(1)
  1696. # Retrieve video webpage to extract further information
  1697. request = urllib2.Request("http://vimeo.com/moogaloop/load/clip:%s" % video_id, None, std_headers)
  1698. try:
  1699. self.report_download_webpage(video_id)
  1700. webpage = urllib2.urlopen(request).read()
  1701. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1702. self._downloader.trouble(u'ERROR: Unable to retrieve video webpage: %s' % str(err))
  1703. return
  1704. # Now we begin extracting as much information as we can from what we
  1705. # retrieved. First we extract the information common to all extractors,
  1706. # and latter we extract those that are Vimeo specific.
  1707. self.report_extraction(video_id)
  1708. # Extract title
  1709. mobj = re.search(r'<caption>(.*?)</caption>', webpage)
  1710. if mobj is None:
  1711. self._downloader.trouble(u'ERROR: unable to extract video title')
  1712. return
  1713. video_title = mobj.group(1).decode('utf-8')
  1714. simple_title = re.sub(ur'(?u)([^%s]+)' % simple_title_chars, ur'_', video_title)
  1715. # Extract uploader
  1716. mobj = re.search(r'<uploader_url>http://vimeo.com/(.*?)</uploader_url>', webpage)
  1717. if mobj is None:
  1718. self._downloader.trouble(u'ERROR: unable to extract video uploader')
  1719. return
  1720. video_uploader = mobj.group(1).decode('utf-8')
  1721. # Extract video thumbnail
  1722. mobj = re.search(r'<thumbnail>(.*?)</thumbnail>', webpage)
  1723. if mobj is None:
  1724. self._downloader.trouble(u'ERROR: unable to extract video thumbnail')
  1725. return
  1726. video_thumbnail = mobj.group(1).decode('utf-8')
  1727. # # Extract video description
  1728. # mobj = re.search(r'<meta property="og:description" content="(.*)" />', webpage)
  1729. # if mobj is None:
  1730. # self._downloader.trouble(u'ERROR: unable to extract video description')
  1731. # return
  1732. # video_description = mobj.group(1).decode('utf-8')
  1733. # if not video_description: video_description = 'No description available.'
  1734. video_description = 'Foo.'
  1735. # Vimeo specific: extract request signature
  1736. mobj = re.search(r'<request_signature>(.*?)</request_signature>', webpage)
  1737. if mobj is None:
  1738. self._downloader.trouble(u'ERROR: unable to extract request signature')
  1739. return
  1740. sig = mobj.group(1).decode('utf-8')
  1741. # Vimeo specific: Extract request signature expiration
  1742. mobj = re.search(r'<request_signature_expires>(.*?)</request_signature_expires>', webpage)
  1743. if mobj is None:
  1744. self._downloader.trouble(u'ERROR: unable to extract request signature expiration')
  1745. return
  1746. sig_exp = mobj.group(1).decode('utf-8')
  1747. video_url = "http://vimeo.com/moogaloop/play/clip:%s/%s/%s" % (video_id, sig, sig_exp)
  1748. try:
  1749. # Process video information
  1750. self._downloader.process_info({
  1751. 'id': video_id.decode('utf-8'),
  1752. 'url': video_url,
  1753. 'uploader': video_uploader,
  1754. 'upload_date': u'NA',
  1755. 'title': video_title,
  1756. 'stitle': simple_title,
  1757. 'ext': u'mp4',
  1758. 'thumbnail': video_thumbnail.decode('utf-8'),
  1759. 'description': video_description,
  1760. 'thumbnail': video_thumbnail,
  1761. 'description': video_description,
  1762. 'player_url': None,
  1763. })
  1764. except UnavailableVideoError:
  1765. self._downloader.trouble(u'ERROR: unable to download video')
  1766. class GenericIE(InfoExtractor):
  1767. """Generic last-resort information extractor."""
  1768. _VALID_URL = r'.*'
  1769. IE_NAME = u'generic'
  1770. def __init__(self, downloader=None):
  1771. InfoExtractor.__init__(self, downloader)
  1772. def report_download_webpage(self, video_id):
  1773. """Report webpage download."""
  1774. self._downloader.to_screen(u'WARNING: Falling back on generic information extractor.')
  1775. self._downloader.to_screen(u'[generic] %s: Downloading webpage' % video_id)
  1776. def report_extraction(self, video_id):
  1777. """Report information extraction."""
  1778. self._downloader.to_screen(u'[generic] %s: Extracting information' % video_id)
  1779. def _real_initialize(self):
  1780. return
  1781. def _real_extract(self, url):
  1782. # At this point we have a new video
  1783. self._downloader.increment_downloads()
  1784. video_id = url.split('/')[-1]
  1785. request = urllib2.Request(url)
  1786. try:
  1787. self.report_download_webpage(video_id)
  1788. webpage = urllib2.urlopen(request).read()
  1789. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1790. self._downloader.trouble(u'ERROR: Unable to retrieve video webpage: %s' % str(err))
  1791. return
  1792. except ValueError, err:
  1793. # since this is the last-resort InfoExtractor, if
  1794. # this error is thrown, it'll be thrown here
  1795. self._downloader.trouble(u'ERROR: Invalid URL: %s' % url)
  1796. return
  1797. self.report_extraction(video_id)
  1798. # Start with something easy: JW Player in SWFObject
  1799. mobj = re.search(r'flashvars: [\'"](?:.*&)?file=(http[^\'"&]*)', webpage)
  1800. if mobj is None:
  1801. # Broaden the search a little bit
  1802. mobj = re.search(r'[^A-Za-z0-9]?(?:file|source)=(http[^\'"&]*)', webpage)
  1803. if mobj is None:
  1804. self._downloader.trouble(u'ERROR: Invalid URL: %s' % url)
  1805. return
  1806. # It's possible that one of the regexes
  1807. # matched, but returned an empty group:
  1808. if mobj.group(1) is None:
  1809. self._downloader.trouble(u'ERROR: Invalid URL: %s' % url)
  1810. return
  1811. video_url = urllib.unquote(mobj.group(1))
  1812. video_id = os.path.basename(video_url)
  1813. # here's a fun little line of code for you:
  1814. video_extension = os.path.splitext(video_id)[1][1:]
  1815. video_id = os.path.splitext(video_id)[0]
  1816. # it's tempting to parse this further, but you would
  1817. # have to take into account all the variations like
  1818. # Video Title - Site Name
  1819. # Site Name | Video Title
  1820. # Video Title - Tagline | Site Name
  1821. # and so on and so forth; it's just not practical
  1822. mobj = re.search(r'<title>(.*)</title>', webpage)
  1823. if mobj is None:
  1824. self._downloader.trouble(u'ERROR: unable to extract title')
  1825. return
  1826. video_title = mobj.group(1).decode('utf-8')
  1827. video_title = sanitize_title(video_title)
  1828. simple_title = re.sub(ur'(?u)([^%s]+)' % simple_title_chars, ur'_', video_title)
  1829. # video uploader is domain name
  1830. mobj = re.match(r'(?:https?://)?([^/]*)/.*', url)
  1831. if mobj is None:
  1832. self._downloader.trouble(u'ERROR: unable to extract title')
  1833. return
  1834. video_uploader = mobj.group(1).decode('utf-8')
  1835. try:
  1836. # Process video information
  1837. self._downloader.process_info({
  1838. 'id': video_id.decode('utf-8'),
  1839. 'url': video_url.decode('utf-8'),
  1840. 'uploader': video_uploader,
  1841. 'upload_date': u'NA',
  1842. 'title': video_title,
  1843. 'stitle': simple_title,
  1844. 'ext': video_extension.decode('utf-8'),
  1845. 'format': u'NA',
  1846. 'player_url': None,
  1847. })
  1848. except UnavailableVideoError, err:
  1849. self._downloader.trouble(u'\nERROR: unable to download video')
  1850. class YoutubeSearchIE(InfoExtractor):
  1851. """Information Extractor for YouTube search queries."""
  1852. _VALID_URL = r'ytsearch(\d+|all)?:[\s\S]+'
  1853. _TEMPLATE_URL = 'http://www.youtube.com/results?search_query=%s&page=%s&gl=US&hl=en'
  1854. _VIDEO_INDICATOR = r'href="/watch\?v=.+?"'
  1855. _MORE_PAGES_INDICATOR = r'(?m)>\s*Next\s*</a>'
  1856. _youtube_ie = None
  1857. _max_youtube_results = 1000
  1858. IE_NAME = u'youtube:search'
  1859. def __init__(self, youtube_ie, downloader=None):
  1860. InfoExtractor.__init__(self, downloader)
  1861. self._youtube_ie = youtube_ie
  1862. def report_download_page(self, query, pagenum):
  1863. """Report attempt to download playlist page with given number."""
  1864. query = query.decode(preferredencoding())
  1865. self._downloader.to_screen(u'[youtube] query "%s": Downloading page %s' % (query, pagenum))
  1866. def _real_initialize(self):
  1867. self._youtube_ie.initialize()
  1868. def _real_extract(self, query):
  1869. mobj = re.match(self._VALID_URL, query)
  1870. if mobj is None:
  1871. self._downloader.trouble(u'ERROR: invalid search query "%s"' % query)
  1872. return
  1873. prefix, query = query.split(':')
  1874. prefix = prefix[8:]
  1875. query = query.encode('utf-8')
  1876. if prefix == '':
  1877. self._download_n_results(query, 1)
  1878. return
  1879. elif prefix == 'all':
  1880. self._download_n_results(query, self._max_youtube_results)
  1881. return
  1882. else:
  1883. try:
  1884. n = long(prefix)
  1885. if n <= 0:
  1886. self._downloader.trouble(u'ERROR: invalid download number %s for query "%s"' % (n, query))
  1887. return
  1888. elif n > self._max_youtube_results:
  1889. self._downloader.to_stderr(u'WARNING: ytsearch returns max %i results (you requested %i)' % (self._max_youtube_results, n))
  1890. n = self._max_youtube_results
  1891. self._download_n_results(query, n)
  1892. return
  1893. except ValueError: # parsing prefix as integer fails
  1894. self._download_n_results(query, 1)
  1895. return
  1896. def _download_n_results(self, query, n):
  1897. """Downloads a specified number of results for a query"""
  1898. video_ids = []
  1899. already_seen = set()
  1900. pagenum = 1
  1901. while True:
  1902. self.report_download_page(query, pagenum)
  1903. result_url = self._TEMPLATE_URL % (urllib.quote_plus(query), pagenum)
  1904. request = urllib2.Request(result_url)
  1905. try:
  1906. page = urllib2.urlopen(request).read()
  1907. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1908. self._downloader.trouble(u'ERROR: unable to download webpage: %s' % str(err))
  1909. return
  1910. # Extract video identifiers
  1911. for mobj in re.finditer(self._VIDEO_INDICATOR, page):
  1912. video_id = page[mobj.span()[0]:mobj.span()[1]].split('=')[2][:-1]
  1913. if video_id not in already_seen:
  1914. video_ids.append(video_id)
  1915. already_seen.add(video_id)
  1916. if len(video_ids) == n:
  1917. # Specified n videos reached
  1918. for id in video_ids:
  1919. self._youtube_ie.extract('http://www.youtube.com/watch?v=%s' % id)
  1920. return
  1921. if re.search(self._MORE_PAGES_INDICATOR, page) is None:
  1922. for id in video_ids:
  1923. self._youtube_ie.extract('http://www.youtube.com/watch?v=%s' % id)
  1924. return
  1925. pagenum = pagenum + 1
  1926. class GoogleSearchIE(InfoExtractor):
  1927. """Information Extractor for Google Video search queries."""
  1928. _VALID_URL = r'gvsearch(\d+|all)?:[\s\S]+'
  1929. _TEMPLATE_URL = 'http://video.google.com/videosearch?q=%s+site:video.google.com&start=%s&hl=en'
  1930. _VIDEO_INDICATOR = r'videoplay\?docid=([^\&>]+)\&'
  1931. _MORE_PAGES_INDICATOR = r'<span>Next</span>'
  1932. _google_ie = None
  1933. _max_google_results = 1000
  1934. IE_NAME = u'video.google:search'
  1935. def __init__(self, google_ie, downloader=None):
  1936. InfoExtractor.__init__(self, downloader)
  1937. self._google_ie = google_ie
  1938. def report_download_page(self, query, pagenum):
  1939. """Report attempt to download playlist page with given number."""
  1940. query = query.decode(preferredencoding())
  1941. self._downloader.to_screen(u'[video.google] query "%s": Downloading page %s' % (query, pagenum))
  1942. def _real_initialize(self):
  1943. self._google_ie.initialize()
  1944. def _real_extract(self, query):
  1945. mobj = re.match(self._VALID_URL, query)
  1946. if mobj is None:
  1947. self._downloader.trouble(u'ERROR: invalid search query "%s"' % query)
  1948. return
  1949. prefix, query = query.split(':')
  1950. prefix = prefix[8:]
  1951. query = query.encode('utf-8')
  1952. if prefix == '':
  1953. self._download_n_results(query, 1)
  1954. return
  1955. elif prefix == 'all':
  1956. self._download_n_results(query, self._max_google_results)
  1957. return
  1958. else:
  1959. try:
  1960. n = long(prefix)
  1961. if n <= 0:
  1962. self._downloader.trouble(u'ERROR: invalid download number %s for query "%s"' % (n, query))
  1963. return
  1964. elif n > self._max_google_results:
  1965. self._downloader.to_stderr(u'WARNING: gvsearch returns max %i results (you requested %i)' % (self._max_google_results, n))
  1966. n = self._max_google_results
  1967. self._download_n_results(query, n)
  1968. return
  1969. except ValueError: # parsing prefix as integer fails
  1970. self._download_n_results(query, 1)
  1971. return
  1972. def _download_n_results(self, query, n):
  1973. """Downloads a specified number of results for a query"""
  1974. video_ids = []
  1975. already_seen = set()
  1976. pagenum = 1
  1977. while True:
  1978. self.report_download_page(query, pagenum)
  1979. result_url = self._TEMPLATE_URL % (urllib.quote_plus(query), pagenum)
  1980. request = urllib2.Request(result_url)
  1981. try:
  1982. page = urllib2.urlopen(request).read()
  1983. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  1984. self._downloader.trouble(u'ERROR: unable to download webpage: %s' % str(err))
  1985. return
  1986. # Extract video identifiers
  1987. for mobj in re.finditer(self._VIDEO_INDICATOR, page):
  1988. video_id = mobj.group(1)
  1989. if video_id not in already_seen:
  1990. video_ids.append(video_id)
  1991. already_seen.add(video_id)
  1992. if len(video_ids) == n:
  1993. # Specified n videos reached
  1994. for id in video_ids:
  1995. self._google_ie.extract('http://video.google.com/videoplay?docid=%s' % id)
  1996. return
  1997. if re.search(self._MORE_PAGES_INDICATOR, page) is None:
  1998. for id in video_ids:
  1999. self._google_ie.extract('http://video.google.com/videoplay?docid=%s' % id)
  2000. return
  2001. pagenum = pagenum + 1
  2002. class YahooSearchIE(InfoExtractor):
  2003. """Information Extractor for Yahoo! Video search queries."""
  2004. _VALID_URL = r'yvsearch(\d+|all)?:[\s\S]+'
  2005. _TEMPLATE_URL = 'http://video.yahoo.com/search/?p=%s&o=%s'
  2006. _VIDEO_INDICATOR = r'href="http://video\.yahoo\.com/watch/([0-9]+/[0-9]+)"'
  2007. _MORE_PAGES_INDICATOR = r'\s*Next'
  2008. _yahoo_ie = None
  2009. _max_yahoo_results = 1000
  2010. IE_NAME = u'video.yahoo:search'
  2011. def __init__(self, yahoo_ie, downloader=None):
  2012. InfoExtractor.__init__(self, downloader)
  2013. self._yahoo_ie = yahoo_ie
  2014. def report_download_page(self, query, pagenum):
  2015. """Report attempt to download playlist page with given number."""
  2016. query = query.decode(preferredencoding())
  2017. self._downloader.to_screen(u'[video.yahoo] query "%s": Downloading page %s' % (query, pagenum))
  2018. def _real_initialize(self):
  2019. self._yahoo_ie.initialize()
  2020. def _real_extract(self, query):
  2021. mobj = re.match(self._VALID_URL, query)
  2022. if mobj is None:
  2023. self._downloader.trouble(u'ERROR: invalid search query "%s"' % query)
  2024. return
  2025. prefix, query = query.split(':')
  2026. prefix = prefix[8:]
  2027. query = query.encode('utf-8')
  2028. if prefix == '':
  2029. self._download_n_results(query, 1)
  2030. return
  2031. elif prefix == 'all':
  2032. self._download_n_results(query, self._max_yahoo_results)
  2033. return
  2034. else:
  2035. try:
  2036. n = long(prefix)
  2037. if n <= 0:
  2038. self._downloader.trouble(u'ERROR: invalid download number %s for query "%s"' % (n, query))
  2039. return
  2040. elif n > self._max_yahoo_results:
  2041. self._downloader.to_stderr(u'WARNING: yvsearch returns max %i results (you requested %i)' % (self._max_yahoo_results, n))
  2042. n = self._max_yahoo_results
  2043. self._download_n_results(query, n)
  2044. return
  2045. except ValueError: # parsing prefix as integer fails
  2046. self._download_n_results(query, 1)
  2047. return
  2048. def _download_n_results(self, query, n):
  2049. """Downloads a specified number of results for a query"""
  2050. video_ids = []
  2051. already_seen = set()
  2052. pagenum = 1
  2053. while True:
  2054. self.report_download_page(query, pagenum)
  2055. result_url = self._TEMPLATE_URL % (urllib.quote_plus(query), pagenum)
  2056. request = urllib2.Request(result_url)
  2057. try:
  2058. page = urllib2.urlopen(request).read()
  2059. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  2060. self._downloader.trouble(u'ERROR: unable to download webpage: %s' % str(err))
  2061. return
  2062. # Extract video identifiers
  2063. for mobj in re.finditer(self._VIDEO_INDICATOR, page):
  2064. video_id = mobj.group(1)
  2065. if video_id not in already_seen:
  2066. video_ids.append(video_id)
  2067. already_seen.add(video_id)
  2068. if len(video_ids) == n:
  2069. # Specified n videos reached
  2070. for id in video_ids:
  2071. self._yahoo_ie.extract('http://video.yahoo.com/watch/%s' % id)
  2072. return
  2073. if re.search(self._MORE_PAGES_INDICATOR, page) is None:
  2074. for id in video_ids:
  2075. self._yahoo_ie.extract('http://video.yahoo.com/watch/%s' % id)
  2076. return
  2077. pagenum = pagenum + 1
  2078. class YoutubePlaylistIE(InfoExtractor):
  2079. """Information Extractor for YouTube playlists."""
  2080. _VALID_URL = r'(?:http://)?(?:\w+\.)?youtube.com/(?:(?:view_play_list|my_playlists|artist|playlist)\?.*?(p|a|list)=|user/.*?/user/|p/|user/.*?#[pg]/c/)([0-9A-Za-z]+)(?:/.*?/([0-9A-Za-z_-]+))?.*'
  2081. _TEMPLATE_URL = 'http://www.youtube.com/%s?%s=%s&page=%s&gl=US&hl=en'
  2082. _VIDEO_INDICATOR = r'/watch\?v=(.+?)&'
  2083. _MORE_PAGES_INDICATOR = r'(?m)>\s*Next\s*</a>'
  2084. _youtube_ie = None
  2085. IE_NAME = u'youtube:playlist'
  2086. def __init__(self, youtube_ie, downloader=None):
  2087. InfoExtractor.__init__(self, downloader)
  2088. self._youtube_ie = youtube_ie
  2089. def report_download_page(self, playlist_id, pagenum):
  2090. """Report attempt to download playlist page with given number."""
  2091. self._downloader.to_screen(u'[youtube] PL %s: Downloading page #%s' % (playlist_id, pagenum))
  2092. def _real_initialize(self):
  2093. self._youtube_ie.initialize()
  2094. def _real_extract(self, url):
  2095. # Extract playlist id
  2096. mobj = re.match(self._VALID_URL, url)
  2097. if mobj is None:
  2098. self._downloader.trouble(u'ERROR: invalid url: %s' % url)
  2099. return
  2100. # Single video case
  2101. if mobj.group(3) is not None:
  2102. self._youtube_ie.extract(mobj.group(3))
  2103. return
  2104. # Download playlist pages
  2105. # prefix is 'p' as default for playlists but there are other types that need extra care
  2106. playlist_prefix = mobj.group(1)
  2107. if playlist_prefix == 'a':
  2108. playlist_access = 'artist'
  2109. else:
  2110. playlist_prefix = 'p'
  2111. playlist_access = 'view_play_list'
  2112. playlist_id = mobj.group(2)
  2113. video_ids = []
  2114. pagenum = 1
  2115. while True:
  2116. self.report_download_page(playlist_id, pagenum)
  2117. request = urllib2.Request(self._TEMPLATE_URL % (playlist_access, playlist_prefix, playlist_id, pagenum))
  2118. try:
  2119. page = urllib2.urlopen(request).read()
  2120. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  2121. self._downloader.trouble(u'ERROR: unable to download webpage: %s' % str(err))
  2122. return
  2123. # Extract video identifiers
  2124. ids_in_page = []
  2125. for mobj in re.finditer(self._VIDEO_INDICATOR, page):
  2126. if mobj.group(1) not in ids_in_page:
  2127. ids_in_page.append(mobj.group(1))
  2128. video_ids.extend(ids_in_page)
  2129. if re.search(self._MORE_PAGES_INDICATOR, page) is None:
  2130. break
  2131. pagenum = pagenum + 1
  2132. playliststart = self._downloader.params.get('playliststart', 1) - 1
  2133. playlistend = self._downloader.params.get('playlistend', -1)
  2134. video_ids = video_ids[playliststart:playlistend]
  2135. for id in video_ids:
  2136. self._youtube_ie.extract('http://www.youtube.com/watch?v=%s' % id)
  2137. return
  2138. class YoutubeUserIE(InfoExtractor):
  2139. """Information Extractor for YouTube users."""
  2140. _VALID_URL = r'(?:(?:(?:http://)?(?:\w+\.)?youtube.com/user/)|ytuser:)([A-Za-z0-9_-]+)'
  2141. _TEMPLATE_URL = 'http://gdata.youtube.com/feeds/api/users/%s'
  2142. _GDATA_PAGE_SIZE = 50
  2143. _GDATA_URL = 'http://gdata.youtube.com/feeds/api/users/%s/uploads?max-results=%d&start-index=%d'
  2144. _VIDEO_INDICATOR = r'/watch\?v=(.+?)&'
  2145. _youtube_ie = None
  2146. IE_NAME = u'youtube:user'
  2147. def __init__(self, youtube_ie, downloader=None):
  2148. InfoExtractor.__init__(self, downloader)
  2149. self._youtube_ie = youtube_ie
  2150. def report_download_page(self, username, start_index):
  2151. """Report attempt to download user page."""
  2152. self._downloader.to_screen(u'[youtube] user %s: Downloading video ids from %d to %d' %
  2153. (username, start_index, start_index + self._GDATA_PAGE_SIZE))
  2154. def _real_initialize(self):
  2155. self._youtube_ie.initialize()
  2156. def _real_extract(self, url):
  2157. # Extract username
  2158. mobj = re.match(self._VALID_URL, url)
  2159. if mobj is None:
  2160. self._downloader.trouble(u'ERROR: invalid url: %s' % url)
  2161. return
  2162. username = mobj.group(1)
  2163. # Download video ids using YouTube Data API. Result size per
  2164. # query is limited (currently to 50 videos) so we need to query
  2165. # page by page until there are no video ids - it means we got
  2166. # all of them.
  2167. video_ids = []
  2168. pagenum = 0
  2169. while True:
  2170. start_index = pagenum * self._GDATA_PAGE_SIZE + 1
  2171. self.report_download_page(username, start_index)
  2172. request = urllib2.Request(self._GDATA_URL % (username, self._GDATA_PAGE_SIZE, start_index))
  2173. try:
  2174. page = urllib2.urlopen(request).read()
  2175. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  2176. self._downloader.trouble(u'ERROR: unable to download webpage: %s' % str(err))
  2177. return
  2178. # Extract video identifiers
  2179. ids_in_page = []
  2180. for mobj in re.finditer(self._VIDEO_INDICATOR, page):
  2181. if mobj.group(1) not in ids_in_page:
  2182. ids_in_page.append(mobj.group(1))
  2183. video_ids.extend(ids_in_page)
  2184. # A little optimization - if current page is not
  2185. # "full", ie. does not contain PAGE_SIZE video ids then
  2186. # we can assume that this page is the last one - there
  2187. # are no more ids on further pages - no need to query
  2188. # again.
  2189. if len(ids_in_page) < self._GDATA_PAGE_SIZE:
  2190. break
  2191. pagenum += 1
  2192. all_ids_count = len(video_ids)
  2193. playliststart = self._downloader.params.get('playliststart', 1) - 1
  2194. playlistend = self._downloader.params.get('playlistend', -1)
  2195. if playlistend == -1:
  2196. video_ids = video_ids[playliststart:]
  2197. else:
  2198. video_ids = video_ids[playliststart:playlistend]
  2199. self._downloader.to_screen("[youtube] user %s: Collected %d video ids (downloading %d of them)" %
  2200. (username, all_ids_count, len(video_ids)))
  2201. for video_id in video_ids:
  2202. self._youtube_ie.extract('http://www.youtube.com/watch?v=%s' % video_id)
  2203. class DepositFilesIE(InfoExtractor):
  2204. """Information extractor for depositfiles.com"""
  2205. _VALID_URL = r'(?:http://)?(?:\w+\.)?depositfiles.com/(?:../(?#locale))?files/(.+)'
  2206. IE_NAME = u'DepositFiles'
  2207. def __init__(self, downloader=None):
  2208. InfoExtractor.__init__(self, downloader)
  2209. def report_download_webpage(self, file_id):
  2210. """Report webpage download."""
  2211. self._downloader.to_screen(u'[DepositFiles] %s: Downloading webpage' % file_id)
  2212. def report_extraction(self, file_id):
  2213. """Report information extraction."""
  2214. self._downloader.to_screen(u'[DepositFiles] %s: Extracting information' % file_id)
  2215. def _real_initialize(self):
  2216. return
  2217. def _real_extract(self, url):
  2218. # At this point we have a new file
  2219. self._downloader.increment_downloads()
  2220. file_id = url.split('/')[-1]
  2221. # Rebuild url in english locale
  2222. url = 'http://depositfiles.com/en/files/' + file_id
  2223. # Retrieve file webpage with 'Free download' button pressed
  2224. free_download_indication = { 'gateway_result' : '1' }
  2225. request = urllib2.Request(url, urllib.urlencode(free_download_indication))
  2226. try:
  2227. self.report_download_webpage(file_id)
  2228. webpage = urllib2.urlopen(request).read()
  2229. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  2230. self._downloader.trouble(u'ERROR: Unable to retrieve file webpage: %s' % str(err))
  2231. return
  2232. # Search for the real file URL
  2233. mobj = re.search(r'<form action="(http://fileshare.+?)"', webpage)
  2234. if (mobj is None) or (mobj.group(1) is None):
  2235. # Try to figure out reason of the error.
  2236. mobj = re.search(r'<strong>(Attention.*?)</strong>', webpage, re.DOTALL)
  2237. if (mobj is not None) and (mobj.group(1) is not None):
  2238. restriction_message = re.sub('\s+', ' ', mobj.group(1)).strip()
  2239. self._downloader.trouble(u'ERROR: %s' % restriction_message)
  2240. else:
  2241. self._downloader.trouble(u'ERROR: unable to extract download URL from: %s' % url)
  2242. return
  2243. file_url = mobj.group(1)
  2244. file_extension = os.path.splitext(file_url)[1][1:]
  2245. # Search for file title
  2246. mobj = re.search(r'<b title="(.*?)">', webpage)
  2247. if mobj is None:
  2248. self._downloader.trouble(u'ERROR: unable to extract title')
  2249. return
  2250. file_title = mobj.group(1).decode('utf-8')
  2251. try:
  2252. # Process file information
  2253. self._downloader.process_info({
  2254. 'id': file_id.decode('utf-8'),
  2255. 'url': file_url.decode('utf-8'),
  2256. 'uploader': u'NA',
  2257. 'upload_date': u'NA',
  2258. 'title': file_title,
  2259. 'stitle': file_title,
  2260. 'ext': file_extension.decode('utf-8'),
  2261. 'format': u'NA',
  2262. 'player_url': None,
  2263. })
  2264. except UnavailableVideoError, err:
  2265. self._downloader.trouble(u'ERROR: unable to download file')
  2266. class FacebookIE(InfoExtractor):
  2267. """Information Extractor for Facebook"""
  2268. _VALID_URL = r'^(?:https?://)?(?:\w+\.)?facebook.com/video/video.php\?(?:.*?)v=(?P<ID>\d+)(?:.*)'
  2269. _LOGIN_URL = 'https://login.facebook.com/login.php?m&next=http%3A%2F%2Fm.facebook.com%2Fhome.php&'
  2270. _NETRC_MACHINE = 'facebook'
  2271. _available_formats = ['highqual', 'lowqual']
  2272. _video_extensions = {
  2273. 'highqual': 'mp4',
  2274. 'lowqual': 'mp4',
  2275. }
  2276. IE_NAME = u'facebook'
  2277. def __init__(self, downloader=None):
  2278. InfoExtractor.__init__(self, downloader)
  2279. def _reporter(self, message):
  2280. """Add header and report message."""
  2281. self._downloader.to_screen(u'[facebook] %s' % message)
  2282. def report_login(self):
  2283. """Report attempt to log in."""
  2284. self._reporter(u'Logging in')
  2285. def report_video_webpage_download(self, video_id):
  2286. """Report attempt to download video webpage."""
  2287. self._reporter(u'%s: Downloading video webpage' % video_id)
  2288. def report_information_extraction(self, video_id):
  2289. """Report attempt to extract video information."""
  2290. self._reporter(u'%s: Extracting video information' % video_id)
  2291. def _parse_page(self, video_webpage):
  2292. """Extract video information from page"""
  2293. # General data
  2294. data = {'title': r'class="video_title datawrap">(.*?)</',
  2295. 'description': r'<div class="datawrap">(.*?)</div>',
  2296. 'owner': r'\("video_owner_name", "(.*?)"\)',
  2297. 'upload_date': r'data-date="(.*?)"',
  2298. 'thumbnail': r'\("thumb_url", "(?P<THUMB>.*?)"\)',
  2299. }
  2300. video_info = {}
  2301. for piece in data.keys():
  2302. mobj = re.search(data[piece], video_webpage)
  2303. if mobj is not None:
  2304. video_info[piece] = urllib.unquote_plus(mobj.group(1).decode("unicode_escape"))
  2305. # Video urls
  2306. video_urls = {}
  2307. for fmt in self._available_formats:
  2308. mobj = re.search(r'\("%s_src\", "(.+?)"\)' % fmt, video_webpage)
  2309. if mobj is not None:
  2310. # URL is in a Javascript segment inside an escaped Unicode format within
  2311. # the generally utf-8 page
  2312. video_urls[fmt] = urllib.unquote_plus(mobj.group(1).decode("unicode_escape"))
  2313. video_info['video_urls'] = video_urls
  2314. return video_info
  2315. def _real_initialize(self):
  2316. if self._downloader is None:
  2317. return
  2318. useremail = None
  2319. password = None
  2320. downloader_params = self._downloader.params
  2321. # Attempt to use provided username and password or .netrc data
  2322. if downloader_params.get('username', None) is not None:
  2323. useremail = downloader_params['username']
  2324. password = downloader_params['password']
  2325. elif downloader_params.get('usenetrc', False):
  2326. try:
  2327. info = netrc.netrc().authenticators(self._NETRC_MACHINE)
  2328. if info is not None:
  2329. useremail = info[0]
  2330. password = info[2]
  2331. else:
  2332. raise netrc.NetrcParseError('No authenticators for %s' % self._NETRC_MACHINE)
  2333. except (IOError, netrc.NetrcParseError), err:
  2334. self._downloader.to_stderr(u'WARNING: parsing .netrc: %s' % str(err))
  2335. return
  2336. if useremail is None:
  2337. return
  2338. # Log in
  2339. login_form = {
  2340. 'email': useremail,
  2341. 'pass': password,
  2342. 'login': 'Log+In'
  2343. }
  2344. request = urllib2.Request(self._LOGIN_URL, urllib.urlencode(login_form))
  2345. try:
  2346. self.report_login()
  2347. login_results = urllib2.urlopen(request).read()
  2348. if re.search(r'<form(.*)name="login"(.*)</form>', login_results) is not None:
  2349. self._downloader.to_stderr(u'WARNING: unable to log in: bad username/password, or exceded login rate limit (~3/min). Check credentials or wait.')
  2350. return
  2351. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  2352. self._downloader.to_stderr(u'WARNING: unable to log in: %s' % str(err))
  2353. return
  2354. def _real_extract(self, url):
  2355. mobj = re.match(self._VALID_URL, url)
  2356. if mobj is None:
  2357. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  2358. return
  2359. video_id = mobj.group('ID')
  2360. # Get video webpage
  2361. self.report_video_webpage_download(video_id)
  2362. request = urllib2.Request('https://www.facebook.com/video/video.php?v=%s' % video_id)
  2363. try:
  2364. page = urllib2.urlopen(request)
  2365. video_webpage = page.read()
  2366. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  2367. self._downloader.trouble(u'ERROR: unable to download video webpage: %s' % str(err))
  2368. return
  2369. # Start extracting information
  2370. self.report_information_extraction(video_id)
  2371. # Extract information
  2372. video_info = self._parse_page(video_webpage)
  2373. # uploader
  2374. if 'owner' not in video_info:
  2375. self._downloader.trouble(u'ERROR: unable to extract uploader nickname')
  2376. return
  2377. video_uploader = video_info['owner']
  2378. # title
  2379. if 'title' not in video_info:
  2380. self._downloader.trouble(u'ERROR: unable to extract video title')
  2381. return
  2382. video_title = video_info['title']
  2383. video_title = video_title.decode('utf-8')
  2384. video_title = sanitize_title(video_title)
  2385. # simplified title
  2386. simple_title = re.sub(ur'(?u)([^%s]+)' % simple_title_chars, ur'_', video_title)
  2387. simple_title = simple_title.strip(ur'_')
  2388. # thumbnail image
  2389. if 'thumbnail' not in video_info:
  2390. self._downloader.trouble(u'WARNING: unable to extract video thumbnail')
  2391. video_thumbnail = ''
  2392. else:
  2393. video_thumbnail = video_info['thumbnail']
  2394. # upload date
  2395. upload_date = u'NA'
  2396. if 'upload_date' in video_info:
  2397. upload_time = video_info['upload_date']
  2398. timetuple = email.utils.parsedate_tz(upload_time)
  2399. if timetuple is not None:
  2400. try:
  2401. upload_date = time.strftime('%Y%m%d', timetuple[0:9])
  2402. except:
  2403. pass
  2404. # description
  2405. video_description = video_info.get('description', 'No description available.')
  2406. url_map = video_info['video_urls']
  2407. if len(url_map.keys()) > 0:
  2408. # Decide which formats to download
  2409. req_format = self._downloader.params.get('format', None)
  2410. format_limit = self._downloader.params.get('format_limit', None)
  2411. if format_limit is not None and format_limit in self._available_formats:
  2412. format_list = self._available_formats[self._available_formats.index(format_limit):]
  2413. else:
  2414. format_list = self._available_formats
  2415. existing_formats = [x for x in format_list if x in url_map]
  2416. if len(existing_formats) == 0:
  2417. self._downloader.trouble(u'ERROR: no known formats available for video')
  2418. return
  2419. if req_format is None:
  2420. video_url_list = [(existing_formats[0], url_map[existing_formats[0]])] # Best quality
  2421. elif req_format == 'worst':
  2422. video_url_list = [(existing_formats[len(existing_formats)-1], url_map[existing_formats[len(existing_formats)-1]])] # worst quality
  2423. elif req_format == '-1':
  2424. video_url_list = [(f, url_map[f]) for f in existing_formats] # All formats
  2425. else:
  2426. # Specific format
  2427. if req_format not in url_map:
  2428. self._downloader.trouble(u'ERROR: requested format not available')
  2429. return
  2430. video_url_list = [(req_format, url_map[req_format])] # Specific format
  2431. for format_param, video_real_url in video_url_list:
  2432. # At this point we have a new video
  2433. self._downloader.increment_downloads()
  2434. # Extension
  2435. video_extension = self._video_extensions.get(format_param, 'mp4')
  2436. try:
  2437. # Process video information
  2438. self._downloader.process_info({
  2439. 'id': video_id.decode('utf-8'),
  2440. 'url': video_real_url.decode('utf-8'),
  2441. 'uploader': video_uploader.decode('utf-8'),
  2442. 'upload_date': upload_date,
  2443. 'title': video_title,
  2444. 'stitle': simple_title,
  2445. 'ext': video_extension.decode('utf-8'),
  2446. 'format': (format_param is None and u'NA' or format_param.decode('utf-8')),
  2447. 'thumbnail': video_thumbnail.decode('utf-8'),
  2448. 'description': video_description.decode('utf-8'),
  2449. 'player_url': None,
  2450. })
  2451. except UnavailableVideoError, err:
  2452. self._downloader.trouble(u'\nERROR: unable to download video')
  2453. class BlipTVIE(InfoExtractor):
  2454. """Information extractor for blip.tv"""
  2455. _VALID_URL = r'^(?:https?://)?(?:\w+\.)?blip\.tv(/.+)$'
  2456. _URL_EXT = r'^.*\.([a-z0-9]+)$'
  2457. IE_NAME = u'blip.tv'
  2458. def report_extraction(self, file_id):
  2459. """Report information extraction."""
  2460. self._downloader.to_screen(u'[blip.tv] %s: Extracting information' % file_id)
  2461. def _simplify_title(self, title):
  2462. res = re.sub(ur'(?u)([^%s]+)' % simple_title_chars, ur'_', title)
  2463. res = res.strip(ur'_')
  2464. return res
  2465. def _real_extract(self, url):
  2466. mobj = re.match(self._VALID_URL, url)
  2467. if mobj is None:
  2468. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  2469. return
  2470. if '?' in url:
  2471. cchar = '&'
  2472. else:
  2473. cchar = '?'
  2474. json_url = url + cchar + 'skin=json&version=2&no_wrap=1'
  2475. request = urllib2.Request(json_url)
  2476. self.report_extraction(mobj.group(1))
  2477. try:
  2478. json_code = urllib2.urlopen(request).read()
  2479. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  2480. self._downloader.trouble(u'ERROR: unable to download video info webpage: %s' % str(err))
  2481. return
  2482. try:
  2483. json_data = json.loads(json_code)
  2484. if 'Post' in json_data:
  2485. data = json_data['Post']
  2486. else:
  2487. data = json_data
  2488. upload_date = datetime.datetime.strptime(data['datestamp'], '%m-%d-%y %H:%M%p').strftime('%Y%m%d')
  2489. video_url = data['media']['url']
  2490. umobj = re.match(self._URL_EXT, video_url)
  2491. if umobj is None:
  2492. raise ValueError('Can not determine filename extension')
  2493. ext = umobj.group(1)
  2494. self._downloader.increment_downloads()
  2495. info = {
  2496. 'id': data['item_id'],
  2497. 'url': video_url,
  2498. 'uploader': data['display_name'],
  2499. 'upload_date': upload_date,
  2500. 'title': data['title'],
  2501. 'stitle': self._simplify_title(data['title']),
  2502. 'ext': ext,
  2503. 'format': data['media']['mimeType'],
  2504. 'thumbnail': data['thumbnailUrl'],
  2505. 'description': data['description'],
  2506. 'player_url': data['embedUrl']
  2507. }
  2508. except (ValueError,KeyError), err:
  2509. self._downloader.trouble(u'ERROR: unable to parse video information: %s' % repr(err))
  2510. return
  2511. try:
  2512. self._downloader.process_info(info)
  2513. except UnavailableVideoError, err:
  2514. self._downloader.trouble(u'\nERROR: unable to download video')
  2515. class MyVideoIE(InfoExtractor):
  2516. """Information Extractor for myvideo.de."""
  2517. _VALID_URL = r'(?:http://)?(?:www\.)?myvideo\.de/watch/([0-9]+)/([^?/]+).*'
  2518. IE_NAME = u'myvideo'
  2519. def __init__(self, downloader=None):
  2520. InfoExtractor.__init__(self, downloader)
  2521. def report_download_webpage(self, video_id):
  2522. """Report webpage download."""
  2523. self._downloader.to_screen(u'[myvideo] %s: Downloading webpage' % video_id)
  2524. def report_extraction(self, video_id):
  2525. """Report information extraction."""
  2526. self._downloader.to_screen(u'[myvideo] %s: Extracting information' % video_id)
  2527. def _real_initialize(self):
  2528. return
  2529. def _real_extract(self,url):
  2530. mobj = re.match(self._VALID_URL, url)
  2531. if mobj is None:
  2532. self._download.trouble(u'ERROR: invalid URL: %s' % url)
  2533. return
  2534. video_id = mobj.group(1)
  2535. simple_title = mobj.group(2).decode('utf-8')
  2536. # should actually not be necessary
  2537. simple_title = sanitize_title(simple_title)
  2538. simple_title = re.sub(ur'(?u)([^%s]+)' % simple_title_chars, ur'_', simple_title)
  2539. # Get video webpage
  2540. request = urllib2.Request('http://www.myvideo.de/watch/%s' % video_id)
  2541. try:
  2542. self.report_download_webpage(video_id)
  2543. webpage = urllib2.urlopen(request).read()
  2544. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  2545. self._downloader.trouble(u'ERROR: Unable to retrieve video webpage: %s' % str(err))
  2546. return
  2547. self.report_extraction(video_id)
  2548. mobj = re.search(r'<link rel=\'image_src\' href=\'(http://is[0-9].myvideo\.de/de/movie[0-9]+/[a-f0-9]+)/thumbs/[^.]+\.jpg\' />',
  2549. webpage)
  2550. if mobj is None:
  2551. self._downloader.trouble(u'ERROR: unable to extract media URL')
  2552. return
  2553. video_url = mobj.group(1) + ('/%s.flv' % video_id)
  2554. mobj = re.search('<title>([^<]+)</title>', webpage)
  2555. if mobj is None:
  2556. self._downloader.trouble(u'ERROR: unable to extract title')
  2557. return
  2558. video_title = mobj.group(1)
  2559. video_title = sanitize_title(video_title)
  2560. try:
  2561. print(video_url)
  2562. self._downloader.process_info({
  2563. 'id': video_id,
  2564. 'url': video_url,
  2565. 'uploader': u'NA',
  2566. 'upload_date': u'NA',
  2567. 'title': video_title,
  2568. 'stitle': simple_title,
  2569. 'ext': u'flv',
  2570. 'format': u'NA',
  2571. 'player_url': None,
  2572. })
  2573. except UnavailableVideoError:
  2574. self._downloader.trouble(u'\nERROR: Unable to download video')
  2575. class ComedyCentralIE(InfoExtractor):
  2576. """Information extractor for The Daily Show and Colbert Report """
  2577. _VALID_URL = r'^(:(?P<shortname>tds|thedailyshow|cr|colbert|colbertnation|colbertreport))|(https?://)?(www\.)?(?P<showname>thedailyshow|colbertnation)\.com/full-episodes/(?P<episode>.*)$'
  2578. IE_NAME = u'comedycentral'
  2579. def report_extraction(self, episode_id):
  2580. self._downloader.to_screen(u'[comedycentral] %s: Extracting information' % episode_id)
  2581. def report_config_download(self, episode_id):
  2582. self._downloader.to_screen(u'[comedycentral] %s: Downloading configuration' % episode_id)
  2583. def report_index_download(self, episode_id):
  2584. self._downloader.to_screen(u'[comedycentral] %s: Downloading show index' % episode_id)
  2585. def report_player_url(self, episode_id):
  2586. self._downloader.to_screen(u'[comedycentral] %s: Determining player URL' % episode_id)
  2587. def _simplify_title(self, title):
  2588. res = re.sub(ur'(?u)([^%s]+)' % simple_title_chars, ur'_', title)
  2589. res = res.strip(ur'_')
  2590. return res
  2591. def _real_extract(self, url):
  2592. mobj = re.match(self._VALID_URL, url)
  2593. if mobj is None:
  2594. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  2595. return
  2596. if mobj.group('shortname'):
  2597. if mobj.group('shortname') in ('tds', 'thedailyshow'):
  2598. url = 'http://www.thedailyshow.com/full-episodes/'
  2599. else:
  2600. url = 'http://www.colbertnation.com/full-episodes/'
  2601. mobj = re.match(self._VALID_URL, url)
  2602. assert mobj is not None
  2603. dlNewest = not mobj.group('episode')
  2604. if dlNewest:
  2605. epTitle = mobj.group('showname')
  2606. else:
  2607. epTitle = mobj.group('episode')
  2608. req = urllib2.Request(url)
  2609. self.report_extraction(epTitle)
  2610. try:
  2611. htmlHandle = urllib2.urlopen(req)
  2612. html = htmlHandle.read()
  2613. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  2614. self._downloader.trouble(u'ERROR: unable to download webpage: %s' % unicode(err))
  2615. return
  2616. if dlNewest:
  2617. url = htmlHandle.geturl()
  2618. mobj = re.match(self._VALID_URL, url)
  2619. if mobj is None:
  2620. self._downloader.trouble(u'ERROR: Invalid redirected URL: ' + url)
  2621. return
  2622. if mobj.group('episode') == '':
  2623. self._downloader.trouble(u'ERROR: Redirected URL is still not specific: ' + url)
  2624. return
  2625. epTitle = mobj.group('episode')
  2626. mMovieParams = re.findall('<param name="movie" value="(http://media.mtvnservices.com/([^"]*episode.*?:.*?))"/>', html)
  2627. if len(mMovieParams) == 0:
  2628. self._downloader.trouble(u'ERROR: unable to find Flash URL in webpage ' + url)
  2629. return
  2630. playerUrl_raw = mMovieParams[0][0]
  2631. self.report_player_url(epTitle)
  2632. try:
  2633. urlHandle = urllib2.urlopen(playerUrl_raw)
  2634. playerUrl = urlHandle.geturl()
  2635. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  2636. self._downloader.trouble(u'ERROR: unable to find out player URL: ' + unicode(err))
  2637. return
  2638. uri = mMovieParams[0][1]
  2639. indexUrl = 'http://shadow.comedycentral.com/feeds/video_player/mrss/?' + urllib.urlencode({'uri': uri})
  2640. self.report_index_download(epTitle)
  2641. try:
  2642. indexXml = urllib2.urlopen(indexUrl).read()
  2643. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  2644. self._downloader.trouble(u'ERROR: unable to download episode index: ' + unicode(err))
  2645. return
  2646. idoc = xml.etree.ElementTree.fromstring(indexXml)
  2647. itemEls = idoc.findall('.//item')
  2648. for itemEl in itemEls:
  2649. mediaId = itemEl.findall('./guid')[0].text
  2650. shortMediaId = mediaId.split(':')[-1]
  2651. showId = mediaId.split(':')[-2].replace('.com', '')
  2652. officialTitle = itemEl.findall('./title')[0].text
  2653. officialDate = itemEl.findall('./pubDate')[0].text
  2654. configUrl = ('http://www.comedycentral.com/global/feeds/entertainment/media/mediaGenEntertainment.jhtml?' +
  2655. urllib.urlencode({'uri': mediaId}))
  2656. configReq = urllib2.Request(configUrl)
  2657. self.report_config_download(epTitle)
  2658. try:
  2659. configXml = urllib2.urlopen(configReq).read()
  2660. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  2661. self._downloader.trouble(u'ERROR: unable to download webpage: %s' % unicode(err))
  2662. return
  2663. cdoc = xml.etree.ElementTree.fromstring(configXml)
  2664. turls = []
  2665. for rendition in cdoc.findall('.//rendition'):
  2666. finfo = (rendition.attrib['bitrate'], rendition.findall('./src')[0].text)
  2667. turls.append(finfo)
  2668. if len(turls) == 0:
  2669. self._downloader.trouble(u'\nERROR: unable to download ' + mediaId + ': No videos found')
  2670. continue
  2671. # For now, just pick the highest bitrate
  2672. format,video_url = turls[-1]
  2673. self._downloader.increment_downloads()
  2674. effTitle = showId + '-' + epTitle
  2675. info = {
  2676. 'id': shortMediaId,
  2677. 'url': video_url,
  2678. 'uploader': showId,
  2679. 'upload_date': officialDate,
  2680. 'title': effTitle,
  2681. 'stitle': self._simplify_title(effTitle),
  2682. 'ext': 'mp4',
  2683. 'format': format,
  2684. 'thumbnail': None,
  2685. 'description': officialTitle,
  2686. 'player_url': playerUrl
  2687. }
  2688. try:
  2689. self._downloader.process_info(info)
  2690. except UnavailableVideoError, err:
  2691. self._downloader.trouble(u'\nERROR: unable to download ' + mediaId)
  2692. continue
  2693. class EscapistIE(InfoExtractor):
  2694. """Information extractor for The Escapist """
  2695. _VALID_URL = r'^(https?://)?(www\.)?escapistmagazine.com/videos/view/(?P<showname>[^/]+)/(?P<episode>[^/?]+)[/?]?.*$'
  2696. IE_NAME = u'escapist'
  2697. def report_extraction(self, showName):
  2698. self._downloader.to_screen(u'[escapist] %s: Extracting information' % showName)
  2699. def report_config_download(self, showName):
  2700. self._downloader.to_screen(u'[escapist] %s: Downloading configuration' % showName)
  2701. def _simplify_title(self, title):
  2702. res = re.sub(ur'(?u)([^%s]+)' % simple_title_chars, ur'_', title)
  2703. res = res.strip(ur'_')
  2704. return res
  2705. def _real_extract(self, url):
  2706. htmlParser = HTMLParser.HTMLParser()
  2707. mobj = re.match(self._VALID_URL, url)
  2708. if mobj is None:
  2709. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  2710. return
  2711. showName = mobj.group('showname')
  2712. videoId = mobj.group('episode')
  2713. self.report_extraction(showName)
  2714. try:
  2715. webPage = urllib2.urlopen(url).read()
  2716. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  2717. self._downloader.trouble(u'ERROR: unable to download webpage: ' + unicode(err))
  2718. return
  2719. descMatch = re.search('<meta name="description" content="([^"]*)"', webPage)
  2720. description = htmlParser.unescape(descMatch.group(1))
  2721. imgMatch = re.search('<meta property="og:image" content="([^"]*)"', webPage)
  2722. imgUrl = htmlParser.unescape(imgMatch.group(1))
  2723. playerUrlMatch = re.search('<meta property="og:video" content="([^"]*)"', webPage)
  2724. playerUrl = htmlParser.unescape(playerUrlMatch.group(1))
  2725. configUrlMatch = re.search('config=(.*)$', playerUrl)
  2726. configUrl = urllib2.unquote(configUrlMatch.group(1))
  2727. self.report_config_download(showName)
  2728. try:
  2729. configJSON = urllib2.urlopen(configUrl).read()
  2730. except (urllib2.URLError, httplib.HTTPException, socket.error), err:
  2731. self._downloader.trouble(u'ERROR: unable to download configuration: ' + unicode(err))
  2732. return
  2733. # Technically, it's JavaScript, not JSON
  2734. configJSON = configJSON.replace("'", '"')
  2735. try:
  2736. config = json.loads(configJSON)
  2737. except (ValueError,), err:
  2738. self._downloader.trouble(u'ERROR: Invalid JSON in configuration file: ' + unicode(err))
  2739. return
  2740. playlist = config['playlist']
  2741. videoUrl = playlist[1]['url']
  2742. self._downloader.increment_downloads()
  2743. info = {
  2744. 'id': videoId,
  2745. 'url': videoUrl,
  2746. 'uploader': showName,
  2747. 'upload_date': None,
  2748. 'title': showName,
  2749. 'stitle': self._simplify_title(showName),
  2750. 'ext': 'flv',
  2751. 'format': 'flv',
  2752. 'thumbnail': imgUrl,
  2753. 'description': description,
  2754. 'player_url': playerUrl,
  2755. }
  2756. try:
  2757. self._downloader.process_info(info)
  2758. except UnavailableVideoError, err:
  2759. self._downloader.trouble(u'\nERROR: unable to download ' + videoId)
  2760. class PostProcessor(object):
  2761. """Post Processor class.
  2762. PostProcessor objects can be added to downloaders with their
  2763. add_post_processor() method. When the downloader has finished a
  2764. successful download, it will take its internal chain of PostProcessors
  2765. and start calling the run() method on each one of them, first with
  2766. an initial argument and then with the returned value of the previous
  2767. PostProcessor.
  2768. The chain will be stopped if one of them ever returns None or the end
  2769. of the chain is reached.
  2770. PostProcessor objects follow a "mutual registration" process similar
  2771. to InfoExtractor objects.
  2772. """
  2773. _downloader = None
  2774. def __init__(self, downloader=None):
  2775. self._downloader = downloader
  2776. def set_downloader(self, downloader):
  2777. """Sets the downloader for this PP."""
  2778. self._downloader = downloader
  2779. def run(self, information):
  2780. """Run the PostProcessor.
  2781. The "information" argument is a dictionary like the ones
  2782. composed by InfoExtractors. The only difference is that this
  2783. one has an extra field called "filepath" that points to the
  2784. downloaded file.
  2785. When this method returns None, the postprocessing chain is
  2786. stopped. However, this method may return an information
  2787. dictionary that will be passed to the next postprocessing
  2788. object in the chain. It can be the one it received after
  2789. changing some fields.
  2790. In addition, this method may raise a PostProcessingError
  2791. exception that will be taken into account by the downloader
  2792. it was called from.
  2793. """
  2794. return information # by default, do nothing
  2795. class FFmpegExtractAudioPP(PostProcessor):
  2796. def __init__(self, downloader=None, preferredcodec=None, preferredquality=None, keepvideo=False):
  2797. PostProcessor.__init__(self, downloader)
  2798. if preferredcodec is None:
  2799. preferredcodec = 'best'
  2800. self._preferredcodec = preferredcodec
  2801. self._preferredquality = preferredquality
  2802. self._keepvideo = keepvideo
  2803. @staticmethod
  2804. def get_audio_codec(path):
  2805. try:
  2806. cmd = ['ffprobe', '-show_streams', '--', path]
  2807. handle = subprocess.Popen(cmd, stderr=file(os.path.devnull, 'w'), stdout=subprocess.PIPE)
  2808. output = handle.communicate()[0]
  2809. if handle.wait() != 0:
  2810. return None
  2811. except (IOError, OSError):
  2812. return None
  2813. audio_codec = None
  2814. for line in output.split('\n'):
  2815. if line.startswith('codec_name='):
  2816. audio_codec = line.split('=')[1].strip()
  2817. elif line.strip() == 'codec_type=audio' and audio_codec is not None:
  2818. return audio_codec
  2819. return None
  2820. @staticmethod
  2821. def run_ffmpeg(path, out_path, codec, more_opts):
  2822. try:
  2823. cmd = ['ffmpeg', '-y', '-i', path, '-vn', '-acodec', codec] + more_opts + ['--', out_path]
  2824. ret = subprocess.call(cmd, stdout=file(os.path.devnull, 'w'), stderr=subprocess.STDOUT)
  2825. return (ret == 0)
  2826. except (IOError, OSError):
  2827. return False
  2828. def run(self, information):
  2829. path = information['filepath']
  2830. filecodec = self.get_audio_codec(path)
  2831. if filecodec is None:
  2832. self._downloader.to_stderr(u'WARNING: unable to obtain file audio codec with ffprobe')
  2833. return None
  2834. more_opts = []
  2835. if self._preferredcodec == 'best' or self._preferredcodec == filecodec:
  2836. if filecodec == 'aac' or filecodec == 'mp3':
  2837. # Lossless if possible
  2838. acodec = 'copy'
  2839. extension = filecodec
  2840. if filecodec == 'aac':
  2841. more_opts = ['-f', 'adts']
  2842. else:
  2843. # MP3 otherwise.
  2844. acodec = 'libmp3lame'
  2845. extension = 'mp3'
  2846. more_opts = []
  2847. if self._preferredquality is not None:
  2848. more_opts += ['-ab', self._preferredquality]
  2849. else:
  2850. # We convert the audio (lossy)
  2851. acodec = {'mp3': 'libmp3lame', 'aac': 'aac'}[self._preferredcodec]
  2852. extension = self._preferredcodec
  2853. more_opts = []
  2854. if self._preferredquality is not None:
  2855. more_opts += ['-ab', self._preferredquality]
  2856. if self._preferredcodec == 'aac':
  2857. more_opts += ['-f', 'adts']
  2858. (prefix, ext) = os.path.splitext(path)
  2859. new_path = prefix + '.' + extension
  2860. self._downloader.to_screen(u'[ffmpeg] Destination: %s' % new_path)
  2861. status = self.run_ffmpeg(path, new_path, acodec, more_opts)
  2862. if not status:
  2863. self._downloader.to_stderr(u'WARNING: error running ffmpeg')
  2864. return None
  2865. # Try to update the date time for extracted audio file.
  2866. if information.get('filetime') is not None:
  2867. try:
  2868. os.utime(new_path, (time.time(), information['filetime']))
  2869. except:
  2870. self._downloader.to_stderr(u'WARNING: Cannot update utime of audio file')
  2871. if not self._keepvideo:
  2872. try:
  2873. os.remove(path)
  2874. except (IOError, OSError):
  2875. self._downloader.to_stderr(u'WARNING: Unable to remove downloaded video file')
  2876. return None
  2877. information['filepath'] = new_path
  2878. return information
  2879. def updateSelf(downloader, filename):
  2880. ''' Update the program file with the latest version from the repository '''
  2881. # Note: downloader only used for options
  2882. if not os.access(filename, os.W_OK):
  2883. sys.exit('ERROR: no write permissions on %s' % filename)
  2884. downloader.to_screen('Updating to latest version...')
  2885. try:
  2886. try:
  2887. urlh = urllib.urlopen(UPDATE_URL)
  2888. newcontent = urlh.read()
  2889. vmatch = re.search("__version__ = '([^']+)'", newcontent)
  2890. if vmatch is not None and vmatch.group(1) == __version__:
  2891. downloader.to_screen('youtube-dl is up-to-date (' + __version__ + ')')
  2892. return
  2893. finally:
  2894. urlh.close()
  2895. except (IOError, OSError), err:
  2896. sys.exit('ERROR: unable to download latest version')
  2897. try:
  2898. outf = open(filename, 'wb')
  2899. try:
  2900. outf.write(newcontent)
  2901. finally:
  2902. outf.close()
  2903. except (IOError, OSError), err:
  2904. sys.exit('ERROR: unable to overwrite current version')
  2905. downloader.to_screen('Updated youtube-dl. Restart youtube-dl to use the new version.')
  2906. def parseOpts():
  2907. # Deferred imports
  2908. import getpass
  2909. import optparse
  2910. def _format_option_string(option):
  2911. ''' ('-o', '--option') -> -o, --format METAVAR'''
  2912. opts = []
  2913. if option._short_opts: opts.append(option._short_opts[0])
  2914. if option._long_opts: opts.append(option._long_opts[0])
  2915. if len(opts) > 1: opts.insert(1, ', ')
  2916. if option.takes_value(): opts.append(' %s' % option.metavar)
  2917. return "".join(opts)
  2918. def _find_term_columns():
  2919. columns = os.environ.get('COLUMNS', None)
  2920. if columns:
  2921. return int(columns)
  2922. try:
  2923. sp = subprocess.Popen(['stty', 'size'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  2924. out,err = sp.communicate()
  2925. return int(out.split()[1])
  2926. except:
  2927. pass
  2928. return None
  2929. max_width = 80
  2930. max_help_position = 80
  2931. # No need to wrap help messages if we're on a wide console
  2932. columns = _find_term_columns()
  2933. if columns: max_width = columns
  2934. fmt = optparse.IndentedHelpFormatter(width=max_width, max_help_position=max_help_position)
  2935. fmt.format_option_strings = _format_option_string
  2936. kw = {
  2937. 'version' : __version__,
  2938. 'formatter' : fmt,
  2939. 'usage' : '%prog [options] url [url...]',
  2940. 'conflict_handler' : 'resolve',
  2941. }
  2942. parser = optparse.OptionParser(**kw)
  2943. # option groups
  2944. general = optparse.OptionGroup(parser, 'General Options')
  2945. selection = optparse.OptionGroup(parser, 'Video Selection')
  2946. authentication = optparse.OptionGroup(parser, 'Authentication Options')
  2947. video_format = optparse.OptionGroup(parser, 'Video Format Options')
  2948. postproc = optparse.OptionGroup(parser, 'Post-processing Options')
  2949. filesystem = optparse.OptionGroup(parser, 'Filesystem Options')
  2950. verbosity = optparse.OptionGroup(parser, 'Verbosity / Simulation Options')
  2951. general.add_option('-h', '--help',
  2952. action='help', help='print this help text and exit')
  2953. general.add_option('-v', '--version',
  2954. action='version', help='print program version and exit')
  2955. general.add_option('-U', '--update',
  2956. action='store_true', dest='update_self', help='update this program to latest version')
  2957. general.add_option('-i', '--ignore-errors',
  2958. action='store_true', dest='ignoreerrors', help='continue on download errors', default=False)
  2959. general.add_option('-r', '--rate-limit',
  2960. dest='ratelimit', metavar='LIMIT', help='download rate limit (e.g. 50k or 44.6m)')
  2961. general.add_option('-R', '--retries',
  2962. dest='retries', metavar='RETRIES', help='number of retries (default is 10)', default=10)
  2963. general.add_option('--dump-user-agent',
  2964. action='store_true', dest='dump_user_agent',
  2965. help='display the current browser identification', default=False)
  2966. general.add_option('--list-extractors',
  2967. action='store_true', dest='list_extractors',
  2968. help='List all supported extractors and the URLs they would handle', default=False)
  2969. selection.add_option('--playlist-start',
  2970. dest='playliststart', metavar='NUMBER', help='playlist video to start at (default is 1)', default=1)
  2971. selection.add_option('--playlist-end',
  2972. dest='playlistend', metavar='NUMBER', help='playlist video to end at (default is last)', default=-1)
  2973. selection.add_option('--match-title', dest='matchtitle', metavar='REGEX',help='download only matching titles (regex or caseless sub-string)')
  2974. selection.add_option('--reject-title', dest='rejecttitle', metavar='REGEX',help='skip download for matching titles (regex or caseless sub-string)')
  2975. authentication.add_option('-u', '--username',
  2976. dest='username', metavar='USERNAME', help='account username')
  2977. authentication.add_option('-p', '--password',
  2978. dest='password', metavar='PASSWORD', help='account password')
  2979. authentication.add_option('-n', '--netrc',
  2980. action='store_true', dest='usenetrc', help='use .netrc authentication data', default=False)
  2981. video_format.add_option('-f', '--format',
  2982. action='store', dest='format', metavar='FORMAT', help='video format code')
  2983. video_format.add_option('--all-formats',
  2984. action='store_const', dest='format', help='download all available video formats', const='all')
  2985. video_format.add_option('--max-quality',
  2986. action='store', dest='format_limit', metavar='FORMAT', help='highest quality format to download')
  2987. verbosity.add_option('-q', '--quiet',
  2988. action='store_true', dest='quiet', help='activates quiet mode', default=False)
  2989. verbosity.add_option('-s', '--simulate',
  2990. action='store_true', dest='simulate', help='do not download the video and do not write anything to disk', default=False)
  2991. verbosity.add_option('--skip-download',
  2992. action='store_true', dest='skip_download', help='do not download the video', default=False)
  2993. verbosity.add_option('-g', '--get-url',
  2994. action='store_true', dest='geturl', help='simulate, quiet but print URL', default=False)
  2995. verbosity.add_option('-e', '--get-title',
  2996. action='store_true', dest='gettitle', help='simulate, quiet but print title', default=False)
  2997. verbosity.add_option('--get-thumbnail',
  2998. action='store_true', dest='getthumbnail',
  2999. help='simulate, quiet but print thumbnail URL', default=False)
  3000. verbosity.add_option('--get-description',
  3001. action='store_true', dest='getdescription',
  3002. help='simulate, quiet but print video description', default=False)
  3003. verbosity.add_option('--get-filename',
  3004. action='store_true', dest='getfilename',
  3005. help='simulate, quiet but print output filename', default=False)
  3006. verbosity.add_option('--get-format',
  3007. action='store_true', dest='getformat',
  3008. help='simulate, quiet but print output format', default=False)
  3009. verbosity.add_option('--no-progress',
  3010. action='store_true', dest='noprogress', help='do not print progress bar', default=False)
  3011. verbosity.add_option('--console-title',
  3012. action='store_true', dest='consoletitle',
  3013. help='display progress in console titlebar', default=False)
  3014. filesystem.add_option('-t', '--title',
  3015. action='store_true', dest='usetitle', help='use title in file name', default=False)
  3016. filesystem.add_option('-l', '--literal',
  3017. action='store_true', dest='useliteral', help='use literal title in file name', default=False)
  3018. filesystem.add_option('-A', '--auto-number',
  3019. action='store_true', dest='autonumber',
  3020. help='number downloaded files starting from 00000', default=False)
  3021. filesystem.add_option('-o', '--output',
  3022. dest='outtmpl', metavar='TEMPLATE', help='output filename template')
  3023. filesystem.add_option('-a', '--batch-file',
  3024. dest='batchfile', metavar='FILE', help='file containing URLs to download (\'-\' for stdin)')
  3025. filesystem.add_option('-w', '--no-overwrites',
  3026. action='store_true', dest='nooverwrites', help='do not overwrite files', default=False)
  3027. filesystem.add_option('-c', '--continue',
  3028. action='store_true', dest='continue_dl', help='resume partially downloaded files', default=False)
  3029. filesystem.add_option('--no-continue',
  3030. action='store_false', dest='continue_dl',
  3031. help='do not resume partially downloaded files (restart from beginning)')
  3032. filesystem.add_option('--cookies',
  3033. dest='cookiefile', metavar='FILE', help='file to dump cookie jar to')
  3034. filesystem.add_option('--no-part',
  3035. action='store_true', dest='nopart', help='do not use .part files', default=False)
  3036. filesystem.add_option('--no-mtime',
  3037. action='store_false', dest='updatetime',
  3038. help='do not use the Last-modified header to set the file modification time', default=True)
  3039. filesystem.add_option('--write-description',
  3040. action='store_true', dest='writedescription',
  3041. help='write video description to a .description file', default=False)
  3042. filesystem.add_option('--write-info-json',
  3043. action='store_true', dest='writeinfojson',
  3044. help='write video metadata to a .info.json file', default=False)
  3045. postproc.add_option('--extract-audio', action='store_true', dest='extractaudio', default=False,
  3046. help='convert video files to audio-only files (requires ffmpeg and ffprobe)')
  3047. postproc.add_option('--audio-format', metavar='FORMAT', dest='audioformat', default='best',
  3048. help='"best", "aac" or "mp3"; best by default')
  3049. postproc.add_option('--audio-quality', metavar='QUALITY', dest='audioquality', default='128K',
  3050. help='ffmpeg audio bitrate specification, 128k by default')
  3051. postproc.add_option('-k', '--keep-video', action='store_true', dest='keepvideo', default=False,
  3052. help='keeps the video file on disk after the post-processing; the video is erased by default')
  3053. parser.add_option_group(general)
  3054. parser.add_option_group(selection)
  3055. parser.add_option_group(filesystem)
  3056. parser.add_option_group(verbosity)
  3057. parser.add_option_group(video_format)
  3058. parser.add_option_group(authentication)
  3059. parser.add_option_group(postproc)
  3060. opts, args = parser.parse_args()
  3061. return parser, opts, args
  3062. def gen_extractors():
  3063. """ Return a list of an instance of every supported extractor.
  3064. The order does matter; the first extractor matched is the one handling the URL.
  3065. """
  3066. youtube_ie = YoutubeIE()
  3067. google_ie = GoogleIE()
  3068. yahoo_ie = YahooIE()
  3069. return [
  3070. youtube_ie,
  3071. MetacafeIE(youtube_ie),
  3072. DailymotionIE(),
  3073. YoutubePlaylistIE(youtube_ie),
  3074. YoutubeUserIE(youtube_ie),
  3075. YoutubeSearchIE(youtube_ie),
  3076. google_ie,
  3077. GoogleSearchIE(google_ie),
  3078. PhotobucketIE(),
  3079. yahoo_ie,
  3080. YahooSearchIE(yahoo_ie),
  3081. DepositFilesIE(),
  3082. FacebookIE(),
  3083. BlipTVIE(),
  3084. VimeoIE(),
  3085. MyVideoIE(),
  3086. ComedyCentralIE(),
  3087. EscapistIE(),
  3088. GenericIE()
  3089. ]
  3090. def main():
  3091. parser, opts, args = parseOpts()
  3092. # Open appropriate CookieJar
  3093. if opts.cookiefile is None:
  3094. jar = cookielib.CookieJar()
  3095. else:
  3096. try:
  3097. jar = cookielib.MozillaCookieJar(opts.cookiefile)
  3098. if os.path.isfile(opts.cookiefile) and os.access(opts.cookiefile, os.R_OK):
  3099. jar.load()
  3100. except (IOError, OSError), err:
  3101. sys.exit(u'ERROR: unable to open cookie file')
  3102. # Dump user agent
  3103. if opts.dump_user_agent:
  3104. print std_headers['User-Agent']
  3105. sys.exit(0)
  3106. # Batch file verification
  3107. batchurls = []
  3108. if opts.batchfile is not None:
  3109. try:
  3110. if opts.batchfile == '-':
  3111. batchfd = sys.stdin
  3112. else:
  3113. batchfd = open(opts.batchfile, 'r')
  3114. batchurls = batchfd.readlines()
  3115. batchurls = [x.strip() for x in batchurls]
  3116. batchurls = [x for x in batchurls if len(x) > 0 and not re.search(r'^[#/;]', x)]
  3117. except IOError:
  3118. sys.exit(u'ERROR: batch file could not be read')
  3119. all_urls = batchurls + args
  3120. # General configuration
  3121. cookie_processor = urllib2.HTTPCookieProcessor(jar)
  3122. opener = urllib2.build_opener(urllib2.ProxyHandler(), cookie_processor, YoutubeDLHandler())
  3123. urllib2.install_opener(opener)
  3124. socket.setdefaulttimeout(300) # 5 minutes should be enough (famous last words)
  3125. extractors = gen_extractors()
  3126. if opts.list_extractors:
  3127. for ie in extractors:
  3128. print(ie.IE_NAME)
  3129. matchedUrls = filter(lambda url: ie.suitable(url), all_urls)
  3130. all_urls = filter(lambda url: url not in matchedUrls, all_urls)
  3131. for mu in matchedUrls:
  3132. print(u' ' + mu)
  3133. sys.exit(0)
  3134. # Conflicting, missing and erroneous options
  3135. if opts.usenetrc and (opts.username is not None or opts.password is not None):
  3136. parser.error(u'using .netrc conflicts with giving username/password')
  3137. if opts.password is not None and opts.username is None:
  3138. parser.error(u'account username missing')
  3139. if opts.outtmpl is not None and (opts.useliteral or opts.usetitle or opts.autonumber):
  3140. parser.error(u'using output template conflicts with using title, literal title or auto number')
  3141. if opts.usetitle and opts.useliteral:
  3142. parser.error(u'using title conflicts with using literal title')
  3143. if opts.username is not None and opts.password is None:
  3144. opts.password = getpass.getpass(u'Type account password and press return:')
  3145. if opts.ratelimit is not None:
  3146. numeric_limit = FileDownloader.parse_bytes(opts.ratelimit)
  3147. if numeric_limit is None:
  3148. parser.error(u'invalid rate limit specified')
  3149. opts.ratelimit = numeric_limit
  3150. if opts.retries is not None:
  3151. try:
  3152. opts.retries = long(opts.retries)
  3153. except (TypeError, ValueError), err:
  3154. parser.error(u'invalid retry count specified')
  3155. try:
  3156. opts.playliststart = int(opts.playliststart)
  3157. if opts.playliststart <= 0:
  3158. raise ValueError(u'Playlist start must be positive')
  3159. except (TypeError, ValueError), err:
  3160. parser.error(u'invalid playlist start number specified')
  3161. try:
  3162. opts.playlistend = int(opts.playlistend)
  3163. if opts.playlistend != -1 and (opts.playlistend <= 0 or opts.playlistend < opts.playliststart):
  3164. raise ValueError(u'Playlist end must be greater than playlist start')
  3165. except (TypeError, ValueError), err:
  3166. parser.error(u'invalid playlist end number specified')
  3167. if opts.extractaudio:
  3168. if opts.audioformat not in ['best', 'aac', 'mp3']:
  3169. parser.error(u'invalid audio format specified')
  3170. # File downloader
  3171. fd = FileDownloader({
  3172. 'usenetrc': opts.usenetrc,
  3173. 'username': opts.username,
  3174. 'password': opts.password,
  3175. 'quiet': (opts.quiet or opts.geturl or opts.gettitle or opts.getthumbnail or opts.getdescription or opts.getfilename or opts.getformat),
  3176. 'forceurl': opts.geturl,
  3177. 'forcetitle': opts.gettitle,
  3178. 'forcethumbnail': opts.getthumbnail,
  3179. 'forcedescription': opts.getdescription,
  3180. 'forcefilename': opts.getfilename,
  3181. 'forceformat': opts.getformat,
  3182. 'simulate': opts.simulate,
  3183. '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),
  3184. 'format': opts.format,
  3185. 'format_limit': opts.format_limit,
  3186. 'outtmpl': ((opts.outtmpl is not None and opts.outtmpl.decode(preferredencoding()))
  3187. or (opts.format == '-1' and opts.usetitle and u'%(stitle)s-%(id)s-%(format)s.%(ext)s')
  3188. or (opts.format == '-1' and opts.useliteral and u'%(title)s-%(id)s-%(format)s.%(ext)s')
  3189. or (opts.format == '-1' and u'%(id)s-%(format)s.%(ext)s')
  3190. or (opts.usetitle and opts.autonumber and u'%(autonumber)s-%(stitle)s-%(id)s.%(ext)s')
  3191. or (opts.useliteral and opts.autonumber and u'%(autonumber)s-%(title)s-%(id)s.%(ext)s')
  3192. or (opts.usetitle and u'%(stitle)s-%(id)s.%(ext)s')
  3193. or (opts.useliteral and u'%(title)s-%(id)s.%(ext)s')
  3194. or (opts.autonumber and u'%(autonumber)s-%(id)s.%(ext)s')
  3195. or u'%(id)s.%(ext)s'),
  3196. 'ignoreerrors': opts.ignoreerrors,
  3197. 'ratelimit': opts.ratelimit,
  3198. 'nooverwrites': opts.nooverwrites,
  3199. 'retries': opts.retries,
  3200. 'continuedl': opts.continue_dl,
  3201. 'noprogress': opts.noprogress,
  3202. 'playliststart': opts.playliststart,
  3203. 'playlistend': opts.playlistend,
  3204. 'logtostderr': opts.outtmpl == '-',
  3205. 'consoletitle': opts.consoletitle,
  3206. 'nopart': opts.nopart,
  3207. 'updatetime': opts.updatetime,
  3208. 'writedescription': opts.writedescription,
  3209. 'writeinfojson': opts.writeinfojson,
  3210. 'matchtitle': opts.matchtitle,
  3211. 'rejecttitle': opts.rejecttitle,
  3212. })
  3213. for extractor in extractors:
  3214. fd.add_info_extractor(extractor)
  3215. # PostProcessors
  3216. if opts.extractaudio:
  3217. fd.add_post_processor(FFmpegExtractAudioPP(preferredcodec=opts.audioformat, preferredquality=opts.audioquality, keepvideo=opts.keepvideo))
  3218. # Update version
  3219. if opts.update_self:
  3220. updateSelf(fd, sys.argv[0])
  3221. # Maybe do nothing
  3222. if len(all_urls) < 1:
  3223. if not opts.update_self:
  3224. parser.error(u'you must provide at least one URL')
  3225. else:
  3226. sys.exit()
  3227. retcode = fd.download(all_urls)
  3228. # Dump cookie jar if requested
  3229. if opts.cookiefile is not None:
  3230. try:
  3231. jar.save()
  3232. except (IOError, OSError), err:
  3233. sys.exit(u'ERROR: unable to save cookie jar')
  3234. sys.exit(retcode)
  3235. if __name__ == '__main__':
  3236. try:
  3237. main()
  3238. except DownloadError:
  3239. sys.exit(1)
  3240. except SameFileError:
  3241. sys.exit(u'ERROR: fixed output name but more than one file to download')
  3242. except KeyboardInterrupt:
  3243. sys.exit(u'\nERROR: Interrupted by user')
  3244. # vim: set ts=4 sw=4 sts=4 noet ai si filetype=python: