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

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