def _update_metadata(self):
        """ Update the metadata for the listings """
        from resources.lib.modules.metadata import Metadata

        # Clear outdated metadata
        kodiutils.invalidate_cache(self.cache_expiry)

        def update_status(_i, _total):
            """ Allow to cancel the background job """
            return self.abortRequested() or not kodiutils.get_setting_bool('metadata_update')

        try:
            success = Metadata().fetch_metadata(callback=update_status)
        except NoLoginException:
            # We have no login yet, but that's okay, we will retry later
            _LOGGER.debug('Skipping background updating since we have no credentials.')
            return

        except Exception as exc:  # pylint: disable=broad-except
            _LOGGER.debug('Skipping background updating since we got an error')
            _LOGGER.exception(exc)
            return

        # Update metadata_last_updated
        if success:
            kodiutils.set_setting('metadata_last_updated', str(int(time())))
 def on_authenticated(self, token):
     self.authorization = token
     set_setting('trakt.authorization', dumps(self.authorization))
     debug('TRAKT Authentication complete: %r' % token)
     self.authDialog.close()
     dok('Trakt', 'Autorizacia uspesna')
     self.update_user()
Esempio n. 3
0
    def getClientId(self):
        clientId = kodiutils.get_setting('clientId')

        if not clientId:
            clientId = uuid.uuid4()
            kodiutils.set_setting('clientId', clientId)

        return clientId
Esempio n. 4
0
def logout():
    requests.post(API_BASE.format('logout'),
                  params={'api_key': API_KEY},
                  data={
                      'api_token': API_TOKEN,
                  },
                  headers=HEADERS)
    kodiutils.set_setting('api_token', '')
    return True
Esempio n. 5
0
def get_uuid():
    uuid = kodiutils.get_setting('uuid')
    if not uuid:
        stringLength = 10
        letters = string.ascii_lowercase
        uuid = ''.join(random.choice(letters) for i in range(stringLength))
        logger.info('Setting Shiri X-UUID to: ' + uuid)
        kodiutils.set_setting('uuid', uuid)
    return uuid
Esempio n. 6
0
        def start_proxy():
            """ Start the Proxy. """
            Proxy.server_inst = TCPServer(('127.0.0.1', 0), Proxy)
            port = Proxy.server_inst.socket.getsockname()[1]
            kodiutils.set_setting('manifest_proxy_port', str(port))
            _LOGGER.debug('Listening on port %s', port)

            # Start listening
            Proxy.server_inst.serve_forever()
def login_espn_plus():
    if not espnplus.have_valid_login_id_token():
        logging.debug('Requesting login id token')
        semaphore = threading.Semaphore(0)
        result_queue = Queue()

        license_plate, ws = espnplus.perform_license_plate_auth_flow(
            semaphore, result_queue)
        progress_dialog = xbmcgui.DialogProgress()
        progress_dialog.create(get_string(40100), get_string(40110),
                               license_plate)
        espnplus.start_websocket_thread(ws)
        times = 0
        sleep_time = 1
        max_time = 180
        max_times = max_time / sleep_time
        # wait a maximum of 3 minutes
        while times < max_times:
            time.sleep(sleep_time)
            canceled = progress_dialog.iscanceled()
            acquired = semaphore.acquire(blocking=False)
            logging.debug('Canceled: %s Acquired: %s' % (canceled, acquired))
            seconds_left = max_time - times * sleep_time
            minutes, seconds = divmod(seconds_left, 60)
            percent = int(times / max_times)
            progress_dialog.update(percent, get_string(40110), license_plate,
                                   get_string(40120) % (minutes, seconds))
            if canceled or acquired:
                break
            times = times + 1
        ws.close()
        progress_dialog.close()

        token = None
        try:
            token = result_queue.get(block=True, timeout=1)
        except Empty as e:
            logging.error('No result from websocket %s', e)

        if token is not None and 'id_token' in token:
            espnplus.handle_license_plate_token(token)
        else:
            dialog = xbmcgui.Dialog()
            dialog.ok(get_string(30037), get_string(40130))
            set_setting('LoggedInToEspnPlus', False)
            return False

    if not espnplus.has_valid_bam_account_access_token():
        espnplus.request_bam_account_access_token()

    logging.debug('Bam token %s' % espnplus.get_bam_account_access_token())
    dialog = xbmcgui.Dialog()
    dialog.ok(get_string(40000), get_string(40101))
    set_setting('LoggedInToEspnPlus', True)
    return True
