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