source: perl/modules/jabber.pl @ b2648bc

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