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

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