source: perl/modules/jabber.pl @ 0da506c

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