-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathirc-socket.js
executable file
·445 lines (364 loc) · 13.9 KB
/
irc-socket.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
/**
*
* IRC Socket
*
* Socket that connects to an IRC network and emits each line from the server.
*
* Send messages to server with .raw(String) method.
*/
var EventEmitter = require("events").EventEmitter;
var inspect = require("util").inspect;
var format = require("util").format;
var Promise = require("bluebird");
var rresult = require("r-result");
var Ok = rresult.Ok;
var Fail = rresult.Fail;
var intoPropertyDescriptors = function (object) {
Object.keys(object).forEach(function (key) {
object[key] = { value: object[key] };
});
return object;
};
var includes = function (array, value) {
return array.indexOf(value) !== -1;
};
var pick = function (object, keys) {
var newObject = Object.create(Object.getPrototypeOf(object));
Object.keys(object)
.filter(function (key) { return includes(keys, key); })
.forEach(function (key) { newObject[key] = object[key]; });
return newObject;
};
var copyJsonMaybe = function (object) {
if (!object) {
return undefined;
}
return JSON.parse(JSON.stringify(object));
};
var endsWith = function (string, postfix) {
return string.lastIndexOf(postfix) === string.length - postfix.length;
};
var failures = {
killed: {},
nicknamesUnavailable: {},
badProxyConfiguration: {},
missingRequiredCapabilities: {},
badPassword: {},
socketEnded: {}
};
var Socket = module.exports = function Socket (config, netSocket) {
var socket = Object.create(Socket.prototype);
// Internal implementation values.
socket.impl = netSocket || config.socket;
// status := ["initialized", "connecting", "starting", "running", "closed"]
socket.status = "initialized";
socket.startupPromise = new Promise(function (resolve, reject) {
socket.resolvePromise = resolve;
socket.rejectPromise = reject;
});
// IRC Connection Handshake Options
socket.proxy = config.proxy;
socket.password = config.password;
socket.capabilities = copyJsonMaybe(config.capabilities);
socket.username = config.username;
socket.realname = config.realname;
socket.nicknames = config.nicknames.slice();
socket.connectOptions = typeof config.connectOptions === "object" ? Object.create(config.connectOptions) : {};
socket.connectOptions.port = config.port || 6667;
socket.connectOptions.host = config.server;
// Socket Timeout variables.
// After five minutes without a server response, send a PONG.
// If the server doesn't PING back (or send any message really)
// within five minutes, we'll have assumed we've be DQed, and
// end the socket.
var timeout = null;
var timeoutPeriod = config.timeout || 5 * 60 * 1000;
var onSilence = function () {
timeout = setTimeout(onNoPong, timeoutPeriod);
socket.raw("PING :ignored");
};
var onNoPong = function () {
socket.emit("timeout");
};
// Data event handling.
// Transforms the raw stream of data events into a stream of
// one complete line per data event.
// Also handles timeouts.
var dataHandler = function () {
var emitLine = socket.emit.bind(socket, "data");
var lastLine = "";
var onData = function (data) {
// The data event will occassionally only be partially
// complete. The last line will not end with "\r\n", and
// need to be appended to the beginning of the first line.
//
// If the last line in the data is complete, then lastLine
// will be set to an empty string, and appending an empty
// string to a string does nothing.
var lines = data.split("\r\n");
lines[0] = lastLine + lines[0];
lastLine = lines.pop();
lines.forEach(function (line) {
emitLine(line.normalize());
});
// We've got data. Reset the timeout.
clearTimeout(timeout);
timeout = setTimeout(onSilence, timeoutPeriod);
};
socket.impl.on("data", onData);
}();
socket.on("data", function (line) {
if (line.slice(0, 4) === "PING") {
// On PING, respond with a PONG so that we stay connected.
socket.raw(["PONG", line.slice(line.indexOf(":"))]);
}
});
// Once connected, do the following:
// 1. Send WEBIRC if proxy set.
// 2. Send PASS if set.
// 3. Do capabilities negotiations if set.
// 4. Send USER
// 5. Send NICK until one is accepted.
// 6. Resolve startupPromise.
// TODO(Havvy): Refactor and clean up!!!
socket.impl.once("connect", function doStartup () {
// If `socket.end()` is called before the connect event
// fires, then we ignore the connect event, since we are
// already ending/ended.
if (!socket.startupPromise.isPending()) {
return;
}
socket.status = "starting";
socket.emit("connect");
timeout = setTimeout(onSilence, timeoutPeriod);
if (socket.capabilities) {
socket.capabilities.requires = socket.capabilities.requires || [];
socket.capabilities.wants = socket.capabilities.wants || [];
var serverCapabilties;
var acknowledgedCapabilities = socket.capabilities.requires.slice();
var sentRequests = 0;
var respondedRequests = 0;
var allRequestsSent = false;
}
var nickname;
var sendUser = function () {
socket.raw(format("USER %s 8 * :%s", socket.username, socket.realname));
};
var sendNick = function () {
if (socket.nicknames.length === 0) {
socket.raw("QUIT");
socket.resolvePromise(Fail(failures.nicknamesUnavailable));
return;
}
nickname = socket.nicknames[0];
socket.nicknames.shift();
socket.raw(["NICK", nickname]);
};
var startupHandler = function startupHandler (line) {
var parts = line.split(" ");
// If WEBIRC fails.
if (parts[0] === "ERROR") {
socket.resolvePromise(Fail(failures.badProxyConfiguration));
return;
// Ignore PINGs.
} else if (parts[0] === "PING") {
return;
}
var numeric = parts[1];
if (numeric === "CAP") {
var capabilities = socket.capabilities;
if (parts[3] === "LS") {
serverCapabilties = parts.slice(4);
// Remove the colon off the first capability.
serverCapabilties[0] = serverCapabilties[0].slice(1);
if (capabilities.requires.length !== 0) {
if (capabilities.requires.every(function (capability) {
return includes(serverCapabilties, capability);
}))
{
socket.raw(format("CAP REQ :%s", capabilities.requires.join(" ")));
sentRequests += 1;
} else {
socket.raw("QUIT");
socket.resolvePromise(Fail(failures.missingRequiredCapabilities));
return;
}
}
capabilities.wants
.filter(function (capability) {
return includes(serverCapabilties, capability);
})
.forEach(function (capability) {
socket.raw(format("CAP REQ :%s", capability));
sentRequests += 1;
});
return;
} else if (parts[3] === "NAK") {
respondedRequests += 1;
var capability = parts[4].slice(1);
if (includes(capabilities.requires, capability)) {
socket.raw("QUIT");
socket.resolvePromise(Fail(failures.missingRequiredCapabilities));
return;
}
} else if (parts[3] === "ACK") {
respondedRequests += 1;
var capability = parts[4].slice(1);
if (includes(capabilities.wants, capability)) {
acknowledgedCapabilities.push(capability);
}
}
if (sentRequests === respondedRequests) {
socket.raw("CAP END");
// 4. Send USER
sendUser();
// 5. Send NICK
sendNick();
}
} else if (numeric === "NOTICE") {
if (endsWith(line, "Login unsuccessful")) {
// irc.twitch.tv only in their non-standardness.
// Server doesn't kill the socket, but it doesn't accept input afterwards either.
socket.resolvePromise(Fail(failures.badPassword));
}
} else if (numeric === "001") {
socket.status = "running";
var data = {
capabilities: acknowledgedCapabilities,
nickname: nickname
};
socket.emit("ready", data);
socket.resolvePromise(Ok(data));
} else if (includes(["410", "421"], numeric)) {
// Sent by Twitch.tv when doing a CAP command.
if (socket.capabilities.requires) {
socket.raw("QUIT");
socket.resolvePromise(Fail(failures.missingRequiredCapabilities));
} else {
// 4. Send USER
sendUser();
// 5. Send NICK
sendNick();
}
} else if (numeric === "464") {
// Only sent if a bad password is given.
// Server will end the socket afterwards.
socket.resolvePromise(Fail(failures.badPassword));
} else if (includes(["431", "432", "433", "436", "437", "484"], numeric)) {
// Reasons you cannot use a nickname. We ignore what it is,
// and just try with the next nickname.
sendNick();
} else if (numeric === "PING") {
// PINGs are handled elsewhere, and a known message type.
/* no-op */
}
};
// Subscribe & Unsubscribe
// TODO(Havvy): Return /this/ Promise,
socket.on("data", startupHandler);
socket.startupPromise.finally(function (res) {
socket.removeListener("data", startupHandler);
});
// 1. Send WEBIRC
if (typeof socket.proxy === "object") {
var proxy = socket.proxy;
socket.raw(["WEBIRC", proxy.password, proxy.username, proxy.hostname, proxy.ip]);
}
// 2. Send PASS
// Will force kill connection if wrong.
if (typeof socket.password === "string") {
socket.raw(["PASS", socket.password]);
}
// 3. Send CAP LS
if (typeof socket.capabilities === "object") {
socket.raw("CAP LS");
} else {
// 4. Send USER
sendUser();
// 5. Send NICK.
sendNick();
}
});
socket.impl.on("error", function (error) {
socket.status = "closed";
socket.emit("error", error);
});
socket.impl.on("close", function () {
if (socket.status === "starting" || socket.status === "connecting") {
socket.resolvePromise(Fail(failures.killed));
}
socket.status = "closed";
socket.emit("close");
});
socket.impl.on("end", function () {
socket.emit("end");
if (socket.startupPromise.isPending()) {
socket.resolvePromise(Fail(failures.socketEnded));
}
// Clean up our timeout.
clearTimeout(timeout);
});
socket.impl.on("timeout", function () {
socket.emit("timeout");
});
socket.impl.setEncoding("utf-8");
socket.impl.setNoDelay();
socket.on("timeout", function () {
socket.end();
});
return socket;
};
Socket.connectFailures = failures;
Socket.prototype = Object.create(EventEmitter.prototype, intoPropertyDescriptors({
connect: function () {
if (this.isStarted()) {
throw new Error("Cannot restart an irc-socket Socket.");
}
this.status = "connecting";
this.impl.connect(this.connectOptions);
return this.startupPromise;
},
end: function () {
if (!this.isConnected()) {
return;
}
if (this.startupPromise.isPending()) {
this.resolvePromise(Fail(failures.socketEnded));
}
this.impl.end();
},
raw: function (message) {
if (!this.isConnected()) {
return;
}
if (Array.isArray(message)) {
message = message.join(" ");
}
if (message.indexOf("\n") !== -1) {
throw new Error("Newline detected in message. Use multiple raws instead.");
}
this.impl.write(message + "\r\n", "utf-8");
},
setTimeout: function (timeout, callback) {
this.impl.setTimeout(timeout, callback);
},
isStarted: function () {
return this.status !== "initialized";
},
isConnected: function () {
return includes(["connecting", "starting", "running"], this.status);
},
isReady: function () {
return this.status === "running";
},
getRealName: function () {
return this._realname;
}
/*
// For debugging tests.
removeListener: function (message, fn) {
console.log(format(" IrcSocket [OFF] %s %s", message, fn.name));
EventEmitter.prototype.removeListener.apply(this, arguments);
}
*/
}));