youtube-dl 124 KB

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