From 9e555a8c57262b73c37f3138771b684e8eaecd71 Mon Sep 17 00:00:00 2001 From: Mekan1206 Date: Sun, 16 Aug 2026 17:38:38 +0500 Subject: [PATCH] Add socket connection management to ChatWidget and enhance channel authorization in echo.js. Implemented socket status tracking and improved error handling for channel subscriptions, ensuring better reliability in chat interactions. --- src/components/ChatWidget/index.jsx | 39 ++++++++++++++++------- src/utils/echo.js | 48 ++++++++++++++++++++++++----- 2 files changed, 69 insertions(+), 18 deletions(-) diff --git a/src/components/ChatWidget/index.jsx b/src/components/ChatWidget/index.jsx index d805bed..c77af59 100644 --- a/src/components/ChatWidget/index.jsx +++ b/src/components/ChatWidget/index.jsx @@ -45,6 +45,7 @@ function ChatWidget() { const [admin, setAdmin] = useState({ available: false, name: null }); const [targetsNext, setTargetsNext] = useState(null); const [loadingTargets, setLoadingTargets] = useState(false); + const [socketLive, setSocketLive] = useState(false); const listRef = useRef(null); const subscribedId = useRef(null); @@ -233,24 +234,40 @@ function ChatWidget() { } subscribedId.current = conversationId; - echo.private(`chat.${conversationId}`).listen(".message.sent", (payload) => { - if (conversationRef.current?.id !== conversationId || screenRef.current !== "thread") { - return; - } - appendMessage(payload); - if (openRef.current) { - markRead(conversationId); - } - }); + setSocketLive(false); + + const channel = echo.private(`chat.${conversationId}`); + channel + .subscribed(() => setSocketLive(true)) + .error(() => setSocketLive(false)) + .listen(".message.sent", (payload) => { + if (conversationRef.current?.id !== conversationId || screenRef.current !== "thread") { + return; + } + appendMessage(payload); + if (openRef.current) { + markRead(conversationId); + } + }); + + const connection = echo.connector?.pusher?.connection; + const markDead = () => setSocketLive(false); + connection?.bind("disconnected", markDead); + connection?.bind("unavailable", markDead); + connection?.bind("failed", markDead); return () => { + connection?.unbind("disconnected", markDead); + connection?.unbind("unavailable", markDead); + connection?.unbind("failed", markDead); leaveChatChannel(conversationId); subscribedId.current = null; + setSocketLive(false); }; }, [appendMessage, conversation?.id, hidden, markRead, screen]); useEffect(() => { - if (!open || screen !== "thread" || !conversation?.id) { + if (!open || screen !== "thread" || !conversation?.id || socketLive) { return undefined; } @@ -293,7 +310,7 @@ function ChatWidget() { clearInterval(timer); document.removeEventListener("visibilitychange", onVisible); }; - }, [conversation?.id, fetchMessages, open, screen]); + }, [conversation?.id, fetchMessages, open, screen, socketLive]); const handleScroll = async () => { if (!listRef.current || !nextPage || !conversation?.id || loadingThread) { diff --git a/src/utils/echo.js b/src/utils/echo.js index 1677605..b14212e 100644 --- a/src/utils/echo.js +++ b/src/utils/echo.js @@ -53,6 +53,43 @@ function reverbEndpoint() { }; } +function authorizeChannel(channel, socketId, callback) { + const token = getToken(); + if (!token) { + callback(true, { message: "Missing auth token" }); + return; + } + + fetch(apiUrl("broadcasting/auth"), { + method: "POST", + credentials: "omit", + headers: { + Authorization: `Bearer ${token}`, + Accept: "application/json", + "Content-Type": "application/json", + "Api-Token": import.meta.env.VITE_API_TOKEN || "hello-mf-s", + }, + body: JSON.stringify({ + socket_id: socketId, + channel_name: channel.name, + }), + }) + .then(async (response) => { + let data = {}; + try { + data = await response.json(); + } catch { + data = {}; + } + if (!response.ok) { + callback(true, data); + return; + } + callback(false, data); + }) + .catch((error) => callback(true, error)); +} + export function getChatEcho() { const key = import.meta.env.VITE_REVERB_APP_KEY; const token = getToken(); @@ -84,15 +121,12 @@ export function getChatEcho() { forceTLS: scheme === "https", enabledTransports: ["ws", "wss"], disableStats: true, + cluster: "mt1", Pusher, authEndpoint: apiUrl("broadcasting/auth"), - auth: { - headers: { - Authorization: `Bearer ${token}`, - Accept: "application/json", - "Api-Token": import.meta.env.VITE_API_TOKEN || "hello-mf-s", - }, - }, + authorizer: (channel) => ({ + authorize: (socketId, callback) => authorizeChannel(channel, socketId, callback), + }), }); return echoClient;