Code refactoring

This commit is contained in:
croneter 2018-02-09 17:48:25 +01:00
parent 90a0c4b545
commit 4fca4ecf63
5 changed files with 125 additions and 122 deletions

View file

@ -7,16 +7,19 @@ import xml.etree.ElementTree as etree
import xbmc
import xbmcgui
from utils import settings, window, language as lang, tryEncode, \
from utils import settings, window, language as lang, tryEncode, tryDecode, \
XmlKodiSetting, reboot_kodi
from migration import check_migration
from downloadutils import DownloadUtils as DU
from userclient import UserClient
from clientinfo import getDeviceId
from PlexAPI import PlexAPI
from PlexFunctions import GetMachineIdentifier, get_PMS_settings
import state
from migration import check_migration
from json_rpc import get_setting, set_setting
import playqueue as PQ
from videonodes import VideoNodes
import state
import variables as v
###############################################################################
@ -25,6 +28,93 @@ LOG = getLogger("PLEX." + __name__)
###############################################################################
WINDOW_PROPERTIES = (
"plex_online", "plex_serverStatus", "plex_onWake", "plex_kodiScan",
"plex_shouldStop", "plex_dbScan", "plex_initialScan",
"plex_customplayqueue", "plex_playbackProps", "pms_token", "plex_token",
"pms_server", "plex_machineIdentifier", "plex_servername",
"plex_authenticated", "PlexUserImage", "useDirectPaths", "countError",
"countUnauthorized", "plex_restricteduser", "plex_allows_mediaDeletion",
"plex_command", "plex_result", "plex_force_transcode_pix"
)
def reload_pkc():
"""
Will reload state.py entirely and then initiate some values from the Kodi
settings file
"""
LOG.info('Start (re-)loading PKC settings')
# Reset state.py
reload(state)
# Reset window props
for prop in WINDOW_PROPERTIES:
window(prop, clear=True)
# Clear video nodes properties
VideoNodes().clearProperties()
# Initializing
state.VERIFY_SSL_CERT = settings('sslverify') == 'true'
state.SSL_CERT_PATH = settings('sslcert') \
if settings('sslcert') != 'None' else None
state.FULL_SYNC_INTERVALL = int(settings('fullSyncInterval')) * 60
state.SYNC_THREAD_NUMBER = int(settings('syncThreadNumber'))
state.SYNC_DIALOG = settings('dbSyncIndicator') == 'true'
state.ENABLE_MUSIC = settings('enableMusic') == 'true'
state.BACKGROUND_SYNC = settings(
'enableBackgroundSync') == 'true'
state.BACKGROUNDSYNC_SAFTYMARGIN = int(
settings('backgroundsync_saftyMargin'))
state.REPLACE_SMB_PATH = settings('replaceSMB') == 'true'
state.REMAP_PATH = settings('remapSMB') == 'true'
state.KODI_PLEX_TIME_OFFSET = float(settings('kodiplextimeoffset'))
state.FETCH_PMS_ITEM_NUMBER = settings('fetch_pms_item_number')
# Init some Queues()
state.COMMAND_PIPELINE_QUEUE = Queue()
state.COMPANION_QUEUE = Queue(maxsize=100)
state.WEBSOCKET_QUEUE = Queue()
set_replace_paths()
set_webserver()
# To detect Kodi profile switches
window('plex_kodiProfile',
value=tryDecode(xbmc.translatePath("special://profile")))
getDeviceId()
# Initialize the PKC playqueues
PQ.init_playqueues()
LOG.info('Done (re-)loading PKC settings')
def set_replace_paths():
"""
Sets our values for direct paths correctly (including using lower-case
protocols like smb:// and NOT SMB://)
"""
for typus in v.REMAP_TYPE_FROM_PLEXTYPE.values():
for arg in ('Org', 'New'):
key = 'remapSMB%s%s' % (typus, arg)
value = settings(key)
if '://' in value:
protocol = value.split('://', 1)[0]
value = value.replace(protocol, protocol.lower())
setattr(state, key, value)
def set_webserver():
"""
Set the Kodi webserver details - used to set the texture cache
"""
if get_setting('services.webserver') in (None, False):
# Enable the webserver, it is disabled
set_setting('services.webserver', True)
# Set standard port and username
# set_setting('services.webserverport', 8080)
# set_setting('services.webserverusername', 'kodi')
# Webserver already enabled
state.WEBSERVER_PORT = get_setting('services.webserverport')
state.WEBSERVER_USERNAME = get_setting('services.webserverusername')
state.WEBSERVER_PASSWORD = get_setting('services.webserverpassword')
class InitialSetup():
def __init__(self):
@ -461,13 +551,6 @@ class InitialSetup():
# Do we need to migrate stuff?
check_migration()
# Initialize the PKC playqueues
PQ.init_playqueues()
# Init some Queues()
state.COMMAND_PIPELINE_QUEUE = Queue()
state.COMPANION_QUEUE = Queue(maxsize=100)
state.WEBSOCKET_QUEUE = Queue()
# If a Plex server IP has already been set
# return only if the right machine identifier is found
if self.server:

