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
2024-09-30 08:09:01 +00:00
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' ) ;
2024-09-30 08:09:01 +00:00
const resultElement = document . getElementById ( "result" + agent _id ) ;
2024-10-02 13:35:10 +00:00
const cacheInfoElement = document . getElementById ( "cacheInfo" + agent _id ) ;
2024-09-30 08:09:01 +00:00
2024-09-27 06:49:50 +00:00
// Show loading text
2024-09-30 08:09:01 +00:00
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);
2024-09-30 08:09:01 +00:00
// Handle invalid URL error
try {
2024-09-30 08:55:23 +00:00
xhr . open ( "POST" , agentUrl , true ) ;
2024-09-30 08:09:01 +00:00
} 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 ;
2024-09-30 08:09:01 +00:00
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
2024-09-30 08:09:01 +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 ( ) {
2024-09-30 08:09:01 +00:00
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
}
2024-09-30 08:09:01 +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 ) ;
2024-09-30 08:09:01 +00:00
}
} 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-30 08:09:01 +00:00
}
2024-09-27 06:49:50 +00:00
}
} ;
2024-09-30 08:09:01 +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. ` ;
2024-09-30 08:09:01 +00:00
} ;
// 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
2024-09-30 08:09:01 +00:00
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 ) ) ;
}