source: perl/modules/jabber.pl @ 855dc8d

barnowl_perlaimdebianrelease-1.10release-1.4release-1.5release-1.6release-1.7release-1.8release-1.9
Last change on this file since 855dc8d was e1b197e8, checked in by Nelson Elhage <nelhage@mit.edu>, 17 years ago
Some jmuc presence bugfixes
  • Property mode set to 100644
File size: 36.1 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 {$_->BaseJID ne $muc->BaseJID} $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    $muc = shift @args if scalar @args;
693    die("Usage: jmuc presence MUC") unless $muc;
694
695    my $m = $conn->getConnectionFromJidStr($jid)->FindMUC(jid => $muc);
696    die("No such muc: $muc") unless $m;
697
698    my @jids = $m->Presence();
699    BarnOwl::popless_ztext("JIDs present in " . $m->BaseJID . "\n\t" .
700                           join("\n\t", map {$_->GetResource}@jids) . "\n");
701}
702
703
704#XXX TODO: Consider merging this with jmuc and selecting off the first two args.
705sub cmd_jroster {
706    die "You are not logged in to Jabber" unless $conn->connected();
707    my $ocmd = shift;
708    my $cmd  = shift;
709    if ( !$cmd ) {
710
711        #XXX TODO: Write general usage for jroster command.
712        return;
713    }
714
715    my %jroster_commands = (
716        sub      => \&jroster_sub,
717        unsub    => \&jroster_unsub,
718        add      => \&jroster_add,
719        remove   => \&jroster_remove,
720        auth     => \&jroster_auth,
721        deauth   => \&jroster_deauth
722    );
723
724    my $func = $jroster_commands{$cmd};
725    if ( !$func ) {
726        BarnOwl::error("jroster: Unknown command: $cmd");
727        return;
728    }
729
730    {
731        local @ARGV = @_;
732        my $jid;
733        my $name;
734        my @groups;
735        my $purgeGroups;
736        my $getopt = Getopt::Long::Parser->new;
737        $getopt->configure('pass_through');
738        $getopt->getoptions(
739            'account=s' => \$jid,
740            'group=s' => \@groups,
741            'purgegroups' => \$purgeGroups,
742            'name=s' => \$name
743        );
744        $jid ||= defaultJID();
745        if ($jid) {
746            $jid = resolveJID($jid);
747            return unless $jid;
748        }
749        else {
750            BarnOwl::error('You must specify an account with -a {jid}');
751        }
752        return $func->( $jid, $name, \@groups, $purgeGroups,  @ARGV );
753    }
754}
755
756sub jroster_sub {
757    my $jid = shift;
758    my $name = shift;
759    my @groups = @{ shift() };
760    my $purgeGroups = shift;
761    my $baseJid = baseJID($jid);
762
763    my $roster = $conn->getRosterFromJidStr($jid);
764
765    # Adding lots of users with the same name is a bad idea.
766    $name = "" unless (1 == scalar(@ARGV));
767
768    my $p = new Net::XMPP::Presence;
769    $p->SetType('subscribe');
770
771    foreach my $to (@ARGV) {
772        jroster_add($jid, $name, \@groups, $purgeGroups, ($to)) unless ($roster->exists($to));
773
774        $p->SetTo($to);
775        $conn->getConnectionFromJidStr($jid)->Send($p);
776        queue_admin_msg("You ($baseJid) have requested a subscription to ($to)'s presence.");
777    }
778}
779
780sub jroster_unsub {
781    my $jid = shift;
782    my $name = shift;
783    my @groups = @{ shift() };
784    my $purgeGroups = shift;
785    my $baseJid = baseJID($jid);
786
787    my $p = new Net::XMPP::Presence;
788    $p->SetType('unsubscribe');
789    foreach my $to (@ARGV) {
790        $p->SetTo($to);
791        $conn->getConnectionFromJidStr($jid)->Send($p);
792        queue_admin_msg("You ($baseJid) have unsubscribed from ($to)'s presence.");
793    }
794}
795
796sub jroster_add {
797    my $jid = shift;
798    my $name = shift;
799    my @groups = @{ shift() };
800    my $purgeGroups = shift;
801    my $baseJid = baseJID($jid);
802
803    my $roster = $conn->getRosterFromJidStr($jid);
804
805    # Adding lots of users with the same name is a bad idea.
806    $name = "" unless (1 == scalar(@ARGV));
807
808    foreach my $to (@ARGV) {
809        my %jq  = $roster->query($to);
810        my $iq = new Net::XMPP::IQ;
811        $iq->SetType('set');
812        my $item = new XML::Stream::Node('item');
813        $iq->NewChild('jabber:iq:roster')->AddChild($item);
814
815        my %allGroups = ();
816
817        foreach my $g (@groups) {
818            $allGroups{$g} = $g;
819        }
820
821        unless ($purgeGroups) {
822            foreach my $g (@{$jq{groups}}) {
823                $allGroups{$g} = $g;
824            }
825        }
826
827        foreach my $g (keys %allGroups) {
828            $item->add_child('group')->add_cdata($g);
829        }
830
831        $item->put_attrib(jid => $to);
832        $item->put_attrib(name => $name) if $name;
833        $conn->getConnectionFromJidStr($jid)->Send($iq);
834        my $msg = "$baseJid: "
835          . ($name ? "$name ($to)" : "($to)")
836          . " is on your roster in the following groups: { "
837          . join(" , ", keys %allGroups)
838          . " }";
839        queue_admin_msg($msg);
840    }
841}
842
843sub jroster_remove {
844    my $jid = shift;
845    my $name = shift;
846    my @groups = @{ shift() };
847    my $purgeGroups = shift;
848    my $baseJid = baseJID($jid);
849
850    my $iq = new Net::XMPP::IQ;
851    $iq->SetType('set');
852    my $item = new XML::Stream::Node('item');
853    $iq->NewChild('jabber:iq:roster')->AddChild($item);
854    $item->put_attrib(subscription=> 'remove');
855    foreach my $to (@ARGV) {
856        $item->put_attrib(jid => $to);
857        $conn->getConnectionFromJidStr($jid)->Send($iq);
858        queue_admin_msg("You ($baseJid) have removed ($to) from your roster.");
859    }
860}
861
862sub jroster_auth {
863    my $jid = shift;
864    my $name = shift;
865    my @groups = @{ shift() };
866    my $purgeGroups = shift;
867    my $baseJid = baseJID($jid);
868
869    my $p = new Net::XMPP::Presence;
870    $p->SetType('subscribed');
871    foreach my $to (@ARGV) {
872        $p->SetTo($to);
873        $conn->getConnectionFromJidStr($jid)->Send($p);
874        queue_admin_msg("($to) has been subscribed to your ($baseJid) presence.");
875    }
876}
877
878sub jroster_deauth {
879    my $jid = shift;
880    my $name = shift;
881    my @groups = @{ shift() };
882    my $purgeGroups = shift;
883    my $baseJid = baseJID($jid);
884
885    my $p = new Net::XMPP::Presence;
886    $p->SetType('unsubscribed');
887    foreach my $to (@ARGV) {
888        $p->SetTo($to);
889        $conn->getConnectionFromJidStr($jid)->Send($p);
890        queue_admin_msg("($to) has been unsubscribed from your ($baseJid) presence.");
891    }
892}
893
894################################################################################
895### Owl Callbacks
896sub process_owl_jwrite {
897    my $body = shift;
898
899    my $j = new Net::XMPP::Message;
900    $body =~ s/\n\z//;
901    $j->SetMessage(
902        to   => $vars{jwrite}{to},
903        from => $vars{jwrite}{from},
904        type => $vars{jwrite}{type},
905        body => $body
906    );
907
908    $j->SetThread( $vars{jwrite}{thread} )   if ( $vars{jwrite}{thread} );
909    $j->SetSubject( $vars{jwrite}{subject} ) if ( $vars{jwrite}{subject} );
910
911    my $m = j2o( $j, { direction => 'out' } );
912    if ( $vars{jwrite}{type} ne 'groupchat' && BarnOwl::getvar('displayoutgoing') eq 'on') {
913        BarnOwl::queue_message($m);
914    }
915
916    if ($vars{jwrite}{sid} && $conn->sidExists( $vars{jwrite}{sid} )) {
917        $conn->getConnectionFromSid($vars{jwrite}{sid})->Send($j);
918    }
919    else {
920        $conn->getConnectionFromJidStr($vars{jwrite}{from})->Send($j);
921    }
922
923    delete $vars{jwrite};
924    BarnOwl::message("");   # Kludge to make the ``type your message...'' message go away
925}
926
927### XMPP Callbacks
928
929sub process_incoming_chat_message {
930    my ( $sid, $j ) = @_;
931    BarnOwl::queue_message( j2o( $j, { direction => 'in',
932                                   sid => $sid } ) );
933}
934
935sub process_incoming_error_message {
936    my ( $sid, $j ) = @_;
937    my %jhash = j2hash( $j, { direction => 'in',
938                              sid => $sid } );
939    $jhash{type} = 'admin';
940    BarnOwl::queue_message( BarnOwl::Message->new(%jhash) );
941}
942
943sub process_incoming_groupchat_message {
944    my ( $sid, $j ) = @_;
945
946    # HACK IN PROGRESS (ignoring delayed messages)
947    return if ( $j->DefinedX('jabber:x:delay') && $j->GetX('jabber:x:delay') );
948    BarnOwl::queue_message( j2o( $j, { direction => 'in',
949                                   sid => $sid } ) );
950}
951
952sub process_incoming_headline_message {
953    my ( $sid, $j ) = @_;
954    BarnOwl::queue_message( j2o( $j, { direction => 'in',
955                                   sid => $sid } ) );
956}
957
958sub process_incoming_normal_message {
959    my ( $sid, $j ) = @_;
960    my %jhash = j2hash( $j, { direction => 'in',
961                              sid => $sid } );
962
963    # XXX TODO: handle things such as MUC invites here.
964
965    #    if ($j->HasX('http://jabber.org/protocol/muc#user'))
966    #    {
967    #   my $x = $j->GetX('http://jabber.org/protocol/muc#user');
968    #   if ($x->HasChild('invite'))
969    #   {
970    #       $props
971    #   }
972    #    }
973    #
974    BarnOwl::queue_message( BarnOwl::Message->new(%jhash) );
975}
976
977sub process_muc_presence {
978    my ( $sid, $p ) = @_;
979    return unless ( $p->HasX('http://jabber.org/protocol/muc#user') );
980}
981
982
983sub process_presence_available {
984    my ( $sid, $p ) = @_;
985    my $from = $p->GetFrom();
986    my $to = $p->GetTo();
987    my $type = $p->GetType();
988    my %props = (
989        to => $to,
990        from => $from,
991        recipient => $to,
992        sender => $from,
993        type => 'jabber',
994        jtype => $p->GetType(),
995        status => $p->GetStatus(),
996        show => $p->GetShow(),
997        xml => $p->GetXML(),
998        direction => 'in');
999
1000    if ($type eq '' || $type eq 'available') {
1001        $props{body} = "$from is now online. ";
1002        $props{loginout} = 'login';
1003    }
1004    else {
1005        $props{body} = "$from is now offline. ";
1006        $props{loginout} = 'logout';
1007    }
1008    $props{replysendercmd} = $props{replycmd} = "jwrite $from -i $sid";
1009    if(BarnOwl::getvar('debug') eq 'on') {
1010        BarnOwl::queue_message(BarnOwl::Message->new(%props));
1011    }
1012}
1013
1014sub process_presence_subscribe {
1015    my ( $sid, $p ) = @_;
1016    my $from = $p->GetFrom();
1017    my $to = $p->GetTo();
1018    my %props = (
1019        to => $to,
1020        from => $from,
1021        xml => $p->GetXML(),
1022        type => 'admin',
1023        adminheader => 'Jabber presence: subscribe',
1024        direction => 'in');
1025
1026    $props{body} = "Allow user ($from) to subscribe to your ($to) presence?\n" .
1027                   "(Answer with the `yes' or `no' commands)";
1028    $props{yescommand} = "jroster auth $from -a $to";
1029    $props{nocommand} = "jroster deauth $from -a $to";
1030    $props{question} = "true";
1031    BarnOwl::queue_message(BarnOwl::Message->new(%props));
1032}
1033
1034sub process_presence_unsubscribe {
1035    my ( $sid, $p ) = @_;
1036    my $from = $p->GetFrom();
1037    my $to = $p->GetTo();
1038    my %props = (
1039        to => $to,
1040        from => $from,
1041        xml => $p->GetXML(),
1042        type => 'admin',
1043        adminheader => 'Jabber presence: unsubscribe',
1044        direction => 'in');
1045
1046    $props{body} = "The user ($from) has been unsubscribed from your ($to) presence.\n";
1047    BarnOwl::queue_message(BarnOwl::Message->new(%props));
1048
1049    # Find a connection to reply with.
1050    foreach my $jid ($conn->getJids()) {
1051        my $cJid = new Net::XMPP::JID;
1052        $cJid->SetJID($jid);
1053        if ($to eq $cJid->GetJID('base') ||
1054            $to eq $cJid->GetJID('full')) {
1055            my $reply = $p->Reply(type=>"unsubscribed");
1056            $conn->getConnectionFromJidStr($jid)->Send($reply);
1057            return;
1058        }
1059    }
1060}
1061
1062sub process_presence_subscribed {
1063    my ( $sid, $p ) = @_;
1064    queue_admin_msg("ignoring:".$p->GetXML());
1065    # RFC 3921 says we should respond to this with a "subscribe"
1066    # but this causes a flood of sub/sub'd presence packets with
1067    # some servers, so we won't. We may want to detect this condition
1068    # later, and have per-server settings.
1069    return;
1070}
1071
1072sub process_presence_unsubscribed {
1073    my ( $sid, $p ) = @_;
1074    queue_admin_msg("ignoring:".$p->GetXML());
1075    # RFC 3921 says we should respond to this with a "subscribe"
1076    # but this causes a flood of unsub/unsub'd presence packets with
1077    # some servers, so we won't. We may want to detect this condition
1078    # later, and have per-server settings.
1079    return;
1080}
1081
1082sub process_presence_error {
1083    my ( $sid, $p ) = @_;
1084    my $code = $p->GetErrorCode();
1085    my $error = $p->GetError();
1086    BarnOwl::error("Jabber: $code $error");
1087}
1088
1089
1090### Helper functions
1091
1092sub j2hash {
1093    my $j   = shift;
1094    my %initProps = %{ shift() };
1095
1096    my $dir = 'none';
1097    my %props = ( type => 'jabber' );
1098
1099    foreach my $k (keys %initProps) {
1100        $dir = $initProps{$k} if ($k eq 'direction');
1101        $props{$k} = $initProps{$k};
1102    }
1103
1104    my $jtype = $props{jtype} = $j->GetType();
1105    my $from = $j->GetFrom('jid');
1106    my $to   = $j->GetTo('jid');
1107
1108    $props{from} = $from->GetJID('full');
1109    $props{to}   = $to->GetJID('full');
1110
1111    $props{recipient}  = $to->GetJID('base');
1112    $props{sender}     = $from->GetJID('base');
1113    $props{subject}    = $j->GetSubject() if ( $j->DefinedSubject() );
1114    $props{thread}     = $j->GetThread() if ( $j->DefinedThread() );
1115    $props{body}       = $j->GetBody() if ( $j->DefinedBody() );
1116    $props{error}      = $j->GetError() if ( $j->DefinedError() );
1117    $props{error_code} = $j->GetErrorCode() if ( $j->DefinedErrorCode() );
1118    $props{xml}        = $j->GetXML();
1119
1120    if ( $jtype eq 'chat' ) {
1121        $props{replycmd} =
1122          "jwrite " . ( ( $dir eq 'in' ) ? $props{from} : $props{to} );
1123        $props{replycmd} .=
1124          " -a " . ( ( $dir eq 'out' ) ? $props{from} : $props{to} );
1125        $props{private} = 1;
1126    }
1127    elsif ( $jtype eq 'groupchat' ) {
1128        my $nick = $props{nick} = $from->GetResource();
1129        my $room = $props{room} = $from->GetJID('base');
1130        $props{replycmd} = "jwrite -g $room";
1131        $props{replycmd} .=
1132          " -a " . ( ( $dir eq 'out' ) ? $props{from} : $props{to} );
1133
1134        $props{sender} = $nick || $room;
1135        $props{recipient} = $room;
1136
1137        if ( $props{subject} && !$props{body} ) {
1138            $props{body} =
1139              '[' . $nick . " has set the topic to: " . $props{subject} . "]";
1140        }
1141    }
1142    elsif ( $jtype eq 'normal' ) {
1143        $props{replycmd}  = undef;
1144        $props{private} = 1;
1145    }
1146    elsif ( $jtype eq 'headline' ) {
1147        $props{replycmd} = undef;
1148    }
1149    elsif ( $jtype eq 'error' ) {
1150        $props{replycmd} = undef;
1151        $props{body}     = "Error "
1152          . $props{error_code}
1153          . " sending to "
1154          . $props{from} . "\n"
1155          . $props{error};
1156    }
1157
1158    $props{replysendercmd} = $props{replycmd};
1159    return %props;
1160}
1161
1162sub j2o {
1163    return BarnOwl::Message->new( j2hash(@_) );
1164}
1165
1166sub queue_admin_msg {
1167    my $err = shift;
1168    my $m   = BarnOwl::Message->new(
1169        type      => 'admin',
1170        direction => 'none',
1171        body      => $err
1172    );
1173    BarnOwl::queue_message($m);
1174}
1175
1176sub boldify($) {
1177    my $str = shift;
1178
1179    return '@b(' . $str . ')' if ( $str !~ /\)/ );
1180    return '@b<' . $str . '>' if ( $str !~ /\>/ );
1181    return '@b{' . $str . '}' if ( $str !~ /\}/ );
1182    return '@b[' . $str . ']' if ( $str !~ /\]/ );
1183
1184    my $txt = "$str";
1185    $txt =~ s{[)]}{)\@b[)]\@b(}g;
1186    return '@b(' . $txt . ')';
1187}
1188
1189sub getServerFromJID {
1190    my $jid = shift;
1191    my $res = new Net::DNS::Resolver;
1192    my $packet =
1193      $res->search( '_xmpp-client._tcp.' . $jid->GetServer(), 'srv' );
1194
1195    if ($packet)    # Got srv record.
1196    {
1197        my @answer = $packet->answer;
1198        return $answer[0]{target}, $answer[0]{port};
1199    }
1200
1201    return $jid->GetServer(), 5222;
1202}
1203
1204sub defaultJID {
1205    return ( $conn->getJids() )[0] if ( $conn->connected() == 1 );
1206    return;
1207}
1208
1209sub baseJID {
1210    my $givenJidStr = shift;
1211    my $givenJid    = new Net::XMPP::JID;
1212    $givenJid->SetJID($givenJidStr);
1213    return $givenJid->GetJID('base');
1214}
1215
1216sub resolveJID {
1217    my $givenJidStr = shift;
1218    my $givenJid    = new Net::XMPP::JID;
1219    $givenJid->SetJID($givenJidStr);
1220
1221    # Account fully specified.
1222    if ( $givenJid->GetResource() ) {
1223        # Specified account exists
1224        return $givenJidStr if ($conn->jidExists($givenJidStr) );
1225        BarnOwl::error("Invalid account: $givenJidStr");
1226    }
1227
1228    # Disambiguate.
1229    else {
1230        my $matchingJid = "";
1231        my $errStr =
1232          "Ambiguous account reference. Please specify a resource.\n";
1233        my $ambiguous = 0;
1234
1235        foreach my $jid ( $conn->getJids() ) {
1236            my $cJid = new Net::XMPP::JID;
1237            $cJid->SetJID($jid);
1238            if ( $givenJidStr eq $cJid->GetJID('base') ) {
1239                $ambiguous = 1 if ( $matchingJid ne "" );
1240                $matchingJid = $jid;
1241                $errStr .= "\t$jid\n";
1242            }
1243        }
1244
1245        # Need further disambiguation.
1246        if ($ambiguous) {
1247            queue_admin_msg($errStr);
1248        }
1249
1250        # Not one of ours.
1251        elsif ( $matchingJid eq "" ) {
1252            BarnOwl::error("Invalid account: $givenJidStr");
1253        }
1254
1255        # It's this one.
1256        else {
1257            return $matchingJid;
1258        }
1259    }
1260    return "";
1261}
1262
1263#####################################################################
1264#####################################################################
1265
1266package BarnOwl::Message::Jabber;
1267
1268our @ISA = qw( BarnOwl::Message );
1269
1270sub jtype { shift->{jtype} };
1271sub from { shift->{from} };
1272sub to { shift->{to} };
1273sub room { shift->{room} };
1274
1275sub smartfilter {
1276    my $self = shift;
1277    my $inst = shift;
1278
1279    my ($filter, $ftext);
1280
1281    if($self->jtype eq 'chat') {
1282        my $user;
1283        if($self->direction eq 'in') {
1284            $user = $self->from;
1285        } else {
1286            $user = $self->to;
1287        }
1288        $user = Net::Jabber::JID->new($user)->GetJID($inst ? 'full' : 'base');
1289        $filter = "jabber-user-$user";
1290        $ftext = qq{type ^jabber\$ and ( ( direction ^in\$ and from ^$user ) } .
1291                 qq{or ( direction ^out\$ and to ^$user ) ) };
1292        BarnOwl::filter("$filter $ftext");
1293        return $filter;
1294    } elsif ($self->jtype eq 'groupchat') {
1295        my $room = $self->room;
1296        $filter = "jabber-room-$room";
1297        $ftext = qq{type ^jabber\$ and room ^$room\$};
1298        BarnOwl::filter("$filter $ftext");
1299        return $filter;
1300    }
1301}
1302
13031;
Note: See TracBrowser for help on using the repository browser.