youtube-dl 140 KB

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