diff --git a/public/assets/panel/js/chat.js b/public/assets/panel/js/chat.js index f45bcd0..e116bcb 100644 --- a/public/assets/panel/js/chat.js +++ b/public/assets/panel/js/chat.js @@ -21,21 +21,71 @@ const SOUND_URL = "/assets/panel/audio/sound.mp3"; const AudioContextClass = window.AudioContext || window.webkitAudioContext; - const audioCtx = AudioContextClass ? new AudioContextClass() : null; - const fallbackAudio = document.getElementById("mm-chat-sound"); - if (fallbackAudio) { - fallbackAudio.src = SOUND_URL; - fallbackAudio.preload = "auto"; - fallbackAudio.playsInline = true; - fallbackAudio.controls = false; - fallbackAudio.volume = 1; - fallbackAudio.style.cssText = "position:absolute;left:0;bottom:0;width:1px;height:1px;opacity:0.01"; - } + let audioCtx = null; + let soundBuffer = null; + let isAudioUnlocked = false; + + const audioFallback = new Audio(SOUND_URL); + audioFallback.preload = "auto"; const soundedIds = new Set(); let inboxReady = false; - let soundBuffer = null; - let soundPending = false; + + // Initialize and unlock audio context on explicit user gesture + function unlockAudio() { + if (isAudioUnlocked) return; + + if (!audioCtx && AudioContextClass) { + audioCtx = new AudioContextClass(); + } + + if (audioCtx && audioCtx.state === "suspended") { + audioCtx.resume(); + } + + // Warm up HTML Audio element for browsers blocking Web Audio + audioFallback.play().then(() => { + audioFallback.pause(); + audioFallback.currentTime = 0; + isAudioUnlocked = true; + }).catch(() => { + // User interaction required + }); + + if (audioCtx && !soundBuffer) { + fetch(SOUND_URL, { credentials: "same-origin", cache: "force-cache" }) + .then((res) => res.arrayBuffer()) + .then((bytes) => audioCtx.decodeAudioData(bytes)) + .then((buf) => { soundBuffer = buf; }) + .catch(() => {}); + } + } + + function playNotifySound() { + // Attempt 1: Web Audio API + if (audioCtx && audioCtx.state === "running" && soundBuffer) { + try { + const source = audioCtx.createBufferSource(); + source.buffer = soundBuffer; + source.connect(audioCtx.destination); + source.start(0); + return; + } catch (e) {} + } + + // Attempt 2: HTML5 Audio Fallback + audioFallback.currentTime = 0; + audioFallback.play().catch(() => {}); + } + + function playIncomingSound(message) { + const key = messageKey(message); + if (!key || soundedIds.has(key)) { + return; + } + soundedIds.add(key); + playNotifySound(); + } function headers(json) { const next = { @@ -43,38 +93,26 @@ "X-CSRF-TOKEN": config.csrf, "X-Requested-With": "XMLHttpRequest", }; - - if (json) { - next["Content-Type"] = "application/json"; - } - + if (json) next["Content-Type"] = "application/json"; return next; } async function request(url, options) { const response = await fetch(url, options); - if (!response.ok) { - throw new Error("Chat request failed"); - } + if (!response.ok) throw new Error("Chat request failed"); return response.json(); } function formatTime(value) { - if (!value) { - return ""; - } + if (!value) return ""; const date = new Date(value); - if (Number.isNaN(date.getTime())) { - return ""; - } + if (Number.isNaN(date.getTime())) return ""; const pad = (n) => String(n).padStart(2, "0"); - return `${pad(date.getHours())}:${pad(date.getMinutes())}, ${pad(date.getDate())}.${pad(date.getMonth() + 1)}.${date.getFullYear()}`; + return `${pad(date.getHours())}:${pad(date.getMinutes())}, ${pad(date.getDate())}.${pad(date.getMonth() + 1)}.${pad(date.getFullYear())}`; } function preview(body) { - if (!body) { - return ""; - } + if (!body) return ""; return body.length > 80 ? `${body.slice(0, 80)}…` : body; } @@ -124,9 +162,7 @@ if (phone) { button.querySelector(".mm-chat__item-phone").textContent = String(phone); } - button.querySelector(".mm-chat__item-preview").textContent = last - ? preview(last.body) - : ""; + button.querySelector(".mm-chat__item-preview").textContent = last ? preview(last.body) : ""; const unread = button.querySelector(".mm-chat__item-unread"); if (unread) { unread.textContent = String(conversation.unread_count); @@ -149,106 +185,13 @@ } function normalizeIncoming(payload) { - if (!payload || typeof payload !== "object") { - return payload; - } - if (payload.conversation_id && payload.id) { - return payload; - } - if (payload.message && payload.message.id) { - return payload.message; - } - if (payload.data && payload.data.id) { - return payload.data; - } + if (!payload || typeof payload !== "object") return payload; + if (payload.conversation_id && payload.id) return payload; + if (payload.message && payload.message.id) return payload.message; + if (payload.data && payload.data.id) return payload.data; return payload; } - function loadSoundBuffer() { - if (!audioCtx) { - return Promise.resolve(); - } - return fetch(SOUND_URL, { credentials: "same-origin", cache: "force-cache" }) - .then((response) => { - if (!response.ok) { - throw new Error("Sound file missing"); - } - return response.arrayBuffer(); - }) - .then((bytes) => audioCtx.decodeAudioData(bytes.slice(0))) - .then((buffer) => { - soundBuffer = buffer; - }) - .catch(() => {}); - } - - loadSoundBuffer(); - - function unlockSound() { - if (audioCtx && audioCtx.state === "suspended") { - audioCtx.resume(); - } - if (fallbackAudio && fallbackAudio.paused) { - const play = fallbackAudio.play(); - if (play && typeof play.then === "function") { - play - .then(() => { - fallbackAudio.pause(); - fallbackAudio.currentTime = 0; - }) - .catch(() => {}); - } - } - if (soundPending) { - soundPending = false; - playNotifySound(); - } - } - - function playNotifySound() { - if (audioCtx && audioCtx.state !== "running") { - soundPending = true; - audioCtx.resume().then(() => { - if (audioCtx.state === "running") { - soundPending = false; - playNotifySound(); - } - }).catch(() => {}); - return; - } - - if (audioCtx && soundBuffer) { - const source = audioCtx.createBufferSource(); - source.buffer = soundBuffer; - source.connect(audioCtx.destination); - source.start(0); - return; - } - - if (fallbackAudio) { - try { - fallbackAudio.currentTime = 0; - } catch (error) { - // Ignore until metadata is ready. - } - fallbackAudio.play().catch(() => { - soundPending = true; - }); - return; - } - - soundPending = true; - } - - function playIncomingSound(message) { - const key = messageKey(message); - if (!key || soundedIds.has(key)) { - return; - } - soundedIds.add(key); - playNotifySound(); - } - function renderMessages() { const conversation = state.conversations.find((item) => item.id === state.activeId); messagesEl.innerHTML = ""; @@ -289,10 +232,9 @@ const prev = previous.find((item) => item.id === conversation.id); const last = conversation.last_message; const lastChanged = Boolean(last) && messageKey(last) !== messageKey(prev && prev.last_message); - const unreadUp = - (conversation.unread_count || 0) > ((prev && prev.unread_count) || 0); + const unreadUp = (conversation.unread_count || 0) > ((prev && prev.unread_count) || 0); - if (lastChanged) { + if (lastChanged && !isOutgoing(last, conversation)) { playIncomingSound(last); } else if (unreadUp) { playNotifySound(); @@ -312,9 +254,7 @@ } async function loadMessages(conversationId, reset) { - if (state.loadingMessages) { - return; - } + if (state.loadingMessages) return; state.loadingMessages = true; const url = reset @@ -337,13 +277,6 @@ state.messages = items.concat(state.messages); } - items.forEach((message) => { - const key = messageKey(message); - if (key) { - soundedIds.add(key); - } - }); - renderMessages(); } finally { state.loadingMessages = false; @@ -351,14 +284,10 @@ } async function markRead(conversationId, force) { - if (!conversationId || conversationId !== state.activeId) { - return; - } + if (!conversationId || conversationId !== state.activeId) return; const conversation = state.conversations.find((item) => item.id === conversationId); - if (!conversation || (!force && !conversation.unread_count)) { - return; - } + if (!conversation || (!force && !conversation.unread_count)) return; await request(`${config.messagesUrl}/${conversationId}/read`, { method: "POST", @@ -377,7 +306,7 @@ } async function openConversation(conversationId) { - unlockSound(); + unlockAudio(); state.activeId = conversationId; const conversation = state.conversations.find((item) => item.id === conversationId); const name = (conversation && conversation.user && conversation.user.name) || `#${conversationId}`; @@ -395,11 +324,10 @@ async function sendMessage(event) { event.preventDefault(); + unlockAudio(); const body = (inputEl.value || "").trim(); const conversation = state.conversations.find((item) => item.id === state.activeId); - if (!body || !state.activeId || !conversation || conversation.can_reply === false) { - return; - } + if (!body || !state.activeId || !conversation || conversation.can_reply === false) return; sendEl.disabled = true; try { @@ -429,11 +357,12 @@ function upsertIncoming(payload) { const message = normalizeIncoming(payload); - if (!message || !message.conversation_id) { - return; - } + if (!message || !message.conversation_id) return; - playIncomingSound(message); + const conversation = state.conversations.find((item) => item.id === message.conversation_id); + if (!isOutgoing(message, conversation)) { + playIncomingSound(message); + } if (state.activeId === message.conversation_id) { if (!state.messages.some((item) => String(item.id) === String(message.id))) { @@ -447,9 +376,7 @@ } function subscribeThread(conversationId) { - if (!state.echo) { - return; - } + if (!state.echo) return; state.echo.private(`chat.${conversationId}`).listen(".message.sent", upsertIncoming); } @@ -478,9 +405,7 @@ function bootEcho() { const pusher = config.pusher || {}; const EchoClass = window.Echo; - if (typeof EchoClass !== "function" || !window.Pusher || !pusher.key) { - return; - } + if (typeof EchoClass !== "function" || !window.Pusher || !pusher.key) return; const endpoint = echoEndpoint(pusher); @@ -540,9 +465,7 @@ } async function mergeActiveMessages() { - if (!state.activeId || state.loadingMessages) { - return false; - } + if (!state.activeId || state.loadingMessages) return false; const payload = await request( `${config.messagesUrl}/${state.activeId}/messages?perPage=50`, @@ -556,7 +479,10 @@ if (!known.has(String(message.id))) { state.messages.push(message); added = true; - playIncomingSound(message); + const conversation = state.conversations.find((i) => i.id === state.activeId); + if (!isOutgoing(message, conversation)) { + playIncomingSound(message); + } } }); @@ -587,17 +513,17 @@ } }); - ["pointerdown", "keydown", "touchstart", "click"].forEach((eventName) => { - document.addEventListener(eventName, unlockSound, true); + // Global user interaction handlers to unlock autoplay block + ["click", "keydown", "touchstart"].forEach((eventName) => { + document.addEventListener(eventName, unlockAudio, { once: false, capture: true }); }); loadInbox(); bootEcho(); + setInterval(() => { loadInbox().then(async () => { - if (!state.activeId) { - return; - } + if (!state.activeId) return; const added = await mergeActiveMessages(); const conversation = state.conversations.find((item) => item.id === state.activeId); if (added || (conversation && conversation.unread_count > 0)) { @@ -611,4 +537,4 @@ markRead(state.activeId); } }); -})(); +})(); \ No newline at end of file