[mediasite] Relax _VALID_URL
[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     unescapeHTML,
17     unsmuggle_url,
18     url_or_none,
19     urljoin,
20 )
21
22
23 class MediasiteIE(InfoExtractor):
24     _VALID_URL = r'(?xi)https?://[^/]+/Mediasite/(?:Play|Showcase/livebroadcast/Presentation)/(?P<id>[0-9a-f]{32,34})(?P<query>\?[^#]+|)'
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
94     # look in Mediasite.Core.js (Mediasite.ContentStreamType[*])
95     _STREAM_TYPES = {
96         0: 'video1',  # the main video
97         2: 'slide',
98         3: 'presentation',
99         4: 'video2',  # screencast?
100         5: 'video3',
101     }
102
103     @staticmethod
104     def _extract_urls(webpage):
105         return [
106             unescapeHTML(mobj.group('url'))
107             for mobj in re.finditer(
108                 r'(?xi)<iframe\b[^>]+\bsrc=(["\'])(?P<url>(?:(?:https?:)?//[^/]+)?/Mediasite/Play/[0-9a-f]{32,34}(?:\?.*?)?)\1',
109                 webpage)]
110
111     def _real_extract(self, url):
112         url, data = unsmuggle_url(url, {})
113         mobj = re.match(self._VALID_URL, url)
114         resource_id = mobj.group('id')
115         query = mobj.group('query')
116
117         webpage, urlh = self._download_webpage_handle(url, resource_id)  # XXX: add UrlReferrer?
118         redirect_url = compat_str(urlh.geturl())
119
120         # XXX: might have also extracted UrlReferrer and QueryString from the html
121         service_path = compat_urlparse.urljoin(redirect_url, self._html_search_regex(
122             r'<div[^>]+\bid=["\']ServicePath[^>]+>(.+?)</div>', webpage, resource_id,
123             default='/Mediasite/PlayerService/PlayerService.svc/json'))
124
125         player_options = self._download_json(
126             '%s/GetPlayerOptions' % service_path, resource_id,
127             headers={
128                 'Content-type': 'application/json; charset=utf-8',
129                 'X-Requested-With': 'XMLHttpRequest',
130             },
131             data=json.dumps({
132                 'getPlayerOptionsRequest': {
133                     'ResourceId': resource_id,
134                     'QueryString': query,
135                     'UrlReferrer': data.get('UrlReferrer', ''),
136                     'UseScreenReader': False,
137                 }
138             }).encode('utf-8'))['d']
139
140         presentation = player_options['Presentation']
141         title = presentation['Title']
142
143         if presentation is None:
144             raise ExtractorError(
145                 'Mediasite says: %s' % player_options['PlayerPresentationStatusMessage'],
146                 expected=True)
147
148         thumbnails = []
149         formats = []
150         for snum, Stream in enumerate(presentation['Streams']):
151             stream_type = Stream.get('StreamType')
152             if stream_type is None:
153                 continue
154
155             video_urls = Stream.get('VideoUrls')
156             if not isinstance(video_urls, list):
157                 video_urls = []
158
159             stream_id = self._STREAM_TYPES.get(
160                 stream_type, 'type%u' % stream_type)
161
162             stream_formats = []
163             for unum, VideoUrl in enumerate(video_urls):
164                 video_url = url_or_none(VideoUrl.get('Location'))
165                 if not video_url:
166                     continue
167                 # XXX: if Stream.get('CanChangeScheme', False), switch scheme to HTTP/HTTPS
168
169                 media_type = VideoUrl.get('MediaType')
170                 if media_type == 'SS':
171                     stream_formats.extend(self._extract_ism_formats(
172                         video_url, resource_id,
173                         ism_id='%s-%u.%u' % (stream_id, snum, unum),
174                         fatal=False))
175                 elif media_type == 'Dash':
176                     stream_formats.extend(self._extract_mpd_formats(
177                         video_url, resource_id,
178                         mpd_id='%s-%u.%u' % (stream_id, snum, unum),
179                         fatal=False))
180                 else:
181                     stream_formats.append({
182                         'format_id': '%s-%u.%u' % (stream_id, snum, unum),
183                         'url': video_url,
184                         'ext': mimetype2ext(VideoUrl.get('MimeType')),
185                     })
186
187             # TODO: if Stream['HasSlideContent']:
188             # synthesise an MJPEG video stream '%s-%u.slides' % (stream_type, snum)
189             # from Stream['Slides']
190             # this will require writing a custom downloader...
191
192             # disprefer 'secondary' streams
193             if stream_type != 0:
194                 for fmt in stream_formats:
195                     fmt['preference'] = -1
196
197             thumbnail_url = Stream.get('ThumbnailUrl')
198             if thumbnail_url:
199                 thumbnails.append({
200                     'id': '%s-%u' % (stream_id, snum),
201                     'url': urljoin(redirect_url, thumbnail_url),
202                     'preference': -1 if stream_type != 0 else 0,
203                 })
204             formats.extend(stream_formats)
205
206         self._sort_formats(formats)
207
208         # XXX: Presentation['Presenters']
209         # XXX: Presentation['Transcript']
210
211         return {
212             'id': resource_id,
213             'title': title,
214             'description': presentation.get('Description'),
215             'duration': float_or_none(presentation.get('Duration'), 1000),
216             'timestamp': float_or_none(presentation.get('UnixTime'), 1000),
217             'formats': formats,
218             'thumbnails': thumbnails,
219         }