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

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