forked from bingsen0806/Project-ReHash
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
279 lines (250 loc) · 8.12 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
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
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
//Importing modules and defining ports
const express = require("express");
const app = express();
const server = require("http").createServer(app);
const { Server } = require("socket.io");
const io = new Server(server, {
cors: {
origin: [
"http://localhost:3000",
"http://localhost:8080",
"https://projectrehash.herokuapp.com/",
],
},
});
const mongoose = require("mongoose");
const dotenv = require("dotenv");
const helmet = require("helmet");
const morgan = require("morgan");
const userRoute = require("./routes/users");
const authRoute = require("./routes/auth");
const itemRoute = require("./routes/items");
const categoryRoute = require("./routes/categories");
const conversationRoute = require("./routes/conversations");
const messageRoute = require("./routes/messages");
const reviewRoute = require("./routes/reviews");
const agreementRoute = require("./routes/agreements");
const groupRoute = require("./routes/groups");
const postRoute = require("./routes/posts");
const commentRoute = require("./routes/comments");
const notificationRoute = require("./routes/notifications");
const multer = require("multer");
var cors = require("cors");
let port = process.env.PORT || 8080;
var path = require("path");
const User = require("./models/User");
//read from the .env file
dotenv.config();
//connect to database
mongoose
.connect(
"mongodb+srv://bingsen0806:testing123@rehash.3cwin.mongodb.net/rehash?retryWrites=true&w=majority",
{
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
}
)
.then(() => console.log("Database connected!"))
.catch((err) => console.log(err));
/** TODO ADD groups path to production environment **/
//setup for production environment
if (process.env.NODE_ENV === "production") {
console.log("environment is production!");
console.log("__dirname is: " + __dirname);
app.use(express.static(path.join(__dirname, "/frontend/build")));
app.get("/", function (req, res) {
res.sendFile(path.join(__dirname, "/frontend/build", "index.html"));
});
app.get("/register", function (req, res) {
res.sendFile(path.join(__dirname, "/frontend/build", "index.html"));
});
app.get("/home", function (req, res) {
res.sendFile(path.join(__dirname, "/frontend/build", "index.html"));
});
app.get("/create", function (req, res) {
res.sendFile(path.join(__dirname, "/frontend/build", "index.html"));
});
app.get("/product/*", function (req, res) {
res.sendFile(path.join(__dirname, "/frontend/build", "index.html"));
});
app.get("/chat/*", function (req, res) {
res.sendFile(path.join(__dirname, "/frontend/build", "index.html"));
});
app.get("/profile/*", function (req, res) {
res.sendFile(path.join(__dirname, "/frontend/build", "index.html"));
});
app.get("/items/*", function (req, res) {
res.sendFile(path.join(__dirname, "/frontend/build", "index.html"));
});
app.get("/groups/*", function (req, res) {
res.sendFile(path.join(__dirname, "/frontend/build", "index.html"));
});
}
app.use("/images", express.static(path.join(__dirname, "/public/images")));
//middleware
app.use(cors());
app.use(express.json());
app.use(helmet());
app.use(morgan("common"));
//uploading images with multer
const itemStorage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, path.join(__dirname, "public/images/items"));
},
filename: (req, file, cb) => {
cb(null, Date.now() + file.originalname);
},
});
const personStorage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, path.join(__dirname, "public/images/person"));
},
filename: (req, file, cb) => {
cb(null, Date.now() + file.originalname);
},
});
const groupStorage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, path.join(__dirname, "public/images/group"));
},
filename: (req, file, cb) => {
cb(null, Date.now() + file.originalname);
},
});
const itemUpload = multer({ storage: itemStorage });
app.post("/api/upload/items", itemUpload.array("file"), (req, res) => {
try {
var imageFileNames = [];
for (let i = 0; i < req.files.length; i += 1) {
console.log(
`File ${req.files[i].filename} uploaded to ${req.files[i].path}`
);
imageFileNames.push("items/" + req.files[i].filename);
}
console.log(imageFileNames);
return res.status(200).json({ imagePaths: imageFileNames });
} catch (err) {
console.log(err);
}
});
const personUpload = multer({ storage: personStorage });
app.post("/api/upload/person", personUpload.single("file"), (req, res) => {
try {
const imageFileName = "person/" + req.file.filename;
console.log(imageFileName);
return res.status(200).json({ imagePath: imageFileName });
} catch (err) {
console.log(err);
}
});
const groupUpload = multer({ storage: groupStorage });
app.post("/api/upload/group", groupUpload.single("file"), (req, res) => {
try {
const imageFileName = "group/" + req.file.filename;
console.log(imageFileName);
return res.status(200).json({ imagePath: imageFileName });
} catch (err) {
console.log(err);
}
});
//routes
app.use("/api/users", userRoute);
app.use("/api/auth", authRoute);
app.use("/api/items", itemRoute);
app.use("/api/conversations", conversationRoute);
app.use("/api/messages", messageRoute);
app.use("/api/items", itemRoute);
app.use("/api/categories", categoryRoute);
app.use("/api/reviews", reviewRoute);
app.use("/api/agreements", agreementRoute);
app.use("/api/groups", groupRoute);
app.use("/api/posts", postRoute);
app.use("/api/comments", commentRoute);
app.use("/api/notifications", notificationRoute);
//socket.io connections
let users = [];
var someoneGetUser = false;
var myInterval;
const addUser = (userId, socketId) => {
if (!users.some((user) => user.userId === userId)) {
users.push({ userId, socketId });
} else {
users = users.filter((user) => user.userId !== userId);
users.push({ userId, socketId });
}
};
const removeUser = (socketId) => {
users = users.filter((user) => user.socketId !== socketId);
};
setInterval(function () {
// console.log("someoneGetUser is: ", someoneGetUser);
if (!someoneGetUser) {
myInterval = setInterval(function () {
io.emit("getUsers", users);
// console.log("the one sending getUsers now is: ", socket.id);
}, 15000);
someoneGetUser = true;
console.log("myInterval changed!");
}
}, 1000);
io.on("connection", (socket) => {
//when a user connects
console.log("a user connected");
//utility functions
const getUser = (userId) => {
return users.find((user) => user.userId === userId);
};
const getUserBySocketId = (socketId) => {
return users.find((user) => user.socketId === socketId);
};
const updateLastActive = async () => {
const socketUser = await getUserBySocketId(socket.id);
try {
const user = await User.findById(socketUser.userId);
const date = new Date();
await user.updateOne({ lastActive: date });
console.log("updatedLastActive");
} catch (err) {
console.log(err);
}
};
//when "addUser" is called from frontend, take userId from frontend and add user
socket.on("addUser", (userId) => {
addUser(userId, socket.id);
updateLastActive();
io.emit("getUsers", users); //tell all sockets with "getUsers" that a new user is added
console.log("user is: ");
console.log(users);
});
//send and get message
socket.on("sendMessage", ({ senderId, receiverId, text }) => {
const user = getUser(receiverId);
if (user) {
console.log("emitting getMessage once!");
io.to(user.socketId).emit("getMessage", {
senderId,
text,
});
}
});
//when asked to updateLastActive
socket.on("updateLastActive", () => {
updateLastActive();
});
//when disconnect
socket.on("disconnect", async () => {
console.log("a user disconnected");
if (myInterval) {
clearInterval(myInterval);
someoneGetUser = false;
}
updateLastActive();
removeUser(socket.id);
console.log(users);
io.emit("getUsers", users); //tell everyone a user is removed
});
});
server.listen(port, () => {
console.log("Server listening on port: " + port);
});