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.

This commit is contained in:
Mekan1206
2026-08-16 17:38:38 +05:00
parent d2196398cc
commit 9e555a8c57
2 changed files with 69 additions and 18 deletions

View File

@@ -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) {

View File

@@ -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;