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.

521 lines
19 KiB

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