Update to 1.21.6 and java 21 using cosmos

This commit is contained in:
akastijn 2025-06-28 04:52:39 +02:00
parent e4ca6d986f
commit 42a9701959
25 changed files with 272 additions and 274 deletions

1
.gitignore vendored
View File

@ -36,3 +36,4 @@ target/
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid*
*.bat

29
Jenkinsfile vendored Normal file
View File

@ -0,0 +1,29 @@
pipeline {
agent any
stages {
stage('Gradle') {
steps {
sh '''
chmod +x gradlew
./gradlew build
'''
}
}
stage('Archive') {
steps {
archiveArtifacts artifacts: 'build/libs/', followSymlinks: false
}
}
stage('discord') {
when {
anyOf {
branch 'main'
branch 'master'
}
}
steps {
discordSend description: "Build: ${BUILD_NUMBER}", showChangeset: true, result: currentBuild.currentResult, title: currentBuild.fullProjectName, webhookURL: env.discordwebhook
}
}
}
}

View File

@ -1,19 +1,16 @@
import com.github.jengelman.gradle.plugins.shadow.tasks.ConfigureShadowRelocation
plugins {
id("java")
id("com.github.johnrengelman.shadow") version "7.1.0"
}
group = "com.alttd"
version = "1.0.0-SNAPSHOT"
version = "1.1.0-SNAPSHOT"
description = "Altitude player flag plugin."
apply<JavaLibraryPlugin>()
java {
toolchain {
languageVersion.set(JavaLanguageVersion.of(17))
languageVersion.set(JavaLanguageVersion.of(21))
}
}
@ -25,24 +22,10 @@ tasks {
withType<Javadoc> {
options.encoding = Charsets.UTF_8.name()
}
shadowJar {
dependsOn(getByName("relocateJars") as ConfigureShadowRelocation)
archiveFileName.set("${project.name}-${project.version}.jar")
minimize()
configurations = listOf(project.configurations.shadow.get())
}
build {
dependsOn(shadowJar)
}
create<ConfigureShadowRelocation>("relocateJars") {
target = shadowJar.get()
prefix = "${project.name}.lib"
}
}
dependencies {
compileOnly("com.alttd:Galaxy-API:1.19-R0.1-SNAPSHOT")
}
compileOnly("com.alttd.cosmos:cosmos-api:1.21.6-R0.1-SNAPSHOT") {
isChanging = true
}
}

BIN
gradle/wrapper/gradle-wrapper.jar vendored Normal file

Binary file not shown.

View File

@ -0,0 +1,7 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.6-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

51
gradlew vendored
View File

@ -1,7 +1,7 @@
#!/bin/sh
#
# Copyright © 2015-2021 the original authors.
# Copyright © 2015-2021 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@ -32,10 +32,10 @@
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
@ -55,7 +55,7 @@
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
@ -80,13 +80,11 @@ do
esac
done
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
APP_NAME="Gradle"
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
@ -133,22 +131,29 @@ location of your Java installation."
fi
else
JAVACMD=java
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
@ -193,11 +198,15 @@ if "$cygwin" || "$msys" ; then
done
fi
# Collect all arguments for the java command;
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
# shell script including quotes and variable substitutions, so put them in
# double quotes to make sure that they get re-expanded; and
# * put everything else in single quotes, so that it's not re-expanded.
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
@ -205,6 +214,12 @@ set -- \
org.gradle.wrapper.GradleWrapperMain \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.

15
gradlew.bat vendored
View File

@ -14,7 +14,7 @@
@rem limitations under the License.
@rem
@if "%DEBUG%" == "" @echo off
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@ -25,7 +25,8 @@
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@ -40,7 +41,7 @@ if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto execute
if %ERRORLEVEL% equ 0 goto execute
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
@ -75,13 +76,15 @@ set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
if %ERRORLEVEL% equ 0 goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd
if "%OS%"=="Windows_NT" endlocal

50
pom.xml
View File

@ -1,50 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>groupId</groupId>
<artifactId>LiteFlags</artifactId>
<version>1.0</version>
<properties>
<maven.compiler.source>16</maven.compiler.source>
<maven.compiler.target>16</maven.compiler.target>
</properties>
<build>
<finalName>${project.artifactId}</finalName>
<defaultGoal>clean package</defaultGoal>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>17</source>
<target>17</target>
</configuration>
</plugin>
</plugins>
<resources>
<resource>
<directory>src/main/resources</directory>
</resource>
</resources>
</build>
<repositories>
<repository>
<id>Alttd-Nexus</id>
<url>https://repo.destro.xyz/snapshots</url>
</repository>
</repositories>
<dependencies>
<dependency><!-- Galaxy -->
<groupId>com.alttd</groupId>
<artifactId>Galaxy-API</artifactId>
<version>1.18.2-R0.1-SNAPSHOT</version>
</dependency>
</dependencies>
</project>

View File

