Skip to content

Commit

Permalink
Add private messaging functionality
Browse files Browse the repository at this point in the history
  • Loading branch information
etienne committed Feb 15, 2024
1 parent e87fa00 commit 1b2a079
Show file tree
Hide file tree
Showing 4 changed files with 68 additions and 7 deletions.
38 changes: 38 additions & 0 deletions backend/src/routes/socket.ts
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,45 @@ io.on("connection", (socket) => {
socket.emit("room_joined", { roomName: room.name, roomId: roomId });
});

socket.on(
"send_private_message",
async (roomId, nickname, username, userid, messageData) => {
// Récupérer l'ID du socket associé au surnom
const userId = Object.keys(userNames).find(
(key) => userNames[key] === nickname
);

let roomName = nickname + "," + username;

if (userId) {
socket?.emit("join_room", roomId, roomName);

socket.emit("join", roomId);
io.to(userId).emit("join", roomId);

socket.emit("room_joined", { roomName: roomName, roomId: roomId });
io.to(userId).emit("room_joined", {
roomName: roomName,
roomId: roomId,
});

// Envoyez le message à la salle
socket.emit("private_message_sent", {
text: messageData,
name: username,
userId: userid,
date: new Date(),
socketId: socket.id,
roomId: roomId,
});
} else {
socket.emit("error", "Nickname not found.");
}
}
);

socket.on("send_message", async (data) => {
console.log("Message received: ", data);
io.emit("receive_message", data);

// Save message to MongoDB
Expand Down
2 changes: 2 additions & 0 deletions frontend/src/components/Chat/ChatBody.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
"use client";
import { useSocket } from "@/contexts/SocketContext";
import { useUser } from "@/contexts/UserContext";
import React, { useEffect, useRef, useState } from "react";
import Avatar from "react-avatar";
import ChatImage from "./ChatImage";
Expand All @@ -8,6 +9,7 @@ function ChatBody({ roomId }: { roomId: string }) {
const [typing, setTyping] = useState<string>("");
const lastMessageRef = useRef<HTMLDivElement>(null);
const { messages, socket, setMessages } = useSocket();
const { username } = useUser();

useEffect(() => {
lastMessageRef.current?.scrollIntoView({ behavior: "smooth" });
Expand Down
32 changes: 25 additions & 7 deletions frontend/src/components/Chat/ChatFooter.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,14 @@ import { toast, ToastContainer } from "react-toastify";
import { v4 as uuidv4 } from "uuid";
import { useRoom } from "@/contexts/RoomContext";
import { useRouter } from "next/navigation";
import local from "next/font/local";

function ChatFooter({ roomId }: { roomId: string }) {
const [showListPopup, setShowListPopup] = useState(false);
const [roomList, setRoomList] = useState([]);
const [message, setMessage] = useState<string>("");
const { socket } = useSocket();
const { username } = useUser();
const { username, setUsername } = useUser();
const { myRooms, setMyRooms } = useRoom();
const [id, setId] = useState<string>("");
const [showEmojiPicker, setShowEmojiPicker] = useState<boolean>(false);
Expand Down Expand Up @@ -93,11 +94,13 @@ function ChatFooter({ roomId }: { roomId: string }) {
switch (command) {
case "nick":
const newName = args.join(" ");
setUsername(newName);
socket?.emit("change_name", {
OldName: localStorage.getItem("name"),
newName,
roomId,
});
localStorage.setItem("name", newName);
break;
case "list":
socket.emit("list", args.join(" "));
Expand Down Expand Up @@ -129,12 +132,12 @@ function ChatFooter({ roomId }: { roomId: string }) {
toast.error("Please specify a room ID to join.");
} else {
const roomIdToJoin = args[0];
const username = localStorage.getItem("name");
socket.emit("join", roomIdToJoin, username);
const userName = localStorage.getItem("name");
socket.emit("join", roomIdToJoin, userName);
}
break;
case "quit":
const username = localStorage.getItem("name");
const userName = localStorage.getItem("name") || username;
socket?.emit("leave_room", username, roomId);
setMyRooms(myRooms.filter((room) => room.id !== roomId));
router.push("/chat/1");
Expand All @@ -143,8 +146,24 @@ function ChatFooter({ roomId }: { roomId: string }) {
socket?.emit("users");
break;
case "msg":
const msgParam = args.join(" ");
socket?.emit("msg", msgParam);
if (args.length < 2) {
console.error("Please specify a nickname and a message.");
toast.error("Please specify a nickname and a message.");
} else {
const nickname = args[0];
const messageData = args.slice(1).join(" ");
const newRoomId = uuidv4(); // Générer un nouvel ID de salle

// Envoyer le surnom et le message au serveur
socket?.emit(
"send_private_message",
newRoomId,
nickname,
username,
localStorage.getItem("userId"),
messageData
);
}
break;
case "clear":
socket.emit("clear", roomId);
Expand All @@ -154,7 +173,6 @@ function ChatFooter({ roomId }: { roomId: string }) {
break;
}
}

const handleSendMessage = (e: React.FormEvent, message: string) => {
e.preventDefault();
if (message.trim() || image) {
Expand Down
3 changes: 3 additions & 0 deletions frontend/src/contexts/SocketContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,9 @@ export default function SocketProvider({
});
});
socket.on("users_response", (data) => setRoomUsers(data));
socket.on("private_message_sent", (data) => {
socket.emit("send_message", data);
});
setSocket(socket);
}
}, []);
Expand Down

0 comments on commit 1b2a079

Please sign in to comment.