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

barnowl_perlaimdebianrelease-1.10release-1.4release-1.5release-1.6release-1.7release-1.8release-1.9
Last change on this file since ee310eb was ee310eb, checked in by Alejandro R. Sedeño <asedeno@mit.edu>, 16 years ago
Merged revisions 909-923 via svnmerge from file:///afs/sipb.mit.edu/project/barnowl/src/svn/trunk ........ r910 | nelhage | 2008-01-29 20:47:41 -0500 (Tue, 29 Jan 2008) | 1 line Fix IRC -- I forgot to add one ->conn in the last patch ........ r911 | asedeno | 2008-01-30 15:49:35 -0500 (Wed, 30 Jan 2008) | 5 lines Jabber Buddy Lists: * Query the jabber:show_offline_buddies once when invoking onGetBuddyList() * Don't bold online roster entries when hiding offline ones ........ r922 | asedeno | 2008-02-03 00:49:46 -0500 (Sun, 03 Feb 2008) | 1 line Bounds checking. ........ r923 | asedeno | 2008-02-03 01:01:07 -0500 (Sun, 03 Feb 2008) | 1 line Portability - removing C++ style comments. ........
  • Property mode set to 100644
File size: 39.4 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;
27
28use utf8;
29
30our $VERSION = 0.1;
31
32BEGIN {
33    if(eval {require IO::Socket::SSL;}) {
34        if($IO::Socket::SSL::VERSION eq "0.97") {
35            BarnOwl::error("You are using IO::Socket:SSL 0.97, which \n" .
36                           "contains bugs causing it not to work with barnowl's\n" .
37                           "jabber support. We recommend updating to the latest\n" .
38                           "IO::Socket::SSL from CPAN. \n");
39            die("Not loading Jabber.par\n");
40        }
41    }
42}
43
44no warnings 'redefine';
45
46################################################################################
47# owl perl jabber support
48#
49# XXX Todo:
50# Rosters for MUCs
51# More user feedback
52#  * joining MUC
53#  * parting MUC
54#  * presence (Roster and MUC)
55# Implementing formatting and logging callbacks for C
56# Appropriate callbacks for presence subscription messages.
57#
58################################################################################
59
60our $conn;
61$conn ||= BarnOwl::Module::Jabber::ConnectionManager->new;
62our %vars;
63
64sub onStart {
65    if ( *BarnOwl::queue_message{CODE} ) {
66        register_owl_commands();
67        register_keybindings();
68        register_filters();
69        $BarnOwl::Hooks::mainLoop->add(\&onMainLoop);
70        $BarnOwl::Hooks::getBuddyList->add(\&onGetBuddyList);
71        $vars{show} = '';
72        BarnOwl::new_variable_bool("jabber:show_offline_buddies",
73                                   { default => 1,
74                                     summary => 'Show offline or pending buddies.'});
75        BarnOwl::new_variable_int("jabber:auto_away_timeout",
76                                  { default => 5,
77                                    summary => 'After minutes idle, auto away.',
78                                  });
79        BarnOwl::new_variable_int("jabber:auto_xa_timeout",
80                                  { default => 15,
81                                    summary => 'After minutes idle, auto extended away.'
82                                });
83    } else {
84        # Our owl doesn't support queue_message. Unfortunately, this
85        # means it probably *also* doesn't support BarnOwl::error. So just
86        # give up silently.
87    }
88}
89
90$BarnOwl::Hooks::startup->add(\&onStart);
91
92sub onMainLoop {
93    return if ( !$conn->connected() );
94
95    $vars{status_changed} = 0;
96    my $auto_away = BarnOwl::getvar('jabber:auto_away_timeout');
97    my $auto_xa = BarnOwl::getvar('jabber:auto_xa_timeout');
98    my $idletime = BarnOwl::getidletime();
99    if ($auto_xa != 0 && $idletime >= (60 * $auto_xa) && ($vars{show} eq 'away' || $vars{show} eq '' )) {
100        $vars{show} = 'xa';
101        $vars{status} = 'Auto extended-away after '.$auto_xa.' minute'.($auto_xa == 1 ? '' : 's').' idle.';
102        $vars{status_changed} = 1;
103    } elsif ($auto_away != 0 && $idletime >= (60 * $auto_away) && $vars{show} eq '') {
104        $vars{show} = 'away';
105        $vars{status} = 'Auto away after '.$auto_away.' minute'.($auto_away == 1 ? '' : 's').' idle.';
106        $vars{status_changed} = 1;
107    } elsif ($idletime == 0 && $vars{show} ne '') {
108        $vars{show} = '';
109        $vars{status} = '';
110        $vars{status_changed} = 1;
111    }
112
113    foreach my $jid ( $conn->getJIDs() ) {
114        my $client = $conn->getConnectionFromJID($jid);
115
116        unless($client) {
117            $conn->removeConnection($jid);
118            BarnOwl::error("Connection for $jid undefined -- error in reload?");
119        }
120
121        my $status = $client->Process(0);
122        if ( !defined($status) ) {
123            BarnOwl::error("Jabber account $jid disconnected!");
124            do_logout($jid);
125        }
126        if ($::shutdown) {
127            do_logout($jid);
128            return;
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            }
392        }
393    }
394    delete $vars{jlogin_jid};
395    $vars{jlogin_password} =~ tr/\0-\377/x/ if $vars{jlogin_password};
396    delete $vars{jlogin_password};
397    delete $vars{jlogin_havepass};
398    delete $vars{jlogin_connhash};
399    delete $vars{jlogin_authhash};
400
401    return "";
402}
403
404sub do_logout {
405    my $jid = shift;
406    my $disconnected = $conn->removeConnection($jid);
407    queue_admin_msg("Jabber disconnected ($jid).") if $disconnected;
408}
409
410sub cmd_logout {
411    # Logged into multiple accounts
412    if ( $conn->connected() > 1 ) {
413        # Logged into multiple accounts, no accout specified.
414        if ( !$_[1] ) {
415            my $errStr =
416              "You are logged into multiple accounts. Please specify an account to log out of.\n";
417            foreach my $jid ( $conn->getJIDs() ) {
418                $errStr .= "\t$jid\n";
419            }
420            queue_admin_msg($errStr);
421        }
422        # Logged into multiple accounts, account specified.
423        else {
424            if ( $_[1] eq '-a' )    #All accounts.
425            {
426                foreach my $jid ( $conn->getJIDs() ) {
427                    do_logout($jid);
428                }
429            }
430            else                    #One account.
431            {
432                my $jid = resolveConnectedJID( $_[1] );
433                do_logout($jid) if ( $jid ne '' );
434            }
435        }
436    }
437    else                            # Only one account logged in.
438    {
439        do_logout( ( $conn->getJIDs() )[0] );
440    }
441    return "";
442}
443
444sub cmd_jlist {
445    if ( !( scalar $conn->getJIDs() ) ) {
446        BarnOwl::error("You are not logged in to Jabber.");
447        return;
448    }
449    BarnOwl::popless_ztext( onGetBuddyList() );
450}
451
452sub cmd_jwrite {
453    if ( !$conn->connected() ) {
454        BarnOwl::error("You are not logged in to Jabber.");
455        return;
456    }
457
458    my $jwrite_to      = "";
459    my $jwrite_from    = "";
460    my $jwrite_sid     = "";
461    my $jwrite_thread  = "";
462    my $jwrite_subject = "";
463    my ($to, $from);
464    my $jwrite_type    = "chat";
465
466    my @args = @_;
467    shift;
468    local @ARGV = @_;
469    my $gc;
470    GetOptions(
471        'thread=s'  => \$jwrite_thread,
472        'subject=s' => \$jwrite_subject,
473        'account=s' => \$from,
474        'id=s'     =>  \$jwrite_sid,
475    );
476    $jwrite_type = 'groupchat' if $gc;
477
478    if ( scalar @ARGV != 1 ) {
479        BarnOwl::error(
480            "Usage: jwrite JID [-t thread] [-s 'subject'] [-a account]");
481        return;
482    }
483    else {
484      $to = shift @ARGV;
485    }
486
487    my @candidates = guess_jwrite($from, $to);
488
489    unless(scalar @candidates) {
490        die("Unable to resolve JID $to");
491    }
492
493    @candidates = grep {defined $_->[0]} @candidates;
494
495    unless(scalar @candidates) {
496        if(!$from) {
497            die("You must specify an account with -a");
498        } else {
499            die("Unable to resolve account $from");
500        }
501    }
502
503
504    ($jwrite_from, $jwrite_to, $jwrite_type) = @{$candidates[0]};
505
506    $vars{jwrite} = {
507        to      => $jwrite_to,
508        from    => $jwrite_from,
509        sid     => $jwrite_sid,
510        subject => $jwrite_subject,
511        thread  => $jwrite_thread,
512        type    => $jwrite_type
513    };
514
515    if(scalar @candidates > 1) {
516        BarnOwl::message(
517            "Warning: Guessing account and/or destination JID"
518           );
519    } else  {
520        BarnOwl::message(
521            "Type your message below.  End with a dot on a line by itself.  ^C will quit."
522           );
523    }
524
525    my $cmd = "jwrite $jwrite_to -a $jwrite_from";
526    $cmd .= " -t $jwrite_thread" if $jwrite_thread;
527    $cmd .= " -s $jwrite_subject" if $jwrite_subject;
528
529    BarnOwl::start_edit_win($cmd, \&process_owl_jwrite );
530}
531
532sub cmd_jmuc {
533    die "You are not logged in to Jabber" unless $conn->connected();
534    my $ocmd = shift;
535    my $cmd  = shift;
536    if ( !$cmd ) {
537
538        #XXX TODO: Write general usage for jmuc command.
539        return;
540    }
541
542    my %jmuc_commands = (
543        join      => \&jmuc_join,
544        part      => \&jmuc_part,
545        invite    => \&jmuc_invite,
546        configure => \&jmuc_configure,
547        presence  => \&jmuc_presence
548    );
549    my $func = $jmuc_commands{$cmd};
550    if ( !$func ) {
551        BarnOwl::error("jmuc: Unknown command: $cmd");
552        return;
553    }
554
555    {
556        local @ARGV = @_;
557        my $jid;
558        my $muc;
559        my $m = BarnOwl::getcurmsg();
560        if ( $m && $m->is_jabber && $m->{jtype} eq 'groupchat' ) {
561            $muc = $m->{room};
562            $jid = $m->{to};
563        }
564
565        my $getopt = Getopt::Long::Parser->new;
566        $getopt->configure('pass_through');
567        $getopt->getoptions( 'account=s' => \$jid );
568        $jid ||= defaultJID();
569        if ($jid) {
570            $jid = resolveConnectedJID($jid);
571            return unless $jid;
572        }
573        else {
574            BarnOwl::error('You must specify an account with -a {jid}');
575        }
576        return $func->( $jid, $muc, @ARGV );
577    }
578}
579
580sub jmuc_join {
581    my ( $jid, $muc, @args ) = @_;
582    local @ARGV = @args;
583    my $password;
584    GetOptions( 'password=s' => \$password );
585
586    $muc = shift @ARGV
587      or die("Usage: jmuc join MUC [-p password] [-a account]");
588
589    die("Error: Must specify a fully-qualified MUC name (e.g. barnowl\@conference.mit.edu)\n")
590        unless $muc =~ /@/;
591    $muc = Net::Jabber::JID->new($muc);
592    $jid = Net::Jabber::JID->new($jid);
593    $muc->SetResource($jid->GetJID('full')) unless length $muc->GetResource();
594
595    $conn->getConnectionFromJID($jid)->MUCJoin(JID      => $muc,
596                                               Password => $password,
597                                               History  => {
598                                                   MaxChars => 0
599                                                  });
600    return;
601}
602
603sub jmuc_part {
604    my ( $jid, $muc, @args ) = @_;
605
606    $muc = shift @args if scalar @args;
607    die("Usage: jmuc part MUC [-a account]") unless $muc;
608
609    if($conn->getConnectionFromJID($jid)->MUCLeave(JID => $muc)) {
610        queue_admin_msg("$jid has left $muc.");
611    } else {
612        die("Error: Not joined to $muc");
613    }
614}
615
616sub jmuc_invite {
617    my ( $jid, $muc, @args ) = @_;
618
619    my $invite_jid = shift @args;
620    $muc = shift @args if scalar @args;
621
622    die('Usage: jmuc invite JID [muc] [-a account]')
623      unless $muc && $invite_jid;
624
625    my $message = Net::Jabber::Message->new();
626    $message->SetTo($muc);
627    my $x = $message->NewChild('http://jabber.org/protocol/muc#user');
628    $x->AddInvite();
629    $x->GetInvite()->SetTo($invite_jid);
630    $conn->getConnectionFromJID($jid)->Send($message);
631    queue_admin_msg("$jid has invited $invite_jid to $muc.");
632}
633
634sub jmuc_configure {
635    my ( $jid, $muc, @args ) = @_;
636    $muc = shift @args if scalar @args;
637    die("Usage: jmuc configure [muc]") unless $muc;
638    my $iq = Net::Jabber::IQ->new();
639    $iq->SetTo($muc);
640    $iq->SetType('set');
641    my $query = $iq->NewQuery("http://jabber.org/protocol/muc#owner");
642    my $x     = $query->NewChild("jabber:x:data");
643    $x->SetType('submit');
644
645    $conn->getConnectionFromJID($jid)->Send($iq);
646    queue_admin_msg("Accepted default instant configuration for $muc");
647}
648
649sub jmuc_presence_single {
650    my $m = shift;
651    my @jids = $m->Presence();
652
653    my $presence = "JIDs present in " . $m->BaseJID;
654    if($m->Anonymous) {
655        $presence .= " [anonymous MUC]";
656    }
657    $presence .= "\n\t";
658    $presence .= join("\n\t", map {pp_jid($m, $_);} @jids) . "\n";
659    return $presence;
660}
661
662sub pp_jid {
663    my ($m, $jid) = @_;
664    my $nick = $jid->GetResource;
665    my $full = $m->GetFullJID($jid);
666    if($full && $full ne $nick) {
667        return "$nick ($full)";
668    } else {
669        return "$nick";
670    }
671}
672
673sub jmuc_presence {
674    my ( $jid, $muc, @args ) = @_;
675
676    $muc = shift @args if scalar @args;
677    die("Usage: jmuc presence MUC") unless $muc;
678
679    if ($muc eq '-a') {
680        my $str = "";
681        foreach my $jid ($conn->getJIDs()) {
682            $str .= BarnOwl::Style::boldify("Conferences for $jid:\n");
683            my $connection = $conn->getConnectionFromJID($jid);
684            foreach my $muc ($connection->MUCs) {
685                $str .= jmuc_presence_single($muc)."\n";
686            }
687        }
688        BarnOwl::popless_ztext($str);
689    }
690    else {
691        my $m = $conn->getConnectionFromJID($jid)->FindMUC(jid => $muc);
692        die("No such muc: $muc") unless $m;
693        BarnOwl::popless_ztext(jmuc_presence_single($m));
694    }
695}
696
697
698#XXX TODO: Consider merging this with jmuc and selecting off the first two args.
699sub cmd_jroster {
700    die "You are not logged in to Jabber" unless $conn->connected();
701    my $ocmd = shift;
702    my $cmd  = shift;
703    if ( !$cmd ) {
704
705        #XXX TODO: Write general usage for jroster command.
706        return;
707    }
708
709    my %jroster_commands = (
710        sub      => \&jroster_sub,
711        unsub    => \&jroster_unsub,
712        add      => \&jroster_add,
713        remove   => \&jroster_remove,
714        auth     => \&jroster_auth,
715        deauth   => \&jroster_deauth
716    );
717    my $func = $jroster_commands{$cmd};
718    if ( !$func ) {
719        BarnOwl::error("jroster: Unknown command: $cmd");
720        return;
721    }
722
723    {
724        local @ARGV = @_;
725        my $jid;
726        my $name;
727        my @groups;
728        my $purgeGroups;
729        my $getopt = Getopt::Long::Parser->new;
730        $getopt->configure('pass_through');
731        $getopt->getoptions(
732            'account=s' => \$jid,
733            'group=s' => \@groups,
734            'purgegroups' => \$purgeGroups,
735            'name=s' => \$name
736        );
737        $jid ||= defaultJID();
738        if ($jid) {
739            $jid = resolveConnectedJID($jid);
740            return unless $jid;
741        }
742        else {
743            BarnOwl::error('You must specify an account with -a {jid}');
744        }
745        return $func->( $jid, $name, \@groups, $purgeGroups,  @ARGV );
746    }
747}
748
749sub jroster_sub {
750    my $jid = shift;
751    my $name = shift;
752    my @groups = @{ shift() };
753    my $purgeGroups = shift;
754    my $baseJID = baseJID($jid);
755
756    my $roster = $conn->getRosterFromJID($jid);
757
758    # Adding lots of users with the same name is a bad idea.
759    $name = "" unless (1 == scalar(@ARGV));
760
761    my $p = new Net::Jabber::Presence;
762    $p->SetType('subscribe');
763
764    foreach my $to (@ARGV) {
765        jroster_add($jid, $name, \@groups, $purgeGroups, ($to)) unless ($roster->exists($to));
766
767        $p->SetTo($to);
768        $conn->getConnectionFromJID($jid)->Send($p);
769        queue_admin_msg("You ($baseJID) have requested a subscription to ($to)'s presence.");
770    }
771}
772
773sub jroster_unsub {
774    my $jid = shift;
775    my $name = shift;
776    my @groups = @{ shift() };
777    my $purgeGroups = shift;
778    my $baseJID = baseJID($jid);
779
780    my $p = new Net::Jabber::Presence;
781    $p->SetType('unsubscribe');
782    foreach my $to (@ARGV) {
783        $p->SetTo($to);
784        $conn->getConnectionFromJID($jid)->Send($p);
785        queue_admin_msg("You ($baseJID) have unsubscribed from ($to)'s presence.");
786    }
787}
788
789sub jroster_add {
790    my $jid = shift;
791    my $name = shift;
792    my @groups = @{ shift() };
793    my $purgeGroups = shift;
794    my $baseJID = baseJID($jid);
795
796    my $roster = $conn->getRosterFromJID($jid);
797
798    # Adding lots of users with the same name is a bad idea.
799    $name = "" unless (1 == scalar(@ARGV));
800
801    foreach my $to (@ARGV) {
802        my %jq  = $roster->query($to);
803        my $iq = new Net::Jabber::IQ;
804        $iq->SetType('set');
805        my $item = new XML::Stream::Node('item');
806        $iq->NewChild('jabber:iq:roster')->AddChild($item);
807
808        my %allGroups = ();
809
810        foreach my $g (@groups) {
811            $allGroups{$g} = $g;
812        }
813
814        unless ($purgeGroups) {
815            foreach my $g (@{$jq{groups}}) {
816                $allGroups{$g} = $g;
817            }
818        }
819
820        foreach my $g (keys %allGroups) {
821            $item->add_child('group')->add_cdata($g);
822        }
823
824        $item->put_attrib(jid => $to);
825        $item->put_attrib(name => $name) if $name;
826        $conn->getConnectionFromJID($jid)->Send($iq);
827        my $msg = "$baseJID: "
828          . ($name ? "$name ($to)" : "($to)")
829          . " is on your roster in the following groups: { "
830          . join(" , ", keys %allGroups)
831          . " }";
832        queue_admin_msg($msg);
833    }
834}
835
836sub jroster_remove {
837    my $jid = shift;
838    my $name = shift;
839    my @groups = @{ shift() };
840    my $purgeGroups = shift;
841    my $baseJID = baseJID($jid);
842
843    my $iq = new Net::Jabber::IQ;
844    $iq->SetType('set');
845    my $item = new XML::Stream::Node('item');
846    $iq->NewChild('jabber:iq:roster')->AddChild($item);
847    $item->put_attrib(subscription=> 'remove');
848    foreach my $to (@ARGV) {
849        $item->put_attrib(jid => $to);
850        $conn->getConnectionFromJID($jid)->Send($iq);
851        queue_admin_msg("You ($baseJID) have removed ($to) from your roster.");
852    }
853}
854
855sub jroster_auth {
856    my $jid = shift;
857    my $name = shift;
858    my @groups = @{ shift() };
859    my $purgeGroups = shift;
860    my $baseJID = baseJID($jid);
861
862    my $p = new Net::Jabber::Presence;
863    $p->SetType('subscribed');
864    foreach my $to (@ARGV) {
865        $p->SetTo($to);
866        $conn->getConnectionFromJID($jid)->Send($p);
867        queue_admin_msg("($to) has been subscribed to your ($baseJID) presence.");
868    }
869}
870
871sub jroster_deauth {
872    my $jid = shift;
873    my $name = shift;
874    my @groups = @{ shift() };
875    my $purgeGroups = shift;
876    my $baseJID = baseJID($jid);
877
878    my $p = new Net::Jabber::Presence;
879    $p->SetType('unsubscribed');
880    foreach my $to (@ARGV) {
881        $p->SetTo($to);
882        $conn->getConnectionFromJID($jid)->Send($p);
883        queue_admin_msg("($to) has been unsubscribed from your ($baseJID) presence.");
884    }
885}
886
887################################################################################
888### Owl Callbacks
889sub process_owl_jwrite {
890    my $body = shift;
891
892    my $j = new Net::Jabber::Message;
893    $body =~ s/\n\z//;
894    $j->SetMessage(
895        to   => $vars{jwrite}{to},
896        from => $vars{jwrite}{from},
897        type => $vars{jwrite}{type},
898        body => $body
899    );
900
901    $j->SetThread( $vars{jwrite}{thread} )   if ( $vars{jwrite}{thread} );
902    $j->SetSubject( $vars{jwrite}{subject} ) if ( $vars{jwrite}{subject} );
903
904    my $m = j2o( $j, { direction => 'out' } );
905    if ( $vars{jwrite}{type} ne 'groupchat') {
906        BarnOwl::queue_message($m);
907    }
908
909    $j->RemoveFrom(); # Kludge to get around gtalk's random bits after the resource.
910    if ($vars{jwrite}{sid} && $conn->sidExists( $vars{jwrite}{sid} )) {
911        $conn->getConnectionFromSid($vars{jwrite}{sid})->Send($j);
912    }
913    else {
914        $conn->getConnectionFromJID($vars{jwrite}{from})->Send($j);
915    }
916
917    delete $vars{jwrite};
918    BarnOwl::message("");   # Kludge to make the ``type your message...'' message go away
919}
920
921### XMPP Callbacks
922
923sub process_incoming_chat_message {
924    my ( $sid, $j ) = @_;
925    BarnOwl::queue_message( j2o( $j, { direction => 'in',
926                                   sid => $sid } ) );
927}
928
929sub process_incoming_error_message {
930    my ( $sid, $j ) = @_;
931    my %jhash = j2hash( $j, { direction => 'in',
932                              sid => $sid } );
933    $jhash{type} = 'admin';
934   
935    BarnOwl::queue_message( BarnOwl::Message->new(%jhash) );
936}
937
938sub process_incoming_groupchat_message {
939    my ( $sid, $j ) = @_;
940
941    # HACK IN PROGRESS (ignoring delayed messages)
942    return if ( $j->DefinedX('jabber:x:delay') && $j->GetX('jabber:x:delay') );
943    BarnOwl::queue_message( j2o( $j, { direction => 'in',
944                                   sid => $sid } ) );
945}
946
947sub process_incoming_headline_message {
948    my ( $sid, $j ) = @_;
949    BarnOwl::queue_message( j2o( $j, { direction => 'in',
950                                   sid => $sid } ) );
951}
952
953sub process_incoming_normal_message {
954    my ( $sid, $j ) = @_;
955    my %jhash = j2hash( $j, { direction => 'in',
956                              sid => $sid } );
957
958    # XXX TODO: handle things such as MUC invites here.
959
960    #    if ($j->HasX('http://jabber.org/protocol/muc#user'))
961    #    {
962    #   my $x = $j->GetX('http://jabber.org/protocol/muc#user');
963    #   if ($x->HasChild('invite'))
964    #   {
965    #       $props
966    #   }
967    #    }
968    #
969    BarnOwl::queue_message( BarnOwl::Message->new(%jhash) );
970}
971
972sub process_muc_presence {
973    my ( $sid, $p ) = @_;
974    return unless ( $p->HasX('http://jabber.org/protocol/muc#user') );
975}
976
977
978sub process_presence_available {
979    my ( $sid, $p ) = @_;
980    my $from = $p->GetFrom();
981    my $to = $p->GetTo();
982    my $type = $p->GetType();
983    my %props = (
984        to => $to,
985        from => $from,
986        recipient => $to,
987        sender => $from,
988        type => 'jabber',
989        jtype => $p->GetType(),
990        status => $p->GetStatus(),
991        show => $p->GetShow(),
992        xml => $p->GetXML(),
993        direction => 'in');
994
995    if ($type eq '' || $type eq 'available') {
996        $props{body} = "$from is now online. ";
997        $props{loginout} = 'login';
998    }
999    else {
1000        $props{body} = "$from is now offline. ";
1001        $props{loginout} = 'logout';
1002    }
1003    $props{replysendercmd} = $props{replycmd} = "jwrite $from -i $sid";
1004    if(BarnOwl::getvar('debug') eq 'on') {
1005        BarnOwl::queue_message(BarnOwl::Message->new(%props));
1006    }
1007}
1008
1009sub process_presence_subscribe {
1010    my ( $sid, $p ) = @_;
1011    my $from = $p->GetFrom();
1012    my $to = $p->GetTo();
1013    my %props = (
1014        to => $to,
1015        from => $from,
1016        xml => $p->GetXML(),
1017        type => 'admin',
1018        adminheader => 'Jabber presence: subscribe',
1019        direction => 'in');
1020
1021    $props{body} = "Allow user ($from) to subscribe to your ($to) presence?\n" .
1022                   "(Answer with the `yes' or `no' commands)";
1023    $props{yescommand} = "jroster auth $from -a $to";
1024    $props{nocommand} = "jroster deauth $from -a $to";
1025    $props{question} = "true";
1026    BarnOwl::queue_message(BarnOwl::Message->new(%props));
1027}
1028
1029sub process_presence_unsubscribe {
1030    my ( $sid, $p ) = @_;
1031    my $from = $p->GetFrom();
1032    my $to = $p->GetTo();
1033    my %props = (
1034        to => $to,
1035        from => $from,
1036        xml => $p->GetXML(),
1037        type => 'admin',
1038        adminheader => 'Jabber presence: unsubscribe',
1039        direction => 'in');
1040
1041    $props{body} = "The user ($from) has been unsubscribed from your ($to) presence.\n";
1042    BarnOwl::queue_message(BarnOwl::Message->new(%props));
1043
1044    # Find a connection to reply with.
1045    foreach my $jid ($conn->getJIDs()) {
1046        my $cJID = new Net::Jabber::JID;
1047        $cJID->SetJID($jid);
1048        if ($to eq $cJID->GetJID('base') ||
1049            $to eq $cJID->GetJID('full')) {
1050            my $reply = $p->Reply(type=>"unsubscribed");
1051            $conn->getConnectionFromJID($jid)->Send($reply);
1052            return;
1053        }
1054    }
1055}
1056
1057sub process_presence_subscribed {
1058    my ( $sid, $p ) = @_;
1059    queue_admin_msg("ignoring:".$p->GetXML());
1060    # RFC 3921 says we should respond to this with a "subscribe"
1061    # but this causes a flood of sub/sub'd presence packets with
1062    # some servers, so we won't. We may want to detect this condition
1063    # later, and have per-server settings.
1064    return;
1065}
1066
1067sub process_presence_unsubscribed {
1068    my ( $sid, $p ) = @_;
1069    queue_admin_msg("ignoring:".$p->GetXML());
1070    # RFC 3921 says we should respond to this with a "subscribe"
1071    # but this causes a flood of unsub/unsub'd presence packets with
1072    # some servers, so we won't. We may want to detect this condition
1073    # later, and have per-server settings.
1074    return;
1075}
1076
1077sub process_presence_error {
1078    my ( $sid, $p ) = @_;
1079    my $code = $p->GetErrorCode();
1080    my $error = $p->GetError();
1081    BarnOwl::error("Jabber: $code $error");
1082}
1083
1084
1085### Helper functions
1086
1087sub j2hash {
1088    my $j   = shift;
1089    my %initProps = %{ shift() };
1090
1091    my $dir = 'none';
1092    my %props = ( type => 'jabber' );
1093
1094    foreach my $k (keys %initProps) {
1095        $dir = $initProps{$k} if ($k eq 'direction');
1096        $props{$k} = $initProps{$k};
1097    }
1098
1099    my $jtype = $props{jtype} = $j->GetType();
1100    my $from = $j->GetFrom('jid');
1101    my $to   = $j->GetTo('jid');
1102
1103    $props{from} = $from->GetJID('full');
1104    $props{to}   = $to->GetJID('full');
1105
1106    $props{recipient}  = $to->GetJID('base');
1107    $props{sender}     = $from->GetJID('base');
1108    $props{subject}    = $j->GetSubject() if ( $j->DefinedSubject() );
1109    $props{thread}     = $j->GetThread() if ( $j->DefinedThread() );
1110    $props{body}       = $j->GetBody() if ( $j->DefinedBody() );
1111    $props{error}      = $j->GetError() if ( $j->DefinedError() );
1112    $props{error_code} = $j->GetErrorCode() if ( $j->DefinedErrorCode() );
1113    $props{xml}        = $j->GetXML();
1114
1115    if ( $jtype eq 'chat' ) {
1116        $props{replycmd} =
1117          "jwrite " . ( ( $dir eq 'in' ) ? $props{from} : $props{to} );
1118        $props{replycmd} .=
1119          " -a " . ( ( $dir eq 'out' ) ? $props{from} : $props{to} );
1120        $props{private} = 1;
1121
1122        my $connection;
1123        if ($dir eq 'in') {
1124            $connection = $conn->getConnectionFromSid($props{sid});
1125        }
1126        else {
1127            $connection = $conn->getConnectionFromJID($props{from});
1128        }
1129
1130        # Check to see if we're doing personals with someone in a muc.
1131        # If we are, show the full jid because the base jid is the room.
1132        if ($connection) {
1133            $props{sender} = $props{from}
1134              if ($connection->FindMUC(jid => $from));
1135            $props{recipient} = $props{to}
1136              if ($connection->FindMUC(jid => $to));
1137        }
1138    }
1139    elsif ( $jtype eq 'groupchat' ) {
1140        my $nick = $props{nick} = $from->GetResource();
1141        my $room = $props{room} = $from->GetJID('base');
1142        $props{replycmd} = "jwrite $room";
1143        $props{replycmd} .=
1144          " -a " . ( ( $dir eq 'out' ) ? $props{from} : $props{to} );
1145        if ($props{subject}) {
1146          $props{replycmd} .= " -s " . $props{subject}
1147        }
1148
1149        if ($dir eq 'out') {
1150            $props{replysendercmd} = "jwrite ".$props{to}." -a ".$props{from};
1151        }
1152        else {
1153            $props{replysendercmd} = "jwrite ".$props{from}." -a ".$props{to};
1154        }
1155
1156        $props{sender} = $nick || $room;
1157        $props{recipient} = $room;
1158
1159        if ( $props{subject} && !$props{body} ) {
1160            $props{body} =
1161              '[' . $nick . " has set the topic to: " . $props{subject} . "]";
1162        }
1163    }
1164    elsif ( $jtype eq 'normal' ) {
1165        $props{replycmd}  = "";
1166        $props{private} = 1;
1167    }
1168    elsif ( $jtype eq 'headline' ) {
1169        $props{replycmd} = "";
1170    }
1171    elsif ( $jtype eq 'error' ) {
1172        $props{replycmd} = "";
1173        $props{body}     = "Error "
1174          . $props{error_code}
1175          . " sending to "
1176          . $props{from} . "\n"
1177          . $props{error};
1178    }
1179
1180    $props{replysendercmd} = $props{replycmd} unless $props{replysendercmd};
1181    return %props;
1182}
1183
1184sub j2o {
1185    return BarnOwl::Message->new( j2hash(@_) );
1186}
1187
1188sub queue_admin_msg {
1189    my $err = shift;
1190    BarnOwl::admin_message("Jabber", $err);
1191}
1192
1193sub getServerFromJID {
1194    my $jid = shift;
1195    my $res = new Net::DNS::Resolver;
1196    my $packet =
1197      $res->search( '_xmpp-client._tcp.' . $jid->GetServer(), 'srv' );
1198
1199    if ($packet)    # Got srv record.
1200    {
1201        my @answer = $packet->answer;
1202        return $answer[0]{target}, $answer[0]{port};
1203    }
1204
1205    return $jid->GetServer(), 5222;
1206}
1207
1208sub defaultJID {
1209    return ( $conn->getJIDs() )[0] if ( $conn->connected() == 1 );
1210    return;
1211}
1212
1213sub baseJID {
1214    my $givenJIDStr = shift;
1215    my $givenJID    = new Net::Jabber::JID;
1216    $givenJID->SetJID($givenJIDStr);
1217    return $givenJID->GetJID('base');
1218}
1219
1220sub resolveConnectedJID {
1221    my $givenJIDStr = shift;
1222    my $givenJID    = new Net::Jabber::JID;
1223    $givenJID->SetJID($givenJIDStr);
1224
1225    # Account fully specified.
1226    if ( $givenJID->GetResource() ) {
1227        # Specified account exists
1228        return $givenJIDStr if ($conn->jidExists($givenJIDStr) );
1229        die("Invalid account: $givenJIDStr");
1230    }
1231
1232    # Disambiguate.
1233    else {
1234        my $matchingJID = "";
1235        my $errStr =
1236          "Ambiguous account reference. Please specify a resource.\n";
1237        my $ambiguous = 0;
1238
1239        foreach my $jid ( $conn->getJIDs() ) {
1240            my $cJID = new Net::Jabber::JID;
1241            $cJID->SetJID($jid);
1242            if ( $givenJIDStr eq $cJID->GetJID('base') ) {
1243                $ambiguous = 1 if ( $matchingJID ne "" );
1244                $matchingJID = $jid;
1245                $errStr .= "\t$jid\n";
1246            }
1247        }
1248
1249        # Need further disambiguation.
1250        if ($ambiguous) {
1251            die($errStr);
1252        }
1253
1254        # Not one of ours.
1255        elsif ( $matchingJID eq "" ) {
1256            die("Invalid account: $givenJIDStr");
1257        }
1258
1259        # It's this one.
1260        else {
1261            return $matchingJID;
1262        }
1263    }
1264    return "";
1265}
1266
1267sub resolveDestJID {
1268    my ($to, $from) = @_;
1269    my $jid = Net::Jabber::JID->new($to);
1270
1271    my $roster = $conn->getRosterFromJID($from);
1272    my @jids = $roster->jids('all');
1273    for my $j (@jids) {
1274        if(($roster->query($j, 'name') || $j->GetUserID()) eq $to) {
1275            return $j->GetJID('full');
1276        } elsif($j->GetJID('base') eq baseJID($to)) {
1277            return $jid->GetJID('full');
1278        }
1279    }
1280
1281    # If we found nothing being clever, check to see if our input was
1282    # sane enough to look like a jid with a UserID.
1283    return $jid->GetJID('full') if $jid->GetUserID();
1284    return undef;
1285}
1286
1287sub resolveType {
1288    my $to = shift;
1289    my $from = shift;
1290    return unless $from;
1291    my @mucs = $conn->getConnectionFromJID($from)->MUCs;
1292    if(grep {$_->BaseJID eq $to } @mucs) {
1293        return 'groupchat';
1294    } else {
1295        return 'chat';
1296    }
1297}
1298
1299sub guess_jwrite {
1300    # Heuristically guess what jids a jwrite was meant to be going to/from
1301    my ($from, $to) = (@_);
1302    my ($from_jid, $to_jid);
1303    my @matches;
1304    if($from) {
1305        $from_jid = resolveConnectedJID($from);
1306        die("Unable to resolve account $from") unless $from_jid;
1307        $to_jid = resolveDestJID($to, $from_jid);
1308        push @matches, [$from_jid, $to_jid] if $to_jid;
1309    } else {
1310        for my $f ($conn->getJIDs) {
1311            $to_jid = resolveDestJID($to, $f);
1312            if(defined($to_jid)) {
1313                push @matches, [$f, $to_jid];
1314            }
1315        }
1316        if($to =~ /@/) {
1317            push @matches, [$_, $to]
1318               for ($conn->getJIDs);
1319        }
1320    }
1321
1322    for my $m (@matches) {
1323        my $type = resolveType($m->[1], $m->[0]);
1324        push @$m, $type;
1325    }
1326
1327    return @matches;
1328}
1329
13301;
Note: See TracBrowser for help on using the repository browser.