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

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