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

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