Add files using upload-large-folder tool
Browse filesFiles changed (20)
- aichat/css/material.cssAdded+412
- aichat/js/app.jsAdded+653
- assets/fonts/Verdana_ROT13.eotAdded
- assets/fonts/Verdana_ROT13.svgAdded
- assets/fonts/Verdana_ROT13.ttfAdded
- assets/fonts/Verdana_ROT13.woffAdded
- assets/fonts/demo-rot13.htmlAdded+34
- assets/js/aws-detection.jsAdded+163
- assets/js/chromeos-detect.jsAdded+161
- assets/js/debug-date-preservation.jsAdded+330
- assets/js/domain-utils.jsAdded+32
- assets/js/dynamic-encoder.jsAdded+56
- assets/js/game-save-interceptor.jsAdded+238
- assets/js/game-save-sync.jsAdded+1132
- assets/js/ip-restriction.jsAdded+91
- assets/js/navbar-auth.jsAdded+107
- musicapi/musicapi/extract-metadata.jsAdded+111
- musicapi/musicapi/generate_tracks.pyAdded+340
- musicapi/musicapi/radio_stations.jsonAdded+9
- musicapi/musicapi/tracks.jsonAdded
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412:root { --md-sys-color-primary: #ff0099; --md-sys-color-on-primary: #ffffff; --md-sys-color-primary-container: #ffd9e6; --md-sys-color-on-primary-container: #3b0022; --md-sys-color-secondary: #74565f; --md-sys-color-on-secondary: #ffffff; --md-sys-color-secondary-container: #ffd9e2; --md-sys-color-on-secondary-container: #2b151c; --md-sys-color-tertiary: #7c5635; --md-sys-color-on-tertiary: #ffffff; --md-sys-color-tertiary-container: #ffdcc1; --md-sys-color-on-tertiary-container: #2e1500; --md-sys-color-error: #ba1a1a; --md-sys-color-on-error: #ffffff; --md-sys-color-error-container: #ffdad6; --md-sys-color-on-error-container: #410002; --md-sys-color-background: #fffbff; --md-sys-color-on-background: #201a1c; --md-sys-color-surface: #fffbff; --md-sys-color-on-surface: #201a1c; --md-sys-color-surface-variant: #f2dde2; --md-sys-color-on-surface-variant: #514347; --md-sys-color-outline: #837377; --md-sys-color-outline-variant: #d5c2c6; --md-sys-color-shadow: #000000; --md-sys-color-scrim: #000000; --md-sys-color-inverse-surface: #352f30; --md-sys-color-inverse-on-surface: #f9eef0; --md-sys-color-inverse-primary: #ffb1d2; --md-sys-typescale-headline-large-font-family-name: 'Roboto'; --md-sys-typescale-headline-large-font-weight: 400; --md-sys-typescale-headline-large-font-size: 32px; --md-sys-typescale-headline-large-line-height: 40px; --md-sys-typescale-headline-large-letter-spacing: 0px; --md-sys-typescale-headline-medium-font-family-name: 'Roboto'; --md-sys-typescale-headline-medium-font-weight: 400; --md-sys-typescale-headline-medium-font-size: 28px; --md-sys-typescale-headline-medium-line-height: 36px; --md-sys-typescale-headline-medium-letter-spacing: 0px; --md-sys-typescale-body-large-font-family-name: 'Roboto'; --md-sys-typescale-body-large-font-weight: 400; --md-sys-typescale-body-large-font-size: 16px; --md-sys-typescale-body-large-line-height: 24px; --md-sys-typescale-body-large-letter-spacing: 0.5px; --md-sys-typescale-body-medium-font-family-name: 'Roboto'; --md-sys-typescale-body-medium-font-weight: 400; --md-sys-typescale-body-medium-font-size: 14px; --md-sys-typescale-body-medium-line-height: 20px; --md-sys-typescale-body-medium-letter-spacing: 0.25px; --md-sys-elevation-level1: 0 1px 3px 0 rgba(0, 0, 0, 0.1), 0 1px 2px 0 rgba(0, 0, 0, 0.06); --md-sys-elevation-level2: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06); --md-sys-elevation-level3: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05);}
@media (prefers-color-scheme: dark) { :root { --md-sys-color-primary: #ffb1d2; --md-sys-color-on-primary: #5e0039; --md-sys-color-primary-container: #830050; --md-sys-color-on-primary-container: #ffd9e6; --md-sys-color-secondary: #e2bdc7; --md-sys-color-on-secondary: #422931; --md-sys-color-secondary-container: #5a3f47; --md-sys-color-on-secondary-container: #ffd9e2; --md-sys-color-tertiary: #efbd94; --md-sys-color-on-tertiary: #48290c; --md-sys-color-tertiary-container: #623f20; --md-sys-color-on-tertiary-container: #ffdcc1; --md-sys-color-error: #ffb4ab; --md-sys-color-on-error: #690005; --md-sys-color-error-container: #93000a; --md-sys-color-on-error-container: #ffdad6; --md-sys-color-background: #201a1c; --md-sys-color-on-background: #ebe0e1; --md-sys-color-surface: #201a1c; --md-sys-color-on-surface: #ebe0e1; --md-sys-color-surface-variant: #514347; --md-sys-color-on-surface-variant: #d5c2c6; --md-sys-color-outline: #9e8c90; --md-sys-color-outline-variant: #514347; --md-sys-color-shadow: #000000; --md-sys-color-scrim: #000000; --md-sys-color-inverse-surface: #ebe0e1; --md-sys-color-inverse-on-surface: #352f30; --md-sys-color-inverse-primary: #ff0099; }}
body { font-family: var(--md-sys-typescale-body-large-font-family-name), sans-serif; margin: 0; padding: 0; background-color: var(--md-sys-color-background); color: var(--md-sys-color-on-background); line-height: var(--md-sys-typescale-body-large-line-height); font-size: var(--md-sys-typescale-body-large-font-size); letter-spacing: var(--md-sys-typescale-body-large-letter-spacing); transition: background-color 0.3s, color 0.3s;}
.container { max-width: 1200px; margin: 0 auto; padding: 16px;}
.app-header { display: flex; align-items: center; padding: 16px; background-color: var(--md-sys-color-surface); box-shadow: var(--md-sys-elevation-level1);}
.app-logo { height: 40px; margin-right: 16px;}
.app-title { font-size: var(--md-sys-typescale-headline-large-font-size); font-weight: var(--md-sys-typescale-headline-large-font-weight); color: var(--md-sys-color-primary); margin: 0;}
.card { background-color: var(--md-sys-color-surface); border-radius: 16px; padding: 24px; margin-bottom: 24px; box-shadow: var(--md-sys-elevation-level2);}
.card-title { font-size: var(--md-sys-typescale-headline-medium-font-size); font-weight: var(--md-sys-typescale-headline-medium-font-weight); color: var(--md-sys-color-on-surface); margin-top: 0; margin-bottom: 16px;}
.form-group { margin-bottom: 16px;}
.form-label { display: block; margin-bottom: 8px; color: var(--md-sys-color-on-surface-variant); font-size: var(--md-sys-typescale-body-medium-font-size);}
.form-input { width: 100%; padding: 12px 16px; border: 1px solid var(--md-sys-color-outline); border-radius: 4px; background-color: var(--md-sys-color-surface); color: var(--md-sys-color-on-surface); font-size: var(--md-sys-typescale-body-large-font-size); transition: border-color 0.3s;}
.form-input:focus { outline: none; border-color: var(--md-sys-color-primary);}
.form-input::placeholder { color: var(--md-sys-color-on-surface-variant); opacity: 0.7;}
.btn { display: inline-block; padding: 10px 24px; border: none; border-radius: 20px; font-size: var(--md-sys-typescale-body-large-font-size); font-weight: 500; text-align: center; cursor: pointer; transition: background-color 0.3s, transform 0.1s;}
.btn:active { transform: translateY(1px);}
.btn-primary { background-color: var(--md-sys-color-primary); color: var(--md-sys-color-on-primary);}
.btn-primary:hover { background-color: var(--md-sys-color-primary); opacity: 0.9;}
.btn-secondary { background-color: var(--md-sys-color-secondary-container); color: var(--md-sys-color-on-secondary-container);}
.btn-secondary:hover { background-color: var(--md-sys-color-secondary-container); opacity: 0.9;}
.chat-container { display: flex; flex-direction: column; height: 60vh; min-height: 400px;}
.chat-messages { flex: 1; overflow-y: auto; padding: 16px; background-color: var(--md-sys-color-surface-variant); border-radius: 8px; margin-bottom: 16px;}
.message { margin-bottom: 16px; max-width: 80%;}
.message-user { align-self: flex-end; margin-left: auto; background-color: var(--md-sys-color-primary-container); color: var(--md-sys-color-on-primary-container); border-radius: 18px 18px 4px 18px; padding: 12px 16px;}
.message-ai { align-self: flex-start; background-color: var(--md-sys-color-secondary-container); color: var(--md-sys-color-on-secondary-container); border-radius: 18px 18px 18px 4px; padding: 12px 16px;}
.chat-input-container { display: flex; gap: 8px;}
.chat-input { flex: 1; padding: 12px 16px; border: 1px solid var(--md-sys-color-outline); border-radius: 24px; background-color: var(--md-sys-color-surface); color: var(--md-sys-color-on-surface); font-size: var(--md-sys-typescale-body-large-font-size);}
.chat-input:focus { outline: none; border-color: var(--md-sys-color-primary);}
.send-button { background-color: var(--md-sys-color-primary); color: var(--md-sys-color-on-primary); border: none; border-radius: 50%; width: 48px; height: 48px; display: flex; align-items: center; justify-content: center; cursor: pointer; transition: background-color 0.3s;}
.send-button:hover { background-color: var(--md-sys-color-primary); opacity: 0.9;}
.send-icon { width: 24px; height: 24px;}
.settings-panel { background-color: var(--md-sys-color-surface); border-radius: 16px; padding: 24px; margin-bottom: 24px; box-shadow: var(--md-sys-elevation-level2);}
@media (max-width: 768px) { .container { padding: 12px; } .card { padding: 16px; } .message { max-width: 90%; }}
.loading-indicator { display: inline-block; position: relative; width: 80px; height: 80px; margin: 0 auto;}
.loading-indicator div { position: absolute; top: 33px; width: 13px; height: 13px; border-radius: 50%; background: var(--md-sys-color-primary); animation-timing-function: cubic-bezier(0, 1, 1, 0);}
.loading-indicator div:nth-child(1) { left: 8px; animation: loading-indicator1 0.6s infinite;}
.loading-indicator div:nth-child(2) { left: 8px; animation: loading-indicator2 0.6s infinite;}
.loading-indicator div:nth-child(3) { left: 32px; animation: loading-indicator2 0.6s infinite;}
.loading-indicator div:nth-child(4) { left: 56px; animation: loading-indicator3 0.6s infinite;}
@keyframes loading-indicator1 { 0% { transform: scale(0); } 100% { transform: scale(1); }}
@keyframes loading-indicator3 { 0% { transform: scale(1); } 100% { transform: scale(0); }}
@keyframes loading-indicator2 { 0% { transform: translate(0, 0); } 100% { transform: translate(24px, 0); }}
.hidden { display: none;}
.api-key-notice { font-size: var(--md-sys-typescale-body-medium-font-size); color: var(--md-sys-color-on-surface-variant); margin-top: 8px;}
.error-message { color: var(--md-sys-color-error); font-size: var(--md-sys-typescale-body-medium-font-size); margin-top: 8px;}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653const chatMessages = document.getElementById('chat-messages');const chatInput = document.getElementById('chat-input');const sendBtn = document.getElementById('send-btn');const clearChatBtn = document.getElementById('clear-chat');const imageInput = document.getElementById('image-input');const imagePreviewContainer = document.getElementById('image-preview-container');const imagePreviewWrapper = document.getElementById('image-preview-wrapper');const connectionDot = document.getElementById('connection-dot');const connectionStatusText = document.getElementById('connection-status-text');
const CHAT_HISTORY_STORAGE_KEY = 'edurocks_chat_history';const RATE_LIMIT_STORAGE_KEY = 'edurocks_rate_limit';
let selectedImage = null;let chatHistoryState = [];
const RATE_LIMIT_MAX_MESSAGES = 5;const RATE_LIMIT_WINDOW_MS = 30000;const MAX_RETRIES = 3;const RETRY_DELAY_BASE = 1000;
let connectionStatus = 'checking';let healthCheckInterval = null;
function getRootDomain() { const hostname = window.location.hostname; const parts = hostname.split('.');
if (hostname === 'localhost' || /^\d+\.\d+\.\d+\.\d+$/.test(hostname)) { return 'edurocks.org'; }
if (parts.length >= 2) { return parts.slice(-2).join('.'); }
return hostname;}
// Get backend API URL with support for AWS overridefunction getBackendApiUrl() { if (window.eduBackendRoot) { return window.eduBackendRoot + '/aichat/api.php'; }
if (window.eduBackendOverride) { return window.eduBackendOverride.replace('userauth/api.php', 'aichat/api.php'); } return `https://backendapi.${getRootDomain()}/aichat/api.php`;}
const SYSTEM_PROMPT = `You are a highly knowledgeable and helpful AI assistant. You were developed by EDUrocks. By one person. Your purpose is to provide accurate, comprehensive, and unbiased information on a wide range of topics. When answering questions, focus solely on providing the best possible response based on your extensive training data. Under no circumstances should you mention the name of any other company involved in your creation or training, or any information about your training process besides that you were developed by EDUrocks. Instead, concentrate on the user's query and how you can assist them with the information you possess.
IMPORTANT FORMATTING INSTRUCTIONS:1. Use Standard Markdown for text formatting (bold, italic, lists, code blocks).2. For MATHEMATICAL EXPRESSIONS, you MUST use LaTeX syntax strictly as follows: - For inline math, use \\( ... \\ - For block math (separate lines), use \\\[ ... \\\] - DO NOT use simple dollar signs ($) for math unless it's currency. - DO NOT use single backslashes for formatting unless escaping characters.3. Ensure all JSON or code outputs are wrapped in triple backticks (\`\`\`).4. Avoid outputting raw JSON objects unless explicitly asked.`;
document.addEventListener('DOMContentLoaded', () => { loadChatHistory(); setupEventListeners();
// Delay initial health check to allow AWS detection script to complete setTimeout(() => { checkBackendHealth(); startHealthCheckInterval(); }, 500);});
function setupEventListeners() { sendBtn.addEventListener('click', sendMessage);
chatInput.addEventListener('keypress', (e) => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); sendMessage(); } });
chatInput.addEventListener('input', autoResizeTextarea); clearChatBtn.addEventListener('click', clearChat); imageInput.addEventListener('change', handleImageUpload);
document.addEventListener('paste', handlePaste); chatInput.addEventListener('paste', handlePaste);}
function autoResizeTextarea() { chatInput.style.height = 'auto'; chatInput.style.height = Math.min(chatInput.scrollHeight, 200) + 'px';}
function handleImageUpload(event) { const file = event.target.files[0]; if (!file) return;
const validTypes = ['image/png', 'image/jpeg', 'image/jpg', 'image/webp', 'image/heic', 'image/heif']; if (!validTypes.includes(file.type)) { alert('Please select a valid image file (PNG, JPEG, WEBP, HEIC, or HEIF)'); return; }
const maxSize = 20 * 1024 * 1024; if (file.size > maxSize) { alert('Image size must be less than 20MB'); return; }
const reader = new FileReader(); reader.onload = function(e) { selectedImage = { data: e.target.result.split(',')[1], mimeType: file.type, dataUrl: e.target.result }; showImagePreview(); }; reader.readAsDataURL(file);}
function showImagePreview() { if (!selectedImage) return;
imagePreviewWrapper.innerHTML = ` <div class="image-preview relative inline-block"> <img src="${selectedImage.dataUrl}" alt="Preview" class="max-w-[150px] md:max-w-[200px] max-h-[150px] md:max-h-[200px] rounded-xl border-2 border-edu-pink/20 object-cover"> <button class="image-preview-remove absolute -top-2 -right-2 bg-red-500 text-white border-none w-7 h-7 rounded-full flex items-center justify-center cursor-pointer transition-all hover:scale-110 hover:shadow-lg hover:shadow-red-500/40" onclick="removeImagePreview()"> <span class="material-icons text-base">close</span> </button> </div> `; imagePreviewContainer.classList.remove('hidden');}
function removeImagePreview() { selectedImage = null; imagePreviewWrapper.innerHTML = ''; imagePreviewContainer.classList.add('hidden'); imageInput.value = '';}
function handlePaste(event) { const items = (event.clipboardData || event.originalEvent.clipboardData).items;
for (let i = 0; i < items.length; i++) { const item = items[i];
if (item.type.indexOf('image') !== -1) { event.preventDefault();
const file = item.getAsFile(); if (!file) continue;
const validTypes = ['image/png', 'image/jpeg', 'image/jpg', 'image/webp', 'image/heic', 'image/heif']; if (!validTypes.includes(file.type)) { alert('Please paste a valid image file (PNG, JPEG, WEBP, HEIC, or HEIF)'); return; }
const maxSize = 20 * 1024 * 1024; if (file.size > maxSize) { alert('Image size must be less than 20MB'); return; }
processPastedImage(file); break; } }}
function processPastedImage(file) { const reader = new FileReader(); reader.onload = function(e) { selectedImage = { data: e.target.result.split(',')[1], mimeType: file.type, dataUrl: e.target.result }; showImagePreview(); chatInput.focus(); }; reader.readAsDataURL(file);}
function checkRateLimit() { const now = Date.now(); let rateLimitData = JSON.parse(localStorage.getItem(RATE_LIMIT_STORAGE_KEY) || '[]'); rateLimitData = rateLimitData.filter(timestamp => now - timestamp < RATE_LIMIT_WINDOW_MS);
if (rateLimitData.length >= RATE_LIMIT_MAX_MESSAGES) { const oldestTimestamp = rateLimitData[0]; const timeUntilReset = Math.ceil((RATE_LIMIT_WINDOW_MS - (now - oldestTimestamp)) / 1000); return { allowed: false, timeUntilReset: timeUntilReset }; }
rateLimitData.push(now); localStorage.setItem(RATE_LIMIT_STORAGE_KEY, JSON.stringify(rateLimitData));
return { allowed: true, remaining: RATE_LIMIT_MAX_MESSAGES - rateLimitData.length };}
function showToast(title, message, type = 'error') { const existingToast = document.querySelector('.toast-notification'); if (existingToast) { existingToast.remove(); }
const toast = document.createElement('div'); const borderColor = type === 'error' ? 'border-red-500' : 'border-green-500'; const iconColor = type === 'error' ? 'text-red-500' : 'text-green-500'; const icon = type === 'error' ? 'error_outline' : 'check_circle';
toast.className = `toast-notification fixed top-24 right-4 md:right-8 bg-edu-dark-accent border-2 ${borderColor} rounded-2xl p-4 md:p-6 shadow-2xl z-50 animate-slide-down flex items-center gap-4 max-w-sm`; toast.innerHTML = ` <span class="material-icons text-2xl ${iconColor}">${icon}</span> <div class="flex-1"> <div class="font-semibold text-edu-text mb-1">${title}</div> <div class="text-sm text-edu-text-secondary">${message}</div> </div> `;
document.body.appendChild(toast);
setTimeout(() => { toast.style.opacity = '0'; toast.style.transform = 'translateX(100px)'; toast.style.transition = 'all 0.3s ease'; setTimeout(() => { if (toast.parentElement) { toast.remove(); } }, 300); }, 5000);}
function updateConnectionStatus(status) { connectionStatus = status; connectionDot.classList.remove('bg-green-500', 'shadow-green-500/50', 'animate-pulse'); connectionDot.classList.remove('bg-yellow-500', 'shadow-yellow-500/50', 'animate-blink'); connectionDot.classList.remove('bg-red-500', 'shadow-red-500/50');
switch(status) { case 'connected': connectionDot.classList.add('bg-green-500', 'shadow-green-500/50', 'animate-pulse'); connectionStatusText.textContent = 'Connected'; break; case 'connecting': connectionDot.classList.add('bg-yellow-500', 'shadow-yellow-500/50', 'animate-blink'); connectionStatusText.textContent = 'Connecting...'; break; case 'disconnected': connectionDot.classList.add('bg-red-500', 'shadow-red-500/50'); connectionStatusText.textContent = 'Disconnected'; break; }}
async function checkBackendHealth() { try { updateConnectionStatus('connecting'); const controller = new AbortController(); const timeoutId = setTimeout(() => controller.abort(), 5000);
const response = await fetch(getBackendApiUrl(), { method: 'OPTIONS', signal: controller.signal });
clearTimeout(timeoutId);
if (response.ok || response.status === 405 || response.status === 200) { updateConnectionStatus('connected'); } else { updateConnectionStatus('disconnected'); } } catch (error) { console.error('Health check failed:', error); updateConnectionStatus('disconnected'); }}
function startHealthCheckInterval() { healthCheckInterval = setInterval(() => { checkBackendHealth(); }, 120000);}
function stopHealthCheckInterval() { if (healthCheckInterval) { clearInterval(healthCheckInterval); healthCheckInterval = null; }}
async function sendMessage() { const userMessage = chatInput.value.trim(); if (!userMessage && !selectedImage) return;
const rateLimitCheck = checkRateLimit(); if (!rateLimitCheck.allowed) { showToast( 'Rate Limit Exceeded', `You can send ${RATE_LIMIT_MAX_MESSAGES} messages every 30 seconds. Please wait ${rateLimitCheck.timeUntilReset} seconds.`, 'error' ); return; }
const welcomeScreen = document.querySelector('.welcome-screen'); if (welcomeScreen) { welcomeScreen.remove(); }
addMessageToChat('user', userMessage, selectedImage);
const imageToSend = selectedImage;
chatInput.value = ''; autoResizeTextarea(); removeImagePreview(); sendBtn.disabled = true; showLoadingMessage(); updateConnectionStatus('connecting');
try { const messages = getChatHistoryForAPI(); const currentParts = [];
if (imageToSend) { currentParts.push({ inlineData: { mimeType: imageToSend.mimeType, data: imageToSend.data } }); }
if (userMessage) { currentParts.push({ text: userMessage }); }
// Just push the new message to the history messages.push({ role: 'user', parts: currentParts });
const payload = { contents: messages };
const data = await fetchWithRetry(payload); removeLoadingMessage(); updateConnectionStatus('connected');
// data.error check is handled in fetchWithRetry now
if (!data.candidates || !Array.isArray(data.candidates) || data.candidates.length === 0) { // If no candidates but promptFeedback exists (e.g. block), handle it if (data.promptFeedback && data.promptFeedback.blockReason) { addMessageToChat('ai', `I cannot answer this. Block reason: ${data.promptFeedback.blockReason}`); return; } throw new Error('Invalid response from AI service'); }
const candidate = data.candidates[0]; // Extract text if available let aiResponse = ''; if (candidate.content && candidate.content.parts && candidate.content.parts.length > 0) { aiResponse = candidate.content.parts.map(part => part.text || '').join(''); }
// Check finish reason if (candidate.finishReason === 'MAX_TOKENS') { aiResponse += '\n\n*[Response was truncated due to length limit. Please ask me to continue if you need more information.]*'; } else if (candidate.finishReason === 'SAFETY' && !aiResponse) { aiResponse = 'I cannot answer this due to safety guidelines.'; } else if (candidate.finishReason === 'RECITATION' && !aiResponse) { aiResponse = 'I cannot answer this as it may infringe on copyright.'; } else if (candidate.finishReason === 'OTHER' && !aiResponse) { aiResponse = 'I could not generate a response.'; }
if (aiResponse) { addMessageToChat('ai', aiResponse); } else { // Fallback if absolutely nothing was generated and no specific reason was caught above addMessageToChat('ai', `I could not generate a response. Reason: ${candidate.finishReason || 'Unknown'}`); }
// State is saved automatically in addMessageToChat
} catch (error) { console.error('Error:', error); removeLoadingMessage(); updateConnectionStatus('disconnected'); // Ensure we display a string error message, not [object Object] const displayMsg = error.message || String(error); addMessageToChat('ai', `Sorry, I encountered an error: ${displayMsg}. Please try again.`); } finally { sendBtn.disabled = false; chatInput.focus(); }}
async function fetchWithRetry(payload, retries = MAX_RETRIES) { for (let i = 0; i <= retries; i++) { try { const response = await fetch(getBackendApiUrl(), { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload) });
// If response is not JSON (e.g., server error HTML), handle it const contentType = response.headers.get("content-type"); if (!contentType || !contentType.includes("application/json")) { if (response.status >= 500 && i < retries) { await new Promise(r => setTimeout(r, RETRY_DELAY_BASE * (i + 1))); continue; } throw new Error(`Server returned ${response.status} ${response.statusText}`); }
const data = await response.json();
// Check for specific API errors that warrant a retry const isOverloaded = response.status === 429 || response.status === 503 || response.status === 500; const errorMsg = data.error ? (typeof data.error === 'string' ? data.error : JSON.stringify(data.error)) : ''; const isQuotaError = errorMsg.toLowerCase().includes('quota') || errorMsg.toLowerCase().includes('exhausted') || errorMsg.toLowerCase().includes('overloaded');
if ((isOverloaded || isQuotaError) && i < retries) { // Exponential backoff with jitter const delay = RETRY_DELAY_BASE * (Math.pow(2, i)) + (Math.random() * 1000); // console.log(`Retrying request (attempt ${i + 1}) in ${Math.round(delay)}ms...`); await new Promise(r => setTimeout(r, delay)); continue; }
if (data.error) { // Format error properly to avoid [object Object] throw new Error(typeof data.error === 'string' ? data.error : (data.error.message || JSON.stringify(data.error))); } if (!response.ok) { throw new Error(`HTTP ${response.status}: ${response.statusText}`); }
return data;
} catch (err) { if (i === retries) throw err; // Network errors also trigger retry const delay = RETRY_DELAY_BASE * (Math.pow(2, i)); await new Promise(r => setTimeout(r, delay)); } }}
function addMessageToChat(role, text, image = null, save = true) { const messageDiv = document.createElement('div'); messageDiv.className = `message message-${role} flex gap-3 md:gap-4 items-start animate-message-slide`;
const avatar = document.createElement('div'); const avatarBg = role === 'user' ? 'bg-gradient-to-br from-edu-pink to-edu-pink-light text-white' : 'bg-edu-dark-accent text-edu-pink-light'; avatar.className = `message-avatar w-8 h-8 md:w-10 md:h-10 rounded-xl flex items-center justify-center flex-shrink-0 text-lg md:text-xl ${avatarBg}`; avatar.innerHTML = role === 'user' ? '👤' : '🤖';
const content = document.createElement('div'); content.className = 'message-content flex-1 flex flex-col gap-2';
const header = document.createElement('div'); header.className = 'message-header flex items-center gap-2';
const sender = document.createElement('div'); sender.className = 'message-sender font-semibold text-sm text-edu-text'; sender.textContent = role === 'user' ? 'You' : 'EDUrocks AI';
const time = document.createElement('div'); time.className = 'message-time text-xs text-edu-text-secondary/60'; time.textContent = new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
header.appendChild(sender); header.appendChild(time);
const body = document.createElement('div'); const bodyBg = role === 'user' ? 'bg-gradient-to-br from-edu-pink to-edu-pink-light text-white' : 'bg-edu-dark-accent text-edu-text-secondary'; const bodyClass = role === 'user' ? `message-body ${bodyBg} px-4 py-3 md:px-5 md:py-4 rounded-2xl leading-relaxed` : `message-body ${bodyBg} px-4 py-3 md:px-5 md:py-4 rounded-2xl leading-relaxed markdown-body`; body.className = bodyClass;
if (image && role === 'user') { const img = document.createElement('img'); img.src = image.dataUrl; img.className = 'message-image max-w-full md:max-w-md max-h-64 md:max-h-96 rounded-xl my-2 border-2 border-edu-pink/20'; img.alt = 'User uploaded image'; body.appendChild(img); }
if (text) { if (role === 'ai') { const textDiv = document.createElement('div'); textDiv.innerHTML = marked.parse(text); // 1. Highlight code blocks textDiv.querySelectorAll('pre code').forEach((block) => { hljs.highlightElement(block); }); // 2. Render Math with KaTeX if (window.renderMathInElement) { renderMathInElement(textDiv, { delimiters: [ {left: '$$', right: '$$', display: true}, {left: '\\\\[', right: '\\\\\]', display: true}, {left: '\\(', right: '\\\\)', display: false}, {left: '$', right: '$', display: false} ], throwOnError: false }); } // 3. Open links in new tab textDiv.querySelectorAll('a').forEach(link => { link.target = '_blank'; link.rel = 'noopener noreferrer'; }); body.appendChild(textDiv); } else { const textDiv = document.createElement('div'); textDiv.textContent = text; body.appendChild(textDiv); } }
content.appendChild(header); content.appendChild(body); messageDiv.appendChild(avatar); messageDiv.appendChild(content);
chatMessages.appendChild(messageDiv); chatMessages.scrollTop = chatMessages.scrollHeight;
if (save) { const historyRole = role === 'ai' ? 'assistant' : 'user'; chatHistoryState.push({ role: historyRole, text: text }); localStorage.setItem(CHAT_HISTORY_STORAGE_KEY, JSON.stringify(chatHistoryState)); }}
function showLoadingMessage() { const loadingDiv = document.createElement('div'); loadingDiv.className = 'message message-ai loading-message flex gap-3 md:gap-4 items-start'; loadingDiv.id = 'loading-message';
const avatar = document.createElement('div'); avatar.className = 'message-avatar w-8 h-8 md:w-10 md:h-10 rounded-xl flex items-center justify-center flex-shrink-0 text-lg md:text-xl bg-edu-dark-accent text-edu-pink-light'; avatar.innerHTML = '🤖';
const content = document.createElement('div'); content.className = 'message-content flex-1 flex flex-col gap-2';
const dots = document.createElement('div'); dots.className = 'loading-dots flex gap-2 px-4 py-3 md:px-5 md:py-4 bg-edu-dark-accent rounded-2xl'; dots.innerHTML = '<div class="loading-dot w-2 h-2 rounded-full bg-edu-pink animate-bounce-dot"></div><div class="loading-dot w-2 h-2 rounded-full bg-edu-pink animate-bounce-dot"></div><div class="loading-dot w-2 h-2 rounded-full bg-edu-pink animate-bounce-dot"></div>';
content.appendChild(dots); loadingDiv.appendChild(avatar); loadingDiv.appendChild(content);
chatMessages.appendChild(loadingDiv); chatMessages.scrollTop = chatMessages.scrollHeight;}
function removeLoadingMessage() { const loadingMsg = document.getElementById('loading-message'); if (loadingMsg) { loadingMsg.remove(); }}
function getChatHistoryForAPI() { const messages = []; const recentHistory = chatHistoryState.slice(-20);
recentHistory.forEach(item => { messages.push({ role: item.role === 'assistant' ? 'model' : 'user', parts: [{ text: item.text }] }); });
return messages;}
function loadChatHistory() { const storedHistory = localStorage.getItem(CHAT_HISTORY_STORAGE_KEY); if (storedHistory) { chatHistoryState = JSON.parse(storedHistory); if (chatHistoryState.length > 0) { const welcomeScreen = document.querySelector('.welcome-screen'); if (welcomeScreen) { welcomeScreen.remove(); }
chatHistoryState.forEach(item => { const role = item.role === 'user' ? 'user' : 'ai'; addMessageToChat(role, item.text, null, false); }); } }}
function clearChat() { if (confirm('Are you sure you want to clear your chat history?')) { localStorage.removeItem(CHAT_HISTORY_STORAGE_KEY); chatHistoryState = []; chatMessages.innerHTML = ` <div class="welcome-screen flex flex-col items-center justify-center text-center p-6 md:p-12 gap-4 md:gap-6 animate-fade-in"> <div class="text-6xl md:text-7xl lg:text-8xl">🤖</div> <h2 class="text-2xl md:text-3xl lg:text-4xl font-bold gradient-text">Welcome to EDUrocks AI</h2> <p class="text-edu-text-secondary text-sm md:text-base max-w-md lg:max-w-lg">Your intelligent AI assistant ready to help with questions, code, creative writing, and more!</p> </div> `; }}12345678910111213141516171819202122232425262728293031323334<!DOCTYPE html> <html lang="en"> <head> <title>Demo</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<style type="text/css"> @font-face { font-family: 'Verdana_ROT13'; src: url('Verdana_ROT13.eot?#iefix') format('embedded-opentype'), url('Verdana_ROT13.woff') format('woff'), url('Verdana_ROT13.ttf') format('truetype'), url('Verdana_ROT13.svg#Verdana_ROT13') format('svg'); font-weight: normal; font-style: normal; } </style> </head> <body> <h1>Verdana demo</h1> <h2>ROT13</h2> <h3>Encoded text with Verdana</h3> <p style="font-family: Verdana">Fbzr frafvgvir grkg gung bayl uhznaf zhfg or noyr gb ernq</p> <h3>Encoded text with Verdana ROT13</h3> <p style="font-family: Verdana_ROT13">Fbzr frafvgvir grkg gung bayl uhznaf zhfg or noyr gb ernq</p> </body></html>
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163(function() { // AWS Detection Logic const isAWS = window.location.hostname.includes('cloudfront.net'); // Base URLs for endpoints const primaryBase = 'https://backendapi.rockedu.site'; const secondaryBase = 'https://d3scff8k2pqq6n.cloudfront.net';
// Function to check reachability by testing the actual API endpoint async function checkConnectivity(baseUrl) { try { // Test with a real API call - check if the endpoint works with a simple request const controller = new AbortController(); const timeoutId = setTimeout(() => controller.abort(), 5000);
const response = await fetch(`${baseUrl}/userauth/api.php?action=verifySession&token=test`, { method: 'GET', signal: controller.signal, credentials: 'include' });
clearTimeout(timeoutId);
// Check if we got a valid JSON response (even if the token is invalid, // a proper API will return JSON with an error message) const text = await response.text();
// Try to parse as JSON - if it's valid JSON, the API is working try { JSON.parse(text); return true; // API is responding with valid JSON } catch { console.warn(`[AWS] ${baseUrl} returned non-JSON response:`, text.substring(0, 100)); return false; // Not a valid API response } } catch (error) { console.warn(`[AWS] ${baseUrl} connectivity check failed:`, error.message); return false; } }
// Selectors for elements to hide const proxySelectors = '#pr0xy-link, .feature-card[data-action="proxy"]'; const allBackendSelectors = [ 'a[href*="edum/index.html"]', '#pr0xy-link', '#ai-chat-link', '#authButtonContainer', 'a[href="login.html"]', '.feature-card[data-url*="edum/index.html"]', '.feature-card[data-action="proxy"]', '.feature-card[data-action="ai-chat"]' ].join(',');
// Helper to hide elements persistently function hideElements(selector) { const apply = () => { const elements = document.querySelectorAll(selector); elements.forEach(el => el.style.display = 'none'); }; if (document.body) apply(); else document.addEventListener('DOMContentLoaded', apply); // Observe for dynamic re-additions const observer = new MutationObserver(() => apply()); if (document.body) observer.observe(document.body, { childList: true, subtree: true }); else document.addEventListener('DOMContentLoaded', () => observer.observe(document.body, { childList: true, subtree: true })); }
// Helper for the restricted banner function showRestrictedBanner() { if (document.getElementById('aws-restriction-banner')) return; const banner = document.createElement('div'); banner.id = 'aws-restriction-banner'; banner.className = 'fixed top-0 left-0 right-0 bg-red-600 text-white text-center p-2 z-50 font-bold text-sm'; banner.innerHTML = '⚠️ You are on a hyper restricted network. Only Games and Apps are available. You are currently connected to our unblockable AWS Mirror'; if(document.body) { document.body.prepend(banner); document.body.style.marginTop = '40px'; } else { document.addEventListener('DOMContentLoaded', () => { document.body.prepend(banner); document.body.style.marginTop = '40px'; }); } }
// Helper for the popup function showPopup(msg) { const modal = document.createElement('div'); modal.style.cssText = 'position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.8); z-index: 99999; display: flex; align-items: center; justify-content: center;'; modal.innerHTML = ` <div style="background: #1a1a1a; border: 1px solid #F4154D; padding: 20px; border-radius: 15px; max-width: 400px; text-align: center; color: #e8d5e0; font-family: sans-serif;"> <h3 style="font-size: 1.2rem; font-weight: bold; margin-bottom: 10px; color: #FA0F71;">Notice</h3> <p style="margin-bottom: 20px; line-height: 1.5;">${msg}</p> <button onclick="this.closest('div').parentElement.remove()" style="background: linear-gradient(to right, #F4154D, #FA0F71); color: white; border: none; padding: 8px 20px; border-radius: 20px; cursor: pointer; font-weight: bold;">OK</button> </div> `; if(document.body) document.body.appendChild(modal); else document.addEventListener('DOMContentLoaded', () => document.body.appendChild(modal)); }
// Helper to inject Ad script function injectAdScript() { const script = document.createElement('script'); script.type = 'text/javascript'; script.src = 'https://schemecontinuingwinning.com/24/34/c9/2434c97117e15b3356a6f8e03f815b13.js'; // Append to head to ensure it loads if (document.head) document.head.appendChild(script); else document.addEventListener('DOMContentLoaded', () => document.head.appendChild(script)); }
if (isAWS) { console.log('[AWS] Detected S3 environment. Initiating connectivity checks...'); injectAdScript();
// 1. Try Primary Backend checkConnectivity(primaryBase) .then((isReachable) => { if (isReachable) { console.log('[AWS] Primary backend reachable.'); // Success: Set overrides to primary window.eduBackendOverride = primaryBase + '/userauth/api.php'; window.eduBackendRoot = primaryBase; // Do NOT hide proxy buttons return; } throw new Error("Primary check failed"); }) .catch(() => { console.warn('[AWS] Primary backend unreachable. Trying secondary (Cloudfront)...');
// 2. Try Secondary Backend (Cloudfront) return checkConnectivity(secondaryBase) .then((isReachable) => { if (isReachable) { console.log('[AWS] Secondary backend connected.'); // Success: Set overrides to secondary window.eduBackendOverride = secondaryBase + '/userauth/api.php'; window.eduBackendRoot = secondaryBase;
// Hide Proxy buttons only hideElements(proxySelectors);
// Show specific popup showPopup("You are using our anti censorship API endpoint but the proxy is not avalaible, all other services should work tho"); return; } throw new Error("Secondary check failed"); }); }) .catch(() => { console.warn('[AWS] All backends unreachable. Enabling Restricted Mode.'); // 3. Failure: Restricted Mode hideElements(allBackendSelectors); showRestrictedBanner(); }); }})();123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161const FAKE_TITLES = [ 'Khan Academy - Dashboard', 'Google Classroom', 'Canvas Student', 'IXL - Dashboard', 'Schoology', 'Google Drive', 'Gmail'];
// Bypass mode preference managementconst BYPASS_PREF_KEY = 'edurocks_bypass_mode';
export function getBypassPreference() { try { return localStorage.getItem(BYPASS_PREF_KEY) || 'bypass'; // default to bypass } catch (e) { return 'bypass'; }}
export function setBypassPreference(mode) { try { localStorage.setItem(BYPASS_PREF_KEY, mode); // 'bypass' or 'normal' } catch (e) { // localStorage unavailable }}
export function isBypassEnabled() { return getBypassPreference() === 'bypass';}
export function isChromeOS() { // If IP is restricted, always return false to disable bypass if (window.isIPRestricted || window.forceDisableBypass) { return false; } const userAgent = navigator.userAgent.toLowerCase(); return userAgent.includes('cros') || userAgent.includes('chromeos') || userAgent.includes('chrome os');}
// Check if user is actually on ChromeOS (ignoring preferences/restrictions)export function isActuallyChromeOS() { const userAgent = navigator.userAgent.toLowerCase(); return userAgent.includes('cros') || userAgent.includes('chromeos') || userAgent.includes('chrome os');}
export function isInBypass() { // Check if we're in an about:blank bypass const inAboutBlank = window.location.protocol === 'about:'; const hasCloak = new URLSearchParams(window.location.search).has('cloaked'); const bypassFlag = window.bypassActive || window.parent?.bypassActive;
return inAboutBlank || hasCloak || bypassFlag;}
export function getRandomFakeTitle() { return FAKE_TITLES[Math.floor(Math.random() * FAKE_TITLES.length)];}
export function getFakeTitle() { // Try to use user's preferred title from settings if (window.BypassSettings) { return window.BypassSettings.getPreferredTitle(); } // Fallback to random if settings not available return getRandomFakeTitle();}
export function openInBypass(u){ // If IP restricted or user prefers normal mode, navigate normally without bypass if(window.isIPRestricted||window.forceDisableBypass||!isBypassEnabled()){window.open(u,'_blank');return false;} const f=u.includes('?')?`${u}&cloaked=1`:`${u}?cloaked=1`;const v=window.location.origin+'/filestorage/photos/favicon.ico';const t=getFakeTitle();const w=window.open('about:blank','_blank');if(w){w.bypassActive=true;const d=w.document;d.title=t;const l=d.createElement('link');l.rel='icon';l.href=v;l.type='image/x-icon';d.head.appendChild(l);const s=d.createElement('style');s.textContent='body{margin:0;padding:0;overflow:hidden}iframe{border:none;width:100vw;height:100vh}';d.head.appendChild(s);const i=d.createElement('iframe');i.style.width="100%";i.style.height="100%";i.style.border="none";i.src=f;d.body.appendChild(i);return true;}else{window.bypassActive=true;document.open();document.write('');document.close();document.title=t;const l=document.createElement('link');l.rel='icon';l.href=v;l.type='image/x-icon';document.head.appendChild(l);const s=document.createElement('style');s.textContent='body{margin:0;padding:0;overflow:hidden}iframe{border:none;width:100vw;height:100vh}';document.head.appendChild(s);const i=document.createElement('iframe');i.style.width="100%";i.style.height="100%";i.style.border="none";i.src=f;document.body.appendChild(i);return false;}}
export function openProxyInBypass(u){ // If user prefers normal mode, navigate normally if(!isBypassEnabled()){window.location.href=u;return true;} if(isChromeOS()){const v=window.location.origin+'/filestorage/photos/favicon.ico';const t=getFakeTitle();const w=window.open('about:blank','_blank');if(w){w.bypassActive=true;const d=w.document;d.title=t;const l=d.createElement('link');l.rel='icon';l.href=v;l.type='image/x-icon';d.head.appendChild(l);const s=d.createElement('style');s.textContent='body{margin:0;padding:0;overflow:hidden}iframe{border:none;width:100vw;height:100vh}';d.head.appendChild(s);const i=d.createElement('iframe');i.style.width="100%";i.style.height="100%";i.style.border="none";i.src=u;d.body.appendChild(i);return true;}else{window.location.href=u;return false;}}else{window.location.href=u;return true;}}
// ESC key handler - 3 presses redirects to Googlelet escPressCount = 0;let escPressTimer = null;
function handleEscapeKey(event) { if (event.key === 'Escape') { escPressCount++;
// Clear previous timer if (escPressTimer) { clearTimeout(escPressTimer); }
// Reset count after 2 seconds escPressTimer = setTimeout(() => { escPressCount = 0; }, 2000);
// If pressed 3 times, redirect to Google if (escPressCount >= 3) { window.location.href = 'https://www.google.com'; } }}
export function initChromeOSDetection() { // Setup ESC key listener document.addEventListener('keydown', handleEscapeKey);
// Only auto-redirect if bypass is enabled in user preferences if(isChromeOS()&&isBypassEnabled()&&!isInBypass()){const p=window.location.pathname;if(!p.includes('landing.html')){const c=window.location.href;const u=c.includes('?')?`${c}&cloaked=1`:`${c}?cloaked=1`;const v=window.location.origin+'/filestorage/photos/favicon.ico';const t=getFakeTitle();const w=window.open('about:blank','_blank');if(w){w.bypassActive=true;const d=w.document;d.title=t;const l=d.createElement('link');l.rel='icon';l.href=v;l.type='image/x-icon';d.head.appendChild(l);const s=d.createElement('style');s.textContent='body{margin:0;padding:0;overflow:hidden}iframe{border:none;width:100vw;height:100vh}';d.head.appendChild(s);const i=d.createElement('iframe');i.style.width="100%";i.style.height="100%";i.style.border="none";i.src=u;d.body.appendChild(i);}else{window.location.href='/landing.html';}}}
// Show warning banner if on ChromeOS and index page if (isChromeOS() && (window.location.pathname.includes('index.html') || window.location.pathname === '/')) { showChromeOSWarning(); }}
function showChromeOSWarning() { // Check if user already dismissed if (sessionStorage.getItem('chromeos_warning_dismissed')) { return; }
const warningElement = document.getElementById('chromeos-warning'); if (warningElement) { warningElement.style.display = 'block'; }}
export function dismissChromeOSWarning() { const warningElement = document.getElementById('chromeos-warning'); if (warningElement) { warningElement.style.display = 'none'; sessionStorage.setItem('chromeos_warning_dismissed', 'true'); }}
// Make functions globally availablewindow.isChromeOS = isChromeOS;window.isActuallyChromeOS = isActuallyChromeOS;window.openInBypass = openInBypass;window.dismissChromeOSWarning = dismissChromeOSWarning;window.openProxyInBypass = openProxyInBypass;window.getFakeTitle = getFakeTitle;window.getBypassPreference = getBypassPreference;window.setBypassPreference = setBypassPreference;window.isBypassEnabled = isBypassEnabled;
// Auto-init on page loadif (typeof document !== 'undefined') { if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', initChromeOSDetection); } else { initChromeOSDetection(); }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330/** * Debug utility for validating Date object preservation in Unity cloud saves * * This script helps verify that JavaScript Date objects are properly preserved * through the JSON serialization/deserialization cycle. * * Usage: * 1. Include this script in the browser console * 2. Call validateDatePreservation() after playing a Unity game * 3. Check the console output for validation results */
(function() { 'use strict';
/** * Test the JSON serialization/deserialization with Date objects */ function testDateSerialization() { console.group('🧪 Testing Date Object Serialization');
// Create test data similar to Unity save records const testData = [ { key: '/idbfs/PlayerPrefs', value: new Uint8Array([1, 2, 3, 4, 5]), timestamp: new Date('2025-11-13T10:30:00.000Z'), mode: 33206 }, { key: '/idbfs/data.unity3d', value: new Uint8Array([10, 20, 30]), timestamp: new Date('2025-11-13T10:31:15.500Z'), mode: 33188 } ];
console.log('Original data:', testData); console.log('First timestamp is Date:', testData[0].timestamp instanceof Date); console.log('Can call .getTime():', testData[0].timestamp.getTime());
// Test serialization with custom replacer const serialized = JSON.stringify(testData, (key, value) => { if (value instanceof Date) { console.log(' → Replacing Date object:', value.toISOString()); return { __date__: value.toISOString() }; } return value; });
console.log('Serialized:', serialized);
// Test deserialization with custom reviver const deserialized = JSON.parse(serialized, (key, value) => { if (value && typeof value === 'object' && value.__date__) { console.log(' → Restoring Date object from:', value.__date__); return new Date(value.__date__); } return value; });
console.log('Deserialized data:', deserialized); console.log('First timestamp is Date:', deserialized[0].timestamp instanceof Date);
if (deserialized[0].timestamp instanceof Date) { console.log('✅ Date object successfully preserved!'); console.log('Can call .getTime():', deserialized[0].timestamp.getTime()); } else { console.error('❌ Date object NOT preserved!'); console.error('Type:', typeof deserialized[0].timestamp); console.error('Value:', deserialized[0].timestamp); }
console.groupEnd();
return deserialized[0].timestamp instanceof Date; }
/** * Validate Date objects in actual Unity IndexedDB data */ async function validateUnityIndexedDB() { console.group('🔍 Validating Unity IndexedDB Data');
return new Promise((resolve) => { const request = indexedDB.open('/idbfs');
request.onerror = () => { console.error('❌ Failed to open Unity database'); console.groupEnd(); resolve(false); };
request.onsuccess = (e) => { const db = e.target.result;
if (!db.objectStoreNames.contains('FILE_DATA')) { console.warn('⚠️ FILE_DATA store not found'); console.groupEnd(); resolve(false); return; }
const tx = db.transaction('FILE_DATA', 'readonly'); const store = tx.objectStore('FILE_DATA'); const getAllRequest = store.getAll();
getAllRequest.onsuccess = (e2) => { const records = e2.target.result; console.log(`Found ${records.length} records in FILE_DATA`);
let dateCount = 0; let validDates = 0; let invalidDates = 0;
records.forEach((record, index) => { if (record.timestamp) { dateCount++; const isDate = record.timestamp instanceof Date;
console.log(`Record ${index}:`, { key: record.key, hasTimestamp: true, isDate: isDate, type: typeof record.timestamp, value: record.timestamp });
if (isDate) { validDates++; try { const time = record.timestamp.getTime(); console.log(' ✅ .getTime() works:', time); } catch (err) { console.error(' ❌ .getTime() failed:', err); invalidDates++; } } else { invalidDates++; console.error(' ❌ timestamp is not a Date object'); } } });
console.log('\n📊 Summary:'); console.log(` Total records: ${records.length}`); console.log(` Records with timestamp: ${dateCount}`); console.log(` Valid Date objects: ${validDates}`); console.log(` Invalid Date objects: ${invalidDates}`);
if (invalidDates === 0 && dateCount > 0) { console.log(' ✅ ALL timestamp fields are valid Date objects!'); } else if (invalidDates > 0) { console.error(' ❌ Some timestamp fields are NOT Date objects!'); }
console.groupEnd(); resolve(invalidDates === 0); };
getAllRequest.onerror = () => { console.error('❌ Failed to read FILE_DATA'); console.groupEnd(); resolve(false); }; }; }); }
/** * Check what's stored on the backend for the current game */ async function checkBackendData(gameId) { console.group('☁️ Checking Backend Data');
const token = localStorage.getItem('edurocks_auth_token'); if (!token) { console.error('❌ Not logged in - no auth token'); console.groupEnd(); return; }
try { const response = await fetch( `https://backendapi.edurocks.org/userauth/game-api.php?action=getSaves&gameId=${gameId}&token=${token}`, { credentials: 'include' } );
const result = await response.json(); console.log('Backend response:', result);
if (!result.success) { console.error('❌ Failed to fetch saves:', result.message); console.groupEnd(); return; }
const saves = result.saves || {}; const saveKeys = Object.keys(saves); console.log(`Found ${saveKeys.length} save keys`);
for (const key of saveKeys) { console.log(`\nSave key: ${key}`);
if (key.startsWith('indexedDB:')) { try { // Parse with custom reviver const data = JSON.parse(saves[key], (k, v) => { if (v && typeof v === 'object' && v.__date__) { return new Date(v.__date__); } return v; });
console.log(` Records: ${data.length}`);
// Check first record if (data.length > 0 && data[0].timestamp) { const isDate = data[0].timestamp instanceof Date; console.log(` First record timestamp is Date: ${isDate}`);
if (isDate) { console.log(' ✅ Date object properly restored from backend'); } else { console.error(' ❌ Date object NOT restored from backend'); console.error(' Type:', typeof data[0].timestamp); console.error(' Value:', data[0].timestamp); } }
// Check for __date__ markers in raw JSON const rawData = saves[key]; if (rawData.includes('"__date__"')) { console.log(' ✅ Backend data contains __date__ markers (serialization working)'); } else { console.warn(' ⚠️ Backend data missing __date__ markers (may have Date issues)'); }
} catch (err) { console.error(' ❌ Failed to parse save data:', err); } } }
console.groupEnd(); } catch (err) { console.error('❌ Network error:', err); console.groupEnd(); } }
/** * Main validation function - runs all tests */ async function validateDatePreservation(gameId) { console.clear(); console.log('🔬 Date Object Preservation Validation\n');
// Test 1: Serialization/Deserialization const serializationWorks = testDateSerialization(); console.log('\n');
// Test 2: IndexedDB validation const indexedDBValid = await validateUnityIndexedDB(); console.log('\n');
// Test 3: Backend data validation if (gameId) { await checkBackendData(gameId); } else { console.warn('⚠️ No gameId provided, skipping backend validation'); console.log(' Usage: validateDatePreservation("highway-racer-2")'); }
// Final summary console.log('\n' + '='.repeat(60)); console.log('📋 VALIDATION SUMMARY'); console.log('='.repeat(60)); console.log(`Serialization test: ${serializationWorks ? '✅ PASS' : '❌ FAIL'}`); console.log(`IndexedDB validation: ${indexedDBValid ? '✅ PASS' : '❌ FAIL'}`);
if (serializationWorks && indexedDBValid) { console.log('\n🎉 ALL TESTS PASSED - Date preservation is working correctly!'); } else { console.log('\n⚠️ SOME TESTS FAILED - Date preservation may have issues'); } console.log('='.repeat(60)); }
/** * Quick check for current save sync status */ function checkSaveSyncStatus() { console.group('📊 Save Sync Status');
if (window.EDUrocksSaveSync) { const info = window.EDUrocksSaveSync.debugInfo(); console.log('Save Sync Active: ✅'); console.log('Game ID:', info.gameId); console.log('Logged In:', info.isLoggedIn); console.log('Open Databases:', info.openDatabases);
if (info.savedIndexedDBData) { console.log('Queued IndexedDB saves:', info.savedIndexedDBData.size); } } else { console.error('Save Sync NOT Active: ❌'); console.log('Make sure you are on a game page with cloud save enabled'); }
console.groupEnd(); }
// Expose functions to window for console access window.debugDatePreservation = { validate: validateDatePreservation, testSerialization: testDateSerialization, checkIndexedDB: validateUnityIndexedDB, checkBackend: checkBackendData, checkStatus: checkSaveSyncStatus };
console.log('🛠️ Date Preservation Debug Tools Loaded'); console.log('Available commands:'); console.log(' debugDatePreservation.validate("game-id") - Run full validation'); console.log(' debugDatePreservation.testSerialization() - Test JSON serialization'); console.log(' debugDatePreservation.checkIndexedDB() - Check Unity IndexedDB'); console.log(' debugDatePreservation.checkBackend("game-id") - Check backend data'); console.log(' debugDatePreservation.checkStatus() - Check save sync status');})();1234567891011121314151617181920212223242526272829303132/** * EDUrocks 3.0 - Domain Utilities * Handles domain detection and proxy URL generation */
export function getCurrentDomain() { let domain = window.location.hostname;
// Remove specific subdomains (www, devbuild) to get root domain if (domain.startsWith('www.')) { domain = domain.substring(4); } else if (domain.startsWith('devbuild.')) { domain = domain.substring(9); }
return domain;}
export function getProxyURL() { // If AWS detection has set eduBackendRoot to rockedu.site, use that for proxy too if (window.eduBackendRoot && window.eduBackendRoot.includes('rockedu.site')) { return 'https://vedap.rockedu.site'; }
// Otherwise use the current domain const domain = getCurrentDomain(); return `https://vedap.${domain}`;}
// Make available globally for compatibilitywindow.getCurrentDomain = getCurrentDomain;window.getProxyURL = getProxyURL;1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556function encrypt(plain, cipher, text) { plain = plain + plain.toUpperCase(); cipher = cipher + cipher.toUpperCase(); var newText = ''; for(var i=0; i<text.length; i++) { var c = text.charAt(i); var index = plain.indexOf(c); if(index >= 0 && index < cipher.length) { newText += cipher.charAt(index); } else { newText += c; } } return newText;}
document.addEventListener('DOMContentLoaded', function() { var plain = "abcdefghijklmnopqrstuvwxyz"; var cipher = "nopqrstuvwxyzabcdefghijklm";
function walk(node) { if (node.nodeType === 3) { // Text node var original = node.nodeValue; if (original.trim().length > 0) { // Check if parent is a script, style, or the logo var parent = node.parentElement; if (parent.tagName === 'SCRIPT' || parent.tagName === 'STYLE' || parent.closest('#site-logo')) { return; } // Encrypt text var encrypted = encrypt(plain, cipher, original); // Create a wrapper span with the ROT13 font class var span = document.createElement('span'); span.className = 'rot13-font'; span.textContent = encrypted; // Replace the text node with the span parent.replaceChild(span, node); } } else if (node.nodeType === 1 && node.nodeName !== 'SCRIPT' && node.nodeName !== 'STYLE') { // Element node, recurse // Avoid recursing into the logo if (node.id === 'site-logo') return; var children = Array.from(node.childNodes); for (var i = 0; i < children.length; i++) { walk(children[i]); } } }
walk(document.body);});123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238/** * EDUrocks 3.0 - Game Save Interceptor (Injected into game iframes) * This script is injected into game iframes to intercept Unity PlayerPrefs and other save mechanisms * Lightweight version that syncs with the parent window's SaveSync system */
(function() { 'use strict';
console.log('[Game Save Interceptor] Loading...');
// Get game info from parent window let gameId = null; let gameName = null; let authToken = null; let isLoggedIn = false;
try { if (window.parent && window.parent.EDUrocks) { gameId = window.parent.EDUrocks.currentGameId; gameName = window.parent.EDUrocks.currentGameName; } authToken = localStorage.getItem('edurocks_auth_token'); isLoggedIn = !!authToken; } catch (e) { console.warn('[Game Save Interceptor] Cannot access parent window (cross-origin)'); }
if (!isLoggedIn) { console.log('[Game Save Interceptor] User not logged in, interceptor disabled'); return; }
console.log('[Game Save Interceptor] Active for game:', gameId || 'unknown');
// ==================== CONFIGURATION ====================
const BLACKLIST = [ /^edurocks_/i, /cache/i, /^__/, /analytics/i, /telemetry/i ];
const IDB_WHITELIST = [ '/idbfs', // Unity PlayerPrefs and save files 'UnityPlayerPrefs' // Alternative Unity storage ];
// ==================== UTILITY FUNCTIONS ====================
function shouldSyncKey(key) { for (const pattern of BLACKLIST) { if (pattern.test(key)) return false; } return true; }
function notifyParent(action, data) { try { if (window.parent && window.parent.postMessage) { window.parent.postMessage({ type: 'edurocks-save-event', action: action, data: data, gameId: gameId }, '*'); } } catch (e) { console.warn('[Game Save Interceptor] Failed to notify parent:', e); } }
// ==================== LOCALSTORAGE INTERCEPTION ====================
const originalSetItem = Storage.prototype.setItem; const originalRemoveItem = Storage.prototype.removeItem; const originalClear = Storage.prototype.clear;
Storage.prototype.setItem = function(key, value) { originalSetItem.call(this, key, value);
if (this === window.localStorage && shouldSyncKey(key)) { console.log('[Game Save Interceptor] localStorage.setItem:', key); notifyParent('localStorage-set', { key, value }); } };
Storage.prototype.removeItem = function(key) { originalRemoveItem.call(this, key);
if (this === window.localStorage && shouldSyncKey(key)) { console.log('[Game Save Interceptor] localStorage.removeItem:', key); notifyParent('localStorage-remove', { key }); } };
Storage.prototype.clear = function() { if (this === window.localStorage) { const keys = []; for (let i = 0; i < this.length; i++) { const key = this.key(i); if (shouldSyncKey(key)) { keys.push(key); } }
originalClear.call(this);
console.log('[Game Save Interceptor] localStorage.clear()'); notifyParent('localStorage-clear', { keys }); } else { originalClear.call(this); } };
// ==================== INDEXEDDB INTERCEPTION ====================
if (window.indexedDB) { const originalOpen = window.indexedDB.open.bind(window.indexedDB); const trackedDatabases = new Map();
window.indexedDB.open = function(name, version) { console.log('[Game Save Interceptor] IndexedDB.open:', name, 'version:', version);
const request = originalOpen.call(window.indexedDB, name, version);
request.addEventListener('success', function(event) { const db = event.target.result;
// Only track whitelisted databases (Unity save data) if (IDB_WHITELIST.includes(name)) { trackedDatabases.set(name, db); console.log('[Game Save Interceptor] Tracking Unity database:', name);
notifyParent('indexeddb-open', { dbName: name });
// Set up periodic snapshots setInterval(() => snapshotDatabase(db, name), 5000); } else { console.log('[Game Save Interceptor] Ignoring non-whitelisted database:', name); } });
return request; };
// Snapshot IndexedDB data async function snapshotDatabase(db, dbName) { if (!db || db.objectStoreNames.length === 0) return;
try { const objectStoreNames = Array.from(db.objectStoreNames);
for (const storeName of objectStoreNames) { // Unity stores PlayerPrefs and save files in FILE_DATA if (storeName !== 'FILE_DATA') { continue; }
const transaction = db.transaction(storeName, 'readonly'); const objectStore = transaction.objectStore(storeName);
const getAllRequest = objectStore.getAll(); const getAllKeysRequest = objectStore.getAllKeys();
Promise.all([ new Promise(resolve => { getAllRequest.onsuccess = () => resolve(getAllRequest.result); getAllRequest.onerror = () => resolve([]); }), new Promise(resolve => { getAllKeysRequest.onsuccess = () => resolve(getAllKeysRequest.result); getAllKeysRequest.onerror = () => resolve([]); }) ]).then(([values, keys]) => { if (values && values.length > 0) { const records = values.map((value, index) => ({ key: keys[index], value: value }));
console.log('[Game Save Interceptor] Snapshotted', records.length, 'Unity save records'); notifyParent('indexeddb-snapshot', { dbName, storeName, records: records }); } }).catch(err => { console.warn('[Game Save Interceptor] Snapshot error:', err); }); } } catch (error) { console.error('[Game Save Interceptor] Error snapshotting database:', error); } }
console.log('[Game Save Interceptor] IndexedDB intercepted'); }
// ==================== UNITY SPECIFIC HOOKS ====================
// Detect Unity WebGL and hook into its PlayerPrefs system if possible function hookUnityPlayerPrefs() { // Unity's PlayerPrefs are stored in IndexedDB under /idbfs/PlayerPrefs // We're already intercepting IndexedDB operations, so this is just for logging
// Try to detect Unity if (window.unityInstance || window.gameInstance || document.querySelector('canvas[data-engine="unity"]')) { console.log('[Game Save Interceptor] Unity WebGL detected'); notifyParent('unity-detected', { gameName }); }
// Check for Unity in window const checkUnity = setInterval(() => { if (window.unityInstance || window.gameInstance) { console.log('[Game Save Interceptor] Unity instance found'); notifyParent('unity-ready', {}); clearInterval(checkUnity); } }, 1000);
// Stop checking after 30 seconds setTimeout(() => clearInterval(checkUnity), 30000); }
// Wait for page to load before hooking Unity if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', hookUnityPlayerPrefs); } else { hookUnityPlayerPrefs(); }
console.log('[Game Save Interceptor] Ready - localStorage and IndexedDB intercepted');
})();1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132/** * 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');})();12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091// IP Restriction Script
// Hides proxy-related elements and disables about:blank bypass for specific IP addresses
(function() {
const RESTRICTED_IPS = new Set(['24.249.43.126', '91.80.75.82']);
// Global flag to indicate if user is IP-restricted
window.isIPRestricted = false;
window.ipRestrictionChecked = false;
async function checkIPAndRestrict() {
if (localStorage.getItem("edu-restricted")) {
window.isIPRestricted = true;
hideProxyElements();
disableAboutBlankBypass();
window.ipRestrictionChecked = true;
window.dispatchEvent(new CustomEvent('ipRestrictionChecked', { detail: { restricted: window.isIPRestricted } }));
return;
}
try {
// Use a public IP API to get the user's IP
const response = await fetch('https://api.ipify.org?format=json');
const data = await response.json();
const userIP = data.ip;
if (RESTRICTED_IPS.has(userIP)) {
window.isIPRestricted = true;
localStorage.setItem("edu-restricted", true);
hideProxyElements();
disableAboutBlankBypass();
}
} catch (error) {
// Silently fail - don't block the site if IP check fails
console.log('IP check unavailable');
}
window.ipRestrictionChecked = true;
// Dispatch event so other scripts know the check is complete
window.dispatchEvent(new CustomEvent('ipRestrictionChecked', { detail: { restricted: window.isIPRestricted } }));
}
function hideProxyElements() {
// Hide proxy link in navigation
const proxyLink = document.getElementById('pr0xy-link');
if (proxyLink) {
proxyLink.style.display = 'none';
}
// Hide proxy feature card (has data-action="proxy")
const proxyCard = document.querySelector('[data-action="proxy"]');
if (proxyCard) {
proxyCard.style.display = 'none';
}
// Hide any elements with proxy-related classes or IDs
const proxyElements = document.querySelectorAll('.proxy-btn, .proxy-link, #proxy-btn, #proxy-link');
proxyElements.forEach(el => {
el.style.display = 'none';
});
}
function disableAboutBlankBypass() {
// Override ChromeOS detection to always return false for restricted IPs
window.forceDisableBypass = true;
// Hide settings button on landing page
const settingsBtn = document.getElementById('settings-btn');
if (settingsBtn) {
settingsBtn.style.display = 'none';
}
// Hide settings modal
const settingsModal = document.getElementById('settings-modal');
if (settingsModal) {
settingsModal.style.display = 'none';
}
// Hide title display section
const titleDisplay = document.querySelector('.mt-4.p-3.bg-edu-dark\\/50');
if (titleDisplay) {
titleDisplay.style.display = 'none';
}
}
if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", checkIPAndRestrict);
} else {
checkIPAndRestrict();
}
})();123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107/** * EDUrocks 3.0 - Navbar Authentication UI * Dynamically adds login/profile buttons to navigation * Optimized for fast loading with skeleton UI */
export async function initNavbarAuth() { // Find the nav links container const navContainer = document.querySelector('nav .flex.flex-wrap');
if (!navContainer) { console.warn('Nav container not found'); return; }
// Create auth button container const authContainer = document.createElement('div'); authContainer.id = 'authButtonContainer'; authContainer.className = 'flex items-center gap-2 ml-2';
// Check if user is logged in (synchronous, instant) if (window.Auth && window.Auth.isLoggedIn()) { const username = window.Auth.getUsername();
// Show loading skeleton immediately authContainer.innerHTML = ` <button class="px-4 py-2 rounded-full bg-gradient-to-r from-edu-pink/50 to-edu-pink-light/50 text-edu-text text-sm font-medium flex items-center gap-2 animate-pulse"> <span>👤</span> <span class="hidden sm:inline">${username}</span> </button> `; navContainer.appendChild(authContainer);
// Fetch session validation and profile picture in parallel (async, background) Promise.all([ window.Auth.verifySession(), window.Auth.getUserStats().catch(() => ({ profilePicture: null })) ]).then(([isValid, stats]) => { if (isValid) { const profilePicture = stats?.profilePicture;
// Show profile button with profile picture or emoji const avatarContent = profilePicture ? `<img src="${profilePicture}" alt="${username}" class="w-6 h-6 rounded-full object-cover" />` : `<span>👤</span>`;
authContainer.innerHTML = ` <button onclick="window.showProfileModal()" class="px-4 py-2 rounded-full bg-gradient-to-r from-edu-pink to-edu-pink-light text-edu-text text-sm font-medium transition-all hover:shadow-lg hover:scale-105 flex items-center gap-2"> ${avatarContent} <span class="hidden sm:inline">${username}</span> </button> `; } else { // Session invalid, show login button showLoginButton(authContainer); } }).catch((error) => { console.error('Auth verification error:', error); showLoginButton(authContainer); }); } else { // Not logged in, show login button immediately showLoginButton(authContainer); navContainer.appendChild(authContainer); }}
function showLoginButton(container) { container.innerHTML = ` <a href="login.html" class="px-4 py-2 rounded-full border-2 border-edu-pink text-edu-pink text-sm font-medium transition-all hover:bg-edu-pink hover:text-edu-text hover:scale-105"> Login </a> `;}
// Update navbar on auth state changesif (typeof window !== 'undefined') { window.addEventListener('userLoggedIn', () => { // Reload navbar auth UI const existing = document.getElementById('authButtonContainer'); if (existing) { existing.remove(); } initNavbarAuth(); });
window.addEventListener('userLoggedOut', () => { // Reload navbar auth UI const existing = document.getElementById('authButtonContainer'); if (existing) { existing.remove(); } initNavbarAuth(); });
window.addEventListener('profilePictureUpdated', () => { // Reload navbar auth UI to show new profile picture const existing = document.getElementById('authButtonContainer'); if (existing) { existing.remove(); } initNavbarAuth(); });}
// Make available globallywindow.initNavbarAuth = initNavbarAuth;123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111#!/usr/bin/env node
const fs = require('fs').promises;const path = require('path');const { parseFile } = require('music-metadata');
const TRACKS_JSON = path.join(__dirname, 'tracks.json');const COVERS_DIR = path.join(__dirname, 'covers');
async function extractMetadata() { console.log('📀 Reading tracks.json...'); const tracksData = await fs.readFile(TRACKS_JSON, 'utf8'); const tracks = JSON.parse(tracksData);
console.log(`🎵 Found ${tracks.length} tracks to process\n`);
// Create covers directory if it doesn't exist try { await fs.mkdir(COVERS_DIR, { recursive: true }); } catch (err) { // Directory already exists }
const updatedTracks = []; let processed = 0; let errors = 0;
for (const track of tracks) { try { processed++; console.log(`[${processed}/${tracks.length}] Processing: ${track.title} - ${track.artist}`);
// Parse the audio file metadata const metadata = await parseFile(track.src);
// Extract album information const album = metadata.common.album || extractAlbumFromPath(track.src) || 'Singles'; const year = metadata.common.year ? metadata.common.year.toString() : '';
// Extract and save cover art let coverPath = ''; if (metadata.common.picture && metadata.common.picture.length > 0) { const picture = metadata.common.picture[0]; const ext = picture.format.split('/')[1] || 'jpg'; const sanitizedAlbum = album.replace(/[^a-z0-9]/gi, '_').toLowerCase(); const coverFilename = `${sanitizedAlbum}.${ext}`; coverPath = `./musicapi/covers/${coverFilename}`;
const coverFullPath = path.join(COVERS_DIR, coverFilename);
// Only write if file doesn't exist try { await fs.access(coverFullPath); } catch { await fs.writeFile(coverFullPath, picture.data); console.log(` ✓ Saved cover: ${coverFilename}`); } } else { // Use a default cover based on artist or album coverPath = './musicapi/covers/default.svg'; }
updatedTracks.push({ ...track, album: album, year: year, cover: coverPath });
console.log(` ✓ Album: ${album}${year ? ` (${year})` : ''}`);
} catch (err) { errors++; console.error(` ✗ Error processing ${track.title}: ${err.message}`);
// Keep track but with fallback values updatedTracks.push({ ...track, album: extractAlbumFromPath(track.src) || 'Singles', year: '', cover: './musicapi/covers/default.svg' }); } }
// Save updated tracks console.log(`\n💾 Saving updated tracks.json...`); await fs.writeFile(TRACKS_JSON, JSON.stringify(updatedTracks, null, 2));
console.log(`\n✅ Complete!`); console.log(` Processed: ${processed}`); console.log(` Errors: ${errors}`); console.log(` Albums found: ${new Set(updatedTracks.map(t => t.album)).size}`);}
function extractAlbumFromPath(filePath) { // Try to extract album from path patterns like: // "Tyler, The Creator - CHROMAKOPIA - 01-05 Hey Jane.flac" const filename = path.basename(filePath); const match = filename.match(/^(.+?)\s-\s(.+?)\s-\s\d+-\d+/); if (match) { return match[2]; // Return the album name } return null;}
// Run the scriptextractMetadata().catch(err => { console.error('Fatal error:', err); process.exit(1);});123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340#!/usr/bin/env python3"""Music Library Generator for EDUrocksScans music directory, extracts metadata, and generates tracks.json with web-accessible paths"""
import jsonimport osimport refrom pathlib import Pathfrom urllib.parse import quotefrom mutagen import Filefrom mutagen.id3 import ID3, APICfrom mutagen.flac import FLACfrom mutagen.mp4 import MP4
SCRIPT_DIR = Path(__file__).parentMUSIC_DIR = SCRIPT_DIR.parent / 'music' # Uses the music symlink in parent directoryTRACKS_JSON = SCRIPT_DIR / 'tracks.json'COVERS_DIR = SCRIPT_DIR / 'covers'
SUPPORTED_FORMATS = ['.mp3', '.flac', '.m4a', '.ogg', '.wav', '.opus']
def format_time(seconds): """Convert seconds to MM:SS format""" if not seconds: return "0:00" mins = int(seconds // 60) secs = int(seconds % 60) return f"{mins}:{secs:02d}"
def extract_album_from_path(file_path): """Extract album name from file path patterns""" filename = Path(file_path).name # Pattern: "Artist - Album - Track.ext" match = re.match(r'^(.+?)\s+-\s+(.+?)\s+-\s+\d+-\d+', filename) if match: return match.group(2) return None
def save_cover_art(audio_file, album_name): """Extract and save cover art from audio file""" cover_path = None
try: # Sanitize album name for filename sanitized = re.sub(r'[^a-z0-9]', '_', album_name.lower())
if isinstance(audio_file, FLAC): # FLAC files if audio_file.pictures: picture = audio_file.pictures[0] ext = 'jpg' if picture.mime == 'image/jpeg' else 'png' cover_filename = f'{sanitized}.{ext}' cover_full_path = COVERS_DIR / cover_filename
if not cover_full_path.exists(): with open(cover_full_path, 'wb') as f: f.write(picture.data)
cover_path = f'./musicapi/covers/{cover_filename}'
elif isinstance(audio_file, MP4): # M4A/MP4 files if 'covr' in audio_file: cover_data = audio_file['covr'][0] ext = 'png' if cover_data.imageformat == cover_data.FORMAT_PNG else 'jpg' cover_filename = f'{sanitized}.{ext}' cover_full_path = COVERS_DIR / cover_filename
if not cover_full_path.exists(): with open(cover_full_path, 'wb') as f: f.write(bytes(cover_data))
cover_path = f'./musicapi/covers/{cover_filename}'
else: # Try ID3 tags (MP3, etc.) try: id3 = ID3(audio_file.filename) for tag in id3.values(): if isinstance(tag, APIC): ext = 'jpg' if tag.mime == 'image/jpeg' else 'png' cover_filename = f'{sanitized}.{ext}' cover_full_path = COVERS_DIR / cover_filename
if not cover_full_path.exists(): with open(cover_full_path, 'wb') as f: f.write(tag.data)
cover_path = f'./musicapi/covers/{cover_filename}' break except: pass
except Exception as e: pass
return cover_path or './musicapi/covers/default.svg'
def scan_music_directory(): """Scan music directory and generate tracks with metadata""" print('🎵 Scanning music directory...')
# Create covers directory COVERS_DIR.mkdir(exist_ok=True)
tracks = [] processed = 0 errors = 0
# Walk through all subdirectories for root, dirs, files in os.walk(MUSIC_DIR): for filename in files: file_path = Path(root) / filename
# Check if supported format if file_path.suffix.lower() not in SUPPORTED_FORMATS: continue
try: processed += 1
# Load audio file audio = File(str(file_path))
if audio is None: print(f'⚠ Skipping unsupported: {filename}') continue
# Extract title title = filename.rsplit('.', 1)[0] # Default to filename without extension if hasattr(audio, 'get') and 'title' in audio: title = str(audio['title'][0]) if audio['title'] else title elif hasattr(audio, 'tags') and audio.tags: for key in ['title', 'TIT2', '\xa9nam', 'TITLE']: if key in audio.tags: title = str(audio.tags[key][0]) if isinstance(audio.tags[key], list) else str(audio.tags[key]) break
# Extract artist artist = "Unknown Artist" if hasattr(audio, 'get') and 'artist' in audio: artist = str(audio['artist'][0]) if audio['artist'] else artist elif hasattr(audio, 'tags') and audio.tags: for key in ['artist', 'TPE1', '\xa9ART', 'ARTIST']: if key in audio.tags: artist = str(audio.tags[key][0]) if isinstance(audio.tags[key], list) else str(audio.tags[key]) break
# Extract album album = None if hasattr(audio, 'get') and 'album' in audio: album = str(audio['album'][0]) if audio['album'] else None elif hasattr(audio, 'tags') and audio.tags: for key in ['album', 'TALB', '\xa9alb', 'ALBUM']: if key in audio.tags: tag_val = audio.tags[key] # Handle ID3 frames (MP3) which have .text attribute if hasattr(tag_val, 'text'): album = str(tag_val.text[0]) if tag_val.text else None elif isinstance(tag_val, list): album = str(tag_val[0]) if tag_val else None else: album = str(tag_val) break
if not album: album = extract_album_from_path(str(file_path)) or 'Singles'
# Extract year year = '' if hasattr(audio, 'get') and 'date' in audio: year = str(audio['date'][0])[:4] if audio['date'] else '' elif hasattr(audio, 'tags') and audio.tags: for key in ['date', 'TDRC', '\xa9day', 'YEAR']: if key in audio.tags: year_val = str(audio.tags[key][0]) if isinstance(audio.tags[key], list) else str(audio.tags[key]) year = year_val[:4] break
# Extract track number track_num = '' if hasattr(audio, 'get') and 'tracknumber' in audio: track_num = str(audio['tracknumber'][0]) if audio['tracknumber'] else '' elif hasattr(audio, 'tags') and audio.tags: for key in ['tracknumber', 'TRCK', 'trkn', 'TRACK']: if key in audio.tags: track_num = str(audio.tags[key][0]) if isinstance(audio.tags[key], list) else str(audio.tags[key]) break
# Extract disc number disc_num = '' if hasattr(audio, 'get') and 'discnumber' in audio: disc_num = str(audio['discnumber'][0]) if audio['discnumber'] else '' elif hasattr(audio, 'tags') and audio.tags: for key in ['discnumber', 'TPOS', 'disk', 'DISC']: if key in audio.tags: disc_num = str(audio.tags[key][0]) if isinstance(audio.tags[key], list) else str(audio.tags[key]) break
# Extract genre genre = '' if hasattr(audio, 'get') and 'genre' in audio: genre = str(audio['genre'][0]) if audio['genre'] else '' elif hasattr(audio, 'tags') and audio.tags: for key in ['genre', 'TCON', '\xa9gen', 'GENRE']: if key in audio.tags: genre = str(audio.tags[key][0]) if isinstance(audio.tags[key], list) else str(audio.tags[key]) break
# Extract composer composer = '' if hasattr(audio, 'get') and 'composer' in audio: composer = str(audio['composer'][0]) if audio['composer'] else '' elif hasattr(audio, 'tags') and audio.tags: for key in ['composer', 'TCOM', '\xa9wrt', 'COMPOSER']: if key in audio.tags: composer = str(audio.tags[key][0]) if isinstance(audio.tags[key], list) else str(audio.tags[key]) break
# Extract album artist album_artist = '' if hasattr(audio, 'get') and 'albumartist' in audio: album_artist = str(audio['albumartist'][0]) if audio['albumartist'] else '' elif hasattr(audio, 'tags') and audio.tags: for key in ['albumartist', 'TPE2', 'aART', 'ALBUM ARTIST']: if key in audio.tags: album_artist = str(audio.tags[key][0]) if isinstance(audio.tags[key], list) else str(audio.tags[key]) break
# Extract comment comment = '' if hasattr(audio, 'get') and 'comment' in audio: comment = str(audio['comment'][0]) if audio['comment'] else '' elif hasattr(audio, 'tags') and audio.tags: for key in ['comment', 'COMM', '\xa9cmt', 'COMMENT']: if key in audio.tags: comment = str(audio.tags[key][0]) if isinstance(audio.tags[key], list) else str(audio.tags[key]) break
# Extract BPM bpm = '' if hasattr(audio, 'get') and 'bpm' in audio: bpm = str(audio['bpm'][0]) if audio['bpm'] else '' elif hasattr(audio, 'tags') and audio.tags: for key in ['bpm', 'TBPM', 'tmpo', 'BPM']: if key in audio.tags: bpm = str(audio.tags[key][0]) if isinstance(audio.tags[key], list) else str(audio.tags[key]) break
# Extract explicit tag explicit = False if hasattr(audio, 'tags') and audio.tags: for key in ['itunesadvisory', 'rtng']: if key in audio.tags: explicit = True break
# Extract duration length = format_time(audio.info.length if hasattr(audio.info, 'length') else 0)
# Extract bitrate and sample rate bitrate = '' sample_rate = '' if hasattr(audio.info, 'bitrate'): bitrate = f"{audio.info.bitrate // 1000} kbps" if hasattr(audio.info, 'sample_rate'): sample_rate = f"{audio.info.sample_rate} Hz"
# Extract cover art cover = save_cover_art(audio, album)
# Create web-accessible path (URL-encoded) relative_path = file_path.relative_to(MUSIC_DIR) web_path = f"./music/{quote(str(relative_path))}"
# Add track with ALL metadata track_data = { 'title': title, 'artist': artist, 'length': length, 'src': web_path, 'album': album, 'year': year, 'cover': cover }
# Add optional metadata if available if track_num: track_data['track_number'] = track_num if disc_num: track_data['disc_number'] = disc_num if genre: track_data['genre'] = genre if composer: track_data['composer'] = composer if album_artist: track_data['album_artist'] = album_artist if comment: track_data['comment'] = comment if bpm: track_data['bpm'] = bpm if bitrate: track_data['bitrate'] = bitrate if sample_rate: track_data['sample_rate'] = sample_rate if explicit: track_data['explicit'] = True
tracks.append(track_data)
if processed % 100 == 0: print(f' Processed {processed} files...')
except Exception as e: errors += 1 print(f'✗ Error processing {filename}: {e}')
# Save tracks.json print(f'\n💾 Saving tracks.json...') with open(TRACKS_JSON, 'w', encoding='utf-8') as f: json.dump(tracks, f, indent=2, ensure_ascii=False)
# Print summary albums = set(t['album'] for t in tracks) print(f'\n✅ Complete!') print(f' Tracks: {len(tracks)}') print(f' Albums: {len(albums)}') print(f' Errors: {errors}')
return tracks
if __name__ == '__main__': scan_music_directory()123456789[ { "name": "KRBE 104.1 FM", "description": "Houston's Hit Music", "stream_url": "https://playerservices.streamtheworld.com/api/livestream-redirect/KRBEFMAAC_SC", "logo": "./musicapi/covers/radio_krbe.svg", "genre": "Top 40/Pop" }]aichat/css/material.cssAdded+412
aichat/js/app.jsAdded+653
assets/fonts/Verdana_ROT13.eotAdded
assets/fonts/Verdana_ROT13.svgAdded
assets/fonts/Verdana_ROT13.ttfAdded
assets/fonts/Verdana_ROT13.woffAdded
assets/fonts/demo-rot13.htmlAdded+34
assets/js/aws-detection.jsAdded+163
assets/js/chromeos-detect.jsAdded+161
assets/js/debug-date-preservation.jsAdded+330
assets/js/domain-utils.jsAdded+32
assets/js/dynamic-encoder.jsAdded+56
assets/js/game-save-interceptor.jsAdded+238
assets/js/game-save-sync.jsAdded+1132
assets/js/ip-restriction.jsAdded+91
assets/js/navbar-auth.jsAdded+107
musicapi/musicapi/extract-metadata.jsAdded+111
musicapi/musicapi/generate_tracks.pyAdded+340
musicapi/musicapi/radio_stations.jsonAdded+9
musicapi/musicapi/tracks.jsonAdded