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

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