Compare commits

..

11 Commits
1.2.5 ... 1.3.0

Author SHA1 Message Date
Govindas
2140cd67ff Update README.md 2020-11-28 10:14:19 +02:00
Govindas
e9ae0bd50b Update README.md 2020-11-28 10:12:11 +02:00
Govindass
6ea120a85a Optimizations 2020-11-28 10:02:14 +02:00
Govindass
01525e4d63 Merge branch 'master' of https://github.com/Limework/RediSkript 2020-11-26 17:05:11 +02:00
Govindass
c63495e201 Some more work on variables (Still very unfinished) 2020-11-26 17:05:07 +02:00
Govindas
265dbfa84d Remove to-do list from readme (refer to issues) 2020-11-25 17:07:30 +02:00
Govindass
6f600cc96e Add cross-server variable editing (I'll make it use {} instead of strings later) 2020-11-25 17:01:11 +02:00
Govindass
1b151dfbbe Allow sending multiple redis messages in one go 2020-11-25 13:53:52 +02:00
Govindass
afdb0c3e59 Fix rare error on disable 2020-11-25 13:18:23 +02:00
Govindass
ca64ec19db Fix wrong prefix coloring in command 2020-11-12 12:36:12 +02:00
Govindass
c0bd63e3cd test 2020-11-03 12:23:00 +02:00
10 changed files with 237 additions and 77 deletions

2
.gitignore vendored
View File

@@ -1,4 +1,4 @@
target target
out out
.idea/workspace.xml .idea
compile compile

View File

@@ -1,6 +1,6 @@
<component name="ArtifactManager"> <component name="ArtifactManager">
<artifact type="jar" build-on-make="true" name="RediSkript:jar"> <artifact type="jar" build-on-make="true" name="RediSkript:jar">
<output-path>$PROJECT_DIR$/out/artifacts/RediSkript_jar</output-path> <output-path>$PROJECT_DIR$/../../Govindo/testserver/plugins</output-path>
<root id="archive" name="RediSkript.jar"> <root id="archive" name="RediSkript.jar">
<element id="module-output" name="RediSkript" /> <element id="module-output" name="RediSkript" />
<element id="extracted-dir" path="$MAVEN_REPOSITORY$/org/cryptomator/siv-mode/1.4.0/siv-mode-1.4.0.jar" path-in-jar="/" /> <element id="extracted-dir" path="$MAVEN_REPOSITORY$/org/cryptomator/siv-mode/1.4.0/siv-mode-1.4.0.jar" path-in-jar="/" />

View File

@@ -1,14 +1,11 @@
**To-do List**
1. Fix memory leak of /reloadredis (Not yet known how to fix it, it can be easily noticed by changing IP addresses and using NetworkInterceptor plugin, it'll show connections still being done to old IP address, aswell as the new one, even if it doesn't use old IP address for anything.)
RediSkript allows you to communicate between your servers with use of Redis, it's very fast and easy to use. RediSkript allows you to communicate between your servers with use of Redis, it's very fast and easy to use.
You can transfer any data in the form of text between your servers, you can program it to execute a set of instructions on the server depending on the redis message, etc. This can be used for making scripts that sync data between all servers and much more! You can transfer any data in the form of text between your servers, you can program it to execute a set of instructions on the server depending on the redis message, etc. This can be used for making scripts that sync data between all servers and much more!
It is originally developed by the team of Govindas Limework developers and is now maintained only by Govindas. It is originally developed by the team of Govindas Limework developers and is now maintained only by Govindas.
Example:
Redis Message:
``` ```
on redis message: on redis message:
if redis channel is "world": if redis channel is "world":
@@ -20,8 +17,26 @@ command /sendredis <text> <text>:
send redis message arg 1 to channel arg 2 send redis message arg 1 to channel arg 2
send redis message "hello world!" to channel "world" send redis message "hello world!" to channel "world"
``` ```
Managing variables:
```
set variables "test::1", "test::2", "test::3" in channel "global" to 100
#then use this in any server that listens to "global" redis channel and was online when the above line was executed:
send "%{test::*}%" #outputs 100, 100 and 100
and that's all there is to this addon! You only need to have matching configuration in every server for communication and a Redis server to connect to. I recommend using VPS for hosting redis server, I personally use VPS from humbleservers.com. delete variables "test::*" in channel "global"
set variable "test::%uuid of player%" in channel "playerdata" to tool of player
#then you can in any server that is listening to "playerdata" channel and was online when the above line was executed:
give {test::%uuid of player%} to player
```
Syntax:
```
variable[s] %strings% in [redis] [channel] %string%
```
There is only one command: /reloadredis it fully reloads the configuration, you can reload IP, password, channels and everything else.
You only need to have matching configuration in every server for communication and a Redis server to connect to. I recommend using VPS for hosting redis server, I personally use VPS from humbleservers.com.
Configuration: Configuration:
``` ```

View File

@@ -6,7 +6,7 @@
<groupId>net.limework.rediskript</groupId> <groupId>net.limework.rediskript</groupId>
<artifactId>RediSkript</artifactId> <artifactId>RediSkript</artifactId>
<version>1.2.5</version> <version>1.3.0</version>
<packaging>jar</packaging> <packaging>jar</packaging>
<build> <build>

View File

@@ -1,15 +1,13 @@
package net.limework.rediskript; package net.limework.rediskript;
import net.limework.rediskript.commands.CommandReloadRedis; import net.limework.rediskript.commands.CommandReloadRedis;
import net.limework.rediskript.skript.SkriptHook;
import net.limework.rediskript.managers.RedisManager; import net.limework.rediskript.managers.RedisManager;
import org.bukkit.Bukkit; import net.limework.rediskript.skript.SkriptHook;
import org.bukkit.command.PluginCommand; import org.bukkit.command.PluginCommand;
import org.bukkit.event.EventHandler; import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority; import org.bukkit.event.EventPriority;
import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.plugin.java.JavaPlugin;
import java.util.concurrent.TimeUnit;
public class RediSkript extends JavaPlugin { public class RediSkript extends JavaPlugin {
//Redis manager //Redis manager

View File

@@ -18,7 +18,7 @@ public class CommandReloadRedis implements CommandExecutor {
if (sender instanceof Player) { if (sender instanceof Player) {
//not using bungee TextComponent because it is not present in 1.8.8 //not using bungee TextComponent because it is not present in 1.8.8
sender.sendMessage((ChatColor.translateAlternateColorCodes('&' sender.sendMessage((ChatColor.translateAlternateColorCodes('&'
, "&2[&aRediSkript&a] &cThis command can only be executed in console."))); , "&2[&aRediSkript&2] &cThis command can only be executed in console.")));
return true; return true;
} }
plugin.getRm().reload(); plugin.getRm().reload();

View File

@@ -1,29 +1,33 @@
package net.limework.rediskript.managers; package net.limework.rediskript.managers;
import ch.njol.skript.registrations.Classes;
import ch.njol.skript.variables.Variables;
import net.limework.rediskript.RediSkript; import net.limework.rediskript.RediSkript;
import net.limework.rediskript.events.RedisMessageEvent;
import net.limework.rediskript.data.Encryption; import net.limework.rediskript.data.Encryption;
import net.limework.rediskript.events.RedisMessageEvent;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.ChatColor; import org.bukkit.ChatColor;
import org.bukkit.configuration.Configuration; import org.bukkit.configuration.Configuration;
import org.cryptomator.siv.UnauthenticCiphertextException; import org.cryptomator.siv.UnauthenticCiphertextException;
import org.json.JSONArray;
import org.json.JSONObject; import org.json.JSONObject;
import redis.clients.jedis.BinaryJedis; import redis.clients.jedis.BinaryJedis;
import redis.clients.jedis.BinaryJedisPubSub; import redis.clients.jedis.BinaryJedisPubSub;
import redis.clients.jedis.JedisPool; import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig; import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.exceptions.JedisConnectionException;
import javax.crypto.IllegalBlockSizeException; import javax.crypto.IllegalBlockSizeException;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.List; import java.util.List;
import java.util.concurrent.ExecutorService; import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicBoolean;
public class RedisManager extends BinaryJedisPubSub implements Runnable { public class RedisManager extends BinaryJedisPubSub implements Runnable {
private final ExecutorService RedisReconnector; private ExecutorService RedisReconnector;
private RediSkript plugin; private RediSkript plugin;
private JedisPool jedisPool; private JedisPool jedisPool;
@@ -71,7 +75,7 @@ public class RedisManager extends BinaryJedisPubSub implements Runnable {
@Override @Override
public void run() { public void run() {
while (!isShuttingDown.get()) { while (!isShuttingDown.get() && plugin.isEnabled()) {
try { try {
plugin.getLogger().info(ChatColor.translateAlternateColorCodes('&', "&cConnecting to redis...")); plugin.getLogger().info(ChatColor.translateAlternateColorCodes('&', "&cConnecting to redis..."));
if (!this.subscribeJedis.isConnected()) this.subscribeJedis = this.jedisPool.getResource(); if (!this.subscribeJedis.isConnected()) this.subscribeJedis = this.jedisPool.getResource();
@@ -98,6 +102,9 @@ public class RedisManager extends BinaryJedisPubSub implements Runnable {
} catch (Exception e) { } catch (Exception e) {
if (isShuttingDown.get() || !plugin.isEnabled()) {
return;
}
plugin.getLogger().warning(ChatColor.translateAlternateColorCodes('&', "&cConnection to redis has failed! &cReconnecting...")); plugin.getLogger().warning(ChatColor.translateAlternateColorCodes('&', "&cConnection to redis has failed! &cReconnecting..."));
if (this.subscribeJedis != null) { if (this.subscribeJedis != null) {
this.subscribeJedis.close(); this.subscribeJedis.close();
@@ -128,16 +135,62 @@ public class RedisManager extends BinaryJedisPubSub implements Runnable {
//encryption is disabled, so let's just get the string //encryption is disabled, so let's just get the string
receivedMessage = new String(message, StandardCharsets.UTF_8); receivedMessage = new String(message, StandardCharsets.UTF_8);
} }
if (receivedMessage != null) { if (receivedMessage != null) {
JSONObject j = new JSONObject(receivedMessage); JSONObject j = new JSONObject(receivedMessage);
//System.out.println("Message got from channel: "+channel +" and the Message: " +json.toString()); if (j.get("Type").equals("Skript")) {
RedisMessageEvent event = new RedisMessageEvent(channelString, j.getString("Message"), j.getLong("Date")); JSONArray messages = j.getJSONArray("Messages");
RedisMessageEvent event;
for (int i = 0; i < messages.length(); i++) {
event = new RedisMessageEvent(channelString, messages.get(i).toString(), j.getLong("Date"));
//if plugin is disabling, don't call events anymore
if (plugin.isEnabled()) {
RedisMessageEvent finalEvent = event;
Bukkit.getScheduler().runTask(plugin, () -> plugin.getServer().getPluginManager().callEvent(finalEvent));
}
}
} else if (j.get("Type").equals("SkriptVariables")) {
//if plugin is disabling, don't call events anymore //Transfer variables between servers
if (plugin.isEnabled()) { JSONArray variableNames = j.getJSONArray("Names");
Bukkit.getScheduler().runTask(plugin, () -> plugin.getServer().getPluginManager().callEvent(event)); Object inputValue;
String changeValue = null;
JSONArray variableValues = null;
if (!j.isNull("Values")) {
variableValues = j.getJSONArray("Values");
}
for (int i = 0; i < variableNames.length(); i++) {
if (j.isNull("Values")) {
//only check for SET here, because null has to be ignored in all other cases
if (j.getString("Operation").equals("SET")) {
Variables.setVariable(variableNames.get(i).toString(), null, null, false);
}
} else {
if (!variableValues.isNull(i)) {
changeValue = variableValues.get(i).toString();
}
String[] inputs = changeValue.split("\\^", 2);
inputValue = Classes.deserialize(inputs[0], Base64.getDecoder().decode(inputs[1]));
switch (j.getString("Operation")) {
case "ADD":
//I will add this once someone tells me how to remove from Skript variable
//because using SET operation has issues with inconvertible types (Double and Long)
//variable = (Variable) Variables.getVariable(variableNames.get(i).toString(), null, false);
// variable.change(null, (Object[]) inputValue, Changer.ChangeMode.REMOVE);
case "REMOVE":
//I will add this once someone tells me how to remove from Skript variable
//because using SET operation has issues with inconvertible types (Double and Long)
//variable = (Variable) Variables.getVariable(variableNames.get(i).toString(), null, false);
// variable.change(null, (Object[]) inputValue, Changer.ChangeMode.REMOVE);
break;
case "SET":
Variables.setVariable(variableNames.get(i).toString(), inputValue, null, false);
}
}
}
} }
} }
} catch (Exception e) { } catch (Exception e) {
@@ -147,13 +200,56 @@ public class RedisManager extends BinaryJedisPubSub implements Runnable {
} }
} }
public void sendMessage(String[] message, String channel) {
JSONObject json = new JSONObject();
json.put("Messages", new JSONArray(message));
json.put("Type", "Skript");
json.put("Date", System.currentTimeMillis()); //for unique string every time & PING calculations
finishSendMessage(json, channel);
}
public void sendVariables(String[] variableNames, String[] variableValues, String channel, String operation) {
JSONObject json = new JSONObject();
json.put("Names", new JSONArray(variableNames));
if (variableValues != null) {
json.put("Values", new JSONArray(variableValues));
}
json.put("Type", "SkriptVariables");
json.put("Date", System.currentTimeMillis()); //for unique string every time & PING calculations
json.put("Operation", operation);
finishSendMessage(json, channel);
}
public void finishSendMessage(JSONObject json, String channel) {
try {
byte[] message;
if (this.getEncryption().isEncryptionEnabled()) {
message = this.getEncryption().encrypt(json.toString());
} else {
message = json.toString().getBytes(StandardCharsets.UTF_8);
}
//execute sending of redis message on the main thread if plugin is disabling
//so it can still process the sending
//sending a redis message blocks main thread if there's no more connections available
//so to avoid issues, it's best to do it always on separate thread
if (plugin.isEnabled()) {
this.getRedisService().execute(() -> {
BinaryJedis j = this.getJedisPool().getResource();
j.publish(channel.getBytes(StandardCharsets.UTF_8), message);
j.close();
});
} else {
BinaryJedis j = this.getJedisPool().getResource();
j.publish(channel.getBytes(StandardCharsets.UTF_8), message);
j.close();
}
} catch (JedisConnectionException exception) {
exception.printStackTrace();
}
}
public void shutdown() { public void shutdown() {
try {
this.RedisService.awaitTermination(1, TimeUnit.SECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
this.isShuttingDown.set(true); this.isShuttingDown.set(true);
if (this.subscribeJedis != null) { if (this.subscribeJedis != null) {
this.unsubscribe(); this.unsubscribe();
@@ -161,8 +257,11 @@ public class RedisManager extends BinaryJedisPubSub implements Runnable {
this.subscribeJedis.getClient().close(); this.subscribeJedis.getClient().close();
this.jedisPool.getResource().close(); this.jedisPool.getResource().close();
} }
isShuttingDown.set(true);
this.RedisReconnector.shutdown(); this.RedisReconnector.shutdown();
this.RedisService.shutdown(); this.RedisService.shutdown();
this.RedisService = null;
this.RedisReconnector = null;
} }
public void reload() { public void reload() {

View File

@@ -6,12 +6,10 @@ import ch.njol.skript.lang.ExpressionType;
import ch.njol.skript.registrations.EventValues; import ch.njol.skript.registrations.EventValues;
import ch.njol.skript.util.Date; import ch.njol.skript.util.Date;
import ch.njol.skript.util.Getter; import ch.njol.skript.util.Getter;
import ch.njol.skript.util.Timespan;
import net.limework.rediskript.RediSkript; import net.limework.rediskript.RediSkript;
import net.limework.rediskript.events.RedisMessageEvent; import net.limework.rediskript.events.RedisMessageEvent;
import net.limework.rediskript.skript.elements.EvtRedis; import net.limework.rediskript.skript.elements.*;
import net.limework.rediskript.skript.elements.ExprChannel;
import net.limework.rediskript.skript.elements.ExprMessage;
import net.limework.rediskript.skript.elements.ExprMessageDate;
import java.io.IOException; import java.io.IOException;
@@ -21,6 +19,8 @@ public class SkriptHook {
try { try {
addon.loadClasses("net.limework.rediskript.skript", "elements"); addon.loadClasses("net.limework.rediskript.skript", "elements");
Skript.registerEvent("redis message", EvtRedis.class, RedisMessageEvent.class, "redis message"); Skript.registerEvent("redis message", EvtRedis.class, RedisMessageEvent.class, "redis message");
Skript.registerExpression(ExprVariableInChannel.class, Object.class, ExpressionType.PROPERTY, "variable[s] %strings% in [redis] [channel] %string%");
Skript.registerExpression(ExprChannel.class, String.class, ExpressionType.SIMPLE, "redis channel"); Skript.registerExpression(ExprChannel.class, String.class, ExpressionType.SIMPLE, "redis channel");
EventValues.registerEventValue(RedisMessageEvent.class, String.class, new Getter<String, RedisMessageEvent>() { EventValues.registerEventValue(RedisMessageEvent.class, String.class, new Getter<String, RedisMessageEvent>() {
@Override @Override

View File

@@ -6,19 +6,13 @@ import ch.njol.skript.lang.Expression;
import ch.njol.skript.lang.SkriptParser; import ch.njol.skript.lang.SkriptParser;
import ch.njol.util.Kleenean; import ch.njol.util.Kleenean;
import net.limework.rediskript.RediSkript; import net.limework.rediskript.RediSkript;
import net.limework.rediskript.managers.RedisManager;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.ChatColor; import org.bukkit.ChatColor;
import org.bukkit.event.Event; import org.bukkit.event.Event;
import org.json.JSONObject;
import redis.clients.jedis.BinaryJedis;
import redis.clients.jedis.exceptions.JedisConnectionException;
import java.nio.charset.StandardCharsets;
public class EffSendMessage extends Effect { public class EffSendMessage extends Effect {
static { static {
Skript.registerEffect(EffSendMessage.class, "send redis message %string% to [channel] %string%"); Skript.registerEffect(EffSendMessage.class, "send redis message[s] %strings% to [channel] %string%");
} }
@@ -31,10 +25,9 @@ public class EffSendMessage extends Effect {
RediSkript plugin = (RediSkript) Bukkit.getPluginManager().getPlugin("RediSkript"); RediSkript plugin = (RediSkript) Bukkit.getPluginManager().getPlugin("RediSkript");
String message = this.message.getSingle(event); String[] message = this.message.getAll(event);
String channel = this.channel.getSingle(event); String channel = this.channel.getSingle(event);
if (message[0] == null) {
if (message == null) {
Bukkit.getLogger().warning(ChatColor.translateAlternateColorCodes('&', "&2[&aRediSkript&a] &cRedis message was empty. Please check your code.")); Bukkit.getLogger().warning(ChatColor.translateAlternateColorCodes('&', "&2[&aRediSkript&a] &cRedis message was empty. Please check your code."));
return; return;
} }
@@ -42,40 +35,7 @@ public class EffSendMessage extends Effect {
Bukkit.getLogger().warning(ChatColor.translateAlternateColorCodes('&', "&2[&aRediSkript&a] &cChannel was empty. Please check your code.")); Bukkit.getLogger().warning(ChatColor.translateAlternateColorCodes('&', "&2[&aRediSkript&a] &cChannel was empty. Please check your code."));
return; return;
} }
assert plugin != null; plugin.getRm().sendMessage(message, channel);
JSONObject json = new JSONObject();
json.put("Message", message);
json.put("Type", "Skript");
json.put("Date", System.currentTimeMillis()); //for unique string every time & PING calculations
byte[] msg;
RedisManager manager = plugin.getRm();
if (manager.getEncryption().isEncryptionEnabled()) {
msg = manager.getEncryption().encrypt(json.toString());
} else {
msg = json.toString().getBytes(StandardCharsets.UTF_8);
}
try {
//execute sending of redis message on the main thread if plugin is disabling
//so it can still process the sending
//sending a redis message blocks main thread if there's no more connections available
//so to avoid issues, it's best to do it always on separate thread
if (plugin.isEnabled()) {
manager.getRedisService().execute(() -> {
BinaryJedis j = manager.getJedisPool().getResource();
j.publish(channel.getBytes(StandardCharsets.UTF_8), msg);
j.close();
});
} else {
BinaryJedis j = manager.getJedisPool().getResource();
j.publish(channel.getBytes(StandardCharsets.UTF_8), msg);
j.close();
}
} catch (JedisConnectionException exception) {
exception.printStackTrace();
}
} }
@Override @Override

View File

@@ -0,0 +1,88 @@
package net.limework.rediskript.skript.elements;
import ch.njol.skript.classes.Changer;
import ch.njol.skript.lang.Expression;
import ch.njol.skript.lang.SkriptParser;
import ch.njol.skript.lang.util.SimpleExpression;
import ch.njol.skript.registrations.Classes;
import ch.njol.skript.variables.SerializedVariable;
import ch.njol.util.Kleenean;
import ch.njol.util.coll.CollectionUtils;
import net.limework.rediskript.RediSkript;
import org.bukkit.Bukkit;
import org.bukkit.event.Event;
import java.util.Base64;
public class ExprVariableInChannel extends SimpleExpression<Object> {
private Expression<String> name;
private Expression<String> channel;
@Override
public boolean init(Expression<?>[] expressions, int matchedPattern, Kleenean isDelayed, SkriptParser.ParseResult parser) {
//if (expressions[0] instanceof Variable) {
// Variable<?> variable = (Variable<?>) expressions[0];
// System.out.println(variable.getName().toString());
// String var = variable.getName().toString();
// var = var.substring(1, var.length() - 1);
//}
name = (Expression<String>) expressions[0];
channel = (Expression<String>) expressions[1];
return true;
}
@Override
protected Object[] get(Event event) {
return null;
}
@Override
public boolean isSingle() {
return true;
}
@Override
public Class<? extends Object> getReturnType() {
return Object.class;
}
@Override
public String toString(Event event, boolean b) {
return "variable in redis channel";
}
@Override
public void change(Event e, Object[] changer, Changer.ChangeMode mode) {
RediSkript plugin = (RediSkript) Bukkit.getPluginManager().getPlugin("RediSkript");
switch (mode) {
case ADD:
case SET:
case REMOVE:
SerializedVariable.Value serialized;
String encoded;
String[] values = new String[changer.length+1];
for( int i = 0; i < changer.length; i++) {
if (changer[i] != null) {
serialized = Classes.serialize(changer[i]);
encoded = Base64.getEncoder().encodeToString(serialized.data);
encoded = serialized.type + "^" + encoded;
values[i] = encoded;
}
}
String operation = mode.toString();
plugin.getRm().sendVariables(name.getAll(e), values, channel.getSingle(e), operation);
break;
case DELETE:
plugin.getRm().sendVariables(name.getAll(e), null, channel.getSingle(e), "SET");
break;
}
}
@Override
public Class<?>[] acceptChange(Changer.ChangeMode mode) {
//if (mode == Changer.ChangeMode.DELETE || mode == Changer.ChangeMode.SET || mode == Changer.ChangeMode.ADD || mode == Changer.ChangeMode.REMOVE)
if (mode == Changer.ChangeMode.DELETE || mode == Changer.ChangeMode.SET)
return CollectionUtils.array(Object.class);
return null;
}
}