Beispiel #1
0
 def setUserPref(self):
     log.info('Setting user preferences')
     # Only try to get user avatar if there is a token
     if self.currToken:
         url = PlexAPI.PlexAPI().GetUserArtworkURL(self.currUser)
         if url:
             window('PlexUserImage', value=url)
Beispiel #2
0
    def loadCurrUser(self, username, userId, usertoken, authenticated=False):
        log.debug('Loading current user')
        doUtils = self.doUtils

        self.currUserId = userId
        self.currToken = usertoken
        self.currServer = self.getServer()
        self.ssl = self.getSSLverify()
        self.sslcert = self.getSSL()

        if authenticated is False:
            log.debug('Testing validity of current token')
            res = PlexAPI.PlexAPI().CheckConnection(self.currServer,
                                                    token=self.currToken,
                                                    verifySSL=self.ssl)
            if res is False:
                # PMS probably offline
                return False
            elif res == 401:
                log.error('Token is no longer valid')
                return 401
            elif res >= 400:
                log.error('Answer from PMS is not as expected. Retrying')
                return False

        # Set to windows property
        window('currUserId', value=userId)
        window('plex_username', value=username)
        # This is the token for the current PMS (might also be '')
        window('pms_token', value=self.currToken)
        # This is the token for plex.tv for the current user
        # Is only '' if user is not signed in to plex.tv
        window('plex_token', value=settings('plexToken'))
        window('plex_restricteduser', value=settings('plex_restricteduser'))
        window('pms_server', value=self.currServer)
        window('plex_machineIdentifier', value=self.machineIdentifier)
        window('plex_servername', value=self.servername)
        window('plex_authenticated', value='true')

        window('useDirectPaths', value='true'
               if settings('useDirectPaths') == "1" else 'false')
        window('plex_force_transcode_pix', value='true'
               if settings('force_transcode_pix') == "1" else 'false')

        # Start DownloadUtils session
        doUtils.startSession(reset=True)
        # self.getAdditionalUsers()
        # Set user preferences in settings
        self.currUser = username
        self.setUserPref()

        # Writing values to settings file
        settings('username', value=username)
        settings('userid', value=userId)
        settings('accessToken', value=usertoken)
        return True
    def __init__(self):
        log.debug('Entering initialsetup class')
        self.clientInfo = clientinfo.ClientInfo()
        self.addonId = self.clientInfo.getAddonId()
        self.doUtils = downloadutils.DownloadUtils().downloadUrl
        self.userClient = userclient.UserClient()
        self.plx = PlexAPI.PlexAPI()
        self.dialog = xbmcgui.Dialog()

        self.server = self.userClient.getServer()
        self.serverid = settings('plex_machineIdentifier')
        # Get Plex credentials from settings file, if they exist
        plexdict = self.plx.GetPlexLoginFromSettings()
        self.myplexlogin = plexdict['myplexlogin'] == 'true'
        self.plexLogin = plexdict['plexLogin']
        self.plexToken = plexdict['plexToken']
        self.plexid = plexdict['plexid']
        if self.plexToken:
            log.debug('Found a plex.tv token in the settings')
