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