Exemplo n.º 1
0
    def Login(self):
        t1 = int(xbmcaddon.Addon().getSetting('s.timestamp'))
        t2 = int(time.time())
        update = (abs(t2 - t1) / 3600) >= 24 or t1 == 0
        if update == False:
            return

        login_url = 'https://%s/accounts.login?loginID=%s&password=%s&targetEnv=mobile&format=jsonp&apiKey=%s&callback=jsonp'
        most_baseUrl = 'https://www.rtlmost.hu'

        most_source = net.request(most_baseUrl)
        client_js = re.search('''<script\s*type=['"]module['"]\s*src=['"](\/?client-.+?)['"]''', most_source).group(1)
        api_src = net.request(urlparse.urljoin(most_baseUrl, client_js))
        api_src = re.findall('gigya\s*:\s*(\{[^\}]+\})', api_src)
        api_src = [i for i in api_src if 'login.rtlmost.hu' in i][0]
        api_src = json.loads(re.sub('([{,:])(\w+)([},:])','\\1\"\\2\"\\3', api_src))

        r = net.request(login_url % (api_src['domain'], self.username, self.password, api_src['key']))
        r = re.search('\(([^\)]+)', r).group(1)
        jsonparse = json.loads(r)

        if 'errorMessage' in jsonparse:
            xbmcgui.Dialog().ok(u'Bejelentkez\u00E9si hiba', jsonparse['errorMessage'])
            xbmcaddon.Addon().setSetting('loggedin', 'false')
            xbmcaddon.Addon().setSetting('s.timestamp', '0')
            sys.exit(0)

        xbmcaddon.Addon().setSetting('userid', jsonparse['UID'])
        xbmcaddon.Addon().setSetting('signature', jsonparse['UIDSignature'])
        xbmcaddon.Addon().setSetting('s.timestamp', jsonparse['signatureTimestamp'])
        xbmcaddon.Addon().setSetting('loggedin', 'true')
Exemplo n.º 2
0
    def programs(self, id):
        query = base_url + prog_link
        programs = net.request(query % id)
        prgs = {}
        for i in json.loads(programs):
            prg = {}
            title = py2_encode(i['title'])
            try:
                thumb = img_link % [
                    x['external_key']
                    for x in i['images'] if x['role'] == 'logo'
                ][0]
            except:
                thumb = ''
            try:
                fanart = img_link % [
                    x['external_key']
                    for x in i['images'] if x['role'] == 'mea'
                ][0]
            except:
                fanart = None
            id = str(i['id'])
            plot = py2_encode(i['description'])
            extraInfo = ""
            if xbmcaddon.Addon().getSetting('show_content_summary') == 'true':
                try:
                    if (i['count']['vi'] > 0):
                        extraInfo = " (%d %s)" % (
                            i['count']['vi'],
                            py2_encode(i['program_type_wording']['plural'])
                            if i['program_type_wording'] != None else
                            'Teljes adás')
                    else:
                        extraInfo = " (%d előzetes és részletek)" % (
                            i['count']['vc'])
                except:
                    pass
            prg = {
                'extraInfo': extraInfo,
                'id': id,
                'fanart': fanart,
                'thumb': thumb,
                'plot': plot
            }
            prgs[title] = prg
        prgTitles = list(prgs.keys())
        if (xbmcaddon.Addon().getSetting('sort_programs') == 'true'):
            prgTitles.sort(key=locale.strxfrm)
        for prg in prgTitles:
            #self.addDirectoryItem("%s[I][COLOR silver]%s[/COLOR][/I]" % (title, extraInfo), 'episodes&url=%s&fanart=%s' % (id, fanart), thumb, 'DefaultTVShows.png', Fanart=fanart, meta={'plot': plot})
            self.addDirectoryItem("%s[I][COLOR silver]%s[/COLOR][/I]" %
                                  (prg, prgs[prg]['extraInfo']),
                                  'episodes&url=%s&fanart=%s' %
                                  (prgs[prg]['id'], prgs[prg]['fanart']),
                                  prgs[prg]['thumb'],
                                  'DefaultTVShows.png',
                                  Fanart=prgs[prg]['fanart'],
                                  meta={'plot': prgs[prg]['plot']})

        self.endDirectory(type='tvshows')
Exemplo n.º 3
0
 def liveChannels(self):
     liveChannels = {'rtlhu_rtl_klub': 'RTL Klub', 'rtlhu_rtl_ii': 'RTL II', 'rtlhu_cool': 'Cool TV', 'rtlhu_rtl_gold': 'RTL Gold', 'rtlhu_rtl_plus': 'RTL+', 'rtlhu_film_plus': 'Film+', 'rtlhu_sorozat_plus': 'Sorozat+', 'rtlhu_muzsika_tv': 'Muzsika TV'}
     query = base_url + livechannels_link.decode('base64')
     lives = net.request(query)
     for (i,j) in json.loads(lives, object_pairs_hook=OrderedDict).items():
         self.addDirectoryItem("[B]"+liveChannels[i.encode('utf-8')] + "[/B] - " + j[0]['title'].encode('utf-8') + "  [COLOR gold][" + j[0]['diffusion_start_date'].encode('utf-8')[11:-3] + " - " + j[0]['diffusion_end_date'].encode('utf-8')[11:-3] + "][/COLOR]", 'liveChannel&url=%s' % i.encode('utf-8'), '', 'DefaultTVShows.png')
     self.endDirectory()
