generated from jphacks/JP_sample
-
Notifications
You must be signed in to change notification settings - Fork 0
/
events.ts
99 lines (87 loc) · 2.47 KB
/
events.ts
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
import { Server, Socket } from "socket.io";
import {
initEventInterface,
messageDownEventInterface,
updateEventInterface,
User,
} from "../types/interface.js";
import { hashIPAddress } from "../utils/hash.js";
import {
getLocalUser,
createGroup,
setUser,
groups,
users,
removeUser,
} from "../utils/users.js";
const emitUpdate = (io: Server, groupId: number) => {
groups[groupId].forEach((socketId: string) => {
io.to(socketId).emit(
"update",
groups[groupId].map(
(socketId): updateEventInterface => ({
name: users[socketId].name,
addressHash: users[socketId].addressHash,
})
)
);
});
};
export const createInitEvent = (socket: Socket, io: Server) => {
socket.on("init", ({ name, position }: initEventInterface) => {
console.log("Received init: ", name, position);
// validate position
if (!position.latitude || !position.longitude) {
console.log("Invalid position");
console.log("name: ", name);
return;
}
const localUser = getLocalUser(position);
let groupId;
if (!localUser) {
groupId = createGroup();
} else {
groupId = localUser.groupId;
}
const ipHeader = socket.handshake.headers["x-forwarded-for"];
const ip = Array.isArray(ipHeader)
? ipHeader[0]
: ipHeader
? ipHeader.split(",")[0]
: socket.handshake.address;
const addressHash = hashIPAddress(ip);
const user: User = {
name,
position,
groupId,
addressHash: addressHash,
};
setUser(socket.id, user);
emitUpdate(io, groupId);
});
};
export const createDisconnectEvent = (socket: Socket, io: Server) => {
socket.on("disconnect", () => {
const groupId = users[socket.id].groupId;
removeUser(socket.id);
emitUpdate(io, groupId);
console.log("User disconnected");
});
};
export const createMessageEvent = (socket: Socket, io: Server) => {
socket.on("message", (message) => {
console.log("Received message: ", message);
console.log("user id: ", socket.id);
console.log("group id: ", users[socket.id].groupId);
groups[users[socket.id].groupId].forEach((socketId: string) => {
const messageData: messageDownEventInterface = {
name: users[socket.id].name,
addressHash: users[socket.id].addressHash,
format: "text",
message: message,
isSelfMessage: socketId === socket.id,
};
io.to(socketId).emit("message", messageData);
});
});
};