Clean up code for userclient

This commit is contained in:
Croneter 2018-04-18 08:39:41 +02:00
parent 78f3fdb31c
commit 32a880cef0
3 changed files with 93 additions and 89 deletions

View file

@ -141,7 +141,7 @@ class InitialSetup(object):
""" """
def __init__(self): def __init__(self):
LOG.debug('Entering initialsetup class') LOG.debug('Entering initialsetup class')
self.server = UserClient().getServer() self.server = UserClient().get_server()
self.serverid = settings('plex_machineIdentifier') self.serverid = settings('plex_machineIdentifier')
# Get Plex credentials from settings file, if they exist # Get Plex credentials from settings file, if they exist
plexdict = PF.GetPlexLoginFromSettings() plexdict = PF.GetPlexLoginFromSettings()

View file

@ -22,7 +22,9 @@ LOG = getLogger("PLEX." + __name__)
@thread_methods(add_suspends=['SUSPEND_USER_CLIENT']) @thread_methods(add_suspends=['SUSPEND_USER_CLIENT'])
class UserClient(Thread): class UserClient(Thread):
"""
Manage Plex users
"""
# Borg - multiple instances, shared state # Borg - multiple instances, shared state
__shared_state = {} __shared_state = {}
@ -32,100 +34,98 @@ class UserClient(Thread):
self.auth = True self.auth = True
self.retry = 0 self.retry = 0
self.currUser = None self.user = None
self.currServer = None self.has_access = True
self.currToken = None
self.HasAccess = True
self.AdditionalUser = []
self.userSettings = None self.server = None
self.server_name = None
self.machine_identifier = None
self.token = None
self.ssl = None
self.sslcert = None
self.addon = xbmcaddon.Addon() self.addon = xbmcaddon.Addon()
self.doUtils = DU() self.do_utils = None
Thread.__init__(self) Thread.__init__(self)
def getUsername(self): def get_server(self):
""" """
Returns username as unicode Get the current PMS' URL
""" """
username = settings('username')
if not username:
LOG.debug("No username saved, trying to get Plex username")
username = settings('plexLogin')
if not username:
LOG.debug("Also no Plex username found")
return ""
return username
def getServer(self, prefix=True):
# Original host # Original host
self.servername = settings('plex_servername') self.server_name = settings('plex_servername')
HTTPS = settings('https') == "true" https = settings('https') == "true"
host = settings('ipaddress') host = settings('ipaddress')
port = settings('port') port = settings('port')
self.machineIdentifier = settings('plex_machineIdentifier') self.machine_identifier = settings('plex_machineIdentifier')
server = host + ":" + port
if not host: if not host:
LOG.debug("No server information saved.") LOG.debug("No server information saved.")
return False return False
server = host + ":" + port
# If https is true # If https is true
if prefix and HTTPS: if https:
server = "https://%s" % server server = "https://%s" % server
# If https is false # If https is false
elif prefix and not HTTPS: else:
server = "http://%s" % server server = "http://%s" % server
# User entered IP; we need to get the machineIdentifier # User entered IP; we need to get the machineIdentifier
if self.machineIdentifier == '' and prefix is True: if not self.machine_identifier:
self.machineIdentifier = PF.GetMachineIdentifier(server) self.machine_identifier = PF.GetMachineIdentifier(server)
if self.machineIdentifier is None: if not self.machine_identifier:
self.machineIdentifier = '' self.machine_identifier = ''
settings('plex_machineIdentifier', value=self.machineIdentifier) settings('plex_machineIdentifier', value=self.machine_identifier)
LOG.debug('Returning active server: %s', server) LOG.debug('Returning active server: %s', server)
return server return server
def getSSLverify(self): @staticmethod
# Verify host certificate def get_ssl_verify():
"""
Do we need to verify the SSL certificate? Return None if that is the
case, else False
"""
return None if settings('sslverify') == 'true' else False return None if settings('sslverify') == 'true' else False
def getSSL(self): @staticmethod
# Client side certificate def get_ssl_certificate():
"""
Client side certificate
"""
return None if settings('sslcert') == 'None' \ return None if settings('sslcert') == 'None' \
else settings('sslcert') else settings('sslcert')
def setUserPref(self): def set_user_prefs(self):
"""
Load a user's profile picture
"""
LOG.debug('Setting user preferences') LOG.debug('Setting user preferences')
# Only try to get user avatar if there is a token # Only try to get user avatar if there is a token
if self.currToken: if self.token:
url = PF.GetUserArtworkURL(self.currUser) url = PF.GetUserArtworkURL(self.user)
if url: if url:
window('PlexUserImage', value=url) window('PlexUserImage', value=url)
# Set resume point max
# url = "{server}/emby/System/Configuration?format=json"
# result = doUtils.downloadUrl(url)
def hasAccess(self): @staticmethod
def check_access():
# Plex: always return True for now # Plex: always return True for now
return True return True
def loadCurrUser(self, username, userId, usertoken, authenticated=False): def load_user(self, username, user_id, usertoken, authenticated=False):
"""
Load the current user's details for PKC
"""
LOG.debug('Loading current user') LOG.debug('Loading current user')
doUtils = self.doUtils self.token = usertoken
self.server = self.get_server()
self.currToken = usertoken self.ssl = self.get_ssl_verify()
self.currServer = self.getServer() self.sslcert = self.get_ssl_certificate()
self.ssl = self.getSSLverify()
self.sslcert = self.getSSL()
if authenticated is False: if authenticated is False:
if self.currServer is None: if self.server is None:
return False return False
LOG.debug('Testing validity of current token') LOG.debug('Testing validity of current token')
res = PF.check_connection(self.currServer, res = PF.check_connection(self.server,
token=self.currToken, token=self.token,
verifySSL=self.ssl) verifySSL=self.ssl)
if res is False: if res is False:
# PMS probably offline # PMS probably offline
@ -138,7 +138,7 @@ class UserClient(Thread):
return False return False
# Set to windows property # Set to windows property
state.PLEX_USER_ID = userId or None state.PLEX_USER_ID = user_id or None
state.PLEX_USERNAME = username state.PLEX_USERNAME = username
# This is the token for the current PMS (might also be '') # This is the token for the current PMS (might also be '')
window('pms_token', value=usertoken) window('pms_token', value=usertoken)
@ -150,9 +150,9 @@ class UserClient(Thread):
window('plex_restricteduser', value=settings('plex_restricteduser')) window('plex_restricteduser', value=settings('plex_restricteduser'))
state.RESTRICTED_USER = True \ state.RESTRICTED_USER = True \
if settings('plex_restricteduser') == 'true' else False if settings('plex_restricteduser') == 'true' else False
window('pms_server', value=self.currServer) window('pms_server', value=self.server)
window('plex_machineIdentifier', value=self.machineIdentifier) window('plex_machineIdentifier', value=self.machine_identifier)
window('plex_servername', value=self.servername) window('plex_servername', value=self.server_name)
window('plex_authenticated', value='true') window('plex_authenticated', value='true')
state.AUTHENTICATED = True state.AUTHENTICATED = True
@ -166,19 +166,22 @@ class UserClient(Thread):
if settings('force_transcode_pix') == "1" else 'false') if settings('force_transcode_pix') == "1" else 'false')
# Start DownloadUtils session # Start DownloadUtils session
doUtils.startSession(reset=True) self.do_utils = DU()
# self.getAdditionalUsers() self.do_utils.startSession(reset=True)
# Set user preferences in settings # Set user preferences in settings
self.currUser = username self.user = username
self.setUserPref() self.set_user_prefs()
# Writing values to settings file # Writing values to settings file
settings('username', value=username) settings('username', value=username)
settings('userid', value=userId) settings('userid', value=user_id)
settings('accessToken', value=usertoken) settings('accessToken', value=usertoken)
return True return True
def authenticate(self): def authenticate(self):
"""
Authenticate the current user
"""
LOG.debug('Authenticating user') LOG.debug('Authenticating user')
# Give attempts at entering password / selecting user # Give attempts at entering password / selecting user
@ -198,7 +201,7 @@ class UserClient(Thread):
LOG.error("Error, no settings.xml found.") LOG.error("Error, no settings.xml found.")
self.auth = False self.auth = False
return False return False
server = self.getServer() server = self.get_server()
# If there is no server we can connect to # If there is no server we can connect to
if not server: if not server:
LOG.info("Missing server information.") LOG.info("Missing server information.")
@ -213,10 +216,10 @@ class UserClient(Thread):
# Found a user in the settings, try to authenticate # Found a user in the settings, try to authenticate
if username and enforceLogin == 'false': if username and enforceLogin == 'false':
LOG.debug('Trying to authenticate with old settings') LOG.debug('Trying to authenticate with old settings')
answ = self.loadCurrUser(username, answ = self.load_user(username,
userId, userId,
usertoken, usertoken,
authenticated=False) authenticated=False)
if answ is True: if answ is True:
# SUCCESS: loaded a user from the settings # SUCCESS: loaded a user from the settings
return True return True
@ -248,7 +251,7 @@ class UserClient(Thread):
userId = '' userId = ''
usertoken = '' usertoken = ''
if self.loadCurrUser(username, userId, usertoken, authenticated=False): if self.load_user(username, userId, usertoken, authenticated=False):
# SUCCESS: loaded a user from the settings # SUCCESS: loaded a user from the settings
return True return True
# Something went wrong, try again # Something went wrong, try again
@ -256,9 +259,12 @@ class UserClient(Thread):
self.retry += 1 self.retry += 1
return False return False
def resetClient(self): def reset_client(self):
"""
Reset all user settings
"""
LOG.debug("Reset UserClient authentication.") LOG.debug("Reset UserClient authentication.")
self.doUtils.stopSession() self.do_utils.stopSession()
window('plex_authenticated', clear=True) window('plex_authenticated', clear=True)
state.AUTHENTICATED = False state.AUTHENTICATED = False
@ -279,13 +285,16 @@ class UserClient(Thread):
settings('userid', value='') settings('userid', value='')
settings('accessToken', value='') settings('accessToken', value='')
self.currToken = None self.token = None
self.auth = True self.auth = True
self.currUser = None self.user = None
self.retry = 0 self.retry = 0
def run(self): def run(self):
"""
Do the work
"""
LOG.info("----===## Starting UserClient ##===----") LOG.info("----===## Starting UserClient ##===----")
stopped = self.stopped stopped = self.stopped
suspended = self.suspended suspended = self.suspended
@ -299,19 +308,14 @@ class UserClient(Thread):
sleep(500) sleep(500)
continue continue
# Verify the connection status to server
elif state.PMS_STATUS == "restricted":
# Parental control is restricting access
self.HasAccess = False
elif state.PMS_STATUS == "401": elif state.PMS_STATUS == "401":
# Unauthorized access, revoke token # Unauthorized access, revoke token
state.PMS_STATUS = 'Auth' state.PMS_STATUS = 'Auth'
window('plex_serverStatus', value='Auth') window('plex_serverStatus', value='Auth')
self.resetClient() self.reset_client()
sleep(3000) sleep(3000)
if self.auth and (self.currUser is None): if self.auth and (self.user is None):
# Try to authenticate user # Try to authenticate user
if not state.PMS_STATUS or state.PMS_STATUS == "Auth": if not state.PMS_STATUS or state.PMS_STATUS == "Auth":
# Set auth flag because we no longer need # Set auth flag because we no longer need
@ -320,16 +324,16 @@ class UserClient(Thread):
if self.authenticate(): if self.authenticate():
# Successfully authenticated and loaded a user # Successfully authenticated and loaded a user
LOG.info("Successfully authenticated!") LOG.info("Successfully authenticated!")
LOG.info("Current user: %s", self.currUser) LOG.info("Current user: %s", self.user)
LOG.info("Current userId: %s", state.PLEX_USER_ID) LOG.info("Current userId: %s", state.PLEX_USER_ID)
self.retry = 0 self.retry = 0
state.SUSPEND_LIBRARY_THREAD = False state.SUSPEND_LIBRARY_THREAD = False
window('plex_serverStatus', clear=True) window('plex_serverStatus', clear=True)
state.PMS_STATUS = False state.PMS_STATUS = False
if not self.auth and (self.currUser is None): if not self.auth and (self.user is None):
# Loop if no server found # Loop if no server found
server = self.getServer() server = self.get_server()
# The status Stop is for when user cancelled password dialog. # The status Stop is for when user cancelled password dialog.
# Or retried too many times # Or retried too many times

