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.

239 lines
8.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. @staticmethod
  63. def _extract_url(webpage):
  64. mobj = (
  65. re.search(
  66. r"""(?xs)
  67. kWidget\.(?:thumb)?[Ee]mbed\(
  68. \{.*?
  69. (?P<q1>['\"])wid(?P=q1)\s*:\s*
  70. (?P<q2>['\"])_?(?P<partner_id>[^'\"]+)(?P=q2),.*?
  71. (?P<q3>['\"])entry_?[Ii]d(?P=q3)\s*:\s*
  72. (?P<q4>['\"])(?P<id>[^'\"]+)(?P=q4),
  73. """, webpage) or
  74. re.search(
  75. r'''(?xs)
  76. (?P<q1>["\'])
  77. (?:https?:)?//cdnapi(?:sec)?\.kaltura\.com/.*?(?:p|partner_id)/(?P<partner_id>\d+).*?
  78. (?P=q1).*?
  79. (?:
  80. entry_?[Ii]d|
  81. (?P<q2>["\'])entry_?[Ii]d(?P=q2)
  82. )\s*:\s*
  83. (?P<q3>["\'])(?P<id>.+?)(?P=q3)
  84. ''', webpage))
  85. if mobj:
  86. return 'kaltura:%(partner_id)s:%(id)s' % mobj.groupdict()
  87. def _kaltura_api_call(self, video_id, actions, *args, **kwargs):
  88. params = actions[0]
  89. if len(actions) > 1:
  90. for i, a in enumerate(actions[1:], start=1):
  91. for k, v in a.items():
  92. params['%d:%s' % (i, k)] = v
  93. query = compat_urllib_parse_urlencode(params)
  94. url = self._API_BASE + query
  95. data = self._download_json(url, video_id, *args, **kwargs)
  96. status = data if len(actions) == 1 else data[0]
  97. if status.get('objectType') == 'KalturaAPIException':
  98. raise ExtractorError(
  99. '%s said: %s' % (self.IE_NAME, status['message']))
  100. return data
  101. def _get_kaltura_signature(self, video_id, partner_id):
  102. actions = [{
  103. 'apiVersion': '3.1',
  104. 'expiry': 86400,
  105. 'format': 1,
  106. 'service': 'session',
  107. 'action': 'startWidgetSession',
  108. 'widgetId': '_%s' % partner_id,
  109. }]
  110. return self._kaltura_api_call(
  111. video_id, actions, note='Downloading Kaltura signature')['ks']
  112. def _get_video_info(self, video_id, partner_id):
  113. signature = self._get_kaltura_signature(video_id, partner_id)
  114. actions = [
  115. {
  116. 'action': 'null',
  117. 'apiVersion': '3.1.5',
  118. 'clientTag': 'kdp:v3.8.5',
  119. 'format': 1, # JSON, 2 = XML, 3 = PHP
  120. 'service': 'multirequest',
  121. 'ks': signature,
  122. },
  123. {
  124. 'action': 'get',
  125. 'entryId': video_id,
  126. 'service': 'baseentry',
  127. 'version': '-1',
  128. },
  129. {
  130. 'action': 'getbyentryid',
  131. 'entryId': video_id,
  132. 'service': 'flavorAsset',
  133. },
  134. ]
  135. return self._kaltura_api_call(
  136. video_id, actions, note='Downloading video info JSON')
  137. def _real_extract(self, url):
  138. url, smuggled_data = unsmuggle_url(url, {})
  139. mobj = re.match(self._VALID_URL, url)
  140. partner_id, entry_id = mobj.group('partner_id', 'id')
  141. ks = None
  142. if partner_id and entry_id:
  143. info, flavor_assets = self._get_video_info(entry_id, partner_id)
  144. else:
  145. path, query = mobj.group('path', 'query')
  146. if not path and not query:
  147. raise ExtractorError('Invalid URL', expected=True)
  148. params = {}
  149. if query:
  150. params = compat_parse_qs(query)
  151. if path:
  152. splitted_path = path.split('/')
  153. params.update(dict((zip(splitted_path[::2], [[v] for v in splitted_path[1::2]]))))
  154. if 'wid' in params:
  155. partner_id = params['wid'][0][1:]
  156. elif 'p' in params:
  157. partner_id = params['p'][0]
  158. else:
  159. raise ExtractorError('Invalid URL', expected=True)
  160. if 'entry_id' in params:
  161. entry_id = params['entry_id'][0]
  162. info, flavor_assets = self._get_video_info(entry_id, partner_id)
  163. elif 'uiconf_id' in params and 'flashvars[referenceId]' in params:
  164. reference_id = params['flashvars[referenceId]'][0]
  165. webpage = self._download_webpage(url, reference_id)
  166. entry_data = self._parse_json(self._search_regex(
  167. r'window\.kalturaIframePackageData\s*=\s*({.*});',
  168. webpage, 'kalturaIframePackageData'),
  169. reference_id)['entryResult']
  170. info, flavor_assets = entry_data['meta'], entry_data['contextData']['flavorAssets']
  171. entry_id = info['id']
  172. else:
  173. raise ExtractorError('Invalid URL', expected=True)
  174. ks = params.get('flashvars[ks]', [None])[0]
  175. source_url = smuggled_data.get('source_url')
  176. if source_url:
  177. referrer = base64.b64encode(
  178. '://'.join(compat_urlparse.urlparse(source_url)[:2])
  179. .encode('utf-8')).decode('utf-8')
  180. else:
  181. referrer = None
  182. def sign_url(unsigned_url):
  183. if ks:
  184. unsigned_url += '/ks/%s' % ks
  185. if referrer:
  186. unsigned_url += '?referrer=%s' % referrer
  187. return unsigned_url
  188. formats = []
  189. for f in flavor_assets:
  190. # Continue if asset is not ready
  191. if f['status'] != 2:
  192. continue
  193. video_url = sign_url('%s/flavorId/%s' % (info['dataUrl'], f['id']))
  194. formats.append({
  195. 'format_id': '%(fileExt)s-%(bitrate)s' % f,
  196. 'ext': f.get('fileExt'),
  197. 'tbr': int_or_none(f['bitrate']),
  198. 'fps': int_or_none(f.get('frameRate')),
  199. 'filesize_approx': int_or_none(f.get('size'), invscale=1024),
  200. 'container': f.get('containerFormat'),
  201. 'vcodec': f.get('videoCodecId'),
  202. 'height': int_or_none(f.get('height')),
  203. 'width': int_or_none(f.get('width')),
  204. 'url': video_url,
  205. })
  206. m3u8_url = sign_url(info['dataUrl'].replace('format/url', 'format/applehttp'))
  207. formats.extend(self._extract_m3u8_formats(
  208. m3u8_url, entry_id, 'mp4', 'm3u8_native', m3u8_id='hls', fatal=False))
  209. self._check_formats(formats, entry_id)
  210. self._sort_formats(formats)
  211. return {
  212. 'id': entry_id,
  213. 'title': info['name'],
  214. 'formats': formats,
  215. 'description': clean_html(info.get('description')),
  216. 'thumbnail': info.get('thumbnailUrl'),
  217. 'duration': info.get('duration'),
  218. 'timestamp': info.get('createdAt'),
  219. 'uploader_id': info.get('userId'),
  220. 'view_count': info.get('plays'),
  221. }