mini refactor
[KiwiIRC.git] / server / irc / state.js
CommitLineData
b09157de
JA
1var util = require('util'),
2 events = require('events'),
3 _ = require('lodash'),
4 IrcConnection = require('./connection.js').IrcConnection;
76ff1063
JA
5
6var State = function (client, save_state) {
6b8fa7a6
D
7 var that = this;
8
76ff1063
JA
9 events.EventEmitter.call(this);
10 this.client = client;
11 this.save_state = save_state || false;
12
13 this.irc_connections = [];
14 this.next_connection = 0;
15
5befab98 16 this.client.on('dispose', function () {
6b8fa7a6
D
17 if (!that.save_state) {
18 _.each(that.irc_connections, function (irc_connection, i, cons) {
76ff1063
JA
19 if (irc_connection) {
20 irc_connection.end('QUIT :' + (global.config.quit_message || ''));
21 irc_connection.dispose();
8838bdd6 22 global.servers.removeConnection(irc_connection);
76ff1063
JA
23 cons[i] = null;
24 }
25 });
26
6b8fa7a6 27 that.dispose();
76ff1063
JA
28 }
29 });
30};
31
32util.inherits(State, events.EventEmitter);
33
34module.exports = State;
35
36State.prototype.connect = function (hostname, port, ssl, nick, user, pass, callback) {
37 var that = this;
38 var con, con_num;
83c25bfa 39
2087f5d1
JA
40 // Check the per-server limit on the number of connections
41 if ((global.config.max_server_conns > 0) &&
42 (!global.config.restrict_server) &&
43 (!(global.config.webirc_pass && global.config.webirc_pass[hostname])) &&
8ae445ce 44 (!(global.config.ip_as_username && _.contains(global.config.ip_as_username, hostname))) &&
2087f5d1
JA
45 (global.servers.numOnHost(hostname) >= global.config.max_server_conns))
46 {
47 return callback('Too many connections to host', {host: hostname, limit: global.config.max_server_conns});
76ff1063 48 }
2087f5d1 49
c3204224
PV
50 con = new IrcConnection(
51 hostname,
52 port,
53 ssl,
54 nick,
55 user,
56 pass,
57 this);
76ff1063
JA
58
59 con_num = this.next_connection++;
60 this.irc_connections[con_num] = con;
61 con.con_num = con_num;
62
63 new IrcCommands(con, con_num, this).bindEvents();
64
65 con.on('connected', function () {
8838bdd6 66 global.servers.addConnection(this);
76ff1063
JA
67 return callback(null, con_num);
68 });
69
70 con.on('error', function (err) {
b09157de 71 console.log('irc_connection error (' + hostname + '):', err);
76ff1063
JA
72 return callback(err.code, {server: con_num, error: err});
73 });
74
75 con.on('close', function () {
76 that.irc_connections[con_num] = null;
8838bdd6 77 global.servers.removeConnection(this);
76ff1063
JA
78 });
79};
80
81State.prototype.sendIrcCommand = function () {
82 this.client.sendIrcCommand.apply(this.client, arguments);
83};
84
85State.prototype.sendKiwiCommand = function () {
86 this.client.sendKiwicommand.apply(this.client, arguments);
87};
88
89State.prototype.dispose = function () {
5befab98 90 this.emit('dispose');
76ff1063
JA
91 this.removeAllListeners();
92};