source: perl/modules/jabber.pl @ ac1bbe2

barnowl_perlaimdebianrelease-1.10release-1.4release-1.5release-1.6release-1.7release-1.8release-1.9
Last change on this file since ac1bbe2 was ac1bbe2, checked in by Nelson Elhage <nelhage@mit.edu>, 17 years ago
Binding j to jwrite
  • Property mode set to 100644
File size: 42.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::XMPP::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        register_keys unless $BarnOwl::reload;
220        push @::onMainLoop,     sub { BarnOwl::Jabber::onMainLoop(@_) };
221        push @::onGetBuddyList, sub { BarnOwl::Jabber::onGetBuddyList(@_) };
222        $vars{show} = '';
223    } else {
224        # Our owl doesn't support queue_message. Unfortunately, this
225        # means it probably *also* doesn't support BarnOwl::error. So just
226        # give up silently.
227    }
228}
229
230push @::onStartSubs, sub { BarnOwl::Jabber::onStart(@_) };
231
232sub onMainLoop {
233    return if ( !$conn->connected() );
234
235    $vars{status_changed} = 0;
236    my $idletime = owl::getidletime();
237    if ($idletime >= 900 && $vars{show} eq 'away') {
238        $vars{show} = 'xa';
239        $vars{status} = 'Auto extended-away after 15 minutes idle.';
240        $vars{status_changed} = 1;
241    } elsif ($idletime >= 300 && $vars{show} eq '') {
242        $vars{show} = 'away';
243        $vars{status} = 'Auto away after 5 minutes idle.';
244        $vars{status_changed} = 1;
245    } elsif ($idletime == 0 && $vars{show} ne '') {
246        $vars{show} = '';
247        $vars{status} = '';
248        $vars{status_changed} = 1;
249    }
250
251    foreach my $jid ( $conn->getJIDs() ) {
252        my $client = $conn->getConnectionFromJID($jid);
253
254        unless($client) {
255            $conn->removeConnection($jid);
256            BarnOwl::error("Connection for $jid undefined -- error in reload?");
257        }
258
259        my $status = $client->Process(0);
260        if ( !defined($status) ) {
261            BarnOwl::error("Jabber account $jid disconnected!");
262            do_logout($jid);
263        }
264        if ($::shutdown) {
265            do_logout($jid);
266            return;
267        }
268        if ($vars{status_changed}) {
269            my $p = new Net::Jabber::Presence;
270            $p->SetShow($vars{show}) if $vars{show};
271            $p->SetStatus($vars{status}) if $vars{status};
272            $client->Send($p);
273        }
274    }
275}
276
277sub blist_listBuddy {
278    my $roster = shift;
279    my $buddy  = shift;
280    my $blistStr .= "    ";
281    my %jq  = $roster->query($buddy);
282    my $res = $roster->resource($buddy);
283
284    my $name = $jq{name} || $buddy->GetUserID();
285
286    $blistStr .= sprintf '%-15s %s', $name, $buddy->GetJID();
287
288    if ($res) {
289        my %rq = $roster->resourceQuery( $buddy, $res );
290        $blistStr .= " [" . ( $rq{show} ? $rq{show} : 'online' ) . "]";
291        $blistStr .= " " . $rq{status} if $rq{status};
292        $blistStr = boldify($blistStr);
293    }
294    else {
295        if ($jq{ask}) {
296            $blistStr .= " [pending]";
297        }
298        elsif ($jq{subscription} eq 'none' || $jq{subscription} eq 'from') {
299            $blistStr .= " [not subscribed]";
300        }
301        else {
302            $blistStr .= " [offline]";
303        }
304    }
305    return $blistStr . "\n";
306}
307
308sub getSingleBuddyList {
309    my $jid = shift;
310    $jid = resolveConnectedJID($jid);
311    return "" unless $jid;
312    my $blist = "";
313    my $roster = $conn->getRosterFromJID($jid);
314    if ($roster) {
315        $blist .= "\n" . boldify("Jabber Roster for $jid\n");
316
317        foreach my $group ( $roster->groups() ) {
318            $blist .= "  Group: $group\n";
319            my @buddies = $roster->jids( 'group', $group );
320            foreach my $buddy ( @buddies ) {
321                $blist .= blist_listBuddy( $roster, $buddy );
322            }
323        }
324
325        my @unsorted = $roster->jids('nogroup');
326        if (@unsorted) {
327            $blist .= "  [unsorted]\n";
328            foreach my $buddy (@unsorted) {
329                $blist .= blist_listBuddy( $roster, $buddy );
330            }
331        }
332    }
333    return $blist;
334}
335
336sub onGetBuddyList {
337    my $blist = "";
338    foreach my $jid ($conn->getJIDs()) {
339        $blist .= getSingleBuddyList($jid);
340    }
341    return $blist;
342}
343
344################################################################################
345### Owl Commands
346sub register_owl_commands() {
347    BarnOwl::new_command(
348        jabberlogin => \&cmd_login,
349        { summary => "Log into jabber", },
350        { usage   => "jabberlogin JID [PASSWORD]" }
351    );
352    BarnOwl::new_command(
353        jabberlogout => \&cmd_logout,
354        { summary => "Log out of jabber" }
355    );
356    BarnOwl::new_command(
357        jwrite => \&cmd_jwrite,
358        {
359            summary => "Send a Jabber Message",
360            usage   => "jwrite JID [-t thread] [-s subject]"
361        }
362    );
363    BarnOwl::new_command(
364        jlist => \&cmd_jlist,
365        {
366            summary => "Show your Jabber roster.",
367            usage   => "jlist"
368        }
369    );
370    BarnOwl::new_command(
371        jmuc => \&cmd_jmuc,
372        {
373            summary     => "Jabber MUC related commands.",
374            description => "jmuc sends jabber commands related to muc.\n\n"
375              . "The following commands are available\n\n"
376              . "join <muc>  Join a muc.\n\n"
377              . "part <muc>  Part a muc.\n"
378              . "            The muc is taken from the current message if not supplied.\n\n"
379              . "invite <jid> <muc>\n"
380              . "            Invite <jid> to <muc>.\n"
381              . "            The muc is taken from the current message if not supplied.\n\n"
382              . "configure <muc>\n"
383              . "            Configures a MUC.\n"
384              . "            Necessary to initalize a new MUC.\n"
385              . "            At present, only the default configuration is supported.\n"
386              . "            The muc is taken from the current message if not supplied.\n\n"
387              . "presence <muc>\n"
388              . "            Shows the roster for <muc>.\n"
389              . "            The muc is taken from the current message if not supplied.\n\n"
390              . "presence -a\n"
391              . "            Shows rosters for all MUCs you're participating in.\n\n",
392            usage => "jmuc COMMAND ARGS"
393        }
394    );
395    BarnOwl::new_command(
396        jroster => \&cmd_jroster,
397        {
398            summary     => "Jabber Roster related commands.",
399            description => "jroster sends jabber commands related to rosters.\n\n"
400              . "The following commands are available\n\n"
401              . "sub <jid>     Subscribe to <jid>'s presence. (implicit add)\n\n"
402              . "add <jid>     Adds <jid> to your roster.\n\n"
403              . "unsub <jid>   Unsubscribe from <jid>'s presence.\n\n"
404              . "remove <jid>  Removes <jid> to your roster. (implicit unsub)\n\n"
405              . "auth <jid>    Authorizes <jid> to subscribe to your presence.\n\n"
406              . "deauth <jid>  De-authorizes <jid>'s subscription to your presence.\n\n"
407              . "The following arguments are supported for all commands\n\n"
408              . "-a <jid>      Specify which account to make the roster changes on.\n"
409              . "              Required if you're signed into more than one account.\n\n"
410              . "The following arguments only work with the add and sub commands.\n\n"
411              . "-g <group>    Add <jid> to group <group>.\n"
412              . "              May be specified more than once, will not remove <jid> from any groups.\n\n"
413              . "-p            Purge. Removes <jid> from all groups.\n"
414              . "              May be combined with -g completely alter <jid>'s groups.\n\n"
415              . "-n <name>     Sets <name> as <jid>'s short name.\n\n"
416              . "Note: Unless -n is used, you can specify multiple <jid> arguments.\n",
417            usage       => "jroster COMMAND ARGS"
418        }
419    );
420}
421
422sub register_keybindings {
423    BarnOwl::bindkey("recv j command jwrite");
424}
425
426sub cmd_login {
427    my $cmd = shift;
428    my $jid = new Net::Jabber::JID;
429    $jid->SetJID(shift);
430    my $password = '';
431    $password = shift if @_;
432
433    my $uid           = $jid->GetUserID();
434    my $componentname = $jid->GetServer();
435    my $resource      = $jid->GetResource() || 'owl';
436    $jid->SetResource($resource);
437    my $jidStr = $jid->GetJID('full');
438
439    if ( !$uid || !$componentname ) {
440        BarnOwl::error("usage: $cmd JID");
441        return;
442    }
443
444    if ( $conn->jidExists($jidStr) ) {
445        BarnOwl::error("Already logged in as $jidStr.");
446        return;
447    }
448
449    my ( $server, $port ) = getServerFromJID($jid);
450
451    $vars{jlogin_jid} = $jidStr;
452    $vars{jlogin_connhash} = {
453        hostname      => $server,
454        tls           => 1,
455        port          => $port,
456        componentname => $componentname
457    };
458    $vars{jlogin_authhash} =
459      { username => $uid,
460        resource => $resource,
461    };
462
463    return do_login($password);
464}
465
466sub do_login {
467    $vars{jlogin_password} = shift;
468    $vars{jlogin_authhash}->{password} = sub { return $vars{jlogin_password} || '' };
469    my $jidStr = $vars{jlogin_jid};
470    if ( !$jidStr && $vars{jlogin_havepass}) {
471        BarnOwl::error("Got password but have no jid!");
472    }
473    else
474    {
475        my $client = $conn->addConnection($jidStr);
476
477        #XXX Todo: Add more callbacks.
478        # * MUC presence handlers
479        # We use the anonymous subrefs in order to have the correct behavior
480        # when we reload
481        $client->SetMessageCallBacks(
482            chat      => sub { BarnOwl::Jabber::process_incoming_chat_message(@_) },
483            error     => sub { BarnOwl::Jabber::process_incoming_error_message(@_) },
484            groupchat => sub { BarnOwl::Jabber::process_incoming_groupchat_message(@_) },
485            headline  => sub { BarnOwl::Jabber::process_incoming_headline_message(@_) },
486            normal    => sub { BarnOwl::Jabber::process_incoming_normal_message(@_) }
487        );
488        $client->SetPresenceCallBacks(
489            available    => sub { BarnOwl::Jabber::process_presence_available(@_) },
490            unavailable  => sub { BarnOwl::Jabber::process_presence_available(@_) },
491            subscribe    => sub { BarnOwl::Jabber::process_presence_subscribe(@_) },
492            subscribed   => sub { BarnOwl::Jabber::process_presence_subscribed(@_) },
493            unsubscribe  => sub { BarnOwl::Jabber::process_presence_unsubscribe(@_) },
494            unsubscribed => sub { BarnOwl::Jabber::process_presence_unsubscribed(@_) },
495            error        => sub { BarnOwl::Jabber::process_presence_error(@_) });
496
497        my $status = $client->Connect( %{ $vars{jlogin_connhash} } );
498        if ( !$status ) {
499            $conn->removeConnection($jidStr);
500            BarnOwl::error("We failed to connect");
501        } else {
502            my @result = $client->AuthSend( %{ $vars{jlogin_authhash} } );
503
504            if ( !@result || $result[0] ne 'ok' ) {
505                if ( !$vars{jlogin_havepass} && ( !@result || $result[0] eq '401' ) ) {
506                    $vars{jlogin_havepass} = 1;
507                    $conn->removeConnection($jidStr);
508                    BarnOwl::start_password( "Password for $jidStr: ", \&do_login );
509                    return "";
510                }
511                $conn->removeConnection($jidStr);
512                BarnOwl::error( "Error in connect: " . join( " ", @result ) );
513            } else {
514                $conn->getRosterFromJID($jidStr)->fetch();
515                $client->PresenceSend( priority => 1 );
516                queue_admin_msg("Connected to jabber as $jidStr");
517            }
518        }
519
520    }
521    delete $vars{jlogin_jid};
522    $vars{jlogin_password} =~ tr/\0-\377/x/ if $vars{jlogin_password};
523    delete $vars{jlogin_password};
524    delete $vars{jlogin_havepass};
525    delete $vars{jlogin_connhash};
526    delete $vars{jlogin_authhash};
527    return "";
528}
529
530sub do_logout {
531    my $jid = shift;
532    my $disconnected = $conn->removeConnection($jid);
533    queue_admin_msg("Jabber disconnected ($jid).") if $disconnected;
534}
535
536sub cmd_logout {
537    # Logged into multiple accounts
538    if ( $conn->connected() > 1 ) {
539        # Logged into multiple accounts, no accout specified.
540        if ( !$_[1] ) {
541            my $errStr =
542              "You are logged into multiple accounts. Please specify an account to log out of.\n";
543            foreach my $jid ( $conn->getJIDs() ) {
544                $errStr .= "\t$jid\n";
545            }
546            queue_admin_msg($errStr);
547        }
548        # Logged into multiple accounts, account specified.
549        else {
550            if ( $_[1] eq '-a' )    #All accounts.
551            {
552                foreach my $jid ( $conn->getJIDs() ) {
553                    do_logout($jid);
554                }
555            }
556            else                    #One account.
557            {
558                my $jid = resolveConnectedJID( $_[1] );
559                do_logout($jid) if ( $jid ne '' );
560            }
561        }
562    }
563    else                            # Only one account logged in.
564    {
565        do_logout( ( $conn->getJIDs() )[0] );
566    }
567    return "";
568}
569
570sub cmd_jlist {
571    if ( !( scalar $conn->getJIDs() ) ) {
572        BarnOwl::error("You are not logged in to Jabber.");
573        return;
574    }
575    BarnOwl::popless_ztext( onGetBuddyList() );
576}
577
578sub cmd_jwrite {
579    if ( !$conn->connected() ) {
580        BarnOwl::error("You are not logged in to Jabber.");
581        return;
582    }
583
584    my $jwrite_to      = "";
585    my $jwrite_from    = "";
586    my $jwrite_sid     = "";
587    my $jwrite_thread  = "";
588    my $jwrite_subject = "";
589    my ($to, $from);
590    my $jwrite_type    = "chat";
591
592    my @args = @_;
593    shift;
594    local @ARGV = @_;
595    my $gc;
596    GetOptions(
597        'thread=s'  => \$jwrite_thread,
598        'subject=s' => \$jwrite_subject,
599        'account=s' => \$from,
600        'id=s'     =>  \$jwrite_sid,
601    );
602    $jwrite_type = 'groupchat' if $gc;
603
604    if ( scalar @ARGV != 1 ) {
605        BarnOwl::error(
606            "Usage: jwrite JID [-t thread] [-s 'subject'] [-a account]");
607        return;
608    }
609    else {
610        $to = shift @ARGV;
611    }
612
613    my @candidates = guess_jwrite($from, $to);
614
615    unless(scalar @candidates) {
616        die("Unable to resolve JID $to");
617    }
618
619    @candidates = grep {defined $_->[0]} @candidates;
620
621    unless(scalar @candidates) {
622        if(!$from) {
623            die("You must specify an account with -a");
624        } else {
625            die("Unable to resolve account $from");
626        }
627    }
628
629
630    ($jwrite_from, $jwrite_to, $jwrite_type) = @{$candidates[0]};
631
632    $vars{jwrite} = {
633        to      => $jwrite_to,
634        from    => $jwrite_from,
635        sid     => $jwrite_sid,
636        subject => $jwrite_subject,
637        thread  => $jwrite_thread,
638        type    => $jwrite_type
639    };
640
641    if(scalar @candidates > 1) {
642        BarnOwl::message(
643            "Warning: Guessing account and/or destination JID"
644           );
645    } else  {
646        BarnOwl::message(
647            "Type your message below.  End with a dot on a line by itself.  ^C will quit."
648           );
649    }
650
651    my $cmd = "jwrite $jwrite_to -a $jwrite_from";
652    $cmd .= " -t $jwrite_thread" if $jwrite_thread;
653    $cmd .= " -t $jwrite_subject" if $jwrite_subject;
654    BarnOwl::start_edit_win( $cmd, \&process_owl_jwrite );
655}
656
657sub cmd_jmuc {
658    die "You are not logged in to Jabber" unless $conn->connected();
659    my $ocmd = shift;
660    my $cmd  = shift;
661    if ( !$cmd ) {
662
663        #XXX TODO: Write general usage for jmuc command.
664        return;
665    }
666
667    my %jmuc_commands = (
668        join      => \&jmuc_join,
669        part      => \&jmuc_part,
670        invite    => \&jmuc_invite,
671        configure => \&jmuc_configure,
672        presence  => \&jmuc_presence
673    );
674    my $func = $jmuc_commands{$cmd};
675    if ( !$func ) {
676        BarnOwl::error("jmuc: Unknown command: $cmd");
677        return;
678    }
679
680    {
681        local @ARGV = @_;
682        my $jid;
683        my $muc;
684        my $m = BarnOwl::getcurmsg();
685        if ( $m && $m->is_jabber && $m->{jtype} eq 'groupchat' ) {
686            $muc = $m->{room};
687            $jid = $m->{to};
688        }
689
690        my $getopt = Getopt::Long::Parser->new;
691        $getopt->configure('pass_through');
692        $getopt->getoptions( 'account=s' => \$jid );
693        $jid ||= defaultJID();
694        if ($jid) {
695            $jid = resolveConnectedJID($jid);
696            return unless $jid;
697        }
698        else {
699            BarnOwl::error('You must specify an account with -a {jid}');
700        }
701        return $func->( $jid, $muc, @ARGV );
702    }
703}
704
705sub jmuc_join {
706    my ( $jid, $muc, @args ) = @_;
707    local @ARGV = @args;
708    my $password;
709    GetOptions( 'password=s' => \$password );
710
711    $muc = shift @ARGV
712      or die("Usage: jmuc join MUC [-p password] [-a account]");
713
714    $conn->getConnectionFromJID($jid)->MUCJoin(JID      => $muc,
715                                                  Password => $password,
716                                                  History  => {
717                                                      MaxChars => 0
718                                                     });
719    return;
720}
721
722sub jmuc_part {
723    my ( $jid, $muc, @args ) = @_;
724
725    $muc = shift @args if scalar @args;
726    die("Usage: jmuc part MUC [-a account]") unless $muc;
727
728    $conn->getConnectionFromJID($jid)->MUCLeave(JID => $muc);
729    queue_admin_msg("$jid has left $muc.");
730}
731
732sub jmuc_invite {
733    my ( $jid, $muc, @args ) = @_;
734
735    my $invite_jid = shift @args;
736    $muc = shift @args if scalar @args;
737
738    die('Usage: jmuc invite JID [muc] [-a account]')
739      unless $muc && $invite_jid;
740
741    my $message = Net::Jabber::Message->new();
742    $message->SetTo($muc);
743    my $x = $message->NewChild('http://jabber.org/protocol/muc#user');
744    $x->AddInvite();
745    $x->GetInvite()->SetTo($invite_jid);
746    $conn->getConnectionFromJID($jid)->Send($message);
747    queue_admin_msg("$jid has invited $invite_jid to $muc.");
748}
749
750sub jmuc_configure {
751    my ( $jid, $muc, @args ) = @_;
752    $muc = shift @args if scalar @args;
753    die("Usage: jmuc configure [muc]") unless $muc;
754    my $iq = Net::Jabber::IQ->new();
755    $iq->SetTo($muc);
756    $iq->SetType('set');
757    my $query = $iq->NewQuery("http://jabber.org/protocol/muc#owner");
758    my $x     = $query->NewChild("jabber:x:data");
759    $x->SetType('submit');
760
761    $conn->getConnectionFromJID($jid)->Send($iq);
762    queue_admin_msg("Accepted default instant configuration for $muc");
763}
764
765sub jmuc_presence_single {
766    my $m = shift;
767    my @jids = $m->Presence();
768    return "JIDs present in " . $m->BaseJID . "\n\t"
769      . join("\n\t", map {$_->GetResource}@jids) . "\n";
770}
771
772sub jmuc_presence {
773    my ( $jid, $muc, @args ) = @_;
774
775    $muc = shift @args if scalar @args;
776    die("Usage: jmuc presence MUC") unless $muc;
777
778    if ($muc eq '-a') {
779        my $str = "";
780        foreach my $jid ($conn->getJIDs()) {
781            $str .= boldify("Conferences for $jid:\n");
782            my $connection = $conn->getConnectionFromJID($jid);
783            foreach my $muc ($connection->MUCs) {
784                $str .= jmuc_presence_single($muc)."\n";
785            }
786        }
787        BarnOwl::popless_ztext($str);
788    }
789    else {
790        my $m = $conn->getConnectionFromJID($jid)->FindMUC(jid => $muc);
791        die("No such muc: $muc") unless $m;
792        BarnOwl::popless_ztext(jmuc_presence_single($m));
793    }
794}
795
796
797#XXX TODO: Consider merging this with jmuc and selecting off the first two args.
798sub cmd_jroster {
799    die "You are not logged in to Jabber" unless $conn->connected();
800    my $ocmd = shift;
801    my $cmd  = shift;
802    if ( !$cmd ) {
803
804        #XXX TODO: Write general usage for jroster command.
805        return;
806    }
807
808    my %jroster_commands = (
809        sub      => \&jroster_sub,
810        unsub    => \&jroster_unsub,
811        add      => \&jroster_add,
812        remove   => \&jroster_remove,
813        auth     => \&jroster_auth,
814        deauth   => \&jroster_deauth
815    );
816    my $func = $jroster_commands{$cmd};
817    if ( !$func ) {
818        BarnOwl::error("jroster: Unknown command: $cmd");
819        return;
820    }
821
822    {
823        local @ARGV = @_;
824        my $jid;
825        my $name;
826        my @groups;
827        my $purgeGroups;
828        my $getopt = Getopt::Long::Parser->new;
829        $getopt->configure('pass_through');
830        $getopt->getoptions(
831            'account=s' => \$jid,
832            'group=s' => \@groups,
833            'purgegroups' => \$purgeGroups,
834            'name=s' => \$name
835        );
836        $jid ||= defaultJID();
837        if ($jid) {
838            $jid = resolveConnectedJID($jid);
839            return unless $jid;
840        }
841        else {
842            BarnOwl::error('You must specify an account with -a {jid}');
843        }
844        return $func->( $jid, $name, \@groups, $purgeGroups,  @ARGV );
845    }
846}
847
848sub jroster_sub {
849    my $jid = shift;
850    my $name = shift;
851    my @groups = @{ shift() };
852    my $purgeGroups = shift;
853    my $baseJID = baseJID($jid);
854
855    my $roster = $conn->getRosterFromJID($jid);
856
857    # Adding lots of users with the same name is a bad idea.
858    $name = "" unless (1 == scalar(@ARGV));
859
860    my $p = new Net::Jabber::Presence;
861    $p->SetType('subscribe');
862
863    foreach my $to (@ARGV) {
864        jroster_add($jid, $name, \@groups, $purgeGroups, ($to)) unless ($roster->exists($to));
865
866        $p->SetTo($to);
867        $conn->getConnectionFromJID($jid)->Send($p);
868        queue_admin_msg("You ($baseJID) have requested a subscription to ($to)'s presence.");
869    }
870}
871
872sub jroster_unsub {
873    my $jid = shift;
874    my $name = shift;
875    my @groups = @{ shift() };
876    my $purgeGroups = shift;
877    my $baseJID = baseJID($jid);
878
879    my $p = new Net::Jabber::Presence;
880    $p->SetType('unsubscribe');
881    foreach my $to (@ARGV) {
882        $p->SetTo($to);
883        $conn->getConnectionFromJID($jid)->Send($p);
884        queue_admin_msg("You ($baseJID) have unsubscribed from ($to)'s presence.");
885    }
886}
887
888sub jroster_add {
889    my $jid = shift;
890    my $name = shift;
891    my @groups = @{ shift() };
892    my $purgeGroups = shift;
893    my $baseJID = baseJID($jid);
894
895    my $roster = $conn->getRosterFromJID($jid);
896
897    # Adding lots of users with the same name is a bad idea.
898    $name = "" unless (1 == scalar(@ARGV));
899
900    foreach my $to (@ARGV) {
901        my %jq  = $roster->query($to);
902        my $iq = new Net::Jabber::IQ;
903        $iq->SetType('set');
904        my $item = new XML::Stream::Node('item');
905        $iq->NewChild('jabber:iq:roster')->AddChild($item);
906
907        my %allGroups = ();
908
909        foreach my $g (@groups) {
910            $allGroups{$g} = $g;
911        }
912
913        unless ($purgeGroups) {
914            foreach my $g (@{$jq{groups}}) {
915                $allGroups{$g} = $g;
916            }
917        }
918
919        foreach my $g (keys %allGroups) {
920            $item->add_child('group')->add_cdata($g);
921        }
922
923        $item->put_attrib(jid => $to);
924        $item->put_attrib(name => $name) if $name;
925        $conn->getConnectionFromJID($jid)->Send($iq);
926        my $msg = "$baseJID: "
927          . ($name ? "$name ($to)" : "($to)")
928          . " is on your roster in the following groups: { "
929          . join(" , ", keys %allGroups)
930          . " }";
931        queue_admin_msg($msg);
932    }
933}
934
935sub jroster_remove {
936    my $jid = shift;
937    my $name = shift;
938    my @groups = @{ shift() };
939    my $purgeGroups = shift;
940    my $baseJID = baseJID($jid);
941
942    my $iq = new Net::Jabber::IQ;
943    $iq->SetType('set');
944    my $item = new XML::Stream::Node('item');
945    $iq->NewChild('jabber:iq:roster')->AddChild($item);
946    $item->put_attrib(subscription=> 'remove');
947    foreach my $to (@ARGV) {
948        $item->put_attrib(jid => $to);
949        $conn->getConnectionFromJID($jid)->Send($iq);
950        queue_admin_msg("You ($baseJID) have removed ($to) from your roster.");
951    }
952}
953
954sub jroster_auth {
955    my $jid = shift;
956    my $name = shift;
957    my @groups = @{ shift() };
958    my $purgeGroups = shift;
959    my $baseJID = baseJID($jid);
960
961    my $p = new Net::Jabber::Presence;
962    $p->SetType('subscribed');
963    foreach my $to (@ARGV) {
964        $p->SetTo($to);
965        $conn->getConnectionFromJID($jid)->Send($p);
966        queue_admin_msg("($to) has been subscribed to your ($baseJID) presence.");
967    }
968}
969
970sub jroster_deauth {
971    my $jid = shift;
972    my $name = shift;
973    my @groups = @{ shift() };
974    my $purgeGroups = shift;
975    my $baseJID = baseJID($jid);
976
977    my $p = new Net::Jabber::Presence;
978    $p->SetType('unsubscribed');
979    foreach my $to (@ARGV) {
980        $p->SetTo($to);
981        $conn->getConnectionFromJID($jid)->Send($p);
982        queue_admin_msg("($to) has been unsubscribed from your ($baseJID) presence.");
983    }
984}
985
986################################################################################
987### Owl Callbacks
988sub process_owl_jwrite {
989    my $body = shift;
990
991    my $j = new Net::Jabber::Message;
992    $body =~ s/\n\z//;
993    $j->SetMessage(
994        to   => $vars{jwrite}{to},
995        from => $vars{jwrite}{from},
996        type => $vars{jwrite}{type},
997        body => $body
998    );
999
1000    $j->SetThread( $vars{jwrite}{thread} )   if ( $vars{jwrite}{thread} );
1001    $j->SetSubject( $vars{jwrite}{subject} ) if ( $vars{jwrite}{subject} );
1002
1003    my $m = j2o( $j, { direction => 'out' } );
1004    if ( $vars{jwrite}{type} ne 'groupchat' && BarnOwl::getvar('displayoutgoing') eq 'on') {
1005        BarnOwl::queue_message($m);
1006    }
1007
1008    $j->RemoveFrom(); # Kludge to get around gtalk's random bits after the resource.
1009    if ($vars{jwrite}{sid} && $conn->sidExists( $vars{jwrite}{sid} )) {
1010        $conn->getConnectionFromSid($vars{jwrite}{sid})->Send($j);
1011    }
1012    else {
1013        $conn->getConnectionFromJID($vars{jwrite}{from})->Send($j);
1014    }
1015
1016    delete $vars{jwrite};
1017    BarnOwl::message("");   # Kludge to make the ``type your message...'' message go away
1018}
1019
1020### XMPP Callbacks
1021
1022sub process_incoming_chat_message {
1023    my ( $sid, $j ) = @_;
1024    BarnOwl::queue_message( j2o( $j, { direction => 'in',
1025                                   sid => $sid } ) );
1026}
1027
1028sub process_incoming_error_message {
1029    my ( $sid, $j ) = @_;
1030    my %jhash = j2hash( $j, { direction => 'in',
1031                              sid => $sid } );
1032    $jhash{type} = 'admin';
1033    BarnOwl::queue_message( BarnOwl::Message->new(%jhash) );
1034}
1035
1036sub process_incoming_groupchat_message {
1037    my ( $sid, $j ) = @_;
1038
1039    # HACK IN PROGRESS (ignoring delayed messages)
1040    return if ( $j->DefinedX('jabber:x:delay') && $j->GetX('jabber:x:delay') );
1041    BarnOwl::queue_message( j2o( $j, { direction => 'in',
1042                                   sid => $sid } ) );
1043}
1044
1045sub process_incoming_headline_message {
1046    my ( $sid, $j ) = @_;
1047    BarnOwl::queue_message( j2o( $j, { direction => 'in',
1048                                   sid => $sid } ) );
1049}
1050
1051sub process_incoming_normal_message {
1052    my ( $sid, $j ) = @_;
1053    my %jhash = j2hash( $j, { direction => 'in',
1054                              sid => $sid } );
1055
1056    # XXX TODO: handle things such as MUC invites here.
1057
1058    #    if ($j->HasX('http://jabber.org/protocol/muc#user'))
1059    #    {
1060    #   my $x = $j->GetX('http://jabber.org/protocol/muc#user');
1061    #   if ($x->HasChild('invite'))
1062    #   {
1063    #       $props
1064    #   }
1065    #    }
1066    #
1067    BarnOwl::queue_message( BarnOwl::Message->new(%jhash) );
1068}
1069
1070sub process_muc_presence {
1071    my ( $sid, $p ) = @_;
1072    return unless ( $p->HasX('http://jabber.org/protocol/muc#user') );
1073}
1074
1075
1076sub process_presence_available {
1077    my ( $sid, $p ) = @_;
1078    my $from = $p->GetFrom();
1079    my $to = $p->GetTo();
1080    my $type = $p->GetType();
1081    my %props = (
1082        to => $to,
1083        from => $from,
1084        recipient => $to,
1085        sender => $from,
1086        type => 'jabber',
1087        jtype => $p->GetType(),
1088        status => $p->GetStatus(),
1089        show => $p->GetShow(),
1090        xml => $p->GetXML(),
1091        direction => 'in');
1092
1093    if ($type eq '' || $type eq 'available') {
1094        $props{body} = "$from is now online. ";
1095        $props{loginout} = 'login';
1096    }
1097    else {
1098        $props{body} = "$from is now offline. ";
1099        $props{loginout} = 'logout';
1100    }
1101    $props{replysendercmd} = $props{replycmd} = "jwrite $from -i $sid";
1102    if(BarnOwl::getvar('debug') eq 'on') {
1103        BarnOwl::queue_message(BarnOwl::Message->new(%props));
1104    }
1105}
1106
1107sub process_presence_subscribe {
1108    my ( $sid, $p ) = @_;
1109    my $from = $p->GetFrom();
1110    my $to = $p->GetTo();
1111    my %props = (
1112        to => $to,
1113        from => $from,
1114        xml => $p->GetXML(),
1115        type => 'admin',
1116        adminheader => 'Jabber presence: subscribe',
1117        direction => 'in');
1118
1119    $props{body} = "Allow user ($from) to subscribe to your ($to) presence?\n" .
1120                   "(Answer with the `yes' or `no' commands)";
1121    $props{yescommand} = "jroster auth $from -a $to";
1122    $props{nocommand} = "jroster deauth $from -a $to";
1123    $props{question} = "true";
1124    BarnOwl::queue_message(BarnOwl::Message->new(%props));
1125}
1126
1127sub process_presence_unsubscribe {
1128    my ( $sid, $p ) = @_;
1129    my $from = $p->GetFrom();
1130    my $to = $p->GetTo();
1131    my %props = (
1132        to => $to,
1133        from => $from,
1134        xml => $p->GetXML(),
1135        type => 'admin',
1136        adminheader => 'Jabber presence: unsubscribe',
1137        direction => 'in');
1138
1139    $props{body} = "The user ($from) has been unsubscribed from your ($to) presence.\n";
1140    BarnOwl::queue_message(BarnOwl::Message->new(%props));
1141
1142    # Find a connection to reply with.
1143    foreach my $jid ($conn->getJIDs()) {
1144        my $cJID = new Net::Jabber::JID;
1145        $cJID->SetJID($jid);
1146        if ($to eq $cJID->GetJID('base') ||
1147            $to eq $cJID->GetJID('full')) {
1148            my $reply = $p->Reply(type=>"unsubscribed");
1149            $conn->getConnectionFromJID($jid)->Send($reply);
1150            return;
1151        }
1152    }
1153}
1154
1155sub process_presence_subscribed {
1156    my ( $sid, $p ) = @_;
1157    queue_admin_msg("ignoring:".$p->GetXML());
1158    # RFC 3921 says we should respond to this with a "subscribe"
1159    # but this causes a flood of sub/sub'd presence packets with
1160    # some servers, so we won't. We may want to detect this condition
1161    # later, and have per-server settings.
1162    return;
1163}
1164
1165sub process_presence_unsubscribed {
1166    my ( $sid, $p ) = @_;
1167    queue_admin_msg("ignoring:".$p->GetXML());
1168    # RFC 3921 says we should respond to this with a "subscribe"
1169    # but this causes a flood of unsub/unsub'd presence packets with
1170    # some servers, so we won't. We may want to detect this condition
1171    # later, and have per-server settings.
1172    return;
1173}
1174
1175sub process_presence_error {
1176    my ( $sid, $p ) = @_;
1177    my $code = $p->GetErrorCode();
1178    my $error = $p->GetError();
1179    BarnOwl::error("Jabber: $code $error");
1180}
1181
1182
1183### Helper functions
1184
1185sub j2hash {
1186    my $j   = shift;
1187    my %initProps = %{ shift() };
1188
1189    my $dir = 'none';
1190    my %props = ( type => 'jabber' );
1191
1192    foreach my $k (keys %initProps) {
1193        $dir = $initProps{$k} if ($k eq 'direction');
1194        $props{$k} = $initProps{$k};
1195    }
1196
1197    my $jtype = $props{jtype} = $j->GetType();
1198    my $from = $j->GetFrom('jid');
1199    my $to   = $j->GetTo('jid');
1200
1201    $props{from} = $from->GetJID('full');
1202    $props{to}   = $to->GetJID('full');
1203
1204    $props{recipient}  = $to->GetJID('base');
1205    $props{sender}     = $from->GetJID('base');
1206    $props{subject}    = $j->GetSubject() if ( $j->DefinedSubject() );
1207    $props{thread}     = $j->GetThread() if ( $j->DefinedThread() );
1208    $props{body}       = $j->GetBody() if ( $j->DefinedBody() );
1209    $props{error}      = $j->GetError() if ( $j->DefinedError() );
1210    $props{error_code} = $j->GetErrorCode() if ( $j->DefinedErrorCode() );
1211    $props{xml}        = $j->GetXML();
1212
1213    if ( $jtype eq 'chat' ) {
1214        $props{replycmd} =
1215          "jwrite " . ( ( $dir eq 'in' ) ? $props{from} : $props{to} );
1216        $props{replycmd} .=
1217          " -a " . ( ( $dir eq 'out' ) ? $props{from} : $props{to} );
1218        $props{private} = 1;
1219
1220        my $connection;
1221        if ($dir eq 'in') {
1222            $connection = $conn->getConnectionFromSid($props{sid});
1223        }
1224        else {
1225            $connection = $conn->getConnectionFromJID($props{from});
1226        }
1227
1228        # Check to see if we're doing personals with someone in a muc.
1229        # If we are, show the full jid because the base jid is the room.
1230        if ($connection) {
1231            $props{sender} = $props{from}
1232              if ($connection->FindMUC(jid => $from));
1233            $props{recipient} = $props{to}
1234              if ($connection->FindMUC(jid => $to));
1235        }
1236    }
1237    elsif ( $jtype eq 'groupchat' ) {
1238        my $nick = $props{nick} = $from->GetResource();
1239        my $room = $props{room} = $from->GetJID('base');
1240        $props{replycmd} = "jwrite $room";
1241        $props{replycmd} .=
1242          " -a " . ( ( $dir eq 'out' ) ? $props{from} : $props{to} );
1243
1244        if ($dir eq 'out') {
1245            $props{replysendercmd} = "jwrite ".$props{to}." -a ".$props{from};
1246        }
1247        else {
1248            $props{replysendercmd} = "jwrite ".$props{from}." -a ".$props{to};
1249        }
1250
1251        $props{sender} = $nick || $room;
1252        $props{recipient} = $room;
1253
1254        if ( $props{subject} && !$props{body} ) {
1255            $props{body} =
1256              '[' . $nick . " has set the topic to: " . $props{subject} . "]";
1257        }
1258    }
1259    elsif ( $jtype eq 'normal' ) {
1260        $props{replycmd}  = undef;
1261        $props{private} = 1;
1262    }
1263    elsif ( $jtype eq 'headline' ) {
1264        $props{replycmd} = undef;
1265    }
1266    elsif ( $jtype eq 'error' ) {
1267        $props{replycmd} = undef;
1268        $props{body}     = "Error "
1269          . $props{error_code}
1270          . " sending to "
1271          . $props{from} . "\n"
1272          . $props{error};
1273    }
1274
1275    $props{replysendercmd} = $props{replycmd} unless $props{replysendercmd};
1276    return %props;
1277}
1278
1279sub j2o {
1280    return BarnOwl::Message->new( j2hash(@_) );
1281}
1282
1283sub queue_admin_msg {
1284    my $err = shift;
1285    my $m   = BarnOwl::Message->new(
1286        type      => 'admin',
1287        direction => 'none',
1288        body      => $err
1289    );
1290    BarnOwl::queue_message($m);
1291}
1292
1293sub boldify($) {
1294    my $str = shift;
1295
1296    return '@b(' . $str . ')' if ( $str !~ /\)/ );
1297    return '@b<' . $str . '>' if ( $str !~ /\>/ );
1298    return '@b{' . $str . '}' if ( $str !~ /\}/ );
1299    return '@b[' . $str . ']' if ( $str !~ /\]/ );
1300
1301    my $txt = "$str";
1302    $txt =~ s{[)]}{)\@b[)]\@b(}g;
1303    return '@b(' . $txt . ')';
1304}
1305
1306sub getServerFromJID {
1307    my $jid = shift;
1308    my $res = new Net::DNS::Resolver;
1309    my $packet =
1310      $res->search( '_xmpp-client._tcp.' . $jid->GetServer(), 'srv' );
1311
1312    if ($packet)    # Got srv record.
1313    {
1314        my @answer = $packet->answer;
1315        return $answer[0]{target}, $answer[0]{port};
1316    }
1317
1318    return $jid->GetServer(), 5222;
1319}
1320
1321sub defaultJID {
1322    return ( $conn->getJIDs() )[0] if ( $conn->connected() == 1 );
1323    return;
1324}
1325
1326sub baseJID {
1327    my $givenJIDStr = shift;
1328    my $givenJID    = new Net::Jabber::JID;
1329    $givenJID->SetJID($givenJIDStr);
1330    return $givenJID->GetJID('base');
1331}
1332
1333sub resolveConnectedJID {
1334    my $givenJIDStr = shift;
1335    my $givenJID    = new Net::Jabber::JID;
1336    $givenJID->SetJID($givenJIDStr);
1337
1338    # Account fully specified.
1339    if ( $givenJID->GetResource() ) {
1340        # Specified account exists
1341        return $givenJIDStr if ($conn->jidExists($givenJIDStr) );
1342        die("Invalid account: $givenJIDStr");
1343    }
1344
1345    # Disambiguate.
1346    else {
1347        my $matchingJID = "";
1348        my $errStr =
1349          "Ambiguous account reference. Please specify a resource.\n";
1350        my $ambiguous = 0;
1351
1352        foreach my $jid ( $conn->getJIDs() ) {
1353            my $cJID = new Net::Jabber::JID;
1354            $cJID->SetJID($jid);
1355            if ( $givenJIDStr eq $cJID->GetJID('base') ) {
1356                $ambiguous = 1 if ( $matchingJID ne "" );
1357                $matchingJID = $jid;
1358                $errStr .= "\t$jid\n";
1359            }
1360        }
1361
1362        # Need further disambiguation.
1363        if ($ambiguous) {
1364            die($errStr);
1365        }
1366
1367        # Not one of ours.
1368        elsif ( $matchingJID eq "" ) {
1369            die("Invalid account: $givenJIDStr");
1370        }
1371
1372        # It's this one.
1373        else {
1374            return $matchingJID;
1375        }
1376    }
1377    return "";
1378}
1379
1380sub resolveDestJID {
1381    my ($to, $from) = @_;
1382    my $jid = Net::Jabber::JID->new($to);
1383
1384    my $roster = $conn->getRosterFromJID($from);
1385    my @jids = $roster->jids('all');
1386    for my $j (@jids) {
1387        if(($roster->query($j, 'name') || $j->GetUserID()) eq $to) {
1388            return $j->GetJID('full');
1389        } elsif($j->GetJID('base') eq baseJID($to)) {
1390            return $jid->GetJID('full');
1391        }
1392    }
1393
1394    # If we found nothing being clever, check to see if our input was
1395    # sane enough to look like a jid with a UserID.
1396    return $jid->GetJID('full') if $jid->GetUserID();
1397    return undef;
1398}
1399
1400sub resolveType {
1401    my $to = shift;
1402    my $from = shift;
1403    return unless $from;
1404    my @mucs = $conn->getConnectionFromJID($from)->MUCs;
1405    if(grep {$_->BaseJID eq $to } @mucs) {
1406        return 'groupchat';
1407    } else {
1408        return 'chat';
1409    }
1410}
1411
1412sub guess_jwrite {
1413    # Heuristically guess what jids a jwrite was meant to be going to/from
1414    my ($from, $to) = (@_);
1415    my ($from_jid, $to_jid);
1416    my @matches;
1417    if($from) {
1418        $from_jid = resolveConnectedJID($from);
1419        die("Unable to resolve account $from") unless $from_jid;
1420        $to_jid = resolveDestJID($to, $from_jid);
1421        push @matches, [$from_jid, $to_jid] if $to_jid;
1422    } else {
1423        for my $f ($conn->getJIDs) {
1424            $to_jid = resolveDestJID($to, $f);
1425            if(defined($to_jid)) {
1426                push @matches, [$f, $to_jid];
1427            }
1428        }
1429        if($to =~ /@/) {
1430            push @matches, [$_, $to]
1431               for ($conn->getJIDs);
1432        }
1433    }
1434
1435    for my $m (@matches) {
1436        my $type = resolveType($m->[1], $m->[0]);
1437        push @$m, $type;
1438    }
1439
1440    return @matches;
1441}
1442
1443#####################################################################
1444#####################################################################
1445
1446package BarnOwl::Message::Jabber;
1447
1448our @ISA = qw( BarnOwl::Message );
1449
1450sub jtype { shift->{jtype} };
1451sub from { shift->{from} };
1452sub to { shift->{to} };
1453sub room { shift->{room} };
1454
1455sub smartfilter {
1456    my $self = shift;
1457    my $inst = shift;
1458
1459    my ($filter, $ftext);
1460
1461    if($self->jtype eq 'chat') {
1462        my $user;
1463        if($self->direction eq 'in') {
1464            $user = $self->from;
1465        } else {
1466            $user = $self->to;
1467        }
1468        return smartfilter_user($user, $inst);
1469    } elsif ($self->jtype eq 'groupchat') {
1470        my $room = $self->room;
1471        $filter = "jabber-room-$room";
1472        $ftext = qq{type ^jabber\$ and room ^$room\$};
1473        BarnOwl::filter("$filter $ftext");
1474        return $filter;
1475    } elsif ($self->login ne 'none') {
1476        return smartfilter_user($self->from, $inst);
1477    }
1478}
1479
1480sub smartfilter_user {
1481    my $user = shift;
1482    my $inst = shift;
1483
1484    $user   = Net::Jabber::JID->new($user)->GetJID( $inst ? 'full' : 'base' );
1485    my $filter = "jabber-user-$user";
1486    my $ftext  =
1487        qq{type ^jabber\$ and ( ( direction ^in\$ and from ^$user ) }
1488      . qq{or ( direction ^out\$ and to ^$user ) ) };
1489    BarnOwl::filter("$filter $ftext");
1490    return $filter;
1491
1492}
1493
1494
14951;
Note: See TracBrowser for help on using the repository browser.