Beispiel #4
0
    def authenticate(self):
        log.info('Authenticating user')
        dialog = xbmcgui.Dialog()

        # Give attempts at entering password / selecting user
        if self.retry >= 2:
            log.error("Too many retries to login.")
            window('plex_serverStatus', value="Stop")
            dialog.ok(lang(33001), lang(39023))
            xbmc.executebuiltin(
                'Addon.OpenSettings(plugin.video.plexkodiconnect)')
            return False

        # Get /profile/addon_data
        addondir = tryDecode(
            xbmc.translatePath(self.addon.getAddonInfo('profile')))
        hasSettings = xbmcvfs.exists("%ssettings.xml" % addondir)

        # If there's no settings.xml
        if not hasSettings:
            log.error("Error, no settings.xml found.")
            self.auth = False
            return False
        server = self.getServer()
        # If there is no server we can connect to
        if not server:
            log.info("Missing server information.")
            self.auth = False
            return False

        # If there is a username in the settings, try authenticating
        username = settings('username')
        userId = settings('userid')
        usertoken = settings('accessToken')
        enforceLogin = settings('enforceUserLogin')
        # Found a user in the settings, try to authenticate
        if username and enforceLogin == 'false':
            log.info('Trying to authenticate with old settings')
            if self.loadCurrUser(username,
                                 userId,
                                 usertoken,
                                 authenticated=False):
                # SUCCESS: loaded a user from the settings
                return True
            else:
                # Failed to use the settings - delete them!
                log.info("Failed to use settings credentials. Deleting them")
                settings('username', value='')
                settings('userid', value='')
                settings('accessToken', value='')

        plx = PlexAPI.PlexAPI()

        # Could not use settings - try to get Plex user list from plex.tv
        plextoken = settings('plexToken')
        if plextoken:
            log.info("Trying to connect to plex.tv to get a user list")
            userInfo = plx.ChoosePlexHomeUser(plextoken)
            if userInfo is False:
                # FAILURE: Something went wrong, try again
                self.auth = True
                self.retry += 1
                return False
            username = userInfo['username']
            userId = userInfo['userid']
            usertoken = userInfo['token']
        else:
            log.info("Trying to authenticate without a token")
            username = ''
            userId = ''
            usertoken = ''

        if self.loadCurrUser(username, userId, usertoken, authenticated=False):
            # SUCCESS: loaded a user from the settings
            return True
        else:
            # FAILUR: Something went wrong, try again
            self.auth = True
            self.retry += 1
            return False
Beispiel #5
0
    def loadCurrUser(self, username, userId, usertoken, authenticated=False):
        log.info('Loading current user')
        doUtils = self.doUtils

        self.currUserId = userId
        self.currToken = usertoken
        self.currServer = self.getServer()
        self.ssl = self.getSSLverify()
        self.sslcert = self.getSSL()

        if authenticated is False:
            log.info('Testing validity of current token')
            res = PlexAPI.PlexAPI().CheckConnection(self.currServer,
                                                    token=self.currToken,
                                                    verifySSL=self.ssl)
            if res is False:
                log.error('Answer from PMS is not as expected. Retrying')
                return False
            elif res == 401:
                log.warn('Token is no longer valid')
                return False
            elif res >= 400:
                log.error('Answer from PMS is not as expected. Retrying')
                return False

        # Set to windows property
        window('currUserId', value=userId)
        window('plex_username', value=username)
        # This is the token for the current PMS (might also be '')
        window('pms_token', value=self.currToken)
        # This is the token for plex.tv for the current user
        # Is only '' if user is not signed in to plex.tv
        window('plex_token', value=settings('plexToken'))
        window('plex_restricteduser', value=settings('plex_restricteduser'))
        window('pms_server', value=self.currServer)
        window('plex_machineIdentifier', value=self.machineIdentifier)
        window('plex_servername', value=self.servername)
        window('plex_authenticated', value='true')

        window('useDirectPaths',
               value='true' if settings('useDirectPaths') == "1" else 'false')

        # Start DownloadUtils session
        doUtils.startSession(reset=True)
        # self.getAdditionalUsers()
        # Set user preferences in settings
        self.currUser = username
        self.setUserPref()

        # Writing values to settings file
        settings('username', value=username)
        settings('userid', value=userId)
        settings('accessToken', value=usertoken)

        dialog = xbmcgui.Dialog()
        if settings('connectMsg') == "true":
            if username:
                dialog.notification(
                    heading=addonName,
                    message="Welcome " + username,
                    icon=
                    "special://home/addons/plugin.video.plexkodiconnect/icon.png"
                )
            else:
                dialog.notification(
                    heading=addonName,
                    message="Welcome",
                    icon=
                    "special://home/addons/plugin.video.plexkodiconnect/icon.png"
                )
        return True
