-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
345 lines (276 loc) · 8.8 KB
/
Copy pathserver.js
File metadata and controls
345 lines (276 loc) · 8.8 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
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
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
const express = require("express");
const multer = require("multer");
const path = require("path");
const fs = require("fs");
const sharp = require("sharp");
const { exec } = require("child_process");
const app = express();
const PORT = process.env.PORT || 3000;
/* =========================================================
IMPROVED PROFANITY FILTER
========================================================= */
const bannedWords = [
"fuck",
"shit",
"asshole",
"bastard",
"damn",
"crap",
"dick",
"piss",
"bullshit",
"motherfucker",
"pussy"
];
// Normalize text to defeat bypass attempts
function normalizeText(text) {
return text
.toLowerCase()
// Replace common leetspeak
.replace(/0/g, "o")
.replace(/1/g, "i")
.replace(/3/g, "e")
.replace(/4/g, "a")
.replace(/5/g, "s")
.replace(/7/g, "t")
.replace(/\$/g, "s")
.replace(/@/g, "a")
// Remove symbols
.replace(/[^a-z]/g, "")
// Collapse repeated letters (fuuuuuck → fuck)
.replace(/(.)\1{2,}/g, "$1");
}
function containsBadWord(text) {
if (!text) return false;
const normalized = normalizeText(text);
return bannedWords.some(word =>
normalized.includes(word)
);
}
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
if (!fs.existsSync("uploads")) fs.mkdirSync("uploads");
// 3DS-safe static serving for images
app.use("/uploads", express.static("uploads"));
app.use(express.static("public"));
let rooms = {};
let activeUsers = {};
let lastActive = {};
const MAX_MESSAGES = 10000000000000000;
const IDLE_TIMEOUT = 30000;
/* ---------- TORONTO TIME ---------- */
function timestamp() {
const formatter = new Intl.DateTimeFormat("en-CA", {
timeZone: "America/Toronto",
hour: "2-digit",
minute: "2-digit",
hour12: false
});
const parts = formatter.formatToParts(new Date());
const hour = parts.find(p => p.type === "hour").value;
const minute = parts.find(p => p.type === "minute").value;
return `[${hour}:${minute}]`;
}
/* ---------- UTIL ---------- */
function addMessage(room, msg) {
if (!rooms[room]) return;
rooms[room].push(msg);
if (rooms[room].length > MAX_MESSAGES)
rooms[room].shift();
}
function ensureRoom(name) {
if (!rooms[name]) {
rooms[name] = [];
activeUsers[name] = {};
lastActive[name] = {};
addMessage(name, {
system: true,
text: timestamp() + " Chat room created."
});
}
}
function joinUser(room, user) {
ensureRoom(room);
if (!activeUsers[room][user]) {
activeUsers[room][user] = true;
addMessage(room, {
system: true,
text: timestamp() + " " + user + " has entered the room."
});
}
lastActive[room][user] = Date.now();
}
function leaveUser(room, user, reason = "has left the room.") {
if (!rooms[room]) return;
if (activeUsers[room][user]) {
delete activeUsers[room][user];
delete lastActive[room][user];
addMessage(room, {
system: true,
text: timestamp() + " " + user + " " + reason
});
}
}
/* ---------- CREATE ROOM ---------- */
app.post("/create-room", (req, res) => {
const name = req.body.name?.trim();
if (!name) return res.sendStatus(400);
if (rooms[name]) {
return res.status(409).json({ error: "Room already exists" });
}
rooms[name] = [];
activeUsers[name] = {};
lastActive[name] = {};
addMessage(name, {
system: true,
text: timestamp() + " Chat room created."
});
res.sendStatus(200);
});
/* ---------- GET MESSAGES ---------- */
app.get("/messages", (req, res) => {
const room = req.query.room;
if (!rooms[room])
return res.json({ messages: [], users: [] });
res.json({
messages: rooms[room],
users: Object.keys(activeUsers[room])
});
});
/* ---------- JOIN ---------- */
app.post("/join", (req, res) => {
const { room, user } = req.body;
if (!room || !user) return res.sendStatus(400);
joinUser(room.trim(), user.trim());
res.sendStatus(200);
});
/* ---------- LEAVE ---------- */
app.post("/leave", (req, res) => {
const { room, user } = req.body;
if (!room || !user) return res.sendStatus(400);
leaveUser(room.trim(), user.trim());
res.sendStatus(200);
});
/* ---------- SEND MESSAGE ---------- */
app.post("/send", (req, res) => {
const { room, user, text } = req.body;
if (!room || !user || !text)
return res.sendStatus(400);
joinUser(room.trim(), user.trim());
if (containsBadWord(text)) {
addMessage(room.trim(), {
system: true,
text: timestamp() + ` User ${user.trim()} tried to send an inappropriate message.`
});
return res.status(400).json({
warning: "Your message contains inappropriate words."
});
}
addMessage(room.trim(), {
system: false,
user: user.trim(),
text: timestamp() + " " + text
});
lastActive[room.trim()][user.trim()] = Date.now();
res.sendStatus(200);
});
/* ---------- UPLOAD (IMAGES + VIDEOS) ---------- */
const storage = multer.diskStorage({
destination: (req, file, cb) => cb(null, "uploads/"),
filename: (req, file, cb) => {
const ext = path.extname(file.originalname) || ".jpg";
cb(null, Date.now() + "-" + Math.random().toString(36).slice(2) + ext);
}
});
// Remove file size limit and file type filter
const upload = multer({
storage,
// No limits on file size (be cautious with this in production)
limits: {},
fileFilter: (req, file, cb) => cb(null, true) // Allow all file types
});
app.post("/upload", upload.single("image"), async (req, res) => {
try {
const { room, user } = req.body;
if (!room || !user || !req.file) return res.sendStatus(400);
joinUser(room.trim(), user.trim());
const inputPath = req.file.path;
const isImage = req.file.mimetype.startsWith("image/"); // Check if it's an image
const isVideo = req.file.mimetype.startsWith("video/"); // Check if it's a video
if (isImage) {
// If it's an image, process it with Sharp
const outputName = Date.now() + ".jpg";
const outputPath = path.join("uploads", outputName);
await sharp(inputPath)
.resize({ width: 400 }) // Resize the image to 400px width
.jpeg({ quality: 70 }) // Compress to 70% quality
.toFile(outputPath); // Save the processed image
fs.unlinkSync(inputPath); // Delete the original file after processing
const imageUrl = "/uploads/" + outputName;
addMessage(room.trim(), {
system: false,
user: user.trim(),
text: timestamp() + `<br><a href="${imageUrl}" target="_blank"><img src="${imageUrl}" width="150"></a>`
});
} else if (isVideo || req.file.mimetype.startsWith("audio/") || req.file.mimetype.startsWith("application/")) {
// If it's a video, audio, or unsupported file type (treated as video)
const outputName = Date.now() + ".mp4";
const outputPath = path.join("uploads", outputName);
const ffmpegCmd = `ffmpeg -y -i "${inputPath}" \
-c:v libx264 -profile:v high -b:v 682k -r 30 -c:a aac -b:a 128k -ar 48000 -ac 2 \
-s 640x360 -metadata:s:v:0 language=eng \
"${outputPath}"`;
await new Promise((resolve, reject) => {
exec(ffmpegCmd, (err, stdout, stderr) => {
if (err) {
console.error("FFmpeg failed:", err);
console.error(stderr);
return reject(err);
}
resolve();
});
});
fs.unlinkSync(inputPath); // Delete the original file after processing
const mediaUrl = "/uploads/" + outputName;
addMessage(room.trim(), {
system: false,
user: user.trim(),
text: timestamp() + `<a href="${mediaUrl}" target="_blank">[VIDEO ATTACHMENT]</a>`
});
} else {
// If it's neither an image, video, nor audio (unsupported type), return an error
fs.unlinkSync(inputPath); // Clean up the unsupported file
return res.status(400).json({ error: "Unsupported file type. Treating it as a video." });
}
lastActive[room.trim()][user.trim()] = Date.now();
res.redirect("/");
} catch (err) {
console.error(err);
res.sendStatus(500);
}
});
/* ---------- 3DS-SAFE VIDEO DELIVERY (Content-Length required) ---------- */
app.get("/uploads/:file", (req, res) => {
const file = path.join("uploads", req.params.file);
if (!fs.existsSync(file)) return res.sendStatus(404);
const stat = fs.statSync(file);
res.setHeader("Content-Length", stat.size);
res.setHeader("Content-Type", "video/mp4");
fs.createReadStream(file).pipe(res);
});
/* ---------- IDLE CLEANUP ---------- */
setInterval(() => {
const now = Date.now();
for (const room in lastActive) {
for (const user in lastActive[room]) {
if (now - lastActive[room][user] > IDLE_TIMEOUT) {
leaveUser(room, user, "has been idle and left.");
}
}
}
}, 5000);
/* ---------- START ---------- */
ensureRoom("Lobby");
app.listen(PORT, () =>
console.log("AIM XP 3DS running on port " + PORT)
);