Пример #1
0
def _device_link():
    start = time.time()
    data = api.device_code()
    monitor = xbmc.Monitor()

    poll_time = int(data['retryInterval'] / 1000)
    max_time = int(data['retryDuration'] / 1000)
    device_token = data['deviceToken']
    code = data['activationCode']

    with gui.progress(_(_.DEVICE_LINK_STEPS,
                        url=config.device_link_url,
                        code=code),
                      heading=_.DEVICE_LINK) as progress:
        while (time.time() - start) < max_time:
            for i in range(poll_time):
                if progress.iscanceled() or monitor.waitForAbort(1):
                    return

                progress.update(int(((time.time() - start) / max_time) * 100))

            result = api.device_login(code, device_token)
            if result:
                return True

            elif result == -1:
                return False
Пример #2
0
    def run(self):

        monitor = xbmc.Monitor()
        token = self.client.config.data['auth.token']
        device_id = self.client.config.data['app.device_id']
        server = self.client.config.data['auth.server']
        server = server.replace(
            'https', "wss") if server.startswith('https') else server.replace(
                'http', "ws")
        wsc_url = "%s/socket?api_key=%s&device_id=%s" % (server, token,
                                                         device_id)

        LOG.info("Websocket url: %s", wsc_url)

        self.wsc = websocket.WebSocketApp(wsc_url,
                                          on_message=self.on_message,
                                          on_error=self.on_error)
        self.wsc.on_open = self.on_open

        while not self.stop:

            self.wsc.run_forever(ping_interval=10)

            if not self.stop and monitor.waitForAbort(5):
                break

        LOG.info("---<[ websocket ]")
Пример #3
0
    def run(self):

        ''' Prepare the request. Request removes the urlencode which is required in this case.
            Use a session allows to use a pool of connections.
        '''
        with requests.Session() as s:
            while True:
                try:
                    url = self.queue.get(timeout=2)
                except Queue.Empty:

                    self.is_done = True
                    LOG.info("--<[ q:artwork/%s ]", id(self))

                    return

                try:
                    req = requests.Request(method='HEAD',
                                           url="http://%s:%s/image/image://%s" % (self.kodi['host'], self.kodi['port'], url),
                                           auth=(self.kodi['username'], self.kodi['password']))
                    prep = req.prepare()
                    prep.url = "http://%s:%s/image/image://%s" % (self.kodi['host'], self.kodi['port'], url)
                    s.send(prep, timeout=(0.01, 0.01))
                    s.content  # release the connection
                except Exception as error:
                    LOG.exception(error)

                self.queue.task_done()

                if xbmc.Monitor().abortRequested():
                    break
def monitor_channel_transcode_playback(context, server, session_id):
    # Logic may appear backward, but this does allow for a failed start to be detected
    # First while loop waiting for start
    if context.settings.playback_monitor_disabled():
        return

    count = 0
    monitor = xbmc.Monitor()
    player = xbmc.Player()

    LOG.debug(
        'Not playing yet...sleeping for up to 20 seconds at 2 second intervals'
    )
    while not player.isPlaying() and not monitor.abortRequested():
        count += 1
        if count >= 10:
            # Waited 20 seconds and still no movie playing - assume it isn't going to..
            return
        if monitor.waitForAbort(2.0):
            return

    LOG.debug('Waiting for playback to finish')
    while player.isPlaying() and not monitor.abortRequested():
        if monitor.waitForAbort(0.5):
            break

    LOG.debug('Playback Stopped')
    LOG.debug('Stopping PMS transcode job with session: %s' % session_id)
    server.stop_transcode_session(session_id)
