source: perl/modules/jabber.pl @ ac1bbe2

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