Esempio n. 8
0
    def clean():
        """ Clear metadata (called from settings) """
        cache_path = kodiutils.get_cache_path()
        _, files = kodiutils.listdir(cache_path)
        for filename in files:
            if not kodiutils.delete(os.path.join(cache_path, filename)):
                return kodiutils.ok_dialog(message=kodiutils.localize(
                    30721))  # Clearing local metadata failed

        kodiutils.set_setting('metadata_last_updated', '0')
        return kodiutils.ok_dialog(
            message=kodiutils.localize(30714))  # Local metadata is cleared
 def _has_credentials_changed():
     """ Check if credentials have changed """
     old_hash = kodiutils.get_setting('credentials_hash')
     new_hash = ''
     if kodiutils.get_setting('username') or kodiutils.get_setting(
             'password'):
         new_hash = hashlib.md5((kodiutils.get_setting('username') +
                                 kodiutils.get_setting('password')
                                 ).encode('utf-8')).hexdigest()
     if new_hash != old_hash:
         kodiutils.set_setting('credentials_hash', new_hash)
         return True
     return False
Esempio n. 10
0
    def _update_metadata(self):
        """ Update the metadata for the listings """
        from resources.lib.modules.metadata import Metadata

        # Clear outdated metadata
        kodiutils.invalidate_cache(self.cache_expiry)

        def update_status(_i, _total):
            """ Allow to cancel the background job """
            return self.abortRequested() or not kodiutils.get_setting_bool('metadata_update')

        success = Metadata().fetch_metadata(callback=update_status)

        # Update metadata_last_updated
        if success:
            kodiutils.set_setting('metadata_last_updated', str(int(time())))
Esempio n. 11
0
    def _update_metadata(self):
        """ Update the metadata for the listings """
        from resources.lib.modules.metadata import Metadata

        def update_status(_i, _total):
            """ Allow to cancel the background job """
            return self.abortRequested(
            ) or not kodiutils.get_setting_bool('metadata_update')

        # Clear metadata that has expired for 30 days
        self._remove_expired_metadata(30 * 24 * 60 * 60)

        # Fetch new metadata
        success = Metadata().fetch_metadata(callback=update_status)

        # Update metadata_last_updated
        if success:
            kodiutils.set_setting('metadata_last_updated', str(int(time())))
    def run(self):
        debug(
            'START SERVICE....................................................................'
        )
        last_changelog = get_setting('system.changelog')

        update_addon()

        if last_changelog != ADDON.getAddonInfo('version'):
            debug('SYSTEM.CHANGELOG: {}'.format(
                ADDON.getAddonInfo('changelog')))
            set_setting('system.changelog',
                        '{}'.format(ADDON.getAddonInfo('version')))
            dtextviewer('', ADDON.getAddonInfo('changelog'))

        if get_setting_as_bool('system.autoexec'):
            try:
                exec_build_in(
                    'ActivateWindow(videos,plugin://{})'.format(ADDON_ID))
            except:
                pass

        if get_setting('kraska.user'):
            kra = Kraska()
            kra.check_user()

        if get_setting_as_bool('system.ws.remote.enable'):
            ws = websocket.WS()
            ws.reconnect()

        self.next_ep = NextEp()

        clean_textures()
        from threading import Thread
        w = Thread(target=player.run)
        w.start()

        while not monitor.abortRequested():
            try:
                self.periodical_check()
            except:
                debug('error: {}'.format(traceback.format_exc()))
                pass
            sleep(1000 * 5)
Esempio n. 13
0
    def run(self):
        """ Background loop for maintenance tasks """
        _LOGGER.debug('Service started')

        kodiutils.set_setting('manifest_proxy_port', None)
        if kodiutils.get_setting_bool('manifest_proxy'):
            _LOGGER.debug('Starting Manifest Proxy...')
            self._proxy_thread = Proxy.start()

        while not self.abortRequested():
            # Stop when abort requested
            if self.waitForAbort(60):
                break

        # Wait for the proxy thread to stop
        if self._proxy_thread and self._proxy_thread.is_alive():
            _LOGGER.debug('Stopping Manifest Proxy...')
            Proxy.stop()

        _LOGGER.debug('Service stopped')
Esempio n. 14
0
    def _update_metadata(self):
        """ Update the metadata for the listings """
        from resources.lib.modules.metadata import Metadata

        # Clear outdated metadata
        kodiutils.invalidate_cache(self.cache_expiry)

        def update_status(_i, _total):
            """ Allow to cancel the background job """
            return self.abortRequested() or not kodiutils.get_setting_bool('metadata_update')

        try:
            success = Metadata().fetch_metadata(callback=update_status)
        except NoLoginException:
            # We have no login yet, but that's okay, we will retry later
            success = True

        # Update metadata_last_updated
        if success:
            kodiutils.set_setting('metadata_last_updated', str(int(time())))
