nrk.py 12 KB

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