@ -2,49 +2,49 @@ package com.liteflags;
import com.liteflags.auth.AuthTimer;
import com.liteflags.commands.CommandManager;
import com.liteflags.config.Config;
import com.liteflags.data.database.DatabaseConnection;
import com.liteflags.events.ChatEvent;
import com.liteflags.events.LoginEvent;
import com.liteflags.events.LogoutEvent;
import com.liteflags.events.MoveEvent;
import java.sql.SQLException;
import com.liteflags.config.Config;
import org.bukkit.plugin.java.JavaPlugin;
import java.sql.SQLException;
public class LiteFlags extends JavaPlugin {
private static LiteFlags instance;
public DatabaseConnection database;
public AuthTimer timer;
private static LiteFlags instance;
public DatabaseConnection database;
public AuthTimer timer;
public void onEnable() {
instance = this;
Config.reload();
this.getCommand("flag").setExecutor(new CommandManager());
this.getServer().getPluginManager().registerEvents(new LoginEvent(), this);
this.getServer().getPluginManager().registerEvents(new LogoutEvent(), this);
this.getServer().getPluginManager().registerEvents(new ChatEvent(), this);
this.getServer().getPluginManager().registerEvents(new MoveEvent(), this);
public void onEnable() {
instance = this;
Config.reload();
this.getCommand("flag").setExecutor(new CommandManager());
this.getServer().getPluginManager().registerEvents(new LoginEvent(), this);
this.getServer().getPluginManager().registerEvents(new LogoutEvent(), this);
this.getServer().getPluginManager().registerEvents(new ChatEvent(), this);
this.getServer().getPluginManager().registerEvents(new MoveEvent(), this);
try {
DatabaseConnection.initialize();
} catch (SQLException exception) {
this.getLogger().severe("*** Could not connect to the database. ***");
this.getLogger().severe("*** This plugin will be disabled. ***");
this.setEnabled(false);
exception.printStackTrace();
}
try {
DatabaseConnection.initialize();
} catch (SQLException exception) {
this.getLogger().severe("*** Could not connect to the database. ***");
this.getLogger().severe("*** This plugin will be disabled. ***");
this.setEnabled(false);
exception.printStackTrace();
}
}
}
public void onDisable() {
}
public void onDisable() {
}
public static LiteFlags getInstance() {
return instance;
}
public static LiteFlags getInstance() {
return instance;
}
public AuthTimer authTimer() {
return this.timer;
}
public AuthTimer authTimer() {
return this.timer;
}
}

View File

