nrk.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531
  1. # coding: utf-8
  2. from __future__ import unicode_literals
  3. import re
  4. from .common import InfoExtractor
  5. from ..compat import compat_urllib_parse_unquote
  6. from ..utils import (
  7. ExtractorError,
  8. int_or_none,
  9. parse_age_limit,
  10. parse_duration,
  11. )
  12. class NRKBaseIE(InfoExtractor):
  13. _GEO_COUNTRIES = ['NO']
  14. _api_host = None
  15. def _real_extract(self, url):
  16. video_id = self._match_id(url)
  17. api_hosts = (self._api_host, ) if self._api_host else self._API_HOSTS
  18. for api_host in api_hosts:
  19. data = self._download_json(
  20. 'http://%s/mediaelement/%s' % (api_host, video_id),
  21. video_id, 'Downloading mediaelement JSON',
  22. fatal=api_host == api_hosts[-1])
  23. if not data:
  24. continue
  25. self._api_host = api_host
  26. break
  27. title = data.get('fullTitle') or data.get('mainTitle') or data['title']
  28. video_id = data.get('id') or video_id
  29. entries = []
  30. conviva = data.get('convivaStatistics') or {}
  31. live = (data.get('mediaElementType') == 'Live' or
  32. data.get('isLive') is True or conviva.get('isLive'))
  33. def make_title(t):
  34. return self._live_title(t) if live else t
  35. media_assets = data.get('mediaAssets')
  36. if media_assets and isinstance(media_assets, list):
  37. def video_id_and_title(idx):
  38. return ((video_id, title) if len(media_assets) == 1
  39. else ('%s-%d' % (video_id, idx), '%s (Part %d)' % (title, idx)))
  40. for num, asset in enumerate(media_assets, 1):
  41. asset_url = asset.get('url')
  42. if not asset_url:
  43. continue
  44. formats = self._extract_akamai_formats(asset_url, video_id)
  45. if not formats:
  46. continue
  47. self._sort_formats(formats)
  48. # Some f4m streams may not work with hdcore in fragments' URLs
  49. for f in formats:
  50. extra_param = f.get('extra_param_to_segment_url')
  51. if extra_param and 'hdcore' in extra_param:
  52. del f['extra_param_to_segment_url']
  53. entry_id, entry_title = video_id_and_title(num)
  54. duration = parse_duration(asset.get('duration'))
  55. subtitles = {}
  56. for subtitle in ('webVtt', 'timedText'):
  57. subtitle_url = asset.get('%sSubtitlesUrl' % subtitle)
  58. if subtitle_url:
  59. subtitles.setdefault('no', []).append({
  60. 'url': compat_urllib_parse_unquote(subtitle_url)
  61. })
  62. entries.append({
  63. 'id': asset.get('carrierId') or entry_id,
  64. 'title': make_title(entry_title),
  65. 'duration': duration,
  66. 'subtitles': subtitles,
  67. 'formats': formats,
  68. })
  69. if not entries:
  70. media_url = data.get('mediaUrl')
  71. if media_url:
  72. formats = self._extract_akamai_formats(media_url, video_id)
  73. self._sort_formats(formats)
  74. duration = parse_duration(data.get('duration'))
  75. entries = [{
  76. 'id': video_id,
  77. 'title': make_title(title),
  78. 'duration': duration,
  79. 'formats': formats,
  80. }]
  81. if not entries:
  82. MESSAGES = {
  83. 'ProgramRightsAreNotReady': 'Du kan dessverre ikke se eller høre programmet',
  84. 'ProgramRightsHasExpired': 'Programmet har gått ut',
  85. 'ProgramIsGeoBlocked': 'NRK har ikke rettigheter til å vise dette programmet utenfor Norge',
  86. }
  87. message_type = data.get('messageType', '')
  88. # Can be ProgramIsGeoBlocked or ChannelIsGeoBlocked*
  89. if 'IsGeoBlocked' in message_type:
  90. self.raise_geo_restricted(
  91. msg=MESSAGES.get('ProgramIsGeoBlocked'),
  92. countries=self._GEO_COUNTRIES)
  93. raise ExtractorError(
  94. '%s said: %s' % (self.IE_NAME, MESSAGES.get(
  95. message_type, message_type)),
  96. expected=True)
  97. series = conviva.get('seriesName') or data.get('seriesTitle')
  98. episode = conviva.get('episodeName') or data.get('episodeNumberOrDate')
  99. season_number = None
  100. episode_number = None
  101. if data.get('mediaElementType') == 'Episode':
  102. _season_episode = data.get('scoresStatistics', {}).get('springStreamStream') or \
  103. data.get('relativeOriginUrl', '')
  104. EPISODENUM_RE = [
  105. r'/s(?P<season>\d{,2})e(?P<episode>\d{,2})\.',
  106. r'/sesong-(?P<season>\d{,2})/episode-(?P<episode>\d{,2})',
  107. ]
  108. season_number = int_or_none(self._search_regex(
  109. EPISODENUM_RE, _season_episode, 'season number',
  110. default=None, group='season'))
  111. episode_number = int_or_none(self._search_regex(
  112. EPISODENUM_RE, _season_episode, 'episode number',
  113. default=None, group='episode'))
  114. thumbnails = None
  115. images = data.get('images')
  116. if images and isinstance(images, dict):
  117. web_images = images.get('webImages')
  118. if isinstance(web_images, list):
  119. thumbnails = [{
  120. 'url': image['imageUrl'],
  121. 'width': int_or_none(image.get('width')),
  122. 'height': int_or_none(image.get('height')),
  123. } for image in web_images if image.get('imageUrl')]
  124. description = data.get('description')
  125. category = data.get('mediaAnalytics', {}).get('category')
  126. common_info = {
  127. 'description': description,
  128. 'series': series,
  129. 'episode': episode,
  130. 'season_number': season_number,
  131. 'episode_number': episode_number,
  132. 'categories': [category] if category else None,
  133. 'age_limit': parse_age_limit(data.get('legalAge')),
  134. 'thumbnails': thumbnails,
  135. }
  136. vcodec = 'none' if data.get('mediaType') == 'Audio' else None
  137. for entry in entries:
  138. entry.update(common_info)
  139. for f in entry['formats']:
  140. f['vcodec'] = vcodec
  141. points = data.get('shortIndexPoints')
  142. if isinstance(points, list):
  143. chapters = []
  144. for next_num, point in enumerate(points, start=1):
  145. if not isinstance(point, dict):
  146. continue
  147. start_time = parse_duration(point.get('startPoint'))
  148. if start_time is None:
  149. continue
  150. end_time = parse_duration(
  151. data.get('duration')
  152. if next_num == len(points)
  153. else points[next_num].get('startPoint'))
  154. if end_time is None:
  155. continue
  156. chapters.append({
  157. 'start_time': start_time,
  158. 'end_time': end_time,
  159. 'title': point.get('title'),
  160. })
  161. if chapters and len(entries) == 1:
  162. entries[0]['chapters'] = chapters
  163. return self.playlist_result(entries, video_id, title, description)
  164. class NRKIE(NRKBaseIE):
  165. _VALID_URL = r'''(?x)
  166. (?:
  167. nrk:|
  168. https?://
  169. (?:
  170. (?:www\.)?nrk\.no/video/PS\*|
  171. v8[-.]psapi\.nrk\.no/mediaelement/
  172. )
  173. )
  174. (?P<id>[^?#&]+)
  175. '''
  176. _API_HOSTS = ('psapi.nrk.no', 'v8-psapi.nrk.no')
  177. _TESTS = [{
  178. # video
  179. 'url': 'http://www.nrk.no/video/PS*150533',
  180. 'md5': '2f7f6eeb2aacdd99885f355428715cfa',
  181. 'info_dict': {
  182. 'id': '150533',
  183. 'ext': 'mp4',
  184. 'title': 'Dompap og andre fugler i Piip-Show',
  185. 'description': 'md5:d9261ba34c43b61c812cb6b0269a5c8f',
  186. 'duration': 263,
  187. }
  188. }, {
  189. # audio
  190. 'url': 'http://www.nrk.no/video/PS*154915',
  191. # MD5 is unstable
  192. 'info_dict': {
  193. 'id': '154915',
  194. 'ext': 'flv',
  195. 'title': 'Slik høres internett ut når du er blind',
  196. 'description': 'md5:a621f5cc1bd75c8d5104cb048c6b8568',
  197. 'duration': 20,
  198. }
  199. }, {
  200. 'url': 'nrk:ecc1b952-96dc-4a98-81b9-5296dc7a98d9',
  201. 'only_matching': True,
  202. }, {
  203. 'url': 'nrk:clip/7707d5a3-ebe7-434a-87d5-a3ebe7a34a70',
  204. 'only_matching': True,
  205. }, {
  206. 'url': 'https://v8-psapi.nrk.no/mediaelement/ecc1b952-96dc-4a98-81b9-5296dc7a98d9',
  207. 'only_matching': True,
  208. }]
  209. class NRKTVIE(NRKBaseIE):
  210. IE_DESC = 'NRK TV and NRK Radio'
  211. _EPISODE_RE = r'(?P<id>[a-zA-Z]{4}\d{8})'
  212. _VALID_URL = r'''(?x)
  213. https?://
  214. (?:tv|radio)\.nrk(?:super)?\.no/
  215. (?:serie/[^/]+|program)/
  216. (?![Ee]pisodes)%s
  217. (?:/\d{2}-\d{2}-\d{4})?
  218. (?:\#del=(?P<part_id>\d+))?
  219. ''' % _EPISODE_RE
  220. _API_HOSTS = ('psapi-ne.nrk.no', 'psapi-we.nrk.no')
  221. _TESTS = [{
  222. 'url': 'https://tv.nrk.no/serie/20-spoersmaal-tv/MUHH48000314/23-05-2014',
  223. 'md5': '4e9ca6629f09e588ed240fb11619922a',
  224. 'info_dict': {
  225. 'id': 'MUHH48000314AA',
  226. 'ext': 'mp4',
  227. 'title': '20 spørsmål 23.05.2014',
  228. 'description': 'md5:bdea103bc35494c143c6a9acdd84887a',
  229. 'duration': 1741,
  230. 'series': '20 spørsmål - TV',
  231. 'episode': '23.05.2014',
  232. },
  233. }, {
  234. 'url': 'https://tv.nrk.no/program/mdfp15000514',
  235. 'info_dict': {
  236. 'id': 'MDFP15000514CA',
  237. 'ext': 'mp4',
  238. 'title': 'Grunnlovsjubiléet - Stor ståhei for ingenting 24.05.2014',
  239. 'description': 'md5:89290c5ccde1b3a24bb8050ab67fe1db',
  240. 'duration': 4605,
  241. 'series': 'Kunnskapskanalen',
  242. 'episode': '24.05.2014',
  243. },
  244. 'params': {
  245. 'skip_download': True,
  246. },
  247. }, {
  248. # single playlist video
  249. 'url': 'https://tv.nrk.no/serie/tour-de-ski/MSPO40010515/06-01-2015#del=2',
  250. 'info_dict': {
  251. 'id': 'MSPO40010515-part2',
  252. 'ext': 'flv',
  253. 'title': 'Tour de Ski: Sprint fri teknikk, kvinner og menn 06.01.2015 (del 2:2)',
  254. 'description': 'md5:238b67b97a4ac7d7b4bf0edf8cc57d26',
  255. },
  256. 'params': {
  257. 'skip_download': True,
  258. },
  259. 'expected_warnings': ['Video is geo restricted'],
  260. 'skip': 'particular part is not supported currently',
  261. }, {
  262. 'url': 'https://tv.nrk.no/serie/tour-de-ski/MSPO40010515/06-01-2015',
  263. 'playlist': [{
  264. 'info_dict': {
  265. 'id': 'MSPO40010515AH',
  266. 'ext': 'mp4',
  267. 'title': 'Sprint fri teknikk, kvinner og menn 06.01.2015 (Part 1)',
  268. 'description': 'md5:c03aba1e917561eface5214020551b7a',
  269. 'duration': 772,
  270. 'series': 'Tour de Ski',
  271. 'episode': '06.01.2015',
  272. },
  273. 'params': {
  274. 'skip_download': True,
  275. },
  276. }, {
  277. 'info_dict': {
  278. 'id': 'MSPO40010515BH',
  279. 'ext': 'mp4',
  280. 'title': 'Sprint fri teknikk, kvinner og menn 06.01.2015 (Part 2)',
  281. 'description': 'md5:c03aba1e917561eface5214020551b7a',
  282. 'duration': 6175,
  283. 'series': 'Tour de Ski',
  284. 'episode': '06.01.2015',
  285. },
  286. 'params': {
  287. 'skip_download': True,
  288. },
  289. }],
  290. 'info_dict': {
  291. 'id': 'MSPO40010515',
  292. 'title': 'Sprint fri teknikk, kvinner og menn 06.01.2015',
  293. 'description': 'md5:c03aba1e917561eface5214020551b7a',
  294. },
  295. 'expected_warnings': ['Video is geo restricted'],
  296. }, {
  297. 'url': 'https://tv.nrk.no/serie/anno/KMTE50001317/sesong-3/episode-13',
  298. 'info_dict': {
  299. 'id': 'KMTE50001317AA',
  300. 'ext': 'mp4',
  301. 'title': 'Anno 13:30',
  302. 'description': 'md5:11d9613661a8dbe6f9bef54e3a4cbbfa',
  303. 'duration': 2340,
  304. 'series': 'Anno',
  305. 'episode': '13:30',
  306. 'season_number': 3,
  307. 'episode_number': 13,
  308. },
  309. 'params': {
  310. 'skip_download': True,
  311. },
  312. }, {
  313. 'url': 'https://tv.nrk.no/serie/nytt-paa-nytt/MUHH46000317/27-01-2017',
  314. 'info_dict': {
  315. 'id': 'MUHH46000317AA',
  316. 'ext': 'mp4',
  317. 'title': 'Nytt på Nytt 27.01.2017',
  318. 'description': 'md5:5358d6388fba0ea6f0b6d11c48b9eb4b',
  319. 'duration': 1796,
  320. 'series': 'Nytt på nytt',
  321. 'episode': '27.01.2017',
  322. },
  323. 'params': {
  324. 'skip_download': True,
  325. },
  326. }, {
  327. 'url': 'https://radio.nrk.no/serie/dagsnytt/NPUB21019315/12-07-2015#',
  328. 'only_matching': True,
  329. }]
  330. class NRKTVDirekteIE(NRKTVIE):
  331. IE_DESC = 'NRK TV Direkte and NRK Radio Direkte'
  332. _VALID_URL = r'https?://(?:tv|radio)\.nrk\.no/direkte/(?P<id>[^/?#&]+)'
  333. _TESTS = [{
  334. 'url': 'https://tv.nrk.no/direkte/nrk1',
  335. 'only_matching': True,
  336. }, {
  337. 'url': 'https://radio.nrk.no/direkte/p1_oslo_akershus',
  338. 'only_matching': True,
  339. }]
  340. class NRKPlaylistBaseIE(InfoExtractor):
  341. def _extract_description(self, webpage):
  342. pass
  343. def _real_extract(self, url):
  344. playlist_id = self._match_id(url)
  345. webpage = self._download_webpage(url, playlist_id)
  346. entries = [
  347. self.url_result('nrk:%s' % video_id, NRKIE.ie_key())
  348. for video_id in re.findall(self._ITEM_RE, webpage)
  349. ]
  350. playlist_title = self. _extract_title(webpage)
  351. playlist_description = self._extract_description(webpage)
  352. return self.playlist_result(
  353. entries, playlist_id, playlist_title, playlist_description)
  354. class NRKPlaylistIE(NRKPlaylistBaseIE):
  355. _VALID_URL = r'https?://(?:www\.)?nrk\.no/(?!video|skole)(?:[^/]+/)+(?P<id>[^/]+)'
  356. _ITEM_RE = r'class="[^"]*\brich\b[^"]*"[^>]+data-video-id="([^"]+)"'
  357. _TESTS = [{
  358. 'url': 'http://www.nrk.no/troms/gjenopplev-den-historiske-solformorkelsen-1.12270763',
  359. 'info_dict': {
  360. 'id': 'gjenopplev-den-historiske-solformorkelsen-1.12270763',
  361. 'title': 'Gjenopplev den historiske solformørkelsen',
  362. 'description': 'md5:c2df8ea3bac5654a26fc2834a542feed',
  363. },
  364. 'playlist_count': 2,
  365. }, {
  366. 'url': 'http://www.nrk.no/kultur/bok/rivertonprisen-til-karin-fossum-1.12266449',
  367. 'info_dict': {
  368. 'id': 'rivertonprisen-til-karin-fossum-1.12266449',
  369. 'title': 'Rivertonprisen til Karin Fossum',
  370. 'description': 'Første kvinne på 15 år til å vinne krimlitteraturprisen.',
  371. },
  372. 'playlist_count': 5,
  373. }]
  374. def _extract_title(self, webpage):
  375. return self._og_search_title(webpage, fatal=False)
  376. def _extract_description(self, webpage):
  377. return self._og_search_description(webpage)
  378. class NRKTVEpisodesIE(NRKPlaylistBaseIE):
  379. _VALID_URL = r'https?://tv\.nrk\.no/program/[Ee]pisodes/[^/]+/(?P<id>\d+)'
  380. _ITEM_RE = r'data-episode=["\']%s' % NRKTVIE._EPISODE_RE
  381. _TESTS = [{
  382. 'url': 'https://tv.nrk.no/program/episodes/nytt-paa-nytt/69031',
  383. 'info_dict': {
  384. 'id': '69031',
  385. 'title': 'Nytt på nytt, sesong: 201210',
  386. },
  387. 'playlist_count': 4,
  388. }]
  389. def _extract_title(self, webpage):
  390. return self._html_search_regex(
  391. r'<h1>([^<]+)</h1>', webpage, 'title', fatal=False)
  392. class NRKTVSeriesIE(InfoExtractor):
  393. _VALID_URL = r'https?://(?:tv|radio)\.nrk(?:super)?\.no/serie/(?P<id>[^/]+)'
  394. _ITEM_RE = r'(?:data-season=["\']|id=["\']season-)(?P<id>\d+)'
  395. _TESTS = [{
  396. 'url': 'https://tv.nrk.no/serie/groenn-glede',
  397. 'info_dict': {
  398. 'id': 'groenn-glede',
  399. 'title': 'Grønn glede',
  400. 'description': 'md5:7576e92ae7f65da6993cf90ee29e4608',
  401. },
  402. 'playlist_mincount': 9,
  403. }, {
  404. 'url': 'http://tv.nrksuper.no/serie/labyrint',
  405. 'info_dict': {
  406. 'id': 'labyrint',
  407. 'title': 'Labyrint',
  408. 'description': 'md5:58afd450974c89e27d5a19212eee7115',
  409. },
  410. 'playlist_mincount': 3,
  411. }, {
  412. 'url': 'https://tv.nrk.no/serie/broedrene-dal-og-spektralsteinene',
  413. 'only_matching': True,
  414. }, {
  415. 'url': 'https://tv.nrk.no/serie/saving-the-human-race',
  416. 'only_matching': True,
  417. }, {
  418. 'url': 'https://tv.nrk.no/serie/postmann-pat',
  419. 'only_matching': True,
  420. }]
  421. @classmethod
  422. def suitable(cls, url):
  423. return False if NRKTVIE.suitable(url) else super(NRKTVSeriesIE, cls).suitable(url)
  424. def _real_extract(self, url):
  425. series_id = self._match_id(url)
  426. webpage = self._download_webpage(url, series_id)
  427. entries = [
  428. self.url_result(
  429. 'https://tv.nrk.no/program/Episodes/{series}/{season}'.format(
  430. series=series_id, season=season_id))
  431. for season_id in re.findall(self._ITEM_RE, webpage)
  432. ]
  433. title = self._html_search_meta(
  434. 'seriestitle', webpage,
  435. 'title', default=None) or self._og_search_title(
  436. webpage, fatal=False)
  437. description = self._html_search_meta(
  438. 'series_description', webpage,
  439. 'description', default=None) or self._og_search_description(webpage)
  440. return self.playlist_result(entries, series_id, title, description)
  441. class NRKSkoleIE(InfoExtractor):
  442. IE_DESC = 'NRK Skole'
  443. _VALID_URL = r'https?://(?:www\.)?nrk\.no/skole/?\?.*\bmediaId=(?P<id>\d+)'
  444. _TESTS = [{
  445. 'url': 'https://www.nrk.no/skole/?page=search&q=&mediaId=14099',
  446. 'md5': '6bc936b01f9dd8ed45bc58b252b2d9b6',
  447. 'info_dict': {
  448. 'id': '6021',
  449. 'ext': 'mp4',
  450. 'title': 'Genetikk og eneggede tvillinger',
  451. 'description': 'md5:3aca25dcf38ec30f0363428d2b265f8d',
  452. 'duration': 399,
  453. },
  454. }, {
  455. 'url': 'https://www.nrk.no/skole/?page=objectives&subject=naturfag&objective=K15114&mediaId=19355',
  456. 'only_matching': True,
  457. }]
  458. def _real_extract(self, url):
  459. video_id = self._match_id(url)
  460. webpage = self._download_webpage(
  461. 'https://mimir.nrk.no/plugin/1.0/static?mediaId=%s' % video_id,
  462. video_id)
  463. nrk_id = self._parse_json(
  464. self._search_regex(
  465. r'<script[^>]+type=["\']application/json["\'][^>]*>({.+?})</script>',
  466. webpage, 'application json'),
  467. video_id)['activeMedia']['psId']
  468. return self.url_result('nrk:%s' % nrk_id)