PlexKodiConnect/resources/lib/userclient.py

463 lines
15 KiB
Python
Raw Normal View History

2015-12-25 07:07:00 +11:00
# -*- coding: utf-8 -*-
2016-02-20 06:03:06 +11:00
###############################################################################
2015-12-25 07:07:00 +11:00
import threading
import xbmc
import xbmcgui
import xbmcaddon
import xbmcvfs
import utils
import downloadutils
2015-12-28 03:12:46 +11:00
import PlexAPI
2016-02-20 06:03:06 +11:00
###############################################################################
2015-12-25 07:07:00 +11:00
2016-01-27 03:20:13 +11:00
@utils.logging
2016-03-04 23:34:30 +11:00
@utils.ThreadMethodsAdditionalSuspend('suspend_Userclient')
2016-01-27 01:13:03 +11:00
@utils.ThreadMethods
2015-12-25 07:07:00 +11:00
class UserClient(threading.Thread):
# Borg - multiple instances, shared state
2016-01-25 20:36:24 +11:00
__shared_state = {}
2015-12-25 07:07:00 +11:00
auth = True
retry = 0
currUser = None
currUserId = None
currServer = None
currToken = None
HasAccess = True
AdditionalUser = []
userSettings = None
def __init__(self):
2016-01-25 20:36:24 +11:00
self.__dict__ = self.__shared_state
2015-12-25 07:07:00 +11:00
self.addon = xbmcaddon.Addon()
self.doUtils = downloadutils.DownloadUtils()
2016-01-13 03:23:55 +11:00
2015-12-25 07:07:00 +11:00
threading.Thread.__init__(self)
def getAdditionalUsers(self):
additionalUsers = utils.settings('additionalUsers')
2016-02-20 06:03:06 +11:00
2015-12-25 07:07:00 +11:00
if additionalUsers:
self.AdditionalUser = additionalUsers.split(',')
def getUsername(self):
"""
Returns username as unicode
"""
2015-12-25 07:07:00 +11:00
username = utils.settings('username').decode('utf-8')
2015-12-25 07:07:00 +11:00
if not username:
2016-03-04 23:34:30 +11:00
self.logMsg("No username saved, trying to get Plex username", 0)
username = utils.settings('plexLogin').decode('utf-8')
2016-03-04 23:34:30 +11:00
if not username:
self.logMsg("Also no Plex username found", 0)
return ""
2015-12-25 07:07:00 +11:00
return username
def getLogLevel(self):
try:
logLevel = int(utils.settings('logLevel'))
except ValueError:
logLevel = 0
2016-02-20 06:03:06 +11:00
2015-12-25 07:07:00 +11:00
return logLevel
2016-03-04 23:34:30 +11:00
def getUserId(self, username=None):
2015-12-25 07:07:00 +11:00
2016-02-17 19:13:37 +11:00
log = self.logMsg
window = utils.window
settings = utils.settings
2016-03-04 23:34:30 +11:00
if username is None:
username = self.getUsername()
2016-02-17 19:13:37 +11:00
w_userId = window('emby_currUser')
s_userId = settings('userId')
2015-12-25 07:07:00 +11:00
# Verify the window property
if w_userId:
if not s_userId:
# Save access token if it's missing from settings
settings('userId', value=w_userId)
log("Returning userId %s from WINDOW for username %s"
% (w_userId, username), 0)
2015-12-25 07:07:00 +11:00
return w_userId
# Verify the settings
elif s_userId:
log("Returning userId %s from SETTINGS for username %s"
% (w_userId, username), 0)
2015-12-25 07:07:00 +11:00
return s_userId
# No userId found
log("No userId saved. Trying to get Plex to use instead", 0)
plexId = settings('plexid')
if not plexId:
log('Also no Plex ID found in settings', 0)
return ''
log('Using Plex ID %s as userid for username %s'
% (plexId, username), 0)
settings('userId', value=plexId)
return plexId
2015-12-25 07:07:00 +11:00
def getServer(self, prefix=True):
2016-02-17 19:13:37 +11:00
settings = utils.settings
2016-03-04 23:34:30 +11:00
# Original host
HTTPS = settings('https') == "true"
host = settings('ipaddress')
port = settings('port')
2015-12-25 07:07:00 +11:00
server = host + ":" + port
2016-02-20 06:03:06 +11:00
2015-12-25 07:07:00 +11:00
if not host:
self.logMsg("No server information saved.", 2)
return False
# If https is true
if prefix and HTTPS:
server = "https://%s" % server
return server
# If https is false
elif prefix and not HTTPS:
server = "http://%s" % server
return server
# If only the host:port is required
elif not prefix:
return server
2016-03-04 23:34:30 +11:00
def getToken(self, username=None, userId=None):
2015-12-25 07:07:00 +11:00
2016-02-17 19:13:37 +11:00
log = self.logMsg
window = utils.window
settings = utils.settings
2016-03-04 23:34:30 +11:00
if username is None:
username = self.getUsername()
if userId is None:
userId = self.getUserId()
2016-02-17 19:13:37 +11:00
w_token = window('emby_accessToken%s' % userId)
s_token = settings('accessToken')
2016-02-20 06:03:06 +11:00
2015-12-25 07:07:00 +11:00
# Verify the window property
if w_token:
if not s_token:
# Save access token if it's missing from settings
2016-02-17 19:13:37 +11:00
settings('accessToken', value=w_token)
log("Returning accessToken from WINDOW for username: %s "
"accessToken: xxxx" % username, 2)
2015-12-25 07:07:00 +11:00
return w_token
# Verify the settings
elif s_token:
log("Returning accessToken from SETTINGS for username: %s "
"accessToken: xxxx" % username, 2)
window('emby_accessToken%s' % userId, value=s_token)
2015-12-25 07:07:00 +11:00
return s_token
else:
2016-02-17 19:13:37 +11:00
log("No token found.", 1)
2015-12-25 07:07:00 +11:00
return ""
def getSSLverify(self):
# Verify host certificate
2016-02-17 19:13:37 +11:00
settings = utils.settings
s_sslverify = settings('sslverify')
if settings('altip') == "true":
s_sslverify = settings('secondsslverify')
2015-12-25 07:07:00 +11:00
if s_sslverify == "true":
return True
else:
return False
def getSSL(self):
# Client side certificate
2016-02-17 19:13:37 +11:00
settings = utils.settings
s_cert = settings('sslcert')
if settings('altip') == "true":
s_cert = settings('secondsslcert')
2015-12-25 07:07:00 +11:00
if s_cert == "None":
return None
else:
return s_cert
def setUserPref(self):
2016-03-04 23:34:30 +11:00
self.logMsg('Setting user preferences', 0)
2015-12-28 20:35:27 +11:00
url = PlexAPI.PlexAPI().GetUserArtworkURL(self.currUser)
if url:
2015-12-28 21:04:28 +11:00
utils.window('EmbyUserImage', value=url)
2015-12-25 07:07:00 +11:00
# Set resume point max
2015-12-28 20:35:27 +11:00
# url = "{server}/emby/System/Configuration?format=json"
# result = doUtils.downloadUrl(url)
2015-12-25 07:07:00 +11:00
2015-12-28 20:35:27 +11:00
# utils.settings('markPlayed', value=str(result['MaxResumePct']))
2015-12-25 07:07:00 +11:00
def getPublicUsers(self):
server = self.getServer()
# Get public Users
url = "%s/emby/Users/Public?format=json" % server
result = self.doUtils.downloadUrl(url, authenticate=False)
2016-02-20 06:03:06 +11:00
2015-12-25 07:07:00 +11:00
if result != "":
return result
else:
# Server connection failed
return False
def hasAccess(self):
2016-02-20 06:03:06 +11:00
# Plex: always return True for now
return True
2015-12-25 07:07:00 +11:00
# hasAccess is verified in service.py
2016-02-17 19:13:37 +11:00
log = self.logMsg
window = utils.window
2015-12-25 07:07:00 +11:00
url = "{server}/emby/Users?format=json"
result = self.doUtils.downloadUrl(url)
2016-02-20 06:03:06 +11:00
2015-12-25 07:07:00 +11:00
if result == False:
# Access is restricted, set in downloadutils.py via exception
2016-02-17 19:13:37 +11:00
log("Access is restricted.", 1)
2015-12-25 07:07:00 +11:00
self.HasAccess = False
2016-02-20 06:03:06 +11:00
2016-02-17 19:13:37 +11:00
elif window('emby_online') != "true":
2015-12-25 07:07:00 +11:00
# Server connection failed
pass
2016-02-17 19:13:37 +11:00
elif window('emby_serverStatus') == "restricted":
log("Access is granted.", 1)
2015-12-25 07:07:00 +11:00
self.HasAccess = True
2016-02-17 19:13:37 +11:00
window('emby_serverStatus', clear=True)
xbmcgui.Dialog().notification(
self.addonName,
utils.language(33007).encode('utf-8'))
2015-12-25 07:07:00 +11:00
def loadCurrUser(self, authenticated=False):
2016-03-04 23:34:30 +11:00
self.logMsg('Loading current user', 0)
2016-02-17 19:13:37 +11:00
window = utils.window
2015-12-25 07:07:00 +11:00
doUtils = self.doUtils
username = self.getUsername()
userId = self.getUserId()
2016-02-20 06:03:06 +11:00
2015-12-25 07:07:00 +11:00
self.currUserId = userId
self.currServer = self.getServer()
self.currToken = self.getToken()
2016-02-20 06:03:06 +11:00
self.machineIdentifier = utils.settings('plex_machineIdentifier')
2015-12-25 07:07:00 +11:00
self.ssl = self.getSSLverify()
self.sslcert = self.getSSL()
2016-02-20 06:03:06 +11:00
if authenticated is False:
2016-03-04 23:34:30 +11:00
self.logMsg('Testing validity of current token', 0)
2016-02-20 06:03:06 +11:00
window('emby_currUser', value=userId)
window('plex_username', value=username)
window('emby_accessToken%s' % userId, value=self.currToken)
2016-03-04 23:34:30 +11:00
res = PlexAPI.PlexAPI().CheckConnection(
self.currServer, self.currToken)
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)
2015-12-25 07:07:00 +11:00
self.resetClient()
return False
2016-03-04 23:34:30 +11:00
elif res >= 400:
self.logMsg('Answer from PMS is not as expected. Retrying', -1)
return False
2015-12-25 07:07:00 +11:00
# Set to windows property
2016-02-20 06:03:06 +11:00
window('emby_currUser', value=userId)
window('plex_username', value=username)
window('emby_accessToken%s' % userId, value=self.currToken)
window('emby_server%s' % userId, value=self.currServer)
window('plex_machineIdentifier', value=self.machineIdentifier)
2015-12-25 07:07:00 +11:00
2016-03-04 23:34:30 +11:00
window('emby_serverStatus', clear=True)
window('suspend_LibraryThread', clear=True)
2015-12-25 07:07:00 +11:00
# Set DownloadUtils values
doUtils.setUsername(username)
doUtils.setUserId(self.currUserId)
doUtils.setServer(self.currServer)
doUtils.setToken(self.currToken)
doUtils.setSSL(self.ssl, self.sslcert)
# parental control - let's verify if access is restricted
2015-12-28 20:35:27 +11:00
# self.hasAccess()
2015-12-25 07:07:00 +11:00
# Start DownloadUtils session
doUtils.startSession()
2016-03-04 01:28:44 +11:00
# self.getAdditionalUsers()
2015-12-25 07:07:00 +11:00
# Set user preferences in settings
self.currUser = username
self.setUserPref()
2015-12-28 21:04:28 +11:00
return True
2015-12-25 07:07:00 +11:00
def authenticate(self):
2016-02-17 19:13:37 +11:00
log = self.logMsg
2016-03-04 23:34:30 +11:00
log('Authenticating user', 1)
2016-02-17 19:13:37 +11:00
lang = utils.language
window = utils.window
settings = utils.settings
dialog = xbmcgui.Dialog()
2015-12-25 07:07:00 +11:00
# Get /profile/addon_data
addondir = xbmc.translatePath(self.addon.getAddonInfo('profile')).decode('utf-8')
hasSettings = xbmcvfs.exists("%ssettings.xml" % addondir)
# If there's no settings.xml
if not hasSettings:
2016-03-04 23:34:30 +11:00
log("Error, no settings.xml found.", -1)
2015-12-25 07:07:00 +11:00
self.auth = False
return
2016-03-04 23:34:30 +11:00
server = self.getServer()
2015-12-25 07:07:00 +11:00
# If no user information
2016-03-04 23:34:30 +11:00
if not server:
2016-02-20 06:03:06 +11:00
log("Missing server information.", 0)
2015-12-25 07:07:00 +11:00
self.auth = False
return
2016-03-04 23:34:30 +11:00
username = self.getUsername()
userId = self.getUserId(username)
# If there's a token, load the user
if self.getToken(username=username, userId=userId):
if self.loadCurrUser() is False:
2015-12-25 07:07:00 +11:00
pass
else:
2016-03-04 23:34:30 +11:00
# We successfully loaded a user
2016-02-20 06:03:06 +11:00
log("Current user: %s" % self.currUser, 1)
log("Current userId: %s" % self.currUserId, 1)
log("Current accessToken: xxxx", 1)
2015-12-25 07:07:00 +11:00
return
2016-02-20 06:03:06 +11:00
# AUTHENTICATE USER #####
2016-03-04 23:34:30 +11:00
plx = PlexAPI.PlexAPI()
2015-12-28 03:12:46 +11:00
# Choose Plex user login
2016-03-04 23:34:30 +11:00
plexdict = plx.GetPlexLoginFromSettings()
myplexlogin = plexdict['myplexlogin']
plexhome = plexdict['plexhome']
2016-01-15 00:47:34 +11:00
if myplexlogin == "true" and plexhome == 'true':
username, userId, accessToken = plx.ChoosePlexHomeUser()
else:
2016-02-20 06:03:06 +11:00
log("Trying to connect to PMS without a token", 0)
2016-01-15 00:47:34 +11:00
accessToken = ''
# Check connection
if plx.CheckConnection(server, accessToken) == 200:
2015-12-25 07:07:00 +11:00
self.currUser = username
2016-03-04 23:34:30 +11:00
settings('accessToken', value=accessToken)
settings('userId', value=userId)
2016-03-04 23:34:30 +11:00
log("User authenticated with an access token", 1)
if self.loadCurrUser(authenticated=True) is False:
# Something went really wrong, return and try again
self.auth = True
self.currUser = None
return
# Success!
2016-01-15 00:47:34 +11:00
if username:
dialog.notification(
heading=self.addonName,
message=("Welcome " + username).encode('utf-8'),
icon="special://home/addons/plugin.video.plexkodiconnect/icon.png")
2016-01-15 00:47:34 +11:00
else:
dialog.notification(
heading=self.addonName,
message="Welcome",
icon="special://home/addons/plugin.video.plexkodiconnect/icon.png")
2015-12-25 07:07:00 +11:00
self.retry = 0
2016-01-25 20:36:24 +11:00
# Make sure that lib sync thread is not paused
2015-12-25 07:07:00 +11:00
else:
2016-01-15 00:47:34 +11:00
self.logMsg("Error: user authentication failed.", -1)
2016-02-20 06:03:06 +11:00
settings('accessToken', value="")
settings('userId', value="")
2016-03-04 23:34:30 +11:00
# Give attempts at entering password / selecting user
if self.retry >= 5:
log("Too many retries.", 1)
2016-02-20 06:03:06 +11:00
window('emby_serverStatus', value="Stop")
dialog.ok(lang(33001).encode('utf-8'),
lang(39023).encode('utf-8'))
2016-03-04 23:34:30 +11:00
xbmc.executebuiltin(
'Addon.OpenSettings(plugin.video.plexkodiconnect)')
self.retry += 1
2015-12-25 07:07:00 +11:00
self.auth = False
def resetClient(self):
2016-02-20 06:03:06 +11:00
self.logMsg("Reset UserClient authentication.", 1)
2016-01-13 03:23:55 +11:00
utils.settings('accessToken', value="")
2016-03-04 01:28:44 +11:00
utils.window('emby_accessToken%s' % self.currUserId, clear=True)
2016-01-13 03:23:55 +11:00
self.currToken = None
2016-03-04 01:28:44 +11:00
self.logMsg("User token has been removed. Pausing Lib sync thread", 1)
utils.window('suspend_LibraryThread', value="true")
2016-01-13 03:23:55 +11:00
2015-12-25 07:07:00 +11:00
self.auth = True
self.currUser = None
2016-03-04 01:28:44 +11:00
self.currUserId = None
2016-01-13 03:23:55 +11:00
2015-12-25 07:07:00 +11:00
def run(self):
2016-02-20 06:03:06 +11:00
log = self.logMsg
window = utils.window
2016-03-04 01:28:44 +11:00
# Start library sync thread in a suspended mode, until signed in
utils.window('suspend_LibraryThread', value="true")
2015-12-25 07:07:00 +11:00
2016-02-17 19:13:37 +11:00
log("----===## Starting UserClient ##===----", 0)
2016-01-27 01:13:03 +11:00
while not self.threadStopped():
while self.threadSuspended():
if self.threadStopped():
break
2016-03-08 21:20:11 +11:00
xbmc.sleep(1000)
2015-12-25 07:07:00 +11:00
2016-02-17 19:13:37 +11:00
status = window('emby_serverStatus')
2015-12-25 07:07:00 +11:00
if status:
# Verify the connection status to server
if status == "restricted":
# Parental control is restricting access
self.HasAccess = False
elif status == "401":
# Unauthorized access, revoke token
2016-02-17 19:13:37 +11:00
window('emby_serverStatus', value="Auth")
2015-12-25 07:07:00 +11:00
self.resetClient()
if self.auth and (self.currUser is None):
# Try to authenticate user
if not status or status == "Auth":
# Set auth flag because we no longer need
# to authenticate the user
self.auth = False
self.authenticate()
if not self.auth and (self.currUser is None):
2016-03-04 23:34:30 +11:00
# Loop if no server found
2015-12-25 07:07:00 +11:00
server = self.getServer()
2016-02-20 06:03:06 +11:00
2015-12-25 07:07:00 +11:00
# The status Stop is for when user cancelled password dialog.
2016-03-04 23:34:30 +11:00
if server and status != "Stop":
2015-12-25 07:07:00 +11:00
# Only if there's information found to login
2016-02-17 19:13:37 +11:00
log("Server found: %s" % server, 2)
2015-12-25 07:07:00 +11:00
self.auth = True
# Minimize CPU load
xbmc.sleep(500)
2016-01-27 01:13:03 +11:00
self.doUtils.stopSession()
2016-02-20 06:03:06 +11:00
log("##===---- UserClient Stopped ----===##", 0)