nrk.py 29 KB

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