(function () { "use strict"; // ========================================================================= // 1. AUDIO MANAGER (Cached, Single-Fetch, Autoplay-Safe) // ========================================================================= const SOUND_URL = "/assets/panel/audio/sound.mp3"; const AudioContextClass = window.AudioContext || window.webkitAudioContext; let audioCtx = null; let soundBuffer = null; let isUnlocked = false; // Single HTML5 Audio instance fallback const fallbackAudio = new Audio(); fallbackAudio.preload = "auto"; // Fetch audio file ONCE and keep in memory buffer function preloadAudio() { fallbackAudio.src = SOUND_URL; fetch(SOUND_URL, { cache: "force-cache" }) .then((res) => { if (!res.ok) throw new Error("Network response error"); return res.arrayBuffer(); }) .then((bytes) => { if (audioCtx) { return audioCtx.decodeAudioData(bytes); } }) .then((buffer) => { if (buffer) soundBuffer = buffer; }) .catch((err) => { // Fallback gracefully if arrayBuffer fails }); } // Preload on script load preloadAudio(); // Unlock AudioContext on User Gesture function unlockAudio() { if (isUnlocked) return; if (!audioCtx && AudioContextClass) { audioCtx = new AudioContextClass(); preloadAudio(); } if (audioCtx && audioCtx.state === "suspended") { audioCtx.resume(); } // Play silent snippet on HTML5 Audio to unlock media pipeline fallbackAudio.volume = 0; const promise = fallbackAudio.play(); if (promise !== undefined) { promise .then(() => { fallbackAudio.pause(); fallbackAudio.currentTime = 0; fallbackAudio.volume = 1; isUnlocked = true; removeUnlockListeners(); }) .catch(() => { }); } } function removeUnlockListeners() { ["click", "pointerdown", "keydown", "touchstart"].forEach((event) => { document.removeEventListener(event, unlockAudio, true); }); } // Listen for initial user interaction to unlock audio ["click", "pointerdown", "keydown", "touchstart"].forEach((event) => { document.addEventListener(event, unlockAudio, { capture: true, passive: true }); }); // Play notification sound safely without triggering network calls function playNotifySound() { if (!isUnlocked) { console.warn("[Chat]: Audio blocked - page not interacted with yet."); return; } // 1. Play using Web Audio API buffer if (audioCtx && audioCtx.state === "running" && soundBuffer) { try { const source = audioCtx.createBufferSource(); source.buffer = soundBuffer; source.connect(audioCtx.destination); source.start(0); return; } catch (e) { } } // 2. Fallback to cached HTML5 Audio instance try { fallbackAudio.currentTime = 0; fallbackAudio.volume = 1; fallbackAudio.play().catch(() => { }); } catch (e) { } } // ========================================================================= // 2. MESSAGE DEDUPLICATION TRACKER // ========================================================================= const processedMessageIds = new Set(); function isDuplicateMessage(messageData) { // Check by ID if server supplies one if (messageData.id) { if (processedMessageIds.has(messageData.id)) { return true; } processedMessageIds.add(messageData.id); return false; } // Fallback deduplication by DOM attribute check if (messageData.tempId || messageData.client_id) { const uniqueKey = messageData.tempId || messageData.client_id; if (document.querySelector(`[data-msg-id="${uniqueKey}"]`)) { return true; } } return false; } // ========================================================================= // 3. WEBSOCKET & CHAT EVENT HANDLERS // ========================================================================= // Call this function when an incoming message is received from WebSocket function onIncomingMessage(data) { // Fix duplicate rendering: ignore if message is already rendered if (isDuplicateMessage(data)) { return; } // Append to Chat UI renderMessageToDOM(data); // Play notification sound ONLY for messages from client (not admin's own echo) if (data.sender !== "admin") { playNotifySound(); } } // Call this function when Admin clicks "Send" button or hits Enter function sendAdminMessage(text) { if (!text || !text.trim()) return; const tempId = "msg_" + Date.now() + "_" + Math.random().toString(36).substr(2, 9); const messagePayload = { tempId: tempId, sender: "admin", text: text, timestamp: new Date().toISOString() }; // Render immediately in DOM for responsiveness renderMessageToDOM(messagePayload); processedMessageIds.add(tempId); // Send payload through WebSocket if (window.chatSocket && window.chatSocket.readyState === WebSocket.OPEN) { window.chatSocket.send(JSON.stringify(messagePayload)); } } // DOM Renderer Function function renderMessageToDOM(msg) { const chatContainer = document.getElementById("chat-messages-container"); if (!chatContainer) return; // Double-check DOM to prevent accidental duplicate insertion const msgId = msg.id || msg.tempId; if (msgId && chatContainer.querySelector(`[data-msg-id="${msgId}"]`)) { return; } const msgElement = document.createElement("div"); msgElement.className = `message-bubble ${msg.sender === "admin" ? "admin-message" : "client-message"}`; if (msgId) { msgElement.setAttribute("data-msg-id", msgId); } msgElement.textContent = msg.text; chatContainer.appendChild(msgElement); chatContainer.scrollTop = chatContainer.scrollHeight; } // Example WebSocket Receiver Setup function initWebSocket() { window.chatSocket = new WebSocket("wss://" + window.location.host + "/ws/chat/"); window.chatSocket.onmessage = function (event) { try { const data = JSON.parse(event.data); onIncomingMessage(data); } catch (e) { console.error("Invalid JSON received:", e); } }; } // Initialize document.addEventListener("DOMContentLoaded", function () { initWebSocket(); }); })();