[cleanup] Misc (#8968)
[yt-dlp.git] / yt_dlp / extractor / mediasite.py
blob7ea78ab69184ae2f6246f34f8def4dee7e782953
1 import re
2 import json
4 from .common import InfoExtractor
5 from ..compat import (
6 compat_str,
7 compat_urlparse,
9 from ..utils import (
10 ExtractorError,
11 float_or_none,
12 mimetype2ext,
13 str_or_none,
14 try_call,
15 try_get,
16 smuggle_url,
17 unsmuggle_url,
18 url_or_none,
19 urljoin,
23 _ID_RE = r'(?:[0-9a-f]{32,34}|[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12,14})'
26 class MediasiteIE(InfoExtractor):
27 _VALID_URL = r'(?xi)https?://[^/]+/Mediasite/(?:Play|Showcase/[^/#?]+/Presentation)/(?P<id>%s)(?P<query>\?[^#]+|)' % _ID_RE
28 _EMBED_REGEX = [r'(?xi)<iframe\b[^>]+\bsrc=(["\'])(?P<url>(?:(?:https?:)?//[^/]+)?/Mediasite/Play/%s(?:\?.*?)?)\1' % _ID_RE]
29 _TESTS = [
31 'url': 'https://hitsmediaweb.h-its.org/mediasite/Play/2db6c271681e4f199af3c60d1f82869b1d',
32 'info_dict': {
33 'id': '2db6c271681e4f199af3c60d1f82869b1d',
34 'ext': 'mp4',
35 'title': 'Lecture: Tuesday, September 20, 2016 - Sir Andrew Wiles',
36 'description': 'Sir Andrew Wiles: “Equations in arithmetic”\\n\\nI will describe some of the interactions between modern number theory and the problem of solving equations in rational numbers or integers\\u0027.',
37 'timestamp': 1474268400.0,
38 'upload_date': '20160919',
42 'url': 'http://mediasite.uib.no/Mediasite/Play/90bb363295d945d6b548c867d01181361d?catalog=a452b7df-9ae1-46b7-a3ba-aceeb285f3eb',
43 'info_dict': {
44 'id': '90bb363295d945d6b548c867d01181361d',
45 'ext': 'mp4',
46 'upload_date': '20150429',
47 'title': '5) IT-forum 2015-Dag 1 - Dungbeetle - How and why Rain created a tiny bug tracker for Unity',
48 'timestamp': 1430311380.0,
52 'url': 'https://collegerama.tudelft.nl/Mediasite/Play/585a43626e544bdd97aeb71a0ec907a01d',
53 'md5': '481fda1c11f67588c0d9d8fbdced4e39',
54 'info_dict': {
55 'id': '585a43626e544bdd97aeb71a0ec907a01d',
56 'ext': 'mp4',
57 'title': 'Een nieuwe wereld: waarden, bewustzijn en techniek van de mensheid 2.0.',
58 'description': '',
59 'thumbnail': r're:^https?://.*\.jpg(?:\?.*)?$',
60 'duration': 7713.088,
61 'timestamp': 1413309600,
62 'upload_date': '20141014',
66 'url': 'https://collegerama.tudelft.nl/Mediasite/Play/86a9ea9f53e149079fbdb4202b521ed21d?catalog=fd32fd35-6c99-466c-89d4-cd3c431bc8a4',
67 'md5': 'ef1fdded95bdf19b12c5999949419c92',
68 'info_dict': {
69 'id': '86a9ea9f53e149079fbdb4202b521ed21d',
70 'ext': 'wmv',
71 'title': '64ste Vakantiecursus: Afvalwater',
72 'description': 'md5:7fd774865cc69d972f542b157c328305',
73 'thumbnail': r're:^https?://.*\.jpg(?:\?.*?)?$',
74 'duration': 10853,
75 'timestamp': 1326446400,
76 'upload_date': '20120113',
80 'url': 'http://digitalops.sandia.gov/Mediasite/Play/24aace4429fc450fb5b38cdbf424a66e1d',
81 'md5': '9422edc9b9a60151727e4b6d8bef393d',
82 'info_dict': {
83 'id': '24aace4429fc450fb5b38cdbf424a66e1d',
84 'ext': 'mp4',
85 'title': 'Xyce Software Training - Section 1',
86 'description': r're:(?s)SAND Number: SAND 2013-7800.{200,}',
87 'upload_date': '20120409',
88 'timestamp': 1333983600,
89 'duration': 7794,
93 'url': 'https://collegerama.tudelft.nl/Mediasite/Showcase/livebroadcast/Presentation/ada7020854f743c49fbb45c9ec7dbb351d',
94 'only_matching': True,
97 'url': 'https://mediasite.ntnu.no/Mediasite/Showcase/default/Presentation/7d8b913259334b688986e970fae6fcb31d',
98 'only_matching': True,
101 # dashed id
102 'url': 'https://hitsmediaweb.h-its.org/mediasite/Play/2db6c271-681e-4f19-9af3-c60d1f82869b1d',
103 'only_matching': True,
107 # look in Mediasite.Core.js (Mediasite.ContentStreamType[*])
108 _STREAM_TYPES = {
109 0: 'video1', # the main video
110 2: 'slide',
111 3: 'presentation',
112 4: 'video2', # screencast?
113 5: 'video3',
116 @classmethod
117 def _extract_embed_urls(cls, url, webpage):
118 for embed_url in super()._extract_embed_urls(url, webpage):
119 yield smuggle_url(embed_url, {'UrlReferrer': url})
121 def __extract_slides(self, *, stream_id, snum, Stream, duration, images):
122 slide_base_url = Stream['SlideBaseUrl']
124 fname_template = Stream['SlideImageFileNameTemplate']
125 if fname_template != 'slide_{0:D4}.jpg':
126 self.report_warning('Unusual slide file name template; report a bug if slide downloading fails')
127 fname_template = re.sub(r'\{0:D([0-9]+)\}', r'{0:0\1}', fname_template)
129 fragments = []
130 for i, slide in enumerate(Stream['Slides']):
131 if i == 0:
132 if slide['Time'] > 0:
133 default_slide = images.get('DefaultSlide')
134 if default_slide is None:
135 default_slide = images.get('DefaultStreamImage')
136 if default_slide is not None:
137 default_slide = default_slide['ImageFilename']
138 if default_slide is not None:
139 fragments.append({
140 'path': default_slide,
141 'duration': slide['Time'] / 1000,
144 next_time = try_call(
145 lambda: Stream['Slides'][i + 1]['Time'],
146 lambda: duration,
147 lambda: slide['Time'],
148 expected_type=(int, float))
150 fragments.append({
151 'path': fname_template.format(slide.get('Number', i + 1)),
152 'duration': (next_time - slide['Time']) / 1000
155 return {
156 'format_id': '%s-%u.slides' % (stream_id, snum),
157 'ext': 'mhtml',
158 'url': slide_base_url,
159 'protocol': 'mhtml',
160 'acodec': 'none',
161 'vcodec': 'none',
162 'format_note': 'Slides',
163 'fragments': fragments,
164 'fragment_base_url': slide_base_url,
167 def _real_extract(self, url):
168 url, data = unsmuggle_url(url, {})
169 mobj = self._match_valid_url(url)
170 resource_id = mobj.group('id')
171 query = mobj.group('query')
173 webpage, urlh = self._download_webpage_handle(url, resource_id) # XXX: add UrlReferrer?
174 redirect_url = urlh.url
176 # XXX: might have also extracted UrlReferrer and QueryString from the html
177 service_path = compat_urlparse.urljoin(redirect_url, self._html_search_regex(
178 r'<div[^>]+\bid=["\']ServicePath[^>]+>(.+?)</div>', webpage, resource_id,
179 default='/Mediasite/PlayerService/PlayerService.svc/json'))
181 player_options = self._download_json(
182 '%s/GetPlayerOptions' % service_path, resource_id,
183 headers={
184 'Content-type': 'application/json; charset=utf-8',
185 'X-Requested-With': 'XMLHttpRequest',
187 data=json.dumps({
188 'getPlayerOptionsRequest': {
189 'ResourceId': resource_id,
190 'QueryString': query,
191 'UrlReferrer': data.get('UrlReferrer', ''),
192 'UseScreenReader': False,
194 }).encode('utf-8'))['d']
196 presentation = player_options['Presentation']
197 title = presentation['Title']
199 if presentation is None:
200 raise ExtractorError(
201 'Mediasite says: %s' % player_options['PlayerPresentationStatusMessage'],
202 expected=True)
204 thumbnails = []
205 formats = []
206 for snum, Stream in enumerate(presentation['Streams']):
207 stream_type = Stream.get('StreamType')
208 if stream_type is None:
209 continue
211 video_urls = Stream.get('VideoUrls')
212 if not isinstance(video_urls, list):
213 video_urls = []
215 stream_id = self._STREAM_TYPES.get(
216 stream_type, 'type%u' % stream_type)
218 stream_formats = []
219 for unum, VideoUrl in enumerate(video_urls):
220 video_url = url_or_none(VideoUrl.get('Location'))
221 if not video_url:
222 continue
223 # XXX: if Stream.get('CanChangeScheme', False), switch scheme to HTTP/HTTPS
225 media_type = VideoUrl.get('MediaType')
226 if media_type == 'SS':
227 stream_formats.extend(self._extract_ism_formats(
228 video_url, resource_id,
229 ism_id='%s-%u.%u' % (stream_id, snum, unum),
230 fatal=False))
231 elif media_type == 'Dash':
232 stream_formats.extend(self._extract_mpd_formats(
233 video_url, resource_id,
234 mpd_id='%s-%u.%u' % (stream_id, snum, unum),
235 fatal=False))
236 else:
237 stream_formats.append({
238 'format_id': '%s-%u.%u' % (stream_id, snum, unum),
239 'url': video_url,
240 'ext': mimetype2ext(VideoUrl.get('MimeType')),
243 if Stream.get('HasSlideContent', False):
244 images = player_options['PlayerLayoutOptions']['Images']
245 stream_formats.append(self.__extract_slides(
246 stream_id=stream_id,
247 snum=snum,
248 Stream=Stream,
249 duration=presentation.get('Duration'),
250 images=images,
253 # disprefer 'secondary' streams
254 if stream_type != 0:
255 for fmt in stream_formats:
256 fmt['quality'] = -10
258 thumbnail_url = Stream.get('ThumbnailUrl')
259 if thumbnail_url:
260 thumbnails.append({
261 'id': '%s-%u' % (stream_id, snum),
262 'url': urljoin(redirect_url, thumbnail_url),
263 'preference': -1 if stream_type != 0 else 0,
265 formats.extend(stream_formats)
267 # XXX: Presentation['Presenters']
268 # XXX: Presentation['Transcript']
270 return {
271 'id': resource_id,
272 'title': title,
273 'description': presentation.get('Description'),
274 'duration': float_or_none(presentation.get('Duration'), 1000),
275 'timestamp': float_or_none(presentation.get('UnixTime'), 1000),
276 'formats': formats,
277 'thumbnails': thumbnails,
281 class MediasiteCatalogIE(InfoExtractor):
282 _VALID_URL = r'''(?xi)
283 (?P<url>https?://[^/]+/Mediasite)
284 /Catalog/Full/
285 (?P<catalog_id>{0})
287 /(?P<current_folder_id>{0})
288 /(?P<root_dynamic_folder_id>{0})
290 '''.format(_ID_RE)
291 _TESTS = [{
292 'url': 'http://events7.mediasite.com/Mediasite/Catalog/Full/631f9e48530d454381549f955d08c75e21',
293 'info_dict': {
294 'id': '631f9e48530d454381549f955d08c75e21',
295 'title': 'WCET Summit: Adaptive Learning in Higher Ed: Improving Outcomes Dynamically',
297 'playlist_count': 6,
298 'expected_warnings': ['is not a supported codec'],
299 }, {
300 # with CurrentFolderId and RootDynamicFolderId
301 'url': 'https://medaudio.medicine.iu.edu/Mediasite/Catalog/Full/9518c4a6c5cf4993b21cbd53e828a92521/97a9db45f7ab47428c77cd2ed74bb98f14/9518c4a6c5cf4993b21cbd53e828a92521',
302 'info_dict': {
303 'id': '9518c4a6c5cf4993b21cbd53e828a92521',
304 'title': 'IUSM Family and Friends Sessions',
306 'playlist_count': 2,
307 }, {
308 'url': 'http://uipsyc.mediasite.com/mediasite/Catalog/Full/d5d79287c75243c58c50fef50174ec1b21',
309 'only_matching': True,
310 }, {
311 # no AntiForgeryToken
312 'url': 'https://live.libraries.psu.edu/Mediasite/Catalog/Full/8376d4b24dd1457ea3bfe4cf9163feda21',
313 'only_matching': True,
314 }, {
315 'url': 'https://medaudio.medicine.iu.edu/Mediasite/Catalog/Full/9518c4a6c5cf4993b21cbd53e828a92521/97a9db45f7ab47428c77cd2ed74bb98f14/9518c4a6c5cf4993b21cbd53e828a92521',
316 'only_matching': True,
317 }, {
318 # dashed id
319 'url': 'http://events7.mediasite.com/Mediasite/Catalog/Full/631f9e48-530d-4543-8154-9f955d08c75e',
320 'only_matching': True,
323 def _real_extract(self, url):
324 mobj = self._match_valid_url(url)
325 mediasite_url = mobj.group('url')
326 catalog_id = mobj.group('catalog_id')
327 current_folder_id = mobj.group('current_folder_id') or catalog_id
328 root_dynamic_folder_id = mobj.group('root_dynamic_folder_id')
330 webpage = self._download_webpage(url, catalog_id)
332 # AntiForgeryToken is optional (e.g. [1])
333 # 1. https://live.libraries.psu.edu/Mediasite/Catalog/Full/8376d4b24dd1457ea3bfe4cf9163feda21
334 anti_forgery_token = self._search_regex(
335 r'AntiForgeryToken\s*:\s*(["\'])(?P<value>(?:(?!\1).)+)\1',
336 webpage, 'anti forgery token', default=None, group='value')
337 if anti_forgery_token:
338 anti_forgery_header = self._search_regex(
339 r'AntiForgeryHeaderName\s*:\s*(["\'])(?P<value>(?:(?!\1).)+)\1',
340 webpage, 'anti forgery header name',
341 default='X-SOFO-AntiForgeryHeader', group='value')
343 data = {
344 'IsViewPage': True,
345 'IsNewFolder': True,
346 'AuthTicket': None,
347 'CatalogId': catalog_id,
348 'CurrentFolderId': current_folder_id,
349 'RootDynamicFolderId': root_dynamic_folder_id,
350 'ItemsPerPage': 1000,
351 'PageIndex': 0,
352 'PermissionMask': 'Execute',
353 'CatalogSearchType': 'SearchInFolder',
354 'SortBy': 'Date',
355 'SortDirection': 'Descending',
356 'StartDate': None,
357 'EndDate': None,
358 'StatusFilterList': None,
359 'PreviewKey': None,
360 'Tags': [],
363 headers = {
364 'Content-Type': 'application/json; charset=UTF-8',
365 'Referer': url,
366 'X-Requested-With': 'XMLHttpRequest',
368 if anti_forgery_token:
369 headers[anti_forgery_header] = anti_forgery_token
371 catalog = self._download_json(
372 '%s/Catalog/Data/GetPresentationsForFolder' % mediasite_url,
373 catalog_id, data=json.dumps(data).encode(), headers=headers)
375 entries = []
376 for video in catalog['PresentationDetailsList']:
377 if not isinstance(video, dict):
378 continue
379 video_id = str_or_none(video.get('Id'))
380 if not video_id:
381 continue
382 entries.append(self.url_result(
383 '%s/Play/%s' % (mediasite_url, video_id),
384 ie=MediasiteIE.ie_key(), video_id=video_id))
386 title = try_get(
387 catalog, lambda x: x['CurrentFolder']['Name'], compat_str)
389 return self.playlist_result(entries, catalog_id, title,)
392 class MediasiteNamedCatalogIE(InfoExtractor):
393 _VALID_URL = r'(?xi)(?P<url>https?://[^/]+/Mediasite)/Catalog/catalogs/(?P<catalog_name>[^/?#&]+)'
394 _TESTS = [{
395 'url': 'https://msite.misis.ru/Mediasite/Catalog/catalogs/2016-industrial-management-skriabin-o-o',
396 'only_matching': True,
399 def _real_extract(self, url):
400 mobj = self._match_valid_url(url)
401 mediasite_url = mobj.group('url')
402 catalog_name = mobj.group('catalog_name')
404 webpage = self._download_webpage(url, catalog_name)
406 catalog_id = self._search_regex(
407 r'CatalogId\s*:\s*["\'](%s)' % _ID_RE, webpage, 'catalog id')
409 return self.url_result(
410 '%s/Catalog/Full/%s' % (mediasite_url, catalog_id),
411 ie=MediasiteCatalogIE.ie_key(), video_id=catalog_id)