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.

361 lines
13 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. _VALID_URL = r'https?://(?:tv|radio)\.nrk(?:super)?\.no/(?:serie/[^/]+|program)/(?P<id>[a-zA-Z]{4}\d{8})(?:/\d{2}-\d{2}-\d{4})?(?:#del=(?P<part_id>\d+))?'
  180. _API_HOST = 'psapi-we.nrk.no'
  181. _TESTS = [{
  182. 'url': 'https://tv.nrk.no/serie/20-spoersmaal-tv/MUHH48000314/23-05-2014',
  183. 'md5': '4e9ca6629f09e588ed240fb11619922a',
  184. 'info_dict': {
  185. 'id': 'MUHH48000314AA',
  186. 'ext': 'mp4',
  187. 'title': '20 spørsmål 23.05.2014',
  188. 'description': 'md5:bdea103bc35494c143c6a9acdd84887a',
  189. 'duration': 1741,
  190. },
  191. }, {
  192. 'url': 'https://tv.nrk.no/program/mdfp15000514',
  193. 'md5': '43d0be26663d380603a9cf0c24366531',
  194. 'info_dict': {
  195. 'id': 'MDFP15000514CA',
  196. 'ext': 'mp4',
  197. 'title': 'Grunnlovsjubiléet - Stor ståhei for ingenting 24.05.2014',
  198. 'description': 'md5:89290c5ccde1b3a24bb8050ab67fe1db',
  199. 'duration': 4605,
  200. },
  201. }, {
  202. # single playlist video
  203. 'url': 'https://tv.nrk.no/serie/tour-de-ski/MSPO40010515/06-01-2015#del=2',
  204. 'md5': 'adbd1dbd813edaf532b0a253780719c2',
  205. 'info_dict': {
  206. 'id': 'MSPO40010515-part2',
  207. 'ext': 'flv',
  208. 'title': 'Tour de Ski: Sprint fri teknikk, kvinner og menn 06.01.2015 (del 2:2)',
  209. 'description': 'md5:238b67b97a4ac7d7b4bf0edf8cc57d26',
  210. },
  211. 'skip': 'Only works from Norway',
  212. }, {
  213. 'url': 'https://tv.nrk.no/serie/tour-de-ski/MSPO40010515/06-01-2015',
  214. 'playlist': [{
  215. 'md5': '9480285eff92d64f06e02a5367970a7a',
  216. 'info_dict': {
  217. 'id': 'MSPO40010515-part1',
  218. 'ext': 'flv',
  219. 'title': 'Tour de Ski: Sprint fri teknikk, kvinner og menn 06.01.2015 (del 1:2)',
  220. 'description': 'md5:238b67b97a4ac7d7b4bf0edf8cc57d26',
  221. },
  222. }, {
  223. 'md5': 'adbd1dbd813edaf532b0a253780719c2',
  224. 'info_dict': {
  225. 'id': 'MSPO40010515-part2',
  226. 'ext': 'flv',
  227. 'title': 'Tour de Ski: Sprint fri teknikk, kvinner og menn 06.01.2015 (del 2:2)',
  228. 'description': 'md5:238b67b97a4ac7d7b4bf0edf8cc57d26',
  229. },
  230. }],
  231. 'info_dict': {
  232. 'id': 'MSPO40010515',
  233. 'title': 'Tour de Ski: Sprint fri teknikk, kvinner og menn',
  234. 'description': 'md5:238b67b97a4ac7d7b4bf0edf8cc57d26',
  235. 'duration': 6947.52,
  236. },
  237. 'skip': 'Only works from Norway',
  238. }, {
  239. 'url': 'https://radio.nrk.no/serie/dagsnytt/NPUB21019315/12-07-2015#',
  240. 'only_matching': True,
  241. }]
  242. class NRKTVDirekteIE(NRKTVIE):
  243. IE_DESC = 'NRK TV Direkte and NRK Radio Direkte'
  244. _VALID_URL = r'https?://(?:tv|radio)\.nrk\.no/direkte/(?P<id>[^/?#&]+)'
  245. _TESTS = [{
  246. 'url': 'https://tv.nrk.no/direkte/nrk1',
  247. 'only_matching': True,
  248. }, {
  249. 'url': 'https://radio.nrk.no/direkte/p1_oslo_akershus',
  250. 'only_matching': True,
  251. }]
  252. class NRKPlaylistIE(InfoExtractor):
  253. _VALID_URL = r'https?://(?:www\.)?nrk\.no/(?!video|skole)(?:[^/]+/)+(?P<id>[^/]+)'
  254. _TESTS = [{
  255. 'url': 'http://www.nrk.no/troms/gjenopplev-den-historiske-solformorkelsen-1.12270763',
  256. 'info_dict': {
  257. 'id': 'gjenopplev-den-historiske-solformorkelsen-1.12270763',
  258. 'title': 'Gjenopplev den historiske solformørkelsen',
  259. 'description': 'md5:c2df8ea3bac5654a26fc2834a542feed',
  260. },
  261. 'playlist_count': 2,
  262. }, {
  263. 'url': 'http://www.nrk.no/kultur/bok/rivertonprisen-til-karin-fossum-1.12266449',
  264. 'info_dict': {
  265. 'id': 'rivertonprisen-til-karin-fossum-1.12266449',
  266. 'title': 'Rivertonprisen til Karin Fossum',
  267. 'description': 'Første kvinne på 15 år til å vinne krimlitteraturprisen.',
  268. },
  269. 'playlist_count': 5,
  270. }]
  271. def _real_extract(self, url):
  272. playlist_id = self._match_id(url)
  273. webpage = self._download_webpage(url, playlist_id)
  274. entries = [
  275. self.url_result('nrk:%s' % video_id, 'NRK')
  276. for video_id in re.findall(
  277. r'class="[^"]*\brich\b[^"]*"[^>]+data-video-id="([^"]+)"',
  278. webpage)
  279. ]
  280. playlist_title = self._og_search_title(webpage)
  281. playlist_description = self._og_search_description(webpage)
  282. return self.playlist_result(
  283. entries, playlist_id, playlist_title, playlist_description)
  284. class NRKSkoleIE(InfoExtractor):
  285. IE_DESC = 'NRK Skole'
  286. _VALID_URL = r'https?://(?:www\.)?nrk\.no/skole/?\?.*\bmediaId=(?P<id>\d+)'
  287. _TESTS = [{
  288. 'url': 'https://www.nrk.no/skole/?page=search&q=&mediaId=14099',
  289. 'md5': '6bc936b01f9dd8ed45bc58b252b2d9b6',
  290. 'info_dict': {
  291. 'id': '6021',
  292. 'ext': 'mp4',
  293. 'title': 'Genetikk og eneggede tvillinger',
  294. 'description': 'md5:3aca25dcf38ec30f0363428d2b265f8d',
  295. 'duration': 399,
  296. },
  297. }, {
  298. 'url': 'https://www.nrk.no/skole/?page=objectives&subject=naturfag&objective=K15114&mediaId=19355',
  299. 'only_matching': True,
  300. }]
  301. def _real_extract(self, url):
  302. video_id = self._match_id(url)
  303. webpage = self._download_webpage(
  304. 'https://mimir.nrk.no/plugin/1.0/static?mediaId=%s' % video_id,
  305. video_id)
  306. nrk_id = self._parse_json(
  307. self._search_regex(
  308. r'<script[^>]+type=["\']application/json["\'][^>]*>({.+?})</script>',
  309. webpage, 'application json'),
  310. video_id)['activeMedia']['psId']
  311. return self.url_result('nrk:%s' % nrk_id)