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) {
UI_LANG = getSetting("UI_LANG");
@@ -195,12 +196,8 @@ function getString (key) {
if(isEmpty(result))
{
console.log(`pia_lang_${key}_${lang_code}`)
console.log(key)
{
result = getCache(`pia_lang_${key}_en_us`, true);
console.log(result)
}
return result;

View File

@@ -83,8 +83,15 @@ if ($ENABLED_DARKMODE === True) {
<script>
function updateState(){
getParam("state","Back_App_State", true)
setTimeout("updateState()", 5000);
$.get('api/pialert_app_state.json?nocache=' + Date.now(), function(appState) {
console.log(appState)
document.getElementById('state').innerHTML = appState["currentState"].replaceAll('"', '');
setTimeout("updateState()", 1000);
})
}
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() {

View File

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

View File

@@ -19,6 +19,8 @@ from const import *
from logger import mylog, logResult
#-------------------------------------------------------------------------------
def timeNowTZ():
if isinstance(conf.TIMEZONE, str):
@@ -31,19 +33,46 @@ def timeNowTZ():
def timeNow():
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):
# json file containing the state to communicate with teh frontend
stateFile = apiPath + '/pialert_app_state.json'
# ?? Why is the state written to the DB?
# 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
# The Parameters DB table is used to communicate with the front end.
# update self
self.currentState = currentState
self.lastUpdated = str(timeNowTZ())
#sql = db.sql
# update .json file
write_file(stateFile , json.dumps(self, cls=AppStateEncoder))
mylog('debug', '[updateState] changing state to: "' + newState +'"')
db.sql.execute ("UPDATE Parameters SET par_Value='"+ newState +"' WHERE par_ID='Back_App_State'")
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):
subnets = []
@@ -163,12 +192,9 @@ def collect_lang_strings(db, json, pref, stringSqlParams):
for prop in json["localized"]:
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"]), ""))
# db.commitDB()
# sqlParams = import_language_string(db, language_string["language_code"], pref + "_" + prop, language_string["string"])
return stringSqlParams

View File

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

View File

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

View File

@@ -106,7 +106,7 @@ class plugins_state:
def run_plugin_scripts(db, runType, pluginsState = plugins_state()):
# Header
updateState(db,"Run: Plugins")
updateState("Run: Plugins")
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:
# Header
updateState(db,f"Plugins: {prefix}")
updateState(f"Plugins: {prefix}")
print_plugin_info(plugin, ['display_name'])
mylog('debug', ['[Plugins] CMD: ', get_plugin_setting(plugin, "CMD")["value"]])

View File

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

View File

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