Barnabasmolnar/follow mode (#361)

Co-authored-by: dwelle <5153846+dwelle@users.noreply.github.com>
This commit is contained in:
Barnabás Molnár 2023-12-15 15:16:35 +01:00 committed by GitHub
parent 49bf529ea1
commit 03ff435860
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -3,6 +3,15 @@ import express from "express";
import http from "http";
import { Server as SocketIO } from "socket.io";
type UserToFollow = {
socketId: string;
username: string;
};
type OnUserFollowedPayload = {
userToFollow: UserToFollow;
action: "FOLLOW" | "UNFOLLOW";
};
const serverDebug = debug("server");
const ioDebug = debug("io");
const socketDebug = debug("socket");
@ -78,19 +87,59 @@ try {
},
);
socket.on("user-follow", async (payload: OnUserFollowedPayload) => {
const roomID = `follow@${payload.userToFollow.socketId}`;
switch (payload.action) {
case "FOLLOW": {
await socket.join(roomID);
const sockets = await io.in(roomID).fetchSockets();
const followedBy = sockets.map((socket) => socket.id);
io.to(payload.userToFollow.socketId).emit(
"user-follow-room-change",
followedBy,
);
break;
}
case "UNFOLLOW": {
await socket.leave(roomID);
const sockets = await io.in(roomID).fetchSockets();
const followedBy = sockets.map((socket) => socket.id);
io.to(payload.userToFollow.socketId).emit(
"user-follow-room-change",
followedBy,
);
break;
}
}
});
socket.on("disconnecting", async () => {
socketDebug(`${socket.id} has disconnected`);
for (const roomID in socket.rooms) {
for (const roomID of Array.from(socket.rooms)) {
const otherClients = (await io.in(roomID).fetchSockets()).filter(
(_socket) => _socket.id !== socket.id,
);
if (otherClients.length > 0) {
const isFollowRoom = roomID.startsWith("follow@");
if (!isFollowRoom && otherClients.length > 0) {
socket.broadcast.to(roomID).emit(
"room-user-change",
otherClients.map((socket) => socket.id),
);
}
if (isFollowRoom && otherClients.length === 0) {
const socketId = roomID.replace("follow@", "");
io.to(socketId).emit("broadcast-unfollow");
}
}
});