logo

youtube-dl

[mirror] Download/Watch videos from video hostersgit clone https://hacktivis.me/git/mirror/youtube-dl.git

kaltura.py (15427B)


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