@ -3,17 +3,15 @@ package com.liteflags.auth;
import com.liteflags.LiteFlags;
import com.liteflags.config.Config;
import com.liteflags.data.maps.MapCache;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import net.kyori.adventure.text.minimessage.tag.resolver.Placeholder;
import net.kyori.adventure.text.minimessage.tag.resolver.TagResolver;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
public class AuthTimer<taskID> {
public LiteFlags flags;
public static Map<UUID, Integer> taskID = new HashMap<>();
@ -34,9 +32,10 @@ public class AuthTimer<taskID> {
AuthTimer.endTask(player);
} else {
final String code = MapCache.reauthedPlayers.get(uuid);
if (code == null)
if (code == null) {
return;
player.sendMiniMessage(Config.AUTHENTICATE, TagResolver.resolver(
}
player.sendRichMessage(Config.AUTHENTICATE, TagResolver.resolver(
Placeholder.unparsed("code", code)));
Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), Config.AUTH_MESSAGE_COMMAND
.replaceAll("<player>", player.getName())

View File

@ -1,12 +1,11 @@
package com.liteflags.auth;
import com.liteflags.data.maps.MapCache;
import com.liteflags.config.Config;
import com.liteflags.data.maps.MapCache;
import net.kyori.adventure.text.minimessage.tag.resolver.Placeholder;
import net.kyori.adventure.text.minimessage.tag.resolver.TagResolver;
import org.bukkit.entity.Player;
import java.util.List;
import java.util.Random;
public class Authentication {
@ -33,13 +32,14 @@ public class Authentication {
}
public static void checkAuthStatus(Player player) {
if (player.hasPermission("liteflags.authentication.success"))
if (player.hasPermission("liteflags.authentication.success")) {
return;
}
MapCache.reauthedPlayers.put(player.getUniqueId().toString(), getAuthKey());
AuthTimer.startTimer(player);
player.sendMiniMessage(Config.AUTHENTICATE,
TagResolver.resolver(Placeholder.unparsed("code", MapCache.reauthedPlayers.get(player.getUniqueId().toString()))));
player.sendRichMessage(Config.AUTHENTICATE,
TagResolver.resolver(Placeholder.unparsed("code", MapCache.reauthedPlayers.get(player.getUniqueId().toString()))));
}
}

View File

@ -18,7 +18,7 @@ import java.util.stream.Collectors;
public class CommandManager implements CommandExecutor, TabExecutor {
private final List<SubCommand> subCommands;
private SubCommand flagPlayer = new CommandFlagPlayer();
private final SubCommand flagPlayer = new CommandFlagPlayer();
public CommandManager() {
LiteFlags liteFlags = LiteFlags.getInstance();
@ -33,32 +33,32 @@ public class CommandManager implements CommandExecutor, TabExecutor {
command.setTabCompleter(this);
subCommands = Arrays.asList(//TODO add the flag player command separately
new CommandHelp(this),
new CommandFlagList(),
new CommandFlagPlayer(),
new CommandFlagRemove(),
new CommandReload()
);
new CommandHelp(this),
new CommandFlagList(),
new CommandFlagPlayer(),
new CommandFlagRemove(),
new CommandReload()
);
}
@Override
public boolean onCommand(@NotNull CommandSender commandSender, @NotNull Command command, @NotNull String cmd, @NotNull String[] args) {
if (!commandSender.hasPermission("liteflags.use")) {
commandSender.sendMiniMessage(Config.NO_PERMISSION, null);
commandSender.sendRichMessage(Config.NO_PERMISSION);
return true;
}
if (args.length == 0) {
commandSender.sendMiniMessage(Config.HELP_MESSAGE_WRAPPER.replaceAll("<commands>", subCommands.stream()
commandSender.sendRichMessage(Config.HELP_MESSAGE_WRAPPER.replaceAll("<commands>", subCommands.stream()
.filter(subCommand -> commandSender.hasPermission(subCommand.getPermission()))
.map(SubCommand::getHelpMessage)
.collect(Collectors.joining("\n"))), null);
.collect(Collectors.joining("\n"))));
return true;
}
SubCommand subCommand = getSubCommand(args[0]);
if (!commandSender.hasPermission(subCommand.getPermission())) {
commandSender.sendMiniMessage(Config.NO_PERMISSION, null);
commandSender.sendRichMessage(Config.NO_PERMISSION);
return true;
}
@ -71,19 +71,20 @@ public class CommandManager implements CommandExecutor, TabExecutor {
if (args.length <= 1) {
res.addAll(subCommands.stream()
.filter(subCommand -> commandSender.hasPermission(subCommand.getPermission()))
.map(SubCommand::getName)
.filter(Objects::nonNull)
.filter(name -> args.length == 0 || name.startsWith(args[0].toLowerCase()))
.collect(Collectors.toList()));
.filter(subCommand -> commandSender.hasPermission(subCommand.getPermission()))
.map(SubCommand::getName)
.filter(Objects::nonNull)
.filter(name -> args.length == 0 || name.startsWith(args[0].toLowerCase()))
.toList());
res.addAll(Bukkit.getOnlinePlayers().stream()
.map(Player::getName)
.filter(name -> args.length == 0 || name.startsWith(args[0].toLowerCase()))
.collect(Collectors.toList()));
.map(Player::getName)
.filter(name -> args.length == 0 || name.startsWith(args[0].toLowerCase()))
.toList());
} else {
SubCommand subCommand = getSubCommand(args[0]);
if (subCommand != null && commandSender.hasPermission(subCommand.getPermission()))
if (subCommand != null && commandSender.hasPermission(subCommand.getPermission())) {
res.addAll(subCommand.getTabComplete(commandSender, args));
}
}
return res;
}
@ -99,4 +100,4 @@ public class CommandManager implements CommandExecutor, TabExecutor {
.findFirst()
.orElse(flagPlayer);
}
}
}

View File

@ -24,8 +24,6 @@ import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
public class CommandFlagList extends SubCommand {
@Override
@ -38,28 +36,30 @@ public class CommandFlagList extends SubCommand {
Logger.warning("% is not a flagged player", playerName);
return;
}
commandSender.sendMiniMessage(Config.ALERT_ACTIVE_FLAGS, TagResolver.resolver(
commandSender.sendRichMessage(Config.ALERT_ACTIVE_FLAGS, TagResolver.resolver(
Placeholder.parsed("player", player.getName() == null ? playerName : player.getName()),
Placeholder.unparsed("total_act_flags", String.valueOf( Methods.getTotalActiveFlags(player))),
Placeholder.unparsed("total_act_flags", String.valueOf(Methods.getTotalActiveFlags(player))),
Placeholder.unparsed("console_flags", String.valueOf(Methods.consoleFlags)),
Placeholder.unparsed("staff_flags", String.valueOf(Methods.staffFlags))
));
));
});
} else
commandSender.sendMiniMessage(Config.NO_ACTIVE_FLAGS, null);
} else {
commandSender.sendRichMessage(Config.NO_ACTIVE_FLAGS);
}
} else if (args.length == 2 || args.length == 3) {
List<String> body;
if (args.length == 3) {
if (!args[2].equals("full")) {
commandSender.sendMiniMessage(getHelpMessage(), null);
commandSender.sendRichMessage(getHelpMessage());
return true;
}
body = Config.PLAYER_FLAG_LIST_LONG;
} else
} else {
body = Config.PLAYER_FLAG_LIST_SHORT;
}
OfflinePlayer player = Bukkit.getServer().getOfflinePlayerIfCached(args[1]);
if (player == null) {
commandSender.sendMiniMessage(Config.UNKNOWN_PLAYER, TagResolver.resolver(Placeholder.unparsed("player", args[1])));
commandSender.sendRichMessage(Config.UNKNOWN_PLAYER, TagResolver.resolver(Placeholder.unparsed("player", args[1])));
return true;
}
new BukkitRunnable() {
@ -68,8 +68,9 @@ public class CommandFlagList extends SubCommand {
sendFlagMessage(commandSender, player, body);
}
}.runTask(LiteFlags.getInstance());
} else
commandSender.sendMiniMessage(getHelpMessage(), null);
} else {
commandSender.sendRichMessage(getHelpMessage());
}
return true;
}
@ -81,11 +82,12 @@ public class CommandFlagList extends SubCommand {
@Override
public List<String> getTabComplete(CommandSender commandSender, String[] args) {
ArrayList<String> res = new ArrayList<>();
if (args.length == 2)
if (args.length == 2) {
res.addAll(Bukkit.getOnlinePlayers().stream()
.map(Player::getName)
.filter(name -> args[1].isEmpty() || name.toLowerCase().startsWith(args[1].toLowerCase()))
.toList());
.map(Player::getName)
.filter(name -> args[1].isEmpty() || name.toLowerCase().startsWith(args[1].toLowerCase()))
.toList());
}
return res;
}
@ -111,47 +113,51 @@ public class CommandFlagList extends SubCommand {
message = miniMessage.deserialize(Config.PLAYER_FLAGS_HEADER, TagResolver.resolver(List.of(
Placeholder.unparsed("player", targetName),
Placeholder.unparsed("flag_amount", String.valueOf(resultSet.getString("total_flags")))
)));
)));
}
int dbExpireTime = resultSet.getInt("expire_time");
Instant expireTime = dbExpireTime == 0 ? Instant.MIN : Instant.ofEpochSecond(dbExpireTime);
// long expireTime = TimeUnit.SECONDS.toMinutes(resultSet.getInt("expire_time"));
// long expireTime = TimeUnit.SECONDS.toMinutes(resultSet.getInt("expire_time"));
Instant timeFlagged = Instant.ofEpochSecond(resultSet.getInt("time_flagged"));
// long timeFlagged = TimeUnit.SECONDS.toMinutes(resultSet.getInt("time_flagged"));
// long timeFlagged = TimeUnit.SECONDS.toMinutes(resultSet.getInt("time_flagged"));
Instant currentTime = Instant.now();
// long currentTime = TimeUnit.SECONDS.toMinutes(System.currentTimeMillis() / 1000L);
// long currentTime = TimeUnit.SECONDS.toMinutes(System.currentTimeMillis() / 1000L);
Duration convertedExpireTime = Duration.between(currentTime, expireTime);
// int convertedExpireTime = (int) expireTime - (int) currentTime;
// int convertedExpireTime = (int) expireTime - (int) currentTime;
Duration convertedFlaggedTime = Duration.between(currentTime, timeFlagged);
// int convertedFlaggedTime = (int) currentTime - (int) timeFlagged;
// int convertedFlaggedTime = (int) currentTime - (int) timeFlagged;
String id = String.valueOf(resultSet.getInt("id"));
TagResolver templates = TagResolver.resolver(Placeholder.unparsed("player", targetPlayer.getName()),
Placeholder.unparsed("flag", resultSet.getString("reason")),
Placeholder.unparsed("staff", resultSet.getString("flagged_by")),
Placeholder.unparsed("flag_length", resultSet.getString("flag_length")),
Placeholder.unparsed("reason", resultSet.getString("reason")),
Placeholder.unparsed("flag_time", Utilities.convertTime(convertedFlaggedTime)),
Placeholder.unparsed("expire_time", Utilities.convertTime(convertedExpireTime)),
Placeholder.unparsed("nl", "\n"),
Placeholder.unparsed("id", id)
);
Placeholder.unparsed("flag", resultSet.getString("reason")),
Placeholder.unparsed("staff", resultSet.getString("flagged_by")),
Placeholder.unparsed("flag_length", resultSet.getString("flag_length")),
Placeholder.unparsed("reason", resultSet.getString("reason")),
Placeholder.unparsed("flag_time", Utilities.convertTime(convertedFlaggedTime)),
Placeholder.unparsed("expire_time", Utilities.convertTime(convertedExpireTime)),
Placeholder.unparsed("nl", "\n"),
Placeholder.unparsed("id", id)
);
String str = String.join("\n", body)
.replaceAll("<remove_button>", "<white>" +
"<hover:show_text:\"Click to remove this flag\">" +
"<click:run_command:/flag remove " + id + " " + targetPlayer.getName() + ">" +
"[<red>✖</red>]</click></hover></white>");
"<hover:show_text:\"Click to remove this flag\">" +
"<click:run_command:/flag remove " + id + " " + targetPlayer.getName() + ">" +
"[<red>✖</red>]</click></hover></white>");
if (convertedExpireTime.isNegative() && !expireTime.equals(Instant.MIN)) //Not active
{
str = str.replaceAll("<active>", Config.EXPIRED_FLAGS);
else //Active
} else //Active
{
str = str.replaceAll("<active>", Config.ACTIVE_FLAGS);
}
str = "\n" + str;
Logger.info(str);
message = message.append(miniMessage.deserialize(str, TagResolver.resolver(templates)));
}
if (message == null) {
commandSender.sendMiniMessage(Config.NO_FLAGS_FOUND, TagResolver.resolver(Placeholder.unparsed("target", targetName)));
} else
commandSender.sendRichMessage(Config.NO_FLAGS_FOUND, TagResolver.resolver(Placeholder.unparsed("target", targetName)));
} else {
commandSender.sendMessage(message);
}
} catch (SQLException exception) {
exception.printStackTrace();
}

