diff --git a/public/assets/panel/js/chat.js b/public/assets/panel/js/chat.js index 38acbed..7588e7b 100644 --- a/public/assets/panel/js/chat.js +++ b/public/assets/panel/js/chat.js @@ -1,104 +1,220 @@ -// ------------------------------------------------------------- -// AUDIO MANAGER (Bypasses Browser Autoplay Restrictions) -// ------------------------------------------------------------- -const SOUND_URL = "/assets/panel/audio/sound.mp3"; -const AudioContextClass = window.AudioContext || window.webkitAudioContext; +(function () { + "use strict"; -let audioCtx = null; -let soundBuffer = null; -let isUnlocked = false; + // ========================================================================= + // 1. AUDIO MANAGER (Cached, Single-Fetch, Autoplay-Safe) + // ========================================================================= + const SOUND_URL = "/assets/panel/audio/sound.mp3"; + const AudioContextClass = window.AudioContext || window.webkitAudioContext; -// Single HTML5 Audio instance fallback -const fallbackAudio = document.getElementById("mm-chat-sound") || new Audio(SOUND_URL); -fallbackAudio.src = SOUND_URL; -fallbackAudio.preload = "auto"; + let audioCtx = null; + let soundBuffer = null; + let isUnlocked = false; -// Pre-load sound buffer for Web Audio API -function loadSoundBuffer() { - fetch(SOUND_URL, { credentials: "same-origin", cache: "force-cache" }) - .then((res) => { - if (!res.ok) throw new Error("Audio HTTP error"); - return res.arrayBuffer(); - }) - .then((bytes) => { - if (audioCtx) { - return audioCtx.decodeAudioData(bytes); - } - }) - .then((buffer) => { - if (buffer) soundBuffer = buffer; - }) - .catch(() => { }); -} + // Single HTML5 Audio instance fallback + const fallbackAudio = new Audio(); + fallbackAudio.preload = "auto"; -// MUST be invoked directly from a user gesture listener (e.g. click/keydown) -function unlockAudio() { - if (isUnlocked) return; + // Fetch audio file ONCE and keep in memory buffer + function preloadAudio() { + fallbackAudio.src = SOUND_URL; - // Instantiate AudioContext on user gesture - if (!audioCtx && AudioContextClass) { - audioCtx = new AudioContextClass(); - loadSoundBuffer(); - } - - if (audioCtx && audioCtx.state === "suspended") { - audioCtx.resume(); - } - - // Play a silent 1ms audio snippet on the HTML5 element to unlock media playback - fallbackAudio.volume = 0; - const promise = fallbackAudio.play(); - if (promise !== undefined) { - promise - .then(() => { - fallbackAudio.pause(); - fallbackAudio.currentTime = 0; - fallbackAudio.volume = 1; - isUnlocked = true; - removeUnlockListeners(); + fetch(SOUND_URL, { cache: "force-cache" }) + .then((res) => { + if (!res.ok) throw new Error("Network response error"); + return res.arrayBuffer(); }) - .catch(() => { - // User gesture hasn't registered yet + .then((bytes) => { + if (audioCtx) { + return audioCtx.decodeAudioData(bytes); + } + }) + .then((buffer) => { + if (buffer) soundBuffer = buffer; + }) + .catch((err) => { + // Fallback gracefully if arrayBuffer fails }); } -} -function removeUnlockListeners() { - ["click", "pointerdown", "keydown", "touchstart"].forEach((event) => { - document.removeEventListener(event, unlockAudio, true); - }); -} + // Preload on script load + preloadAudio(); -// Attach global passive listeners for user gestures -["click", "pointerdown", "keydown", "touchstart"].forEach((event) => { - document.addEventListener(event, unlockAudio, { capture: true, passive: true }); -}); + // Unlock AudioContext on User Gesture + function unlockAudio() { + if (isUnlocked) return; -// Safe playback function triggered by WebSocket events -function playNotifySound() { - // Check if audio has been unlocked by user gesture - if (!isUnlocked) { - console.warn("[MM Chat Sound]: Notification blocked — user has not interacted with the page yet."); - 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(() => { }); + } } - // 1. Try Web Audio API (Best latency) - if (audioCtx && audioCtx.state === "running" && soundBuffer) { - try { - const source = audioCtx.createBufferSource(); - source.buffer = soundBuffer; - source.connect(audioCtx.destination); - source.start(0); + 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. HTML5 Audio Fallback - try { - fallbackAudio.currentTime = 0; - fallbackAudio.volume = 1; - fallbackAudio.play().catch((err) => { - console.warn("[MM Chat Sound]: Playback blocked by browser policy:", err.message); - }); - } catch (e) { } -} \ No newline at end of file + + // ========================================================================= + // 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(); + }); + +})(); \ No newline at end of file