Project Ready

This commit is contained in:
Jyotirmoy Bandyopadhayaya 2021-11-08 14:31:15 +05:30
commit 48745b5d7a
33 changed files with 77868 additions and 0 deletions

21
LICENSE Normal file
View File

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2021 Nithin Kumar
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

27
README.md Normal file
View File

@ -0,0 +1,27 @@
# Realtime-chat-app-using-nodejs
![Socket.io](https://img.shields.io/badge/Socket.io-v3.0.1-green.svg)
![Javascript](https://img.shields.io/badge/NodeJs-v12.15.0-yellow.svg)
![Javascript](https://img.shields.io/badge/ReactJs-v17.0.1-orange.svg)
<br>
<br>
A simple Real-time chat application using Nodejs and Socket.io. Here users can create rooms and share the link with others to invite them.
<b>Demo: </b> https://chatapp-in.herokuapp.com/
<br>
<h3>Pre-Requisites</h3>
<ul>
<li><b>Socket.io: </b>A javascipt library used for real time communication between services</li>
<li><b>NodeJs: </b>Used for backend</li>
<li><b>ReactJS: </b>Used for frontend</li>
</ul>
<h3>Installation</h3>
<ul>
<li>Clone the entire repository to a new folder</li>
<li>Open the terminal in the above folder and run the command <b>npm install</b>. This will install all the required dependencies</li>
<li>Now Enter the command <b>npm start</b> to start the server</li>
<li>To start the client server go to <b>client/</b> directory and type the command <b>npm start</b></li>
</ul>
<h3>Images</h3>
<img src = "https://res.cloudinary.com/nithin/image/upload/v1610686040/Screenshot_355_qzp5j0.png" alt = "signIn page">
<img src = "https://res.cloudinary.com/nithin/image/upload/v1610686041/Screenshot_354_msf9yx.png" alt = "Chat application page">

23
client/.gitignore vendored Normal file
View File

@ -0,0 +1,23 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.js
# testing
/coverage
# production
/build
# misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local
npm-debug.log*
yarn-debug.log*
yarn-error.log*

70
client/README.md Normal file
View File

@ -0,0 +1,70 @@
# Getting Started with Create React App
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
## Available Scripts
In the project directory, you can run:
### `npm start`
Runs the app in the development mode.\
Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
The page will reload if you make edits.\
You will also see any lint errors in the console.
### `npm test`
Launches the test runner in the interactive watch mode.\
See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
### `npm run build`
Builds the app for production to the `build` folder.\
It correctly bundles React in production mode and optimizes the build for the best performance.
The build is minified and the filenames include the hashes.\
Your app is ready to be deployed!
See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
### `npm run eject`
**Note: this is a one-way operation. Once you `eject`, you cant go back!**
If you arent satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point youre on your own.
You dont have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldnt feel obligated to use this feature. However we understand that this tool wouldnt be useful if you couldnt customize it when you are ready for it.
## Learn More
You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
To learn React, check out the [React documentation](https://reactjs.org/).
### Code Splitting
This section has moved here: [https://facebook.github.io/create-react-app/docs/code-splitting](https://facebook.github.io/create-react-app/docs/code-splitting)
### Analyzing the Bundle Size
This section has moved here: [https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size](https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size)
### Making a Progressive Web App
This section has moved here: [https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app](https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app)
### Advanced Configuration
This section has moved here: [https://facebook.github.io/create-react-app/docs/advanced-configuration](https://facebook.github.io/create-react-app/docs/advanced-configuration)
### Deployment
This section has moved here: [https://facebook.github.io/create-react-app/docs/deployment](https://facebook.github.io/create-react-app/docs/deployment)
### `npm run build` fails to minify
This section has moved here: [https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify](https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify)

2
client/debug.log Normal file
View File

@ -0,0 +1,2 @@
[1115/192150.308:ERROR:directory_reader_win.cc(43)] FindFirstFile: The system cannot find the path specified. (0x3)
[1116/202734.362:ERROR:directory_reader_win.cc(43)] FindFirstFile: The system cannot find the path specified. (0x3)

37862
client/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

44
client/package.json Normal file
View File

@ -0,0 +1,44 @@
{
"name": "client",
"version": "0.1.0",
"private": true,
"dependencies": {
"@testing-library/jest-dom": "^5.11.6",
"@testing-library/react": "^11.1.2",
"@testing-library/user-event": "^12.2.2",
"query-string": "^6.13.7",
"react": "^17.0.1",
"react-dom": "^17.0.1",
"react-emoji": "^0.5.0",
"react-router": "^5.2.0",
"react-router-dom": "^5.2.0",
"react-scripts": "4.0.0",
"react-scroll-to-bottom": "^4.0.0",
"socket.io-client": "^3.0.1",
"web-vitals": "^0.2.4"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}

BIN
client/public/favicon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

43
client/public/index.html Normal file
View File

@ -0,0 +1,43 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="Bravo68web's IRC created using Express and Socket.io"
/>
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
<!--
manifest.json provides metadata used when your web app is installed on a
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
-->
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<!--
Notice the use of %PUBLIC_URL% in the tags above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>Bravo68web's IRC</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
</body>
</html>

BIN
client/public/logo192.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.2 KiB

BIN
client/public/logo512.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.4 KiB

View File

@ -0,0 +1,25 @@
{
"short_name": "bravo68web-irc",
"name": "Bravo68web's IRC",
"icons": [
{
"src": "favicon.ico",
"sizes": "64x64 32x32 24x24 16x16",
"type": "image/x-icon"
},
{
"src": "logo192.png",
"type": "image/png",
"sizes": "192x192"
},
{
"src": "logo512.png",
"type": "image/png",
"sizes": "512x512"
}
],
"start_url": ".",
"display": "standalone",
"theme_color": "#000000",
"background_color": "#ffffff"
}

3
client/public/robots.txt Normal file
View File

@ -0,0 +1,3 @@
# https://www.robotstxt.org/robotstxt.html
User-agent: *
Disallow:

13
client/src/App.js Normal file
View File

@ -0,0 +1,13 @@
import React from 'react';
import { BrowserRouter, Route } from 'react-router-dom';
import Join from './components/Join';
import Chat from './components/Chat';
const App = () => (
<BrowserRouter>
<Route path="/" exact component={Join} />
<Route path="/chat" component={Chat} />
</BrowserRouter>
);
export default App;

View File

@ -0,0 +1,79 @@
import React, { useEffect, useState } from 'react';
import { useHistory } from 'react-router-dom';
import queryString from 'query-string';
import io from 'socket.io-client';
import InfoBar from './InfoBar';
import Input from './Input';
import Messages from './Messages';
import TextContainer from './TextContainer';
import '../index.css';
let socket;
const Chat = ({ location }) => {
const [name, setName] = useState('');
const [room, setRoom] = useState('');
const [message, setMessage] = useState('');
const [messages, setMessages] = useState([]);
const [users, setUsers] = useState('');
const history = useHistory();
let socketUrl = "http://localhost:5000/";
if (process.env.NODE_ENV !== "production") {
socketUrl = "https://irc.bravo68web.me/";
} else if (process.env.NODE_ENV === "production") {
socketUrl = "http://localhost:5000/";
}
useEffect(() => {
const { name, room } = queryString.parse(location.search);
setName(name);
setRoom(room);
socket = io(socketUrl, {
transports: ["websocket", "polling", "flashsocket"],
});
socket.emit("USER_ADDED", { name, room }, (err) => {
if (err) {
alert(err);
history.push("/");
}
});
return () => {
socket.emit("disconnected");
};
}, [socketUrl, location.search]);
useEffect(() => {
socket.on("MESSAGE", (message) => {
setMessages([...messages, message]);
});
socket.on("ROOM_DATA", ({ users }) => {
setUsers(users);
});
}, [messages]);
const sendMessage = (e) => {
e.preventDefault();
if (message) {
socket.emit("NEW_MESSAGE", message, () => setMessage(""));
}
};
return (
<div className = "outerContainer">
<div className = "container">
<InfoBar room = {room}/>
<Messages messages = {messages} name = {name}/>
<Input message = {message} setMessage = {setMessage} sendMessage = {sendMessage} />
</div>
<TextContainer users = {users} />
</div>
);
}
export default Chat;

View File

@ -0,0 +1,21 @@
import '../index.css';
import React from 'react';
import onlineIcon from '../icons/onlineIcon.png';
import closeIcon from '../icons/closeIcon.png';
const InfoBar = ({ room }) => {
return (
<div className = "infoBar">
<div className = "leftInnerContainer">
<img className="onlineIcon" src={onlineIcon} alt="online icon" />
<h3>{room}</h3>
</div>
<div className = "rightInnerContainer">
<a href="/"><img src={closeIcon} alt="close icon" /></a>
</div>
</div>
);
}
export default InfoBar;

View File

@ -0,0 +1,20 @@
import '../index.css';
import React from 'react';
const Input = ({ message, setMessage, sendMessage }) => {
return (
<form className = "form">
<input className = "input"
type = "text"
placeholder = "Type to send a message"
value = {message}
onChange = {(e) => setMessage(e.target.value)}
onKeyPress = {(e) => e.key === 'Enter' ? sendMessage(e) : null}
/>
<button className = "sendButton" onClick = {(e) => sendMessage(e)}>Send</button>
</form>
);
}
export default Input;

View File

@ -0,0 +1,45 @@
import React, { useState } from 'react';
import { Link } from 'react-router-dom';
import '../index.css';
import ircIcon from "../icons/irc-icon.png";
const Join = () => {
const [name, setName] = useState("");
const [room, setRoom] = useState("");
return (
<div className="joinOuterContainer">
<div className="joinInnerContainer">
<h1 className="heading">Join a #Room</h1>
<img src={ircIcon} alt="IRC Icon" height="150px" width="150px"></img>
<div>
<input
type="text"
placeholder="Name.."
className="joinInput"
onChange={(e) => setName(e.target.value)}
autoFocus
/>
</div>
<div>
<input
type="text"
placeholder="#Room.."
className="joinInput mt-20"
onChange={(e) => setRoom(e.target.value)}
/>
</div>
<Link
onClick={(e) => (!name || !room ? e.preventDefault() : null)}
to={`/chat/?name=${name}&room=${room}`}
>
<button className="button mt-20" type="submit">
Sign In
</button>
</Link>
</div>
</div>
);
};
export default Join;

View File

@ -0,0 +1,41 @@
import { React } from "react";
import '../index.css';
import ReactEmoji from 'react-emoji';
const Message = ({ message : { user, text }, name }) => {
let isMessageSentByCurrentUser = false;
let isSentByAdmin = false;
const trimmedName = name.trim().toLowerCase();
if (user === trimmedName) {
isMessageSentByCurrentUser = true;
}
if (user === 'admin') {
isSentByAdmin = true;
}
return (
!isMessageSentByCurrentUser ? isSentByAdmin ? (
<div>
<b><p style = {{textAlign: "center", color: "red"}}>{text}</p></b>
</div>
) : (
<div className = "messageContainer justifyStart">
<p className = "sentText pl-10">{user}</p>
<div className = "messageBox backgroundLight">
<p className = "messageText colorDark">{ReactEmoji.emojify(text)}</p>
</div>
</div>
) :(
<div className = "messageContainer justifyEnd">
<p className = "sentText pr-10">{name}</p>
<div className = "messageBox backgroundBlue">
<p className = "messageText colorWhite">{ReactEmoji.emojify(text)}</p>
</div>
</div>
)
)
}
export default Message;

View File

@ -0,0 +1,12 @@
import { React } from "react";
import '../index.css';
import ScrollToBottom from 'react-scroll-to-bottom';
import Message from './Message';
const Messages = ({ messages, name }) => (
<ScrollToBottom className = "messages">
{messages.map((message, index) => <div key = {index}><Message message = {message} name = {name} /></div>)}
</ScrollToBottom>
);
export default Messages;

View File

@ -0,0 +1,40 @@
import React from 'react';
import onlineIcon from '../icons/onlineIcon.png';
import ircIcon from "../icons/irc-icon.png";
import "../index.css";
const TextContainer = ({ users }) => (
<div className="textContainer">
<div>
<h1>
Bravo68web's IRC{" "}
<span role="img" aria-label="emoji">
💬
</span>
</h1>
{/*<h2>Created with React, Express, Node and Socket.IO <span role="img" aria-label="emoji"></span></h2>
<h2>Try it out right now! <span role="img" aria-label="emoji"></span></h2>*/}
</div>
{users ? (
<div>
<h1>Active Members 🌍</h1>
<div className="activeContainer">
<h2>
{users.map(({ name }) => (
<div key={name} className="activeItem">
<img alt="Online Icon" src={onlineIcon} />
{name}
</div>
))}
</h2>
<br />
{/* <img src={ircIcon} alt="IRC Icon" height="200px" width="200px"></img> */}
</div>
</div>
) : null}
</div>
);
export default TextContainer;

Binary file not shown.

After

Width:  |  Height:  |  Size: 182 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 146 B

293
client/src/index.css Normal file
View File

@ -0,0 +1,293 @@
/*Chat Component */
.outerContainer {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
background-color: #1A1A1D;
}
.container {
display: flex;
flex-direction: column;
justify-content: space-between;
background: #FFFFFF;
border-radius: 8px;
height: 60%;
width: 35%;
}
@media (min-width: 320px) and (max-width: 480px) {
.outerContainer {
height: 100%;
}
.container {
width: 100%;
height: 100%;
}
}
@media (min-width: 480px) and (max-width: 1200px) {
.container {
width: 60%;
}
}
/*Join Component */
html, body {
font-family: 'Roboto', sans-serif;
padding: 0;
margin: 0;
}
#root {
height: 100vh;
}
* {
box-sizing: border-box;
}
.joinOuterContainer {
display: flex;
justify-content: center;
text-align: center;
height: 100vh;
align-items: center;
background-color: #1A1A1D;
}
.joinInnerContainer {
width: 20%;
}
.joinInput {
border-radius: 0;
padding: 15px 20px;
width: 100%;
}
.heading {
color: white;
font-size: 2.5em;
padding-bottom: 10px;
border-bottom: 2px solid white;
}
.button {
color: #fff !important;
text-transform: uppercase;
text-decoration: none;
background: #2979FF;
padding: 20px;
border-radius: 5px;
display: inline-block;
border: none;
width: 100%;
cursor: pointer;
}
.button:hover {
opacity: 0.6;
color: #FFFFFF !important;
transform: scale(1.1);
}
.mt-20 {
margin-top: 20px;
}
@media (min-width: 320px) and (max-width: 480px) {
.joinOuterContainer {
height: 100%;
}
.joinInnerContainer {
width: 90%;
}
}
button:focus {
outline: 0;
}
/* InfoBar */
.infoBar {
display: flex;
align-items: center;
justify-content: space-between;
background: #ffb429;
border-radius: 4px 4px 0 0;
height: 60px;
width: 100%;
}
.leftInnerContainer {
flex: 0.5;
display: flex;
align-items: center;
margin-left: 5%;
color: white;
}
.rightInnerContainer {
display: flex;
flex: 0.5;
justify-content: flex-end;
margin-right: 5%;
}
.onlineIcon {
margin-right: 5%;
}
/* Input */
.form {
display: flex;
border-top: 2px solid #D3D3D3;
}
.input {
border: none;
border-radius: 0;
padding: 5%;
width: 80%;
font-size: 1.2em;
}
input:focus, textarea:focus, select:focus{
outline: none;
}
.sendButton {
color: #fff !important;
text-transform: uppercase;
text-decoration: none;
background: #7d20f7;
padding: 20px;
display: inline-block;
border: none;
width: 20%;
}
.sendButton:hover {
cursor: pointer;
}
/* Messages */
.messages {
padding: 5% 0;
overflow: auto;
flex: auto;
}
/* Message */
.messageBox {
background: #F3F3F3;
border-radius: 20px;
padding: 0px 20px;
color: white;
display: inline-block;
max-width: 80%;
}
.messageText {
width: 100%;
letter-spacing: 0;
float: left;
font-size: 1.1em;
word-wrap: break-word;
}
.messageText img {
vertical-align: middle;
}
.messageContainer {
display: flex;
justify-content: flex-end;
padding: 0 5%;
margin-top: 3px;
}
.sentText {
display: flex;
align-items: center;
font-family: Helvetica;
color: #828282;
letter-spacing: 0.3px;
}
.pl-10 {
padding-left: 10px;
}
.pr-10 {
padding-right: 10px;
}
.justifyStart {
justify-content: flex-start;
}
.justifyEnd {
justify-content: flex-end;
}
.colorWhite {
color: white;
}
.colorDark {
color: #353535;
}
.colorRed {
color: red;
}
.backgroundBlue {
background: #2979FF;
}
.backgroundLight {
background: #F3F3F3;
}
/* Text Container */
.textContainer {
display: flex;
flex-direction: column;
margin-left: 100px;
color: white;
height: 60%;
justify-content: space-between;
}
.activeContainer {
display: flex;
align-items: center;
margin-bottom: 50%;
}
.activeItem {
display: flex;
align-items: center;
}
.activeContainer img {
padding-right: 10px;
}
.textContainer h1 {
margin-bottom: 0px;
}
@media (min-width: 320px) and (max-width: 1200px) {
.textContainer {
display: none;
}
}

5
client/src/index.js Normal file
View File

@ -0,0 +1,5 @@
import React from 'react';
import ReactDom from 'react-dom';
import App from './App';
ReactDom.render(<App />, document.querySelector('#root'));

1
server/.env Normal file
View File

@ -0,0 +1 @@
NODE_ENV=production

23
server/.gitignore vendored Normal file
View File

@ -0,0 +1,23 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.js
# testing
/coverage
# production
/build
# misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local
npm-debug.log*
yarn-debug.log*
yarn-error.log*

95
server/index.js Normal file
View File

@ -0,0 +1,95 @@
const express = require("express");
const socketIo = require("socket.io");
const http = require("http");
const router = require("./router");
var path = require("path");
const cors = require("cors");
const { addUser, removeUser, getAllUsersInRoom, getUser } = require("./users");
const { use } = require("./router");
require("dotenv").config();
const PORT = process.env.PORT || 5000;
const app = express();
const server = http.createServer(app);
const io = socketIo(server);
if (process.env.NODE_ENV === "production") {
app.use(express.static("../client/build"));
app.get("*", (req, res) => {
res.sendFile(
path.resolve(__dirname, "..", "client", "build", "index.html"),
path.resolve(__dirname, "..", "client", "build", "favicon.ico")
);
});
}
app.use(router);
app.use(cors());
io.on("connection", (socket) => {
console.log(`New user connected with id: ${socket.id}`);
socket.on("USER_ADDED", ({ name, room }, callback) => {
const { err, user } = addUser({ id: socket.id, name, room });
if (err) {
return callback(err);
}
socket.emit("MESSAGE", {
user: "admin",
text: `Welcome to the room #${user.room}, ${user.name}!!`,
});
socket.broadcast.to(user.room).emit("MESSAGE", {
user: "admin",
text: `${user.name} has joined the chat!`,
});
socket.join(user.room);
io.to(user.room).emit("ROOM_DATA", {
room: user.room,
users: getAllUsersInRoom(user.room),
});
callback();
});
socket.on("NEW_MESSAGE", (message, callback) => {
const user = getUser(socket.id);
io.to(user.room).emit("MESSAGE", { user: user.name, text: message });
callback();
});
socket.on("disconnect", () => {
const user = removeUser(socket.id);
if (user) {
io.to(user.room).emit("MESSAGE", {
user: "admin",
text: `${user.name} has left the chat!`,
});
io.to(user.room).emit("ROOM_DATA", {
room: user.room,
users: getAllUsersInRoom(user.room),
});
}
});
socket.on("disconnected", () => {
const user = removeUser(socket.id);
if (user) {
io.to(user.room).emit("MESSAGE", {
user: "admin",
text: `${user.name} has left the chat!`,
});
io.to(user.room).emit("ROOM_DATA", {
room: user.room,
users: getAllUsersInRoom(user.room),
});
}
});
});
server.listen(PORT, () => console.log(`Server is running on port: ${PORT}`));

38999
server/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

20
server/package.json Normal file
View File

@ -0,0 +1,20 @@
{
"name": "server",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "node index.js",
"heroku-postbuild": "NPM_CONFIG_PRODUCTION=false npm install --prefix client && npm run build --prefix client"
},
"author": "Nithin",
"license": "ISC",
"dependencies": {
"cors": "^2.8.5",
"dotenv": "^10.0.0",
"express": "^4.17.1",
"nodemon": "^2.0.6",
"react-scripts": "^4.0.3",
"socket.io": "^3.0.1"
}
}

9
server/router.js Normal file
View File

@ -0,0 +1,9 @@
const express = require('express');
const router = express.Router();
router.get('/', (req, res, next) => {
res.send('Server is running');
});
module.exports = router;

32
server/users.js Normal file
View File

@ -0,0 +1,32 @@
const users = [];
const addUser = ({ id, name, room}) => {
name = name.trim().toLowerCase();
room = room.trim().toLowerCase();
var isAlreadyPresent = users.find((user) => user.name === name && user.room === room);
if (isAlreadyPresent || name === 'admin') {
return {err: "Username already taken"};
}
const user = { id, name, room };
users.push(user);
return { user };
}
const removeUser = (id) => {
const index = users.findIndex((user) => user.id === id);
if (index != -1) {
return users.splice(index, 1)[0];
}
}
const getUser = (id) => {
return users.find((user) => user.id === id);
}
const getAllUsersInRoom = (room) => {
return users.filter((user) => user.room === room);
}
module.exports = { addUser, removeUser, getAllUsersInRoom, getUser};