-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
170 lines (138 loc) · 4.54 KB
/
server.js
File metadata and controls
170 lines (138 loc) · 4.54 KB
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
const express = require("express");
const http = require("http");
const { Server } = require("socket.io");
const path = require("path");
const os = require("os");
const qrcode = require("qrcode");
const fs = require("fs");
const multer = require("multer");
const isPkg = !!process.pkg;
const basePath = isPkg ? path.dirname(process.execPath) : __dirname;
const publicDir = path.join(__dirname, "public");
const uploadDir = path.join(basePath, "uploads");
const app = express();
const server = http.createServer(app);
app.use(express.static(publicDir));
app.get("/", (req, res) => {
const filePath = path.join(publicDir, "index.html");
try {
const fileContent = fs.readFileSync(filePath, "utf8");
res.setHeader("Content-Type", "text/html");
res.send(fileContent);
} catch (err) {
res.status(404).send("HTML file not found.");
}
});
app.get("/style.css", (req, res) => {
const filePath = path.join(publicDir, "style.css");
try {
const fileContent = fs.readFileSync(filePath, "utf8");
res.setHeader("Content-Type", "text/css");
res.send(fileContent);
} catch (err) {
res.status(404).send("CSS file not found.");
}
});
app.get("/script.js", (req, res) => {
const filePath = path.join(publicDir, "script.js");
try {
const fileContent = fs.readFileSync(filePath, "utf8");
res.setHeader("Content-Type", "application/javascript");
res.send(fileContent);
} catch (err) {
res.status(404).send("JS file not found.");
}
});
if (!fs.existsSync(uploadDir)) fs.mkdirSync(uploadDir);
const upload = multer({ dest: uploadDir });
app.use("/uploads", express.static(uploadDir));
app.use('/socket.io', express.static(path.join(basePath, 'node_modules', 'socket.io', 'client-dist')));
app.post('/upload', upload.single('file'), (req, res) => {
res.json({ url: `/uploads/${req.file.filename}`, name: req.file.originalname });
});
const io = new Server(server, {
cors: { origin: "*", methods: ["GET", "POST"] },
});
let users = {};
let chatHistory = {};
function getChatKey(id1, id2) {
return [id1, id2].sort().join("###");
}
function getLocalIP() {
const interfaces = os.networkInterfaces();
for (const iface of Object.values(interfaces)) {
for (const alias of iface) {
if (alias.family === "IPv4" && !alias.internal) return alias.address;
}
}
return "localhost";
}
io.on("connection", (socket) => {
console.log("Connected:", socket.id);
socket.on("setName", (name) => {
users[socket.id] = name || "Anonymous";
io.emit("userList", users);
});
socket.on("private.message", ({ to, text }) => {
const msg = {
id: Date.now() + "-" + Math.random().toString(36).substr(2, 9),
from: socket.id,
fromName: users[socket.id] || "Anonymous",
text,
ts: Date.now(),
to,
status: "sent",
};
const key = getChatKey(socket.id, to);
if (!chatHistory[key]) chatHistory[key] = [];
chatHistory[key].push(msg);
socket.to(to).emit("private.message", msg);
socket.emit("private.message", msg);
});
socket.on("private.file", ({ to, file }) => {
const msg = {
id: Date.now() + "-" + Math.random().toString(36).substr(2, 9),
from: socket.id,
fromName: users[socket.id] || "Anonymous",
file: { name: file.name, url: file.url },
ts: Date.now(),
to,
status: "sent",
};
const key = getChatKey(socket.id, to);
if (!chatHistory[key]) chatHistory[key] = [];
chatHistory[key].push(msg);
socket.to(to).emit("private.file", msg);
socket.emit("private.file", msg);
});
socket.on("getHistory", (otherId) => {
const key = getChatKey(socket.id, otherId);
const history = chatHistory[key] || [];
socket.emit("chatHistory", { with: otherId, messages: history });
});
socket.on("typing", (toId) => {
io.to(toId).emit("typing", socket.id);
});
socket.on("disconnect", () => {
console.log("Disconnected:", socket.id);
delete users[socket.id];
io.emit("userList", users);
});
});
const PORT = process.env.PORT || 5000;
async function startServer() {
server.listen(PORT, "0.0.0.0", async () => {
const localIP = getLocalIP();
const url = `http://${localIP}:${PORT}`;
console.log(`Server running on port ${PORT}`);
console.log(`Open this URL on any device in the same Wi-Fi: ${url}`);
try {
const qr = await qrcode.toString(url, { type: "terminal" });
console.log(qr);
console.log("Scan this QR code with your phone to open the chat app.");
} catch (err) {
console.error("Failed to generate QR code:", err);
}
});
}
startServer();