Beispiel #6
0
    def ServiceEntryPoint(self):
        # Important: Threads depending on abortRequest will not trigger
        # if profile switch happens more than once.
        monitor = self.monitor
        kodiProfile = xbmc.translatePath("special://profile")

        # Server auto-detect
        initialsetup.InitialSetup().setup()

        # Queue for background sync
        queue = Queue.Queue()

        connectMsg = True if settings('connectMsg') == 'true' else False

        # Initialize important threads
        user = userclient.UserClient()
        ws = wsc.WebSocket(queue)
        library = librarysync.LibrarySync(queue)
        plx = PlexAPI.PlexAPI()

        counter = 0
        while not monitor.abortRequested():

            if window('plex_kodiProfile') != kodiProfile:
                # Profile change happened, terminate this thread and others
                log.warn("Kodi profile was: %s and changed to: %s. "
                         "Terminating old PlexKodiConnect thread." %
                         (kodiProfile, window('plex_kodiProfile')))
                break

            # Before proceeding, need to make sure:
            # 1. Server is online
            # 2. User is set
            # 3. User has access to the server

            if window('plex_online') == "true":
                # Plex server is online
                # Verify if user is set and has access to the server
                if (user.currUser is not None) and user.HasAccess:
                    if not self.kodimonitor_running:
                        # Start up events
                        self.warn_auth = True
                        if connectMsg and self.welcome_msg:
                            # Reset authentication warnings
                            self.welcome_msg = False
                            xbmcgui.Dialog().notification(
                                heading=addonName,
                                message="%s %s" % (lang(33000), user.currUser),
                                icon=
                                "special://home/addons/plugin.video.plexkodiconnect/icon.png",
                                time=2000,
                                sound=False)
                        # Start monitoring kodi events
                        self.kodimonitor_running = kodimonitor.KodiMonitor()

                        # Start the Websocket Client
                        if not self.websocket_running:
                            self.websocket_running = True
                            ws.start()
                        # Start the syncing thread
                        if not self.library_running:
                            self.library_running = True
                            library.start()
                        # Start the Plex Companion thread
                        if not self.plexCompanion_running:
                            self.plexCompanion_running = True
                            plexCompanion = PlexCompanion.PlexCompanion()
                            plexCompanion.start()
                else:
                    if (user.currUser is None) and self.warn_auth:
                        # Alert user is not authenticated and suppress future warning
                        self.warn_auth = False
                        log.warn("Not authenticated yet.")

                    # User access is restricted.
                    # Keep verifying until access is granted
                    # unless server goes offline or Kodi is shut down.
                    while user.HasAccess == False:
                        # Verify access with an API call
                        user.hasAccess()

                        if window('plex_online') != "true":
                            # Server went offline
                            break

                        if monitor.waitForAbort(5):
                            # Abort was requested while waiting. We should exit
                            break
                        xbmc.sleep(50)
            else:
                # Wait until Plex server is online
                # or Kodi is shut down.
                while not monitor.abortRequested():
                    server = user.getServer()
                    if server is False:
                        # No server info set in add-on settings
                        pass
                    elif plx.CheckConnection(server, verifySSL=True) is False:
                        # Server is offline or cannot be reached
                        # Alert the user and suppress future warning
                        if self.server_online:
                            log.error("Server is offline.")
                            window('plex_online', value="false")
                            # Suspend threads
                            window('suspend_LibraryThread', value='true')
                            xbmcgui.Dialog().notification(
                                heading=lang(33001),
                                message="%s %s" % (addonName, lang(33002)),
                                icon="special://home/addons/plugin.video."
                                "plexkodiconnect/icon.png",
                                sound=False)
                        self.server_online = False
                        counter += 1
                        # Periodically check if the IP changed, e.g. per minute
                        if counter > 30:
                            counter = 0
                            setup = initialsetup.InitialSetup()
                            tmp = setup.PickPMS()
                            if tmp is not None:
                                setup.WritePMStoSettings(tmp)
                    else:
                        # Server is online
                        counter = 0
                        if not self.server_online:
                            # Server was offline when Kodi started.
                            # Wait for server to be fully established.
                            if monitor.waitForAbort(5):
                                # Abort was requested while waiting.
                                break
                            # Alert the user that server is online.
                            xbmcgui.Dialog().notification(
                                heading=addonName,
                                message=lang(33003),
                                icon="special://home/addons/plugin.video."
                                "plexkodiconnect/icon.png",
                                time=5000,
                                sound=False)
                        self.server_online = True
                        log.warn("Server %s is online and ready." % server)
                        window('plex_online', value="true")
                        if window('plex_authenticated') == 'true':
                            # Server got offline when we were authenticated.
                            # Hence resume threads
                            window('suspend_LibraryThread', clear=True)

                        # Start the userclient thread
                        if not self.userclient_running:
                            self.userclient_running = True
                            user.start()

                        break

                    if monitor.waitForAbort(2):
                        # Abort was requested while waiting.
                        break

            if monitor.waitForAbort(0.05):
                # Abort was requested while waiting. We should exit
                break

        # Terminating PlexKodiConnect

        # Tell all threads to terminate (e.g. several lib sync threads)
        window('plex_terminateNow', value='true')

        try:
            plexCompanion.stopThread()
        except:
            log.warn('plexCompanion already shut down')

        try:
            library.stopThread()
        except:
            log.warn('Library sync already shut down')

        try:
            ws.stopThread()
        except:
            log.warn('Websocket client already shut down')

        try:
            user.stopThread()
        except:
            log.warn('User client already shut down')

        try:
            downloadutils.DownloadUtils().stopSession()
        except:
            pass

        log.warn("======== STOP %s ========" % addonName)
