-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
98 lines (89 loc) · 2.61 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
require("dotenv").config(); // config environmental variables
const http = require("http");
const express = require("express");
const sio = require("socket.io");
const path = require("path");
const app = express();
const server = http.createServer(app);
const io = sio(server);
app.use("/", express.static(path.join(__dirname, "public")));
let users = new Map();
io.sockets.on("connection", (socket) => {
socket.on("enter", (username) => {
if (users.has(username)) {
socket.emit("invalidUsername");
socket.disconnect();
} else {
users.set(username, socket.id);
socket.username = username;
let userList = [];
for (let user of users) {
userList.push(user[0]);
}
socket.emit("userList", userList);
io.emit("joinChat", socket.username);
}
});
socket.on("disconnect", () => {
users.delete(socket.username);
io.emit("exitChat", socket.username);
});
socket.on("sendMessage", (msg) => {
[isAll, userList] = getSendList(msg);
if (isAll) {
io.emit("publicMessage", socket.username, msg, Date.now());
} else {
for (user of userList) {
if (user == socket.username) continue;
if (users.has(user))
io.to(users.get(user)).emit(
"privateMessage",
socket.username,
msg,
Date.now()
);
}
socket.emit("privateMessage", socket.username, msg, Date.now());
}
});
});
server.listen(process.env.PORT, () => {
console.log(`Server Listening on port: ${process.env.PORT}`);
});
function getSendList(msg) {
let isAll = true;
let userList = new Set();
let username_regex = /^[a-zA-Z0-9_]$/;
let inside = false;
let insideString = false;
let close_char;
for (let i = 0; i < msg.length; i++) {
if (!inside && !insideString && msg[i] == "`") {
inside = true;
close_char = "`";
} else if (!inside && !insideString && msg[i] == "*") {
inside = true;
close_char = "*";
} else if (!inside && !insideString && msg[i] == "_") {
inside = true;
close_char = "_";
} else if (inside && !insideString && msg[i] == close_char) {
inside = false;
} else if (!insideString && msg[i] == '"') {
insideString = true;
} else if (insideString && msg[i] == '"') {
insideString = false;
} else if (!insideString && !inside && msg[i] == "@") {
let username = "";
i++;
while (i < msg.length && username_regex.test(msg[i])) {
username = username + msg[i];
i++;
}
userList.add(username);
isAll = false;
i--;
}
}
return [isAll, userList];
}