source: perl/modules/jabber.pl @ 989fae0

barnowl_perlaimdebianrelease-1.10release-1.4release-1.5release-1.6release-1.7release-1.8release-1.9
Last change on this file since 989fae0 was 989fae0, checked in by Nelson Elhage <nelhage@mit.edu>, 17 years ago
Improving JID guessing, adding a warning when we guess. Needs to be tweaked.
  • Property mode set to 100644
File size: 39.2 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 = '';
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_connhash} = {
425        hostname      => $server,
426        tls           => 1,
427        port          => $port,
428        componentname => $componentname
429    };
430    $vars{jlogin_authhash} =
431      { username => $uid,
432        resource => $resource,
433    };
434
435    return do_login($password);
436}
437
438sub do_login {
439    $vars{jlogin_password} = shift;
440    $vars{jlogin_authhash}->{password} = sub { return $vars{jlogin_password} || '' };
441    my $jidStr = $vars{jlogin_jid};
442    if ( !$jidStr && $vars{jlogin_havepass}) {
443        BarnOwl::error("Got password but have no jid!");
444    }
445    else
446    {
447        my $client = $conn->addConnection($jidStr);
448
449        #XXX Todo: Add more callbacks.
450        # * MUC presence handlers
451        # We use the anonymous subrefs in order to have the correct behavior
452        # when we reload
453        $client->SetMessageCallBacks(
454            chat      => sub { BarnOwl::Jabber::process_incoming_chat_message(@_) },
455            error     => sub { BarnOwl::Jabber::process_incoming_error_message(@_) },
456            groupchat => sub { BarnOwl::Jabber::process_incoming_groupchat_message(@_) },
457            headline  => sub { BarnOwl::Jabber::process_incoming_headline_message(@_) },
458            normal    => sub { BarnOwl::Jabber::process_incoming_normal_message(@_) }
459        );
460        $client->SetPresenceCallBacks(
461            available    => sub { BarnOwl::Jabber::process_presence_available(@_) },
462            unavailable  => sub { BarnOwl::Jabber::process_presence_available(@_) },
463            subscribe    => sub { BarnOwl::Jabber::process_presence_subscribe(@_) },
464            subscribed   => sub { BarnOwl::Jabber::process_presence_subscribed(@_) },
465            unsubscribe  => sub { BarnOwl::Jabber::process_presence_unsubscribe(@_) },
466            unsubscribed => sub { BarnOwl::Jabber::process_presence_unsubscribed(@_) },
467            error        => sub { BarnOwl::Jabber::process_presence_error(@_) });
468
469        my $status = $client->Connect( %{ $vars{jlogin_connhash} } );
470        if ( !$status ) {
471            $conn->removeConnection($jidStr);
472            BarnOwl::error("We failed to connect");
473        } else {
474            my @result = $client->AuthSend( %{ $vars{jlogin_authhash} } );
475
476            if ( !@result || $result[0] ne 'ok' ) {
477                if ( !$vars{jlogin_havepass} && ( !@result || $result[0] eq '401' ) ) {
478                    $vars{jlogin_havepass} = 1;
479                    $conn->removeConnection($jidStr);
480                    BarnOwl::start_password( "Password for $jidStr: ", \&do_login );
481                    return "";
482                }
483                $conn->removeConnection($jidStr);
484                BarnOwl::error( "Error in connect: " . join( " ", @result ) );
485            } else {
486                $conn->getRosterFromJID($jidStr)->fetch();
487                $client->PresenceSend( priority => 1 );
488                queue_admin_msg("Connected to jabber as $jidStr");
489            }
490        }
491
492    }
493    delete $vars{jlogin_jid};
494    $vars{jlogin_password} =~ tr/\0-\377/x/;
495    delete $vars{jlogin_password};
496    delete $vars{jlogin_havepass};
497    delete $vars{jlogin_connhash};
498    delete $vars{jlogin_authhash};
499    return "";
500}
501
502sub do_logout {
503    my $jid = shift;
504    my $disconnected = $conn->removeConnection($jid);
505    queue_admin_msg("Jabber disconnected ($jid).") if $disconnected;
506}
507
508sub cmd_logout {
509    # Logged into multiple accounts
510    if ( $conn->connected() > 1 ) {
511        # Logged into multiple accounts, no accout specified.
512        if ( !$_[1] ) {
513            my $errStr =
514              "You are logged into multiple accounts. Please specify an account to log out of.\n";
515            foreach my $jid ( $conn->getJIDs() ) {
516                $errStr .= "\t$jid\n";
517            }
518            queue_admin_msg($errStr);
519        }
520        # Logged into multiple accounts, account specified.
521        else {
522            if ( $_[1] eq '-a' )    #All accounts.
523            {
524                foreach my $jid ( $conn->getJIDs() ) {
525                    do_logout($jid);
526                }
527            }
528            else                    #One account.
529            {
530                my $jid = resolveConnectedJID( $_[1] );
531                do_logout($jid) if ( $jid ne '' );
532            }
533        }
534    }
535    else                            # Only one account logged in.
536    {
537        do_logout( ( $conn->getJIDs() )[0] );
538    }
539    return "";
540}
541
542sub cmd_jlist {
543    if ( !( scalar $conn->getJIDs() ) ) {
544        BarnOwl::error("You are not logged in to Jabber.");
545        return;
546    }
547    BarnOwl::popless_ztext( onGetBuddyList() );
548}
549
550sub cmd_jwrite {
551    if ( !$conn->connected() ) {
552        BarnOwl::error("You are not logged in to Jabber.");
553        return;
554    }
555
556    my $jwrite_to      = "";
557    my $jwrite_from    = "";
558    my $jwrite_sid     = "";
559    my $jwrite_thread  = "";
560    my $jwrite_subject = "";
561    my ($to, $from);
562    my $jwrite_type    = "chat";
563
564    my @args = @_;
565    shift;
566    local @ARGV = @_;
567    my $gc;
568    GetOptions(
569        'thread=s'  => \$jwrite_thread,
570        'subject=s' => \$jwrite_subject,
571        'account=s' => \$from,
572        'id=s'     =>  \$jwrite_sid,
573    );
574    $jwrite_type = 'groupchat' if $gc;
575
576    if ( scalar @ARGV != 1 ) {
577        BarnOwl::error(
578            "Usage: jwrite JID [-t thread] [-s 'subject'] [-a account]");
579        return;
580    }
581    else {
582        $to = shift @ARGV;
583    }
584
585    my @candidates = guess_jwrite($from, $to);
586   
587    unless(scalar @candidates) {
588        die("Unable to resolve JID $to");
589    }
590
591    @candidates = grep {defined $_->[0]} @candidates;
592
593    unless(scalar @candidates) {
594        if(!$from) {
595            die("You must specify an account with -a");
596        } else {
597            die("Unable to resolve account $from");
598        }
599    }
600
601
602    ($jwrite_from, $jwrite_to, $jwrite_type) = @{$candidates[0]};
603   
604    $vars{jwrite} = {
605        to      => $jwrite_to,
606        from    => $jwrite_from,
607        sid     => $jwrite_sid,
608        subject => $jwrite_subject,
609        thread  => $jwrite_thread,
610        type    => $jwrite_type
611    };
612
613    if(scalar @candidates > 1) {
614        BarnOwl::message(
615            "Warning: Guessing account and/or destination JID"
616           );
617    } else  {
618        BarnOwl::message(
619            "Type your message below.  End with a dot on a line by itself.  ^C will quit."
620           );
621    }
622   
623    my $cmd = "jwrite $jwrite_to -a $jwrite_from";
624    $cmd .= " -t $jwrite_thread" if $jwrite_thread;
625    $cmd .= " -t $jwrite_subject" if $jwrite_subject;
626    BarnOwl::start_edit_win( $cmd, \&process_owl_jwrite );
627}
628
629sub cmd_jmuc {
630    die "You are not logged in to Jabber" unless $conn->connected();
631    my $ocmd = shift;
632    my $cmd  = shift;
633    if ( !$cmd ) {
634
635        #XXX TODO: Write general usage for jmuc command.
636        return;
637    }
638
639    my %jmuc_commands = (
640        join      => \&jmuc_join,
641        part      => \&jmuc_part,
642        invite    => \&jmuc_invite,
643        configure => \&jmuc_configure,
644        presence  => \&jmuc_presence
645    );
646    my $func = $jmuc_commands{$cmd};
647    if ( !$func ) {
648        BarnOwl::error("jmuc: Unknown command: $cmd");
649        return;
650    }
651
652    {
653        local @ARGV = @_;
654        my $jid;
655        my $muc;
656        my $m = BarnOwl::getcurmsg();
657        if ( $m && $m->is_jabber && $m->{jtype} eq 'groupchat' ) {
658            $muc = $m->{room};
659            $jid = $m->{to};
660        }
661
662        my $getopt = Getopt::Long::Parser->new;
663        $getopt->configure('pass_through');
664        $getopt->getoptions( 'account=s' => \$jid );
665        $jid ||= defaultJID();
666        if ($jid) {
667            $jid = resolveConnectedJID($jid);
668            return unless $jid;
669        }
670        else {
671            BarnOwl::error('You must specify an account with -a {jid}');
672        }
673        return $func->( $jid, $muc, @ARGV );
674    }
675}
676
677sub jmuc_join {
678    my ( $jid, $muc, @args ) = @_;
679    local @ARGV = @args;
680    my $password;
681    GetOptions( 'password=s' => \$password );
682
683    $muc = shift @ARGV
684      or die("Usage: jmuc join MUC [-p password] [-a account]");
685
686    $conn->getConnectionFromJID($jid)->MUCJoin(JID      => $muc,
687                                                  Password => $password,
688                                                  History  => {
689                                                      MaxChars => 0
690                                                     });
691    return;
692}
693
694sub jmuc_part {
695    my ( $jid, $muc, @args ) = @_;
696
697    $muc = shift @args if scalar @args;
698    die("Usage: jmuc part MUC [-a account]") unless $muc;
699
700    $conn->getConnectionFromJID($jid)->MUCLeave(JID => $muc);
701    queue_admin_msg("$jid has left $muc.");
702}
703
704sub jmuc_invite {
705    my ( $jid, $muc, @args ) = @_;
706
707    my $invite_jid = shift @args;
708    $muc = shift @args if scalar @args;
709
710    die('Usage: jmuc invite JID [muc] [-a account]')
711      unless $muc && $invite_jid;
712
713    my $message = Net::Jabber::Message->new();
714    $message->SetTo($muc);
715    my $x = $message->NewChild('http://jabber.org/protocol/muc#user');
716    $x->AddInvite();
717    $x->GetInvite()->SetTo($invite_jid);
718    $conn->getConnectionFromJID($jid)->Send($message);
719    queue_admin_msg("$jid has invited $invite_jid to $muc.");
720}
721
722sub jmuc_configure {
723    my ( $jid, $muc, @args ) = @_;
724    $muc = shift @args if scalar @args;
725    die("Usage: jmuc configure [muc]") unless $muc;
726    my $iq = Net::Jabber::IQ->new();
727    $iq->SetTo($muc);
728    $iq->SetType('set');
729    my $query = $iq->NewQuery("http://jabber.org/protocol/muc#owner");
730    my $x     = $query->NewChild("jabber:x:data");
731    $x->SetType('submit');
732
733    $conn->getConnectionFromJID($jid)->Send($iq);
734    queue_admin_msg("Accepted default instant configuration for $muc");
735}
736
737sub jmuc_presence {
738    my ( $jid, $muc, @args ) = @_;
739
740    $muc = shift @args if scalar @args;
741    die("Usage: jmuc presence MUC") unless $muc;
742
743    my $m = $conn->getConnectionFromJID($jid)->FindMUC(jid => $muc);
744    die("No such muc: $muc") unless $m;
745
746    my @jids = $m->Presence();
747    BarnOwl::popless_ztext("JIDs present in " . $m->BaseJID . "\n\t" .
748                           join("\n\t", map {$_->GetResource}@jids) . "\n");
749}
750
751
752#XXX TODO: Consider merging this with jmuc and selecting off the first two args.
753sub cmd_jroster {
754    die "You are not logged in to Jabber" unless $conn->connected();
755    my $ocmd = shift;
756    my $cmd  = shift;
757    if ( !$cmd ) {
758
759        #XXX TODO: Write general usage for jroster command.
760        return;
761    }
762
763    my %jroster_commands = (
764        sub      => \&jroster_sub,
765        unsub    => \&jroster_unsub,
766        add      => \&jroster_add,
767        remove   => \&jroster_remove,
768        auth     => \&jroster_auth,
769        deauth   => \&jroster_deauth
770    );
771    my $func = $jroster_commands{$cmd};
772    if ( !$func ) {
773        BarnOwl::error("jroster: Unknown command: $cmd");
774        return;
775    }
776
777    {
778        local @ARGV = @_;
779        my $jid;
780        my $name;
781        my @groups;
782        my $purgeGroups;
783        my $getopt = Getopt::Long::Parser->new;
784        $getopt->configure('pass_through');
785        $getopt->getoptions(
786            'account=s' => \$jid,
787            'group=s' => \@groups,
788            'purgegroups' => \$purgeGroups,
789            'name=s' => \$name
790        );
791        $jid ||= defaultJID();
792        if ($jid) {
793            $jid = resolveConnectedJID($jid);
794            return unless $jid;
795        }
796        else {
797            BarnOwl::error('You must specify an account with -a {jid}');
798        }
799        return $func->( $jid, $name, \@groups, $purgeGroups,  @ARGV );
800    }
801}
802
803sub jroster_sub {
804    my $jid = shift;
805    my $name = shift;
806    my @groups = @{ shift() };
807    my $purgeGroups = shift;
808    my $baseJID = baseJID($jid);
809
810    my $roster = $conn->getRosterFromJID($jid);
811
812    # Adding lots of users with the same name is a bad idea.
813    $name = "" unless (1 == scalar(@ARGV));
814
815    my $p = new Net::XMPP::Presence;
816    $p->SetType('subscribe');
817
818    foreach my $to (@ARGV) {
819        jroster_add($jid, $name, \@groups, $purgeGroups, ($to)) unless ($roster->exists($to));
820
821        $p->SetTo($to);
822        $conn->getConnectionFromJID($jid)->Send($p);
823        queue_admin_msg("You ($baseJID) have requested a subscription to ($to)'s presence.");
824    }
825}
826
827sub jroster_unsub {
828    my $jid = shift;
829    my $name = shift;
830    my @groups = @{ shift() };
831    my $purgeGroups = shift;
832    my $baseJID = baseJID($jid);
833
834    my $p = new Net::XMPP::Presence;
835    $p->SetType('unsubscribe');
836    foreach my $to (@ARGV) {
837        $p->SetTo($to);
838        $conn->getConnectionFromJID($jid)->Send($p);
839        queue_admin_msg("You ($baseJID) have unsubscribed from ($to)'s presence.");
840    }
841}
842
843sub jroster_add {
844    my $jid = shift;
845    my $name = shift;
846    my @groups = @{ shift() };
847    my $purgeGroups = shift;
848    my $baseJID = baseJID($jid);
849
850    my $roster = $conn->getRosterFromJID($jid);
851
852    # Adding lots of users with the same name is a bad idea.
853    $name = "" unless (1 == scalar(@ARGV));
854
855    foreach my $to (@ARGV) {
856        my %jq  = $roster->query($to);
857        my $iq = new Net::XMPP::IQ;
858        $iq->SetType('set');
859        my $item = new XML::Stream::Node('item');
860        $iq->NewChild('jabber:iq:roster')->AddChild($item);
861
862        my %allGroups = ();
863
864        foreach my $g (@groups) {
865            $allGroups{$g} = $g;
866        }
867
868        unless ($purgeGroups) {
869            foreach my $g (@{$jq{groups}}) {
870                $allGroups{$g} = $g;
871            }
872        }
873
874        foreach my $g (keys %allGroups) {
875            $item->add_child('group')->add_cdata($g);
876        }
877
878        $item->put_attrib(jid => $to);
879        $item->put_attrib(name => $name) if $name;
880        $conn->getConnectionFromJID($jid)->Send($iq);
881        my $msg = "$baseJID: "
882          . ($name ? "$name ($to)" : "($to)")
883          . " is on your roster in the following groups: { "
884          . join(" , ", keys %allGroups)
885          . " }";
886        queue_admin_msg($msg);
887    }
888}
889
890sub jroster_remove {
891    my $jid = shift;
892    my $name = shift;
893    my @groups = @{ shift() };
894    my $purgeGroups = shift;
895    my $baseJID = baseJID($jid);
896
897    my $iq = new Net::XMPP::IQ;
898    $iq->SetType('set');
899    my $item = new XML::Stream::Node('item');
900    $iq->NewChild('jabber:iq:roster')->AddChild($item);
901    $item->put_attrib(subscription=> 'remove');
902    foreach my $to (@ARGV) {
903        $item->put_attrib(jid => $to);
904        $conn->getConnectionFromJID($jid)->Send($iq);
905        queue_admin_msg("You ($baseJID) have removed ($to) from your roster.");
906    }
907}
908
909sub jroster_auth {
910    my $jid = shift;
911    my $name = shift;
912    my @groups = @{ shift() };
913    my $purgeGroups = shift;
914    my $baseJID = baseJID($jid);
915
916    my $p = new Net::XMPP::Presence;
917    $p->SetType('subscribed');
918    foreach my $to (@ARGV) {
919        $p->SetTo($to);
920        $conn->getConnectionFromJID($jid)->Send($p);
921        queue_admin_msg("($to) has been subscribed to your ($baseJID) presence.");
922    }
923}
924
925sub jroster_deauth {
926    my $jid = shift;
927    my $name = shift;
928    my @groups = @{ shift() };
929    my $purgeGroups = shift;
930    my $baseJID = baseJID($jid);
931
932    my $p = new Net::XMPP::Presence;
933    $p->SetType('unsubscribed');
934    foreach my $to (@ARGV) {
935        $p->SetTo($to);
936        $conn->getConnectionFromJID($jid)->Send($p);
937        queue_admin_msg("($to) has been unsubscribed from your ($baseJID) presence.");
938    }
939}
940
941################################################################################
942### Owl Callbacks
943sub process_owl_jwrite {
944    my $body = shift;
945
946    my $j = new Net::XMPP::Message;
947    $body =~ s/\n\z//;
948    $j->SetMessage(
949        to   => $vars{jwrite}{to},
950        from => $vars{jwrite}{from},
951        type => $vars{jwrite}{type},
952        body => $body
953    );
954
955    $j->SetThread( $vars{jwrite}{thread} )   if ( $vars{jwrite}{thread} );
956    $j->SetSubject( $vars{jwrite}{subject} ) if ( $vars{jwrite}{subject} );
957
958    my $m = j2o( $j, { direction => 'out' } );
959    if ( $vars{jwrite}{type} ne 'groupchat' && BarnOwl::getvar('displayoutgoing') eq 'on') {
960        BarnOwl::queue_message($m);
961    }
962
963    $j->RemoveFrom(); # Kludge to get around gtalk's random bits after the resouce.
964    if ($vars{jwrite}{sid} && $conn->sidExists( $vars{jwrite}{sid} )) {
965        $conn->getConnectionFromSid($vars{jwrite}{sid})->Send($j);
966    }
967    else {
968        $conn->getConnectionFromJID($vars{jwrite}{from})->Send($j);
969    }
970
971    delete $vars{jwrite};
972    BarnOwl::message("");   # Kludge to make the ``type your message...'' message go away
973}
974
975### XMPP Callbacks
976
977sub process_incoming_chat_message {
978    my ( $sid, $j ) = @_;
979    BarnOwl::queue_message( j2o( $j, { direction => 'in',
980                                   sid => $sid } ) );
981}
982
983sub process_incoming_error_message {
984    my ( $sid, $j ) = @_;
985    my %jhash = j2hash( $j, { direction => 'in',
986                              sid => $sid } );
987    $jhash{type} = 'admin';
988    BarnOwl::queue_message( BarnOwl::Message->new(%jhash) );
989}
990
991sub process_incoming_groupchat_message {
992    my ( $sid, $j ) = @_;
993
994    # HACK IN PROGRESS (ignoring delayed messages)
995    return if ( $j->DefinedX('jabber:x:delay') && $j->GetX('jabber:x:delay') );
996    BarnOwl::queue_message( j2o( $j, { direction => 'in',
997                                   sid => $sid } ) );
998}
999
1000sub process_incoming_headline_message {
1001    my ( $sid, $j ) = @_;
1002    BarnOwl::queue_message( j2o( $j, { direction => 'in',
1003                                   sid => $sid } ) );
1004}
1005
1006sub process_incoming_normal_message {
1007    my ( $sid, $j ) = @_;
1008    my %jhash = j2hash( $j, { direction => 'in',
1009                              sid => $sid } );
1010
1011    # XXX TODO: handle things such as MUC invites here.
1012
1013    #    if ($j->HasX('http://jabber.org/protocol/muc#user'))
1014    #    {
1015    #   my $x = $j->GetX('http://jabber.org/protocol/muc#user');
1016    #   if ($x->HasChild('invite'))
1017    #   {
1018    #       $props
1019    #   }
1020    #    }
1021    #
1022    BarnOwl::queue_message( BarnOwl::Message->new(%jhash) );
1023}
1024
1025sub process_muc_presence {
1026    my ( $sid, $p ) = @_;
1027    return unless ( $p->HasX('http://jabber.org/protocol/muc#user') );
1028}
1029
1030
1031sub process_presence_available {
1032    my ( $sid, $p ) = @_;
1033    my $from = $p->GetFrom();
1034    my $to = $p->GetTo();
1035    my $type = $p->GetType();
1036    my %props = (
1037        to => $to,
1038        from => $from,
1039        recipient => $to,
1040        sender => $from,
1041        type => 'jabber',
1042        jtype => $p->GetType(),
1043        status => $p->GetStatus(),
1044        show => $p->GetShow(),
1045        xml => $p->GetXML(),
1046        direction => 'in');
1047
1048    if ($type eq '' || $type eq 'available') {
1049        $props{body} = "$from is now online. ";
1050        $props{loginout} = 'login';
1051    }
1052    else {
1053        $props{body} = "$from is now offline. ";
1054        $props{loginout} = 'logout';
1055    }
1056    $props{replysendercmd} = $props{replycmd} = "jwrite $from -i $sid";
1057    if(BarnOwl::getvar('debug') eq 'on') {
1058        BarnOwl::queue_message(BarnOwl::Message->new(%props));
1059    }
1060}
1061
1062sub process_presence_subscribe {
1063    my ( $sid, $p ) = @_;
1064    my $from = $p->GetFrom();
1065    my $to = $p->GetTo();
1066    my %props = (
1067        to => $to,
1068        from => $from,
1069        xml => $p->GetXML(),
1070        type => 'admin',
1071        adminheader => 'Jabber presence: subscribe',
1072        direction => 'in');
1073
1074    $props{body} = "Allow user ($from) to subscribe to your ($to) presence?\n" .
1075                   "(Answer with the `yes' or `no' commands)";
1076    $props{yescommand} = "jroster auth $from -a $to";
1077    $props{nocommand} = "jroster deauth $from -a $to";
1078    $props{question} = "true";
1079    BarnOwl::queue_message(BarnOwl::Message->new(%props));
1080}
1081
1082sub process_presence_unsubscribe {
1083    my ( $sid, $p ) = @_;
1084    my $from = $p->GetFrom();
1085    my $to = $p->GetTo();
1086    my %props = (
1087        to => $to,
1088        from => $from,
1089        xml => $p->GetXML(),
1090        type => 'admin',
1091        adminheader => 'Jabber presence: unsubscribe',
1092        direction => 'in');
1093
1094    $props{body} = "The user ($from) has been unsubscribed from your ($to) presence.\n";
1095    BarnOwl::queue_message(BarnOwl::Message->new(%props));
1096
1097    # Find a connection to reply with.
1098    foreach my $jid ($conn->getJIDs()) {
1099        my $cJID = new Net::XMPP::JID;
1100        $cJID->SetJID($jid);
1101        if ($to eq $cJID->GetJID('base') ||
1102            $to eq $cJID->GetJID('full')) {
1103            my $reply = $p->Reply(type=>"unsubscribed");
1104            $conn->getConnectionFromJID($jid)->Send($reply);
1105            return;
1106        }
1107    }
1108}
1109
1110sub process_presence_subscribed {
1111    my ( $sid, $p ) = @_;
1112    queue_admin_msg("ignoring:".$p->GetXML());
1113    # RFC 3921 says we should respond to this with a "subscribe"
1114    # but this causes a flood of sub/sub'd presence packets with
1115    # some servers, so we won't. We may want to detect this condition
1116    # later, and have per-server settings.
1117    return;
1118}
1119
1120sub process_presence_unsubscribed {
1121    my ( $sid, $p ) = @_;
1122    queue_admin_msg("ignoring:".$p->GetXML());
1123    # RFC 3921 says we should respond to this with a "subscribe"
1124    # but this causes a flood of unsub/unsub'd presence packets with
1125    # some servers, so we won't. We may want to detect this condition
1126    # later, and have per-server settings.
1127    return;
1128}
1129
1130sub process_presence_error {
1131    my ( $sid, $p ) = @_;
1132    my $code = $p->GetErrorCode();
1133    my $error = $p->GetError();
1134    BarnOwl::error("Jabber: $code $error");
1135}
1136
1137
1138### Helper functions
1139
1140sub j2hash {
1141    my $j   = shift;
1142    my %initProps = %{ shift() };
1143
1144    my $dir = 'none';
1145    my %props = ( type => 'jabber' );
1146
1147    foreach my $k (keys %initProps) {
1148        $dir = $initProps{$k} if ($k eq 'direction');
1149        $props{$k} = $initProps{$k};
1150    }
1151
1152    my $jtype = $props{jtype} = $j->GetType();
1153    my $from = $j->GetFrom('jid');
1154    my $to   = $j->GetTo('jid');
1155
1156    $props{from} = $from->GetJID('full');
1157    $props{to}   = $to->GetJID('full');
1158
1159    $props{recipient}  = $to->GetJID('base');
1160    $props{sender}     = $from->GetJID('base');
1161    $props{subject}    = $j->GetSubject() if ( $j->DefinedSubject() );
1162    $props{thread}     = $j->GetThread() if ( $j->DefinedThread() );
1163    $props{body}       = $j->GetBody() if ( $j->DefinedBody() );
1164    $props{error}      = $j->GetError() if ( $j->DefinedError() );
1165    $props{error_code} = $j->GetErrorCode() if ( $j->DefinedErrorCode() );
1166    $props{xml}        = $j->GetXML();
1167
1168    if ( $jtype eq 'chat' ) {
1169        $props{replycmd} =
1170          "jwrite " . ( ( $dir eq 'in' ) ? $props{from} : $props{to} );
1171        $props{replycmd} .=
1172          " -a " . ( ( $dir eq 'out' ) ? $props{from} : $props{to} );
1173        $props{private} = 1;
1174    }
1175    elsif ( $jtype eq 'groupchat' ) {
1176        my $nick = $props{nick} = $from->GetResource();
1177        my $room = $props{room} = $from->GetJID('base');
1178        $props{replycmd} = "jwrite $room";
1179        $props{replycmd} .=
1180          " -a " . ( ( $dir eq 'out' ) ? $props{from} : $props{to} );
1181
1182        $props{sender} = $nick || $room;
1183        $props{recipient} = $room;
1184
1185        if ( $props{subject} && !$props{body} ) {
1186            $props{body} =
1187              '[' . $nick . " has set the topic to: " . $props{subject} . "]";
1188        }
1189    }
1190    elsif ( $jtype eq 'normal' ) {
1191        $props{replycmd}  = undef;
1192        $props{private} = 1;
1193    }
1194    elsif ( $jtype eq 'headline' ) {
1195        $props{replycmd} = undef;
1196    }
1197    elsif ( $jtype eq 'error' ) {
1198        $props{replycmd} = undef;
1199        $props{body}     = "Error "
1200          . $props{error_code}
1201          . " sending to "
1202          . $props{from} . "\n"
1203          . $props{error};
1204    }
1205
1206    $props{replysendercmd} = $props{replycmd};
1207    return %props;
1208}
1209
1210sub j2o {
1211    return BarnOwl::Message->new( j2hash(@_) );
1212}
1213
1214sub queue_admin_msg {
1215    my $err = shift;
1216    my $m   = BarnOwl::Message->new(
1217        type      => 'admin',
1218        direction => 'none',
1219        body      => $err
1220    );
1221    BarnOwl::queue_message($m);
1222}
1223
1224sub boldify($) {
1225    my $str = shift;
1226
1227    return '@b(' . $str . ')' if ( $str !~ /\)/ );
1228    return '@b<' . $str . '>' if ( $str !~ /\>/ );
1229    return '@b{' . $str . '}' if ( $str !~ /\}/ );
1230    return '@b[' . $str . ']' if ( $str !~ /\]/ );
1231
1232    my $txt = "$str";
1233    $txt =~ s{[)]}{)\@b[)]\@b(}g;
1234    return '@b(' . $txt . ')';
1235}
1236
1237sub getServerFromJID {
1238    my $jid = shift;
1239    my $res = new Net::DNS::Resolver;
1240    my $packet =
1241      $res->search( '_xmpp-client._tcp.' . $jid->GetServer(), 'srv' );
1242
1243    if ($packet)    # Got srv record.
1244    {
1245        my @answer = $packet->answer;
1246        return $answer[0]{target}, $answer[0]{port};
1247    }
1248
1249    return $jid->GetServer(), 5222;
1250}
1251
1252sub defaultJID {
1253    return ( $conn->getJIDs() )[0] if ( $conn->connected() == 1 );
1254    return;
1255}
1256
1257sub baseJID {
1258    my $givenJIDStr = shift;
1259    my $givenJID    = new Net::XMPP::JID;
1260    $givenJID->SetJID($givenJIDStr);
1261    return $givenJID->GetJID('base');
1262}
1263
1264sub resolveConnectedJID {
1265    my $givenJIDStr = shift;
1266    my $givenJID    = new Net::XMPP::JID;
1267    $givenJID->SetJID($givenJIDStr);
1268
1269    # Account fully specified.
1270    if ( $givenJID->GetResource() ) {
1271        # Specified account exists
1272        return $givenJIDStr if ($conn->jidExists($givenJIDStr) );
1273        die("Invalid account: $givenJIDStr");
1274    }
1275
1276    # Disambiguate.
1277    else {
1278        my $matchingJID = "";
1279        my $errStr =
1280          "Ambiguous account reference. Please specify a resource.\n";
1281        my $ambiguous = 0;
1282
1283        foreach my $jid ( $conn->getJIDs() ) {
1284            my $cJID = new Net::XMPP::JID;
1285            $cJID->SetJID($jid);
1286            if ( $givenJIDStr eq $cJID->GetJID('base') ) {
1287                $ambiguous = 1 if ( $matchingJID ne "" );
1288                $matchingJID = $jid;
1289                $errStr .= "\t$jid\n";
1290            }
1291        }
1292
1293        # Need further disambiguation.
1294        if ($ambiguous) {
1295            die($errStr);
1296        }
1297
1298        # Not one of ours.
1299        elsif ( $matchingJID eq "" ) {
1300            die("Invalid account: $givenJIDStr");
1301        }
1302
1303        # It's this one.
1304        else {
1305            return $matchingJID;
1306        }
1307    }
1308    return "";
1309}
1310
1311sub resolveDestJID {
1312    my ($to, $from) = @_;
1313    my $jid = Net::Jabber::JID->new($to);
1314
1315    my $roster = $conn->getRosterFromJID($from);
1316    my @jids = $roster->jids('all');
1317    for my $j (@jids) {
1318        if(($roster->query($j, 'name') || $j->GetUserID()) eq $to) {
1319            return $j->GetJID('full');
1320        } elsif($j->GetJID('base') eq baseJID($to)) {
1321            return $j->GetJID('full');
1322        }
1323    }
1324
1325    return undef;
1326}
1327
1328sub resolveType {
1329    my $to = shift;
1330    my $from = shift;
1331    return unless $from;
1332    my @mucs = $conn->getConnectionFromJID($from)->MUCs;
1333    if(grep {$_->BaseJID eq $to } @mucs) {
1334        return 'groupchat';
1335    } else {
1336        return 'chat';
1337    }
1338}
1339
1340sub guess_jwrite {
1341    # Heuristically guess what jids a jwrite was meant to be going to/from
1342    my ($from, $to) = (@_);
1343    my ($from_jid, $to_jid);
1344    my @matches;
1345    if($from) {
1346        $from_jid = resolveConnectedJID($from);
1347        die("Unable to resolve account $from") unless $from_jid;
1348        $to_jid = resolveDestJID($to, $from_jid);
1349        push @matches, [$from_jid, $to_jid];
1350    } else {
1351        for my $f ($conn->getJIDs) {
1352            $to_jid = resolveDestJID($to, $f);
1353            if(defined($to_jid)) {
1354                push @matches, [$f, $to_jid];
1355            }
1356        }
1357        if($to =~ /@/) {
1358            push @matches, [$_, $to]
1359               for ($conn->getJIDs);
1360        }
1361    }
1362
1363    for my $m (@matches) {
1364        my $type = resolveType($m->[1], $m->[0]);
1365        push @$m, $type;
1366    }
1367   
1368    return @matches;
1369}
1370
1371#####################################################################
1372#####################################################################
1373
1374package BarnOwl::Message::Jabber;
1375
1376our @ISA = qw( BarnOwl::Message );
1377
1378sub jtype { shift->{jtype} };
1379sub from { shift->{from} };
1380sub to { shift->{to} };
1381sub room { shift->{room} };
1382
1383sub smartfilter {
1384    my $self = shift;
1385    my $inst = shift;
1386
1387    my ($filter, $ftext);
1388
1389    if($self->jtype eq 'chat') {
1390        my $user;
1391        if($self->direction eq 'in') {
1392            $user = $self->from;
1393        } else {
1394            $user = $self->to;
1395        }
1396        $user = Net::Jabber::JID->new($user)->GetJID($inst ? 'full' : 'base');
1397        $filter = "jabber-user-$user";
1398        $ftext = qq{type ^jabber\$ and ( ( direction ^in\$ and from ^$user ) } .
1399                 qq{or ( direction ^out\$ and to ^$user ) ) };
1400        BarnOwl::filter("$filter $ftext");
1401        return $filter;
1402    } elsif ($self->jtype eq 'groupchat') {
1403        my $room = $self->room;
1404        $filter = "jabber-room-$room";
1405        $ftext = qq{type ^jabber\$ and room ^$room\$};
1406        BarnOwl::filter("$filter $ftext");
1407        return $filter;
1408    }
1409}
1410
14111;
Note: See TracBrowser for help on using the repository browser.