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

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