__init__.py 156 KB

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