-
Notifications
You must be signed in to change notification settings - Fork 2
/
presence.js
80 lines (61 loc) · 1.67 KB
/
presence.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
var EventEmitter = require('events').EventEmitter;
var UserState = {
offline: 0,
online: 1,
away: 2
};
// UserID -> [client, state]
var presence = {};
// Marks a client as online
var online = function(client) {
// If the client isn't auth'd we can't do presence
if (!client.state.auth) return;
// DRY
var uid = client.state.auth.creator;
// Set this client to online
presence[uid] = [client, UserState.online];
// Fire the event for the userid
events.emit(uid, UserState.online);
};
// Marks a client as offline
var offline = function(client) {
//iIf the client isn't auth'd we can't do presence
if (!client.state.auth) return;
// DRY
var uid = client.state.auth.creator;
// Mark them as offline by removing them from the presence list
delete presence[uid];
// Fire the event for the userid
events.emit(uid, UserState.offline);
};
// Marks a client as away
var away = function(client) {
// If the client isn't auth'd we can't do presence
if (!client.state.auth) return;
// DRY
var uid = client.state.auth.creator;
// Mark them as away
presence[uid] = [client, UserState.away];
// Fire the event for the userid
events.emit(uid, UserState.away);
};
var getState = function(uid) {
if (presence[uid])
return presence[uid][1];
else
return UserState.offline;
};
var getClient = function(uid) {
return presence[uid] ? presence[uid][0] : null;
};
// General Exports
exports.online = online;
exports.offline = offline;
exports.away = away;
exports.getState = getState;
exports.getClient = getClient;
exports.UserState = UserState;
// Event handling
var events = new EventEmitter();
events.setMaxListeners(0);
exports.events = events;