source: perl/modules/jabber.pl @ c18f08d

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