source: perl/modules/Jabber/lib/BarnOwl/Module/Jabber.pm @ 9f5e847

release-1.10release-1.4release-1.5release-1.6release-1.7release-1.8release-1.9
Last change on this file since 9f5e847 was 5118b32, checked in by Alejandro R. Sedeño <asedeno@mit.edu>, 15 years ago
Switch jabber keep-alive and auto-away to a timer. Dropping the dependency on the mainloop hook in jabber. Increasing the keep-alive / auto-away interval in jabber to 5 seconds.
  • Property mode set to 100644
File size: 44.8 KB
RevLine 
[9f183ff]1use strict;
[2cedb7a]2use warnings;
3
4package BarnOwl::Module::Jabber;
5
6=head1 NAME
[9f183ff]7
[2cedb7a]8BarnOwl::Module::Jabber
9
10=head1 DESCRIPTION
11
12This module implements Jabber support for barnowl.
13
14=cut
15
16use BarnOwl;
17use BarnOwl::Hooks;
18use BarnOwl::Message::Jabber;
19use BarnOwl::Module::Jabber::Connection;
20use BarnOwl::Module::Jabber::ConnectionManager;
[2ce12de]21use BarnOwl::Completion::Util qw(complete_flags);
[d47d5fc]22
[38ffdf9]23use Authen::SASL qw(Perl);
24use Net::Jabber;
[1dfc7df]25use Net::Jabber::MUC;
[6a6dd47]26use Net::DNS;
27use Getopt::Long;
[b72a352]28Getopt::Long::Configure(qw(no_getopt_compat prefix_pattern=-|--));
[6a6dd47]29
[e0ffe77]30use utf8;
31
[2cedb7a]32our $VERSION = 0.1;
33
[d47d5fc]34BEGIN {
35    if(eval {require IO::Socket::SSL;}) {
36        if($IO::Socket::SSL::VERSION eq "0.97") {
37            BarnOwl::error("You are using IO::Socket:SSL 0.97, which \n" .
[f6c2b3d]38                           "contains bugs causing it not to work with barnowl's\n" .
39                           "jabber support. We recommend updating to the latest\n" .
40                           "IO::Socket::SSL from CPAN. \n");
41            die("Not loading Jabber.par\n");
[d47d5fc]42        }
[f1589b5]43    }
[d47d5fc]44}
45
[84296f6]46no warnings 'redefine';
47
[38ffdf9]48################################################################################
49# owl perl jabber support
50#
[b6a253c]51# XXX Todo:
52# Rosters for MUCs
53# More user feedback
54#  * joining MUC
55#  * parting MUC
56#  * presence (Roster and MUC)
57# Implementing formatting and logging callbacks for C
58# Appropriate callbacks for presence subscription messages.
[38ffdf9]59#
60################################################################################
61
[1fd5e4c1]62our $conn;
63$conn ||= BarnOwl::Module::Jabber::ConnectionManager->new;
[6a6dd47]64our %vars;
[2ce12de]65our %completion_jids;
[38ffdf9]66
[b405ff6]67sub onStart {
[5551208]68    if ( *BarnOwl::queue_message{CODE} ) {
[b405ff6]69        register_owl_commands();
[2cedb7a]70        register_keybindings();
71        register_filters();
[167044b]72        $BarnOwl::Hooks::getBuddyList->add("BarnOwl::Module::Jabber::onGetBuddyList");
[799b60e]73        $BarnOwl::Hooks::getQuickstart->add("BarnOwl::Module::Jabber::onGetQuickstart");
[7f792c1]74        $vars{show} = '';
[f1589b5]75        BarnOwl::new_variable_bool("jabber:show_offline_buddies",
76                                   { default => 1,
77                                     summary => 'Show offline or pending buddies.'});
[293d5fa]78        BarnOwl::new_variable_bool("jabber:show_logins",
79                                   { default => 0,
80                                     summary => 'Show login/logout messages.'});
[8af89a7]81        BarnOwl::new_variable_bool("jabber:spew",
82                                   { default => 0,
83                                     summary => 'Display unrecognized Jabber messages.'});
[f1589b5]84        BarnOwl::new_variable_int("jabber:auto_away_timeout",
85                                  { default => 5,
86                                    summary => 'After minutes idle, auto away.',
87                                  });
88        BarnOwl::new_variable_int("jabber:auto_xa_timeout",
89                                  { default => 15,
90                                    summary => 'After minutes idle, auto extended away.'
91                                });
[94b4ecb5]92        # Force these. Reload can screw them up.
93        # Taken from Net::Jabber::Protocol.
94        $Net::XMPP::Protocol::NEWOBJECT{'iq'}       = "Net::Jabber::IQ";
95        $Net::XMPP::Protocol::NEWOBJECT{'message'}  = "Net::Jabber::Message";
96        $Net::XMPP::Protocol::NEWOBJECT{'presence'} = "Net::Jabber::Presence";
97        $Net::XMPP::Protocol::NEWOBJECT{'jid'}      = "Net::Jabber::JID";
[9667006]98    } else {
[38ffdf9]99        # Our owl doesn't support queue_message. Unfortunately, this
[d609dd6]100        # means it probably *also* doesn't support BarnOwl::error. So just
[38ffdf9]101        # give up silently.
102    }
103}
[9f183ff]104
[167044b]105$BarnOwl::Hooks::startup->add("BarnOwl::Module::Jabber::onStart");
[38ffdf9]106
[5118b32]107sub do_keep_alive_and_auto_away {
108    if ( !$conn->connected() ) {
109        # We don't need this timer any more.
110        delete $vars{keepAliveTimer};
111        return;
112    }
[6a6dd47]113
[7f792c1]114    $vars{status_changed} = 0;
[f1589b5]115    my $auto_away = BarnOwl::getvar('jabber:auto_away_timeout');
116    my $auto_xa = BarnOwl::getvar('jabber:auto_xa_timeout');
[0c10a79]117    my $idletime = BarnOwl::getidletime();
[f1589b5]118    if ($auto_xa != 0 && $idletime >= (60 * $auto_xa) && ($vars{show} eq 'away' || $vars{show} eq '' )) {
[7f792c1]119        $vars{show} = 'xa';
[f1589b5]120        $vars{status} = 'Auto extended-away after '.$auto_xa.' minute'.($auto_xa == 1 ? '' : 's').' idle.';
[7f792c1]121        $vars{status_changed} = 1;
[f1589b5]122    } elsif ($auto_away != 0 && $idletime >= (60 * $auto_away) && $vars{show} eq '') {
[7f792c1]123        $vars{show} = 'away';
[f1589b5]124        $vars{status} = 'Auto away after '.$auto_away.' minute'.($auto_away == 1 ? '' : 's').' idle.';
[7f792c1]125        $vars{status_changed} = 1;
[5118b32]126    } elsif ($idletime <= $vars{idletime} && $vars{show} ne '') {
[7f792c1]127        $vars{show} = '';
128        $vars{status} = '';
129        $vars{status_changed} = 1;
130    }
[5118b32]131    $vars{idletime} = $idletime;
[7f792c1]132
[63bbef4]133    foreach my $jid ( $conn->getJIDs() ) {
[455f1ab]134        my $client = $conn->getConnectionFromJID($jid);
[b405ff6]135
[2d423e9]136        unless($client) {
137            $conn->removeConnection($jid);
138            BarnOwl::error("Connection for $jid undefined -- error in reload?");
139        }
[5118b32]140        my $status = $client->Process(0); # keep-alive
[b405ff6]141        if ( !defined($status) ) {
[d609dd6]142            BarnOwl::error("Jabber account $jid disconnected!");
[960395d]143            do_logout($jid);
[5118b32]144            next;
[960395d]145        }
[b405ff6]146        if ($::shutdown) {
147            do_logout($jid);
[9c7a701]148            next;
[b405ff6]149        }
[6b580b0]150
[7f792c1]151        if ($vars{status_changed}) {
[b2648bc]152            my $p = new Net::Jabber::Presence;
[7f792c1]153            $p->SetShow($vars{show}) if $vars{show};
154            $p->SetStatus($vars{status}) if $vars{status};
155            $client->Send($p);
156        }
[38ffdf9]157    }
158}
[b6a253c]159
[879e7e94]160our $showOffline = 0;
161
[b405ff6]162sub blist_listBuddy {
[6a6dd47]163    my $roster = shift;
[b405ff6]164    my $buddy  = shift;
[b6a253c]165    my $blistStr .= "    ";
[5c9c27d]166    my %jq  = $roster->query($buddy);
167    my $res = $roster->resource($buddy);
[b6a253c]168
[2d423e9]169    my $name = $jq{name} || $buddy->GetUserID();
170
171    $blistStr .= sprintf '%-15s %s', $name, $buddy->GetJID();
[2ce12de]172    $completion_jids{$name} = 1;
173    $completion_jids{$buddy->GetJID()} = 1;
[b405ff6]174
175    if ($res) {
[5c9c27d]176        my %rq = $roster->resourceQuery( $buddy, $res );
[b405ff6]177        $blistStr .= " [" . ( $rq{show} ? $rq{show} : 'online' ) . "]";
178        $blistStr .= " " . $rq{status} if $rq{status};
[879e7e94]179        $blistStr = BarnOwl::Style::boldify($blistStr) if $showOffline;
[b6a253c]180    }
[b405ff6]181    else {
[879e7e94]182        return '' unless $showOffline;
[84296f6]183        if ($jq{ask}) {
184            $blistStr .= " [pending]";
185        }
186        elsif ($jq{subscription} eq 'none' || $jq{subscription} eq 'from') {
187            $blistStr .= " [not subscribed]";
188        }
189        else {
190            $blistStr .= " [offline]";
191        }
[b6a253c]192    }
[b405ff6]193    return $blistStr . "\n";
[b6a253c]194}
195
[fd79497]196# Sort, ignoring markup.
197sub blistSort {
198    return uc(BarnOwl::ztext_stylestrip($a)) cmp uc(BarnOwl::ztext_stylestrip($b));
199}
200
[84296f6]201sub getSingleBuddyList {
202    my $jid = shift;
[455f1ab]203    $jid = resolveConnectedJID($jid);
[84296f6]204    return "" unless $jid;
[6a6dd47]205    my $blist = "";
[455f1ab]206    my $roster = $conn->getRosterFromJID($jid);
[bed4ff1]207    if ($roster) {
[2cedb7a]208        $blist .= "\n" . BarnOwl::Style::boldify("Jabber Roster for $jid\n");
[84296f6]209
[fd79497]210        my @gTexts = ();
[5c9c27d]211        foreach my $group ( $roster->groups() ) {
[2d423e9]212            my @buddies = $roster->jids( 'group', $group );
[fd79497]213            my @bTexts = ();
[2d423e9]214            foreach my $buddy ( @buddies ) {
[fd79497]215                push(@bTexts, blist_listBuddy( $roster, $buddy ));
[b405ff6]216            }
[fd79497]217            push(@gTexts, "  Group: $group\n".join('',sort blistSort @bTexts));
[84296f6]218        }
[fd79497]219        # Sort groups before adding ungrouped entries.
220        @gTexts = sort blistSort @gTexts;
[b405ff6]221
[5c9c27d]222        my @unsorted = $roster->jids('nogroup');
[84296f6]223        if (@unsorted) {
[fd79497]224            my @bTexts = ();
[84296f6]225            foreach my $buddy (@unsorted) {
[fd79497]226                push(@bTexts, blist_listBuddy( $roster, $buddy ));
[b405ff6]227            }
[fd79497]228            push(@gTexts, "  [unsorted]\n".join('',sort blistSort @bTexts));
[b405ff6]229        }
[fd79497]230        $blist .= join('', @gTexts);
[b6a253c]231    }
[6a6dd47]232    return $blist;
[b6a253c]233}
[38ffdf9]234
[84296f6]235sub onGetBuddyList {
[879e7e94]236    $showOffline = BarnOwl::getvar('jabber:show_offline_buddies') eq 'on';
[84296f6]237    my $blist = "";
[63bbef4]238    foreach my $jid ($conn->getJIDs()) {
[84296f6]239        $blist .= getSingleBuddyList($jid);
240    }
241    return $blist;
242}
243
[799b60e]244sub onGetQuickstart {
245    return <<'EOF'
246@b(Jabber:)
247Type ':jabberlogin @b(username@mit.edu)' to log in to Jabber. The command
248':jroster sub @b(somebody@gmail.com)' will request that they let you message
249them. Once you get a message saying you are subscribed, you can message
250them by typing ':jwrite @b(somebody@gmail.com)' or just 'j @b(somebody)'.
251EOF
252}
253
[38ffdf9]254################################################################################
255### Owl Commands
[b405ff6]256sub register_owl_commands() {
[d609dd6]257    BarnOwl::new_command(
[38ffdf9]258        jabberlogin => \&cmd_login,
[4508e21]259        {
[f1589b5]260            summary => "Log into jabber",
[4508e21]261            usage   => "jabberlogin JID [PASSWORD]"
262        }
[38ffdf9]263    );
[d609dd6]264    BarnOwl::new_command(
[38ffdf9]265        jabberlogout => \&cmd_logout,
266        { summary => "Log out of jabber" }
267    );
[d609dd6]268    BarnOwl::new_command(
[38ffdf9]269        jwrite => \&cmd_jwrite,
270        {
[b405ff6]271            summary => "Send a Jabber Message",
[455f1ab]272            usage   => "jwrite JID [-t thread] [-s subject]"
[38ffdf9]273        }
274    );
[d609dd6]275    BarnOwl::new_command(
[bfc127b]276        jaway => \&cmd_jaway,
277        {
278            summary => "Set Jabber away / presence information",
279            usage   => "jaway [-s online|dnd|...] [<message>]"
280        }
281    );
282    BarnOwl::new_command(
[b6a253c]283        jlist => \&cmd_jlist,
[38ffdf9]284        {
[b405ff6]285            summary => "Show your Jabber roster.",
286            usage   => "jlist"
[38ffdf9]287        }
288    );
[d609dd6]289    BarnOwl::new_command(
[b6a253c]290        jmuc => \&cmd_jmuc,
[38ffdf9]291        {
[b6a253c]292            summary     => "Jabber MUC related commands.",
[b405ff6]293            description => "jmuc sends jabber commands related to muc.\n\n"
294              . "The following commands are available\n\n"
[7cdf756]295              . "join <muc>  Join a muc.\n\n"
296              . "part <muc>  Part a muc.\n"
[b405ff6]297              . "            The muc is taken from the current message if not supplied.\n\n"
[7cdf756]298              . "invite <jid> <muc>\n"
299              . "            Invite <jid> to <muc>.\n"
[b405ff6]300              . "            The muc is taken from the current message if not supplied.\n\n"
[7cdf756]301              . "configure <muc>\n"
302              . "            Configures a MUC.\n"
303              . "            Necessary to initalize a new MUC.\n"
304              . "            At present, only the default configuration is supported.\n"
305              . "            The muc is taken from the current message if not supplied.\n\n"
306              . "presence <muc>\n"
307              . "            Shows the roster for <muc>.\n"
308              . "            The muc is taken from the current message if not supplied.\n\n"
309              . "presence -a\n"
310              . "            Shows rosters for all MUCs you're participating in.\n\n",
[5adb3d7]311            usage => "jmuc COMMAND ARGS"
[38ffdf9]312        }
313    );
[d609dd6]314    BarnOwl::new_command(
[f62550d]315        jroster => \&cmd_jroster,
316        {
317            summary     => "Jabber Roster related commands.",
[45d9eb0]318            description => "jroster sends jabber commands related to rosters.\n\n"
319              . "The following commands are available\n\n"
320              . "sub <jid>     Subscribe to <jid>'s presence. (implicit add)\n\n"
321              . "add <jid>     Adds <jid> to your roster.\n\n"
322              . "unsub <jid>   Unsubscribe from <jid>'s presence.\n\n"
323              . "remove <jid>  Removes <jid> to your roster. (implicit unsub)\n\n"
324              . "auth <jid>    Authorizes <jid> to subscribe to your presence.\n\n"
325              . "deauth <jid>  De-authorizes <jid>'s subscription to your presence.\n\n"
326              . "The following arguments are supported for all commands\n\n"
327              . "-a <jid>      Specify which account to make the roster changes on.\n"
328              . "              Required if you're signed into more than one account.\n\n"
329              . "The following arguments only work with the add and sub commands.\n\n"
330              . "-g <group>    Add <jid> to group <group>.\n"
331              . "              May be specified more than once, will not remove <jid> from any groups.\n\n"
332              . "-p            Purge. Removes <jid> from all groups.\n"
333              . "              May be combined with -g completely alter <jid>'s groups.\n\n"
334              . "-n <name>     Sets <name> as <jid>'s short name.\n\n"
335              . "Note: Unless -n is used, you can specify multiple <jid> arguments.\n",
[5adb3d7]336            usage       => "jroster COMMAND ARGS"
[f62550d]337        }
338    );
[38ffdf9]339}
340
[ac1bbe2]341sub register_keybindings {
[004d683]342    BarnOwl::bindkey(qw(recv j command start-command), 'jwrite ');
[ac1bbe2]343}
344
[c18f08d]345sub register_filters {
[96f7b07]346    BarnOwl::filter(qw(jabber type ^jabber$));
[c18f08d]347}
348
[b405ff6]349sub cmd_login {
[6a6dd47]350    my $cmd = shift;
[b2648bc]351    my $jid = new Net::Jabber::JID;
[367fbf3]352    $jid->SetJID(shift);
[3ce5bdc]353    my $password = '';
[367fbf3]354    $password = shift if @_;
[45d9eb0]355
[b405ff6]356    my $uid           = $jid->GetUserID();
[6a6dd47]357    my $componentname = $jid->GetServer();
[b405ff6]358    my $resource      = $jid->GetResource() || 'owl';
[6a6dd47]359    $jid->SetResource($resource);
360    my $jidStr = $jid->GetJID('full');
361
[b405ff6]362    if ( !$uid || !$componentname ) {
[d609dd6]363        BarnOwl::error("usage: $cmd JID");
[b405ff6]364        return;
[38ffdf9]365    }
[b6a253c]366
[f62550d]367    if ( $conn->jidExists($jidStr) ) {
[d609dd6]368        BarnOwl::error("Already logged in as $jidStr.");
[b405ff6]369        return;
[6a6dd47]370    }
371
[b405ff6]372    my ( $server, $port ) = getServerFromJID($jid);
[6a6dd47]373
[84296f6]374    $vars{jlogin_jid} = $jidStr;
[b405ff6]375    $vars{jlogin_connhash} = {
376        hostname      => $server,
377        tls           => 1,
378        port          => $port,
379        componentname => $componentname
380    };
381    $vars{jlogin_authhash} =
[84296f6]382      { username => $uid,
383        resource => $resource,
384    };
385
[0ad0e97]386    return do_login($password);
[6a6dd47]387}
[38ffdf9]388
[84296f6]389sub do_login {
390    $vars{jlogin_password} = shift;
391    $vars{jlogin_authhash}->{password} = sub { return $vars{jlogin_password} || '' };
392    my $jidStr = $vars{jlogin_jid};
393    if ( !$jidStr && $vars{jlogin_havepass}) {
[d609dd6]394        BarnOwl::error("Got password but have no jid!");
[6a6dd47]395    }
[84296f6]396    else
397    {
[f62550d]398        my $client = $conn->addConnection($jidStr);
[84296f6]399
400        #XXX Todo: Add more callbacks.
401        # * MUC presence handlers
[60986b2]402        # We use the anonymous subrefs in order to have the correct behavior
403        # when we reload
[5c9c27d]404        $client->SetMessageCallBacks(
[2cedb7a]405            chat      => sub { BarnOwl::Module::Jabber::process_incoming_chat_message(@_) },
406            error     => sub { BarnOwl::Module::Jabber::process_incoming_error_message(@_) },
407            groupchat => sub { BarnOwl::Module::Jabber::process_incoming_groupchat_message(@_) },
408            headline  => sub { BarnOwl::Module::Jabber::process_incoming_headline_message(@_) },
409            normal    => sub { BarnOwl::Module::Jabber::process_incoming_normal_message(@_) }
[84296f6]410        );
[bed4ff1]411        $client->SetPresenceCallBacks(
[2cedb7a]412            available    => sub { BarnOwl::Module::Jabber::process_presence_available(@_) },
413            unavailable  => sub { BarnOwl::Module::Jabber::process_presence_available(@_) },
414            subscribe    => sub { BarnOwl::Module::Jabber::process_presence_subscribe(@_) },
415            subscribed   => sub { BarnOwl::Module::Jabber::process_presence_subscribed(@_) },
416            unsubscribe  => sub { BarnOwl::Module::Jabber::process_presence_unsubscribe(@_) },
417            unsubscribed => sub { BarnOwl::Module::Jabber::process_presence_unsubscribed(@_) },
418            error        => sub { BarnOwl::Module::Jabber::process_presence_error(@_) });
[84296f6]419
[5c9c27d]420        my $status = $client->Connect( %{ $vars{jlogin_connhash} } );
[84296f6]421        if ( !$status ) {
[f62550d]422            $conn->removeConnection($jidStr);
[d609dd6]423            BarnOwl::error("We failed to connect");
[46e8a1e]424        } else {
[5c9c27d]425            my @result = $client->AuthSend( %{ $vars{jlogin_authhash} } );
[84296f6]426
[ffe70f9]427            if ( !@result || $result[0] ne 'ok' ) {
[05f0061]428                if ( !$vars{jlogin_havepass} && ( !@result || $result[0] eq '401' || $result[0] eq 'error') ) {
[46e8a1e]429                    $vars{jlogin_havepass} = 1;
430                    $conn->removeConnection($jidStr);
[e0ffe77]431                    BarnOwl::start_password("Password for $jidStr: ", \&do_login );
[46e8a1e]432                    return "";
433                }
[f62550d]434                $conn->removeConnection($jidStr);
[d609dd6]435                BarnOwl::error( "Error in connect: " . join( " ", @result ) );
[46e8a1e]436            } else {
[2ce12de]437                my $roster = $conn->getRosterFromJID($jidStr);
438                $roster->fetch();
[bed4ff1]439                $client->PresenceSend( priority => 1 );
[b55fe2c]440                my $fullJid = $client->{SESSION}->{FULLJID} || $jidStr;
[7f33c18]441                $conn->renameConnection($jidStr, $fullJid);
442                queue_admin_msg("Connected to jabber as $fullJid");
[9c7a701]443                # The remove_dispatch() method is called from the
444                # ConnectionManager's removeConnection() method.
[6b580b0]445                $client->{fileno} = $client->getSocket()->fileno();
446                #queue_admin_msg("Connected to jabber as $fullJid ($client->{fileno})");
447                BarnOwl::add_dispatch($client->{fileno}, sub { $client->OwlProcess() });
[2ce12de]448
449                # populate completion from roster.
450                for my $buddy ( $roster->jids('all') ) {
451                    my %jq  = $roster->query($buddy);
452                    my $name = $jq{name} || $buddy->GetUserID();
453                    $completion_jids{$name} = 1;
454                    $completion_jids{$buddy->GetJID()} = 1;
455                }
[5118b32]456                $vars{idletime} |= BarnOwl::getidletime();
457                unless (exists $vars{keepAliveTimer}) {
458                    $vars{keepAliveTimer} = BarnOwl::Timer->new({
459                        'after' => 5,
460                        'interval' => 5,
461                        'cb' => sub { BarnOwl::Module::Jabber::do_keep_alive_and_auto_away(@_) }
462                                                                });
463                }
[84296f6]464            }
465        }
[6a6dd47]466    }
[84296f6]467    delete $vars{jlogin_jid};
[45d9eb0]468    $vars{jlogin_password} =~ tr/\0-\377/x/ if $vars{jlogin_password};
[84296f6]469    delete $vars{jlogin_password};
470    delete $vars{jlogin_havepass};
[6a6dd47]471    delete $vars{jlogin_connhash};
472    delete $vars{jlogin_authhash};
[f1589b5]473
[38ffdf9]474    return "";
475}
476
[b405ff6]477sub do_logout {
[6a6dd47]478    my $jid = shift;
[f62550d]479    my $disconnected = $conn->removeConnection($jid);
480    queue_admin_msg("Jabber disconnected ($jid).") if $disconnected;
[6a6dd47]481}
482
[b405ff6]483sub cmd_logout {
[bc7037c]484    return "You are not logged into jabber." unless ($conn->connected() > 0);
[6a6dd47]485    # Logged into multiple accounts
[f62550d]486    if ( $conn->connected() > 1 ) {
[b405ff6]487        # Logged into multiple accounts, no accout specified.
488        if ( !$_[1] ) {
489            my $errStr =
[84296f6]490              "You are logged into multiple accounts. Please specify an account to log out of.\n";
[63bbef4]491            foreach my $jid ( $conn->getJIDs() ) {
[b405ff6]492                $errStr .= "\t$jid\n";
493            }
494            queue_admin_msg($errStr);
495        }
496        # Logged into multiple accounts, account specified.
497        else {
498            if ( $_[1] eq '-a' )    #All accounts.
499            {
[63bbef4]500                foreach my $jid ( $conn->getJIDs() ) {
[b405ff6]501                    do_logout($jid);
502                }
503            }
504            else                    #One account.
505            {
[455f1ab]506                my $jid = resolveConnectedJID( $_[1] );
[b405ff6]507                do_logout($jid) if ( $jid ne '' );
508            }
509        }
510    }
511    else                            # Only one account logged in.
[6a6dd47]512    {
[63bbef4]513        do_logout( ( $conn->getJIDs() )[0] );
[38ffdf9]514    }
515    return "";
516}
517
[b405ff6]518sub cmd_jlist {
[63bbef4]519    if ( !( scalar $conn->getJIDs() ) ) {
[d609dd6]520        BarnOwl::error("You are not logged in to Jabber.");
[b405ff6]521        return;
[b6a253c]522    }
[d609dd6]523    BarnOwl::popless_ztext( onGetBuddyList() );
[b6a253c]524}
525
[b405ff6]526sub cmd_jwrite {
[f62550d]527    if ( !$conn->connected() ) {
[d609dd6]528        BarnOwl::error("You are not logged in to Jabber.");
[b405ff6]529        return;
[38ffdf9]530    }
531
[b405ff6]532    my $jwrite_to      = "";
533    my $jwrite_from    = "";
[f62550d]534    my $jwrite_sid     = "";
[b405ff6]535    my $jwrite_thread  = "";
[6a6dd47]536    my $jwrite_subject = "";
[3ce5bdc]537    my ($to, $from);
[b405ff6]538    my $jwrite_type    = "chat";
[38ffdf9]539
[6a6dd47]540    my @args = @_;
541    shift;
[9f183ff]542    local @ARGV = @_;
[6a6dd47]543    my $gc;
[b405ff6]544    GetOptions(
545        'thread=s'  => \$jwrite_thread,
546        'subject=s' => \$jwrite_subject,
[3ce5bdc]547        'account=s' => \$from,
[f62550d]548        'id=s'     =>  \$jwrite_sid,
[1a43ce7]549    ) or die("Usage: jwrite JID [-t thread] [-s 'subject'] [-a account]\n");
[6a6dd47]550    $jwrite_type = 'groupchat' if $gc;
551
[b405ff6]552    if ( scalar @ARGV != 1 ) {
[d609dd6]553        BarnOwl::error(
[455f1ab]554            "Usage: jwrite JID [-t thread] [-s 'subject'] [-a account]");
[b405ff6]555        return;
[6a6dd47]556    }
[b405ff6]557    else {
[367fbf3]558      $to = shift @ARGV;
[6a6dd47]559    }
[b6a253c]560
[989fae0]561    my @candidates = guess_jwrite($from, $to);
[45d9eb0]562
[989fae0]563    unless(scalar @candidates) {
[455f1ab]564        die("Unable to resolve JID $to");
565    }
[0a3f04d]566
[989fae0]567    @candidates = grep {defined $_->[0]} @candidates;
568
569    unless(scalar @candidates) {
[3ce5bdc]570        if(!$from) {
571            die("You must specify an account with -a");
572        } else {
573            die("Unable to resolve account $from");
574        }
[0a3f04d]575    }
[989fae0]576
577
578    ($jwrite_from, $jwrite_to, $jwrite_type) = @{$candidates[0]};
[45d9eb0]579
[b405ff6]580    $vars{jwrite} = {
581        to      => $jwrite_to,
582        from    => $jwrite_from,
[f62550d]583        sid     => $jwrite_sid,
[b405ff6]584        subject => $jwrite_subject,
585        thread  => $jwrite_thread,
586        type    => $jwrite_type
587    };
588
[989fae0]589    if(scalar @candidates > 1) {
590        BarnOwl::message(
591            "Warning: Guessing account and/or destination JID"
592           );
593    } else  {
594        BarnOwl::message(
595            "Type your message below.  End with a dot on a line by itself.  ^C will quit."
596           );
597    }
[45d9eb0]598
[0b4aef2]599    my @cmd = ('jwrite', $jwrite_to, '-a', $jwrite_from);
600    push @cmd, '-t', $jwrite_thread if $jwrite_thread;
601    push @cmd, '-s', $jwrite_subject if $jwrite_subject;
[e0ffe77]602
[0b4aef2]603    BarnOwl::start_edit_win(BarnOwl::quote(@cmd), \&process_owl_jwrite);
[38ffdf9]604}
605
[b405ff6]606sub cmd_jmuc {
[f62550d]607    die "You are not logged in to Jabber" unless $conn->connected();
[b405ff6]608    my $ocmd = shift;
609    my $cmd  = shift;
610    if ( !$cmd ) {
611
612        #XXX TODO: Write general usage for jmuc command.
613        return;
614    }
615
616    my %jmuc_commands = (
617        join      => \&jmuc_join,
618        part      => \&jmuc_part,
619        invite    => \&jmuc_invite,
[1dfc7df]620        configure => \&jmuc_configure,
621        presence  => \&jmuc_presence
[b405ff6]622    );
623    my $func = $jmuc_commands{$cmd};
624    if ( !$func ) {
[d609dd6]625        BarnOwl::error("jmuc: Unknown command: $cmd");
[b405ff6]626        return;
627    }
628
629    {
630        local @ARGV = @_;
631        my $jid;
632        my $muc;
[d609dd6]633        my $m = BarnOwl::getcurmsg();
[6837096]634        if ( $m && $m->is_jabber && $m->{jtype} eq 'groupchat' ) {
[b405ff6]635            $muc = $m->{room};
636            $jid = $m->{to};
637        }
638
639        my $getopt = Getopt::Long::Parser->new;
[1a43ce7]640        $getopt->configure('pass_through', 'no_getopt_compat');
[b405ff6]641        $getopt->getoptions( 'account=s' => \$jid );
642        $jid ||= defaultJID();
643        if ($jid) {
[455f1ab]644            $jid = resolveConnectedJID($jid);
[b405ff6]645            return unless $jid;
646        }
647        else {
[d609dd6]648            BarnOwl::error('You must specify an account with -a {jid}');
[b405ff6]649        }
650        return $func->( $jid, $muc, @ARGV );
651    }
[6df381b]652}
653
654sub jmuc_join {
[b405ff6]655    my ( $jid, $muc, @args ) = @_;
656    local @ARGV = @args;
657    my $password;
658    GetOptions( 'password=s' => \$password );
659
660    $muc = shift @ARGV
[60986b2]661      or die("Usage: jmuc join MUC [-p password] [-a account]");
[b405ff6]662
[86840c5]663    die("Error: Must specify a fully-qualified MUC name (e.g. barnowl\@conference.mit.edu)\n")
664        unless $muc =~ /@/;
[3ec8d9a]665    $muc = Net::Jabber::JID->new($muc);
666    $jid = Net::Jabber::JID->new($jid);
667    $muc->SetResource($jid->GetJID('full')) unless length $muc->GetResource();
668
[63bbef4]669    $conn->getConnectionFromJID($jid)->MUCJoin(JID      => $muc,
[86840c5]670                                               Password => $password,
671                                               History  => {
672                                                   MaxChars => 0
673                                                  });
[2ce12de]674    $completion_jids{$muc} = 1;
[1dfc7df]675    return;
[6df381b]676}
677
678sub jmuc_part {
[b405ff6]679    my ( $jid, $muc, @args ) = @_;
[9f183ff]680
[b405ff6]681    $muc = shift @args if scalar @args;
[60986b2]682    die("Usage: jmuc part MUC [-a account]") unless $muc;
[9f183ff]683
[892568b]684    if($conn->getConnectionFromJID($jid)->MUCLeave(JID => $muc)) {
685        queue_admin_msg("$jid has left $muc.");
686    } else {
687        die("Error: Not joined to $muc");
688    }
[6df381b]689}
690
[b405ff6]691sub jmuc_invite {
692    my ( $jid, $muc, @args ) = @_;
693
694    my $invite_jid = shift @args;
695    $muc = shift @args if scalar @args;
696
[60986b2]697    die('Usage: jmuc invite JID [muc] [-a account]')
[b405ff6]698      unless $muc && $invite_jid;
699
[d9f4a5c]700    my $message = Net::Jabber::Message->new();
[b405ff6]701    $message->SetTo($muc);
[d9f4a5c]702    my $x = $message->NewChild('http://jabber.org/protocol/muc#user');
703    $x->AddInvite();
704    $x->GetInvite()->SetTo($invite_jid);
[455f1ab]705    $conn->getConnectionFromJID($jid)->Send($message);
[b405ff6]706    queue_admin_msg("$jid has invited $invite_jid to $muc.");
[38ffdf9]707}
708
[9f183ff]709sub jmuc_configure {
[b405ff6]710    my ( $jid, $muc, @args ) = @_;
711    $muc = shift @args if scalar @args;
712    die("Usage: jmuc configure [muc]") unless $muc;
713    my $iq = Net::Jabber::IQ->new();
714    $iq->SetTo($muc);
715    $iq->SetType('set');
716    my $query = $iq->NewQuery("http://jabber.org/protocol/muc#owner");
717    my $x     = $query->NewChild("jabber:x:data");
718    $x->SetType('submit');
719
[455f1ab]720    $conn->getConnectionFromJID($jid)->Send($iq);
[b405ff6]721    queue_admin_msg("Accepted default instant configuration for $muc");
[9f183ff]722}
723
[7cdf756]724sub jmuc_presence_single {
725    my $m = shift;
726    my @jids = $m->Presence();
[892568b]727
728    my $presence = "JIDs present in " . $m->BaseJID;
[2ce12de]729    $completion_jids{$m->BaseJID} = 1;
[892568b]730    if($m->Anonymous) {
731        $presence .= " [anonymous MUC]";
732    }
733    $presence .= "\n\t";
734    $presence .= join("\n\t", map {pp_jid($m, $_);} @jids) . "\n";
735    return $presence;
736}
737
738sub pp_jid {
739    my ($m, $jid) = @_;
740    my $nick = $jid->GetResource;
741    my $full = $m->GetFullJID($jid);
742    if($full && $full ne $nick) {
743        return "$nick ($full)";
744    } else {
745        return "$nick";
746    }
[7cdf756]747}
748
[1dfc7df]749sub jmuc_presence {
750    my ( $jid, $muc, @args ) = @_;
751
[e1b197e8]752    $muc = shift @args if scalar @args;
753    die("Usage: jmuc presence MUC") unless $muc;
754
[7cdf756]755    if ($muc eq '-a') {
756        my $str = "";
757        foreach my $jid ($conn->getJIDs()) {
[2cedb7a]758            $str .= BarnOwl::Style::boldify("Conferences for $jid:\n");
[7cdf756]759            my $connection = $conn->getConnectionFromJID($jid);
760            foreach my $muc ($connection->MUCs) {
761                $str .= jmuc_presence_single($muc)."\n";
762            }
763        }
764        BarnOwl::popless_ztext($str);
765    }
766    else {
767        my $m = $conn->getConnectionFromJID($jid)->FindMUC(jid => $muc);
768        die("No such muc: $muc") unless $m;
769        BarnOwl::popless_ztext(jmuc_presence_single($m));
770    }
[1dfc7df]771}
772
[f62550d]773
774#XXX TODO: Consider merging this with jmuc and selecting off the first two args.
775sub cmd_jroster {
776    die "You are not logged in to Jabber" unless $conn->connected();
777    my $ocmd = shift;
778    my $cmd  = shift;
779    if ( !$cmd ) {
780
781        #XXX TODO: Write general usage for jroster command.
782        return;
783    }
784
785    my %jroster_commands = (
786        sub      => \&jroster_sub,
787        unsub    => \&jroster_unsub,
788        add      => \&jroster_add,
789        remove   => \&jroster_remove,
790        auth     => \&jroster_auth,
791        deauth   => \&jroster_deauth
792    );
793    my $func = $jroster_commands{$cmd};
794    if ( !$func ) {
[d609dd6]795        BarnOwl::error("jroster: Unknown command: $cmd");
[f62550d]796        return;
797    }
798
799    {
800        local @ARGV = @_;
801        my $jid;
802        my $name;
803        my @groups;
804        my $purgeGroups;
805        my $getopt = Getopt::Long::Parser->new;
[1a43ce7]806        $getopt->configure('pass_through', 'no_getopt_compat');
[f62550d]807        $getopt->getoptions(
808            'account=s' => \$jid,
809            'group=s' => \@groups,
810            'purgegroups' => \$purgeGroups,
811            'name=s' => \$name
812        );
813        $jid ||= defaultJID();
814        if ($jid) {
[455f1ab]815            $jid = resolveConnectedJID($jid);
[f62550d]816            return unless $jid;
817        }
818        else {
[d609dd6]819            BarnOwl::error('You must specify an account with -a {jid}');
[f62550d]820        }
821        return $func->( $jid, $name, \@groups, $purgeGroups,  @ARGV );
822    }
823}
824
[bfc127b]825sub cmd_jaway {
826    my $cmd = shift;
827    local @ARGV = @_;
828    my $getopt = Getopt::Long::Parser->new;
829    my ($jid, $show);
830    my $p = new Net::Jabber::Presence;
831
832    $getopt->configure('pass_through', 'no_getopt_compat');
833    $getopt->getoptions(
834        'account=s' => \$jid,
835        'show=s'    => \$show
836    );
837    $jid ||= defaultJID();
838    if ($jid) {
839        $jid = resolveConnectedJID($jid);
840        return unless $jid;
841    }
842    else {
843        BarnOwl::error('You must specify an account with -a {jid}');
844    }
845
846    $p->SetShow($show eq "online" ? "" : $show) if $show;
847    $p->SetStatus(join(' ', @ARGV)) if @ARGV;
848    $conn->getConnectionFromJID($jid)->Send($p);
849}
850
851
[f62550d]852sub jroster_sub {
853    my $jid = shift;
854    my $name = shift;
855    my @groups = @{ shift() };
856    my $purgeGroups = shift;
[63bbef4]857    my $baseJID = baseJID($jid);
[f62550d]858
[455f1ab]859    my $roster = $conn->getRosterFromJID($jid);
[f62550d]860
861    # Adding lots of users with the same name is a bad idea.
862    $name = "" unless (1 == scalar(@ARGV));
863
[b2648bc]864    my $p = new Net::Jabber::Presence;
[f62550d]865    $p->SetType('subscribe');
866
867    foreach my $to (@ARGV) {
[bed4ff1]868        jroster_add($jid, $name, \@groups, $purgeGroups, ($to)) unless ($roster->exists($to));
[f62550d]869
870        $p->SetTo($to);
[455f1ab]871        $conn->getConnectionFromJID($jid)->Send($p);
[63bbef4]872        queue_admin_msg("You ($baseJID) have requested a subscription to ($to)'s presence.");
[f62550d]873    }
874}
875
876sub jroster_unsub {
877    my $jid = shift;
878    my $name = shift;
879    my @groups = @{ shift() };
880    my $purgeGroups = shift;
[63bbef4]881    my $baseJID = baseJID($jid);
[f62550d]882
[b2648bc]883    my $p = new Net::Jabber::Presence;
[f62550d]884    $p->SetType('unsubscribe');
885    foreach my $to (@ARGV) {
886        $p->SetTo($to);
[455f1ab]887        $conn->getConnectionFromJID($jid)->Send($p);
[63bbef4]888        queue_admin_msg("You ($baseJID) have unsubscribed from ($to)'s presence.");
[f62550d]889    }
890}
891
892sub jroster_add {
893    my $jid = shift;
894    my $name = shift;
895    my @groups = @{ shift() };
896    my $purgeGroups = shift;
[63bbef4]897    my $baseJID = baseJID($jid);
[f62550d]898
[455f1ab]899    my $roster = $conn->getRosterFromJID($jid);
[f62550d]900
901    # Adding lots of users with the same name is a bad idea.
902    $name = "" unless (1 == scalar(@ARGV));
903
[2ce12de]904    $completion_jids{$baseJID} = 1;
905    $completion_jids{$name} = 1 if $name;
906
[f62550d]907    foreach my $to (@ARGV) {
[bed4ff1]908        my %jq  = $roster->query($to);
[b2648bc]909        my $iq = new Net::Jabber::IQ;
[f62550d]910        $iq->SetType('set');
911        my $item = new XML::Stream::Node('item');
912        $iq->NewChild('jabber:iq:roster')->AddChild($item);
913
914        my %allGroups = ();
915
916        foreach my $g (@groups) {
917            $allGroups{$g} = $g;
918        }
919
920        unless ($purgeGroups) {
921            foreach my $g (@{$jq{groups}}) {
922                $allGroups{$g} = $g;
923            }
924        }
925
926        foreach my $g (keys %allGroups) {
927            $item->add_child('group')->add_cdata($g);
928        }
929
930        $item->put_attrib(jid => $to);
931        $item->put_attrib(name => $name) if $name;
[455f1ab]932        $conn->getConnectionFromJID($jid)->Send($iq);
[63bbef4]933        my $msg = "$baseJID: "
[f62550d]934          . ($name ? "$name ($to)" : "($to)")
935          . " is on your roster in the following groups: { "
936          . join(" , ", keys %allGroups)
937          . " }";
938        queue_admin_msg($msg);
939    }
940}
941
942sub jroster_remove {
943    my $jid = shift;
944    my $name = shift;
945    my @groups = @{ shift() };
946    my $purgeGroups = shift;
[63bbef4]947    my $baseJID = baseJID($jid);
[f62550d]948
[b2648bc]949    my $iq = new Net::Jabber::IQ;
[f62550d]950    $iq->SetType('set');
951    my $item = new XML::Stream::Node('item');
952    $iq->NewChild('jabber:iq:roster')->AddChild($item);
953    $item->put_attrib(subscription=> 'remove');
954    foreach my $to (@ARGV) {
955        $item->put_attrib(jid => $to);
[455f1ab]956        $conn->getConnectionFromJID($jid)->Send($iq);
[63bbef4]957        queue_admin_msg("You ($baseJID) have removed ($to) from your roster.");
[f62550d]958    }
959}
960
961sub jroster_auth {
962    my $jid = shift;
963    my $name = shift;
964    my @groups = @{ shift() };
965    my $purgeGroups = shift;
[63bbef4]966    my $baseJID = baseJID($jid);
[f62550d]967
[b2648bc]968    my $p = new Net::Jabber::Presence;
[f62550d]969    $p->SetType('subscribed');
970    foreach my $to (@ARGV) {
971        $p->SetTo($to);
[455f1ab]972        $conn->getConnectionFromJID($jid)->Send($p);
[63bbef4]973        queue_admin_msg("($to) has been subscribed to your ($baseJID) presence.");
[f62550d]974    }
975}
976
977sub jroster_deauth {
978    my $jid = shift;
979    my $name = shift;
980    my @groups = @{ shift() };
981    my $purgeGroups = shift;
[63bbef4]982    my $baseJID = baseJID($jid);
[f62550d]983
[b2648bc]984    my $p = new Net::Jabber::Presence;
[f62550d]985    $p->SetType('unsubscribed');
986    foreach my $to (@ARGV) {
987        $p->SetTo($to);
[455f1ab]988        $conn->getConnectionFromJID($jid)->Send($p);
[63bbef4]989        queue_admin_msg("($to) has been unsubscribed from your ($baseJID) presence.");
[f62550d]990    }
991}
992
[38ffdf9]993################################################################################
994### Owl Callbacks
[b405ff6]995sub process_owl_jwrite {
[38ffdf9]996    my $body = shift;
997
[b2648bc]998    my $j = new Net::Jabber::Message;
[38ffdf9]999    $body =~ s/\n\z//;
[b405ff6]1000    $j->SetMessage(
1001        to   => $vars{jwrite}{to},
1002        from => $vars{jwrite}{from},
1003        type => $vars{jwrite}{type},
1004        body => $body
1005    );
[f62550d]1006
[b405ff6]1007    $j->SetThread( $vars{jwrite}{thread} )   if ( $vars{jwrite}{thread} );
1008    $j->SetSubject( $vars{jwrite}{subject} ) if ( $vars{jwrite}{subject} );
1009
[f62550d]1010    my $m = j2o( $j, { direction => 'out' } );
[1c2e0b3]1011    if ( $vars{jwrite}{type} ne 'groupchat') {
[13a3c1db]1012        BarnOwl::queue_message($m);
[38ffdf9]1013    }
[f62550d]1014
[b2648bc]1015    $j->RemoveFrom(); # Kludge to get around gtalk's random bits after the resource.
[f62550d]1016    if ($vars{jwrite}{sid} && $conn->sidExists( $vars{jwrite}{sid} )) {
[bed4ff1]1017        $conn->getConnectionFromSid($vars{jwrite}{sid})->Send($j);
[f62550d]1018    }
1019    else {
[455f1ab]1020        $conn->getConnectionFromJID($vars{jwrite}{from})->Send($j);
[f62550d]1021    }
1022
[6a6dd47]1023    delete $vars{jwrite};
[d609dd6]1024    BarnOwl::message("");   # Kludge to make the ``type your message...'' message go away
[38ffdf9]1025}
1026
1027### XMPP Callbacks
1028
[b405ff6]1029sub process_incoming_chat_message {
[f62550d]1030    my ( $sid, $j ) = @_;
[0eb4036]1031    if ($j->DefinedBody()) {
1032        BarnOwl::queue_message( j2o( $j, { direction => 'in',
1033                                           sid => $sid } ) );
1034    }
[38ffdf9]1035}
1036
[b405ff6]1037sub process_incoming_error_message {
[f62550d]1038    my ( $sid, $j ) = @_;
1039    my %jhash = j2hash( $j, { direction => 'in',
1040                              sid => $sid } );
[b6a253c]1041    $jhash{type} = 'admin';
[79c06ae]1042   
[d609dd6]1043    BarnOwl::queue_message( BarnOwl::Message->new(%jhash) );
[38ffdf9]1044}
1045
[b405ff6]1046sub process_incoming_groupchat_message {
[f62550d]1047    my ( $sid, $j ) = @_;
[b405ff6]1048
[38ffdf9]1049    # HACK IN PROGRESS (ignoring delayed messages)
[b405ff6]1050    return if ( $j->DefinedX('jabber:x:delay') && $j->GetX('jabber:x:delay') );
[d609dd6]1051    BarnOwl::queue_message( j2o( $j, { direction => 'in',
[f62550d]1052                                   sid => $sid } ) );
[38ffdf9]1053}
1054
[b405ff6]1055sub process_incoming_headline_message {
[f62550d]1056    my ( $sid, $j ) = @_;
[d609dd6]1057    BarnOwl::queue_message( j2o( $j, { direction => 'in',
[f62550d]1058                                   sid => $sid } ) );
[38ffdf9]1059}
1060
[b405ff6]1061sub process_incoming_normal_message {
[f62550d]1062    my ( $sid, $j ) = @_;
1063    my %jhash = j2hash( $j, { direction => 'in',
1064                              sid => $sid } );
[b6a253c]1065
1066    # XXX TODO: handle things such as MUC invites here.
1067
[b405ff6]1068    #    if ($j->HasX('http://jabber.org/protocol/muc#user'))
1069    #    {
1070    #   my $x = $j->GetX('http://jabber.org/protocol/muc#user');
1071    #   if ($x->HasChild('invite'))
1072    #   {
1073    #       $props
1074    #   }
1075    #    }
1076    #
[8af89a7]1077    if(BarnOwl::getvar('jabber:spew') eq 'on') {
1078        BarnOwl::queue_message( BarnOwl::Message->new(%jhash) );
1079    }
[b6a253c]1080}
1081
[b405ff6]1082sub process_muc_presence {
[f62550d]1083    my ( $sid, $p ) = @_;
[b405ff6]1084    return unless ( $p->HasX('http://jabber.org/protocol/muc#user') );
[f62550d]1085}
1086
1087
1088sub process_presence_available {
1089    my ( $sid, $p ) = @_;
[a1a2036]1090    my $from = $p->GetFrom('jid')->GetJID('base');
[2ce12de]1091    $completion_jids{$from} = 1;
1092    return unless (BarnOwl::getvar('jabber:show_logins') eq 'on');
[f62550d]1093    my $to = $p->GetTo();
1094    my $type = $p->GetType();
1095    my %props = (
1096        to => $to,
[a1a2036]1097        from => $p->GetFrom(),
[f62550d]1098        recipient => $to,
1099        sender => $from,
1100        type => 'jabber',
1101        jtype => $p->GetType(),
1102        status => $p->GetStatus(),
1103        show => $p->GetShow(),
1104        xml => $p->GetXML(),
1105        direction => 'in');
1106
1107    if ($type eq '' || $type eq 'available') {
1108        $props{body} = "$from is now online. ";
1109        $props{loginout} = 'login';
1110    }
1111    else {
1112        $props{body} = "$from is now offline. ";
1113        $props{loginout} = 'logout';
1114    }
[a1a2036]1115    BarnOwl::queue_message(BarnOwl::Message->new(%props));
[f62550d]1116}
1117
1118sub process_presence_subscribe {
1119    my ( $sid, $p ) = @_;
1120    my $from = $p->GetFrom();
1121    my $to = $p->GetTo();
1122    my %props = (
1123        to => $to,
1124        from => $from,
1125        xml => $p->GetXML(),
1126        type => 'admin',
1127        adminheader => 'Jabber presence: subscribe',
1128        direction => 'in');
1129
[5551208]1130    $props{body} = "Allow user ($from) to subscribe to your ($to) presence?\n" .
1131                   "(Answer with the `yes' or `no' commands)";
[8362a48]1132    $props{yescommand} = BarnOwl::quote('jroster', 'auth', $from, '-a', $to);
1133    $props{nocommand} = BarnOwl::quote('jroster', 'deauth', $from, '-a', $to);
[5551208]1134    $props{question} = "true";
[d609dd6]1135    BarnOwl::queue_message(BarnOwl::Message->new(%props));
[f62550d]1136}
1137
1138sub process_presence_unsubscribe {
1139    my ( $sid, $p ) = @_;
1140    my $from = $p->GetFrom();
1141    my $to = $p->GetTo();
1142    my %props = (
1143        to => $to,
1144        from => $from,
1145        xml => $p->GetXML(),
1146        type => 'admin',
1147        adminheader => 'Jabber presence: unsubscribe',
1148        direction => 'in');
1149
1150    $props{body} = "The user ($from) has been unsubscribed from your ($to) presence.\n";
[d609dd6]1151    BarnOwl::queue_message(BarnOwl::Message->new(%props));
[f62550d]1152
1153    # Find a connection to reply with.
[63bbef4]1154    foreach my $jid ($conn->getJIDs()) {
[b2648bc]1155        my $cJID = new Net::Jabber::JID;
[63bbef4]1156        $cJID->SetJID($jid);
1157        if ($to eq $cJID->GetJID('base') ||
1158            $to eq $cJID->GetJID('full')) {
[f62550d]1159            my $reply = $p->Reply(type=>"unsubscribed");
[455f1ab]1160            $conn->getConnectionFromJID($jid)->Send($reply);
[f62550d]1161            return;
1162        }
1163    }
1164}
[38ffdf9]1165
[f62550d]1166sub process_presence_subscribed {
1167    my ( $sid, $p ) = @_;
[b73ce70]1168    queue_admin_msg("ignoring:".$p->GetXML()) if BarnOwl::getvar('jabber:spew') eq 'on';
[f62550d]1169    # RFC 3921 says we should respond to this with a "subscribe"
1170    # but this causes a flood of sub/sub'd presence packets with
1171    # some servers, so we won't. We may want to detect this condition
1172    # later, and have per-server settings.
1173    return;
1174}
1175
1176sub process_presence_unsubscribed {
1177    my ( $sid, $p ) = @_;
[b73ce70]1178    queue_admin_msg("ignoring:".$p->GetXML()) if BarnOwl::getvar('jabber:spew') eq 'on';
[f62550d]1179    # RFC 3921 says we should respond to this with a "subscribe"
1180    # but this causes a flood of unsub/unsub'd presence packets with
1181    # some servers, so we won't. We may want to detect this condition
1182    # later, and have per-server settings.
1183    return;
[b405ff6]1184}
[38ffdf9]1185
[9667006]1186sub process_presence_error {
1187    my ( $sid, $p ) = @_;
1188    my $code = $p->GetErrorCode();
1189    my $error = $p->GetError();
[d609dd6]1190    BarnOwl::error("Jabber: $code $error");
[9667006]1191}
1192
[f62550d]1193
[38ffdf9]1194### Helper functions
1195
[b405ff6]1196sub j2hash {
1197    my $j   = shift;
[7a45a72]1198    my %props = (type => 'jabber',
1199                 dir  => 'none',
1200                 %{$_[0]});
[38ffdf9]1201
[7a45a72]1202    my $dir = $props{direction};
[38ffdf9]1203
[b6a253c]1204    my $jtype = $props{jtype} = $j->GetType();
[b405ff6]1205    my $from = $j->GetFrom('jid');
1206    my $to   = $j->GetTo('jid');
[38ffdf9]1207
[b6a253c]1208    $props{from} = $from->GetJID('full');
1209    $props{to}   = $to->GetJID('full');
[38ffdf9]1210
[b6a253c]1211    $props{recipient}  = $to->GetJID('base');
1212    $props{sender}     = $from->GetJID('base');
[b405ff6]1213    $props{subject}    = $j->GetSubject() if ( $j->DefinedSubject() );
1214    $props{thread}     = $j->GetThread() if ( $j->DefinedThread() );
[e979da9]1215    if ( $j->DefinedBody() ) {
1216        $props{body}   = $j->GetBody();
1217        $props{body}  =~ s/\xEF\xBB\xBF//g; # Strip stray Byte-Order-Marks.
1218    }
[b405ff6]1219    $props{error}      = $j->GetError() if ( $j->DefinedError() );
1220    $props{error_code} = $j->GetErrorCode() if ( $j->DefinedErrorCode() );
[b6a253c]1221    $props{xml}        = $j->GetXML();
[38ffdf9]1222
[b405ff6]1223    if ( $jtype eq 'chat' ) {
[cb769bb]1224        $props{private} = 1;
[b2648bc]1225
1226        my $connection;
1227        if ($dir eq 'in') {
1228            $connection = $conn->getConnectionFromSid($props{sid});
1229        }
1230        else {
1231            $connection = $conn->getConnectionFromJID($props{from});
1232        }
1233
1234        # Check to see if we're doing personals with someone in a muc.
1235        # If we are, show the full jid because the base jid is the room.
1236        if ($connection) {
1237            $props{sender} = $props{from}
1238              if ($connection->FindMUC(jid => $from));
1239            $props{recipient} = $props{to}
1240              if ($connection->FindMUC(jid => $to));
1241        }
[2ce12de]1242
1243        # Populate completion.
1244        if ($dir eq 'in') {
1245            $completion_jids{ $props{sender} }= 1;
1246        }
1247        else {
1248            $completion_jids{ $props{recipient} } = 1;
1249        }
[38ffdf9]1250    }
[b405ff6]1251    elsif ( $jtype eq 'groupchat' ) {
1252        my $nick = $props{nick} = $from->GetResource();
1253        my $room = $props{room} = $from->GetJID('base');
[2ce12de]1254        $completion_jids{$room} = 1;
[45d9eb0]1255
[b405ff6]1256        $props{sender} = $nick || $room;
1257        $props{recipient} = $room;
1258
1259        if ( $props{subject} && !$props{body} ) {
1260            $props{body} =
1261              '[' . $nick . " has set the topic to: " . $props{subject} . "]";
1262        }
[b6a253c]1263    }
[b405ff6]1264    elsif ( $jtype eq 'normal' ) {
[cb769bb]1265        $props{private} = 1;
[b6a253c]1266    }
[b405ff6]1267    elsif ( $jtype eq 'headline' ) {
[b6a253c]1268    }
[b405ff6]1269    elsif ( $jtype eq 'error' ) {
1270        $props{body}     = "Error "
1271          . $props{error_code}
1272          . " sending to "
1273          . $props{from} . "\n"
1274          . $props{error};
1275    }
1276
[b6a253c]1277    return %props;
1278}
[38ffdf9]1279
[b405ff6]1280sub j2o {
[d609dd6]1281    return BarnOwl::Message->new( j2hash(@_) );
[38ffdf9]1282}
1283
[b405ff6]1284sub queue_admin_msg {
[38ffdf9]1285    my $err = shift;
[f6c2b3d]1286    BarnOwl::admin_message("Jabber", $err);
[38ffdf9]1287}
[b6a253c]1288
[b405ff6]1289sub getServerFromJID {
[6a6dd47]1290    my $jid = shift;
1291    my $res = new Net::DNS::Resolver;
[b405ff6]1292    my $packet =
1293      $res->search( '_xmpp-client._tcp.' . $jid->GetServer(), 'srv' );
[6a6dd47]1294
[b405ff6]1295    if ($packet)    # Got srv record.
[6a6dd47]1296    {
[b405ff6]1297        my @answer = $packet->answer;
1298        return $answer[0]{target}, $answer[0]{port};
[6a6dd47]1299    }
1300
1301    return $jid->GetServer(), 5222;
1302}
1303
[9f183ff]1304sub defaultJID {
[63bbef4]1305    return ( $conn->getJIDs() )[0] if ( $conn->connected() == 1 );
[b405ff6]1306    return;
[9f183ff]1307}
1308
[84296f6]1309sub baseJID {
[63bbef4]1310    my $givenJIDStr = shift;
[b2648bc]1311    my $givenJID    = new Net::Jabber::JID;
[63bbef4]1312    $givenJID->SetJID($givenJIDStr);
1313    return $givenJID->GetJID('base');
[84296f6]1314}
1315
[455f1ab]1316sub resolveConnectedJID {
[367fbf3]1317    my $givenJIDStr = shift;
[06f5ef8]1318    my $loose = shift || 0;
[b2648bc]1319    my $givenJID    = new Net::Jabber::JID;
[63bbef4]1320    $givenJID->SetJID($givenJIDStr);
[b405ff6]1321
[6a6dd47]1322    # Account fully specified.
[63bbef4]1323    if ( $givenJID->GetResource() ) {
[b405ff6]1324        # Specified account exists
[63bbef4]1325        return $givenJIDStr if ($conn->jidExists($givenJIDStr) );
[06f5ef8]1326        return resolveConnectedJID($givenJID->GetJID('base')) if $loose;
[63bbef4]1327        die("Invalid account: $givenJIDStr");
[6a6dd47]1328    }
[b405ff6]1329
[6a6dd47]1330    # Disambiguate.
[b405ff6]1331    else {
[06f5ef8]1332        my $JIDMatchingJID = "";
1333        my $strMatchingJID = "";
1334        my $JIDMatches = "";
1335        my $strMatches = "";
1336        my $JIDAmbiguous = 0;
1337        my $strAmbiguous = 0;
[b405ff6]1338
[63bbef4]1339        foreach my $jid ( $conn->getJIDs() ) {
[b2648bc]1340            my $cJID = new Net::Jabber::JID;
[63bbef4]1341            $cJID->SetJID($jid);
1342            if ( $givenJIDStr eq $cJID->GetJID('base') ) {
[06f5ef8]1343                $JIDAmbiguous = 1 if ( $JIDMatchingJID ne "" );
1344                $JIDMatchingJID = $jid;
1345                $JIDMatches .= "\t$jid\n";
1346            }
1347            if ( $cJID->GetJID('base') =~ /$givenJIDStr/ ) {
1348                $strAmbiguous = 1 if ( $strMatchingJID ne "" );
1349                $strMatchingJID = $jid;
1350                $strMatches .= "\t$jid\n";
[b405ff6]1351            }
1352        }
1353
1354        # Need further disambiguation.
[06f5ef8]1355        if ($JIDAmbiguous) {
1356            my $errStr =
1357                "Ambiguous account reference. Please specify a resource.\n";
1358            die($errStr.$JIDMatches);
[b405ff6]1359        }
1360
[06f5ef8]1361        # It's this one.
1362        elsif ($JIDMatchingJID ne "") {
1363            return $JIDMatchingJID;
[b405ff6]1364        }
1365
[06f5ef8]1366        # Further resolution by substring.
1367        elsif ($strAmbiguous) {
1368            my $errStr =
1369                "Ambiguous account reference. Please be more specific.\n";
1370            die($errStr.$strMatches);
1371        }
1372
1373        # It's this one, by substring.
1374        elsif ($strMatchingJID ne "") {
1375            return $strMatchingJID;
1376        }
1377
1378        # Not one of ours.
[b405ff6]1379        else {
[06f5ef8]1380            die("Invalid account: $givenJIDStr");
[b405ff6]1381        }
[06f5ef8]1382
[6a6dd47]1383    }
1384    return "";
1385}
[84296f6]1386
[455f1ab]1387sub resolveDestJID {
1388    my ($to, $from) = @_;
1389    my $jid = Net::Jabber::JID->new($to);
1390
1391    my $roster = $conn->getRosterFromJID($from);
1392    my @jids = $roster->jids('all');
1393    for my $j (@jids) {
[63bbef4]1394        if(($roster->query($j, 'name') || $j->GetUserID()) eq $to) {
[3ce5bdc]1395            return $j->GetJID('full');
1396        } elsif($j->GetJID('base') eq baseJID($to)) {
[c25a20f]1397            return $jid->GetJID('full');
[455f1ab]1398        }
1399    }
1400
[71e33ca]1401    # If we found nothing being clever, check to see if our input was
1402    # sane enough to look like a jid with a UserID.
1403    return $jid->GetJID('full') if $jid->GetUserID();
1404    return undef;
[455f1ab]1405}
1406
1407sub resolveType {
1408    my $to = shift;
1409    my $from = shift;
[3ce5bdc]1410    return unless $from;
[455f1ab]1411    my @mucs = $conn->getConnectionFromJID($from)->MUCs;
1412    if(grep {$_->BaseJID eq $to } @mucs) {
1413        return 'groupchat';
1414    } else {
1415        return 'chat';
1416    }
1417}
1418
1419sub guess_jwrite {
1420    # Heuristically guess what jids a jwrite was meant to be going to/from
1421    my ($from, $to) = (@_);
1422    my ($from_jid, $to_jid);
[989fae0]1423    my @matches;
[455f1ab]1424    if($from) {
[06f5ef8]1425        $from_jid = resolveConnectedJID($from, 1);
[455f1ab]1426        die("Unable to resolve account $from") unless $from_jid;
1427        $to_jid = resolveDestJID($to, $from_jid);
[0da506c]1428        push @matches, [$from_jid, $to_jid] if $to_jid;
[455f1ab]1429    } else {
[989fae0]1430        for my $f ($conn->getJIDs) {
[455f1ab]1431            $to_jid = resolveDestJID($to, $f);
1432            if(defined($to_jid)) {
[989fae0]1433                push @matches, [$f, $to_jid];
[455f1ab]1434            }
1435        }
[989fae0]1436        if($to =~ /@/) {
1437            push @matches, [$_, $to]
1438               for ($conn->getJIDs);
1439        }
[455f1ab]1440    }
1441
[989fae0]1442    for my $m (@matches) {
1443        my $type = resolveType($m->[1], $m->[0]);
1444        push @$m, $type;
1445    }
[45d9eb0]1446
[989fae0]1447    return @matches;
[455f1ab]1448}
1449
[2ce12de]1450################################################################################
1451### Completion
1452
1453sub complete_user_or_muc { return keys %completion_jids; }
1454sub complete_account { return $conn->getJIDs(); }
1455
1456sub complete_jwrite {
1457    my $ctx = shift;
1458    return complete_flags($ctx,
1459                          [qw(-t -i -s)],
1460                          {
1461                              "-a" => \&complete_account,
1462                          },
[57ba9f1]1463                          \&complete_user_or_muc
[2ce12de]1464        );
1465}
1466
[57ba9f1]1467BarnOwl::Completion::register_completer(jwrite => sub { BarnOwl::Module::Jabber::complete_jwrite(@_) });
[2ce12de]1468
[84296f6]14691;
Note: See TracBrowser for help on using the repository browser.