From 784532c44da7029b570bee1fc37ffbeb9f71926f Mon Sep 17 00:00:00 2001 From: Yasen Pramatarov Date: Wed, 2 Oct 2024 16:35:10 +0300 Subject: [PATCH] Fixes cache buttons for agents data --- app/pages/agents.php | 33 +++++++++----- app/templates/agent-list.php | 7 +-- public_html/static/agents.js | 76 ++++++++++++++++++++++++++++++++ public_html/static/loadcache.php | 22 +++++++++ 4 files changed, 124 insertions(+), 14 deletions(-) create mode 100644 public_html/static/loadcache.php diff --git a/app/pages/agents.php b/app/pages/agents.php index e232b8e..0186c64 100644 --- a/app/pages/agents.php +++ b/app/pages/agents.php @@ -6,23 +6,34 @@ require '../app/classes/agent.php'; $agentObject = new Agent($dbWeb); -// if a form is submitted, it's from the edit page +// if it's a POST request, it's saving to cache if ($_SERVER['REQUEST_METHOD'] == 'POST') { -// FIXME code here -// header("Location: $app_root?platform=$platform_id&page=config"); -// exit(); + // read the JSON sent from javascript + $data = file_get_contents("php://input"); + $result = json_decode($data, true); - $force = isset($_POST['force']) && $_POST['force'] == 'true'; - $agent_id = $_POST['agent']; - $result = fetchAgent($agent_id, $force); - - if ($result !== false) { - echo $result; // Return the API response as JSON + // store the data in the session + if ($result) { + $_SESSION["agent{$agent}_cache"] = $result; + $_SESSION["agent{$agent}_cache_time"] = time(); // store the cache time + echo json_encode(['status' => 'success']); } else { - echo json_encode(['error' => 'Failed to fetch API data']); + echo json_encode(['status' => 'error', 'message' => 'Invalid data']); } +//// if it's a GET request, it's read/load from cache +//} elseif ($loadcache === true) { +// +// // check if cached data exists in session +// if (isset($_SESSION["agent{$agent}_cache"])) { +// // return the cached data in JSON format +// echo json_encode(['status' => 'success', 'data' => $_SESSION["agent{$agent}_cache"]]); +// } else { +// // if no cached data exists +// echo json_encode(['status' => 'error', 'message' => 'No cached data found']); +// } + // no form submitted, show the templates } else { $agentDetails = $agentObject->getAgentDetails($platform_id); diff --git a/app/templates/agent-list.php b/app/templates/agent-list.php index d37b5d3..75c5748 100644 --- a/app/templates/agent-list.php +++ b/app/templates/agent-list.php @@ -20,9 +20,10 @@ ]; $jwt = $agentObject->generateAgentToken($payload, $agent['secret_key']); ?> - - - + + + + diff --git a/public_html/static/agents.js b/public_html/static/agents.js index e6ccaed..5b69e94 100644 --- a/public_html/static/agents.js +++ b/public_html/static/agents.js @@ -1,7 +1,9 @@ function fetchData(agent_id, url, endpoint, jwtToken, force = false) { + // FIXME make use of force variable let counter = 0; const resultElement = document.getElementById("result" + agent_id); + const cacheInfoElement = document.getElementById("cacheInfo" + agent_id); // Show loading text resultElement.innerHTML = "Loading... (0 seconds)"; @@ -51,7 +53,11 @@ function fetchData(agent_id, url, endpoint, jwtToken, force = false) { if (result.error) { resultElement.innerHTML = "Error: " + result.error; } else { + // show the result in the html resultElement.innerHTML = JSON.stringify(result, null, 2); + cacheInfoElement.innerHTML = ""; + // send the result to PHP to store in session + saveResultToSession(result, agent_id); } } catch (e) { // Display the error @@ -96,3 +102,73 @@ function fetchData(agent_id, url, endpoint, jwtToken, force = false) { // }, 1000); // Simulate a minimum 1 second delay for testing } + + +// load the result from cache +function loadCache(agent_id) { + const resultElement = document.getElementById("result" + agent_id); + const cacheInfoElement = document.getElementById("cacheInfo" + agent_id); + resultElement.innerHTML = "Loading cached data..."; + + // Fetch the cached data from PHP + var xhr = new XMLHttpRequest(); + xhr.open("GET", "static/loadcache.php?agent="+agent_id, true); + xhr.setRequestHeader("Content-Type", "application/json"); + + xhr.onreadystatechange = function() { + if (xhr.readyState === 4) { + if (xhr.status === 200) { + try { + let response = JSON.parse(xhr.responseText); + + if (response.status === 'success') { + // Display the cached data + resultElement.innerHTML = JSON.stringify(response.data, null, 2); + + // Get the cache timestamp from the session + const cacheTimestamp = new Date(response.cache_time); + + // Display the cache retrieval date and time + const formattedDate = cacheTimestamp.toLocaleDateString(); + const formattedTime = cacheTimestamp.toLocaleTimeString(); + cacheInfoElement.innerHTML = `cache retrieved on ${formattedDate} at ${formattedTime}`; + + } else { + resultElement.innerHTML = "No cached data found."; + cacheInfoElement.innerHTML = ""; + } + } catch (e) { + resultElement.innerHTML = "Error loading cached data."; + } + } else { + resultElement.innerHTML = `Error: Unable to load cache. Status code: ${xhr.status}`; + } + } + }; + + xhr.onerror = function() { + resultElement.innerHTML = "Network error occurred while fetching the cached data."; + }; + + xhr.send(); +} + + +// we send result to PHP session, to be available to the whole app +function saveResultToSession(result, agent_id) { + var xhr = new XMLHttpRequest(); + xhr.open("POST", "?page=agents&agent="+agent_id, true); + xhr.setRequestHeader("Content-Type", "application/json"); + + xhr.onreadystatechange = function() { + if (xhr.readyState === 4 && xhr.status === 200) { + console.log("Data saved to session successfully."); + } + }; + + xhr.onerror = function() { + console.error("Error saving data to session."); + }; + + xhr.send(JSON.stringify(result)); +} diff --git a/public_html/static/loadcache.php b/public_html/static/loadcache.php new file mode 100644 index 0000000..e513951 --- /dev/null +++ b/public_html/static/loadcache.php @@ -0,0 +1,22 @@ + 'success', + 'data' => $_SESSION["agent{$agent}_cache"], + 'cache_time' => $_SESSION["agent{$agent}_cache_time"] ?? time() // we store cache time in the session + ]); +} else { + // If no cached data exists + echo json_encode(['status' => 'error', 'message' => 'No cached data found']); +} + +?>