nrk.py 30 KB

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