logo

oasis-root

Compiled tree of Oasis Linux based on own branch at <https://hacktivis.me/git/oasis/> git clone https://anongit.hacktivis.me/git/oasis-root.git

vrt.py (21503B)


  1. import json
  2. import time
  3. import urllib.parse
  4. from .gigya import GigyaBaseIE
  5. from ..networking.exceptions import HTTPError
  6. from ..utils import (
  7. ExtractorError,
  8. clean_html,
  9. extract_attributes,
  10. float_or_none,
  11. get_element_by_class,
  12. get_element_html_by_class,
  13. int_or_none,
  14. join_nonempty,
  15. jwt_encode_hs256,
  16. make_archive_id,
  17. merge_dicts,
  18. parse_age_limit,
  19. parse_iso8601,
  20. str_or_none,
  21. strip_or_none,
  22. traverse_obj,
  23. url_or_none,
  24. urlencode_postdata,
  25. )
  26. class VRTBaseIE(GigyaBaseIE):
  27. _GEO_BYPASS = False
  28. _PLAYER_INFO = {
  29. 'platform': 'desktop',
  30. 'app': {
  31. 'type': 'browser',
  32. 'name': 'Chrome',
  33. },
  34. 'device': 'undefined (undefined)',
  35. 'os': {
  36. 'name': 'Windows',
  37. 'version': 'x86_64',
  38. },
  39. 'player': {
  40. 'name': 'VRT web player',
  41. 'version': '2.7.4-prod-2023-04-19T06:05:45',
  42. },
  43. }
  44. # From https://player.vrt.be/vrtnws/js/main.js & https://player.vrt.be/ketnet/js/main.8cdb11341bcb79e4cd44.js
  45. _JWT_KEY_ID = '0-0Fp51UZykfaiCJrfTE3+oMI8zvDteYfPtR+2n1R+z8w='
  46. _JWT_SIGNING_KEY = 'b5f500d55cb44715107249ccd8a5c0136cfb2788dbb71b90a4f142423bacaf38' # -dev
  47. # player-stag.vrt.be key: d23987504521ae6fbf2716caca6700a24bb1579477b43c84e146b279de5ca595
  48. # player.vrt.be key: 2a9251d782700769fb856da5725daf38661874ca6f80ae7dc2b05ec1a81a24ae
  49. def _extract_formats_and_subtitles(self, data, video_id):
  50. if traverse_obj(data, 'drm'):
  51. self.report_drm(video_id)
  52. formats, subtitles = [], {}
  53. for target in traverse_obj(data, ('targetUrls', lambda _, v: url_or_none(v['url']) and v['type'])):
  54. format_type = target['type'].upper()
  55. format_url = target['url']
  56. if format_type in ('HLS', 'HLS_AES'):
  57. fmts, subs = self._extract_m3u8_formats_and_subtitles(
  58. format_url, video_id, 'mp4', m3u8_id=format_type, fatal=False)
  59. formats.extend(fmts)
  60. self._merge_subtitles(subs, target=subtitles)
  61. elif format_type == 'HDS':
  62. formats.extend(self._extract_f4m_formats(
  63. format_url, video_id, f4m_id=format_type, fatal=False))
  64. elif format_type == 'MPEG_DASH':
  65. fmts, subs = self._extract_mpd_formats_and_subtitles(
  66. format_url, video_id, mpd_id=format_type, fatal=False)
  67. formats.extend(fmts)
  68. self._merge_subtitles(subs, target=subtitles)
  69. elif format_type == 'HSS':
  70. fmts, subs = self._extract_ism_formats_and_subtitles(
  71. format_url, video_id, ism_id='mss', fatal=False)
  72. formats.extend(fmts)
  73. self._merge_subtitles(subs, target=subtitles)
  74. else:
  75. formats.append({
  76. 'format_id': format_type,
  77. 'url': format_url,
  78. })
  79. for sub in traverse_obj(data, ('subtitleUrls', lambda _, v: v['url'] and v['type'] == 'CLOSED')):
  80. subtitles.setdefault('nl', []).append({'url': sub['url']})
  81. return formats, subtitles
  82. def _call_api(self, video_id, client='null', id_token=None, version='v2'):
  83. player_info = {'exp': (round(time.time(), 3) + 900), **self._PLAYER_INFO}
  84. player_token = self._download_json(
  85. 'https://media-services-public.vrt.be/vualto-video-aggregator-web/rest/external/v2/tokens',
  86. video_id, 'Downloading player token', headers={
  87. **self.geo_verification_headers(),
  88. 'Content-Type': 'application/json',
  89. }, data=json.dumps({
  90. 'identityToken': id_token or {},
  91. 'playerInfo': jwt_encode_hs256(player_info, self._JWT_SIGNING_KEY, headers={
  92. 'kid': self._JWT_KEY_ID,
  93. }).decode(),
  94. }, separators=(',', ':')).encode())['vrtPlayerToken']
  95. return self._download_json(
  96. f'https://media-services-public.vrt.be/media-aggregator/{version}/media-items/{video_id}',
  97. video_id, 'Downloading API JSON', query={
  98. 'vrtPlayerToken': player_token,
  99. 'client': client,
  100. }, expected_status=400)
  101. class VRTIE(VRTBaseIE):
  102. IE_DESC = 'VRT NWS, Flanders News, Flandern Info and Sporza'
  103. _VALID_URL = r'https?://(?:www\.)?(?P<site>vrt\.be/vrtnws|sporza\.be)/[a-z]{2}/\d{4}/\d{2}/\d{2}/(?P<id>[^/?&#]+)'
  104. _TESTS = [{
  105. 'url': 'https://www.vrt.be/vrtnws/nl/2019/05/15/beelden-van-binnenkant-notre-dame-een-maand-na-de-brand/',
  106. 'info_dict': {
  107. 'id': 'pbs-pub-7855fc7b-1448-49bc-b073-316cb60caa71$vid-2ca50305-c38a-4762-9890-65cbd098b7bd',
  108. 'ext': 'mp4',
  109. 'title': 'Beelden van binnenkant Notre-Dame, één maand na de brand',
  110. 'description': 'md5:6fd85f999b2d1841aa5568f4bf02c3ff',
  111. 'duration': 31.2,
  112. 'thumbnail': 'https://images.vrt.be/orig/2019/05/15/2d914d61-7710-11e9-abcc-02b7b76bf47f.jpg',
  113. },
  114. 'params': {'skip_download': 'm3u8'},
  115. }, {
  116. 'url': 'https://sporza.be/nl/2019/05/15/de-belgian-cats-zijn-klaar-voor-het-ek/',
  117. 'info_dict': {
  118. 'id': 'pbs-pub-f2c86a46-8138-413a-a4b9-a0015a16ce2c$vid-1f112b31-e58e-4379-908d-aca6d80f8818',
  119. 'ext': 'mp4',
  120. 'title': 'De Belgian Cats zijn klaar voor het EK',
  121. 'description': 'Video: De Belgian Cats zijn klaar voor het EK mét Ann Wauters | basketbal, sport in het journaal',
  122. 'duration': 115.17,
  123. 'thumbnail': 'https://images.vrt.be/orig/2019/05/15/11c0dba3-770e-11e9-abcc-02b7b76bf47f.jpg',
  124. },
  125. 'params': {'skip_download': 'm3u8'},
  126. }]
  127. _CLIENT_MAP = {
  128. 'vrt.be/vrtnws': 'vrtnieuws',
  129. 'sporza.be': 'sporza',
  130. }
  131. def _real_extract(self, url):
  132. site, display_id = self._match_valid_url(url).groups()
  133. webpage = self._download_webpage(url, display_id)
  134. attrs = extract_attributes(get_element_html_by_class('vrtvideo', webpage) or '')
  135. asset_id = attrs.get('data-video-id') or attrs['data-videoid']
  136. publication_id = traverse_obj(attrs, 'data-publication-id', 'data-publicationid')
  137. if publication_id:
  138. asset_id = f'{publication_id}${asset_id}'
  139. client = traverse_obj(attrs, 'data-client-code', 'data-client') or self._CLIENT_MAP[site]
  140. data = self._call_api(asset_id, client)
  141. formats, subtitles = self._extract_formats_and_subtitles(data, asset_id)
  142. description = self._html_search_meta(
  143. ['og:description', 'twitter:description', 'description'], webpage)
  144. if description == '…':
  145. description = None
  146. return {
  147. 'id': asset_id,
  148. 'formats': formats,
  149. 'subtitles': subtitles,
  150. 'description': description,
  151. 'thumbnail': url_or_none(attrs.get('data-posterimage')),
  152. 'duration': float_or_none(attrs.get('data-duration'), 1000),
  153. '_old_archive_ids': [make_archive_id('Canvas', asset_id)],
  154. **traverse_obj(data, {
  155. 'title': ('title', {str}),
  156. 'description': ('shortDescription', {str}),
  157. 'duration': ('duration', {float_or_none(scale=1000)}),
  158. 'thumbnail': ('posterImageUrl', {url_or_none}),
  159. }),
  160. }
  161. class VrtNUIE(VRTBaseIE):
  162. IE_DESC = 'VRT MAX'
  163. _VALID_URL = r'https?://(?:www\.)?vrt\.be/vrtnu/a-z/(?:[^/]+/){2}(?P<id>[^/?#&]+)'
  164. _TESTS = [{
  165. # CONTENT_IS_AGE_RESTRICTED
  166. 'url': 'https://www.vrt.be/vrtnu/a-z/de-ideale-wereld/2023-vj/de-ideale-wereld-d20230116/',
  167. 'info_dict': {
  168. 'id': 'pbs-pub-855b00a8-6ce2-4032-ac4f-1fcf3ae78524$vid-d2243aa1-ec46-4e34-a55b-92568459906f',
  169. 'ext': 'mp4',
  170. 'title': 'Tom Waes',
  171. 'description': 'Satirisch actualiteitenmagazine met Ella Leyers. Tom Waes is te gast.',
  172. 'timestamp': 1673905125,
  173. 'release_timestamp': 1673905125,
  174. 'series': 'De ideale wereld',
  175. 'season_id': '1672830988794',
  176. 'episode': 'Aflevering 1',
  177. 'episode_number': 1,
  178. 'episode_id': '1672830988861',
  179. 'display_id': 'de-ideale-wereld-d20230116',
  180. 'channel': 'VRT',
  181. 'duration': 1939.0,
  182. 'thumbnail': 'https://images.vrt.be/orig/2023/01/10/1bb39cb3-9115-11ed-b07d-02b7b76bf47f.jpg',
  183. 'release_date': '20230116',
  184. 'upload_date': '20230116',
  185. 'age_limit': 12,
  186. },
  187. }, {
  188. 'url': 'https://www.vrt.be/vrtnu/a-z/buurman--wat-doet-u-nu-/6/buurman--wat-doet-u-nu--s6-trailer/',
  189. 'info_dict': {
  190. 'id': 'pbs-pub-ad4050eb-d9e5-48c2-9ec8-b6c355032361$vid-0465537a-34a8-4617-8352-4d8d983b4eee',
  191. 'ext': 'mp4',
  192. 'title': 'Trailer seizoen 6 \'Buurman, wat doet u nu?\'',
  193. 'description': 'md5:197424726c61384b4e5c519f16c0cf02',
  194. 'timestamp': 1652940000,
  195. 'release_timestamp': 1652940000,
  196. 'series': 'Buurman, wat doet u nu?',
  197. 'season': 'Seizoen 6',
  198. 'season_number': 6,
  199. 'season_id': '1652344200907',
  200. 'episode': 'Aflevering 0',
  201. 'episode_number': 0,
  202. 'episode_id': '1652951873524',
  203. 'display_id': 'buurman--wat-doet-u-nu--s6-trailer',
  204. 'channel': 'VRT',
  205. 'duration': 33.13,
  206. 'thumbnail': 'https://images.vrt.be/orig/2022/05/23/3c234d21-da83-11ec-b07d-02b7b76bf47f.jpg',
  207. 'release_date': '20220519',
  208. 'upload_date': '20220519',
  209. },
  210. 'params': {'skip_download': 'm3u8'},
  211. }]
  212. _NETRC_MACHINE = 'vrtnu'
  213. _authenticated = False
  214. def _perform_login(self, username, password):
  215. auth_info = self._gigya_login({
  216. 'APIKey': '3_0Z2HujMtiWq_pkAjgnS2Md2E11a1AwZjYiBETtwNE-EoEHDINgtnvcAOpNgmrVGy',
  217. 'targetEnv': 'jssdk',
  218. 'loginID': username,
  219. 'password': password,
  220. 'authMode': 'cookie',
  221. })
  222. if auth_info.get('errorDetails'):
  223. raise ExtractorError(f'Unable to login. VrtNU said: {auth_info["errorDetails"]}', expected=True)
  224. # Sometimes authentication fails for no good reason, retry
  225. for retry in self.RetryManager():
  226. if retry.attempt > 1:
  227. self._sleep(1, None)
  228. try:
  229. self._request_webpage(
  230. 'https://token.vrt.be/vrtnuinitlogin', None, note='Requesting XSRF Token',
  231. errnote='Could not get XSRF Token', query={
  232. 'provider': 'site',
  233. 'destination': 'https://www.vrt.be/vrtnu/',
  234. })
  235. self._request_webpage(
  236. 'https://login.vrt.be/perform_login', None,
  237. note='Performing login', errnote='Login failed',
  238. query={'client_id': 'vrtnu-site'}, data=urlencode_postdata({
  239. 'UID': auth_info['UID'],
  240. 'UIDSignature': auth_info['UIDSignature'],
  241. 'signatureTimestamp': auth_info['signatureTimestamp'],
  242. '_csrf': self._get_cookies('https://login.vrt.be').get('OIDCXSRF').value,
  243. }))
  244. except ExtractorError as e:
  245. if isinstance(e.cause, HTTPError) and e.cause.status == 401:
  246. retry.error = e
  247. continue
  248. raise
  249. self._authenticated = True
  250. def _real_extract(self, url):
  251. display_id = self._match_id(url)
  252. parsed_url = urllib.parse.urlparse(url)
  253. details = self._download_json(
  254. f'{parsed_url.scheme}://{parsed_url.netloc}{parsed_url.path.rstrip("/")}.model.json',
  255. display_id, 'Downloading asset JSON', 'Unable to download asset JSON')['details']
  256. watch_info = traverse_obj(details, (
  257. 'actions', lambda _, v: v['type'] == 'watch-episode', {dict}), get_all=False) or {}
  258. video_id = join_nonempty(
  259. 'episodePublicationId', 'episodeVideoId', delim='$', from_dict=watch_info)
  260. if '$' not in video_id:
  261. raise ExtractorError('Unable to extract video ID')
  262. vrtnutoken = self._download_json(
  263. 'https://token.vrt.be/refreshtoken', video_id, note='Retrieving vrtnutoken',
  264. errnote='Token refresh failed')['vrtnutoken'] if self._authenticated else None
  265. video_info = self._call_api(video_id, 'vrtnu-web@PROD', vrtnutoken)
  266. if 'title' not in video_info:
  267. code = video_info.get('code')
  268. if code in ('AUTHENTICATION_REQUIRED', 'CONTENT_IS_AGE_RESTRICTED'):
  269. self.raise_login_required(code, method='password')
  270. elif code in ('INVALID_LOCATION', 'CONTENT_AVAILABLE_ONLY_IN_BE'):
  271. self.raise_geo_restricted(countries=['BE'])
  272. elif code == 'CONTENT_AVAILABLE_ONLY_FOR_BE_RESIDENTS_AND_EXPATS':
  273. if not self._authenticated:
  274. self.raise_login_required(code, method='password')
  275. self.raise_geo_restricted(countries=['BE'])
  276. raise ExtractorError(code, expected=True)
  277. formats, subtitles = self._extract_formats_and_subtitles(video_info, video_id)
  278. return {
  279. **traverse_obj(details, {
  280. 'title': 'title',
  281. 'description': ('description', {clean_html}),
  282. 'timestamp': ('data', 'episode', 'onTime', 'raw', {parse_iso8601}),
  283. 'release_timestamp': ('data', 'episode', 'onTime', 'raw', {parse_iso8601}),
  284. 'series': ('data', 'program', 'title'),
  285. 'season': ('data', 'season', 'title', 'value'),
  286. 'season_number': ('data', 'season', 'title', 'raw', {int_or_none}),
  287. 'season_id': ('data', 'season', 'id', {str_or_none}),
  288. 'episode': ('data', 'episode', 'number', 'value', {str_or_none}),
  289. 'episode_number': ('data', 'episode', 'number', 'raw', {int_or_none}),
  290. 'episode_id': ('data', 'episode', 'id', {str_or_none}),
  291. 'age_limit': ('data', 'episode', 'age', 'raw', {parse_age_limit}),
  292. }),
  293. 'id': video_id,
  294. 'display_id': display_id,
  295. 'channel': 'VRT',
  296. 'formats': formats,
  297. 'duration': float_or_none(video_info.get('duration'), 1000),
  298. 'thumbnail': url_or_none(video_info.get('posterImageUrl')),
  299. 'subtitles': subtitles,
  300. '_old_archive_ids': [make_archive_id('Canvas', video_id)],
  301. }
  302. class KetnetIE(VRTBaseIE):
  303. _VALID_URL = r'https?://(?:www\.)?ketnet\.be/(?P<id>(?:[^/]+/)*[^/?#&]+)'
  304. _TESTS = [{
  305. 'url': 'https://www.ketnet.be/kijken/m/meisjes/6/meisjes-s6a5',
  306. 'info_dict': {
  307. 'id': 'pbs-pub-39f8351c-a0a0-43e6-8394-205d597d6162$vid-5e306921-a9aa-4fa9-9f39-5b82c8f1028e',
  308. 'ext': 'mp4',
  309. 'title': 'Meisjes',
  310. 'episode': 'Reeks 6: Week 5',
  311. 'season': 'Reeks 6',
  312. 'series': 'Meisjes',
  313. 'timestamp': 1685251800,
  314. 'upload_date': '20230528',
  315. },
  316. 'params': {'skip_download': 'm3u8'},
  317. }]
  318. def _real_extract(self, url):
  319. display_id = self._match_id(url)
  320. video = self._download_json(
  321. 'https://senior-bff.ketnet.be/graphql', display_id, query={
  322. 'query': '''{
  323. video(id: "content/ketnet/nl/%s.model.json") {
  324. description
  325. episodeNr
  326. imageUrl
  327. mediaReference
  328. programTitle
  329. publicationDate
  330. seasonTitle
  331. subtitleVideodetail
  332. titleVideodetail
  333. }
  334. }''' % display_id, # noqa: UP031
  335. })['data']['video']
  336. video_id = urllib.parse.unquote(video['mediaReference'])
  337. data = self._call_api(video_id, 'ketnet@PROD', version='v1')
  338. formats, subtitles = self._extract_formats_and_subtitles(data, video_id)
  339. return {
  340. 'id': video_id,
  341. 'formats': formats,
  342. 'subtitles': subtitles,
  343. '_old_archive_ids': [make_archive_id('Canvas', video_id)],
  344. **traverse_obj(video, {
  345. 'title': ('titleVideodetail', {str}),
  346. 'description': ('description', {str}),
  347. 'thumbnail': ('thumbnail', {url_or_none}),
  348. 'timestamp': ('publicationDate', {parse_iso8601}),
  349. 'series': ('programTitle', {str}),
  350. 'season': ('seasonTitle', {str}),
  351. 'episode': ('subtitleVideodetail', {str}),
  352. 'episode_number': ('episodeNr', {int_or_none}),
  353. }),
  354. }
  355. class DagelijkseKostIE(VRTBaseIE):
  356. IE_DESC = 'dagelijksekost.een.be'
  357. _VALID_URL = r'https?://dagelijksekost\.een\.be/gerechten/(?P<id>[^/?#&]+)'
  358. _TESTS = [{
  359. 'url': 'https://dagelijksekost.een.be/gerechten/hachis-parmentier-met-witloof',
  360. 'info_dict': {
  361. 'id': 'md-ast-27a4d1ff-7d7b-425e-b84f-a4d227f592fa',
  362. 'ext': 'mp4',
  363. 'title': 'Hachis parmentier met witloof',
  364. 'description': 'md5:9960478392d87f63567b5b117688cdc5',
  365. 'display_id': 'hachis-parmentier-met-witloof',
  366. },
  367. 'params': {'skip_download': 'm3u8'},
  368. }]
  369. def _real_extract(self, url):
  370. display_id = self._match_id(url)
  371. webpage = self._download_webpage(url, display_id)
  372. video_id = self._html_search_regex(
  373. r'data-url=(["\'])(?P<id>(?:(?!\1).)+)\1', webpage, 'video id', group='id')
  374. data = self._call_api(video_id, 'dako@prod', version='v1')
  375. formats, subtitles = self._extract_formats_and_subtitles(data, video_id)
  376. return {
  377. 'id': video_id,
  378. 'formats': formats,
  379. 'subtitles': subtitles,
  380. 'display_id': display_id,
  381. 'title': strip_or_none(get_element_by_class(
  382. 'dish-metadata__title', webpage) or self._html_search_meta('twitter:title', webpage)),
  383. 'description': clean_html(get_element_by_class(
  384. 'dish-description', webpage)) or self._html_search_meta(
  385. ['description', 'twitter:description', 'og:description'], webpage),
  386. '_old_archive_ids': [make_archive_id('Canvas', video_id)],
  387. }
  388. class Radio1BeIE(VRTBaseIE):
  389. _VALID_URL = r'https?://radio1\.be/(?:lees|luister/select)/(?P<id>[\w/-]+)'
  390. _TESTS = [{
  391. 'url': 'https://radio1.be/luister/select/de-ochtend/komt-n-va-volgend-jaar-op-in-wallonie',
  392. 'info_dict': {
  393. 'id': 'eb6c22e9-544f-44f4-af39-cf8cccd29e22',
  394. 'title': 'Komt N-VA volgend jaar op in Wallonië?',
  395. 'display_id': 'de-ochtend/komt-n-va-volgend-jaar-op-in-wallonie',
  396. 'description': 'md5:b374ea1c9302f38362df9dea1931468e',
  397. 'thumbnail': r're:https?://cds\.vrt\.radio/[^/#\?&]+',
  398. },
  399. 'playlist_mincount': 1,
  400. }, {
  401. 'url': 'https://radio1.be/lees/europese-unie-wil-onmiddellijke-humanitaire-pauze-en-duurzaam-staakt-het-vuren-in-gaza?view=web',
  402. 'info_dict': {
  403. 'id': '5d47f102-dbdb-4fa0-832b-26c1870311f2',
  404. 'title': 'Europese Unie wil "onmiddellijke humanitaire pauze" en "duurzaam staakt-het-vuren" in Gaza',
  405. 'description': 'md5:1aad1fae7d39edeffde5d3e67d276b64',
  406. 'thumbnail': r're:https?://cds\.vrt\.radio/[^/#\?&]+',
  407. 'display_id': 'europese-unie-wil-onmiddellijke-humanitaire-pauze-en-duurzaam-staakt-het-vuren-in-gaza',
  408. },
  409. 'playlist_mincount': 1,
  410. }]
  411. def _extract_video_entries(self, next_js_data, display_id):
  412. video_data = traverse_obj(
  413. next_js_data, ((None, ('paragraphs', ...)), {lambda x: x if x['mediaReference'] else None}))
  414. for data in video_data:
  415. media_reference = data['mediaReference']
  416. formats, subtitles = self._extract_formats_and_subtitles(
  417. self._call_api(media_reference), display_id)
  418. yield {
  419. 'id': media_reference,
  420. 'formats': formats,
  421. 'subtitles': subtitles,
  422. **traverse_obj(data, {
  423. 'title': ('title', {str}),
  424. 'description': ('body', {clean_html}),
  425. }),
  426. }
  427. def _real_extract(self, url):
  428. display_id = self._match_id(url)
  429. webpage = self._download_webpage(url, display_id)
  430. next_js_data = self._search_nextjs_data(webpage, display_id)['props']['pageProps']['item']
  431. return self.playlist_result(
  432. self._extract_video_entries(next_js_data, display_id), **merge_dicts(traverse_obj(
  433. next_js_data, ({
  434. 'id': ('id', {str}),
  435. 'title': ('title', {str}),
  436. 'description': (('description', 'content'), {clean_html}),
  437. }), get_all=False), {
  438. 'display_id': display_id,
  439. 'title': self._html_search_meta(['name', 'og:title', 'twitter:title'], webpage),
  440. 'description': self._html_search_meta(['description', 'og:description', 'twitter:description'], webpage),
  441. 'thumbnail': self._html_search_meta(['og:image', 'twitter:image'], webpage),
  442. }))