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

Message Reactions #70

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 49 additions & 6 deletions backend/controllers/messageControllers.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,14 @@ const User = require("../models/userModel");
const Chat = require("../models/chatModel");

//@description Get all Messages
//@route GET /api/Message/:chatId
//@route GET /api/message/:chatId
//@access Protected
const allMessages = asyncHandler(async (req, res) => {
try {
const messages = await Message.find({ chat: req.params.chatId })
.populate("sender", "name pic email")
.populate("chat");
.populate("chat")
.populate("reactions.user", "name pic email"); // Populate reaction users
res.json(messages);
} catch (error) {
res.status(400);
Expand All @@ -19,7 +20,7 @@ const allMessages = asyncHandler(async (req, res) => {
});

//@description Create New Message
//@route POST /api/Message/
//@route POST /api/message/
//@access Protected
const sendMessage = asyncHandler(async (req, res) => {
const { content, chatId } = req.body;
Expand All @@ -29,14 +30,14 @@ const sendMessage = asyncHandler(async (req, res) => {
return res.sendStatus(400);
}

var newMessage = {
const newMessage = {
sender: req.user._id,
content: content,
chat: chatId,
};

try {
var message = await Message.create(newMessage);
let message = await Message.create(newMessage);

message = await message.populate("sender", "name pic").execPopulate();
message = await message.populate("chat").execPopulate();
Expand All @@ -54,4 +55,46 @@ const sendMessage = asyncHandler(async (req, res) => {
}
});

module.exports = { allMessages, sendMessage };
//@description React to a Message
//@route POST /api/message/:messageId/react
//@access Protected
const reactToMessage = asyncHandler(async (req, res) => {
const { emoji } = req.body;

if (!emoji) {
return res.status(400).json({ message: "Emoji is required" });
}

try {
const message = await Message.findById(req.params.messageId);

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

// Check if the user has already reacted to the message
const existingReaction = message.reactions.find(
(reaction) => reaction.user.toString() === req.user._id.toString()
);

if (existingReaction) {
// Update the existing reaction
existingReaction.emoji = emoji;
} else {
// Add a new reaction
message.reactions.push({ emoji, user: req.user._id });
}

await message.save();

const updatedMessage = await Message.findById(req.params.messageId)
.populate("reactions.user", "name pic email");

res.json(updatedMessage);
} catch (error) {
res.status(400);
throw new Error(error.message);
}
});

module.exports = { allMessages, sendMessage, reactToMessage };
6 changes: 6 additions & 0 deletions backend/models/messageModel.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,12 @@ const messageSchema = mongoose.Schema(
content: { type: String, trim: true },
chat: { type: mongoose.Schema.Types.ObjectId, ref: "Chat" },
readBy: [{ type: mongoose.Schema.Types.ObjectId, ref: "User" }],
reactions: [
{
emoji: { type: String, required: true }, // The emoji used for the reaction
user: { type: mongoose.Schema.Types.ObjectId, ref: "User", required: true }, // User who reacted
},
],
},
{ timestamps: true }
);
Expand Down
1 change: 1 addition & 0 deletions frontend/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

90 changes: 54 additions & 36 deletions frontend/src/components/SingleChat.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { FormControl } from "@chakra-ui/form-control";
import { Input } from "@chakra-ui/input";
import { Box, Text } from "@chakra-ui/layout";
import "./styles.css";
import { IconButton, Spinner, useToast } from "@chakra-ui/react";
import { IconButton, Spinner, useToast, Menu, MenuButton, MenuList, MenuItem } from "@chakra-ui/react";
import { getSender, getSenderFull } from "../config/ChatLogics";
import { useEffect, useState } from "react";
import axios from "axios";
Expand All @@ -11,11 +11,11 @@ import ProfileModal from "./miscellaneous/ProfileModal";
import ScrollableChat from "./ScrollableChat";
import Lottie from "react-lottie";
import animationData from "../animations/typing.json";

import io from "socket.io-client";
import UpdateGroupChatModal from "./miscellaneous/UpdateGroupChatModal";
import { ChatState } from "../Context/ChatProvider";
const ENDPOINT = "http://localhost:5000"; // "https://talk-a-tive.herokuapp.com"; -> After deployment

const ENDPOINT = "http://localhost:5000";
var socket, selectedChatCompare;

const SingleChat = ({ fetchAgain, setFetchAgain }) => {
Expand All @@ -35,8 +35,8 @@ const SingleChat = ({ fetchAgain, setFetchAgain }) => {
preserveAspectRatio: "xMidYMid slice",
},
};
const { selectedChat, setSelectedChat, user, notification, setNotification } =
ChatState();

const { selectedChat, setSelectedChat, user, notification, setNotification } = ChatState();

const fetchMessages = async () => {
if (!selectedChat) return;
Expand All @@ -50,17 +50,14 @@ const SingleChat = ({ fetchAgain, setFetchAgain }) => {

setLoading(true);

const { data } = await axios.get(
`/api/message/${selectedChat._id}`,
config
);
const { data } = await axios.get(`/api/message/${selectedChat._id}`, config);
setMessages(data);
setLoading(false);

socket.emit("join chat", selectedChat._id);
} catch (error) {
toast({
title: "Error Occured!",
title: "Error Occurred!",
description: "Failed to Load the Messages",
status: "error",
duration: 5000,
Expand All @@ -70,6 +67,40 @@ const SingleChat = ({ fetchAgain, setFetchAgain }) => {
}
};

const sendReaction = async (messageId, emoji) => {
try {
const config = {
headers: {
"Content-type": "application/json",
Authorization: `Bearer ${user.token}`,
},
};

const { data } = await axios.post(
"/api/message/react",
{ messageId, emoji },
config
);

// Update the specific message in the messages array
const updatedMessages = messages.map((msg) =>
msg._id === messageId ? { ...msg, reactions: data.reactions } : msg
);

setMessages(updatedMessages);
socket.emit("reaction", data);
} catch (error) {
toast({
title: "Error Occurred!",
description: "Failed to react to the message",
status: "error",
duration: 5000,
isClosable: true,
position: "bottom",
});
}
};

const sendMessage = async (event) => {
if (event.key === "Enter" && newMessage) {
socket.emit("stop typing", selectedChat._id);
Expand All @@ -93,7 +124,7 @@ const SingleChat = ({ fetchAgain, setFetchAgain }) => {
setMessages([...messages, data]);
} catch (error) {
toast({
title: "Error Occured!",
title: "Error Occurred!",
description: "Failed to send the Message",
status: "error",
duration: 5000,
Expand Down Expand Up @@ -122,20 +153,13 @@ const SingleChat = ({ fetchAgain, setFetchAgain }) => {
}, [selectedChat]);

useEffect(() => {
socket.on("message recieved", (newMessageRecieved) => {
if (
!selectedChatCompare || // if chat is not selected or doesn't match current chat
selectedChatCompare._id !== newMessageRecieved.chat._id
) {
if (!notification.includes(newMessageRecieved)) {
setNotification([newMessageRecieved, ...notification]);
setFetchAgain(!fetchAgain);
}
} else {
setMessages([...messages, newMessageRecieved]);
}
socket.on("reaction received", (updatedMessage) => {
const updatedMessages = messages.map((msg) =>
msg._id === updatedMessage._id ? updatedMessage : msg
);
setMessages(updatedMessages);
});
});
}, [messages]);

const typingHandler = (e) => {
setNewMessage(e.target.value);
Expand Down Expand Up @@ -181,9 +205,7 @@ const SingleChat = ({ fetchAgain, setFetchAgain }) => {
(!selectedChat.isGroupChat ? (
<>
{getSender(user, selectedChat.users)}
<ProfileModal
user={getSenderFull(user, selectedChat.users)}
/>
<ProfileModal user={getSenderFull(user, selectedChat.users)} />
</>
) : (
<>
Expand Down Expand Up @@ -217,21 +239,18 @@ const SingleChat = ({ fetchAgain, setFetchAgain }) => {
/>
) : (
<div className="messages">
<ScrollableChat messages={messages} />
<ScrollableChat
messages={messages}
onReact={(messageId, emoji) => sendReaction(messageId, emoji)}
/>
</div>
)}

<FormControl
onKeyDown={sendMessage}
id="first-name"
isRequired
mt={3}
>
<FormControl onKeyDown={sendMessage} id="first-name" isRequired mt={3}>
{istyping ? (
<div>
<Lottie
options={defaultOptions}
// height={50}
width={70}
style={{ marginBottom: 15, marginLeft: 0 }}
/>
Expand All @@ -250,7 +269,6 @@ const SingleChat = ({ fetchAgain, setFetchAgain }) => {
</Box>
</>
) : (
// to get socket.io on same page
<Box d="flex" alignItems="center" justifyContent="center" h="100%">
<Text fontSize="3xl" pb={3} fontFamily="Work sans">
Click on a user to start chatting
Expand Down
Loading