-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
170 lines (132 loc) · 5.01 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
const express = require('express');
const app = express();
const server = require('http').createServer(app)
const io = require('socket.io')(server, { cors: { origin: '*', } });
const path = require('path');
const ConnectToMongo = require('./db');
const fetchUser = require('./middleware/fetchuser');
const Users = require('./models/User')
require('dotenv').config();
const { router } = require('./routes/endpoints')
const { publicRooms } = require('./routes/endpoints')
const { privateRooms } = require('./routes/endpoints')
ConnectToMongo();
const authors = ['leetfeetchat']
const privateRoomsAuthors = []
// express specific stuff
app.use('/static', express.static('static'));
app.use(express.urlencoded({ extended: false }));
app.use(express.json());
app.use('/api/auth', require('./routes/auth'))
app.use('/', router)
// Ejs Specific Stuff
app.set('view engine', 'ejs')
app.set('views', path.join(__dirname, 'views')); // Set The Views Directory
// socket.io Specific Stuff
// Create public room
app.post('/api/createpublicroom', fetchUser, async (req, res) => {
if (publicRooms[req.body.room] != null) {
return res.status(400).json({ error: "Room Name Already Exist" })
}
try {
const user = await Users.findById(req.user.id)
if(!user){
return res.json({error: "Internal Server Error"})
}
let filteredAuthors = authors.filter(myarr => myarr === user.username)
if (filteredAuthors.length > 4) {
return res.json({ error: "You Already Created 5 Rooms Delete Them First Or Upgrade You Tier" })
}
authors.push(user.username.trim())
console.log(filteredAuthors)
console.log(authors)
publicRooms[req.body.room] = { users: {} }
publicRooms[req.body.room].name = req.body.name.trim()
publicRooms[req.body.room].author = user.username.trim()
res.status(200).json({ success: "Room Has Been Created" })
io.emit('room-created', req.body.name.trim(), user.username.trim())
} catch (error) {
console.log(error.message)
return res.json( {error: "Internal Server Error"} )
}
})
// Delete public room
app.post('/api/deletepublicroom', (req, res)=>{
delete publicRooms[req.body.room]
res.json( { success: "Room Has Benn Deleted"} )
io.emit('room-deleted', req.body.room.toLowerCase().trim().replace(/\s+/g, '-'))
})
// Create private room
app.post('/api/createprivateroom', fetchUser, async (req, res)=>{
console.log(req.body.name)
console.log(req.body.password)
let user = await Users.findById(req.user.id)
if(!user){
return res.json({error: "Internal Server Error"})
}
let filteredAuthors = privateRoomsAuthors.filter(myarr => myarr === user.username)
if (filteredAuthors.length > 4) {
return res.json({ error: "You Already Created 5 Rooms Delete Them First Or Upgrade You Tier" })
}
privateRoomsAuthors.push(user.username.trim())
let roomId;
let roomNameArray = Object.keys(privateRooms)
console.log(user)
do{
roomId = 'e' + Math.floor(Math.random() * 1000000000000000);
} while (roomNameArray.includes(roomId))
privateRooms[roomId] = { users: {} }
privateRooms[roomId].name = req.body.name
privateRooms[roomId].password = req.body.password
privateRooms[roomId].author = user.username
privateRooms[roomId].roomId = roomId
console.log(privateRooms)
res.json({roomId: roomId, password: req.body.password})
})
// Delete private room
app.post('/api/deleteprivateroom', (req, res)=>{
let room = req.body.room.toLowerCase().trim().replace(/\s+/g, '-')
delete privateRooms[req.body.room]
res.json( { success: "Room Has Benn Deleted"} )
io.to(room).emit('room-deleted', room)
})
io.on('connection', socket => {
// Listen for new user joins
socket.on('new-user-joined', (room, name) => {
socket.join(room)
publicRooms[room].users[socket.id] = name
socket.to(room).emit('user-joined', name)
console.log(publicRooms)
})
// Listen for new user joins in private room
socket.on('new-user-joined-privateRoom', (room, name) =>{
socket.join(room)
privateRooms[room].users[socket.id] = name
socket.to(room).emit('user-joined', name)
})
// Listen for messages in public room
socket.on('send', (room, message) => {
socket.to(room).emit('receive', { message: message, name: publicRooms[room].users[socket.id] })
})
// Listen for messages in private room
socket.on('send-privateRoom', (room, message) => {
socket.to(room).emit('receive', { message: message, name: privateRooms[room].users[socket.id] })
})
// Listen for disconnect
socket.on('disconnect', () => {
getUserRooms(socket).forEach(room => {
socket.to(room).emit('user-disconnected', publicRooms[room].users[socket.id])
delete publicRooms[room].users[socket.id]
})
})
});
// Get user rooms
function getUserRooms(socket) {
return Object.entries(publicRooms).reduce((names, [name, room]) => {
if (room.users[socket.id] != null) names.push(name)
return names
}, [])
}
server.listen(process.env.PORT || 80, () => {
console.log("Server Is Listening On https://leetfeetchat.onrender.com")
})