Beispiel #7
0
    def ServiceEntryPoint(self):
        # Important: Threads depending on abortRequest will not trigger
        # if profile switch happens more than once.
        monitor = self.monitor
        kodiProfile = v.KODI_PROFILE

        # Detect playback start early on
        self.monitor_kodi_play = Monitor_Kodi_Play(self)
        self.monitor_kodi_play.start()

        # Server auto-detect
        initialsetup.InitialSetup().setup()

        # Initialize important threads, handing over self for callback purposes
        self.user = UserClient(self)
        self.ws = WebSocket(self)
        self.library = LibrarySync(self)
        self.plexCompanion = PlexCompanion(self)
        self.playqueue = Playqueue(self)
        self.playback_starter = Playback_Starter(self)
        if settings('enableTextureCache') == "true":
            self.image_cache_thread = Image_Cache_Thread()

        plx = PlexAPI.PlexAPI()

        welcome_msg = True
        counter = 0
        while not monitor.abortRequested():

            if window('plex_kodiProfile') != kodiProfile:
                # Profile change happened, terminate this thread and others
                log.warn("Kodi profile was: %s and changed to: %s. "
                         "Terminating old PlexKodiConnect thread." %
                         (kodiProfile, window('plex_kodiProfile')))
                break

            # Before proceeding, need to make sure:
            # 1. Server is online
            # 2. User is set
            # 3. User has access to the server

            if window('plex_online') == "true":
                # Plex server is online
                # Verify if user is set and has access to the server
                if (self.user.currUser is not None) and self.user.HasAccess:
                    if not self.kodimonitor_running:
                        # Start up events
                        self.warn_auth = True
                        if welcome_msg is True:
                            # Reset authentication warnings
                            welcome_msg = False
                            dialog('notification',
                                   lang(29999),
                                   "%s %s" % (lang(33000), self.user.currUser),
                                   icon='{plex}',
                                   time=2000,
                                   sound=False)
                        # Start monitoring kodi events
                        self.kodimonitor_running = KodiMonitor(self)
                        # Start playqueue client
                        if not self.playqueue_running:
                            self.playqueue_running = True
                            self.playqueue.start()
                        # Start the Websocket Client
                        if not self.ws_running:
                            self.ws_running = True
                            self.ws.start()
                        # Start the syncing thread
                        if not self.library_running:
                            self.library_running = True
                            self.library.start()
                        # Start the Plex Companion thread
                        if not self.plexCompanion_running:
                            self.plexCompanion_running = True
                            self.plexCompanion.start()
                        if not self.playback_starter_running:
                            self.playback_starter_running = True
                            self.playback_starter.start()
                        if (not self.image_cache_thread_running
                                and settings('enableTextureCache') == "true"):
                            self.image_cache_thread_running = True
                            self.image_cache_thread.start()
                else:
                    if (self.user.currUser is None) and self.warn_auth:
                        # Alert user is not authenticated and suppress future
                        # warning
                        self.warn_auth = False
                        log.warn("Not authenticated yet.")

                    # User access is restricted.
                    # Keep verifying until access is granted
                    # unless server goes offline or Kodi is shut down.
                    while self.user.HasAccess is False:
                        # Verify access with an API call
                        self.user.hasAccess()

                        if window('plex_online') != "true":
                            # Server went offline
                            break

                        if monitor.waitForAbort(5):
                            # Abort was requested while waiting. We should exit
                            break
                        sleep(50)
            else:
                # Wait until Plex server is online
                # or Kodi is shut down.
                while not monitor.abortRequested():
                    server = self.user.getServer()
                    if server is False:
                        # No server info set in add-on settings
                        pass
                    elif plx.CheckConnection(server, verifySSL=True) is False:
                        # Server is offline or cannot be reached
                        # Alert the user and suppress future warning
                        if self.server_online:
                            self.server_online = False
                            window('plex_online', value="false")
                            # Suspend threads
                            window('suspend_LibraryThread', value='true')
                            log.error("Plex Media Server went offline")
                            if settings('show_pms_offline') == 'true':
                                dialog('notification',
                                       lang(33001),
                                       "%s %s" % (lang(29999), lang(33002)),
                                       icon='{plex}',
                                       sound=False)
                        counter += 1
                        # Periodically check if the IP changed, e.g. per minute
                        if counter > 20:
                            counter = 0
                            setup = initialsetup.InitialSetup()
                            tmp = setup.PickPMS()
                            if tmp is not None:
                                setup.WritePMStoSettings(tmp)
                    else:
                        # Server is online
                        counter = 0
                        if not self.server_online:
                            # Server was offline when Kodi started.
                            # Wait for server to be fully established.
                            if monitor.waitForAbort(5):
                                # Abort was requested while waiting.
                                break
                            self.server_online = True
                            # Alert the user that server is online.
                            if (welcome_msg is False and
                                    settings('show_pms_offline') == 'true'):
                                dialog('notification',
                                       lang(29999),
                                       lang(33003),
                                       icon='{plex}',
                                       time=5000,
                                       sound=False)
                        log.info("Server %s is online and ready." % server)
                        window('plex_online', value="true")
                        if window('plex_authenticated') == 'true':
                            # Server got offline when we were authenticated.
                            # Hence resume threads
                            window('suspend_LibraryThread', clear=True)

                        # Start the userclient thread
                        if not self.user_running:
                            self.user_running = True
                            self.user.start()

                        break

                    if monitor.waitForAbort(3):
                        # Abort was requested while waiting.
                        break

            if monitor.waitForAbort(0.05):
                # Abort was requested while waiting. We should exit
                break

        # Terminating PlexKodiConnect

        # Tell all threads to terminate (e.g. several lib sync threads)
        window('plex_terminateNow', value='true')
        try:
            self.plexCompanion.stopThread()
        except:
            log.warn('plexCompanion already shut down')
        try:
            self.library.stopThread()
        except:
            log.warn('Library sync already shut down')
        try:
            self.ws.stopThread()
        except:
            log.warn('Websocket client already shut down')
        try:
            self.user.stopThread()
        except:
            log.warn('User client already shut down')
        try:
            downloadutils.DownloadUtils().stopSession()
        except:
            pass

        log.warn("======== STOP %s ========" % v.ADDON_NAME)
