nrk.py 28 KB

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