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

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