-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
117 lines (98 loc) · 3.1 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
const express = require("express");
const app = express();
const bcrypt = require("bcrypt");
const path = require("path");
const fs = require("fs").promises;
const host = "localhost";
const port = 5000;
const appUrl = `http://${host}:${port}`;
const server = require("http").createServer(app);
const io = require("socket.io")(server);
app.use(express.json()); // Middleware to parse JSON bodies
app.use(express.static(path.join(__dirname + "/public")));
const chatHistoryFile = "chatHistory.json";
//Users API
const users = [];
app.get("/users", (req, res) => {
res.json(users);
});
app.post("/users", async (req, res) => {
try {
const hashedPassword = await bcrypt.hash(req.body.password, 10);
const user = { name: req.body.name, password: hashedPassword };
users.push(user);
res.status(201).send();
} catch {
res.status(500).send();
}
});
app.post("/users/login", async (req, res) => {
const user = users.find((user) => user.name === req.body.name);
if (user == null) {
return res.status(400).send("Cannot find user");
}
try {
if (await bcrypt.compare(req.body.password, user.password)) {
res.send("Success!");
} else {
res.send("Not allowed!");
}
} catch {
res.status(500).send();
}
});
// Load chat history on server start
async function loadChatHistory() {
try {
const chatHistory = await fs.readFile(chatHistoryFile, "utf-8");
return JSON.parse(chatHistory);
} catch (err) {
console.info(
"\x1b[34mMessage for dev: chat history JSON file doesn't exist yet. It will be created on first send submition.\x1b[0m"
);
return []; // Start with an empty array if file doesn't exist
}
}
// Save chat history to file
async function saveChatHistory(chatHistory) {
try {
await fs.writeFile(chatHistoryFile, JSON.stringify(chatHistory));
} catch (err) {
console.error("Error saving chat history:", err);
}
}
// Load chat history on server start
loadChatHistory()
.then((history) => {
app.locals.chatHistory = history;
})
.catch((err) => {
console.error("Error loading chat history:", err);
});
//socket.io users login
io.on("connection", function (socket) {
socket.on("newuser", function (username) {
socket.broadcast.emit("update", username + " joined the chatroom");
});
socket.on("exituser", function (username) {
socket.broadcast.emit("update", username + " left the chatroom");
});
socket.on("chat", (message) => {
message.timestamp = new Date().toISOString(); // Add timestamp
app.locals.chatHistory.push(message);
// Save chat history to file
saveChatHistory(app.locals.chatHistory);
// Broadcast timestamped message to all clients
socket.broadcast.emit("chat", message);
});
// Send history to new users
socket.emit("history", app.locals.chatHistory);
// Clear the chat history
socket.on("disconnect", () => {
io.emit("clearHistory"); // Broadcast clearHistory to all connected clients
});
});
server.listen(port, () => {
console.log("\x1b[32mServer running on port" + port + "\x1b[0m");
console.log(`\x1b[34mOpen the app in your browser:\x1b[0m ${appUrl}`);
});