Skip to content

Commit

Permalink
Add ProxyboundGiveNitroSaraMessage and ToggleNitroSaraPacket
Browse files Browse the repository at this point in the history
  • Loading branch information
acrylic-style committed Jul 7, 2022
1 parent 7b1bc09 commit 868bf66
Show file tree
Hide file tree
Showing 35 changed files with 955 additions and 49 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,17 @@
import net.azisaba.azipluginmessaging.api.entity.PlayerAdapter;
import net.azisaba.azipluginmessaging.api.protocol.PacketQueue;
import net.azisaba.azipluginmessaging.api.server.PacketSender;
import net.azisaba.azipluginmessaging.api.util.SQLThrowableConsumer;
import net.azisaba.azipluginmessaging.api.yaml.YamlObject;
import org.intellij.lang.annotations.Language;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;

import java.sql.PreparedStatement;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;

public interface AziPluginMessaging {
/**
Expand Down Expand Up @@ -56,7 +63,28 @@ public interface AziPluginMessaging {
@NotNull
PacketQueue getPacketQueue();

/**
* Returns the environment which the plugin is running.
* @return the environment
*/
@NotNull
EnvironmentType getEnvironmentType();

interface Proxy {
@ApiStatus.Internal
default void loadConfig(@NotNull YamlObject obj) {
throw new UnsupportedOperationException("Unsupported in current environment.");
}

@Contract
default @NotNull CompletableFuture<Void> runPreparedStatement(@Language("SQL") @NotNull String sql, @NotNull SQLThrowableConsumer<PreparedStatement> action) {
throw new UnsupportedOperationException("Unsupported in current environment.");
}

@Contract
default void checkRankAsync(@NotNull UUID uuid) {
throw new UnsupportedOperationException("Unsupported in current environment.");
}
}

interface Server {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ public class AziPluginMessagingConfig {
public static final Map<String, String> servers = new ConcurrentHashMap<>();
public static final Map<String, String> saraShowServers = new ConcurrentHashMap<>();
public static final Map<String, String> rankableServers = new ConcurrentHashMap<>();
public static final Map<String, String> contextualServers = new ConcurrentHashMap<>();

/**
* Reloads all configuration from config file.
Expand Down Expand Up @@ -91,7 +92,39 @@ public static void reload() {
"# When the proxy receives a packet from non-enabled server, the proxy will drop the packet.",
"rankableServers: # this is meaningless in spigot",
" life: life",
" lifepve: life"
" lifepve: life",
"",
"# for ProxyboundSetPrefixPacket and ProxyboundClearPrefixPacket",
"contextualServers:",
" life: life",
" lifepve: life",
"",
"# Database settings (required)",
"# This setting is used for setting the rank temporary.",
"database:",
" # (scheme)://(host):(port)/(database)",
" # Keep the line commented out unless you get an obvious error message indicating that the driver was not found.",
" # Default driver (net.azisaba.taxoffice.libs.org.mariadb.jdbc.Driver) points to the bundled MariaDB driver in the TaxOffice jar.",
" #driver: net.azisaba.taxoffice.libs.org.mariadb.jdbc.Driver",
"",
" # change to jdbc:mysql if you want to use MySQL instead of MariaDB",
" scheme: jdbc:mariadb",
" hostname: localhost",
" port: 3306",
" name: azipm",
" username: azipm",
" password: azipm",
" properties:",
" useSSL: true",
" verifyServerCertificate: true",
" prepStmtCacheSize: 250",
" prepStmtCacheSqlLimit: 2048",
" cachePrepStmts: true",
" useServerPrepStmts: true # use server-side prepared statements for performance boost",
" socketTimeout: 30000 # milliseconds",
" useLocalSessionState: true",
" rewriteBatchedStatements: true",
" maintainTimeStats: false"
),
StandardOpenOption.CREATE
);
Expand All @@ -102,9 +135,13 @@ public static void reload() {
try {
YamlObject obj = new YamlConfiguration(configPath.toAbsolutePath().toString()).asObject();
debug = obj.getBoolean("debug", false);
readMap(servers, obj, "servers");
readMap(rankableServers, obj, "rankableServers");
readMap(saraShowServers, obj, "saraShowServers");
if (AziPluginMessagingProvider.get().getEnvironmentType() == EnvironmentType.VELOCITY) {
readMap(servers, obj, "servers");
readMap(rankableServers, obj, "rankableServers");
readMap(saraShowServers, obj, "saraShowServers");
readMap(contextualServers, obj, "contextualServers");
AziPluginMessagingProvider.get().getProxy().loadConfig(obj);
}
} catch (IOException ex) {
Logger.getCurrentLogger().warn("Failed to read config.yml", ex);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ public final class AziPluginMessagingProvider {
" - the AziPluginMessaging plugin is not installed or threw exception while initializing\n" +
" - the plugin is not in the dependency of the plugin in the stacktrace\n" +
" - tried to access the API before the plugin is loaded (such as constructor)\n" +
" Call #get() in the plugin's onEnable() method to load the API correctly!";
" Call #get() in the plugin's onEnable() method (or equivalent one) to load the API correctly!";

private static AziPluginMessaging api;

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
package net.azisaba.azipluginmessaging.api;

public enum EnvironmentType {
SPIGOT,
VELOCITY,
}
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ public void error(@NotNull String message, Throwable throwable) {
}

/**
* Returns the currently active logger. If no logger is active, a default logger is returned.
* Returns the logger on the current environment. Returns a default one if the plugin is not yet enabled.
* @return the logger
*/
static @NotNull Logger getCurrentLogger() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,12 @@
import net.azisaba.azipluginmessaging.api.protocol.handler.ProxyboundClearPrefixPacket;
import net.azisaba.azipluginmessaging.api.protocol.handler.ProxyboundEncryptionPacket;
import net.azisaba.azipluginmessaging.api.protocol.handler.ProxyboundGiveGamingSaraPacket;
import net.azisaba.azipluginmessaging.api.protocol.handler.ProxyboundGiveNitroSaraPacket;
import net.azisaba.azipluginmessaging.api.protocol.handler.ProxyboundGiveSaraPacket;
import net.azisaba.azipluginmessaging.api.protocol.handler.ProxyboundSetPrefixPacket;
import net.azisaba.azipluginmessaging.api.protocol.handler.ProxyboundSetRankPacket;
import net.azisaba.azipluginmessaging.api.protocol.handler.ProxyboundToggleGamingSaraPacket;
import net.azisaba.azipluginmessaging.api.protocol.handler.ProxyboundToggleNitroSaraPacket;
import net.azisaba.azipluginmessaging.api.protocol.handler.ProxyboundToggleSaraHidePacket;
import net.azisaba.azipluginmessaging.api.protocol.handler.ProxyboundToggleSaraShowPacket;
import net.azisaba.azipluginmessaging.api.protocol.handler.ServerMessageHandler;
Expand All @@ -22,6 +24,7 @@
import net.azisaba.azipluginmessaging.api.protocol.message.PlayerMessage;
import net.azisaba.azipluginmessaging.api.protocol.message.PlayerWithServerMessage;
import net.azisaba.azipluginmessaging.api.protocol.message.ProxyboundClearPrefixMessage;
import net.azisaba.azipluginmessaging.api.protocol.message.ProxyboundGiveNitroSaraMessage;
import net.azisaba.azipluginmessaging.api.protocol.message.ProxyboundGiveSaraMessage;
import net.azisaba.azipluginmessaging.api.protocol.message.ProxyboundSetPrefixMessage;
import net.azisaba.azipluginmessaging.api.protocol.message.ProxyboundSetRankMessage;
Expand Down Expand Up @@ -65,6 +68,8 @@ public final class Protocol<T extends MessageHandler<M>, M extends Message> {
public static final Protocol<ProxyboundToggleSaraShowPacket, PlayerWithServerMessage> P_TOGGLE_SARA_SHOW = new Protocol<>(PacketFlow.TO_PROXY, 0x06, new ProxyboundToggleSaraShowPacket()); // contextual
public static final Protocol<ProxyboundSetPrefixPacket, ProxyboundSetPrefixMessage> P_SET_PREFIX = new Protocol<>(PacketFlow.TO_PROXY, 0x07, new ProxyboundSetPrefixPacket());
public static final Protocol<ProxyboundClearPrefixPacket, ProxyboundClearPrefixMessage> P_CLEAR_PREFIX = new Protocol<>(PacketFlow.TO_PROXY, 0x08, new ProxyboundClearPrefixPacket());
public static final Protocol<ProxyboundGiveNitroSaraPacket, ProxyboundGiveNitroSaraMessage> P_GIVE_NITRO_SARA = new Protocol<>(PacketFlow.TO_PROXY, 0x09, new ProxyboundGiveNitroSaraPacket());
public static final Protocol<ProxyboundToggleNitroSaraPacket, PlayerMessage> P_TOGGLE_NITRO_SARA = new Protocol<>(PacketFlow.TO_PROXY, 0x0A, new ProxyboundToggleNitroSaraPacket());

public static final Protocol<ServerboundEncryptionPacket, EncryptionMessage> S_ENCRYPTION = new Protocol<>(PacketFlow.TO_SERVER, 0x00, new ServerboundEncryptionPacket());
public static final Protocol<ServerboundActionResponsePacket, ServerboundActionResponseMessage> S_ACTION_RESPONSE = new Protocol<>(PacketFlow.TO_SERVER, 0x01, new ServerboundActionResponsePacket());
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package net.azisaba.azipluginmessaging.api.protocol.handler;

import net.azisaba.azipluginmessaging.api.AziPluginMessagingConfig;
import net.azisaba.azipluginmessaging.api.protocol.message.ProxyboundClearPrefixMessage;
import net.azisaba.azipluginmessaging.api.server.PacketSender;
import net.azisaba.azipluginmessaging.api.server.ServerConnection;
Expand All @@ -19,7 +20,9 @@
public class ProxyboundClearPrefixPacket implements ProxyMessageHandler<ProxyboundClearPrefixMessage> {
@Override
public @NotNull ProxyboundClearPrefixMessage read(@NotNull ServerConnection server, @NotNull DataInputStream in) throws IOException {
return ProxyboundClearPrefixMessage.read(server.getServerInfo().getName(), in);
String serverName = server.getServerInfo().getName();
serverName = AziPluginMessagingConfig.contextualServers.getOrDefault(serverName, serverName);
return ProxyboundClearPrefixMessage.read(serverName, in);
}

@Override
Expand All @@ -30,14 +33,20 @@ public void handle(@NotNull PacketSender sender, @NotNull ProxyboundClearPrefixM
throw new IllegalArgumentException("Could not find an user in LuckPerms database: " + msg.getPlayer().getUniqueId());
}
NodeMap map = user.data();
if (msg.isGlobal()) {
if (msg.isAll()) {
LuckPermsUtil.findAllPrefixNodes(map).forEach(map::remove);
} else if (msg.isGlobal()) {
LuckPermsUtil.findPrefixNodes(map, null).forEach(map::remove);
} else {
LuckPermsUtil.findPrefixNodes(map, msg.getServer()).forEach(map::remove);
}
String username = user.getUsername();
api.getUserManager().saveUser(user);
api.getMessagingService().ifPresent(service -> service.pushUserUpdate(user));
String descServer = "all servers";
if (!msg.isAll()) {
descServer = "server=" + msg.getServer();
}
api.getActionLogger().submit(
Action.builder()
.targetType(Action.Target.Type.USER)
Expand All @@ -46,7 +55,7 @@ public void handle(@NotNull PacketSender sender, @NotNull ProxyboundClearPrefixM
.sourceName("AziPluginMessaging[" + msg.getServer() + "]@" + api.getServerName())
.target(msg.getPlayer().getUniqueId())
.targetName(username)
.description("Clear " + username + "'s prefix in server=" + msg.getServer())
.description("Clear " + username + "'s prefix in " + descServer)
.build());
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
package net.azisaba.azipluginmessaging.api.protocol.handler;

import net.azisaba.azipluginmessaging.api.AziPluginMessagingProvider;
import net.azisaba.azipluginmessaging.api.Logger;
import net.azisaba.azipluginmessaging.api.entity.Player;
import net.azisaba.azipluginmessaging.api.entity.SimplePlayer;
import net.azisaba.azipluginmessaging.api.protocol.message.ProxyboundGiveNitroSaraMessage;
import net.azisaba.azipluginmessaging.api.server.PacketSender;
import net.azisaba.azipluginmessaging.api.server.ServerConnection;
import net.azisaba.azipluginmessaging.api.util.LuckPermsUtil;
import net.luckperms.api.LuckPerms;
import net.luckperms.api.LuckPermsProvider;
import net.luckperms.api.actionlog.Action;
import net.luckperms.api.model.data.DataType;
import net.luckperms.api.model.data.NodeMap;
import net.luckperms.api.model.user.User;
import net.luckperms.api.node.Node;
import org.jetbrains.annotations.NotNull;

import java.io.DataInputStream;
import java.io.IOException;
import java.sql.SQLException;
import java.time.Instant;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

public class ProxyboundGiveNitroSaraPacket implements ProxyMessageHandler<ProxyboundGiveNitroSaraMessage> {
private static final String NITRO_GROUP_NAME = "nitro";

@Override
public @NotNull ProxyboundGiveNitroSaraMessage read(@NotNull ServerConnection server, @NotNull DataInputStream in) throws IOException {
Player player = SimplePlayer.read(in);
int time = in.readInt();
TimeUnit unit = TimeUnit.valueOf(in.readUTF());
return new ProxyboundGiveNitroSaraMessage(player, time, unit);
}

@Override
public void handle(@NotNull PacketSender sender, @NotNull ProxyboundGiveNitroSaraMessage msg) throws SQLException {
LuckPerms api = LuckPermsProvider.get();
User user = api.getUserManager().loadUser(msg.getPlayer().getUniqueId()).join();
if (user == null || user.getUsername() == null) {
throw new IllegalArgumentException("User " + msg.getPlayer().getUniqueId() + " could not be found in the LuckPerms database.");
}
NodeMap map = user.getData(DataType.NORMAL);
Node node = LuckPermsUtil.findParentNode(map, NITRO_GROUP_NAME, null);
if (node == null) {
LuckPermsUtil.addGroup(map, NITRO_GROUP_NAME, null, -1);
}
Node changeSara = LuckPermsUtil.findParentNode(map, "change" + NITRO_GROUP_NAME, null);
if (changeSara == null) {
LuckPermsUtil.addGroup(map, "change" + NITRO_GROUP_NAME, null, -1);
}
// add time
long time = msg.getUnit().toMillis(msg.getTime());
long expiresAt = System.currentTimeMillis() + time;
Logger.getCurrentLogger().info("Adding time of rank " + NITRO_GROUP_NAME + " to " + user.getUsername() + " for " + msg.getTime() + " " + msg.getUnit().name().toLowerCase());
AziPluginMessagingProvider.get().getProxy().runPreparedStatement(
"INSERT INTO `temp_rank` (`player_uuid`, `rank`, `expires_at`, `clear_prefix_on_expire`) VALUES (?, ?, ?, 1) ON DUPLICATE KEY UPDATE `expires_at` = `expires_at` + ?",
(ps) -> {
ps.setString(1, msg.getPlayer().getUniqueId().toString());
ps.setString(2, NITRO_GROUP_NAME);
ps.setLong(3, expiresAt);
ps.setLong(4, time);
ps.executeUpdate();
}).join();
AziPluginMessagingProvider.get().getProxy().runPreparedStatement(
"INSERT INTO `temp_rank` (`player_uuid`, `rank`, `expires_at`, `clear_prefix_on_expire`) VALUES (?, ?, ?, 1) ON DUPLICATE KEY UPDATE `expires_at` = `expires_at` + ?",
(ps) -> {
ps.setString(1, msg.getPlayer().getUniqueId().toString());
ps.setString(2, "change" + NITRO_GROUP_NAME);
ps.setLong(3, expiresAt);
ps.setLong(4, time);
ps.executeUpdate();
}).join();
String username = user.getUsername();
api.getUserManager().saveUser(user).join();
api.getMessagingService().ifPresent(service -> service.pushUserUpdate(user));
api.getActionLogger().submit(
Action.builder()
.targetType(Action.Target.Type.USER)
.timestamp(Instant.now())
.source(new UUID(0L, 0L))
.sourceName("AziPluginMessaging@" + api.getServerName())
.target(msg.getPlayer().getUniqueId())
.targetName(username)
.description("Added nitro sara to " + username + " (+" + msg.getTime() + " " + msg.getUnit().name().toLowerCase() + ")")
.build());
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package net.azisaba.azipluginmessaging.api.protocol.handler;

import net.azisaba.azipluginmessaging.api.AziPluginMessagingConfig;
import net.azisaba.azipluginmessaging.api.protocol.message.ProxyboundSetPrefixMessage;
import net.azisaba.azipluginmessaging.api.server.PacketSender;
import net.azisaba.azipluginmessaging.api.server.ServerConnection;
Expand All @@ -19,7 +20,9 @@
public class ProxyboundSetPrefixPacket implements ProxyMessageHandler<ProxyboundSetPrefixMessage> {
@Override
public @NotNull ProxyboundSetPrefixMessage read(@NotNull ServerConnection server, @NotNull DataInputStream in) throws IOException {
return ProxyboundSetPrefixMessage.read(server.getServerInfo().getName(), in);
String serverName = server.getServerInfo().getName();
serverName = AziPluginMessagingConfig.contextualServers.getOrDefault(serverName, serverName);
return ProxyboundSetPrefixMessage.read(serverName, in);
}

@Override
Expand Down
Loading

0 comments on commit 868bf66

Please sign in to comment.