Removing junk from .po files
[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 IrcCommands = require('./commands.js');
6
7 var State = function (client, save_state) {
8 var that = this;
9
10 events.EventEmitter.call(this);
11 this.client = client;
12 this.save_state = save_state || false;
13
14 this.irc_connections = [];
15 this.next_connection = 0;
16
17 this.client.on('dispose', function () {
18 if (!that.save_state) {
19 _.each(that.irc_connections, function (irc_connection, i, cons) {
20 if (irc_connection) {
21 irc_connection.end('QUIT :' + (global.config.quit_message || ''));
22 irc_connection.dispose();
23 global.servers.removeConnection(irc_connection);
24 cons[i] = null;
25 }
26 });
27
28 that.dispose();
29 }
30 });
31 };
32
33 util.inherits(State, events.EventEmitter);
34
35 module.exports = State;
36
37 State.prototype.connect = function (hostname, port, ssl, nick, user, pass, callback) {
38 var that = this;
39 var con, con_num;
40
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))
47 {
48 return callback('Too many connections to host', {host: hostname, limit: global.config.max_server_conns});
49 }
50
51 con = new IrcConnection(
52 hostname,
53 port,
54 ssl,
55 nick,
56 user,
57 pass,
58 this);
59
60 con_num = this.next_connection++;
61 this.irc_connections[con_num] = con;
62 con.con_num = con_num;
63
64 con.irc_commands = new IrcCommands(con, con_num, this);
65
66 con.on('connected', function () {
67 global.servers.addConnection(this);
68 return callback(null, con_num);
69 });
70
71 con.on('error', function (err) {
72 console.log('irc_connection error (' + hostname + '):', err);
73 return callback(err.code, {server: con_num, error: err});
74 });
75
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'});
79
80 that.irc_connections[con_num] = null;
81 global.servers.removeConnection(this);
82 });
83
84 // Call any modules before making the connection
85 global.modules.emit('irc connecting', {connection: con})
86 .done(function () {
87 con.connect();
88 });
89 };
90
91 State.prototype.sendIrcCommand = function () {
92 this.client.sendIrcCommand.apply(this.client, arguments);
93 };
94
95 State.prototype.sendKiwiCommand = function () {
96 this.client.sendKiwicommand.apply(this.client, arguments);
97 };
98
99 State.prototype.dispose = function () {
100 this.emit('dispose');
101 this.removeAllListeners();
102 };