nrk.py 32 KB

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