Skip to content

Commit

Permalink
added personal chat feature
Browse files Browse the repository at this point in the history
  • Loading branch information
Dushyantbha012 committed Feb 23, 2024
1 parent 6d5275c commit 8b6acaa
Show file tree
Hide file tree
Showing 8 changed files with 224 additions and 19 deletions.
13 changes: 7 additions & 6 deletions Backend-Realm/routers/chatRouters/chatRouters.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,12 @@ chatRouters.get("/userrooms", authMiddleware, async (req, res) => {
console.log("request reached in userrooms")
const filter = req.query.filter || "";
console.log("filter is ", filter)
const user = await User.findOne({ _id: req.userId });
const chatRooms = user.rooms;
const user = await User.findOne({ _id: req.userId});
const tempRooms = user.rooms
const chatRooms = tempRooms.filter(room => !room.includes("@")) ;

if (filter != "") {
const filteredRooms = chatRooms.filter(room => room.includes(filter));
const filteredRooms = chatRooms.filter(room => ( room.includes(filter)));

const room = filteredRooms.map(room => ({
roomId: room,
Expand Down Expand Up @@ -133,7 +134,7 @@ chatRouters.post("/createprivate", authMiddleware, async (req, res) => {
});
if (existingRoom) {

return res.status(200).json({ message: "Room already exists"});
return res.status(200).json({ message: "Room already exists", id: roomId});
}
const room = {
roomId: roomId,
Expand All @@ -152,9 +153,9 @@ chatRouters.post("/createprivate", authMiddleware, async (req, res) => {
{ $addToSet: { rooms: room.roomId } },
{ new: true }
);
res.status(200).json({ message: "Room created" });
res.status(200).json({ message: "Room created" , id: roomId});
} catch {
res.status(411).json({message: "error"})
res.status(411).json({message: "error", id :""})
}
});

Expand Down
8 changes: 7 additions & 1 deletion Frontend-Realm/src/atoms/atoms.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,12 @@ const otherNameState = atom({
key: 'otherEmailState',
default: '',
});
const emailState = atom({
key: 'emailState',
default: '',
});

const privateRoomIdState = atom({key:"privateRoomIdState",default:""})

export {otherBranchState,otherCollegeState,otherEmailState,otherGraduationYearState,otherNameState,otherSIDState}
export {otherBranchState,otherCollegeState,otherEmailState,otherGraduationYearState,otherNameState,otherSIDState, privateRoomIdState,emailState}

79 changes: 79 additions & 0 deletions Frontend-Realm/src/components/PersonalChat/ChatBox.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
import {React, useState, useEffect} from 'react';
import io from "socket.io-client"
import './chat.css'

function ChatBox({roomId, username}) {
console.log("room id recieved is ", roomId)
const socket = io.connect("http://localhost:5000")
const [currentMessage, setCurrentMessage] = useState("");
const [chats, setChats]=useState([]);
useEffect(()=>{
if(username!==""&&roomId!==""){
socket.emit("joinRoom",{roomId : roomId});
socket.on("initialChats",(initialChats)=>{
setChats(initialChats);
})
}
},[roomId, username]);
const handelEnterPress = (event) => {
if (event.key === "Enter") {
sendMessage();
}
};
useEffect(()=>{
socket.on("receiveMessage",(receivedChat)=>{
setChats((prevChats)=>[...prevChats,receivedChat]);
})
},[socket])

const sendMessage = async()=>{
if(currentMessage!=""){
const messageData = {
roomId:roomId,
chat:{
author:username,
message:currentMessage,
timeStamp: new Date(Date.now()).getHours() +
":" +
new Date(Date.now()).getMinutes(),
}
}
await socket.emit("sendMessage",messageData);
setCurrentMessage("");
}
}
return (
<div className="chatbox">
<div className="chat-container">
<div className="header">
<p>Live Chat : {username} : {roomId}</p>
</div>
<div className="chat-messages">
{chats.map((messageContent, index) => (
<div className="message" key={index}>
<span className="author">{messageContent.author}</span>
<span className="content">{messageContent.message}</span>
<span className="timestamp">{messageContent.timeStamp}</span>
</div>
))}
</div>
<div className="footer">
<input
className="input-field"
type="text"
value={currentMessage}
placeholder="Type your message..."
onChange={(event) => setCurrentMessage(event.target.value)}
onKeyDown={handelEnterPress}
/>
<button className="send-button" onClick={sendMessage}>
Send
</button>
</div>
</div>
</div>
)

}

export default ChatBox
14 changes: 14 additions & 0 deletions Frontend-Realm/src/components/PersonalChat/PrivateChat.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import React, { useEffect } from 'react'
import {privateRoomIdState} from "../../atoms/atoms"
import { useRecoilValue } from 'recoil'
import ChatBox from "./ChatBox"
function PrivateChat() {
const privateRoomId = useRecoilValue(privateRoomIdState);
return (
<div>
<ChatBox roomId={privateRoomId} username ={localStorage.getItem("username")} />
</div>
)
}

export default PrivateChat
78 changes: 78 additions & 0 deletions Frontend-Realm/src/components/PersonalChat/chat.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
.chatbox {
display: flex;
justify-content: center;
margin-bottom: 100px;
margin-top: 100px;
}

.chat-container {
width: 1000px;
height: 600px;
border: 1px solid #ddd;
border-radius: 10px;
overflow: hidden;
font-family: Arial, sans-serif;
}

.header {
color: #fff;
padding: 10px;
text-align: center;
font-weight: bold;
}

.chat-messages {
height: 450px;
overflow-y: auto;
padding: 10px;
}

.message {
margin-bottom: 10px;
}

.author {
font-weight: bold;
color: #075e54;
}

.content {
background-color: #dcf8c6;
padding: 8px 12px;
border-radius: 10px;
display: inline-block;
margin-left: 10px;
}

.timestamp {
font-size: 12px;
color: #999;
margin-left: 10px;
}

.footer {
display: flex;
align-items: center;
padding: 10px;
border-top: 1px solid #ddd;
}

.input-field {
flex: 1;
padding: 8px;
border: none;
border-radius: 20px;
outline: none;
color: #000;
}

.send-button {
background-color: #075e54;
color: #fff;
border: none;
border-radius: 50%;
width: 30px;
height: 30px;
margin-left: 10px;
cursor: pointer;
}
1 change: 1 addition & 0 deletions Frontend-Realm/src/components/Profile/Profile.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ function Profile() {
console.log(res);
setProfile(res.data);
localStorage.setItem("username",res.data.username);
localStorage.setItem("email",res.data.email);
};
fetchingProfile();
}, []);
Expand Down
46 changes: 35 additions & 11 deletions Frontend-Realm/src/components/UserSearch/UserProfile.jsx
Original file line number Diff line number Diff line change
@@ -1,19 +1,42 @@
import React from "react";
import React, { useEffect } from "react";
import { useNavigate } from "react-router-dom";
import { useRecoilValue, useRecoilState } from "recoil";
import axios from "axios";
import {
otherBranchState,
otherCollegeState,
otherEmailState,
otherGraduationYearState,
otherNameState,
otherSIDState,
privateRoomIdState,
} from "../..//atoms/atoms";

import {useRecoilValue} from "recoil"

import {otherBranchState,otherCollegeState,otherEmailState,otherGraduationYearState,otherNameState,otherSIDState} from "../..//atoms/atoms"



function UserProfile({
}) {
function UserProfile({}) {
const navigateTo = useNavigate();
const otherBranch = useRecoilValue(otherBranchState);
const otherCollege = useRecoilValue(otherCollegeState);
const otherEmail = useRecoilValue(otherEmailState);
const otherGraduationYear = useRecoilValue(otherGraduationYearState);
const otherName = useRecoilValue(otherNameState);
const otherSID = useRecoilValue(otherSIDState)
const otherSID = useRecoilValue(otherSIDState);
const [privateRoomId, setPrivateRoomId] =
useRecoilState(privateRoomIdState);


const onClickHandeler=async()=>{
const res = await axios({
method: "POST",
url: "http://localhost:3000/api/chat/createprivate",
headers: { authorization: localStorage.getItem("token") },
data:{senderMail:localStorage.getItem("email"),recMail:otherEmail}
});
console.log("room id set is ", res.data.id)
setPrivateRoomId(res.data.id)
navigateTo("/privatechat")
}


return (
<div>
<div>UserProfile</div>
Expand All @@ -22,7 +45,8 @@ function UserProfile({
<div>Branch : {otherBranch}</div>
<div>Graduation Year : {otherGraduationYear}</div>
<div>SID : {otherSID}</div>
<div>email : {otherEmail}</div>
<div>E-mail : {otherEmail}</div>
<button onClick={onClickHandeler}>Chat</button>
</div>
);
}
Expand Down
4 changes: 3 additions & 1 deletion Frontend-Realm/src/main.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ import {
} from "react-router-dom";
import UserSearch from "./components/UserSearch/UserSearch.jsx";
import UserProfile from "./components/UserSearch/UserProfile.jsx";
import PrivateChat from "./components/PersonalChat/PrivateChat.jsx"


const router = createBrowserRouter(
createRoutesFromElements(
Expand All @@ -29,7 +31,7 @@ const router = createBrowserRouter(
<Route path="profile" element={<Profile />} />
<Route path="users" element={<UserSearch />} />
<Route path="usersprofile" element={<UserProfile />} />

<Route path="privatechat" element={<PrivateChat />} />
</Route>
)
);
Expand Down

0 comments on commit 8b6acaa

Please sign in to comment.