View file

@ -10,12 +10,12 @@ from xbmc import Monitor, Player, sleep, getCondVisibility, getInfoLabel, \
from xbmcgui import Window
import plexdb_functions as plexdb
from utils import window, settings, plex_command, thread_methods, \
set_replace_paths
from utils import window, settings, plex_command, thread_methods
from PlexFunctions import scrobble
from kodidb_functions import kodiid_from_filename
from plexbmchelper.subscribers import LOCKER
from playback import playback_triage
from initialsetup import set_replace_paths
import playqueue as PQ
import json_rpc as js
import playlist_func as PL
@ -29,8 +29,7 @@ LOG = getLogger("PLEX." + __name__)
# settings: window-variable
WINDOW_SETTINGS = {
'plex_restricteduser': 'plex_restricteduser',
'force_transcode_pix': 'plex_force_transcode_pix',
'fetch_pms_item_number': 'fetch_pms_item_number'
'force_transcode_pix': 'plex_force_transcode_pix'
}
# settings: state-variable (state.py)
@ -47,7 +46,8 @@ STATE_SETTINGS = {
'remapSMBphotoOrg': 'remapSMBphotoOrg',
'remapSMBphotoNew': 'remapSMBphotoNew',
'enableMusic': 'ENABLE_MUSIC',
'enableBackgroundSync': 'BACKGROUND_SYNC'
'enableBackgroundSync': 'BACKGROUND_SYNC',
'fetch_pms_item_number': 'FETCH_PMS_ITEM_NUMBER'
}
###############################################################################
@ -94,9 +94,6 @@ class KodiMonitor(Monitor):
LOG.debug('PKC window settings changed: %s is now %s',
settings_value, settings(settings_value))
window(window_value, value=settings(settings_value))
if settings_value == 'fetch_pms_item_number':
LOG.info('Requesting playlist/nodes refresh')
plex_command('RUN_LIB_SCAN', 'views')
# Reset the state variables in state.py
for settings_value, state_name in STATE_SETTINGS.iteritems():
new = settings(settings_value)
@ -109,6 +106,9 @@ class KodiMonitor(Monitor):
LOG.debug('PKC state settings %s changed from %s to %s',
settings_value, getattr(state, state_name), new)
setattr(state, state_name, new)
if state_name == 'FETCH_PMS_ITEM_NUMBER':
LOG.info('Requesting playlist/nodes refresh')
plex_command('RUN_LIB_SCAN', 'views')
# Special cases, overwrite all internal settings
set_replace_paths()
state.FULL_SYNC_INTERVALL = int(settings('fullSyncInterval')) * 60

View file

