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

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