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

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