InfoExtractors.py 177 KB

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