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

feat: added Refactored Code That used socket methods #323

Merged
merged 7 commits into from
Sep 30, 2023
Merged
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
12 changes: 6 additions & 6 deletions client/src/components/Anonymous.jsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { useContext, useEffect, useRef, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import PropTypes from 'prop-types';

import { NEW_EVENT_CLOSE, NEW_EVENT_DELETE_MESSAGE, NEW_EVENT_DISPLAY, NEW_EVENT_EDIT_MESSAGE, NEW_EVENT_RECEIVE_MESSAGE } from '../../../constants.json'
// Rsuite
import { Dropdown, IconButton, Tooltip, Whisper } from 'rsuite';
import { Icon } from '@rsuite/icons';
Expand Down Expand Up @@ -41,7 +41,7 @@ const Anonymous = ({ onChatClosed }) => {
const { closeChat } = useChat();
const { setDialog } = useDialog();

socket.on('display', ({ isTyping, chatId }) => {
socket.on(NEW_EVENT_DISPLAY, ({ isTyping, chatId }) => {
// eslint-disable-next-line curly
if (chatId !== currentChatId) return;
if (!isTyping) {
Expand Down Expand Up @@ -72,7 +72,7 @@ const Anonymous = ({ onChatClosed }) => {

socket
.timeout(30000)
.emit('close', currentChatId, (err, chatClosed) => {
.emit(NEW_EVENT_CLOSE, currentChatId, (err, chatClosed) => {
if (err) {
alert('An error occured whiles closing chat.');
setAutoSearchAfterClose(false);
Expand Down Expand Up @@ -122,9 +122,9 @@ const Anonymous = ({ onChatClosed }) => {

useEffect(() => {
const newMessageEvents = [
'receive_message',
'delete_message',
'edit_message',
NEW_EVENT_RECEIVE_MESSAGE,
NEW_EVENT_DELETE_MESSAGE,
NEW_EVENT_EDIT_MESSAGE,
];

function onNewMessage() {
Expand Down
30 changes: 15 additions & 15 deletions client/src/components/BuddyMatcher.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { useChat } from 'src/context/ChatContext';
import { useNavigate } from 'react-router-dom';
import { useNotification } from 'src/lib/notification';
import { useApp } from 'src/context/AppContext';
import { NEW_EVENT_ADDING, NEW_EVENT_CHAT_RESTORE, NEW_EVENT_CLOSE, NEW_EVENT_CREATE_ROOM, NEW_EVENT_INACTIVE, NEW_EVENT_JOIN, NEW_EVENT_JOINED, NEW_EVENT_STOP_SEARCH, NEW_EVENT_STOP_SEARCH_SUCCESS } from '../../../constants.json';

const stoppingSearchLoadingText = <p>Stopping the search</p>;
const BuddyMatcher = () => {
Expand All @@ -28,11 +29,11 @@ const BuddyMatcher = () => {
const startNewSearch = () => {
startSearch();
setLoadingText(defaultLoadingText);
socket.emit('join', { loginId: authState.loginId, email: authState.email });
socket.emit(NEW_EVENT_JOIN, { loginId: authState.loginId, email: authState.email });
};

const handleStopSearch = () => {
socket.emit('stop_search', {
socket.emit(NEW_EVENT_STOP_SEARCH, {
loginId: authState.loginId,
email: authState.email,
});
Expand All @@ -45,7 +46,6 @@ const BuddyMatcher = () => {
isStoppingSearch ? stoppingSearchLoadingText : defaultLoadingText
);
}, [isStoppingSearch]);

useEffect(() => {
if (loadingText === defaultLoadingText) {
timeout = setTimeout(() => {
Expand Down Expand Up @@ -88,7 +88,7 @@ const BuddyMatcher = () => {
socket.connect();
}

socket.on('close', (chatId) => {
socket.on(NEW_EVENT_CLOSE, (chatId) => {
endSearch();
closeChat(chatId);
playNotification('chatClosed');
Expand All @@ -109,20 +109,20 @@ const BuddyMatcher = () => {
socket.on('connect', () => {
// Here server will be informed that user is searching for
// another user
socket.emit('join', { loginId: authState.loginId, email: authState.email });
socket.emit(NEW_EVENT_JOIN, { loginId: authState.loginId, email: authState.email });
});
socket.connected && socket.emit('adding', { userID });
socket.emit('createRoom', `${userID}-in-search`);
socket.connected && socket.emit(NEW_EVENT_ADDING, { userID });
socket.emit(NEW_EVENT_CREATE_ROOM, `${userID}-in-search`);
// From here will get the info from server that user has joined the room

socket.on('joined', ({ roomId, userIds }) => {
socket.on(NEW_EVENT_JOINED, ({ roomId, userIds }) => {
playNotification('buddyPaired');

createChat(roomId, userIds);
endSearch(roomId);
});

socket.on('chat_restore', ({ chats, currentChatId }) => {
socket.on(NEW_EVENT_CHAT_RESTORE, ({ chats, currentChatId }) => {
Object.values(chats).forEach((chat) => {
createChat(
chat.id,
Expand All @@ -134,11 +134,11 @@ const BuddyMatcher = () => {
endSearch(currentChatId);
});

socket.on('inactive', () => {
socket.on(NEW_EVENT_INACTIVE, () => {
closeAllChats();
});

socket.on('stop_search_success', () => {
socket.on(NEW_EVENT_STOP_SEARCH_SUCCESS, () => {
setIsStoppingSearch(false);
endSearch();
navigate('/');
Expand All @@ -147,10 +147,10 @@ const BuddyMatcher = () => {
return () => {
socket
.off('connect')
.off('joined')
.off('chat_restore')
.off('close')
.off('inactive');
.off(NEW_EVENT_JOINED)
.off(NEW_EVENT_CHAT_RESTORE)
.off(NEW_EVENT_CLOSE)
.off(NEW_EVENT_INACTIVE);
socket.disconnect();
};
}, []);
Expand Down
23 changes: 12 additions & 11 deletions client/src/components/Chat.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import useChatUtils from 'src/lib/chat';
import MessageStatus from './MessageStatus';
import listOfBadWordsNotAllowed from 'src/lib/badWords';
import { useNotification } from 'src/lib/notification';
import { NEW_EVENT_DELETE_MESSAGE, NEW_EVENT_EDIT_MESSAGE, NEW_EVENT_RECEIVE_MESSAGE, NEW_EVENT_TYPING } from '../../../constants.json';

let senderId;
const Chat = () => {
Expand Down Expand Up @@ -82,7 +83,7 @@ const Chat = () => {
setEditing({ isediting: false, messageID: null });
socket
.timeout(10000)
.emit('typing', { chatId: app.currentChatId, isTyping: false });
.emit(NEW_EVENT_TYPING, { chatId: app.currentChatId, isTyping: false });
};


Expand Down Expand Up @@ -148,7 +149,7 @@ const Chat = () => {
}

return false;
}
}

return true;
};
Expand Down Expand Up @@ -211,7 +212,7 @@ const Chat = () => {
const handleSubmit = async (e) => {
e.preventDefault();

socket.emit('typing', { chatId: app.currentChatId, isTyping: false });
socket.emit(NEW_EVENT_TYPING, { chatId: app.currentChatId, isTyping: false });
const d = new Date();
let message = inputRef.current.value;

Expand Down Expand Up @@ -314,7 +315,7 @@ const Chat = () => {
if (e.target.value.length > 0) {
socket
.timeout(5000)
.emit('typing', { chatId: app.currentChatId, isTyping: true });
.emit(NEW_EVENT_TYPING, { chatId: app.currentChatId, isTyping: true });
}
}, 500);

Expand Down Expand Up @@ -386,14 +387,14 @@ const Chat = () => {
};

// This is used to recive message form other user.
socket.on('receive_message', newMessageHandler);
socket.on('delete_message', deleteMessageHandler);
socket.on('edit_message', editMessageHandler);
socket.on(NEW_EVENT_RECEIVE_MESSAGE, newMessageHandler);
socket.on(NEW_EVENT_DELETE_MESSAGE, deleteMessageHandler);
socket.on(NEW_EVENT_EDIT_MESSAGE, editMessageHandler);

return () => {
socket.off('receive_message', newMessageHandler);
socket.off('delete_message', deleteMessageHandler);
socket.off('edit_message', editMessageHandler);
socket.off(NEW_EVENT_RECEIVE_MESSAGE, newMessageHandler);
socket.off(NEW_EVENT_DELETE_MESSAGE, deleteMessageHandler);
socket.off(NEW_EVENT_EDIT_MESSAGE, editMessageHandler);
};
}, []);

Expand Down Expand Up @@ -429,7 +430,7 @@ const Chat = () => {
: 'other'
}`}
>
<div className="message">
<div className="message">
<div
className={`content text ${sender.toString() ===
senderId.toString() &&
Expand Down
5 changes: 3 additions & 2 deletions client/src/components/NavBar.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import { SocketContext } from 'context/Context';
// Lib
import { createClassesFromArray } from 'src/lib/utils';
import { useApp } from 'src/context/AppContext';
import { NEW_EVENT_LOGOUT } from '../../../constants.json';

const linkStyle = `md:h-[60px] w-full flex items-center justify-center hover:bg-primary rounded-[15px] `;
const activeStyle = linkStyle + 'bg-primary shadow-2xl';
Expand Down Expand Up @@ -44,12 +45,12 @@ const NavBar = ({ className }) => {
handler: () => {
logOut();
if (socket.disconnected) {
socket.volatile.emit('logout', {
socket.volatile.emit(NEW_EVENT_LOGOUT, {
email: authState.email,
loginId: authState.loginId,
});
} else {
socket.emit('logout', {
socket.emit(NEW_EVENT_LOGOUT, {
email: authState.email,
loginId: authState.loginId,
});
Expand Down
8 changes: 5 additions & 3 deletions client/src/lib/chat.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
* @typedef {import('socket.io-client').Socket} Socket
*/

import { NEW_EVENT_DELETE_MESSAGE, NEW_EVENT_EDIT_MESSAGE, NEW_EVENT_SEND_MESSAGE } from '../../../constants.json';

/**
*
* @param {Socket} socket
Expand All @@ -16,7 +18,7 @@ export default function useChatUtils(socket) {

socket
.timeout(30000)
.emit('send_message', message, (err, sentMessage) => {
.emit(NEW_EVENT_SEND_MESSAGE, message, (err, sentMessage) => {
if (err) {
reject(err);
return;
Expand All @@ -37,7 +39,7 @@ export default function useChatUtils(socket) {
socket
.timeout(30000)
.emit(
'delete_message',
NEW_EVENT_DELETE_MESSAGE,
{ id, chatId },
(err, messageDeleted) => {
if (err) {
Expand All @@ -61,7 +63,7 @@ export default function useChatUtils(socket) {
socket
.timeout(30000)
.emit(
'edit_message',
NEW_EVENT_EDIT_MESSAGE,
{ id, chatId, newMessage },
(err, messageEdited) => {
if (err) {
Expand Down
19 changes: 19 additions & 0 deletions constants.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
{
"NEW_EVENT_CLOSE": "close",
"NEW_EVENT_INACTIVE": "inactive",
"NEW_EVENT_DELETE_MESSAGE": "delete_message",
"NEW_EVENT_EDIT_MESSAGE": "edit_message",
"NEW_EVENT_JOIN": "join",
"NEW_EVENT_JOINED": "joined",
"NEW_EVENT_CHAT_RESTORE": "chat_restore",
"NEW_EVENT_LOGOUT": "logout",
"NEW_EVENT_SEND_MESSAGE": "send_message",
"NEW_EVENT_SEND_FAILED": "send_failed",
"NEW_EVENT_RECEIVE_MESSAGE": "receive_message",
"NEW_EVENT_STOP_SEARCH": "stop_search",
"NEW_EVENT_STOP_SEARCH_SUCCESS": "stop_search_success",
"NEW_EVENT_TYPING": "typing",
"NEW_EVENT_DISPLAY": "display",
"NEW_EVENT_ADDING": "adding",
"NEW_EVENT_CREATE_ROOM": "createRoom"
}
7 changes: 4 additions & 3 deletions server/sockets/close.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
const { NEW_EVENT_CLOSE, NEW_EVENT_INACTIVE } = require("../../constants.json");
const { getActiveUser, chatExists, closeChat } = require("../utils/lib");

module.exports = (socket) => {
socket.on("close", async (chatId, setChatClosed) => {
socket.on(NEW_EVENT_CLOSE, async (chatId, setChatClosed) => {
const user = getActiveUser({
socketId: socket.id,
});
Expand All @@ -14,9 +15,9 @@ module.exports = (socket) => {
const inactiveList = await closeChat(chatId);

setChatClosed(true);
socket.broadcast.to(chatId).emit("close", chatId);
socket.broadcast.to(chatId).emit(NEW_EVENT_CLOSE, chatId);
inactiveList.forEach((emailOrLoginId) => {
socket.broadcast.to(emailOrLoginId).emit("inactive");
socket.broadcast.to(emailOrLoginId).emit(NEW_EVENT_INACTIVE);
});
});
};
5 changes: 3 additions & 2 deletions server/sockets/deleteMessage.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
const { NEW_EVENT_DELETE_MESSAGE } = require("../../constants.json");
const { getActiveUser, removeMessage } = require("../utils/lib");

module.exports = (socket) => {
socket.on(
"delete_message",
NEW_EVENT_DELETE_MESSAGE,
async ({ id: messageId, chatId }, messageWasDeletedSuccessfully) => {
const user = getActiveUser({
socketId: socket.id,
Expand All @@ -17,7 +18,7 @@ module.exports = (socket) => {

socket.broadcast
.to(chatId)
.emit("delete_message", { id: messageId, chatId });
.emit(NEW_EVENT_DELETE_MESSAGE, { id: messageId, chatId });
messageWasDeletedSuccessfully(messageDeleted);
}
);
Expand Down
5 changes: 3 additions & 2 deletions server/sockets/editMessage.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
const { NEW_EVENT_EDIT_MESSAGE } = require("../../constants.json");
const { getActiveUser, editMessage } = require("../utils/lib");

module.exports = (socket) => {
socket.on(
"edit_message",
NEW_EVENT_EDIT_MESSAGE,
async (
{ id: messageId, chatId, newMessage },
messageWasEditedSuccessfully
Expand All @@ -23,7 +24,7 @@ module.exports = (socket) => {

socket.broadcast
.to(chatId)
.emit("edit_message", { id: messageId, chatId, newMessage });
.emit(NEW_EVENT_EDIT_MESSAGE, { id: messageId, chatId, newMessage });
messageWasEditedSuccessfully(messageEditted);
}
);
Expand Down
7 changes: 4 additions & 3 deletions server/sockets/join.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
const { NEW_EVENT_JOIN, NEW_EVENT_JOINED, NEW_EVENT_CHAT_RESTORE } = require('../../constants.json');
const {
isUserActive,
addToWaitingList,
Expand All @@ -18,14 +19,14 @@ const matchMaker = async (io) => {
while (getWaitingUserLen() > 1) {
const chat = await createChat(getRandomPairFromWaitingList());

io.to(chat.id).emit('joined', {
io.to(chat.id).emit(NEW_EVENT_JOINED, {
roomId: chat.id,
userIds: chat.userIds,
});
}
};
module.exports = (io, socket) => {
socket.on('join', ({ loginId, email }) => {
socket.on(NEW_EVENT_JOIN, ({ loginId, email }) => {
/**
* This is necessary to enable us send notifications to users
* using multiple devices to chat
Expand Down Expand Up @@ -61,7 +62,7 @@ module.exports = (io, socket) => {
});

// Then return all chat messages
socket.emit('chat_restore', {
socket.emit(NEW_EVENT_CHAT_RESTORE, {
chats,
currentChatId: user.currentChatId,
});
Expand Down
Loading
Loading