__init__.py 150 KB

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