Skip to content

Commit

Permalink
Merge pull request #162 from agiledev-students-spring2024/UpdateSockets
Browse files Browse the repository at this point in the history
Hides messages from conversations you are not a part of
  • Loading branch information
hongsimmon authored Apr 28, 2024
2 parents 81ac39c + 00a97a0 commit 29008ae
Show file tree
Hide file tree
Showing 13 changed files with 94 additions and 63 deletions.
20 changes: 19 additions & 1 deletion back-end/Server.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ io.on('connection_error', (err) => {
console.log(err);
});

/*
io.use((socket, next) => {
const sockUsername = socket.handshake.auth.username;
if(!sockUsername) {
Expand All @@ -29,12 +30,29 @@ io.use((socket, next) => {
console.log(`Socket username: ${socket.username}`);
next();
});
*/

io.on('connection', (socket) => {
console.log(`a user has connected, user id = ${socket.id}`);
/*
const users = [];
for(let [id, sock] of io.of('/').sockets) {
users.push({
userID: id,
username: sock.username,
});
}
socket.emit('users', users);
//console.log(users);
socket.broadcast.emit('user_connected', {
userID: socket.id,
username: socket.username,
self: false,
});
*/
socket.on('chat_message', (msg) => {
io.emit('chat_message', msg);
socket.broadcast.emit('chat_message', msg);
});

socket.on('disconnect', () => {
Expand Down
30 changes: 0 additions & 30 deletions back-end/answers.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,33 +6,3 @@
"rent_min": 300,
"bedtime": "late"
}

{
"Login": {
Username: john123,
Password: qwerasdf
}

Profile: {
Name: John Doe,
Year: Freshman,
Bio: YOLO!
}

Answers: {
Gender: male,
Pets: yes
Guests: no
}

Preferences {
Gender: male,
Pets: no,
Guests: yes
}

Chat: {
Message: “hi i’m john nice to meet you”
}
}
}
1 change: 1 addition & 0 deletions front-end/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
"react-dom": "^18.2.0",
"react-router-dom": "^6.22.2",
"react-scripts": "5.0.1",
"react-scroll": "^1.9.0",
"socket.io-client": "^4.7.5",
"tailwindcss": "^3.4.1",
"web-vitals": "^2.1.4"
Expand Down
5 changes: 1 addition & 4 deletions front-end/src/ChatList.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { Link } from 'react-router-dom'
import "./ChatList.css"
import Header from "./Header"
import profilepic from './ProfilePic.png';
import { socket } from './sockets/ReactSocket';

const Chatlist = props => {
const navigate = useNavigate();
Expand All @@ -13,9 +14,6 @@ const Chatlist = props => {
const [feedback, setFeedback] = useState('')
const [chats, setChats] = useState([]);




const fetchChats = async () => {
try {
const response = await axios.get('http://localhost:3001/chatlist', {
Expand All @@ -34,7 +32,6 @@ const Chatlist = props => {
}
};


useEffect(() => {

fetchChats()
Expand Down
5 changes: 5 additions & 0 deletions front-end/src/ChatPage.css
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,11 @@ button:hover {
color: white
}

.MessageList {
height: 77vh;
overflow-y: scroll;
}

/* Additional styles specific to the survey page */
/* You may need to customize or add more styles based on your design requirements */

Expand Down
78 changes: 57 additions & 21 deletions front-end/src/ChatPage.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React, { useEffect, useState } from 'react';
import React, { useEffect, useRef, useState } from 'react';
import { Link } from 'react-router-dom';
import './ChatPage.css';
import axios from 'axios'
Expand All @@ -7,6 +7,7 @@ import { socket } from './sockets/ReactSocket';
import { ChatBoxSender, ChatBoxReceiver } from './sockets/ChatBox';
import InputTxt from './sockets/InputTxt';
import { useLocation } from 'react-router-dom';
import {animateScroll} from 'react-scroll'

function ChatPage() {
const location = useLocation(); //for extracting receiver username
Expand All @@ -16,6 +17,9 @@ function ChatPage() {
const [chats, setChats] = useState([]); //stores ongoing messages
const [old_messages, setOldMessages] = useState([]); // New state for storing old messages

//const [userList, setUserList] = useState([]);
//let selectedUser = { otherperson_username, chats: []};

useEffect(() => {
function onConnect() {
//setIsConnected(true);
Expand All @@ -33,7 +37,15 @@ function ChatPage() {
socket.off('disconnect', onDisconnect);
}
}, []);
/*
socket.on('users', (users) => {
console.log(`User list: ${users}`);
});
socket.on('user_connected', (newUser) => {
setUserList([...userList, newUser]);
});
*/
useEffect(() => {
getUser();

Expand All @@ -54,20 +66,32 @@ function ChatPage() {
.catch(error => {
console.error('Error fetching messages:', error);
})
scrollToBottom();
}, []);

//listen for chat_message event from the socket
useEffect(() => {
console.log('Listening for chat messages...');
socket.on('chat_message', (senderMsg) => {
console.log("Message received");
setChats(senderMsg);
})
});
});

//This hook is so you can view the old_messages array once it is populated
useEffect(() => {
console.log("Old messages array updated:", old_messages);
scrollToBottom();
}, [old_messages]);

useEffect(() => {
scrollToBottom();
}, [chats])

function scrollToBottom() {
animateScroll.scrollToBottom({containerId: "msgContainer"});
}

//sends the message to the backend
function sendToSocket(msg) {
socket.emit('chat_message', msg);
Expand All @@ -91,11 +115,14 @@ function ChatPage() {
//the post request to the backend with the new message should probably go here
function sendMessage(msg) {
const msgTime = new Date().toLocaleTimeString();
const newMsg = { ...msg, user, msgTime };
console.log(`Sending message as ${user}`);
const otherUser = otherperson_username;
const newMsg = { ...msg, user, msgTime, otherUser};
//console.log(`Sending message as ${user}`);
setChats([...chats, newMsg]);
sendToSocket([...chats, newMsg]);
scrollToBottom();

console.log(`Other user = ${newMsg.otherUser}`);
let messagestring = newMsg.message;
const currentTime = new Date().toISOString(); //This should be formatted eventually (go see what it looks like in the database messages collection)
const msg_post = {
Expand All @@ -120,30 +147,39 @@ function ChatPage() {
//displays the chat messages to the user
function ChatExchange() {
return chats.map((chat, index) => {
if (chat.user === user) return <ChatBoxSender key={index} message={chat.message} user={chat.user} time={chat.msgTime} />
return <ChatBoxReceiver key={index} message={chat.message} user={chat.user} time={chat.msgTime} />
//console.log(`Other user in chat: ${chat.otherUser}`);
if (chat.user === user && chat.otherUser === otherperson_username) {
return <ChatBoxSender key={index} message={chat.message} user={chat.user} time={chat.msgTime} />
}
else if(chat.otherUser === user && chat.user === otherperson_username) {
return <ChatBoxReceiver key={index} message={chat.message} user={chat.user} time={chat.msgTime} />
}
else {
return
}
});
}

return (
<div>
<Header />
<h3>Your conversation with {otherperson_username}</h3>
{old_messages.map((message, index) => {
//for parsing the timestamp
const timestamp = new Date(message.timestamp);
//format timestamp for month, day, hour, and minute
const formattedTimestamp = `${(timestamp.getMonth() + 1)}/${timestamp.getDate()} ${timestamp.getHours()}:${(timestamp.getMinutes() < 10 ? '0' : '') + timestamp.getMinutes()}`;

//displays message histroy to look like normal messages
if (message.sender === user) {
return <ChatBoxSender key={index} message={message.messagetext} user={message.sender} time={formattedTimestamp} />
}else {
return <ChatBoxReceiver key={index} message={message.messagetext} user={message.sender} time={formattedTimestamp} />
}
})}
<ChatExchange />

<div className="MessageList" id="msgContainer">
{old_messages.map((message, index) => {
//for parsing the timestamp
const timestamp = new Date(message.timestamp);
//format timestamp for month, day, hour, and minute
const formattedTimestamp = `${(timestamp.getMonth() + 1)}/${timestamp.getDate()} ${timestamp.getHours()}:${(timestamp.getMinutes() < 10 ? '0' : '') + timestamp.getMinutes()}`;

//displays message histroy to look like normal messages
if (message.sender === user) {
return <ChatBoxSender key={index} message={message.messagetext} user={message.sender} time={formattedTimestamp} />
}else {
return <ChatBoxReceiver key={index} message={message.messagetext} user={message.sender} time={formattedTimestamp} />
}
})}
<ChatExchange />
</div>
<InputTxt sendMessage={sendMessage} />
</div>
);
Expand Down
4 changes: 2 additions & 2 deletions front-end/src/LoginForm.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,8 @@ function LoginForm() {
console.log('Login successful:', data);

//connect the chat socket and register its username
socket.auth = { username };
socket.connect();
//socket.auth = { username };
//socket.connect();

localStorage.setItem('token', data.token); // Save the token to localStorage
navigate('/matches'); // Navigate to the 'matches' route on successful login
Expand Down
2 changes: 1 addition & 1 deletion front-end/src/Profile.js
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ function Profile() {
const handleLogout = () => {
console.log("Logging out...");
localStorage.removeItem('token');
socket.disconnect(); //disconnect the socket that was in use
//socket.disconnect(); //disconnect the socket that was in use
navigate('/login', { replace: true });
};

Expand Down
4 changes: 2 additions & 2 deletions front-end/src/RegistrationForm.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,8 @@ function RegistrationForm() {
setErrorMessage(data.message || 'Failed to sign up.');
} else {
//connect chat socket and register username
socket.auth = { username };
socket.connect();
//socket.auth = { username };
//socket.connect();

// On successful registration, navigate to the survey page
console.log('Registration successful:', data);
Expand Down
2 changes: 1 addition & 1 deletion front-end/src/Survey.css
Original file line number Diff line number Diff line change
Expand Up @@ -53,4 +53,4 @@ button:hover {
padding: 1rem;
background-color: #57068C;
color: white;
}
}
2 changes: 2 additions & 0 deletions front-end/src/sockets/ChatBox.css
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,13 @@
.SenderBox {
display: flex;
justify-content: flex-end;
padding-right: 5px;
}

.ReceiverBox {
display: flex;
justify-content: flex-start;
padding-left: 5px;
}

.SenderChat {
Expand Down
2 changes: 2 additions & 0 deletions front-end/src/sockets/InputTxt.css
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
.InputContainer {
position: sticky;
bottom: 5px;
display: flex;
justify-content: space-evenly;
align-items: center;
Expand Down
2 changes: 1 addition & 1 deletion front-end/src/sockets/ReactSocket.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
import { io } from 'socket.io-client'

export const socket = io('http://localhost:3002', {autoConnect: false});
export const socket = io('http://localhost:3002');

0 comments on commit 29008ae

Please sign in to comment.