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

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