Пример #5
0
    def run(self):

        monitor = xbmc.Monitor()
        token = self.client.config.data['auth.token']
        device_id = self.client.config.data['app.device_id']
        server = self.client.config.data['auth.server']
        server = server.replace('https://', 'wss://') if server.startswith(
            'https') else server.replace('http://', 'ws://')
        wsc_url = "%s/socket?api_key=%s&device_id=%s" % (server, token,
                                                         device_id)

        LOG.info("Websocket url: %s", wsc_url)

        self.wsc = websocket.WebSocketApp(
            wsc_url,
            on_open=lambda ws: self.on_open(ws),
            on_message=lambda ws, message: self.on_message(ws, message),
            on_error=lambda ws, error: self.on_error(ws, error))

        while not self.stop:

            time.sleep(self.retry_count * 5)
            self.wsc.run_forever(ping_interval=10)

            if not self.stop and monitor.waitForAbort(5):
                break

            # Wait a maximum of 60 seconds before retrying connection
            if self.retry_count < 12:
                self.retry_count += 1

        LOG.info("---<[ websocket ]")
Пример #6
0
def reset_thread(reset_func):
    log.debug('Settings Reset Thread: STARTED')

    monitor    = xbmc.Monitor()
    player     = xbmc.Player()
    sleep_time = 100#ms

    #wait upto 3 seconds for playback to start
    count = 0
    while not monitor.abortRequested():
        if player.isPlaying():
            break

        if count > 3*(1000/sleep_time):
            break

        count += 1
        xbmc.sleep(sleep_time)

    #wait upto 30 seconds for playback to start
    count = 0
    while not monitor.abortRequested():
        if not player.isPlaying() or player.getTime() > 0:
            break

        if count > 30*(1000/sleep_time):
            break

        count += 1
        xbmc.sleep(sleep_time)

    reset_func()

    log.debug('Settings Reset Thread: DONE')
Пример #7
0
 def __init__(self):
     self.myMonitor = xbmc.Monitor()
     self.cache = SimpleCache()
     if not self.chkVersion(): return
     self.lastURL = (REAL_SETTINGS.getSetting("LastURL")
                     or self.buildMain())
     self.lastPath = REAL_SETTINGS.getSetting("LastPath")
     self.selectPath(self.lastURL)
Пример #8
0
 def _init_vars( self ):
     self.SETTINGS = loadSettings()
     self.LW = Logger( preamble='[TVMI Manual]', logdebug=self.SETTINGS['debug'] )
     self.LW.log( ['loaded settings', _logsafe_settings( self.SETTINGS )] )
     self.TVMAZE = tvmaze.API( user=self.SETTINGS['tvmaze_user'], apikey=self.SETTINGS['tvmaze_apikey'] )
     self.TVMCACHEFILE = os.path.join( self.SETTINGS['ADDONDATAPATH'], 'tvm_followed_cache.json' )
     self.DIALOG = xbmcgui.Dialog()
     self.KODIMONITOR = xbmc.Monitor()
Пример #9
0
 def __init__(self, parent_window, token):
     # type: (ConfirmationDialog, Text) -> None
     super(ConfirmationLoop, self).__init__()
     self._parent_window = weakref.proxy(parent_window)  # type: ConfirmationDialog
     self._token = token
     self.username = ''
     self.apikey = ''
     self.error_message = None
     self._monitor = xbmc.Monitor()
     self.stop_event = threading.Event()
