Skip to content
Closed
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
21 changes: 21 additions & 0 deletions backend/controllers/notification.controller.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
const Notification = require("../models/notification.model");

exports.getNotifications = async (req, res) => {
try {
const { userId } = req.params;
const notifications = await Notification.find({ userId }).sort({ createdAt: -1 });
res.json(notifications);
} catch (err) {
res.status(500).json({ error: err.message });
}
};

exports.markAsRead = async (req, res) => {
try {
const { id } = req.params;
await Notification.findByIdAndUpdate(id, { isRead: true });
res.json({ success: true });
} catch (err) {
res.status(500).json({ error: err.message });
}
};
16 changes: 16 additions & 0 deletions backend/models/notification.model.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
const mongoose = require("mongoose");

const notificationSchema = new mongoose.Schema(
{
userId: { type: String, required: true },
type: {
type: String,
enum: ["message", "like", "comment", "request", "system"],
},
content: String,
isRead: { type: Boolean, default: false },
},
{ timestamps: true }
);

module.exports = mongoose.model("Notification", notificationSchema);
7 changes: 7 additions & 0 deletions backend/routes/notification.routes.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
const router = require("express").Router();
const controller = require("../controllers/notification.controller");

router.get("/:userId", controller.getNotifications);

Check failure

Code scanning / CodeQL

Missing rate limiting High

This route handler performs
a database access
, but is not rate-limited.
router.patch("/:id/read", controller.markAsRead);

Check failure

Code scanning / CodeQL

Missing rate limiting High

This route handler performs
a database access
, but is not rate-limited.

module.exports = router;
23 changes: 23 additions & 0 deletions backend/services/socket.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
const { Server } = require("socket.io");

let io;

const initSocket = (server) => {
io = new Server(server, {
cors: { origin: "*" },
});

io.on("connection", (socket) => {
console.log("User connected:", socket.id);

socket.on("join", (userId) => {
socket.join(userId);
});
});
};

const sendNotification = (userId, notification) => {
io.to(userId).emit("new_notification", notification);
};

module.exports = { initSocket, sendNotification };
297 changes: 297 additions & 0 deletions frontend/app/chat/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -304,4 +304,301 @@ socket.on("newMessage", (msg) => {
</div>
</div>
);
}"use client";

import { useState, useEffect, useRef } from "react";
import { io, Socket } from "socket.io-client";
import { motion } from "framer-motion";

type Message = {
id?: string;
user: string;
text: string;
time?: string;
status?: string;
};

export default function ChatPage() {
const [messages, setMessages] = useState<Message[]>([]);
const [input, setInput] = useState("");
const [username, setUsername] = useState("");
const [typingUser, setTypingUser] = useState("");
const [onlineUsers, setOnlineUsers] = useState<string[]>([]);
const [unreadCount, setUnreadCount] = useState(0);

const socketRef = useRef<Socket | null>(null);
const typingTimeoutRef = useRef<any>(null);

const containerRef = useRef<HTMLDivElement>(null);
const bottomRef = useRef<HTMLDivElement>(null);
const isAtBottomRef = useRef(true);

const audioRef = useRef<HTMLAudioElement | null>(null);

// SOCKET SETUP
useEffect(() => {
const socket = io("http://localhost:5000");
socketRef.current = socket;

audioRef.current = new Audio("/ping.mp3");

// FETCH OLD MESSAGES
fetch("http://localhost:5000/api/chat")
.then((res) => res.json())
.then((data) => {
const formatted = data.map((msg: any) => ({
id: msg.id,
user: msg.username,
text: msg.text,
time: new Date(msg.created_at).toLocaleTimeString(),
status: msg.status || "sent",
}));
setMessages(formatted);
});

// NEW MESSAGE
socket.on("newMessage", (msg) => {
setMessages((prev) => {
const exists = prev.some((m) => m.id === msg.id);
if (exists) return prev;

return [
...prev,
{
id: msg.id,
user: msg.username,
text: msg.text,
time: new Date(msg.created_at).toLocaleTimeString(),
status: msg.status || "sent",
},
];
});

if (!isAtBottomRef.current) {
setUnreadCount((prev) => prev + 1);
audioRef.current?.play().catch(() => {});
}
});

// TYPING
socket.on("typing", (user) => {
setTypingUser(user);

if (typingTimeoutRef.current) {
clearTimeout(typingTimeoutRef.current);
}

typingTimeoutRef.current = setTimeout(() => {
setTypingUser("");
}, 1500);
});

// ONLINE USERS
socket.on("onlineUsers", (users) => {
setOnlineUsers(users);
});

// SEEN
socket.on("messageSeen", (messageId) => {
setMessages((prev) =>
prev.map((msg) =>
msg.id === messageId ? { ...msg, status: "seen" } : msg
)
);
});

return () => socket.disconnect();
}, []);

// JOIN USER
useEffect(() => {
if (socketRef.current && username.trim()) {
socketRef.current.emit("join", username);
}
}, [username]);

// AUTO SCROLL
useEffect(() => {
if (isAtBottomRef.current) {
bottomRef.current?.scrollIntoView({ behavior: "smooth" });
}
}, [messages]);

// MARK LAST MESSAGE AS SEEN
useEffect(() => {
if (!socketRef.current) return;
const lastMsg = messages[messages.length - 1];
if (lastMsg?.id) {
socketRef.current.emit("seen", lastMsg.id);
}
}, [messages]);

// SEND MESSAGE (Optimistic UI)
async function handleSend() {
if (!input.trim() || !username.trim()) return;

const tempId = Date.now().toString();

setMessages((prev) => [
...prev,
{
id: tempId,
user: username,
text: input,
time: new Date().toLocaleTimeString(),
status: "sending",
},
]);

setInput("");

try {
await fetch("http://localhost:5000/api/chat", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ text: input, username }),
});
} catch (err) {
console.error(err);
}
}

