source: perl/modules/jabber.pl @ 95e60d6

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