InfoExtractors.py 172 KB

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