__init__.py 159 KB

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