Repository navigation
Expand file tree
/
Copy pathclient.js
More file actions
539 lines (442 loc) · 13.5 KB
/
Copy pathclient.js
File metadata and controls
539 lines (442 loc) · 13.5 KB
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
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
/**
*
* See [the RTM client events](../events/client) for details of the client event lifecycle.
*/
var bind = require('lodash').bind;
var cloneDeep = require('lodash').cloneDeep;
var contains = require('lodash').contains;
var inherits = require('inherits');
var isUndefined = require('lodash').isUndefined;
var RTM_API_EVENTS = require('../events/rtm').EVENTS;
var RTM_CLIENT_INTERNAL_EVENT_TYPES = [
'pong',
RTM_API_EVENTS.HELLO,
RTM_API_EVENTS.TEAM_MIGRATION_STARTED,
];
var UNRECOVERABLE_RTM_START_ERRS = [
'not_authed',
'invalid_auth',
'account_inactive',
];
var CLIENT_EVENTS = require('../events/client').RTM;
var BaseAPIClient = require('../client');
var RtmFacet = require('../web/facets').RtmFacet;
var makeMessageEventWithSubtype = require('../events/utils').makeMessageEventWithSubtype;
var wsSocketFn = require('../transports/ws');
/**
*
* @param {String} token
* @param {object?} opts
* @param {Function} opts.socketFn A function to call, passing in a websocket URL, that should
* return a websocket instance connected to that URL.
* @param {object} opts.dataStore A store to cache Slack info, e.g. channels, users etc. in.
* @param {boolean} opts.autoReconnect Whether or not to automatically reconnect when the connection
* closes.
* @param {number} opts.maxReconnectionAttempts
* @param {number} opts.reconnectionBackoff
* @param {number} opts.wsPingInterval
* @param {number} opts.maxPongInterval
* @param {string} opts.logLevel The log level for the logger.
* @param {Function} opts.logger Function to use for log calls, takes (logLevel, logString)
* parameters.
* @param {SlackDataStore} opts.dataStore
* @constructor
*/
function RTMClient(token, opts) {
var clientOpts = opts || {};
// Force the max request concurrency to 1 for the RTM client. This is because it should not be
// trying to rtm.start in parallel.
clientOpts.maxRequestConcurrency = 1;
BaseAPIClient.call(this, token, clientOpts);
/**
* @type {Function}
*/
this._socketFn = clientOpts.socketFn || wsSocketFn;
/**
* The active websocket.
* @type {Object}
*/
this.ws = undefined;
if (!isUndefined(clientOpts.dataStore)) {
this.registerDataStore(clientOpts.dataStore);
}
this.MAX_RECONNECTION_ATTEMPTS = clientOpts.maxReconnectionAttempts || 10;
this.RECONNECTION_BACKOFF = clientOpts.reconnectionBackoff || 3000;
this.MAX_PONG_INTERVAL = clientOpts.maxPongInterval || 10000;
this.WS_PING_INTERVAL = clientOpts.wsPingInterval || 5000;
this.autoReconnect = clientOpts.autoReconnect !== false;
}
inherits(RTMClient, BaseAPIClient);
/**
* @type {boolean}
*/
RTMClient.prototype.connected = false;
/**
* @type {boolean}
*/
RTMClient.prototype.authenticated = false;
/**
* The id of the user that's currently connected via this client.
* @type {string}
*/
RTMClient.prototype.activeUserId = undefined;
/**
* The id of the team that's currently connected via this client.
* @type {string}
*/
RTMClient.prototype.activeTeamId = undefined;
/**
* Maps message id to message object for messages sent to but not replied to by the remote server.
* @type {Object}
* @private
*/
RTMClient.prototype._pendingMessages = {};
/**
* The timer repeatedly pinging the server to let it know the client is still alive.
* @type {?}
*/
RTMClient.prototype._pingTimer = null;
/**
* The time the last pong was received from the server.
* @type {number}
* @private
*/
RTMClient.prototype._lastPong = 0;
/**
*
* @type {number}
* @private
*/
RTMClient.prototype._connAttempts = 0;
/**
* Whether the server is currently connecting.
* @type {boolean}
* @private
*/
RTMClient.prototype._connecting = false;
/**
* Whether the server is currently re-connecting.
* @type {boolean}
* @private
*/
RTMClient.prototype._reconnecting = false;
/**
* @type {SlackDataStore}
*/
RTMClient.prototype.dataStore = undefined;
/** @inheritDoc */
RTMClient.prototype._createFacets = function _createFacets() {
RTMClient.super_.prototype._createFacets.call(this);
/**
* Allows the RTM client to get setup without needing to have a full web client.
* @type {RtmFacet}
* @private
*/
this._rtm = new RtmFacet(bind(this.makeAPICall, this));
};
/**
*
* @param {object} opts
*/
RTMClient.prototype.start = function start(opts) {
// Check whether the client is currently attempting to connect to the RTM API.
if (!this._connecting) {
this.logger.log('verbose', 'attempting to connect via the RTM API');
this.emit(CLIENT_EVENTS.CONNECTING);
this._connecting = true;
this._rtm.start(opts, bind(this._onStart, this));
}
};
/**
* @deprecated since version 2.0.0, use start() instead.
*/
RTMClient.prototype.login = function login(opts) {
this.start(opts);
};
/**
* Generates the next message id to use.
*/
RTMClient.prototype.nextMessageId = function nextMessageId() {
this._messageId = this._messageId || 1;
return this._messageId++;
};
/**
*
* @param err
* @param data
* @private
*/
RTMClient.prototype._onStart = function _onStart(err, data) {
var errMsg;
this._connecting = false;
this._reconnecting = false;
if (err || !data.url) {
this.emit(CLIENT_EVENTS.UNABLE_TO_RTM_START, err || data.error);
// Any of these mean this client is unusable, so don't attempt to auto-reconnect
if (data && contains(UNRECOVERABLE_RTM_START_ERRS, data.error)) {
errMsg = 'unrecoverable failure connecting to the RTM API';
this.logger.error(errMsg + ': ' + data.error);
this.disconnect(errMsg, data.error);
} else {
this.logger.info('unable to RTM start, attempting reconnect: ' + err || data.error);
this.authenticated = false;
if (this.autoReconnect) {
this.reconnect();
}
}
} else {
this.logger.verbose('rtm.start successful, attempting to open websocket URL');
this.authenticated = true;
this.activeUserId = data.self.id;
this.activeTeamId = data.team.id;
if (!isUndefined(this.dataStore)) {
this.dataStore.cacheRtmStart(data);
}
this.emit(CLIENT_EVENTS.AUTHENTICATED);
this.connect(data.url);
}
};
/**
* Closes the websocket and tears down the ping function.
* @private
*/
RTMClient.prototype._safeDisconnect = function _safeDisconnect() {
if (this._pingTimer) {
clearInterval(this._pingTimer);
this._pingTimer = null;
}
if (this.ws) {
// Stop listening to the websocket's close event, so that the auto-reconnect logic doesn't fire
// twice.
this.ws.removeAllListeners('close');
this.ws.close();
}
this.authenticated = false;
this.connected = false;
};
/**
* Connects to the RTM API.
* @param {string} socketUrl The URL of the websocket to connect to.
*/
RTMClient.prototype.connect = function connect(socketUrl) {
this.emit(CLIENT_EVENTS.WS_OPENING);
this.ws = this._socketFn(socketUrl);
this.ws.on('open', bind(this.handleWsOpen, this));
this.ws.on('message', bind(this.handleWsMessage, this));
this.ws.on('error', bind(this.handleWsError, this));
this.ws.on('close', bind(this.handleWsClose, this));
this.ws.on('ping', bind(this.handleWsPing, this));
};
/**
* Disconnects from the RTM API.
* @param optReason
* @param optCode
*/
RTMClient.prototype.disconnect = function disconnect(optErr, optCode) {
this.emit(CLIENT_EVENTS.DISCONNECT, optErr, optCode);
this.autoReconnect = false;
this._safeDisconnect();
};
/**
*
*/
RTMClient.prototype.reconnect = function reconnect() {
if (!this._reconnecting) {
this.emit(CLIENT_EVENTS.ATTEMPTING_RECONNECT);
this._reconnecting = true;
this._safeDisconnect();
// TODO(leah): Update this to remove the reconn logic in the RTM client as it should be covered
// by the web client policy
this._connAttempts++;
if (this._connAttempts > this.MAX_RECONNECTION_ATTEMPTS) {
throw new Error('unable to connect to Slack RTM API, failed after max reconnection attempts');
}
setTimeout(bind(this.start, this), this._connAttempts * this.RECONNECTION_BACKOFF);
}
};
/**
* Pings the remote server to let it know the client is still alive.
* @private
*/
RTMClient.prototype._pingServer = function _pingServer() {
var pongInterval;
if (this.connected) {
this.send({ type: 'ping' });
// If the last pong was more than MAX_PONG_INTERVAL, force a reconnect
pongInterval = Date.now() - this._lastPong;
if (pongInterval > this.MAX_PONG_INTERVAL) {
this.reconnect();
}
}
};
/**
* Handler to deal with the WebSocket open event.
* NOTE: this.connected doesn't get set to true until the helloHandler is called.
*/
RTMClient.prototype.handleWsOpen = function handleWsOpen() {
this.emit(CLIENT_EVENTS.WS_OPENED);
this._lastPong = Date.now();
this._connAttempts = 0;
if (this._pingTimer) {
clearInterval(this._pingTimer);
} else {
this._pingTimer = setInterval(bind(this._pingServer, this), this.WS_PING_INTERVAL);
}
};
/**
* Handler to deal with the WebSocket message event.
* @param {object} wsMsg
*/
RTMClient.prototype.handleWsMessage = function handleWsMessage(wsMsg) {
var message;
this.logger.log('debug', wsMsg);
this.emit(CLIENT_EVENTS.RAW_MESSAGE, wsMsg);
try {
message = JSON.parse(wsMsg);
} catch (err) {
// TODO(leah): Emit an event here?
this.logger.debug('unable to parse message: ' + err);
return;
}
if (contains(RTM_CLIENT_INTERNAL_EVENT_TYPES, message.type)) {
this._handleWsMessageInternal(message.type, message);
} else {
this._handleWsMessageViaEventHandler(message.type, message);
}
};
/**
*
* @param {String} messageType
* @param {Object} message
* @private
*/
RTMClient.prototype._handleWsMessageInternal = function _handleWsMessageInternal(
messageType, message) {
if (messageType === 'pong') {
this._handlePong(message);
} else if (messageType === RTM_API_EVENTS.HELLO) {
this._handleHello();
} else if (messageType === RTM_API_EVENTS.TEAM_MIGRATION_STARTED) {
this.reconnect();
this.emit(messageType, message);
}
};
/**
*
* @param {String} messageType
* @param {Object} message
* @private
*/
RTMClient.prototype._handleWsMessageViaEventHandler = function _handleWsMessageViaEventHandler(
messageType, message) {
var replyTo;
if (messageType === RTM_API_EVENTS.MESSAGE) {
replyTo = message.reply_to;
if (replyTo) {
// TODO(leah): figure out how message pushes via the RTM API should work and how any errors
// will be handled
if (this._pendingMessages[replyTo]) {
delete this._pendingMessages[replyTo];
} else {
// If the message was sent in reply to a message that's not on this client, skip the message
return;
}
}
}
if (!isUndefined(this.dataStore)) {
this.dataStore.handleRtmMessage(this.activeUserId, this.activeTeamId, messageType, message);
}
this.emit(messageType, message);
if (messageType === RTM_API_EVENTS.MESSAGE && !isUndefined(message.subtype)) {
this.emit(makeMessageEventWithSubtype(message.subtype), message);
}
};
/**
* Emits the websocket error.
* @param {Object} err
*/
RTMClient.prototype.handleWsError = function handleWsError(err) {
this.logger.debug(err);
this.emit(CLIENT_EVENTS.WS_ERROR, err);
};
/**
*
*/
RTMClient.prototype.handleWsClose = function handleWsClose(code, reason) {
this.connected = false;
this.emit(CLIENT_EVENTS.WS_CLOSE, code, reason);
if (this.autoReconnect) {
if (!this._connecting) {
this.reconnect();
}
} else {
this.disconnect('websocket closed with auto-reconnect false on the RTM client');
}
};
/**
* Handler for the websocket ping event.
* This pongs back to the server to let it know the client is still active.
*/
RTMClient.prototype.handleWsPing = function handleWsPing() {
if (this.ws.pong) {
this.ws.pong();
}
};
/**
* Handles the server's pong message, updating the lastPong time on the client.
* @param {Object} message
*/
RTMClient.prototype._handlePong = function _handlePong(message) {
this._lastPong = Date.now();
delete this._pendingMessages[message.reply_to];
};
/** {@link https://api.slack.com/events/hello|hello} */
RTMClient.prototype._handleHello = function _handleHello() {
this.connected = true;
this.emit(CLIENT_EVENTS.RTM_CONNECTION_OPENED);
};
/**
* Helper for sending a simple message to a channel|group|DM etc via the RTM API.
* @param {string} text The text of the messsage to send.
* @param {string} channelId The id of the channel|group|DM to send this message to.
* @param {Function=} optCb
*/
RTMClient.prototype.sendMessage = function sendMessage(text, channelId, optCb) {
this.send({
text: text,
channel: channelId,
type: RTM_API_EVENTS.MESSAGE,
}, optCb);
};
/**
* Sends a message over the websocket to the server.
* @param {*} message The message to send back to the server.
* @param {Function=} optCb
*/
RTMClient.prototype.send = function send(message, optCb) {
var wsMsg = cloneDeep(message);
var jsonMessage;
var err;
var _this = this;
if (this.connected) {
wsMsg.id = this.nextMessageId();
jsonMessage = JSON.stringify(wsMsg);
this.logger.log('debug', jsonMessage);
this._pendingMessages[wsMsg.id] = wsMsg;
this.ws.send(jsonMessage, undefined, function handleWsMsgResponse(wsRespErr) {
if (!isUndefined(wsRespErr)) {
_this.logger.debug('Unable to send message: ' + wsRespErr);
}
if (!isUndefined(optCb)) {
optCb(wsRespErr);
}
});
} else {
err = 'ws not connected, unable to send message';
this.logger.debug(err);
if (!isUndefined(optCb)) {
optCb(new Error(err));
}
}
};
module.exports = RTMClient;