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

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