__init__.py 160 KB

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