rename operations to !(un)track pattern
[MQR.git] / scripts / mqr-xmpp-client.pl
index b07cb93..f7379a4 100755 (executable)
@@ -8,6 +8,8 @@ use AnyEvent::XMPP::Ext::Disco;
 use AnyEvent::XMPP::Ext::Version;
 use AnyEvent::XMPP::Namespaces qw/xmpp_ns/;
 use AnyEvent::Redis;
+use Storable;
+use Data::Dump qw(dump);
 
 binmode STDOUT, ":utf8";
 
@@ -32,6 +34,38 @@ warn "connecting to $jid...\n";
 my $pub = AnyEvent::Redis->new( host => $redis_host, port => $redis_port );
 my $sub = AnyEvent::Redis->new( host => $redis_host, port => $redis_port );
 
+my $track = eval { retrieve '/tmp/track' };
+
+sub track {
+       my ( $who, $to, $value ) = @_;
+       warn "# ${value}track $who $to\n";
+
+       if ( $value ) {
+
+               $track->{$who}->{$to} = time;
+
+               $sub->psubscribe( "channel $to", sub {
+                       my ( $message, $from ) = @_;
+                       return unless $from !~ m/\Q($to|$jid)\E/; # skip our messages
+                       warn "#Q<< $from [$jid] | $message\n";
+                       my ( undef, $channel, $user ) = split(/ /,$from,3);
+                       $cl->send_message( "$channel <$user> $message", $who => $jid, 'chat' );
+               });
+
+       } else {
+               delete $track->{$who}->{$to};
+               $sub->punsubscribe( "channel $to");
+       }
+
+       store $track, '/tmp/track';
+}
+
+foreach my $who ( keys %$track ) {
+       foreach my $to ( keys %{ $track->{$who} } ) {
+               track $who => $to, time;
+       }
+}
+
 $cl->reg_cb (
    session_ready => sub {
       my ($cl, $acc) = @_;
@@ -40,7 +74,7 @@ $cl->reg_cb (
    message => sub {
                my ($cl, $acc, $msg) = @_;
 
-               my $response = '...';
+               my $response;
 
                my $body = $msg->any_body;
 
@@ -48,18 +82,11 @@ $cl->reg_cb (
                $pub->publish( $channel, $body );
                warn "#X<< $channel | $body\n";
 
-               if ( $msg =~ m/!subscribe\s+(\S+)/ ) {
-
-                       $sub->psubscribe( "channel $1", sub {
-                               my ( $message, $from ) = @_;
-                               return unless $from !~ m/\Q$jid\E/; # skip our messages
-                               warn "#Q<< $from | $message\n";
-                               my ( undef, $channal, $user ) = split(/ /,$from,3);
-                               $cl->send_message( "$channel <$user> $message" => $msg->from, $jid, 'chat' );
-                       });
-
-                       $response = "subscribed to $1";
-
+               if ( $msg =~ m/^!(un)?track\s+(\S+)/ ) {
+                       track $msg->from => $2, $1 ? 0 : 1;
+                       $response = "track: " . dump( $track->{$msg->from} );
+               } elsif ( $msg =~ m/^!/ ) {
+                       $response = "UNKNOWN $msg";
                }
 
                my $repl = $msg->make_reply;