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

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