source: perl/modules/jabber.pl @ 272a4a0

barnowl_perlaimdebianrelease-1.10release-1.4release-1.5release-1.6release-1.7release-1.8release-1.9
Last change on this file since 272a4a0 was 1c2e0b3, checked in by Alejandro R. Sedeño <asedeno@mit.edu>, 17 years ago
Export owl_function_add_message and owl_function_queue_message to perl. Use them in jabber.pl.
  • 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 = BarnOwl::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    $muc = Net::Jabber::JID->new($muc);
720    $jid = Net::Jabber::JID->new($jid);
721    $muc->SetResource($jid->GetJID('full')) unless length $muc->GetResource();
722
723    $conn->getConnectionFromJID($jid)->MUCJoin(JID      => $muc,
724                                                  Password => $password,
725                                                  History  => {
726                                                      MaxChars => 0
727                                                     });
728    return;
729}
730
731sub jmuc_part {
732    my ( $jid, $muc, @args ) = @_;
733
734    $muc = shift @args if scalar @args;
735    die("Usage: jmuc part MUC [-a account]") unless $muc;
736
737    $conn->getConnectionFromJID($jid)->MUCLeave(JID => $muc);
738    queue_admin_msg("$jid has left $muc.");
739}
740
741sub jmuc_invite {
742    my ( $jid, $muc, @args ) = @_;
743
744    my $invite_jid = shift @args;
745    $muc = shift @args if scalar @args;
746
747    die('Usage: jmuc invite JID [muc] [-a account]')
748      unless $muc && $invite_jid;
749
750    my $message = Net::Jabber::Message->new();
751    $message->SetTo($muc);
752    my $x = $message->NewChild('http://jabber.org/protocol/muc#user');
753    $x->AddInvite();
754    $x->GetInvite()->SetTo($invite_jid);
755    $conn->getConnectionFromJID($jid)->Send($message);
756    queue_admin_msg("$jid has invited $invite_jid to $muc.");
757}
758
759sub jmuc_configure {
760    my ( $jid, $muc, @args ) = @_;
761    $muc = shift @args if scalar @args;
762    die("Usage: jmuc configure [muc]") unless $muc;
763    my $iq = Net::Jabber::IQ->new();
764    $iq->SetTo($muc);
765    $iq->SetType('set');
766    my $query = $iq->NewQuery("http://jabber.org/protocol/muc#owner");
767    my $x     = $query->NewChild("jabber:x:data");
768    $x->SetType('submit');
769
770    $conn->getConnectionFromJID($jid)->Send($iq);
771    queue_admin_msg("Accepted default instant configuration for $muc");
772}
773
774sub jmuc_presence_single {
775    my $m = shift;
776    my @jids = $m->Presence();
777    return "JIDs present in " . $m->BaseJID . "\n\t"
778      . join("\n\t", map {$_->GetResource}@jids) . "\n";
779}
780
781sub jmuc_presence {
782    my ( $jid, $muc, @args ) = @_;
783
784    $muc = shift @args if scalar @args;
785    die("Usage: jmuc presence MUC") unless $muc;
786
787    if ($muc eq '-a') {
788        my $str = "";
789        foreach my $jid ($conn->getJIDs()) {
790            $str .= boldify("Conferences for $jid:\n");
791            my $connection = $conn->getConnectionFromJID($jid);
792            foreach my $muc ($connection->MUCs) {
793                $str .= jmuc_presence_single($muc)."\n";
794            }
795        }
796        BarnOwl::popless_ztext($str);
797    }
798    else {
799        my $m = $conn->getConnectionFromJID($jid)->FindMUC(jid => $muc);
800        die("No such muc: $muc") unless $m;
801        BarnOwl::popless_ztext(jmuc_presence_single($m));
802    }
803}
804
805
806#XXX TODO: Consider merging this with jmuc and selecting off the first two args.
807sub cmd_jroster {
808    die "You are not logged in to Jabber" unless $conn->connected();
809    my $ocmd = shift;
810    my $cmd  = shift;
811    if ( !$cmd ) {
812
813        #XXX TODO: Write general usage for jroster command.
814        return;
815    }
816
817    my %jroster_commands = (
818        sub      => \&jroster_sub,
819        unsub    => \&jroster_unsub,
820        add      => \&jroster_add,
821        remove   => \&jroster_remove,
822        auth     => \&jroster_auth,
823        deauth   => \&jroster_deauth
824    );
825    my $func = $jroster_commands{$cmd};
826    if ( !$func ) {
827        BarnOwl::error("jroster: Unknown command: $cmd");
828        return;
829    }
830
831    {
832        local @ARGV = @_;
833        my $jid;
834        my $name;
835        my @groups;
836        my $purgeGroups;
837        my $getopt = Getopt::Long::Parser->new;
838        $getopt->configure('pass_through');
839        $getopt->getoptions(
840            'account=s' => \$jid,
841            'group=s' => \@groups,
842            'purgegroups' => \$purgeGroups,
843            'name=s' => \$name
844        );
845        $jid ||= defaultJID();
846        if ($jid) {
847            $jid = resolveConnectedJID($jid);
848            return unless $jid;
849        }
850        else {
851            BarnOwl::error('You must specify an account with -a {jid}');
852        }
853        return $func->( $jid, $name, \@groups, $purgeGroups,  @ARGV );
854    }
855}
856
857sub jroster_sub {
858    my $jid = shift;
859    my $name = shift;
860    my @groups = @{ shift() };
861    my $purgeGroups = shift;
862    my $baseJID = baseJID($jid);
863
864    my $roster = $conn->getRosterFromJID($jid);
865
866    # Adding lots of users with the same name is a bad idea.
867    $name = "" unless (1 == scalar(@ARGV));
868
869    my $p = new Net::Jabber::Presence;
870    $p->SetType('subscribe');
871
872    foreach my $to (@ARGV) {
873        jroster_add($jid, $name, \@groups, $purgeGroups, ($to)) unless ($roster->exists($to));
874
875        $p->SetTo($to);
876        $conn->getConnectionFromJID($jid)->Send($p);
877        queue_admin_msg("You ($baseJID) have requested a subscription to ($to)'s presence.");
878    }
879}
880
881sub jroster_unsub {
882    my $jid = shift;
883    my $name = shift;
884    my @groups = @{ shift() };
885    my $purgeGroups = shift;
886    my $baseJID = baseJID($jid);
887
888    my $p = new Net::Jabber::Presence;
889    $p->SetType('unsubscribe');
890    foreach my $to (@ARGV) {
891        $p->SetTo($to);
892        $conn->getConnectionFromJID($jid)->Send($p);
893        queue_admin_msg("You ($baseJID) have unsubscribed from ($to)'s presence.");
894    }
895}
896
897sub jroster_add {
898    my $jid = shift;
899    my $name = shift;
900    my @groups = @{ shift() };
901    my $purgeGroups = shift;
902    my $baseJID = baseJID($jid);
903
904    my $roster = $conn->getRosterFromJID($jid);
905
906    # Adding lots of users with the same name is a bad idea.
907    $name = "" unless (1 == scalar(@ARGV));
908
909    foreach my $to (@ARGV) {
910        my %jq  = $roster->query($to);
911        my $iq = new Net::Jabber::IQ;
912        $iq->SetType('set');
913        my $item = new XML::Stream::Node('item');
914        $iq->NewChild('jabber:iq:roster')->AddChild($item);
915
916        my %allGroups = ();
917
918        foreach my $g (@groups) {
919            $allGroups{$g} = $g;
920        }
921
922        unless ($purgeGroups) {
923            foreach my $g (@{$jq{groups}}) {
924                $allGroups{$g} = $g;
925            }
926        }
927
928        foreach my $g (keys %allGroups) {
929            $item->add_child('group')->add_cdata($g);
930        }
931
932        $item->put_attrib(jid => $to);
933        $item->put_attrib(name => $name) if $name;
934        $conn->getConnectionFromJID($jid)->Send($iq);
935        my $msg = "$baseJID: "
936          . ($name ? "$name ($to)" : "($to)")
937          . " is on your roster in the following groups: { "
938          . join(" , ", keys %allGroups)
939          . " }";
940        queue_admin_msg($msg);
941    }
942}
943
944sub jroster_remove {
945    my $jid = shift;
946    my $name = shift;
947    my @groups = @{ shift() };
948    my $purgeGroups = shift;
949    my $baseJID = baseJID($jid);
950
951    my $iq = new Net::Jabber::IQ;
952    $iq->SetType('set');
953    my $item = new XML::Stream::Node('item');
954    $iq->NewChild('jabber:iq:roster')->AddChild($item);
955    $item->put_attrib(subscription=> 'remove');
956    foreach my $to (@ARGV) {
957        $item->put_attrib(jid => $to);
958        $conn->getConnectionFromJID($jid)->Send($iq);
959        queue_admin_msg("You ($baseJID) have removed ($to) from your roster.");
960    }
961}
962
963sub jroster_auth {
964    my $jid = shift;
965    my $name = shift;
966    my @groups = @{ shift() };
967    my $purgeGroups = shift;
968    my $baseJID = baseJID($jid);
969
970    my $p = new Net::Jabber::Presence;
971    $p->SetType('subscribed');
972    foreach my $to (@ARGV) {
973        $p->SetTo($to);
974        $conn->getConnectionFromJID($jid)->Send($p);
975        queue_admin_msg("($to) has been subscribed to your ($baseJID) presence.");
976    }
977}
978
979sub jroster_deauth {
980    my $jid = shift;
981    my $name = shift;
982    my @groups = @{ shift() };
983    my $purgeGroups = shift;
984    my $baseJID = baseJID($jid);
985
986    my $p = new Net::Jabber::Presence;
987    $p->SetType('unsubscribed');
988    foreach my $to (@ARGV) {
989        $p->SetTo($to);
990        $conn->getConnectionFromJID($jid)->Send($p);
991        queue_admin_msg("($to) has been unsubscribed from your ($baseJID) presence.");
992    }
993}
994
995################################################################################
996### Owl Callbacks
997sub process_owl_jwrite {
998    my $body = shift;
999
1000    my $j = new Net::Jabber::Message;
1001    $body =~ s/\n\z//;
1002    $j->SetMessage(
1003        to   => $vars{jwrite}{to},
1004        from => $vars{jwrite}{from},
1005        type => $vars{jwrite}{type},
1006        body => $body
1007    );
1008
1009    $j->SetThread( $vars{jwrite}{thread} )   if ( $vars{jwrite}{thread} );
1010    $j->SetSubject( $vars{jwrite}{subject} ) if ( $vars{jwrite}{subject} );
1011
1012    my $m = j2o( $j, { direction => 'out' } );
1013    if ( $vars{jwrite}{type} ne 'groupchat') {
1014        BarnOwl::add_message($m);
1015    }
1016
1017    $j->RemoveFrom(); # Kludge to get around gtalk's random bits after the resource.
1018    if ($vars{jwrite}{sid} && $conn->sidExists( $vars{jwrite}{sid} )) {
1019        $conn->getConnectionFromSid($vars{jwrite}{sid})->Send($j);
1020    }
1021    else {
1022        $conn->getConnectionFromJID($vars{jwrite}{from})->Send($j);
1023    }
1024
1025    delete $vars{jwrite};
1026    BarnOwl::message("");   # Kludge to make the ``type your message...'' message go away
1027}
1028
1029### XMPP Callbacks
1030
1031sub process_incoming_chat_message {
1032    my ( $sid, $j ) = @_;
1033    BarnOwl::queue_message( j2o( $j, { direction => 'in',
1034                                   sid => $sid } ) );
1035}
1036
1037sub process_incoming_error_message {
1038    my ( $sid, $j ) = @_;
1039    my %jhash = j2hash( $j, { direction => 'in',
1040                              sid => $sid } );
1041    $jhash{type} = 'admin';
1042    BarnOwl::queue_message( BarnOwl::Message->new(%jhash) );
1043}
1044
1045sub process_incoming_groupchat_message {
1046    my ( $sid, $j ) = @_;
1047
1048    # HACK IN PROGRESS (ignoring delayed messages)
1049    return if ( $j->DefinedX('jabber:x:delay') && $j->GetX('jabber:x:delay') );
1050    BarnOwl::queue_message( j2o( $j, { direction => 'in',
1051                                   sid => $sid } ) );
1052}
1053
1054sub process_incoming_headline_message {
1055    my ( $sid, $j ) = @_;
1056    BarnOwl::queue_message( j2o( $j, { direction => 'in',
1057                                   sid => $sid } ) );
1058}
1059
1060sub process_incoming_normal_message {
1061    my ( $sid, $j ) = @_;
1062    my %jhash = j2hash( $j, { direction => 'in',
1063                              sid => $sid } );
1064
1065    # XXX TODO: handle things such as MUC invites here.
1066
1067    #    if ($j->HasX('http://jabber.org/protocol/muc#user'))
1068    #    {
1069    #   my $x = $j->GetX('http://jabber.org/protocol/muc#user');
1070    #   if ($x->HasChild('invite'))
1071    #   {
1072    #       $props
1073    #   }
1074    #    }
1075    #
1076    BarnOwl::queue_message( BarnOwl::Message->new(%jhash) );
1077}
1078
1079sub process_muc_presence {
1080    my ( $sid, $p ) = @_;
1081    return unless ( $p->HasX('http://jabber.org/protocol/muc#user') );
1082}
1083
1084
1085sub process_presence_available {
1086    my ( $sid, $p ) = @_;
1087    my $from = $p->GetFrom();
1088    my $to = $p->GetTo();
1089    my $type = $p->GetType();
1090    my %props = (
1091        to => $to,
1092        from => $from,
1093        recipient => $to,
1094        sender => $from,
1095        type => 'jabber',
1096        jtype => $p->GetType(),
1097        status => $p->GetStatus(),
1098        show => $p->GetShow(),
1099        xml => $p->GetXML(),
1100        direction => 'in');
1101
1102    if ($type eq '' || $type eq 'available') {
1103        $props{body} = "$from is now online. ";
1104        $props{loginout} = 'login';
1105    }
1106    else {
1107        $props{body} = "$from is now offline. ";
1108        $props{loginout} = 'logout';
1109    }
1110    $props{replysendercmd} = $props{replycmd} = "jwrite $from -i $sid";
1111    if(BarnOwl::getvar('debug') eq 'on') {
1112        BarnOwl::queue_message(BarnOwl::Message->new(%props));
1113    }
1114}
1115
1116sub process_presence_subscribe {
1117    my ( $sid, $p ) = @_;
1118    my $from = $p->GetFrom();
1119    my $to = $p->GetTo();
1120    my %props = (
1121        to => $to,
1122        from => $from,
1123        xml => $p->GetXML(),
1124        type => 'admin',
1125        adminheader => 'Jabber presence: subscribe',
1126        direction => 'in');
1127
1128    $props{body} = "Allow user ($from) to subscribe to your ($to) presence?\n" .
1129                   "(Answer with the `yes' or `no' commands)";
1130    $props{yescommand} = "jroster auth $from -a $to";
1131    $props{nocommand} = "jroster deauth $from -a $to";
1132    $props{question} = "true";
1133    BarnOwl::queue_message(BarnOwl::Message->new(%props));
1134}
1135
1136sub process_presence_unsubscribe {
1137    my ( $sid, $p ) = @_;
1138    my $from = $p->GetFrom();
1139    my $to = $p->GetTo();
1140    my %props = (
1141        to => $to,
1142        from => $from,
1143        xml => $p->GetXML(),
1144        type => 'admin',
1145        adminheader => 'Jabber presence: unsubscribe',
1146        direction => 'in');
1147
1148    $props{body} = "The user ($from) has been unsubscribed from your ($to) presence.\n";
1149    BarnOwl::queue_message(BarnOwl::Message->new(%props));
1150
1151    # Find a connection to reply with.
1152    foreach my $jid ($conn->getJIDs()) {
1153        my $cJID = new Net::Jabber::JID;
1154        $cJID->SetJID($jid);
1155        if ($to eq $cJID->GetJID('base') ||
1156            $to eq $cJID->GetJID('full')) {
1157            my $reply = $p->Reply(type=>"unsubscribed");
1158            $conn->getConnectionFromJID($jid)->Send($reply);
1159            return;
1160        }
1161    }
1162}
1163
1164sub process_presence_subscribed {
1165    my ( $sid, $p ) = @_;
1166    queue_admin_msg("ignoring:".$p->GetXML());
1167    # RFC 3921 says we should respond to this with a "subscribe"
1168    # but this causes a flood of sub/sub'd presence packets with
1169    # some servers, so we won't. We may want to detect this condition
1170    # later, and have per-server settings.
1171    return;
1172}
1173
1174sub process_presence_unsubscribed {
1175    my ( $sid, $p ) = @_;
1176    queue_admin_msg("ignoring:".$p->GetXML());
1177    # RFC 3921 says we should respond to this with a "subscribe"
1178    # but this causes a flood of unsub/unsub'd presence packets with
1179    # some servers, so we won't. We may want to detect this condition
1180    # later, and have per-server settings.
1181    return;
1182}
1183
1184sub process_presence_error {
1185    my ( $sid, $p ) = @_;
1186    my $code = $p->GetErrorCode();
1187    my $error = $p->GetError();
1188    BarnOwl::error("Jabber: $code $error");
1189}
1190
1191
1192### Helper functions
1193
1194sub j2hash {
1195    my $j   = shift;
1196    my %initProps = %{ shift() };
1197
1198    my $dir = 'none';
1199    my %props = ( type => 'jabber' );
1200
1201    foreach my $k (keys %initProps) {
1202        $dir = $initProps{$k} if ($k eq 'direction');
1203        $props{$k} = $initProps{$k};
1204    }
1205
1206    my $jtype = $props{jtype} = $j->GetType();
1207    my $from = $j->GetFrom('jid');
1208    my $to   = $j->GetTo('jid');
1209
1210    $props{from} = $from->GetJID('full');
1211    $props{to}   = $to->GetJID('full');
1212
1213    $props{recipient}  = $to->GetJID('base');
1214    $props{sender}     = $from->GetJID('base');
1215    $props{subject}    = $j->GetSubject() if ( $j->DefinedSubject() );
1216    $props{thread}     = $j->GetThread() if ( $j->DefinedThread() );
1217    $props{body}       = $j->GetBody() if ( $j->DefinedBody() );
1218    $props{error}      = $j->GetError() if ( $j->DefinedError() );
1219    $props{error_code} = $j->GetErrorCode() if ( $j->DefinedErrorCode() );
1220    $props{xml}        = $j->GetXML();
1221
1222    if ( $jtype eq 'chat' ) {
1223        $props{replycmd} =
1224          "jwrite " . ( ( $dir eq 'in' ) ? $props{from} : $props{to} );
1225        $props{replycmd} .=
1226          " -a " . ( ( $dir eq 'out' ) ? $props{from} : $props{to} );
1227        $props{private} = 1;
1228
1229        my $connection;
1230        if ($dir eq 'in') {
1231            $connection = $conn->getConnectionFromSid($props{sid});
1232        }
1233        else {
1234            $connection = $conn->getConnectionFromJID($props{from});
1235        }
1236
1237        # Check to see if we're doing personals with someone in a muc.
1238        # If we are, show the full jid because the base jid is the room.
1239        if ($connection) {
1240            $props{sender} = $props{from}
1241              if ($connection->FindMUC(jid => $from));
1242            $props{recipient} = $props{to}
1243              if ($connection->FindMUC(jid => $to));
1244        }
1245    }
1246    elsif ( $jtype eq 'groupchat' ) {
1247        my $nick = $props{nick} = $from->GetResource();
1248        my $room = $props{room} = $from->GetJID('base');
1249        $props{replycmd} = "jwrite $room";
1250        $props{replycmd} .=
1251          " -a " . ( ( $dir eq 'out' ) ? $props{from} : $props{to} );
1252
1253        if ($dir eq 'out') {
1254            $props{replysendercmd} = "jwrite ".$props{to}." -a ".$props{from};
1255        }
1256        else {
1257            $props{replysendercmd} = "jwrite ".$props{from}." -a ".$props{to};
1258        }
1259
1260        $props{sender} = $nick || $room;
1261        $props{recipient} = $room;
1262
1263        if ( $props{subject} && !$props{body} ) {
1264            $props{body} =
1265              '[' . $nick . " has set the topic to: " . $props{subject} . "]";
1266        }
1267    }
1268    elsif ( $jtype eq 'normal' ) {
1269        $props{replycmd}  = undef;
1270        $props{private} = 1;
1271    }
1272    elsif ( $jtype eq 'headline' ) {
1273        $props{replycmd} = undef;
1274    }
1275    elsif ( $jtype eq 'error' ) {
1276        $props{replycmd} = undef;
1277        $props{body}     = "Error "
1278          . $props{error_code}
1279          . " sending to "
1280          . $props{from} . "\n"
1281          . $props{error};
1282    }
1283
1284    $props{replysendercmd} = $props{replycmd} unless $props{replysendercmd};
1285    return %props;
1286}
1287
1288sub j2o {
1289    return BarnOwl::Message->new( j2hash(@_) );
1290}
1291
1292sub queue_admin_msg {
1293    my $err = shift;
1294    BarnOwl::admin_message("jabber.pl", $err);
1295}
1296
1297sub boldify($) {
1298    my $str = shift;
1299
1300    return '@b(' . $str . ')' if ( $str !~ /\)/ );
1301    return '@b<' . $str . '>' if ( $str !~ /\>/ );
1302    return '@b{' . $str . '}' if ( $str !~ /\}/ );
1303    return '@b[' . $str . ']' if ( $str !~ /\]/ );
1304
1305    my $txt = "$str";
1306    $txt =~ s{[)]}{)\@b[)]\@b(}g;
1307    return '@b(' . $txt . ')';
1308}
1309
1310sub getServerFromJID {
1311    my $jid = shift;
1312    my $res = new Net::DNS::Resolver;
1313    my $packet =
1314      $res->search( '_xmpp-client._tcp.' . $jid->GetServer(), 'srv' );
1315
1316    if ($packet)    # Got srv record.
1317    {
1318        my @answer = $packet->answer;
1319        return $answer[0]{target}, $answer[0]{port};
1320    }
1321
1322    return $jid->GetServer(), 5222;
1323}
1324
1325sub defaultJID {
1326    return ( $conn->getJIDs() )[0] if ( $conn->connected() == 1 );
1327    return;
1328}
1329
1330sub baseJID {
1331    my $givenJIDStr = shift;
1332    my $givenJID    = new Net::Jabber::JID;
1333    $givenJID->SetJID($givenJIDStr);
1334    return $givenJID->GetJID('base');
1335}
1336
1337sub resolveConnectedJID {
1338    my $givenJIDStr = shift;
1339    my $givenJID    = new Net::Jabber::JID;
1340    $givenJID->SetJID($givenJIDStr);
1341
1342    # Account fully specified.
1343    if ( $givenJID->GetResource() ) {
1344        # Specified account exists
1345        return $givenJIDStr if ($conn->jidExists($givenJIDStr) );
1346        die("Invalid account: $givenJIDStr");
1347    }
1348
1349    # Disambiguate.
1350    else {
1351        my $matchingJID = "";
1352        my $errStr =
1353          "Ambiguous account reference. Please specify a resource.\n";
1354        my $ambiguous = 0;
1355
1356        foreach my $jid ( $conn->getJIDs() ) {
1357            my $cJID = new Net::Jabber::JID;
1358            $cJID->SetJID($jid);
1359            if ( $givenJIDStr eq $cJID->GetJID('base') ) {
1360                $ambiguous = 1 if ( $matchingJID ne "" );
1361                $matchingJID = $jid;
1362                $errStr .= "\t$jid\n";
1363            }
1364        }
1365
1366        # Need further disambiguation.
1367        if ($ambiguous) {
1368            die($errStr);
1369        }
1370
1371        # Not one of ours.
1372        elsif ( $matchingJID eq "" ) {
1373            die("Invalid account: $givenJIDStr");
1374        }
1375
1376        # It's this one.
1377        else {
1378            return $matchingJID;
1379        }
1380    }
1381    return "";
1382}
1383
1384sub resolveDestJID {
1385    my ($to, $from) = @_;
1386    my $jid = Net::Jabber::JID->new($to);
1387
1388    my $roster = $conn->getRosterFromJID($from);
1389    my @jids = $roster->jids('all');
1390    for my $j (@jids) {
1391        if(($roster->query($j, 'name') || $j->GetUserID()) eq $to) {
1392            return $j->GetJID('full');
1393        } elsif($j->GetJID('base') eq baseJID($to)) {
1394            return $jid->GetJID('full');
1395        }
1396    }
1397
1398    # If we found nothing being clever, check to see if our input was
1399    # sane enough to look like a jid with a UserID.
1400    return $jid->GetJID('full') if $jid->GetUserID();
1401    return undef;
1402}
1403
1404sub resolveType {
1405    my $to = shift;
1406    my $from = shift;
1407    return unless $from;
1408    my @mucs = $conn->getConnectionFromJID($from)->MUCs;
1409    if(grep {$_->BaseJID eq $to } @mucs) {
1410        return 'groupchat';
1411    } else {
1412        return 'chat';
1413    }
1414}
1415
1416sub guess_jwrite {
1417    # Heuristically guess what jids a jwrite was meant to be going to/from
1418    my ($from, $to) = (@_);
1419    my ($from_jid, $to_jid);
1420    my @matches;
1421    if($from) {
1422        $from_jid = resolveConnectedJID($from);
1423        die("Unable to resolve account $from") unless $from_jid;
1424        $to_jid = resolveDestJID($to, $from_jid);
1425        push @matches, [$from_jid, $to_jid] if $to_jid;
1426    } else {
1427        for my $f ($conn->getJIDs) {
1428            $to_jid = resolveDestJID($to, $f);
1429            if(defined($to_jid)) {
1430                push @matches, [$f, $to_jid];
1431            }
1432        }
1433        if($to =~ /@/) {
1434            push @matches, [$_, $to]
1435               for ($conn->getJIDs);
1436        }
1437    }
1438
1439    for my $m (@matches) {
1440        my $type = resolveType($m->[1], $m->[0]);
1441        push @$m, $type;
1442    }
1443
1444    return @matches;
1445}
1446
1447#####################################################################
1448#####################################################################
1449
1450package BarnOwl::Message::Jabber;
1451
1452our @ISA = qw( BarnOwl::Message );
1453
1454sub jtype { shift->{jtype} };
1455sub from { shift->{from} };
1456sub to { shift->{to} };
1457sub room { shift->{room} };
1458
1459sub smartfilter {
1460    my $self = shift;
1461    my $inst = shift;
1462
1463    my ($filter, $ftext);
1464
1465    if($self->jtype eq 'chat') {
1466        my $user;
1467        if($self->direction eq 'in') {
1468            $user = $self->from;
1469        } else {
1470            $user = $self->to;
1471        }
1472        return smartfilter_user($user, $inst);
1473    } elsif ($self->jtype eq 'groupchat') {
1474        my $room = $self->room;
1475        $filter = "jabber-room-$room";
1476        $ftext = qq{type ^jabber\$ and room ^$room\$};
1477        BarnOwl::filter("$filter $ftext");
1478        return $filter;
1479    } elsif ($self->login ne 'none') {
1480        return smartfilter_user($self->from, $inst);
1481    }
1482}
1483
1484sub smartfilter_user {
1485    my $user = shift;
1486    my $inst = shift;
1487
1488    $user   = Net::Jabber::JID->new($user)->GetJID( $inst ? 'full' : 'base' );
1489    my $filter = "jabber-user-$user";
1490    my $ftext  =
1491        qq{type ^jabber\$ and ( ( direction ^in\$ and from ^$user ) }
1492      . qq{or ( direction ^out\$ and to ^$user ) ) };
1493    BarnOwl::filter("$filter $ftext");
1494    return $filter;
1495
1496}
1497
1498
14991;
Note: See TracBrowser for help on using the repository browser.