This commit is contained in:
Mekan1206
2026-08-16 20:20:30 +05:00
parent 64407d0241
commit da611b81b6

View File

@@ -1,27 +1,45 @@
(function () {
"use strict";
const config = window.MM_CHAT || {};
const listEl = document.getElementById("mm-chat-list");
const emptyInboxEl = document.getElementById("mm-chat-empty-inbox");
const messagesEl = document.getElementById("mm-chat-messages");
const headEl = document.getElementById("mm-chat-thread-head");
const formEl = document.getElementById("mm-chat-form");
const viewOnlyEl = document.getElementById("mm-chat-view-only");
const inputEl = document.getElementById("mm-chat-input");
const sendEl = document.getElementById("mm-chat-send");
const unreadEl = document.getElementById("mm-chat-unread");
const state = {
conversations: [],
activeId: null,
messages: [],
nextPageUrl: null,
loadingMessages: false,
echo: null,
};
// =========================================================================
// 1. AUDIO MANAGER (Cached, Single-Fetch, Autoplay-Safe)
// 1. AUDIO MANAGER (Cached Audio Buffer, Zero Network Spam, 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;
let isAudioUnlocked = false;
// Single HTML5 Audio instance fallback
const fallbackAudio = new Audio();
const fallbackAudio = document.getElementById("mm-chat-sound") || new Audio(SOUND_URL);
fallbackAudio.src = SOUND_URL;
fallbackAudio.preload = "auto";
// Fetch audio file ONCE and keep in memory buffer
function preloadAudio() {
fallbackAudio.src = SOUND_URL;
const soundedIds = new Set();
let inboxReady = false;
// Pre-load audio once into memory buffer
function preloadSoundBuffer() {
fetch(SOUND_URL, { cache: "force-cache" })
.then((res) => {
if (!res.ok) throw new Error("Network response error");
if (!res.ok) throw new Error("Audio download error");
return res.arrayBuffer();
})
.then((bytes) => {
@@ -32,37 +50,33 @@
.then((buffer) => {
if (buffer) soundBuffer = buffer;
})
.catch((err) => {
// Fallback gracefully if arrayBuffer fails
});
.catch(() => { });
}
// Preload on script load
preloadAudio();
preloadSoundBuffer();
// Unlock AudioContext on User Gesture
function unlockAudio() {
if (isUnlocked) return;
if (isAudioUnlocked) return;
if (!audioCtx && AudioContextClass) {
audioCtx = new AudioContextClass();
preloadAudio();
preloadSoundBuffer();
}
if (audioCtx && audioCtx.state === "suspended") {
audioCtx.resume();
}
// Play silent snippet on HTML5 Audio to unlock media pipeline
// Warm up HTML Audio element
fallbackAudio.volume = 0;
const promise = fallbackAudio.play();
if (promise !== undefined) {
promise
const playPromise = fallbackAudio.play();
if (playPromise !== undefined) {
playPromise
.then(() => {
fallbackAudio.pause();
fallbackAudio.currentTime = 0;
fallbackAudio.volume = 1;
isUnlocked = true;
isAudioUnlocked = true;
removeUnlockListeners();
})
.catch(() => { });
@@ -70,24 +84,15 @@
}
function removeUnlockListeners() {
["click", "pointerdown", "keydown", "touchstart"].forEach((event) => {
document.removeEventListener(event, unlockAudio, true);
["pointerdown", "keydown", "touchstart", "click"].forEach((eventName) => {
document.removeEventListener(eventName, unlockAudio, { capture: 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;
}
if (!isAudioUnlocked) return;
// 1. Play using Web Audio API buffer
// 1. Play from cached RAM buffer (No network request made)
if (audioCtx && audioCtx.state === "running" && soundBuffer) {
try {
const source = audioCtx.createBufferSource();
@@ -98,7 +103,7 @@
} catch (e) { }
}
// 2. Fallback to cached HTML5 Audio instance
// 2. HTML5 Audio Fallback
try {
fallbackAudio.currentTime = 0;
fallbackAudio.volume = 1;
@@ -106,115 +111,474 @@
} 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;
function playIncomingSound(message) {
const key = messageKey(message);
if (!key || soundedIds.has(key)) {
return;
}
// 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;
soundedIds.add(key);
playNotifySound();
}
function headers(json) {
const next = {
Accept: "application/json",
"X-CSRF-TOKEN": config.csrf,
"X-Requested-With": "XMLHttpRequest",
};
if (json) next["Content-Type"] = "application/json";
return next;
}
// =========================================================================
// 3. WEBSOCKET & CHAT EVENT HANDLERS
// =========================================================================
async function request(url, options) {
const response = await fetch(url, options);
if (!response.ok) throw new Error("Chat request failed");
return response.json();
}
// 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)) {
function formatTime(value) {
if (!value) return "";
const date = new Date(value);
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)}.${pad(date.getFullYear())}`;
}
function preview(body) {
if (!body) return "";
return body.length > 80 ? `${body.slice(0, 80)}…` : body;
}
function updateUnreadBadge() {
const total = state.conversations.reduce(
(sum, conversation) => sum + (conversation.unread_count || 0),
0
);
unreadEl.textContent = String(total);
unreadEl.hidden = total < 1;
}
function renderInbox() {
listEl.innerHTML = "";
emptyInboxEl.hidden = state.conversations.length > 0;
state.conversations.forEach((conversation) => {
const button = document.createElement("button");
button.type = "button";
button.className = "mm-chat__item";
if (conversation.id === state.activeId) {
button.classList.add("is-active");
}
const name = (conversation.user && conversation.user.name) || `#${conversation.id}`;
const phone = conversation.user && conversation.user.phone_number;
const last = conversation.last_message;
const time = last ? formatTime(last.created_at) : "";
const subtitle = conversation.channel && conversation.channel.name
? conversation.channel.name
: (config.strings && config.strings.support) || "Support";
button.innerHTML = `
<div class="mm-chat__item-row">
<span class="mm-chat__item-name"></span>
<span class="mm-chat__item-time"></span>
</div>
<div class="mm-chat__item-sub"></div>
${phone ? '<div class="mm-chat__item-phone"></div>' : ""}
<div class="mm-chat__item-preview"></div>
${conversation.unread_count ? '<span class="mm-chat__item-unread"></span>' : ""}
`;
button.querySelector(".mm-chat__item-name").textContent = name;
button.querySelector(".mm-chat__item-time").textContent = time;
button.querySelector(".mm-chat__item-sub").textContent = subtitle;
if (phone) {
button.querySelector(".mm-chat__item-phone").textContent = String(phone);
}
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);
}
button.addEventListener("click", () => openConversation(conversation.id));
listEl.appendChild(button);
});
updateUnreadBadge();
}
function isOutgoing(message, conversation) {
if (!message) return false;
if (message.tempId || message.is_outgoing || message.user?.id === "operator") return true;
const otherId = conversation && conversation.user && conversation.user.id;
return !otherId || message.user?.id !== otherId;
}
function messageKey(message) {
return message && message.id != null ? String(message.id) : "";
}
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;
return payload;
}
function renderMessages() {
const conversation = state.conversations.find((item) => item.id === state.activeId);
messagesEl.innerHTML = "";
if (!state.messages.length) {
const empty = document.createElement("p");
empty.className = "mm-chat__empty";
empty.textContent = config.strings.noMessages;
messagesEl.appendChild(empty);
return;
}
// Append to Chat UI
renderMessageToDOM(data);
state.messages.forEach((message) => {
const bubble = document.createElement("div");
bubble.className = `mm-chat__bubble ${isOutgoing(message, conversation) ? "mm-chat__bubble--out" : "mm-chat__bubble--in"
}`;
const body = document.createElement("div");
body.textContent = message.body;
const meta = document.createElement("span");
meta.className = "mm-chat__meta";
meta.textContent = formatTime(message.created_at);
bubble.appendChild(body);
bubble.appendChild(meta);
messagesEl.appendChild(bubble);
});
// Play notification sound ONLY for messages from client (not admin's own echo)
if (data.sender !== "admin") {
playNotifySound();
messagesEl.scrollTop = messagesEl.scrollHeight;
}
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 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);
if (lastChanged && !isOutgoing(last, conversation)) {
playIncomingSound(last);
} else if (unreadUp) {
playNotifySound();
}
});
} else {
inboxReady = true;
state.conversations.forEach((conversation) => {
const key = messageKey(conversation.last_message);
if (key) {
soundedIds.add(key);
}
});
}
renderInbox();
}
async function loadMessages(conversationId, reset) {
if (state.loadingMessages) return;
state.loadingMessages = true;
const url = reset
? `${config.messagesUrl}/${conversationId}/messages?perPage=50`
: state.nextPageUrl;
if (!url) {
state.loadingMessages = false;
return;
}
try {
const payload = await request(url, { headers: headers() });
const items = (payload.data || []).slice().reverse();
state.nextPageUrl = payload.pagination && payload.pagination.next_page_url;
if (reset) {
state.messages = items;
} else {
state.messages = items.concat(state.messages);
}
renderMessages();
} finally {
state.loadingMessages = false;
}
}
// Call this function when Admin clicks "Send" button or hits Enter
function sendAdminMessage(text) {
if (!text || !text.trim()) return;
async function markRead(conversationId, force) {
if (!conversationId || conversationId !== state.activeId) return;
const tempId = "msg_" + Date.now() + "_" + Math.random().toString(36).substr(2, 9);
const messagePayload = {
const conversation = state.conversations.find((item) => item.id === conversationId);
if (!conversation || (!force && !conversation.unread_count)) return;
await request(`${config.messagesUrl}/${conversationId}/read`, {
method: "POST",
headers: headers(true),
});
conversation.unread_count = 0;
renderInbox();
}
function setComposer(conversation) {
const canReply = Boolean(conversation && conversation.can_reply);
formEl.hidden = !canReply;
if (viewOnlyEl) {
viewOnlyEl.hidden = canReply || !conversation;
}
}
async function openConversation(conversationId) {
unlockAudio();
state.activeId = conversationId;
const conversation = state.conversations.find((item) => item.id === conversationId);
const name = (conversation && conversation.user && conversation.user.name) || `#${conversationId}`;
const phone = conversation && conversation.user && conversation.user.phone_number;
const subtitle = conversation && conversation.channel && conversation.channel.name
? conversation.channel.name
: (config.strings && config.strings.support) || "Support";
headEl.textContent = phone ? `${name} · ${phone} · ${subtitle}` : `${name} · ${subtitle}`;
setComposer(conversation);
renderInbox();
await loadMessages(conversationId, true);
await markRead(conversationId, true);
subscribeThread(conversationId);
}
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;
sendEl.disabled = true;
inputEl.value = "";
// Render optimistic message locally
const tempId = "temp-" + Date.now();
const optimisticMsg = {
id: tempId,
tempId: tempId,
sender: "admin",
text: text,
timestamp: new Date().toISOString()
conversation_id: state.activeId,
body: body,
created_at: new Date().toISOString(),
user: { id: "operator" }
};
// Render immediately in DOM for responsiveness
renderMessageToDOM(messagePayload);
processedMessageIds.add(tempId);
state.messages.push(optimisticMsg);
renderMessages();
// 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);
try {
const payload = await request(
`${config.messagesUrl}/${state.activeId}/messages`,
{
method: "POST",
headers: headers(true),
body: JSON.stringify({ body }),
}
);
const serverMsg = payload.data;
if (serverMsg && serverMsg.id) {
soundedIds.add(messageKey(serverMsg));
// Replace optimistic message with actual server message
const idx = state.messages.findIndex((m) => m.id === tempId || m.tempId === tempId);
if (idx !== -1) {
state.messages[idx] = serverMsg;
} else {
state.messages.push(serverMsg);
}
renderMessages();
}
await loadInbox();
} catch (err) {
// Remove optimistic message on error
state.messages = state.messages.filter((m) => m.id !== tempId && m.tempId !== tempId);
renderMessages();
} finally {
sendEl.disabled = false;
inputEl.focus();
}
}
// =========================================================================
// 2. INCOMING / WEBSOCKET DEDUPLICATION HANDLER
// =========================================================================
function upsertIncoming(payload) {
const message = normalizeIncoming(payload);
if (!message || !message.conversation_id) return;
const conversation = state.conversations.find((item) => item.id === message.conversation_id);
// Play sound ONLY for client messages
if (!isOutgoing(message, conversation)) {
playIncomingSound(message);
}
if (state.activeId === message.conversation_id) {
// Check if message is already rendered (or is an optimistic local message)
const existingIdx = state.messages.findIndex(
(item) => String(item.id) === String(message.id) || (item.tempId && item.body === message.body)
);
if (existingIdx !== -1) {
// Update existing message instead of duplicating
state.messages[existingIdx] = message;
} else {
// Append new message from client
state.messages.push(message);
}
renderMessages();
markRead(message.conversation_id, true);
}
loadInbox();
}
function subscribeThread(conversationId) {
if (!state.echo) return;
state.echo.private(`chat.${conversationId}`).listen(".message.sent", upsertIncoming);
}
function isLoopbackHost(host) {
return !host || host === "127.0.0.1" || host === "localhost" || host === "0.0.0.0" || host === "::1";
}
function echoEndpoint(pusher) {
const pageHost = window.location.hostname;
if (!isLoopbackHost(pageHost)) {
const https = window.location.protocol === "https:";
return {
host: pageHost,
port: https ? 443 : 80,
forceTLS: https,
};
}
return {
host: pusher.host || "127.0.0.1",
port: pusher.port || 8080,
forceTLS: (pusher.scheme || "http") === "https",
};
}
// Initialize
document.addEventListener("DOMContentLoaded", function () {
initWebSocket();
function bootEcho() {
const pusher = config.pusher || {};
const EchoClass = window.Echo;
if (typeof EchoClass !== "function" || !window.Pusher || !pusher.key) return;
const endpoint = echoEndpoint(pusher);
try {
state.echo = new EchoClass({
broadcaster: "reverb",
key: pusher.key,
wsHost: endpoint.host,
wsPort: endpoint.port,
wssPort: endpoint.port,
forceTLS: endpoint.forceTLS,
enabledTransports: ["ws", "wss"],
disableStats: true,
cluster: "mt1",
csrfToken: config.csrf,
authEndpoint: config.broadcastAuthPath || config.broadcastAuth || "/panel/broadcasting/auth",
auth: {
headers: {
"X-CSRF-TOKEN": config.csrf,
Accept: "application/json",
"X-Requested-With": "XMLHttpRequest",
},
},
});
state.echo.private(config.inboxChannel || "chat.support").listen(".message.sent", upsertIncoming);
} catch (err) {
state.echo = null;
}
}
async function mergeActiveMessages() {
if (!state.activeId || state.loadingMessages) return false;
const payload = await request(
`${config.messagesUrl}/${state.activeId}/messages?perPage=50`,
{ headers: headers() }
);
const items = (payload.data || []).slice().reverse();
const known = new Set(state.messages.map((item) => String(item.id)));
let added = false;
items.forEach((message) => {
if (!known.has(String(message.id))) {
state.messages.push(message);
added = true;
const conversation = state.conversations.find((i) => i.id === state.activeId);
if (!isOutgoing(message, conversation)) {
playIncomingSound(message);
}
}
});
if (added) {
state.messages.sort(
(a, b) => new Date(a.created_at) - new Date(b.created_at)
);
renderMessages();
}
return added;
}
formEl.addEventListener("submit", sendMessage);
inputEl.addEventListener("keydown", (event) => {
if (event.key === "Enter" && !event.shiftKey) {
event.preventDefault();
formEl.requestSubmit();
}
});
messagesEl.addEventListener("scroll", () => {
if (messagesEl.scrollTop < 40 && state.nextPageUrl && state.activeId) {
const previousHeight = messagesEl.scrollHeight;
loadMessages(state.activeId, false).then(() => {
messagesEl.scrollTop = messagesEl.scrollHeight - previousHeight;
});
}
});
// Passive listeners to unlock audio on initial admin click/keypress
["pointerdown", "keydown", "touchstart", "click"].forEach((eventName) => {
document.addEventListener(eventName, unlockAudio, { capture: true, passive: true });
});
loadInbox();
bootEcho();
setInterval(() => {
loadInbox().then(async () => {
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)) {
await markRead(state.activeId, true);
}
});
}, 4000);
document.addEventListener("visibilitychange", () => {
if (document.visibilityState === "visible" && state.activeId) {
markRead(state.activeId);
}
});
})();