Client: Encoding within the URL
[KiwiIRC.git] / server / irc / state.js
1 var util = require('util'),
2 events = require('events'),
3 _ = require('lodash'),
4 IrcConnection = require('./connection.js').IrcConnection;
5
6 var State = function (client, save_state) {
7 var that = this;
8
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
16 this.client.on('dispose', function () {
17 if (!that.save_state) {
18 _.each(that.irc_connections, function (irc_connection, i, cons) {
19 if (irc_connection) {
20 irc_connection.end('QUIT :' + (global.config.quit_message || ''));
21 global.servers.removeConnection(irc_connection);
22 cons[i] = null;
23 }
24 });
25
26 that.dispose();
27 }
28 });
29 };
30
31 util.inherits(State, events.EventEmitter);
32
33 module.exports = State;
34
35 State.prototype.connect = function (hostname, port, ssl, nick, user, options, callback) {
36 var that = this;
37 var con, con_num;
38
39 // Check the per-server limit on the number of connections
40 if ((global.config.max_server_conns > 0) &&
41 (!global.config.restrict_server) &&
42 (!(global.config.webirc_pass && global.config.webirc_pass[hostname])) &&
43 (!(global.config.ip_as_username && _.contains(global.config.ip_as_username, hostname))) &&
44 (global.servers.numOnHost(hostname) >= global.config.max_server_conns))
45 {
46 return callback('Too many connections to host', {host: hostname, limit: global.config.max_server_conns});
47 }
48
49 con_num = this.next_connection++;
50 con = new IrcConnection(
51 hostname,
52 port,
53 ssl,
54 nick,
55 user,
56 options,
57 this,
58 con_num);
59
60 this.irc_connections[con_num] = con;
61
62 con.on('connected', function IrcConnectionConnection() {
63 global.servers.addConnection(this);
64 return callback(null, con_num);
65 });
66
67 con.on('error', function IrcConnectionError(err) {
68 console.log('irc_connection error (' + hostname + '):', err);
69 return callback(err.code, {server: con_num, error: err});
70 });
71
72 con.on('close', function IrcConnectionClose() {
73 // TODO: Can we get a better reason for the disconnection? Was it planned?
74 that.sendIrcCommand('disconnect', {server: con.con_num, reason: 'disconnected'});
75
76 that.irc_connections[con_num] = null;
77 global.servers.removeConnection(this);
78 });
79
80 // Call any modules before making the connection
81 global.modules.emit('irc connecting', {connection: con})
82 .done(function () {
83 con.connect();
84 });
85 };
86
87 State.prototype.sendIrcCommand = function () {
88 this.client.sendIrcCommand.apply(this.client, arguments);
89 };
90
91 State.prototype.sendKiwiCommand = function () {
92 this.client.sendKiwicommand.apply(this.client, arguments);
93 };
94
95 State.prototype.dispose = function () {
96 this.emit('dispose');
97 this.removeAllListeners();
98 };