nrk.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875
  1. import itertools
  2. import random
  3. import re
  4. from .common import InfoExtractor
  5. from ..compat import compat_HTTPError, compat_str
  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('%s said: %s' % (self.IE_NAME, 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 'Downloading %s JSON' % item,
  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, compat_HTTPError) and e.cause.code == 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'], compat_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 += '-%s' % 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'], compat_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. 'programs/%s' % 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 += ' - %s' % 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 = r'https?://(?:tv|radio)\.nrk(?:super)?\.no/(?:[^/]+/)*%s' % _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. 'nrk:%s' % 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. r'data-program-id=["\'](%s)' % 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': 'nrk:%s' % 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, compat_str):
  449. continue
  450. entries.append(self.url_result(
  451. 'nrk:%s' % 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. for e in self._extract_entries(entries):
  476. yield e
  477. # Find next URL
  478. next_url_path = try_get(
  479. data,
  480. (lambda x: x['_links']['next']['href'],
  481. lambda x: x['_embedded'][assets_key]['_links']['next']['href']),
  482. compat_str)
  483. if not next_url_path:
  484. break
  485. data = self._call_api(
  486. next_url_path, display_id,
  487. note='Downloading %s JSON page %d' % (assets_key, page_num),
  488. fatal=False)
  489. if not data:
  490. break
  491. class NRKTVSeasonIE(NRKTVSerieBaseIE):
  492. _VALID_URL = r'''(?x)
  493. https?://
  494. (?P<domain>tv|radio)\.nrk\.no/
  495. (?P<serie_kind>serie|pod[ck]ast)/
  496. (?P<serie>[^/]+)/
  497. (?:
  498. (?:sesong/)?(?P<id>\d+)|
  499. sesong/(?P<id_2>[^/?#&]+)
  500. )
  501. '''
  502. _TESTS = [{
  503. 'url': 'https://tv.nrk.no/serie/backstage/sesong/1',
  504. 'info_dict': {
  505. 'id': 'backstage/1',
  506. 'title': 'Sesong 1',
  507. },
  508. 'playlist_mincount': 30,
  509. }, {
  510. # no /sesong/ in path
  511. 'url': 'https://tv.nrk.no/serie/lindmo/2016',
  512. 'info_dict': {
  513. 'id': 'lindmo/2016',
  514. 'title': '2016',
  515. },
  516. 'playlist_mincount': 29,
  517. }, {
  518. # weird nested _embedded in catalog JSON response
  519. 'url': 'https://radio.nrk.no/serie/dickie-dick-dickens/sesong/1',
  520. 'info_dict': {
  521. 'id': 'dickie-dick-dickens/1',
  522. 'title': 'Sesong 1',
  523. },
  524. 'playlist_mincount': 11,
  525. }, {
  526. # 841 entries, multi page
  527. 'url': 'https://radio.nrk.no/serie/dagsnytt/sesong/201509',
  528. 'info_dict': {
  529. 'id': 'dagsnytt/201509',
  530. 'title': 'September 2015',
  531. },
  532. 'playlist_mincount': 841,
  533. }, {
  534. # 180 entries, single page
  535. 'url': 'https://tv.nrk.no/serie/spangas/sesong/1',
  536. 'only_matching': True,
  537. }, {
  538. 'url': 'https://radio.nrk.no/podkast/hele_historien/sesong/diagnose-kverulant',
  539. 'info_dict': {
  540. 'id': 'hele_historien/diagnose-kverulant',
  541. 'title': 'Diagnose kverulant',
  542. },
  543. 'playlist_mincount': 3,
  544. }, {
  545. 'url': 'https://radio.nrk.no/podkast/loerdagsraadet/sesong/202101',
  546. 'only_matching': True,
  547. }]
  548. @classmethod
  549. def suitable(cls, url):
  550. return (False if NRKTVIE.suitable(url) or NRKTVEpisodeIE.suitable(url) or NRKRadioPodkastIE.suitable(url)
  551. else super(NRKTVSeasonIE, cls).suitable(url))
  552. def _real_extract(self, url):
  553. mobj = self._match_valid_url(url)
  554. domain = mobj.group('domain')
  555. serie_kind = mobj.group('serie_kind')
  556. serie = mobj.group('serie')
  557. season_id = mobj.group('id') or mobj.group('id_2')
  558. display_id = '%s/%s' % (serie, season_id)
  559. data = self._call_api(
  560. '%s/catalog/%s/%s/seasons/%s'
  561. % (domain, self._catalog_name(serie_kind), serie, season_id),
  562. display_id, 'season', query={'pageSize': 50})
  563. title = try_get(data, lambda x: x['titles']['title'], compat_str) or display_id
  564. return self.playlist_result(
  565. self._entries(data, display_id),
  566. display_id, title)
  567. class NRKTVSeriesIE(NRKTVSerieBaseIE):
  568. _VALID_URL = r'https?://(?P<domain>(?:tv|radio)\.nrk|(?:tv\.)?nrksuper)\.no/(?P<serie_kind>serie|pod[ck]ast)/(?P<id>[^/]+)'
  569. _TESTS = [{
  570. # new layout, instalments
  571. 'url': 'https://tv.nrk.no/serie/groenn-glede',
  572. 'info_dict': {
  573. 'id': 'groenn-glede',
  574. 'title': 'Grønn glede',
  575. 'description': 'md5:7576e92ae7f65da6993cf90ee29e4608',
  576. },
  577. 'playlist_mincount': 90,
  578. }, {
  579. # new layout, instalments, more entries
  580. 'url': 'https://tv.nrk.no/serie/lindmo',
  581. 'only_matching': True,
  582. }, {
  583. 'url': 'https://tv.nrk.no/serie/blank',
  584. 'info_dict': {
  585. 'id': 'blank',
  586. 'title': 'Blank',
  587. 'description': 'md5:7664b4e7e77dc6810cd3bca367c25b6e',
  588. },
  589. 'playlist_mincount': 30,
  590. }, {
  591. # new layout, seasons
  592. 'url': 'https://tv.nrk.no/serie/backstage',
  593. 'info_dict': {
  594. 'id': 'backstage',
  595. 'title': 'Backstage',
  596. 'description': 'md5:63692ceb96813d9a207e9910483d948b',
  597. },
  598. 'playlist_mincount': 60,
  599. }, {
  600. # old layout
  601. 'url': 'https://tv.nrksuper.no/serie/labyrint',
  602. 'info_dict': {
  603. 'id': 'labyrint',
  604. 'title': 'Labyrint',
  605. 'description': 'I Daidalos sin undersjøiske Labyrint venter spennende oppgaver, skumle robotskapninger og slim.',
  606. },
  607. 'playlist_mincount': 3,
  608. }, {
  609. 'url': 'https://tv.nrk.no/serie/broedrene-dal-og-spektralsteinene',
  610. 'only_matching': True,
  611. }, {
  612. 'url': 'https://tv.nrk.no/serie/saving-the-human-race',
  613. 'only_matching': True,
  614. }, {
  615. 'url': 'https://tv.nrk.no/serie/postmann-pat',
  616. 'only_matching': True,
  617. }, {
  618. 'url': 'https://radio.nrk.no/serie/dickie-dick-dickens',
  619. 'info_dict': {
  620. 'id': 'dickie-dick-dickens',
  621. 'title': 'Dickie Dick Dickens',
  622. 'description': 'md5:19e67411ffe57f7dce08a943d7a0b91f',
  623. },
  624. 'playlist_mincount': 8,
  625. }, {
  626. 'url': 'https://nrksuper.no/serie/labyrint',
  627. 'only_matching': True,
  628. }, {
  629. 'url': 'https://radio.nrk.no/podkast/ulrikkes_univers',
  630. 'info_dict': {
  631. 'id': 'ulrikkes_univers',
  632. },
  633. 'playlist_mincount': 10,
  634. }, {
  635. 'url': 'https://radio.nrk.no/podkast/ulrikkes_univers/nrkno-poddkast-26588-134079-05042018030000',
  636. 'only_matching': True,
  637. }]
  638. @classmethod
  639. def suitable(cls, url):
  640. return (
  641. False if any(ie.suitable(url)
  642. for ie in (NRKTVIE, NRKTVEpisodeIE, NRKRadioPodkastIE, NRKTVSeasonIE))
  643. else super(NRKTVSeriesIE, cls).suitable(url))
  644. def _real_extract(self, url):
  645. site, serie_kind, series_id = self._match_valid_url(url).groups()
  646. is_radio = site == 'radio.nrk'
  647. domain = 'radio' if is_radio else 'tv'
  648. size_prefix = 'p' if is_radio else 'embeddedInstalmentsP'
  649. series = self._call_api(
  650. '%s/catalog/%s/%s'
  651. % (domain, self._catalog_name(serie_kind), series_id),
  652. series_id, 'serie', query={size_prefix + 'ageSize': 50})
  653. titles = try_get(series, [
  654. lambda x: x['titles'],
  655. lambda x: x[x['type']]['titles'],
  656. lambda x: x[x['seriesType']]['titles'],
  657. ]) or {}
  658. entries = []
  659. entries.extend(self._entries(series, series_id))
  660. embedded = series.get('_embedded') or {}
  661. linked_seasons = try_get(series, lambda x: x['_links']['seasons']) or []
  662. embedded_seasons = embedded.get('seasons') or []
  663. if len(linked_seasons) > len(embedded_seasons):
  664. for season in linked_seasons:
  665. season_url = urljoin(url, season.get('href'))
  666. if not season_url:
  667. season_name = season.get('name')
  668. if season_name and isinstance(season_name, compat_str):
  669. season_url = 'https://%s.nrk.no/serie/%s/sesong/%s' % (domain, series_id, season_name)
  670. if season_url:
  671. entries.append(self.url_result(
  672. season_url, ie=NRKTVSeasonIE.ie_key(),
  673. video_title=season.get('title')))
  674. else:
  675. for season in embedded_seasons:
  676. entries.extend(self._entries(season, series_id))
  677. entries.extend(self._entries(
  678. embedded.get('extraMaterial') or {}, series_id))
  679. return self.playlist_result(
  680. entries, series_id, titles.get('title'), titles.get('subtitle'))
  681. class NRKTVDirekteIE(NRKTVIE): # XXX: Do not subclass from concrete IE
  682. IE_DESC = 'NRK TV Direkte and NRK Radio Direkte'
  683. _VALID_URL = r'https?://(?:tv|radio)\.nrk\.no/direkte/(?P<id>[^/?#&]+)'
  684. _TESTS = [{
  685. 'url': 'https://tv.nrk.no/direkte/nrk1',
  686. 'only_matching': True,
  687. }, {
  688. 'url': 'https://radio.nrk.no/direkte/p1_oslo_akershus',
  689. 'only_matching': True,
  690. }]
  691. class NRKRadioPodkastIE(InfoExtractor):
  692. _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})'
  693. _TESTS = [{
  694. 'url': 'https://radio.nrk.no/podkast/ulrikkes_univers/l_96f4f1b0-de54-4e6a-b4f1-b0de54fe6af8',
  695. 'md5': '8d40dab61cea8ab0114e090b029a0565',
  696. 'info_dict': {
  697. 'id': 'MUHH48000314AA',
  698. 'ext': 'mp4',
  699. 'title': '20 spørsmål 23.05.2014',
  700. 'description': 'md5:bdea103bc35494c143c6a9acdd84887a',
  701. 'duration': 1741,
  702. 'series': '20 spørsmål',
  703. 'episode': '23.05.2014',
  704. },
  705. }, {
  706. 'url': 'https://radio.nrk.no/podcast/ulrikkes_univers/l_96f4f1b0-de54-4e6a-b4f1-b0de54fe6af8',
  707. 'only_matching': True,
  708. }, {
  709. 'url': 'https://radio.nrk.no/podkast/ulrikkes_univers/sesong/1/l_96f4f1b0-de54-4e6a-b4f1-b0de54fe6af8',
  710. 'only_matching': True,
  711. }, {
  712. 'url': 'https://radio.nrk.no/podkast/hele_historien/sesong/bortfoert-i-bergen/l_774d1a2c-7aa7-4965-8d1a-2c7aa7d9652c',
  713. 'only_matching': True,
  714. }]
  715. def _real_extract(self, url):
  716. video_id = self._match_id(url)
  717. return self.url_result(
  718. 'nrk:%s' % video_id, ie=NRKIE.ie_key(), video_id=video_id)
  719. class NRKPlaylistBaseIE(InfoExtractor):
  720. def _extract_description(self, webpage):
  721. pass
  722. def _real_extract(self, url):
  723. playlist_id = self._match_id(url)
  724. webpage = self._download_webpage(url, playlist_id)
  725. entries = [
  726. self.url_result('nrk:%s' % video_id, NRKIE.ie_key())
  727. for video_id in re.findall(self._ITEM_RE, webpage)
  728. ]
  729. playlist_title = self._extract_title(webpage)
  730. playlist_description = self._extract_description(webpage)
  731. return self.playlist_result(
  732. entries, playlist_id, playlist_title, playlist_description)
  733. class NRKPlaylistIE(NRKPlaylistBaseIE):
  734. _VALID_URL = r'https?://(?:www\.)?nrk\.no/(?!video|skole)(?:[^/]+/)+(?P<id>[^/]+)'
  735. _ITEM_RE = r'class="[^"]*\brich\b[^"]*"[^>]+data-video-id="([^"]+)"'
  736. _TESTS = [{
  737. 'url': 'http://www.nrk.no/troms/gjenopplev-den-historiske-solformorkelsen-1.12270763',
  738. 'info_dict': {
  739. 'id': 'gjenopplev-den-historiske-solformorkelsen-1.12270763',
  740. 'title': 'Gjenopplev den historiske solformørkelsen',
  741. 'description': 'md5:c2df8ea3bac5654a26fc2834a542feed',
  742. },
  743. 'playlist_count': 2,
  744. }, {
  745. 'url': 'http://www.nrk.no/kultur/bok/rivertonprisen-til-karin-fossum-1.12266449',
  746. 'info_dict': {
  747. 'id': 'rivertonprisen-til-karin-fossum-1.12266449',
  748. 'title': 'Rivertonprisen til Karin Fossum',
  749. 'description': 'Første kvinne på 15 år til å vinne krimlitteraturprisen.',
  750. },
  751. 'playlist_count': 2,
  752. }]
  753. def _extract_title(self, webpage):
  754. return self._og_search_title(webpage, fatal=False)
  755. def _extract_description(self, webpage):
  756. return self._og_search_description(webpage)
  757. class NRKTVEpisodesIE(NRKPlaylistBaseIE):
  758. _VALID_URL = r'https?://tv\.nrk\.no/program/[Ee]pisodes/[^/]+/(?P<id>\d+)'
  759. _ITEM_RE = r'data-episode=["\']%s' % NRKTVIE._EPISODE_RE
  760. _TESTS = [{
  761. 'url': 'https://tv.nrk.no/program/episodes/nytt-paa-nytt/69031',
  762. 'info_dict': {
  763. 'id': '69031',
  764. 'title': 'Nytt på nytt, sesong: 201210',
  765. },
  766. 'playlist_count': 4,
  767. }]
  768. def _extract_title(self, webpage):
  769. return self._html_search_regex(
  770. r'<h1>([^<]+)</h1>', webpage, 'title', fatal=False)
  771. class NRKSkoleIE(InfoExtractor):
  772. IE_DESC = 'NRK Skole'
  773. _VALID_URL = r'https?://(?:www\.)?nrk\.no/skole/?\?.*\bmediaId=(?P<id>\d+)'
  774. _TESTS = [{
  775. 'url': 'https://www.nrk.no/skole/?page=search&q=&mediaId=14099',
  776. 'md5': '18c12c3d071953c3bf8d54ef6b2587b7',
  777. 'info_dict': {
  778. 'id': '6021',
  779. 'ext': 'mp4',
  780. 'title': 'Genetikk og eneggede tvillinger',
  781. 'description': 'md5:3aca25dcf38ec30f0363428d2b265f8d',
  782. 'duration': 399,
  783. },
  784. }, {
  785. 'url': 'https://www.nrk.no/skole/?page=objectives&subject=naturfag&objective=K15114&mediaId=19355',
  786. 'only_matching': True,
  787. }]
  788. def _real_extract(self, url):
  789. video_id = self._match_id(url)
  790. nrk_id = self._download_json(
  791. 'https://nrkno-skole-prod.kube.nrk.no/skole/api/media/%s' % video_id,
  792. video_id)['psId']
  793. return self.url_result('nrk:%s' % nrk_id)