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

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