83 lines
1.9 KiB
JavaScript
83 lines
1.9 KiB
JavaScript
import { io } from "socket.io-client";
|
|
import { v4 as uuidv4 } from "uuid";
|
|
|
|
// FIXME: This file should handle the sockets and the subscriptions
|
|
// Exports must include
|
|
// - initSocket (initialize the connection to the socket server)
|
|
// - socket (variable resulting of initSocket function)
|
|
|
|
// Functions may include:
|
|
// - subscribe (subscribe to a room's stream or chat)
|
|
// - unsubscribe (unsubscribe from a room's stream or chat)
|
|
// - sendMessage (send a message to a room's chat)
|
|
|
|
let socket = null;
|
|
const uuid = uuidv4();
|
|
|
|
/**
|
|
* Initializes the socket when authenticated
|
|
* returns {Promise<void>}
|
|
*/
|
|
async function initSocket() {
|
|
if (socket !== null) {
|
|
console.warn("Blocked attempt to re-init socket connection");
|
|
return;
|
|
}
|
|
|
|
console.debug("Initializing socket connection");
|
|
const token = localStorage.getItem("token");
|
|
|
|
const host = import.meta.env.VITE_HOST;
|
|
const port = import.meta.env.VITE_PORT;
|
|
const wsUri = "ws://" + host + (port ? ":" + port : "");
|
|
|
|
socket = io(wsUri, {
|
|
reconnectionDelayMax: 10000,
|
|
extraHeaders: {
|
|
Authorization: "Bearer " + token,
|
|
},
|
|
});
|
|
|
|
console.debug("Socket active: " + socket.active);
|
|
return;
|
|
}
|
|
|
|
async function subscribe(room, channel) {
|
|
if (!room) {
|
|
room = "epi-place";
|
|
}
|
|
|
|
if (!channel) {
|
|
channel = "message";
|
|
}
|
|
|
|
let path = "rooms.canvas.getStream";
|
|
|
|
if (channel.includes("chat") || channel.includes("message")) {
|
|
path = "rooms.getChat";
|
|
}
|
|
|
|
const msg = {
|
|
id: uuid,
|
|
method: "subscription",
|
|
params: {
|
|
path: path,
|
|
input: {
|
|
json: {
|
|
roomSlug: room,
|
|
},
|
|
},
|
|
},
|
|
};
|
|
|
|
socket.send(msg);
|
|
}
|
|
|
|
// async function unsubscribe() {
|
|
|
|
// }
|
|
// async function sendMessage() {
|
|
|
|
// }
|
|
|
|
export { socket, initSocket, subscribe };
|