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.

337 lines
13 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. 'params': {
  91. 'skip_download': True,
  92. },
  93. },
  94. {
  95. 'url': 'https://www.kaltura.com/index.php/extwidget/preview/partner_id/1770401/uiconf_id/37307382/entry_id/0_58u8kme7/embed/iframe?&flashvars[streamerType]=auto',
  96. 'only_matching': True,
  97. },
  98. {
  99. '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',
  100. 'only_matching': True,
  101. }
  102. ]
  103. @staticmethod
  104. def _extract_url(webpage):
  105. mobj = (
  106. re.search(
  107. r"""(?xs)
  108. kWidget\.(?:thumb)?[Ee]mbed\(
  109. \{.*?
  110. (?P<q1>['\"])wid(?P=q1)\s*:\s*
  111. (?P<q2>['\"])_?(?P<partner_id>(?:(?!(?P=q2)).)+)(?P=q2),.*?
  112. (?P<q3>['\"])entry_?[Ii]d(?P=q3)\s*:\s*
  113. (?P<q4>['\"])(?P<id>(?:(?!(?P=q4)).)+)(?P=q4)(?:,|\s*\})
  114. """, webpage) or
  115. re.search(
  116. r'''(?xs)
  117. (?P<q1>["\'])
  118. (?:https?:)?//cdnapi(?:sec)?\.kaltura\.com(?::\d+)?/(?:(?!(?P=q1)).)*\b(?:p|partner_id)/(?P<partner_id>\d+)(?:(?!(?P=q1)).)*
  119. (?P=q1).*?
  120. (?:
  121. entry_?[Ii]d|
  122. (?P<q2>["\'])entry_?[Ii]d(?P=q2)
  123. )\s*:\s*
  124. (?P<q3>["\'])(?P<id>(?:(?!(?P=q3)).)+)(?P=q3)
  125. ''', webpage))
  126. if mobj:
  127. embed_info = mobj.groupdict()
  128. url = 'kaltura:%(partner_id)s:%(id)s' % embed_info
  129. escaped_pid = re.escape(embed_info['partner_id'])
  130. service_url = re.search(
  131. r'<script[^>]+src=["\']((?:https?:)?//.+?)/p/%s/sp/%s00/embedIframeJs' % (escaped_pid, escaped_pid),
  132. webpage)
  133. if service_url:
  134. url = smuggle_url(url, {'service_url': service_url.group(1)})
  135. return url
  136. def _kaltura_api_call(self, video_id, actions, service_url=None, *args, **kwargs):
  137. params = actions[0]
  138. if len(actions) > 1:
  139. for i, a in enumerate(actions[1:], start=1):
  140. for k, v in a.items():
  141. params['%d:%s' % (i, k)] = v
  142. data = self._download_json(
  143. (service_url or self._SERVICE_URL) + self._SERVICE_BASE,
  144. video_id, query=params, *args, **kwargs)
  145. status = data if len(actions) == 1 else data[0]
  146. if status.get('objectType') == 'KalturaAPIException':
  147. raise ExtractorError(
  148. '%s said: %s' % (self.IE_NAME, status['message']))
  149. return data
  150. def _get_video_info(self, video_id, partner_id, service_url=None):
  151. actions = [
  152. {
  153. 'action': 'null',
  154. 'apiVersion': '3.1.5',
  155. 'clientTag': 'kdp:v3.8.5',
  156. 'format': 1, # JSON, 2 = XML, 3 = PHP
  157. 'service': 'multirequest',
  158. },
  159. {
  160. 'expiry': 86400,
  161. 'service': 'session',
  162. 'action': 'startWidgetSession',
  163. 'widgetId': '_%s' % partner_id,
  164. },
  165. {
  166. 'action': 'get',
  167. 'entryId': video_id,
  168. 'service': 'baseentry',
  169. 'ks': '{1:result:ks}',
  170. },
  171. {
  172. 'action': 'getbyentryid',
  173. 'entryId': video_id,
  174. 'service': 'flavorAsset',
  175. 'ks': '{1:result:ks}',
  176. },
  177. {
  178. 'action': 'list',
  179. 'filter:entryIdEqual': video_id,
  180. 'service': 'caption_captionasset',
  181. 'ks': '{1:result:ks}',
  182. },
  183. ]
  184. return self._kaltura_api_call(
  185. video_id, actions, service_url, note='Downloading video info JSON')
  186. def _real_extract(self, url):
  187. url, smuggled_data = unsmuggle_url(url, {})
  188. mobj = re.match(self._VALID_URL, url)
  189. partner_id, entry_id = mobj.group('partner_id', 'id')
  190. ks = None
  191. captions = None
  192. if partner_id and entry_id:
  193. _, info, flavor_assets, captions = self._get_video_info(entry_id, partner_id, smuggled_data.get('service_url'))
  194. else:
  195. path, query = mobj.group('path', 'query')
  196. if not path and not query:
  197. raise ExtractorError('Invalid URL', expected=True)
  198. params = {}
  199. if query:
  200. params = compat_parse_qs(query)
  201. if path:
  202. splitted_path = path.split('/')
  203. params.update(dict((zip(splitted_path[::2], [[v] for v in splitted_path[1::2]]))))
  204. if 'wid' in params:
  205. partner_id = params['wid'][0][1:]
  206. elif 'p' in params:
  207. partner_id = params['p'][0]
  208. elif 'partner_id' in params:
  209. partner_id = params['partner_id'][0]
  210. else:
  211. raise ExtractorError('Invalid URL', expected=True)
  212. if 'entry_id' in params:
  213. entry_id = params['entry_id'][0]
  214. _, info, flavor_assets, captions = self._get_video_info(entry_id, partner_id)
  215. elif 'uiconf_id' in params and 'flashvars[referenceId]' in params:
  216. reference_id = params['flashvars[referenceId]'][0]
  217. webpage = self._download_webpage(url, reference_id)
  218. entry_data = self._parse_json(self._search_regex(
  219. r'window\.kalturaIframePackageData\s*=\s*({.*});',
  220. webpage, 'kalturaIframePackageData'),
  221. reference_id)['entryResult']
  222. info, flavor_assets = entry_data['meta'], entry_data['contextData']['flavorAssets']
  223. entry_id = info['id']
  224. # Unfortunately, data returned in kalturaIframePackageData lacks
  225. # captions so we will try requesting the complete data using
  226. # regular approach since we now know the entry_id
  227. try:
  228. _, info, flavor_assets, captions = self._get_video_info(
  229. entry_id, partner_id)
  230. except ExtractorError:
  231. # Regular scenario failed but we already have everything
  232. # extracted apart from captions and can process at least
  233. # with this
  234. pass
  235. else:
  236. raise ExtractorError('Invalid URL', expected=True)
  237. ks = params.get('flashvars[ks]', [None])[0]
  238. source_url = smuggled_data.get('source_url')
  239. if source_url:
  240. referrer = base64.b64encode(
  241. '://'.join(compat_urlparse.urlparse(source_url)[:2])
  242. .encode('utf-8')).decode('utf-8')
  243. else:
  244. referrer = None
  245. def sign_url(unsigned_url):
  246. if ks:
  247. unsigned_url += '/ks/%s' % ks
  248. if referrer:
  249. unsigned_url += '?referrer=%s' % referrer
  250. return unsigned_url
  251. data_url = info['dataUrl']
  252. if '/flvclipper/' in data_url:
  253. data_url = re.sub(r'/flvclipper/.*', '/serveFlavor', data_url)
  254. formats = []
  255. for f in flavor_assets:
  256. # Continue if asset is not ready
  257. if f.get('status') != 2:
  258. continue
  259. # Original format that's not available (e.g. kaltura:1926081:0_c03e1b5g)
  260. # skip for now.
  261. if f.get('fileExt') == 'chun':
  262. continue
  263. if not f.get('fileExt'):
  264. # QT indicates QuickTime; some videos have broken fileExt
  265. if f.get('containerFormat') == 'qt':
  266. f['fileExt'] = 'mov'
  267. else:
  268. f['fileExt'] = 'mp4'
  269. video_url = sign_url(
  270. '%s/flavorId/%s' % (data_url, f['id']))
  271. # audio-only has no videoCodecId (e.g. kaltura:1926081:0_c03e1b5g
  272. # -f mp4-56)
  273. vcodec = 'none' if 'videoCodecId' not in f and f.get(
  274. 'frameRate') == 0 else f.get('videoCodecId')
  275. formats.append({
  276. 'format_id': '%(fileExt)s-%(bitrate)s' % f,
  277. 'ext': f.get('fileExt'),
  278. 'tbr': int_or_none(f['bitrate']),
  279. 'fps': int_or_none(f.get('frameRate')),
  280. 'filesize_approx': int_or_none(f.get('size'), invscale=1024),
  281. 'container': f.get('containerFormat'),
  282. 'vcodec': vcodec,
  283. 'height': int_or_none(f.get('height')),
  284. 'width': int_or_none(f.get('width')),
  285. 'url': video_url,
  286. })
  287. if '/playManifest/' in data_url:
  288. m3u8_url = sign_url(data_url.replace(
  289. 'format/url', 'format/applehttp'))
  290. formats.extend(self._extract_m3u8_formats(
  291. m3u8_url, entry_id, 'mp4', 'm3u8_native',
  292. m3u8_id='hls', fatal=False))
  293. self._sort_formats(formats)
  294. subtitles = {}
  295. if captions:
  296. for caption in captions.get('objects', []):
  297. # Continue if caption is not ready
  298. if f.get('status') != 2:
  299. continue
  300. if not caption.get('id'):
  301. continue
  302. caption_format = int_or_none(caption.get('format'))
  303. subtitles.setdefault(caption.get('languageCode') or caption.get('language'), []).append({
  304. 'url': '%s/api_v3/service/caption_captionasset/action/serve/captionAssetId/%s' % (self._SERVICE_URL, caption['id']),
  305. 'ext': caption.get('fileExt') or self._CAPTION_TYPES.get(caption_format) or 'ttml',
  306. })
  307. return {
  308. 'id': entry_id,
  309. 'title': info['name'],
  310. 'formats': formats,
  311. 'subtitles': subtitles,
  312. 'description': clean_html(info.get('description')),
  313. 'thumbnail': info.get('thumbnailUrl'),
  314. 'duration': info.get('duration'),
  315. 'timestamp': info.get('createdAt'),
  316. 'uploader_id': info.get('userId') if info.get('userId') != 'None' else None,
  317. 'view_count': info.get('plays'),
  318. }