youtube-dl 126 KB

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