kaltura.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  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_video_info(self, video_id, partner_id, service_url=None):
  116. actions = [
  117. {
  118. 'action': 'null',
  119. 'apiVersion': '3.1.5',
  120. 'clientTag': 'kdp:v3.8.5',
  121. 'format': 1, # JSON, 2 = XML, 3 = PHP
  122. 'service': 'multirequest',
  123. },
  124. {
  125. 'expiry': 86400,
  126. 'service': 'session',
  127. 'action': 'startWidgetSession',
  128. 'widgetId': '_%s' % partner_id,
  129. },
  130. {
  131. 'action': 'get',
  132. 'entryId': video_id,
  133. 'service': 'baseentry',
  134. 'ks': '{1:result:ks}',
  135. },
  136. {
  137. 'action': 'getbyentryid',
  138. 'entryId': video_id,
  139. 'service': 'flavorAsset',
  140. 'ks': '{1:result:ks}',
  141. },
  142. {
  143. 'action': 'list',
  144. 'filter:entryIdEqual': video_id,
  145. 'service': 'caption_captionasset',
  146. 'ks': '{1:result:ks}',
  147. },
  148. ]
  149. return self._kaltura_api_call(
  150. video_id, actions, service_url, note='Downloading video info JSON')
  151. def _real_extract(self, url):
  152. url, smuggled_data = unsmuggle_url(url, {})
  153. mobj = re.match(self._VALID_URL, url)
  154. partner_id, entry_id = mobj.group('partner_id', 'id')
  155. ks = None
  156. captions = None
  157. if partner_id and entry_id:
  158. _, info, flavor_assets, captions = self._get_video_info(entry_id, partner_id, smuggled_data.get('service_url'))
  159. else:
  160. path, query = mobj.group('path', 'query')
  161. if not path and not query:
  162. raise ExtractorError('Invalid URL', expected=True)
  163. params = {}
  164. if query:
  165. params = compat_parse_qs(query)
  166. if path:
  167. splitted_path = path.split('/')
  168. params.update(dict((zip(splitted_path[::2], [[v] for v in splitted_path[1::2]]))))
  169. if 'wid' in params:
  170. partner_id = params['wid'][0][1:]
  171. elif 'p' in params:
  172. partner_id = params['p'][0]
  173. else:
  174. raise ExtractorError('Invalid URL', expected=True)
  175. if 'entry_id' in params:
  176. entry_id = params['entry_id'][0]
  177. _, info, flavor_assets, captions = self._get_video_info(entry_id, partner_id)
  178. elif 'uiconf_id' in params and 'flashvars[referenceId]' in params:
  179. reference_id = params['flashvars[referenceId]'][0]
  180. webpage = self._download_webpage(url, reference_id)
  181. entry_data = self._parse_json(self._search_regex(
  182. r'window\.kalturaIframePackageData\s*=\s*({.*});',
  183. webpage, 'kalturaIframePackageData'),
  184. reference_id)['entryResult']
  185. info, flavor_assets = entry_data['meta'], entry_data['contextData']['flavorAssets']
  186. entry_id = info['id']
  187. else:
  188. raise ExtractorError('Invalid URL', expected=True)
  189. ks = params.get('flashvars[ks]', [None])[0]
  190. source_url = smuggled_data.get('source_url')
  191. if source_url:
  192. referrer = base64.b64encode(
  193. '://'.join(compat_urlparse.urlparse(source_url)[:2])
  194. .encode('utf-8')).decode('utf-8')
  195. else:
  196. referrer = None
  197. def sign_url(unsigned_url):
  198. if ks:
  199. unsigned_url += '/ks/%s' % ks
  200. if referrer:
  201. unsigned_url += '?referrer=%s' % referrer
  202. return unsigned_url
  203. data_url = info['dataUrl']
  204. if '/flvclipper/' in data_url:
  205. data_url = re.sub(r'/flvclipper/.*', '/serveFlavor', data_url)
  206. formats = []
  207. for f in flavor_assets:
  208. # Continue if asset is not ready
  209. if f.get('status') != 2:
  210. continue
  211. video_url = sign_url(
  212. '%s/flavorId/%s' % (data_url, f['id']))
  213. formats.append({
  214. 'format_id': '%(fileExt)s-%(bitrate)s' % f,
  215. 'ext': f.get('fileExt'),
  216. 'tbr': int_or_none(f['bitrate']),
  217. 'fps': int_or_none(f.get('frameRate')),
  218. 'filesize_approx': int_or_none(f.get('size'), invscale=1024),
  219. 'container': f.get('containerFormat'),
  220. 'vcodec': f.get('videoCodecId'),
  221. 'height': int_or_none(f.get('height')),
  222. 'width': int_or_none(f.get('width')),
  223. 'url': video_url,
  224. })
  225. if '/playManifest/' in data_url:
  226. m3u8_url = sign_url(data_url.replace(
  227. 'format/url', 'format/applehttp'))
  228. formats.extend(self._extract_m3u8_formats(
  229. m3u8_url, entry_id, 'mp4', 'm3u8_native',
  230. m3u8_id='hls', fatal=False))
  231. self._sort_formats(formats)
  232. subtitles = {}
  233. if captions:
  234. for caption in captions.get('objects', []):
  235. # Continue if caption is not ready
  236. if f.get('status') != 2:
  237. continue
  238. subtitles.setdefault(caption.get('languageCode') or caption.get('language'), []).append({
  239. 'url': '%s/api_v3/service/caption_captionasset/action/serve/captionAssetId/%s' % (self._SERVICE_URL, caption['id']),
  240. 'ext': caption.get('fileExt'),
  241. })
  242. return {
  243. 'id': entry_id,
  244. 'title': info['name'],
  245. 'formats': formats,
  246. 'subtitles': subtitles,
  247. 'description': clean_html(info.get('description')),
  248. 'thumbnail': info.get('thumbnailUrl'),
  249. 'duration': info.get('duration'),
  250. 'timestamp': info.get('createdAt'),
  251. 'uploader_id': info.get('userId'),
  252. 'view_count': info.get('plays'),
  253. }