source: perl/modules/Jabber/lib/BarnOwl/Module/Jabber.pm @ 367fbf3

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