nrk.py 30 KB

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