Exemplo n.º 4
0
 def liveChannel(self, channel):
     headers = {
         'x-6play-freemium':
         '1',
         'x-auth-gigya-uid':
         xbmcaddon.Addon().getSetting('userid'),
         'x-auth-gigya-signature':
         xbmcaddon.Addon().getSetting('signature'),
         'x-auth-gigya-signature-timestamp':
         xbmcaddon.Addon().getSetting('s.timestamp'),
         'Origin':
         'https://www.rtlmost.hu'
     }
     query = base_url + live_stream_link
     live = net.request(query % channel, headers=headers)
     live = json.loads(live)
     assets = live[channel][0]['live']['assets']
     if assets != []:
         streams = [{
             'container': 'live',
             'path': i['full_physical_path']
         } for i in assets]
         meta = {'title': live[channel][0]['title']}
         from resources.lib.modules import player
         player.player().play(channel, streams, None, json.dumps(meta))
     else:
         xbmcgui.Dialog().ok(u'Lej\u00E1tsz\u00E1s sikertelen.',
                             freemium_subscription_needed_errormsg)
         xbmcplugin.setResolvedUrl(int(sys.argv[1]), False,
                                   xbmcgui.ListItem())
Exemplo n.º 5
0
    def root(self):
        query = base_url + cat_link.decode('base64')
        categories = net.request(query)

        self.addDirectoryItem('Élő adás', 'liveChannels', '', 'DefaultTVShows.png')
        for i in json.loads(categories):
            self.addDirectoryItem(i['name'].encode('utf-8'), 'programs&url=%s' % str(i['id']), '', 'DefaultTVShows.png')

        self.endDirectory()
Exemplo n.º 6
0
 def get_video(self, id, meta, image):
     query = base_url + video_link.decode('base64')
     clip = net.request(query % id, headers=self.addAuthenticationHeaders())
     clip = json.loads(clip)
     assets = clip['clips'][0].get('assets')
     if assets is not None and assets != []:
         streams = [i['full_physical_path'] for i in assets]
         from resources.lib.modules import player
         player.player().play(id, streams, image, meta)
     else:
         xbmcgui.Dialog().ok(u'Lej\u00E1tsz\u00E1s sikertelen.', freemium_subscription_needed_errormsg.decode('base64').decode('utf-8'))
         xbmcplugin.setResolvedUrl(int(sys.argv[1]), False, xbmcgui.ListItem())
Exemplo n.º 7
0
 def get_video(self, id, meta, image):
     headers = {
         'x-6play-freemium': '1',
         'x-auth-gigya-uid': xbmcaddon.Addon().getSetting('userid'),
         'x-auth-gigya-signature': xbmcaddon.Addon().getSetting('signature'),
         'x-auth-gigya-signature-timestamp': xbmcaddon.Addon().getSetting('s.timestamp'),
         'Origin': 'https://www.rtlmost.hu'}
     query = base_url + video_link.decode('base64')
     clip = net.request(query % id, headers=headers)
     clip = json.loads(clip)
     assets = clip['clips'][0].get('assets')
     streams = [i['full_physical_path'] for i in assets]
     from resources.lib.modules import player
     player.player().play(id, streams, image, meta)
Exemplo n.º 8
0
    def programs(self, id):
        query = base_url + prog_link.decode('base64')
        programs = net.request(query % id)

        for i in json.loads(programs):
            title = i['title'].encode('utf-8')
            try: thumb = img_link % [x['external_key'] for x in i['images'] if x['role'] == 'logo'][0]
            except: thumb = ''
            try: fanart = img_link % [x['external_key'] for x in i['images'] if x['role'] == 'mea'][0]
            except: fanart = None
            id = str(i['id'])
            plot = i['description'].encode('utf-8')
            self.addDirectoryItem(title, 'episodes&url=%s&fanart=%s' % (id, fanart), thumb, 'DefaultTVShows.png', Fanart=fanart, meta={'plot': plot})

        self.endDirectory(type='tvshows')
