Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Barnabasmolnar/follow mode #361

Merged
merged 10 commits into from
Dec 15, 2023
53 changes: 51 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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");
Expand Down Expand Up @@ -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");
}
}
});

Expand Down
Loading