nrk.py 32 KB

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