Beispiel #8
0
    def loadCurrUser(self, username, userId, usertoken, authenticated=False):
        self.logMsg('Loading current user', 0)
        window = utils.window
        settings = utils.settings
        doUtils = self.doUtils

        self.currUserId = userId
        self.currToken = usertoken
        self.currServer = self.getServer()
        self.ssl = self.getSSLverify()
        self.sslcert = self.getSSL()

        if authenticated is False:
            self.logMsg('Testing validity of current token', 0)
            res = PlexAPI.PlexAPI().CheckConnection(self.currServer,
                                                    token=self.currToken,
                                                    verifySSL=self.ssl)
            if res is False:
                self.logMsg('Answer from PMS is not as expected. Retrying', -1)
                return False
            elif res == 401:
                self.logMsg('Token is no longer valid', -1)
                return False
            elif res >= 400:
                self.logMsg('Answer from PMS is not as expected. Retrying', -1)
                return False

        # Set to windows property
        window('currUserId', value=userId)
        window('plex_username', value=username)
        # This is the token for the current PMS (might also be '')
        window('pms_token', value=self.currToken)
        # This is the token for plex.tv for the current user
        # Is only '' if user is not signed in to plex.tv
        window('plex_token', value=settings('plexToken'))
        window('pms_server', value=self.currServer)
        window('plex_machineIdentifier', value=self.machineIdentifier)
        window('plex_servername', value=self.servername)
        window('plex_authenticated', value='true')
        window('plex_serverowned', value=settings('plex_serverowned'))

        window('useDirectPaths', value='true'
               if utils.settings('useDirectPaths') == "1" else 'false')
        window('replaceSMB', value='true'
               if utils.settings('replaceSMB') == "true" else 'false')
        window('remapSMB', value='true'
               if utils.settings('remapSMB') == "true" else 'false')
        if window('remapSMB') == 'true':
            items = ('movie', 'tv', 'music')
            for item in items:
                # Normalize! Get rid of potential (back)slashes at the end
                org = settings('remapSMB%sOrg' % item)
                new = settings('remapSMB%sNew' % item)
                if org.endswith('\\') or org.endswith('/'):
                    org = org[:-1]
                if new.endswith('\\') or new.endswith('/'):
                    new = new[:-1]
                window('remapSMB%sOrg' % item, value=org)
                window('remapSMB%sNew' % item, value=new)

        # Start DownloadUtils session
        doUtils.startSession(reset=True)
        # self.getAdditionalUsers()
        # Set user preferences in settings
        self.currUser = username
        self.setUserPref()

        # Writing values to settings file
        settings('username', value=username)
        settings('userid', value=userId)
        settings('accessToken', value=usertoken)

        dialog = xbmcgui.Dialog()
        if utils.settings('connectMsg') == "true":
            if username:
                dialog.notification(
                    heading=self.addonName,
                    message="Welcome " + username,
                    icon="special://home/addons/plugin.video.plexkodiconnect/icon.png")
            else:
                dialog.notification(
                    heading=self.addonName,
                    message="Welcome",
                    icon="special://home/addons/plugin.video.plexkodiconnect/icon.png")
        return True