Exemplo n.º 9
0
 def getJwtToken(self):
     getJwt_url = 'https://front-auth.6cloud.fr/v2/platforms/m6group_web/getJwt'
     jwtToken = xbmcaddon.Addon().getSetting('jwttoken')
     if jwtToken != "":
         m = re.search('(.*)\.(.*)\.(.*)', jwtToken)
         if m:
             errMsg = ""
             try:
                 errMsg = "RTLMost: cannot base64 decode the group 2: %s" % m.group(
                     2)
                 decodedToken = base64.b64decode(m.group(2) + "===")
                 if sys.version_info[0] == 3:
                     errMsg = "RTLMost: utf-8 decode error: %s" % decodedToken
                     decodedToken = decodedToken.decode("utf-8", "ignore")
                 errMsg = "RTLMost: decodedToken is not a json object: %s" % decodedToken
                 jsObj = json.loads(decodedToken)
                 if "exp" in jsObj:
                     if jsObj["exp"] - int(time.time()) > 0:
                         return jwtToken
                     else:
                         xbmc.log(
                             "RTLMost: jwtToken expired, request a new one.",
                             xbmc.LOGINFO)
                 else:
                     xbmc.log(
                         "RTLMost: match group 2 does not contains exp key: %s"
                         % m.group(2), xbmc.LOGERROR)
             except:
                 xbmc.log(errMsg, xbmc.LOGERROR)
         else:
             xbmc.log(
                 "RTLMost: jwtToken not match to (.*)\.(.*)\.(.*). jwtToken: %s"
                 % jwtToken, xbmc.LOGERROR)
     headers = {
         'x-auth-gigya-uid':
         self.uid,
         'x-auth-gigya-signature':
         xbmcaddon.Addon().getSetting('signature'),
         'x-auth-gigya-signature-timestamp':
         xbmcaddon.Addon().getSetting('s.timestamp'),
         'X-Customer-Name':
         'rtlhu',
         'x-auth-device-id':
         xbmcaddon.Addon().getSetting('deviceid')
     }
     jwtAnswer = json.loads(net.request(getJwt_url, headers=headers))
     xbmcaddon.Addon().setSetting('jwttoken', jwtAnswer['token'])
     return jwtAnswer['token']
Exemplo n.º 10
0
    def myFreemiumCodes(self):
        my_uid = xbmcaddon.Addon().getSetting('userid')
        rsp = net.request(freemiumsubsriptions_url.decode('base64') % my_uid, headers=self.addAuthenticationHeaders())

        my_freemium_product_codes = dict()
        for subscription in json.loads(rsp):
            for product in subscription.get("freemium_products", []):
                code = product["code"]
                id = product["id"]
                if code not in my_freemium_product_codes:
                    # list: if the account has multiple subscriptions, they might provide
                    # the same code under different ids (not very likely, but let's prepare)
                    my_freemium_product_codes[code] = list()
                my_freemium_product_codes[code].append(id)

        return my_freemium_product_codes
Exemplo n.º 11
0
 def liveChannel(self, channel):
     headers = {
         'x-6play-freemium': '1',
         'x-auth-gigya-uid': xbmcaddon.Addon().getSetting('userid'),
         'x-auth-gigya-signature': xbmcaddon.Addon().getSetting('signature'),
         'x-auth-gigya-signature-timestamp': xbmcaddon.Addon().getSetting('s.timestamp'),
         'Origin': 'https://www.rtlmost.hu'}
     query = base_url + live_stream_link.decode('base64')
     live = net.request(query % channel, headers=headers)
     live = json.loads(live)
     assets = live[channel][0]['live']['assets']
     if assets != []:
         streams = [i['full_physical_path'] for i in assets]
         meta = {'title': live[channel][0]['title']}
         from resources.lib.modules import player
         player.player().play(channel, streams, None, json.dumps(meta))
     else:
         xbmcgui.Dialog().ok(u'Lej\u00E1tsz\u00E1s sikertelen.', u'A hozz\u00E1f\u00E9r\u00E9shez RTL Most+ el\u0151fizet\u00E9s sz\u00FCks\u00E9ges.')
         xbmcplugin.setResolvedUrl(int(sys.argv[1]), False, xbmcgui.ListItem())
Exemplo n.º 12
0
    def __init__(self):
        try:
            locale.setlocale(locale.LC_ALL, "")
        except:
            pass
        self.username = xbmcaddon.Addon().getSetting('email').strip()
        self.password = xbmcaddon.Addon().getSetting('password').strip()

        if not (self.username and self.password) != '':
            if xbmcgui.Dialog().ok(
                    'RTL Most',
                    u'A kieg\u00E9sz\u00EDt\u0151 haszn\u00E1lat\u00E1hoz add meg a bejelentkez\u00E9si adataidat.'
            ):
                xbmc.executebuiltin('Dialog.Close(busydialognocancel)')
                addon(addon().getAddonInfo('id')).openSettings()
            sys.exit(0)
        if xbmcaddon.Addon().getSetting('deviceid') == "":
            r = net.request(deviceID_url)
            jsonparse = json.loads(r)
            xbmcaddon.Addon().setSetting('deviceid', jsonparse['device_id'])
        self.Login()
