1 var util
= require('util'),
2 events
= require('events'),
4 IrcConnection
= require('./connection.js').IrcConnection
,
5 IrcCommands
= require('./commands.js');
7 var State = function (client
, save_state
) {
10 events
.EventEmitter
.call(this);
12 this.save_state
= save_state
|| false;
14 this.irc_connections
= [];
15 this.next_connection
= 0;
17 this.client
.on('dispose', function () {
18 if (!that
.save_state
) {
19 _
.each(that
.irc_connections
, function (irc_connection
, i
, cons
) {
21 irc_connection
.end('QUIT :' + (global
.config
.quit_message
|| ''));
22 irc_connection
.dispose();
23 global
.servers
.removeConnection(irc_connection
);
33 util
.inherits(State
, events
.EventEmitter
);
35 module
.exports
= State
;
37 State
.prototype.connect = function (hostname
, port
, ssl
, nick
, user
, pass
, callback
) {
41 // Check the per-server limit on the number of connections
42 if ((global
.config
.max_server_conns
> 0) &&
43 (!global
.config
.restrict_server
) &&
44 (!(global
.config
.webirc_pass
&& global
.config
.webirc_pass
[hostname
])) &&
45 (!(global
.config
.ip_as_username
&& _
.contains(global
.config
.ip_as_username
, hostname
))) &&
46 (global
.servers
.numOnHost(hostname
) >= global
.config
.max_server_conns
))
48 return callback('Too many connections to host', {host
: hostname
, limit
: global
.config
.max_server_conns
});
51 con
= new IrcConnection(
60 con_num
= this.next_connection
++;
61 this.irc_connections
[con_num
] = con
;
62 con
.con_num
= con_num
;
64 con
.irc_commands
= new IrcCommands(con
, con_num
, this);
66 con
.on('connected', function () {
67 global
.servers
.addConnection(this);
68 return callback(null, con_num
);
71 con
.on('error', function (err
) {
72 console
.log('irc_connection error (' + hostname
+ '):', err
);
73 return callback(err
.code
, {server
: con_num
, error
: err
});
76 con
.on('close', function () {
77 // TODO: Can we get a better reason for the disconnection? Was it planned?
78 that
.sendIrcCommand('disconnect', {server
: con
.con_num
, reason
: 'disconnected'});
80 that
.irc_connections
[con_num
] = null;
81 global
.servers
.removeConnection(this);
84 // Call any modules before making the connection
85 global
.modules
.emit('irc connecting', {connection
: con
})
91 State
.prototype.sendIrcCommand = function () {
92 this.client
.sendIrcCommand
.apply(this.client
, arguments
);
95 State
.prototype.sendKiwiCommand = function () {
96 this.client
.sendKiwicommand
.apply(this.client
, arguments
);
99 State
.prototype.dispose = function () {
100 this.emit('dispose');
101 this.removeAllListeners();