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

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