mediasite.py 16 KB

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