Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
  • Loading branch information
Gab committed Feb 14, 2024
2 parents d2296cc + 6c6ab9b commit 3a4d216
Show file tree
Hide file tree
Showing 11 changed files with 191 additions and 31 deletions.
2 changes: 2 additions & 0 deletions backend/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import mongoose from "mongoose";
import { router as roomRoutes } from "./routes/roomRoutes.js";
import { router as messageRoutes } from "./routes/messageRoutes.js";
import { router as userRoutes } from "./routes/userRoutes.js";
import { router as SingleUser } from "./routes/single_user.js";
import { app, server } from "./routes/socket.js";
import { log } from "./utils/log.js";
import cors from "cors";
Expand All @@ -21,6 +22,7 @@ app.use(bodyParser.json());
app.use("/rooms", roomRoutes);
app.use("/messages", messageRoutes);
app.use("/user", userRoutes);
app.use("/single_user", SingleUser);

server.listen(process.env.PORT || 4000, () => {
log("SERVER RUNNING");
Expand Down
30 changes: 30 additions & 0 deletions backend/src/models/single_user.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { Schema, model, Document, Model } from "mongoose";

interface ISingleUser extends Document {
username: string;
socketId: string;
}

interface ISingleUserModel extends Model<ISingleUser> {
findAll(): Promise<ISingleUser[]>;
}

const singleUserSchema = new Schema<ISingleUser>({
username: { type: String, required: true, unique: true },
socketId: { type: String, required: true },
});

singleUserSchema.statics.findAll = function (): Promise<ISingleUser[]> {
return this.find().exec();
};

singleUserSchema.statics.findOneByUsername = function (
socketId: string
): Promise<ISingleUser | null> {
return this.findOne({ socketId }).exec();
};

export const SingleUser = model<ISingleUser, ISingleUserModel>(
"SingleUser",
singleUserSchema
);
74 changes: 74 additions & 0 deletions backend/src/routes/single_user.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
import express, { Request, Response } from "express";
export const router = express.Router();
import { SingleUser } from "../models/single_user.js";

router.post("/newuser", async (req: Request, res: Response) => {
const { username, socketId } = req.body;

console.log(req.body); // Log the request body

try {
const existingUser = await SingleUser.findOne({
$or: [{ username }, { socketId }],
});
if (existingUser) {
return res
.status(400)
.json({ message: "Username or SocketId already exists" });
}

const newUser = await SingleUser.create({
username,
socketId,
});

res.status(201).json(newUser);
} catch (error: any) {
console.error(error); // Log the entire error
res.status(500).json({ message: error.message });
}
});

router.get("/", async (req: Request, res: Response) => {
try {
const users = await SingleUser.find();
res.status(200).json(users);
} catch (error: any) {
res.status(500).json({ message: error.message });
}
});

router.get("/:socketId", async (req: Request, res: Response) => {
const { socketId } = req.params;

try {
const user = await SingleUser.findOne({ socketId });

if (!user) {
return res.status(404).json({ message: "User not found" });
}

res.status(200).json(user);
} catch (error: any) {
res.status(500).json({ message: error.message });
}
});

router.put("/updateusername", async (req: Request, res: Response) => {
const { socketId, newUsername } = req.body;

try {
const user = await SingleUser.findOne({ socketId });

if (!user) {
return res.status(404).json({ message: "User not found" });
}

user.username = newUsername;
const updatedUser = await user.save();

res.status(200).json(updatedUser);
} catch (error: any) {
res.status(500).json({ message: error.message });
}
});
49 changes: 33 additions & 16 deletions backend/src/routes/socket.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ import express from "express";
import dotenv from "dotenv";
import { User } from "../models/user.js";


export const app = express();
app.use(cors());
dotenv.config();
Expand All @@ -24,7 +23,6 @@ const io = new Server(server, {
maxHttpBufferSize: 2e7,
});

let users: { [key: string]: string } = {};
mongoose
.connect(
`mongodb://${process.env.MONGODB_USER}:${process.env.MONGODB_USER_PASSWORD}@mongodb:27017/${process.env.MONGO_INITDB_DATABASE}`
Expand All @@ -38,7 +36,6 @@ let userNames: { [key: string]: string } = {};
io.on("connection", (socket) => {
// changer de nom
socket.on("change_name", ({ newName, OldName, roomId }) => {
console.log("User changed name: ", newName);
userNames[socket.id] = newName;
socket.emit("name_changed", newName);

Expand Down Expand Up @@ -80,10 +77,7 @@ io.on("connection", (socket) => {

socket.on("delete_room", async (roomId) => {
try {
// Delete the room from the database
await Room.findByIdAndDelete(roomId);

// Notify all clients that the room has been deleted
io.emit("room_deleted", roomId);

console.log(`Room ${roomId} deleted.`);
Expand Down Expand Up @@ -114,6 +108,29 @@ io.on("connection", (socket) => {
io.emit("users_response", roomUsers);
log(`User with ID: ${socket.id} joined room: ${roomId}`);
});

socket.on("join", async (roomId, username) => {
// Vérifie si la salle existe
let room = await Room.findById(roomId);
if (!room) {
// Si la salle n'existe pas, vous pouvez choisir de la créer ou d'envoyer une erreur
socket.emit("join_error", `Room ${roomId} does not exist.`);
return;
}

// Rejoint la salle
socket.join(roomId);
roomUsers[roomId] = [...(roomUsers[roomId] ?? []), socket.id];

// Informe les autres utilisateurs de la salle
socket.to(roomId).emit("receive_message", {
text: `${username} has joined the room.`,
systemMessage: true,
});

// Confirme la jonction à l'utilisateur
socket.emit("room_joined", {roomName: room.name, roomId: roomId});
});

socket.on("send_message", async (data) => {
io.emit("receive_message", data);
Expand Down Expand Up @@ -142,15 +159,15 @@ io.on("connection", (socket) => {
});

socket.on("user_joined", ({ username, roomId }) => {
socket.to(roomId).emit("receive_message", {
io.emit("receive_message", {
text: username + " joined the room. 🗿",
socketId: "Kurama-chat",
roomId: roomId,
systemMessage: true,
});
});

socket.on("leave_room", ({ username, roomId }) => {
socket.on("leave_room", async ({ username, roomId }) => {
socket.leave(roomId);
if (roomUsers[roomId]) {
roomUsers[roomId] = roomUsers[roomId].filter((id) => id !== socket.id);
Expand All @@ -163,8 +180,8 @@ io.on("connection", (socket) => {
systemMessage: true,
});

io.emit("users_response", roomUsers);
log(`User with ID: ${socket.id} left room: ${roomId}`);
socket.to(roomId).emit("users_response", roomUsers);
console.log(`User with ID: ${socket.id} left room: ${roomId}`);
});

socket.on("quit_room", async ({ username, roomId }) => {
Expand All @@ -180,7 +197,7 @@ io.on("connection", (socket) => {
systemMessage: true,
});

io.emit("users_response", roomUsers);
socket.to(roomId).emit("users_response", roomUsers);

if (roomUsers[roomId] && roomUsers[roomId].length === 0) {
try {
Expand All @@ -194,21 +211,21 @@ io.on("connection", (socket) => {
}
});

socket.on("logout", ({ username, roomId }) => {
socket.leave(roomId);
socket.on("logout", async ({ username, roomId }) => {
if (roomUsers[roomId]) {
roomUsers[roomId] = roomUsers[roomId].filter((id) => id !== socket.id);
}

io.emit("receive_message", {
text: username + " left the room. ➡️🚪",
text: username + " disconnect. ❌",
socketId: "Kurama-chat",
roomId: roomId,
systemMessage: true,
});

io.emit("users_response", roomUsers);
socket.to(roomId).emit("users_response", roomUsers);
log(`User with ID: ${socket.id} left room: ${roomId}`);
socket.leave(roomId);
delete userNames[socket.id];
});

Expand All @@ -223,8 +240,8 @@ io.on("connection", (socket) => {
roomId: roomId,
systemMessage: true,
});
socket.to(roomId).emit("users_response", roomUsers);
}
}
io.emit("users_response", roomUsers);
});
});
7 changes: 4 additions & 3 deletions docker-compose.yml
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
version: "2"
version: "3"
services:
traefik:
image: traefik
Expand All @@ -8,8 +8,10 @@ services:
- "--providers.docker=true"
- "--providers.docker.exposedbydefault=false"
- "--entrypoints.web.address=:80"
- "--entrypoints.websecure.address=:443"
ports:
- "80:80"
- "443:443"
- "8080:8080"
volumes:
- /var/run/docker.sock:/var/run/docker.sock
Expand Down Expand Up @@ -49,7 +51,6 @@ services:
- MONGODB_USER_PASSWORD=${MONGODB_USER_PASSWORD}
- PORT=${PORT}
- DEBUG=${DEBUG}
- ORIGIN_URL=${ORIGIN_URL}
ports:
- 4000:4000

Expand All @@ -65,7 +66,7 @@ services:
labels:
- "traefik.enable=true"
- "traefik.http.routers.frontend.rule=HostRegexp(`{any:.*}`)"
- "traefik.http.routers.frontend.entrypoints=web"
- "traefik.http.routers.frontend.entrypoints=web,websecure"
- "traefik.http.services.frontend.loadbalancer.server.port=3000"
networks:
- web
Expand Down
5 changes: 5 additions & 0 deletions frontend/src/app/chat/[roomId]/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,11 @@ function Page() {
roomId: roomId,
});
socket?.emit("join_room", roomId);
socket?.emit("change_name", {
newName: username,
OldName: username,
roomId: "",
});
}, []);

return (
Expand Down
37 changes: 33 additions & 4 deletions frontend/src/components/Chat/ChatFooter.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import 'react-toastify/dist/ReactToastify.css';
import { toast, ToastContainer } from 'react-toastify';
import { v4 as uuidv4 } from 'uuid';
import { useRoom } from "@/contexts/RoomContext";
import { useRouter } from "next/navigation";


function ChatFooter({ roomId }: { roomId: string }) {
Expand All @@ -26,6 +27,7 @@ function ChatFooter({ roomId }: { roomId: string }) {
const [image, setImage] = useState<string | null>(null);
const [showToast, setShowToast] = useState<boolean>(false);
const [toastMessage, setToastMessage] = useState<string>("");
const router = useRouter();
const onEmojiPick = (emojiObj: any) => {
setMessage((prevInput) => prevInput + emojiObj.emoji);
inputRef.current.focus();
Expand Down Expand Up @@ -63,10 +65,30 @@ function ChatFooter({ roomId }: { roomId: string }) {
}
}, [socket, roomId]);

useEffect(() => {
if (socket) {
socket.on("room_joined", (id, username) => {
toast.success(`Joined room: ${id.roomName}`);
setMyRooms((prevRooms) => [...prevRooms, { id: id.roomId, title: id.roomName }]);
});

socket.on("join_error", (errorMessage) => {
toast.error(errorMessage);
});

return () => {
socket.off("room_joined");
socket.off("join_error");
};
}
}, [socket]);


function handleCommand(commandString: string, socket: any) {
const parts = commandString.substr(1).split(" ");
const command = parts[0].toLowerCase();
const args = parts.slice(1);


switch (command) {
case "nick":
Expand All @@ -90,7 +112,7 @@ function ChatFooter({ roomId }: { roomId: string }) {

let newRoom = {
title: roomName,
id: newRoomId, // Use the constant
id: newRoomId,
};
console.log("New room: ", newRoomId);
setMyRooms([...myRooms, newRoom]);
Expand All @@ -102,13 +124,20 @@ function ChatFooter({ roomId }: { roomId: string }) {
socket?.emit("delete_room", roomId);
toast.info("Deleting room...");
break;
case "join":
const joinParam = args.join(" ");
socket?.emit("join", joinParam);
case "join":
if (args.length === 0) {
toast.error("Please specify a room ID to join.");
} else {
const roomIdToJoin = args[0];
const username = localStorage.getItem("name");
socket.emit("join", roomIdToJoin, username);
}
break;
case "quit":
const username = localStorage.getItem("name");
socket?.emit("leave_room", username, roomId);
setMyRooms(myRooms.filter((room) => room.id !== roomId));
router.push("/chat/1");
break;
case "users":
socket?.emit("users");
Expand Down
1 change: 0 additions & 1 deletion frontend/src/components/Room/AddRoomPanel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@ function AddRoomPanel({ hideAddRoomPanel }: any) {
return;
}

// Fetch room data from server
const response = await fetch(
process.env.NEXT_PUBLIC_BASE_URL + `rooms/${joinId}`
);
Expand Down
Loading

0 comments on commit 3a4d216

Please sign in to comment.