Пример #10
0
    def __init__(self):
        try:
            from urllib.parse import urlparse
        except ImportError:
            from urlparse import urlparse

        # argv[0] can contain the entire path, so we limit ourselves to the base url
        pid = urlparse(argv[0])
        self.pluginid = '{}://{}/'.format(pid.scheme, pid.netloc)
        self.pluginhandle = int(argv[1]) if (1 < len(argv)) and self.pluginid else -1

        self._globals['monitor'] = xbmc.Monitor()
        self._globals['addon'] = xbmcaddon.Addon()
        self._globals['dialog'] = xbmcgui.Dialog()
        # self._globals['dialogprogress'] = xbmcgui.DialogProgress()
        self._globals['hasExtRC'] = xbmc.getCondVisibility('System.HasAddon(script.chromium_remotecontrol)')

        self._globals['DATA_PATH'] = py2_decode(xbmc.translatePath(self.addon.getAddonInfo('profile')))
        self._globals['CONFIG_PATH'] = OSPJoin(self._globals['DATA_PATH'], 'config')
        self._globals['HOME_PATH'] = py2_decode(xbmc.translatePath('special://home'))
        self._globals['PLUGIN_PATH'] = py2_decode(self._globals['addon'].getAddonInfo('path'))

        # With main PATHs configured, we initialise the get/write path attributes
        # and generate/retrieve the device ID
        getConfig.configPath = self._globals['CONFIG_PATH']
        writeConfig.configPath = self._globals['CONFIG_PATH']
        self._globals['deviceID'] = self.genID()

        self._globals['__plugin__'] = self._globals['addon'].getAddonInfo('name')
        self._globals['__authors__'] = self._globals['addon'].getAddonInfo('author')
        self._globals['__credits__'] = ""
        self._globals['__version__'] = self._globals['addon'].getAddonInfo('version')

        # OS Detection
        if xbmc.getCondVisibility('system.platform.windows'):
            self._globals['platform'] |= self.OS_WINDOWS
        if xbmc.getCondVisibility('system.platform.linux'):
            self._globals['platform'] |= self.OS_LINUX
        if xbmc.getCondVisibility('system.platform.osx'):
            self._globals['platform'] |= self.OS_OSX
        if xbmc.getCondVisibility('system.platform.android'):
            self._globals['platform'] |= self.OS_ANDROID
        if (xbmcvfs.exists('/etc/os-release')) and ('libreelec' in xbmcvfs.File('/etc/os-release').read()):
            self._globals['platform'] |= self.OS_LE

        # Save the language code for HTTP requests and set the locale for l10n
        loc = getdefaultlocale()[0]
        userAcceptLanguages = 'en-gb{}, en;q=0.5'
        self._globals['userAcceptLanguages'] = userAcceptLanguages.format('') if not loc else '{}, {}'.format(loc.lower().replace('_', '-'), userAcceptLanguages.format(';q=0.75'))

        self._globals['CONTEXTMENU_MULTIUSER'] = [
            (getString(30130, self._globals['addon']).split('…')[0], 'RunPlugin({}?mode=LogIn)'.format(self.pluginid)),
            (getString(30131, self._globals['addon']).split('…')[0], 'RunPlugin({}?mode=removeUser)'.format(self.pluginid)),
            (getString(30132, self._globals['addon']), 'RunPlugin({}?mode=renameUser)'.format(self.pluginid))
        ]
Пример #11
0
def should_stop():
    ''' Checkpoint during the sync process.
    '''
    if xbmc.Monitor().waitForAbort(0.00001):
        return True

    if window('jellyfin_should_stop.bool'):
        LOG.info("exiiiiitttinggg")
        return True

    return not window('jellyfin_online.bool')
Пример #12
0
 class Worker(Thread):
     monitor = xbmc.Monitor()
     
     def run(self):
         while not self.monitor.abortRequested() and not errors:
             try:
                 idx, item = queue.get(block=False)
                 try:
                     results[idx] = func(item)
                     if self.monitor.waitForAbort(0.001): break
                 except Exception as e: errors[idx] = sys.exc_info()
             except Empty: break
