-
Notifications
You must be signed in to change notification settings - Fork 1
/
conference.js
119 lines (101 loc) · 2.98 KB
/
conference.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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
const xss = require("xss");
//Boiler plate code for joining a conference
module.exports = (server) => {
//Updated path to use a specific endpoint
//Use this path on the client side when making connection
var io = require("socket.io")(server, {
path: "/api/v1/conference/join",
});
sanitizeString = (str) => {
return xss(str);
};
//Socket io code
connections = {};
messages = {};
timeOnline = {};
io.on("connection", (socket) => {
socket.on("join-call", (path) => {
if (connections[path] === undefined) {
connections[path] = [];
}
connections[path].push(socket.id);
timeOnline[socket.id] = new Date();
for (let a = 0; a < connections[path].length; ++a) {
io.to(connections[path][a]).emit(
"user-joined",
socket.id,
connections[path]
);
}
if (messages[path] !== undefined) {
for (let a = 0; a < messages[path].length; ++a) {
io.to(socket.id).emit(
"chat-message",
messages[path][a]["data"],
messages[path][a]["sender"],
messages[path][a]["socket-id-sender"]
);
}
}
console.log(path, connections[path]);
});
socket.on("signal", (toId, message) => {
io.to(toId).emit("signal", socket.id, message);
});
socket.on("chat-message", (data, sender) => {
data = sanitizeString(data);
sender = sanitizeString(sender);
var key;
var ok = false;
for (const [k, v] of Object.entries(connections)) {
for (let a = 0; a < v.length; ++a) {
if (v[a] === socket.id) {
key = k;
ok = true;
}
}
}
if (ok === true) {
if (messages[key] === undefined) {
messages[key] = [];
}
messages[key].push({
sender: sender,
data: data,
"socket-id-sender": socket.id,
});
console.log("message", key, ":", sender, data);
for (let a = 0; a < connections[key].length; ++a) {
io.to(connections[key][a]).emit(
"chat-message",
data,
sender,
socket.id
);
}
}
});
socket.on("disconnect", () => {
var diffTime = Math.abs(timeOnline[socket.id] - new Date());
var key;
for (const [k, v] of JSON.parse(
JSON.stringify(Object.entries(connections))
)) {
for (let a = 0; a < v.length; ++a) {
if (v[a] === socket.id) {
key = k;
for (let a = 0; a < connections[key].length; ++a) {
io.to(connections[key][a]).emit("user-left", socket.id);
}
var index = connections[key].indexOf(socket.id);
connections[key].splice(index, 1);
console.log(key, socket.id, Math.ceil(diffTime / 1000));
if (connections[key].length === 0) {
delete connections[key];
}
}
}
}
});
});
};