108 lines
2.6 KiB
JavaScript
108 lines
2.6 KiB
JavaScript
import Echo from "laravel-echo";
|
|
import Pusher from "pusher-js";
|
|
|
|
let echoClient = null;
|
|
let echoToken = null;
|
|
|
|
function getToken() {
|
|
const authTokenCookie = document.cookie
|
|
.split("; ")
|
|
.find((row) => row.startsWith("authToken="));
|
|
const guestTokenCookie = document.cookie
|
|
.split("; ")
|
|
.find((row) => row.startsWith("guestToken="));
|
|
|
|
if (authTokenCookie) return authTokenCookie.split("=")[1];
|
|
if (localStorage.getItem("authToken")) return localStorage.getItem("authToken");
|
|
if (guestTokenCookie) return guestTokenCookie.split("=")[1];
|
|
if (localStorage.getItem("guestToken")) return localStorage.getItem("guestToken");
|
|
|
|
return null;
|
|
}
|
|
|
|
function apiUrl(path) {
|
|
const base = import.meta.env.VITE_API_URL || "https://mm.com.tm/api/v1/";
|
|
const normalized = base.endsWith("/") ? base : `${base}/`;
|
|
|
|
return `${normalized}${String(path).replace(/^\//, "")}`;
|
|
}
|
|
|
|
function isLoopbackHost(host) {
|
|
return !host || host === "127.0.0.1" || host === "localhost" || host === "0.0.0.0";
|
|
}
|
|
|
|
function reverbEndpoint() {
|
|
const envHost = import.meta.env.VITE_REVERB_HOST;
|
|
const envScheme = import.meta.env.VITE_REVERB_SCHEME;
|
|
const envPort = import.meta.env.VITE_REVERB_PORT;
|
|
|
|
if (import.meta.env.PROD && isLoopbackHost(envHost)) {
|
|
const https = window.location.protocol === "https:";
|
|
return {
|
|
host: window.location.hostname,
|
|
scheme: https ? "https" : "http",
|
|
port: https ? 443 : 80,
|
|
};
|
|
}
|
|
|
|
const scheme = envScheme || "http";
|
|
return {
|
|
host: envHost || "127.0.0.1",
|
|
scheme,
|
|
port: Number(envPort || (scheme === "https" ? 443 : 8080)),
|
|
};
|
|
}
|
|
|
|
export function getChatEcho() {
|
|
const key = import.meta.env.VITE_REVERB_APP_KEY;
|
|
const token = getToken();
|
|
|
|
if (!key || !token) {
|
|
return null;
|
|
}
|
|
|
|
if (echoClient && echoToken !== token) {
|
|
echoClient.disconnect();
|
|
echoClient = null;
|
|
}
|
|
|
|
if (echoClient) {
|
|
return echoClient;
|
|
}
|
|
|
|
window.Pusher = Pusher;
|
|
|
|
const { host, scheme, port } = reverbEndpoint();
|
|
|
|
echoToken = token;
|
|
echoClient = new Echo({
|
|
broadcaster: "reverb",
|
|
key,
|
|
wsHost: host,
|
|
wsPort: port,
|
|
wssPort: port,
|
|
forceTLS: scheme === "https",
|
|
enabledTransports: ["ws", "wss"],
|
|
disableStats: true,
|
|
Pusher,
|
|
authEndpoint: apiUrl("broadcasting/auth"),
|
|
auth: {
|
|
headers: {
|
|
Authorization: `Bearer ${token}`,
|
|
Accept: "application/json",
|
|
"Api-Token": import.meta.env.VITE_API_TOKEN || "hello-mf-s",
|
|
},
|
|
},
|
|
});
|
|
|
|
return echoClient;
|
|
}
|
|
|
|
export function leaveChatChannel(conversationId) {
|
|
if (!echoClient || !conversationId) {
|
|
return;
|
|
}
|
|
|
|
echoClient.leave(`chat.${conversationId}`);
|
|
}
|