Download assets/js/game-save-sync.js from EDUrocks/EDUrocks-3.0-frontend-source-code: direct link, hf CLI and curl.
- Browser
- Download file 51.6 kB
-
https://huggingface.co/datasets/EDUrocks/EDUrocks-3.0-frontend-source-code/resolve/main/assets/js/game-save-sync.js
- Command line
-
hf download hf://datasets/EDUrocks/EDUrocks-3.0-frontend-source-code/assets/js/game-save-sync.js
-
curl -L -o game-save-sync.js https://huggingface.co/datasets/EDUrocks/EDUrocks-3.0-frontend-source-code/resolve/main/assets/js/game-save-sync.js
51.6 kB
/**
* EDUrocks 3.0 - Universal Game Save Sync System
* Complete all-in-one solution for save syncing, achievements, notifications, and overlay
* Supports: localStorage
*/
(function() {
'use strict';
// ==================== CONFIGURATION ====================
const CONFIG = {
SYNC_INTERVAL: 10000, // Sync every 10 seconds
HEARTBEAT_INTERVAL: 30000, // Heartbeat every 30 seconds
ACHIEVEMENT_CHECK_INTERVAL: 60000, // Check achievements every minute
NOTIFICATION_CHECK_INTERVAL: 300000, // Check notifications every 5 minutes
};
// Blacklist - never sync these keys
const BLACKLIST = [
/^edurocks_/i,
/cache/i,
/^__/
];
// ==================== STATE ====================
let gameId = null;
let gameName = null;
let isLoggedIn = false;
let authToken = null;
let userUuid = null;
let sessionId = null;
let sessionStartTime = null;
let lastSyncedPlayTime = 0; // Track last synced playtime for delta calculations
let totalPausedTime = 0; // Track total time the tab was inactive
let lastPauseTime = null; // When the tab became inactive
let isTabActive = true; // Track if tab is currently active
let syncQueue = new Map();
let isSyncing = false;
let overlayInstance = null;
let isRestoring = false; // Flag to prevent restore from triggering sync
let originalSetItem = null; // Store original for bypass during restore
let originalRemoveItem = null;
let originalClear = null;
// ==================== UTILITY FUNCTIONS ====================
function getApiUrl() {
if (window.eduBackendRoot) {
return window.eduBackendRoot + '/userauth';
}
const hostname = window.location.hostname;
const isIP = /^(\d{1,3}\.){3}\d{1,3}$/.test(hostname) || /^[0-9a-fA-F:]+$/.test(hostname);
const isLocal = hostname === 'localhost' || hostname.endsWith('.local') || hostname === '127.0.0.1' || hostname === '::1';
if (hostname === 'devbuild.edurocks.org' || isIP || isLocal) {
return 'https://backendapi.edurocks.org/userauth';
}
const domain = hostname.replace(/^www\./, "");
return `https://backendapi.${domain}/userauth`;
}
// Don't cache the URL - always call getApiUrl() to pick up AWS overrides
// const API_URL = getApiUrl() + '/game-api.php';
function getGameId() {
const pathParts = window.location.pathname.split('/').filter(p => p);
return pathParts[pathParts.length - 2] || pathParts[pathParts.length - 1] || 'unknown';
}
function getGameName() {
return document.title || gameId;
}
function shouldSyncKey(key) {
for (const pattern of BLACKLIST) {
if (pattern.test(key)) return false;
}
return true;
}
// Calculate active playtime (excluding time when tab was inactive)
function getActivePlayTime() {
if (!sessionStartTime) return 0;
const totalElapsed = Date.now() - sessionStartTime;
const activeTime = totalElapsed - totalPausedTime;
// If currently paused, subtract current pause duration
if (!isTabActive && lastPauseTime) {
const currentPauseDuration = Date.now() - lastPauseTime;
return Math.floor((activeTime - currentPauseDuration) / 1000);
}
return Math.floor(activeTime / 1000);
}
// Handle tab visibility changes
function setupVisibilityTracking() {
const handleVisibilityChange = () => {
if (document.hidden) {
// Tab became inactive
isTabActive = false;
lastPauseTime = Date.now();
console.log('[SaveSync] βΈοΈ Tab inactive - pausing playtime tracking');
} else {
// Tab became active again
if (!isTabActive && lastPauseTime) {
const pauseDuration = Date.now() - lastPauseTime;
totalPausedTime += pauseDuration;
console.log('[SaveSync] βΆοΈ Tab active - resuming playtime tracking (paused for', Math.floor(pauseDuration / 1000), 'seconds)');
}
isTabActive = true;
lastPauseTime = null;
}
};
document.addEventListener('visibilitychange', handleVisibilityChange);
// Also track window focus/blur as backup
window.addEventListener('blur', () => {
if (isTabActive) {
handleVisibilityChange();
}
});
window.addEventListener('focus', () => {
if (!isTabActive) {
handleVisibilityChange();
}
});
console.log('[SaveSync] Visibility tracking initialized');
}
// ==================== LOCALSTORAGE INTERCEPTION ====================
function interceptLocalStorage() {
// Store original methods globally for use during restore
originalSetItem = Storage.prototype.setItem;
originalRemoveItem = Storage.prototype.removeItem;
originalClear = Storage.prototype.clear;
Storage.prototype.setItem = function(key, value) {
originalSetItem.call(this, key, value);
// Don't queue if we're restoring from backend
if (this === window.localStorage && shouldSyncKey(key) && !isRestoring) {
queueSync(`localStorage:${key}`, value, 'localStorage');
}
};
Storage.prototype.removeItem = function(key) {
originalRemoveItem.call(this, key);
// Don't queue if we're restoring from backend
if (this === window.localStorage && shouldSyncKey(key) && !isRestoring) {
queueSync(`localStorage:${key}`, null, 'localStorage');
}
};
Storage.prototype.clear = function() {
if (this === window.localStorage) {
// Create array of keys to avoid iteration issues
const keysToDelete = [];
for (let i = 0; i < this.length; i++) {
const key = this.key(i);
if (shouldSyncKey(key)) {
keysToDelete.push(key);
}
}
// Queue deletions (unless restoring)
if (!isRestoring) {
for (const key of keysToDelete) {
queueSync(`localStorage:${key}`, null, 'localStorage');
}
}
}
originalClear.call(this);
};
console.log('[SaveSync] localStorage intercepted');
}
// ==================== SYNC QUEUE ====================
function queueSync(key, value, type) {
const clientTimestamp = new Date().toISOString();
syncQueue.set(key, { value, type, clientTimestamp });
console.log('[SaveSync] Queued:', key, '- Size:', value ? value.length : 0, 'bytes');
}
async function forceSync(key, data, force = false) {
console.log('[SaveSync] Force syncing:', key);
isSyncing = true;
if (overlayInstance) overlayInstance.setSyncStatus('syncing');
try {
const response = await fetch(`${getApiUrl()}/game-api.php?action=setSave`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${authToken}` },
credentials: 'include',
body: JSON.stringify({
gameId,
saveKey: key,
saveValue: data.value,
clientTimestamp: data.clientTimestamp,
force: force
})
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
if (overlayInstance) overlayInstance.setSyncStatus('success');
console.log('[SaveSync] Force sync completed successfully');
} catch (error) {
console.error('[SaveSync] Force sync error:', error);
if (overlayInstance) overlayInstance.setSyncStatus('error');
} finally {
isSyncing = false;
}
}
async function syncToBackend() {
if (!isLoggedIn || !gameId || isSyncing || syncQueue.size === 0) return;
console.log('[SaveSync] Starting sync of', syncQueue.size, 'items');
isSyncing = true;
const itemsToSync = new Map(syncQueue);
// DON'T clear queue yet - only clear successfully synced items
if (overlayInstance) overlayInstance.setSyncStatus('syncing');
const successfullySynced = [];
let hasErrors = false;
try {
for (const [key, data] of itemsToSync) {
let response;
try {
if (data.value === null) {
response = await fetch(`${getApiUrl()}/game-api.php?action=deleteSave`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${authToken}` },
credentials: 'include',
body: JSON.stringify({ gameId, saveKey: key })
});
} else {
response = await fetch(`${API_URL}?action=setSave`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${authToken}` },
credentials: 'include',
body: JSON.stringify({
gameId,
saveKey: key,
saveValue: data.value,
clientTimestamp: data.clientTimestamp
})
});
}
if (response.status === 409) { // Conflict
const conflictData = await response.json();
console.warn('[SaveSync] Conflict detected for key:', key);
showConflictModal(key, data, conflictData.serverSave);
successfullySynced.push(key); // Remove from queue even on conflict
} else if (response.ok) {
successfullySynced.push(key);
} else {
// Try to get error details before throwing
let errorDetails = null;
try {
errorDetails = await response.json();
console.error('[SaveSync] β Backend error for key:', key, errorDetails);
} catch (e) {
console.error('[SaveSync] β Could not parse error response for key:', key);
}
throw new Error(`HTTP error! status: ${response.status}${errorDetails ? ' - ' + (errorDetails.details || errorDetails.error) : ''}`);
}
} catch (error) {
console.error('[SaveSync] Failed to sync key:', key, error);
hasErrors = true;
// Don't add to successfullySynced - will retry next time
}
}
// After the loop, try to extract error details from failed responses
if (hasErrors) {
for (const [key, data] of itemsToSync) {
if (!successfullySynced.includes(key)) {
console.error('[SaveSync] β Failed key details:', {
key: key,
valueLength: data.value ? data.value.length : 0,
timestamp: data.clientTimestamp
});
}
}
}
// Only remove successfully synced items from queue
for (const key of successfullySynced) {
syncQueue.delete(key);
}
if (overlayInstance) overlayInstance.setSyncStatus(hasErrors ? 'error' : 'success');
console.log('[SaveSync] Sync completed -', successfullySynced.length, 'synced,',
(itemsToSync.size - successfullySynced.length), 'failed (will retry)');
} catch (error) {
console.error('[SaveSync] Sync error:', error);
if (overlayInstance) overlayInstance.setSyncStatus('error');
} finally {
isSyncing = false;
}
}
async function loadSavesFromBackend() {
if (!isLoggedIn || !gameId) return;
try {
console.log('[SaveSync] Loading saves for game:', gameId);
const response = await fetch(`${getApiUrl()}/game-api.php?action=getSaves&gameId=${encodeURIComponent(gameId)}&token=${authToken}`, {
credentials: 'include'
});
if (!response.ok) {
console.warn('[SaveSync] Failed to load saves, status:', response.status);
return;
}
const data = await response.json();
console.log('[SaveSync] Received data:', data);
if (data.success && data.saves) {
const saveKeys = Object.keys(data.saves);
console.log('[SaveSync] Found', saveKeys.length, 'saves:', saveKeys);
// Set restoring flag to prevent interceptor from queueing
isRestoring = true;
let hasRestoredSaves = false;
for (const key of saveKeys) {
const saveData = data.saves[key];
console.log('[SaveSync] Restoring save:', key, 'value length:', saveData.value?.length);
await restoreSave(key, saveData.value);
hasRestoredSaves = true;
}
// Clear flag after all saves restored
isRestoring = false;
console.log('[SaveSync] Loaded', saveKeys.length, 'saves from backend');
// Auto-reload to apply restored saves ONLY on first load
// Check if this is first load by looking for a session flag
const hasReloadedKey = `edurocks_reloaded_${gameId}`;
const hasAlreadyReloaded = sessionStorage.getItem(hasReloadedKey);
if (hasRestoredSaves && saveKeys.length > 0 && !hasAlreadyReloaded) {
console.log('[SaveSync] π First load with saves detected, reloading page to apply...');
// Mark that we're about to reload
sessionStorage.setItem(hasReloadedKey, 'true');
// Check if we're in an iframe
if (window.self !== window.top) {
// We're in an iframe - reload just the iframe
setTimeout(() => {
window.location.reload();
}, 500);
} else {
// We're in a normal tab - reload the page
setTimeout(() => {
window.location.reload();
}, 500);
}
} else if (hasAlreadyReloaded) {
console.log('[SaveSync] β
Already reloaded once, skipping auto-reload');
}
} else {
console.log('[SaveSync] No saves found or invalid response');
}
} catch (error) {
console.error('[SaveSync] Error loading saves:', error);
isRestoring = false; // Ensure flag is cleared on error
}
}
async function restoreSave(key, value) {
try {
console.log('[SaveSync] restoreSave called with key:', key);
if (key.startsWith('localStorage:')) {
const actualKey = key.replace('localStorage:', '');
localStorage.setItem(actualKey, value);
console.log('[SaveSync] Restored localStorage:', actualKey);
} else {
// Key doesn't have prefix, assume it's localStorage
console.log('[SaveSync] Key has no prefix, assuming localStorage:', key);
localStorage.setItem(key, value);
console.log('[SaveSync] Restored to localStorage (no prefix):', key);
}
} catch (error) {
console.error('[SaveSync] Error restoring save:', key, error);
}
}
// ==================== SAVE HISTORY & CONFLICT ====================
function showConflictModal(key, localSave, serverSave) {
const modal = document.createElement('div');
modal.style.cssText = `position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.7); z-index: 99999; display: flex; align-items: center; justify-content: center;`;
modal.innerHTML = `
<div style="background: #2a1a20; padding: 20px; border-radius: 8px; text-align: center; color: white; border: 1px solid #F4154D;">
<h2>Save Conflict</h2>
<p>A newer save file was found on the server.</p>
<p><b>Your local save:</b> ${new Date(localSave.clientTimestamp).toLocaleString()}</p>
<p><b>Cloud save:</b> ${new Date(serverSave.lastModified).toLocaleString()}</p>
<p>Which version would you like to keep?</p>
<button id="keep-local" style="padding: 10px 20px; margin: 10px; border-radius: 5px; border: none; background: #F4154D; color: white; cursor: pointer;">Keep My Local Save</button>
<button id="use-server" style="padding: 10px 20px; margin: 10px; border-radius: 5px; border: none; background: #6b7280; color: white; cursor: pointer;">Use Cloud Save</button>
</div>
`;
document.body.appendChild(modal);
document.getElementById('keep-local').onclick = () => {
forceSync(key, localSave, true);
document.body.removeChild(modal);
};
document.getElementById('use-server').onclick = () => {
restoreSave(key, serverSave.value);
location.reload();
};
}
async function showHistoryModal() {
// For simplicity, we'll manage history for the most recently changed key.
// A more robust implementation would let the user pick which save key's history to view.
const lastKey = Array.from(syncQueue.keys()).pop() || 'localStorage:game_slot_1'; // Fallback for demo
try {
const response = await fetch(`${getApiUrl()}/game-api.php?action=getHistory&gameId=${gameId}&saveKey=${lastKey}&token=${authToken}`);
const data = await response.json();
if (!data.success || data.history.length === 0) {
alert('No save history found for this game.');
return;
}
const modal = document.createElement('div');
modal.style.cssText = `position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.7); z-index: 99999; display: flex; align-items: center; justify-content: center;`;
let historyHtml = data.history.map(h => `
<div style="display: flex; justify-content: space-between; align-items: center; padding: 10px; border-bottom: 1px solid #444;">
<span>${new Date(h.saved_at).toLocaleString()}</span>
<button class="restore-history-btn" data-history-id="${h.id}" style="padding: 5px 10px; border-radius: 5px; border: none; background: #F4154D; color: white; cursor: pointer;">Restore</button>
</div>
`).join('');
modal.innerHTML = `
<div style="background: #2a1a20; padding: 20px; border-radius: 8px; color: white; border: 1px solid #F4154D; width: 400px;">
<h2 style="text-align: center;">Save History</h2>
<div style="max-height: 300px; overflow-y: auto; margin-top: 15px;">
${historyHtml}
</div>
<button id="close-history" style="width: 100%; padding: 10px; margin-top: 15px; border-radius: 5px; border: none; background: #6b7280; color: white; cursor: pointer;">Close</button>
</div>
`;
document.body.appendChild(modal);
document.getElementById('close-history').onclick = () => {
document.body.removeChild(modal);
};
document.querySelectorAll('.restore-history-btn').forEach(btn => {
btn.onclick = async (e) => {
const historyId = e.target.dataset.historyId;
await restoreFromHistory(historyId);
document.body.removeChild(modal);
};
});
} catch (error) {
console.error('Failed to get save history:', error);
alert('Could not retrieve save history.');
}
}
async function restoreFromHistory(historyId) {
try {
const response = await fetch(`${getApiUrl()}/game-api.php?action=restoreHistory`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${authToken}` },
body: JSON.stringify({ historyId })
});
const data = await response.json();
if (data.success) {
alert('Save restored successfully! The game will now reload.');
location.reload();
} else {
throw new Error(data.error || 'Failed to restore save.');
}
} catch (error) {
console.error('Failed to restore from history:', error);
alert('Could not restore the selected save.');
}
}
// ==================== SESSION MANAGEMENT ====================
async function startSession() {
if (!isLoggedIn || !gameId) return;
sessionStartTime = Date.now();
try {
const response = await fetch(`${getApiUrl()}/game-api.php?action=startSession`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${authToken}` },
credentials: 'include',
body: JSON.stringify({
gameId,
gameName,
deviceInfo: navigator.userAgent
})
});
const data = await response.json();
if (data.success) {
sessionId = data.sessionId;
console.log('[SaveSync] Session started:', sessionId, 'for game:', gameId);
} else {
console.error('[SaveSync] Failed to start session:', data.error);
}
} catch (error) {
console.error('[SaveSync] Error starting session:', error);
}
}
async function heartbeat() {
if (!isLoggedIn || !sessionId) return;
const playTime = getActivePlayTime(); // Only count time when tab is active
try {
const response = await fetch(`${getApiUrl()}/game-api.php?action=heartbeat`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${authToken}` },
credentials: 'include',
body: JSON.stringify({
sessionId,
playTime,
gameId,
lastSyncedPlayTime
})
});
const data = await response.json();
if (data.success) {
// Update lastSyncedPlayTime after successful heartbeat
lastSyncedPlayTime = playTime;
console.log('[SaveSync] β
Heartbeat sent - PlayTime:', playTime, 'seconds (Live update sent to database)');
// Clear user stats cache so dashboard shows updated playtime live
if (window.Auth && window.Auth.clearUserStatsCache) {
window.Auth.clearUserStatsCache();
}
}
if (overlayInstance) overlayInstance.updatePlaytime(playTime);
} catch (error) {
console.error('[SaveSync] Heartbeat error:', error);
}
}
async function endSession() {
if (!isLoggedIn || !sessionId) return;
const playTime = getActivePlayTime(); // Only count time when tab is active
try {
await fetch(`${getApiUrl()}/game-api.php?action=endSession`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${authToken}` },
credentials: 'include',
body: JSON.stringify({
sessionId,
playTime,
gameId,
lastSyncedPlayTime
})
});
console.log('[SaveSync] Session ended, playTime:', playTime, 'seconds (final delta synced)');
// Clear user stats cache so dashboard shows updated playtime
if (window.Auth && window.Auth.clearUserStatsCache) {
window.Auth.clearUserStatsCache();
console.log('[SaveSync] Cleared user stats cache for fresh dashboard data');
}
} catch (error) {
console.error('[SaveSync] Error ending session:', error);
}
}
// Final sync on page unload - uses sendBeacon for reliability
function finalSyncOnUnload() {
if (!isLoggedIn || !gameId || syncQueue.size === 0) {
return;
}
console.log('[SaveSync] Final sync before unload -', syncQueue.size, 'items');
// Try to sync all pending items using sendBeacon (more reliable on unload)
for (const [key, data] of syncQueue) {
try {
// Include auth token in URL for sendBeacon compatibility
const action = data.value === null ? 'deleteSave' : 'setSave';
const url = `${getApiUrl()}/game-api.php?action=${action}`;
const payload = JSON.stringify({
gameId,
saveKey: key,
saveValue: data.value,
clientTimestamp: data.clientTimestamp,
token: authToken // Include token in payload since headers don't work with sendBeacon
});
// Use sendBeacon if available (most reliable for unload)
if (navigator.sendBeacon) {
const blob = new Blob([payload], { type: 'application/json' });
navigator.sendBeacon(url, blob);
} else {
// Fallback to synchronous XHR (less ideal but works)
const xhr = new XMLHttpRequest();
xhr.open('POST', url, false); // synchronous
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.setRequestHeader('Authorization', `Bearer ${authToken}`);
xhr.send(payload);
}
} catch (error) {
console.error('[SaveSync] Error in final sync for key:', key, error);
}
}
}
// ==================== HISTORY & RESTORE ====================
async function showHistoryModal() {
if (!gameId) {
alert('No game context available');
return;
}
// Get all saves for this game first
try {
const response = await fetch(`${getApiUrl()}/game-api.php?action=getGameSaves&gameId=${encodeURIComponent(gameId)}&token=${authToken}`, {
credentials: 'include'
});
const data = await response.json();
if (!data.success || !data.saves || data.saves.length === 0) {
alert('No saves found for this game');
return;
}
// Build modal HTML
let savesListHtml = '<div style="max-height: 400px; overflow-y: auto;">';
for (const save of data.saves) {
const saveKeyDisplay = save.save_key.replace(/^(localStorage:|indexedDB:)/, '');
savesListHtml += `
<div style="background: rgba(255,255,255,0.05); border: 1px solid rgba(139, 74, 122, 0.3); border-radius: 8px; padding: 12px; margin-bottom: 12px;">
<div style="font-weight: 600; margin-bottom: 8px;">${saveKeyDisplay}</div>
<div style="font-size: 12px; color: rgba(255,255,255,0.6); margin-bottom: 8px;">
Size: ${formatBytes(parseInt(save.size || 0))} β’ Last modified: ${new Date(save.last_modified).toLocaleString()}
</div>
<button onclick="window.viewSaveHistory('${save.save_key}')" style="width: 100%; background: rgba(139, 74, 122, 0.3); border: 1px solid rgba(139, 74, 122, 0.5); color: white; padding: 8px; border-radius: 6px; cursor: pointer; font-size: 13px;">
π View History
</button>
</div>
`;
}
savesListHtml += '</div>';
// Create modal
const modal = document.createElement('div');
modal.id = 'history-modal';
modal.style.cssText = 'position: fixed; inset: 0; background: rgba(0,0,0,0.8); z-index: 2147483646; display: flex; align-items: center; justify-content: center; padding: 20px;';
modal.innerHTML = `
<div style="background: #1a1a1a; border: 1px solid rgba(139, 74, 122, 0.3); border-radius: 16px; max-width: 600px; width: 100%; max-height: 90vh; overflow: hidden; display: flex; flex-direction: column;">
<div style="background: linear-gradient(135deg, #F4154D 0%, #a855a0 100%); padding: 20px; display: flex; justify-content: space-between; align-items: center;">
<div style="font-size: 20px; font-weight: 600; color: white;">π Save History - ${gameId}</div>
<button onclick="document.getElementById('history-modal').remove()" style="background: none; border: none; color: white; font-size: 28px; cursor: pointer; padding: 0; line-height: 1;">×</button>
</div>
<div style="padding: 20px; color: white; overflow-y: auto;">
<div style="font-size: 14px; color: rgba(255,255,255,0.7); margin-bottom: 16px;">
Select a save slot to view its history:
</div>
${savesListHtml}
</div>
</div>
`;
modal.onclick = (e) => { if (e.target === modal) modal.remove(); };
document.body.appendChild(modal);
} catch (error) {
console.error('[SaveSync] Error loading save history:', error);
alert('Failed to load save history: ' + error.message);
}
}
window.viewSaveHistory = async function(saveKey) {
try {
const response = await fetch(`${getApiUrl()}/game-api.php?action=getHistory&gameId=${encodeURIComponent(gameId)}&saveKey=${encodeURIComponent(saveKey)}&token=${authToken}`, {
credentials: 'include'
});
const data = await response.json();
if (!data.success || !data.history || data.history.length === 0) {
alert('No history found for this save slot');
return;
}
const saveKeyDisplay = saveKey.replace(/^(localStorage:|indexedDB:)/, '');
// Build history list HTML
let historyListHtml = '<div style="max-height: 400px; overflow-y: auto;">';
for (const entry of data.history) {
const timestamp = new Date(entry.saved_at).toLocaleString();
const clientTimestamp = entry.client_timestamp ? new Date(entry.client_timestamp).toLocaleString() : 'N/A';
historyListHtml += `
<div style="background: rgba(255,255,255,0.05); border: 1px solid rgba(139, 74, 122, 0.3); border-radius: 8px; padding: 12px; margin-bottom: 12px;">
<div style="display: flex; justify-content: space-between; align-items: start; margin-bottom: 8px;">
<div>
<div style="font-size: 14px; font-weight: 600;">Version #${entry.id}</div>
<div style="font-size: 12px; color: rgba(255,255,255,0.6); margin-top: 4px;">
Saved: ${timestamp}<br>
Client: ${clientTimestamp}
</div>
</div>
<button onclick="window.restoreFromHistory(${entry.id}, '${saveKey}')" style="background: rgba(16, 185, 129, 0.2); border: 1px solid rgba(16, 185, 129, 0.5); color: #10b981; padding: 6px 12px; border-radius: 6px; cursor: pointer; font-size: 12px; font-weight: 600;">
β» Restore
</button>
</div>
</div>
`;
}
historyListHtml += '</div>';
// Replace modal content
const modal = document.getElementById('history-modal');
if (modal) {
modal.innerHTML = `
<div style="background: #1a1a1a; border: 1px solid rgba(139, 74, 122, 0.3); border-radius: 16px; max-width: 600px; width: 100%; max-height: 90vh; overflow: hidden; display: flex; flex-direction: column;">
<div style="background: linear-gradient(135deg, #F4154D 0%, #a855a0 100%); padding: 20px; display: flex; justify-content: space-between; align-items: center;">
<div>
<div style="font-size: 20px; font-weight: 600; color: white;">π History: ${saveKeyDisplay}</div>
<button onclick="window.showHistoryModal ? window.showHistoryModal() : document.getElementById('history-modal').remove()" style="background: none; border: none; color: rgba(255,255,255,0.8); font-size: 12px; cursor: pointer; padding: 0; margin-top: 4px;">β Back to saves</button>
</div>
<button onclick="document.getElementById('history-modal').remove()" style="background: none; border: none; color: white; font-size: 28px; cursor: pointer; padding: 0; line-height: 1;">×</button>
</div>
<div style="padding: 20px; color: white; overflow-y: auto;">
<div style="font-size: 14px; color: rgba(255,255,255,0.7); margin-bottom: 16px;">
Found ${data.history.length} previous version(s). Click "Restore" to load an older save.
</div>
${historyListHtml}
</div>
</div>
`;
}
} catch (error) {
console.error('[SaveSync] Error loading save history details:', error);
alert('Failed to load history: ' + error.message);
}
};
window.restoreFromHistory = async function(historyId, saveKey) {
if (!confirm('This will replace your current save with this older version. Continue?')) {
return;
}
try {
const response = await fetch(`${getApiUrl()}/game-api.php?action=restoreHistory`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${authToken}` },
credentials: 'include',
body: JSON.stringify({ historyId })
});
const data = await response.json();
if (!data.success) {
throw new Error(data.error || 'Failed to restore');
}
// Update localStorage immediately with restored value
if (data.save && data.save.save_value !== null) {
const actualKey = saveKey.replace(/^localStorage:/, '');
isRestoring = true;
localStorage.setItem(actualKey, data.save.save_value);
isRestoring = false;
console.log('[SaveSync] β
Restored save from history:', saveKey);
alert('Save restored successfully! The page will reload to apply changes.');
// Reload the page to ensure game picks up the restored save
window.location.reload();
} else {
throw new Error('No save data in response');
}
} catch (error) {
console.error('[SaveSync] Error restoring from history:', error);
alert('Failed to restore save: ' + error.message);
}
};
function formatBytes(bytes) {
if (!bytes || bytes === 0) return '0 B';
if (bytes < 1024) return bytes + ' B';
if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + ' KB';
return (bytes / 1024 / 1024).toFixed(1) + ' MB';
}
// Make showHistoryModal available globally for overlay button
window.showHistoryModal = showHistoryModal;
// Force sync function for overlay and dashboard
async function forceSyncNow() {
console.log('[SaveSync] π Force sync requested...');
overlayInstance?.setSyncStatus('syncing');
await syncToBackend();
console.log('[SaveSync] β
Force sync complete');
}
window.forceSyncNow = forceSyncNow;
// ==================== ACHIEVEMENTS & NOTIFICATIONS ====================
async function checkAchievements() {
if (!authToken) return;
try {
const response = await fetch(`${getApiUrl()}/game-api.php?action=checkAchievements`, {
method: 'POST',
headers: { 'Authorization': `Bearer ${authToken}`, 'Content-Type': 'application/json' },
credentials: 'include'
});
if (!response.ok) {
if (response.status === 500) {
// Try to get error details
try {
const errorData = await response.json();
console.error('[SaveSync] Achievement check failed:', errorData.details || errorData.error);
} catch (e) {
console.error('[SaveSync] Achievement check failed with 500 error');
}
return;
}
throw new Error(`HTTP ${response.status}`);
}
const data = await response.json();
if (data.success && data.newAchievements && data.newAchievements.length > 0) {
console.log('[SaveSync] New achievements unlocked:', data.newAchievements.length);
for (const achievement of data.newAchievements) {
if (window.EDUrocksNotifications) {
window.EDUrocksNotifications.achievement(
'Achievement Unlocked!',
`${achievement.name} - ${achievement.description}`,
achievement.icon
);
}
}
}
} catch (error) {
// Silently fail - achievements are optional
console.debug('[SaveSync] Achievement check error (non-critical):', error);
}
}
async function checkNotifications() {
if (!authToken) return;
try {
const response = await fetch(`${getApiUrl()}/game-api.php?action=getNotifications&unread=true&limit=5&token=${authToken}`, {
credentials: 'include'
});
if (!response.ok) return; // Silently fail
const data = await response.json();
if (data.success && data.notifications && data.notifications.length > 0) {
for (const notification of data.notifications) {
if (window.EDUrocksNotifications) {
window.EDUrocksNotifications.show({
type: notification.type === 'achievement' ? 'achievement' : 'info',
title: notification.title,
message: notification.message,
icon: notification.icon
});
}
}
}
} catch (error) {
// Silently fail - notifications are optional
}
}
// ==================== OVERLAY ====================
const GameOverlay = {
overlay: null,
collapsed: true,
position: 'bottom-right',
syncStatus: 'idle',
stats: { playtime: 0, lastSync: null },
updateInterval: null,
init: function(options = {}) {
this.position = options.position || 'bottom-right';
this.overlay = document.createElement('div');
this.overlay.id = 'edurocks-overlay';
this.overlay.style.cssText = `position: fixed; z-index: 2147483647; pointer-events: auto; ${this.position.includes('right') ? 'right: 20px;' : 'left: 20px;'} ${this.position.includes('bottom') ? 'bottom: 20px;' : 'top: 20px;'}`;
this.render();
document.body.appendChild(this.overlay);
// Start real-time playtime updates (every second)
this.startRealtimeUpdates();
console.log('[SaveSync] Overlay initialized with real-time updates');
},
startRealtimeUpdates: function() {
// Update playtime display every second
if (this.updateInterval) clearInterval(this.updateInterval);
this.updateInterval = setInterval(() => {
if (!sessionStartTime || !isLoggedIn) return;
// Calculate current playtime from session start (only active time)
const currentPlaytime = getActivePlayTime();
this.stats.playtime = currentPlaytime;
// Only update the playtime display if overlay is open
if (!this.collapsed) {
this.updatePlaytimeDisplay();
}
}, 1000); // Update every second
},
updatePlaytimeDisplay: function() {
// Update just the playtime text without re-rendering entire overlay
const playtimeEl = this.overlay.querySelector('.overlay-playtime');
if (playtimeEl) {
playtimeEl.textContent = this.formatPlaytime();
}
},
render: function() {
const self = this;
const statusColor = { idle: '#6b7280', syncing: '#3b82f6', success: '#10b981', error: '#ef4444' }[this.syncStatus];
const statusIcon = { idle: 'πΎ', syncing: 'π', success: 'β', error: 'β' }[this.syncStatus];
const statusText = { idle: 'Ready', syncing: 'Syncing...', success: 'Synced', error: 'Failed' }[this.syncStatus];
this.overlay.innerHTML = `
<div class="overlay-button" style="width: 36px; height: 36px; background: linear-gradient(135deg, #F4154D 0%, #a855a0 100%); border-radius: 50%; display: flex; align-items: center; justify-content: center; cursor: pointer; box-shadow: 0 4px 12px rgba(0,0,0,0.3); position: relative;">
<div style="position: absolute; top: 1px; right: 1px; width: 10px; height: 10px; border-radius: 50%; border: 2px solid white; background: ${statusColor};"></div>
<div style="font-size: 18px; color: white;">${statusIcon}</div>
</div>
<div class="overlay-panel" style="display: ${this.collapsed ? 'none' : 'block'}; position: absolute; ${this.position.includes('right') ? 'right: 0;' : 'left: 0;'} ${this.position.includes('bottom') ? 'bottom: 48px;' : 'top: 48px;'} background: #1a1a1a; border: 1px solid rgba(139, 74, 122, 0.3); border-radius: 12px; padding: 16px; min-width: 250px; box-shadow: 0 8px 24px rgba(0,0,0,0.5); color: white;">
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 16px; padding-bottom: 12px; border-bottom: 1px solid rgba(255,255,255,0.1);">
<div style="font-weight: 600; font-size: 14px;">EDUrocks SaveSync</div>
<button class="overlay-close" style="background: none; border: none; color: rgba(255,255,255,0.6); font-size: 24px; cursor: pointer; padding: 0; line-height: 1;">×</button>
</div>
<div style="margin-bottom: 12px;">
<div style="font-size: 11px; text-transform: uppercase; color: rgba(255,255,255,0.5); margin-bottom: 4px;">Status</div>
<div style="font-size: 14px; font-weight: 500;">${statusIcon} ${statusText}</div>
</div>
<div style="margin-bottom: 12px;">
<div style="font-size: 11px; text-transform: uppercase; color: rgba(255,255,255,0.5); margin-bottom: 4px;">Session Time</div>
<div class="overlay-playtime" style="font-size: 14px; font-weight: 500;">${this.formatPlaytime()}</div>
</div>
<button class="force-sync-btn" style="width: 100%; background: rgba(139, 74, 122, 0.2); border: 1px solid rgba(139, 74, 122, 0.3); color: white; padding: 8px 12px; border-radius: 6px; cursor: pointer; font-size: 13px; margin-top: 12px;">π Force Sync</button>
<button class="history-btn" style="width: 100%; background: rgba(139, 74, 122, 0.2); border: 1px solid rgba(139, 74, 122, 0.3); color: white; padding: 8px 12px; border-radius: 6px; cursor: pointer; font-size: 13px; margin-top: 8px;">π Save History</button>
</div>
`;
setTimeout(() => {
const btn = this.overlay.querySelector('.overlay-button');
if (btn) btn.onclick = () => { this.collapsed = !this.collapsed; this.render(); };
const closeBtn = this.overlay.querySelector('.overlay-close');
if (closeBtn) closeBtn.onclick = () => { this.collapsed = true; this.render(); };
const syncBtn = this.overlay.querySelector('.force-sync-btn');
if (syncBtn) syncBtn.onclick = async () => {
console.log('[SaveSync] π Force sync triggered from overlay');
this.setSyncStatus('syncing');
await syncToBackend();
this.setSyncStatus('success');
console.log('[SaveSync] β
Force sync complete');
};
const historyBtn = this.overlay.querySelector('.history-btn');
if (historyBtn) historyBtn.onclick = () => showHistoryModal();
}, 0);
},
setSyncStatus: function(status) {
this.syncStatus = status;
if (status === 'success') this.stats.lastSync = new Date();
this.render();
},
updatePlaytime: function(seconds) {
this.stats.playtime = seconds;
},
formatPlaytime: function() {
const s = this.stats.playtime;
if (s < 60) return `${s}s`;
if (s < 3600) return `${Math.floor(s / 60)}m ${s % 60}s`;
return `${Math.floor(s / 3600)}h ${Math.floor((s % 3600) / 60)}m`;
}
};
// ==================== INITIALIZATION ====================
function init() {
gameId = getGameId();
gameName = getGameName();
authToken = localStorage.getItem('edurocks_auth_token');
isLoggedIn = !!authToken;
console.log('[SaveSync] Initializing for game:', gameId);
if (!isLoggedIn) {
console.log('[SaveSync] User not logged in, sync disabled');
return;
}
console.log('[SaveSync] User logged in, enabling sync');
// Intercept localStorage IMMEDIATELY to catch all writes
interceptLocalStorage();
// Setup tab visibility tracking to only count active time
setupVisibilityTracking();
// IMPORTANT: Load saves from backend
loadSavesFromBackend().then(() => {
console.log('[SaveSync] Saves loaded and restored');
// Dispatch custom event so games can wait for saves to be ready
window.dispatchEvent(new CustomEvent('edurocks-saves-ready', {
detail: { gameId, timestamp: Date.now() }
}));
console.log('[SaveSync] Ready event dispatched, game can access restored data');
}).catch(error => {
console.error('[SaveSync] Error during save load:', error);
// Still dispatch event even on error so game doesn't hang
window.dispatchEvent(new CustomEvent('edurocks-saves-ready', {
detail: { gameId, timestamp: Date.now(), error: true }
}));
});
// Start session
startSession();
// Start periodic tasks
setInterval(syncToBackend, CONFIG.SYNC_INTERVAL);
setInterval(heartbeat, CONFIG.HEARTBEAT_INTERVAL);
setInterval(checkAchievements, CONFIG.ACHIEVEMENT_CHECK_INTERVAL);
setInterval(checkNotifications, CONFIG.NOTIFICATION_CHECK_INTERVAL);
// Initialize overlay
if (document.body) {
overlayInstance = GameOverlay;
overlayInstance.init({ position: 'bottom-right' });
}
// Cleanup on page unload
window.addEventListener('beforeunload', (event) => {
// First, try to sync any pending saves
finalSyncOnUnload();
// Then end the session
endSession();
});
console.log('[SaveSync] Initialization complete');
}
// Start when DOM is ready
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', init);
} else {
init();
}
// Force reload of saves (useful for debugging or manual refresh)
async function forceReloadSaves() {
if (!isLoggedIn || !gameId) {
console.error('[SaveSync] Not logged in or no game ID');
alert('You must be logged in to reload saves');
return;
}
console.log('[SaveSync] Force reloading all saves...');
await loadSavesFromBackend();
console.log('[SaveSync] Force reload complete');
alert('Saves reloaded! Refresh the page to apply changes.');
}
// Make globally available
window.EDUrocksSaveSync = {
sync: syncToBackend,
getSessionInfo: () => ({ playTime: overlayInstance ? overlayInstance.stats.playtime : 0 }),
forceReloadSaves: forceReloadSaves,
debugInfo: () => ({
gameId,
isLoggedIn,
})
};
console.log('[SaveSync] Module loaded');
})();
/**
* EDUrocks 3.0 - Universal Game Save Sync System
* Complete all-in-one solution for save syncing, achievements, notifications, and overlay
* Supports: localStorage
*/
(function() {
'use strict';
// ==================== CONFIGURATION ====================
const CONFIG = {
SYNC_INTERVAL: 10000, // Sync every 10 seconds
HEARTBEAT_INTERVAL: 30000, // Heartbeat every 30 seconds
ACHIEVEMENT_CHECK_INTERVAL: 60000, // Check achievements every minute
NOTIFICATION_CHECK_INTERVAL: 300000, // Check notifications every 5 minutes
};
// Blacklist - never sync these keys
const BLACKLIST = [
/^edurocks_/i,
/cache/i,
/^__/
];
// ==================== STATE ====================
let gameId = null;
let gameName = null;
let isLoggedIn = false;
let authToken = null;
let userUuid = null;
let sessionId = null;
let sessionStartTime = null;
let lastSyncedPlayTime = 0; // Track last synced playtime for delta calculations
let totalPausedTime = 0; // Track total time the tab was inactive
let lastPauseTime = null; // When the tab became inactive
let isTabActive = true; // Track if tab is currently active
let syncQueue = new Map();
let isSyncing = false;
let overlayInstance = null;
let isRestoring = false; // Flag to prevent restore from triggering sync
let originalSetItem = null; // Store original for bypass during restore
let originalRemoveItem = null;
let originalClear = null;
// ==================== UTILITY FUNCTIONS ====================
function getApiUrl() {
if (window.eduBackendRoot) {
return window.eduBackendRoot + '/userauth';
}
const hostname = window.location.hostname;
const isIP = /^(\d{1,3}\.){3}\d{1,3}$/.test(hostname) || /^[0-9a-fA-F:]+$/.test(hostname);
const isLocal = hostname === 'localhost' || hostname.endsWith('.local') || hostname === '127.0.0.1' || hostname === '::1';
if (hostname === 'devbuild.edurocks.org' || isIP || isLocal) {
return 'https://backendapi.edurocks.org/userauth';
}
const domain = hostname.replace(/^www\./, "");
return `https://backendapi.${domain}/userauth`;
}
// Don't cache the URL - always call getApiUrl() to pick up AWS overrides
// const API_URL = getApiUrl() + '/game-api.php';
function getGameId() {
const pathParts = window.location.pathname.split('/').filter(p => p);
return pathParts[pathParts.length - 2] || pathParts[pathParts.length - 1] || 'unknown';
}
function getGameName() {
return document.title || gameId;
}
function shouldSyncKey(key) {
for (const pattern of BLACKLIST) {
if (pattern.test(key)) return false;
}
return true;
}
// Calculate active playtime (excluding time when tab was inactive)
function getActivePlayTime() {
if (!sessionStartTime) return 0;
const totalElapsed = Date.now() - sessionStartTime;
const activeTime = totalElapsed - totalPausedTime;
// If currently paused, subtract current pause duration
if (!isTabActive && lastPauseTime) {
const currentPauseDuration = Date.now() - lastPauseTime;
return Math.floor((activeTime - currentPauseDuration) / 1000);
}
return Math.floor(activeTime / 1000);
}
// Handle tab visibility changes
function setupVisibilityTracking() {