Pass callback to state.connect, fix vars
[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 events.EventEmitter.call(this);
8 this.client = client;
9 this.save_state = save_state || false;
10
11 this.irc_connections = [];
12 this.next_connection = 0;
13
14 this.client.on('disconnect', function () {
15 if (!this.save_state) {
16 _.each(this.irc_connections, function (irc_connection, i, cons) {
17 if (irc_connection) {
18 irc_connection.end('QUIT :' + (global.config.quit_message || ''));
19 irc_connection.dispose();
20 cons[i] = null;
21 }
22 });
23
24 this.dispose();
25 }
26 });
27 };
28
29 util.inherits(State, events.EventEmitter);
30
31 module.exports = State;
32
33 State.prototype.connect = function (hostname, port, ssl, nick, user, pass, callback) {
34 var that = this;
35 var con, con_num;
36 if (global.config.restrict_server) {
37 con = new IrcConnection(
38 global.config.restrict_server,
39 global.config.restrict_server_port,
40 global.config.restrict_server_ssl,
41 nick,
42 user,
43 global.config.restrict_server_password,
44 this);
45
46 } else {
47 con = new IrcConnection(
48 hostname,
49 port,
50 ssl,
51 nick,
52 user,
53 pass,
54 this);
55 }
56
57 con_num = this.next_connection++;
58 this.irc_connections[con_num] = con;
59 con.con_num = con_num;
60
61 new IrcCommands(con, con_num, this).bindEvents();
62
63 con.on('connected', function () {
64 return callback(null, con_num);
65 });
66
67 con.on('error', function (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 () {
73 that.irc_connections[con_num] = null;
74 });
75 };
76
77 State.prototype.sendIrcCommand = function () {
78 this.client.sendIrcCommand.apply(this.client, arguments);
79 };
80
81 State.prototype.sendKiwiCommand = function () {
82 this.client.sendKiwicommand.apply(this.client, arguments);
83 };
84
85 State.prototype.dispose = function () {
86 this.emit('destroy');
87 this.removeAllListeners();
88 };