Exemplo n.º 13
0
    def programs(self, id):
        query = base_url + prog_link.decode('base64')
        programs = net.request(query % id)

        for i in json.loads(programs):
            title = i['title'].encode('utf-8')
            try: thumb = img_link % [x['external_key'] for x in i['images'] if x['role'] == 'logo'][0]
            except: thumb = ''
            try: fanart = img_link % [x['external_key'] for x in i['images'] if x['role'] == 'mea'][0]
            except: fanart = None
            id = str(i['id'])
            plot = i['description'].encode('utf-8')
            extraInfo = ""
            try:
                if (i['count']['vi']>0):
                    extraInfo = " (%d %s)" % (i['count']['vi'], i['program_type_wording']['plural'].encode('utf-8') if i['program_type_wording'] != None else 'Teljes adás')
                else:
                    extraInfo = " (%d előzetes és részletek)" % (i['count']['vc'])
            except: pass
            self.addDirectoryItem("%s[I][COLOR silver]%s[/COLOR][/I]" % (title, extraInfo), 'episodes&url=%s&fanart=%s' % (id, fanart), thumb, 'DefaultTVShows.png', Fanart=fanart, meta={'plot': plot})

        self.endDirectory(type='tvshows')
Exemplo n.º 14
0
    def play(self, id, streams, image, meta):
        streams = sorted(streams)
        #dash_url = [i for i in streams if 'drmnp.ism/Manifest.mpd' in i]
        dash_url = [i for i in streams if re.match(r'(.*)drm(.*)Manifest.mpd(.*)', i)]
        hls_url = [i for i in streams if 'unpnp.ism/Manifest.m3u8' in i]
        live_url = [i for i in streams if 'stream.m3u8' in i]
        li = None

        if dash_url != []:
            # Inputstream and DRM
            manifest_url = net.request(dash_url[0], redirect=False)
            stream_url = os.path.dirname(manifest_url) + '/Manifest.mpd'         
            headers = {
                'x-auth-gigya-uid': self.uid,
                'x-auth-gigya-signature': xbmcaddon.Addon().getSetting('signature'),
                'x-auth-gigya-signature-timestamp': xbmcaddon.Addon().getSetting('s.timestamp'),
                'Origin': 'https://www.rtlmost.hu'}

            token_source = net.request(token_url.decode('base64') % (self.uid, id), headers=headers)
            token_source = json.loads(token_source)
            x_dt_auth_token = token_source['token'].encode('utf-8')

            license_headers = 'x-dt-auth-token=' + x_dt_auth_token + '&Origin=https://www.rtlmost.hu&Content-Type='
            license_key = 'https://lic.drmtoday.com/license-proxy-widevine/cenc/' + '|' + license_headers + '|R{SSM}|JBlicense'
            DRM = 'com.widevine.alpha'
            PROTOCOL = 'mpd'

            from inputstreamhelper import Helper
            is_helper = Helper(PROTOCOL, drm=DRM)
            if is_helper.check_inputstream():
                li = xbmcgui.ListItem(path=stream_url)
                li.setProperty('inputstreamaddon', 'inputstream.adaptive')
                li.setProperty('inputstream.adaptive.manifest_type', PROTOCOL)
                li.setProperty('inputstream.adaptive.license_type', DRM)
                li.setProperty('inputstream.adaptive.license_key', license_key)
                li.setMimeType('application/dash+xml')
                li.setContentLookup(False)

        elif hls_url != []:
            stream_url = hls_url[0]
            manifest_url = net.request(stream_url, redirect=False)

            manifest = net.request(manifest_url)
            sources = m3u8_parser.parse(manifest)
            if len(sources) == 0:
                manifest_url = stream_url
                manifest = net.request(manifest_url)
                sources = m3u8_parser.parse(manifest)

            root = os.path.dirname(manifest_url)

            sources = sorted(sources, key=lambda x: x['resolution'])[::-1]

            auto_pick = xbmcaddon.Addon().getSetting('hls_quality') == '0'

            if len(sources) == 1 or auto_pick == True:
                source = sources[0]['uri']
            else:
                result = xbmcgui.Dialog().select(u'Min\u0151s\u00E9g', [str(source['resolution']) if 'resolution' in source else 'Unknown' for source in sources])
                if result == -1:
                    return
                else:
                    source = sources[result]['uri']
            stream_url = root + '/' + source
            li = xbmcgui.ListItem(path=stream_url)

        elif live_url != []:
            sources = []
            for i in live_url:
                stream_url = i
                try:
                    manifest = net.request(stream_url)
                    sources_temp = m3u8_parser.parse(manifest)
                    root = os.path.dirname(stream_url)
                    for j in sources_temp:
                        j['root'] = root
                    sources.extend(sources_temp)
                except:
                        pass
            sources = sorted(sources, key=lambda x: x['resolution'], reverse=False)
            auto_pick = xbmcaddon.Addon().getSetting('hls_quality') == '0'

            if len(sources) > 0:
                if len(sources) == 1 or auto_pick == True:
                    source = sources[0]['uri']
                else:
                    result = xbmcgui.Dialog().select(u'Min\u0151s\u00E9g', [str(source['resolution']) if 'resolution' in source else 'Unknown' for source in sources])
                    if result == -1:
                        return
                    else:
                        source = sources[result]['uri']
                stream_url = root + '/' + source
            else:
                stream_url = live_url[0]
            li = xbmcgui.ListItem(path=stream_url)
            meta = json.loads(meta)
            li.setInfo(type='Video', infoLabels = meta)
            xbmc.Player().play(stream_url, li)
            return

        if li is None:
            xbmcgui.Dialog().notification(u'Lej\u00E1tsz\u00E1s sikertelen. DRM v\u00E9dett m\u0171sor.', 'RTL Most', time=8000)
            xbmcplugin.setResolvedUrl(int(sys.argv[1]), False, xbmcgui.ListItem())
            return

        stream_url_content = net.request(stream_url)
        meta = json.loads(meta)
        li.setArt({'icon': image, 'thumb': image, 'poster': image, 'tvshow.poster': image})
        li.setInfo(type='Video', infoLabels = meta)
        xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, li)
