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

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