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.

335 lines
12 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. media_assets = data.get('mediaAssets')
  40. if media_assets and isinstance(media_assets, list):
  41. def video_id_and_title(idx):
  42. return ((video_id, title) if len(media_assets) == 1
  43. else ('%s-%d' % (video_id, idx), '%s (Part %d)' % (title, idx)))
  44. for num, asset in enumerate(media_assets, 1):
  45. asset_url = asset.get('url')
  46. if not asset_url:
  47. continue
  48. formats = self._extract_akamai_formats(asset_url, video_id)
  49. if not formats:
  50. continue
  51. self._sort_formats(formats)
  52. entry_id, entry_title = video_id_and_title(num)
  53. duration = parse_duration(asset.get('duration'))
  54. subtitles = {}
  55. for subtitle in ('webVtt', 'timedText'):
  56. subtitle_url = asset.get('%sSubtitlesUrl' % subtitle)
  57. if subtitle_url:
  58. subtitles.setdefault('no', []).append({
  59. 'url': compat_urllib_parse_unquote(subtitle_url)
  60. })
  61. entries.append({
  62. 'id': asset.get('carrierId') or entry_id,
  63. 'title': entry_title,
  64. 'duration': duration,
  65. 'subtitles': subtitles,
  66. 'formats': formats,
  67. 'http_headers': http_headers,
  68. })
  69. if not entries:
  70. media_url = data.get('mediaUrl')
  71. if media_url:
  72. formats = self._extract_akamai_formats(media_url, video_id)
  73. self._sort_formats(formats)
  74. duration = parse_duration(data.get('duration'))
  75. entries = [{
  76. 'id': video_id,
  77. 'title': title,
  78. 'duration': duration,
  79. 'formats': formats,
  80. }]
  81. if not entries:
  82. message_type = data.get('messageType', '')
  83. # Can be ProgramIsGeoBlocked or ChannelIsGeoBlocked*
  84. if 'IsGeoBlocked' in message_type and not self._faked_ip:
  85. self.report_warning(
  86. 'Video is geo restricted, trying to fake IP')
  87. self._fake_ip()
  88. return self._real_extract(url)
  89. MESSAGES = {
  90. 'ProgramRightsAreNotReady': 'Du kan dessverre ikke se eller høre programmet',
  91. 'ProgramRightsHasExpired': 'Programmet har gått ut',
  92. 'ProgramIsGeoBlocked': 'NRK har ikke rettigheter til å vise dette programmet utenfor Norge',
  93. }
  94. raise ExtractorError(
  95. '%s said: %s' % (self.IE_NAME, MESSAGES.get(
  96. message_type, message_type)),
  97. expected=True)
  98. conviva = data.get('convivaStatistics') or {}
  99. series = conviva.get('seriesName') or data.get('seriesTitle')
  100. episode = conviva.get('episodeName') or data.get('episodeNumberOrDate')
  101. thumbnails = None
  102. images = data.get('images')
  103. if images and isinstance(images, dict):
  104. web_images = images.get('webImages')
  105. if isinstance(web_images, list):
  106. thumbnails = [{
  107. 'url': image['imageUrl'],
  108. 'width': int_or_none(image.get('width')),
  109. 'height': int_or_none(image.get('height')),
  110. } for image in web_images if image.get('imageUrl')]
  111. description = data.get('description')
  112. common_info = {
  113. 'description': description,
  114. 'series': series,
  115. 'episode': episode,
  116. 'age_limit': parse_age_limit(data.get('legalAge')),
  117. 'thumbnails': thumbnails,
  118. }
  119. vcodec = 'none' if data.get('mediaType') == 'Audio' else None
  120. # TODO: extract chapters when https://github.com/rg3/youtube-dl/pull/9409 is merged
  121. for entry in entries:
  122. entry.update(common_info)
  123. for f in entry['formats']:
  124. f['vcodec'] = vcodec
  125. return self.playlist_result(entries, video_id, title, description)
  126. class NRKIE(NRKBaseIE):
  127. _VALID_URL = r'''(?x)
  128. (?:
  129. nrk:|
  130. https?://
  131. (?:
  132. (?:www\.)?nrk\.no/video/PS\*|
  133. v8-psapi\.nrk\.no/mediaelement/
  134. )
  135. )
  136. (?P<id>[^/?#&]+)
  137. '''
  138. _API_HOST = 'v8.psapi.nrk.no'
  139. _TESTS = [{
  140. # video
  141. 'url': 'http://www.nrk.no/video/PS*150533',
  142. 'md5': '2f7f6eeb2aacdd99885f355428715cfa',
  143. 'info_dict': {
  144. 'id': '150533',
  145. 'ext': 'mp4',
  146. 'title': 'Dompap og andre fugler i Piip-Show',
  147. 'description': 'md5:d9261ba34c43b61c812cb6b0269a5c8f',
  148. 'duration': 263,
  149. }
  150. }, {
  151. # audio
  152. 'url': 'http://www.nrk.no/video/PS*154915',
  153. # MD5 is unstable
  154. 'info_dict': {
  155. 'id': '154915',
  156. 'ext': 'flv',
  157. 'title': 'Slik høres internett ut når du er blind',
  158. 'description': 'md5:a621f5cc1bd75c8d5104cb048c6b8568',
  159. 'duration': 20,
  160. }
  161. }, {
  162. 'url': 'nrk:ecc1b952-96dc-4a98-81b9-5296dc7a98d9',
  163. 'only_matching': True,
  164. }, {
  165. 'url': 'https://v8-psapi.nrk.no/mediaelement/ecc1b952-96dc-4a98-81b9-5296dc7a98d9',
  166. 'only_matching': True,
  167. }]
  168. class NRKTVIE(NRKBaseIE):
  169. IE_DESC = 'NRK TV and NRK Radio'
  170. _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+))?'
  171. _API_HOST = 'psapi-we.nrk.no'
  172. _TESTS = [{
  173. 'url': 'https://tv.nrk.no/serie/20-spoersmaal-tv/MUHH48000314/23-05-2014',
  174. 'md5': '4e9ca6629f09e588ed240fb11619922a',
  175. 'info_dict': {
  176. 'id': 'MUHH48000314AA',
  177. 'ext': 'mp4',
  178. 'title': '20 spørsmål 23.05.2014',
  179. 'description': 'md5:bdea103bc35494c143c6a9acdd84887a',
  180. 'duration': 1741,
  181. },
  182. }, {
  183. 'url': 'https://tv.nrk.no/program/mdfp15000514',
  184. 'md5': '43d0be26663d380603a9cf0c24366531',
  185. 'info_dict': {
  186. 'id': 'MDFP15000514CA',
  187. 'ext': 'mp4',
  188. 'title': 'Grunnlovsjubiléet - Stor ståhei for ingenting 24.05.2014',
  189. 'description': 'md5:89290c5ccde1b3a24bb8050ab67fe1db',
  190. 'duration': 4605,
  191. },
  192. }, {
  193. # single playlist video
  194. 'url': 'https://tv.nrk.no/serie/tour-de-ski/MSPO40010515/06-01-2015#del=2',
  195. 'md5': 'adbd1dbd813edaf532b0a253780719c2',
  196. 'info_dict': {
  197. 'id': 'MSPO40010515-part2',
  198. 'ext': 'flv',
  199. 'title': 'Tour de Ski: Sprint fri teknikk, kvinner og menn 06.01.2015 (del 2:2)',
  200. 'description': 'md5:238b67b97a4ac7d7b4bf0edf8cc57d26',
  201. },
  202. 'skip': 'Only works from Norway',
  203. }, {
  204. 'url': 'https://tv.nrk.no/serie/tour-de-ski/MSPO40010515/06-01-2015',
  205. 'playlist': [{
  206. 'md5': '9480285eff92d64f06e02a5367970a7a',
  207. 'info_dict': {
  208. 'id': 'MSPO40010515-part1',
  209. 'ext': 'flv',
  210. 'title': 'Tour de Ski: Sprint fri teknikk, kvinner og menn 06.01.2015 (del 1:2)',
  211. 'description': 'md5:238b67b97a4ac7d7b4bf0edf8cc57d26',
  212. },
  213. }, {
  214. 'md5': 'adbd1dbd813edaf532b0a253780719c2',
  215. 'info_dict': {
  216. 'id': 'MSPO40010515-part2',
  217. 'ext': 'flv',
  218. 'title': 'Tour de Ski: Sprint fri teknikk, kvinner og menn 06.01.2015 (del 2:2)',
  219. 'description': 'md5:238b67b97a4ac7d7b4bf0edf8cc57d26',
  220. },
  221. }],
  222. 'info_dict': {
  223. 'id': 'MSPO40010515',
  224. 'title': 'Tour de Ski: Sprint fri teknikk, kvinner og menn',
  225. 'description': 'md5:238b67b97a4ac7d7b4bf0edf8cc57d26',
  226. 'duration': 6947.52,
  227. },
  228. 'skip': 'Only works from Norway',
  229. }, {
  230. 'url': 'https://radio.nrk.no/serie/dagsnytt/NPUB21019315/12-07-2015#',
  231. 'only_matching': True,
  232. }]
  233. class NRKPlaylistIE(InfoExtractor):
  234. _VALID_URL = r'https?://(?:www\.)?nrk\.no/(?!video|skole)(?:[^/]+/)+(?P<id>[^/]+)'
  235. _TESTS = [{
  236. 'url': 'http://www.nrk.no/troms/gjenopplev-den-historiske-solformorkelsen-1.12270763',
  237. 'info_dict': {
  238. 'id': 'gjenopplev-den-historiske-solformorkelsen-1.12270763',
  239. 'title': 'Gjenopplev den historiske solformørkelsen',
  240. 'description': 'md5:c2df8ea3bac5654a26fc2834a542feed',
  241. },
  242. 'playlist_count': 2,
  243. }, {
  244. 'url': 'http://www.nrk.no/kultur/bok/rivertonprisen-til-karin-fossum-1.12266449',
  245. 'info_dict': {
  246. 'id': 'rivertonprisen-til-karin-fossum-1.12266449',
  247. 'title': 'Rivertonprisen til Karin Fossum',
  248. 'description': 'Første kvinne på 15 år til å vinne krimlitteraturprisen.',
  249. },
  250. 'playlist_count': 5,
  251. }]
  252. def _real_extract(self, url):
  253. playlist_id = self._match_id(url)
  254. webpage = self._download_webpage(url, playlist_id)
  255. entries = [
  256. self.url_result('nrk:%s' % video_id, 'NRK')
  257. for video_id in re.findall(
  258. r'class="[^"]*\brich\b[^"]*"[^>]+data-video-id="([^"]+)"',
  259. webpage)
  260. ]
  261. playlist_title = self._og_search_title(webpage)
  262. playlist_description = self._og_search_description(webpage)
  263. return self.playlist_result(
  264. entries, playlist_id, playlist_title, playlist_description)
  265. class NRKSkoleIE(InfoExtractor):
  266. IE_DESC = 'NRK Skole'
  267. _VALID_URL = r'https?://(?:www\.)?nrk\.no/skole/?\?.*\bmediaId=(?P<id>\d+)'
  268. _TESTS = [{
  269. 'url': 'https://www.nrk.no/skole/?page=search&q=&mediaId=14099',
  270. 'md5': '6bc936b01f9dd8ed45bc58b252b2d9b6',
  271. 'info_dict': {
  272. 'id': '6021',
  273. 'ext': 'mp4',
  274. 'title': 'Genetikk og eneggede tvillinger',
  275. 'description': 'md5:3aca25dcf38ec30f0363428d2b265f8d',
  276. 'duration': 399,
  277. },
  278. }, {
  279. 'url': 'https://www.nrk.no/skole/?page=objectives&subject=naturfag&objective=K15114&mediaId=19355',
  280. 'only_matching': True,
  281. }]
  282. def _real_extract(self, url):
  283. video_id = self._match_id(url)
  284. webpage = self._download_webpage(
  285. 'https://mimir.nrk.no/plugin/1.0/static?mediaId=%s' % video_id,
  286. video_id)
  287. nrk_id = self._parse_json(
  288. self._search_regex(
  289. r'<script[^>]+type=["\']application/json["\'][^>]*>({.+?})</script>',
  290. webpage, 'application json'),
  291. video_id)['activeMedia']['psId']
  292. return self.url_result('nrk:%s' % nrk_id)