Exemplo n.º 15
0
    def episodes(self, id, fanart, subcats=None):
        try:
            myfreemiumcodes = json.loads(
                xbmcaddon.Addon().getSetting('myfreemiumcodes'))
        except:
            myfreemiumcodes = {}

        class title_sorter:
            PATTERNS_IN_PRIORITY_ORDER = [
                re.compile(
                    r'^(?P<YEAR>\d{2,4})-(?P<MONTH>\d{2})-(?P<DAY>\d{2})$'
                ),  # Date-only
                re.compile(r'^(?P<SEASON>\d+)\. évad (?P<EPISODE>\d+)\. rész$'
                           ),  # Only Season + Episode
                re.compile(r'^(?P<EPISODE>\d+)\. rész$'),  # Only Episode
                re.compile(
                    r'.* (?P<YEAR>\d{2,4})-(?P<MONTH>\d{2})-(?P<DAY>\d{2})$'
                ),  # Title + Date
                re.compile(
                    r'.* \((?P<YEAR>\d{2,4})-(?P<MONTH>\d{2})-(?P<DAY>\d{2})\)$'
                ),  # Title + (Date)
                re.compile(
                    r'^(?P<YEAR>\d{2,4})-(?P<MONTH>\d{2})-(?P<DAY>\d{2}) .*'
                ),  # Date + Title
                re.compile(
                    r'.* (?P<SEASON>\d+)\. évad (?P<EPISODE>\d+)\. rész$'
                ),  # Title + Season + Episode
                re.compile(r'.* (?P<EPISODE>\d+)\. rész$')  # Title + Episode
            ]

            @classmethod
            def find_first_common_pattern(cls, episodes):
                for pattern in cls.PATTERNS_IN_PRIORITY_ORDER:
                    if all([
                            pattern.match(ep.get('title', '')) is not None
                            for ep in episodes
                    ]):
                        return pattern
                return None

            @classmethod
            def all_match_same_pattern(cls, episodes):
                return cls.find_first_common_pattern(episodes) is not None

            @classmethod
            def sorted(cls, episodes, reverse):
                def key(episode):
                    m = pattern.match(episode.get('title', ''))
                    return tuple(int(i) for i in m.groups())

                pattern = cls.find_first_common_pattern(episodes)
                return sorted(episodes,
                              key=lambda ep: key(ep),
                              reverse=reverse)

        def getClipID(item):
            return int(item['clips'][0]['id'])

        def getEpisode(item):
            return int(item['clips'][0]['product']['episode'])

        def allEpisodeFilled(episodes):
            allFilled = True
            for item in episodes:
                if (item['clips'][0]['product']['episode'] is None):
                    allFilled = False
            return allFilled

        def episodeIsMostPlus(episode):
            return (('freemium_products' in item)
                    and (len(item['freemium_products']) > 0))

        def userIsEligibleToPlayEpisode(episode):
            if not episodeIsMostPlus(episode):
                return True
            for product in item['freemium_products']:
                code = product["code"]
                id = product["id"]
                if code in myfreemiumcodes and id in myfreemiumcodes[code]:
                    return True
            return False

        try:
            subcats = json.loads(subcats)
        except:
            pass
        if subcats == None:
            query = base_url + episode_subcat_link
            subcats = net.request(query % id)
            subcats = [
                i for i in json.loads(subcats)['program_subcats'] if 'id' in i
            ]

        if len(subcats) > 1:
            # the show has multiple seasons or subcategories, list these, and let the user to choose one
            for item in subcats:
                str(item['id'])
                self.addDirectoryItem(
                    py2_encode(item['title']),
                    'episodes&url=%s&fanart=%s&subcats=%s' %
                    (id, fanart, quote_plus(json.dumps([item]))),
                    '',
                    'DefaultFolder.png',
                    Fanart=fanart)
            self.endDirectory(type='seasons')
            return

        query = base_url + episode_link
        episodes = net.request(query % (id, str(subcats[0]['id'])))
        episodes = json.loads(episodes)

        hidePlus = xbmcaddon.Addon().getSetting('hide_plus') == 'true'

        sortedEpisodes = episodes
        if (xbmcaddon.Addon().getSetting('sort_episodes') == 'true'):
            reverseSorting = False
            if (xbmcaddon.Addon().getSetting('sort_reverse') == 'true'):
                reverseSorting = True
            if (allEpisodeFilled(episodes)):
                sortedEpisodes = sorted(episodes,
                                        key=getEpisode,
                                        reverse=reverseSorting)
            elif title_sorter.all_match_same_pattern(episodes):
                sortedEpisodes = title_sorter.sorted(episodes,
                                                     reverse=reverseSorting)
            else:
                sortedEpisodes = sorted(episodes,
                                        key=getClipID,
                                        reverse=reverseSorting)

        hasItemsListed = False
        for item in sortedEpisodes:
            try:
                eligible = userIsEligibleToPlayEpisode(item)
                if (not hidePlus) or eligible:
                    title = py2_encode(item['title'])
                    if not eligible:
                        title = '[COLOR red]' + title + ' [B](Most+)[/B][/COLOR]'
                    plot = py2_encode(item['description'])
                    duration = str(item['duration'])
                    try:
                        thumb = img_link % [
                            i['external_key']
                            for i in item['images'] if i['role'] == 'vignette'
                        ][0]
                    except:
                        thumb = img_link % item['display_image']['external_key']
                    thumb = thumb
                    assets = item['clips'][0].get('assets')
                    clip_id = py2_encode(item['id'])
                    meta = {'title': title, 'plot': plot, 'duration': duration}
                    self.addDirectoryItem(
                        title,
                        'play&url=%s&meta=%s&image=%s' %
                        (quote_plus(clip_id), quote_plus(
                            json.dumps(meta)), thumb),
                        thumb,
                        'DefaultTVShows.png',
                        meta=meta,
                        isFolder=False,
                        Fanart=fanart)
                    hasItemsListed = True
            except:
                pass

        self.endDirectory(type='episodes')

        if hidePlus and not hasItemsListed and len(sortedEpisodes) > 0:
            xbmcgui.Dialog().ok('RTL Most',
                                freemium_subscription_needed_errormsg)
            xbmc.executebuiltin("XBMC.Action(Back)")
