forked from zwily/faye-presence
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
91 lines (76 loc) · 2.53 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
var RedisEngine = require('./lib/redis_engine');
var _ = require('underscore');
exports.setup = function(server, client, options) {
var self = this;
self.engine = options.engine || RedisEngine.create(options.servers);
self.channelRe = options.channelRe || /^\/presence\//;
server.addExtension({
incoming: function(message, callback) {
if (message.channel !== '/meta/subscribe' ||
message.error ||
!message.subscription.match(self.channelRe)) {
return callback(message);
}
if (!message.ext || !message.ext.presence || !message.ext.presence.id) {
message.error = 'No presence id specified in presence subscription';
return callback(message);
}
var data = message.ext.presence;
if (data) {
data = JSON.stringify(data);
}
self.engine.addClient(
message.subscription,
message.clientId,
message.ext.presence.id,
data,
function(err, isNew) {
if (err) {
message.error = 'An error occurred subscribing to presence channel';
console.log('error adding client to channel', err, message);
return callback(message);
}
if (isNew) {
var publish = {
subscribe: {}
};
publish.subscribe[message.ext.presence.id] = message.ext.presence;
client.publish(message.subscription, publish);
}
return callback(message);
}
);
},
outgoing: function(message, callback) {
if (message.channel !== '/meta/subscribe' ||
message.error ||
!message.subscription.match(self.channelRe)) {
return callback(message);
}
self.engine.getSubscribers(message.subscription, function(err, subscribers) {
subscribers = _.mapObject(subscribers, function(val) {
return JSON.parse(val);
});
message.ext = message.ext || {};
message.ext.presence = { subscribe: subscribers };
return callback(message);
});
}
});
server.on('unsubscribe', function(clientId, channel) {
if (!channel.match(self.channelRe)) {
return;
}
self.engine.unsubscribe(channel, clientId, function(err, presenceId, isLast) {
if (err) {
console.log('error unsubscribing', clientId, channel, err);
return;
}
if (isLast) {
var publish = { unsubscribe: {} };
publish.unsubscribe[presenceId] = null;
client.publish(channel, publish);
}
});
});
}