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

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