source: perl/modules/jabber.pl @ 45d9eb0

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