source: perl/modules/Jabber/lib/BarnOwl/Module/Jabber.pm @ 799b60e

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