InfoExtractors.py 167 KB

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