Exemplo n.º 16
0
    def episodes(self, id, fanart, subcats=None):
        try: myfreemiumcodes = json.loads(xbmcaddon.Addon().getSetting('myfreemiumcodes'))
        except: myfreemiumcodes = {}

        def getClipID(item):
            return int(item['clips'][0]['id'])
        
        def getEpisode(item):
            return int(item['clips'][0]['product']['episode'])

        def allEpisodeFilled(episodes):
            allFilled = True
            for item in episodes:
                if (item['clips'][0]['product']['episode'] is None):
                    allFilled = False
            return allFilled

        def episodeIsMostPlus(episode):
            return (('freemium_products' in item) and (len(item['freemium_products']) > 0))

        def userIsEligibleToPlayEpisode(episode):
            if not episodeIsMostPlus(episode):
                return True
            for product in item['freemium_products']:
                code = product["code"]
                id = product["id"]
                if code in myfreemiumcodes and id in myfreemiumcodes[code]:
                    return True
            return False

        try: subcats = json.loads(subcats)
        except: pass
        if subcats == None:
            query = base_url + episode_subcat_link.decode('base64')
            subcats = net.request(query % id)
            subcats = [i for i in json.loads(subcats)['program_subcats'] if 'id' in i]

        if len(subcats) > 1:
            # the show has multiple seasons or subcategories, list these, and let the user to choose one
            for item in subcats:
                str(item['id'])
                self.addDirectoryItem(item['title'].encode('utf-8'), 'episodes&url=%s&fanart=%s&subcats=%s' % (id, fanart, json.dumps([item])), '', 'DefaultFolder.png', Fanart=fanart)
            self.endDirectory(type='seasons')
            return

        query = base_url + episode_link.decode('base64')
        episodes = net.request(query % (id, str(subcats[0]['id'])))
        episodes = json.loads(episodes)

        hidePlus = xbmcaddon.Addon().getSetting('hide_plus') == 'true'

        sortedEpisodes = episodes
        if (xbmcaddon.Addon().getSetting('sort_episodes') == 'true'):
            reverseSorting = False
            if (xbmcaddon.Addon().getSetting('sort_reverse') == 'true'):
                reverseSorting = True
            if (allEpisodeFilled(episodes)):
                sortedEpisodes = sorted(episodes, key=getEpisode, reverse=reverseSorting)
            else:
                sortedEpisodes = sorted(episodes, key=getClipID, reverse=reverseSorting)

        hasItemsListed = False
        for item in sortedEpisodes:
            try:
                eligible = userIsEligibleToPlayEpisode(item)
                if (not hidePlus) or eligible:
                    title = item['title'].encode('utf-8')
                    if not eligible:
                        title = '[COLOR red]' + title + ' [B](Most+)[/B][/COLOR]'
                    plot = item['description'].encode('utf-8')
                    duration = str(item['duration'])
                    try: thumb = img_link % [i['external_key'] for i in item['images'] if i['role'] == 'vignette'][0]
                    except: thumb = img_link % item['display_image']['external_key']
                    thumb = thumb.encode('utf-8')
                    assets = item['clips'][0].get('assets')
                    clip_id = item['id'].encode('utf-8')
                    meta = {'title': title, 'plot': plot, 'duration': duration}
                    self.addDirectoryItem(title, 'play&url=%s&meta=%s&image=%s' % (urllib.quote_plus(clip_id), urllib.quote_plus(json.dumps(meta)), thumb), thumb, 'DefaultTVShows.png', meta=meta, isFolder=False, Fanart=fanart)
                    hasItemsListed = True
            except:
                pass

        self.endDirectory(type='episodes')

        if hidePlus and not hasItemsListed and len(sortedEpisodes) > 0:
            xbmcgui.Dialog().ok('RTL Most', freemium_subscription_needed_errormsg.decode('base64').decode('utf-8'))
            xbmc.executebuiltin("XBMC.Action(Back)")
