InfoExtractors.py 177 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. from __future__ import absolute_import
  4. import base64
  5. import datetime
  6. import itertools
  7. import netrc
  8. import os
  9. import re
  10. import socket
  11. import time
  12. import email.utils
  13. import xml.etree.ElementTree
  14. import random
  15. import math
  16. import operator
  17. from .utils import *
  18. class InfoExtractor(object):
  19. """Information Extractor class.
  20. Information extractors are the classes that, given a URL, extract
  21. information about the video (or videos) the URL refers to. This
  22. information includes the real video URL, the video title, author and
  23. others. The information is stored in a dictionary which is then
  24. passed to the FileDownloader. The FileDownloader processes this
  25. information possibly downloading the video to the file system, among
  26. other possible outcomes.
  27. The dictionaries must include the following fields:
  28. id: Video identifier.
  29. url: Final video URL.
  30. title: Video title, unescaped.
  31. ext: Video filename extension.
  32. The following fields are optional:
  33. format: The video format, defaults to ext (used for --get-format)
  34. thumbnail: Full URL to a video thumbnail image.
  35. description: One-line video description.
  36. uploader: Full name of the video uploader.
  37. upload_date: Video upload date (YYYYMMDD).
  38. uploader_id: Nickname or id of the video uploader.
  39. location: Physical location of the video.
  40. player_url: SWF Player URL (used for rtmpdump).
  41. subtitles: The subtitle file contents.
  42. urlhandle: [internal] The urlHandle to be used to download the file,
  43. like returned by urllib.request.urlopen
  44. The fields should all be Unicode strings.
  45. Subclasses of this one should re-define the _real_initialize() and
  46. _real_extract() methods and define a _VALID_URL regexp.
  47. Probably, they should also be added to the list of extractors.
  48. _real_extract() must return a *list* of information dictionaries as
  49. described above.
  50. Finally, the _WORKING attribute should be set to False for broken IEs
  51. in order to warn the users and skip the tests.
  52. """
  53. _ready = False
  54. _downloader = None
  55. _WORKING = True
  56. def __init__(self, downloader=None):
  57. """Constructor. Receives an optional downloader."""
  58. self._ready = False
  59. self.set_downloader(downloader)
  60. @classmethod
  61. def suitable(cls, url):
  62. """Receives a URL and returns True if suitable for this IE."""
  63. return re.match(cls._VALID_URL, url) is not None
  64. @classmethod
  65. def working(cls):
  66. """Getter method for _WORKING."""
  67. return cls._WORKING
  68. def initialize(self):
  69. """Initializes an instance (authentication, etc)."""
  70. if not self._ready:
  71. self._real_initialize()
  72. self._ready = True
  73. def extract(self, url):
  74. """Extracts URL information and returns it in list of dicts."""
  75. self.initialize()
  76. return self._real_extract(url)
  77. def set_downloader(self, downloader):
  78. """Sets the downloader for this IE."""
  79. self._downloader = downloader
  80. def _real_initialize(self):
  81. """Real initialization process. Redefine in subclasses."""
  82. pass
  83. def _real_extract(self, url):
  84. """Real extraction process. Redefine in subclasses."""
  85. pass
  86. @property
  87. def IE_NAME(self):
  88. return type(self).__name__[:-2]
  89. def _request_webpage(self, url_or_request, video_id, note=None, errnote=None):
  90. """ Returns the response handle """
  91. if note is None:
  92. note = u'Downloading video webpage'
  93. if note is not False:
  94. self._downloader.to_screen(u'[%s] %s: %s' % (self.IE_NAME, video_id, note))
  95. try:
  96. return compat_urllib_request.urlopen(url_or_request)
  97. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  98. if errnote is None:
  99. errnote = u'Unable to download webpage'
  100. raise ExtractorError(u'%s: %s' % (errnote, compat_str(err)), sys.exc_info()[2])
  101. def _download_webpage(self, url_or_request, video_id, note=None, errnote=None):
  102. """ Returns the data of the page as a string """
  103. urlh = self._request_webpage(url_or_request, video_id, note, errnote)
  104. content_type = urlh.headers.get('Content-Type', '')
  105. m = re.match(r'[a-zA-Z0-9_.-]+/[a-zA-Z0-9_.-]+\s*;\s*charset=(.+)', content_type)
  106. if m:
  107. encoding = m.group(1)
  108. else:
  109. encoding = 'utf-8'
  110. webpage_bytes = urlh.read()
  111. if self._downloader.params.get('dump_intermediate_pages', False):
  112. try:
  113. url = url_or_request.get_full_url()
  114. except AttributeError:
  115. url = url_or_request
  116. self._downloader.to_screen(u'Dumping request to ' + url)
  117. dump = base64.b64encode(webpage_bytes).decode('ascii')
  118. self._downloader.to_screen(dump)
  119. return webpage_bytes.decode(encoding, 'replace')
  120. class YoutubeIE(InfoExtractor):
  121. """Information extractor for youtube.com."""
  122. _VALID_URL = r"""^
  123. (
  124. (?:https?://)? # http(s):// (optional)
  125. (?:youtu\.be/|(?:\w+\.)?youtube(?:-nocookie)?\.com/|
  126. tube\.majestyc\.net/) # the various hostnames, with wildcard subdomains
  127. (?:.*?\#/)? # handle anchor (#/) redirect urls
  128. (?: # the various things that can precede the ID:
  129. (?:(?:v|embed|e)/) # v/ or embed/ or e/
  130. |(?: # or the v= param in all its forms
  131. (?:watch(?:_popup)?(?:\.php)?)? # preceding watch(_popup|.php) or nothing (like /?v=xxxx)
  132. (?:\?|\#!?) # the params delimiter ? or # or #!
  133. (?:.*?&)? # any other preceding param (like /?s=tuff&v=xxxx)
  134. v=
  135. )
  136. )? # optional -> youtube.com/xxxx is OK
  137. )? # all until now is optional -> you can pass the naked ID
  138. ([0-9A-Za-z_-]+) # here is it! the YouTube video ID
  139. (?(1).+)? # if we found the ID, everything can follow
  140. $"""
  141. _LANG_URL = r'http://www.youtube.com/?hl=en&persist_hl=1&gl=US&persist_gl=1&opt_out_ackd=1'
  142. _LOGIN_URL = 'https://accounts.google.com/ServiceLogin'
  143. _AGE_URL = 'http://www.youtube.com/verify_age?next_url=/&gl=US&hl=en'
  144. _NEXT_URL_RE = r'[\?&]next_url=([^&]+)'
  145. _NETRC_MACHINE = 'youtube'
  146. # Listed in order of quality
  147. _available_formats = ['38', '37', '46', '22', '45', '35', '44', '34', '18', '43', '6', '5', '17', '13']
  148. _available_formats_prefer_free = ['38', '46', '37', '45', '22', '44', '35', '43', '34', '18', '6', '5', '17', '13']
  149. _video_extensions = {
  150. '13': '3gp',
  151. '17': 'mp4',
  152. '18': 'mp4',
  153. '22': 'mp4',
  154. '37': 'mp4',
  155. '38': 'video', # You actually don't know if this will be MOV, AVI or whatever
  156. '43': 'webm',
  157. '44': 'webm',
  158. '45': 'webm',
  159. '46': 'webm',
  160. }
  161. _video_dimensions = {
  162. '5': '240x400',
  163. '6': '???',
  164. '13': '???',
  165. '17': '144x176',
  166. '18': '360x640',
  167. '22': '720x1280',
  168. '34': '360x640',
  169. '35': '480x854',
  170. '37': '1080x1920',
  171. '38': '3072x4096',
  172. '43': '360x640',
  173. '44': '480x854',
  174. '45': '720x1280',
  175. '46': '1080x1920',
  176. }
  177. IE_NAME = u'youtube'
  178. @classmethod
  179. def suitable(cls, url):
  180. """Receives a URL and returns True if suitable for this IE."""
  181. if YoutubePlaylistIE.suitable(url): return False
  182. return re.match(cls._VALID_URL, url, re.VERBOSE) is not None
  183. def report_lang(self):
  184. """Report attempt to set language."""
  185. self._downloader.to_screen(u'[youtube] Setting language')
  186. def report_login(self):
  187. """Report attempt to log in."""
  188. self._downloader.to_screen(u'[youtube] Logging in')
  189. def report_age_confirmation(self):
  190. """Report attempt to confirm age."""
  191. self._downloader.to_screen(u'[youtube] Confirming age')
  192. def report_video_webpage_download(self, video_id):
  193. """Report attempt to download video webpage."""
  194. self._downloader.to_screen(u'[youtube] %s: Downloading video webpage' % video_id)
  195. def report_video_info_webpage_download(self, video_id):
  196. """Report attempt to download video info webpage."""
  197. self._downloader.to_screen(u'[youtube] %s: Downloading video info webpage' % video_id)
  198. def report_video_subtitles_download(self, video_id):
  199. """Report attempt to download video info webpage."""
  200. self._downloader.to_screen(u'[youtube] %s: Checking available subtitles' % video_id)
  201. def report_video_subtitles_request(self, video_id, sub_lang, format):
  202. """Report attempt to download video info webpage."""
  203. self._downloader.to_screen(u'[youtube] %s: Downloading video subtitles for %s.%s' % (video_id, sub_lang, format))
  204. def report_video_subtitles_available(self, video_id, sub_lang_list):
  205. """Report available subtitles."""
  206. sub_lang = ",".join(list(sub_lang_list.keys()))
  207. self._downloader.to_screen(u'[youtube] %s: Available subtitles for video: %s' % (video_id, sub_lang))
  208. def report_information_extraction(self, video_id):
  209. """Report attempt to extract video information."""
  210. self._downloader.to_screen(u'[youtube] %s: Extracting video information' % video_id)
  211. def report_unavailable_format(self, video_id, format):
  212. """Report extracted video URL."""
  213. self._downloader.to_screen(u'[youtube] %s: Format %s not available' % (video_id, format))
  214. def report_rtmp_download(self):
  215. """Indicate the download will use the RTMP protocol."""
  216. self._downloader.to_screen(u'[youtube] RTMP download detected')
  217. def _get_available_subtitles(self, video_id):
  218. self.report_video_subtitles_download(video_id)
  219. request = compat_urllib_request.Request('http://video.google.com/timedtext?hl=en&type=list&v=%s' % video_id)
  220. try:
  221. sub_list = compat_urllib_request.urlopen(request).read().decode('utf-8')
  222. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  223. return (u'unable to download video subtitles: %s' % compat_str(err), None)
  224. sub_lang_list = re.findall(r'name="([^"]*)"[^>]+lang_code="([\w\-]+)"', sub_list)
  225. sub_lang_list = dict((l[1], l[0]) for l in sub_lang_list)
  226. if not sub_lang_list:
  227. return (u'video doesn\'t have subtitles', None)
  228. return sub_lang_list
  229. def _list_available_subtitles(self, video_id):
  230. sub_lang_list = self._get_available_subtitles(video_id)
  231. self.report_video_subtitles_available(video_id, sub_lang_list)
  232. def _request_subtitle(self, sub_lang, sub_name, video_id, format):
  233. """
  234. Return tuple:
  235. (error_message, sub_lang, sub)
  236. """
  237. self.report_video_subtitles_request(video_id, sub_lang, format)
  238. params = compat_urllib_parse.urlencode({
  239. 'lang': sub_lang,
  240. 'name': sub_name,
  241. 'v': video_id,
  242. 'fmt': format,
  243. })
  244. url = 'http://www.youtube.com/api/timedtext?' + params
  245. try:
  246. sub = compat_urllib_request.urlopen(url).read().decode('utf-8')
  247. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  248. return (u'unable to download video subtitles: %s' % compat_str(err), None, None)
  249. if not sub:
  250. return (u'Did not fetch video subtitles', None, None)
  251. return (None, sub_lang, sub)
  252. def _extract_subtitle(self, video_id):
  253. """
  254. Return a list with a tuple:
  255. [(error_message, sub_lang, sub)]
  256. """
  257. sub_lang_list = self._get_available_subtitles(video_id)
  258. sub_format = self._downloader.params.get('subtitlesformat')
  259. if isinstance(sub_lang_list,tuple): #There was some error, it didn't get the available subtitles
  260. return [(sub_lang_list[0], None, None)]
  261. if self._downloader.params.get('subtitleslang', False):
  262. sub_lang = self._downloader.params.get('subtitleslang')
  263. elif 'en' in sub_lang_list:
  264. sub_lang = 'en'
  265. else:
  266. sub_lang = list(sub_lang_list.keys())[0]
  267. if not sub_lang in sub_lang_list:
  268. return [(u'no closed captions found in the specified language "%s"' % sub_lang, None, None)]
  269. subtitle = self._request_subtitle(sub_lang, sub_lang_list[sub_lang].encode('utf-8'), video_id, sub_format)
  270. return [subtitle]
  271. def _extract_all_subtitles(self, video_id):
  272. sub_lang_list = self._get_available_subtitles(video_id)
  273. sub_format = self._downloader.params.get('subtitlesformat')
  274. if isinstance(sub_lang_list,tuple): #There was some error, it didn't get the available subtitles
  275. return [(sub_lang_list[0], None, None)]
  276. subtitles = []
  277. for sub_lang in sub_lang_list:
  278. subtitle = self._request_subtitle(sub_lang, sub_lang_list[sub_lang].encode('utf-8'), video_id, sub_format)
  279. subtitles.append(subtitle)
  280. return subtitles
  281. def _print_formats(self, formats):
  282. print('Available formats:')
  283. for x in formats:
  284. print('%s\t:\t%s\t[%s]' %(x, self._video_extensions.get(x, 'flv'), self._video_dimensions.get(x, '???')))
  285. def _real_initialize(self):
  286. if self._downloader is None:
  287. return
  288. username = None
  289. password = None
  290. downloader_params = self._downloader.params
  291. # Attempt to use provided username and password or .netrc data
  292. if downloader_params.get('username', None) is not None:
  293. username = downloader_params['username']
  294. password = downloader_params['password']
  295. elif downloader_params.get('usenetrc', False):
  296. try:
  297. info = netrc.netrc().authenticators(self._NETRC_MACHINE)
  298. if info is not None:
  299. username = info[0]
  300. password = info[2]
  301. else:
  302. raise netrc.NetrcParseError('No authenticators for %s' % self._NETRC_MACHINE)
  303. except (IOError, netrc.NetrcParseError) as err:
  304. self._downloader.report_warning(u'parsing .netrc: %s' % compat_str(err))
  305. return
  306. # Set language
  307. request = compat_urllib_request.Request(self._LANG_URL)
  308. try:
  309. self.report_lang()
  310. compat_urllib_request.urlopen(request).read()
  311. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  312. self._downloader.report_warning(u'unable to set language: %s' % compat_str(err))
  313. return
  314. # No authentication to be performed
  315. if username is None:
  316. return
  317. request = compat_urllib_request.Request(self._LOGIN_URL)
  318. try:
  319. login_page = compat_urllib_request.urlopen(request).read().decode('utf-8')
  320. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  321. self._downloader.report_warning(u'unable to fetch login page: %s' % compat_str(err))
  322. return
  323. galx = None
  324. dsh = None
  325. match = re.search(re.compile(r'<input.+?name="GALX".+?value="(.+?)"', re.DOTALL), login_page)
  326. if match:
  327. galx = match.group(1)
  328. match = re.search(re.compile(r'<input.+?name="dsh".+?value="(.+?)"', re.DOTALL), login_page)
  329. if match:
  330. dsh = match.group(1)
  331. # Log in
  332. login_form_strs = {
  333. u'continue': u'http://www.youtube.com/signin?action_handle_signin=true&feature=sign_in_button&hl=en_US&nomobiletemp=1',
  334. u'Email': username,
  335. u'GALX': galx,
  336. u'Passwd': password,
  337. u'PersistentCookie': u'yes',
  338. u'_utf8': u'霱',
  339. u'bgresponse': u'js_disabled',
  340. u'checkConnection': u'',
  341. u'checkedDomains': u'youtube',
  342. u'dnConn': u'',
  343. u'dsh': dsh,
  344. u'pstMsg': u'0',
  345. u'rmShown': u'1',
  346. u'secTok': u'',
  347. u'signIn': u'Sign in',
  348. u'timeStmp': u'',
  349. u'service': u'youtube',
  350. u'uilel': u'3',
  351. u'hl': u'en_US',
  352. }
  353. # Convert to UTF-8 *before* urlencode because Python 2.x's urlencode
  354. # chokes on unicode
  355. login_form = dict((k.encode('utf-8'), v.encode('utf-8')) for k,v in login_form_strs.items())
  356. login_data = compat_urllib_parse.urlencode(login_form).encode('ascii')
  357. request = compat_urllib_request.Request(self._LOGIN_URL, login_data)
  358. try:
  359. self.report_login()
  360. login_results = compat_urllib_request.urlopen(request).read().decode('utf-8')
  361. if re.search(r'(?i)<form[^>]* id="gaia_loginform"', login_results) is not None:
  362. self._downloader.report_warning(u'unable to log in: bad username or password')
  363. return
  364. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  365. self._downloader.report_warning(u'unable to log in: %s' % compat_str(err))
  366. return
  367. # Confirm age
  368. age_form = {
  369. 'next_url': '/',
  370. 'action_confirm': 'Confirm',
  371. }
  372. request = compat_urllib_request.Request(self._AGE_URL, compat_urllib_parse.urlencode(age_form))
  373. try:
  374. self.report_age_confirmation()
  375. age_results = compat_urllib_request.urlopen(request).read().decode('utf-8')
  376. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  377. self._downloader.report_error(u'unable to confirm age: %s' % compat_str(err))
  378. return
  379. def _extract_id(self, url):
  380. mobj = re.match(self._VALID_URL, url, re.VERBOSE)
  381. if mobj is None:
  382. self._downloader.report_error(u'invalid URL: %s' % url)
  383. return
  384. video_id = mobj.group(2)
  385. return video_id
  386. def _real_extract(self, url):
  387. # Extract original video URL from URL with redirection, like age verification, using next_url parameter
  388. mobj = re.search(self._NEXT_URL_RE, url)
  389. if mobj:
  390. url = 'http://www.youtube.com/' + compat_urllib_parse.unquote(mobj.group(1)).lstrip('/')
  391. video_id = self._extract_id(url)
  392. # Get video webpage
  393. self.report_video_webpage_download(video_id)
  394. url = 'http://www.youtube.com/watch?v=%s&gl=US&hl=en&has_verified=1' % video_id
  395. request = compat_urllib_request.Request(url)
  396. try:
  397. video_webpage_bytes = compat_urllib_request.urlopen(request).read()
  398. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  399. self._downloader.report_error(u'unable to download video webpage: %s' % compat_str(err))
  400. return
  401. video_webpage = video_webpage_bytes.decode('utf-8', 'ignore')
  402. # Attempt to extract SWF player URL
  403. mobj = re.search(r'swfConfig.*?"(http:\\/\\/.*?watch.*?-.*?\.swf)"', video_webpage)
  404. if mobj is not None:
  405. player_url = re.sub(r'\\(.)', r'\1', mobj.group(1))
  406. else:
  407. player_url = None
  408. # Get video info
  409. self.report_video_info_webpage_download(video_id)
  410. for el_type in ['&el=embedded', '&el=detailpage', '&el=vevo', '']:
  411. video_info_url = ('https://www.youtube.com/get_video_info?&video_id=%s%s&ps=default&eurl=&gl=US&hl=en'
  412. % (video_id, el_type))
  413. video_info_webpage = self._download_webpage(video_info_url, video_id,
  414. note=False,
  415. errnote='unable to download video info webpage')
  416. video_info = compat_parse_qs(video_info_webpage)
  417. if 'token' in video_info:
  418. break
  419. if 'token' not in video_info:
  420. if 'reason' in video_info:
  421. self._downloader.report_error(u'YouTube said: %s' % video_info['reason'][0])
  422. else:
  423. self._downloader.report_error(u'"token" parameter not in video info for unknown reason')
  424. return
  425. # Check for "rental" videos
  426. if 'ypc_video_rental_bar_text' in video_info and 'author' not in video_info:
  427. self._downloader.report_error(u'"rental" videos not supported')
  428. return
  429. # Start extracting information
  430. self.report_information_extraction(video_id)
  431. # uploader
  432. if 'author' not in video_info:
  433. self._downloader.report_error(u'unable to extract uploader name')
  434. return
  435. video_uploader = compat_urllib_parse.unquote_plus(video_info['author'][0])
  436. # uploader_id
  437. video_uploader_id = None
  438. mobj = re.search(r'<link itemprop="url" href="http://www.youtube.com/(?:user|channel)/([^"]+)">', video_webpage)
  439. if mobj is not None:
  440. video_uploader_id = mobj.group(1)
  441. else:
  442. self._downloader.report_warning(u'unable to extract uploader nickname')
  443. # title
  444. if 'title' not in video_info:
  445. self._downloader.report_error(u'unable to extract video title')
  446. return
  447. video_title = compat_urllib_parse.unquote_plus(video_info['title'][0])
  448. # thumbnail image
  449. if 'thumbnail_url' not in video_info:
  450. self._downloader.report_warning(u'unable to extract video thumbnail')
  451. video_thumbnail = ''
  452. else: # don't panic if we can't find it
  453. video_thumbnail = compat_urllib_parse.unquote_plus(video_info['thumbnail_url'][0])
  454. # upload date
  455. upload_date = None
  456. mobj = re.search(r'id="eow-date.*?>(.*?)</span>', video_webpage, re.DOTALL)
  457. if mobj is not None:
  458. upload_date = ' '.join(re.sub(r'[/,-]', r' ', mobj.group(1)).split())
  459. format_expressions = ['%d %B %Y', '%B %d %Y', '%b %d %Y']
  460. for expression in format_expressions:
  461. try:
  462. upload_date = datetime.datetime.strptime(upload_date, expression).strftime('%Y%m%d')
  463. except:
  464. pass
  465. # description
  466. video_description = get_element_by_id("eow-description", video_webpage)
  467. if video_description:
  468. video_description = clean_html(video_description)
  469. else:
  470. video_description = ''
  471. # subtitles
  472. video_subtitles = None
  473. if self._downloader.params.get('writesubtitles', False):
  474. video_subtitles = self._extract_subtitle(video_id)
  475. if video_subtitles:
  476. (sub_error, sub_lang, sub) = video_subtitles[0]
  477. if sub_error:
  478. self._downloader.report_error(sub_error)
  479. if self._downloader.params.get('allsubtitles', False):
  480. video_subtitles = self._extract_all_subtitles(video_id)
  481. for video_subtitle in video_subtitles:
  482. (sub_error, sub_lang, sub) = video_subtitle
  483. if sub_error:
  484. self._downloader.report_error(sub_error)
  485. if self._downloader.params.get('listsubtitles', False):
  486. sub_lang_list = self._list_available_subtitles(video_id)
  487. return
  488. if 'length_seconds' not in video_info:
  489. self._downloader.report_warning(u'unable to extract video duration')
  490. video_duration = ''
  491. else:
  492. video_duration = compat_urllib_parse.unquote_plus(video_info['length_seconds'][0])
  493. # token
  494. video_token = compat_urllib_parse.unquote_plus(video_info['token'][0])
  495. # Decide which formats to download
  496. req_format = self._downloader.params.get('format', None)
  497. if 'conn' in video_info and video_info['conn'][0].startswith('rtmp'):
  498. self.report_rtmp_download()
  499. video_url_list = [(None, video_info['conn'][0])]
  500. elif 'url_encoded_fmt_stream_map' in video_info and len(video_info['url_encoded_fmt_stream_map']) >= 1:
  501. url_data_strs = video_info['url_encoded_fmt_stream_map'][0].split(',')
  502. url_data = [compat_parse_qs(uds) for uds in url_data_strs]
  503. url_data = [ud for ud in url_data if 'itag' in ud and 'url' in ud]
  504. url_map = dict((ud['itag'][0], ud['url'][0] + '&signature=' + ud['sig'][0] + '&ratebypass=yes') for ud in url_data)
  505. format_limit = self._downloader.params.get('format_limit', None)
  506. available_formats = self._available_formats_prefer_free if self._downloader.params.get('prefer_free_formats', False) else self._available_formats
  507. if format_limit is not None and format_limit in available_formats:
  508. format_list = available_formats[available_formats.index(format_limit):]
  509. else:
  510. format_list = available_formats
  511. existing_formats = [x for x in format_list if x in url_map]
  512. if len(existing_formats) == 0:
  513. self._downloader.report_error(u'no known formats available for video')
  514. return
  515. if self._downloader.params.get('listformats', None):
  516. self._print_formats(existing_formats)
  517. return
  518. if req_format is None or req_format == 'best':
  519. video_url_list = [(existing_formats[0], url_map[existing_formats[0]])] # Best quality
  520. elif req_format == 'worst':
  521. video_url_list = [(existing_formats[len(existing_formats)-1], url_map[existing_formats[len(existing_formats)-1]])] # worst quality
  522. elif req_format in ('-1', 'all'):
  523. video_url_list = [(f, url_map[f]) for f in existing_formats] # All formats
  524. else:
  525. # Specific formats. We pick the first in a slash-delimeted sequence.
  526. # For example, if '1/2/3/4' is requested and '2' and '4' are available, we pick '2'.
  527. req_formats = req_format.split('/')
  528. video_url_list = None
  529. for rf in req_formats:
  530. if rf in url_map:
  531. video_url_list = [(rf, url_map[rf])]
  532. break
  533. if video_url_list is None:
  534. self._downloader.report_error(u'requested format not available')
  535. return
  536. else:
  537. self._downloader.report_error(u'no conn or url_encoded_fmt_stream_map information found in video info')
  538. return
  539. results = []
  540. for format_param, video_real_url in video_url_list:
  541. # Extension
  542. video_extension = self._video_extensions.get(format_param, 'flv')
  543. video_format = '{0} - {1}'.format(format_param if format_param else video_extension,
  544. self._video_dimensions.get(format_param, '???'))
  545. results.append({
  546. 'id': video_id,
  547. 'url': video_real_url,
  548. 'uploader': video_uploader,
  549. 'uploader_id': video_uploader_id,
  550. 'upload_date': upload_date,
  551. 'title': video_title,
  552. 'ext': video_extension,
  553. 'format': video_format,
  554. 'thumbnail': video_thumbnail,
  555. 'description': video_description,
  556. 'player_url': player_url,
  557. 'subtitles': video_subtitles,
  558. 'duration': video_duration
  559. })
  560. return results
  561. class MetacafeIE(InfoExtractor):
  562. """Information Extractor for metacafe.com."""
  563. _VALID_URL = r'(?:http://)?(?:www\.)?metacafe\.com/watch/([^/]+)/([^/]+)/.*'
  564. _DISCLAIMER = 'http://www.metacafe.com/family_filter/'
  565. _FILTER_POST = 'http://www.metacafe.com/f/index.php?inputType=filter&controllerGroup=user'
  566. IE_NAME = u'metacafe'
  567. def __init__(self, downloader=None):
  568. InfoExtractor.__init__(self, downloader)
  569. def report_disclaimer(self):
  570. """Report disclaimer retrieval."""
  571. self._downloader.to_screen(u'[metacafe] Retrieving disclaimer')
  572. def report_age_confirmation(self):
  573. """Report attempt to confirm age."""
  574. self._downloader.to_screen(u'[metacafe] Confirming age')
  575. def report_download_webpage(self, video_id):
  576. """Report webpage download."""
  577. self._downloader.to_screen(u'[metacafe] %s: Downloading webpage' % video_id)
  578. def report_extraction(self, video_id):
  579. """Report information extraction."""
  580. self._downloader.to_screen(u'[metacafe] %s: Extracting information' % video_id)
  581. def _real_initialize(self):
  582. # Retrieve disclaimer
  583. request = compat_urllib_request.Request(self._DISCLAIMER)
  584. try:
  585. self.report_disclaimer()
  586. disclaimer = compat_urllib_request.urlopen(request).read()
  587. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  588. self._downloader.report_error(u'unable to retrieve disclaimer: %s' % compat_str(err))
  589. return
  590. # Confirm age
  591. disclaimer_form = {
  592. 'filters': '0',
  593. 'submit': "Continue - I'm over 18",
  594. }
  595. request = compat_urllib_request.Request(self._FILTER_POST, compat_urllib_parse.urlencode(disclaimer_form))
  596. try:
  597. self.report_age_confirmation()
  598. disclaimer = compat_urllib_request.urlopen(request).read()
  599. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  600. self._downloader.report_error(u'unable to confirm age: %s' % compat_str(err))
  601. return
  602. def _real_extract(self, url):
  603. # Extract id and simplified title from URL
  604. mobj = re.match(self._VALID_URL, url)
  605. if mobj is None:
  606. self._downloader.report_error(u'invalid URL: %s' % url)
  607. return
  608. video_id = mobj.group(1)
  609. # Check if video comes from YouTube
  610. mobj2 = re.match(r'^yt-(.*)$', video_id)
  611. if mobj2 is not None:
  612. self._downloader.download(['http://www.youtube.com/watch?v=%s' % mobj2.group(1)])
  613. return
  614. # Retrieve video webpage to extract further information
  615. request = compat_urllib_request.Request('http://www.metacafe.com/watch/%s/' % video_id)
  616. try:
  617. self.report_download_webpage(video_id)
  618. webpage = compat_urllib_request.urlopen(request).read()
  619. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  620. self._downloader.report_error(u'unable retrieve video webpage: %s' % compat_str(err))
  621. return
  622. # Extract URL, uploader and title from webpage
  623. self.report_extraction(video_id)
  624. mobj = re.search(r'(?m)&mediaURL=([^&]+)', webpage)
  625. if mobj is not None:
  626. mediaURL = compat_urllib_parse.unquote(mobj.group(1))
  627. video_extension = mediaURL[-3:]
  628. # Extract gdaKey if available
  629. mobj = re.search(r'(?m)&gdaKey=(.*?)&', webpage)
  630. if mobj is None:
  631. video_url = mediaURL
  632. else:
  633. gdaKey = mobj.group(1)
  634. video_url = '%s?__gda__=%s' % (mediaURL, gdaKey)
  635. else:
  636. mobj = re.search(r' name="flashvars" value="(.*?)"', webpage)
  637. if mobj is None:
  638. self._downloader.report_error(u'unable to extract media URL')
  639. return
  640. vardict = compat_parse_qs(mobj.group(1))
  641. if 'mediaData' not in vardict:
  642. self._downloader.report_error(u'unable to extract media URL')
  643. return
  644. mobj = re.search(r'"mediaURL":"(http.*?)","key":"(.*?)"', vardict['mediaData'][0])
  645. if mobj is None:
  646. self._downloader.report_error(u'unable to extract media URL')
  647. return
  648. mediaURL = mobj.group(1).replace('\\/', '/')
  649. video_extension = mediaURL[-3:]
  650. video_url = '%s?__gda__=%s' % (mediaURL, mobj.group(2))
  651. mobj = re.search(r'(?im)<title>(.*) - Video</title>', webpage)
  652. if mobj is None:
  653. self._downloader.report_error(u'unable to extract title')
  654. return
  655. video_title = mobj.group(1).decode('utf-8')
  656. mobj = re.search(r'submitter=(.*?);', webpage)
  657. if mobj is None:
  658. self._downloader.report_error(u'unable to extract uploader nickname')
  659. return
  660. video_uploader = mobj.group(1)
  661. return [{
  662. 'id': video_id.decode('utf-8'),
  663. 'url': video_url.decode('utf-8'),
  664. 'uploader': video_uploader.decode('utf-8'),
  665. 'upload_date': None,
  666. 'title': video_title,
  667. 'ext': video_extension.decode('utf-8'),
  668. }]
  669. class DailymotionIE(InfoExtractor):
  670. """Information Extractor for Dailymotion"""
  671. _VALID_URL = r'(?i)(?:https?://)?(?:www\.)?dailymotion\.[a-z]{2,3}/video/([^/]+)'
  672. IE_NAME = u'dailymotion'
  673. _WORKING = False
  674. def __init__(self, downloader=None):
  675. InfoExtractor.__init__(self, downloader)
  676. def report_extraction(self, video_id):
  677. """Report information extraction."""
  678. self._downloader.to_screen(u'[dailymotion] %s: Extracting information' % video_id)
  679. def _real_extract(self, url):
  680. # Extract id and simplified title from URL
  681. mobj = re.match(self._VALID_URL, url)
  682. if mobj is None:
  683. self._downloader.report_error(u'invalid URL: %s' % url)
  684. return
  685. video_id = mobj.group(1).split('_')[0].split('?')[0]
  686. video_extension = 'mp4'
  687. # Retrieve video webpage to extract further information
  688. request = compat_urllib_request.Request(url)
  689. request.add_header('Cookie', 'family_filter=off')
  690. webpage = self._download_webpage(request, video_id)
  691. # Extract URL, uploader and title from webpage
  692. self.report_extraction(video_id)
  693. mobj = re.search(r'\s*var flashvars = (.*)', webpage)
  694. if mobj is None:
  695. self._downloader.report_error(u'unable to extract media URL')
  696. return
  697. flashvars = compat_urllib_parse.unquote(mobj.group(1))
  698. for key in ['hd1080URL', 'hd720URL', 'hqURL', 'sdURL', 'ldURL', 'video_url']:
  699. if key in flashvars:
  700. max_quality = key
  701. self._downloader.to_screen(u'[dailymotion] Using %s' % key)
  702. break
  703. else:
  704. self._downloader.report_error(u'unable to extract video URL')
  705. return
  706. mobj = re.search(r'"' + max_quality + r'":"(.+?)"', flashvars)
  707. if mobj is None:
  708. self._downloader.report_error(u'unable to extract video URL')
  709. return
  710. video_url = compat_urllib_parse.unquote(mobj.group(1)).replace('\\/', '/')
  711. # TODO: support choosing qualities
  712. mobj = re.search(r'<meta property="og:title" content="(?P<title>[^"]*)" />', webpage)
  713. if mobj is None:
  714. self._downloader.report_error(u'unable to extract title')
  715. return
  716. video_title = unescapeHTML(mobj.group('title'))
  717. video_uploader = None
  718. mobj = re.search(r'(?im)<span class="owner[^\"]+?">[^<]+?<a [^>]+?>([^<]+?)</a>', webpage)
  719. if mobj is None:
  720. # lookin for official user
  721. mobj_official = re.search(r'<span rel="author"[^>]+?>([^<]+?)</span>', webpage)
  722. if mobj_official is None:
  723. self._downloader.report_warning(u'unable to extract uploader nickname')
  724. else:
  725. video_uploader = mobj_official.group(1)
  726. else:
  727. video_uploader = mobj.group(1)
  728. video_upload_date = None
  729. mobj = re.search(r'<div class="[^"]*uploaded_cont[^"]*" title="[^"]*">([0-9]{2})-([0-9]{2})-([0-9]{4})</div>', webpage)
  730. if mobj is not None:
  731. video_upload_date = mobj.group(3) + mobj.group(2) + mobj.group(1)
  732. return [{
  733. 'id': video_id,
  734. 'url': video_url,
  735. 'uploader': video_uploader,
  736. 'upload_date': video_upload_date,
  737. 'title': video_title,
  738. 'ext': video_extension,
  739. }]
  740. class PhotobucketIE(InfoExtractor):
  741. """Information extractor for photobucket.com."""
  742. _VALID_URL = r'(?:http://)?(?:[a-z0-9]+\.)?photobucket\.com/.*[\?\&]current=(.*\.flv)'
  743. IE_NAME = u'photobucket'
  744. def __init__(self, downloader=None):
  745. InfoExtractor.__init__(self, downloader)
  746. def report_download_webpage(self, video_id):
  747. """Report webpage download."""
  748. self._downloader.to_screen(u'[photobucket] %s: Downloading webpage' % video_id)
  749. def report_extraction(self, video_id):
  750. """Report information extraction."""
  751. self._downloader.to_screen(u'[photobucket] %s: Extracting information' % video_id)
  752. def _real_extract(self, url):
  753. # Extract id from URL
  754. mobj = re.match(self._VALID_URL, url)
  755. if mobj is None:
  756. self._downloader.report_error(u'Invalid URL: %s' % url)
  757. return
  758. video_id = mobj.group(1)
  759. video_extension = 'flv'
  760. # Retrieve video webpage to extract further information
  761. request = compat_urllib_request.Request(url)
  762. try:
  763. self.report_download_webpage(video_id)
  764. webpage = compat_urllib_request.urlopen(request).read()
  765. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  766. self._downloader.report_error(u'Unable to retrieve video webpage: %s' % compat_str(err))
  767. return
  768. # Extract URL, uploader, and title from webpage
  769. self.report_extraction(video_id)
  770. mobj = re.search(r'<link rel="video_src" href=".*\?file=([^"]+)" />', webpage)
  771. if mobj is None:
  772. self._downloader.report_error(u'unable to extract media URL')
  773. return
  774. mediaURL = compat_urllib_parse.unquote(mobj.group(1))
  775. video_url = mediaURL
  776. mobj = re.search(r'<title>(.*) video by (.*) - Photobucket</title>', webpage)
  777. if mobj is None:
  778. self._downloader.report_error(u'unable to extract title')
  779. return
  780. video_title = mobj.group(1).decode('utf-8')
  781. video_uploader = mobj.group(2).decode('utf-8')
  782. return [{
  783. 'id': video_id.decode('utf-8'),
  784. 'url': video_url.decode('utf-8'),
  785. 'uploader': video_uploader,
  786. 'upload_date': None,
  787. 'title': video_title,
  788. 'ext': video_extension.decode('utf-8'),
  789. }]
  790. class YahooIE(InfoExtractor):
  791. """Information extractor for video.yahoo.com."""
  792. _WORKING = False
  793. # _VALID_URL matches all Yahoo! Video URLs
  794. # _VPAGE_URL matches only the extractable '/watch/' URLs
  795. _VALID_URL = r'(?:http://)?(?:[a-z]+\.)?video\.yahoo\.com/(?:watch|network)/([0-9]+)(?:/|\?v=)([0-9]+)(?:[#\?].*)?'
  796. _VPAGE_URL = r'(?:http://)?video\.yahoo\.com/watch/([0-9]+)/([0-9]+)(?:[#\?].*)?'
  797. IE_NAME = u'video.yahoo'
  798. def __init__(self, downloader=None):
  799. InfoExtractor.__init__(self, downloader)
  800. def report_download_webpage(self, video_id):
  801. """Report webpage download."""
  802. self._downloader.to_screen(u'[video.yahoo] %s: Downloading webpage' % video_id)
  803. def report_extraction(self, video_id):
  804. """Report information extraction."""
  805. self._downloader.to_screen(u'[video.yahoo] %s: Extracting information' % video_id)
  806. def _real_extract(self, url, new_video=True):
  807. # Extract ID from URL
  808. mobj = re.match(self._VALID_URL, url)
  809. if mobj is None:
  810. self._downloader.report_error(u'Invalid URL: %s' % url)
  811. return
  812. video_id = mobj.group(2)
  813. video_extension = 'flv'
  814. # Rewrite valid but non-extractable URLs as
  815. # extractable English language /watch/ URLs
  816. if re.match(self._VPAGE_URL, url) is None:
  817. request = compat_urllib_request.Request(url)
  818. try:
  819. webpage = compat_urllib_request.urlopen(request).read()
  820. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  821. self._downloader.report_error(u'Unable to retrieve video webpage: %s' % compat_str(err))
  822. return
  823. mobj = re.search(r'\("id", "([0-9]+)"\);', webpage)
  824. if mobj is None:
  825. self._downloader.report_error(u'Unable to extract id field')
  826. return
  827. yahoo_id = mobj.group(1)
  828. mobj = re.search(r'\("vid", "([0-9]+)"\);', webpage)
  829. if mobj is None:
  830. self._downloader.report_error(u'Unable to extract vid field')
  831. return
  832. yahoo_vid = mobj.group(1)
  833. url = 'http://video.yahoo.com/watch/%s/%s' % (yahoo_vid, yahoo_id)
  834. return self._real_extract(url, new_video=False)
  835. # Retrieve video webpage to extract further information
  836. request = compat_urllib_request.Request(url)
  837. try:
  838. self.report_download_webpage(video_id)
  839. webpage = compat_urllib_request.urlopen(request).read()
  840. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  841. self._downloader.report_error(u'Unable to retrieve video webpage: %s' % compat_str(err))
  842. return
  843. # Extract uploader and title from webpage
  844. self.report_extraction(video_id)
  845. mobj = re.search(r'<meta name="title" content="(.*)" />', webpage)
  846. if mobj is None:
  847. self._downloader.report_error(u'unable to extract video title')
  848. return
  849. video_title = mobj.group(1).decode('utf-8')
  850. mobj = re.search(r'<h2 class="ti-5"><a href="http://video\.yahoo\.com/(people|profile)/[0-9]+" beacon=".*">(.*)</a></h2>', webpage)
  851. if mobj is None:
  852. self._downloader.report_error(u'unable to extract video uploader')
  853. return
  854. video_uploader = mobj.group(1).decode('utf-8')
  855. # Extract video thumbnail
  856. mobj = re.search(r'<link rel="image_src" href="(.*)" />', webpage)
  857. if mobj is None:
  858. self._downloader.report_error(u'unable to extract video thumbnail')
  859. return
  860. video_thumbnail = mobj.group(1).decode('utf-8')
  861. # Extract video description
  862. mobj = re.search(r'<meta name="description" content="(.*)" />', webpage)
  863. if mobj is None:
  864. self._downloader.report_error(u'unable to extract video description')
  865. return
  866. video_description = mobj.group(1).decode('utf-8')
  867. if not video_description:
  868. video_description = 'No description available.'
  869. # Extract video height and width
  870. mobj = re.search(r'<meta name="video_height" content="([0-9]+)" />', webpage)
  871. if mobj is None:
  872. self._downloader.report_error(u'unable to extract video height')
  873. return
  874. yv_video_height = mobj.group(1)
  875. mobj = re.search(r'<meta name="video_width" content="([0-9]+)" />', webpage)
  876. if mobj is None:
  877. self._downloader.report_error(u'unable to extract video width')
  878. return
  879. yv_video_width = mobj.group(1)
  880. # Retrieve video playlist to extract media URL
  881. # I'm not completely sure what all these options are, but we
  882. # seem to need most of them, otherwise the server sends a 401.
  883. yv_lg = 'R0xx6idZnW2zlrKP8xxAIR' # not sure what this represents
  884. yv_bitrate = '700' # according to Wikipedia this is hard-coded
  885. request = compat_urllib_request.Request('http://cosmos.bcst.yahoo.com/up/yep/process/getPlaylistFOP.php?node_id=' + video_id +
  886. '&tech=flash&mode=playlist&lg=' + yv_lg + '&bitrate=' + yv_bitrate + '&vidH=' + yv_video_height +
  887. '&vidW=' + yv_video_width + '&swf=as3&rd=video.yahoo.com&tk=null&adsupported=v1,v2,&eventid=1301797')
  888. try:
  889. self.report_download_webpage(video_id)
  890. webpage = compat_urllib_request.urlopen(request).read()
  891. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  892. self._downloader.report_error(u'Unable to retrieve video webpage: %s' % compat_str(err))
  893. return
  894. # Extract media URL from playlist XML
  895. mobj = re.search(r'<STREAM APP="(http://.*)" FULLPATH="/?(/.*\.flv\?[^"]*)"', webpage)
  896. if mobj is None:
  897. self._downloader.report_error(u'Unable to extract media URL')
  898. return
  899. video_url = compat_urllib_parse.unquote(mobj.group(1) + mobj.group(2)).decode('utf-8')
  900. video_url = unescapeHTML(video_url)
  901. return [{
  902. 'id': video_id.decode('utf-8'),
  903. 'url': video_url,
  904. 'uploader': video_uploader,
  905. 'upload_date': None,
  906. 'title': video_title,
  907. 'ext': video_extension.decode('utf-8'),
  908. 'thumbnail': video_thumbnail.decode('utf-8'),
  909. 'description': video_description,
  910. }]
  911. class VimeoIE(InfoExtractor):
  912. """Information extractor for vimeo.com."""
  913. # _VALID_URL matches Vimeo URLs
  914. _VALID_URL = r'(?P<proto>https?://)?(?:(?:www|player)\.)?vimeo\.com/(?:(?:groups|album)/[^/]+/)?(?P<direct_link>play_redirect_hls\?clip_id=)?(?:videos?/)?(?P<id>[0-9]+)'
  915. IE_NAME = u'vimeo'
  916. def __init__(self, downloader=None):
  917. InfoExtractor.__init__(self, downloader)
  918. def report_download_webpage(self, video_id):
  919. """Report webpage download."""
  920. self._downloader.to_screen(u'[vimeo] %s: Downloading webpage' % video_id)
  921. def report_extraction(self, video_id):
  922. """Report information extraction."""
  923. self._downloader.to_screen(u'[vimeo] %s: Extracting information' % video_id)
  924. def _real_extract(self, url, new_video=True):
  925. # Extract ID from URL
  926. mobj = re.match(self._VALID_URL, url)
  927. if mobj is None:
  928. self._downloader.report_error(u'Invalid URL: %s' % url)
  929. return
  930. video_id = mobj.group('id')
  931. if not mobj.group('proto'):
  932. url = 'https://' + url
  933. if mobj.group('direct_link'):
  934. url = 'https://vimeo.com/' + video_id
  935. # Retrieve video webpage to extract further information
  936. request = compat_urllib_request.Request(url, None, std_headers)
  937. try:
  938. self.report_download_webpage(video_id)
  939. webpage_bytes = compat_urllib_request.urlopen(request).read()
  940. webpage = webpage_bytes.decode('utf-8')
  941. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  942. self._downloader.report_error(u'Unable to retrieve video webpage: %s' % compat_str(err))
  943. return
  944. # Now we begin extracting as much information as we can from what we
  945. # retrieved. First we extract the information common to all extractors,
  946. # and latter we extract those that are Vimeo specific.
  947. self.report_extraction(video_id)
  948. # Extract the config JSON
  949. try:
  950. config = webpage.split(' = {config:')[1].split(',assets:')[0]
  951. config = json.loads(config)
  952. except:
  953. self._downloader.report_error(u'unable to extract info section')
  954. return
  955. # Extract title
  956. video_title = config["video"]["title"]
  957. # Extract uploader and uploader_id
  958. video_uploader = config["video"]["owner"]["name"]
  959. video_uploader_id = config["video"]["owner"]["url"].split('/')[-1]
  960. # Extract video thumbnail
  961. video_thumbnail = config["video"]["thumbnail"]
  962. # Extract video description
  963. video_description = get_element_by_attribute("itemprop", "description", webpage)
  964. if video_description: video_description = clean_html(video_description)
  965. else: video_description = u''
  966. # Extract upload date
  967. video_upload_date = None
  968. mobj = re.search(r'<meta itemprop="dateCreated" content="(\d{4})-(\d{2})-(\d{2})T', webpage)
  969. if mobj is not None:
  970. video_upload_date = mobj.group(1) + mobj.group(2) + mobj.group(3)
  971. # Vimeo specific: extract request signature and timestamp
  972. sig = config['request']['signature']
  973. timestamp = config['request']['timestamp']
  974. # Vimeo specific: extract video codec and quality information
  975. # First consider quality, then codecs, then take everything
  976. # TODO bind to format param
  977. codecs = [('h264', 'mp4'), ('vp8', 'flv'), ('vp6', 'flv')]
  978. files = { 'hd': [], 'sd': [], 'other': []}
  979. for codec_name, codec_extension in codecs:
  980. if codec_name in config["video"]["files"]:
  981. if 'hd' in config["video"]["files"][codec_name]:
  982. files['hd'].append((codec_name, codec_extension, 'hd'))
  983. elif 'sd' in config["video"]["files"][codec_name]:
  984. files['sd'].append((codec_name, codec_extension, 'sd'))
  985. else:
  986. files['other'].append((codec_name, codec_extension, config["video"]["files"][codec_name][0]))
  987. for quality in ('hd', 'sd', 'other'):
  988. if len(files[quality]) > 0:
  989. video_quality = files[quality][0][2]
  990. video_codec = files[quality][0][0]
  991. video_extension = files[quality][0][1]
  992. self._downloader.to_screen(u'[vimeo] %s: Downloading %s file at %s quality' % (video_id, video_codec.upper(), video_quality))
  993. break
  994. else:
  995. self._downloader.report_error(u'no known codec found')
  996. return
  997. video_url = "http://player.vimeo.com/play_redirect?clip_id=%s&sig=%s&time=%s&quality=%s&codecs=%s&type=moogaloop_local&embed_location=" \
  998. %(video_id, sig, timestamp, video_quality, video_codec.upper())
  999. return [{
  1000. 'id': video_id,
  1001. 'url': video_url,
  1002. 'uploader': video_uploader,
  1003. 'uploader_id': video_uploader_id,
  1004. 'upload_date': video_upload_date,
  1005. 'title': video_title,
  1006. 'ext': video_extension,
  1007. 'thumbnail': video_thumbnail,
  1008. 'description': video_description,
  1009. }]
  1010. class ArteTvIE(InfoExtractor):
  1011. """arte.tv information extractor."""
  1012. _VALID_URL = r'(?:http://)?videos\.arte\.tv/(?:fr|de)/videos/.*'
  1013. _LIVE_URL = r'index-[0-9]+\.html$'
  1014. IE_NAME = u'arte.tv'
  1015. def __init__(self, downloader=None):
  1016. InfoExtractor.__init__(self, downloader)
  1017. def report_download_webpage(self, video_id):
  1018. """Report webpage download."""
  1019. self._downloader.to_screen(u'[arte.tv] %s: Downloading webpage' % video_id)
  1020. def report_extraction(self, video_id):
  1021. """Report information extraction."""
  1022. self._downloader.to_screen(u'[arte.tv] %s: Extracting information' % video_id)
  1023. def fetch_webpage(self, url):
  1024. request = compat_urllib_request.Request(url)
  1025. try:
  1026. self.report_download_webpage(url)
  1027. webpage = compat_urllib_request.urlopen(request).read()
  1028. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1029. self._downloader.report_error(u'Unable to retrieve video webpage: %s' % compat_str(err))
  1030. return
  1031. except ValueError as err:
  1032. self._downloader.report_error(u'Invalid URL: %s' % url)
  1033. return
  1034. return webpage
  1035. def grep_webpage(self, url, regex, regexFlags, matchTuples):
  1036. page = self.fetch_webpage(url)
  1037. mobj = re.search(regex, page, regexFlags)
  1038. info = {}
  1039. if mobj is None:
  1040. self._downloader.report_error(u'Invalid URL: %s' % url)
  1041. return
  1042. for (i, key, err) in matchTuples:
  1043. if mobj.group(i) is None:
  1044. self._downloader.trouble(err)
  1045. return
  1046. else:
  1047. info[key] = mobj.group(i)
  1048. return info
  1049. def extractLiveStream(self, url):
  1050. video_lang = url.split('/')[-4]
  1051. info = self.grep_webpage(
  1052. url,
  1053. r'src="(.*?/videothek_js.*?\.js)',
  1054. 0,
  1055. [
  1056. (1, 'url', u'ERROR: Invalid URL: %s' % url)
  1057. ]
  1058. )
  1059. http_host = url.split('/')[2]
  1060. next_url = 'http://%s%s' % (http_host, compat_urllib_parse.unquote(info.get('url')))
  1061. info = self.grep_webpage(
  1062. next_url,
  1063. r'(s_artestras_scst_geoFRDE_' + video_lang + '.*?)\'.*?' +
  1064. '(http://.*?\.swf).*?' +
  1065. '(rtmp://.*?)\'',
  1066. re.DOTALL,
  1067. [
  1068. (1, 'path', u'ERROR: could not extract video path: %s' % url),
  1069. (2, 'player', u'ERROR: could not extract video player: %s' % url),
  1070. (3, 'url', u'ERROR: could not extract video url: %s' % url)
  1071. ]
  1072. )
  1073. video_url = u'%s/%s' % (info.get('url'), info.get('path'))
  1074. def extractPlus7Stream(self, url):
  1075. video_lang = url.split('/')[-3]
  1076. info = self.grep_webpage(
  1077. url,
  1078. r'param name="movie".*?videorefFileUrl=(http[^\'"&]*)',
  1079. 0,
  1080. [
  1081. (1, 'url', u'ERROR: Invalid URL: %s' % url)
  1082. ]
  1083. )
  1084. next_url = compat_urllib_parse.unquote(info.get('url'))
  1085. info = self.grep_webpage(
  1086. next_url,
  1087. r'<video lang="%s" ref="(http[^\'"&]*)' % video_lang,
  1088. 0,
  1089. [
  1090. (1, 'url', u'ERROR: Could not find <video> tag: %s' % url)
  1091. ]
  1092. )
  1093. next_url = compat_urllib_parse.unquote(info.get('url'))
  1094. info = self.grep_webpage(
  1095. next_url,
  1096. r'<video id="(.*?)".*?>.*?' +
  1097. '<name>(.*?)</name>.*?' +
  1098. '<dateVideo>(.*?)</dateVideo>.*?' +
  1099. '<url quality="hd">(.*?)</url>',
  1100. re.DOTALL,
  1101. [
  1102. (1, 'id', u'ERROR: could not extract video id: %s' % url),
  1103. (2, 'title', u'ERROR: could not extract video title: %s' % url),
  1104. (3, 'date', u'ERROR: could not extract video date: %s' % url),
  1105. (4, 'url', u'ERROR: could not extract video url: %s' % url)
  1106. ]
  1107. )
  1108. return {
  1109. 'id': info.get('id'),
  1110. 'url': compat_urllib_parse.unquote(info.get('url')),
  1111. 'uploader': u'arte.tv',
  1112. 'upload_date': info.get('date'),
  1113. 'title': info.get('title').decode('utf-8'),
  1114. 'ext': u'mp4',
  1115. 'format': u'NA',
  1116. 'player_url': None,
  1117. }
  1118. def _real_extract(self, url):
  1119. video_id = url.split('/')[-1]
  1120. self.report_extraction(video_id)
  1121. if re.search(self._LIVE_URL, video_id) is not None:
  1122. self.extractLiveStream(url)
  1123. return
  1124. else:
  1125. info = self.extractPlus7Stream(url)
  1126. return [info]
  1127. class GenericIE(InfoExtractor):
  1128. """Generic last-resort information extractor."""
  1129. _VALID_URL = r'.*'
  1130. IE_NAME = u'generic'
  1131. def __init__(self, downloader=None):
  1132. InfoExtractor.__init__(self, downloader)
  1133. def report_download_webpage(self, video_id):
  1134. """Report webpage download."""
  1135. if not self._downloader.params.get('test', False):
  1136. self._downloader.to_screen(u'WARNING: Falling back on generic information extractor.')
  1137. self._downloader.to_screen(u'[generic] %s: Downloading webpage' % video_id)
  1138. def report_extraction(self, video_id):
  1139. """Report information extraction."""
  1140. self._downloader.to_screen(u'[generic] %s: Extracting information' % video_id)
  1141. def report_following_redirect(self, new_url):
  1142. """Report information extraction."""
  1143. self._downloader.to_screen(u'[redirect] Following redirect to %s' % new_url)
  1144. def _test_redirect(self, url):
  1145. """Check if it is a redirect, like url shorteners, in case restart chain."""
  1146. class HeadRequest(compat_urllib_request.Request):
  1147. def get_method(self):
  1148. return "HEAD"
  1149. class HEADRedirectHandler(compat_urllib_request.HTTPRedirectHandler):
  1150. """
  1151. Subclass the HTTPRedirectHandler to make it use our
  1152. HeadRequest also on the redirected URL
  1153. """
  1154. def redirect_request(self, req, fp, code, msg, headers, newurl):
  1155. if code in (301, 302, 303, 307):
  1156. newurl = newurl.replace(' ', '%20')
  1157. newheaders = dict((k,v) for k,v in req.headers.items()
  1158. if k.lower() not in ("content-length", "content-type"))
  1159. return HeadRequest(newurl,
  1160. headers=newheaders,
  1161. origin_req_host=req.get_origin_req_host(),
  1162. unverifiable=True)
  1163. else:
  1164. raise compat_urllib_error.HTTPError(req.get_full_url(), code, msg, headers, fp)
  1165. class HTTPMethodFallback(compat_urllib_request.BaseHandler):
  1166. """
  1167. Fallback to GET if HEAD is not allowed (405 HTTP error)
  1168. """
  1169. def http_error_405(self, req, fp, code, msg, headers):
  1170. fp.read()
  1171. fp.close()
  1172. newheaders = dict((k,v) for k,v in req.headers.items()
  1173. if k.lower() not in ("content-length", "content-type"))
  1174. return self.parent.open(compat_urllib_request.Request(req.get_full_url(),
  1175. headers=newheaders,
  1176. origin_req_host=req.get_origin_req_host(),
  1177. unverifiable=True))
  1178. # Build our opener
  1179. opener = compat_urllib_request.OpenerDirector()
  1180. for handler in [compat_urllib_request.HTTPHandler, compat_urllib_request.HTTPDefaultErrorHandler,
  1181. HTTPMethodFallback, HEADRedirectHandler,
  1182. compat_urllib_request.HTTPErrorProcessor, compat_urllib_request.HTTPSHandler]:
  1183. opener.add_handler(handler())
  1184. response = opener.open(HeadRequest(url))
  1185. new_url = response.geturl()
  1186. if url == new_url:
  1187. return False
  1188. self.report_following_redirect(new_url)
  1189. self._downloader.download([new_url])
  1190. return True
  1191. def _real_extract(self, url):
  1192. if self._test_redirect(url): return
  1193. video_id = url.split('/')[-1]
  1194. try:
  1195. webpage = self._download_webpage(url, video_id)
  1196. except ValueError as err:
  1197. # since this is the last-resort InfoExtractor, if
  1198. # this error is thrown, it'll be thrown here
  1199. self._downloader.report_error(u'Invalid URL: %s' % url)
  1200. return
  1201. self.report_extraction(video_id)
  1202. # Start with something easy: JW Player in SWFObject
  1203. mobj = re.search(r'flashvars: [\'"](?:.*&)?file=(http[^\'"&]*)', webpage)
  1204. if mobj is None:
  1205. # Broaden the search a little bit
  1206. mobj = re.search(r'[^A-Za-z0-9]?(?:file|source)=(http[^\'"&]*)', webpage)
  1207. if mobj is None:
  1208. # Broaden the search a little bit: JWPlayer JS loader
  1209. mobj = re.search(r'[^A-Za-z0-9]?file:\s*["\'](http[^\'"&]*)', webpage)
  1210. if mobj is None:
  1211. self._downloader.report_error(u'Invalid URL: %s' % url)
  1212. return
  1213. # It's possible that one of the regexes
  1214. # matched, but returned an empty group:
  1215. if mobj.group(1) is None:
  1216. self._downloader.report_error(u'Invalid URL: %s' % url)
  1217. return
  1218. video_url = compat_urllib_parse.unquote(mobj.group(1))
  1219. video_id = os.path.basename(video_url)
  1220. # here's a fun little line of code for you:
  1221. video_extension = os.path.splitext(video_id)[1][1:]
  1222. video_id = os.path.splitext(video_id)[0]
  1223. # it's tempting to parse this further, but you would
  1224. # have to take into account all the variations like
  1225. # Video Title - Site Name
  1226. # Site Name | Video Title
  1227. # Video Title - Tagline | Site Name
  1228. # and so on and so forth; it's just not practical
  1229. mobj = re.search(r'<title>(.*)</title>', webpage)
  1230. if mobj is None:
  1231. self._downloader.report_error(u'unable to extract title')
  1232. return
  1233. video_title = mobj.group(1)
  1234. # video uploader is domain name
  1235. mobj = re.match(r'(?:https?://)?([^/]*)/.*', url)
  1236. if mobj is None:
  1237. self._downloader.report_error(u'unable to extract title')
  1238. return
  1239. video_uploader = mobj.group(1)
  1240. return [{
  1241. 'id': video_id,
  1242. 'url': video_url,
  1243. 'uploader': video_uploader,
  1244. 'upload_date': None,
  1245. 'title': video_title,
  1246. 'ext': video_extension,
  1247. }]
  1248. class YoutubeSearchIE(InfoExtractor):
  1249. """Information Extractor for YouTube search queries."""
  1250. _VALID_URL = r'ytsearch(\d+|all)?:[\s\S]+'
  1251. _API_URL = 'https://gdata.youtube.com/feeds/api/videos?q=%s&start-index=%i&max-results=50&v=2&alt=jsonc'
  1252. _max_youtube_results = 1000
  1253. IE_NAME = u'youtube:search'
  1254. def __init__(self, downloader=None):
  1255. InfoExtractor.__init__(self, downloader)
  1256. def report_download_page(self, query, pagenum):
  1257. """Report attempt to download search page with given number."""
  1258. query = query.decode(preferredencoding())
  1259. self._downloader.to_screen(u'[youtube] query "%s": Downloading page %s' % (query, pagenum))
  1260. def _real_extract(self, query):
  1261. mobj = re.match(self._VALID_URL, query)
  1262. if mobj is None:
  1263. self._downloader.report_error(u'invalid search query "%s"' % query)
  1264. return
  1265. prefix, query = query.split(':')
  1266. prefix = prefix[8:]
  1267. query = query.encode('utf-8')
  1268. if prefix == '':
  1269. self._download_n_results(query, 1)
  1270. return
  1271. elif prefix == 'all':
  1272. self._download_n_results(query, self._max_youtube_results)
  1273. return
  1274. else:
  1275. try:
  1276. n = int(prefix)
  1277. if n <= 0:
  1278. self._downloader.report_error(u'invalid download number %s for query "%s"' % (n, query))
  1279. return
  1280. elif n > self._max_youtube_results:
  1281. self._downloader.report_warning(u'ytsearch returns max %i results (you requested %i)' % (self._max_youtube_results, n))
  1282. n = self._max_youtube_results
  1283. self._download_n_results(query, n)
  1284. return
  1285. except ValueError: # parsing prefix as integer fails
  1286. self._download_n_results(query, 1)
  1287. return
  1288. def _download_n_results(self, query, n):
  1289. """Downloads a specified number of results for a query"""
  1290. video_ids = []
  1291. pagenum = 0
  1292. limit = n
  1293. while (50 * pagenum) < limit:
  1294. self.report_download_page(query, pagenum+1)
  1295. result_url = self._API_URL % (compat_urllib_parse.quote_plus(query), (50*pagenum)+1)
  1296. request = compat_urllib_request.Request(result_url)
  1297. try:
  1298. data = compat_urllib_request.urlopen(request).read().decode('utf-8')
  1299. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1300. self._downloader.report_error(u'unable to download API page: %s' % compat_str(err))
  1301. return
  1302. api_response = json.loads(data)['data']
  1303. if not 'items' in api_response:
  1304. self._downloader.trouble(u'[youtube] No video results')
  1305. return
  1306. new_ids = list(video['id'] for video in api_response['items'])
  1307. video_ids += new_ids
  1308. limit = min(n, api_response['totalItems'])
  1309. pagenum += 1
  1310. if len(video_ids) > n:
  1311. video_ids = video_ids[:n]
  1312. for id in video_ids:
  1313. self._downloader.download(['http://www.youtube.com/watch?v=%s' % id])
  1314. return
  1315. class GoogleSearchIE(InfoExtractor):
  1316. """Information Extractor for Google Video search queries."""
  1317. _VALID_URL = r'gvsearch(\d+|all)?:[\s\S]+'
  1318. _TEMPLATE_URL = 'http://video.google.com/videosearch?q=%s+site:video.google.com&start=%s&hl=en'
  1319. _VIDEO_INDICATOR = r'<a href="http://video\.google\.com/videoplay\?docid=([^"\&]+)'
  1320. _MORE_PAGES_INDICATOR = r'class="pn" id="pnnext"'
  1321. _max_google_results = 1000
  1322. IE_NAME = u'video.google:search'
  1323. def __init__(self, downloader=None):
  1324. InfoExtractor.__init__(self, downloader)
  1325. def report_download_page(self, query, pagenum):
  1326. """Report attempt to download playlist page with given number."""
  1327. query = query.decode(preferredencoding())
  1328. self._downloader.to_screen(u'[video.google] query "%s": Downloading page %s' % (query, pagenum))
  1329. def _real_extract(self, query):
  1330. mobj = re.match(self._VALID_URL, query)
  1331. if mobj is None:
  1332. self._downloader.report_error(u'invalid search query "%s"' % query)
  1333. return
  1334. prefix, query = query.split(':')
  1335. prefix = prefix[8:]
  1336. query = query.encode('utf-8')
  1337. if prefix == '':
  1338. self._download_n_results(query, 1)
  1339. return
  1340. elif prefix == 'all':
  1341. self._download_n_results(query, self._max_google_results)
  1342. return
  1343. else:
  1344. try:
  1345. n = int(prefix)
  1346. if n <= 0:
  1347. self._downloader.report_error(u'invalid download number %s for query "%s"' % (n, query))
  1348. return
  1349. elif n > self._max_google_results:
  1350. self._downloader.report_warning(u'gvsearch returns max %i results (you requested %i)' % (self._max_google_results, n))
  1351. n = self._max_google_results
  1352. self._download_n_results(query, n)
  1353. return
  1354. except ValueError: # parsing prefix as integer fails
  1355. self._download_n_results(query, 1)
  1356. return
  1357. def _download_n_results(self, query, n):
  1358. """Downloads a specified number of results for a query"""
  1359. video_ids = []
  1360. pagenum = 0
  1361. while True:
  1362. self.report_download_page(query, pagenum)
  1363. result_url = self._TEMPLATE_URL % (compat_urllib_parse.quote_plus(query), pagenum*10)
  1364. request = compat_urllib_request.Request(result_url)
  1365. try:
  1366. page = compat_urllib_request.urlopen(request).read()
  1367. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1368. self._downloader.report_error(u'unable to download webpage: %s' % compat_str(err))
  1369. return
  1370. # Extract video identifiers
  1371. for mobj in re.finditer(self._VIDEO_INDICATOR, page):
  1372. video_id = mobj.group(1)
  1373. if video_id not in video_ids:
  1374. video_ids.append(video_id)
  1375. if len(video_ids) == n:
  1376. # Specified n videos reached
  1377. for id in video_ids:
  1378. self._downloader.download(['http://video.google.com/videoplay?docid=%s' % id])
  1379. return
  1380. if re.search(self._MORE_PAGES_INDICATOR, page) is None:
  1381. for id in video_ids:
  1382. self._downloader.download(['http://video.google.com/videoplay?docid=%s' % id])
  1383. return
  1384. pagenum = pagenum + 1
  1385. class YahooSearchIE(InfoExtractor):
  1386. """Information Extractor for Yahoo! Video search queries."""
  1387. _WORKING = False
  1388. _VALID_URL = r'yvsearch(\d+|all)?:[\s\S]+'
  1389. _TEMPLATE_URL = 'http://video.yahoo.com/search/?p=%s&o=%s'
  1390. _VIDEO_INDICATOR = r'href="http://video\.yahoo\.com/watch/([0-9]+/[0-9]+)"'
  1391. _MORE_PAGES_INDICATOR = r'\s*Next'
  1392. _max_yahoo_results = 1000
  1393. IE_NAME = u'video.yahoo:search'
  1394. def __init__(self, downloader=None):
  1395. InfoExtractor.__init__(self, downloader)
  1396. def report_download_page(self, query, pagenum):
  1397. """Report attempt to download playlist page with given number."""
  1398. query = query.decode(preferredencoding())
  1399. self._downloader.to_screen(u'[video.yahoo] query "%s": Downloading page %s' % (query, pagenum))
  1400. def _real_extract(self, query):
  1401. mobj = re.match(self._VALID_URL, query)
  1402. if mobj is None:
  1403. self._downloader.report_error(u'invalid search query "%s"' % query)
  1404. return
  1405. prefix, query = query.split(':')
  1406. prefix = prefix[8:]
  1407. query = query.encode('utf-8')
  1408. if prefix == '':
  1409. self._download_n_results(query, 1)
  1410. return
  1411. elif prefix == 'all':
  1412. self._download_n_results(query, self._max_yahoo_results)
  1413. return
  1414. else:
  1415. try:
  1416. n = int(prefix)
  1417. if n <= 0:
  1418. self._downloader.report_error(u'invalid download number %s for query "%s"' % (n, query))
  1419. return
  1420. elif n > self._max_yahoo_results:
  1421. self._downloader.report_warning(u'yvsearch returns max %i results (you requested %i)' % (self._max_yahoo_results, n))
  1422. n = self._max_yahoo_results
  1423. self._download_n_results(query, n)
  1424. return
  1425. except ValueError: # parsing prefix as integer fails
  1426. self._download_n_results(query, 1)
  1427. return
  1428. def _download_n_results(self, query, n):
  1429. """Downloads a specified number of results for a query"""
  1430. video_ids = []
  1431. already_seen = set()
  1432. pagenum = 1
  1433. while True:
  1434. self.report_download_page(query, pagenum)
  1435. result_url = self._TEMPLATE_URL % (compat_urllib_parse.quote_plus(query), pagenum)
  1436. request = compat_urllib_request.Request(result_url)
  1437. try:
  1438. page = compat_urllib_request.urlopen(request).read()
  1439. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1440. self._downloader.report_error(u'unable to download webpage: %s' % compat_str(err))
  1441. return
  1442. # Extract video identifiers
  1443. for mobj in re.finditer(self._VIDEO_INDICATOR, page):
  1444. video_id = mobj.group(1)
  1445. if video_id not in already_seen:
  1446. video_ids.append(video_id)
  1447. already_seen.add(video_id)
  1448. if len(video_ids) == n:
  1449. # Specified n videos reached
  1450. for id in video_ids:
  1451. self._downloader.download(['http://video.yahoo.com/watch/%s' % id])
  1452. return
  1453. if re.search(self._MORE_PAGES_INDICATOR, page) is None:
  1454. for id in video_ids:
  1455. self._downloader.download(['http://video.yahoo.com/watch/%s' % id])
  1456. return
  1457. pagenum = pagenum + 1
  1458. class YoutubePlaylistIE(InfoExtractor):
  1459. """Information Extractor for YouTube playlists."""
  1460. _VALID_URL = r"""(?:
  1461. (?:https?://)?
  1462. (?:\w+\.)?
  1463. youtube\.com/
  1464. (?:
  1465. (?:course|view_play_list|my_playlists|artist|playlist|watch)
  1466. \? (?:.*?&)*? (?:p|a|list)=
  1467. | p/
  1468. )
  1469. ((?:PL|EC|UU)?[0-9A-Za-z-_]{10,})
  1470. .*
  1471. |
  1472. ((?:PL|EC|UU)[0-9A-Za-z-_]{10,})
  1473. )"""
  1474. _TEMPLATE_URL = 'https://gdata.youtube.com/feeds/api/playlists/%s?max-results=%i&start-index=%i&v=2&alt=json'
  1475. _MAX_RESULTS = 50
  1476. IE_NAME = u'youtube:playlist'
  1477. def __init__(self, downloader=None):
  1478. InfoExtractor.__init__(self, downloader)
  1479. @classmethod
  1480. def suitable(cls, url):
  1481. """Receives a URL and returns True if suitable for this IE."""
  1482. return re.match(cls._VALID_URL, url, re.VERBOSE) is not None
  1483. def report_download_page(self, playlist_id, pagenum):
  1484. """Report attempt to download playlist page with given number."""
  1485. self._downloader.to_screen(u'[youtube] PL %s: Downloading page #%s' % (playlist_id, pagenum))
  1486. def _real_extract(self, url):
  1487. # Extract playlist id
  1488. mobj = re.match(self._VALID_URL, url, re.VERBOSE)
  1489. if mobj is None:
  1490. self._downloader.report_error(u'invalid url: %s' % url)
  1491. return
  1492. # Download playlist videos from API
  1493. playlist_id = mobj.group(1) or mobj.group(2)
  1494. page_num = 1
  1495. videos = []
  1496. while True:
  1497. self.report_download_page(playlist_id, page_num)
  1498. url = self._TEMPLATE_URL % (playlist_id, self._MAX_RESULTS, self._MAX_RESULTS * (page_num - 1) + 1)
  1499. try:
  1500. page = compat_urllib_request.urlopen(url).read().decode('utf8')
  1501. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1502. self._downloader.report_error(u'unable to download webpage: %s' % compat_str(err))
  1503. return
  1504. try:
  1505. response = json.loads(page)
  1506. except ValueError as err:
  1507. self._downloader.report_error(u'Invalid JSON in API response: ' + compat_str(err))
  1508. return
  1509. if not 'feed' in response or not 'entry' in response['feed']:
  1510. self._downloader.report_error(u'Got a malformed response from YouTube API')
  1511. return
  1512. videos += [ (entry['yt$position']['$t'], entry['content']['src'])
  1513. for entry in response['feed']['entry']
  1514. if 'content' in entry ]
  1515. if len(response['feed']['entry']) < self._MAX_RESULTS:
  1516. break
  1517. page_num += 1
  1518. videos = [v[1] for v in sorted(videos)]
  1519. total = len(videos)
  1520. playliststart = self._downloader.params.get('playliststart', 1) - 1
  1521. playlistend = self._downloader.params.get('playlistend', -1)
  1522. if playlistend == -1:
  1523. videos = videos[playliststart:]
  1524. else:
  1525. videos = videos[playliststart:playlistend]
  1526. if len(videos) == total:
  1527. self._downloader.to_screen(u'[youtube] PL %s: Found %i videos' % (playlist_id, total))
  1528. else:
  1529. self._downloader.to_screen(u'[youtube] PL %s: Found %i videos, downloading %i' % (playlist_id, total, len(videos)))
  1530. for video in videos:
  1531. self._downloader.download([video])
  1532. return
  1533. class YoutubeChannelIE(InfoExtractor):
  1534. """Information Extractor for YouTube channels."""
  1535. _VALID_URL = r"^(?:https?://)?(?:youtu\.be|(?:\w+\.)?youtube(?:-nocookie)?\.com)/channel/([0-9A-Za-z_-]+)(?:/.*)?$"
  1536. _TEMPLATE_URL = 'http://www.youtube.com/channel/%s/videos?sort=da&flow=list&view=0&page=%s&gl=US&hl=en'
  1537. _MORE_PAGES_INDICATOR = u"Next \N{RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK}"
  1538. IE_NAME = u'youtube:channel'
  1539. def report_download_page(self, channel_id, pagenum):
  1540. """Report attempt to download channel page with given number."""
  1541. self._downloader.to_screen(u'[youtube] Channel %s: Downloading page #%s' % (channel_id, pagenum))
  1542. def _real_extract(self, url):
  1543. # Extract channel id
  1544. mobj = re.match(self._VALID_URL, url)
  1545. if mobj is None:
  1546. self._downloader.report_error(u'invalid url: %s' % url)
  1547. return
  1548. # Download channel pages
  1549. channel_id = mobj.group(1)
  1550. video_ids = []
  1551. pagenum = 1
  1552. while True:
  1553. self.report_download_page(channel_id, pagenum)
  1554. url = self._TEMPLATE_URL % (channel_id, pagenum)
  1555. request = compat_urllib_request.Request(url)
  1556. try:
  1557. page = compat_urllib_request.urlopen(request).read().decode('utf8')
  1558. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1559. self._downloader.report_error(u'unable to download webpage: %s' % compat_str(err))
  1560. return
  1561. # Extract video identifiers
  1562. ids_in_page = []
  1563. for mobj in re.finditer(r'href="/watch\?v=([0-9A-Za-z_-]+)&', page):
  1564. if mobj.group(1) not in ids_in_page:
  1565. ids_in_page.append(mobj.group(1))
  1566. video_ids.extend(ids_in_page)
  1567. if self._MORE_PAGES_INDICATOR not in page:
  1568. break
  1569. pagenum = pagenum + 1
  1570. self._downloader.to_screen(u'[youtube] Channel %s: Found %i videos' % (channel_id, len(video_ids)))
  1571. for id in video_ids:
  1572. self._downloader.download(['http://www.youtube.com/watch?v=%s' % id])
  1573. return
  1574. class YoutubeUserIE(InfoExtractor):
  1575. """Information Extractor for YouTube users."""
  1576. _VALID_URL = r'(?:(?:(?:https?://)?(?:\w+\.)?youtube\.com/user/)|ytuser:)([A-Za-z0-9_-]+)'
  1577. _TEMPLATE_URL = 'http://gdata.youtube.com/feeds/api/users/%s'
  1578. _GDATA_PAGE_SIZE = 50
  1579. _GDATA_URL = 'http://gdata.youtube.com/feeds/api/users/%s/uploads?max-results=%d&start-index=%d'
  1580. _VIDEO_INDICATOR = r'/watch\?v=(.+?)[\<&]'
  1581. IE_NAME = u'youtube:user'
  1582. def __init__(self, downloader=None):
  1583. InfoExtractor.__init__(self, downloader)
  1584. def report_download_page(self, username, start_index):
  1585. """Report attempt to download user page."""
  1586. self._downloader.to_screen(u'[youtube] user %s: Downloading video ids from %d to %d' %
  1587. (username, start_index, start_index + self._GDATA_PAGE_SIZE))
  1588. def _real_extract(self, url):
  1589. # Extract username
  1590. mobj = re.match(self._VALID_URL, url)
  1591. if mobj is None:
  1592. self._downloader.report_error(u'invalid url: %s' % url)
  1593. return
  1594. username = mobj.group(1)
  1595. # Download video ids using YouTube Data API. Result size per
  1596. # query is limited (currently to 50 videos) so we need to query
  1597. # page by page until there are no video ids - it means we got
  1598. # all of them.
  1599. video_ids = []
  1600. pagenum = 0
  1601. while True:
  1602. start_index = pagenum * self._GDATA_PAGE_SIZE + 1
  1603. self.report_download_page(username, start_index)
  1604. request = compat_urllib_request.Request(self._GDATA_URL % (username, self._GDATA_PAGE_SIZE, start_index))
  1605. try:
  1606. page = compat_urllib_request.urlopen(request).read().decode('utf-8')
  1607. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1608. self._downloader.report_error(u'unable to download webpage: %s' % compat_str(err))
  1609. return
  1610. # Extract video identifiers
  1611. ids_in_page = []
  1612. for mobj in re.finditer(self._VIDEO_INDICATOR, page):
  1613. if mobj.group(1) not in ids_in_page:
  1614. ids_in_page.append(mobj.group(1))
  1615. video_ids.extend(ids_in_page)
  1616. # A little optimization - if current page is not
  1617. # "full", ie. does not contain PAGE_SIZE video ids then
  1618. # we can assume that this page is the last one - there
  1619. # are no more ids on further pages - no need to query
  1620. # again.
  1621. if len(ids_in_page) < self._GDATA_PAGE_SIZE:
  1622. break
  1623. pagenum += 1
  1624. all_ids_count = len(video_ids)
  1625. playliststart = self._downloader.params.get('playliststart', 1) - 1
  1626. playlistend = self._downloader.params.get('playlistend', -1)
  1627. if playlistend == -1:
  1628. video_ids = video_ids[playliststart:]
  1629. else:
  1630. video_ids = video_ids[playliststart:playlistend]
  1631. self._downloader.to_screen(u"[youtube] user %s: Collected %d video ids (downloading %d of them)" %
  1632. (username, all_ids_count, len(video_ids)))
  1633. for video_id in video_ids:
  1634. self._downloader.download(['http://www.youtube.com/watch?v=%s' % video_id])
  1635. class BlipTVUserIE(InfoExtractor):
  1636. """Information Extractor for blip.tv users."""
  1637. _VALID_URL = r'(?:(?:(?:https?://)?(?:\w+\.)?blip\.tv/)|bliptvuser:)([^/]+)/*$'
  1638. _PAGE_SIZE = 12
  1639. IE_NAME = u'blip.tv:user'
  1640. def __init__(self, downloader=None):
  1641. InfoExtractor.__init__(self, downloader)
  1642. def report_download_page(self, username, pagenum):
  1643. """Report attempt to download user page."""
  1644. self._downloader.to_screen(u'[%s] user %s: Downloading video ids from page %d' %
  1645. (self.IE_NAME, username, pagenum))
  1646. def _real_extract(self, url):
  1647. # Extract username
  1648. mobj = re.match(self._VALID_URL, url)
  1649. if mobj is None:
  1650. self._downloader.report_error(u'invalid url: %s' % url)
  1651. return
  1652. username = mobj.group(1)
  1653. page_base = 'http://m.blip.tv/pr/show_get_full_episode_list?users_id=%s&lite=0&esi=1'
  1654. request = compat_urllib_request.Request(url)
  1655. try:
  1656. page = compat_urllib_request.urlopen(request).read().decode('utf-8')
  1657. mobj = re.search(r'data-users-id="([^"]+)"', page)
  1658. page_base = page_base % mobj.group(1)
  1659. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1660. self._downloader.report_error(u'unable to download webpage: %s' % compat_str(err))
  1661. return
  1662. # Download video ids using BlipTV Ajax calls. Result size per
  1663. # query is limited (currently to 12 videos) so we need to query
  1664. # page by page until there are no video ids - it means we got
  1665. # all of them.
  1666. video_ids = []
  1667. pagenum = 1
  1668. while True:
  1669. self.report_download_page(username, pagenum)
  1670. url = page_base + "&page=" + str(pagenum)
  1671. request = compat_urllib_request.Request( url )
  1672. try:
  1673. page = compat_urllib_request.urlopen(request).read().decode('utf-8')
  1674. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1675. self._downloader.report_error(u'unable to download webpage: %s' % str(err))
  1676. return
  1677. # Extract video identifiers
  1678. ids_in_page = []
  1679. for mobj in re.finditer(r'href="/([^"]+)"', page):
  1680. if mobj.group(1) not in ids_in_page:
  1681. ids_in_page.append(unescapeHTML(mobj.group(1)))
  1682. video_ids.extend(ids_in_page)
  1683. # A little optimization - if current page is not
  1684. # "full", ie. does not contain PAGE_SIZE video ids then
  1685. # we can assume that this page is the last one - there
  1686. # are no more ids on further pages - no need to query
  1687. # again.
  1688. if len(ids_in_page) < self._PAGE_SIZE:
  1689. break
  1690. pagenum += 1
  1691. all_ids_count = len(video_ids)
  1692. playliststart = self._downloader.params.get('playliststart', 1) - 1
  1693. playlistend = self._downloader.params.get('playlistend', -1)
  1694. if playlistend == -1:
  1695. video_ids = video_ids[playliststart:]
  1696. else:
  1697. video_ids = video_ids[playliststart:playlistend]
  1698. self._downloader.to_screen(u"[%s] user %s: Collected %d video ids (downloading %d of them)" %
  1699. (self.IE_NAME, username, all_ids_count, len(video_ids)))
  1700. for video_id in video_ids:
  1701. self._downloader.download([u'http://blip.tv/'+video_id])
  1702. class DepositFilesIE(InfoExtractor):
  1703. """Information extractor for depositfiles.com"""
  1704. _VALID_URL = r'(?:http://)?(?:\w+\.)?depositfiles\.com/(?:../(?#locale))?files/(.+)'
  1705. def report_download_webpage(self, file_id):
  1706. """Report webpage download."""
  1707. self._downloader.to_screen(u'[DepositFiles] %s: Downloading webpage' % file_id)
  1708. def report_extraction(self, file_id):
  1709. """Report information extraction."""
  1710. self._downloader.to_screen(u'[DepositFiles] %s: Extracting information' % file_id)
  1711. def _real_extract(self, url):
  1712. file_id = url.split('/')[-1]
  1713. # Rebuild url in english locale
  1714. url = 'http://depositfiles.com/en/files/' + file_id
  1715. # Retrieve file webpage with 'Free download' button pressed
  1716. free_download_indication = { 'gateway_result' : '1' }
  1717. request = compat_urllib_request.Request(url, compat_urllib_parse.urlencode(free_download_indication))
  1718. try:
  1719. self.report_download_webpage(file_id)
  1720. webpage = compat_urllib_request.urlopen(request).read()
  1721. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1722. self._downloader.report_error(u'Unable to retrieve file webpage: %s' % compat_str(err))
  1723. return
  1724. # Search for the real file URL
  1725. mobj = re.search(r'<form action="(http://fileshare.+?)"', webpage)
  1726. if (mobj is None) or (mobj.group(1) is None):
  1727. # Try to figure out reason of the error.
  1728. mobj = re.search(r'<strong>(Attention.*?)</strong>', webpage, re.DOTALL)
  1729. if (mobj is not None) and (mobj.group(1) is not None):
  1730. restriction_message = re.sub('\s+', ' ', mobj.group(1)).strip()
  1731. self._downloader.report_error(u'%s' % restriction_message)
  1732. else:
  1733. self._downloader.report_error(u'unable to extract download URL from: %s' % url)
  1734. return
  1735. file_url = mobj.group(1)
  1736. file_extension = os.path.splitext(file_url)[1][1:]
  1737. # Search for file title
  1738. mobj = re.search(r'<b title="(.*?)">', webpage)
  1739. if mobj is None:
  1740. self._downloader.report_error(u'unable to extract title')
  1741. return
  1742. file_title = mobj.group(1).decode('utf-8')
  1743. return [{
  1744. 'id': file_id.decode('utf-8'),
  1745. 'url': file_url.decode('utf-8'),
  1746. 'uploader': None,
  1747. 'upload_date': None,
  1748. 'title': file_title,
  1749. 'ext': file_extension.decode('utf-8'),
  1750. }]
  1751. class FacebookIE(InfoExtractor):
  1752. """Information Extractor for Facebook"""
  1753. _VALID_URL = r'^(?:https?://)?(?:\w+\.)?facebook\.com/(?:video/video|photo)\.php\?(?:.*?)v=(?P<ID>\d+)(?:.*)'
  1754. _LOGIN_URL = 'https://login.facebook.com/login.php?m&next=http%3A%2F%2Fm.facebook.com%2Fhome.php&'
  1755. _NETRC_MACHINE = 'facebook'
  1756. IE_NAME = u'facebook'
  1757. def report_login(self):
  1758. """Report attempt to log in."""
  1759. self._downloader.to_screen(u'[%s] Logging in' % self.IE_NAME)
  1760. def _real_initialize(self):
  1761. if self._downloader is None:
  1762. return
  1763. useremail = None
  1764. password = None
  1765. downloader_params = self._downloader.params
  1766. # Attempt to use provided username and password or .netrc data
  1767. if downloader_params.get('username', None) is not None:
  1768. useremail = downloader_params['username']
  1769. password = downloader_params['password']
  1770. elif downloader_params.get('usenetrc', False):
  1771. try:
  1772. info = netrc.netrc().authenticators(self._NETRC_MACHINE)
  1773. if info is not None:
  1774. useremail = info[0]
  1775. password = info[2]
  1776. else:
  1777. raise netrc.NetrcParseError('No authenticators for %s' % self._NETRC_MACHINE)
  1778. except (IOError, netrc.NetrcParseError) as err:
  1779. self._downloader.report_warning(u'parsing .netrc: %s' % compat_str(err))
  1780. return
  1781. if useremail is None:
  1782. return
  1783. # Log in
  1784. login_form = {
  1785. 'email': useremail,
  1786. 'pass': password,
  1787. 'login': 'Log+In'
  1788. }
  1789. request = compat_urllib_request.Request(self._LOGIN_URL, compat_urllib_parse.urlencode(login_form))
  1790. try:
  1791. self.report_login()
  1792. login_results = compat_urllib_request.urlopen(request).read()
  1793. if re.search(r'<form(.*)name="login"(.*)</form>', login_results) is not None:
  1794. self._downloader.report_warning(u'unable to log in: bad username/password, or exceded login rate limit (~3/min). Check credentials or wait.')
  1795. return
  1796. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1797. self._downloader.report_warning(u'unable to log in: %s' % compat_str(err))
  1798. return
  1799. def _real_extract(self, url):
  1800. mobj = re.match(self._VALID_URL, url)
  1801. if mobj is None:
  1802. self._downloader.report_error(u'invalid URL: %s' % url)
  1803. return
  1804. video_id = mobj.group('ID')
  1805. url = 'https://www.facebook.com/video/video.php?v=%s' % video_id
  1806. webpage = self._download_webpage(url, video_id)
  1807. BEFORE = '[["allowFullScreen","true"],["allowScriptAccess","always"],["salign","tl"],["scale","noscale"],["wmode","opaque"]].forEach(function(param) {swf.addParam(param[0], param[1]);});\n'
  1808. AFTER = '.forEach(function(variable) {swf.addVariable(variable[0], variable[1]);});'
  1809. m = re.search(re.escape(BEFORE) + '(.*?)' + re.escape(AFTER), webpage)
  1810. if not m:
  1811. raise ExtractorError(u'Cannot parse data')
  1812. data = dict(json.loads(m.group(1)))
  1813. params_raw = compat_urllib_parse.unquote(data['params'])
  1814. params = json.loads(params_raw)
  1815. video_url = params['hd_src']
  1816. if not video_url:
  1817. video_url = params['sd_src']
  1818. if not video_url:
  1819. raise ExtractorError(u'Cannot find video URL')
  1820. video_duration = int(params['video_duration'])
  1821. m = re.search('<h2 class="uiHeaderTitle">([^<]+)</h2>', webpage)
  1822. if not m:
  1823. raise ExtractorError(u'Cannot find title in webpage')
  1824. video_title = unescapeHTML(m.group(1))
  1825. info = {
  1826. 'id': video_id,
  1827. 'title': video_title,
  1828. 'url': video_url,
  1829. 'ext': 'mp4',
  1830. 'duration': video_duration,
  1831. 'thumbnail': params['thumbnail_src'],
  1832. }
  1833. return [info]
  1834. class BlipTVIE(InfoExtractor):
  1835. """Information extractor for blip.tv"""
  1836. _VALID_URL = r'^(?:https?://)?(?:\w+\.)?blip\.tv(/.+)$'
  1837. _URL_EXT = r'^.*\.([a-z0-9]+)$'
  1838. IE_NAME = u'blip.tv'
  1839. def report_extraction(self, file_id):
  1840. """Report information extraction."""
  1841. self._downloader.to_screen(u'[%s] %s: Extracting information' % (self.IE_NAME, file_id))
  1842. def report_direct_download(self, title):
  1843. """Report information extraction."""
  1844. self._downloader.to_screen(u'[%s] %s: Direct download detected' % (self.IE_NAME, title))
  1845. def _real_extract(self, url):
  1846. mobj = re.match(self._VALID_URL, url)
  1847. if mobj is None:
  1848. self._downloader.report_error(u'invalid URL: %s' % url)
  1849. return
  1850. urlp = compat_urllib_parse_urlparse(url)
  1851. if urlp.path.startswith('/play/'):
  1852. request = compat_urllib_request.Request(url)
  1853. response = compat_urllib_request.urlopen(request)
  1854. redirecturl = response.geturl()
  1855. rurlp = compat_urllib_parse_urlparse(redirecturl)
  1856. file_id = compat_parse_qs(rurlp.fragment)['file'][0].rpartition('/')[2]
  1857. url = 'http://blip.tv/a/a-' + file_id
  1858. return self._real_extract(url)
  1859. if '?' in url:
  1860. cchar = '&'
  1861. else:
  1862. cchar = '?'
  1863. json_url = url + cchar + 'skin=json&version=2&no_wrap=1'
  1864. request = compat_urllib_request.Request(json_url)
  1865. request.add_header('User-Agent', 'iTunes/10.6.1')
  1866. self.report_extraction(mobj.group(1))
  1867. info = None
  1868. try:
  1869. urlh = compat_urllib_request.urlopen(request)
  1870. if urlh.headers.get('Content-Type', '').startswith('video/'): # Direct download
  1871. basename = url.split('/')[-1]
  1872. title,ext = os.path.splitext(basename)
  1873. title = title.decode('UTF-8')
  1874. ext = ext.replace('.', '')
  1875. self.report_direct_download(title)
  1876. info = {
  1877. 'id': title,
  1878. 'url': url,
  1879. 'uploader': None,
  1880. 'upload_date': None,
  1881. 'title': title,
  1882. 'ext': ext,
  1883. 'urlhandle': urlh
  1884. }
  1885. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1886. raise ExtractorError(u'ERROR: unable to download video info webpage: %s' % compat_str(err))
  1887. if info is None: # Regular URL
  1888. try:
  1889. json_code_bytes = urlh.read()
  1890. json_code = json_code_bytes.decode('utf-8')
  1891. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1892. self._downloader.report_error(u'unable to read video info webpage: %s' % compat_str(err))
  1893. return
  1894. try:
  1895. json_data = json.loads(json_code)
  1896. if 'Post' in json_data:
  1897. data = json_data['Post']
  1898. else:
  1899. data = json_data
  1900. upload_date = datetime.datetime.strptime(data['datestamp'], '%m-%d-%y %H:%M%p').strftime('%Y%m%d')
  1901. video_url = data['media']['url']
  1902. umobj = re.match(self._URL_EXT, video_url)
  1903. if umobj is None:
  1904. raise ValueError('Can not determine filename extension')
  1905. ext = umobj.group(1)
  1906. info = {
  1907. 'id': data['item_id'],
  1908. 'url': video_url,
  1909. 'uploader': data['display_name'],
  1910. 'upload_date': upload_date,
  1911. 'title': data['title'],
  1912. 'ext': ext,
  1913. 'format': data['media']['mimeType'],
  1914. 'thumbnail': data['thumbnailUrl'],
  1915. 'description': data['description'],
  1916. 'player_url': data['embedUrl'],
  1917. 'user_agent': 'iTunes/10.6.1',
  1918. }
  1919. except (ValueError,KeyError) as err:
  1920. self._downloader.report_error(u'unable to parse video information: %s' % repr(err))
  1921. return
  1922. return [info]
  1923. class MyVideoIE(InfoExtractor):
  1924. """Information Extractor for myvideo.de."""
  1925. _VALID_URL = r'(?:http://)?(?:www\.)?myvideo\.de/watch/([0-9]+)/([^?/]+).*'
  1926. IE_NAME = u'myvideo'
  1927. def __init__(self, downloader=None):
  1928. InfoExtractor.__init__(self, downloader)
  1929. def report_extraction(self, video_id):
  1930. """Report information extraction."""
  1931. self._downloader.to_screen(u'[myvideo] %s: Extracting information' % video_id)
  1932. def _real_extract(self,url):
  1933. mobj = re.match(self._VALID_URL, url)
  1934. if mobj is None:
  1935. self._download.report_error(u'invalid URL: %s' % url)
  1936. return
  1937. video_id = mobj.group(1)
  1938. # Get video webpage
  1939. webpage_url = 'http://www.myvideo.de/watch/%s' % video_id
  1940. webpage = self._download_webpage(webpage_url, video_id)
  1941. self.report_extraction(video_id)
  1942. mobj = re.search(r'<link rel=\'image_src\' href=\'(http://is[0-9].myvideo\.de/de/movie[0-9]+/[a-f0-9]+)/thumbs/.*?\.jpg\'',
  1943. webpage)
  1944. if mobj is None:
  1945. self._downloader.report_error(u'unable to extract media URL')
  1946. return
  1947. video_url = mobj.group(1) + ('/%s.flv' % video_id)
  1948. mobj = re.search('<title>([^<]+)</title>', webpage)
  1949. if mobj is None:
  1950. self._downloader.report_error(u'unable to extract title')
  1951. return
  1952. video_title = mobj.group(1)
  1953. return [{
  1954. 'id': video_id,
  1955. 'url': video_url,
  1956. 'uploader': None,
  1957. 'upload_date': None,
  1958. 'title': video_title,
  1959. 'ext': u'flv',
  1960. }]
  1961. class ComedyCentralIE(InfoExtractor):
  1962. """Information extractor for The Daily Show and Colbert Report """
  1963. # urls can be abbreviations like :thedailyshow or :colbert
  1964. # urls for episodes like:
  1965. # or urls for clips like: http://www.thedailyshow.com/watch/mon-december-10-2012/any-given-gun-day
  1966. # or: http://www.colbertnation.com/the-colbert-report-videos/421667/november-29-2012/moon-shattering-news
  1967. # or: http://www.colbertnation.com/the-colbert-report-collections/422008/festival-of-lights/79524
  1968. _VALID_URL = r"""^(:(?P<shortname>tds|thedailyshow|cr|colbert|colbertnation|colbertreport)
  1969. |(https?://)?(www\.)?
  1970. (?P<showname>thedailyshow|colbertnation)\.com/
  1971. (full-episodes/(?P<episode>.*)|
  1972. (?P<clip>
  1973. (the-colbert-report-(videos|collections)/(?P<clipID>[0-9]+)/[^/]*/(?P<cntitle>.*?))
  1974. |(watch/(?P<date>[^/]*)/(?P<tdstitle>.*)))))
  1975. $"""
  1976. _available_formats = ['3500', '2200', '1700', '1200', '750', '400']
  1977. _video_extensions = {
  1978. '3500': 'mp4',
  1979. '2200': 'mp4',
  1980. '1700': 'mp4',
  1981. '1200': 'mp4',
  1982. '750': 'mp4',
  1983. '400': 'mp4',
  1984. }
  1985. _video_dimensions = {
  1986. '3500': '1280x720',
  1987. '2200': '960x540',
  1988. '1700': '768x432',
  1989. '1200': '640x360',
  1990. '750': '512x288',
  1991. '400': '384x216',
  1992. }
  1993. @classmethod
  1994. def suitable(cls, url):
  1995. """Receives a URL and returns True if suitable for this IE."""
  1996. return re.match(cls._VALID_URL, url, re.VERBOSE) is not None
  1997. def report_extraction(self, episode_id):
  1998. self._downloader.to_screen(u'[comedycentral] %s: Extracting information' % episode_id)
  1999. def report_config_download(self, episode_id, media_id):
  2000. self._downloader.to_screen(u'[comedycentral] %s: Downloading configuration for %s' % (episode_id, media_id))
  2001. def report_index_download(self, episode_id):
  2002. self._downloader.to_screen(u'[comedycentral] %s: Downloading show index' % episode_id)
  2003. def _print_formats(self, formats):
  2004. print('Available formats:')
  2005. for x in formats:
  2006. print('%s\t:\t%s\t[%s]' %(x, self._video_extensions.get(x, 'mp4'), self._video_dimensions.get(x, '???')))
  2007. def _real_extract(self, url):
  2008. mobj = re.match(self._VALID_URL, url, re.VERBOSE)
  2009. if mobj is None:
  2010. self._downloader.report_error(u'invalid URL: %s' % url)
  2011. return
  2012. if mobj.group('shortname'):
  2013. if mobj.group('shortname') in ('tds', 'thedailyshow'):
  2014. url = u'http://www.thedailyshow.com/full-episodes/'
  2015. else:
  2016. url = u'http://www.colbertnation.com/full-episodes/'
  2017. mobj = re.match(self._VALID_URL, url, re.VERBOSE)
  2018. assert mobj is not None
  2019. if mobj.group('clip'):
  2020. if mobj.group('showname') == 'thedailyshow':
  2021. epTitle = mobj.group('tdstitle')
  2022. else:
  2023. epTitle = mobj.group('cntitle')
  2024. dlNewest = False
  2025. else:
  2026. dlNewest = not mobj.group('episode')
  2027. if dlNewest:
  2028. epTitle = mobj.group('showname')
  2029. else:
  2030. epTitle = mobj.group('episode')
  2031. req = compat_urllib_request.Request(url)
  2032. self.report_extraction(epTitle)
  2033. try:
  2034. htmlHandle = compat_urllib_request.urlopen(req)
  2035. html = htmlHandle.read()
  2036. webpage = html.decode('utf-8')
  2037. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2038. self._downloader.report_error(u'unable to download webpage: %s' % compat_str(err))
  2039. return
  2040. if dlNewest:
  2041. url = htmlHandle.geturl()
  2042. mobj = re.match(self._VALID_URL, url, re.VERBOSE)
  2043. if mobj is None:
  2044. self._downloader.report_error(u'Invalid redirected URL: ' + url)
  2045. return
  2046. if mobj.group('episode') == '':
  2047. self._downloader.report_error(u'Redirected URL is still not specific: ' + url)
  2048. return
  2049. epTitle = mobj.group('episode')
  2050. mMovieParams = re.findall('(?:<param name="movie" value="|var url = ")(http://media.mtvnservices.com/([^"]*(?:episode|video).*?:.*?))"', webpage)
  2051. if len(mMovieParams) == 0:
  2052. # The Colbert Report embeds the information in a without
  2053. # a URL prefix; so extract the alternate reference
  2054. # and then add the URL prefix manually.
  2055. altMovieParams = re.findall('data-mgid="([^"]*(?:episode|video).*?:.*?)"', webpage)
  2056. if len(altMovieParams) == 0:
  2057. self._downloader.report_error(u'unable to find Flash URL in webpage ' + url)
  2058. return
  2059. else:
  2060. mMovieParams = [("http://media.mtvnservices.com/" + altMovieParams[0], altMovieParams[0])]
  2061. uri = mMovieParams[0][1]
  2062. indexUrl = 'http://shadow.comedycentral.com/feeds/video_player/mrss/?' + compat_urllib_parse.urlencode({'uri': uri})
  2063. self.report_index_download(epTitle)
  2064. try:
  2065. indexXml = compat_urllib_request.urlopen(indexUrl).read()
  2066. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2067. self._downloader.report_error(u'unable to download episode index: ' + compat_str(err))
  2068. return
  2069. results = []
  2070. idoc = xml.etree.ElementTree.fromstring(indexXml)
  2071. itemEls = idoc.findall('.//item')
  2072. for partNum,itemEl in enumerate(itemEls):
  2073. mediaId = itemEl.findall('./guid')[0].text
  2074. shortMediaId = mediaId.split(':')[-1]
  2075. showId = mediaId.split(':')[-2].replace('.com', '')
  2076. officialTitle = itemEl.findall('./title')[0].text
  2077. officialDate = itemEl.findall('./pubDate')[0].text
  2078. configUrl = ('http://www.comedycentral.com/global/feeds/entertainment/media/mediaGenEntertainment.jhtml?' +
  2079. compat_urllib_parse.urlencode({'uri': mediaId}))
  2080. configReq = compat_urllib_request.Request(configUrl)
  2081. self.report_config_download(epTitle, shortMediaId)
  2082. try:
  2083. configXml = compat_urllib_request.urlopen(configReq).read()
  2084. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2085. self._downloader.report_error(u'unable to download webpage: %s' % compat_str(err))
  2086. return
  2087. cdoc = xml.etree.ElementTree.fromstring(configXml)
  2088. turls = []
  2089. for rendition in cdoc.findall('.//rendition'):
  2090. finfo = (rendition.attrib['bitrate'], rendition.findall('./src')[0].text)
  2091. turls.append(finfo)
  2092. if len(turls) == 0:
  2093. self._downloader.report_error(u'unable to download ' + mediaId + ': No videos found')
  2094. continue
  2095. if self._downloader.params.get('listformats', None):
  2096. self._print_formats([i[0] for i in turls])
  2097. return
  2098. # For now, just pick the highest bitrate
  2099. format,rtmp_video_url = turls[-1]
  2100. # Get the format arg from the arg stream
  2101. req_format = self._downloader.params.get('format', None)
  2102. # Select format if we can find one
  2103. for f,v in turls:
  2104. if f == req_format:
  2105. format, rtmp_video_url = f, v
  2106. break
  2107. m = re.match(r'^rtmpe?://.*?/(?P<finalid>gsp.comedystor/.*)$', rtmp_video_url)
  2108. if not m:
  2109. raise ExtractorError(u'Cannot transform RTMP url')
  2110. base = 'http://mtvnmobile.vo.llnwd.net/kip0/_pxn=1+_pxI0=Ripod-h264+_pxL0=undefined+_pxM0=+_pxK=18639+_pxE=mp4/44620/mtvnorigin/'
  2111. video_url = base + m.group('finalid')
  2112. effTitle = showId + u'-' + epTitle + u' part ' + compat_str(partNum+1)
  2113. info = {
  2114. 'id': shortMediaId,
  2115. 'url': video_url,
  2116. 'uploader': showId,
  2117. 'upload_date': officialDate,
  2118. 'title': effTitle,
  2119. 'ext': 'mp4',
  2120. 'format': format,
  2121. 'thumbnail': None,
  2122. 'description': officialTitle,
  2123. }
  2124. results.append(info)
  2125. return results
  2126. class EscapistIE(InfoExtractor):
  2127. """Information extractor for The Escapist """
  2128. _VALID_URL = r'^(https?://)?(www\.)?escapistmagazine\.com/videos/view/(?P<showname>[^/]+)/(?P<episode>[^/?]+)[/?]?.*$'
  2129. IE_NAME = u'escapist'
  2130. def report_extraction(self, showName):
  2131. self._downloader.to_screen(u'[escapist] %s: Extracting information' % showName)
  2132. def report_config_download(self, showName):
  2133. self._downloader.to_screen(u'[escapist] %s: Downloading configuration' % showName)
  2134. def _real_extract(self, url):
  2135. mobj = re.match(self._VALID_URL, url)
  2136. if mobj is None:
  2137. self._downloader.report_error(u'invalid URL: %s' % url)
  2138. return
  2139. showName = mobj.group('showname')
  2140. videoId = mobj.group('episode')
  2141. self.report_extraction(showName)
  2142. try:
  2143. webPage = compat_urllib_request.urlopen(url)
  2144. webPageBytes = webPage.read()
  2145. m = re.match(r'text/html; charset="?([^"]+)"?', webPage.headers['Content-Type'])
  2146. webPage = webPageBytes.decode(m.group(1) if m else 'utf-8')
  2147. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2148. self._downloader.report_error(u'unable to download webpage: ' + compat_str(err))
  2149. return
  2150. descMatch = re.search('<meta name="description" content="([^"]*)"', webPage)
  2151. description = unescapeHTML(descMatch.group(1))
  2152. imgMatch = re.search('<meta property="og:image" content="([^"]*)"', webPage)
  2153. imgUrl = unescapeHTML(imgMatch.group(1))
  2154. playerUrlMatch = re.search('<meta property="og:video" content="([^"]*)"', webPage)
  2155. playerUrl = unescapeHTML(playerUrlMatch.group(1))
  2156. configUrlMatch = re.search('config=(.*)$', playerUrl)
  2157. configUrl = compat_urllib_parse.unquote(configUrlMatch.group(1))
  2158. self.report_config_download(showName)
  2159. try:
  2160. configJSON = compat_urllib_request.urlopen(configUrl)
  2161. m = re.match(r'text/html; charset="?([^"]+)"?', configJSON.headers['Content-Type'])
  2162. configJSON = configJSON.read().decode(m.group(1) if m else 'utf-8')
  2163. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2164. self._downloader.report_error(u'unable to download configuration: ' + compat_str(err))
  2165. return
  2166. # Technically, it's JavaScript, not JSON
  2167. configJSON = configJSON.replace("'", '"')
  2168. try:
  2169. config = json.loads(configJSON)
  2170. except (ValueError,) as err:
  2171. self._downloader.report_error(u'Invalid JSON in configuration file: ' + compat_str(err))
  2172. return
  2173. playlist = config['playlist']
  2174. videoUrl = playlist[1]['url']
  2175. info = {
  2176. 'id': videoId,
  2177. 'url': videoUrl,
  2178. 'uploader': showName,
  2179. 'upload_date': None,
  2180. 'title': showName,
  2181. 'ext': 'mp4',
  2182. 'thumbnail': imgUrl,
  2183. 'description': description,
  2184. 'player_url': playerUrl,
  2185. }
  2186. return [info]
  2187. class CollegeHumorIE(InfoExtractor):
  2188. """Information extractor for collegehumor.com"""
  2189. _WORKING = False
  2190. _VALID_URL = r'^(?:https?://)?(?:www\.)?collegehumor\.com/video/(?P<videoid>[0-9]+)/(?P<shorttitle>.*)$'
  2191. IE_NAME = u'collegehumor'
  2192. def report_manifest(self, video_id):
  2193. """Report information extraction."""
  2194. self._downloader.to_screen(u'[%s] %s: Downloading XML manifest' % (self.IE_NAME, video_id))
  2195. def report_extraction(self, video_id):
  2196. """Report information extraction."""
  2197. self._downloader.to_screen(u'[%s] %s: Extracting information' % (self.IE_NAME, video_id))
  2198. def _real_extract(self, url):
  2199. mobj = re.match(self._VALID_URL, url)
  2200. if mobj is None:
  2201. self._downloader.report_error(u'invalid URL: %s' % url)
  2202. return
  2203. video_id = mobj.group('videoid')
  2204. info = {
  2205. 'id': video_id,
  2206. 'uploader': None,
  2207. 'upload_date': None,
  2208. }
  2209. self.report_extraction(video_id)
  2210. xmlUrl = 'http://www.collegehumor.com/moogaloop/video/' + video_id
  2211. try:
  2212. metaXml = compat_urllib_request.urlopen(xmlUrl).read()
  2213. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2214. self._downloader.report_error(u'unable to download video info XML: %s' % compat_str(err))
  2215. return
  2216. mdoc = xml.etree.ElementTree.fromstring(metaXml)
  2217. try:
  2218. videoNode = mdoc.findall('./video')[0]
  2219. info['description'] = videoNode.findall('./description')[0].text
  2220. info['title'] = videoNode.findall('./caption')[0].text
  2221. info['thumbnail'] = videoNode.findall('./thumbnail')[0].text
  2222. manifest_url = videoNode.findall('./file')[0].text
  2223. except IndexError:
  2224. self._downloader.report_error(u'Invalid metadata XML file')
  2225. return
  2226. manifest_url += '?hdcore=2.10.3'
  2227. self.report_manifest(video_id)
  2228. try:
  2229. manifestXml = compat_urllib_request.urlopen(manifest_url).read()
  2230. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2231. self._downloader.report_error(u'unable to download video info XML: %s' % compat_str(err))
  2232. return
  2233. adoc = xml.etree.ElementTree.fromstring(manifestXml)
  2234. try:
  2235. media_node = adoc.findall('./{http://ns.adobe.com/f4m/1.0}media')[0]
  2236. node_id = media_node.attrib['url']
  2237. video_id = adoc.findall('./{http://ns.adobe.com/f4m/1.0}id')[0].text
  2238. except IndexError as err:
  2239. self._downloader.report_error(u'Invalid manifest file')
  2240. return
  2241. url_pr = compat_urllib_parse_urlparse(manifest_url)
  2242. url = url_pr.scheme + '://' + url_pr.netloc + '/z' + video_id[:-2] + '/' + node_id + 'Seg1-Frag1'
  2243. info['url'] = url
  2244. info['ext'] = 'f4f'
  2245. return [info]
  2246. class XVideosIE(InfoExtractor):
  2247. """Information extractor for xvideos.com"""
  2248. _VALID_URL = r'^(?:https?://)?(?:www\.)?xvideos\.com/video([0-9]+)(?:.*)'
  2249. IE_NAME = u'xvideos'
  2250. def report_extraction(self, video_id):
  2251. """Report information extraction."""
  2252. self._downloader.to_screen(u'[%s] %s: Extracting information' % (self.IE_NAME, video_id))
  2253. def _real_extract(self, url):
  2254. mobj = re.match(self._VALID_URL, url)
  2255. if mobj is None:
  2256. self._downloader.report_error(u'invalid URL: %s' % url)
  2257. return
  2258. video_id = mobj.group(1)
  2259. webpage = self._download_webpage(url, video_id)
  2260. self.report_extraction(video_id)
  2261. # Extract video URL
  2262. mobj = re.search(r'flv_url=(.+?)&', webpage)
  2263. if mobj is None:
  2264. self._downloader.report_error(u'unable to extract video url')
  2265. return
  2266. video_url = compat_urllib_parse.unquote(mobj.group(1))
  2267. # Extract title
  2268. mobj = re.search(r'<title>(.*?)\s+-\s+XVID', webpage)
  2269. if mobj is None:
  2270. self._downloader.report_error(u'unable to extract video title')
  2271. return
  2272. video_title = mobj.group(1)
  2273. # Extract video thumbnail
  2274. 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]+/([a-fA-F0-9.]+jpg)', webpage)
  2275. if mobj is None:
  2276. self._downloader.report_error(u'unable to extract video thumbnail')
  2277. return
  2278. video_thumbnail = mobj.group(0)
  2279. info = {
  2280. 'id': video_id,
  2281. 'url': video_url,
  2282. 'uploader': None,
  2283. 'upload_date': None,
  2284. 'title': video_title,
  2285. 'ext': 'flv',
  2286. 'thumbnail': video_thumbnail,
  2287. 'description': None,
  2288. }
  2289. return [info]
  2290. class SoundcloudIE(InfoExtractor):
  2291. """Information extractor for soundcloud.com
  2292. To access the media, the uid of the song and a stream token
  2293. must be extracted from the page source and the script must make
  2294. a request to media.soundcloud.com/crossdomain.xml. Then
  2295. the media can be grabbed by requesting from an url composed
  2296. of the stream token and uid
  2297. """
  2298. _VALID_URL = r'^(?:https?://)?(?:www\.)?soundcloud\.com/([\w\d-]+)/([\w\d-]+)'
  2299. IE_NAME = u'soundcloud'
  2300. def __init__(self, downloader=None):
  2301. InfoExtractor.__init__(self, downloader)
  2302. def report_resolve(self, video_id):
  2303. """Report information extraction."""
  2304. self._downloader.to_screen(u'[%s] %s: Resolving id' % (self.IE_NAME, video_id))
  2305. def report_extraction(self, video_id):
  2306. """Report information extraction."""
  2307. self._downloader.to_screen(u'[%s] %s: Retrieving stream' % (self.IE_NAME, video_id))
  2308. def _real_extract(self, url):
  2309. mobj = re.match(self._VALID_URL, url)
  2310. if mobj is None:
  2311. self._downloader.report_error(u'invalid URL: %s' % url)
  2312. return
  2313. # extract uploader (which is in the url)
  2314. uploader = mobj.group(1)
  2315. # extract simple title (uploader + slug of song title)
  2316. slug_title = mobj.group(2)
  2317. simple_title = uploader + u'-' + slug_title
  2318. self.report_resolve('%s/%s' % (uploader, slug_title))
  2319. url = 'http://soundcloud.com/%s/%s' % (uploader, slug_title)
  2320. resolv_url = 'http://api.soundcloud.com/resolve.json?url=' + url + '&client_id=b45b1aa10f1ac2941910a7f0d10f8e28'
  2321. request = compat_urllib_request.Request(resolv_url)
  2322. try:
  2323. info_json_bytes = compat_urllib_request.urlopen(request).read()
  2324. info_json = info_json_bytes.decode('utf-8')
  2325. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2326. self._downloader.report_error(u'unable to download video webpage: %s' % compat_str(err))
  2327. return
  2328. info = json.loads(info_json)
  2329. video_id = info['id']
  2330. self.report_extraction('%s/%s' % (uploader, slug_title))
  2331. streams_url = 'https://api.sndcdn.com/i1/tracks/' + str(video_id) + '/streams?client_id=b45b1aa10f1ac2941910a7f0d10f8e28'
  2332. request = compat_urllib_request.Request(streams_url)
  2333. try:
  2334. stream_json_bytes = compat_urllib_request.urlopen(request).read()
  2335. stream_json = stream_json_bytes.decode('utf-8')
  2336. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2337. self._downloader.report_error(u'unable to download stream definitions: %s' % compat_str(err))
  2338. return
  2339. streams = json.loads(stream_json)
  2340. mediaURL = streams['http_mp3_128_url']
  2341. return [{
  2342. 'id': info['id'],
  2343. 'url': mediaURL,
  2344. 'uploader': info['user']['username'],
  2345. 'upload_date': info['created_at'],
  2346. 'title': info['title'],
  2347. 'ext': u'mp3',
  2348. 'description': info['description'],
  2349. }]
  2350. class SoundcloudSetIE(InfoExtractor):
  2351. """Information extractor for soundcloud.com sets
  2352. To access the media, the uid of the song and a stream token
  2353. must be extracted from the page source and the script must make
  2354. a request to media.soundcloud.com/crossdomain.xml. Then
  2355. the media can be grabbed by requesting from an url composed
  2356. of the stream token and uid
  2357. """
  2358. _VALID_URL = r'^(?:https?://)?(?:www\.)?soundcloud\.com/([\w\d-]+)/sets/([\w\d-]+)'
  2359. IE_NAME = u'soundcloud'
  2360. def __init__(self, downloader=None):
  2361. InfoExtractor.__init__(self, downloader)
  2362. def report_resolve(self, video_id):
  2363. """Report information extraction."""
  2364. self._downloader.to_screen(u'[%s] %s: Resolving id' % (self.IE_NAME, video_id))
  2365. def report_extraction(self, video_id):
  2366. """Report information extraction."""
  2367. self._downloader.to_screen(u'[%s] %s: Retrieving stream' % (self.IE_NAME, video_id))
  2368. def _real_extract(self, url):
  2369. mobj = re.match(self._VALID_URL, url)
  2370. if mobj is None:
  2371. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  2372. return
  2373. # extract uploader (which is in the url)
  2374. uploader = mobj.group(1)
  2375. # extract simple title (uploader + slug of song title)
  2376. slug_title = mobj.group(2)
  2377. simple_title = uploader + u'-' + slug_title
  2378. self.report_resolve('%s/sets/%s' % (uploader, slug_title))
  2379. url = 'http://soundcloud.com/%s/sets/%s' % (uploader, slug_title)
  2380. resolv_url = 'http://api.soundcloud.com/resolve.json?url=' + url + '&client_id=b45b1aa10f1ac2941910a7f0d10f8e28'
  2381. request = compat_urllib_request.Request(resolv_url)
  2382. try:
  2383. info_json_bytes = compat_urllib_request.urlopen(request).read()
  2384. info_json = info_json_bytes.decode('utf-8')
  2385. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2386. self._downloader.trouble(u'ERROR: unable to download video webpage: %s' % compat_str(err))
  2387. return
  2388. videos = []
  2389. info = json.loads(info_json)
  2390. if 'errors' in info:
  2391. for err in info['errors']:
  2392. self._downloader.trouble(u'ERROR: unable to download video webpage: %s' % compat_str(err['error_message']))
  2393. return
  2394. for track in info['tracks']:
  2395. video_id = track['id']
  2396. self.report_extraction('%s/sets/%s' % (uploader, slug_title))
  2397. streams_url = 'https://api.sndcdn.com/i1/tracks/' + str(video_id) + '/streams?client_id=b45b1aa10f1ac2941910a7f0d10f8e28'
  2398. request = compat_urllib_request.Request(streams_url)
  2399. try:
  2400. stream_json_bytes = compat_urllib_request.urlopen(request).read()
  2401. stream_json = stream_json_bytes.decode('utf-8')
  2402. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2403. self._downloader.trouble(u'ERROR: unable to download stream definitions: %s' % compat_str(err))
  2404. return
  2405. streams = json.loads(stream_json)
  2406. mediaURL = streams['http_mp3_128_url']
  2407. videos.append({
  2408. 'id': video_id,
  2409. 'url': mediaURL,
  2410. 'uploader': track['user']['username'],
  2411. 'upload_date': track['created_at'],
  2412. 'title': track['title'],
  2413. 'ext': u'mp3',
  2414. 'description': track['description'],
  2415. })
  2416. return videos
  2417. class InfoQIE(InfoExtractor):
  2418. """Information extractor for infoq.com"""
  2419. _VALID_URL = r'^(?:https?://)?(?:www\.)?infoq\.com/[^/]+/[^/]+$'
  2420. def report_extraction(self, video_id):
  2421. """Report information extraction."""
  2422. self._downloader.to_screen(u'[%s] %s: Extracting information' % (self.IE_NAME, video_id))
  2423. def _real_extract(self, url):
  2424. mobj = re.match(self._VALID_URL, url)
  2425. if mobj is None:
  2426. self._downloader.report_error(u'invalid URL: %s' % url)
  2427. return
  2428. webpage = self._download_webpage(url, video_id=url)
  2429. self.report_extraction(url)
  2430. # Extract video URL
  2431. mobj = re.search(r"jsclassref='([^']*)'", webpage)
  2432. if mobj is None:
  2433. self._downloader.report_error(u'unable to extract video url')
  2434. return
  2435. real_id = compat_urllib_parse.unquote(base64.b64decode(mobj.group(1).encode('ascii')).decode('utf-8'))
  2436. video_url = 'rtmpe://video.infoq.com/cfx/st/' + real_id
  2437. # Extract title
  2438. mobj = re.search(r'contentTitle = "(.*?)";', webpage)
  2439. if mobj is None:
  2440. self._downloader.report_error(u'unable to extract video title')
  2441. return
  2442. video_title = mobj.group(1)
  2443. # Extract description
  2444. video_description = u'No description available.'
  2445. mobj = re.search(r'<meta name="description" content="(.*)"(?:\s*/)?>', webpage)
  2446. if mobj is not None:
  2447. video_description = mobj.group(1)
  2448. video_filename = video_url.split('/')[-1]
  2449. video_id, extension = video_filename.split('.')
  2450. info = {
  2451. 'id': video_id,
  2452. 'url': video_url,
  2453. 'uploader': None,
  2454. 'upload_date': None,
  2455. 'title': video_title,
  2456. 'ext': extension, # Extension is always(?) mp4, but seems to be flv
  2457. 'thumbnail': None,
  2458. 'description': video_description,
  2459. }
  2460. return [info]
  2461. class MixcloudIE(InfoExtractor):
  2462. """Information extractor for www.mixcloud.com"""
  2463. _WORKING = False # New API, but it seems good http://www.mixcloud.com/developers/documentation/
  2464. _VALID_URL = r'^(?:https?://)?(?:www\.)?mixcloud\.com/([\w\d-]+)/([\w\d-]+)'
  2465. IE_NAME = u'mixcloud'
  2466. def __init__(self, downloader=None):
  2467. InfoExtractor.__init__(self, downloader)
  2468. def report_download_json(self, file_id):
  2469. """Report JSON download."""
  2470. self._downloader.to_screen(u'[%s] Downloading json' % self.IE_NAME)
  2471. def report_extraction(self, file_id):
  2472. """Report information extraction."""
  2473. self._downloader.to_screen(u'[%s] %s: Extracting information' % (self.IE_NAME, file_id))
  2474. def get_urls(self, jsonData, fmt, bitrate='best'):
  2475. """Get urls from 'audio_formats' section in json"""
  2476. file_url = None
  2477. try:
  2478. bitrate_list = jsonData[fmt]
  2479. if bitrate is None or bitrate == 'best' or bitrate not in bitrate_list:
  2480. bitrate = max(bitrate_list) # select highest
  2481. url_list = jsonData[fmt][bitrate]
  2482. except TypeError: # we have no bitrate info.
  2483. url_list = jsonData[fmt]
  2484. return url_list
  2485. def check_urls(self, url_list):
  2486. """Returns 1st active url from list"""
  2487. for url in url_list:
  2488. try:
  2489. compat_urllib_request.urlopen(url)
  2490. return url
  2491. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2492. url = None
  2493. return None
  2494. def _print_formats(self, formats):
  2495. print('Available formats:')
  2496. for fmt in formats.keys():
  2497. for b in formats[fmt]:
  2498. try:
  2499. ext = formats[fmt][b][0]
  2500. print('%s\t%s\t[%s]' % (fmt, b, ext.split('.')[-1]))
  2501. except TypeError: # we have no bitrate info
  2502. ext = formats[fmt][0]
  2503. print('%s\t%s\t[%s]' % (fmt, '??', ext.split('.')[-1]))
  2504. break
  2505. def _real_extract(self, url):
  2506. mobj = re.match(self._VALID_URL, url)
  2507. if mobj is None:
  2508. self._downloader.report_error(u'invalid URL: %s' % url)
  2509. return
  2510. # extract uploader & filename from url
  2511. uploader = mobj.group(1).decode('utf-8')
  2512. file_id = uploader + "-" + mobj.group(2).decode('utf-8')
  2513. # construct API request
  2514. file_url = 'http://www.mixcloud.com/api/1/cloudcast/' + '/'.join(url.split('/')[-3:-1]) + '.json'
  2515. # retrieve .json file with links to files
  2516. request = compat_urllib_request.Request(file_url)
  2517. try:
  2518. self.report_download_json(file_url)
  2519. jsonData = compat_urllib_request.urlopen(request).read()
  2520. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2521. self._downloader.report_error(u'Unable to retrieve file: %s' % compat_str(err))
  2522. return
  2523. # parse JSON
  2524. json_data = json.loads(jsonData)
  2525. player_url = json_data['player_swf_url']
  2526. formats = dict(json_data['audio_formats'])
  2527. req_format = self._downloader.params.get('format', None)
  2528. bitrate = None
  2529. if self._downloader.params.get('listformats', None):
  2530. self._print_formats(formats)
  2531. return
  2532. if req_format is None or req_format == 'best':
  2533. for format_param in formats.keys():
  2534. url_list = self.get_urls(formats, format_param)
  2535. # check urls
  2536. file_url = self.check_urls(url_list)
  2537. if file_url is not None:
  2538. break # got it!
  2539. else:
  2540. if req_format not in formats:
  2541. self._downloader.report_error(u'format is not available')
  2542. return
  2543. url_list = self.get_urls(formats, req_format)
  2544. file_url = self.check_urls(url_list)
  2545. format_param = req_format
  2546. return [{
  2547. 'id': file_id.decode('utf-8'),
  2548. 'url': file_url.decode('utf-8'),
  2549. 'uploader': uploader.decode('utf-8'),
  2550. 'upload_date': None,
  2551. 'title': json_data['name'],
  2552. 'ext': file_url.split('.')[-1].decode('utf-8'),
  2553. 'format': (format_param is None and u'NA' or format_param.decode('utf-8')),
  2554. 'thumbnail': json_data['thumbnail_url'],
  2555. 'description': json_data['description'],
  2556. 'player_url': player_url.decode('utf-8'),
  2557. }]
  2558. class StanfordOpenClassroomIE(InfoExtractor):
  2559. """Information extractor for Stanford's Open ClassRoom"""
  2560. _VALID_URL = r'^(?:https?://)?openclassroom.stanford.edu(?P<path>/?|(/MainFolder/(?:HomePage|CoursePage|VideoPage)\.php([?]course=(?P<course>[^&]+)(&video=(?P<video>[^&]+))?(&.*)?)?))$'
  2561. IE_NAME = u'stanfordoc'
  2562. def report_download_webpage(self, objid):
  2563. """Report information extraction."""
  2564. self._downloader.to_screen(u'[%s] %s: Downloading webpage' % (self.IE_NAME, objid))
  2565. def report_extraction(self, video_id):
  2566. """Report information extraction."""
  2567. self._downloader.to_screen(u'[%s] %s: Extracting information' % (self.IE_NAME, video_id))
  2568. def _real_extract(self, url):
  2569. mobj = re.match(self._VALID_URL, url)
  2570. if mobj is None:
  2571. raise ExtractorError(u'Invalid URL: %s' % url)
  2572. if mobj.group('course') and mobj.group('video'): # A specific video
  2573. course = mobj.group('course')
  2574. video = mobj.group('video')
  2575. info = {
  2576. 'id': course + '_' + video,
  2577. 'uploader': None,
  2578. 'upload_date': None,
  2579. }
  2580. self.report_extraction(info['id'])
  2581. baseUrl = 'http://openclassroom.stanford.edu/MainFolder/courses/' + course + '/videos/'
  2582. xmlUrl = baseUrl + video + '.xml'
  2583. try:
  2584. metaXml = compat_urllib_request.urlopen(xmlUrl).read()
  2585. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2586. self._downloader.report_error(u'unable to download video info XML: %s' % compat_str(err))
  2587. return
  2588. mdoc = xml.etree.ElementTree.fromstring(metaXml)
  2589. try:
  2590. info['title'] = mdoc.findall('./title')[0].text
  2591. info['url'] = baseUrl + mdoc.findall('./videoFile')[0].text
  2592. except IndexError:
  2593. self._downloader.report_error(u'Invalid metadata XML file')
  2594. return
  2595. info['ext'] = info['url'].rpartition('.')[2]
  2596. return [info]
  2597. elif mobj.group('course'): # A course page
  2598. course = mobj.group('course')
  2599. info = {
  2600. 'id': course,
  2601. 'type': 'playlist',
  2602. 'uploader': None,
  2603. 'upload_date': None,
  2604. }
  2605. coursepage = self._download_webpage(url, info['id'],
  2606. note='Downloading course info page',
  2607. errnote='Unable to download course info page')
  2608. m = re.search('<h1>([^<]+)</h1>', coursepage)
  2609. if m:
  2610. info['title'] = unescapeHTML(m.group(1))
  2611. else:
  2612. info['title'] = info['id']
  2613. m = re.search('<description>([^<]+)</description>', coursepage)
  2614. if m:
  2615. info['description'] = unescapeHTML(m.group(1))
  2616. links = orderedSet(re.findall('<a href="(VideoPage.php\?[^"]+)">', coursepage))
  2617. info['list'] = [
  2618. {
  2619. 'type': 'reference',
  2620. 'url': 'http://openclassroom.stanford.edu/MainFolder/' + unescapeHTML(vpage),
  2621. }
  2622. for vpage in links]
  2623. results = []
  2624. for entry in info['list']:
  2625. assert entry['type'] == 'reference'
  2626. results += self.extract(entry['url'])
  2627. return results
  2628. else: # Root page
  2629. info = {
  2630. 'id': 'Stanford OpenClassroom',
  2631. 'type': 'playlist',
  2632. 'uploader': None,
  2633. 'upload_date': None,
  2634. }
  2635. self.report_download_webpage(info['id'])
  2636. rootURL = 'http://openclassroom.stanford.edu/MainFolder/HomePage.php'
  2637. try:
  2638. rootpage = compat_urllib_request.urlopen(rootURL).read()
  2639. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2640. self._downloader.report_error(u'unable to download course info page: ' + compat_str(err))
  2641. return
  2642. info['title'] = info['id']
  2643. links = orderedSet(re.findall('<a href="(CoursePage.php\?[^"]+)">', rootpage))
  2644. info['list'] = [
  2645. {
  2646. 'type': 'reference',
  2647. 'url': 'http://openclassroom.stanford.edu/MainFolder/' + unescapeHTML(cpage),
  2648. }
  2649. for cpage in links]
  2650. results = []
  2651. for entry in info['list']:
  2652. assert entry['type'] == 'reference'
  2653. results += self.extract(entry['url'])
  2654. return results
  2655. class MTVIE(InfoExtractor):
  2656. """Information extractor for MTV.com"""
  2657. _VALID_URL = r'^(?P<proto>https?://)?(?:www\.)?mtv\.com/videos/[^/]+/(?P<videoid>[0-9]+)/[^/]+$'
  2658. IE_NAME = u'mtv'
  2659. def report_extraction(self, video_id):
  2660. """Report information extraction."""
  2661. self._downloader.to_screen(u'[%s] %s: Extracting information' % (self.IE_NAME, video_id))
  2662. def _real_extract(self, url):
  2663. mobj = re.match(self._VALID_URL, url)
  2664. if mobj is None:
  2665. self._downloader.report_error(u'invalid URL: %s' % url)
  2666. return
  2667. if not mobj.group('proto'):
  2668. url = 'http://' + url
  2669. video_id = mobj.group('videoid')
  2670. webpage = self._download_webpage(url, video_id)
  2671. mobj = re.search(r'<meta name="mtv_vt" content="([^"]+)"/>', webpage)
  2672. if mobj is None:
  2673. self._downloader.report_error(u'unable to extract song name')
  2674. return
  2675. song_name = unescapeHTML(mobj.group(1).decode('iso-8859-1'))
  2676. mobj = re.search(r'<meta name="mtv_an" content="([^"]+)"/>', webpage)
  2677. if mobj is None:
  2678. self._downloader.report_error(u'unable to extract performer')
  2679. return
  2680. performer = unescapeHTML(mobj.group(1).decode('iso-8859-1'))
  2681. video_title = performer + ' - ' + song_name
  2682. mobj = re.search(r'<meta name="mtvn_uri" content="([^"]+)"/>', webpage)
  2683. if mobj is None:
  2684. self._downloader.report_error(u'unable to mtvn_uri')
  2685. return
  2686. mtvn_uri = mobj.group(1)
  2687. mobj = re.search(r'MTVN.Player.defaultPlaylistId = ([0-9]+);', webpage)
  2688. if mobj is None:
  2689. self._downloader.report_error(u'unable to extract content id')
  2690. return
  2691. content_id = mobj.group(1)
  2692. 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
  2693. self.report_extraction(video_id)
  2694. request = compat_urllib_request.Request(videogen_url)
  2695. try:
  2696. metadataXml = compat_urllib_request.urlopen(request).read()
  2697. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2698. self._downloader.report_error(u'unable to download video metadata: %s' % compat_str(err))
  2699. return
  2700. mdoc = xml.etree.ElementTree.fromstring(metadataXml)
  2701. renditions = mdoc.findall('.//rendition')
  2702. # For now, always pick the highest quality.
  2703. rendition = renditions[-1]
  2704. try:
  2705. _,_,ext = rendition.attrib['type'].partition('/')
  2706. format = ext + '-' + rendition.attrib['width'] + 'x' + rendition.attrib['height'] + '_' + rendition.attrib['bitrate']
  2707. video_url = rendition.find('./src').text
  2708. except KeyError:
  2709. self._downloader.trouble('Invalid rendition field.')
  2710. return
  2711. info = {
  2712. 'id': video_id,
  2713. 'url': video_url,
  2714. 'uploader': performer,
  2715. 'upload_date': None,
  2716. 'title': video_title,
  2717. 'ext': ext,
  2718. 'format': format,
  2719. }
  2720. return [info]
  2721. class YoukuIE(InfoExtractor):
  2722. _VALID_URL = r'(?:http://)?v\.youku\.com/v_show/id_(?P<ID>[A-Za-z0-9]+)\.html'
  2723. def report_download_webpage(self, file_id):
  2724. """Report webpage download."""
  2725. self._downloader.to_screen(u'[%s] %s: Downloading webpage' % (self.IE_NAME, file_id))
  2726. def report_extraction(self, file_id):
  2727. """Report information extraction."""
  2728. self._downloader.to_screen(u'[%s] %s: Extracting information' % (self.IE_NAME, file_id))
  2729. def _gen_sid(self):
  2730. nowTime = int(time.time() * 1000)
  2731. random1 = random.randint(1000,1998)
  2732. random2 = random.randint(1000,9999)
  2733. return "%d%d%d" %(nowTime,random1,random2)
  2734. def _get_file_ID_mix_string(self, seed):
  2735. mixed = []
  2736. source = list("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/\:._-1234567890")
  2737. seed = float(seed)
  2738. for i in range(len(source)):
  2739. seed = (seed * 211 + 30031 ) % 65536
  2740. index = math.floor(seed / 65536 * len(source) )
  2741. mixed.append(source[int(index)])
  2742. source.remove(source[int(index)])
  2743. #return ''.join(mixed)
  2744. return mixed
  2745. def _get_file_id(self, fileId, seed):
  2746. mixed = self._get_file_ID_mix_string(seed)
  2747. ids = fileId.split('*')
  2748. realId = []
  2749. for ch in ids:
  2750. if ch:
  2751. realId.append(mixed[int(ch)])
  2752. return ''.join(realId)
  2753. def _real_extract(self, url):
  2754. mobj = re.match(self._VALID_URL, url)
  2755. if mobj is None:
  2756. self._downloader.report_error(u'invalid URL: %s' % url)
  2757. return
  2758. video_id = mobj.group('ID')
  2759. info_url = 'http://v.youku.com/player/getPlayList/VideoIDS/' + video_id
  2760. request = compat_urllib_request.Request(info_url, None, std_headers)
  2761. try:
  2762. self.report_download_webpage(video_id)
  2763. jsondata = compat_urllib_request.urlopen(request).read()
  2764. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2765. self._downloader.report_error(u'Unable to retrieve video webpage: %s' % compat_str(err))
  2766. return
  2767. self.report_extraction(video_id)
  2768. try:
  2769. jsonstr = jsondata.decode('utf-8')
  2770. config = json.loads(jsonstr)
  2771. video_title = config['data'][0]['title']
  2772. seed = config['data'][0]['seed']
  2773. format = self._downloader.params.get('format', None)
  2774. supported_format = list(config['data'][0]['streamfileids'].keys())
  2775. if format is None or format == 'best':
  2776. if 'hd2' in supported_format:
  2777. format = 'hd2'
  2778. else:
  2779. format = 'flv'
  2780. ext = u'flv'
  2781. elif format == 'worst':
  2782. format = 'mp4'
  2783. ext = u'mp4'
  2784. else:
  2785. format = 'flv'
  2786. ext = u'flv'
  2787. fileid = config['data'][0]['streamfileids'][format]
  2788. keys = [s['k'] for s in config['data'][0]['segs'][format]]
  2789. except (UnicodeDecodeError, ValueError, KeyError):
  2790. self._downloader.report_error(u'unable to extract info section')
  2791. return
  2792. files_info=[]
  2793. sid = self._gen_sid()
  2794. fileid = self._get_file_id(fileid, seed)
  2795. #column 8,9 of fileid represent the segment number
  2796. #fileid[7:9] should be changed
  2797. for index, key in enumerate(keys):
  2798. temp_fileid = '%s%02X%s' % (fileid[0:8], index, fileid[10:])
  2799. download_url = 'http://f.youku.com/player/getFlvPath/sid/%s_%02X/st/flv/fileid/%s?k=%s' % (sid, index, temp_fileid, key)
  2800. info = {
  2801. 'id': '%s_part%02d' % (video_id, index),
  2802. 'url': download_url,
  2803. 'uploader': None,
  2804. 'upload_date': None,
  2805. 'title': video_title,
  2806. 'ext': ext,
  2807. }
  2808. files_info.append(info)
  2809. return files_info
  2810. class XNXXIE(InfoExtractor):
  2811. """Information extractor for xnxx.com"""
  2812. _VALID_URL = r'^(?:https?://)?video\.xnxx\.com/video([0-9]+)/(.*)'
  2813. IE_NAME = u'xnxx'
  2814. VIDEO_URL_RE = r'flv_url=(.*?)&amp;'
  2815. VIDEO_TITLE_RE = r'<title>(.*?)\s+-\s+XNXX.COM'
  2816. VIDEO_THUMB_RE = r'url_bigthumb=(.*?)&amp;'
  2817. def report_webpage(self, video_id):
  2818. """Report information extraction"""
  2819. self._downloader.to_screen(u'[%s] %s: Downloading webpage' % (self.IE_NAME, video_id))
  2820. def report_extraction(self, video_id):
  2821. """Report information extraction"""
  2822. self._downloader.to_screen(u'[%s] %s: Extracting information' % (self.IE_NAME, video_id))
  2823. def _real_extract(self, url):
  2824. mobj = re.match(self._VALID_URL, url)
  2825. if mobj is None:
  2826. self._downloader.report_error(u'invalid URL: %s' % url)
  2827. return
  2828. video_id = mobj.group(1)
  2829. self.report_webpage(video_id)
  2830. # Get webpage content
  2831. try:
  2832. webpage_bytes = compat_urllib_request.urlopen(url).read()
  2833. webpage = webpage_bytes.decode('utf-8')
  2834. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2835. self._downloader.report_error(u'unable to download video webpage: %s' % err)
  2836. return
  2837. result = re.search(self.VIDEO_URL_RE, webpage)
  2838. if result is None:
  2839. self._downloader.report_error(u'unable to extract video url')
  2840. return
  2841. video_url = compat_urllib_parse.unquote(result.group(1))
  2842. result = re.search(self.VIDEO_TITLE_RE, webpage)
  2843. if result is None:
  2844. self._downloader.report_error(u'unable to extract video title')
  2845. return
  2846. video_title = result.group(1)
  2847. result = re.search(self.VIDEO_THUMB_RE, webpage)
  2848. if result is None:
  2849. self._downloader.report_error(u'unable to extract video thumbnail')
  2850. return
  2851. video_thumbnail = result.group(1)
  2852. return [{
  2853. 'id': video_id,
  2854. 'url': video_url,
  2855. 'uploader': None,
  2856. 'upload_date': None,
  2857. 'title': video_title,
  2858. 'ext': 'flv',
  2859. 'thumbnail': video_thumbnail,
  2860. 'description': None,
  2861. }]
  2862. class GooglePlusIE(InfoExtractor):
  2863. """Information extractor for plus.google.com."""
  2864. _VALID_URL = r'(?:https://)?plus\.google\.com/(?:[^/]+/)*?posts/(\w+)'
  2865. IE_NAME = u'plus.google'
  2866. def __init__(self, downloader=None):
  2867. InfoExtractor.__init__(self, downloader)
  2868. def report_extract_entry(self, url):
  2869. """Report downloading extry"""
  2870. self._downloader.to_screen(u'[plus.google] Downloading entry: %s' % url)
  2871. def report_date(self, upload_date):
  2872. """Report downloading extry"""
  2873. self._downloader.to_screen(u'[plus.google] Entry date: %s' % upload_date)
  2874. def report_uploader(self, uploader):
  2875. """Report downloading extry"""
  2876. self._downloader.to_screen(u'[plus.google] Uploader: %s' % uploader)
  2877. def report_title(self, video_title):
  2878. """Report downloading extry"""
  2879. self._downloader.to_screen(u'[plus.google] Title: %s' % video_title)
  2880. def report_extract_vid_page(self, video_page):
  2881. """Report information extraction."""
  2882. self._downloader.to_screen(u'[plus.google] Extracting video page: %s' % video_page)
  2883. def _real_extract(self, url):
  2884. # Extract id from URL
  2885. mobj = re.match(self._VALID_URL, url)
  2886. if mobj is None:
  2887. self._downloader.report_error(u'Invalid URL: %s' % url)
  2888. return
  2889. post_url = mobj.group(0)
  2890. video_id = mobj.group(1)
  2891. video_extension = 'flv'
  2892. # Step 1, Retrieve post webpage to extract further information
  2893. self.report_extract_entry(post_url)
  2894. request = compat_urllib_request.Request(post_url)
  2895. try:
  2896. webpage = compat_urllib_request.urlopen(request).read().decode('utf-8')
  2897. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2898. self._downloader.report_error(u'Unable to retrieve entry webpage: %s' % compat_str(err))
  2899. return
  2900. # Extract update date
  2901. upload_date = None
  2902. pattern = 'title="Timestamp">(.*?)</a>'
  2903. mobj = re.search(pattern, webpage)
  2904. if mobj:
  2905. upload_date = mobj.group(1)
  2906. # Convert timestring to a format suitable for filename
  2907. upload_date = datetime.datetime.strptime(upload_date, "%Y-%m-%d")
  2908. upload_date = upload_date.strftime('%Y%m%d')
  2909. self.report_date(upload_date)
  2910. # Extract uploader
  2911. uploader = None
  2912. pattern = r'rel\="author".*?>(.*?)</a>'
  2913. mobj = re.search(pattern, webpage)
  2914. if mobj:
  2915. uploader = mobj.group(1)
  2916. self.report_uploader(uploader)
  2917. # Extract title
  2918. # Get the first line for title
  2919. video_title = u'NA'
  2920. pattern = r'<meta name\=\"Description\" content\=\"(.*?)[\n<"]'
  2921. mobj = re.search(pattern, webpage)
  2922. if mobj:
  2923. video_title = mobj.group(1)
  2924. self.report_title(video_title)
  2925. # Step 2, Stimulate clicking the image box to launch video
  2926. pattern = '"(https\://plus\.google\.com/photos/.*?)",,"image/jpeg","video"\]'
  2927. mobj = re.search(pattern, webpage)
  2928. if mobj is None:
  2929. self._downloader.report_error(u'unable to extract video page URL')
  2930. video_page = mobj.group(1)
  2931. request = compat_urllib_request.Request(video_page)
  2932. try:
  2933. webpage = compat_urllib_request.urlopen(request).read().decode('utf-8')
  2934. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2935. self._downloader.report_error(u'Unable to retrieve video webpage: %s' % compat_str(err))
  2936. return
  2937. self.report_extract_vid_page(video_page)
  2938. # Extract video links on video page
  2939. """Extract video links of all sizes"""
  2940. pattern = '\d+,\d+,(\d+),"(http\://redirector\.googlevideo\.com.*?)"'
  2941. mobj = re.findall(pattern, webpage)
  2942. if len(mobj) == 0:
  2943. self._downloader.report_error(u'unable to extract video links')
  2944. # Sort in resolution
  2945. links = sorted(mobj)
  2946. # Choose the lowest of the sort, i.e. highest resolution
  2947. video_url = links[-1]
  2948. # Only get the url. The resolution part in the tuple has no use anymore
  2949. video_url = video_url[-1]
  2950. # Treat escaped \u0026 style hex
  2951. try:
  2952. video_url = video_url.decode("unicode_escape")
  2953. except AttributeError: # Python 3
  2954. video_url = bytes(video_url, 'ascii').decode('unicode-escape')
  2955. return [{
  2956. 'id': video_id,
  2957. 'url': video_url,
  2958. 'uploader': uploader,
  2959. 'upload_date': upload_date,
  2960. 'title': video_title,
  2961. 'ext': video_extension,
  2962. }]
  2963. class NBAIE(InfoExtractor):
  2964. _VALID_URL = r'^(?:https?://)?(?:watch\.|www\.)?nba\.com/(?:nba/)?video(/[^?]*)(\?.*)?$'
  2965. IE_NAME = u'nba'
  2966. def _real_extract(self, url):
  2967. mobj = re.match(self._VALID_URL, url)
  2968. if mobj is None:
  2969. self._downloader.report_error(u'invalid URL: %s' % url)
  2970. return
  2971. video_id = mobj.group(1)
  2972. if video_id.endswith('/index.html'):
  2973. video_id = video_id[:-len('/index.html')]
  2974. webpage = self._download_webpage(url, video_id)
  2975. video_url = u'http://ht-mobile.cdn.turner.com/nba/big' + video_id + '_nba_1280x720.mp4'
  2976. def _findProp(rexp, default=None):
  2977. m = re.search(rexp, webpage)
  2978. if m:
  2979. return unescapeHTML(m.group(1))
  2980. else:
  2981. return default
  2982. shortened_video_id = video_id.rpartition('/')[2]
  2983. title = _findProp(r'<meta property="og:title" content="(.*?)"', shortened_video_id).replace('NBA.com: ', '')
  2984. info = {
  2985. 'id': shortened_video_id,
  2986. 'url': video_url,
  2987. 'ext': 'mp4',
  2988. 'title': title,
  2989. 'uploader_date': _findProp(r'<b>Date:</b> (.*?)</div>'),
  2990. 'description': _findProp(r'<div class="description">(.*?)</h1>'),
  2991. }
  2992. return [info]
  2993. class JustinTVIE(InfoExtractor):
  2994. """Information extractor for justin.tv and twitch.tv"""
  2995. # TODO: One broadcast may be split into multiple videos. The key
  2996. # 'broadcast_id' is the same for all parts, and 'broadcast_part'
  2997. # starts at 1 and increases. Can we treat all parts as one video?
  2998. _VALID_URL = r"""(?x)^(?:http://)?(?:www\.)?(?:twitch|justin)\.tv/
  2999. ([^/]+)(?:/b/([^/]+))?/?(?:\#.*)?$"""
  3000. _JUSTIN_PAGE_LIMIT = 100
  3001. IE_NAME = u'justin.tv'
  3002. def report_extraction(self, file_id):
  3003. """Report information extraction."""
  3004. self._downloader.to_screen(u'[%s] %s: Extracting information' % (self.IE_NAME, file_id))
  3005. def report_download_page(self, channel, offset):
  3006. """Report attempt to download a single page of videos."""
  3007. self._downloader.to_screen(u'[%s] %s: Downloading video information from %d to %d' %
  3008. (self.IE_NAME, channel, offset, offset + self._JUSTIN_PAGE_LIMIT))
  3009. # Return count of items, list of *valid* items
  3010. def _parse_page(self, url):
  3011. try:
  3012. urlh = compat_urllib_request.urlopen(url)
  3013. webpage_bytes = urlh.read()
  3014. webpage = webpage_bytes.decode('utf-8', 'ignore')
  3015. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  3016. self._downloader.report_error(u'unable to download video info JSON: %s' % compat_str(err))
  3017. return
  3018. response = json.loads(webpage)
  3019. if type(response) != list:
  3020. error_text = response.get('error', 'unknown error')
  3021. self._downloader.report_error(u'Justin.tv API: %s' % error_text)
  3022. return
  3023. info = []
  3024. for clip in response:
  3025. video_url = clip['video_file_url']
  3026. if video_url:
  3027. video_extension = os.path.splitext(video_url)[1][1:]
  3028. video_date = re.sub('-', '', clip['start_time'][:10])
  3029. video_uploader_id = clip.get('user_id', clip.get('channel_id'))
  3030. video_id = clip['id']
  3031. video_title = clip.get('title', video_id)
  3032. info.append({
  3033. 'id': video_id,
  3034. 'url': video_url,
  3035. 'title': video_title,
  3036. 'uploader': clip.get('channel_name', video_uploader_id),
  3037. 'uploader_id': video_uploader_id,
  3038. 'upload_date': video_date,
  3039. 'ext': video_extension,
  3040. })
  3041. return (len(response), info)
  3042. def _real_extract(self, url):
  3043. mobj = re.match(self._VALID_URL, url)
  3044. if mobj is None:
  3045. self._downloader.report_error(u'invalid URL: %s' % url)
  3046. return
  3047. api = 'http://api.justin.tv'
  3048. video_id = mobj.group(mobj.lastindex)
  3049. paged = False
  3050. if mobj.lastindex == 1:
  3051. paged = True
  3052. api += '/channel/archives/%s.json'
  3053. else:
  3054. api += '/broadcast/by_archive/%s.json'
  3055. api = api % (video_id,)
  3056. self.report_extraction(video_id)
  3057. info = []
  3058. offset = 0
  3059. limit = self._JUSTIN_PAGE_LIMIT
  3060. while True:
  3061. if paged:
  3062. self.report_download_page(video_id, offset)
  3063. page_url = api + ('?offset=%d&limit=%d' % (offset, limit))
  3064. page_count, page_info = self._parse_page(page_url)
  3065. info.extend(page_info)
  3066. if not paged or page_count != limit:
  3067. break
  3068. offset += limit
  3069. return info
  3070. class FunnyOrDieIE(InfoExtractor):
  3071. _VALID_URL = r'^(?:https?://)?(?:www\.)?funnyordie\.com/videos/(?P<id>[0-9a-f]+)/.*$'
  3072. def _real_extract(self, url):
  3073. mobj = re.match(self._VALID_URL, url)
  3074. if mobj is None:
  3075. self._downloader.report_error(u'invalid URL: %s' % url)
  3076. return
  3077. video_id = mobj.group('id')
  3078. webpage = self._download_webpage(url, video_id)
  3079. m = re.search(r'<video[^>]*>\s*<source[^>]*>\s*<source src="(?P<url>[^"]+)"', webpage, re.DOTALL)
  3080. if not m:
  3081. self._downloader.report_error(u'unable to find video information')
  3082. video_url = unescapeHTML(m.group('url'))
  3083. m = re.search(r"<h1 class='player_page_h1'.*?>(?P<title>.*?)</h1>", webpage, flags=re.DOTALL)
  3084. if not m:
  3085. self._downloader.trouble(u'Cannot find video title')
  3086. title = clean_html(m.group('title'))
  3087. m = re.search(r'<meta property="og:description" content="(?P<desc>.*?)"', webpage)
  3088. if m:
  3089. desc = unescapeHTML(m.group('desc'))
  3090. else:
  3091. desc = None
  3092. info = {
  3093. 'id': video_id,
  3094. 'url': video_url,
  3095. 'ext': 'mp4',
  3096. 'title': title,
  3097. 'description': desc,
  3098. }
  3099. return [info]
  3100. class SteamIE(InfoExtractor):
  3101. _VALID_URL = r"""http://store.steampowered.com/
  3102. (?P<urltype>video|app)/ #If the page is only for videos or for a game
  3103. (?P<gameID>\d+)/?
  3104. (?P<videoID>\d*)(?P<extra>\??) #For urltype == video we sometimes get the videoID
  3105. """
  3106. @classmethod
  3107. def suitable(cls, url):
  3108. """Receives a URL and returns True if suitable for this IE."""
  3109. return re.match(cls._VALID_URL, url, re.VERBOSE) is not None
  3110. def _real_extract(self, url):
  3111. m = re.match(self._VALID_URL, url, re.VERBOSE)
  3112. urlRE = r"'movie_(?P<videoID>\d+)': \{\s*FILENAME: \"(?P<videoURL>[\w:/\.\?=]+)\"(,\s*MOVIE_NAME: \"(?P<videoName>[\w:/\.\?=\+-]+)\")?\s*\},"
  3113. gameID = m.group('gameID')
  3114. videourl = 'http://store.steampowered.com/video/%s/' % gameID
  3115. webpage = self._download_webpage(videourl, gameID)
  3116. mweb = re.finditer(urlRE, webpage)
  3117. namesRE = r'<span class="title">(?P<videoName>.+?)</span>'
  3118. titles = re.finditer(namesRE, webpage)
  3119. thumbsRE = r'<img class="movie_thumb" src="(?P<thumbnail>.+?)">'
  3120. thumbs = re.finditer(thumbsRE, webpage)
  3121. videos = []
  3122. for vid,vtitle,thumb in zip(mweb,titles,thumbs):
  3123. video_id = vid.group('videoID')
  3124. title = vtitle.group('videoName')
  3125. video_url = vid.group('videoURL')
  3126. video_thumb = thumb.group('thumbnail')
  3127. if not video_url:
  3128. self._downloader.report_error(u'Cannot find video url for %s' % video_id)
  3129. info = {
  3130. 'id':video_id,
  3131. 'url':video_url,
  3132. 'ext': 'flv',
  3133. 'title': unescapeHTML(title),
  3134. 'thumbnail': video_thumb
  3135. }
  3136. videos.append(info)
  3137. return videos
  3138. class UstreamIE(InfoExtractor):
  3139. _VALID_URL = r'https?://www\.ustream\.tv/recorded/(?P<videoID>\d+)'
  3140. IE_NAME = u'ustream'
  3141. def _real_extract(self, url):
  3142. m = re.match(self._VALID_URL, url)
  3143. video_id = m.group('videoID')
  3144. video_url = u'http://tcdn.ustream.tv/video/%s' % video_id
  3145. webpage = self._download_webpage(url, video_id)
  3146. m = re.search(r'data-title="(?P<title>.+)"',webpage)
  3147. title = m.group('title')
  3148. m = re.search(r'<a class="state" data-content-type="channel" data-content-id="(?P<uploader>\d+)"',webpage)
  3149. uploader = m.group('uploader')
  3150. info = {
  3151. 'id':video_id,
  3152. 'url':video_url,
  3153. 'ext': 'flv',
  3154. 'title': title,
  3155. 'uploader': uploader
  3156. }
  3157. return [info]
  3158. class WorldStarHipHopIE(InfoExtractor):
  3159. _VALID_URL = r'http://(?:www|m)\.worldstar(?:candy|hiphop)\.com/videos/video\.php\?v=(?P<id>.*)'
  3160. IE_NAME = u'WorldStarHipHop'
  3161. def _real_extract(self, url):
  3162. _src_url = r"""(http://hw-videos.*(?:mp4|flv))"""
  3163. webpage_src = compat_urllib_request.urlopen(url).read()
  3164. webpage_src = webpage_src.decode('utf-8')
  3165. mobj = re.search(_src_url, webpage_src)
  3166. m = re.match(self._VALID_URL, url)
  3167. video_id = m.group('id')
  3168. if mobj is not None:
  3169. video_url = mobj.group()
  3170. if 'mp4' in video_url:
  3171. ext = 'mp4'
  3172. else:
  3173. ext = 'flv'
  3174. else:
  3175. self._downloader.trouble(u'ERROR: Cannot find video url for %s' % video_id)
  3176. return
  3177. _title = r"""<title>(.*)</title>"""
  3178. mobj = re.search(_title, webpage_src)
  3179. if mobj is not None:
  3180. title = mobj.group(1)
  3181. else:
  3182. title = 'World Start Hip Hop - %s' % time.ctime()
  3183. _thumbnail = r"""rel="image_src" href="(.*)" />"""
  3184. mobj = re.search(_thumbnail, webpage_src)
  3185. # Getting thumbnail and if not thumbnail sets correct title for WSHH candy video.
  3186. if mobj is not None:
  3187. thumbnail = mobj.group(1)
  3188. else:
  3189. _title = r"""candytitles.*>(.*)</span>"""
  3190. mobj = re.search(_title, webpage_src)
  3191. if mobj is not None:
  3192. title = mobj.group(1)
  3193. thumbnail = None
  3194. results = [{
  3195. 'id': video_id,
  3196. 'url' : video_url,
  3197. 'title' : title,
  3198. 'thumbnail' : thumbnail,
  3199. 'ext' : ext,
  3200. }]
  3201. return results
  3202. class RBMARadioIE(InfoExtractor):
  3203. _VALID_URL = r'https?://(?:www\.)?rbmaradio\.com/shows/(?P<videoID>[^/]+)$'
  3204. def _real_extract(self, url):
  3205. m = re.match(self._VALID_URL, url)
  3206. video_id = m.group('videoID')
  3207. webpage = self._download_webpage(url, video_id)
  3208. m = re.search(r'<script>window.gon = {.*?};gon\.show=(.+?);</script>', webpage)
  3209. if not m:
  3210. raise ExtractorError(u'Cannot find metadata')
  3211. json_data = m.group(1)
  3212. try:
  3213. data = json.loads(json_data)
  3214. except ValueError as e:
  3215. raise ExtractorError(u'Invalid JSON: ' + str(e))
  3216. video_url = data['akamai_url'] + '&cbr=256'
  3217. url_parts = compat_urllib_parse_urlparse(video_url)
  3218. video_ext = url_parts.path.rpartition('.')[2]
  3219. info = {
  3220. 'id': video_id,
  3221. 'url': video_url,
  3222. 'ext': video_ext,
  3223. 'title': data['title'],
  3224. 'description': data.get('teaser_text'),
  3225. 'location': data.get('country_of_origin'),
  3226. 'uploader': data.get('host', {}).get('name'),
  3227. 'uploader_id': data.get('host', {}).get('slug'),
  3228. 'thumbnail': data.get('image', {}).get('large_url_2x'),
  3229. 'duration': data.get('duration'),
  3230. }
  3231. return [info]
  3232. class YouPornIE(InfoExtractor):
  3233. """Information extractor for youporn.com."""
  3234. _VALID_URL = r'^(?:https?://)?(?:\w+\.)?youporn\.com/watch/(?P<videoid>[0-9]+)/(?P<title>[^/]+)'
  3235. def _print_formats(self, formats):
  3236. """Print all available formats"""
  3237. print(u'Available formats:')
  3238. print(u'ext\t\tformat')
  3239. print(u'---------------------------------')
  3240. for format in formats:
  3241. print(u'%s\t\t%s' % (format['ext'], format['format']))
  3242. def _specific(self, req_format, formats):
  3243. for x in formats:
  3244. if(x["format"]==req_format):
  3245. return x
  3246. return None
  3247. def _real_extract(self, url):
  3248. mobj = re.match(self._VALID_URL, url)
  3249. if mobj is None:
  3250. self._downloader.report_error(u'invalid URL: %s' % url)
  3251. return
  3252. video_id = mobj.group('videoid')
  3253. req = compat_urllib_request.Request(url)
  3254. req.add_header('Cookie', 'age_verified=1')
  3255. webpage = self._download_webpage(req, video_id)
  3256. # Get the video title
  3257. result = re.search(r'<h1.*?>(?P<title>.*)</h1>', webpage)
  3258. if result is None:
  3259. raise ExtractorError(u'Unable to extract video title')
  3260. video_title = result.group('title').strip()
  3261. # Get the video date
  3262. result = re.search(r'Date:</label>(?P<date>.*) </li>', webpage)
  3263. if result is None:
  3264. self._downloader.report_warning(u'unable to extract video date')
  3265. upload_date = None
  3266. else:
  3267. upload_date = result.group('date').strip()
  3268. # Get the video uploader
  3269. result = re.search(r'Submitted:</label>(?P<uploader>.*)</li>', webpage)
  3270. if result is None:
  3271. self._downloader.report_warning(u'unable to extract uploader')
  3272. video_uploader = None
  3273. else:
  3274. video_uploader = result.group('uploader').strip()
  3275. video_uploader = clean_html( video_uploader )
  3276. # Get all of the formats available
  3277. DOWNLOAD_LIST_RE = r'(?s)<ul class="downloadList">(?P<download_list>.*?)</ul>'
  3278. result = re.search(DOWNLOAD_LIST_RE, webpage)
  3279. if result is None:
  3280. raise ExtractorError(u'Unable to extract download list')
  3281. download_list_html = result.group('download_list').strip()
  3282. # Get all of the links from the page
  3283. LINK_RE = r'(?s)<a href="(?P<url>[^"]+)">'
  3284. links = re.findall(LINK_RE, download_list_html)
  3285. if(len(links) == 0):
  3286. raise ExtractorError(u'ERROR: no known formats available for video')
  3287. self._downloader.to_screen(u'[youporn] Links found: %d' % len(links))
  3288. formats = []
  3289. for link in links:
  3290. # A link looks like this:
  3291. # http://cdn1.download.youporn.phncdn.com/201210/31/8004515/480p_370k_8004515/YouPorn%20-%20Nubile%20Films%20The%20Pillow%20Fight.mp4?nvb=20121113051249&nva=20121114051249&ir=1200&sr=1200&hash=014b882080310e95fb6a0
  3292. # A path looks like this:
  3293. # /201210/31/8004515/480p_370k_8004515/YouPorn%20-%20Nubile%20Films%20The%20Pillow%20Fight.mp4
  3294. video_url = unescapeHTML( link )
  3295. path = compat_urllib_parse_urlparse( video_url ).path
  3296. extension = os.path.splitext( path )[1][1:]
  3297. format = path.split('/')[4].split('_')[:2]
  3298. size = format[0]
  3299. bitrate = format[1]
  3300. format = "-".join( format )
  3301. title = u'%s-%s-%s' % (video_title, size, bitrate)
  3302. formats.append({
  3303. 'id': video_id,
  3304. 'url': video_url,
  3305. 'uploader': video_uploader,
  3306. 'upload_date': upload_date,
  3307. 'title': title,
  3308. 'ext': extension,
  3309. 'format': format,
  3310. 'thumbnail': None,
  3311. 'description': None,
  3312. 'player_url': None
  3313. })
  3314. if self._downloader.params.get('listformats', None):
  3315. self._print_formats(formats)
  3316. return
  3317. req_format = self._downloader.params.get('format', None)
  3318. self._downloader.to_screen(u'[youporn] Format: %s' % req_format)
  3319. if req_format is None or req_format == 'best':
  3320. return [formats[0]]
  3321. elif req_format == 'worst':
  3322. return [formats[-1]]
  3323. elif req_format in ('-1', 'all'):
  3324. return formats
  3325. else:
  3326. format = self._specific( req_format, formats )
  3327. if result is None:
  3328. self._downloader.report_error(u'requested format not available')
  3329. return
  3330. return [format]
  3331. class PornotubeIE(InfoExtractor):
  3332. """Information extractor for pornotube.com."""
  3333. _VALID_URL = r'^(?:https?://)?(?:\w+\.)?pornotube\.com(/c/(?P<channel>[0-9]+))?(/m/(?P<videoid>[0-9]+))(/(?P<title>.+))$'
  3334. def _real_extract(self, url):
  3335. mobj = re.match(self._VALID_URL, url)
  3336. if mobj is None:
  3337. self._downloader.report_error(u'invalid URL: %s' % url)
  3338. return
  3339. video_id = mobj.group('videoid')
  3340. video_title = mobj.group('title')
  3341. # Get webpage content
  3342. webpage = self._download_webpage(url, video_id)
  3343. # Get the video URL
  3344. VIDEO_URL_RE = r'url: "(?P<url>http://video[0-9].pornotube.com/.+\.flv)",'
  3345. result = re.search(VIDEO_URL_RE, webpage)
  3346. if result is None:
  3347. self._downloader.report_error(u'unable to extract video url')
  3348. return
  3349. video_url = compat_urllib_parse.unquote(result.group('url'))
  3350. #Get the uploaded date
  3351. VIDEO_UPLOADED_RE = r'<div class="video_added_by">Added (?P<date>[0-9\/]+) by'
  3352. result = re.search(VIDEO_UPLOADED_RE, webpage)
  3353. if result is None:
  3354. self._downloader.report_error(u'unable to extract video title')
  3355. return
  3356. upload_date = result.group('date')
  3357. info = {'id': video_id,
  3358. 'url': video_url,
  3359. 'uploader': None,
  3360. 'upload_date': upload_date,
  3361. 'title': video_title,
  3362. 'ext': 'flv',
  3363. 'format': 'flv'}
  3364. return [info]
  3365. class YouJizzIE(InfoExtractor):
  3366. """Information extractor for youjizz.com."""
  3367. _VALID_URL = r'^(?:https?://)?(?:\w+\.)?youjizz\.com/videos/(?P<videoid>[^.]+).html$'
  3368. def _real_extract(self, url):
  3369. mobj = re.match(self._VALID_URL, url)
  3370. if mobj is None:
  3371. self._downloader.report_error(u'invalid URL: %s' % url)
  3372. return
  3373. video_id = mobj.group('videoid')
  3374. # Get webpage content
  3375. webpage = self._download_webpage(url, video_id)
  3376. # Get the video title
  3377. result = re.search(r'<title>(?P<title>.*)</title>', webpage)
  3378. if result is None:
  3379. raise ExtractorError(u'ERROR: unable to extract video title')
  3380. video_title = result.group('title').strip()
  3381. # Get the embed page
  3382. result = re.search(r'https?://www.youjizz.com/videos/embed/(?P<videoid>[0-9]+)', webpage)
  3383. if result is None:
  3384. raise ExtractorError(u'ERROR: unable to extract embed page')
  3385. embed_page_url = result.group(0).strip()
  3386. video_id = result.group('videoid')
  3387. webpage = self._download_webpage(embed_page_url, video_id)
  3388. # Get the video URL
  3389. result = re.search(r'so.addVariable\("file",encodeURIComponent\("(?P<source>[^"]+)"\)\);', webpage)
  3390. if result is None:
  3391. raise ExtractorError(u'ERROR: unable to extract video url')
  3392. video_url = result.group('source')
  3393. info = {'id': video_id,
  3394. 'url': video_url,
  3395. 'title': video_title,
  3396. 'ext': 'flv',
  3397. 'format': 'flv',
  3398. 'player_url': embed_page_url}
  3399. return [info]
  3400. class EightTracksIE(InfoExtractor):
  3401. IE_NAME = '8tracks'
  3402. _VALID_URL = r'https?://8tracks.com/(?P<user>[^/]+)/(?P<id>[^/#]+)(?:#.*)?$'
  3403. def _real_extract(self, url):
  3404. mobj = re.match(self._VALID_URL, url)
  3405. if mobj is None:
  3406. raise ExtractorError(u'Invalid URL: %s' % url)
  3407. playlist_id = mobj.group('id')
  3408. webpage = self._download_webpage(url, playlist_id)
  3409. m = re.search(r"PAGE.mix = (.*?);\n", webpage, flags=re.DOTALL)
  3410. if not m:
  3411. raise ExtractorError(u'Cannot find trax information')
  3412. json_like = m.group(1)
  3413. data = json.loads(json_like)
  3414. session = str(random.randint(0, 1000000000))
  3415. mix_id = data['id']
  3416. track_count = data['tracks_count']
  3417. first_url = 'http://8tracks.com/sets/%s/play?player=sm&mix_id=%s&format=jsonh' % (session, mix_id)
  3418. next_url = first_url
  3419. res = []
  3420. for i in itertools.count():
  3421. api_json = self._download_webpage(next_url, playlist_id,
  3422. note=u'Downloading song information %s/%s' % (str(i+1), track_count),
  3423. errnote=u'Failed to download song information')
  3424. api_data = json.loads(api_json)
  3425. track_data = api_data[u'set']['track']
  3426. info = {
  3427. 'id': track_data['id'],
  3428. 'url': track_data['track_file_stream_url'],
  3429. 'title': track_data['performer'] + u' - ' + track_data['name'],
  3430. 'raw_title': track_data['name'],
  3431. 'uploader_id': data['user']['login'],
  3432. 'ext': 'm4a',
  3433. }
  3434. res.append(info)
  3435. if api_data['set']['at_last_track']:
  3436. break
  3437. next_url = 'http://8tracks.com/sets/%s/next?player=sm&mix_id=%s&format=jsonh&track_id=%s' % (session, mix_id, track_data['id'])
  3438. return res
  3439. class KeekIE(InfoExtractor):
  3440. _VALID_URL = r'http://(?:www\.)?keek\.com/(?:!|\w+/keeks/)(?P<videoID>\w+)'
  3441. IE_NAME = u'keek'
  3442. def _real_extract(self, url):
  3443. m = re.match(self._VALID_URL, url)
  3444. video_id = m.group('videoID')
  3445. video_url = u'http://cdn.keek.com/keek/video/%s' % video_id
  3446. thumbnail = u'http://cdn.keek.com/keek/thumbnail/%s/w100/h75' % video_id
  3447. webpage = self._download_webpage(url, video_id)
  3448. m = re.search(r'<meta property="og:title" content="(?P<title>.*?)"', webpage)
  3449. title = unescapeHTML(m.group('title'))
  3450. m = re.search(r'<div class="user-name-and-bio">[\S\s]+?<h2>(?P<uploader>.+?)</h2>', webpage)
  3451. uploader = clean_html(m.group('uploader'))
  3452. info = {
  3453. 'id': video_id,
  3454. 'url': video_url,
  3455. 'ext': 'mp4',
  3456. 'title': title,
  3457. 'thumbnail': thumbnail,
  3458. 'uploader': uploader
  3459. }
  3460. return [info]
  3461. class TEDIE(InfoExtractor):
  3462. _VALID_URL=r'''http://www.ted.com/
  3463. (
  3464. ((?P<type_playlist>playlists)/(?P<playlist_id>\d+)) # We have a playlist
  3465. |
  3466. ((?P<type_talk>talks)) # We have a simple talk
  3467. )
  3468. /(?P<name>\w+) # Here goes the name and then ".html"
  3469. '''
  3470. @classmethod
  3471. def suitable(cls, url):
  3472. """Receives a URL and returns True if suitable for this IE."""
  3473. return re.match(cls._VALID_URL, url, re.VERBOSE) is not None
  3474. def _real_extract(self, url):
  3475. m=re.match(self._VALID_URL, url, re.VERBOSE)
  3476. if m.group('type_talk'):
  3477. return [self._talk_info(url)]
  3478. else :
  3479. playlist_id=m.group('playlist_id')
  3480. name=m.group('name')
  3481. self._downloader.to_screen(u'[%s] Getting info of playlist %s: "%s"' % (self.IE_NAME,playlist_id,name))
  3482. return self._playlist_videos_info(url,name,playlist_id)
  3483. def _talk_video_link(self,mediaSlug):
  3484. '''Returns the video link for that mediaSlug'''
  3485. return 'http://download.ted.com/talks/%s.mp4' % mediaSlug
  3486. def _playlist_videos_info(self,url,name,playlist_id=0):
  3487. '''Returns the videos of the playlist'''
  3488. video_RE=r'''
  3489. <li\ id="talk_(\d+)"([.\s]*?)data-id="(?P<video_id>\d+)"
  3490. ([.\s]*?)data-playlist_item_id="(\d+)"
  3491. ([.\s]*?)data-mediaslug="(?P<mediaSlug>.+?)"
  3492. '''
  3493. video_name_RE=r'<p\ class="talk-title"><a href="(?P<talk_url>/talks/(.+).html)">(?P<fullname>.+?)</a></p>'
  3494. webpage=self._download_webpage(url, playlist_id, 'Downloading playlist webpage')
  3495. m_videos=re.finditer(video_RE,webpage,re.VERBOSE)
  3496. m_names=re.finditer(video_name_RE,webpage)
  3497. info=[]
  3498. for m_video, m_name in zip(m_videos,m_names):
  3499. video_id=m_video.group('video_id')
  3500. talk_url='http://www.ted.com%s' % m_name.group('talk_url')
  3501. info.append(self._talk_info(talk_url,video_id))
  3502. return info
  3503. def _talk_info(self, url, video_id=0):
  3504. """Return the video for the talk in the url"""
  3505. m=re.match(self._VALID_URL, url,re.VERBOSE)
  3506. videoName=m.group('name')
  3507. webpage=self._download_webpage(url, video_id, 'Downloading \"%s\" page' % videoName)
  3508. # If the url includes the language we get the title translated
  3509. title_RE=r'<span id="altHeadline" >(?P<title>.*)</span>'
  3510. title=re.search(title_RE, webpage).group('title')
  3511. info_RE=r'''<script\ type="text/javascript">var\ talkDetails\ =(.*?)
  3512. "id":(?P<videoID>[\d]+).*?
  3513. "mediaSlug":"(?P<mediaSlug>[\w\d]+?)"'''
  3514. thumb_RE=r'</span>[\s.]*</div>[\s.]*<img src="(?P<thumbnail>.*?)"'
  3515. thumb_match=re.search(thumb_RE,webpage)
  3516. info_match=re.search(info_RE,webpage,re.VERBOSE)
  3517. video_id=info_match.group('videoID')
  3518. mediaSlug=info_match.group('mediaSlug')
  3519. video_url=self._talk_video_link(mediaSlug)
  3520. info = {
  3521. 'id': video_id,
  3522. 'url': video_url,
  3523. 'ext': 'mp4',
  3524. 'title': title,
  3525. 'thumbnail': thumb_match.group('thumbnail')
  3526. }
  3527. return info
  3528. class MySpassIE(InfoExtractor):
  3529. _VALID_URL = r'http://www.myspass.de/.*'
  3530. def _real_extract(self, url):
  3531. META_DATA_URL_TEMPLATE = 'http://www.myspass.de/myspass/includes/apps/video/getvideometadataxml.php?id=%s'
  3532. # video id is the last path element of the URL
  3533. # usually there is a trailing slash, so also try the second but last
  3534. url_path = compat_urllib_parse_urlparse(url).path
  3535. url_parent_path, video_id = os.path.split(url_path)
  3536. if not video_id:
  3537. _, video_id = os.path.split(url_parent_path)
  3538. # get metadata
  3539. metadata_url = META_DATA_URL_TEMPLATE % video_id
  3540. metadata_text = self._download_webpage(metadata_url, video_id)
  3541. metadata = xml.etree.ElementTree.fromstring(metadata_text.encode('utf-8'))
  3542. # extract values from metadata
  3543. url_flv_el = metadata.find('url_flv')
  3544. if url_flv_el is None:
  3545. self._downloader.report_error(u'unable to extract download url')
  3546. return
  3547. video_url = url_flv_el.text
  3548. extension = os.path.splitext(video_url)[1][1:]
  3549. title_el = metadata.find('title')
  3550. if title_el is None:
  3551. self._downloader.report_error(u'unable to extract title')
  3552. return
  3553. title = title_el.text
  3554. format_id_el = metadata.find('format_id')
  3555. if format_id_el is None:
  3556. format = ext
  3557. else:
  3558. format = format_id_el.text
  3559. description_el = metadata.find('description')
  3560. if description_el is not None:
  3561. description = description_el.text
  3562. else:
  3563. description = None
  3564. imagePreview_el = metadata.find('imagePreview')
  3565. if imagePreview_el is not None:
  3566. thumbnail = imagePreview_el.text
  3567. else:
  3568. thumbnail = None
  3569. info = {
  3570. 'id': video_id,
  3571. 'url': video_url,
  3572. 'title': title,
  3573. 'ext': extension,
  3574. 'format': format,
  3575. 'thumbnail': thumbnail,
  3576. 'description': description
  3577. }
  3578. return [info]
  3579. class SpiegelIE(InfoExtractor):
  3580. _VALID_URL = r'https?://(?:www\.)?spiegel\.de/video/[^/]*-(?P<videoID>[0-9]+)(?:\.html)?(?:#.*)?$'
  3581. def _real_extract(self, url):
  3582. m = re.match(self._VALID_URL, url)
  3583. video_id = m.group('videoID')
  3584. webpage = self._download_webpage(url, video_id)
  3585. m = re.search(r'<div class="spVideoTitle">(.*?)</div>', webpage)
  3586. if not m:
  3587. raise ExtractorError(u'Cannot find title')
  3588. video_title = unescapeHTML(m.group(1))
  3589. xml_url = u'http://video2.spiegel.de/flash/' + video_id + u'.xml'
  3590. xml_code = self._download_webpage(xml_url, video_id,
  3591. note=u'Downloading XML', errnote=u'Failed to download XML')
  3592. idoc = xml.etree.ElementTree.fromstring(xml_code)
  3593. last_type = idoc[-1]
  3594. filename = last_type.findall('./filename')[0].text
  3595. duration = float(last_type.findall('./duration')[0].text)
  3596. video_url = 'http://video2.spiegel.de/flash/' + filename
  3597. video_ext = filename.rpartition('.')[2]
  3598. info = {
  3599. 'id': video_id,
  3600. 'url': video_url,
  3601. 'ext': video_ext,
  3602. 'title': video_title,
  3603. 'duration': duration,
  3604. }
  3605. return [info]
  3606. class LiveLeakIE(InfoExtractor):
  3607. _VALID_URL = r'^(?:http?://)?(?:\w+\.)?liveleak\.com/view\?(?:.*?)i=(?P<video_id>[\w_]+)(?:.*)'
  3608. IE_NAME = u'liveleak'
  3609. def _real_extract(self, url):
  3610. mobj = re.match(self._VALID_URL, url)
  3611. if mobj is None:
  3612. self._downloader.trouble(u'ERROR: invalid URL: %s' % url)
  3613. return
  3614. video_id = mobj.group('video_id')
  3615. webpage = self._download_webpage(url, video_id)
  3616. m = re.search(r'file: "(.*?)",', webpage)
  3617. if not m:
  3618. self._downloader.report_error(u'unable to find video url')
  3619. return
  3620. video_url = m.group(1)
  3621. m = re.search(r'<meta property="og:title" content="(?P<title>.*?)"', webpage)
  3622. if not m:
  3623. self._downloader.trouble(u'Cannot find video title')
  3624. title = unescapeHTML(m.group('title')).replace('LiveLeak.com -', '').strip()
  3625. m = re.search(r'<meta property="og:description" content="(?P<desc>.*?)"', webpage)
  3626. if m:
  3627. desc = unescapeHTML(m.group('desc'))
  3628. else:
  3629. desc = None
  3630. m = re.search(r'By:.*?(\w+)</a>', webpage)
  3631. if m:
  3632. uploader = clean_html(m.group(1))
  3633. else:
  3634. uploader = None
  3635. info = {
  3636. 'id': video_id,
  3637. 'url': video_url,
  3638. 'ext': 'mp4',
  3639. 'title': title,
  3640. 'description': desc,
  3641. 'uploader': uploader
  3642. }
  3643. return [info]
  3644. class ARDIE(InfoExtractor):
  3645. _VALID_URL = r'^(?:https?://)?(?:(?:www\.)?ardmediathek\.de|mediathek\.daserste\.de)/(?:.*/)(?P<video_id>[^/\?]+)(?:\?.*)?'
  3646. _TITLE = r'<h1(?: class="boxTopHeadline")?>(?P<title>.*)</h1>'
  3647. _MEDIA_STREAM = r'mediaCollection\.addMediaStream\((?P<media_type>\d+), (?P<quality>\d+), "(?P<rtmp_url>[^"]*)", "(?P<video_url>[^"]*)", "[^"]*"\)'
  3648. def _real_extract(self, url):
  3649. # determine video id from url
  3650. m = re.match(self._VALID_URL, url)
  3651. numid = re.search(r'documentId=([0-9]+)', url)
  3652. if numid:
  3653. video_id = numid.group(1)
  3654. else:
  3655. video_id = m.group('video_id')
  3656. # determine title and media streams from webpage
  3657. html = self._download_webpage(url, video_id)
  3658. title = re.search(self._TITLE, html).group('title')
  3659. streams = [m.groupdict() for m in re.finditer(self._MEDIA_STREAM, html)]
  3660. if not streams:
  3661. assert '"fsk"' in html
  3662. self._downloader.report_error(u'this video is only available after 8:00 pm')
  3663. return
  3664. # choose default media type and highest quality for now
  3665. stream = max([s for s in streams if int(s["media_type"]) == 0],
  3666. key=lambda s: int(s["quality"]))
  3667. # there's two possibilities: RTMP stream or HTTP download
  3668. info = {'id': video_id, 'title': title, 'ext': 'mp4'}
  3669. if stream['rtmp_url']:
  3670. self._downloader.to_screen(u'[%s] RTMP download detected' % self.IE_NAME)
  3671. assert stream['video_url'].startswith('mp4:')
  3672. info["url"] = stream["rtmp_url"]
  3673. info["play_path"] = stream['video_url']
  3674. else:
  3675. assert stream["video_url"].endswith('.mp4')
  3676. info["url"] = stream["video_url"]
  3677. return [info]
  3678. def gen_extractors():
  3679. """ Return a list of an instance of every supported extractor.
  3680. The order does matter; the first extractor matched is the one handling the URL.
  3681. """
  3682. return [
  3683. YoutubePlaylistIE(),
  3684. YoutubeChannelIE(),
  3685. YoutubeUserIE(),
  3686. YoutubeSearchIE(),
  3687. YoutubeIE(),
  3688. MetacafeIE(),
  3689. DailymotionIE(),
  3690. GoogleSearchIE(),
  3691. PhotobucketIE(),
  3692. YahooIE(),
  3693. YahooSearchIE(),
  3694. DepositFilesIE(),
  3695. FacebookIE(),
  3696. BlipTVUserIE(),
  3697. BlipTVIE(),
  3698. VimeoIE(),
  3699. MyVideoIE(),
  3700. ComedyCentralIE(),
  3701. EscapistIE(),
  3702. CollegeHumorIE(),
  3703. XVideosIE(),
  3704. SoundcloudSetIE(),
  3705. SoundcloudIE(),
  3706. InfoQIE(),
  3707. MixcloudIE(),
  3708. StanfordOpenClassroomIE(),
  3709. MTVIE(),
  3710. YoukuIE(),
  3711. XNXXIE(),
  3712. YouJizzIE(),
  3713. PornotubeIE(),
  3714. YouPornIE(),
  3715. GooglePlusIE(),
  3716. ArteTvIE(),
  3717. NBAIE(),
  3718. WorldStarHipHopIE(),
  3719. JustinTVIE(),
  3720. FunnyOrDieIE(),
  3721. SteamIE(),
  3722. UstreamIE(),
  3723. RBMARadioIE(),
  3724. EightTracksIE(),
  3725. KeekIE(),
  3726. TEDIE(),
  3727. MySpassIE(),
  3728. SpiegelIE(),
  3729. LiveLeakIE(),
  3730. ARDIE(),
  3731. GenericIE()
  3732. ]