-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapp.js
249 lines (231 loc) · 7.04 KB
/
app.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
// Use dotenv to read .env vars into Node
require("dotenv").config();
// Constants
const express = require("express"),
bodyParser = require("body-parser"),
PORT = process.env.PORT,
HOST = process.env.HOST,
app = express(),
swaggerUi = require("swagger-ui-express"),
mongose = require("mongoose"),
Message = require("./models/message.js"),
http = require("http").createServer(app),
io = require("socket.io")(http),
YAML = require("yamljs"),
handlebars = require("express-handlebars"),
path = require("path"),
cors = require("cors"),
flash = require("connect-flash"),
passport = require("passport"),
expressSession = require("express-session"),
initPassport = require("./config/passport/initialPassport");
const adminRoute = require("./routes/admin");
// Config handlebars
app.engine(
".hbs",
handlebars({
extname: ".hbs",
defaultLayout: "main",
partialsDir: path.join(__dirname, "views/partials"),
layoutsDir: path.join(__dirname, "views"),
})
);
app.set("view engine", ".hbs");
app.set("views", path.join(__dirname, "views"));
// Config app
app.use(cors());
app.use(flash());
app.use(express.static(path.join(__dirname, "public")));
app.use(bodyParser.json({ limit: "50mb" })); // parse form data client
app.use(bodyParser.urlencoded({ limit: "50mb", extended: true }));
//Configure Mongodb
const db = require("./config/database.js").mongoURI;
//Connect to Mongosse
mongose
.connect(db, {
useNewUrlParser: true,
useFindAndModify: false,
useCreateIndex: true,
useUnifiedTopology: true,
})
.then(() => {
console.log("MONGODB CONNECTED ... ");
})
.catch((err) => console.log(err));
//Configure passport
app.use(
expressSession({
secret: "VTNPD",
resave: false,
saveUninitialized: true,
})
);
app.use(passport.initialize());
app.use(passport.session());
initPassport(passport);
//Config Socket io
const Room = require("./models/room");
const User = require("./models/user");
let userIdOnlines = [];
io.on("connection", (socket) => {
socket.on("online", async (user_id) => {
socket.join(user_id);
socket.user_id = user_id;
if (userIdOnlines[user_id] == undefined) {
userIdOnlines.push(user_id);
}
console.log(userIdOnlines);
await joins(socket, user_id);
console.log(`${socket.email} connect: ${user_id}`);
});
socket.on("newRoom", (roomString) => {
const room = JSON.parse(roomString);
if (socket.rooms[room._id] == undefined) {
socket.join(room._id);
console.log(`${socket.email} connect new room: ${room._id}`);
const user_ids = [...room.user_id];
user_ids.shift(socket.user_id);
if (userIdOnlines.includes(user_ids[0])) {
socket.join(user_ids[0]);
console.log(`${socket.email} connect: ${user_ids[0]}`);
socket.broadcast.to(user_ids[0]).emit("joinRoom", JSON.stringify(room));
}
}
});
socket.on("joinRoom", async (roomString) => {
const room = JSON.parse(roomString);
socket.join(room._id);
console.log(`${socket.email} connect new room: ${room._id}`);
const user_ids = [...room.user_id];
user_ids.shift(socket.user_id);
if (userIdOnlines.includes(user_ids[0])) {
const roomResponse = await handleResponseRoom(user_ids[0], room);
console.log(`${socket.email} send roomResponse to: ${user_ids[0]}`);
io.to(room._id).emit("updateRooms", JSON.stringify(roomResponse));
}
});
socket.on("joinChat", (roomId) => {
let size = 0;
socket.join(roomId + roomId);
Message.updateMany(
{ room_id: roomId, is_read: 0 },
{ $set: { is_read: 1 } },
{ multi: true },
(err, writeResult) => {
if (err) {
console.log("Socket: isRead ", err);
} else {
console.log("Socket: isRead " + writeResult);
}
}
);
console.log(`${socket.email} join chat: ${roomId}`);
const adapters = io.sockets.adapter.rooms[roomId + roomId];
if (adapters !== undefined) size = adapters.length;
const newRoom = {
_id: roomId,
size: size,
};
io.to(roomId).emit("joinChat", newRoom);
});
socket.on("leaveChat", (roomId) => {
let size = 0;
socket.leave(roomId + roomId);
console.log(`${socket.email} leave chat: ${roomId}`);
const adapters = io.sockets.adapter.rooms[roomId + roomId];
if (adapters !== undefined) size = adapters.length;
const newRoom = {
_id: roomId,
size: size,
};
io.to(roomId).emit("leaveChat", newRoom);
});
socket.on("clientSendMessage", (data) => {
console.log(data);
const message = JSON.parse(data);
const roomId = message.room_id;
Message.create(
{
room_id: message.room_id,
user_id: message.user_id,
content: message.content,
is_read: message.is_read,
},
(err, docs) => {
if (err) {
res.json(err);
} else {
console.log(`${socket.email} send message to: ${docs}`);
socket.broadcast
.to(roomId)
.emit("serverSendMessage", JSON.stringify(docs));
}
}
);
});
socket.on("typing", (room_id) => {
//Only roomNumber is needed here
console.log("typing triggered");
socket.broadcast.to(`${room_id}`).emit("typing");
});
socket.on("stopTyping", (room_id) => {
//Only roomNumber is needed here
console.log("stopTyping triggered");
socket.broadcast.to(`${room_id}`).emit("stopTyping");
});
socket.on("disconnect", () => {
userIdOnlines.shift(socket.user_id);
});
});
const handleResponseRoom = async (user_id, room) => {
let newRoom = { room: room };
const userReceive = await User.findOne(
{ _id: user_id },
{
password: 0,
device_token: 0,
token: 0,
email_code: 0,
email_code_expires: 0,
}
);
newRoom.userReceive = userReceive;
return newRoom;
};
const joins = async (socket, user_id) => {
const user = await User.findOne({ _id: user_id });
socket.email = user.email;
const filter = { user_id: user._id };
Room.find(filter, (err, docs) => {
if (err) {
console.log(`error:` + err);
} else {
docs.forEach((element) => {
socket.join(element._id);
console.log(`${user.email} connect to room: ${element._id}`);
});
}
});
};
// configure body-parser
app.use(bodyParser.json({ limit: "50mb" })); // parse form data client
app.use(bodyParser.urlencoded({ limit: "50mb", extended: true }));
// app entry point
app.get("/", (req, res) => res.send("Welcome to Lus"));
//Route
app.use("/api/v1", require("./routes/api.js"));
app.use("/admin", adminRoute(passport));
// Swagger
const swaggerDocument = YAML.load(path.join(__dirname, "docs/api-docs.yml"));
app.use("/api-docs", swaggerUi.serve, swaggerUi.setup(swaggerDocument));
// Setup a default catch-all route that sends back a welcome message in JSON format.
app.get("*", (req, res) => {
res.render("admin/errors/error404.hbs", {
layout: "admin/layouts/index.hbs",
});
});
http.listen(PORT, async function () {
console.log(`Running on http://${HOST}:${PORT}`);
// await Room.remove({});
// await Message.remove({});
});