-
Notifications
You must be signed in to change notification settings - Fork 1
/
socketManager.js
100 lines (81 loc) · 2.97 KB
/
socketManager.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
import { Server } from "socket.io";
import { sessionMiddleware } from "./utils/session.js";
import { FindIfPlayerInMatch } from "./matchManager.js";
import { GetMatch, GetUserRole } from "./database.js";
import { userRoles } from "./public/constants/userData.js";
import { instrument } from "@socket.io/admin-ui";
let io;
var connected = false;
export function CreateSocketConnection (server){
if (connected) return;
console.log("Setting up socket connection");
io = new Server(server, {
cors: {
origin: ["https://admin.socket.io"],
credentials: true
}
});
io.engine.use(sessionMiddleware);
io.on("connection", socket => {
//join match id as room
socket.on('join', function(room){
if (typeof(room) !== 'string') return;
const userId = socket.request.session.user;
if (room == 'userRoom'){
if (!userId) return;
let userQueRoom = 'userRoom' + userId;
socket.join(userQueRoom);
return;
}
if (room.slice(0, 5) == 'match'){
SocketJoinMatchRoom(socket, room);
}
});
/*socket.on('disconnect',function(){
console.log("disconnected, " + socket.id);
});*/
});
if (process.env.ADMIN_IO_ENABLED === 'true'){
console.log("Setting up socket admin page");
instrument(io, {
auth: {
type: "basic",
username: 'admin',
password: "$2b$10$TgmL4SJUGCI42Kh1GN8vDuiEMw7bJHHtWnkQM7gyEWv6KtiR/YjaO"
},
mode: (process.env.ADMIN_IO_ADVANCED === 'true') ? "development" : "production",
});
}
if (process.env.LOG_SOCKET_ERRORS === 'true'){
io.engine.on("connection_error", (err) => {
console.log("socket connection error");
console.log(err.req); // the request object
console.log(err.code); // the error code, for example 1
console.log(err.message); // the error message, for example "Session ID unknown"
console.log(err.context); // some additional error context
});
}
connected = true;
};
async function SocketJoinMatchRoom(socket, room){
const userId = socket.request.session.user;
const roomId = room.slice(5);
if (!roomId) return;
if (!userId) return;
//find if user in active match
if (FindIfPlayerInMatch(userId)) socket.join(room);
//find if user is in inactive match
const match = await GetMatch(roomId);
if (match){
if (match.player1_id == userId || match.player2_id == userId) socket.join(room);
}
//if user is mod
const userRole = await GetUserRole(userId);
if (userRole == userRoles.mod) socket.join(room);
}
export function SendSocketMessage(roomId, key, message){
io.to(roomId).emit(key, message);
}
export function SendEmptySocketMessage(roomId, key){
io.to(roomId).emit(key);
}