source: perl/modules/jabber.pl @ 25729b2

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