Exemplo n.º 17
0
    def play(self, id, streams, image, meta):
        def sort_by_resolution_pattern(x):
            patterns = ['_1080p_', '_720p_', '_hd_', '_540p_', '_sd_']
            pattern = '|'.join('(%s)' % x for x in patterns)
            match = re.search(pattern, x)
            return match.lastindex if match != None else len(patterns) + 1

        #dash_url = [i for i in streams if 'drmnp.ism/Manifest.mpd' in i]
        dash_url = sorted(
            [i['path'] for i in streams if i['container'] == 'mpd'],
            key=sort_by_resolution_pattern)
        hls_url = sorted(
            [i['path'] for i in streams if i['container'] == 'm3u8'])
        live_url = sorted(
            [i['path'] for i in streams if i['container'] == 'live'])
        li = None
        if dash_url != []:
            # Inputstream and DRM
            #manifest_url = net.request(dash_url[0], redirect=False)
            #stream_url = os.path.dirname(manifest_url) + '/Manifest.mpd'
            stream_url = dash_url[0]

            stream_url = net.request(stream_url, redirect=False)

            parsed = urlparse(stream_url)

            if len(parsed.scheme) == 0 or len(parsed.netloc) == 0:
                stream_url = dash_url[0]

            headers = {
                'x-customer-name': 'rtlhu',
                'authorization': 'Bearer %s' % self.getJwtToken(),
                'Origin': 'https://www.rtlmost.hu'
            }

            token_source = net.request(token_url % (self.uid, id),
                                       headers=headers)
            token_source = json.loads(token_source)
            x_dt_auth_token = py2_encode(token_source['token'])

            license_headers = 'x-dt-auth-token=' + x_dt_auth_token + '&Origin=https://www.rtlmost.hu&Content-Type='
            license_key = 'https://lic.drmtoday.com/license-proxy-widevine/cenc/' + '|' + license_headers + '|R{SSM}|JBlicense'
            DRM = 'com.widevine.alpha'
            PROTOCOL = 'mpd'

            from inputstreamhelper import Helper
            is_helper = Helper(PROTOCOL, drm=DRM)
            if is_helper.check_inputstream():
                li = xbmcgui.ListItem(path=stream_url)
                if sys.version_info < (
                        3, 0
                ):  # if python version < 3 is safe to assume we are running on Kodi 18
                    li.setProperty(
                        'inputstreamaddon',
                        'inputstream.adaptive')  # compatible with Kodi 18 API
                else:
                    li.setProperty(
                        'inputstream', 'inputstream.adaptive'
                    )  # compatible with recent builds Kodi 19 API
                li.setProperty('inputstream.adaptive.manifest_type', PROTOCOL)
                li.setProperty('inputstream.adaptive.license_type', DRM)
                li.setProperty('inputstream.adaptive.license_key', license_key)
                li.setMimeType('application/dash+xml')
                li.setContentLookup(False)
        elif hls_url != []:
            stream_url = hls_url[0]
            manifest_url = net.request(stream_url, redirect=False)

            manifest = net.request(manifest_url)
            sources = m3u8_parser.parse(manifest)
            if len(sources) == 0:
                manifest_url = stream_url
                manifest = net.request(manifest_url)
                sources = m3u8_parser.parse(manifest)

            root = os.path.dirname(manifest_url)

            sources = sorted(sources, key=lambda x: x['resolution'])[::-1]

            auto_pick = xbmcaddon.Addon().getSetting('hls_quality') == '0'

            if len(sources) == 1 or auto_pick == True:
                source = sources[0]['uri']
            else:
                result = xbmcgui.Dialog().select(u'Min\u0151s\u00E9g', [
                    str(source['resolution'])
                    if 'resolution' in source else 'Unknown'
                    for source in sources
                ])
                if result == -1:
                    return
                else:
                    source = sources[result]['uri']
            stream_url = root + '/' + source
            li = xbmcgui.ListItem(path=stream_url)

        elif live_url != []:
            live_url.sort(reverse=True)
            sources = []
            for i in live_url:
                stream_url = i
                try:
                    manifest = net.request(stream_url, timeout=30)
                    sources_temp = m3u8_parser.parse(manifest)
                    root = os.path.dirname(stream_url)
                    for j in sources_temp:
                        j['root'] = root
                    sources.extend(sources_temp)
                    if len(sources) > 0:
                        break
                except:
                    pass
            sources = sorted(sources,
                             key=lambda x: x['resolution'],
                             reverse=False)
            auto_pick = xbmcaddon.Addon().getSetting('hls_quality') == '0'

            if len(sources) > 0:
                if len(sources) == 1 or auto_pick == True:
                    source = sources[0]['uri']
                else:
                    result = xbmcgui.Dialog().select(u'Min\u0151s\u00E9g', [
                        str(source['resolution'])
                        if 'resolution' in source else 'Unknown'
                        for source in sources
                    ])
                    if result == -1:
                        return
                    else:
                        source = sources[result]['uri']
                stream_url = root + '/' + source
            else:
                stream_url = live_url[0]
            li = xbmcgui.ListItem(path=stream_url)
            meta = json.loads(meta)
            li.setInfo(type='Video', infoLabels=meta)
            xbmc.Player().play(stream_url, li)
            return

        if li is None:
            xbmcgui.Dialog().notification(
                u'Lej\u00E1tsz\u00E1s sikertelen. DRM v\u00E9dett m\u0171sor.',
                'RTL Most',
                time=8000)
            xbmcplugin.setResolvedUrl(int(sys.argv[1]), False,
                                      xbmcgui.ListItem())
            return

        meta = json.loads(meta)
        li.setArt({
            'icon': image,
            'thumb': image,
            'poster': image,
            'tvshow.poster': image
        })
        li.setInfo(type='Video', infoLabels=meta)
        xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, li)
