[mediasite:catalog] Add extractor (closes #20507)
[youtube-dl] / youtube_dl / 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}'
26
27
28 class MediasiteIE(InfoExtractor):
29     _VALID_URL = r'(?xi)https?://[^/]+/Mediasite/(?:Play|Showcase/(?:default|livebroadcast)/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
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     @staticmethod
113     def _extract_urls(webpage):
114         return [
115             unescapeHTML(mobj.group('url'))
116             for mobj in re.finditer(
117                 r'(?xi)<iframe\b[^>]+\bsrc=(["\'])(?P<url>(?:(?:https?:)?//[^/]+)?/Mediasite/Play/%s(?:\?.*?)?)\1' % _ID_RE,
118                 webpage)]
119
120     def _real_extract(self, url):
121         url, data = unsmuggle_url(url, {})
122         mobj = re.match(self._VALID_URL, url)
123         resource_id = mobj.group('id')
124         query = mobj.group('query')
125
126         webpage, urlh = self._download_webpage_handle(url, resource_id)  # XXX: add UrlReferrer?
127         redirect_url = compat_str(urlh.geturl())
128
129         # XXX: might have also extracted UrlReferrer and QueryString from the html
130         service_path = compat_urlparse.urljoin(redirect_url, self._html_search_regex(
131             r'<div[^>]+\bid=["\']ServicePath[^>]+>(.+?)</div>', webpage, resource_id,
132             default='/Mediasite/PlayerService/PlayerService.svc/json'))
133
134         player_options = self._download_json(
135             '%s/GetPlayerOptions' % service_path, resource_id,
136             headers={
137                 'Content-type': 'application/json; charset=utf-8',
138                 'X-Requested-With': 'XMLHttpRequest',
139             },
140             data=json.dumps({
141                 'getPlayerOptionsRequest': {
142                     'ResourceId': resource_id,
143                     'QueryString': query,
144                     'UrlReferrer': data.get('UrlReferrer', ''),
145                     'UseScreenReader': False,
146                 }
147             }).encode('utf-8'))['d']
148
149         presentation = player_options['Presentation']
150         title = presentation['Title']
151
152         if presentation is None:
153             raise ExtractorError(
154                 'Mediasite says: %s' % player_options['PlayerPresentationStatusMessage'],
155                 expected=True)
156
157         thumbnails = []
158         formats = []
159         for snum, Stream in enumerate(presentation['Streams']):
160             stream_type = Stream.get('StreamType')
161             if stream_type is None:
162                 continue
163
164             video_urls = Stream.get('VideoUrls')
165             if not isinstance(video_urls, list):
166                 video_urls = []
167
168             stream_id = self._STREAM_TYPES.get(
169                 stream_type, 'type%u' % stream_type)
170
171             stream_formats = []
172             for unum, VideoUrl in enumerate(video_urls):
173                 video_url = url_or_none(VideoUrl.get('Location'))
174                 if not video_url:
175                     continue
176                 # XXX: if Stream.get('CanChangeScheme', False), switch scheme to HTTP/HTTPS
177
178                 media_type = VideoUrl.get('MediaType')
179                 if media_type == 'SS':
180                     stream_formats.extend(self._extract_ism_formats(
181                         video_url, resource_id,
182                         ism_id='%s-%u.%u' % (stream_id, snum, unum),
183                         fatal=False))
184                 elif media_type == 'Dash':
185                     stream_formats.extend(self._extract_mpd_formats(
186                         video_url, resource_id,
187                         mpd_id='%s-%u.%u' % (stream_id, snum, unum),
188                         fatal=False))
189                 else:
190                     stream_formats.append({
191                         'format_id': '%s-%u.%u' % (stream_id, snum, unum),
192                         'url': video_url,
193                         'ext': mimetype2ext(VideoUrl.get('MimeType')),
194                     })
195
196             # TODO: if Stream['HasSlideContent']:
197             # synthesise an MJPEG video stream '%s-%u.slides' % (stream_type, snum)
198             # from Stream['Slides']
199             # this will require writing a custom downloader...
200
201             # disprefer 'secondary' streams
202             if stream_type != 0:
203                 for fmt in stream_formats:
204                     fmt['preference'] = -1
205
206             thumbnail_url = Stream.get('ThumbnailUrl')
207             if thumbnail_url:
208                 thumbnails.append({
209                     'id': '%s-%u' % (stream_id, snum),
210                     'url': urljoin(redirect_url, thumbnail_url),
211                     'preference': -1 if stream_type != 0 else 0,
212                 })
213             formats.extend(stream_formats)
214
215         self._sort_formats(formats)
216
217         # XXX: Presentation['Presenters']
218         # XXX: Presentation['Transcript']
219
220         return {
221             'id': resource_id,
222             'title': title,
223             'description': presentation.get('Description'),
224             'duration': float_or_none(presentation.get('Duration'), 1000),
225             'timestamp': float_or_none(presentation.get('UnixTime'), 1000),
226             'formats': formats,
227             'thumbnails': thumbnails,
228         }
229
230
231 class MediasiteCatalogIE(InfoExtractor):
232     _VALID_URL = r'''(?xi)
233                         (?P<url>https?://[^/]+/Mediasite)
234                         /Catalog/Full/
235                         (?P<catalog_id>{0})
236                         (?:
237                             /(?P<current_folder_id>{0})
238                             /(?P<root_dynamic_folder_id>{0})
239                         )?
240                     '''.format(_ID_RE)
241     _TESTS = [{
242         'url': 'http://events7.mediasite.com/Mediasite/Catalog/Full/631f9e48530d454381549f955d08c75e21',
243         'info_dict': {
244             'id': '631f9e48530d454381549f955d08c75e21',
245             'title': 'WCET Summit: Adaptive Learning in Higher Ed: Improving Outcomes Dynamically',
246         },
247         'playlist_count': 6,
248         'expected_warnings': ['is not a supported codec'],
249     }, {
250         # with CurrentFolderId and RootDynamicFolderId
251         'url': 'https://medaudio.medicine.iu.edu/Mediasite/Catalog/Full/9518c4a6c5cf4993b21cbd53e828a92521/97a9db45f7ab47428c77cd2ed74bb98f14/9518c4a6c5cf4993b21cbd53e828a92521',
252         'info_dict': {
253             'id': '9518c4a6c5cf4993b21cbd53e828a92521',
254             'title': 'IUSM Family and Friends Sessions',
255         },
256         'playlist_count': 2,
257     }, {
258         'url': 'http://uipsyc.mediasite.com/mediasite/Catalog/Full/d5d79287c75243c58c50fef50174ec1b21',
259         'only_matching': True,
260     }, {
261         # no AntiForgeryToken
262         'url': 'https://live.libraries.psu.edu/Mediasite/Catalog/Full/8376d4b24dd1457ea3bfe4cf9163feda21',
263         'only_matching': True,
264     }, {
265         'url': 'https://medaudio.medicine.iu.edu/Mediasite/Catalog/Full/9518c4a6c5cf4993b21cbd53e828a92521/97a9db45f7ab47428c77cd2ed74bb98f14/9518c4a6c5cf4993b21cbd53e828a92521',
266         'only_matching': True,
267     }]
268
269     def _real_extract(self, url):
270         mobj = re.match(self._VALID_URL, url)
271         mediasite_url = mobj.group('url')
272         catalog_id = mobj.group('catalog_id')
273         current_folder_id = mobj.group('current_folder_id') or catalog_id
274         root_dynamic_folder_id = mobj.group('root_dynamic_folder_id')
275
276         webpage = self._download_webpage(url, catalog_id)
277
278         # AntiForgeryToken is optional (e.g. [1])
279         # 1. https://live.libraries.psu.edu/Mediasite/Catalog/Full/8376d4b24dd1457ea3bfe4cf9163feda21
280         anti_forgery_token = self._search_regex(
281             r'AntiForgeryToken\s*:\s*(["\'])(?P<value>(?:(?!\1).)+)\1',
282             webpage, 'anti forgery token', default=None, group='value')
283         if anti_forgery_token:
284             anti_forgery_header = self._search_regex(
285                 r'AntiForgeryHeaderName\s*:\s*(["\'])(?P<value>(?:(?!\1).)+)\1',
286                 webpage, 'anti forgery header name',
287                 default='X-SOFO-AntiForgeryHeader', group='value')
288
289         data = {
290             'IsViewPage': True,
291             'IsNewFolder': True,
292             'AuthTicket': None,
293             'CatalogId': catalog_id,
294             'CurrentFolderId': current_folder_id,
295             'RootDynamicFolderId': root_dynamic_folder_id,
296             'ItemsPerPage': 1000,
297             'PageIndex': 0,
298             'PermissionMask': 'Execute',
299             'CatalogSearchType': 'SearchInFolder',
300             'SortBy': 'Date',
301             'SortDirection': 'Descending',
302             'StartDate': None,
303             'EndDate': None,
304             'StatusFilterList': None,
305             'PreviewKey': None,
306             'Tags': [],
307         }
308
309         headers = {
310             'Content-Type': 'application/json; charset=UTF-8',
311             'Referer': url,
312             'X-Requested-With': 'XMLHttpRequest',
313         }
314         if anti_forgery_token:
315             headers[anti_forgery_header] = anti_forgery_token
316
317         catalog = self._download_json(
318             '%s/Catalog/Data/GetPresentationsForFolder' % mediasite_url,
319             catalog_id, data=json.dumps(data).encode(), headers=headers)
320
321         entries = []
322         for video in catalog['PresentationDetailsList']:
323             if not isinstance(video, dict):
324                 continue
325             video_id = str_or_none(video.get('Id'))
326             if not video_id:
327                 continue
328             entries.append(self.url_result(
329                 '%s/Play/%s' % (mediasite_url, video_id),
330                 ie=MediasiteIE.ie_key(), video_id=video_id))
331
332         title = try_get(
333             catalog, lambda x: x['CurrentFolder']['Name'], compat_str)
334
335         return self.playlist_result(entries, catalog_id, title,)