Skip to content

Commit

Permalink
Remove ability to en/disable whitelist directly via command. Instead,…
Browse files Browse the repository at this point in the history
… the whitelist's state must be changed in the config file, thereafter you can reload the config through /necrify reload
  • Loading branch information
JvstvsHD committed Sep 1, 2024
1 parent 5bc351f commit 4bd649d
Show file tree
Hide file tree
Showing 8 changed files with 119 additions and 96 deletions.
6 changes: 3 additions & 3 deletions build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -107,13 +107,13 @@ subprojects {
hangarPublish {
publications.register("necrify") {
version.set(buildVersion())
channel.set(if (!isRelease) "Snapshot" else "Release")
channel.set(if (!rootProject.isRelease) "Snapshot" else "Release")
id.set("necrify")
apiKey.set(System.getenv("HANGAR_API_TOKEN") ?: "")
if (!isRelease) {
if (!rootProject.isRelease) {
changelog.set(changelogMessage())
} else {
changelog.set("Changes will be provided shortly.\nComplete changelog can be found on GitHub: https://www.github.com/JvstvsHD/necrify/releases/tag/v$version")
changelog.set("Changes will be provided shortly.\nComplete changelog can be found on GitHub: https://www.github.com/JvstvsHD/necrify/releases/tag/v${rootProject.version.toString()}")
}
platforms {
register(Platforms.PAPER) {
Expand Down
1 change: 1 addition & 0 deletions buildSrc/src/main/kotlin/Git.kt
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ fun Project.git(vararg command: String): String {
project.exec {
commandLine = listOf("git", *command)
standardOutput = byteOut
errorOutput = System.err
}
return byteOut.toString(Charsets.UTF_8.name()).trim()
}
Expand Down
14 changes: 10 additions & 4 deletions buildSrc/src/main/kotlin/Version.kt
Original file line number Diff line number Diff line change
Expand Up @@ -15,18 +15,24 @@ fun Project.publishingVersion(): String {
}

fun Project.buildVersion(): String {
val git = Git(project)
val versionString: String = project.version as String
return if (project.isSnapshot) "$versionString-${git.latestCommitHashShort()}"
else versionString
if (!project.isSnapshot) {
return versionString
}
val buildNum = project.buildNumber()
if (buildNum != null) {
return "$versionString-$buildNum"
} else {
return versionString
}
}

fun Project.changelogMessage() = with(git) {
"[https://github.com/JvstvsHD/necrify/commit/${latestCommitHash()}](${latestCommitHashShort()}: ${latestCommitMessage()}"
}

val Project.isRelease: Boolean
get() = version.toString().contains("-")
get() = !version.toString().contains("-")

val Project.isSnapshot: Boolean
get() = version.toString().endsWith("-SNAPSHOT")
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
import de.jvstvshd.necrify.api.punishment.StandardPunishmentType;
import de.jvstvshd.necrify.api.user.NecrifyUser;
import de.jvstvshd.necrify.common.commands.*;
import de.jvstvshd.necrify.common.config.ConfigurationManager;
import de.jvstvshd.necrify.common.punishment.NecrifyKick;
import de.jvstvshd.necrify.common.punishment.NecrifyPunishmentFactory;
import net.kyori.adventure.text.Component;
Expand All @@ -44,7 +45,10 @@
import org.slf4j.Logger;

import java.io.IOException;
import java.util.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ExecutorService;

public abstract class AbstractNecrifyPlugin implements Necrify {
Expand All @@ -54,9 +58,13 @@ public abstract class AbstractNecrifyPlugin implements Necrify {
public static final String BUILD_NUMBER = BuildParameters.BUILD_NUMBER;

protected ExecutorService executorService;
protected final ConfigurationManager configurationManager;
private final Logger logger;

public AbstractNecrifyPlugin(ExecutorService executorService) {
public AbstractNecrifyPlugin(ExecutorService executorService, ConfigurationManager configurationManager, Logger logger) {
this.executorService = executorService;
this.configurationManager = configurationManager;
this.logger = logger;
}

@Override
Expand All @@ -73,10 +81,10 @@ public AbstractNecrifyPlugin(ExecutorService executorService) {
* Registers the punishment types of the plugin to the {@link PunishmentTypeRegistry}. This method should be called
* before any user-input is processed, as the registry is used to determine the type of punishment that should be created.
*/
public final void registerRegistries() {
var registry = new NecrifyPunishmentFactory(this);
public final void registerFactories() {
var factory = new NecrifyPunishmentFactory(this);
for (StandardPunishmentType type : StandardPunishmentType.values()) {
PunishmentTypeRegistry.registerType(type, registry);
PunishmentTypeRegistry.registerType(type, factory);
}
}

Expand Down Expand Up @@ -137,7 +145,23 @@ public final void registerCommands(CommandManager<NecrifyUser> manager, boolean
}

//TODO: Move config to necrify-common
public abstract String getDefaultReason(PunishmentType type);
public String getDefaultReason(PunishmentType type) {
return configurationManager.getConfiguration().getPunishmentConfigData().getPunishmentMessages().get(type.getId());
}

public boolean loadConfig() {
try {
configurationManager.load();
if (configurationManager.getConfiguration().isWhitelistActivated()) {
logger.info("Whitelist is activated. This means that nobody can join this server beside players you have explicitly allowed to join this server via /necrify user <player> whitelist (toggles current state).");
}
} catch (IOException e) {
logger.error("Could not load configuration", e);
logger.error("Aborting start-up");
return false;
}
return true;
}

@SuppressWarnings("ConstantValue")
public static String buildInfo() {
Expand All @@ -149,14 +173,18 @@ public static String buildInfo() {
return buildInfo + ")";
}

public ConfigurationManager getConfig() {
return configurationManager;
}

public abstract NecrifyKick createKick(Component reason, NecrifyUser user, UUID punishmentUuid);

public abstract Logger getLogger();
public Logger getLogger() {
return logger;
}

//TODO return just a set of objects. Create a new User object that does not get loaded from the database.
public abstract Set<Pair<String, UUID>> getOnlinePlayers();

public abstract boolean isWhitelistActive();

//TODO kick all non-whitelisted players
public abstract void setWhitelistActive(boolean active) throws IOException;
}
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
import de.jvstvshd.necrify.api.user.NecrifyUser;
import de.jvstvshd.necrify.api.user.UserDeletionReason;
import de.jvstvshd.necrify.common.AbstractNecrifyPlugin;
import de.jvstvshd.necrify.common.config.ConfigData;
import de.jvstvshd.necrify.common.util.PunishmentHelper;
import de.jvstvshd.necrify.common.util.Util;
import net.kyori.adventure.text.Component;
Expand Down Expand Up @@ -54,7 +55,6 @@
import java.util.List;
import java.util.Locale;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;

public class NecrifyCommand {

Expand All @@ -65,7 +65,6 @@ public class NecrifyCommand {

private static final List<String> PUNISHMENT_COMMAND_OPTIONS = List.of("cancel", "remove", "info", "change");
private static final List<String> USER_COMMAND_OPTIONS = List.of("info", "delete", "whitelist");
private static final List<String> WHITELIST_COMMAND_OPTIONS = List.of("enable", "disable", "status");

public NecrifyCommand(AbstractNecrifyPlugin plugin) {
this.plugin = plugin;
Expand Down Expand Up @@ -315,30 +314,52 @@ public void userCommand(
}
}

@Command("necrify whitelist [option]")
@Command("necrify reload")
@Permission(value = {"necrify.command.reload", "necrify.admin"}, mode = Permission.Mode.ANY_OF)
public void reloadCommand(NecrifyUser sender) {
try {
sender.sendMessage(provider.provide("command.reload.start").color(NamedTextColor.GRAY));
long start = System.currentTimeMillis();
final ConfigData old = plugin.getConfig().getConfiguration();
plugin.getConfig().load();
ConfigData reloaded = plugin.getConfig().getConfiguration();
if (!old.isWhitelistActivated() && reloaded.isWhitelistActivated()) {
Util.executeAsync(() -> {
logger.info("Whitelist activated. Kicking all players who aren't allowed here anymore. This may take some time...");
var startKick = System.currentTimeMillis();
var onlinePlayers = plugin.getOnlinePlayers();
onlinePlayers.forEach(pair -> {
try {
var user = plugin.getUserManager().loadOrCreateUser(pair.second()).join().get();
if (!user.isWhitelisted()) {
user.kick(provider.provide("whitelist.removed").color(NamedTextColor.RED)).join();
}
} catch (Exception e) {
logException(e);
}
});
logger.info("Kicked all non-whitelisted players. Took {} seconds.", (System.currentTimeMillis() - startKick) / 1000.0);
return null;
}, plugin.getExecutor());
}
String took = String.format("%.2f", (System.currentTimeMillis() - start) / 1000.0);
sender.sendMessage(provider.provide("command.reload.success", Component.text(took).color(NamedTextColor.YELLOW)).color(NamedTextColor.GREEN));
} catch (IOException e) {
logException(sender, e);
sender.sendMessage(provider.provide("command.reload.failure").color(NamedTextColor.RED));
}
}

@Command("necrify whitelist")
@Permission(value = {"necrify.command.whitelist", "necrify.admin"}, mode = Permission.Mode.ANY_OF)
public void whitelistCommand(
NecrifyUser sender,
@Argument(value = "option", description = "Option to manage the whitelist", suggestions = "suggestWhitelistCommandOptions") @Default("status") String option
@Argument(value = "option", description = "Option to retrieve the whitelist's status", suggestions = "suggestWhitelistCommandOptions") @Default("status") String option
) {
switch (option) {
case "status" -> {
var whitelist = plugin.isWhitelistActive();
var activeState = whitelist ? "active" : "inactive";
sender.sendMessage(provider.provide("command.whitelist." + activeState).color(NamedTextColor.GRAY));
}
case "enable", "disable" -> {
var state = "enable".equals(option);
try {
plugin.setWhitelistActive(state);
} catch (IOException e) {
logException(sender, e);
return;
}
sender.sendMessage(provider.provide("command.whitelist." + (state ? "enabled" : "disabled")).color(NamedTextColor.GREEN));
}
default -> sender.sendMessage(unknownOption(option, WHITELIST_COMMAND_OPTIONS));
}
var whitelist = plugin.isWhitelistActive();
var activeState = whitelist ? "active" : "inactive";
sender.sendMessage(provider.provide("command.whitelist." + activeState).color(NamedTextColor.GRAY));
sender.sendMessage(provider.provide("whitelist.change-in-config"));
}

//SUGGESTIONS
Expand Down Expand Up @@ -383,15 +404,6 @@ public List<? extends Suggestion> suggestUserCommandOptions(CommandContext<Necri
.toList();
}

@Suggestions("suggestWhitelistCommandOptions")
public List<? extends Suggestion> suggestWhitelistCommandOptions(CommandContext<NecrifyUser> context, CommandInput input) {
return WHITELIST_COMMAND_OPTIONS
.stream()
.filter(option -> option.toLowerCase().startsWith(input.peekString().toLowerCase()))
.map(option -> ComponentTooltipSuggestion.suggestion(option, miniMessage(option)))
.toList();
}

//HELPER METHODS

/**
Expand Down Expand Up @@ -448,7 +460,7 @@ private void tryChainPunishments(NecrifyUser sender, NecrifyUser target, Punishm
sender.sendMessage(provider.provide("command.punishment.chain.info").color(NamedTextColor.GRAY));
for (Punishment unchainedPunishment : unchainedPunishments) {
sender.sendMessage(provider.provide("command.punishment.chain",
Component.text(unchainedPunishment.getPunishmentUuid().toString()).color(NamedTextColor.YELLOW)).color(NamedTextColor.GRAY)
Component.text(unchainedPunishment.getPunishmentUuid().toString()).color(NamedTextColor.YELLOW)).color(NamedTextColor.GRAY)
.clickEvent(ClickEvent.runCommand("/necrify punishment " + unchainedPunishment.getPunishmentUuid().toString().toLowerCase(Locale.ROOT)
+ " chain " + newPunishment.getPunishmentUuid().toString().toLowerCase(Locale.ROOT)))
.hoverEvent((HoverEventSource<Component>) op -> HoverEvent.showText(provider.provide("command.punishment.chain").color(NamedTextColor.GREEN))));
Expand Down
4 changes: 4 additions & 0 deletions necrify-common/src/main/resources/translations/de.properties
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,9 @@ command.punishment.punishments=Dieser Spieler hat derzeit {0} laufende Bestrafun
command.punishment.uuid-parse-error={0} ist keine valide UUID.
command.punishment.unknown-option=Unbekannte Option: {0}
command.punishment.unknown-punishment-id=Es konnte keine Strafe für die ID {0} gefunden werden.
command.reload.start=Die Konfiguration wird neu geladen. Hierdurch wird nicht die Datenbank-Verbindung neugestartet. Bitte starte den Server dazu neu!
command.reload.success=Die Konfiguration wurde erfolgreich in {0}s neu geladen.
command.reload.failure=Beim Neuladen der Konfiguration ist ein Fehler aufgetreten. Bitte überprüfe die Konsole.
command.tempban.usage=Bitte benutze /tempban <Spieler> <Dauer> [Grund].
command.tempban.success=Du hast den Spieler {0}/{1} für {2} bis {3} gebannt.
command.tempmute.usage=Bitte benutze /tempmute <Spieler> <Dauer> [Grund].
Expand Down Expand Up @@ -66,5 +69,6 @@ punishment.mute.temp.full-reason=Du wurdest f
prefix=<gray>[<aqua>Bestrafung</aqua>]</gray>
whitelist.blacklisted=Die Whitelist ist derzeit aktiv. Um zu joinen, kontaktiere bitte das Server-Team, da du nicht auf der Whitelist stehst.
whitelist.removed=Du wurdest soeben von der Whitelist entfernt. Bitte kontaktiere das Server-Team, um wieder hinzugefügt zu werden.
whitelist.change-in-config=Um die Whitelist zu aktivieren oder deaktivieren, ändere bitte die Konfiguration unter whitelist-activated. Nutze anschließend /necrify reload, um die Änderungen zu übernehmen.
whitelist.status.whitelisted=Zugriff erlaubt
whitelist.status.disallowed=Zugriff verweigert
4 changes: 4 additions & 0 deletions necrify-common/src/main/resources/translations/en.properties
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,9 @@ command.punishment.punishments=This player has {0} punishment(s).
command.punishment.uuid-parse-error=Could not parse string {0} as uuid.
command.punishment.unknown-option=Unknown option: {0}
command.punishment.unknown-punishment-id=Could not find a punishment for id {0}.
command.reload.start=The configuration is being reloaded. This does not restart the database connection. Please restart the server for that.
command.reload.success=The configuration has been successfully reloaded in {0}s.
command.reload.failure=An error occurred while reloading the configuration. Please check the console.
command.tempban.usage=Please use /tempban <player> <duration> [reason].
command.tempban.success=You have banned the player {0}/{1} for {2} until {3}.
command.tempmute.usage=Please use /tempmute <player> <duration> [reason].
Expand Down Expand Up @@ -64,5 +67,6 @@ punishment.mute.temp.full-reason=You are muted for {0}. Reason: {1}. End of puni
prefix=<gray>[<aqua>Punishment</aqua>]</gray>
whitelist.blacklisted=The whitelist is currently active. To join, please contact the server team since you are currently not whitelisted.
whitelist.removed=You were removed from the whitelist.
whitelist.change-in-config=In order to change the whitelist status, change whitelist-activated in the config. Afterwards, use /necrify reload to apply the changes.
whitelist.status.whitelisted=access allowed
whitelist.status.disallowed=access disallowed
Loading

0 comments on commit 4bd649d

Please sign in to comment.