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

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