Esempio n. 15
0
    def set_cache_n_update(self, addon_id, addon_epg, addon_channel):
        """Find epgs min. Start and min. Stop time"""
        now = self.getLocalTime()
        max_start = min([
            min([
                dateutil.parser.parse(program['start'])
                for program in programmes
            ],
                default=now) for channel, programmes in addon_epg.items()
        ],
                        default=now)  #earliest first start
        max_stop = min([
            max([
                dateutil.parser.parse(program['stop'])
                for program in programmes
            ],
                default=now) for channel, programmes in addon_epg.items()
        ],
                       default=now)  #earliest last stop

        guide_hours, r = divmod(
            abs(max_start - max_stop).total_seconds(),
            3600)  #amount of guidedata available.
        half_life_hours = round(guide_hours //
                                2)  #guidedata half life (update time).
        next_update = (max_stop - datetime.timedelta(hours=half_life_hours)
                       )  #start update prematurely to assure no gaps in meta.
        cache_life = abs(now - next_update).total_seconds()

        self.cache.set('iptvmanager.epg.%s' % (addon_id),
                       addon_epg,
                       expiration=datetime.timedelta(seconds=cache_life))
        self.cache.set('iptvmanager.channel.%s' % (addon_id),
                       addon_channel,
                       expiration=datetime.timedelta(seconds=cache_life))
        kodiutils.set_setting('%s.next_update' % (addon_id),
                              next_update.strftime('%Y%m%d%H%M%S %z').rstrip())
        _LOGGER.info(
            '%s next update %s, life %s' %
            (addon_id, next_update.strftime('%Y%m%d%H%M%S %z').rstrip(),
             half_life_hours))
    def select_profile(self, key=None):
        """ Show your profiles.

        :type key: str
        """
        profiles = self._auth.get_profiles()

        # Show warning when you have no profiles
        if not profiles:
            # Your account has no profiles defined. Please login on www.streamz.be/streamz and create a profile.
            kodiutils.ok_dialog(message=kodiutils.localize(30703))
            kodiutils.end_of_directory()
            return

        # Select the first profile when you only have one
        if len(profiles) == 1:
            key = profiles[0].key

        # Save the selected profile
        if key:
            profile = [x for x in profiles if x.key == key][0]
            _LOGGER.debug('Setting profile to %s', profile)
            kodiutils.set_setting('profile',
                                  '%s:%s' % (profile.key, profile.product))
            kodiutils.set_setting('profile_name', profile.name)

            kodiutils.redirect(kodiutils.url_for('show_main_menu'))
            return

        # Show profile selection when you have multiple profiles
        listing = [
            TitleItem(
                title=self._get_profile_name(p),
                path=kodiutils.url_for('select_profile', key=p.key),
                art_dict=dict(icon='DefaultUser.png'),
                info_dict=dict(plot=p.name, ),
            ) for p in profiles
        ]

        kodiutils.show_listing(listing, sort=['unsorted'],
                               category=30057)  # Select Profile
Esempio n. 17
0
def login():
    email = kodiutils.get_setting('email')
    password = kodiutils.get_setting('password')
    if not email or not password:
        kodiutils.notification('Missing Credentials',
                               'Enter credentials in settings and try again',
                               time=1000)
    r = requests.post(API_BASE.format('login'),
                      params={'api_key': API_KEY},
                      data={
                          'login_id': email,
                          'pw': password,
                          'type': '1',
                          'device_identifier': '',
                      },
                      headers=HEADERS)
    if r.json()['status'] == 1:
        kodiutils.set_setting('api_token', r.json()['api_token'])
        kodiutils.set_setting("api_token_expiry", 60 * 60 * 24 * 14 + time())
        return True
    else:
        kodiutils.notification('Login Failed',
                               'Login failed, check credentials and try again',
                               time=1000)
Esempio n. 18
0
    def run(self):
        """ Background loop for maintenance tasks """
        _LOGGER.debug('Service started')

        kodiutils.set_setting('manifest_proxy_port', None)
        if kodiutils.get_setting_bool('manifest_proxy'):
            _LOGGER.debug('Starting Manifest Proxy...')
            self._proxy_thread = Proxy.start()

        while not self.abortRequested():
            # Update every `update_interval` after the last update
            if kodiutils.get_setting_bool('metadata_update') and int(kodiutils.get_setting('metadata_last_updated', 0)) + self.update_interval < time():
                self._update_metadata()

            # Stop when abort requested
            if self.waitForAbort(10):
                break

        # Wait for the proxy thread to stop
        if self._proxy_thread and self._proxy_thread.is_alive():
            _LOGGER.debug('Stopping Manifest Proxy...')
            Proxy.stop()

        _LOGGER.debug('Service stopped')
