This commit is contained in:
Mekan1206 committed 2026-08-16 20:18:06 +05:00
1 parent c126032cc9
commit 64407d0241
1 file changed
+203 -87
+203 -87
View File
@@ -1,104 +1,220 @@
// ------------------------------------------------------------- (function () {
// AUDIO MANAGER (Bypasses Browser Autoplay Restrictions) "use strict";
// -------------------------------------------------------------
const SOUND_URL = "/assets/panel/audio/sound.mp3";
const AudioContextClass = window.AudioContext || window.webkitAudioContext;
let audioCtx = null; // =========================================================================
let soundBuffer = null; // 1. AUDIO MANAGER (Cached, Single-Fetch, Autoplay-Safe)
let isUnlocked = false; // =========================================================================
const SOUND_URL = "/assets/panel/audio/sound.mp3";
const AudioContextClass = window.AudioContext || window.webkitAudioContext;
// Single HTML5 Audio instance fallback let audioCtx = null;
const fallbackAudio = document.getElementById("mm-chat-sound") || new Audio(SOUND_URL); let soundBuffer = null;
fallbackAudio.src = SOUND_URL; let isUnlocked = false;
fallbackAudio.preload = "auto";
// Pre-load sound buffer for Web Audio API // Single HTML5 Audio instance fallback
function loadSoundBuffer() { const fallbackAudio = new Audio();
fetch(SOUND_URL, { credentials: "same-origin", cache: "force-cache" }) fallbackAudio.preload = "auto";
.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(() => { });
}
// MUST be invoked directly from a user gesture listener (e.g. click/keydown) // Fetch audio file ONCE and keep in memory buffer
function unlockAudio() { function preloadAudio() {
if (isUnlocked) return; fallbackAudio.src = SOUND_URL;
// Instantiate AudioContext on user gesture fetch(SOUND_URL, { cache: "force-cache" })
if (!audioCtx && AudioContextClass) { .then((res) => {
audioCtx = new AudioContextClass(); if (!res.ok) throw new Error("Network response error");
loadSoundBuffer(); return res.arrayBuffer();
}
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();
}) })
.catch(() => { .then((bytes) => {
// User gesture hasn't registered yet if (audioCtx) {
return audioCtx.decodeAudioData(bytes);
}
})
.then((buffer) => {
if (buffer) soundBuffer = buffer;
})
.catch((err) => {
// Fallback gracefully if arrayBuffer fails
}); });
} }
}
function removeUnlockListeners() { // Preload on script load
["click", "pointerdown", "keydown", "touchstart"].forEach((event) => { preloadAudio();
document.removeEventListener(event, unlockAudio, true);
});
}
// Attach global passive listeners for user gestures // Unlock AudioContext on User Gesture
["click", "pointerdown", "keydown", "touchstart"].forEach((event) => { function unlockAudio() {
document.addEventListener(event, unlockAudio, { capture: true, passive: true }); if (isUnlocked) return;
});
// Safe playback function triggered by WebSocket events if (!audioCtx && AudioContextClass) {
function playNotifySound() { audioCtx = new AudioContextClass();
// Check if audio has been unlocked by user gesture preloadAudio();
if (!isUnlocked) { }
console.warn("[MM Chat Sound]: Notification blocked — user has not interacted with the page yet.");
return; 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) function removeUnlockListeners() {
if (audioCtx && audioCtx.state === "running" && soundBuffer) { ["click", "pointerdown", "keydown", "touchstart"].forEach((event) => {
try { document.removeEventListener(event, unlockAudio, true);
const source = audioCtx.createBufferSource(); });
source.buffer = soundBuffer; }
source.connect(audioCtx.destination);
source.start(0); // 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; 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) { } } catch (e) { }
} }
// 2. HTML5 Audio Fallback
try { // =========================================================================
fallbackAudio.currentTime = 0; // 2. MESSAGE DEDUPLICATION TRACKER
fallbackAudio.volume = 1; // =========================================================================
fallbackAudio.play().catch((err) => { const processedMessageIds = new Set();
console.warn("[MM Chat Sound]: Playback blocked by browser policy:", err.message);
}); function isDuplicateMessage(messageData) {
} catch (e) { } // 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();
});
})();