source: perl/modules/jabber.pl @ 99c7549

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