redbee.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  1. import json
  2. import re
  3. import time
  4. import urllib.parse
  5. import uuid
  6. from .common import InfoExtractor
  7. from ..utils import (
  8. ExtractorError,
  9. float_or_none,
  10. int_or_none,
  11. strip_or_none,
  12. traverse_obj,
  13. try_call,
  14. unified_timestamp,
  15. )
  16. class RedBeeBaseIE(InfoExtractor):
  17. _DEVICE_ID = str(uuid.uuid4())
  18. @property
  19. def _API_URL(self):
  20. """
  21. Ref: https://apidocs.emp.ebsd.ericsson.net
  22. Subclasses must set _REDBEE_CUSTOMER, _REDBEE_BUSINESS_UNIT
  23. """
  24. return f'https://exposure.api.redbee.live/v2/customer/{self._REDBEE_CUSTOMER}/businessunit/{self._REDBEE_BUSINESS_UNIT}'
  25. def _get_bearer_token(self, asset_id, jwt=None):
  26. request = {
  27. 'deviceId': self._DEVICE_ID,
  28. 'device': {
  29. 'deviceId': self._DEVICE_ID,
  30. 'name': 'Mozilla Firefox 102',
  31. 'type': 'WEB',
  32. },
  33. }
  34. if jwt:
  35. request['jwt'] = jwt
  36. return self._download_json(
  37. f'{self._API_URL}/auth/{"gigyaLogin" if jwt else "anonymous"}',
  38. asset_id, data=json.dumps(request).encode('utf-8'), headers={
  39. 'Content-Type': 'application/json;charset=utf-8'
  40. })['sessionToken']
  41. def _get_formats_and_subtitles(self, asset_id, **kwargs):
  42. bearer_token = self._get_bearer_token(asset_id, **kwargs)
  43. api_response = self._download_json(
  44. f'{self._API_URL}/entitlement/{asset_id}/play',
  45. asset_id, headers={
  46. 'Authorization': f'Bearer {bearer_token}',
  47. 'Accept': 'application/json, text/plain, */*'
  48. })
  49. formats, subtitles = [], {}
  50. for format in api_response['formats']:
  51. if not format.get('mediaLocator'):
  52. continue
  53. fmts, subs = [], {}
  54. if format.get('format') == 'DASH':
  55. fmts, subs = self._extract_mpd_formats_and_subtitles(
  56. format['mediaLocator'], asset_id, fatal=False)
  57. elif format.get('format') == 'SMOOTHSTREAMING':
  58. fmts, subs = self._extract_ism_formats_and_subtitles(
  59. format['mediaLocator'], asset_id, fatal=False)
  60. elif format.get('format') == 'HLS':
  61. fmts, subs = self._extract_m3u8_formats_and_subtitles(
  62. format['mediaLocator'], asset_id, fatal=False)
  63. if format.get('drm'):
  64. for f in fmts:
  65. f['has_drm'] = True
  66. formats.extend(fmts)
  67. self._merge_subtitles(subs, target=subtitles)
  68. return formats, subtitles
  69. class ParliamentLiveUKIE(RedBeeBaseIE):
  70. IE_NAME = 'parliamentlive.tv'
  71. IE_DESC = 'UK parliament videos'
  72. _VALID_URL = r'(?i)https?://(?:www\.)?parliamentlive\.tv/Event/Index/(?P<id>[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12})'
  73. _REDBEE_CUSTOMER = 'UKParliament'
  74. _REDBEE_BUSINESS_UNIT = 'ParliamentLive'
  75. _TESTS = [{
  76. 'url': 'http://parliamentlive.tv/Event/Index/c1e9d44d-fd6c-4263-b50f-97ed26cc998b',
  77. 'info_dict': {
  78. 'id': 'c1e9d44d-fd6c-4263-b50f-97ed26cc998b',
  79. 'ext': 'mp4',
  80. 'title': 'Home Affairs Committee',
  81. 'timestamp': 1395153872,
  82. 'upload_date': '20140318',
  83. 'thumbnail': r're:https?://[^?#]+c1e9d44d-fd6c-4263-b50f-97ed26cc998b[^/]*/thumbnail',
  84. },
  85. }, {
  86. 'url': 'http://parliamentlive.tv/event/index/3f24936f-130f-40bf-9a5d-b3d6479da6a4',
  87. 'only_matching': True,
  88. }, {
  89. 'url': 'https://parliamentlive.tv/Event/Index/27cf25e4-e77b-42a3-93c5-c815cd6d7377',
  90. 'info_dict': {
  91. 'id': '27cf25e4-e77b-42a3-93c5-c815cd6d7377',
  92. 'ext': 'mp4',
  93. 'title': 'House of Commons',
  94. 'timestamp': 1658392447,
  95. 'upload_date': '20220721',
  96. 'thumbnail': r're:https?://[^?#]+27cf25e4-e77b-42a3-93c5-c815cd6d7377[^/]*/thumbnail',
  97. },
  98. }]
  99. def _real_extract(self, url):
  100. video_id = self._match_id(url)
  101. formats, subtitles = self._get_formats_and_subtitles(video_id)
  102. video_info = self._download_json(
  103. f'https://www.parliamentlive.tv/Event/GetShareVideo/{video_id}', video_id, fatal=False)
  104. return {
  105. 'id': video_id,
  106. 'formats': formats,
  107. 'subtitles': subtitles,
  108. 'title': traverse_obj(video_info, ('event', 'title')),
  109. 'thumbnail': traverse_obj(video_info, 'thumbnailUrl'),
  110. 'timestamp': traverse_obj(
  111. video_info, ('event', 'publishedStartTime'), expected_type=unified_timestamp),
  112. '_format_sort_fields': ('res', 'proto'),
  113. }
  114. class RTBFIE(RedBeeBaseIE):
  115. _VALID_URL = r'''(?x)
  116. https?://(?:www\.)?rtbf\.be/
  117. (?:
  118. video/[^?]+\?.*\bid=|
  119. ouftivi/(?:[^/]+/)*[^?]+\?.*\bvideoId=|
  120. auvio/[^/]+\?.*\b(?P<live>l)?id=
  121. )(?P<id>\d+)'''
  122. _NETRC_MACHINE = 'rtbf'
  123. _REDBEE_CUSTOMER = 'RTBF'
  124. _REDBEE_BUSINESS_UNIT = 'Auvio'
  125. _TESTS = [{
  126. 'url': 'https://www.rtbf.be/video/detail_les-diables-au-coeur-episode-2?id=1921274',
  127. 'md5': '8c876a1cceeb6cf31b476461ade72384',
  128. 'info_dict': {
  129. 'id': '1921274',
  130. 'ext': 'mp4',
  131. 'title': 'Les Diables au coeur (épisode 2)',
  132. 'description': '(du 25/04/2014)',
  133. 'duration': 3099.54,
  134. 'upload_date': '20140425',
  135. 'timestamp': 1398456300,
  136. },
  137. 'skip': 'No longer available',
  138. }, {
  139. # geo restricted
  140. 'url': 'http://www.rtbf.be/ouftivi/heros/detail_scooby-doo-mysteres-associes?id=1097&videoId=2057442',
  141. 'only_matching': True,
  142. }, {
  143. 'url': 'http://www.rtbf.be/ouftivi/niouzz?videoId=2055858',
  144. 'only_matching': True,
  145. }, {
  146. 'url': 'http://www.rtbf.be/auvio/detail_jeudi-en-prime-siegfried-bracke?id=2102996',
  147. 'only_matching': True,
  148. }, {
  149. # Live
  150. 'url': 'https://www.rtbf.be/auvio/direct_pure-fm?lid=134775',
  151. 'only_matching': True,
  152. }, {
  153. # Audio
  154. 'url': 'https://www.rtbf.be/auvio/detail_cinq-heures-cinema?id=2360811',
  155. 'only_matching': True,
  156. }, {
  157. # With Subtitle
  158. 'url': 'https://www.rtbf.be/auvio/detail_les-carnets-du-bourlingueur?id=2361588',
  159. 'only_matching': True,
  160. }, {
  161. 'url': 'https://www.rtbf.be/auvio/detail_investigation?id=2921926',
  162. 'md5': 'd5d11bb62169fef38d7ce7ac531e034f',
  163. 'info_dict': {
  164. 'id': '2921926',
  165. 'ext': 'mp4',
  166. 'title': 'Le handicap un confinement perpétuel - Maladie de Lyme',
  167. 'description': 'md5:dcbd5dcf6015488c9069b057c15ccc52',
  168. 'duration': 5258.8,
  169. 'upload_date': '20220727',
  170. 'timestamp': 1658934000,
  171. 'series': '#Investigation',
  172. 'thumbnail': r're:^https?://[^?&]+\.jpg$',
  173. },
  174. }, {
  175. 'url': 'https://www.rtbf.be/auvio/detail_la-belgique-criminelle?id=2920492',
  176. 'md5': '054f9f143bc79c89647c35e5a7d35fa8',
  177. 'info_dict': {
  178. 'id': '2920492',
  179. 'ext': 'mp4',
  180. 'title': '04 - Le crime de la rue Royale',
  181. 'description': 'md5:0c3da1efab286df83f2ab3f8f96bd7a6',
  182. 'duration': 1574.6,
  183. 'upload_date': '20220723',
  184. 'timestamp': 1658596887,
  185. 'series': 'La Belgique criminelle - TV',
  186. 'thumbnail': r're:^https?://[^?&]+\.jpg$',
  187. },
  188. }]
  189. _IMAGE_HOST = 'http://ds1.ds.static.rtbf.be'
  190. _PROVIDERS = {
  191. 'YOUTUBE': 'Youtube',
  192. 'DAILYMOTION': 'Dailymotion',
  193. 'VIMEO': 'Vimeo',
  194. }
  195. _QUALITIES = [
  196. ('mobile', 'SD'),
  197. ('web', 'MD'),
  198. ('high', 'HD'),
  199. ]
  200. _LOGIN_URL = 'https://login.rtbf.be/accounts.login'
  201. _GIGYA_API_KEY = '3_kWKuPgcdAybqnqxq_MvHVk0-6PN8Zk8pIIkJM_yXOu-qLPDDsGOtIDFfpGivtbeO'
  202. _LOGIN_COOKIE_ID = f'glt_{_GIGYA_API_KEY}'
  203. def _perform_login(self, username, password):
  204. if self._get_cookies(self._LOGIN_URL).get(self._LOGIN_COOKIE_ID):
  205. return
  206. self._set_cookie('.rtbf.be', 'gmid', 'gmid.ver4', secure=True, expire_time=time.time() + 3600)
  207. login_response = self._download_json(
  208. self._LOGIN_URL, None, data=urllib.parse.urlencode({
  209. 'loginID': username,
  210. 'password': password,
  211. 'APIKey': self._GIGYA_API_KEY,
  212. 'targetEnv': 'jssdk',
  213. 'sessionExpiration': '-2',
  214. }).encode('utf-8'), headers={
  215. 'Content-Type': 'application/x-www-form-urlencoded',
  216. })
  217. if login_response['statusCode'] != 200:
  218. raise ExtractorError('Login failed. Server message: %s' % login_response['errorMessage'], expected=True)
  219. self._set_cookie('.rtbf.be', self._LOGIN_COOKIE_ID, login_response['sessionInfo']['login_token'],
  220. secure=True, expire_time=time.time() + 3600)
  221. def _get_formats_and_subtitles(self, url, media_id):
  222. login_token = self._get_cookies(url).get(self._LOGIN_COOKIE_ID)
  223. if not login_token:
  224. self.raise_login_required()
  225. session_jwt = try_call(lambda: self._get_cookies(url)['rtbf_jwt'].value) or self._download_json(
  226. 'https://login.rtbf.be/accounts.getJWT', media_id, query={
  227. 'login_token': login_token.value,
  228. 'APIKey': self._GIGYA_API_KEY,
  229. 'sdk': 'js_latest',
  230. 'authMode': 'cookie',
  231. 'pageURL': url,
  232. 'sdkBuild': '13273',
  233. 'format': 'json',
  234. })['id_token']
  235. return super()._get_formats_and_subtitles(media_id, jwt=session_jwt)
  236. def _real_extract(self, url):
  237. live, media_id = self._match_valid_url(url).groups()
  238. embed_page = self._download_webpage(
  239. 'https://www.rtbf.be/auvio/embed/' + ('direct' if live else 'media'),
  240. media_id, query={'id': media_id})
  241. media_data = self._html_search_regex(r'data-media="([^"]+)"', embed_page, 'media data', fatal=False)
  242. if not media_data:
  243. if re.search(r'<div[^>]+id="js-error-expired"[^>]+class="(?![^"]*hidden)', embed_page):
  244. raise ExtractorError('Livestream has ended.', expected=True)
  245. if re.search(r'<div[^>]+id="js-sso-connect"[^>]+class="(?![^"]*hidden)', embed_page):
  246. self.raise_login_required()
  247. raise ExtractorError('Could not find media data')
  248. data = self._parse_json(media_data, media_id)
  249. error = data.get('error')
  250. if error:
  251. raise ExtractorError('%s said: %s' % (self.IE_NAME, error), expected=True)
  252. provider = data.get('provider')
  253. if provider in self._PROVIDERS:
  254. return self.url_result(data['url'], self._PROVIDERS[provider])
  255. title = traverse_obj(data, 'subtitle', 'title')
  256. is_live = data.get('isLive')
  257. height_re = r'-(\d+)p\.'
  258. formats, subtitles = [], {}
  259. # The old api still returns m3u8 and mpd manifest for livestreams, but these are 'fake'
  260. # since all they contain is a 20s video that is completely unrelated.
  261. # https://github.com/hypervideo/hypervideo/issues/4656#issuecomment-1214461092
  262. m3u8_url = None if data.get('isLive') else traverse_obj(data, 'urlHlsAes128', 'urlHls')
  263. if m3u8_url:
  264. fmts, subs = self._extract_m3u8_formats_and_subtitles(
  265. m3u8_url, media_id, 'mp4', m3u8_id='hls', fatal=False)
  266. formats.extend(fmts)
  267. self._merge_subtitles(subs, target=subtitles)
  268. fix_url = lambda x: x.replace('//rtbf-vod.', '//rtbf.') if '/geo/drm/' in x else x
  269. http_url = data.get('url')
  270. if formats and http_url and re.search(height_re, http_url):
  271. http_url = fix_url(http_url)
  272. for m3u8_f in formats[:]:
  273. height = m3u8_f.get('height')
  274. if not height:
  275. continue
  276. f = m3u8_f.copy()
  277. del f['protocol']
  278. f.update({
  279. 'format_id': m3u8_f['format_id'].replace('hls-', 'http-'),
  280. 'url': re.sub(height_re, '-%dp.' % height, http_url),
  281. })
  282. formats.append(f)
  283. else:
  284. sources = data.get('sources') or {}
  285. for key, format_id in self._QUALITIES:
  286. format_url = sources.get(key)
  287. if not format_url:
  288. continue
  289. height = int_or_none(self._search_regex(
  290. height_re, format_url, 'height', default=None))
  291. formats.append({
  292. 'format_id': format_id,
  293. 'url': fix_url(format_url),
  294. 'height': height,
  295. })
  296. mpd_url = None if data.get('isLive') else data.get('urlDash')
  297. if mpd_url and (self.get_param('allow_unplayable_formats') or not data.get('drm')):
  298. fmts, subs = self._extract_mpd_formats_and_subtitles(
  299. mpd_url, media_id, mpd_id='dash', fatal=False)
  300. formats.extend(fmts)
  301. self._merge_subtitles(subs, target=subtitles)
  302. audio_url = data.get('urlAudio')
  303. if audio_url:
  304. formats.append({
  305. 'format_id': 'audio',
  306. 'url': audio_url,
  307. 'vcodec': 'none',
  308. })
  309. for track in (data.get('tracks') or {}).values():
  310. sub_url = track.get('url')
  311. if not sub_url:
  312. continue
  313. subtitles.setdefault(track.get('lang') or 'fr', []).append({
  314. 'url': sub_url,
  315. })
  316. if not formats:
  317. fmts, subs = self._get_formats_and_subtitles(url, f'live_{media_id}' if is_live else media_id)
  318. formats.extend(fmts)
  319. self._merge_subtitles(subs, target=subtitles)
  320. return {
  321. 'id': media_id,
  322. 'formats': formats,
  323. 'title': title,
  324. 'description': strip_or_none(data.get('description')),
  325. 'thumbnail': data.get('thumbnail'),
  326. 'duration': float_or_none(data.get('realDuration')),
  327. 'timestamp': int_or_none(data.get('liveFrom')),
  328. 'series': data.get('programLabel'),
  329. 'subtitles': subtitles,
  330. 'is_live': is_live,
  331. '_format_sort_fields': ('res', 'proto'),
  332. }