source: perl/modules/Jabber/lib/BarnOwl/Module/Jabber.pm @ 94b4ecb5

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