You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

522 lines
19 KiB

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