youtube-dl 129 KB

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