Пример #13
0
def start():
    http = HTTP()

    monitor = xbmc.Monitor()
    restart_queued = False

    boot_merge = settings.getBool('boot_merge', False)
    set_kodi_string('_iptv_merge_force_run')

    while not monitor.waitForAbort(1):
        http.start() if settings.getBool('http_api', False) else http.stop()

        forced = get_kodi_string('_iptv_merge_force_run') or 0

        if forced or boot_merge or (settings.getBool('auto_merge', True) and time.time() - userdata.get('last_run', 0) > settings.getInt('reload_time_hours', 12) * 3600):
            set_kodi_string('_iptv_merge_force_run', '1')

            url = router.url_for('run_merge', forced=int(forced))
            dirs, files = xbmcvfs.listdir(url)
            result, msg = int(files[0][0]), unquote_plus(files[0][1:])
            if result:
                restart_queued = True

            userdata.set('last_run', int(time.time()))
            set_kodi_string('_iptv_merge_force_run')

        if restart_queued and settings.getBool('restart_pvr', False):
            if forced: progress = gui.progressbg(heading='Reloading IPTV Simple Client')

            if KODI_VERSION > 18:
                restart_queued = False
                try: xbmcaddon.Addon(IPTV_SIMPLE_ID).setSetting('m3uPathType', '0')
                except Exception as e: pass

            elif forced or (not xbmc.getCondVisibility('Pvr.IsPlayingTv') and not xbmc.getCondVisibility('Pvr.IsPlayingRadio')):
                restart_queued = False
                kodi_rpc('Addons.SetAddonEnabled', {'addonid': IPTV_SIMPLE_ID, 'enabled': False})

                wait_delay = 4
                for i in range(wait_delay):
                    if monitor.waitForAbort(1):
                        break
                    if forced: progress.update((i+1)*int(100/wait_delay))

                kodi_rpc('Addons.SetAddonEnabled', {'addonid': IPTV_SIMPLE_ID, 'enabled': True})

            if forced:
                progress.update(100)
                progress.close()

        boot_merge = False

    http.stop()
Пример #14
0
def reset():
    ''' Reset both the jellyfin database and the kodi database.
    '''
    from views import Views
    views = Views()

    if not dialog("yesno", heading="{jellyfin}", line1=translate(33074)):
        return

    window('jellyfin_should_stop.bool', True)
    count = 10

    while window('jellyfin_sync.bool'):

        LOG.info("Sync is running...")
        count -= 1

        if not count:
            dialog("ok", heading="{jellyfin}", line1=translate(33085))

            return

        if xbmc.Monitor().waitForAbort(1):
            return

    reset_kodi()
    reset_jellyfin()
    views.delete_playlists()
    views.delete_nodes()

    if dialog("yesno", heading="{jellyfin}", line1=translate(33086)):
        reset_artwork()

    addon_data = xbmc.translatePath(
        "special://profile/addon_data/plugin.video.jellyfin/")

    if dialog("yesno", heading="{jellyfin}", line1=translate(33087)):

        xbmcvfs.delete(os.path.join(addon_data, "settings.xml"))
        xbmcvfs.delete(os.path.join(addon_data, "data.json"))
        LOG.info("[ reset settings ]")

    if xbmcvfs.exists(os.path.join(addon_data, "sync.json")):
        xbmcvfs.delete(os.path.join(addon_data, "sync.json"))

    settings('enableMusic.bool', False)
    settings('MinimumSetup', "")
    settings('MusicRescan.bool', False)
    settings('SyncInstallRunDone.bool', False)
    dialog("ok", heading="{jellyfin}", line1=translate(33088))
    xbmc.executebuiltin('RestartApp')
Пример #15
0
def _device_link():
    monitor = xbmc.Monitor()
    serial, code = api.device_code()
    timeout = 600

    with gui.progress(_(_.DEVICE_LINK_STEPS, code=code), heading=_.DEVICE_LINK) as progress:
        for i in range(timeout):
            if progress.iscanceled() or monitor.waitForAbort(1):
                return

            progress.update(int((i / float(timeout)) * 100))

            if i % 5 == 0 and api.device_login(serial, code):
                return True
def run():
    monitor = xbmc.Monitor()
    dialog = SkipIntroDialog('skip_intro.xml',
                             CONFIG['addon'].getAddonInfo('path'),
                             'default',
                             '720p',
                             intro_end=1000000)
    xbmc.executebuiltin('Dialog.Close(all,true)')
    dialog.show()
    monitor.waitForAbort(0.5)
    while not monitor.abortRequested() and dialog.showing:
        if monitor.waitForAbort(0.5):
            break
    dialog.close()
Пример #17
0
def _device_link():
    monitor = xbmc.Monitor()
    timeout = 600

    with api.device_login() as login_progress:
        with gui.progress(_(_.DEVICE_LINK_STEPS, code=login_progress.code), heading=_.DEVICE_LINK) as progress:
            for i in range(timeout):
                if progress.iscanceled() or not login_progress.is_alive() or monitor.waitForAbort(1):
                    break

                progress.update(int((i / float(timeout)) * 100))

            login_progress.stop()
            return login_progress.result