Beispiel #9
0
    def ServiceEntryPoint(self):

        log = self.logMsg
        window = utils.window
        lang = utils.language

        # Important: Threads depending on abortRequest will not trigger
        # if profile switch happens more than once.
        monitor = self.monitor
        kodiProfile = xbmc.translatePath("special://profile")

        # Server auto-detect
        initialsetup.InitialSetup().setup()

        # Queue for background sync
        queue = Queue.Queue(maxsize=200)

        connectMsg = True if utils.settings('connectMsg') == 'true' else False

        # Initialize important threads
        user = userclient.UserClient()
        ws = wsc.WebSocket(queue)
        library = librarysync.LibrarySync(queue)
        kplayer = player.Player()
        xplayer = xbmc.Player()
        plx = PlexAPI.PlexAPI()

        # Sync and progress report
        lastProgressUpdate = datetime.today()

        while not monitor.abortRequested():

            if window('emby_kodiProfile') != kodiProfile:
                # Profile change happened, terminate this thread and others
                log(
                    "Kodi profile was: %s and changed to: %s. Terminating old Emby thread."
                    % (kodiProfile, utils.window('emby_kodiProfile')), 1)

                break

            # Before proceeding, need to make sure:
            # 1. Server is online
            # 2. User is set
            # 3. User has access to the server

            if window('emby_online') == "true":
                # Emby server is online
                # Verify if user is set and has access to the server
                if (user.currUser is not None) and user.HasAccess:
                    # If an item is playing
                    if xplayer.isPlaying():
                        try:
                            # Update and report progress
                            playtime = xplayer.getTime()
                            totalTime = xplayer.getTotalTime()
                            currentFile = kplayer.currentFile

                            # Update positionticks
                            if kplayer.played_info.get(
                                    currentFile) is not None:
                                kplayer.played_info[currentFile][
                                    'currentPosition'] = playtime

                            td = datetime.today() - lastProgressUpdate
                            secDiff = td.seconds

                            # Report progress to Emby server
                            if (secDiff > 3):
                                kplayer.reportPlayback()
                                lastProgressUpdate = datetime.today()

                            elif window('emby_command') == "true":
                                # Received a remote control command that
                                # requires updating immediately
                                window('emby_command', clear=True)
                                kplayer.reportPlayback()
                                lastProgressUpdate = datetime.today()
                        except Exception as e:
                            log(
                                "Exception in Playback Monitor Service: %s" %
                                e, 1)
                            pass
                    else:
                        # Start up events
                        self.warn_auth = True
                        if connectMsg and self.welcome_msg:
                            # Reset authentication warnings
                            self.welcome_msg = False
                            xbmcgui.Dialog().notification(
                                heading=self.addonName,
                                message="%s %s" % (lang(33000), user.currUser),
                                icon=
                                "special://home/addons/plugin.video.plexkodiconnect/icon.png",
                                time=2000,
                                sound=False)
                        # Start monitoring kodi events
                        if not self.kodimonitor_running:
                            self.kodimonitor_running = kodimonitor.KodiMonitor(
                            )

                        # Start the Websocket Client
                        if not self.websocket_running:
                            self.websocket_running = True
                            ws.start()
                        # Start the syncing thread
                        if not self.library_running:
                            self.library_running = True
                            library.start()
                        # Start the Plex Companion thread
                        if not self.plexCompanion_running and \
                                self.runPlexCompanion == "true":
                            self.plexCompanion_running = True
                            plexCompanion = PlexCompanion.PlexCompanion()
                            plexCompanion.start()
                else:
                    if (user.currUser is None) and self.warn_auth:
                        # Alert user is not authenticated and suppress future warning
                        self.warn_auth = False
                        log("Not authenticated yet.", 1)

                    # User access is restricted.
                    # Keep verifying until access is granted
                    # unless server goes offline or Kodi is shut down.
                    while user.HasAccess == False:
                        # Verify access with an API call
                        user.hasAccess()

                        if window('emby_online') != "true":
                            # Server went offline
                            break

                        if monitor.waitForAbort(5):
                            # Abort was requested while waiting. We should exit
                            break
                        xbmc.sleep(50)
            else:
                # Wait until Emby server is online
                # or Kodi is shut down.
                while not monitor.abortRequested():
                    server = user.getServer()
                    if server is False:
                        # No server info set in add-on settings
                        pass
                    elif plx.CheckConnection(server, verifySSL=True) is False:
                        # Server is offline or cannot be reached
                        # Alert the user and suppress future warning
                        if self.server_online:
                            log("Server is offline.", 1)
                            window('emby_online', value="false")
                            # Suspend threads
                            window('suspend_LibraryThread', value='true')

                            xbmcgui.Dialog().notification(
                                heading=lang(33001),
                                message="%s %s" %
                                (self.addonName, lang(33002)),
                                icon="special://home/addons/plugin.video."
                                "plexkodiconnect/icon.png",
                                sound=False)
                        self.server_online = False
                    else:
                        # Server is online
                        if not self.server_online:
                            # Server was offline when Kodi started.
                            # Wait for server to be fully established.
                            if monitor.waitForAbort(5):
                                # Abort was requested while waiting.
                                break
                            # Alert the user that server is online.
                            xbmcgui.Dialog().notification(
                                heading=self.addonName,
                                message=lang(33003),
                                icon="special://home/addons/plugin.video."
                                "plexkodiconnect/icon.png",
                                time=2000,
                                sound=False)
                        self.server_online = True
                        log("Server %s is online and ready." % server, 1)
                        window('emby_online', value="true")
                        if window('plex_authenticated') == 'true':
                            # Server got offline when we were authenticated.
                            # Hence resume threads
                            window('suspend_LibraryThread', clear=True)

                        # Start the userclient thread
                        if not self.userclient_running:
                            self.userclient_running = True
                            user.start()

                        break

                    if monitor.waitForAbort(1):
                        # Abort was requested while waiting.
                        break
                    xbmc.sleep(50)

            if monitor.waitForAbort(1):
                # Abort was requested while waiting. We should exit
                break

        # Terminating PlexKodiConnect

        # Tell all threads to terminate (e.g. several lib sync threads)
        utils.window('plex_terminateNow', value='true')

        try:
            plexCompanion.stopThread()
        except:
            xbmc.log('plexCompanion already shut down')

        try:
            library.stopThread()
        except:
            xbmc.log('Library sync already shut down')

        try:
            ws.stopThread()
        except:
            xbmc.log('Websocket client already shut down')

        try:
            user.stopThread()
        except:
            xbmc.log('User client already shut down')

        try:
            downloadutils.DownloadUtils().stopSession()
        except:
            pass

        log("======== STOP %s ========" % self.addonName, 0)
