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

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