Dedicated methods within initialsetup

This commit is contained in:
tomkat83 2016-05-24 20:43:52 +02:00
parent ae34b63de9
commit 72910d79e9
2 changed files with 227 additions and 169 deletions

View file

@ -77,7 +77,7 @@ def chooseServer():
Lets user choose from list of PMS (signs out & signs in) Lets user choose from list of PMS (signs out & signs in)
""" """
string = xbmcaddon.Addon().getLocalizedString string = xbmcaddon.Addon().getLocalizedString
utils.logMsg(title, "Choosing PMS server requested, starting", 0) utils.logMsg(title, "Choosing PMS server requested, starting", 1)
dialog = xbmcgui.Dialog() dialog = xbmcgui.Dialog()
# Resetting, please wait # Resetting, please wait
dialog.notification( dialog.notification(
@ -93,33 +93,24 @@ def chooseServer():
while utils.window('emby_dbScan') == 'true': while utils.window('emby_dbScan') == 'true':
if counter > 100: if counter > 100:
# Failed to reset PMS and plex.tv connects. Try to restart Kodi. # Failed to reset PMS and plex.tv connects. Try to restart Kodi.
dialog.ok(addonName, dialog.ok(addonName, string(39208))
string(39208))
# Resuming threads, just in case # Resuming threads, just in case
utils.window('suspend_LibraryThread', clear=True) utils.window('suspend_LibraryThread', clear=True)
utils.logMsg(title, "Could not stop library sync, aborting", -1) utils.logMsg(title, "Could not stop library sync, aborting", -1)
return return
counter += 1 counter += 1
xbmc.sleep(50) xbmc.sleep(50)
utils.logMsg(title, "Successfully stopped library sync", 0) utils.logMsg(title, "Successfully stopped library sync", 1)
# Reset connection details
utils.settings('plex_machineIdentifier', value="")
utils.settings('plex_servername', value="")
utils.settings('https', value="")
utils.settings('ipaddress', value="")
utils.settings('port', value="")
# Log out currently signed in user: # Log out currently signed in user:
utils.window('emby_serverStatus', value="401") utils.window('emby_serverStatus', value="401")
# Above method needs to have run its course! Hence wait # Above method needs to have run its course! Hence wait
counter = 0 counter = 0
while utils.window('emby_serverStatus') == "401": while utils.window('emby_serverStatus') == "401":
if counter > 100: if counter > 100:
dialog.ok(addonName, dialog.ok(addonName,
string(39208)) string(39208))
utils.logMsg(title, "Could not sign out, aborting", -1) utils.logMsg(title, "Could not sign out, aborting PMS", -1)
return return
counter += 1 counter += 1
xbmc.sleep(50) xbmc.sleep(50)
@ -127,12 +118,22 @@ def chooseServer():
utils.window('suspend_Userclient', value='true') utils.window('suspend_Userclient', value='true')
import initialsetup import initialsetup
initialsetup.InitialSetup().setup(chooseServer=True) setup = initialsetup.InitialSetup()
server = setup.PickPMS()
if server is None:
utils.logMsg('We did not connect to a new PMS, aborting', -1)
utils.window('suspend_Userclient', clear=True)
utils.window('suspend_LibraryThread', clear=True)
return
setup.WritePMStoSettings(server)
# Request lib sync to get user view data (e.g. watched/unwatched) # Request lib sync to get user view data (e.g. watched/unwatched)
utils.window('plex_runLibScan', value='full') utils.window('plex_runLibScan', value='full')
# Restart user client # Restart user client
utils.window('suspend_Userclient', clear=True) utils.window('suspend_Userclient', clear=True)
utils.logMsg(title, "Choosing new PMS complete", 0) utils.logMsg(title, "Choosing new PMS complete", 0)
# And do NOT clear suspend_LibraryThread flag, that needs to be done in
# service.py
def reConnect(): def reConnect():

View file

@ -21,150 +21,157 @@ from PlexFunctions import GetMachineIdentifier
class InitialSetup(): class InitialSetup():
def __init__(self): def __init__(self):
self.logMsg('Entering initialsetup class', 1)
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
self.userClient = userclient.UserClient() self.userClient = userclient.UserClient()
self.plx = PlexAPI.PlexAPI() self.plx = PlexAPI.PlexAPI()
self.dialog = xbmcgui.Dialog()
def PlexTvSignIn(self): self.string = xbmcaddon.Addon().getLocalizedString
self.server = self.userClient.getServer()
self.serverid = utils.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:
self.logMsg('Found a plex.tv token in the settings', 1)
def PlexTVSignIn(self):
"""
Signs (freshly) in to plex.tv (will be saved to file settings)
Returns True if successful, or False if not
"""
result = self.plx.PlexTvSignInWithPin()
if result:
self.plexLogin = result['username']
self.plexToken = result['token']
self.plexid = result['plexid']
return True
return False
def CheckPlexTVSignIn(self):
""" """
Checks existing connection to plex.tv. If not, triggers sign in Checks existing connection to plex.tv. If not, triggers sign in
""" """
chk = self.plx.CheckConnection('plex.tv', self.plexToken)
def setup(self, forcePlexTV=False, chooseServer=False): if chk in (401, 403):
""" # HTTP Error: unauthorized. Token is no longer valid
Initial setup. Run once upon startup. self.logMsg('plex.tv connection returned HTTP %s' % chk, 1)
Check server, user, direct paths, music, direct stream if not direct # Delete token in the settings
path. utils.settings('plexToken', value='')
""" # Could not login, please try again
string = xbmcaddon.Addon().getLocalizedString self.dialog.ok(self.addonName,
# SERVER INFO ##### self.string(39009))
self.logMsg("Initial setup called.", 0) self.PlexTVSignIn()
server = self.userClient.getServer() elif chk is False or chk >= 400:
serverid = utils.settings('plex_machineIdentifier') # Problems connecting to plex.tv. Network or internet issue?
# Get Plex credentials from settings file, if they exist self.logMsg('plex.tv connection returned HTTP %s'
plexdict = self.plx.GetPlexLoginFromSettings() % str(chk), 1)
myplexlogin = plexdict['myplexlogin'] self.dialog.ok(self.addonName,
plexLogin = plexdict['plexLogin'] self.string(39010))
plexToken = plexdict['plexToken'] else:
plexid = plexdict['plexid'] self.logMsg('plex.tv connection with token successful', 1)
if plexToken: # Refresh the info from Plex.tv
self.logMsg('Found a plex.tv token in the settings', 0) xml = self.doUtils('https://plex.tv/users/account',
authenticate=False,
dialog = xbmcgui.Dialog() headerOptions={'X-Plex-Token': self.plexToken})
try:
# Optionally sign into plex.tv. Will not be called on very first run self.plexLogin = xml.attrib['title']
# as plexToken will be '' except (AttributeError, KeyError):
if (plexToken and myplexlogin == 'true' and forcePlexTV is False self.logMsg('Failed to update Plex info from plex.tv', -1)
and chooseServer is False):
chk = self.plx.CheckConnection('plex.tv', plexToken)
if chk in (401, 403):
# HTTP Error: unauthorized. Token is no longer valid
self.logMsg('plex.tv connection returned HTTP %s' % chk, 0)
# Delete token in the settings
utils.settings('plexToken', value='')
# Could not login, please try again
dialog.ok(self.addonName,
string(39009))
result = self.plx.PlexTvSignInWithPin()
if result:
plexLogin = result['username']
plexToken = result['token']
plexid = result['plexid']
elif chk is False or chk >= 400:
# Problems connecting to plex.tv. Network or internet issue?
self.logMsg('plex.tv connection returned HTTP %s'
% str(chk), 0)
dialog.ok(self.addonName,
string(39010))
else: else:
self.logMsg('plex.tv connection with token successful', 0) utils.settings('plexLogin', value=self.plexLogin)
# Refresh the info from Plex.tv home = 'true' if xml.attrib.get('home') == '1' else 'false'
xml = self.doUtils('https://plex.tv/users/account', utils.settings('plexhome', value=home)
authenticate=False, utils.settings('plexAvatar', value=xml.attrib.get('thumb'))
headerOptions={'X-Plex-Token': plexToken}) utils.settings(
try: 'plexHomeSize', value=xml.attrib.get('homeSize', '1'))
plexLogin = xml.attrib['title'] self.logMsg('Updated Plex info from plex.tv', 1)
except (AttributeError, KeyError):
self.logMsg('Failed to update Plex info from plex.tv', -1)
else:
utils.settings('plexLogin', value=plexLogin)
home = 'true' if xml.attrib.get('home') == '1' else 'false'
utils.settings('plexhome', value=home)
utils.settings('plexAvatar', value=xml.attrib.get('thumb'))
utils.settings(
'plexHomeSize', value=xml.attrib.get('homeSize', '1'))
self.logMsg('Updated Plex info from plex.tv', 0)
# If a Plex server IP has already been set def CheckPMS(self):
# return only if the right machine identifier is found """
getNewPMS = False Check the PMS that was set in file settings.
if server and forcePlexTV is False and chooseServer is False: Will return False if we need to reconnect, because:
self.logMsg("PMS is already set: %s. Checking now..." % server, 0) PMS could not be reached (no matter the authorization)
chk = self.plx.CheckConnection(server, verifySSL=False) machineIdentifier did not match
if chk is False:
self.logMsg('Could not reach PMS %s' % server, -1)
getNewPMS = True
if getNewPMS is False and not serverid:
self.logMsg('No PMS machineIdentifier found for %s. Trying to '
'get the PMS unique ID' % server, 1)
serverid = GetMachineIdentifier(server)
if serverid is None:
self.logMsg('Could not retrieve machineIdentifier', -1)
getNewPMS = True
else:
utils.settings('plex_machineIdentifier', value=serverid)
elif getNewPMS is False:
tempServerid = GetMachineIdentifier(server)
if tempServerid != serverid:
self.logMsg('The current PMS %s was expected to have a '
'unique machineIdentifier of %s. But we got '
'%s. Pick a new server to be sure'
% (server, serverid, tempServerid), 1)
getNewPMS = True
if getNewPMS is False:
self.logMsg("Using PMS %s with machineIdentifier %s"
% (server, serverid), 0)
return
# If not already retrieved myplex info, optionally let user sign in Will also set the PMS machineIdentifier in the file settings if it was
# to plex.tv. This DOES get called on very first install run not set before
if ((not plexToken and myplexlogin == 'true' and chooseServer is False) """
or forcePlexTV): answer = True
result = self.plx.PlexTvSignInWithPin() chk = self.plx.CheckConnection(self.server, verifySSL=False)
if result: if chk is False:
plexLogin = result['username'] self.logMsg('Could not reach PMS %s' % self.server, -1)
plexToken = result['token'] answer = False
plexid = result['plexid'] if answer is True and not self.serverid:
# Get g_PMS list of servers (saved to plx.g_PMS) self.logMsg('No PMS machineIdentifier found for %s. Trying to '
'get the PMS unique ID' % self.server, 1)
self.serverid = GetMachineIdentifier(self.server)
if self.serverid is None:
self.logMsg('Could not retrieve machineIdentifier', -1)
answer = False
else:
utils.settings('plex_machineIdentifier', value=self.serverid)
elif answer is True:
tempServerid = GetMachineIdentifier(self.server)
if tempServerid != self.serverid:
self.logMsg('The current PMS %s was expected to have a '
'unique machineIdentifier of %s. But we got '
'%s. Pick a new server to be sure'
% (self.server, self.serverid, tempServerid), 1)
answer = False
return answer
def PickPMS(self):
"""
Searches for PMS and lets user pick one
Returns the picked PMS' detail as a dict:
{
'name': friendlyName, the Plex server's name
'address': ip:port
'ip': ip, without http/https
'port': port
'scheme': 'http'/'https', nice for checking for secure connections
'local': '1'/'0', Is the server a local server?
'owned': '1'/'0', Is the server owned by the user?
'machineIdentifier': id, Plex server machine identifier
'accesstoken': token Access token to this server
'baseURL': baseURL scheme://ip:port
'ownername' Plex username of PMS owner
}
or None if unsuccessful
"""
httpsUpdated = False httpsUpdated = False
while True: while True:
if httpsUpdated is False: if httpsUpdated is False:
# Populate g_PMS variable with the found Plex servers # Populate g_PMS variable with the found Plex servers
self.plx.discoverPMS(xbmc.getIPAddress(), self.plx.discoverPMS(xbmc.getIPAddress(),
plexToken=plexToken) plexToken=self.plexToken)
isconnected = False
self.logMsg('g_PMS: %s' % self.plx.g_PMS, 1)
serverlist = self.plx.returnServerList(self.plx.g_PMS) serverlist = self.plx.returnServerList(self.plx.g_PMS)
self.logMsg('PMS serverlist: %s' % serverlist, 2) self.logMsg('PMS serverlist: %s' % serverlist, 2)
# Let user pick server from a list
# Get a nicer list
dialoglist = []
# Exit if no servers found # Exit if no servers found
if len(serverlist) == 0: if len(serverlist) == 0:
dialog.ok( self.dialog.ok(self.addonName, self.string(39011))
self.addonName, server = None
string(39011)
)
break break
# Get a nicer list
dialoglist = []
for server in serverlist: for server in serverlist:
if server['local'] == '1': if server['local'] == '1':
# server is in the same network as client. Add "local" # server is in the same network as client. Add "local"
msg = string(39022) msg = self.string(39022)
else: else:
# Add 'remote' # Add 'remote'
msg = string(39054) msg = self.string(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)'
@ -173,29 +180,21 @@ class InitialSetup():
msg)) msg))
else: else:
dialoglist.append('%s (%s)' dialoglist.append('%s (%s)'
% (server['name'], % (server['name'], msg))
msg)) # Let user pick server from a list
resp = dialog.select(string(39012), dialoglist) resp = self.dialog.select(self.string(39012), dialoglist)
server = serverlist[resp] server = serverlist[resp]
activeServer = server['machineIdentifier']
# Re-direct via plex if remote - will lead to the correct SSL # Re-direct via plex if remote - will lead to the correct SSL
# certificate # certificate
if server['local'] == '1': if server['local'] == '1':
url = server['scheme'] + '://' + server['ip'] + ':' \ url = '%s://%s:%s' \
+ server['port'] % (server['scheme'], server['ip'], server['port'])
else: else:
url = server['baseURL'] url = server['baseURL']
# Deactive SSL verification if the server is local! # Deactive SSL verification if the server is local!
# Watch out - settings is cached by Kodi - use dedicated var!
if server['local'] == '1': if server['local'] == '1':
utils.settings('sslverify', 'false')
self.logMsg("Setting SSL verify to false, because server is "
"local", 1)
verifySSL = False verifySSL = False
else: else:
utils.settings('sslverify', 'true')
self.logMsg("Setting SSL verify to true, because server is "
"not local", 1)
verifySSL = None verifySSL = None
chk = self.plx.CheckConnection(url, chk = self.plx.CheckConnection(url,
server['accesstoken'], server['accesstoken'],
@ -209,66 +208,124 @@ class InitialSetup():
if chk == 401: if chk == 401:
# Not yet authorized for Plex server # Not yet authorized for Plex server
# Please sign in to plex.tv # Please sign in to plex.tv
dialog.ok(self.addonName, self.dialog.ok(self.addonName,
string(39013) + server['name'], self.string(39013) + server['name'],
string(39014)) self.string(39014))
result = self.plx.PlexTvSignInWithPin() if self.PlexTVSignIn() is False:
if result:
plexLogin = result['username']
plexToken = result['token']
plexid = result['plexid']
else:
# Exit while loop if user cancels # Exit while loop if user cancels
server = None
break break
# 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?
resp = dialog.yesno(self.addonName, answ = self.dialog.yesno(self.addonName,
string(39015)) self.string(39015))
# Exit while loop if user chooses No # Exit while loop if user chooses No
if not resp: if not answ:
server = None
break break
# Otherwise: connection worked! # Otherwise: connection worked!
else: else:
isconnected = True
break break
if not isconnected: return server
# Enter Kodi settings instead
xbmc.executebuiltin('Addon.OpenSettings(%s)' % self.addonId) def WritePMStoSettings(self, server):
return """
# Write to Kodi settings file Saves server to file settings. server is a dict of the form:
utils.settings('plex_machineIdentifier', activeServer) {
'name': friendlyName, the Plex server's name
'address': ip:port
'ip': ip, without http/https
'port': port
'scheme': 'http'/'https', nice for checking for secure connections
'local': '1'/'0', Is the server a local server?
'owned': '1'/'0', Is the server owned by the user?
'machineIdentifier': id, Plex server machine identifier
'accesstoken': token Access token to this server
'baseURL': baseURL scheme://ip:port
'ownername' Plex username of PMS owner
}
"""
utils.settings('plex_machineIdentifier', server['machineIdentifier'])
utils.settings('plex_servername', server['name']) utils.settings('plex_servername', server['name'])
utils.settings('plex_serverowned', utils.settings('plex_serverowned',
'true' if server['owned'] == '1' 'true' if server['owned'] == '1'
else 'false') else 'false')
# 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']) utils.settings('ipaddress', server['ip'])
utils.settings('port', server['port']) utils.settings('port', server['port'])
self.logMsg("Setting SSL verify to false, because server is "
"local", 1)
utils.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('//', '')) utils.settings('ipaddress', baseURL[1].replace('//', ''))
utils.settings('port', baseURL[2]) utils.settings('port', baseURL[2])
self.logMsg("Setting SSL verify to true, because server is not "
"local", 1)
utils.settings('sslverify', 'true')
if scheme == 'https': if scheme == 'https':
utils.settings('https', 'true') utils.settings('https', 'true')
else: else:
utils.settings('https', 'false') utils.settings('https', 'false')
# And finally do some logging
self.logMsg("Writing to Kodi user settings file", 0) self.logMsg("Writing to Kodi user settings file", 0)
self.logMsg("PMS machineIdentifier: %s, ip: %s, port: %s, https: %s " self.logMsg("PMS machineIdentifier: %s, ip: %s, port: %s, https: %s "
% (activeServer, server['ip'], server['port'], % (server['machineIdentifier'], server['ip'],
server['scheme']), 0) server['port'], server['scheme']), 0)
if forcePlexTV is True or chooseServer is True: def setup(self, forcePlexTV=False, chooseServer=False):
"""
Initial setup. Run once upon startup.
Check server, user, direct paths, music, direct stream if not direct
path.
"""
self.logMsg("Initial setup called.", 0)
dialog = self.dialog
string = self.string
# Optionally sign into plex.tv. Will not be called on very first run
# as plexToken will be ''
if self.plexToken and self.myplexlogin:
self.CheckPlexTVSignIn()
# If a Plex server IP has already been set
# return only if the right machine identifier is found
getNewPMS = False
if self.server:
self.logMsg("PMS is already set: %s. Checking now..."
% self.server, 0)
getNewPMS = not self.CheckPMS()
if getNewPMS is False:
self.logMsg("Using PMS %s with machineIdentifier %s"
% (self.server, self.serverid), 0)
return
# If not already retrieved myplex info, optionally let user sign in
# to plex.tv. This DOES get called on very first install run
if not self.plexToken and self.myplexlogin:
self.PlexTVSignIn()
server = self.PickPMS()
if server is None:
# Enter Kodi settings instead
xbmc.executebuiltin('Addon.OpenSettings(%s)' % self.addonId)
return return
# Write our chosen server to Kodi settings file
self.WritePMStoSettings(server)
# Additional settings where the user needs to choose
goToSettings = False goToSettings = False
# Direct paths (\\NAS\mymovie.mkv) or addon (http)? # Direct paths (\\NAS\mymovie.mkv) or addon (http)?
if dialog.yesno(heading=self.addonName, if dialog.yesno(self.addonName,
line1=string(39027), string(39027),
line2=string(39028), string(39028),
nolabel="Addon (Default)", nolabel="Addon (Default)",
yeslabel="Native (Direct Paths)"): yeslabel="Native (Direct Paths)"):
self.logMsg("User opted to use direct paths.", 1) self.logMsg("User opted to use direct paths.", 1)