# Jabber Conference Plug-in for
# Blagg: the Blosxom RSS aggregator
# Author: DJ Adams <dj.adams@pobox.com>
# Version: 0+1b

# changes

# 0+1b
# simple escaping of body text to prevent XML chunder

# 0+1
# original version

# A Blagg plug-in that sends info on new RSS items to a conference space

# Usage:
# Add the following to the standard -blog and -mode command-line switches:
# -plugin=jabberconf - activate the Jabber Conference plug-in
# -jid={JID to connect with}
# -password={JID's password}
# -room={JID of conference room into which to post}
# -nickname={nickname for room} <-- this is optional, default is 'blagg'
#
# E.g. 
# blagg -blog=someblog -mode=automatic -plugin=jabberconf
#       -jid=blagg@gnu.mine.nu -password=secret
#       -room=newsitems@jabber.org

package blaggplug;

use strict;

use CGI qw{:standard}; # access to command-line switches (e.g. -blog=someblog)
use Jabber::Connection;

my $c;
my $joined = 0;
my $DEFAULTNICK = 'blagg';
my $WAIT = 3;

my %escape = ('<'=>'&lt;', '>'=>'&gt;', '&'=>'&amp;', '"'=>'&quot;');  
my $escape_re  = join '|' => keys %escape;

sub init {
	# check arguments
	die "-jid, -password and -room arguments needed for jabberconf plugin"
	unless param('-jid') and param('-password') and param('-room');

	# connect & auth
	my ($user, $host) = split('@', param('-jid'));
	_debug("connecting to Jabber");
	$c = new Jabber::Connection(server => $host);
	$c->connect or die "Cannot connect to Jabber server at $host";
	$c->auth($user, param('-password'), 'blagg');

	my $roomnick = param('-room').'/'.(param('-nickname') || $DEFAULTNICK);

	# set presence callback to check on room entry only
	$c->register_handler('presence', sub { _handlePresence($roomnick, @_) });

	# enter room and check
	$c->send("<presence to='$roomnick'/>");
	$c->process(1) foreach (1..$WAIT);
	die "Cannot enter room" unless $joined;

}

sub post {
	my($title, $link, $description, $feed_title, $feed_link) = @_;
	_debug("post from $feed_title: $title");
	my $room = param('-room');
    my $body = "[$feed_title] $title [$link]";
    $body =~ s/($escape_re)/$escape{$1}/g;
	$c->send(<<EO_MSG);
<message type='groupchat' to='$room'>
<body>$body</body>
</message>
EO_MSG
	sleep 1; # karma!
}

sub destroy {
	_debug("disconnecting from Jabber");
	sleep 5;
	$c->disconnect;
}

sub _debug {
	print STDERR scalar(localtime)." @_\n";
}

sub _handlePresence {
	my ($roomnick, $node) = @_;
	my $type = $node->attr('type') || '';
	$joined = 1 if $node->attr('from') eq $roomnick and $type ne 'error';
	1;
}

1;
