source: perl/modules/jabber.pl @ 63bbef4

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