Esempio n. 19
0
def login_tv_provider():
    logging.debug('Authenticate Device')
    if adobe_activate_api.is_authenticated():
        logging.debug('Device already authenticated, skipping authentication')
        dialog = xbmcgui.Dialog()
        dialog.ok(get_string(30037), get_string(30301))
        set_setting('LoggedInToTvProvider', True)
        return True
    else:
        regcode = adobe_activate_api.get_regcode()
        dialog = xbmcgui.Dialog()
        ok = dialog.yesno(get_string(30310), get_string(30320),
                          get_string(30330) % regcode, get_string(30340),
                          get_string(30360), get_string(30350))
        if ok:
            try:
                adobe_activate_api.authenticate(regcode)
                dialog.ok(get_string(30310), get_string(30370))
                set_setting('LoggedInToTvProvider', True)
                return True
            except HTTPError as e:
                dialog.ok(get_string(30037), get_string(30420) % e)
                set_setting('LoggedInToTvProvider', False)
                return False
 def on_token_refreshed(self, response):
     # OAuth token refreshed, save token for future calls
     self.authorization = response
     set_setting('trakt.authorization', dumps(self.authorization))
Esempio n. 21
0
elif mode[0] == 'authenticate':
    print_log('Authenticate Device')
    hgtv_handle = hgtv.HGTV()
    auth_info = hgtv_handle.setupAuthentication()
    if auth_info:
        dialog = xbmcgui.Dialog()
        print_log(str(auth_info))
        ok = dialog.yesno(get_string(30310),
                          get_string(30320) % auth_info['activation_url'],
                          get_string(30330) % auth_info['user_code'],
                          get_string(30340), get_string(30360),
                          get_string(30350))
        if ok:
            print_log(str(hgtv_handle.headers))
            hgtv_handle.checkAuthentication()
            set_setting('LoggedInToTvProvider', True)

elif mode[0] == 'logoutprovider':
    print_log('Deauthenticate Device')
    hgtv_handle = hgtv.HGTV()
    hgtv_handle.deauthorize()
    set_setting('LoggedInToTvProvider', False)

elif mode[0] == 'play':
    url = args.get('playbackUrl', None)
    if url is not None:
        url = url[0]
        if url != 'AUTH_NEEDED':
            hgtv_handle = hgtv.HGTV()
            print_log(url)
            stream_url, txt = hgtv_handle.playURL(url)
Esempio n. 22
0
 def clean():
     """ Clear metadata (called from settings) """
     kodiutils.invalidate_cache()
     kodiutils.set_setting('metadata_last_updated', '0')
     kodiutils.ok_dialog(
         message=kodiutils.localize(30714))  # Local metadata is cleared
Esempio n. 23
0
defaultupcoming = os.path.join(addon_data_path,
                               'resources/media/new_upcoming.png')

# User Agents
UA_PC = 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.81 Safari/537.36'
UA_ATV = 'AppleCoreMedia/1.0.0.13Y234 (Apple TV; U; CPU OS 9_2 like Mac OS X; en_us)'

global_session = requests.Session()

if get_setting_as_bool('DisableSSL'):
    global_session.verify = False

if not get_setting_as_bool('DisableInputStream'):
    # Check that it is enabled
    addon_id = 'inputstream.adaptive'
    rpc_request = {
        "jsonrpc": "2.0",
        "method": "Addons.GetAddonDetails",
        "id": 1,
        "params": {
            "addonid": "%s" % addon_id,
            "properties": ["enabled"]
        }
    }
    result = kodi_json_request(rpc_request)
    if result is None:
        set_setting('DisableInputStream', True)
    else:
        if result['addon']['enabled'] is False:
            set_setting('DisableInputStream', True)
