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

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