@ -28,6 +28,8 @@ DIRECT_PATHS = False
INDICATE_MEDIA_VERSIONS = False
# Do we need to run a special library scan?
RUN_LIB_SCAN = None
# Number of items to fetch and display in widgets
FETCH_PMS_ITEM_NUMBER = None
# Stemming from the PKC settings.xml
# Shall we show Kodi dialogs when synching?

View file

@ -362,21 +362,6 @@ def create_actor_db_index():
conn.close()
def set_replace_paths():
"""
Sets our values for direct paths correctly (including using lower-case
protocols like smb:// and NOT SMB://)
"""
for typus in v.REMAP_TYPE_FROM_PLEXTYPE.values():
for arg in ('Org', 'New'):
key = 'remapSMB%s%s' % (typus, arg)
value = settings(key)
if '://' in value:
protocol = value.split('://', 1)[0]
value = value.replace(protocol, protocol.lower())
setattr(state, key, value)
def reset():
# Are you sure you want to reset your local Kodi database?
if not dialog('yesno',

View file

@ -9,35 +9,31 @@ from xbmcaddon import Addon
###############################################################################
_addon = Addon(id='plugin.video.plexkodiconnect')
_ADDON = Addon(id='plugin.video.plexkodiconnect')
try:
_addon_path = _addon.getAddonInfo('path').decode('utf-8')
_ADDON_PATH = _ADDON.getAddonInfo('path').decode('utf-8')
except TypeError:
_addon_path = _addon.getAddonInfo('path').decode()
_ADDON_PATH = _ADDON.getAddonInfo('path').decode()
try:
_base_resource = translatePath(os_path.join(
_addon_path,
_BASE_RESOURCE = translatePath(os_path.join(
_ADDON_PATH,
'resources',
'lib')).decode('utf-8')
except TypeError:
_base_resource = translatePath(os_path.join(
_addon_path,
_BASE_RESOURCE = translatePath(os_path.join(
_ADDON_PATH,
'resources',
'lib')).decode()
sys_path.append(_base_resource)
sys_path.append(_BASE_RESOURCE)
###############################################################################
from utils import settings, window, language as lang, dialog, tryDecode, \
set_replace_paths
from utils import settings, window, language as lang, dialog
from userclient import UserClient
import initialsetup
from kodimonitor import KodiMonitor, SpecialMonitor
from librarysync import LibrarySync
import videonodes
from websocket_client import PMS_Websocket, Alexa_Websocket
import downloadutils
import clientinfo
import PlexAPI
from PlexCompanion import PlexCompanion
@ -45,7 +41,6 @@ from command_pipeline import Monitor_Window
from playback_starter import Playback_Starter
from playqueue import PlayqueueMonitor
from artwork import Image_Cache_Thread
from json_rpc import get_setting, set_setting
import variables as v
import state
@ -56,21 +51,6 @@ loghandler.config()
LOG = getLogger("PLEX.service")
###############################################################################
def set_webserver():
"""
Set the Kodi webserver details - used to set the texture cache
"""
if get_setting('services.webserver') in (None, False):
# Enable the webserver, it is disabled
set_setting('services.webserver', True)
# Set standard port and username
# set_setting('services.webserverport', 8080)
# set_setting('services.webserverusername', 'kodi')
# Webserver already enabled
state.WEBSERVER_PORT = get_setting('services.webserverport')
state.WEBSERVER_USERNAME = get_setting('services.webserverusername')
state.WEBSERVER_PASSWORD = get_setting('services.webserverpassword')
class Service():
@ -100,51 +80,9 @@ class Service():
LOG.info("PKC Direct Paths: %s", settings('useDirectPaths') == "true")
LOG.info("Number of sync threads: %s", settings('syncThreadNumber'))
LOG.info("Full sys.argv received: %s", argv)
# Reset window props for profile switch
properties = [
"plex_online", "plex_serverStatus", "plex_onWake",
"plex_kodiScan",
"plex_shouldStop", "plex_dbScan",
"plex_initialScan", "plex_customplayqueue", "plex_playbackProps",
"pms_token", "plex_token",
"pms_server", "plex_machineIdentifier", "plex_servername",
"plex_authenticated", "PlexUserImage", "useDirectPaths",
"countError", "countUnauthorized",
"plex_restricteduser", "plex_allows_mediaDeletion",
"plex_command", "plex_result", "plex_force_transcode_pix"
]
for prop in properties:
window(prop, clear=True)
# Clear video nodes properties
videonodes.VideoNodes().clearProperties()
# Init some stuff
state.VERIFY_SSL_CERT = settings('sslverify') == 'true'
state.SSL_CERT_PATH = settings('sslcert') \
if settings('sslcert') != 'None' else None
state.FULL_SYNC_INTERVALL = int(settings('fullSyncInterval')) * 60
state.SYNC_THREAD_NUMBER = int(settings('syncThreadNumber'))
state.SYNC_DIALOG = settings('dbSyncIndicator') == 'true'
state.ENABLE_MUSIC = settings('enableMusic') == 'true'
state.BACKGROUND_SYNC = settings(
'enableBackgroundSync') == 'true'
state.BACKGROUNDSYNC_SAFTYMARGIN = int(
settings('backgroundsync_saftyMargin'))
state.REPLACE_SMB_PATH = settings('replaceSMB') == 'true'
state.REMAP_PATH = settings('remapSMB') == 'true'
set_replace_paths()
state.KODI_PLEX_TIME_OFFSET = float(settings('kodiplextimeoffset'))
window('plex_minDBVersion', value="2.0.0")
set_webserver()
self.monitor = Monitor()
window('plex_kodiProfile',
value=tryDecode(translatePath("special://profile")))
window('fetch_pms_item_number',
value=settings('fetch_pms_item_number'))
clientinfo.getDeviceId()
# Load/Reset PKC entirely - important for user/Kodi profile switch
initialsetup.reload_pkc()
def __stop_PKC(self):
"""
@ -187,9 +125,8 @@ class Service():
if window('plex_kodiProfile') != kodiProfile:
# Profile change happened, terminate this thread and others
LOG.info("Kodi profile was: %s and changed to: %s. "
"Terminating old PlexKodiConnect thread."
% (kodiProfile,
window('plex_kodiProfile')))
"Terminating old PlexKodiConnect thread.",
kodiProfile, window('plex_kodiProfile'))
break
# Before proceeding, need to make sure:
@ -313,7 +250,7 @@ class Service():
icon='{plex}',
time=5000,
sound=False)
LOG.info("Server %s is online and ready." % server)
LOG.info("Server %s is online and ready.", server)
window('plex_online', value="true")
if state.AUTHENTICATED:
# Server got offline when we were authenticated.
@ -338,28 +275,24 @@ class Service():
# Tell all threads to terminate (e.g. several lib sync threads)
state.STOP_PKC = True
try:
downloadutils.DownloadUtils().stopSession()
except:
pass
window('plex_service_started', clear=True)
LOG.info("======== STOP %s ========" % v.ADDON_NAME)
LOG.info("======== STOP %s ========", v.ADDON_NAME)
# Safety net - Kody starts PKC twice upon first installation!
if window('plex_service_started') == 'true':
exit = True
EXIT = True
else:
window('plex_service_started', value='true')
exit = False
EXIT = False
# Delay option
delay = int(settings('startupDelay'))
DELAY = int(settings('startupDelay'))
LOG.info("Delaying Plex startup by: %s sec..." % delay)
if exit:
LOG.info("Delaying Plex startup by: %s sec...", DELAY)
if EXIT:
LOG.error('PKC service.py already started - exiting this instance')
elif delay and Monitor().waitForAbort(delay):
elif DELAY and Monitor().waitForAbort(DELAY):
# Start the service
LOG.info("Abort requested while waiting. PKC not started.")
else: