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.

395 lines
14 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. thumbnails = None
  111. images = data.get('images')
  112. if images and isinstance(images, dict):
  113. web_images = images.get('webImages')
  114. if isinstance(web_images, list):
  115. thumbnails = [{
  116. 'url': image['imageUrl'],
  117. 'width': int_or_none(image.get('width')),
  118. 'height': int_or_none(image.get('height')),
  119. } for image in web_images if image.get('imageUrl')]
  120. description = data.get('description')
  121. common_info = {
  122. 'description': description,
  123. 'series': series,
  124. 'episode': episode,
  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': 'https://v8-psapi.nrk.no/mediaelement/ecc1b952-96dc-4a98-81b9-5296dc7a98d9',
  175. 'only_matching': True,
  176. }]
  177. class NRKTVIE(NRKBaseIE):
  178. IE_DESC = 'NRK TV and NRK Radio'
  179. _EPISODE_RE = r'(?P<id>[a-zA-Z]{4}\d{8})'
  180. _VALID_URL = r'''(?x)
  181. https?://
  182. (?:tv|radio)\.nrk(?:super)?\.no/
  183. (?:serie/[^/]+|program)/
  184. (?![Ee]pisodes)%s
  185. (?:/\d{2}-\d{2}-\d{4})?
  186. (?:\#del=(?P<part_id>\d+))?
  187. ''' % _EPISODE_RE
  188. _API_HOST = 'psapi-we.nrk.no'
  189. _TESTS = [{
  190. 'url': 'https://tv.nrk.no/serie/20-spoersmaal-tv/MUHH48000314/23-05-2014',
  191. 'md5': '4e9ca6629f09e588ed240fb11619922a',
  192. 'info_dict': {
  193. 'id': 'MUHH48000314AA',
  194. 'ext': 'mp4',
  195. 'title': '20 spørsmål 23.05.2014',
  196. 'description': 'md5:bdea103bc35494c143c6a9acdd84887a',
  197. 'duration': 1741,
  198. },
  199. }, {
  200. 'url': 'https://tv.nrk.no/program/mdfp15000514',
  201. 'md5': '43d0be26663d380603a9cf0c24366531',
  202. 'info_dict': {
  203. 'id': 'MDFP15000514CA',
  204. 'ext': 'mp4',
  205. 'title': 'Grunnlovsjubiléet - Stor ståhei for ingenting 24.05.2014',
  206. 'description': 'md5:89290c5ccde1b3a24bb8050ab67fe1db',
  207. 'duration': 4605,
  208. },
  209. }, {
  210. # single playlist video
  211. 'url': 'https://tv.nrk.no/serie/tour-de-ski/MSPO40010515/06-01-2015#del=2',
  212. 'md5': 'adbd1dbd813edaf532b0a253780719c2',
  213. 'info_dict': {
  214. 'id': 'MSPO40010515-part2',
  215. 'ext': 'flv',
  216. 'title': 'Tour de Ski: Sprint fri teknikk, kvinner og menn 06.01.2015 (del 2:2)',
  217. 'description': 'md5:238b67b97a4ac7d7b4bf0edf8cc57d26',
  218. },
  219. 'skip': 'Only works from Norway',
  220. }, {
  221. 'url': 'https://tv.nrk.no/serie/tour-de-ski/MSPO40010515/06-01-2015',
  222. 'playlist': [{
  223. 'md5': '9480285eff92d64f06e02a5367970a7a',
  224. 'info_dict': {
  225. 'id': 'MSPO40010515-part1',
  226. 'ext': 'flv',
  227. 'title': 'Tour de Ski: Sprint fri teknikk, kvinner og menn 06.01.2015 (del 1:2)',
  228. 'description': 'md5:238b67b97a4ac7d7b4bf0edf8cc57d26',
  229. },
  230. }, {
  231. 'md5': 'adbd1dbd813edaf532b0a253780719c2',
  232. 'info_dict': {
  233. 'id': 'MSPO40010515-part2',
  234. 'ext': 'flv',
  235. 'title': 'Tour de Ski: Sprint fri teknikk, kvinner og menn 06.01.2015 (del 2:2)',
  236. 'description': 'md5:238b67b97a4ac7d7b4bf0edf8cc57d26',
  237. },
  238. }],
  239. 'info_dict': {
  240. 'id': 'MSPO40010515',
  241. 'title': 'Tour de Ski: Sprint fri teknikk, kvinner og menn',
  242. 'description': 'md5:238b67b97a4ac7d7b4bf0edf8cc57d26',
  243. 'duration': 6947.52,
  244. },
  245. 'skip': 'Only works from Norway',
  246. }, {
  247. 'url': 'https://radio.nrk.no/serie/dagsnytt/NPUB21019315/12-07-2015#',
  248. 'only_matching': True,
  249. }]
  250. class NRKTVDirekteIE(NRKTVIE):
  251. IE_DESC = 'NRK TV Direkte and NRK Radio Direkte'
  252. _VALID_URL = r'https?://(?:tv|radio)\.nrk\.no/direkte/(?P<id>[^/?#&]+)'
  253. _TESTS = [{
  254. 'url': 'https://tv.nrk.no/direkte/nrk1',
  255. 'only_matching': True,
  256. }, {
  257. 'url': 'https://radio.nrk.no/direkte/p1_oslo_akershus',
  258. 'only_matching': True,
  259. }]
  260. class NRKPlaylistBaseIE(InfoExtractor):
  261. def _extract_description(self, webpage):
  262. pass
  263. def _real_extract(self, url):
  264. playlist_id = self._match_id(url)
  265. webpage = self._download_webpage(url, playlist_id)
  266. entries = [
  267. self.url_result('nrk:%s' % video_id, NRKIE.ie_key())
  268. for video_id in re.findall(self._ITEM_RE, webpage)
  269. ]
  270. playlist_title = self. _extract_title(webpage)
  271. playlist_description = self._extract_description(webpage)
  272. return self.playlist_result(
  273. entries, playlist_id, playlist_title, playlist_description)
  274. class NRKPlaylistIE(NRKPlaylistBaseIE):
  275. _VALID_URL = r'https?://(?:www\.)?nrk\.no/(?!video|skole)(?:[^/]+/)+(?P<id>[^/]+)'
  276. _ITEM_RE = r'class="[^"]*\brich\b[^"]*"[^>]+data-video-id="([^"]+)"'
  277. _TESTS = [{
  278. 'url': 'http://www.nrk.no/troms/gjenopplev-den-historiske-solformorkelsen-1.12270763',
  279. 'info_dict': {
  280. 'id': 'gjenopplev-den-historiske-solformorkelsen-1.12270763',
  281. 'title': 'Gjenopplev den historiske solformørkelsen',
  282. 'description': 'md5:c2df8ea3bac5654a26fc2834a542feed',
  283. },
  284. 'playlist_count': 2,
  285. }, {
  286. 'url': 'http://www.nrk.no/kultur/bok/rivertonprisen-til-karin-fossum-1.12266449',
  287. 'info_dict': {
  288. 'id': 'rivertonprisen-til-karin-fossum-1.12266449',
  289. 'title': 'Rivertonprisen til Karin Fossum',
  290. 'description': 'Første kvinne på 15 år til å vinne krimlitteraturprisen.',
  291. },
  292. 'playlist_count': 5,
  293. }]
  294. def _extract_title(self, webpage):
  295. return self._og_search_title(webpage, fatal=False)
  296. def _extract_description(self, webpage):
  297. return self._og_search_description(webpage)
  298. class NRKTVEpisodesIE(NRKPlaylistBaseIE):
  299. _VALID_URL = r'https?://tv\.nrk\.no/program/[Ee]pisodes/[^/]+/(?P<id>\d+)'
  300. _ITEM_RE = r'data-episode=["\']%s' % NRKTVIE._EPISODE_RE
  301. _TESTS = [{
  302. 'url': 'https://tv.nrk.no/program/episodes/nytt-paa-nytt/69031',
  303. 'info_dict': {
  304. 'id': '69031',
  305. 'title': 'Nytt på nytt, sesong: 201210',
  306. },
  307. 'playlist_count': 4,
  308. }]
  309. def _extract_title(self, webpage):
  310. return self._html_search_regex(
  311. r'<h1>([^<]+)</h1>', webpage, 'title', fatal=False)
  312. class NRKSkoleIE(InfoExtractor):
  313. IE_DESC = 'NRK Skole'
  314. _VALID_URL = r'https?://(?:www\.)?nrk\.no/skole/?\?.*\bmediaId=(?P<id>\d+)'
  315. _TESTS = [{
  316. 'url': 'https://www.nrk.no/skole/?page=search&q=&mediaId=14099',
  317. 'md5': '6bc936b01f9dd8ed45bc58b252b2d9b6',
  318. 'info_dict': {
  319. 'id': '6021',
  320. 'ext': 'mp4',
  321. 'title': 'Genetikk og eneggede tvillinger',
  322. 'description': 'md5:3aca25dcf38ec30f0363428d2b265f8d',
  323. 'duration': 399,
  324. },
  325. }, {
  326. 'url': 'https://www.nrk.no/skole/?page=objectives&subject=naturfag&objective=K15114&mediaId=19355',
  327. 'only_matching': True,
  328. }]
  329. def _real_extract(self, url):
  330. video_id = self._match_id(url)
  331. webpage = self._download_webpage(
  332. 'https://mimir.nrk.no/plugin/1.0/static?mediaId=%s' % video_id,
  333. video_id)
  334. nrk_id = self._parse_json(
  335. self._search_regex(
  336. r'<script[^>]+type=["\']application/json["\'][^>]*>({.+?})</script>',
  337. webpage, 'application json'),
  338. video_id)['activeMedia']['psId']
  339. return self.url_result('nrk:%s' % nrk_id)