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.

213 lines
7.9 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_urllib_parse_urlencode,
  8. compat_urlparse,
  9. compat_parse_qs,
  10. )
  11. from ..utils import (
  12. clean_html,
  13. ExtractorError,
  14. int_or_none,
  15. unsmuggle_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/
  23. (?:
  24. (?:
  25. # flash player
  26. index\.php/kwidget|
  27. # html5 player
  28. html5/html5lib/[^/]+/mwEmbedFrame\.php
  29. )
  30. )(?:/(?P<path>[^?]+))?(?:\?(?P<query>.*))?
  31. )
  32. '''
  33. _API_BASE = 'http://cdnapi.kaltura.com/api_v3/index.php?'
  34. _TESTS = [
  35. {
  36. 'url': 'kaltura:269692:1_1jc2y3e4',
  37. 'md5': '3adcbdb3dcc02d647539e53f284ba171',
  38. 'info_dict': {
  39. 'id': '1_1jc2y3e4',
  40. 'ext': 'mp4',
  41. 'title': 'Straight from the Heart',
  42. 'upload_date': '20131219',
  43. 'uploader_id': 'mlundberg@wolfgangsvault.com',
  44. 'description': 'The Allman Brothers Band, 12/16/1981',
  45. 'thumbnail': 're:^https?://.*/thumbnail/.*',
  46. 'timestamp': int,
  47. },
  48. },
  49. {
  50. 'url': 'http://www.kaltura.com/index.php/kwidget/cache_st/1300318621/wid/_269692/uiconf_id/3873291/entry_id/1_1jc2y3e4',
  51. 'only_matching': True,
  52. },
  53. {
  54. 'url': 'https://cdnapisec.kaltura.com/index.php/kwidget/wid/_557781/uiconf_id/22845202/entry_id/1_plr1syf3',
  55. 'only_matching': True,
  56. },
  57. {
  58. 'url': 'https://cdnapisec.kaltura.com/html5/html5lib/v2.30.2/mwEmbedFrame.php/p/1337/uiconf_id/20540612/entry_id/1_sf5ovm7u?wid=_243342',
  59. 'only_matching': True,
  60. }
  61. ]
  62. def _kaltura_api_call(self, video_id, actions, *args, **kwargs):
  63. params = actions[0]
  64. if len(actions) > 1:
  65. for i, a in enumerate(actions[1:], start=1):
  66. for k, v in a.items():
  67. params['%d:%s' % (i, k)] = v
  68. query = compat_urllib_parse_urlencode(params)
  69. url = self._API_BASE + query
  70. data = self._download_json(url, video_id, *args, **kwargs)
  71. status = data if len(actions) == 1 else data[0]
  72. if status.get('objectType') == 'KalturaAPIException':
  73. raise ExtractorError(
  74. '%s said: %s' % (self.IE_NAME, status['message']))
  75. return data
  76. def _get_kaltura_signature(self, video_id, partner_id):
  77. actions = [{
  78. 'apiVersion': '3.1',
  79. 'expiry': 86400,
  80. 'format': 1,
  81. 'service': 'session',
  82. 'action': 'startWidgetSession',
  83. 'widgetId': '_%s' % partner_id,
  84. }]
  85. return self._kaltura_api_call(
  86. video_id, actions, note='Downloading Kaltura signature')['ks']
  87. def _get_video_info(self, video_id, partner_id):
  88. signature = self._get_kaltura_signature(video_id, partner_id)
  89. actions = [
  90. {
  91. 'action': 'null',
  92. 'apiVersion': '3.1.5',
  93. 'clientTag': 'kdp:v3.8.5',
  94. 'format': 1, # JSON, 2 = XML, 3 = PHP
  95. 'service': 'multirequest',
  96. 'ks': signature,
  97. },
  98. {
  99. 'action': 'get',
  100. 'entryId': video_id,
  101. 'service': 'baseentry',
  102. 'version': '-1',
  103. },
  104. {
  105. 'action': 'getbyentryid',
  106. 'entryId': video_id,
  107. 'service': 'flavorAsset',
  108. },
  109. ]
  110. return self._kaltura_api_call(
  111. video_id, actions, note='Downloading video info JSON')
  112. def _real_extract(self, url):
  113. url, smuggled_data = unsmuggle_url(url, {})
  114. mobj = re.match(self._VALID_URL, url)
  115. partner_id, entry_id = mobj.group('partner_id', 'id')
  116. ks = None
  117. if partner_id and entry_id:
  118. info, flavor_assets = self._get_video_info(entry_id, partner_id)
  119. else:
  120. path, query = mobj.group('path', 'query')
  121. if not path and not query:
  122. raise ExtractorError('Invalid URL', expected=True)
  123. params = {}
  124. if query:
  125. params = compat_parse_qs(query)
  126. if path:
  127. splitted_path = path.split('/')
  128. params.update(dict((zip(splitted_path[::2], [[v] for v in splitted_path[1::2]]))))
  129. if 'wid' in params:
  130. partner_id = params['wid'][0][1:]
  131. elif 'p' in params:
  132. partner_id = params['p'][0]
  133. else:
  134. raise ExtractorError('Invalid URL', expected=True)
  135. if 'entry_id' in params:
  136. entry_id = params['entry_id'][0]
  137. info, flavor_assets = self._get_video_info(entry_id, partner_id)
  138. elif 'uiconf_id' in params and 'flashvars[referenceId]' in params:
  139. reference_id = params['flashvars[referenceId]'][0]
  140. webpage = self._download_webpage(url, reference_id)
  141. entry_data = self._parse_json(self._search_regex(
  142. r'window\.kalturaIframePackageData\s*=\s*({.*});',
  143. webpage, 'kalturaIframePackageData'),
  144. reference_id)['entryResult']
  145. info, flavor_assets = entry_data['meta'], entry_data['contextData']['flavorAssets']
  146. entry_id = info['id']
  147. else:
  148. raise ExtractorError('Invalid URL', expected=True)
  149. ks = params.get('flashvars[ks]', [None])[0]
  150. source_url = smuggled_data.get('source_url')
  151. if source_url:
  152. referrer = base64.b64encode(
  153. '://'.join(compat_urlparse.urlparse(source_url)[:2])
  154. .encode('utf-8')).decode('utf-8')
  155. else:
  156. referrer = None
  157. def sign_url(unsigned_url):
  158. if ks:
  159. unsigned_url += '/ks/%s' % ks
  160. if referrer:
  161. unsigned_url += '?referrer=%s' % referrer
  162. return unsigned_url
  163. formats = []
  164. for f in flavor_assets:
  165. # Continue if asset is not ready
  166. if f['status'] != 2:
  167. continue
  168. video_url = sign_url('%s/flavorId/%s' % (info['dataUrl'], f['id']))
  169. formats.append({
  170. 'format_id': '%(fileExt)s-%(bitrate)s' % f,
  171. 'ext': f.get('fileExt'),
  172. 'tbr': int_or_none(f['bitrate']),
  173. 'fps': int_or_none(f.get('frameRate')),
  174. 'filesize_approx': int_or_none(f.get('size'), invscale=1024),
  175. 'container': f.get('containerFormat'),
  176. 'vcodec': f.get('videoCodecId'),
  177. 'height': int_or_none(f.get('height')),
  178. 'width': int_or_none(f.get('width')),
  179. 'url': video_url,
  180. })
  181. m3u8_url = sign_url(info['dataUrl'].replace('format/url', 'format/applehttp'))
  182. formats.extend(self._extract_m3u8_formats(
  183. m3u8_url, entry_id, 'mp4', 'm3u8_native', m3u8_id='hls', fatal=False))
  184. self._check_formats(formats, entry_id)
  185. self._sort_formats(formats)
  186. return {
  187. 'id': entry_id,
  188. 'title': info['name'],
  189. 'formats': formats,
  190. 'description': clean_html(info.get('description')),
  191. 'thumbnail': info.get('thumbnailUrl'),
  192. 'duration': info.get('duration'),
  193. 'timestamp': info.get('createdAt'),
  194. 'uploader_id': info.get('userId'),
  195. 'view_count': info.get('plays'),
  196. }