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

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