source: perl/modules/jabber.pl @ 30c735c

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