logo

youtube-dl

[mirror] Download/Watch videos from video hostersgit clone https://hacktivis.me/git/mirror/youtube-dl.git

mediasite.py (14672B)


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