nrk.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871
  1. import itertools
  2. import random
  3. import re
  4. from .common import InfoExtractor
  5. from ..networking.exceptions import HTTPError
  6. from ..utils import (
  7. ExtractorError,
  8. determine_ext,
  9. int_or_none,
  10. parse_duration,
  11. parse_iso8601,
  12. str_or_none,
  13. try_get,
  14. url_or_none,
  15. urljoin,
  16. )
  17. class NRKBaseIE(InfoExtractor):
  18. _GEO_COUNTRIES = ['NO']
  19. _CDN_REPL_REGEX = r'''(?x)://
  20. (?:
  21. nrkod\d{1,2}-httpcache0-47115-cacheod0\.dna\.ip-only\.net/47115-cacheod0|
  22. nrk-od-no\.telenorcdn\.net|
  23. minicdn-od\.nrk\.no/od/nrkhd-osl-rr\.netwerk\.no/no
  24. )/'''
  25. def _extract_nrk_formats(self, asset_url, video_id):
  26. if re.match(r'https?://[^/]+\.akamaihd\.net/i/', asset_url):
  27. return self._extract_akamai_formats(asset_url, video_id)
  28. asset_url = re.sub(r'(?:bw_(?:low|high)=\d+|no_audio_only)&?', '', asset_url)
  29. formats = self._extract_m3u8_formats(
  30. asset_url, video_id, 'mp4', 'm3u8_native', fatal=False)
  31. if not formats and re.search(self._CDN_REPL_REGEX, asset_url):
  32. formats = self._extract_m3u8_formats(
  33. re.sub(self._CDN_REPL_REGEX, '://nrk-od-%02d.akamaized.net/no/' % random.randint(0, 99), asset_url),
  34. video_id, 'mp4', 'm3u8_native', fatal=False)
  35. return formats
  36. def _raise_error(self, data):
  37. MESSAGES = {
  38. 'ProgramRightsAreNotReady': 'Du kan dessverre ikke se eller høre programmet',
  39. 'ProgramRightsHasExpired': 'Programmet har gått ut',
  40. 'NoProgramRights': 'Ikke tilgjengelig',
  41. 'ProgramIsGeoBlocked': 'NRK har ikke rettigheter til å vise dette programmet utenfor Norge',
  42. }
  43. message_type = data.get('messageType', '')
  44. # Can be ProgramIsGeoBlocked or ChannelIsGeoBlocked*
  45. if 'IsGeoBlocked' in message_type or try_get(data, lambda x: x['usageRights']['isGeoBlocked']) is True:
  46. self.raise_geo_restricted(
  47. msg=MESSAGES.get('ProgramIsGeoBlocked'),
  48. countries=self._GEO_COUNTRIES)
  49. message = data.get('endUserMessage') or MESSAGES.get(message_type, message_type)
  50. raise ExtractorError(f'{self.IE_NAME} said: {message}', expected=True)
  51. def _call_api(self, path, video_id, item=None, note=None, fatal=True, query=None):
  52. return self._download_json(
  53. urljoin('https://psapi.nrk.no/', path),
  54. video_id, note or f'Downloading {item} JSON',
  55. fatal=fatal, query=query)
  56. class NRKIE(NRKBaseIE):
  57. _VALID_URL = r'''(?x)
  58. (?:
  59. nrk:|
  60. https?://
  61. (?:
  62. (?:www\.)?nrk\.no/video/(?:PS\*|[^_]+_)|
  63. v8[-.]psapi\.nrk\.no/mediaelement/
  64. )
  65. )
  66. (?P<id>[^?\#&]+)
  67. '''
  68. _TESTS = [{
  69. # video
  70. 'url': 'http://www.nrk.no/video/PS*150533',
  71. 'md5': 'f46be075326e23ad0e524edfcb06aeb6',
  72. 'info_dict': {
  73. 'id': '150533',
  74. 'ext': 'mp4',
  75. 'title': 'Dompap og andre fugler i Piip-Show',
  76. 'description': 'md5:d9261ba34c43b61c812cb6b0269a5c8f',
  77. 'duration': 262,
  78. },
  79. }, {
  80. # audio
  81. 'url': 'http://www.nrk.no/video/PS*154915',
  82. # MD5 is unstable
  83. 'info_dict': {
  84. 'id': '154915',
  85. 'ext': 'mp4',
  86. 'title': 'Slik høres internett ut når du er blind',
  87. 'description': 'md5:a621f5cc1bd75c8d5104cb048c6b8568',
  88. 'duration': 20,
  89. },
  90. }, {
  91. 'url': 'nrk:ecc1b952-96dc-4a98-81b9-5296dc7a98d9',
  92. 'only_matching': True,
  93. }, {
  94. 'url': 'nrk:clip/7707d5a3-ebe7-434a-87d5-a3ebe7a34a70',
  95. 'only_matching': True,
  96. }, {
  97. 'url': 'https://v8-psapi.nrk.no/mediaelement/ecc1b952-96dc-4a98-81b9-5296dc7a98d9',
  98. 'only_matching': True,
  99. }, {
  100. 'url': 'https://www.nrk.no/video/dompap-og-andre-fugler-i-piip-show_150533',
  101. 'only_matching': True,
  102. }, {
  103. 'url': 'https://www.nrk.no/video/humor/kommentatorboksen-reiser-til-sjos_d1fda11f-a4ad-437a-a374-0398bc84e999',
  104. 'only_matching': True,
  105. }, {
  106. # podcast
  107. 'url': 'nrk:l_96f4f1b0-de54-4e6a-b4f1-b0de54fe6af8',
  108. 'only_matching': True,
  109. }, {
  110. 'url': 'nrk:podcast/l_96f4f1b0-de54-4e6a-b4f1-b0de54fe6af8',
  111. 'only_matching': True,
  112. }, {
  113. # clip
  114. 'url': 'nrk:150533',
  115. 'only_matching': True,
  116. }, {
  117. 'url': 'nrk:clip/150533',
  118. 'only_matching': True,
  119. }, {
  120. # program
  121. 'url': 'nrk:MDDP12000117',
  122. 'only_matching': True,
  123. }, {
  124. 'url': 'nrk:program/ENRK10100318',
  125. 'only_matching': True,
  126. }, {
  127. # direkte
  128. 'url': 'nrk:nrk1',
  129. 'only_matching': True,
  130. }, {
  131. 'url': 'nrk:channel/nrk1',
  132. 'only_matching': True,
  133. }]
  134. def _real_extract(self, url):
  135. video_id = self._match_id(url).split('/')[-1]
  136. def call_playback_api(item, query=None):
  137. try:
  138. return self._call_api(f'playback/{item}/program/{video_id}', video_id, item, query=query)
  139. except ExtractorError as e:
  140. if isinstance(e.cause, HTTPError) and e.cause.status == 400:
  141. return self._call_api(f'playback/{item}/{video_id}', video_id, item, query=query)
  142. raise
  143. # known values for preferredCdn: akamai, iponly, minicdn and telenor
  144. manifest = call_playback_api('manifest', {'preferredCdn': 'akamai'})
  145. video_id = try_get(manifest, lambda x: x['id'], str) or video_id
  146. if manifest.get('playability') == 'nonPlayable':
  147. self._raise_error(manifest['nonPlayable'])
  148. playable = manifest['playable']
  149. formats = []
  150. for asset in playable['assets']:
  151. if not isinstance(asset, dict):
  152. continue
  153. if asset.get('encrypted'):
  154. continue
  155. format_url = url_or_none(asset.get('url'))
  156. if not format_url:
  157. continue
  158. asset_format = (asset.get('format') or '').lower()
  159. if asset_format == 'hls' or determine_ext(format_url) == 'm3u8':
  160. formats.extend(self._extract_nrk_formats(format_url, video_id))
  161. elif asset_format == 'mp3':
  162. formats.append({
  163. 'url': format_url,
  164. 'format_id': asset_format,
  165. 'vcodec': 'none',
  166. })
  167. data = call_playback_api('metadata')
  168. preplay = data['preplay']
  169. titles = preplay['titles']
  170. title = titles['title']
  171. alt_title = titles.get('subtitle')
  172. description = try_get(preplay, lambda x: x['description'].replace('\r', '\n'))
  173. duration = parse_duration(playable.get('duration')) or parse_duration(data.get('duration'))
  174. thumbnails = []
  175. for image in try_get(
  176. preplay, lambda x: x['poster']['images'], list) or []:
  177. if not isinstance(image, dict):
  178. continue
  179. image_url = url_or_none(image.get('url'))
  180. if not image_url:
  181. continue
  182. thumbnails.append({
  183. 'url': image_url,
  184. 'width': int_or_none(image.get('pixelWidth')),
  185. 'height': int_or_none(image.get('pixelHeight')),
  186. })
  187. subtitles = {}
  188. for sub in try_get(playable, lambda x: x['subtitles'], list) or []:
  189. if not isinstance(sub, dict):
  190. continue
  191. sub_url = url_or_none(sub.get('webVtt'))
  192. if not sub_url:
  193. continue
  194. sub_key = str_or_none(sub.get('language')) or 'nb'
  195. sub_type = str_or_none(sub.get('type'))
  196. if sub_type:
  197. sub_key += f'-{sub_type}'
  198. subtitles.setdefault(sub_key, []).append({
  199. 'url': sub_url,
  200. })
  201. legal_age = try_get(
  202. data, lambda x: x['legalAge']['body']['rating']['code'], str)
  203. # https://en.wikipedia.org/wiki/Norwegian_Media_Authority
  204. age_limit = None
  205. if legal_age:
  206. if legal_age == 'A':
  207. age_limit = 0
  208. elif legal_age.isdigit():
  209. age_limit = int_or_none(legal_age)
  210. is_series = try_get(data, lambda x: x['_links']['series']['name']) == 'series'
  211. info = {
  212. 'id': video_id,
  213. 'title': title,
  214. 'alt_title': alt_title,
  215. 'description': description,
  216. 'duration': duration,
  217. 'thumbnails': thumbnails,
  218. 'age_limit': age_limit,
  219. 'formats': formats,
  220. 'subtitles': subtitles,
  221. 'timestamp': parse_iso8601(try_get(manifest, lambda x: x['availability']['onDemand']['from'], str)),
  222. }
  223. if is_series:
  224. series = season_id = season_number = episode = episode_number = None
  225. programs = self._call_api(
  226. f'programs/{video_id}', video_id, 'programs', fatal=False)
  227. if programs and isinstance(programs, dict):
  228. series = str_or_none(programs.get('seriesTitle'))
  229. season_id = str_or_none(programs.get('seasonId'))
  230. season_number = int_or_none(programs.get('seasonNumber'))
  231. episode = str_or_none(programs.get('episodeTitle'))
  232. episode_number = int_or_none(programs.get('episodeNumber'))
  233. if not series:
  234. series = title
  235. if alt_title:
  236. title += f' - {alt_title}'
  237. if not season_number:
  238. season_number = int_or_none(self._search_regex(
  239. r'Sesong\s+(\d+)', description or '', 'season number',
  240. default=None))
  241. if not episode:
  242. episode = alt_title if is_series else None
  243. if not episode_number:
  244. episode_number = int_or_none(self._search_regex(
  245. r'^(\d+)\.', episode or '', 'episode number',
  246. default=None))
  247. if not episode_number:
  248. episode_number = int_or_none(self._search_regex(
  249. r'\((\d+)\s*:\s*\d+\)', description or '',
  250. 'episode number', default=None))
  251. info.update({
  252. 'title': title,
  253. 'series': series,
  254. 'season_id': season_id,
  255. 'season_number': season_number,
  256. 'episode': episode,
  257. 'episode_number': episode_number,
  258. })
  259. return info
  260. class NRKTVIE(InfoExtractor):
  261. IE_DESC = 'NRK TV and NRK Radio'
  262. _EPISODE_RE = r'(?P<id>[a-zA-Z]{4}\d{8})'
  263. _VALID_URL = rf'https?://(?:tv|radio)\.nrk(?:super)?\.no/(?:[^/]+/)*{_EPISODE_RE}'
  264. _TESTS = [{
  265. 'url': 'https://tv.nrk.no/program/MDDP12000117',
  266. 'md5': 'c4a5960f1b00b40d47db65c1064e0ab1',
  267. 'info_dict': {
  268. 'id': 'MDDP12000117',
  269. 'ext': 'mp4',
  270. 'title': 'Alarm Trolltunga',
  271. 'description': 'md5:46923a6e6510eefcce23d5ef2a58f2ce',
  272. 'duration': 2223.44,
  273. 'age_limit': 6,
  274. 'subtitles': {
  275. 'nb-nor': [{
  276. 'ext': 'vtt',
  277. }],
  278. 'nb-ttv': [{
  279. 'ext': 'vtt',
  280. }],
  281. },
  282. },
  283. }, {
  284. 'url': 'https://tv.nrk.no/serie/20-spoersmaal-tv/MUHH48000314/23-05-2014',
  285. 'md5': '8d40dab61cea8ab0114e090b029a0565',
  286. 'info_dict': {
  287. 'id': 'MUHH48000314',
  288. 'ext': 'mp4',
  289. 'title': '20 spørsmål - 23. mai 2014',
  290. 'alt_title': '23. mai 2014',
  291. 'description': 'md5:bdea103bc35494c143c6a9acdd84887a',
  292. 'duration': 1741,
  293. 'series': '20 spørsmål',
  294. 'episode': '23. mai 2014',
  295. 'age_limit': 0,
  296. },
  297. }, {
  298. 'url': 'https://tv.nrk.no/program/mdfp15000514',
  299. 'info_dict': {
  300. 'id': 'MDFP15000514',
  301. 'ext': 'mp4',
  302. 'title': 'Kunnskapskanalen - Grunnlovsjubiléet - Stor ståhei for ingenting',
  303. 'description': 'md5:89290c5ccde1b3a24bb8050ab67fe1db',
  304. 'duration': 4605.08,
  305. 'series': 'Kunnskapskanalen',
  306. 'episode': 'Grunnlovsjubiléet - Stor ståhei for ingenting',
  307. 'age_limit': 0,
  308. },
  309. 'params': {
  310. 'skip_download': True,
  311. },
  312. }, {
  313. # single playlist video
  314. 'url': 'https://tv.nrk.no/serie/tour-de-ski/MSPO40010515/06-01-2015#del=2',
  315. 'info_dict': {
  316. 'id': 'MSPO40010515',
  317. 'ext': 'mp4',
  318. 'title': 'Sprint fri teknikk, kvinner og menn 06.01.2015',
  319. 'description': 'md5:c03aba1e917561eface5214020551b7a',
  320. 'age_limit': 0,
  321. },
  322. 'params': {
  323. 'skip_download': True,
  324. },
  325. 'expected_warnings': ['Failed to download m3u8 information'],
  326. 'skip': 'particular part is not supported currently',
  327. }, {
  328. 'url': 'https://tv.nrk.no/serie/tour-de-ski/MSPO40010515/06-01-2015',
  329. 'info_dict': {
  330. 'id': 'MSPO40010515',
  331. 'ext': 'mp4',
  332. 'title': 'Sprint fri teknikk, kvinner og menn 06.01.2015',
  333. 'description': 'md5:c03aba1e917561eface5214020551b7a',
  334. 'age_limit': 0,
  335. },
  336. 'expected_warnings': ['Failed to download m3u8 information'],
  337. 'skip': 'Ikke tilgjengelig utenfor Norge',
  338. }, {
  339. 'url': 'https://tv.nrk.no/serie/anno/KMTE50001317/sesong-3/episode-13',
  340. 'info_dict': {
  341. 'id': 'KMTE50001317',
  342. 'ext': 'mp4',
  343. 'title': 'Anno - 13. episode',
  344. 'description': 'md5:11d9613661a8dbe6f9bef54e3a4cbbfa',
  345. 'duration': 2340,
  346. 'series': 'Anno',
  347. 'episode': '13. episode',
  348. 'season_number': 3,
  349. 'episode_number': 13,
  350. 'age_limit': 0,
  351. },
  352. 'params': {
  353. 'skip_download': True,
  354. },
  355. }, {
  356. 'url': 'https://tv.nrk.no/serie/nytt-paa-nytt/MUHH46000317/27-01-2017',
  357. 'info_dict': {
  358. 'id': 'MUHH46000317',
  359. 'ext': 'mp4',
  360. 'title': 'Nytt på Nytt 27.01.2017',
  361. 'description': 'md5:5358d6388fba0ea6f0b6d11c48b9eb4b',
  362. 'duration': 1796,
  363. 'series': 'Nytt på nytt',
  364. 'episode': '27.01.2017',
  365. 'age_limit': 0,
  366. },
  367. 'params': {
  368. 'skip_download': True,
  369. },
  370. 'skip': 'ProgramRightsHasExpired',
  371. }, {
  372. 'url': 'https://radio.nrk.no/serie/dagsnytt/NPUB21019315/12-07-2015#',
  373. 'only_matching': True,
  374. }, {
  375. 'url': 'https://tv.nrk.no/serie/lindmo/2018/MUHU11006318/avspiller',
  376. 'only_matching': True,
  377. }, {
  378. 'url': 'https://radio.nrk.no/serie/dagsnytt/sesong/201507/NPUB21019315',
  379. 'only_matching': True,
  380. }]
  381. def _real_extract(self, url):
  382. video_id = self._match_id(url)
  383. return self.url_result(
  384. f'nrk:{video_id}', ie=NRKIE.ie_key(), video_id=video_id)
  385. class NRKTVEpisodeIE(InfoExtractor):
  386. _VALID_URL = r'https?://tv\.nrk\.no/serie/(?P<id>[^/]+/sesong/(?P<season_number>\d+)/episode/(?P<episode_number>\d+))'
  387. _TESTS = [{
  388. 'url': 'https://tv.nrk.no/serie/hellums-kro/sesong/1/episode/2',
  389. 'info_dict': {
  390. 'id': 'MUHH36005220',
  391. 'ext': 'mp4',
  392. 'title': 'Hellums kro - 2. Kro, krig og kjærlighet',
  393. 'description': 'md5:ad92ddffc04cea8ce14b415deef81787',
  394. 'duration': 1563.92,
  395. 'series': 'Hellums kro',
  396. 'season_number': 1,
  397. 'episode_number': 2,
  398. 'episode': '2. Kro, krig og kjærlighet',
  399. 'age_limit': 6,
  400. },
  401. 'params': {
  402. 'skip_download': True,
  403. },
  404. }, {
  405. 'url': 'https://tv.nrk.no/serie/backstage/sesong/1/episode/8',
  406. 'info_dict': {
  407. 'id': 'MSUI14000816',
  408. 'ext': 'mp4',
  409. 'title': 'Backstage - 8. episode',
  410. 'description': 'md5:de6ca5d5a2d56849e4021f2bf2850df4',
  411. 'duration': 1320,
  412. 'series': 'Backstage',
  413. 'season_number': 1,
  414. 'episode_number': 8,
  415. 'episode': '8. episode',
  416. 'age_limit': 0,
  417. },
  418. 'params': {
  419. 'skip_download': True,
  420. },
  421. 'skip': 'ProgramRightsHasExpired',
  422. }]
  423. def _real_extract(self, url):
  424. display_id, season_number, episode_number = self._match_valid_url(url).groups()
  425. webpage = self._download_webpage(url, display_id)
  426. info = self._search_json_ld(webpage, display_id, default={})
  427. nrk_id = info.get('@id') or self._html_search_meta(
  428. 'nrk:program-id', webpage, default=None) or self._search_regex(
  429. rf'data-program-id=["\']({NRKTVIE._EPISODE_RE})', webpage,
  430. 'nrk id')
  431. assert re.match(NRKTVIE._EPISODE_RE, nrk_id)
  432. info.update({
  433. '_type': 'url',
  434. 'id': nrk_id,
  435. 'url': f'nrk:{nrk_id}',
  436. 'ie_key': NRKIE.ie_key(),
  437. 'season_number': int(season_number),
  438. 'episode_number': int(episode_number),
  439. })
  440. return info
  441. class NRKTVSerieBaseIE(NRKBaseIE):
  442. def _extract_entries(self, entry_list):
  443. if not isinstance(entry_list, list):
  444. return []
  445. entries = []
  446. for episode in entry_list:
  447. nrk_id = episode.get('prfId') or episode.get('episodeId')
  448. if not nrk_id or not isinstance(nrk_id, str):
  449. continue
  450. entries.append(self.url_result(
  451. f'nrk:{nrk_id}', ie=NRKIE.ie_key(), video_id=nrk_id))
  452. return entries
  453. _ASSETS_KEYS = ('episodes', 'instalments')
  454. def _extract_assets_key(self, embedded):
  455. for asset_key in self._ASSETS_KEYS:
  456. if embedded.get(asset_key):
  457. return asset_key
  458. @staticmethod
  459. def _catalog_name(serie_kind):
  460. return 'podcast' if serie_kind in ('podcast', 'podkast') else 'series'
  461. def _entries(self, data, display_id):
  462. for page_num in itertools.count(1):
  463. embedded = data.get('_embedded') or data
  464. if not isinstance(embedded, dict):
  465. break
  466. assets_key = self._extract_assets_key(embedded)
  467. if not assets_key:
  468. break
  469. # Extract entries
  470. entries = try_get(
  471. embedded,
  472. (lambda x: x[assets_key]['_embedded'][assets_key],
  473. lambda x: x[assets_key]),
  474. list)
  475. yield from self._extract_entries(entries)
  476. # Find next URL
  477. next_url_path = try_get(
  478. data,
  479. (lambda x: x['_links']['next']['href'],
  480. lambda x: x['_embedded'][assets_key]['_links']['next']['href']),
  481. str)
  482. if not next_url_path:
  483. break
  484. data = self._call_api(
  485. next_url_path, display_id,
  486. note=f'Downloading {assets_key} JSON page {page_num}',
  487. fatal=False)
  488. if not data:
  489. break
  490. class NRKTVSeasonIE(NRKTVSerieBaseIE):
  491. _VALID_URL = r'''(?x)
  492. https?://
  493. (?P<domain>tv|radio)\.nrk\.no/
  494. (?P<serie_kind>serie|pod[ck]ast)/
  495. (?P<serie>[^/]+)/
  496. (?:
  497. (?:sesong/)?(?P<id>\d+)|
  498. sesong/(?P<id_2>[^/?#&]+)
  499. )
  500. '''
  501. _TESTS = [{
  502. 'url': 'https://tv.nrk.no/serie/backstage/sesong/1',
  503. 'info_dict': {
  504. 'id': 'backstage/1',
  505. 'title': 'Sesong 1',
  506. },
  507. 'playlist_mincount': 30,
  508. }, {
  509. # no /sesong/ in path
  510. 'url': 'https://tv.nrk.no/serie/lindmo/2016',
  511. 'info_dict': {
  512. 'id': 'lindmo/2016',
  513. 'title': '2016',
  514. },
  515. 'playlist_mincount': 29,
  516. }, {
  517. # weird nested _embedded in catalog JSON response
  518. 'url': 'https://radio.nrk.no/serie/dickie-dick-dickens/sesong/1',
  519. 'info_dict': {
  520. 'id': 'dickie-dick-dickens/1',
  521. 'title': 'Sesong 1',
  522. },
  523. 'playlist_mincount': 11,
  524. }, {
  525. # 841 entries, multi page
  526. 'url': 'https://radio.nrk.no/serie/dagsnytt/sesong/201509',
  527. 'info_dict': {
  528. 'id': 'dagsnytt/201509',
  529. 'title': 'September 2015',
  530. },
  531. 'playlist_mincount': 841,
  532. }, {
  533. # 180 entries, single page
  534. 'url': 'https://tv.nrk.no/serie/spangas/sesong/1',
  535. 'only_matching': True,
  536. }, {
  537. 'url': 'https://radio.nrk.no/podkast/hele_historien/sesong/diagnose-kverulant',
  538. 'info_dict': {
  539. 'id': 'hele_historien/diagnose-kverulant',
  540. 'title': 'Diagnose kverulant',
  541. },
  542. 'playlist_mincount': 3,
  543. }, {
  544. 'url': 'https://radio.nrk.no/podkast/loerdagsraadet/sesong/202101',
  545. 'only_matching': True,
  546. }]
  547. @classmethod
  548. def suitable(cls, url):
  549. return (False if NRKTVIE.suitable(url) or NRKTVEpisodeIE.suitable(url) or NRKRadioPodkastIE.suitable(url)
  550. else super().suitable(url))
  551. def _real_extract(self, url):
  552. mobj = self._match_valid_url(url)
  553. domain = mobj.group('domain')
  554. serie_kind = mobj.group('serie_kind')
  555. serie = mobj.group('serie')
  556. season_id = mobj.group('id') or mobj.group('id_2')
  557. display_id = f'{serie}/{season_id}'
  558. data = self._call_api(
  559. f'{domain}/catalog/{self._catalog_name(serie_kind)}/{serie}/seasons/{season_id}',
  560. display_id, 'season', query={'pageSize': 50})
  561. title = try_get(data, lambda x: x['titles']['title'], str) or display_id
  562. return self.playlist_result(
  563. self._entries(data, display_id),
  564. display_id, title)
  565. class NRKTVSeriesIE(NRKTVSerieBaseIE):
  566. _VALID_URL = r'https?://(?P<domain>(?:tv|radio)\.nrk|(?:tv\.)?nrksuper)\.no/(?P<serie_kind>serie|pod[ck]ast)/(?P<id>[^/]+)'
  567. _TESTS = [{
  568. # new layout, instalments
  569. 'url': 'https://tv.nrk.no/serie/groenn-glede',
  570. 'info_dict': {
  571. 'id': 'groenn-glede',
  572. 'title': 'Grønn glede',
  573. 'description': 'md5:7576e92ae7f65da6993cf90ee29e4608',
  574. },
  575. 'playlist_mincount': 90,
  576. }, {
  577. # new layout, instalments, more entries
  578. 'url': 'https://tv.nrk.no/serie/lindmo',
  579. 'only_matching': True,
  580. }, {
  581. 'url': 'https://tv.nrk.no/serie/blank',
  582. 'info_dict': {
  583. 'id': 'blank',
  584. 'title': 'Blank',
  585. 'description': 'md5:7664b4e7e77dc6810cd3bca367c25b6e',
  586. },
  587. 'playlist_mincount': 30,
  588. }, {
  589. # new layout, seasons
  590. 'url': 'https://tv.nrk.no/serie/backstage',
  591. 'info_dict': {
  592. 'id': 'backstage',
  593. 'title': 'Backstage',
  594. 'description': 'md5:63692ceb96813d9a207e9910483d948b',
  595. },
  596. 'playlist_mincount': 60,
  597. }, {
  598. # old layout
  599. 'url': 'https://tv.nrksuper.no/serie/labyrint',
  600. 'info_dict': {
  601. 'id': 'labyrint',
  602. 'title': 'Labyrint',
  603. 'description': 'I Daidalos sin undersjøiske Labyrint venter spennende oppgaver, skumle robotskapninger og slim.',
  604. },
  605. 'playlist_mincount': 3,
  606. }, {
  607. 'url': 'https://tv.nrk.no/serie/broedrene-dal-og-spektralsteinene',
  608. 'only_matching': True,
  609. }, {
  610. 'url': 'https://tv.nrk.no/serie/saving-the-human-race',
  611. 'only_matching': True,
  612. }, {
  613. 'url': 'https://tv.nrk.no/serie/postmann-pat',
  614. 'only_matching': True,
  615. }, {
  616. 'url': 'https://radio.nrk.no/serie/dickie-dick-dickens',
  617. 'info_dict': {
  618. 'id': 'dickie-dick-dickens',
  619. 'title': 'Dickie Dick Dickens',
  620. 'description': 'md5:19e67411ffe57f7dce08a943d7a0b91f',
  621. },
  622. 'playlist_mincount': 8,
  623. }, {
  624. 'url': 'https://nrksuper.no/serie/labyrint',
  625. 'only_matching': True,
  626. }, {
  627. 'url': 'https://radio.nrk.no/podkast/ulrikkes_univers',
  628. 'info_dict': {
  629. 'id': 'ulrikkes_univers',
  630. },
  631. 'playlist_mincount': 10,
  632. }, {
  633. 'url': 'https://radio.nrk.no/podkast/ulrikkes_univers/nrkno-poddkast-26588-134079-05042018030000',
  634. 'only_matching': True,
  635. }]
  636. @classmethod
  637. def suitable(cls, url):
  638. return (
  639. False if any(ie.suitable(url)
  640. for ie in (NRKTVIE, NRKTVEpisodeIE, NRKRadioPodkastIE, NRKTVSeasonIE))
  641. else super().suitable(url))
  642. def _real_extract(self, url):
  643. site, serie_kind, series_id = self._match_valid_url(url).groups()
  644. is_radio = site == 'radio.nrk'
  645. domain = 'radio' if is_radio else 'tv'
  646. size_prefix = 'p' if is_radio else 'embeddedInstalmentsP'
  647. series = self._call_api(
  648. f'{domain}/catalog/{self._catalog_name(serie_kind)}/{series_id}',
  649. series_id, 'serie', query={size_prefix + 'ageSize': 50})
  650. titles = try_get(series, [
  651. lambda x: x['titles'],
  652. lambda x: x[x['type']]['titles'],
  653. lambda x: x[x['seriesType']]['titles'],
  654. ]) or {}
  655. entries = []
  656. entries.extend(self._entries(series, series_id))
  657. embedded = series.get('_embedded') or {}
  658. linked_seasons = try_get(series, lambda x: x['_links']['seasons']) or []
  659. embedded_seasons = embedded.get('seasons') or []
  660. if len(linked_seasons) > len(embedded_seasons):
  661. for season in linked_seasons:
  662. season_url = urljoin(url, season.get('href'))
  663. if not season_url:
  664. season_name = season.get('name')
  665. if season_name and isinstance(season_name, str):
  666. season_url = f'https://{domain}.nrk.no/serie/{series_id}/sesong/{season_name}'
  667. if season_url:
  668. entries.append(self.url_result(
  669. season_url, ie=NRKTVSeasonIE.ie_key(),
  670. video_title=season.get('title')))
  671. else:
  672. for season in embedded_seasons:
  673. entries.extend(self._entries(season, series_id))
  674. entries.extend(self._entries(
  675. embedded.get('extraMaterial') or {}, series_id))
  676. return self.playlist_result(
  677. entries, series_id, titles.get('title'), titles.get('subtitle'))
  678. class NRKTVDirekteIE(NRKTVIE): # XXX: Do not subclass from concrete IE
  679. IE_DESC = 'NRK TV Direkte and NRK Radio Direkte'
  680. _VALID_URL = r'https?://(?:tv|radio)\.nrk\.no/direkte/(?P<id>[^/?#&]+)'
  681. _TESTS = [{
  682. 'url': 'https://tv.nrk.no/direkte/nrk1',
  683. 'only_matching': True,
  684. }, {
  685. 'url': 'https://radio.nrk.no/direkte/p1_oslo_akershus',
  686. 'only_matching': True,
  687. }]
  688. class NRKRadioPodkastIE(InfoExtractor):
  689. _VALID_URL = r'https?://radio\.nrk\.no/pod[ck]ast/(?:[^/]+/)+(?P<id>l_[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12})'
  690. _TESTS = [{
  691. 'url': 'https://radio.nrk.no/podkast/ulrikkes_univers/l_96f4f1b0-de54-4e6a-b4f1-b0de54fe6af8',
  692. 'md5': '8d40dab61cea8ab0114e090b029a0565',
  693. 'info_dict': {
  694. 'id': 'MUHH48000314AA',
  695. 'ext': 'mp4',
  696. 'title': '20 spørsmål 23.05.2014',
  697. 'description': 'md5:bdea103bc35494c143c6a9acdd84887a',
  698. 'duration': 1741,
  699. 'series': '20 spørsmål',
  700. 'episode': '23.05.2014',
  701. },
  702. }, {
  703. 'url': 'https://radio.nrk.no/podcast/ulrikkes_univers/l_96f4f1b0-de54-4e6a-b4f1-b0de54fe6af8',
  704. 'only_matching': True,
  705. }, {
  706. 'url': 'https://radio.nrk.no/podkast/ulrikkes_univers/sesong/1/l_96f4f1b0-de54-4e6a-b4f1-b0de54fe6af8',
  707. 'only_matching': True,
  708. }, {
  709. 'url': 'https://radio.nrk.no/podkast/hele_historien/sesong/bortfoert-i-bergen/l_774d1a2c-7aa7-4965-8d1a-2c7aa7d9652c',
  710. 'only_matching': True,
  711. }]
  712. def _real_extract(self, url):
  713. video_id = self._match_id(url)
  714. return self.url_result(
  715. f'nrk:{video_id}', ie=NRKIE.ie_key(), video_id=video_id)
  716. class NRKPlaylistBaseIE(InfoExtractor):
  717. def _extract_description(self, webpage):
  718. pass
  719. def _real_extract(self, url):
  720. playlist_id = self._match_id(url)
  721. webpage = self._download_webpage(url, playlist_id)
  722. entries = [
  723. self.url_result(f'nrk:{video_id}', NRKIE.ie_key())
  724. for video_id in re.findall(self._ITEM_RE, webpage)
  725. ]
  726. playlist_title = self._extract_title(webpage)
  727. playlist_description = self._extract_description(webpage)
  728. return self.playlist_result(
  729. entries, playlist_id, playlist_title, playlist_description)
  730. class NRKPlaylistIE(NRKPlaylistBaseIE):
  731. _VALID_URL = r'https?://(?:www\.)?nrk\.no/(?!video|skole)(?:[^/]+/)+(?P<id>[^/]+)'
  732. _ITEM_RE = r'class="[^"]*\brich\b[^"]*"[^>]+data-video-id="([^"]+)"'
  733. _TESTS = [{
  734. 'url': 'http://www.nrk.no/troms/gjenopplev-den-historiske-solformorkelsen-1.12270763',
  735. 'info_dict': {
  736. 'id': 'gjenopplev-den-historiske-solformorkelsen-1.12270763',
  737. 'title': 'Gjenopplev den historiske solformørkelsen',
  738. 'description': 'md5:c2df8ea3bac5654a26fc2834a542feed',
  739. },
  740. 'playlist_count': 2,
  741. }, {
  742. 'url': 'http://www.nrk.no/kultur/bok/rivertonprisen-til-karin-fossum-1.12266449',
  743. 'info_dict': {
  744. 'id': 'rivertonprisen-til-karin-fossum-1.12266449',
  745. 'title': 'Rivertonprisen til Karin Fossum',
  746. 'description': 'Første kvinne på 15 år til å vinne krimlitteraturprisen.',
  747. },
  748. 'playlist_count': 2,
  749. }]
  750. def _extract_title(self, webpage):
  751. return self._og_search_title(webpage, fatal=False)
  752. def _extract_description(self, webpage):
  753. return self._og_search_description(webpage)
  754. class NRKTVEpisodesIE(NRKPlaylistBaseIE):
  755. _VALID_URL = r'https?://tv\.nrk\.no/program/[Ee]pisodes/[^/]+/(?P<id>\d+)'
  756. _ITEM_RE = rf'data-episode=["\']{NRKTVIE._EPISODE_RE}'
  757. _TESTS = [{
  758. 'url': 'https://tv.nrk.no/program/episodes/nytt-paa-nytt/69031',
  759. 'info_dict': {
  760. 'id': '69031',
  761. 'title': 'Nytt på nytt, sesong: 201210',
  762. },
  763. 'playlist_count': 4,
  764. }]
  765. def _extract_title(self, webpage):
  766. return self._html_search_regex(
  767. r'<h1>([^<]+)</h1>', webpage, 'title', fatal=False)
  768. class NRKSkoleIE(InfoExtractor):
  769. IE_DESC = 'NRK Skole'
  770. _VALID_URL = r'https?://(?:www\.)?nrk\.no/skole/?\?.*\bmediaId=(?P<id>\d+)'
  771. _TESTS = [{
  772. 'url': 'https://www.nrk.no/skole/?page=search&q=&mediaId=14099',
  773. 'md5': '18c12c3d071953c3bf8d54ef6b2587b7',
  774. 'info_dict': {
  775. 'id': '6021',
  776. 'ext': 'mp4',
  777. 'title': 'Genetikk og eneggede tvillinger',
  778. 'description': 'md5:3aca25dcf38ec30f0363428d2b265f8d',
  779. 'duration': 399,
  780. },
  781. }, {
  782. 'url': 'https://www.nrk.no/skole/?page=objectives&subject=naturfag&objective=K15114&mediaId=19355',
  783. 'only_matching': True,
  784. }]
  785. def _real_extract(self, url):
  786. video_id = self._match_id(url)
  787. nrk_id = self._download_json(
  788. f'https://nrkno-skole-prod.kube.nrk.no/skole/api/media/{video_id}',
  789. video_id)['psId']
  790. return self.url_result(f'nrk:{nrk_id}')