Пример #18
0
 def runDebugged(self, funcName, *args, **kwargs):
     if PY2 or not self.debuggerEnabled:
         funcName(*args, **kwargs)
     else:
         log.info('Starting Debugging Thread')
         thread = threading.Thread(target=funcName,
                                   name='Debug.%s' % self.pluginName,
                                   *args,
                                   **kwargs)
         thread.start()
         cnt = 1
         while not xbmc.Monitor().waitForAbort(
                 timeout=0.25) and thread.is_alive():
             cnt = cnt + 1
             log.info('Debugging Thread stopped')
Пример #19
0
def run(interval=ROUTE_SERVICE_INTERVAL):
    url = url_for(ROUTE_SERVICE)
    cmd = 'XBMC.RunPlugin({0})'.format(url)
    last_run = 0

    monitor = xbmc.Monitor()

    delay = settings.getInt('service_delay', 0) or random.randint(10, 60)
    monitor.waitForAbort(delay)

    while not monitor.abortRequested():
        if time.time() - last_run >= interval:
            xbmc.executebuiltin(cmd)
            last_run = time.time()

        monitor.waitForAbort(random.randint(5, 20))
Пример #20
0
def get_active_dls():
    PLog('get_active_dls_start:')
    import threading

    xbmc.sleep(1000)  # Pause für Datei-OP durch Haupt-PRG

    open(DL_CHECK, 'w').close()  # Lock dl_check_alive anlegen
    PLog("dl_check_alive_angelegt")

    icon = R('icon-downl.png')
    monitor = xbmc.Monitor()
    i = 0
    while not monitor.abortRequested():  # Abbruch durch Kodi
        if os.path.exists(DL_CHECK) == False:  # Abbruch durch Addon
            break
        if SETTINGS.getSetting('pref_dl_cnt') == 'false':  # dopp. Sicherung
            break

        if os.path.exists(DL_CNT):
            with open(DL_CNT, 'r') as f:
                line = f.read()
                cnt, new_len = line.split("|")
                if new_len == '0' or new_len == '':
                    new_len = u"Größe unbekannt"
                else:
                    new_len = humanbytes(new_len)
        else:
            cnt = ''
        # PLog("%d.dlcnt: %s" %  (i, cnt)) # Debug
        if cnt != '' and cnt != '0':
            msg1 = "Downloads"
            msg2 = "Anzahl: %s | %s" % (cnt, new_len)
            xbmcgui.Dialog().notification(msg1, msg2, icon, 2000)
        i = i + 1
        xbmc.sleep(2000)

    PLog('get_active_dls_stop:')
    #--------------------------					# Abbruch durch Addon oder Kodi
    if os.path.exists(DL_CHECK):
        os.remove(DL_CHECK)  # Lock dl_check_alive entfernen
        PLog("dl_check_alive_entfernt")
    if os.path.exists(DL_CNT):
        os.remove(DL_CNT)  # Zähler dl_cnt entfernen
        PLog("dl_cnt_entfernt")

    return
Пример #21
0
def service():
    monitor = xbmc.Monitor()

    prev_kodi_time = None

    while not monitor.waitForAbort(POLL_TIME):
        kodi_time = arrow.now().timestamp

        if not prev_kodi_time:
            prev_kodi_time = kodi_time
            continue

        diff = kodi_time - prev_kodi_time
        if diff > (POLL_TIME + 30) or diff < 0:
            callback()

        prev_kodi_time = kodi_time
Пример #22
0
def service(interval=ROUTE_SERVICE_INTERVAL):
    monitor = xbmc.Monitor()

    delay = settings.getInt('service_delay', 0) or random.randint(10, 60)
    monitor.waitForAbort(delay)

    last_run = 0
    while not monitor.abortRequested():
        if time.time() - last_run >= interval:

            try:
                signals.emit(signals.ON_SERVICE)
            except Exception as e:
                #catch all errors so dispatch doesn't show error
                log.exception(e)

            last_run = time.time()

        monitor.waitForAbort(5)