Esempio n. 24
0
def process_playback_url(playback_url, auth_string):
    logging.debug('Playback url %s' % playback_url)
    stream_quality = str(get_setting('StreamQuality'))
    bitrate_limit = int(get_setting('BitrateLimit'))
    logging.debug('Stream Quality %s' % stream_quality)
    try:
        m3u8_obj = m3u8.load(playback_url)
    except Exception as e:
        logging.error('Unable to load m3u8 %s' % e)
        playback_url += '|' + auth_string
        item = xbmcgui.ListItem(path=playback_url)
        return setResolvedUrl(plugin.handle, True, item)

    success = True

    use_inputstream_addon = not get_setting_as_bool('DisableInputStream')

    if not use_inputstream_addon:
        if m3u8_obj.is_variant:
            stream_options = list()
            bandwidth_key = 'bandwidth'
            m3u8_obj.playlists.sort(
                key=lambda playlist: playlist.stream_info.bandwidth,
                reverse=True)
            m3u8_obj.data['playlists'].sort(key=lambda playlist: int(playlist[
                'stream_info'][bandwidth_key]),
                                            reverse=True)
            stream_quality_index = str(get_setting('StreamQualityIndex'))
            stream_index = None
            should_ask = False
            try:
                stream_index = int(stream_quality_index)
                if stream_index < 0 or stream_index >= len(m3u8_obj.playlists):
                    should_ask = True
            except ValueError:
                should_ask = True
            if '0' == stream_quality:  # Best
                stream_index = 0
                should_ask = False
                for playlist in m3u8_obj.data['playlists']:
                    stream_info = playlist['stream_info']
                    bandwidth = int(stream_info[bandwidth_key]) / 1024
                    if bandwidth <= bitrate_limit:
                        break
                    stream_index += 1
            elif '2' == stream_quality:  # Ask everytime
                should_ask = True
            if should_ask:
                for playlist in m3u8_obj.data['playlists']:
                    stream_info = playlist['stream_info']
                    resolution = stream_info['resolution']
                    frame_rate = stream_info[
                        'frame_rate'] if 'frame_rate' in stream_info else 30.0
                    bandwidth = int(int(stream_info[bandwidth_key]) / 1024)
                    if 'average_bandwidth' in stream_info:
                        logging.debug('bandwidth: %s average bandwidth: %s' %
                                      (stream_info['bandwidth'],
                                       stream_info['average_bandwidth']))
                    stream_options.append(
                        get_string(30450) %
                        (resolution, frame_rate, bandwidth))
                dialog = xbmcgui.Dialog()
                stream_index = dialog.select(get_string(30440), stream_options)
                if stream_index < 0:
                    success = False
                else:
                    set_setting('StreamQualityIndex', value=str(stream_index))

            uri = m3u8_obj.playlists[stream_index].uri
            logging.debug('Chose stream %d; %s' % (stream_index, uri))
            if 'http' not in uri[0:4]:
                index_of_last_slash = playback_url.rfind('/')
                uri = playback_url[0:index_of_last_slash] + '/' + uri
            item = xbmcgui.ListItem(path=uri + '|' + auth_string)
            setResolvedUrl(plugin.handle, success, item)
        else:
            item = xbmcgui.ListItem(path=playback_url)
            setResolvedUrl(plugin.handle, success, item)
    else:
        logging.debug('Using inputstream.adaptive addon')
        item = xbmcgui.ListItem(path=playback_url)
        item.setProperty('inputstreamaddon', 'inputstream.adaptive')
        item.setProperty('inputstream.adaptive.manifest_type', 'hls')
        setResolvedUrl(plugin.handle, success, item)
Esempio n. 25
0
def logout():
    os.path.isfile(
        ADDONDATA + 'channels.json') and os.remove(ADDONDATA + 'channels.json')
    kodiutils.set_setting('username', '')
    kodiutils.set_setting('password', '')
Esempio n. 26
0
def check_auth_status(auth_types, packages, resource, network_name):
    logging.debug('Checking auth of %s and %s' % (auth_types, packages))

    if requires_adobe_auth(auth_types):
        # Adobe auth
        if not adobe_activate_api.is_authenticated():
            dialog = xbmcgui.Dialog()
            ret = dialog.yesno(get_string(30038),
                               get_string(30050),
                               yeslabel=get_string(30051),
                               nolabel=get_string(30360))
            if ret:
                authed = auth_routes.login_tv_provider()
                if not authed:
                    return None
            else:
                return None
        try:
            # testing code raise HTTPError(url='test', code=403, msg='no', hdrs=dict(), fp=None)
            logging.debug('getting media token for resource %s' % resource)
            return adobe_activate_api.get_short_media_token(resource)
        except HTTPError as http_exception:
            logging.debug('error getting media token %s' % http_exception)
            if http_exception.code == 410 or http_exception.code == 404 or http_exception.code == 401:
                dialog = xbmcgui.Dialog()
                dialog.ok(get_string(30037), get_string(30840))
                adobe_activate_api.deauthorize()
                return None
            elif http_exception.code == 403:
                # Check for blackout
                dialog = xbmcgui.Dialog()
                ok = dialog.yesno(get_string(30037),
                                  get_string(30900) % http_exception)
                if ok:
                    setting = get_setting_from_channel(network_name)
                    if setting is not None:
                        set_setting(setting, False)
                return None
            else:
                return None
        except adobe_activate_api.AuthorizationException as exception:
            logging.debug('Error authorizating media token %s' % exception)
            if 'message' in exception.resp and 'details' in exception.resp:
                message = exception.resp['message']
                details = exception.resp['details']
                if 'noAuthz' == message:
                    # Channel likely not supported
                    dialog = xbmcgui.Dialog()
                    ok = dialog.yesno(get_string(30037),
                                      get_string(30900) % details)
                    if ok:
                        setting = get_setting_from_channel(network_name)
                        if setting is not None:
                            set_setting(setting, False)
                    return None
            dialog = xbmcgui.Dialog()
            dialog.ok(get_string(30037), get_string(30840))
            adobe_activate_api.deauthorize()
            return None
    elif 'direct' in auth_types:
        # bam authentication
        if not espnplus.can_we_access_without_prompt():
            logging.debug('Invalid token')
            dialog = xbmcgui.Dialog()
            ret = dialog.yesno(get_string(30038),
                               get_string(30060),
                               yeslabel=get_string(30061),
                               nolabel=get_string(30360))
            if ret:
                authed = auth_routes.login_espn_plus()
                if not authed:
                    return None
            else:
                return None
        espnplus.ensure_valid_access_token()

        # Check packages
        entitlements = espnplus.get_entitlements()
        has_entitlement = is_entitled(packages, entitlements)

        if not has_entitlement:
            missing_packages = get_missing_packages(packages, entitlements)
            dialog = xbmcgui.Dialog()
            dialog.ok(get_string(40000),
                      get_string(40270) % ', '.join(missing_packages))

        return espnplus.get_bam_account_access_token()

    elif 'isp' in auth_types:
        return adobe_activate_api.get_device_id()
    logging.error('Unable to handle auth types')
    return None
 def update_user(self):
     data = self.get_user()
     debug('trakt user: {}'.format(dumps(data)))
     user = data['user']['username'] if 'username' in data.get(
         'user', {}) else data['user']['name']
     set_setting('trakt.user', user)
