nrk.py 12 KB

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