logo

youtube-dl

[mirror] Download/Watch videos from video hostersgit clone https://hacktivis.me/git/mirror/youtube-dl.git

nrk.py (31822B)


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