Esempio n. 28
0
def play_video(video_id, channel):
    # remove channel number if available
    if "_" in video_id:
        video_id = video_id.split("_")[1]
    config_url = ""
    if channel == "All Channels Feed" or channel == "":
        # no channel info guess by id
        if not video_id.isdigit():
            #probalby a video from puls4 or atv
            config_url = ids.get_livestream_config_url("puls4_and_atv_at")
        else:
            config_url = ids.get_livestream_config_url("austrian_tv")
    else:
        if channel == "PULS 4" or channel == "ATV":
            config_url = ids.get_livestream_config_url("puls4_and_atv_at")
        else:
            config_url = ids.get_livestream_config_url("austrian_tv")
    config = json.loads(get_url(config_url, cache=True, critical=True))
    mdsV2 = config["mdsclient"]["mdsV2"]
    sources_request_url = mdsV2["baseUrl"]+"vas/live/v2/videos?access_token=%s&client_location=null&client_name=%s&ids=%s" % (mdsV2["accessToken"], mdsV2["clientName"], video_id)
    sources_request = json.loads(get_url(sources_request_url, critical=True))
    log("sources_request: " + str(sources_request))
    protected = sources_request[0]["is_protected"]
    mpd_id = 0
    m3u8_id = 0
    ism_id = 0
    mp4_id = 0
    protocol = ""
    for source in sources_request[0]["sources"]:
        if source["mimetype"] == "text/xml":
            ism_id = source["id"]
        if source["mimetype"] == "application/x-mpegURL":
            m3u8_id = source["id"]
        if source["mimetype"] == "application/dash+xml":
            mpd_id = source["id"]
        if source["mimetype"] == "video/mp4":
            mp4_id = source["id"]
    drm = None
    if not protected:
        if kodiutils.get_setting_as_int('non_drm_format') == 0:
            source_id = mpd_id
            protocol = "mpd"
        elif kodiutils.get_setting_as_int('non_drm_format') == 3:
            source_id = mp4_id
            protocol = "mp4"
        else:
            source_id = m3u8_id
            protocol = "hls"
    else:
        if kodiutils.get_setting("drm") == "0":
            source_id = mpd_id
            protocol = "mpd"
            drm_name = "widevine"
            drm = 'com.widevine.alpha'
        else:
            source_id = ism_id
            protocol = "ism"
            drm_name = "playready"
            drm = 'com.microsoft.playready'

    if protected and LooseVersion('18.0') > LooseVersion(xbmc.getInfoLabel('System.BuildVersion')):
        log("version is: " + xbmc.getInfoLabel('System.BuildVersion'))
        kodiutils.notification('ERROR', kodiutils.get_string(32025))
        setResolvedUrl(plugin.handle, False, ListItem('none'))
        return

    server_request_token = get_video_server_request_token(access_token=mdsV2["accessToken"], client_location="null", client_name=mdsV2["clientName"], video_id=video_id, salt=mdsV2["salt"])
    server_request_url = mdsV2["baseUrl"]+"vas/live/v2/videos/%s/sources?access_token=%s&client_id=%s&client_location=null&client_name=%s" % (video_id, mdsV2["accessToken"], server_request_token, mdsV2["clientName"])
    server_request = json.loads(get_url(server_request_url, critical=True))
    server_id = server_request["server_id"]

    start = ""
    end = ""
    if protected and kodiutils.get_setting("drm") == "0" and kodiutils.get_setting_as_bool("oldformat"):
        start = "0"
        end = "999999999"

    source_url_request_token = get_video_source_request_token(access_token=mdsV2["accessToken"], client_location="null", client_name=mdsV2["clientName"], server_id= server_id, source_id=source_id, video_id=video_id, salt=mdsV2["salt"], start=start, end=end)
    source_url_request_url = mdsV2["baseUrl"]+"vas/live/v2/videos/%s/sources/url?access_token=%s&client_id=%s&client_location=null&client_name=%s&secure_delivery=true&server_id=%s&source_ids=%s" % (video_id, mdsV2["accessToken"], source_url_request_token, mdsV2["clientName"], server_id, source_id)

    if protected and kodiutils.get_setting("drm") == "0"and kodiutils.get_setting_as_bool("oldformat"):
        source_url_request_url += "&subclip_start=0&subclip_end=999999999"

    source_url_request = json.loads(get_url(source_url_request_url, critical=True))
    if not "status_code" in source_url_request or source_url_request["status_code"] != 0:
        log("error on video request: " + str(source_url_request))
        return sys.exit(0)

    playitem = ListItem('none')
    log("selected non drm format: " + kodiutils.get_setting('non_drm_format'))
    log("media url: " + source_url_request["sources"][0]["url"])
    if not protected and (kodiutils.get_setting_as_int('non_drm_format') == 2 or kodiutils.get_setting_as_int('non_drm_format') == 3):
        playitem = ListItem(label=xbmc.getInfoLabel('Container.ShowTitle'), path=source_url_request["sources"][0]["url"]+"|User-Agent=Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36")
        setResolvedUrl(plugin.handle, True, playitem)
    else:
        is_helper = None
        try:
            is_helper = inputstreamhelper.Helper(protocol, drm=drm)
        except Exception as e:
            if str(e) == 'UnsupportedDRMScheme' and drm == 'com.microsoft.playready':
                is_helper = inputstreamhelper.Helper(protocol, drm=None)
                pass
            else:
                kodiutils.notification('ERROR', kodiutils.get_string(32018).format(drm))
        #check for inputstream_addon
        inputstream_installed = False
        if is_helper:
            inputstream_installed = is_helper._has_inputstream()

        if is_helper and not inputstream_installed:
            # ask to install inputstream
            xbmc.executebuiltin('InstallAddon({})'.format(is_helper.inputstream_addon), True)
            inputstream_installed = is_helper._has_inputstream()

        if is_helper and inputstream_installed and is_helper.check_inputstream():
            version = xbmcaddon.Addon('inputstream.adaptive').getAddonInfo('version')
            if not protected and kodiutils.get_setting_as_int('non_drm_format') == 0 and LooseVersion(version) < LooseVersion("2.2.2"):
                # inputstream to old cannot play mpd
                # switch to hls
                kodiutils.set_setting('non_drm_format', 1)
                play_video(video_id, channel)
            elif protected and LooseVersion(version) < LooseVersion("2.2.2"):
                # inputstream to old cannot play mpd
                xbmcgui.Dialog().ok(heading=kodiutils.get_string(32023), line1=kodiutils.get_string(32024))
                setResolvedUrl(plugin.handle, False, ListItem(label='none'))
            else:
                playitem = ListItem(label=xbmc.getInfoLabel('Container.ShowTitle'), path=source_url_request["sources"][0]["url"]+"|User-Agent=Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36")
                playitem.setProperty('inputstreamaddon', is_helper.inputstream_addon)
                playitem.setProperty('inputstream.adaptive.manifest_type', protocol)
                if protected:
                    playitem.setProperty('inputstream.adaptive.license_type', drm)
                    playitem.setProperty('inputstream.adaptive.license_key', source_url_request["drm"]["licenseAcquisitionUrl"] + "?token=" + source_url_request["drm"]["token"] +"|User-Agent=Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36" +'|R{SSM}|')
                setResolvedUrl(plugin.handle, True, playitem)
        else:
            if drm:
                kodiutils.notification('ERROR', kodiutils.get_string(32019).format(drm))
                setResolvedUrl(plugin.handle, False, playitem)
            else:
                if xbmcgui.Dialog().yesno(heading=kodiutils.get_string(32020), line1=kodiutils.get_string(32021), line2=kodiutils.get_string(32022).format(kodiutils.get_string(32110))):
                    if LooseVersion('18.0') > LooseVersion(xbmc.getInfoLabel('System.BuildVersion')):
                        kodiutils.set_setting('non_drm_format', 3)
                    else:
                        kodiutils.set_setting('non_drm_format', 2)
                    play_video(video_id, channel)
                else:
                    setResolvedUrl(plugin.handle, False, playitem)
