-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver.js
248 lines (173 loc) · 6.44 KB
/
server.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
const path = require('path');
const http = require('http');
const socketio = require('socket.io');
const express = require('express');
const mongoose = require('mongoose');
const moment = require('moment');
const CryptoJS = require('crypto-js');
const {
userJoin,
getCurrentUser,
userLeave,
getRoomUsers
} = require('./utils/users');
const app = express();
const server = http.createServer(app);
const io = socketio(server);
// Format messages to object
const formatMessage = require('./utils/messages');
// Serve the front-end to user on connecttion
app.use(express.static(path.join(__dirname, 'public')));
// Chat-bot name
botName = "chat-on";
// DB connection URL pwd="admin" db="database0"
const connection_url = "mongodb+srv://admin:[email protected]/database0?retryWrites=true&w=majority";
// // Connect to database
// mongoose.connect(connection_url, {
// useNewUrlParser: true, useUnifiedTopology: true
// });
// var connection = mongoose.connection;
// connection.on("once", function() {
// console.log("DB connected!")
// });
// connection.on('error', console.error.bind(console, 'MongoDB connection error:'));
// Correct method
const MongoClient = require('mongodb').MongoClient;
//const uri = "mongodb+srv://admin:[email protected]/myFirstDatabase?retryWrites=true&w=majority";
const client = new MongoClient(connection_url, { useNewUrlParser: true, useUnifiedTopology: true });
// client.connect(err => {
// const collection = client.db("database0").collection("chats");
// // perform actions on the collection object
// console.log("Connected to the database", client.db);
// client.close();
// });
async function deleteAllChatsInDB() {
try {
await client.connect();
// Select the DB
const database = client.db("database0");
// collection = table
const chats = database.collection("chats");
// Delete all documents in 'chats'
const result = await chats.remove( {} );
console.log(
"All documents of " + chats + " are deleted"
);
}
finally {
await client.close();
}
}
// Call this function when delete chats is called
//deleteAllChatsInDB().catch(console.dir);
async function addChatsToDB(room, username, message, time) {
try {
await client.connect();
const database = client.db("database0");
// collection = table
const chats = database.collection("chats");
// Create a document to be inserted
const document = {
room: room,
name: username,
message: message,
time: time
};
// Insert to DB
const result = await chats.insertOne(document);
console.log(
`${result.insertedCount} chat was inserted with the _id: ${result.insertedId}`,
);
}
finally{
// Do nothing (for now)
}
}
async function getChatsFromDB(room) {
try {
await client.connect();
const database = client.db("database0");
// collection = table
const chats = database.collection("chats");
const query = { room : room };
const options = {
projection: { _id: 0 }
};
// MongoDB returns cursor not a object for find op
const cursor = chats.find(query, options);
// Return 0 when query is empty
if ((await cursor.count()) === 0) {
console.log("No documents found!");
return 0;
}
const arr = await cursor.toArray();
const obj = {};
// Array to object
for(let i=0; i<arr.length; i++)
{
obj[i] = await arr[i];
}
//await console.log(obj[0].room);
//console.log(cursor);
return obj;
}
finally{
// Do nothing here (for now)
}
}
// getChatsFromDB("1").catch(console.dir);
// When user connects to 'socket'
io.on('connection', socket => {
console.log("New client connected!")
// When user joins new room. Here by default on landing on index.html.
// Making tis function async since we want to wait for previous chats
// to be loaded from the database, without continuing further.
socket.on('joinRoom', async ( {username, room} ) => {
const user = userJoin(socket.id, username, room);
console.log(socket.id, user.room, room, user.username, username);
socket.join(user.room);
// Dump here from DB all previous conversations.
// Do this only when room is entered for 2> time.
const obj = await getChatsFromDB(user.room).catch(console.dir);
//console.log(Object.keys(obj).length);
//console.log(obj[0].name);
// Send welcome message to all users on joining
await socket.emit('bot-message',
formatMessage(botName, "Welcome to chat app!", moment().format('h:mm a')));
// 0 when empty
// console.log("obj value " + obj);
// Check if room exists
if(obj != 0) {
// Send old messages from db in encrypted format
for(var i=0; i<Object.keys(obj).length; i++) {
socket.emit('client-message',
formatMessage(obj[i].name, obj[i].message, obj[i].time));
}
console.log("INFO: Message load complete!");
}
// Notify the room who has joined the chat
socket.broadcast
.to(user.room)
.emit(
'bot-message',
formatMessage(botName, `${user.username} has joined the chat`, moment().format('h:mm a'))
);
})
// Listen for client-chat message
socket.on('chat-message', (encrypted_msg) => {
const user = getCurrentUser(socket.id);
// Call method to insert chat-message[ENCRYPTED] to DB
addChatsToDB(user.room, user.username, encrypted_msg, moment().format('h:mm a')).catch(console.dir);
// Emit the messages to room in encrypted format
io.to(user.room).emit('client-message',
formatMessage(user.username, encrypted_msg, moment().format('h:mm a')));
})
// Notify every other user on disconnection
socket.on('disconnect', () => {
const user = getCurrentUser(socket.id);
io.to(user.room).emit('message',
formatMessage(botName, user.username+' as left!', moment().format('h:mm a')))
})
});
const PORT = 3005 || process.env.PORT;
server.listen(PORT, () => console.log('Server listening on port ' + PORT));