youtube-dl 118 KB

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