source: perl/modules/Jabber/lib/BarnOwl/Module/Jabber.pm @ 05f0061

barnowl_perlaimdebianrelease-1.10release-1.4release-1.5release-1.6release-1.7release-1.8release-1.9
Last change on this file since 05f0061 was 05f0061, checked in by Alejandro R. Sedeño <asedeno@mit.edu>, 16 years ago
Jabber - * fix logins to jabber.org - reported by gendalia
  • Property mode set to 100644
File size: 39.3 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' ) {
[05f0061]372                if ( !$vars{jlogin_havepass} && ( !@result || $result[0] eq '401' || $result[0] eq 'error') ) {
[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
[86840c5]583    die("Error: Must specify a fully-qualified MUC name (e.g. barnowl\@conference.mit.edu)\n")
584        unless $muc =~ /@/;
[3ec8d9a]585    $muc = Net::Jabber::JID->new($muc);
586    $jid = Net::Jabber::JID->new($jid);
587    $muc->SetResource($jid->GetJID('full')) unless length $muc->GetResource();
588
[63bbef4]589    $conn->getConnectionFromJID($jid)->MUCJoin(JID      => $muc,
[86840c5]590                                               Password => $password,
591                                               History  => {
592                                                   MaxChars => 0
593                                                  });
[1dfc7df]594    return;
[6df381b]595}
596
597sub jmuc_part {
[b405ff6]598    my ( $jid, $muc, @args ) = @_;
[9f183ff]599
[b405ff6]600    $muc = shift @args if scalar @args;
[60986b2]601    die("Usage: jmuc part MUC [-a account]") unless $muc;
[9f183ff]602
[892568b]603    if($conn->getConnectionFromJID($jid)->MUCLeave(JID => $muc)) {
604        queue_admin_msg("$jid has left $muc.");
605    } else {
606        die("Error: Not joined to $muc");
607    }
[6df381b]608}
609
[b405ff6]610sub jmuc_invite {
611    my ( $jid, $muc, @args ) = @_;
612
613    my $invite_jid = shift @args;
614    $muc = shift @args if scalar @args;
615
[60986b2]616    die('Usage: jmuc invite JID [muc] [-a account]')
[b405ff6]617      unless $muc && $invite_jid;
618
[d9f4a5c]619    my $message = Net::Jabber::Message->new();
[b405ff6]620    $message->SetTo($muc);
[d9f4a5c]621    my $x = $message->NewChild('http://jabber.org/protocol/muc#user');
622    $x->AddInvite();
623    $x->GetInvite()->SetTo($invite_jid);
[455f1ab]624    $conn->getConnectionFromJID($jid)->Send($message);
[b405ff6]625    queue_admin_msg("$jid has invited $invite_jid to $muc.");
[38ffdf9]626}
627
[9f183ff]628sub jmuc_configure {
[b405ff6]629    my ( $jid, $muc, @args ) = @_;
630    $muc = shift @args if scalar @args;
631    die("Usage: jmuc configure [muc]") unless $muc;
632    my $iq = Net::Jabber::IQ->new();
633    $iq->SetTo($muc);
634    $iq->SetType('set');
635    my $query = $iq->NewQuery("http://jabber.org/protocol/muc#owner");
636    my $x     = $query->NewChild("jabber:x:data");
637    $x->SetType('submit');
638
[455f1ab]639    $conn->getConnectionFromJID($jid)->Send($iq);
[b405ff6]640    queue_admin_msg("Accepted default instant configuration for $muc");
[9f183ff]641}
642
[7cdf756]643sub jmuc_presence_single {
644    my $m = shift;
645    my @jids = $m->Presence();
[892568b]646
647    my $presence = "JIDs present in " . $m->BaseJID;
648    if($m->Anonymous) {
649        $presence .= " [anonymous MUC]";
650    }
651    $presence .= "\n\t";
652    $presence .= join("\n\t", map {pp_jid($m, $_);} @jids) . "\n";
653    return $presence;
654}
655
656sub pp_jid {
657    my ($m, $jid) = @_;
658    my $nick = $jid->GetResource;
659    my $full = $m->GetFullJID($jid);
660    if($full && $full ne $nick) {
661        return "$nick ($full)";
662    } else {
663        return "$nick";
664    }
[7cdf756]665}
666
[1dfc7df]667sub jmuc_presence {
668    my ( $jid, $muc, @args ) = @_;
669
[e1b197e8]670    $muc = shift @args if scalar @args;
671    die("Usage: jmuc presence MUC") unless $muc;
672
[7cdf756]673    if ($muc eq '-a') {
674        my $str = "";
675        foreach my $jid ($conn->getJIDs()) {
[2cedb7a]676            $str .= BarnOwl::Style::boldify("Conferences for $jid:\n");
[7cdf756]677            my $connection = $conn->getConnectionFromJID($jid);
678            foreach my $muc ($connection->MUCs) {
679                $str .= jmuc_presence_single($muc)."\n";
680            }
681        }
682        BarnOwl::popless_ztext($str);
683    }
684    else {
685        my $m = $conn->getConnectionFromJID($jid)->FindMUC(jid => $muc);
686        die("No such muc: $muc") unless $m;
687        BarnOwl::popless_ztext(jmuc_presence_single($m));
688    }
[1dfc7df]689}
690
[f62550d]691
692#XXX TODO: Consider merging this with jmuc and selecting off the first two args.
693sub cmd_jroster {
694    die "You are not logged in to Jabber" unless $conn->connected();
695    my $ocmd = shift;
696    my $cmd  = shift;
697    if ( !$cmd ) {
698
699        #XXX TODO: Write general usage for jroster command.
700        return;
701    }
702
703    my %jroster_commands = (
704        sub      => \&jroster_sub,
705        unsub    => \&jroster_unsub,
706        add      => \&jroster_add,
707        remove   => \&jroster_remove,
708        auth     => \&jroster_auth,
709        deauth   => \&jroster_deauth
710    );
711    my $func = $jroster_commands{$cmd};
712    if ( !$func ) {
[d609dd6]713        BarnOwl::error("jroster: Unknown command: $cmd");
[f62550d]714        return;
715    }
716
717    {
718        local @ARGV = @_;
719        my $jid;
720        my $name;
721        my @groups;
722        my $purgeGroups;
723        my $getopt = Getopt::Long::Parser->new;
724        $getopt->configure('pass_through');
725        $getopt->getoptions(
726            'account=s' => \$jid,
727            'group=s' => \@groups,
728            'purgegroups' => \$purgeGroups,
729            'name=s' => \$name
730        );
731        $jid ||= defaultJID();
732        if ($jid) {
[455f1ab]733            $jid = resolveConnectedJID($jid);
[f62550d]734            return unless $jid;
735        }
736        else {
[d609dd6]737            BarnOwl::error('You must specify an account with -a {jid}');
[f62550d]738        }
739        return $func->( $jid, $name, \@groups, $purgeGroups,  @ARGV );
740    }
741}
742
743sub jroster_sub {
744    my $jid = shift;
745    my $name = shift;
746    my @groups = @{ shift() };
747    my $purgeGroups = shift;
[63bbef4]748    my $baseJID = baseJID($jid);
[f62550d]749
[455f1ab]750    my $roster = $conn->getRosterFromJID($jid);
[f62550d]751
752    # Adding lots of users with the same name is a bad idea.
753    $name = "" unless (1 == scalar(@ARGV));
754
[b2648bc]755    my $p = new Net::Jabber::Presence;
[f62550d]756    $p->SetType('subscribe');
757
758    foreach my $to (@ARGV) {
[bed4ff1]759        jroster_add($jid, $name, \@groups, $purgeGroups, ($to)) unless ($roster->exists($to));
[f62550d]760
761        $p->SetTo($to);
[455f1ab]762        $conn->getConnectionFromJID($jid)->Send($p);
[63bbef4]763        queue_admin_msg("You ($baseJID) have requested a subscription to ($to)'s presence.");
[f62550d]764    }
765}
766
767sub jroster_unsub {
768    my $jid = shift;
769    my $name = shift;
770    my @groups = @{ shift() };
771    my $purgeGroups = shift;
[63bbef4]772    my $baseJID = baseJID($jid);
[f62550d]773
[b2648bc]774    my $p = new Net::Jabber::Presence;
[f62550d]775    $p->SetType('unsubscribe');
776    foreach my $to (@ARGV) {
777        $p->SetTo($to);
[455f1ab]778        $conn->getConnectionFromJID($jid)->Send($p);
[63bbef4]779        queue_admin_msg("You ($baseJID) have unsubscribed from ($to)'s presence.");
[f62550d]780    }
781}
782
783sub jroster_add {
784    my $jid = shift;
785    my $name = shift;
786    my @groups = @{ shift() };
787    my $purgeGroups = shift;
[63bbef4]788    my $baseJID = baseJID($jid);
[f62550d]789
[455f1ab]790    my $roster = $conn->getRosterFromJID($jid);
[f62550d]791
792    # Adding lots of users with the same name is a bad idea.
793    $name = "" unless (1 == scalar(@ARGV));
794
795    foreach my $to (@ARGV) {
[bed4ff1]796        my %jq  = $roster->query($to);
[b2648bc]797        my $iq = new Net::Jabber::IQ;
[f62550d]798        $iq->SetType('set');
799        my $item = new XML::Stream::Node('item');
800        $iq->NewChild('jabber:iq:roster')->AddChild($item);
801
802        my %allGroups = ();
803
804        foreach my $g (@groups) {
805            $allGroups{$g} = $g;
806        }
807
808        unless ($purgeGroups) {
809            foreach my $g (@{$jq{groups}}) {
810                $allGroups{$g} = $g;
811            }
812        }
813
814        foreach my $g (keys %allGroups) {
815            $item->add_child('group')->add_cdata($g);
816        }
817
818        $item->put_attrib(jid => $to);
819        $item->put_attrib(name => $name) if $name;
[455f1ab]820        $conn->getConnectionFromJID($jid)->Send($iq);
[63bbef4]821        my $msg = "$baseJID: "
[f62550d]822          . ($name ? "$name ($to)" : "($to)")
823          . " is on your roster in the following groups: { "
824          . join(" , ", keys %allGroups)
825          . " }";
826        queue_admin_msg($msg);
827    }
828}
829
830sub jroster_remove {
831    my $jid = shift;
832    my $name = shift;
833    my @groups = @{ shift() };
834    my $purgeGroups = shift;
[63bbef4]835    my $baseJID = baseJID($jid);
[f62550d]836
[b2648bc]837    my $iq = new Net::Jabber::IQ;
[f62550d]838    $iq->SetType('set');
839    my $item = new XML::Stream::Node('item');
840    $iq->NewChild('jabber:iq:roster')->AddChild($item);
841    $item->put_attrib(subscription=> 'remove');
842    foreach my $to (@ARGV) {
843        $item->put_attrib(jid => $to);
[455f1ab]844        $conn->getConnectionFromJID($jid)->Send($iq);
[63bbef4]845        queue_admin_msg("You ($baseJID) have removed ($to) from your roster.");
[f62550d]846    }
847}
848
849sub jroster_auth {
850    my $jid = shift;
851    my $name = shift;
852    my @groups = @{ shift() };
853    my $purgeGroups = shift;
[63bbef4]854    my $baseJID = baseJID($jid);
[f62550d]855
[b2648bc]856    my $p = new Net::Jabber::Presence;
[f62550d]857    $p->SetType('subscribed');
858    foreach my $to (@ARGV) {
859        $p->SetTo($to);
[455f1ab]860        $conn->getConnectionFromJID($jid)->Send($p);
[63bbef4]861        queue_admin_msg("($to) has been subscribed to your ($baseJID) presence.");
[f62550d]862    }
863}
864
865sub jroster_deauth {
866    my $jid = shift;
867    my $name = shift;
868    my @groups = @{ shift() };
869    my $purgeGroups = shift;
[63bbef4]870    my $baseJID = baseJID($jid);
[f62550d]871
[b2648bc]872    my $p = new Net::Jabber::Presence;
[f62550d]873    $p->SetType('unsubscribed');
874    foreach my $to (@ARGV) {
875        $p->SetTo($to);
[455f1ab]876        $conn->getConnectionFromJID($jid)->Send($p);
[63bbef4]877        queue_admin_msg("($to) has been unsubscribed from your ($baseJID) presence.");
[f62550d]878    }
879}
880
[38ffdf9]881################################################################################
882### Owl Callbacks
[b405ff6]883sub process_owl_jwrite {
[38ffdf9]884    my $body = shift;
885
[b2648bc]886    my $j = new Net::Jabber::Message;
[38ffdf9]887    $body =~ s/\n\z//;
[b405ff6]888    $j->SetMessage(
889        to   => $vars{jwrite}{to},
890        from => $vars{jwrite}{from},
891        type => $vars{jwrite}{type},
892        body => $body
893    );
[f62550d]894
[b405ff6]895    $j->SetThread( $vars{jwrite}{thread} )   if ( $vars{jwrite}{thread} );
896    $j->SetSubject( $vars{jwrite}{subject} ) if ( $vars{jwrite}{subject} );
897
[f62550d]898    my $m = j2o( $j, { direction => 'out' } );
[1c2e0b3]899    if ( $vars{jwrite}{type} ne 'groupchat') {
[13a3c1db]900        BarnOwl::queue_message($m);
[38ffdf9]901    }
[f62550d]902
[b2648bc]903    $j->RemoveFrom(); # Kludge to get around gtalk's random bits after the resource.
[f62550d]904    if ($vars{jwrite}{sid} && $conn->sidExists( $vars{jwrite}{sid} )) {
[bed4ff1]905        $conn->getConnectionFromSid($vars{jwrite}{sid})->Send($j);
[f62550d]906    }
907    else {
[455f1ab]908        $conn->getConnectionFromJID($vars{jwrite}{from})->Send($j);
[f62550d]909    }
910
[6a6dd47]911    delete $vars{jwrite};
[d609dd6]912    BarnOwl::message("");   # Kludge to make the ``type your message...'' message go away
[38ffdf9]913}
914
915### XMPP Callbacks
916
[b405ff6]917sub process_incoming_chat_message {
[f62550d]918    my ( $sid, $j ) = @_;
[d609dd6]919    BarnOwl::queue_message( j2o( $j, { direction => 'in',
[f62550d]920                                   sid => $sid } ) );
[38ffdf9]921}
922
[b405ff6]923sub process_incoming_error_message {
[f62550d]924    my ( $sid, $j ) = @_;
925    my %jhash = j2hash( $j, { direction => 'in',
926                              sid => $sid } );
[b6a253c]927    $jhash{type} = 'admin';
[79c06ae]928   
[d609dd6]929    BarnOwl::queue_message( BarnOwl::Message->new(%jhash) );
[38ffdf9]930}
931
[b405ff6]932sub process_incoming_groupchat_message {
[f62550d]933    my ( $sid, $j ) = @_;
[b405ff6]934
[38ffdf9]935    # HACK IN PROGRESS (ignoring delayed messages)
[b405ff6]936    return if ( $j->DefinedX('jabber:x:delay') && $j->GetX('jabber:x:delay') );
[d609dd6]937    BarnOwl::queue_message( j2o( $j, { direction => 'in',
[f62550d]938                                   sid => $sid } ) );
[38ffdf9]939}
940
[b405ff6]941sub process_incoming_headline_message {
[f62550d]942    my ( $sid, $j ) = @_;
[d609dd6]943    BarnOwl::queue_message( j2o( $j, { direction => 'in',
[f62550d]944                                   sid => $sid } ) );
[38ffdf9]945}
946
[b405ff6]947sub process_incoming_normal_message {
[f62550d]948    my ( $sid, $j ) = @_;
949    my %jhash = j2hash( $j, { direction => 'in',
950                              sid => $sid } );
[b6a253c]951
952    # XXX TODO: handle things such as MUC invites here.
953
[b405ff6]954    #    if ($j->HasX('http://jabber.org/protocol/muc#user'))
955    #    {
956    #   my $x = $j->GetX('http://jabber.org/protocol/muc#user');
957    #   if ($x->HasChild('invite'))
958    #   {
959    #       $props
960    #   }
961    #    }
962    #
[d609dd6]963    BarnOwl::queue_message( BarnOwl::Message->new(%jhash) );
[b6a253c]964}
965
[b405ff6]966sub process_muc_presence {
[f62550d]967    my ( $sid, $p ) = @_;
[b405ff6]968    return unless ( $p->HasX('http://jabber.org/protocol/muc#user') );
[f62550d]969}
970
971
972sub process_presence_available {
973    my ( $sid, $p ) = @_;
974    my $from = $p->GetFrom();
975    my $to = $p->GetTo();
976    my $type = $p->GetType();
977    my %props = (
978        to => $to,
979        from => $from,
980        recipient => $to,
981        sender => $from,
982        type => 'jabber',
983        jtype => $p->GetType(),
984        status => $p->GetStatus(),
985        show => $p->GetShow(),
986        xml => $p->GetXML(),
987        direction => 'in');
988
989    if ($type eq '' || $type eq 'available') {
990        $props{body} = "$from is now online. ";
991        $props{loginout} = 'login';
992    }
993    else {
994        $props{body} = "$from is now offline. ";
995        $props{loginout} = 'logout';
996    }
997    $props{replysendercmd} = $props{replycmd} = "jwrite $from -i $sid";
[575877f]998    if(BarnOwl::getvar('debug') eq 'on') {
[f3c1aba]999        BarnOwl::queue_message(BarnOwl::Message->new(%props));
[575877f]1000    }
[f62550d]1001}
1002
1003sub process_presence_subscribe {
1004    my ( $sid, $p ) = @_;
1005    my $from = $p->GetFrom();
1006    my $to = $p->GetTo();
1007    my %props = (
1008        to => $to,
1009        from => $from,
1010        xml => $p->GetXML(),
1011        type => 'admin',
1012        adminheader => 'Jabber presence: subscribe',
1013        direction => 'in');
1014
[5551208]1015    $props{body} = "Allow user ($from) to subscribe to your ($to) presence?\n" .
1016                   "(Answer with the `yes' or `no' commands)";
1017    $props{yescommand} = "jroster auth $from -a $to";
1018    $props{nocommand} = "jroster deauth $from -a $to";
1019    $props{question} = "true";
[d609dd6]1020    BarnOwl::queue_message(BarnOwl::Message->new(%props));
[f62550d]1021}
1022
1023sub process_presence_unsubscribe {
1024    my ( $sid, $p ) = @_;
1025    my $from = $p->GetFrom();
1026    my $to = $p->GetTo();
1027    my %props = (
1028        to => $to,
1029        from => $from,
1030        xml => $p->GetXML(),
1031        type => 'admin',
1032        adminheader => 'Jabber presence: unsubscribe',
1033        direction => 'in');
1034
1035    $props{body} = "The user ($from) has been unsubscribed from your ($to) presence.\n";
[d609dd6]1036    BarnOwl::queue_message(BarnOwl::Message->new(%props));
[f62550d]1037
1038    # Find a connection to reply with.
[63bbef4]1039    foreach my $jid ($conn->getJIDs()) {
[b2648bc]1040        my $cJID = new Net::Jabber::JID;
[63bbef4]1041        $cJID->SetJID($jid);
1042        if ($to eq $cJID->GetJID('base') ||
1043            $to eq $cJID->GetJID('full')) {
[f62550d]1044            my $reply = $p->Reply(type=>"unsubscribed");
[455f1ab]1045            $conn->getConnectionFromJID($jid)->Send($reply);
[f62550d]1046            return;
1047        }
1048    }
1049}
[38ffdf9]1050
[f62550d]1051sub process_presence_subscribed {
1052    my ( $sid, $p ) = @_;
1053    queue_admin_msg("ignoring:".$p->GetXML());
1054    # RFC 3921 says we should respond to this with a "subscribe"
1055    # but this causes a flood of sub/sub'd presence packets with
1056    # some servers, so we won't. We may want to detect this condition
1057    # later, and have per-server settings.
1058    return;
1059}
1060
1061sub process_presence_unsubscribed {
1062    my ( $sid, $p ) = @_;
1063    queue_admin_msg("ignoring:".$p->GetXML());
1064    # RFC 3921 says we should respond to this with a "subscribe"
1065    # but this causes a flood of unsub/unsub'd presence packets with
1066    # some servers, so we won't. We may want to detect this condition
1067    # later, and have per-server settings.
1068    return;
[b405ff6]1069}
[38ffdf9]1070
[9667006]1071sub process_presence_error {
1072    my ( $sid, $p ) = @_;
1073    my $code = $p->GetErrorCode();
1074    my $error = $p->GetError();
[d609dd6]1075    BarnOwl::error("Jabber: $code $error");
[9667006]1076}
1077
[f62550d]1078
[38ffdf9]1079### Helper functions
1080
[b405ff6]1081sub j2hash {
1082    my $j   = shift;
[f62550d]1083    my %initProps = %{ shift() };
[38ffdf9]1084
[f62550d]1085    my $dir = 'none';
1086    my %props = ( type => 'jabber' );
1087
1088    foreach my $k (keys %initProps) {
1089        $dir = $initProps{$k} if ($k eq 'direction');
1090        $props{$k} = $initProps{$k};
1091    }
[38ffdf9]1092
[b6a253c]1093    my $jtype = $props{jtype} = $j->GetType();
[b405ff6]1094    my $from = $j->GetFrom('jid');
1095    my $to   = $j->GetTo('jid');
[38ffdf9]1096
[b6a253c]1097    $props{from} = $from->GetJID('full');
1098    $props{to}   = $to->GetJID('full');
[38ffdf9]1099
[b6a253c]1100    $props{recipient}  = $to->GetJID('base');
1101    $props{sender}     = $from->GetJID('base');
[b405ff6]1102    $props{subject}    = $j->GetSubject() if ( $j->DefinedSubject() );
1103    $props{thread}     = $j->GetThread() if ( $j->DefinedThread() );
1104    $props{body}       = $j->GetBody() if ( $j->DefinedBody() );
1105    $props{error}      = $j->GetError() if ( $j->DefinedError() );
1106    $props{error_code} = $j->GetErrorCode() if ( $j->DefinedErrorCode() );
[b6a253c]1107    $props{xml}        = $j->GetXML();
[38ffdf9]1108
[b405ff6]1109    if ( $jtype eq 'chat' ) {
1110        $props{replycmd} =
[f62550d]1111          "jwrite " . ( ( $dir eq 'in' ) ? $props{from} : $props{to} );
1112        $props{replycmd} .=
1113          " -a " . ( ( $dir eq 'out' ) ? $props{from} : $props{to} );
[cb769bb]1114        $props{private} = 1;
[b2648bc]1115
1116        my $connection;
1117        if ($dir eq 'in') {
1118            $connection = $conn->getConnectionFromSid($props{sid});
1119        }
1120        else {
1121            $connection = $conn->getConnectionFromJID($props{from});
1122        }
1123
1124        # Check to see if we're doing personals with someone in a muc.
1125        # If we are, show the full jid because the base jid is the room.
1126        if ($connection) {
1127            $props{sender} = $props{from}
1128              if ($connection->FindMUC(jid => $from));
1129            $props{recipient} = $props{to}
1130              if ($connection->FindMUC(jid => $to));
1131        }
[38ffdf9]1132    }
[b405ff6]1133    elsif ( $jtype eq 'groupchat' ) {
1134        my $nick = $props{nick} = $from->GetResource();
1135        my $room = $props{room} = $from->GetJID('base');
[455f1ab]1136        $props{replycmd} = "jwrite $room";
[f62550d]1137        $props{replycmd} .=
1138          " -a " . ( ( $dir eq 'out' ) ? $props{from} : $props{to} );
[693c8f2]1139        if ($props{subject}) {
1140          $props{replycmd} .= " -s " . $props{subject}
1141        }
[b405ff6]1142
[45d9eb0]1143        if ($dir eq 'out') {
1144            $props{replysendercmd} = "jwrite ".$props{to}." -a ".$props{from};
1145        }
1146        else {
1147            $props{replysendercmd} = "jwrite ".$props{from}." -a ".$props{to};
1148        }
1149
[b405ff6]1150        $props{sender} = $nick || $room;
1151        $props{recipient} = $room;
1152
1153        if ( $props{subject} && !$props{body} ) {
1154            $props{body} =
1155              '[' . $nick . " has set the topic to: " . $props{subject} . "]";
1156        }
[b6a253c]1157    }
[b405ff6]1158    elsif ( $jtype eq 'normal' ) {
[79c06ae]1159        $props{replycmd}  = "";
[cb769bb]1160        $props{private} = 1;
[b6a253c]1161    }
[b405ff6]1162    elsif ( $jtype eq 'headline' ) {
[79c06ae]1163        $props{replycmd} = "";
[b6a253c]1164    }
[b405ff6]1165    elsif ( $jtype eq 'error' ) {
[79c06ae]1166        $props{replycmd} = "";
[b405ff6]1167        $props{body}     = "Error "
1168          . $props{error_code}
1169          . " sending to "
1170          . $props{from} . "\n"
1171          . $props{error};
1172    }
1173
[45d9eb0]1174    $props{replysendercmd} = $props{replycmd} unless $props{replysendercmd};
[b6a253c]1175    return %props;
1176}
[38ffdf9]1177
[b405ff6]1178sub j2o {
[d609dd6]1179    return BarnOwl::Message->new( j2hash(@_) );
[38ffdf9]1180}
1181
[b405ff6]1182sub queue_admin_msg {
[38ffdf9]1183    my $err = shift;
[f6c2b3d]1184    BarnOwl::admin_message("Jabber", $err);
[38ffdf9]1185}
[b6a253c]1186
[b405ff6]1187sub getServerFromJID {
[6a6dd47]1188    my $jid = shift;
1189    my $res = new Net::DNS::Resolver;
[b405ff6]1190    my $packet =
1191      $res->search( '_xmpp-client._tcp.' . $jid->GetServer(), 'srv' );
[6a6dd47]1192
[b405ff6]1193    if ($packet)    # Got srv record.
[6a6dd47]1194    {
[b405ff6]1195        my @answer = $packet->answer;
1196        return $answer[0]{target}, $answer[0]{port};
[6a6dd47]1197    }
1198
1199    return $jid->GetServer(), 5222;
1200}
1201
[9f183ff]1202sub defaultJID {
[63bbef4]1203    return ( $conn->getJIDs() )[0] if ( $conn->connected() == 1 );
[b405ff6]1204    return;
[9f183ff]1205}
1206
[84296f6]1207sub baseJID {
[63bbef4]1208    my $givenJIDStr = shift;
[b2648bc]1209    my $givenJID    = new Net::Jabber::JID;
[63bbef4]1210    $givenJID->SetJID($givenJIDStr);
1211    return $givenJID->GetJID('base');
[84296f6]1212}
1213
[455f1ab]1214sub resolveConnectedJID {
[63bbef4]1215    my $givenJIDStr = shift;
[b2648bc]1216    my $givenJID    = new Net::Jabber::JID;
[63bbef4]1217    $givenJID->SetJID($givenJIDStr);
[b405ff6]1218
[6a6dd47]1219    # Account fully specified.
[63bbef4]1220    if ( $givenJID->GetResource() ) {
[b405ff6]1221        # Specified account exists
[63bbef4]1222        return $givenJIDStr if ($conn->jidExists($givenJIDStr) );
1223        die("Invalid account: $givenJIDStr");
[6a6dd47]1224    }
[b405ff6]1225
[6a6dd47]1226    # Disambiguate.
[b405ff6]1227    else {
[63bbef4]1228        my $matchingJID = "";
[b405ff6]1229        my $errStr =
1230          "Ambiguous account reference. Please specify a resource.\n";
1231        my $ambiguous = 0;
1232
[63bbef4]1233        foreach my $jid ( $conn->getJIDs() ) {
[b2648bc]1234            my $cJID = new Net::Jabber::JID;
[63bbef4]1235            $cJID->SetJID($jid);
1236            if ( $givenJIDStr eq $cJID->GetJID('base') ) {
1237                $ambiguous = 1 if ( $matchingJID ne "" );
1238                $matchingJID = $jid;
[b405ff6]1239                $errStr .= "\t$jid\n";
1240            }
1241        }
1242
1243        # Need further disambiguation.
1244        if ($ambiguous) {
[455f1ab]1245            die($errStr);
[b405ff6]1246        }
1247
1248        # Not one of ours.
[63bbef4]1249        elsif ( $matchingJID eq "" ) {
1250            die("Invalid account: $givenJIDStr");
[b405ff6]1251        }
1252
[84296f6]1253        # It's this one.
[b405ff6]1254        else {
[63bbef4]1255            return $matchingJID;
[b405ff6]1256        }
[6a6dd47]1257    }
1258    return "";
1259}
[84296f6]1260
[455f1ab]1261sub resolveDestJID {
1262    my ($to, $from) = @_;
1263    my $jid = Net::Jabber::JID->new($to);
1264
1265    my $roster = $conn->getRosterFromJID($from);
1266    my @jids = $roster->jids('all');
1267    for my $j (@jids) {
[63bbef4]1268        if(($roster->query($j, 'name') || $j->GetUserID()) eq $to) {
[3ce5bdc]1269            return $j->GetJID('full');
1270        } elsif($j->GetJID('base') eq baseJID($to)) {
[c25a20f]1271            return $jid->GetJID('full');
[455f1ab]1272        }
1273    }
1274
[71e33ca]1275    # If we found nothing being clever, check to see if our input was
1276    # sane enough to look like a jid with a UserID.
1277    return $jid->GetJID('full') if $jid->GetUserID();
1278    return undef;
[455f1ab]1279}
1280
1281sub resolveType {
1282    my $to = shift;
1283    my $from = shift;
[3ce5bdc]1284    return unless $from;
[455f1ab]1285    my @mucs = $conn->getConnectionFromJID($from)->MUCs;
1286    if(grep {$_->BaseJID eq $to } @mucs) {
1287        return 'groupchat';
1288    } else {
1289        return 'chat';
1290    }
1291}
1292
1293sub guess_jwrite {
1294    # Heuristically guess what jids a jwrite was meant to be going to/from
1295    my ($from, $to) = (@_);
1296    my ($from_jid, $to_jid);
[989fae0]1297    my @matches;
[455f1ab]1298    if($from) {
1299        $from_jid = resolveConnectedJID($from);
1300        die("Unable to resolve account $from") unless $from_jid;
1301        $to_jid = resolveDestJID($to, $from_jid);
[0da506c]1302        push @matches, [$from_jid, $to_jid] if $to_jid;
[455f1ab]1303    } else {
[989fae0]1304        for my $f ($conn->getJIDs) {
[455f1ab]1305            $to_jid = resolveDestJID($to, $f);
1306            if(defined($to_jid)) {
[989fae0]1307                push @matches, [$f, $to_jid];
[455f1ab]1308            }
1309        }
[989fae0]1310        if($to =~ /@/) {
1311            push @matches, [$_, $to]
1312               for ($conn->getJIDs);
1313        }
[455f1ab]1314    }
1315
[989fae0]1316    for my $m (@matches) {
1317        my $type = resolveType($m->[1], $m->[0]);
1318        push @$m, $type;
1319    }
[45d9eb0]1320
[989fae0]1321    return @matches;
[455f1ab]1322}
1323
[84296f6]13241;
Note: See TracBrowser for help on using the repository browser.