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

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