View file

@ -135,7 +135,7 @@ class Service():
if window('plex_online') == "true": if window('plex_online') == "true":
# Plex server is online # Plex server is online
# Verify if user is set and has access to the server # Verify if user is set and has access to the server
if (self.user.currUser is not None) and self.user.HasAccess: if (self.user.currUser is not None) and self.user.has_access:
if not self.kodimonitor_running: if not self.kodimonitor_running:
# Start up events # Start up events
self.warn_auth = True self.warn_auth = True
@ -187,9 +187,9 @@ class Service():
# User access is restricted. # User access is restricted.
# Keep verifying until access is granted # Keep verifying until access is granted
# unless server goes offline or Kodi is shut down. # unless server goes offline or Kodi is shut down.
while self.user.HasAccess is False: while self.user.has_access is False:
# Verify access with an API call # Verify access with an API call
self.user.hasAccess() self.user.check_access()
if window('plex_online') != "true": if window('plex_online') != "true":
# Server went offline # Server went offline
@ -202,7 +202,7 @@ class Service():
# Wait until Plex server is online # Wait until Plex server is online
# or Kodi is shut down. # or Kodi is shut down.
while not self.__stop_PKC(): while not self.__stop_PKC():
server = self.user.getServer() server = self.user.get_server()
if server is False: if server is False:
# No server info set in add-on settings # No server info set in add-on settings
pass pass