source: perl/modules/jabber.pl @ 65581e9

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