source: perl/modules/jabber.pl @ 1dfc7df

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