nrk.py 31 KB

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