Exemplo n.º 18
0
    def episodes(self, id, fanart, subcats=None):

        def getClipID(item):
            return int(item['clips'][0]['id'])
        
        def getEpisode(item):
            return int(item['clips'][0]['product']['episode'])

        def allEpisodeFilled(episodes):
            allFilled = True
            for item in episodes:
                if (item['clips'][0]['product']['episode'] is None):
                    allFilled = False
            return allFilled

        def episodeIsMostPlus(episode):
            return (('freemium_products' in item) and (len(item['freemium_products']) > 0))

        try: subcats = json.loads(subcats)
        except: pass
        if subcats == None:
            query = base_url + episode_subcat_link.decode('base64')
            subcats = net.request(query % id)
            subcats = [str(i['id']) for i in json.loads(subcats)['program_subcats'] if 'id' in i]

        query = base_url + episode_link.decode('base64')
        episodes = net.request(query % (id, subcats[0]))
        episodes = json.loads(episodes)
        
        try: del subcats[0]
        except: subcats = []
        if len(subcats) == 0: subcats = '0'

        hidePlus = xbmcaddon.Addon().getSetting('hide_plus') == 'true'

        sortedEpisodes = episodes
        if (xbmcaddon.Addon().getSetting('sort_episodes') == 'true'):
            reverseSorting = False
            if (xbmcaddon.Addon().getSetting('sort_reverse') == 'true'):
                reverseSorting = True
            if (allEpisodeFilled(episodes)):
                sortedEpisodes = sorted(episodes, key=getEpisode, reverse=reverseSorting)
            else:
                sortedEpisodes = sorted(episodes, key=getClipID, reverse=reverseSorting)
        for item in sortedEpisodes:
            try:
                if ((not hidePlus) or (not episodeIsMostPlus(item))):
                    title = item['title'].encode('utf-8')
                    if (episodeIsMostPlus(item)):
                        title = '[COLOR red]' + title + '[/COLOR]'
                    plot = item['description'].encode('utf-8')
                    duration = str(item['duration'])
                    try: thumb = img_link % [i['external_key'] for i in item['images'] if i['role'] == 'vignette'][0]
                    except: thumb = img_link % item['display_image']['external_key']
                    thumb = thumb.encode('utf-8')
                    assets = item['clips'][0].get('assets')
                    clip_id = item['id'].encode('utf-8')
                    meta = {'title': title, 'plot': plot, 'duration': duration}
                    self.addDirectoryItem(title, 'play&url=%s&meta=%s&image=%s' % (urllib.quote_plus(clip_id), urllib.quote_plus(json.dumps(meta)), thumb), thumb, 'DefaultTVShows.png', meta=meta, isFolder=False, Fanart=fanart)
            except:
                pass
        
        if subcats and subcats != '0':
            self.addDirectoryItem(u'[I]K\u00F6vetkez\u0151 oldal  >>[/I]', 'episodes&url=%s&fanart=%s&subcats=%s' % (id, fanart, json.dumps(subcats)), '', 'DefaultFolder.png', Fanart=fanart)

        self.endDirectory(type='episodes')