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

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