/
index.js
246 lines (205 loc) · 5.43 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
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
239
240
241
242
243
244
245
246
/**
* Module dependencies.
*/
var uid2 = require('uid2');
var redis = require('redis').createClient;
var msgpack = require('msgpack-js');
var Adapter = require('socket.io-adapter');
var Emitter = require('events').EventEmitter;
var debug = require('debug')('socket.io-redis');
var async = require('async');
/**
* Module exports.
*/
module.exports = adapter;
/**
* Returns a redis Adapter class.
*
* @param {String} optional, redis uri
* @return {RedisAdapter} adapter
* @api public
*/
function adapter(uri, opts){
opts = opts || {};
// handle options only
if ('object' == typeof uri) {
opts = uri;
uri = null;
}
// opts
var pub = opts.pubClient;
var sub = opts.subClient;
var prefix = opts.key || 'socket.io';
var subEvent = opts.subEvent || 'message';
// init clients if needed
function createClient(redis_opts) {
if (uri) {
// handle uri string
return redis(uri, redis_opts);
} else {
return redis(opts.port, opts.host, redis_opts);
}
}
if (!pub) pub = createClient();
if (!sub) sub = createClient({ return_buffers: true });
// this server's key
var uid = uid2(6);
/**
* Adapter constructor.
*
* @param {String} namespace name
* @api public
*/
function Redis(nsp){
Adapter.call(this, nsp);
this.uid = uid;
this.prefix = prefix;
this.channel = prefix + '#' + nsp.name + '#';
if (String.prototype.startsWith) {
this.channelMatches = function (messageChannel, subscribedChannel) {
return messageChannel.startsWith(subscribedChannel);
}
} else { // Fallback to other impl for older Node.js
this.channelMatches = function (messageChannel, subscribedChannel) {
return messageChannel.substr(0, subscribedChannel.length) === subscribedChannel;
}
}
this.pubClient = pub;
this.subClient = sub;
var self = this;
sub.subscribe(this.channel, function(err){
if (err) self.emit('error', err);
});
sub.on(subEvent, this.onmessage.bind(this));
}
/**
* Inherits from `Adapter`.
*/
Redis.prototype.__proto__ = Adapter.prototype;
/**
* Called with a subscription message
*
* @api private
*/
Redis.prototype.onmessage = function(channel, msg){
if (!this.channelMatches(channel.toString(), this.channel)) {
return debug('ignore different channel');
}
var args = msgpack.decode(msg);
var packet;
if (uid == args.shift()) return debug('ignore same uid');
packet = args[0];
if (packet && packet.nsp === undefined) {
packet.nsp = '/';
}
if (!packet || packet.nsp != this.nsp.name) {
return debug('ignore different namespace');
}
args.push(true);
this.broadcast.apply(this, args);
};
/**
* Broadcasts a packet.
*
* @param {Object} packet to emit
* @param {Object} options
* @param {Boolean} whether the packet came from another node
* @api public
*/
Redis.prototype.broadcast = function(packet, opts, remote){
Adapter.prototype.broadcast.call(this, packet, opts);
if (!remote) {
var chn = prefix + '#' + packet.nsp + '#';
var msg = msgpack.encode([uid, packet, opts]);
if (opts.rooms) {
opts.rooms.forEach(function(room) {
var chnRoom = chn + room + '#';
pub.publish(chnRoom, msg);
});
} else {
pub.publish(chn, msg);
}
}
};
/**
* Subscribe client to room messages.
*
* @param {String} client id
* @param {String} room
* @param {Function} callback (optional)
* @api public
*/
Redis.prototype.add = function(id, room, fn){
debug('adding %s to %s ', id, room);
var self = this;
Adapter.prototype.add.call(this, id, room);
var channel = prefix + '#' + this.nsp.name + '#' + room + '#';
sub.subscribe(channel, function(err){
if (err) {
self.emit('error', err);
if (fn) fn(err);
return;
}
if (fn) fn(null);
});
};
/**
* Unsubscribe client from room messages.
*
* @param {String} session id
* @param {String} room id
* @param {Function} callback (optional)
* @api public
*/
Redis.prototype.del = function(id, room, fn){
debug('removing %s from %s', id, room);
var self = this;
var hasRoom = this.rooms.hasOwnProperty(room);
Adapter.prototype.del.call(this, id, room);
if (hasRoom && !this.rooms[room]) {
var channel = prefix + '#' + this.nsp.name + '#' + room + '#';
sub.unsubscribe(channel, function(err){
if (err) {
self.emit('error', err);
if (fn) fn(err);
return;
}
if (fn) fn(null);
});
} else {
if (fn) process.nextTick(fn.bind(null, null));
}
};
/**
* Unsubscribe client completely.
*
* @param {String} client id
* @param {Function} callback (optional)
* @api public
*/
Redis.prototype.delAll = function(id, fn){
debug('removing %s from all rooms', id);
var self = this;
var rooms = this.sids[id];
if (!rooms) {
if (fn) process.nextTick(fn.bind(null, null));
return;
}
async.forEach(Object.keys(rooms), function(room, next){
self.del(id, room, next);
}, function(err){
if (err) {
self.emit('error', err);
if (fn) fn(err);
return;
}
delete self.sids[id];
if (fn) fn(null);
});
};
Redis.uid = uid;
Redis.pubClient = pub;
Redis.subClient = sub;
Redis.prefix = prefix;
return Redis;
}