__init__.py 148 KB

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