"use strict";
// Global variables for workers dashboard
let workerData = null;
let refreshTimer;
let pageLoadTime = Date.now();
let currentProgress = 0;
const PROGRESS_MAX = 60; // 60 seconds for a complete cycle
let lastUpdateTime = Date.now();
let filterState = {
currentFilter: 'all',
searchTerm: ''
};
let miniChart = null;
let connectionRetryCount = 0;
// Server time variables for uptime calculation - synced with main dashboard
let serverTimeOffset = 0;
let serverStartTime = null;
// New variable to track custom refresh timing
let lastManualRefreshTime = 0;
const MIN_REFRESH_INTERVAL = 10000; // Minimum 10 seconds between refreshes
// Initialize the page
$(document).ready(function() {
// Set up initial UI
initializePage();
// Get server time for uptime calculation
updateServerTime();
// Set up refresh synchronization with main dashboard
setupRefreshSync();
// Fetch worker data immediately on page load
fetchWorkerData();
// Set up refresh timer
setInterval(updateProgressBar, 1000);
// Set up uptime timer - synced with main dashboard
setInterval(updateUptime, 1000);
// Start server time polling - same as main dashboard
setInterval(updateServerTime, 30000);
// Auto-refresh worker data - aligned with main dashboard if possible
setInterval(function() {
// Check if it's been at least PROGRESS_MAX seconds since last update
const timeSinceLastUpdate = Date.now() - lastUpdateTime;
if (timeSinceLastUpdate >= PROGRESS_MAX * 1000) {
// Check if there was a recent manual refresh
const timeSinceManualRefresh = Date.now() - lastManualRefreshTime;
if (timeSinceManualRefresh >= MIN_REFRESH_INTERVAL) {
console.log("Auto-refresh triggered after time interval");
fetchWorkerData();
}
}
}, 10000); // Check every 10 seconds to align better with main dashboard
// Set up filter button click handlers
$('.filter-button').click(function() {
$('.filter-button').removeClass('active');
$(this).addClass('active');
filterState.currentFilter = $(this).data('filter');
filterWorkers();
});
// Set up search input handler
$('#worker-search').on('input', function() {
filterState.searchTerm = $(this).val().toLowerCase();
filterWorkers();
});
});
// Set up refresh synchronization with main dashboard
function setupRefreshSync() {
// Listen for storage events (triggered by main dashboard)
window.addEventListener('storage', function(event) {
// Check if this is our dashboard refresh event
if (event.key === 'dashboardRefreshEvent') {
console.log("Detected dashboard refresh event");
// Prevent too frequent refreshes
const now = Date.now();
const timeSinceLastRefresh = now - lastUpdateTime;
if (timeSinceLastRefresh >= MIN_REFRESH_INTERVAL) {
console.log("Syncing refresh with main dashboard");
// Reset progress bar and immediately fetch
resetProgressBar();
// Refresh the worker data
fetchWorkerData();
} else {
console.log("Skipping too-frequent refresh", timeSinceLastRefresh);
// Just reset the progress bar to match main dashboard
resetProgressBar();
}
}
});
// On page load, check if we should align with main dashboard timing
try {
const lastDashboardRefresh = localStorage.getItem('dashboardRefreshTime');
if (lastDashboardRefresh) {
const lastRefreshTime = parseInt(lastDashboardRefresh);
const timeSinceLastDashboardRefresh = Date.now() - lastRefreshTime;
// If main dashboard refreshed recently, adjust our timer
if (timeSinceLastDashboardRefresh < PROGRESS_MAX * 1000) {
console.log("Adjusting timer to align with main dashboard");
currentProgress = Math.floor(timeSinceLastDashboardRefresh / 1000);
updateProgressBar(currentProgress);
// Calculate when next update will happen (roughly 60 seconds from last dashboard refresh)
const timeUntilNextRefresh = (PROGRESS_MAX * 1000) - timeSinceLastDashboardRefresh;
// Schedule a one-time check near the expected refresh time
if (timeUntilNextRefresh > 0) {
console.log(`Scheduling coordinated refresh in ${Math.floor(timeUntilNextRefresh/1000)} seconds`);
setTimeout(function() {
// Check if a refresh happened in the last few seconds via localStorage event
const newLastRefresh = parseInt(localStorage.getItem('dashboardRefreshTime') || '0');
const secondsSinceLastRefresh = (Date.now() - newLastRefresh) / 1000;
// If dashboard hasn't refreshed in the last 5 seconds, do our own refresh
if (secondsSinceLastRefresh > 5) {
console.log("Coordinated refresh time reached, fetching data");
fetchWorkerData();
} else {
console.log("Dashboard already refreshed recently, skipping coordinated refresh");
}
}, timeUntilNextRefresh);
}
}
}
} catch (e) {
console.error("Error reading dashboard refresh time:", e);
}
// Check for dashboard refresh periodically
setInterval(function() {
try {
const lastDashboardRefresh = parseInt(localStorage.getItem('dashboardRefreshTime') || '0');
const now = Date.now();
const timeSinceLastRefresh = (now - lastUpdateTime) / 1000;
const timeSinceDashboardRefresh = (now - lastDashboardRefresh) / 1000;
// If dashboard refreshed more recently than we did and we haven't refreshed in at least 10 seconds
if (lastDashboardRefresh > lastUpdateTime && timeSinceLastRefresh > 10) {
console.log("Catching up with dashboard refresh");
resetProgressBar();
fetchWorkerData();
}
} catch (e) {
console.error("Error in periodic dashboard check:", e);
}
}, 5000); // Check every 5 seconds
}
// Server time update via polling - same as main.js
function updateServerTime() {
$.ajax({
url: "/api/time",
method: "GET",
timeout: 5000,
success: function(data) {
serverTimeOffset = new Date(data.server_timestamp).getTime() - Date.now();
serverStartTime = new Date(data.server_start_time).getTime();
},
error: function(jqXHR, textStatus, errorThrown) {
console.error("Error fetching server time:", textStatus, errorThrown);
}
});
}
// Update uptime display - synced with main dashboard
function updateUptime() {
if (serverStartTime) {
const currentServerTime = Date.now() + serverTimeOffset;
const diff = currentServerTime - serverStartTime;
const hours = Math.floor(diff / (1000 * 60 * 60));
const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
const seconds = Math.floor((diff % (1000 * 60)) / 1000);
$("#uptimeTimer").html("Uptime: " + hours + "h " + minutes + "m " + seconds + "s");
}
}
// Initialize page elements
function initializePage() {
// Initialize mini chart for total hashrate if the element exists
if (document.getElementById('total-hashrate-chart')) {
initializeMiniChart();
}
// Show loading state
$('#worker-grid').html('
Loading worker data...
');
// Add retry button (hidden by default)
if (!$('#retry-button').length) {
$('body').append('');
$('#retry-button').on('click', function() {
$(this).text('Retrying...').prop('disabled', true);
fetchWorkerData(true);
setTimeout(() => {
$('#retry-button').text('Retry Loading Data').prop('disabled', false);
}, 3000);
});
}
}
// Fetch worker data from API
function fetchWorkerData(forceRefresh = false) {
// Track this as a manual refresh for throttling purposes
lastManualRefreshTime = Date.now();
$('#worker-grid').addClass('loading-fade');
// Update progress bar to show data is being fetched
resetProgressBar();
// Choose API URL based on whether we're forcing a refresh
const apiUrl = `/api/workers${forceRefresh ? '?force=true' : ''}`;
$.ajax({
url: apiUrl,
method: 'GET',
dataType: 'json',
timeout: 15000, // 15 second timeout
success: function(data) {
workerData = data;
lastUpdateTime = Date.now();
// Update UI with new data
updateWorkerGrid();
updateSummaryStats();
updateMiniChart();
updateLastUpdated();
// Hide retry button
$('#retry-button').hide();
// Reset connection retry count
connectionRetryCount = 0;
console.log("Worker data updated successfully");
},
error: function(xhr, status, error) {
console.error("Error fetching worker data:", error);
// Show error in worker grid
$('#worker-grid').html(`