source: perl/modules/Jabber/lib/BarnOwl/Module/Jabber.pm @ 96134cb

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