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

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