Пример #23
0
def _device_link():
    start = time.time()
    data = api.device_code()
    monitor = xbmc.Monitor()

    #qr_code_url = data['ImagePath']

    with gui.progress(_(_.DEVICE_LINK_STEPS, code=data['Code']),
                      heading=_.DEVICE_LINK) as progress:
        while (time.time() - start) < data['ExpireDate']:
            for i in range(5):
                if progress.iscanceled() or monitor.waitForAbort(1):
                    return

                progress.update(
                    int(((time.time() - start) / data['ExpireDate']) * 100))

            if api.device_login(data['Code']):
                return True
Пример #24
0
def _device_link():
    start = time.time()
    data = api.device_code()
    monitor = xbmc.Monitor()

    with gui.progress(_(_.DEVICE_LINK_STEPS,
                        url=data['verification_uri'],
                        code=data['user_code']),
                      heading=_.DEVICE_LINK) as progress:
        while (time.time() - start) < data['expires_in']:
            for i in range(data['interval']):
                if progress.iscanceled() or monitor.waitForAbort(1):
                    return

                progress.update(
                    int(((time.time() - start) / data['expires_in']) * 100))

            if api.device_login(data['device_code']):
                return True
Пример #25
0
def root():
    gslug_url = plugin.args.get("url", [""])[-1]
    if gslug_url:
        gslug_referer = plugin.args.get("referer", [gslug_url])[-1]
        quality = plugin.args.get("quality", ["best"])[-1]
        _port = find_free_port()

        LIVE = False
        xbmc.executebuiltin(
            "RunScript({0},{1},{2},{3},{4},{5})".format(
                XBMC_GSLUG_SCRIPT, gslug_url, gslug_referer, user_agent, quality, _port
            )
        )

        playlist_path = "http://127.0.0.1:{0}/{1}/chunks.m3u8".format(
            _port, sha256(gslug_url.encode("utf-8")).hexdigest()
        )

        timeout = 0
        monitor = xbmc.Monitor()
        while not monitor.abortRequested() and (timeout < 10):
            try:
                _r = requests.head(playlist_path, timeout=1)
                _r.raise_for_status()
                LIVE = True
                break
            except Exception:
                if monitor.waitForAbort(1):
                    break
                else:
                    timeout +=1

        if LIVE:
            headers = urlencode([("User-Agent", user_agent,)])
            li = xbmcgui.ListItem(path="{0}|{1}".format(playlist_path, headers))
            li.setMimeType("application/vnd.apple.mpegurl")
            li.setContentLookup(False)
            xbmcplugin.setResolvedUrl(plugin.handle, True, li)
        else:
            xbmcgui.Dialog().notification(plugin.name, "Stream offline", xbmcgui.NOTIFICATION_ERROR)
            xbmcplugin.setResolvedUrl(plugin.handle, False, xbmcgui.ListItem())
Пример #26
0
def wait_for_busy_dialog():
    """
    Wait for busy dialogs to close, starting playback while the busy dialog is active
    could crash Kodi 18 / 19 (pre-alpha)

    Github issues:
        https://github.com/xbmc/xbmc/issues/16756
        https://github.com/xbmc/xbmc/pull/16450  # possible solution

    TODO: remove this function when the above issue is resolved
    """
    monitor = xbmc.Monitor()
    start_time = time.time()
    xbmc.sleep(500)

    def _abort():
        return monitor.abortRequested()

    def _busy():
        return xbmcgui.getCurrentWindowDialogId() in [10138, 10160]

    def _wait():
        LOG.debug('Waiting for busy dialogs to close ...')
        while not _abort() and _busy():
            if monitor.waitForAbort(1):
                break

    while not _abort():
        if _busy():
            _wait()

        if monitor.waitForAbort(1):
            break

        if not _busy():
            break

    LOG.debug('Waited %.2f for busy dialogs to close.' %
              (time.time() - start_time))
    return not _abort() and not _busy()
