-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
261 lines (211 loc) · 9.11 KB
/
main.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
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
const ws = require("ws")
const http = require("http")
const express = require("express")
const {MongoClient, ServerApiVersion} = require("mongodb")
const clui = require("clui")
require("dotenv").config()
const port = process.env.PORT || 3000
const logging = JSON.parse(process.env.LOGGING)
let users = []
let rooms = {}
const spinner = new clui.Spinner("Loading env variables...")
if(logging) spinner.start()
const mongoUserName = process.env.MONGODBUSERNAME
const mongoPassword = process.env.MONGODBPASSWORD
const mongoClusterName = process.env.MONGODBCLUSTERNAME
const mongoURLEnd = process.env.MONGODBURLEND
const mongoDataBase = process.env.HISTORYDB || "prod"
const mongoCol = process.env.HISTORYCOL || "latestMessages"
let messageHistoryLength
let mongoURI
if(mongoClusterName && mongoPassword && mongoUserName && mongoURLEnd) {
messageHistoryLength = process.env.HISTORYLENGTH || 10
mongoURI = `mongodb+srv://${mongoUserName}:${mongoPassword}@${mongoClusterName}.${mongoURLEnd}.mongodb.net/?retryWrites=true&w=majority`
} else {
messageHistoryLength = 0
}
spinner.message("Setting up mongodb...")
let mongoClient
if(mongoURI) {
mongoClient = new MongoClient(mongoURI, {
serverApi: {
version: ServerApiVersion.v1,
strict: true,
deprecationErrors: true,
}
})
}
if(messageHistoryLength) {
if(logging) console.log(`A message history of ${messageHistoryLength} messages will be kept on the mongodb cluster ${`mongodb+srv://${mongoUserName}:<password>@${mongoClusterName}.${mongoURLEnd}.mongodb.net/?retryWrites=true&w=majority`}`)
if(logging) console.log(`Messages will be kept in the database "${mongoDataBase}" under the collection "${mongoCol}"`)
if(mongoPassword) {
if(logging) console.log("a password is present, but wont be logged for obvious security reasons.")
} else {
console.log("YOU FORGOT SETTING THE \"MONGODBPASSWORD\" ENVIROMENT VARIABLE.")
}
} else {
if(logging) console.log("tip: did you know you can use this app connected to a mongodb database for message persistence?")
}
spinner.message("creating server...")
const app = express()
const server = http.createServer(app)
const wss = new ws.Server({ server })
app.get("/health", (req, res) => {
res.json({"healthy": true}).send
})
wss.on("connection", ws => {
ws.on("message", (message) => {
message = JSON.parse(message.toString())
if(message.login) {
const index = users.findIndex(e => e.ws === ws);
if (index < 0) {
users.push({
ws: ws,
userName: message.login.userName,
room: message.login.room
})
if(rooms[message.login.room]) {
rooms[message.login.room].push(ws)
} else {
rooms[message.login.room] = [ws]
}
if(logging) console.log(`registered User "${message.login.userName}" in room "${message.login.room}"`)
rooms[message.login.room].forEach(user => {
if(user.OPEN && user != ws)
user.send(JSON.stringify({
"message": `User "${message.login.userName}" just connected. There are now ${rooms[message.login.room].length} user(s) connected to this room.`,
"sender": "TheBaum's messaging server",
"time": new Date()
}))
})
}
if(messageHistoryLength) {
let previousMessages = []
async function queryDatabase() {
try {
const database = mongoClient.db(mongoDataBase)
const col = database.collection(mongoCol)
const query = {room: message.login.room}
let messagesFromRoom = await col.findOne(query)
if(messagesFromRoom) {
previousMessages = messagesFromRoom.messages
previousMessages.forEach(elem => {
ws.send(JSON.stringify({
"message": elem.message,
"sender": elem.sender,
"time": elem.time
}))
})
}
ws.send(JSON.stringify({
"message": `You connected to the room "${message.login.room}" as "${message.login.userName}". There are now ${rooms[message.login.room].length} user(s) connected to this room.`,
"sender": "TheBaum's messaging server",
"time": new Date()
}))
ws.send(JSON.stringify({
"message": `Did you know you can host your own instance of this chat server? For more info visit https://github.com/TheBaum123/chat-app-ws`,
"sender": "TheBaum's messaging server",
"time": new Date()
}))
} finally {
}
}
queryDatabase().catch(console.dir)
} else {
ws.send(JSON.stringify({
"message": `You connected to the room "${message.login.room}" as "${message.login.userName}". There are now ${rooms[message.login.room].length} user(s) connected to this room.`,
"sender": "TheBaum's messaging server",
"time": new Date()
}))
}
}
})
ws.send(JSON.stringify({
message:"Welcome to TheBaum's messaging server.",
sender:"TheBaum's messaging server",
time: new Date()
}))
ws.on("message", (message, isBinary) => {
const index = users.findIndex(e => e.ws === ws);
if (index > -1 && !JSON.parse(message.toString()).login) {
let messageToSave = JSON.parse(message.toString())
messageToSave["sender"] = users[index].userName
if(messageHistoryLength){updateDatabase(users[index].room, messageToSave)}
users.forEach(user => {
if(user.ws != ws && user.ws.OPEN && user.room == users[index].room && !JSON.parse(message.toString()).login) {
user.ws.send(JSON.stringify(messageToSave), {binary: isBinary})
}
})
}
})
ws.on("close", () => {
const usersIndex = users.findIndex(e => e.ws === ws);
if(usersIndex > -1) {
const roomLeft = users[usersIndex].room
const leavingUserName = users[usersIndex].userName
const indexInRooms = rooms[roomLeft].findIndex(wsElem => wsElem == ws)
rooms[roomLeft].splice(indexInRooms, 1)
users.splice(usersIndex, 1)
let brodcastMessage = ("User \"" + leavingUserName + "\" just left. There are now " + rooms[roomLeft].length + " user(s) connected to this room.")
rooms[roomLeft].forEach(user => {
user.send(JSON.stringify({
"message": brodcastMessage,
"sender": "TheBaum's messaging server",
"time": new Date()
}))
})
if(logging) console.log(`removed User "${leavingUserName}" from room "${roomLeft}"`)
}
})
})
spinner.message("setting up frontend...")
app.use(express.static("public"))
server.listen(port, () => {
if(logging) console.log("listening on port " + port)
spinner.message(`listening on port ${port}`)
setTimeout(() => {
if(logging) spinner.stop()
}, 1000);
})
async function updateDatabase(room, message) {
try {
const database = mongoClient.db(mongoDataBase)
const col = database.collection(mongoCol)
const filter = {room: room}
const options = {upsert: true}
const query = {room: room}
let messagesFromRoom = await col.findOne(query)
let previousMessages = []
if(messagesFromRoom) {
previousMessages = messagesFromRoom.messages
if(messageHistoryLength > 1) {
while(previousMessages.length > messageHistoryLength - 1) {
previousMessages.splice(0, 1)
}
}
previousMessages.push(message)
if(messageHistoryLength == 0) {
previousMessages = []
}
if(messageHistoryLength == 1) {
previousMessages = [message]
}
} else {
previousMessages = [message]
}
let updateDoc = {
$set: {
"messages": previousMessages
}
}
await col.updateOne(filter, updateDoc, options)
}
finally {
}
}
process.on("SIGINT", async function() {
if(logging) console.log("closing mongodb connection")
await mongoClient.close()
if(logging) console.log("conection to mongodb closed")
process.exit()
})