Esempio n. 29
0
    def select_profile(self, key=None):  # pylint: disable=too-many-return-statements
        """ Show your profiles
        :type key: str
        """
        try:
            profiles = self._auth.get_profiles()
        except InvalidLoginException:
            kodiutils.ok_dialog(message=kodiutils.localize(
                30203))  # Your credentials are not valid!
            kodiutils.open_settings()
            return

        except InvalidTokenException:
            self._auth.logout()
            kodiutils.redirect(kodiutils.url_for('select_profile'))
            return

        except LoginErrorException as exc:
            kodiutils.ok_dialog(message=kodiutils.localize(
                30702,
                code=exc.code))  # Unknown error while logging in: {code}
            kodiutils.open_settings()
            return

        except ApiUpdateRequired:
            kodiutils.ok_dialog(message=kodiutils.localize(
                30705))  # The VTM GO Service has been updated...
            return

        except Exception as exc:  # pylint: disable=broad-except
            kodiutils.ok_dialog(message="%s" % exc)
            return

        # Show warning when you have no profiles
        if not profiles:
            # Your account has no profiles defined. Please login on vtm.be/vtmgo and create a Profile.
            kodiutils.ok_dialog(message=kodiutils.localize(30703))
            kodiutils.end_of_directory()
            return

        # Select the first profile when you only have one
        if len(profiles) == 1:
            key = profiles[0].key

        # Save the selected profile
        if key:
            profile = [x for x in profiles if x.key == key][0]
            _LOGGER.debug('Setting profile to %s', profile)
            kodiutils.set_setting('profile',
                                  '%s:%s' % (profile.key, profile.product))
            kodiutils.set_setting('profile_name', profile.name)

            kodiutils.redirect(kodiutils.url_for('show_main_menu'))
            return

        # Show profile selection when you have multiple profiles
        listing = [
            kodiutils.TitleItem(
                title=self._get_profile_name(p),
                path=kodiutils.url_for('select_profile', key=p.key),
                art_dict=dict(icon='DefaultUser.png'),
                info_dict=dict(plot=p.name, ),
            ) for p in profiles
        ]

        kodiutils.show_listing(listing, sort=['unsorted'],
                               category=30057)  # Select Profile
    def action(self, action, sc):
        from resources.lib.params import params
        debug('trakt action: {} / {}'.format(action, params.args))
        if action == 'trakt.login':
            set_setting_as_bool('trakt.enabled', True)
            self.login()
        elif action == 'trakt.logout':
            set_setting('trakt.authorization', '')
            set_setting('trakt.user', '')
        elif action == 'trakt.list':
            u = 'me' if not params.args.get('user',
                                            None) else params.args.get('user')
            if u == 'me':
                for i in ['watchlist']:
                    itm = {
                        'type': 'action',
                        'title': i,
                        'action': 'trakt.list.items',
                        'id': i,
                        'user': u
                    }
                    item = SCItem(itm)
                    if item.visible:
                        sc.items.append(item.get())

            for l in self.get_lists(user=u):
                # l.name = l.name.encode('utf-8')
                itm = {
                    'type': 'action',
                    'title': l.name,
                    'action': 'trakt.list.items',
                    'id': l.id,
                    'user': u
                }
                item = SCItem(itm)
                if item.visible:
                    sc.items.append(item.get())
        elif action == 'trakt.sync.shows':
            self.sync_local_episodes(last=0, force=True)
        elif action == 'trakt.list.items':
            u = 'me' if not params.args.get('user',
                                            None) else params.args.get('user')
            name = params.args.get('id')
            if name == 'watchlist':
                data = self.get_watchlist(u).json()
            else:
                data = self.get_list_items(name, u).items(parse=False).json()
            items = []
            for i in data:
                t = i.get('type')
                debug('item: {} {}'.format(t, i))
                if t not in ['movie', 'tvshow', 'show']:
                    continue
                sc_type = 1 if t == 'movie' else 3
                data = i.get(t, {})
                ids = data.get('ids')
                tr = ids.get('trakt')
                itm = "{},{}".format(sc_type, tr)
                items.append(itm)
            debug('items: {}'.format(items))
            self.show_items(items, sc)
        else:
            debug('Neznama akcia trakt.tv {}'.format(action))
        sc.succeeded = True
        sc.end()