var IRC = require('./node_modules/node-irc/irc').IRC; var util = require('util'); var events = require('events'); var _ = require('underscore'); function info() { var copy = [].slice.apply(arguments) console.log('IrcClient: ' + copy.join(' ')); } function Channel(name) { this.name = name; this.listeners = []; } Channel.prototype.addListener = function(f) { this.listeners.push(f); }; Channel.prototype.fire = function(event) { _.each(this.listeners, function(f) { f(event); }); }; function IrcClient(nick, realName, ident, server, port, password) { this.nick = nick; this.realName = realName; this.ident = ident; this.server = server; this.port = port; this.password = password; this.channels = {}; this.connected = false; this.debugLevel = undefined; this.irc = undefined; } util.inherits(IrcClient, events.EventEmitter); IrcClient.prototype.init = function(irc) { // TODO: hmm.. var client = this; this.debugLevel && irc.setDebugLevel(this.debugLevel); irc.on('connected', function() { info('Connected, channels: ' + _.keys(client.channels).join(', ')); _.each(client.channels, function(channel) { info('JOINing ' + channel.name); irc.join(channel.name); }); }); irc.on('disconnected', function() { info('Disconnected, reconnecting...'); client.connect(); }); irc.on('join', function(nick, channelName) { info('JOINed ' + channelName); client.getChannel(channelName).fire(channelName); }); irc.on('privmsg', function(nick, channel, message) { client.emit.call(['privmsg'].slice.apply(arguments)); // client.emit('privmsg', nick, channel, message); }); irc.on('topic', function() { console.log('topic: ' + util.inspect(arguments)); client.emit.call(null, ['topic'].slice.apply(arguments)); }); return irc; } IrcClient.prototype.getChannel = function(name) { var c = this.channels[name]; if(typeof c == "undefined") { c = new Channel(name); this.channels[name] = c; } return c; } IrcClient.prototype.setDebugLevel = function(level) { this.debugLevel = level; this.irc && this.irc.setDebugLevel(level); } IrcClient.prototype.connect = function() { this.irc = this.init(new IRC(this.server, this.port, this.password)); this.irc.connect(this.nick, this.realName, this.ident); } IrcClient.prototype.join = function(name, cb) { var c = this.getChannel(name); if(typeof cb != "undefined") { c.addListener(cb); } if(this.connected) { info('join: already connected: ' + name); c.fire(name); } } // TODO: fix function dispatch(name) { this.irc[name].apply(this.irc, arguments); } IrcClient.prototype.notice = function() { this.irc.notice.apply(this.irc, arguments); } IrcClient.prototype.privmsg = function() { this.irc.privmsg.apply(this.irc, arguments); } IrcClient.prototype.topic = function() { this.irc.topic.apply(this.irc, arguments); } module.exports.IrcClient = IrcClient;