-
Notifications
You must be signed in to change notification settings - Fork 62
/
client.js
457 lines (341 loc) · 12 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
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
var EventEmitter = require('events').EventEmitter;
var util = require('util');
var _ = require('lodash');
var MiddlewareHandler = require('middleware-handler');
var MiddlewareStream = require('./middlewarestream');
var IrcCommandHandler = require('./commands/').CommandHandler;
var Connection = require('./connection');
var NetworkInfo = require('./networkinfo');
var User = require('./user');
var Channel = require('./channel');
function IrcClient() {
EventEmitter.call(this);
// Provides middleware hooks for either raw IRC commands or the easier to use parsed commands
this.raw_middleware = new MiddlewareHandler();
this.parsed_middleware = new MiddlewareHandler();
this.request_extra_caps = [];
}
util.inherits(IrcClient, EventEmitter);
module.exports = IrcClient;
IrcClient.prototype._applyDefaultOptions = function(user_options) {
var defaults = {
nick: 'ircbot',
username: 'ircbot',
gecos: 'ircbot',
encoding: 'utf8',
version: 'node.js irc-framework',
auto_reconnect: true,
auto_reconnect_wait: 4000,
auto_reconnect_max_retries: 3,
ping_interval: 30,
ping_timeout: 120
};
var props = Object.keys(defaults);
for (var i = 0; i < props.length; i++) {
if (typeof user_options[props[i]] === 'undefined') {
user_options[ props[ i ] ] = defaults[ props[ i ] ];
}
}
return user_options;
};
IrcClient.prototype.requestCap = function(cap) {
this.request_extra_caps = this.request_extra_caps.concat(cap);
};
IrcClient.prototype.use = function(middleware_fn) {
middleware_fn(this, this.raw_middleware, this.parsed_middleware);
return this;
};
IrcClient.prototype.connect = function(options) {
var client = this;
this.options = options;
this._applyDefaultOptions(this.options);
if (this.connection && this.connection.connected) {
this.connection.end();
}
this.connection = new Connection(this.options);
this.network = new NetworkInfo();
this.user = new User({
nick: options.nick,
username: options.username,
gecos: options.gecos
});
this.command_handler = new IrcCommandHandler(this.connection, this.network);
this.command_handler.requestExtraCaps(this.request_extra_caps);
client.addCommandHandlerListeners();
// Proxy some connection events onto this client
[
'reconnecting',
'close',
'socket close',
'socket error',
'raw socket connected',
'debug',
'raw'
].forEach(function(event_name) {
client.connection.on(event_name, function() {
var args = Array.prototype.slice.call(arguments);
client.emit.apply(client, [event_name].concat(args));
});
});
this.connection.on('socket connected', function() {
client.emit('socket connected');
client.registerToNetwork();
client.startPeriodicPing();
});
// IRC command routing
this.connection
.pipe(new MiddlewareStream(this.raw_middleware, this))
.pipe(this.command_handler);
// Proxy the command handler events onto the client object, with some added sugar
this.proxyIrcEvents();
// Everything is setup and prepared, start connecting
this.connection.connect();
};
// Proxy the command handler events onto the client object, with some added sugar
// Events are handled in order:
// 1. Received from the command handler
// 2. Checked if any extra properties/methods are to be added to the event + re-emitted
// 3. Routed through middleware
// 4. Emitted from the client instance
IrcClient.prototype.proxyIrcEvents = function() {
var client = this;
this.command_handler.on('all', function(event_name, event_arg) {
client.resetPingTimer();
// Add a reply() function to selected message events
if (['privmsg', 'notice', 'action'].indexOf(event_name) > -1) {
event_arg.reply = function(message) {
var dest = event_arg.target === client.user.nick ?
event_arg.nick :
event_arg.target;
client.say(dest, message);
};
// These events with .reply() function are all messages. Emit it separately
// TODO: Should this consider a notice a message?
client.command_handler.emit('message', _.extend({type: event_name}, event_arg));
}
client.parsed_middleware.handle([event_name, event_arg, client], function(err) {
if (err) {
//console.error('Middleware error', err.stack);
return;
}
client.emit(event_name, event_arg);
});
});
};
IrcClient.prototype.addCommandHandlerListeners = function() {
var client = this;
var commands = this.command_handler;
commands.on('nick', function(event) {
if (client.user.nick === event.nick) {
client.user.nick = event.new_nick;
}
});
commands.on('registered', function(event) {
client.emit('connected', event);
client.user.nick = event.nick;
client.connection.registeredSuccessfully();
});
// Don't let IRC ERROR command kill the node.js process if unhandled
commands.on('error', function(event) {
});
};
IrcClient.prototype.registerToNetwork = function() {
var webirc = this.options.webirc;
if (webirc) {
this.raw('WEBIRC', webirc.password, webirc.username, webirc.hostname, webirc.address);
}
this.raw('CAP LS');
if (this.options.password) {
this.raw('PASS', this.options.password);
}
this.raw('NICK', this.user.nick);
this.raw('USER', this.user.username, 0, '*', this.user.gecos);
};
IrcClient.prototype.startPeriodicPing = function() {
var that = this;
var ping_timer = null;
var timeout_timer = null;
if(that.options.ping_interval <= 0 || that.options.ping_timeout <= 0) {
return;
}
function scheduleNextPing() {
ping_timer = that.connection.setTimeout(pingServer, that.options.ping_interval*1000);
}
function resetPingTimer() {
if(ping_timer) {
that.connection.clearTimeout(ping_timer);
}
if(timeout_timer) {
that.connection.clearTimeout(timeout_timer);
}
scheduleNextPing();
}
function pingServer() {
timeout_timer = that.connection.setTimeout(pingTimeout, that.options.ping_timeout*1000);
that.ping();
}
function pingTimeout() {
that.emit('ping timeout');
that.quit('Ping timeout (' + that.options.ping_timeout + ' seconds)');
}
this.resetPingTimer = resetPingTimer;
scheduleNextPing();
};
IrcClient.prototype.resetPingTimer = function() {};
Object.defineProperty(IrcClient.prototype, 'connected', {
enumerable: true,
get: function() {
return this.connection && this.connection.connected;
}
});
/**
* Client API
*/
IrcClient.prototype.raw = function(input) {
this.connection.write(this.rawString.apply(this, arguments));
};
IrcClient.prototype.rawString = function(input) {
var args;
if (input.constructor === Array) {
args = input;
} else {
args = Array.prototype.slice.call(arguments, 0);
}
args = args.filter(function(item) {
return (typeof item === 'number' || typeof item === 'string');
});
if (args.length > 1 && args[args.length - 1].match(/^:|\s/)) {
args[args.length - 1] = ':' + args[args.length - 1];
}
return args.join(' ');
};
IrcClient.prototype.quit = function(message) {
this.connection.end(this.rawString('QUIT', message));
};
IrcClient.prototype.ping = function(message) {
this.raw('PING', message || '*');
};
IrcClient.prototype.changeNick = function(nick) {
this.raw('NICK', nick);
};
IrcClient.prototype.say = function(target, message) {
var that = this;
// Maximum length of target + message we can send to the IRC server is 500 characters
// but we need to leave extra room for the sender prefix so the entire message can
// be sent from the IRCd to the target without being truncated.
var blocks = truncateString(message, 350);
blocks.forEach(function(block) {
that.raw('PRIVMSG', target, block);
});
};
IrcClient.prototype.notice = function(target, message) {
var that = this;
// Maximum length of target + message we can send to the IRC server is 500 characters
// but we need to leave extra room for the sender prefix so the entire message can
// be sent from the IRCd to the target without being truncated.
var blocks = truncateString(message, 350);
blocks.forEach(function(block) {
that.raw('NOTICE', target, block);
});
};
IrcClient.prototype.join = function(channel, key) {
var raw = ['JOIN', channel];
if (key) {
raw.push(key);
}
this.raw(raw);
};
IrcClient.prototype.part = function(channel, message) {
var raw = ['PART', channel];
if (message) {
raw.push(message);
}
this.raw(raw);
};
IrcClient.prototype.ctcpRequest = function(target, type /*, paramN*/) {
var params = Array.prototype.slice.call(arguments, 2);
this.raw(
'PRIVMSG',
target,
String.fromCharCode(1) + type.toUpperCase() + ' ' +
params.join(' ') + String.fromCharCode(1)
);
};
IrcClient.prototype.ctcpResponse = function(target, type /*, paramN*/) {
var params = Array.prototype.slice.call(arguments, 2);
this.raw(
'NOTICE',
target,
String.fromCharCode(1) + type.toUpperCase() + ' ' +
params.join(' ') + String.fromCharCode(1)
);
};
IrcClient.prototype.action = function(target, message) {
var that = this;
// Maximum length of target + message we can send to the IRC server is 500 characters
// but we need to leave extra room for the sender prefix so the entire message can
// be sent from the IRCd to the target without being truncated.
var blocks = truncateString(message, 350);
blocks.forEach(function(block) {
that.ctcpRequest(target, 'ACTION', block);
});
};
IrcClient.prototype.whois = function(target, cb) {
var client = this;
this.on('whois', function onWhois(event) {
if (event.nick.toLowerCase() === target.toLowerCase()) {
client.removeListener('whois', onWhois);
if (typeof cb === 'function') {
cb(event);
}
}
});
this.raw('WHOIS', target);
};
/**
* Explicitely start a channel list, avoiding potential issues with broken IRC servers not sending RPL_LISTSTART
*/
IrcClient.prototype.list = function(/* paramN */) {
var args = Array.prototype.slice(arguments, 0);
this.command_handler.cache('chanlist').channels = [];
args.unshift('LIST');
this.raw(args);
};
IrcClient.prototype.channel = function(channel_name) {
return new Channel(this, channel_name);
};
IrcClient.prototype.match = function(match_regex, cb, message_type) {
var client = this;
var onMessage = function(event) {
if (event.message.match(match_regex)) {
cb(event);
}
};
this.on(message_type || 'message', onMessage);
return {
stop: function() {
client.removeListener(message_type || 'message', onMessage);
}
};
};
IrcClient.prototype.matchNotice = function(match_regex, cb) {
return this.match(match_regex, cb, 'notice');
};
IrcClient.prototype.matchMessage = function(match_regex, cb) {
return this.match(match_regex, cb, 'privmsg');
};
IrcClient.prototype.matchAction = function(match_regex, cb) {
return this.match(match_regex, cb, 'action');
};
/**
* Truncate a string into blocks of a set size
*/
function truncateString(str, block_size) {
block_size = block_size || 350;
var blocks = [];
var current_pos;
for (current_pos = 0; current_pos < str.length; current_pos = current_pos + block_size) {
blocks.push(str.substr(current_pos, block_size));
}
return blocks;
}