__init__.py 155 KB

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