nrk.py 31 KB

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