[mediasite] Add extractor, subsume sandia and collegerama extractors
[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 compat_urlparse
9 from ..utils import (
10     ExtractorError,
11     unsmuggle_url,
12     mimetype2ext,
13     float_or_none,
14 )
15
16
17 class MediasiteIE(InfoExtractor):
18     _VALID_URL = r'''(?xi)
19         https?://[a-z0-9\-\.:\[\]]+/Mediasite/Play/
20         (?P<id>[0-9a-f]{32,34})
21         (?P<QueryString>\?[^#]+|)
22     '''
23     _TESTS = [
24         {
25             'url': 'https://hitsmediaweb.h-its.org/mediasite/Play/2db6c271681e4f199af3c60d1f82869b1d',
26             'info_dict': {
27                 'id': '2db6c271681e4f199af3c60d1f82869b1d',
28                 'ext': 'mp4',
29                 'title': 'Lecture: Tuesday, September 20, 2016 - Sir Andrew Wiles',
30                 '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.',
31                 'timestamp': 1474268400.0,
32                 'upload_date': '20160919',
33             },
34         },
35         {
36             'url': 'http://mediasite.uib.no/Mediasite/Play/90bb363295d945d6b548c867d01181361d?catalog=a452b7df-9ae1-46b7-a3ba-aceeb285f3eb',
37             'info_dict': {
38                 'id': '90bb363295d945d6b548c867d01181361d',
39                 'ext': 'mp4',
40                 'upload_date': '20150429',
41                 'title': '5) IT-forum 2015-Dag 1  - Dungbeetle -  How and why Rain created a tiny bug tracker for Unity',
42                 'timestamp': 1430311380.0,
43             },
44         },
45         {
46             'url': 'https://collegerama.tudelft.nl/Mediasite/Play/585a43626e544bdd97aeb71a0ec907a01d',
47             'md5': '481fda1c11f67588c0d9d8fbdced4e39',
48             'info_dict': {
49                 'id': '585a43626e544bdd97aeb71a0ec907a01d',
50                 'ext': 'mp4',
51                 'title': 'Een nieuwe wereld: waarden, bewustzijn en techniek van de mensheid 2.0.',
52                 'description': '',
53                 'thumbnail': r're:^https?://.*\.jpg(?:\?.*)?$',
54                 'duration': 7713.088,
55                 'timestamp': 1413309600,
56                 'upload_date': '20141014',
57             },
58         },
59         {
60             'url': 'https://collegerama.tudelft.nl/Mediasite/Play/86a9ea9f53e149079fbdb4202b521ed21d?catalog=fd32fd35-6c99-466c-89d4-cd3c431bc8a4',
61             'md5': 'ef1fdded95bdf19b12c5999949419c92',
62             'info_dict': {
63                 'id': '86a9ea9f53e149079fbdb4202b521ed21d',
64                 'ext': 'wmv',
65                 'title': '64ste Vakantiecursus: Afvalwater',
66                 'description': 'md5:7fd774865cc69d972f542b157c328305',
67                 'thumbnail': r're:^https?://.*\.jpg(?:\?.*?)?$',
68                 'duration': 10853,
69                 'timestamp': 1326446400,
70                 'upload_date': '20120113',
71             },
72         },
73         {
74             'url': 'http://digitalops.sandia.gov/Mediasite/Play/24aace4429fc450fb5b38cdbf424a66e1d',
75             'md5': '9422edc9b9a60151727e4b6d8bef393d',
76             'info_dict': {
77                 'id': '24aace4429fc450fb5b38cdbf424a66e1d',
78                 'ext': 'mp4',
79                 'title': 'Xyce Software Training - Section 1',
80                 'description': r're:(?s)SAND Number: SAND 2013-7800.{200,}',
81                 'upload_date': '20120409',
82                 'timestamp': 1333983600,
83                 'duration': 7794,
84             }
85         }
86     ]
87
88     # look in Mediasite.Core.js (Mediasite.ContentStreamType[*])
89     _STREAM_TYPES = {
90         0: 'video1', # the main video
91         2: 'slide',
92         3: 'presentation',
93         4: 'video2', # screencast?
94         5: 'video3',
95     }
96
97     def _real_extract(self, url):
98         url, data = unsmuggle_url(url, {})
99         mobj = re.match(self._VALID_URL, url)
100         ResourceId = mobj.group('id')
101         QueryString = mobj.group('QueryString')
102
103         webpage = self._download_webpage(url, ResourceId) # XXX: add UrlReferrer?
104
105         # XXX: might have also extracted UrlReferrer and QueryString from the html
106         ServicePath = compat_urlparse.urljoin(url, self._html_search_regex(
107             r'<div id="ServicePath">(.+?)</div>', webpage, ResourceId,
108             default='/Mediasite/PlayerService/PlayerService.svc/json'))
109
110         PlayerOptions = self._download_json(
111             '%s/GetPlayerOptions' % (ServicePath), ResourceId,
112             headers={
113                 'Content-type': 'application/json; charset=utf-8',
114                 'X-Requested-With': 'XMLHttpRequest',
115             },
116             data=json.dumps({
117                 'getPlayerOptionsRequest': {
118                     'ResourceId': ResourceId,
119                     'QueryString': QueryString,
120                     'UrlReferrer': data.get('UrlReferrer', ''),
121                     'UseScreenReader': False,
122                 }
123             }).encode('utf-8'))
124         Presentation = PlayerOptions['d']['Presentation']
125         if Presentation is None:
126             raise ExtractorError('Mediasite says: %s' %
127                 (PlayerOptions['d']['PlayerPresentationStatusMessage'],),
128                 expected=True)
129
130         thumbnails = []
131         formats = []
132         for snum, Stream in enumerate(Presentation['Streams']):
133             stream_type = self._STREAM_TYPES.get(
134                 Stream['StreamType'], 'type%u' % Stream['StreamType'])
135
136             stream_formats = []
137             for unum, VideoUrl in enumerate(Stream['VideoUrls']):
138                 url = VideoUrl['Location']
139                 # XXX: if Stream.get('CanChangeScheme', False), switch scheme to HTTP/HTTPS
140
141                 if VideoUrl['MediaType'] == 'SS':
142                     stream_formats.extend(self._extract_ism_formats(
143                         url, ResourceId, ism_id='%s-%u.%u' % (stream_type, snum, unum)))
144                     continue
145
146                 stream_formats.append({
147                     'format_id': '%s-%u.%u' % (stream_type, snum, unum),
148                     'url': url,
149                     'ext': mimetype2ext(VideoUrl['MimeType']),
150                 })
151
152             # TODO: if Stream['HasSlideContent']:
153             # synthesise an MJPEG video stream '%s-%u.slides' % (stream_type, snum)
154             # from Stream['Slides']
155             # this will require writing a custom downloader...
156
157             # disprefer 'secondary' streams
158             if Stream['StreamType'] != 0:
159                 for fmt in stream_formats:
160                     fmt['preference'] = -1
161
162             ThumbnailUrl = Stream.get('ThumbnailUrl')
163             if ThumbnailUrl:
164                 thumbnails.append({
165                     'id': '%s-%u' % (stream_type, snum),
166                     'url': compat_urlparse.urljoin(url, ThumbnailUrl),
167                     'preference': -1 if Stream['StreamType'] != 0 else 0,
168                 })
169             formats.extend(stream_formats)
170
171         self._sort_formats(formats)
172
173         # XXX: Presentation['Presenters']
174         # XXX: Presentation['Transcript']
175
176         return {
177             'id': ResourceId,
178             'title': Presentation['Title'],
179             'description': Presentation.get('Description'),
180             'duration': float_or_none(Presentation.get('Duration'), 1000),
181             'timestamp': float_or_none(Presentation.get('UnixTime'), 1000),
182             'formats': formats,
183             'thumbnails': thumbnails,
184         }