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

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