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

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