// TYPING
function handleTyping(e: any) {
setInput(e.target.value);

if (socketRef.current && username.trim()) {
socketRef.current.emit("typing", username);
}
}

return (
<div className="p-4 max-w-4xl mx-auto relative">
{/* HEADER */}
<div className="sticky top-0 bg-white z-10 pb-2">
<h1 className="text-2xl font-bold mb-2">Team Chat</h1>

<input
value={username}
onChange={(e) => setUsername(e.target.value)}
placeholder="Enter name"
className="mb-2 p-2 border rounded w-full"
/>

<div className="text-sm text-green-600">
Online: {onlineUsers.join(", ")}
</div>
</div>

{/* CHAT BOX */}
<div
ref={containerRef}
onScroll={() => {
const el = containerRef.current;
if (!el) return;

const atBottom =
el.scrollHeight - el.scrollTop - el.clientHeight < 100;

isAtBottomRef.current = atBottom;

if (atBottom) setUnreadCount(0);
}}
className="h-[60vh] md:h-[400px] overflow-y-auto space-y-2 border p-3 bg-gray-50 rounded"
>
{messages.map((msg, i) => {
const prevMsg = messages[i - 1];
const isSameUser = prevMsg && prevMsg.user === msg.user;
const isMe = msg.user === username;

return (
<motion.div
key={msg.id || i}
initial={{ opacity: 0, y: 10 }}
animate={{ opacity: 1, y: 0 }}
className={`flex ${
isMe ? "justify-end" : "justify-start"
} ${isSameUser ? "mt-1" : "mt-3"}`}
>
<div
className={`p-3 max-w-xs shadow ${
isMe
? "bg-green-500 text-white rounded-2xl"
: "bg-gray-200 text-black rounded-2xl"
}`}
>
{/* Avatar + Name */}
{!isMe && !isSameUser && (
<div className="flex items-center gap-2 mb-1">
<div className="w-6 h-6 bg-gray-400 text-white flex items-center justify-center rounded-full text-xs">
{msg.user[0]?.toUpperCase()}
</div>
<p className="font-semibold text-sm">{msg.user}</p>
</div>
)}

<p>{msg.text}</p>

{/* STATUS */}
<p className="text-xs text-right opacity-70 flex justify-end gap-1">
{msg.time}
{msg.status === "sending" && "🕓"}
{msg.status === "sent" && "✓"}
{msg.status === "seen" && (
<span className="text-blue-500">✓✓</span>
)}
</p>
</div>
</motion.div>
);
})}

<div ref={bottomRef}></div>
</div>

{/* UNREAD BUTTON */}
{unreadCount > 0 && (
<div className="absolute bottom-24 left-1/2 -translate-x-1/2">
<button
onClick={() => {
bottomRef.current?.scrollIntoView({ behavior: "smooth" });
setUnreadCount(0);
}}
className="bg-blue-500 text-white px-4 py-1 rounded-full shadow-lg hover:scale-105 transition"
>
{unreadCount} New Message{unreadCount > 1 ? "s" : ""}
</button>
</div>
)}

{/* TYPING INDICATOR */}
{typingUser && typingUser !== username && (
<div className="text-sm italic mt-1 flex items-center gap-1">
{typingUser} typing
<span className="animate-bounce">.</span>
<span className="animate-bounce delay-100">.</span>
<span className="animate-bounce delay-200">.</span>
</div>
)}

{/* INPUT */}
<div className="flex mt-3 gap-2">
<input
value={input}
onChange={handleTyping}
onKeyDown={(e) => e.key === "Enter" && handleSend()}
placeholder="Type message"
className="flex-1 border p-2 rounded"
/>
<button
onClick={handleSend}
className="bg-green-600 text-white px-4 rounded"
>
Send
</button>
</div>
</div>
);
}
Loading
Loading