source: perl/modules/Jabber/lib/BarnOwl/Module/Jabber.pm @ 6b580b0

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