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

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