Beispiel #10
0
 def __init__(self):
     self.clientInfo = clientinfo.ClientInfo()
     self.addonId = self.clientInfo.getAddonId()
     self.doUtils = downloadutils.DownloadUtils().downloadUrl
     self.userClient = userclient.UserClient()
     self.plx = PlexAPI.PlexAPI()
Beispiel #11
0
    def loadCurrUser(self, username, userId, usertoken, authenticated=False):
        log.debug('Loading current user')
        doUtils = self.doUtils

        self.currToken = usertoken
        self.currServer = self.getServer()
        self.ssl = self.getSSLverify()
        self.sslcert = self.getSSL()

        if authenticated is False:
            if self.currServer is None:
                return False
            log.debug('Testing validity of current token')
            res = PlexAPI.PlexAPI().CheckConnection(self.currServer,
                                                    token=self.currToken,
                                                    verifySSL=self.ssl)
            if res is False:
                # PMS probably offline
                return False
            elif res == 401:
                log.error('Token is no longer valid')
                return 401
            elif res >= 400:
                log.error('Answer from PMS is not as expected. Retrying')
                return False

        # Set to windows property
        state.PLEX_USER_ID = userId or None
        state.PLEX_USERNAME = username
        # This is the token for the current PMS (might also be '')
        window('pms_token', value=self.currToken)
        # This is the token for plex.tv for the current user
        # Is only '' if user is not signed in to plex.tv
        window('plex_token', value=settings('plexToken'))
        state.PLEX_TOKEN = settings('plexToken') or None
        window('plex_restricteduser', value=settings('plex_restricteduser'))
        state.RESTRICTED_USER = True \
            if settings('plex_restricteduser') == 'true' else False
        window('pms_server', value=self.currServer)
        window('plex_machineIdentifier', value=self.machineIdentifier)
        window('plex_servername', value=self.servername)
        window('plex_authenticated', value='true')
        state.AUTHENTICATED = True

        window('useDirectPaths',
               value='true' if settings('useDirectPaths') == "1" else 'false')
        state.DIRECT_PATHS = True if settings('useDirectPaths') == "1" \
            else False
        state.INDICATE_MEDIA_VERSIONS = True \
            if settings('indicate_media_versions') == "true" else False
        window('plex_force_transcode_pix',
               value='true'
               if settings('force_transcode_pix') == "1" else 'false')

        # Start DownloadUtils session
        doUtils.startSession(reset=True)
        # self.getAdditionalUsers()
        # Set user preferences in settings
        self.currUser = username
        self.setUserPref()

        # Writing values to settings file
        settings('username', value=username)
        settings('userid', value=userId)
        settings('accessToken', value=usertoken)
        return True