From 18c5b3ceac115200f994c440b78ceccda9a9862d Mon Sep 17 00:00:00 2001 From: Trygve Laugstøl Date: Mon, 4 Jun 2012 00:08:25 +0200 Subject: wip --- irc-client.js | 103 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 103 insertions(+) create mode 100644 irc-client.js (limited to 'irc-client.js') diff --git a/irc-client.js b/irc-client.js new file mode 100644 index 0000000..bd8edb8 --- /dev/null +++ b/irc-client.js @@ -0,0 +1,103 @@ +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: ' + _.size(client.channels)); + _.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) { + _.each(client.channels, function(channel) { + info('JOINed ' + channel.name); + channel.fire(channelName); + }); + }); + irc.on('privmsg', function(nick, channel, message) { + client.emit('privmsg', nick, channel, message); + }); + 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) { + c.fire(name); + } +} + +IrcClient.prototype.notice = function(to, message) { + this.irc.notice(to, message); +} + +module.exports.IrcClient = IrcClient; -- cgit v1.2.3