diff --git a/public/assets/panel/audio/sound.mp3 b/public/assets/panel/audio/sound.mp3 new file mode 100644 index 0000000..7f8301d Binary files /dev/null and b/public/assets/panel/audio/sound.mp3 differ diff --git a/public/assets/panel/js/chat.js b/public/assets/panel/js/chat.js index 231a8b7..3873012 100644 --- a/public/assets/panel/js/chat.js +++ b/public/assets/panel/js/chat.js @@ -19,6 +19,10 @@ echo: null, }; + const notifySound = new Audio("/assets/panel/audio/sound.mp3"); + const soundedIds = new Set(); + let inboxReady = false; + function headers(json) { const next = { Accept: "application/json", @@ -126,6 +130,24 @@ return !otherId || message.user?.id !== otherId; } + function playIncomingSound(message) { + if (!message || !message.id || soundedIds.has(message.id)) { + return; + } + + const conversation = state.conversations.find( + (item) => item.id === message.conversation_id + ); + + if (conversation && isOutgoing(message, conversation)) { + return; + } + + soundedIds.add(message.id); + notifySound.currentTime = 0; + notifySound.play().catch(() => {}); + } + function renderMessages() { const conversation = state.conversations.find((item) => item.id === state.activeId); messagesEl.innerHTML = ""; @@ -158,7 +180,26 @@ async function loadInbox() { const payload = await request(config.conversationsUrl, { headers: headers() }); + const previous = state.conversations; state.conversations = payload.data || []; + + if (inboxReady) { + state.conversations.forEach((conversation) => { + const last = conversation.last_message; + if (!last) { + return; + } + const prev = previous.find((item) => item.id === conversation.id); + const prevLastId = prev && prev.last_message && prev.last_message.id; + if (prevLastId === last.id) { + return; + } + playIncomingSound(last); + }); + } else { + inboxReady = true; + } + renderInbox(); } @@ -272,6 +313,8 @@ return; } + playIncomingSound(message); + if (state.activeId === message.conversation_id) { if (!state.messages.some((item) => item.id === message.id)) { state.messages.push(message); @@ -393,6 +436,7 @@ if (!known.has(message.id)) { state.messages.push(message); added = true; + playIncomingSound(message); } }); @@ -423,6 +467,14 @@ } }); + document.addEventListener( + "pointerdown", + () => { + notifySound.load(); + }, + { once: true } + ); + loadInbox(); bootEcho(); setInterval(() => {