]> jfr.im git - yt-dlp.git/blame - yt_dlp/extractor/mediasite.py
[ie/orf:on] Improve extraction (#9677)
[yt-dlp.git] / yt_dlp / extractor / mediasite.py
CommitLineData
8056c854 1import re
2import json
3
4from .common import InfoExtractor
2ca7ed41
S
5from ..compat import (
6 compat_str,
7 compat_urlparse,
8)
8056c854 9from ..utils import (
10 ExtractorError,
8056c854 11 float_or_none,
2ca7ed41 12 mimetype2ext,
4014a486 13 str_or_none,
c4f60dd7 14 try_call,
4014a486 15 try_get,
bfd973ec 16 smuggle_url,
2ca7ed41 17 unsmuggle_url,
3052a30d 18 url_or_none,
2ca7ed41 19 urljoin,
8056c854 20)
21
22
efee62ac 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})'
4014a486
S
24
25
8056c854 26class MediasiteIE(InfoExtractor):
c72967d5 27 _VALID_URL = r'(?xi)https?://[^/]+/Mediasite/(?:Play|Showcase/[^/#?]+/Presentation)/(?P<id>%s)(?P<query>\?[^#]+|)' % _ID_RE
bfd973ec 28 _EMBED_REGEX = [r'(?xi)<iframe\b[^>]+\bsrc=(["\'])(?P<url>(?:(?:https?:)?//[^/]+)?/Mediasite/Play/%s(?:\?.*?)?)\1' % _ID_RE]
8056c854 29 _TESTS = [
30 {
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',
39 },
40 },
41 {
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,
49 },
50 },
51 {
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',
63 },
64 },
65 {
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',
77 },
78 },
79 {
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,
90 }
cfd13c4c
DV
91 },
92 {
93 'url': 'https://collegerama.tudelft.nl/Mediasite/Showcase/livebroadcast/Presentation/ada7020854f743c49fbb45c9ec7dbb351d',
94 'only_matching': True,
95 },
4ee18454
S
96 {
97 'url': 'https://mediasite.ntnu.no/Mediasite/Showcase/default/Presentation/7d8b913259334b688986e970fae6fcb31d',
98 'only_matching': True,
99 },
efee62ac
S
100 {
101 # dashed id
102 'url': 'https://hitsmediaweb.h-its.org/mediasite/Play/2db6c271-681e-4f19-9af3-c60d1f82869b1d',
103 'only_matching': True,
104 }
8056c854 105 ]
106
107 # look in Mediasite.Core.js (Mediasite.ContentStreamType[*])
108 _STREAM_TYPES = {
2ca7ed41 109 0: 'video1', # the main video
8056c854 110 2: 'slide',
111 3: 'presentation',
2ca7ed41 112 4: 'video2', # screencast?
8056c854 113 5: 'video3',
114 }
115
bfd973ec 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})
2ca7ed41 120
3fd4c2a5 121 def __extract_slides(self, *, stream_id, snum, Stream, duration, images):
122 slide_base_url = Stream['SlideBaseUrl']
123
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)
128
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,
142 })
143
c4f60dd7 144 next_time = try_call(
145 lambda: Stream['Slides'][i + 1]['Time'],
146 lambda: duration,
147 lambda: slide['Time'],
148 expected_type=(int, float))
3fd4c2a5 149
150 fragments.append({
151 'path': fname_template.format(slide.get('Number', i + 1)),
152 'duration': (next_time - slide['Time']) / 1000
153 })
154
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,
165 }
166
8056c854 167 def _real_extract(self, url):
168 url, data = unsmuggle_url(url, {})
5ad28e7f 169 mobj = self._match_valid_url(url)
2ca7ed41
S
170 resource_id = mobj.group('id')
171 query = mobj.group('query')
8056c854 172
2ca7ed41 173 webpage, urlh = self._download_webpage_handle(url, resource_id) # XXX: add UrlReferrer?
3d2623a8 174 redirect_url = urlh.url
8056c854 175
176 # XXX: might have also extracted UrlReferrer and QueryString from the html
2ca7ed41
S
177 service_path = compat_urlparse.urljoin(redirect_url, self._html_search_regex(
178 r'<div[^>]+\bid=["\']ServicePath[^>]+>(.+?)</div>', webpage, resource_id,
8056c854 179 default='/Mediasite/PlayerService/PlayerService.svc/json'))
180
2ca7ed41
S
181 player_options = self._download_json(
182 '%s/GetPlayerOptions' % service_path, resource_id,
8056c854 183 headers={
184 'Content-type': 'application/json; charset=utf-8',
185 'X-Requested-With': 'XMLHttpRequest',
186 },
187 data=json.dumps({
188 'getPlayerOptionsRequest': {
2ca7ed41
S
189 'ResourceId': resource_id,
190 'QueryString': query,
8056c854 191 'UrlReferrer': data.get('UrlReferrer', ''),
192 'UseScreenReader': False,
193 }
2ca7ed41
S
194 }).encode('utf-8'))['d']
195
196 presentation = player_options['Presentation']
197 title = presentation['Title']
198
199 if presentation is None:
200 raise ExtractorError(
201 'Mediasite says: %s' % player_options['PlayerPresentationStatusMessage'],
8056c854 202 expected=True)
203
204 thumbnails = []
205 formats = []
2ca7ed41
S
206 for snum, Stream in enumerate(presentation['Streams']):
207 stream_type = Stream.get('StreamType')
208 if stream_type is None:
209 continue
210
211 video_urls = Stream.get('VideoUrls')
212 if not isinstance(video_urls, list):
213 video_urls = []
214
215 stream_id = self._STREAM_TYPES.get(
216 stream_type, 'type%u' % stream_type)
8056c854 217
218 stream_formats = []
2ca7ed41 219 for unum, VideoUrl in enumerate(video_urls):
3052a30d
S
220 video_url = url_or_none(VideoUrl.get('Location'))
221 if not video_url:
2ca7ed41 222 continue
8056c854 223 # XXX: if Stream.get('CanChangeScheme', False), switch scheme to HTTP/HTTPS
224
2ca7ed41
S
225 media_type = VideoUrl.get('MediaType')
226 if media_type == 'SS':
8056c854 227 stream_formats.extend(self._extract_ism_formats(
2ca7ed41
S
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')),
241 })
8056c854 242
3fd4c2a5 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,
251 ))
8056c854 252
253 # disprefer 'secondary' streams
2ca7ed41 254 if stream_type != 0:
8056c854 255 for fmt in stream_formats:
f983b875 256 fmt['quality'] = -10
8056c854 257
2ca7ed41
S
258 thumbnail_url = Stream.get('ThumbnailUrl')
259 if thumbnail_url:
8056c854 260 thumbnails.append({
2ca7ed41
S
261 'id': '%s-%u' % (stream_id, snum),
262 'url': urljoin(redirect_url, thumbnail_url),
263 'preference': -1 if stream_type != 0 else 0,
8056c854 264 })
265 formats.extend(stream_formats)
266
8056c854 267 # XXX: Presentation['Presenters']
268 # XXX: Presentation['Transcript']
269
270 return {
2ca7ed41
S
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),
8056c854 276 'formats': formats,
277 'thumbnails': thumbnails,
278 }
4014a486
S
279
280
281class MediasiteCatalogIE(InfoExtractor):
282 _VALID_URL = r'''(?xi)
283 (?P<url>https?://[^/]+/Mediasite)
284 /Catalog/Full/
285 (?P<catalog_id>{0})
286 (?:
287 /(?P<current_folder_id>{0})
288 /(?P<root_dynamic_folder_id>{0})
289 )?
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',
296 },
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',
305 },
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,
efee62ac
S
317 }, {
318 # dashed id
319 'url': 'http://events7.mediasite.com/Mediasite/Catalog/Full/631f9e48-530d-4543-8154-9f955d08c75e',
320 'only_matching': True,
4014a486
S
321 }]
322
323 def _real_extract(self, url):
5ad28e7f 324 mobj = self._match_valid_url(url)
4014a486
S
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')
329
330 webpage = self._download_webpage(url, catalog_id)
331
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')
342
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': [],
361 }
362
363 headers = {
364 'Content-Type': 'application/json; charset=UTF-8',
365 'Referer': url,
366 'X-Requested-With': 'XMLHttpRequest',
367 }
368 if anti_forgery_token:
369 headers[anti_forgery_header] = anti_forgery_token
370
371 catalog = self._download_json(
372 '%s/Catalog/Data/GetPresentationsForFolder' % mediasite_url,
373 catalog_id, data=json.dumps(data).encode(), headers=headers)
374
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))
385
386 title = try_get(
387 catalog, lambda x: x['CurrentFolder']['Name'], compat_str)
388
389 return self.playlist_result(entries, catalog_id, title,)
efee62ac
S
390
391
392class 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,
397 }]
398
399 def _real_extract(self, url):
5ad28e7f 400 mobj = self._match_valid_url(url)
efee62ac
S
401 mediasite_url = mobj.group('url')
402 catalog_name = mobj.group('catalog_name')
403
404 webpage = self._download_webpage(url, catalog_name)
405
406 catalog_id = self._search_regex(
407 r'CatalogId\s*:\s*["\'](%s)' % _ID_RE, webpage, 'catalog id')
408
409 return self.url_result(
410 '%s/Catalog/Full/%s' % (mediasite_url, catalog_id),
411 ie=MediasiteCatalogIE.ie_key(), video_id=catalog_id)