1"""Plugin for NOS: Nederlandse Omroep Stichting
2
3Supports:
4   MP$: http://nos.nl/uitzending/nieuwsuur.html
5   Live: http://www.nos.nl/livestream/*
6"""
7
8import re
9import json
10
11from livestreamer.plugin import Plugin
12from livestreamer.plugin.api import http
13from livestreamer.plugin.api.utils import parse_json
14from livestreamer.stream import HTTPStream, HLSStream
15
16_url_re = re.compile("http(s)?://(\w+\.)?nos.nl/")
17_js_re = re.compile('\((.*)\)')
18_data_stream_re = re.compile('data-stream="(.*?)"', re.DOTALL | re.IGNORECASE)
19_source_re = re.compile("<source(?P<source>[^>]+)>", re.IGNORECASE)
20_source_src_re = re.compile("src=\"(?P<src>[^\"]+)\"", re.IGNORECASE)
21_source_type_re = re.compile("type=\"(?P<type>[^\"]+)\"", re.IGNORECASE)
22
23
24class NOS(Plugin):
25    @classmethod
26    def can_handle_url(cls, url):
27        return _url_re.match(url)
28
29    def _resolve_stream(self):
30        res = http.get(self.url)
31        match = _data_stream_re.search(res.text)
32        if not match:
33            return
34        data_stream = match.group(1)
35
36        resolve_data = {
37            'stream': data_stream
38        }
39        res = http.post(
40            'http://www-ipv4.nos.nl/livestream/resolve/',
41            data=json.dumps(resolve_data)
42        )
43        data = http.json(res)
44
45        res = http.get(data['url'])
46        match = _js_re.search(res.text)
47        if not match:
48            return
49
50        stream_url = parse_json(match.group(1))
51
52        return HLSStream.parse_variant_playlist(self.session, stream_url)
53
54    def _get_source_streams(self):
55        res = http.get(self.url)
56
57        streams = {}
58        sources = _source_re.findall(res.text)
59        for source in sources:
60            src = _source_src_re.search(source).group("src")
61            pixels = _source_type_re.search(source).group("type")
62
63            streams[pixels] = HTTPStream(self.session, src)
64
65        return streams
66
67    def _get_streams(self):
68        urlparts = self.url.split('/')
69
70        if urlparts[-2] == 'livestream':
71            return self._resolve_stream()
72        else:
73            return self._get_source_streams()
74
75__plugin__ = NOS
76