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

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