jilo-web/public_html/static/agents.js

216 lines
8.5 KiB
JavaScript
Raw Normal View History

2024-10-01 07:18:53 +00:00
function fetchData(agent_id, url, endpoint, jwtToken, force = false) {
2024-10-02 13:35:10 +00:00
// FIXME make use of force variable
let counter = 0;
2024-10-03 07:59:32 +00:00
const loadCacheButton = document.getElementById('agent' + agent_id + '-cache');
const clearCacheButton = document.getElementById('agent' + agent_id + '-clear');
const resultElement = document.getElementById("result" + agent_id);
2024-10-02 13:35:10 +00:00
const cacheInfoElement = document.getElementById("cacheInfo" + agent_id);
2024-09-27 06:49:50 +00:00
// Show loading text
resultElement.innerHTML = "Loading... (0 seconds)";
// Create an interval to update the counter every second
const intervalId = setInterval(() => {
counter++;
resultElement.innerHTML = `Loading... (${counter} seconds)`;
}, 1000);
2024-09-27 06:49:50 +00:00
// Create an AJAX request
var xhr = new XMLHttpRequest();
2024-09-30 08:55:23 +00:00
const agentUrl = url + endpoint;
2024-10-02 11:04:45 +00:00
// DEBUG show the requested URL for debugging purpose
//console.log("Requesting URL:", agentUrl);
// Handle invalid URL error
try {
2024-09-30 08:55:23 +00:00
xhr.open("POST", agentUrl, true);
} catch (e) {
clearInterval(intervalId); // Stop the counter on error
2024-09-30 08:55:23 +00:00
resultElement.innerHTML = `Error: Invalid URL ${agentUrl}<br />` + e.message;
return; // Exit the function early
}
2024-10-01 07:18:53 +00:00
// send the token
2024-09-27 06:49:50 +00:00
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
2024-10-02 11:04:45 +00:00
xhr.setRequestHeader("Authorization", "Bearer " + jwtToken);
2024-09-27 06:49:50 +00:00
// Set a timeout in milliseconds (10 seconds = 10000 ms)
xhr.timeout = 10000;
// Handle the request state change
2024-09-27 06:49:50 +00:00
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
clearInterval(intervalId); // Stop the counter when the request completes
clearTimeout(requestTimeout); // Clear the timeout if response is received
if (xhr.status === 200) {
try {
// Parse and display the result
let result = JSON.parse(xhr.responseText);
2024-10-02 11:04:45 +00:00
// DEBUG display the result
//console.log(xhr.responseText);
2024-09-30 08:55:23 +00:00
if (result.error) {
resultElement.innerHTML = "Error: " + result.error;
} else {
2024-10-02 13:35:10 +00:00
// show the result in the html
2024-09-30 08:55:23 +00:00
resultElement.innerHTML = JSON.stringify(result, null, 2);
2024-10-02 19:33:09 +00:00
2024-10-03 07:59:32 +00:00
// get the cache timestamp from the session
2024-10-02 19:50:27 +00:00
const now = Date.now();
const cacheTimestamp = new Date(now);
2024-10-02 19:33:09 +00:00
2024-10-03 07:59:32 +00:00
// display the cache retrieval date and time
2024-10-02 19:33:09 +00:00
const formattedDate = cacheTimestamp.toLocaleDateString();
const formattedTime = cacheTimestamp.toLocaleTimeString();
2024-10-03 07:59:32 +00:00
cacheInfoElement.style.display = '';
2024-10-02 19:33:09 +00:00
cacheInfoElement.innerHTML = `cache refreshed on ${formattedDate} at ${formattedTime}`;
2024-10-03 07:59:32 +00:00
// show the cache buttons
loadCacheButton.disabled = false;
loadCacheButton.style.display = '';
clearCacheButton.disabled = false;
clearCacheButton.style.display = '';
2024-10-02 13:35:10 +00:00
// send the result to PHP to store in session
saveResultToSession(result, agent_id);
2024-09-30 08:55:23 +00:00
}
} catch (e) {
// Display the error
resultElement.innerHTML = "Error: Response is not a valid JSON.<br />Response: " + xhr.responseText;
2024-10-02 19:33:09 +00:00
console.error("error:", e);
}
} else {
2024-09-30 08:55:23 +00:00
resultElement.innerHTML = `Error: Unable to fetch data from ${agentUrl}<br />Status Code: ${xhr.status}<br />Status Text: ${xhr.statusText}<br />Response: ${xhr.responseText}`;
}
2024-09-27 06:49:50 +00:00
}
};
// Handle network-level errors (e.g., connection refused)
xhr.onerror = function() {
clearInterval(intervalId); // Stop the counter on error
2024-09-30 08:55:23 +00:00
resultElement.innerHTML = `Network Error:<br />Unable to connect to ${agentUrl}<br />Check network connection or try again later.`;
};
// Handle the timeout event
xhr.ontimeout = function() {
clearInterval(intervalId); // Stop the counter on timeout
resultElement.innerHTML = "Request timed out. Please try again.";
};
// Additional manual timeout
var requestTimeout = setTimeout(function() {
if (xhr.readyState !== 4) {
xhr.abort(); // Abort the request if still pending after timeout
clearInterval(intervalId); // Stop the counter
resultElement.innerHTML = "Request timed out.";
}
}, 10000); // 10 seconds
2024-09-27 06:49:50 +00:00
// Send the AJAX request, with force flag
xhr.send("action=fetch&agent_id=" + agent_id + "&force=" + (force ? 'true' : 'false'));
// // If the request finishes quickly, set this up to show at least 1 second delay
// setTimeout(function() {
// if (counter === 0) {
// counter++;
// resultElement.innerHTML = `Loading... (${counter} seconds)`;
// }
// }, 1000); // Simulate a minimum 1 second delay for testing
2024-09-27 06:49:50 +00:00
}
2024-10-02 13:35:10 +00:00
// 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
2024-10-02 19:50:27 +00:00
const cacheTimestamp = new Date(response.cache_time * 1000);
2024-10-02 13:35:10 +00:00
// 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.";
2024-10-02 19:33:09 +00:00
console.error("error:", e);
2024-10-02 13:35:10 +00:00
}
} 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();
}
2024-10-03 07:59:32 +00:00
// clear cache
function clearCache(agent_id) {
const loadCacheButton = document.getElementById('agent' + agent_id + '-cache');
const clearCacheButton = document.getElementById('agent' + agent_id + '-clear');
const cacheInfoElement = document.getElementById('cacheInfo' + agent_id);
const resultElement = document.getElementById("result" + agent_id);
saveResultToSession(null, agent_id);
// hides the cache buttons
// FIXME add a check whether the saveResult function was successful
loadCacheButton.disabled = true;
loadCacheButton.style.display = 'none';
clearCacheButton.disabled = true;
clearCacheButton.style.display = 'none';
cacheInfoElement.innerHTML = '';
cacheInfoElement.style.display = 'none';
resultElement.innerHTML = 'click a button to to display data from the agent.';
}
2024-10-02 13:35:10 +00:00
// 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));
}