Пример #27
0
    def run(self):
        service = None

        try:
            service = Service()

            if DELAY and xbmc.Monitor().waitForAbort(DELAY):
                raise Exception("Aborted during startup delay")

            service.service()
        except Exception as error:
            LOG.exception(error)

            if service is not None:
                # TODO: fix this properly as to not match on str()
                if 'ExitService' not in str(error):
                    service.shutdown()

                if 'RestartService' in str(error):
                    service.reload_objects()

            self.exception = error
Пример #28
0
def reset_thread(_id):
    log.debug('Settings Reset Thread: STARTED')

    if ADDON_DEV:
        return

    monitor = xbmc.Monitor()
    player = xbmc.Player()
    sleep_time = 100  #ms

    # wait upto 10 seconds for playback to start
    count = 0
    while not monitor.abortRequested():
        if player.isPlaying():
            break

        if count > 10 * (1000 / sleep_time):
            break

        count += 1
        xbmc.sleep(sleep_time)

    # wait until playback stops
    while not monitor.abortRequested():
        if not player.isPlaying():
            break

        xbmc.sleep(sleep_time)

    reset_settings = common_data.get('reset_settings')
    if reset_settings and reset_settings[0] == _id:
        if reset_settings[1]:
            inputstream.set_settings(reset_settings[2])
        else:
            set_gui_settings(reset_settings[2])

        common_data.delete('reset_settings')

    log.debug('Reset Settings Thread: DONE')
def reset_thread(is_ia, old_settings):
    log.debug('Settings Reset Thread: STARTED')

    monitor = xbmc.Monitor()
    player = xbmc.Player()
    sleep_time = 100  #ms

    #wait upto 10 seconds for playback to start
    count = 0
    while not monitor.abortRequested():
        if player.isPlaying():
            break

        if count > 10 * (1000 / sleep_time):
            break

        count += 1
        xbmc.sleep(sleep_time)

    # wait until playback stops
    while not monitor.abortRequested():
        if not player.isPlaying():
            break

        xbmc.sleep(sleep_time)

    xbmc.sleep(2000)

    #cant set settings while they are being used in kodi 17
    if not player.isPlaying():
        if is_ia:
            inputstream.set_settings(old_settings)
        else:
            set_gui_settings(old_settings)

    log.debug('Settings Reset Thread: DONE')
    xbmc.executebuiltin('Skin.SetString(quality_reset_thread,)')
"""PseudoTV Live / IPTV Manager Integration module"""
import os, re, json
from kodi_six import xbmc, xbmcaddon, xbmcgui

# Plugin Info
ADDON_ID = 'plugin.video.newson'
PROP_KEY = 'PseudoTV_Recommended.%s' % (ADDON_ID)
REAL_SETTINGS = xbmcaddon.Addon(id=ADDON_ID)
ADDON_NAME = REAL_SETTINGS.getAddonInfo('name')
ADDON_PATH = REAL_SETTINGS.getAddonInfo('path')
ADDON_VERSION = REAL_SETTINGS.getAddonInfo('version')
ICON = REAL_SETTINGS.getAddonInfo('icon')
LANGUAGE = REAL_SETTINGS.getLocalizedString
LOGO = os.path.join('special://home/addons/%s/' % (ADDON_ID), 'resources',
                    'images', 'logo.png')
MONITOR = xbmc.Monitor()


def slugify(text):
    non_url_safe = [
        ' ', '"', '#', '$', '%', '&', '+', ',', '/', ':', ';', '=', '?', '@',
        '[', '\\', ']', '^', '`', '{', '|', '}', '~', "'"
    ]
    non_url_safe_regex = re.compile(r'[{}]'.format(''.join(
        re.escape(x) for x in non_url_safe)))
    text = non_url_safe_regex.sub('', text).strip()
    text = u'_'.join(re.split(r'\s+', text))
    return text


def regPseudoTV():