You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

357 lines
14 KiB

  1. # coding: utf-8
  2. from __future__ import unicode_literals
  3. import re
  4. import base64
  5. from .common import InfoExtractor
  6. from ..compat import (
  7. compat_urlparse,
  8. compat_parse_qs,
  9. )
  10. from ..utils import (
  11. clean_html,
  12. ExtractorError,
  13. int_or_none,
  14. unsmuggle_url,
  15. smuggle_url,
  16. )
  17. class KalturaIE(InfoExtractor):
  18. _VALID_URL = r'''(?x)
  19. (?:
  20. kaltura:(?P<partner_id>\d+):(?P<id>[0-9a-z_]+)|
  21. https?://
  22. (:?(?:www|cdnapi(?:sec)?)\.)?kaltura\.com(?::\d+)?/
  23. (?:
  24. (?:
  25. # flash player
  26. index\.php/(?:kwidget|extwidget/preview)|
  27. # html5 player
  28. html5/html5lib/[^/]+/mwEmbedFrame\.php
  29. )
  30. )(?:/(?P<path>[^?]+))?(?:\?(?P<query>.*))?
  31. )
  32. '''
  33. _SERVICE_URL = 'http://cdnapi.kaltura.com'
  34. _SERVICE_BASE = '/api_v3/index.php'
  35. # See https://github.com/kaltura/server/blob/master/plugins/content/caption/base/lib/model/enums/CaptionType.php
  36. _CAPTION_TYPES = {
  37. 1: 'srt',
  38. 2: 'ttml',
  39. 3: 'vtt',
  40. }
  41. _TESTS = [
  42. {
  43. 'url': 'kaltura:269692:1_1jc2y3e4',
  44. 'md5': '3adcbdb3dcc02d647539e53f284ba171',
  45. 'info_dict': {
  46. 'id': '1_1jc2y3e4',
  47. 'ext': 'mp4',
  48. 'title': 'Straight from the Heart',
  49. 'upload_date': '20131219',
  50. 'uploader_id': 'mlundberg@wolfgangsvault.com',
  51. 'description': 'The Allman Brothers Band, 12/16/1981',
  52. 'thumbnail': 're:^https?://.*/thumbnail/.*',
  53. 'timestamp': int,
  54. },
  55. },
  56. {
  57. 'url': 'http://www.kaltura.com/index.php/kwidget/cache_st/1300318621/wid/_269692/uiconf_id/3873291/entry_id/1_1jc2y3e4',
  58. 'only_matching': True,
  59. },
  60. {
  61. 'url': 'https://cdnapisec.kaltura.com/index.php/kwidget/wid/_557781/uiconf_id/22845202/entry_id/1_plr1syf3',
  62. 'only_matching': True,
  63. },
  64. {
  65. 'url': 'https://cdnapisec.kaltura.com/html5/html5lib/v2.30.2/mwEmbedFrame.php/p/1337/uiconf_id/20540612/entry_id/1_sf5ovm7u?wid=_243342',
  66. 'only_matching': True,
  67. },
  68. {
  69. # video with subtitles
  70. 'url': 'kaltura:111032:1_cw786r8q',
  71. 'only_matching': True,
  72. },
  73. {
  74. # video with ttml subtitles (no fileExt)
  75. 'url': 'kaltura:1926081:0_l5ye1133',
  76. 'info_dict': {
  77. 'id': '0_l5ye1133',
  78. 'ext': 'mp4',
  79. 'title': 'What Can You Do With Python?',
  80. 'upload_date': '20160221',
  81. 'uploader_id': 'stork',
  82. 'thumbnail': 're:^https?://.*/thumbnail/.*',
  83. 'timestamp': int,
  84. 'subtitles': {
  85. 'en': [{
  86. 'ext': 'ttml',
  87. }],
  88. },
  89. },
  90. 'skip': 'Gone. Maybe https://www.safaribooksonline.com/library/tutorials/introduction-to-python-anon/3469/',
  91. 'params': {
  92. 'skip_download': True,
  93. },
  94. },
  95. {
  96. 'url': 'https://www.kaltura.com/index.php/extwidget/preview/partner_id/1770401/uiconf_id/37307382/entry_id/0_58u8kme7/embed/iframe?&flashvars[streamerType]=auto',
  97. 'only_matching': True,
  98. },
  99. {
  100. 'url': 'https://www.kaltura.com:443/index.php/extwidget/preview/partner_id/1770401/uiconf_id/37307382/entry_id/0_58u8kme7/embed/iframe?&flashvars[streamerType]=auto',
  101. 'only_matching': True,
  102. }
  103. ]
  104. @staticmethod
  105. def _extract_url(webpage):
  106. # Embed codes: https://knowledge.kaltura.com/embedding-kaltura-media-players-your-site
  107. mobj = (
  108. re.search(
  109. r"""(?xs)
  110. kWidget\.(?:thumb)?[Ee]mbed\(
  111. \{.*?
  112. (?P<q1>['"])wid(?P=q1)\s*:\s*
  113. (?P<q2>['"])_?(?P<partner_id>(?:(?!(?P=q2)).)+)(?P=q2),.*?
  114. (?P<q3>['"])entry_?[Ii]d(?P=q3)\s*:\s*
  115. (?P<q4>['"])(?P<id>(?:(?!(?P=q4)).)+)(?P=q4)(?:,|\s*\})
  116. """, webpage) or
  117. re.search(
  118. r'''(?xs)
  119. (?P<q1>["'])
  120. (?:https?:)?//cdnapi(?:sec)?\.kaltura\.com(?::\d+)?/(?:(?!(?P=q1)).)*\b(?:p|partner_id)/(?P<partner_id>\d+)(?:(?!(?P=q1)).)*
  121. (?P=q1).*?
  122. (?:
  123. (?:
  124. entry_?[Ii]d|
  125. (?P<q2>["'])entry_?[Ii]d(?P=q2)
  126. )\s*:\s*|
  127. \[\s*(?P<q2_1>["'])entry_?[Ii]d(?P=q2_1)\s*\]\s*=\s*
  128. )
  129. (?P<q3>["'])(?P<id>(?:(?!(?P=q3)).)+)(?P=q3)
  130. ''', webpage) or
  131. re.search(
  132. r'''(?xs)
  133. <(?:iframe[^>]+src|meta[^>]+\bcontent)=(?P<q1>["'])
  134. (?:https?:)?//(?:(?:www|cdnapi(?:sec)?)\.)?kaltura\.com/(?:(?!(?P=q1)).)*\b(?:p|partner_id)/(?P<partner_id>\d+)
  135. (?:(?!(?P=q1)).)*
  136. [?&;]entry_id=(?P<id>(?:(?!(?P=q1))[^&])+)
  137. (?:(?!(?P=q1)).)*
  138. (?P=q1)
  139. ''', webpage)
  140. )
  141. if mobj:
  142. embed_info = mobj.groupdict()
  143. url = 'kaltura:%(partner_id)s:%(id)s' % embed_info
  144. escaped_pid = re.escape(embed_info['partner_id'])
  145. service_url = re.search(
  146. r'<script[^>]+src=["\']((?:https?:)?//.+?)/p/%s/sp/%s00/embedIframeJs' % (escaped_pid, escaped_pid),
  147. webpage)
  148. if service_url:
  149. url = smuggle_url(url, {'service_url': service_url.group(1)})
  150. return url
  151. def _kaltura_api_call(self, video_id, actions, service_url=None, *args, **kwargs):
  152. params = actions[0]
  153. if len(actions) > 1:
  154. for i, a in enumerate(actions[1:], start=1):
  155. for k, v in a.items():
  156. params['%d:%s' % (i, k)] = v
  157. data = self._download_json(
  158. (service_url or self._SERVICE_URL) + self._SERVICE_BASE,
  159. video_id, query=params, *args, **kwargs)
  160. status = data if len(actions) == 1 else data[0]
  161. if status.get('objectType') == 'KalturaAPIException':
  162. raise ExtractorError(
  163. '%s said: %s' % (self.IE_NAME, status['message']))
  164. return data
  165. def _get_video_info(self, video_id, partner_id, service_url=None):
  166. actions = [
  167. {
  168. 'action': 'null',
  169. 'apiVersion': '3.1.5',
  170. 'clientTag': 'kdp:v3.8.5',
  171. 'format': 1, # JSON, 2 = XML, 3 = PHP
  172. 'service': 'multirequest',
  173. },
  174. {
  175. 'expiry': 86400,
  176. 'service': 'session',
  177. 'action': 'startWidgetSession',
  178. 'widgetId': '_%s' % partner_id,
  179. },
  180. {
  181. 'action': 'get',
  182. 'entryId': video_id,
  183. 'service': 'baseentry',
  184. 'ks': '{1:result:ks}',
  185. 'responseProfile:fields': 'createdAt,dataUrl,duration,name,plays,thumbnailUrl,userId',
  186. 'responseProfile:type': 1,
  187. },
  188. {
  189. 'action': 'getbyentryid',
  190. 'entryId': video_id,
  191. 'service': 'flavorAsset',
  192. 'ks': '{1:result:ks}',
  193. },
  194. {
  195. 'action': 'list',
  196. 'filter:entryIdEqual': video_id,
  197. 'service': 'caption_captionasset',
  198. 'ks': '{1:result:ks}',
  199. },
  200. ]
  201. return self._kaltura_api_call(
  202. video_id, actions, service_url, note='Downloading video info JSON')
  203. def _real_extract(self, url):
  204. url, smuggled_data = unsmuggle_url(url, {})
  205. mobj = re.match(self._VALID_URL, url)
  206. partner_id, entry_id = mobj.group('partner_id', 'id')
  207. ks = None
  208. captions = None
  209. if partner_id and entry_id:
  210. _, info, flavor_assets, captions = self._get_video_info(entry_id, partner_id, smuggled_data.get('service_url'))
  211. else:
  212. path, query = mobj.group('path', 'query')
  213. if not path and not query:
  214. raise ExtractorError('Invalid URL', expected=True)
  215. params = {}
  216. if query:
  217. params = compat_parse_qs(query)
  218. if path:
  219. splitted_path = path.split('/')
  220. params.update(dict((zip(splitted_path[::2], [[v] for v in splitted_path[1::2]]))))
  221. if 'wid' in params:
  222. partner_id = params['wid'][0][1:]
  223. elif 'p' in params:
  224. partner_id = params['p'][0]
  225. elif 'partner_id' in params:
  226. partner_id = params['partner_id'][0]
  227. else:
  228. raise ExtractorError('Invalid URL', expected=True)
  229. if 'entry_id' in params:
  230. entry_id = params['entry_id'][0]
  231. _, info, flavor_assets, captions = self._get_video_info(entry_id, partner_id)
  232. elif 'uiconf_id' in params and 'flashvars[referenceId]' in params:
  233. reference_id = params['flashvars[referenceId]'][0]
  234. webpage = self._download_webpage(url, reference_id)
  235. entry_data = self._parse_json(self._search_regex(
  236. r'window\.kalturaIframePackageData\s*=\s*({.*});',
  237. webpage, 'kalturaIframePackageData'),
  238. reference_id)['entryResult']
  239. info, flavor_assets = entry_data['meta'], entry_data['contextData']['flavorAssets']
  240. entry_id = info['id']
  241. # Unfortunately, data returned in kalturaIframePackageData lacks
  242. # captions so we will try requesting the complete data using
  243. # regular approach since we now know the entry_id
  244. try:
  245. _, info, flavor_assets, captions = self._get_video_info(
  246. entry_id, partner_id)
  247. except ExtractorError:
  248. # Regular scenario failed but we already have everything
  249. # extracted apart from captions and can process at least
  250. # with this
  251. pass
  252. else:
  253. raise ExtractorError('Invalid URL', expected=True)
  254. ks = params.get('flashvars[ks]', [None])[0]
  255. source_url = smuggled_data.get('source_url')
  256. if source_url:
  257. referrer = base64.b64encode(
  258. '://'.join(compat_urlparse.urlparse(source_url)[:2])
  259. .encode('utf-8')).decode('utf-8')
  260. else:
  261. referrer = None
  262. def sign_url(unsigned_url):
  263. if ks:
  264. unsigned_url += '/ks/%s' % ks
  265. if referrer:
  266. unsigned_url += '?referrer=%s' % referrer
  267. return unsigned_url
  268. data_url = info['dataUrl']
  269. if '/flvclipper/' in data_url:
  270. data_url = re.sub(r'/flvclipper/.*', '/serveFlavor', data_url)
  271. formats = []
  272. for f in flavor_assets:
  273. # Continue if asset is not ready
  274. if f.get('status') != 2:
  275. continue
  276. # Original format that's not available (e.g. kaltura:1926081:0_c03e1b5g)
  277. # skip for now.
  278. if f.get('fileExt') == 'chun':
  279. continue
  280. # DRM-protected video, cannot be decrypted
  281. if f.get('fileExt') == 'wvm':
  282. continue
  283. if not f.get('fileExt'):
  284. # QT indicates QuickTime; some videos have broken fileExt
  285. if f.get('containerFormat') == 'qt':
  286. f['fileExt'] = 'mov'
  287. else:
  288. f['fileExt'] = 'mp4'
  289. video_url = sign_url(
  290. '%s/flavorId/%s' % (data_url, f['id']))
  291. # audio-only has no videoCodecId (e.g. kaltura:1926081:0_c03e1b5g
  292. # -f mp4-56)
  293. vcodec = 'none' if 'videoCodecId' not in f and f.get(
  294. 'frameRate') == 0 else f.get('videoCodecId')
  295. formats.append({
  296. 'format_id': '%(fileExt)s-%(bitrate)s' % f,
  297. 'ext': f.get('fileExt'),
  298. 'tbr': int_or_none(f['bitrate']),
  299. 'fps': int_or_none(f.get('frameRate')),
  300. 'filesize_approx': int_or_none(f.get('size'), invscale=1024),
  301. 'container': f.get('containerFormat'),
  302. 'vcodec': vcodec,
  303. 'height': int_or_none(f.get('height')),
  304. 'width': int_or_none(f.get('width')),
  305. 'url': video_url,
  306. })
  307. if '/playManifest/' in data_url:
  308. m3u8_url = sign_url(data_url.replace(
  309. 'format/url', 'format/applehttp'))
  310. formats.extend(self._extract_m3u8_formats(
  311. m3u8_url, entry_id, 'mp4', 'm3u8_native',
  312. m3u8_id='hls', fatal=False))
  313. self._sort_formats(formats)
  314. subtitles = {}
  315. if captions:
  316. for caption in captions.get('objects', []):
  317. # Continue if caption is not ready
  318. if caption.get('status') != 2:
  319. continue
  320. if not caption.get('id'):
  321. continue
  322. caption_format = int_or_none(caption.get('format'))
  323. subtitles.setdefault(caption.get('languageCode') or caption.get('language'), []).append({
  324. 'url': '%s/api_v3/service/caption_captionasset/action/serve/captionAssetId/%s' % (self._SERVICE_URL, caption['id']),
  325. 'ext': caption.get('fileExt') or self._CAPTION_TYPES.get(caption_format) or 'ttml',
  326. })
  327. return {
  328. 'id': entry_id,
  329. 'title': info['name'],
  330. 'formats': formats,
  331. 'subtitles': subtitles,
  332. 'description': clean_html(info.get('description')),
  333. 'thumbnail': info.get('thumbnailUrl'),
  334. 'duration': info.get('duration'),
  335. 'timestamp': info.get('createdAt'),
  336. 'uploader_id': info.get('userId') if info.get('userId') != 'None' else None,
  337. 'view_count': info.get('plays'),
  338. }