caching fixes 🩹

This commit is contained in:
Jokob-sk
2024-03-03 11:38:27 +11:00
parent 6a367c826e
commit a44575926f
4 changed files with 140 additions and 72 deletions

View File

@@ -114,7 +114,7 @@ This project would be nothing without the amazing work of the community, with sp
Here is every one that helped and contributed to this project: Here is every one that helped and contributed to this project:
<a href="https://github.com/usememos/memos/graphs/contributors"> <a href="https://github.com/jokob-sk/pi.alert/graphs/contributors">
<img src="https://contri-graphy.yourselfhosted.com/graph?repo=jokob-sk/pi.alert&format=svg" /> <img src="https://contri-graphy.yourselfhosted.com/graph?repo=jokob-sk/pi.alert&format=svg" />
</a> </a>

View File

@@ -35,8 +35,8 @@ function checkIfNewVersionAvailable()
{ {
$.get('api/app_state.json?nocache=' + Date.now(), function(appState) { $.get('api/app_state.json?nocache=' + Date.now(), function(appState) {
console.log(appState["isNewVersionChecked"]) // console.log(appState["isNewVersionChecked"])
console.log(appState["isNewVersion"]) // console.log(appState["isNewVersion"])
// cache value // cache value
setCookie("isNewVersion", appState["isNewVersion"], 30); setCookie("isNewVersion", appState["isNewVersion"], 30);

View File

@@ -112,7 +112,7 @@ function deleteAllCookies() {
function cacheSettings() function cacheSettings()
{ {
$.get('api/table_settings.json', function(res) { $.get('api/table_settings.json?nocache=' + Date.now(), function(res) {
settingsJSON = res; settingsJSON = res;
@@ -124,8 +124,12 @@ function cacheSettings()
}) })
} }
// Get a setting value by key
function getSetting (key) { function getSetting (key) {
// handle initial load to make sure everything is set-up and cached
handleFirstLoad()
result = getCache(`pia_set_${key}`, true); result = getCache(`pia_set_${key}`, true);
if (result == "") if (result == "")
@@ -146,7 +150,7 @@ function cacheStrings()
var allLanguages = ["en_us", "es_es", "de_de"]; // needs to be same as in lang.php var allLanguages = ["en_us", "es_es", "de_de"]; // needs to be same as in lang.php
allLanguages.forEach(function (language_code) { allLanguages.forEach(function (language_code) {
$.get(`php/templates/language/${language_code}.json`, function (res) { $.get(`php/templates/language/${language_code}.json?nocache=${Date.now()}`, function (res) {
// Iterate over each language // Iterate over each language
Object.entries(res).forEach(([key, value]) => { Object.entries(res).forEach(([key, value]) => {
// Store translations for each key-value pair // Store translations for each key-value pair
@@ -157,7 +161,7 @@ function cacheStrings()
// handle strings and translations from plugins // handle strings and translations from plugins
$.get('api/table_plugins_language_strings.json', function(res) { $.get(`api/table_plugins_language_strings.json?nocache=${Date.now()}`, function(res) {
data = res["data"]; data = res["data"];
@@ -171,6 +175,9 @@ function cacheStrings()
// Get translated language string // Get translated language string
function getString (key) { function getString (key) {
// handle initial laod to make sure everything is set-up and cached
handleFirstLoad()
UI_LANG = getSetting("UI_LANG"); UI_LANG = getSetting("UI_LANG");
lang_code = 'en_us'; lang_code = 'en_us';
@@ -369,8 +376,6 @@ function handle_locked_DB(data)
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
function numberArrayFromString(data) function numberArrayFromString(data)
{ {
data = JSON.parse(sanitize(data)); data = JSON.parse(sanitize(data));
return data.replace(/\[|\]/g, '').split(',').map(Number); return data.replace(/\[|\]/g, '').split(',').map(Number);
} }
@@ -772,7 +777,6 @@ function showSpinner(stringKey='Loading')
{ {
if($("#loadingSpinner").length) if($("#loadingSpinner").length)
{ {
$("#loadingSpinner").show(); $("#loadingSpinner").show();
} }
else{ else{
@@ -818,17 +822,76 @@ function updateApi()
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
// initialize // initialize
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
cacheSettings() // Define a unique key for storing the flag in sessionStorage
cacheStrings() var sessionStorageKey = "myScriptExecuted_pialert_common";
initDeviceListAll_JSON()
workInProgress() function resetInitializedFlag()
{
// Set the flag in sessionStorage to indicate that the code and cahce needs to be reloaded
sessionStorage.setItem(sessionStorageKey, "false");
}
// check if cache needs to be refreshed because of setting changes
$.get('api/app_state.json?nocache=' + Date.now(), function(appState) {
console.log(appState["settingsImported"]*1000)
importedMiliseconds = parseInt((appState["settingsImported"]*1000));
lastReloaded = parseInt(sessionStorage.getItem(sessionStorageKey + '_time'));
if(importedMiliseconds > lastReloaded)
{
resetInitializedFlag()
location.reload();
}
});
// Display spinner and reload page if not yet initialized
function handleFirstLoad()
{
if(!pialert_common_init)
{
setTimeout(function() {
location.reload();
}, 100);
}
}
// Check if the code has been executed before by checking sessionStorage
var pialert_common_init = sessionStorage.getItem(sessionStorageKey) === "true";
// Define a function that will execute the code only once
function executeOnce() {
if (!pialert_common_init) {
showSpinner()
// Your initialization code here
cacheSettings();
cacheStrings();
initDeviceListAll_JSON();
workInProgress();
// Set the flag in sessionStorage to indicate that the code has been executed and save time when last time the page for initialized
sessionStorage.setItem(sessionStorageKey, "true");
const millisecondsNow = Date.now();
sessionStorage.setItem(sessionStorageKey + '_time', millisecondsNow);
console.log("init pialert_common.js");
}
}
// Call the function to execute the code
executeOnce();
console.log("init pialert_common.js")

View File

@@ -634,41 +634,6 @@ while ($row = $result -> fetchArray (SQLITE3_ASSOC)) {
$('#SCAN_SUBNETS').empty(); $('#SCAN_SUBNETS').empty();
} }
// ---------------------------------------------------------
function collectSettings()
{
var settingsArray = [];
// collect values for each of the different input form controls
const noConversion = ['text', 'integer', 'string', 'password', 'readonly', 'text.select', 'integer.select', 'text.multiselect'];
settingsJSON["data"].forEach(set => {
if (noConversion.includes(set['Type'])) {
settingsArray.push([set["Group"], set["Code_Name"], set["Type"], $('#'+set["Code_Name"]).val()]);
} else if (set['Type'] === 'boolean' || set['Type'] === 'integer.checkbox') {
const temp = $(`#${set["Code_Name"]}`).is(':checked') ? 1 : 0;
settingsArray.push([set["Group"], set["Code_Name"], set["Type"], temp]);
} else if (set['Type'] === 'list' || set['Type'] === 'subnets') {
const temps = [];
$(`#${set["Code_Name"]} option`).each(function (i, selected) {
const vl = $(selected).val();
if (vl !== '') {
temps.push(vl);
}
});
settingsArray.push([set["Group"], set["Code_Name"], set["Type"], JSON.stringify(temps)]);
} else if (set['Type'] === 'json') {
const temps = $('#'+set["Code_Name"]).val();
settingsArray.push([set["Group"], set["Code_Name"], set["Type"], temps]);
}
});
return settingsArray;
}
// --------------------------------------------------------- // ---------------------------------------------------------
function saveSettings() { function saveSettings() {
@@ -677,27 +642,67 @@ while ($row = $result -> fetchArray (SQLITE3_ASSOC)) {
showModalOk('WARNING', "<?= lang("settings_missing_block")?>"); showModalOk('WARNING', "<?= lang("settings_missing_block")?>");
} else } else
{ {
var settingsArray = [];
// trigger a save settings event in the backend // collect values for each of the different input form controls
$.ajax({ const noConversion = ['text', 'integer', 'string', 'password', 'readonly', 'text.select', 'integer.select', 'text.multiselect'];
method: "POST",
url: "php/server/util.php",
data: {
function: 'savesettings',
settings: JSON.stringify(collectSettings()) },
success: function(data, textStatus) {
showModalOk ('Result', data ); // get settings to determine setting type to store values appropriately
$.get('api/table_settings.json', function(res) {
// Remove navigation prompt "Are you sure you want to leave..." settingsJSON = res;
window.onbeforeunload = null;
// Reloads the current page data = settingsJSON["data"];
setTimeout("window.location.reload()", 3000);
data.forEach(set => {
if (noConversion.includes(set['Type'])) {
settingsArray.push([set["Group"], set["Code_Name"], set["Type"], $('#'+set["Code_Name"]).val()]);
} else if (set['Type'] === 'boolean' || set['Type'] === 'integer.checkbox') {
const temp = $(`#${set["Code_Name"]}`).is(':checked') ? 1 : 0;
settingsArray.push([set["Group"], set["Code_Name"], set["Type"], temp]);
} else if (set['Type'] === 'list' || set['Type'] === 'subnets') {
const temps = [];
$(`#${set["Code_Name"]} option`).each(function (i, selected) {
const vl = $(selected).val();
if (vl !== '') {
temps.push(vl);
}
});
settingsArray.push([set["Group"], set["Code_Name"], set["Type"], JSON.stringify(temps)]);
} else if (set['Type'] === 'json') {
const temps = $('#'+set["Code_Name"]).val();
settingsArray.push([set["Group"], set["Code_Name"], set["Type"], temps]);
}
});
// trigger a save settings event in the backend
$.ajax({
method: "POST",
url: "php/server/util.php",
data: {
function: 'savesettings',
settings: JSON.stringify(settingsArray) },
success: function(data, textStatus) {
showModalOk ('Result', data );
// Remove navigation prompt "Are you sure you want to leave..."
window.onbeforeunload = null;
// Reloads the current page
setTimeout("window.location.reload()", 3000);
}
});
})
}
});
} }
} }