View File

@ -7,7 +7,7 @@ import com.liteflags.data.database.Database;
import com.liteflags.data.database.Methods;
import com.liteflags.data.maps.MapCache;
import com.liteflags.util.Utilities;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.ComponentLike;
import net.kyori.adventure.text.minimessage.MiniMessage;
import net.kyori.adventure.text.minimessage.tag.resolver.Placeholder;
import net.kyori.adventure.text.minimessage.tag.resolver.TagResolver;
@ -23,32 +23,31 @@ import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
public class CommandFlagPlayer extends SubCommand {
@Override
public boolean onCommand(CommandSender commandSender, String[] args) {
if (args.length < 2) {
commandSender.sendMiniMessage(getHelpMessage(), null);
commandSender.sendRichMessage(getHelpMessage());
return true;
}
OfflinePlayer target = Bukkit.getServer().getOfflinePlayerIfCached(args[0]);
if (target == null) {
commandSender.sendMiniMessage(Config.UNKNOWN_PLAYER, TagResolver.resolver(Placeholder.unparsed("player", args[2])));
commandSender.sendRichMessage(Config.UNKNOWN_PLAYER, TagResolver.resolver(Placeholder.unparsed("player", args[2])));
return true;
}
if (Config.MAX_ACTIVE_FLAGS >= 0 && Methods.getTotalActiveFlags(target) >= Config.MAX_ACTIVE_FLAGS) {
commandSender.sendMiniMessage(Config.ACTIVE_FLAGS_LIMIT, TagResolver.resolver(
commandSender.sendRichMessage(Config.ACTIVE_FLAGS_LIMIT, TagResolver.resolver(
Placeholder.unparsed("player", target.getName() == null ? target.getUniqueId().toString() : target.getName())
));
));
return true;
}
if (args[1].equals("*")) {
if (!commandSender.hasPermission(getPermission() + ".variable-time")) {
commandSender.sendMiniMessage(Config.VARIABLE_LENGTH_NOT_ALLOWED, null);
commandSender.sendRichMessage(Config.VARIABLE_LENGTH_NOT_ALLOWED);
return true;
}
permFlag(commandSender, args, target);
@ -77,12 +76,12 @@ public class CommandFlagPlayer extends SubCommand {
MapCache.activeFlags.add(target.getName());
}
Component message = MiniMessage.miniMessage().deserialize(Config.FLAGGED_PLAYER, TagResolver.resolver(List.of(
ComponentLike message = MiniMessage.miniMessage().deserialize(Config.FLAGGED_PLAYER, TagResolver.resolver(List.of(
Placeholder.unparsed("staff", sender.getName()),
Placeholder.unparsed("player", target.getName() == null ? target.getUniqueId().toString() : target.getName()),
Placeholder.unparsed("flag_length", "Permanent"),
Placeholder.unparsed("reason", reason)
)));
)));
Bukkit.getOnlinePlayers().stream()
.filter(player -> player.hasPermission("liteflags.alertflags"))
@ -95,7 +94,7 @@ public class CommandFlagPlayer extends SubCommand {
int firstArg = 2;
Duration flagDuration;
if (flagDurationIfExists.isPresent() && !commandSender.hasPermission(getPermission() + ".variable-time")) {
commandSender.sendMiniMessage(Config.VARIABLE_LENGTH_NOT_ALLOWED, null);
commandSender.sendRichMessage(Config.VARIABLE_LENGTH_NOT_ALLOWED);
return;
}
if (flagDurationIfExists.isEmpty()) {
@ -119,12 +118,12 @@ public class CommandFlagPlayer extends SubCommand {
MapCache.activeFlags.add(target.getName());
}
Component message = MiniMessage.miniMessage().deserialize(Config.FLAGGED_PLAYER, TagResolver.resolver(List.of(
ComponentLike message = MiniMessage.miniMessage().deserialize(Config.FLAGGED_PLAYER, TagResolver.resolver(List.of(
Placeholder.unparsed("staff", commandSender.getName()),
Placeholder.unparsed("player", target.getName() == null ? target.getUniqueId().toString() : target.getName()),
Placeholder.unparsed("flag_length", Utilities.convertTime(flagDuration)),
Placeholder.unparsed("reason", reason)
)));
)));
Bukkit.getOnlinePlayers().stream()
.filter(player -> player.hasPermission("liteflags.alertflags"))
@ -172,11 +171,13 @@ public class CommandFlagPlayer extends SubCommand {
@Override
public List<String> getTabComplete(CommandSender commandSender, String[] args) {
ArrayList<String> res = new ArrayList<>();
if (args.length == 2 && commandSender.hasPermission(getPermission() + ".variable-time"))
if (args.length == 2 && commandSender.hasPermission(getPermission() + ".variable-time")) {
for (int i = 1; i <= 9; i++) {
if (args[1].isEmpty() || args[1].startsWith(String.valueOf(i)))
if (args[1].isEmpty() || args[1].startsWith(String.valueOf(i))) {
res.add(i + "d");
}
}
}
return res;
}

View File

@ -20,43 +20,43 @@ public class CommandFlagRemove extends SubCommand {
OfflinePlayer target = Bukkit.getServer().getOfflinePlayerIfCached(args[2]);
if (target == null) {
commandSender.sendMiniMessage(Config.UNKNOWN_PLAYER, TagResolver.resolver(Placeholder.unparsed("player", args[2])));
commandSender.sendRichMessage(Config.UNKNOWN_PLAYER, TagResolver.resolver(Placeholder.unparsed("player", args[2])));
return true;
}
if (args.length == 4) {
if (args[3].isEmpty() || !args[3].equalsIgnoreCase("-c")) {
commandSender.sendMiniMessage(getHelpMessage(), null);
commandSender.sendRichMessage(getHelpMessage());
return true;
}
String flagReason = Database.getFlagReason(target.getUniqueId(), id);
flagReason = flagReason == null ? "Flag not found" : flagReason;
if (Database.removeFlag(target.getUniqueId(), id)) {
commandSender.sendMiniMessage(Config.FLAG_REMOVED, TagResolver.resolver(
commandSender.sendRichMessage(Config.FLAG_REMOVED, TagResolver.resolver(
Placeholder.unparsed("flag_reason", flagReason),
Placeholder.unparsed("target", target.getName() == null ? target.getUniqueId().toString() : target.getName())
));
));
Logger.info("% has removed the flag '%' from %'s flag history.", commandSender.getName(), flagReason, target.getName());
} else {
commandSender.sendMiniMessage(Config.NO_FLAG_FOUND, TagResolver.resolver(
commandSender.sendRichMessage(Config.NO_FLAG_FOUND, TagResolver.resolver(
Placeholder.unparsed("target", target.getName() == null ? target.getUniqueId().toString() : target.getName()),
Placeholder.unparsed("id", String.valueOf(id))
));
));
}
} else if (args.length == 3) {
String flagReason = Database.getFlagReason(target.getUniqueId(), id);
String name = target.getName();
// commandSender.sendMiniMessage("<white>Are you sure you want to remove the flag <flag_reason> from " +
// "<yellow><target_name></yellow>'s flag history? " +
// "<hover:Click to confirm><click:run_command:/flag remove " + id + " " + target.getName() + " -c>[<green>Confirm</green>]</click></hover></white>", List.of(
// Placeholder.unparsed("flag_reason", flagReason == null ? "Unknown" : flagReason),
// Placeholder.unparsed("target_name", name == null ? target.getUniqueId().toString() : name),
// Placeholder.unparsed("id", String.valueOf(id))
// ));
commandSender.sendMiniMessage(Config.FLAG_CONFIRM, TagResolver.resolver(
// commandSender.sendRichMessage("<white>Are you sure you want to remove the flag <flag_reason> from " +
// "<yellow><target_name></yellow>'s flag history? " +
// "<hover:Click to confirm><click:run_command:/flag remove " + id + " " + target.getName() + " -c>[<green>Confirm</green>]</click></hover></white>", List.of(
// Placeholder.unparsed("flag_reason", flagReason == null ? "Unknown" : flagReason),
// Placeholder.unparsed("target_name", name == null ? target.getUniqueId().toString() : name),
// Placeholder.unparsed("id", String.valueOf(id))
// ));
commandSender.sendRichMessage(Config.FLAG_CONFIRM, TagResolver.resolver(
Placeholder.parsed("flag_reason", flagReason == null ? "Unknown" : flagReason),
Placeholder.parsed("target_name", name == null ? target.getUniqueId().toString() : name),
Placeholder.parsed("id", String.valueOf(id))
));
));
}
return true;
}

View File

@ -20,10 +20,10 @@ public class CommandHelp extends SubCommand {
@Override
public boolean onCommand(CommandSender commandSender, String[] args) {
commandSender.sendMiniMessage(Config.HELP_MESSAGE_WRAPPER.replaceAll("<commands>", commandManager.getSubCommands().stream()
commandSender.sendRichMessage(Config.HELP_MESSAGE_WRAPPER.replaceAll("<commands>", commandManager.getSubCommands().stream()
.filter(subCommand -> commandSender.hasPermission(subCommand.getPermission()))
.map(SubCommand::getHelpMessage)
.collect(Collectors.joining("\n"))), null);
.collect(Collectors.joining("\n"))));
return true;
}

View File

@ -2,7 +2,6 @@ package com.liteflags.commands.subcommands;
import com.liteflags.commands.SubCommand;
import com.liteflags.config.Config;
import com.liteflags.util.Utilities;
import org.bukkit.command.CommandSender;
import java.util.ArrayList;
@ -12,7 +11,7 @@ public class CommandReload extends SubCommand {
@Override
public boolean onCommand(CommandSender commandSender, String[] args) {
Config.reload();
commandSender.sendMiniMessage(Config.CONFIG_RELOADED, null);
commandSender.sendRichMessage(Config.CONFIG_RELOADED);
return false;
}

View File

@ -114,8 +114,7 @@ abstract class AbstractConfig {
final ConfigurationSection section = yaml.getConfigurationSection(path);
if (section != null) {
for (String key : section.getKeys(false)) {
@SuppressWarnings("unchecked")
final T val = (T) section.get(key);
@SuppressWarnings("unchecked") final T val = (T) section.get(key);
if (val != null) {
builder.put(key, val);
}
@ -127,4 +126,4 @@ abstract class AbstractConfig {
ConfigurationSection getConfigurationSection(String path) {
return yaml.getConfigurationSection(path);
}
}
}

View File

@ -9,6 +9,7 @@ public final class Config extends AbstractConfig {
static Config config;
static int version;
public Config() {
super(new File(File.separator + "mnt" + File.separator + "configs" + File.separator + "LiteFlags"), "config.yml");
}
@ -23,8 +24,8 @@ public final class Config extends AbstractConfig {
}
public static String ALERT_ACTIVE_FLAGS = "<gray><hover:show_text:\"Click to view <player>'s flags\"><click:run_command:\"/flag list <player>\">" +
"<player> has <red><total_act_flags></red> active flags!</click></hover> " +
"(<red><console_flags></red> Console, <red><staff_flags></red> Staff)</gray>";
"<player> has <red><total_act_flags></red> active flags!</click></hover> " +
"(<red><console_flags></red> Console, <red><staff_flags></red> Staff)</gray>";
public static String PLAYER_FLAGS_HEADER = "<yellow><player> has <red><flag_amount></red> flags: </yellow>";
public static List<String> PLAYER_FLAG_LIST_SHORT = List.of("<yellow>- <active> <flag> <gray><flag_time> ago</gray></yellow>");
public static List<String> PLAYER_FLAG_LIST_LONG = List.of(
@ -49,16 +50,18 @@ public final class Config extends AbstractConfig {
public static String NO_FLAG_FOUND = "<red>No flag found for <target> with id: <id></red>";
public static String INVALID_TIME_ARGUMENT = "<red>Invalid time argument <arg>! Example: 1d</red>";
public static String FLAG_CONFIRM = "<white>Are you sure you want to remove the flag <flag_reason> from " +
"<yellow><target_name></yellow>'s flag history? " +
"<hover:show_text:\"Click to confirm\"><click:run_command:\"/flag remove <id> <target_name> -c\">[<green>Confirm</green>]</click></hover></white>";
"<yellow><target_name></yellow>'s flag history? " +
"<hover:show_text:\"Click to confirm\"><click:run_command:\"/flag remove <id> <target_name> -c\">[<green>Confirm</green>]</click></hover></white>";
public static String VARIABLE_LENGTH_NOT_ALLOWED = "<red>You do not have permission to set a flag at a custom length</red>";
private static void loadMessages() {
ALERT_ACTIVE_FLAGS = config.getString("messages.alert-active-flags", ALERT_ACTIVE_FLAGS);
PLAYER_FLAGS_HEADER = config.getString("messages.player-flags-header", PLAYER_FLAGS_HEADER);
PLAYER_FLAG_LIST_SHORT = config.getList("messages.player-flag-list-short", PLAYER_FLAG_LIST_SHORT).stream()
.filter(object -> object instanceof String) //TODO check if this is needed
.map(object -> Objects.toString(object, null))
.collect(Collectors.toList());;
.collect(Collectors.toList());
;
PLAYER_FLAG_LIST_LONG = config.getList("messages.player-flag-list-long", PLAYER_FLAG_LIST_LONG).stream()
.filter(object -> object instanceof String) //TODO check if this is needed
.map(object -> Objects.toString(object, null))
@ -88,10 +91,11 @@ public final class Config extends AbstractConfig {
public static String HELP_FLAG_LIST = "<green><gold>/flag list</gold>: Show all the players with active flags</green>";
public static String HELP_FLAG_LIST_PLAYER = "<green><gold>/flag list <player> [full]</gold>: Show the flags a player has</green>";
public static String HELP_FLAG_PLAYER = "<green><gold>/flag <player> <time> <reason></gold>: Flag a player for " +
"a given reason <i>Ex: /flag BobTheBuilder 7d Possible hacked client.</i></green>";
"a given reason <i>Ex: /flag BobTheBuilder 7d Possible hacked client.</i></green>";
public static String HELP_FLAG_REMOVE = "<green><gold>/flag remove <player> <id>></gold>: Remove a specific flag from a player " +
"(easier to use from /flag list <player>)";
"(easier to use from /flag list <player>)";
public static String HELP_RELOAD = "<green><gold>/flag reload</gold>: Reload the config for LiteFlags</green>";
private static void loadHelp() {
HELP_MESSAGE_WRAPPER = config.getString("help.help-wrapper", HELP_MESSAGE_WRAPPER);
HELP_MESSAGE = config.getString("help.help", HELP_MESSAGE);
@ -106,6 +110,7 @@ public final class Config extends AbstractConfig {
public static String USERNAME = "root";
public static String PASSWORD = "root";
public static String DRIVERS = "mysql";
private static void loadDatabaseSettings() {
IP = config.getString("database.ip", IP);
PORT = config.getString("database.port", PORT);
@ -124,6 +129,7 @@ public final class Config extends AbstractConfig {
public static String AUTH_MESSAGE_COMMAND = "cmi titlemessage <player> -keep:80 &7You need to authenticate! <nl>&7Type &6<code> &7in chat to authenticate. (CaSe SeNsiTiVe)";
public static String AUTH_SUCCESS_COMMAND = "lp user <player> permission settemp <permission> true <expire_time>";
public static int DEFAULT_FLAG_LENGTH_DAYS = 30;
private static void loadSettings() {
MAX_ACTIVE_FLAGS = config.getInt("settings.max-active-flags", MAX_ACTIVE_FLAGS);
MAX_FLAGS_LISTED = config.getInt("settings.max-flags-listed", MAX_FLAGS_LISTED);

View File

@ -72,8 +72,9 @@ public class Database {
PreparedStatement statement = DatabaseConnection.getConnection().prepareStatement(sql);
statement.setString(1, uuid.toString());
statement.setInt(2, id);
if (statement.executeUpdate() > 0)
if (statement.executeUpdate() > 0) {
return true;
}
} catch (SQLException var16) {
var16.printStackTrace();
}
@ -112,18 +113,18 @@ public class Database {
}
}
//
// public static boolean hasFlag(UUID uuid, int id) {
// try {
// if (getStringResult("SELECT * FROM player_flags WHERE uuid = ?", uuid.toString()).next()) {
// return true;
// }
// } catch (SQLException var2) {
// var2.printStackTrace();
// }
//
// return false;
// }
//
// public static boolean hasFlag(UUID uuid, int id) {
// try {
// if (getStringResult("SELECT * FROM player_flags WHERE uuid = ?", uuid.toString()).next()) {
// return true;
// }
// } catch (SQLException var2) {
// var2.printStackTrace();
// }
//
// return false;
// }
public static void addPlayerCache(UUID uuid, String playerName) {
String sql = "INSERT INTO player_cache (uuid, player_name) VALUES (?, ?) ON DUPLICATE KEY UPDATE player_name = ?";

View File

@ -15,7 +15,6 @@ import org.bukkit.event.Listener;
import org.bukkit.event.player.AsyncPlayerChatEvent;
import org.bukkit.scheduler.BukkitRunnable;
import java.util.List;
import java.util.concurrent.TimeUnit;
public class ChatEvent implements Listener {
@ -33,7 +32,7 @@ public class ChatEvent implements Listener {
if (e.getMessage().equals(value)) {
e.setCancelled(true);
player.sendMiniMessage(Config.AUTHENTICATE_SUCCESS, null);
player.sendRichMessage(Config.AUTHENTICATE_SUCCESS);
final int min = Config.MIN_RANDOM_RE_AUTH;
final int max = Config.MAX_RANDOM_RE_AUTH;
@ -43,11 +42,11 @@ public class ChatEvent implements Listener {
new BukkitRunnable() {
public void run() {
Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(),
Config.AUTH_SUCCESS_COMMAND
.replaceAll("<player>", player.getName())
.replaceAll("<permission>", "liteflags.authentication.success")
.replaceAll("<expiretime>", Methods.getRandomIntegerBetweenRange(min, max)
+ timeAmount.substring(0, 1).toLowerCase()));
Config.AUTH_SUCCESS_COMMAND
.replaceAll("<player>", player.getName())
.replaceAll("<permission>", "liteflags.authentication.success")
.replaceAll("<expiretime>", Methods.getRandomIntegerBetweenRange(min, max)
+ timeAmount.substring(0, 1).toLowerCase()));
}
}.runTask(LiteFlags.getInstance());
@ -69,7 +68,7 @@ public class ChatEvent implements Listener {
} else {
e.setCancelled(true);
player.sendMiniMessage(Config.AUTHENTICATE_FAILED, TagResolver.resolver(
player.sendRichMessage(Config.AUTHENTICATE_FAILED, TagResolver.resolver(
Placeholder.unparsed("code", MapCache.reauthedPlayers.get(player.getUniqueId().toString()))));
Logger.info(player.getName() + " tried talking while authenticating: " + e.getMessage());
}

View File

@ -5,7 +5,7 @@ import com.liteflags.auth.Authentication;
import com.liteflags.config.Config;
import com.liteflags.data.database.Methods;
import com.liteflags.data.maps.MapCache;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.ComponentLike;
import net.kyori.adventure.text.minimessage.MiniMessage;
import net.kyori.adventure.text.minimessage.tag.resolver.Placeholder;
import net.kyori.adventure.text.minimessage.tag.resolver.TagResolver;
@ -36,12 +36,12 @@ public class LoginEvent implements Listener {
MapCache.activeFlags.add(player.getName());
Component message = MiniMessage.miniMessage().deserialize(Config.ALERT_ACTIVE_FLAGS, TagResolver.resolver(List.of(
ComponentLike message = MiniMessage.miniMessage().deserialize(Config.ALERT_ACTIVE_FLAGS, TagResolver.resolver(List.of(
Placeholder.parsed("player", player.getName()),
Placeholder.unparsed("total_act_flags", String.valueOf(Methods.getTotalActiveFlags(player))),
Placeholder.unparsed("console_flags", String.valueOf(Methods.consoleFlags)),
Placeholder.unparsed("staff_flags", String.valueOf(Methods.staffFlags))
)));
)));
Bukkit.getOnlinePlayers().stream()
.filter(onlinePlayer -> onlinePlayer.hasPermission("liteflags.alertflags"))

View File

@ -10,7 +10,8 @@ public class MoveEvent implements Listener {
@EventHandler
public void onPlayerMove(PlayerMoveEvent e) {
Player player = e.getPlayer();
if (MapCache.reauthedPlayers.containsKey(player.getUniqueId().toString()))
if (MapCache.reauthedPlayers.containsKey(player.getUniqueId().toString())) {
e.setCancelled(true);
}
}
}

View File

@ -10,24 +10,21 @@ public class Logger {
logger = LiteFlags.getInstance().getLogger();
}
public static void info(String info, String... variables)
{
public static void info(String info, String... variables) {
for (String variable : variables) {
info = info.replaceFirst("%", variable);
}
logger.info(info);
}
public static void warning(String warning, String... variables)
{
public static void warning(String warning, String... variables) {
for (String variable : variables) {
warning = warning.replaceFirst("%", variable);
}
logger.warning(warning);
}
public static void severe(String severe, String... variables)
{
public static void severe(String severe, String... variables) {
for (String variable : variables) {
severe = severe.replaceFirst("%", variable);
}

View File

@ -12,8 +12,9 @@ public class Utilities {
timeString += (timeString.length() == 0 ? "" : (hours == 0 ? "" : ", ")) + formatTime(hours, " hour");
timeString += (timeString.length() == 0 ? "" : (minutes == 0 ? "" : ", ")) + formatTime(minutes, " minute");
if (timeString.length() == 0)
if (timeString.length() == 0) {
timeString = "0 minutes";
}
return timeString;
}