forked from SocketCluster/sc-stateless-presence
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.js
238 lines (206 loc) · 8.18 KB
/
client.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
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
const isEmpty = require('lodash.isempty');
const StreamDemux = require('stream-demux');
let SCStatelessPresenceClient = function (socket, options) {
options = options || {};
this.presenceChannelPrefix = 'presence>';
this.socket = socket;
this.channelUsers = {};
this.channelPresenceTrackerStreams = {};
this._trackerStreamMultiplexer = new StreamDemux();
this.socket.options.autoSubscribeOnConnect = false;
this.presenceCheckInterval = options.presenceCheckInterval || 1000;
this._setupPresenceExpiryInterval();
let lastSocketId = null;
let setupSocketChannel = () => {
lastSocketId = socket.id;
if (this._lastSocketChannel) {
this._lastSocketChannel.unsubscribe();
this._lastSocketChannel.kill();
}
let socketChannelName = this._getSocketPresenceChannelName(lastSocketId);
let socketChannel = this.socket.subscribe(socketChannelName);
this._lastSocketChannel = socketChannel;
// Give socketChannel a higher priority, that way it will subscribe first.
let maxPriority = 0;
let subscriptions = this.socket.subscriptions(true);
subscriptions.forEach((channelName) => {
let priority = socket.channel(channelName).priority;
if (priority > maxPriority) {
maxPriority = priority;
}
});
socketChannel.priority = maxPriority + 1;
(async () => {
// Set up a loop to handle remote transmitted events.
for await (let presencePacket of socketChannel.listener('message')) {
if (presencePacket.type == 'pong') {
this._markUserAsPresent(presencePacket.channel, presencePacket.username, Date.now() + presencePacket.timeout);
}
}
})();
this.socket.processPendingSubscriptions();
};
this._connectConsumer = this.socket.listener('connect').createConsumer();
this._closeConsumer = this.socket.listener('close').createConsumer();
if (this.socket.state == 'open') {
setupSocketChannel();
}
(async () => {
// Set up a loop to handle remote transmitted events.
for await (let message of this._connectConsumer) {
setupSocketChannel();
}
})();
(async () => {
// Set up a loop to handle remote transmitted events.
for await (let message of this._closeConsumer) {
let socketChannelName = this._getSocketPresenceChannelName(lastSocketId);
this.socket.unsubscribe(socketChannelName);
Object.keys(this.channelUsers).forEach((channelName) => {
Object.keys(this.channelUsers[channelName] || {}).forEach((username) => {
let userData = this.channelUsers[channelName][username];
this._markUserAsAbsent(channelName, username);
});
});
}
})();
};
SCStatelessPresenceClient.prototype._getSocketPresenceChannelName = function (socketId) {
return this.presenceChannelPrefix + 'socket/' + socketId;
};
SCStatelessPresenceClient.prototype._setupPresenceExpiryInterval = function () {
this._presenceExpiryInterval = setInterval(() => {
Object.keys(this.channelUsers).forEach((channelName) => {
Object.keys(this.channelUsers[channelName] || {}).forEach((username) => {
let userData = this.channelUsers[channelName][username];
if (userData.expiry < Date.now()) {
this._markUserAsAbsent(channelName, username);
}
});
});
}, this.presenceCheckInterval);
};
SCStatelessPresenceClient.prototype.isPresent = function (channelName, username) {
return !!(this.channelUsers[channelName] && this.channelUsers[channelName][username]);
};
SCStatelessPresenceClient.prototype.getPresenceList = function (channelName) {
let userMap = this.channelUsers[channelName];
let userList = [];
for (let username in userMap) {
if (userMap.hasOwnProperty(username)) {
userList.push(username);
}
}
return userList;
};
SCStatelessPresenceClient.prototype._markUserAsPresent = function (channelName, username, expiry) {
if (!this.channelUsers[channelName]) {
this.channelUsers[channelName] = {};
}
if (!this.channelUsers[channelName][username]) {
this.channelUsers[channelName][username] = {};
}
let userData = this.channelUsers[channelName][username];
userData.expiry = expiry;
if (!userData.isPresent) {
userData.isPresent = true;
let presenceChannelName = this.presenceChannelPrefix + channelName;
this._trackerStreamMultiplexer.write(presenceChannelName, {
action: 'join',
username: username
});
}
};
SCStatelessPresenceClient.prototype._markUserAsAbsent = function (channelName, username) {
if (!this.channelUsers[channelName]) {
return;
}
let userData = this.channelUsers[channelName][username];
if (userData) {
delete this.channelUsers[channelName][username];
if (userData.isPresent) {
delete userData.isPresent;
let presenceChannelName = this.presenceChannelPrefix + channelName;
this._trackerStreamMultiplexer.write(presenceChannelName, {
action: 'leave',
username: username
});
}
}
if (isEmpty(this.channelUsers[channelName])) {
delete this.channelUsers[channelName];
}
};
SCStatelessPresenceClient.prototype._sendSocketChannelPong = function (socket, channelName, presencePacket) {
if (socket.authToken && socket.authToken.username != null) {
let socketChannelName = this._getSocketPresenceChannelName(presencePacket.socketId);
socket.transmitPublish(socketChannelName, {
type: 'pong',
channel: channelName,
username: socket.authToken.username,
timeout: presencePacket.timeout
});
}
};
SCStatelessPresenceClient.prototype.trackPresence = function (channelName) {
let presenceChannelName = this.presenceChannelPrefix + channelName;
this.socket.subscribe(presenceChannelName);
let substream = this._trackerStreamMultiplexer.stream(presenceChannelName);
this.channelPresenceTrackerStreams[channelName] = true;
(async () => {
let channel = this.socket.channel(presenceChannelName)
// Set up a loop to handle remote transmitted events.
for await (let presencePacket of channel) {
let now = Date.now();
if (presencePacket.type == 'join') {
// A socket can join without necessarily having a user attached (not authenticated);
// in this case we won't have any new user to mark as present but we will pong back
// the socket anyway with the current socket's presence status.
if (presencePacket.username != null) {
this._markUserAsPresent(channelName, presencePacket.username, now + presencePacket.timeout);
}
this._sendSocketChannelPong(this.socket, channelName, presencePacket);
} else if (presencePacket.type == 'ping') {
presencePacket.users.forEach((username) => {
this._markUserAsPresent(channelName, username, now + presencePacket.timeout);
});
} else if (presencePacket.type == 'leave') {
this._markUserAsAbsent(channelName, presencePacket.username);
}
}
})();
return substream;
};
SCStatelessPresenceClient.prototype._cleanupPresenceChannelTracking = function (channelName, presenceChannelName) {
let channel = this.socket.channel(presenceChannelName);
if (channel) {
channel.unsubscribe();
channel.kill();
delete this.channelPresenceTrackerStreams[channelName];
delete this.channelUsers[channelName];
}
};
SCStatelessPresenceClient.prototype.untrackPresence = function (channelName) {
let presenceChannelName = this.presenceChannelPrefix + channelName;
this._cleanupPresenceChannelTracking(channelName, presenceChannelName);
};
SCStatelessPresenceClient.prototype.untrackAllPresences = function () {
let presenceChannels = Object.keys(this.channelPresenceTrackerStreams);
for (let channelName of presenceChannels) {
this.untrackPresence(channelName);
}
}
SCStatelessPresenceClient.prototype.destroy = function () {
clearInterval(this._presenceExpiryInterval);
this.untrackAllPresences();
this._connectConsumer.kill();
this._closeConsumer.kill();
if (this._lastSocketChannel) {
this._lastSocketChannel.unsubscribe();
this._lastSocketChannel.kill();
}
};
module.exports.SCStatelessPresenceClient = SCStatelessPresenceClient;
module.exports.create = function (socket, options) {
return new SCStatelessPresenceClient(socket, options);
};