Cleanup initialsetup.py

This commit is contained in:
tomkat83 2016-08-30 16:13:13 +02:00
parent fcf8093977
commit 44d309e5b7

View file

@ -2,11 +2,11 @@
############################################################################### ###############################################################################
import logging
import xbmc import xbmc
import xbmcgui import xbmcgui
import xbmcaddon
import utils from utils import settings, window, language as lang
import clientinfo import clientinfo
import downloadutils import downloadutils
import userclient import userclient
@ -16,12 +16,17 @@ from PlexFunctions import GetMachineIdentifier
############################################################################### ###############################################################################
log = logging.getLogger("PLEX."+__name__)
addonName = 'PlexKodiConnect'
###############################################################################
@utils.logging
class InitialSetup(): class InitialSetup():
def __init__(self): def __init__(self):
self.logMsg('Entering initialsetup class', 1) log.debug('Entering initialsetup class')
self.clientInfo = clientinfo.ClientInfo() self.clientInfo = clientinfo.ClientInfo()
self.addonId = self.clientInfo.getAddonId() self.addonId = self.clientInfo.getAddonId()
self.doUtils = downloadutils.DownloadUtils().downloadUrl self.doUtils = downloadutils.DownloadUtils().downloadUrl
@ -29,10 +34,8 @@ class InitialSetup():
self.plx = PlexAPI.PlexAPI() self.plx = PlexAPI.PlexAPI()
self.dialog = xbmcgui.Dialog() self.dialog = xbmcgui.Dialog()
self.string = xbmcaddon.Addon().getLocalizedString
self.server = self.userClient.getServer() self.server = self.userClient.getServer()
self.serverid = utils.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 = self.plx.GetPlexLoginFromSettings() plexdict = self.plx.GetPlexLoginFromSettings()
self.myplexlogin = plexdict['myplexlogin'] == 'true' self.myplexlogin = plexdict['myplexlogin'] == 'true'
@ -40,7 +43,7 @@ class InitialSetup():
self.plexToken = plexdict['plexToken'] self.plexToken = plexdict['plexToken']
self.plexid = plexdict['plexid'] self.plexid = plexdict['plexid']
if self.plexToken: if self.plexToken:
self.logMsg('Found a plex.tv token in the settings', 1) log.debug('Found a plex.tv token in the settings')
def PlexTVSignIn(self): def PlexTVSignIn(self):
""" """
@ -66,24 +69,22 @@ class InitialSetup():
chk = self.plx.CheckConnection('plex.tv', token=self.plexToken) chk = self.plx.CheckConnection('plex.tv', token=self.plexToken)
if chk in (401, 403): if chk in (401, 403):
# HTTP Error: unauthorized. Token is no longer valid # HTTP Error: unauthorized. Token is no longer valid
self.logMsg('plex.tv connection returned HTTP %s' % str(chk), 1) log.info('plex.tv connection returned HTTP %s' % str(chk))
# Delete token in the settings # Delete token in the settings
utils.settings('plexToken', value='') settings('plexToken', value='')
utils.settings('plexLogin', value='') settings('plexLogin', value='')
# Could not login, please try again # Could not login, please try again
self.dialog.ok(self.addonName, self.dialog.ok(addonName, lang(39009))
self.string(39009))
answer = self.PlexTVSignIn() answer = self.PlexTVSignIn()
elif chk is False or chk >= 400: elif chk is False or chk >= 400:
# Problems connecting to plex.tv. Network or internet issue? # Problems connecting to plex.tv. Network or internet issue?
self.logMsg('Problems connecting to plex.tv; connection returned ' log.info('Problems connecting to plex.tv; connection returned '
'HTTP %s' % str(chk), 1) 'HTTP %s' % str(chk))
self.dialog.ok(self.addonName, self.dialog.ok(addonName, lang(39010))
self.string(39010))
answer = False answer = False
else: else:
self.logMsg('plex.tv connection with token successful', 1) log.info('plex.tv connection with token successful')
utils.settings('plex_status', value='Logged in to plex.tv') settings('plex_status', value='Logged in to plex.tv')
# Refresh the info from Plex.tv # Refresh the info from Plex.tv
xml = self.doUtils('https://plex.tv/users/account', xml = self.doUtils('https://plex.tv/users/account',
authenticate=False, authenticate=False,
@ -91,15 +92,14 @@ class InitialSetup():
try: try:
self.plexLogin = xml.attrib['title'] self.plexLogin = xml.attrib['title']
except (AttributeError, KeyError): except (AttributeError, KeyError):
self.logMsg('Failed to update Plex info from plex.tv', -1) log.error('Failed to update Plex info from plex.tv')
else: else:
utils.settings('plexLogin', value=self.plexLogin) settings('plexLogin', value=self.plexLogin)
home = 'true' if xml.attrib.get('home') == '1' else 'false' home = 'true' if xml.attrib.get('home') == '1' else 'false'
utils.settings('plexhome', value=home) settings('plexhome', value=home)
utils.settings('plexAvatar', value=xml.attrib.get('thumb')) settings('plexAvatar', value=xml.attrib.get('thumb'))
utils.settings( settings('plexHomeSize', value=xml.attrib.get('homeSize', '1'))
'plexHomeSize', value=xml.attrib.get('homeSize', '1')) log.info('Updated Plex info from plex.tv')
self.logMsg('Updated Plex info from plex.tv', 1)
return answer return answer
def CheckPMS(self): def CheckPMS(self):
@ -113,27 +113,26 @@ class InitialSetup():
not set before not set before
""" """
answer = True answer = True
chk = self.plx.CheckConnection(self.server, chk = self.plx.CheckConnection(self.server, verifySSL=False)
verifySSL=False)
if chk is False: if chk is False:
self.logMsg('Could not reach PMS %s' % self.server, -1) log.warn('Could not reach PMS %s' % self.server)
answer = False answer = False
if answer is True and not self.serverid: if answer is True and not self.serverid:
self.logMsg('No PMS machineIdentifier found for %s. Trying to ' log.info('No PMS machineIdentifier found for %s. Trying to '
'get the PMS unique ID' % self.server, 1) 'get the PMS unique ID' % self.server)
self.serverid = GetMachineIdentifier(self.server) self.serverid = GetMachineIdentifier(self.server)
if self.serverid is None: if self.serverid is None:
self.logMsg('Could not retrieve machineIdentifier', -1) log.warn('Could not retrieve machineIdentifier')
answer = False answer = False
else: else:
utils.settings('plex_machineIdentifier', value=self.serverid) settings('plex_machineIdentifier', value=self.serverid)
elif answer is True: elif answer is True:
tempServerid = GetMachineIdentifier(self.server) tempServerid = GetMachineIdentifier(self.server)
if tempServerid != self.serverid: if tempServerid != self.serverid:
self.logMsg('The current PMS %s was expected to have a ' log.warn('The current PMS %s was expected to have a '
'unique machineIdentifier of %s. But we got ' 'unique machineIdentifier of %s. But we got '
'%s. Pick a new server to be sure' '%s. Pick a new server to be sure'
% (self.server, self.serverid, tempServerid), 1) % (self.server, self.serverid, tempServerid))
answer = False answer = False
return answer return answer
@ -144,7 +143,7 @@ class InitialSetup():
self.plx.discoverPMS(xbmc.getIPAddress(), self.plx.discoverPMS(xbmc.getIPAddress(),
plexToken=self.plexToken) plexToken=self.plexToken)
serverlist = self.plx.returnServerList(self.plx.g_PMS) serverlist = self.plx.returnServerList(self.plx.g_PMS)
self.logMsg('PMS serverlist: %s' % serverlist, 2) log.debug('PMS serverlist: %s' % serverlist)
return serverlist return serverlist
def _checkServerCon(self, server): def _checkServerCon(self, server):
@ -217,14 +216,14 @@ class InitialSetup():
if item.get('machineIdentifier') == self.serverid: if item.get('machineIdentifier') == self.serverid:
server = item server = item
if server is None: if server is None:
name = utils.settings('plex_servername') name = settings('plex_servername')
self.logMsg('The PMS you have used before with a unique ' log.warn('The PMS you have used before with a unique '
'machineIdentifier of %s and name %s is ' 'machineIdentifier of %s and name %s is '
'offline' % (self.serverid, name), -1) 'offline' % (self.serverid, name))
# "PMS xyz offline" # "PMS xyz offline"
self.dialog.notification(self.addonName, self.dialog.notification(addonName,
'%s %s' '%s %s'
% (name, self.string(39213)), % (name, lang(39213)),
xbmcgui.NOTIFICATION_ERROR, xbmcgui.NOTIFICATION_ERROR,
7000, 7000,
False) False)
@ -236,8 +235,8 @@ class InitialSetup():
httpsUpdated = True httpsUpdated = True
continue continue
if chk == 401: if chk == 401:
self.logMsg('Not yet authorized for Plex server %s' log.warn('Not yet authorized for Plex server %s'
% server['name'], -1) % server['name'])
if self.CheckPlexTVSignIn() is True: if self.CheckPlexTVSignIn() is True:
if checkedPlexTV is False: if checkedPlexTV is False:
# Try again # Try again
@ -245,20 +244,20 @@ class InitialSetup():
httpsUpdated = False httpsUpdated = False
continue continue
else: else:
self.logMsg('Not authorized even though we are signed ' log.warn('Not authorized even though we are signed '
' in to plex.tv correctly', -1) ' in to plex.tv correctly')
self.dialog.ok(self.addonName, '%s %s' self.dialog.ok(addonName, '%s %s'
% self.string(39214) + server['name']) % lang(39214) + server['name'])
return return
else: else:
return return
# Problems connecting # Problems connecting
elif chk >= 400 or chk is False: elif chk >= 400 or chk is False:
self.logMsg('Problems connecting to server %s. chk is %s' log.warn('Problems connecting to server %s. chk is %s'
% (server['name'], chk), -1) % (server['name'], chk))
return return
self.logMsg('We found a server to automatically connect to: %s' log.info('We found a server to automatically connect to: %s'
% server['name'], 1) % server['name'])
return server return server
def _UserPickPMS(self): def _UserPickPMS(self):
@ -273,8 +272,8 @@ class InitialSetup():
serverlist = self._getServerList() serverlist = self._getServerList()
# Exit if no servers found # Exit if no servers found
if len(serverlist) == 0: if len(serverlist) == 0:
self.logMsg('No plex media servers found!', -1) log.warn('No plex media servers found!')
self.dialog.ok(self.addonName, self.string(39011)) self.dialog.ok(addonName, lang(39011))
return return
# Get a nicer list # Get a nicer list
dialoglist = [] dialoglist = []
@ -282,10 +281,10 @@ class InitialSetup():
if server['local'] == '1': if server['local'] == '1':
# server is in the same network as client. # server is in the same network as client.
# Add"local" # Add"local"
msg = self.string(39022) msg = lang(39022)
else: else:
# Add 'remote' # Add 'remote'
msg = self.string(39054) msg = lang(39054)
if server.get('ownername'): if server.get('ownername'):
# Display username if its not our PMS # Display username if its not our PMS
dialoglist.append('%s (%s, %s)' dialoglist.append('%s (%s, %s)'
@ -296,7 +295,7 @@ class InitialSetup():
dialoglist.append('%s (%s)' dialoglist.append('%s (%s)'
% (server['name'], msg)) % (server['name'], msg))
# Let user pick server from a list # Let user pick server from a list
resp = self.dialog.select(self.string(39012), dialoglist) resp = self.dialog.select(lang(39012), dialoglist)
server = serverlist[resp] server = serverlist[resp]
chk = self._checkServerCon(server) chk = self._checkServerCon(server)
@ -307,20 +306,20 @@ class InitialSetup():
continue continue
httpsUpdated = False httpsUpdated = False
if chk == 401: if chk == 401:
self.logMsg('Not yet authorized for Plex server %s' log.warn('Not yet authorized for Plex server %s'
% server['name'], -1) % server['name'])
# Please sign in to plex.tv # Please sign in to plex.tv
self.dialog.ok(self.addonName, self.dialog.ok(addonName,
self.string(39013) + server['name'], lang(39013) + server['name'],
self.string(39014)) lang(39014))
if self.PlexTVSignIn() is False: if self.PlexTVSignIn() is False:
# Exit while loop if user cancels # Exit while loop if user cancels
return return
# Problems connecting # Problems connecting
elif chk >= 400 or chk is False: elif chk >= 400 or chk is False:
# Problems connecting to server. Pick another server? # Problems connecting to server. Pick another server?
answ = self.dialog.yesno(self.addonName, answ = self.dialog.yesno(addonName,
self.string(39015)) lang(39015))
# Exit while loop if user chooses No # Exit while loop if user chooses No
if not answ: if not answ:
return return
@ -345,35 +344,35 @@ class InitialSetup():
'ownername' Plex username of PMS owner 'ownername' Plex username of PMS owner
} }
""" """
utils.settings('plex_machineIdentifier', server['machineIdentifier']) settings('plex_machineIdentifier', server['machineIdentifier'])
utils.settings('plex_servername', server['name']) settings('plex_servername', server['name'])
utils.settings('plex_serverowned', settings('plex_serverowned',
'true' if server['owned'] == '1' 'true' if server['owned'] == '1'
else 'false') else 'false')
# Careful to distinguish local from remote PMS # Careful to distinguish local from remote PMS
if server['local'] == '1': if server['local'] == '1':
scheme = server['scheme'] scheme = server['scheme']
utils.settings('ipaddress', server['ip']) settings('ipaddress', server['ip'])
utils.settings('port', server['port']) settings('port', server['port'])
self.logMsg("Setting SSL verify to false, because server is " log.debug("Setting SSL verify to false, because server is "
"local", 1) "local")
utils.settings('sslverify', 'false') settings('sslverify', 'false')
else: else:
baseURL = server['baseURL'].split(':') baseURL = server['baseURL'].split(':')
scheme = baseURL[0] scheme = baseURL[0]
utils.settings('ipaddress', baseURL[1].replace('//', '')) settings('ipaddress', baseURL[1].replace('//', ''))
utils.settings('port', baseURL[2]) settings('port', baseURL[2])
self.logMsg("Setting SSL verify to true, because server is not " log.debug("Setting SSL verify to true, because server is not "
"local", 1) "local")
utils.settings('sslverify', 'true') settings('sslverify', 'true')
if scheme == 'https': if scheme == 'https':
utils.settings('https', 'true') settings('https', 'true')
else: else:
utils.settings('https', 'false') settings('https', 'false')
# And finally do some logging # And finally do some logging
self.logMsg("Writing to Kodi user settings file", 0) log.debug("Writing to Kodi user settings file")
self.logMsg("PMS machineIdentifier: %s, ip: %s, port: %s, https: %s " log.debug("PMS machineIdentifier: %s, ip: %s, port: %s, https: %s "
% (server['machineIdentifier'], server['ip'], % (server['machineIdentifier'], server['ip'],
server['port'], server['scheme']), 0) server['port'], server['scheme']), 0)
@ -384,13 +383,12 @@ class InitialSetup():
Check server, user, direct paths, music, direct stream if not direct Check server, user, direct paths, music, direct stream if not direct
path. path.
""" """
self.logMsg("Initial setup called.", 0) log.info("Initial setup called.")
dialog = self.dialog dialog = self.dialog
string = self.string
# Optionally sign into plex.tv. Will not be called on very first run # Optionally sign into plex.tv. Will not be called on very first run
# as plexToken will be '' # as plexToken will be ''
utils.settings('plex_status', value='Not logged in to plex.tv') settings('plex_status', value='Not logged in to plex.tv')
if self.plexToken and self.myplexlogin: if self.plexToken and self.myplexlogin:
self.CheckPlexTVSignIn() self.CheckPlexTVSignIn()
@ -398,12 +396,11 @@ class InitialSetup():
# return only if the right machine identifier is found # return only if the right machine identifier is found
getNewIP = False getNewIP = False
if self.server: if self.server:
self.logMsg("PMS is already set: %s. Checking now..." log.info("PMS is already set: %s. Checking now..." % self.server)
% self.server, 0)
getNewIP = not self.CheckPMS() getNewIP = not self.CheckPMS()
if getNewIP is False: if getNewIP is False:
self.logMsg("Using PMS %s with machineIdentifier %s" log.info("Using PMS %s with machineIdentifier %s"
% (self.server, self.serverid), 0) % (self.server, self.serverid))
return return
# If not already retrieved myplex info, optionally let user sign in # If not already retrieved myplex info, optionally let user sign in
@ -417,81 +414,74 @@ class InitialSetup():
self.WritePMStoSettings(server) self.WritePMStoSettings(server)
# User already answered the installation questions # User already answered the installation questions
if utils.settings('InstallQuestionsAnswered') == 'true': if settings('InstallQuestionsAnswered') == 'true':
return return
# Additional settings where the user needs to choose # Additional settings where the user needs to choose
# Direct paths (\\NAS\mymovie.mkv) or addon (http)? # Direct paths (\\NAS\mymovie.mkv) or addon (http)?
if dialog.yesno(self.addonName, if dialog.yesno(addonName,
string(39027), lang(39027),
string(39028), lang(39028),
nolabel="Addon (Default)", nolabel="Addon (Default)",
yeslabel="Native (Direct Paths)"): yeslabel="Native (Direct Paths)"):
self.logMsg("User opted to use direct paths.", 1) log.debug("User opted to use direct paths.")
utils.settings('useDirectPaths', value="1") settings('useDirectPaths', value="1")
# Are you on a system where you would like to replace paths # Are you on a system where you would like to replace paths
# \\NAS\mymovie.mkv with smb://NAS/mymovie.mkv? (e.g. Windows) # \\NAS\mymovie.mkv with smb://NAS/mymovie.mkv? (e.g. Windows)
if dialog.yesno(heading=self.addonName, if dialog.yesno(heading=addonName, line1=lang(39033)):
line1=string(39033)): log.debug("User chose to replace paths with smb")
self.logMsg("User chose to replace paths with smb", 1)
else: else:
utils.settings('replaceSMB', value="false") settings('replaceSMB', value="false")
# complete replace all original Plex library paths with custom SMB # complete replace all original Plex library paths with custom SMB
if dialog.yesno(heading=self.addonName, if dialog.yesno(heading=addonName, line1=lang(39043)):
line1=string(39043)): log.debug("User chose custom smb paths")
self.logMsg("User chose custom smb paths", 1) settings('remapSMB', value="true")
utils.settings('remapSMB', value="true")
# Please enter your custom smb paths in the settings under # Please enter your custom smb paths in the settings under
# "Sync Options" and then restart Kodi # "Sync Options" and then restart Kodi
dialog.ok(heading=self.addonName, dialog.ok(heading=addonName, line1=lang(39044))
line1=string(39044))
goToSettings = True goToSettings = True
# Go to network credentials? # Go to network credentials?
if dialog.yesno(heading=self.addonName, if dialog.yesno(heading=addonName,
line1=string(39029), line1=lang(39029),
line2=string(39030)): line2=lang(39030)):
self.logMsg("Presenting network credentials dialog.", 1) log.debug("Presenting network credentials dialog.")
utils.passwordsXML() from utils import passwordsXML
passwordsXML()
# Disable Plex music? # Disable Plex music?
if dialog.yesno(heading=self.addonName, if dialog.yesno(heading=addonName, line1=lang(39016)):
line1=string(39016)): log.debug("User opted to disable Plex music library.")
self.logMsg("User opted to disable Plex music library.", 1) settings('enableMusic', value="false")
utils.settings('enableMusic', value="false")
else: else:
utils.advancedSettingsXML() from utils import advancedSettingsXML
advancedSettingsXML()
# Download additional art from FanArtTV # Download additional art from FanArtTV
if dialog.yesno(heading=self.addonName, if dialog.yesno(heading=addonName, line1=lang(39061)):
line1=string(39061)): log.debug("User opted to use FanArtTV")
self.logMsg("User opted to use FanArtTV", 1) settings('FanartTV', value="true")
utils.settings('FanartTV', value="true")
# Is your Kodi installed on a low-powered device like a Raspberry Pi? # Is your Kodi installed on a low-powered device like a Raspberry Pi?
# If yes, then we will reduce the strain on Kodi to prevent it from # If yes, then we will reduce the strain on Kodi to prevent it from
# crashing. # crashing.
if dialog.yesno(heading=self.addonName, if dialog.yesno(heading=addonName, line1=lang(39072)):
line1=string(39072)): log.debug('User thinks that PKC runs on a raspi or similar')
self.logMsg('User thinks that PKC runs on a raspi or similar', 1) settings('imageCacheLimit', value='1')
utils.settings('imageCacheLimit', value='1')
# Make sure that we only ask these questions upon first installation # Make sure that we only ask these questions upon first installation
utils.settings('InstallQuestionsAnswered', value='true') settings('InstallQuestionsAnswered', value='true')
if goToSettings is False: if goToSettings is False:
# Open Settings page now? You will need to restart! # Open Settings page now? You will need to restart!
goToSettings = dialog.yesno(heading=self.addonName, goToSettings = dialog.yesno(heading=addonName, line1=lang(39017))
line1=string(39017))
if goToSettings: if goToSettings:
utils.window('plex_serverStatus', value="Stop") window('plex_serverStatus', value="Stop")
xbmc.executebuiltin( xbmc.executebuiltin(
'Addon.OpenSettings(plugin.video.plexkodiconnect)') 'Addon.OpenSettings(plugin.video.plexkodiconnect)')
else: else:
# "Kodi will now restart to apply the changes" # "Kodi will now restart to apply the changes"
dialog.ok( dialog.ok(heading=addonName, line1=lang(33033))
heading=self.addonName,
line1=string(33033))
xbmc.executebuiltin('RestartApp') xbmc.executebuiltin('RestartApp')
# We should always restart to ensure e.g. Kodi settings for Music # We should always restart to ensure e.g. Kodi settings for Music
# are in use! # are in use!