-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
126 lines (103 loc) · 2.88 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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
const express = require('express');
const app = express();
const http = require('http');
const server = http.createServer(app);
const { Server } = require("socket.io");
const { User } = require('./models')
const io = new Server(server);
app.get('/', (req, res) => {
return res.send('ok')
});
app.use(express.static('public'))
async function updateUser(data){
const { id: userId, status } = data
const [user, isCreated] = await User.findOrCreate({
where: {
userId
},
defaults: {
userId,
status
}
})
if(!isCreated){
user.status = status
user.save()
}
}
const socketList = {}, userCache = {};
// first initialize
User.findAll().then(users => {
for(let user of users){
userCache[user.userId] = {
status: user.status
}
}
})
io.on('connection', (socket) => {
const socketId = socket.id
socketList[socketId] = socket
socket.on('agent sub', (data) => {
const { id, status } = data
let cachedStatus = status
if(userCache[id]){
userCache[id].socketId = socketId
cachedStatus = userCache[id].status
}
else {
userCache[id] = {
socketId,
status
}
}
const updatedData = {
id, status: cachedStatus
}
io.in('admin room').emit('agent update', updatedData)
socket.emit('agent update', updatedData)
if(socketList[socketId])
socketList[socketId].userId = id
socket.join('agent room')
updateUser(updatedData)
})
socket.on('admin sub', () => {
const userList = []
for(const key in userCache){
userList.push({
id: key,
...userCache[key]
})
}
socket.join('admin room')
socket.emit('admin sub', userList)
})
socket.on('agent update', async (data) => {
const uc = userCache[data.id]
if(uc){
uc.status = data.status
io.in('admin room').emit('agent update', data)
io.in('agent room').emit('agent update', data)
updateUser(data)
}
})
socket.on('disconnect', () => {
const userId = socketList[socketId].userId
if(userId && userCache[userId]){
const uc = userCache[userId]
uc.status = 'offline'
delete uc.socketId
const data = {
id: userId,
status: 'offline'
}
io.in('agent room').emit('agent update', data)
io.in('admin room').emit('agent update', data)
updateUser(data)
}
// remove object
delete socketList[socketId]
});
});
server.listen(3000, () => {
console.log('listening on *:3000');
});