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

Feature/message storing #80

Closed
wants to merge 4 commits into from
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
36 changes: 34 additions & 2 deletions client/src/app/messages/Chatlog.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,12 @@ const Chatlog = () => {
const { selectedUserId } = useUserContext(); // Access the selectedUserId from context
const { username } = useUserContext();
const [currentUserId, setCurrentUserId] = useState<string>("");
const [conversationId, setConversationId] = useState<string>("");
const chatContainerRef = useRef<HTMLDivElement>(null); // Ref to the chat container

const fetchUserData = async () => {
try {
const response = await backendConnection.get("users/self", { withCredentials: true })
const response = await backendConnection.get("user/self", { withCredentials: true })
.then((res) => res.data)
.then((data) => {
setCurrentUserId(data);
Expand All @@ -26,11 +27,39 @@ const Chatlog = () => {
}
};

// Load messages based on conversation ID
const loadMessages = async (conversationId: string) => {
try {
// Get conversation's messages from backend
const response = await backendConnection.get(`/api/messages/${conversationId}`);

// Create array of the retrieved messages
const messages = response.data.map((msg:any) => ({
sender: msg.user_id === currentUserId ? "user" : "other",
text: msg.message,
timestamp: new Date(msg.timestamp).toLocaleTimeString,
}));
setMessages(messages);
} catch (error){
console.error("Error loading messages", error);
}
}

useEffect(() => {
if (selectedUserId) {
// Create the conversation ID (same logic as backend)
const newConversationId = currentUserId > selectedUserId
? `${currentUserId}${selectedUserId}`
: `${selectedUserId}${currentUserId}`;

setConversationId(newConversationId);

// Emit 'join_chat' event to the server
socket.emit("join_chat", currentUserId, selectedUserId);

// Call load messages to load the messages associated with the conversation ID
loadMessages(newConversationId);

// Listen for new messages
socket.on("receive_message", (data) => {
if (data.user_id !== currentUserId) {
Expand All @@ -48,9 +77,12 @@ const Chatlog = () => {
socket.off("receive_message");
};
}
fetchUserData();
}, [selectedUserId, currentUserId]);


useEffect(() => {
fetchUserData();
}, []);
// Scroll to the newest message when `messages` updates
useEffect(() => {
if (chatContainerRef.current) {
Expand Down
2 changes: 1 addition & 1 deletion client/src/app/messages/RecentMessages.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ const RecentMessages: React.FC = () => {

// For now the "recent messages" are jsut going to be all users until we can estabilsh saving messages in database
const fetchRecentMessages = async () => {
const response = await backendConnection.get('users/all', { withCredentials: true })
const response = await backendConnection.get('user/all', { withCredentials: true })
.then((res) => res.data)
.then((data) => {
console.log("users")
Expand Down
21 changes: 8 additions & 13 deletions server/bin/www.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ const app_1 = __importDefault(require("../app"));
const debug_1 = __importDefault(require("debug"));
const http_1 = __importDefault(require("http"));
const socket_io_1 = require("socket.io");
const Message_1 = __importDefault(require("../models/Message"));
/**
* Get port from environment and store in Express.
*/
Expand All @@ -31,19 +32,6 @@ app_1.default.set('port', port);
*/
const server = http_1.default.createServer(app_1.default);
exports.server = server;
/**
* Connect to MongoDB
*/
// const mongoURI = process.env.MONGO_URI;
// if (!mongoURI) {
// console.error('MONGO_URI is not defined in the environment variables.');
// process.exit(1); // Exit the process with a failure
// }
// mongoose.connect(mongoURI).then(() => {
// console.log('Connected to MongoDB');
// }).catch((err) => {
// console.error('Error connecting to MongoDB:', err);
// });
/**
* Create SocketIO server
*/
Expand Down Expand Up @@ -72,11 +60,18 @@ io.on('connection', (socket) => {
});
socket.on('send_message', (data) => __awaiter(void 0, void 0, void 0, function* () {
const { message, user_id } = data;
const newMessage = new Message_1.default({
message: message,
user_id: user_id,
timestamp: new Date(),
conversation_id: conversation_id
});
try {
// Broadcast the message to the unique chat room
io.to(conversation_id).emit('receive_message', { message, user_id });
// Optionally, acknowledge the sender that the message was sent
socket.emit('message_sent', { success: true, message });
yield newMessage.save();
}
catch (error) {
console.error('Error sending message:', error);
Expand Down
29 changes: 10 additions & 19 deletions server/bin/www.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import debug from 'debug';
import http from 'http';
import { Socket, Server} from 'socket.io';
import mongoose from 'mongoose';
import { Message } from '../models/messageSchema';
import Message from '../models/Message';
import { v4 as uuidv4} from 'uuid';

/**
Expand All @@ -24,22 +24,6 @@ app.set('port', port);
*/

const server = http.createServer(app);
/**
* Connect to MongoDB
*/

// const mongoURI = process.env.MONGO_URI;

// if (!mongoURI) {
// console.error('MONGO_URI is not defined in the environment variables.');
// process.exit(1); // Exit the process with a failure
// }

// mongoose.connect(mongoURI).then(() => {
// console.log('Connected to MongoDB');
// }).catch((err) => {
// console.error('Error connecting to MongoDB:', err);
// });

/**
* Create SocketIO server
Expand Down Expand Up @@ -77,13 +61,20 @@ io.on('connection', (socket: Socket) => {

socket.on('send_message', async (data) => {
const { message, user_id } = data;

const newMessage = new Message({
message: message,
user_id: user_id,
timestamp: new Date(),
conversation_id: conversation_id
})
try {
// Broadcast the message to the unique chat room
// Broadcast the message to the unique chat room
io.to(conversation_id).emit('receive_message', { message, user_id });

// Optionally, acknowledge the sender that the message was sent
socket.emit('message_sent', { success: true, message });

await newMessage.save();
} catch (error) {
console.error('Error sending message:', error);
socket.emit('error_message', { error: 'Failed to send message' });
Expand Down
24 changes: 7 additions & 17 deletions server/models/Message.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,23 +15,13 @@ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const mongoose_1 = __importStar(require("mongoose"));
const messageSchema = new mongoose_1.Schema({
Expand Down
24 changes: 7 additions & 17 deletions server/models/Post.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,23 +15,13 @@ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const mongoose_1 = __importStar(require("mongoose"));
const postSchema = new mongoose_1.Schema({
Expand Down
4 changes: 1 addition & 3 deletions server/routes/post.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,6 @@ const express_1 = __importDefault(require("express"));
const Post_1 = __importDefault(require("../models/Post"));
const User_1 = require("../models/User");
const mongoose_1 = __importDefault(require("mongoose"));
const User_1 = require("../models/User");
const mongoose_1 = __importDefault(require("mongoose"));
const router = express_1.default.Router();
/**
* @route POST /
Expand Down Expand Up @@ -59,7 +57,6 @@ router.post("/", (req, res) => __awaiter(void 0, void 0, void 0, function* () {
cost,
numStores,
author: req.user.user_id,
author: req.user.user_id,
available_stores,
image,
tags,
Expand Down Expand Up @@ -316,4 +313,5 @@ router.patch("/like", (req, res) => __awaiter(void 0, void 0, void 0, function*
res.status(500).json({ error: "Error liking post" });
}
}));
// Export the router
exports.default = router;
17 changes: 6 additions & 11 deletions server/routes/user.js
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,6 @@ router.post('/follow', (req, res) => __awaiter(void 0, void 0, void 0, function*
res.status(500).json({ message: 'Following error occurred:', err });
}
}));

/**
* @route PATCH /profile
* @desc Edit profile
Expand All @@ -146,6 +145,7 @@ router.post('/follow', (req, res) => __awaiter(void 0, void 0, void 0, function*
*
* Responses:
* - 200: The profile was updated successfully.
* - 400: Username was taken.
* - 401: Unauthorized.
* - 404: The user was not found.
* - 500: Internal server error.
Expand All @@ -170,16 +170,11 @@ router.patch('/profile', (req, res) => __awaiter(void 0, void 0, void 0, functio
return;
}
if (tags) {
if (user.tags.includes(tags)) {
yield User_1.User.findOneAndUpdate({ user_id: user_id }, {
$pull: { tags: tags }
}, { new: true });
}
else {
yield User_1.User.findOneAndUpdate({ user_id: user_id }, {
$push: { tags: { $each: [tags] } }
}, { new: true });
if (!Array.isArray(tags)) {
res.status(400).json({ message: 'Tags must be an array' });
return;
}
yield User_1.User.findOneAndUpdate({ user_id: user_id }, { $set: { tags: tags } }, { new: true });
}
const updatedUser = yield User_1.User.findOneAndUpdate({ user_id: user_id }, {
$set: {
Expand Down Expand Up @@ -212,7 +207,7 @@ router.patch('/profile', (req, res) => __awaiter(void 0, void 0, void 0, functio
*/
router.get('/self', (req, res, next) => __awaiter(void 0, void 0, void 0, function* () {
if (req.user) {
const user = yield User_1.User.findOne({ user_id: req.user.user_id });
const user = req.user.user_id;
res.status(200).json(user);
}
else {
Expand Down
18 changes: 9 additions & 9 deletions server/routes/user.ts
Original file line number Diff line number Diff line change
Expand Up @@ -172,15 +172,15 @@ router.patch('/profile', async (req, res) => {
}

if (tags){
if(user.tags.includes(tags)){
await User.findOneAndUpdate({user_id: user_id},{
$pull: {tags: tags}
}, {new: true});
} else{
await User.findOneAndUpdate({user_id: user_id},{
$push: {tags: {$each: [tags]}}
}, {new: true})
if (!Array.isArray(tags)) {
res.status(400).json({message: 'Tags must be an array'});
return;
}
await User.findOneAndUpdate(
{user_id: user_id},
{ $set: { tags: tags }},
{new: true}
);
}
const updatedUser = await User.findOneAndUpdate({user_id: user_id},{
$set: {
Expand Down Expand Up @@ -215,7 +215,7 @@ router.patch('/profile', async (req, res) => {

router.get('/self', async (req: Request, res: Response, next: NextFunction) => {
if (req.user) {
const user = await User.findOne({ user_id: (req.user as IUser).user_id});
const user = (req.user as IUser).user_id;
res.status(200).json(user);
} else {
res.status(401).send('Unauthorized');
Expand Down