source: perl/modules/jabber.pl @ 3066d23

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