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

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