source: perl/modules/Jabber/lib/BarnOwl/Module/Jabber.pm @ f798d02

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