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.

501 lines
18 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. # TODO: extract chapters when https://github.com/rg3/youtube-dl/pull/9409 is merged
  130. for entry in entries:
  131. entry.update(common_info)
  132. for f in entry['formats']:
  133. f['vcodec'] = vcodec
  134. return self.playlist_result(entries, video_id, title, description)
  135. class NRKIE(NRKBaseIE):
  136. _VALID_URL = r'''(?x)
  137. (?:
  138. nrk:|
  139. https?://
  140. (?:
  141. (?:www\.)?nrk\.no/video/PS\*|
  142. v8[-.]psapi\.nrk\.no/mediaelement/
  143. )
  144. )
  145. (?P<id>[^?#&]+)
  146. '''
  147. _API_HOST = 'v8-psapi.nrk.no'
  148. _TESTS = [{
  149. # video
  150. 'url': 'http://www.nrk.no/video/PS*150533',
  151. 'md5': '2f7f6eeb2aacdd99885f355428715cfa',
  152. 'info_dict': {
  153. 'id': '150533',
  154. 'ext': 'mp4',
  155. 'title': 'Dompap og andre fugler i Piip-Show',
  156. 'description': 'md5:d9261ba34c43b61c812cb6b0269a5c8f',
  157. 'duration': 263,
  158. }
  159. }, {
  160. # audio
  161. 'url': 'http://www.nrk.no/video/PS*154915',
  162. # MD5 is unstable
  163. 'info_dict': {
  164. 'id': '154915',
  165. 'ext': 'flv',
  166. 'title': 'Slik høres internett ut når du er blind',
  167. 'description': 'md5:a621f5cc1bd75c8d5104cb048c6b8568',
  168. 'duration': 20,
  169. }
  170. }, {
  171. 'url': 'nrk:ecc1b952-96dc-4a98-81b9-5296dc7a98d9',
  172. 'only_matching': True,
  173. }, {
  174. 'url': 'nrk:clip/7707d5a3-ebe7-434a-87d5-a3ebe7a34a70',
  175. 'only_matching': True,
  176. }, {
  177. 'url': 'https://v8-psapi.nrk.no/mediaelement/ecc1b952-96dc-4a98-81b9-5296dc7a98d9',
  178. 'only_matching': True,
  179. }]
  180. class NRKTVIE(NRKBaseIE):
  181. IE_DESC = 'NRK TV and NRK Radio'
  182. _EPISODE_RE = r'(?P<id>[a-zA-Z]{4}\d{8})'
  183. _VALID_URL = r'''(?x)
  184. https?://
  185. (?:tv|radio)\.nrk(?:super)?\.no/
  186. (?:serie/[^/]+|program)/
  187. (?![Ee]pisodes)%s
  188. (?:/\d{2}-\d{2}-\d{4})?
  189. (?:\#del=(?P<part_id>\d+))?
  190. ''' % _EPISODE_RE
  191. _API_HOST = 'psapi-we.nrk.no'
  192. _TESTS = [{
  193. 'url': 'https://tv.nrk.no/serie/20-spoersmaal-tv/MUHH48000314/23-05-2014',
  194. 'md5': '4e9ca6629f09e588ed240fb11619922a',
  195. 'info_dict': {
  196. 'id': 'MUHH48000314AA',
  197. 'ext': 'mp4',
  198. 'title': '20 spørsmål 23.05.2014',
  199. 'description': 'md5:bdea103bc35494c143c6a9acdd84887a',
  200. 'duration': 1741,
  201. 'series': '20 spørsmål - TV',
  202. 'episode': '23.05.2014',
  203. },
  204. }, {
  205. 'url': 'https://tv.nrk.no/program/mdfp15000514',
  206. 'info_dict': {
  207. 'id': 'MDFP15000514CA',
  208. 'ext': 'mp4',
  209. 'title': 'Grunnlovsjubiléet - Stor ståhei for ingenting 24.05.2014',
  210. 'description': 'md5:89290c5ccde1b3a24bb8050ab67fe1db',
  211. 'duration': 4605,
  212. 'series': 'Kunnskapskanalen',
  213. 'episode': '24.05.2014',
  214. },
  215. 'params': {
  216. 'skip_download': True,
  217. },
  218. }, {
  219. # single playlist video
  220. 'url': 'https://tv.nrk.no/serie/tour-de-ski/MSPO40010515/06-01-2015#del=2',
  221. 'info_dict': {
  222. 'id': 'MSPO40010515-part2',
  223. 'ext': 'flv',
  224. 'title': 'Tour de Ski: Sprint fri teknikk, kvinner og menn 06.01.2015 (del 2:2)',
  225. 'description': 'md5:238b67b97a4ac7d7b4bf0edf8cc57d26',
  226. },
  227. 'params': {
  228. 'skip_download': True,
  229. },
  230. 'expected_warnings': ['Video is geo restricted'],
  231. 'skip': 'particular part is not supported currently',
  232. }, {
  233. 'url': 'https://tv.nrk.no/serie/tour-de-ski/MSPO40010515/06-01-2015',
  234. 'playlist': [{
  235. 'info_dict': {
  236. 'id': 'MSPO40010515AH',
  237. 'ext': 'mp4',
  238. 'title': 'Sprint fri teknikk, kvinner og menn 06.01.2015 (Part 1)',
  239. 'description': 'md5:c03aba1e917561eface5214020551b7a',
  240. 'duration': 772,
  241. 'series': 'Tour de Ski',
  242. 'episode': '06.01.2015',
  243. },
  244. 'params': {
  245. 'skip_download': True,
  246. },
  247. }, {
  248. 'info_dict': {
  249. 'id': 'MSPO40010515BH',
  250. 'ext': 'mp4',
  251. 'title': 'Sprint fri teknikk, kvinner og menn 06.01.2015 (Part 2)',
  252. 'description': 'md5:c03aba1e917561eface5214020551b7a',
  253. 'duration': 6175,
  254. 'series': 'Tour de Ski',
  255. 'episode': '06.01.2015',
  256. },
  257. 'params': {
  258. 'skip_download': True,
  259. },
  260. }],
  261. 'info_dict': {
  262. 'id': 'MSPO40010515',
  263. 'title': 'Sprint fri teknikk, kvinner og menn 06.01.2015',
  264. 'description': 'md5:c03aba1e917561eface5214020551b7a',
  265. },
  266. 'expected_warnings': ['Video is geo restricted'],
  267. }, {
  268. 'url': 'https://tv.nrk.no/serie/anno/KMTE50001317/sesong-3/episode-13',
  269. 'info_dict': {
  270. 'id': 'KMTE50001317AA',
  271. 'ext': 'mp4',
  272. 'title': 'Anno 13:30',
  273. 'description': 'md5:11d9613661a8dbe6f9bef54e3a4cbbfa',
  274. 'duration': 2340,
  275. 'series': 'Anno',
  276. 'episode': '13:30',
  277. 'season_number': 3,
  278. 'episode_number': 13,
  279. },
  280. 'params': {
  281. 'skip_download': True,
  282. },
  283. }, {
  284. 'url': 'https://tv.nrk.no/serie/nytt-paa-nytt/MUHH46000317/27-01-2017',
  285. 'info_dict': {
  286. 'id': 'MUHH46000317AA',
  287. 'ext': 'mp4',
  288. 'title': 'Nytt på Nytt 27.01.2017',
  289. 'description': 'md5:5358d6388fba0ea6f0b6d11c48b9eb4b',
  290. 'duration': 1796,
  291. 'series': 'Nytt på nytt',
  292. 'episode': '27.01.2017',
  293. },
  294. 'params': {
  295. 'skip_download': True,
  296. },
  297. }, {
  298. 'url': 'https://radio.nrk.no/serie/dagsnytt/NPUB21019315/12-07-2015#',
  299. 'only_matching': True,
  300. }]
  301. class NRKTVDirekteIE(NRKTVIE):
  302. IE_DESC = 'NRK TV Direkte and NRK Radio Direkte'
  303. _VALID_URL = r'https?://(?:tv|radio)\.nrk\.no/direkte/(?P<id>[^/?#&]+)'
  304. _TESTS = [{
  305. 'url': 'https://tv.nrk.no/direkte/nrk1',
  306. 'only_matching': True,
  307. }, {
  308. 'url': 'https://radio.nrk.no/direkte/p1_oslo_akershus',
  309. 'only_matching': True,
  310. }]
  311. class NRKPlaylistBaseIE(InfoExtractor):
  312. def _extract_description(self, webpage):
  313. pass
  314. def _real_extract(self, url):
  315. playlist_id = self._match_id(url)
  316. webpage = self._download_webpage(url, playlist_id)
  317. entries = [
  318. self.url_result('nrk:%s' % video_id, NRKIE.ie_key())
  319. for video_id in re.findall(self._ITEM_RE, webpage)
  320. ]
  321. playlist_title = self. _extract_title(webpage)
  322. playlist_description = self._extract_description(webpage)
  323. return self.playlist_result(
  324. entries, playlist_id, playlist_title, playlist_description)
  325. class NRKPlaylistIE(NRKPlaylistBaseIE):
  326. _VALID_URL = r'https?://(?:www\.)?nrk\.no/(?!video|skole)(?:[^/]+/)+(?P<id>[^/]+)'
  327. _ITEM_RE = r'class="[^"]*\brich\b[^"]*"[^>]+data-video-id="([^"]+)"'
  328. _TESTS = [{
  329. 'url': 'http://www.nrk.no/troms/gjenopplev-den-historiske-solformorkelsen-1.12270763',
  330. 'info_dict': {
  331. 'id': 'gjenopplev-den-historiske-solformorkelsen-1.12270763',
  332. 'title': 'Gjenopplev den historiske solformørkelsen',
  333. 'description': 'md5:c2df8ea3bac5654a26fc2834a542feed',
  334. },
  335. 'playlist_count': 2,
  336. }, {
  337. 'url': 'http://www.nrk.no/kultur/bok/rivertonprisen-til-karin-fossum-1.12266449',
  338. 'info_dict': {
  339. 'id': 'rivertonprisen-til-karin-fossum-1.12266449',
  340. 'title': 'Rivertonprisen til Karin Fossum',
  341. 'description': 'Første kvinne på 15 år til å vinne krimlitteraturprisen.',
  342. },
  343. 'playlist_count': 5,
  344. }]
  345. def _extract_title(self, webpage):
  346. return self._og_search_title(webpage, fatal=False)
  347. def _extract_description(self, webpage):
  348. return self._og_search_description(webpage)
  349. class NRKTVEpisodesIE(NRKPlaylistBaseIE):
  350. _VALID_URL = r'https?://tv\.nrk\.no/program/[Ee]pisodes/[^/]+/(?P<id>\d+)'
  351. _ITEM_RE = r'data-episode=["\']%s' % NRKTVIE._EPISODE_RE
  352. _TESTS = [{
  353. 'url': 'https://tv.nrk.no/program/episodes/nytt-paa-nytt/69031',
  354. 'info_dict': {
  355. 'id': '69031',
  356. 'title': 'Nytt på nytt, sesong: 201210',
  357. },
  358. 'playlist_count': 4,
  359. }]
  360. def _extract_title(self, webpage):
  361. return self._html_search_regex(
  362. r'<h1>([^<]+)</h1>', webpage, 'title', fatal=False)
  363. class NRKTVSeriesIE(InfoExtractor):
  364. _VALID_URL = r'https?://(?:tv|radio)\.nrk(?:super)?\.no/serie/(?P<id>[^/]+)'
  365. _ITEM_RE = r'(?:data-season=["\']|id=["\']season-)(?P<id>\d+)'
  366. _TESTS = [{
  367. 'url': 'https://tv.nrk.no/serie/groenn-glede',
  368. 'info_dict': {
  369. 'id': 'groenn-glede',
  370. 'title': 'Grønn glede',
  371. 'description': 'md5:7576e92ae7f65da6993cf90ee29e4608',
  372. },
  373. 'playlist_mincount': 9,
  374. }, {
  375. 'url': 'http://tv.nrksuper.no/serie/labyrint',
  376. 'info_dict': {
  377. 'id': 'labyrint',
  378. 'title': 'Labyrint',
  379. 'description': 'md5:58afd450974c89e27d5a19212eee7115',
  380. },
  381. 'playlist_mincount': 3,
  382. }, {
  383. 'url': 'https://tv.nrk.no/serie/broedrene-dal-og-spektralsteinene',
  384. 'only_matching': True,
  385. }, {
  386. 'url': 'https://tv.nrk.no/serie/saving-the-human-race',
  387. 'only_matching': True,
  388. }, {
  389. 'url': 'https://tv.nrk.no/serie/postmann-pat',
  390. 'only_matching': True,
  391. }]
  392. @classmethod
  393. def suitable(cls, url):
  394. return False if NRKTVIE.suitable(url) else super(NRKTVSeriesIE, cls).suitable(url)
  395. def _real_extract(self, url):
  396. series_id = self._match_id(url)
  397. webpage = self._download_webpage(url, series_id)
  398. entries = [
  399. self.url_result(
  400. 'https://tv.nrk.no/program/Episodes/{series}/{season}'.format(
  401. series=series_id, season=season_id))
  402. for season_id in re.findall(self._ITEM_RE, webpage)
  403. ]
  404. title = self._html_search_meta(
  405. 'seriestitle', webpage,
  406. 'title', default=None) or self._og_search_title(
  407. webpage, fatal=False)
  408. description = self._html_search_meta(
  409. 'series_description', webpage,
  410. 'description', default=None) or self._og_search_description(webpage)
  411. return self.playlist_result(entries, series_id, title, description)
  412. class NRKSkoleIE(InfoExtractor):
  413. IE_DESC = 'NRK Skole'
  414. _VALID_URL = r'https?://(?:www\.)?nrk\.no/skole/?\?.*\bmediaId=(?P<id>\d+)'
  415. _TESTS = [{
  416. 'url': 'https://www.nrk.no/skole/?page=search&q=&mediaId=14099',
  417. 'md5': '6bc936b01f9dd8ed45bc58b252b2d9b6',
  418. 'info_dict': {
  419. 'id': '6021',
  420. 'ext': 'mp4',
  421. 'title': 'Genetikk og eneggede tvillinger',
  422. 'description': 'md5:3aca25dcf38ec30f0363428d2b265f8d',
  423. 'duration': 399,
  424. },
  425. }, {
  426. 'url': 'https://www.nrk.no/skole/?page=objectives&subject=naturfag&objective=K15114&mediaId=19355',
  427. 'only_matching': True,
  428. }]
  429. def _real_extract(self, url):
  430. video_id = self._match_id(url)
  431. webpage = self._download_webpage(
  432. 'https://mimir.nrk.no/plugin/1.0/static?mediaId=%s' % video_id,
  433. video_id)
  434. nrk_id = self._parse_json(
  435. self._search_regex(
  436. r'<script[^>]+type=["\']application/json["\'][^>]*>({.+?})</script>',
  437. webpage, 'application json'),
  438. video_id)['activeMedia']['psId']
  439. return self.url_result('nrk:%s' % nrk_id)