pialert_app_state.json

This commit is contained in:
Jokob-sk
2023-09-16 08:34:14 +10:00
parent 03970f985e
commit 6cb4439d59
9 changed files with 63 additions and 53 deletions

View File

@@ -173,6 +173,7 @@ function cacheStrings()
} }
// Get translated language string
function getString (key) { function getString (key) {
UI_LANG = getSetting("UI_LANG"); UI_LANG = getSetting("UI_LANG");
@@ -196,11 +197,7 @@ function getString (key) {
if(isEmpty(result)) if(isEmpty(result))
{ {
console.log(`pia_lang_${key}_${lang_code}`)
console.log(key)
result = getCache(`pia_lang_${key}_en_us`, true); result = getCache(`pia_lang_${key}_en_us`, true);
console.log(result)
} }
return result; return result;

View File

@@ -83,8 +83,15 @@ if ($ENABLED_DARKMODE === True) {
<script> <script>
function updateState(){ function updateState(){
getParam("state","Back_App_State", true) $.get('api/pialert_app_state.json?nocache=' + Date.now(), function(appState) {
setTimeout("updateState()", 5000);
console.log(appState)
document.getElementById('state').innerHTML = appState["currentState"].replaceAll('"', '');
setTimeout("updateState()", 1000);
})
} }
function show_pia_servertime() { function show_pia_servertime() {
@@ -277,26 +284,6 @@ if ($ENABLED_DARKMODE === True) {
//-------------------------------------------------------------- //--------------------------------------------------------------
//--------------------------------------------------------------
function getParam(targetId, key, skipCache = false) {
skipCacheQuery = "";
if(skipCache)
{
skipCacheQuery = "&skipcache";
}
// get parameter value
$.get('php/server/parameters.php?action=get&defaultValue=NULL&parameter='+ key + skipCacheQuery, function(data) {
var result = data;
document.getElementById(targetId).innerHTML = result.replaceAll('"', '');
});
}
//-------------------------------------------------------------- //--------------------------------------------------------------
function toggleFullscreen() { function toggleFullscreen() {

View File

@@ -134,7 +134,7 @@ def main ():
last_internet_IP_scan = conf.last_internet_IP_scan last_internet_IP_scan = conf.last_internet_IP_scan
# Header # Header
updateState(db,"Process: Start") updateState("Process: Start")
# Timestamp # Timestamp
startTime = loop_start_time startTime = loop_start_time
@@ -197,7 +197,7 @@ def main ():
db.commitDB() db.commitDB()
# Footer # Footer
updateState(db,"Process: Wait") updateState("Process: Wait")
mylog('verbose', ['[MAIN] Process: Wait']) mylog('verbose', ['[MAIN] Process: Wait'])
else: else:
# do something # do something

View File

@@ -19,6 +19,8 @@ from const import *
from logger import mylog, logResult from logger import mylog, logResult
#------------------------------------------------------------------------------- #-------------------------------------------------------------------------------
def timeNowTZ(): def timeNowTZ():
if isinstance(conf.TIMEZONE, str): if isinstance(conf.TIMEZONE, str):
@@ -31,19 +33,46 @@ def timeNowTZ():
def timeNow(): def timeNow():
return datetime.datetime.now().replace(microsecond=0) return datetime.datetime.now().replace(microsecond=0)
#------------------------------------------------------------------------------- #-------------------------------------------------------------------------------
def updateState(db, newState): # A class to manage the application state and to provide a frontend accessible API point
class app_state_class:
def __init__(self, currentState):
# ?? Why is the state written to the DB? # json file containing the state to communicate with teh frontend
# The state is written to the DB so the front-end can use the value to display the current state in the header of the app stateFile = apiPath + '/pialert_app_state.json'
# The Parameters DB table is used to communicate with the front end.
#sql = db.sql # update self
self.currentState = currentState
self.lastUpdated = str(timeNowTZ())
mylog('debug', '[updateState] changing state to: "' + newState +'"') # update .json file
db.sql.execute ("UPDATE Parameters SET par_Value='"+ newState +"' WHERE par_ID='Back_App_State'") write_file(stateFile , json.dumps(self, cls=AppStateEncoder))
def isSet(self):
result = False
if self.currentState != "":
result = True
return result
#-------------------------------------------------------------------------------
# Checks if the object has a __dict__ attribute. If it does, it assumes that it's an instance of a class and serializes its attributes dynamically.
class AppStateEncoder(json.JSONEncoder):
def default(self, obj):
if hasattr(obj, '__dict__'):
# If the object has a '__dict__', assume it's an instance of a class
return obj.__dict__
return super().default(obj)
#-------------------------------------------------------------------------------
def updateState( newState):
state = app_state_class(newState)
db.commitDB()
#------------------------------------------------------------------------------- #-------------------------------------------------------------------------------
def updateSubnets(scan_subnets): def updateSubnets(scan_subnets):
subnets = [] subnets = []
@@ -163,12 +192,9 @@ def collect_lang_strings(db, json, pref, stringSqlParams):
for prop in json["localized"]: for prop in json["localized"]:
for language_string in json[prop]: for language_string in json[prop]:
# db.sql.execute ("""INSERT INTO Plugins_Language_Strings ("Language_Code", "String_Key", "String_Value", "Extra") VALUES (?, ?, ?, ?)""",
stringSqlParams.append((str(language_string["language_code"]), str(pref + "_" + prop), str(language_string["string"]), "")) stringSqlParams.append((str(language_string["language_code"]), str(pref + "_" + prop), str(language_string["string"]), ""))
# db.commitDB()
# sqlParams = import_language_string(db, language_string["language_code"], pref + "_" + prop, language_string["string"])
return stringSqlParams return stringSqlParams

View File

@@ -74,7 +74,7 @@ def importConfigs (db):
return return
# Header # Header
updateState(db,"Import config") updateState("Import config")
mylog('debug', ['[Import Config] importing config file']) mylog('debug', ['[Import Config] importing config file'])
conf.mySettings = [] # reset settings conf.mySettings = [] # reset settings
@@ -198,7 +198,7 @@ def importConfigs (db):
index = 0 index = 0
for plugin in conf.plugins: for plugin in conf.plugins:
# Header # Header
updateState(db,f"Import plugin {index} of {len(conf.plugins)}") updateState(f"Import plugin {index} of {len(conf.plugins)}")
index +=1 index +=1
pref = plugin["unique_prefix"] pref = plugin["unique_prefix"]

View File

@@ -16,7 +16,7 @@ from logger import mylog
def update_devices_MAC_vendors (db, pArg = ''): def update_devices_MAC_vendors (db, pArg = ''):
sql = db.sql # TO-DO sql = db.sql # TO-DO
# Header # Header
updateState(db,"Upkeep: Vendors") updateState("Upkeep: Vendors")
mylog('verbose', ['[', timeNowTZ(), '] Upkeep - Update HW Vendors:' ]) mylog('verbose', ['[', timeNowTZ(), '] Upkeep - Update HW Vendors:' ])
# Update vendors DB (iab oui) # Update vendors DB (iab oui)

View File

@@ -106,7 +106,7 @@ class plugins_state:
def run_plugin_scripts(db, runType, pluginsState = plugins_state()): def run_plugin_scripts(db, runType, pluginsState = plugins_state()):
# Header # Header
updateState(db,"Run: Plugins") updateState("Run: Plugins")
mylog('debug', ['[Plugins] Check if any plugins need to be executed on run type: ', runType]) mylog('debug', ['[Plugins] Check if any plugins need to be executed on run type: ', runType])
@@ -129,7 +129,7 @@ def run_plugin_scripts(db, runType, pluginsState = plugins_state()):
if shouldRun: if shouldRun:
# Header # Header
updateState(db,f"Plugins: {prefix}") updateState(f"Plugins: {prefix}")
print_plugin_info(plugin, ['display_name']) print_plugin_info(plugin, ['display_name'])
mylog('debug', ['[Plugins] CMD: ', get_plugin_setting(plugin, "CMD")["value"]]) mylog('debug', ['[Plugins] CMD: ', get_plugin_setting(plugin, "CMD")["value"]])

View File

@@ -293,38 +293,38 @@ def send_notifications (db):
send_api() send_api()
if conf.REPORT_MAIL and check_config('email'): if conf.REPORT_MAIL and check_config('email'):
updateState(db,"Send: Email") updateState("Send: Email")
mylog('minimal', ['[Notification] Sending report by Email']) mylog('minimal', ['[Notification] Sending report by Email'])
send_email (msg ) send_email (msg )
else : else :
mylog('verbose', ['[Notification] Skip email']) mylog('verbose', ['[Notification] Skip email'])
if conf.REPORT_APPRISE and check_config('apprise'): if conf.REPORT_APPRISE and check_config('apprise'):
updateState(db,"Send: Apprise") updateState("Send: Apprise")
mylog('minimal', ['[Notification] Sending report by Apprise']) mylog('minimal', ['[Notification] Sending report by Apprise'])
send_apprise (msg) send_apprise (msg)
else : else :
mylog('verbose', ['[Notification] Skip Apprise']) mylog('verbose', ['[Notification] Skip Apprise'])
if conf.REPORT_WEBHOOK and check_config('webhook'): if conf.REPORT_WEBHOOK and check_config('webhook'):
updateState(db,"Send: Webhook") updateState("Send: Webhook")
mylog('minimal', ['[Notification] Sending report by Webhook']) mylog('minimal', ['[Notification] Sending report by Webhook'])
send_webhook (msg) send_webhook (msg)
else : else :
mylog('verbose', ['[Notification] Skip webhook']) mylog('verbose', ['[Notification] Skip webhook'])
if conf.REPORT_NTFY and check_config('ntfy'): if conf.REPORT_NTFY and check_config('ntfy'):
updateState(db,"Send: NTFY") updateState("Send: NTFY")
mylog('minimal', ['[Notification] Sending report by NTFY']) mylog('minimal', ['[Notification] Sending report by NTFY'])
send_ntfy (msg) send_ntfy (msg)
else : else :
mylog('verbose', ['[Notification] Skip NTFY']) mylog('verbose', ['[Notification] Skip NTFY'])
if conf.REPORT_PUSHSAFER and check_config('pushsafer'): if conf.REPORT_PUSHSAFER and check_config('pushsafer'):
updateState(db,"Send: PUSHSAFER") updateState("Send: PUSHSAFER")
mylog('minimal', ['[Notification] Sending report by PUSHSAFER']) mylog('minimal', ['[Notification] Sending report by PUSHSAFER'])
send_pushsafer (msg) send_pushsafer (msg)
else : else :
mylog('verbose', ['[Notification] Skip PUSHSAFER']) mylog('verbose', ['[Notification] Skip PUSHSAFER'])
# Update MQTT entities # Update MQTT entities
if conf.REPORT_MQTT and check_config('mqtt'): if conf.REPORT_MQTT and check_config('mqtt'):
updateState(db,"Send: MQTT") updateState("Send: MQTT")
mylog('minimal', ['[Notification] Establishing MQTT thread']) mylog('minimal', ['[Notification] Establishing MQTT thread'])
mqtt_start(db) mqtt_start(db)
else : else :

View File

@@ -21,7 +21,7 @@ from const import logPath
def check_internet_IP ( db ): def check_internet_IP ( db ):
# Header # Header
updateState(db,"Scan: Internet IP") updateState("Scan: Internet IP")
mylog('verbose', ['[Internet IP] Check Internet IP started']) mylog('verbose', ['[Internet IP] Check Internet IP started'])
# Get Internet IP # Get Internet IP