source: perl/modules/Jabber/lib/BarnOwl/Module/Jabber.pm @ 5f3168a

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