nrk.py 28 KB

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