-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
88 lines (77 loc) · 2.4 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
import express from 'express';
import { createServer } from 'node:http';
import { Server } from 'socket.io'
const app = express();
const server = createServer(app);
const io = new Server(server, {
cors: {
origin: '*',
}
});
const port = process.env.PORT || 3000
app.get('/', (req, res) => {
res.send('Welcome to socket io of virtual meet');
});
const users = {};
const admins = []
const rooms = io.sockets.adapter.rooms;
io.on('connection', (socket) => {
let currRoom;
socket.on('join', (room) => {
const roomValues = [...rooms].map(([roo]) => roo);
if(room){
if(roomValues.includes(room)){
socket.join(room);
socket.emit('joined-room', room)
}else {
socket.emit('joined-room', false)
}
}else{
let roomId = generateId()
while (roomValues.includes(roomId)) {
roomId = generateId()
}
socket.join(roomId)
admins.push(socket.id)
socket.emit('joined-room', roomId)
console.log(socket.id, 'created room:', roomId)
}
})
socket.on('user-model', (data) => {
currRoom = [...socket.rooms][1];
users[currRoom] = {...users[currRoom], [socket.id]: data};
});
socket.on('get-all-users', () => {
currRoom = [...socket.rooms][1]
const allUsers = { ...users[currRoom] }
delete allUsers[socket.id]
socket.emit('all-users', allUsers);
});
socket.on('disconnect', () => {
if (currRoom && users[currRoom] && users[currRoom][socket.id]) {
const data = users[currRoom][socket.id];
socket.broadcast.to(currRoom).emit('user-disconnected', {socketId: socket.id, peerId: data['peerId']});
delete users[currRoom][socket.id]
}
if (currRoom && users[currRoom] && Object.keys(users[currRoom]).length === 0) {
delete users[currRoom]
console.log('deleted room:', currRoom)
}
});
socket.on('end-for-all', () => {
if(admins.includes(socket.id)){
socket.broadcast.to(currRoom).emit('admin-ended-call')
}
})
});
server.listen(port, () => {
console.log(`server running at port ${port}`);
});
const generateId = () => {
const characters = 'abcdefghijklmnopqrstuvwxyz0123456789';
let randomCode = '';
for (let i = 0; i < 6; i++) {
randomCode += characters.charAt(Math.floor(Math.random() * characters.length));
}
return randomCode;
}