From a44575926f4a340509e332559412d9074b40d116 Mon Sep 17 00:00:00 2001 From: Jokob-sk Date: Sun, 3 Mar 2024 11:38:27 +1100 Subject: [PATCH] =?UTF-8?q?caching=20fixes=20=F0=9F=A9=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 2 +- front/js/handle_version.js | 4 +- front/js/pialert_common.js | 93 +++++++++++++++++++++++++----- front/settings.php | 113 +++++++++++++++++++------------------ 4 files changed, 140 insertions(+), 72 deletions(-) diff --git a/README.md b/README.md index a8bb1d37..dca3f5ae 100755 --- a/README.md +++ b/README.md @@ -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: - + diff --git a/front/js/handle_version.js b/front/js/handle_version.js index 4699da36..5073c7f4 100755 --- a/front/js/handle_version.js +++ b/front/js/handle_version.js @@ -35,8 +35,8 @@ function checkIfNewVersionAvailable() { $.get('api/app_state.json?nocache=' + Date.now(), function(appState) { - console.log(appState["isNewVersionChecked"]) - console.log(appState["isNewVersion"]) + // console.log(appState["isNewVersionChecked"]) + // console.log(appState["isNewVersion"]) // cache value setCookie("isNewVersion", appState["isNewVersion"], 30); diff --git a/front/js/pialert_common.js b/front/js/pialert_common.js index 1ca3bf9a..d3251a33 100755 --- a/front/js/pialert_common.js +++ b/front/js/pialert_common.js @@ -112,7 +112,7 @@ function deleteAllCookies() { function cacheSettings() { - $.get('api/table_settings.json', function(res) { + $.get('api/table_settings.json?nocache=' + Date.now(), function(res) { settingsJSON = res; @@ -124,7 +124,11 @@ function cacheSettings() }) } +// Get a setting value by key function getSetting (key) { + + // handle initial load to make sure everything is set-up and cached + handleFirstLoad() result = getCache(`pia_set_${key}`, true); @@ -146,7 +150,7 @@ function cacheStrings() var allLanguages = ["en_us", "es_es", "de_de"]; // needs to be same as in lang.php 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 Object.entries(res).forEach(([key, value]) => { // Store translations for each key-value pair @@ -157,7 +161,7 @@ function cacheStrings() // 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"]; @@ -170,6 +174,9 @@ function cacheStrings() // Get translated language string function getString (key) { + + // handle initial laod to make sure everything is set-up and cached + handleFirstLoad() UI_LANG = getSetting("UI_LANG"); @@ -368,9 +375,7 @@ function handle_locked_DB(data) // ----------------------------------------------------------------------------- function numberArrayFromString(data) -{ - - +{ data = JSON.parse(sanitize(data)); return data.replace(/\[|\]/g, '').split(',').map(Number); } @@ -771,8 +776,7 @@ function workInProgress() { function showSpinner(stringKey='Loading') { if($("#loadingSpinner").length) - { - + { $("#loadingSpinner").show(); } else{ @@ -818,17 +822,76 @@ function updateApi() } - - // ----------------------------------------------------------------------------- // initialize // ----------------------------------------------------------------------------- -cacheSettings() -cacheStrings() -initDeviceListAll_JSON() -workInProgress() +// Define a unique key for storing the flag in sessionStorage +var sessionStorageKey = "myScriptExecuted_pialert_common"; + +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") diff --git a/front/settings.php b/front/settings.php index 3e54d560..fe85d575 100755 --- a/front/settings.php +++ b/front/settings.php @@ -634,41 +634,6 @@ while ($row = $result -> fetchArray (SQLITE3_ASSOC)) { $('#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() { @@ -677,27 +642,67 @@ while ($row = $result -> fetchArray (SQLITE3_ASSOC)) { showModalOk('WARNING', ""); } else { + var settingsArray = []; - // trigger a save settings event in the backend - $.ajax({ - method: "POST", - url: "php/server/util.php", - data: { - function: 'savesettings', - settings: JSON.stringify(collectSettings()) }, - success: function(data, textStatus) { - - showModalOk ('Result', data ); - - // Remove navigation prompt "Are you sure you want to leave..." - window.onbeforeunload = null; + // collect values for each of the different input form controls + const noConversion = ['text', 'integer', 'string', 'password', 'readonly', 'text.select', 'integer.select', 'text.multiselect']; - // Reloads the current page - setTimeout("window.location.reload()", 3000); + // get settings to determine setting type to store values appropriately + $.get('api/table_settings.json', function(res) { + + settingsJSON = res; + + data = settingsJSON["data"]; + + 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); + + + } + }); + + }) + + } } @@ -747,7 +752,7 @@ while ($row = $result -> fetchArray (SQLITE3_ASSOC)) { } else { - hideSpinner() + hideSpinner() } document.getElementById('lastImportedTime').innerHTML = humanReadable;