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.

284 lines
11 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/
  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. _SERVICE_URL = 'http://cdnapi.kaltura.com'
  34. _SERVICE_BASE = '/api_v3/index.php'
  35. _TESTS = [
  36. {
  37. 'url': 'kaltura:269692:1_1jc2y3e4',
  38. 'md5': '3adcbdb3dcc02d647539e53f284ba171',
  39. 'info_dict': {
  40. 'id': '1_1jc2y3e4',
  41. 'ext': 'mp4',
  42. 'title': 'Straight from the Heart',
  43. 'upload_date': '20131219',
  44. 'uploader_id': 'mlundberg@wolfgangsvault.com',
  45. 'description': 'The Allman Brothers Band, 12/16/1981',
  46. 'thumbnail': 're:^https?://.*/thumbnail/.*',
  47. 'timestamp': int,
  48. },
  49. },
  50. {
  51. 'url': 'http://www.kaltura.com/index.php/kwidget/cache_st/1300318621/wid/_269692/uiconf_id/3873291/entry_id/1_1jc2y3e4',
  52. 'only_matching': True,
  53. },
  54. {
  55. 'url': 'https://cdnapisec.kaltura.com/index.php/kwidget/wid/_557781/uiconf_id/22845202/entry_id/1_plr1syf3',
  56. 'only_matching': True,
  57. },
  58. {
  59. 'url': 'https://cdnapisec.kaltura.com/html5/html5lib/v2.30.2/mwEmbedFrame.php/p/1337/uiconf_id/20540612/entry_id/1_sf5ovm7u?wid=_243342',
  60. 'only_matching': True,
  61. },
  62. {
  63. # video with subtitles
  64. 'url': 'kaltura:111032:1_cw786r8q',
  65. 'only_matching': True,
  66. }
  67. ]
  68. @staticmethod
  69. def _extract_url(webpage):
  70. mobj = (
  71. re.search(
  72. r"""(?xs)
  73. kWidget\.(?:thumb)?[Ee]mbed\(
  74. \{.*?
  75. (?P<q1>['\"])wid(?P=q1)\s*:\s*
  76. (?P<q2>['\"])_?(?P<partner_id>[^'\"]+)(?P=q2),.*?
  77. (?P<q3>['\"])entry_?[Ii]d(?P=q3)\s*:\s*
  78. (?P<q4>['\"])(?P<id>[^'\"]+)(?P=q4),
  79. """, webpage) or
  80. re.search(
  81. r'''(?xs)
  82. (?P<q1>["\'])
  83. (?:https?:)?//cdnapi(?:sec)?\.kaltura\.com/.*?(?:p|partner_id)/(?P<partner_id>\d+).*?
  84. (?P=q1).*?
  85. (?:
  86. entry_?[Ii]d|
  87. (?P<q2>["\'])entry_?[Ii]d(?P=q2)
  88. )\s*:\s*
  89. (?P<q3>["\'])(?P<id>.+?)(?P=q3)
  90. ''', webpage))
  91. if mobj:
  92. embed_info = mobj.groupdict()
  93. url = 'kaltura:%(partner_id)s:%(id)s' % embed_info
  94. escaped_pid = re.escape(embed_info['partner_id'])
  95. service_url = re.search(
  96. r'<script[^>]+src=["\']((?:https?:)?//.+?)/p/%s/sp/%s00/embedIframeJs' % (escaped_pid, escaped_pid),
  97. webpage)
  98. if service_url:
  99. url = smuggle_url(url, {'service_url': service_url.group(1)})
  100. return url
  101. def _kaltura_api_call(self, video_id, actions, service_url=None, *args, **kwargs):
  102. params = actions[0]
  103. if len(actions) > 1:
  104. for i, a in enumerate(actions[1:], start=1):
  105. for k, v in a.items():
  106. params['%d:%s' % (i, k)] = v
  107. data = self._download_json(
  108. (service_url or self._SERVICE_URL) + self._SERVICE_BASE,
  109. video_id, query=params, *args, **kwargs)
  110. status = data if len(actions) == 1 else data[0]
  111. if status.get('objectType') == 'KalturaAPIException':
  112. raise ExtractorError(
  113. '%s said: %s' % (self.IE_NAME, status['message']))
  114. return data
  115. def _get_kaltura_signature(self, video_id, partner_id, service_url=None):
  116. actions = [{
  117. 'apiVersion': '3.1',
  118. 'expiry': 86400,
  119. 'format': 1,
  120. 'service': 'session',
  121. 'action': 'startWidgetSession',
  122. 'widgetId': '_%s' % partner_id,
  123. }]
  124. return self._kaltura_api_call(
  125. video_id, actions, service_url, note='Downloading Kaltura signature')['ks']
  126. def _get_video_info(self, video_id, partner_id, service_url=None):
  127. actions = [
  128. {
  129. 'action': 'null',
  130. 'apiVersion': '3.1.5',
  131. 'clientTag': 'kdp:v3.8.5',
  132. 'format': 1, # JSON, 2 = XML, 3 = PHP
  133. 'service': 'multirequest',
  134. },
  135. {
  136. 'expiry': 86400,
  137. 'service': 'session',
  138. 'action': 'startWidgetSession',
  139. 'widgetId': '_%s' % partner_id,
  140. },
  141. {
  142. 'action': 'get',
  143. 'entryId': video_id,
  144. 'service': 'baseentry',
  145. 'ks': '{1:result:ks}',
  146. },
  147. {
  148. 'action': 'getbyentryid',
  149. 'entryId': video_id,
  150. 'service': 'flavorAsset',
  151. 'ks': '{1:result:ks}',
  152. },
  153. {
  154. 'action': 'list',
  155. 'filter:entryIdEqual': video_id,
  156. 'service': 'caption_captionasset',
  157. 'ks': '{1:result:ks}',
  158. },
  159. ]
  160. return self._kaltura_api_call(
  161. video_id, actions, service_url, note='Downloading video info JSON')
  162. def _real_extract(self, url):
  163. url, smuggled_data = unsmuggle_url(url, {})
  164. mobj = re.match(self._VALID_URL, url)
  165. partner_id, entry_id = mobj.group('partner_id', 'id')
  166. ks = None
  167. captions = None
  168. if partner_id and entry_id:
  169. _, info, flavor_assets, captions = self._get_video_info(entry_id, partner_id, smuggled_data.get('service_url'))
  170. else:
  171. path, query = mobj.group('path', 'query')
  172. if not path and not query:
  173. raise ExtractorError('Invalid URL', expected=True)
  174. params = {}
  175. if query:
  176. params = compat_parse_qs(query)
  177. if path:
  178. splitted_path = path.split('/')
  179. params.update(dict((zip(splitted_path[::2], [[v] for v in splitted_path[1::2]]))))
  180. if 'wid' in params:
  181. partner_id = params['wid'][0][1:]
  182. elif 'p' in params:
  183. partner_id = params['p'][0]
  184. else:
  185. raise ExtractorError('Invalid URL', expected=True)
  186. if 'entry_id' in params:
  187. entry_id = params['entry_id'][0]
  188. _, info, flavor_assets, captions = self._get_video_info(entry_id, partner_id)
  189. elif 'uiconf_id' in params and 'flashvars[referenceId]' in params:
  190. reference_id = params['flashvars[referenceId]'][0]
  191. webpage = self._download_webpage(url, reference_id)
  192. entry_data = self._parse_json(self._search_regex(
  193. r'window\.kalturaIframePackageData\s*=\s*({.*});',
  194. webpage, 'kalturaIframePackageData'),
  195. reference_id)['entryResult']
  196. info, flavor_assets = entry_data['meta'], entry_data['contextData']['flavorAssets']
  197. entry_id = info['id']
  198. else:
  199. raise ExtractorError('Invalid URL', expected=True)
  200. ks = params.get('flashvars[ks]', [None])[0]
  201. source_url = smuggled_data.get('source_url')
  202. if source_url:
  203. referrer = base64.b64encode(
  204. '://'.join(compat_urlparse.urlparse(source_url)[:2])
  205. .encode('utf-8')).decode('utf-8')
  206. else:
  207. referrer = None
  208. def sign_url(unsigned_url):
  209. if ks:
  210. unsigned_url += '/ks/%s' % ks
  211. if referrer:
  212. unsigned_url += '?referrer=%s' % referrer
  213. return unsigned_url
  214. data_url = info['dataUrl']
  215. if '/flvclipper/' in data_url:
  216. data_url = re.sub(r'/flvclipper/.*', '/serveFlavor', data_url)
  217. formats = []
  218. for f in flavor_assets:
  219. # Continue if asset is not ready
  220. if f.get('status') != 2:
  221. continue
  222. video_url = sign_url(
  223. '%s/flavorId/%s' % (data_url, f['id']))
  224. formats.append({
  225. 'format_id': '%(fileExt)s-%(bitrate)s' % f,
  226. 'ext': f.get('fileExt'),
  227. 'tbr': int_or_none(f['bitrate']),
  228. 'fps': int_or_none(f.get('frameRate')),
  229. 'filesize_approx': int_or_none(f.get('size'), invscale=1024),
  230. 'container': f.get('containerFormat'),
  231. 'vcodec': f.get('videoCodecId'),
  232. 'height': int_or_none(f.get('height')),
  233. 'width': int_or_none(f.get('width')),
  234. 'url': video_url,
  235. })
  236. if '/playManifest/' in data_url:
  237. m3u8_url = sign_url(data_url.replace(
  238. 'format/url', 'format/applehttp'))
  239. formats.extend(self._extract_m3u8_formats(
  240. m3u8_url, entry_id, 'mp4', 'm3u8_native',
  241. m3u8_id='hls', fatal=False))
  242. self._sort_formats(formats)
  243. subtitles = {}
  244. if captions:
  245. for caption in captions.get('objects', []):
  246. # Continue if caption is not ready
  247. if f.get('status') != 2:
  248. continue
  249. subtitles.setdefault(caption.get('languageCode') or caption.get('language'), []).append({
  250. 'url': '%s/api_v3/service/caption_captionasset/action/serve/captionAssetId/%s' % (self._SERVICE_URL, caption['id']),
  251. 'ext': caption.get('fileExt'),
  252. })
  253. return {
  254. 'id': entry_id,
  255. 'title': info['name'],
  256. 'formats': formats,
  257. 'subtitles': subtitles,
  258. 'description': clean_html(info.get('description')),
  259. 'thumbnail': info.get('thumbnailUrl'),
  260. 'duration': info.get('duration'),
  261. 'timestamp': info.get('createdAt'),
  262. 'uploader_id': info.get('userId'),
  263. 'view_count': info.get('plays'),
  264. }