PlexKodiConnect/resources/lib/userclient.py

422 lines
14 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 getUsername(self):
"""
Returns username as unicode
"""
2015-12-25 07:07:00 +11:00
username = utils.settings('username')
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')
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
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
2016-03-10 01:37:27 +11:00
self.machineIdentifier = utils.settings('plex_machineIdentifier')
self.servername = utils.settings('plex_servername')
2016-03-04 23:34:30 +11:00
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
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)
2016-03-10 01:37:27 +11:00
# Only try to get user avatar if there is a token
if self.currToken:
url = PlexAPI.PlexAPI().GetUserArtworkURL(self.currUser)
if url:
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 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))
2015-12-25 07:07:00 +11:00
2016-03-10 01:37:27 +11:00
def loadCurrUser(self, username, userId, usertoken, 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
2016-03-10 01:37:27 +11:00
settings = utils.settings
2015-12-25 07:07:00 +11:00
doUtils = self.doUtils
2016-02-20 06:03:06 +11:00
2015-12-25 07:07:00 +11:00
self.currUserId = userId
2016-03-10 01:37:27 +11:00
self.currToken = usertoken
2015-12-25 07:07:00 +11:00
self.currServer = self.getServer()
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)
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
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-03-11 02:02:46 +11:00
window('currUserId', value=userId)
2016-02-20 06:03:06 +11:00
window('plex_username', value=username)
2016-03-11 02:02:46 +11:00
# 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('accessToken'))
window('pms_server', value=self.currServer)
2016-02-20 06:03:06 +11:00
window('plex_machineIdentifier', value=self.machineIdentifier)
2016-03-10 01:37:27 +11:00
window('plex_servername', value=self.servername)
window('plex_authenticated', value='true')
# self.directpath
window('useDirectPaths', value='true'
if utils.settings('useDirectPaths') == "1" else 'false')
window('replaceSMB', value='true'
if utils.settings('replaceSMB') == "true" else 'false')
2016-03-04 23:34:30 +11:00
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)
2015-12-28 20:35:27 +11:00
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()
2016-03-10 01:37:27 +11:00
# 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")
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()
2016-03-10 01:37:27 +11:00
# Give attempts at entering password / selecting user
if self.retry >= 2:
log("Too many retries to login.", -1)
window('emby_serverStatus', value="Stop")
dialog.ok(lang(33001),
lang(39023))
xbmc.executebuiltin(
'Addon.OpenSettings(plugin.video.plexkodiconnect)')
2015-12-25 07:07:00 +11:00
# Get /profile/addon_data
addondir = xbmc.translatePath(
self.addon.getAddonInfo('profile')).decode('utf-8')
2015-12-25 07:07:00 +11:00
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
2016-03-10 01:37:27 +11:00
return False
2016-03-04 23:34:30 +11:00
server = self.getServer()
2016-03-10 01:37:27 +11:00
# If there is no server we can connect to
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
2016-03-10 01:37:27 +11:00
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('Trying to authenticate with old settings', 0)
if self.loadCurrUser(username,
userId,
usertoken,
authenticated=False):
# SUCCESS: loaded a user from the settings
return True
2015-12-25 07:07:00 +11:00
else:
2016-03-10 01:37:27 +11:00
# Failed to use the settings - delete them!
log("Failed to use the settings credentials. Deleting them", 1)
settings('username', value='')
settings('userid', value='')
settings('accessToken', value='')
2015-12-25 07:07:00 +11:00
2016-03-04 23:34:30 +11:00
plx = PlexAPI.PlexAPI()
2016-03-10 01:37:27 +11:00
# Could not use settings - try to get Plex user list from plex.tv
plextoken = settings('plexToken')
if plextoken:
log("Trying to connect to plex.tv to get a user list", 0)
userInfo = plx.ChoosePlexHomeUser(plextoken)
if userInfo is False:
# FAILURE: Something went wrong, try again
2016-03-04 23:34:30 +11:00
self.auth = True
2016-03-10 01:37:27 +11:00
self.retry += 1
return False
username = userInfo['username']
userId = userInfo['userid']
usertoken = userInfo['token']
2015-12-25 07:07:00 +11:00
else:
2016-03-10 01:37:27 +11:00
log("Trying to authenticate without a token", 0)
username = ''
userId = ''
usertoken = ''
2016-03-10 01:37:27 +11:00
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
2016-03-10 01:37:27 +11:00
return False
2015-12-25 07:07:00 +11:00
def resetClient(self):
2016-02-20 06:03:06 +11:00
self.logMsg("Reset UserClient authentication.", 1)
2016-03-11 02:02:46 +11:00
self.doUtils.stopSession()
2016-03-10 01:37:27 +11:00
settings = utils.settings
window = utils.window
2016-01-13 03:23:55 +11:00
window('plex_authenticated', clear=True)
2016-03-11 02:02:46 +11:00
window('pms_token', clear=True)
window('plex_token', clear=True)
window('pms_server', clear=True)
window('plex_machineIdentifier', clear=True)
window('plex_servername', clear=True)
window('currUserId', clear=True)
2016-03-10 01:37:27 +11:00
window('plex_username', clear=True)
2016-01-13 03:23:55 +11:00
2016-03-10 01:37:27 +11:00
settings('username', value='')
settings('userid', value='')
settings('accessToken', value='')
# Reset token in downloads
self.doUtils.setToken('')
self.doUtils.setUserId('')
self.doUtils.setUsername('')
self.currToken = None
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
2016-03-10 01:37:27 +11:00
self.retry = 0
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
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')
2016-03-11 02:02:46 +11:00
if status == "Stop":
xbmc.sleep(500)
continue
# Verify the connection status to server
elif status == "restricted":
# Parental control is restricting access
self.HasAccess = False
elif status == "401":
# Unauthorized access, revoke token
window('emby_serverStatus', value="Auth")
self.resetClient()
xbmc.sleep(2000)
2015-12-25 07:07:00 +11:00
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
2016-03-10 01:37:27 +11:00
if self.authenticate():
2016-03-10 01:53:46 +11:00
# Successfully authenticated and loaded a user
2016-03-10 01:37:27 +11:00
log("Current user: %s" % self.currUser, 1)
log("Current userId: %s" % self.currUserId, 1)
log("Current accessToken: xxxx", 1)
self.retry = 0
window('suspend_LibraryThread', clear=True)
window('emby_serverStatus', clear=True)
2015-12-25 07:07:00 +11:00
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-11 02:02:46 +11:00
# Or retried too many times
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(100)
2016-01-27 01:13:03 +11:00
self.doUtils.stopSession()
2016-02-20 06:03:06 +11:00
log("##===---- UserClient Stopped ----===##", 0)