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

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