[CHORE] Code reformat

This commit is contained in:
2024-01-02 03:22:48 +02:00
parent bbe1c05cb8
commit a343acd8aa
26 changed files with 180 additions and 147 deletions

View File

@@ -38,9 +38,10 @@ public class DiscordAuthor {
/**
* Internal. Use {@link #of(String, String, String)}
*
* @param displayName The Username of the Author
* @param avatar The avatar URL of the Author
* @param isServer Is the Author the Minecraft Server
* @param avatar The avatar URL of the Author
* @param isServer Is the Author the Minecraft Server
*/
private DiscordAuthor(String displayName, String avatar, String username, boolean isServer, String uuid) {
this.displayName = displayName;
@@ -52,8 +53,9 @@ public class DiscordAuthor {
/**
* Create a new Discord Author
*
* @param displayName The name/Username of the Author
* @param uuid The Mojang UUID of the Author
* @param uuid The Mojang UUID of the Author
* @return A constructed {@link DiscordAuthor}
*/
public static DiscordAuthor of(String displayName, String uuid, String username) {

View File

@@ -11,16 +11,20 @@ import lombok.Setter;
@AllArgsConstructor(staticName = "of")
public class DiscordUser {
@Getter @Setter
@Getter
@Setter
private String effectiveName;
@Getter @Setter
@Getter
@Setter
private String avatarUrl;
@Getter @Setter
@Getter
@Setter
private long userId;
@Getter @Setter
@Getter
@Setter
private String asMention;
}

View File

@@ -30,12 +30,8 @@ import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.sql.Time;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
@@ -58,10 +54,11 @@ public class MinecraftAccount {
/**
* Internal. Use {@link #of(String)} (String)} or {@link #of(GameProfile)}
* @param username The Username of the Player
* @param uuid The UUID of the player
*
* @param username The Username of the Player
* @param uuid The UUID of the player
* @param isOffline Is this an OFFLINE/Unauthenticated Account
* @param isValid Is the account valid
* @param isValid Is the account valid
*/
private MinecraftAccount(String username, UUID uuid, boolean isOffline, boolean isValid) {
this.username = username;
@@ -73,6 +70,7 @@ public class MinecraftAccount {
/**
* Try to fetch a player from the Mojang API.
* Will return an offline player if the request fails, or if they don't have a valid account
*
* @param username The username of the player
*/
public static MinecraftAccount of(String username) {
@@ -96,6 +94,7 @@ public class MinecraftAccount {
/**
* Convert a GameProfile into a MinecraftAccount for usage inside the mod
*
* @param profile The player GameProfile
*/
public static MinecraftAccount of(GameProfile profile) {
@@ -104,6 +103,7 @@ public class MinecraftAccount {
/**
* Convert a username to an offline account
*
* @param username The Username to search for
*/
private static MinecraftAccount offline(String username) {
@@ -121,6 +121,57 @@ public class MinecraftAccount {
return sdlinkDatabase.findById(uuid, SDLinkAccount.class);
}
//<editor-fold desc="Helper Methods">
private static Pair<String, UUID> fetchPlayer(String name) {
OkHttpClient client = new OkHttpClient.Builder()
.callTimeout(20, TimeUnit.SECONDS)
.readTimeout(20, TimeUnit.SECONDS)
.connectTimeout(20, TimeUnit.SECONDS)
.build();
try {
Request request = new Request.Builder()
.url("https://api.mojang.com/users/profiles/minecraft/" + name)
.cacheControl(new CacheControl.Builder().noCache().build())
.build();
Response response = client.newCall(request).execute();
if (response.isSuccessful() && response.body() != null) {
JSONObject obj = new JSONObject(new JSONTokener(response.body().string()));
String uuid = "";
String returnname = name;
if (obj.has("name") && !obj.getString("name").isEmpty()) {
returnname = obj.getString("name");
}
if (obj.has("id") && !obj.getString("id").isEmpty()) {
uuid = obj.getString("id");
}
response.close();
return Pair.of(returnname, uuid.isEmpty() ? null : mojangIdToUUID(uuid));
}
} catch (IOException | JSONException e) {
e.printStackTrace();
}
return Pair.of("", null);
}
private static UUID mojangIdToUUID(String id) {
final List<String> strings = new ArrayList<>();
strings.add(id.substring(0, 8));
strings.add(id.substring(8, 12));
strings.add(id.substring(12, 16));
strings.add(id.substring(16, 20));
strings.add(id.substring(20, 32));
return UUID.fromString(String.join("-", strings));
}
private static Pair<String, UUID> offlinePlayer(String offlineName) {
return Pair.of(offlineName, UUID.nameUUIDFromBytes(("OfflinePlayer:" + offlineName).getBytes(StandardCharsets.UTF_8)));
}
public boolean isAccountVerified() {
SDLinkAccount account = getStoredAccount();
@@ -316,7 +367,7 @@ public class MinecraftAccount {
}
if (!SDLinkConfig.INSTANCE.accessControl.requiredRoles.isEmpty() || ! SDLinkConfig.INSTANCE.accessControl.deniedRoles.isEmpty()) {
if (!SDLinkConfig.INSTANCE.accessControl.requiredRoles.isEmpty() || !SDLinkConfig.INSTANCE.accessControl.deniedRoles.isEmpty()) {
Profiler profiler = Profiler.getProfiler("checkRequiredRoles");
profiler.start("Checking Required Roles");
AtomicBoolean anyFound = new AtomicBoolean(false);
@@ -381,56 +432,5 @@ public class MinecraftAccount {
public boolean isOffline() {
return isOffline;
}
//<editor-fold desc="Helper Methods">
private static Pair<String, UUID> fetchPlayer(String name) {
OkHttpClient client = new OkHttpClient.Builder()
.callTimeout(20, TimeUnit.SECONDS)
.readTimeout(20, TimeUnit.SECONDS)
.connectTimeout(20, TimeUnit.SECONDS)
.build();
try {
Request request = new Request.Builder()
.url("https://api.mojang.com/users/profiles/minecraft/" + name)
.cacheControl(new CacheControl.Builder().noCache().build())
.build();
Response response = client.newCall(request).execute();
if (response.isSuccessful() && response.body() != null) {
JSONObject obj = new JSONObject(new JSONTokener(response.body().string()));
String uuid = "";
String returnname = name;
if (obj.has("name") && !obj.getString("name").isEmpty()) {
returnname = obj.getString("name");
}
if (obj.has("id") && !obj.getString("id").isEmpty()) {
uuid = obj.getString("id");
}
response.close();
return Pair.of(returnname, uuid.isEmpty() ? null : mojangIdToUUID(uuid));
}
} catch (IOException | JSONException e) {
e.printStackTrace();
}
return Pair.of("", null);
}
private static UUID mojangIdToUUID(String id) {
final List<String> strings = new ArrayList<>();
strings.add(id.substring(0, 8));
strings.add(id.substring(8, 12));
strings.add(id.substring(12, 16));
strings.add(id.substring(16, 20));
strings.add(id.substring(20, 32));
return UUID.fromString(String.join("-", strings));
}
private static Pair<String, UUID> offlinePlayer(String offlineName) {
return Pair.of(offlineName, UUID.nameUUIDFromBytes(("OfflinePlayer:" + offlineName).getBytes(StandardCharsets.UTF_8)));
}
//</editor-fold>
}

View File

@@ -91,7 +91,11 @@ public class ChatSettingsConfig {
@Path("ignoredCommands")
@SpecComment("Commands that should not be broadcast to discord")
public List<String> ignoredCommands = new ArrayList<String>() {{ add("particle"); add("login"); add("execute"); }};
public List<String> ignoredCommands = new ArrayList<String>() {{
add("particle");
add("login");
add("execute");
}};
@Path("allowMentionsFromChat")
@SpecComment("Allow mentioning discord roles, users and channels from Minecraft Chat")

View File

@@ -24,6 +24,17 @@ public class MessageIgnoreConfig {
@SpecComment("Ignore messages sent from certain threads")
public List<String> ignoredThread = new ArrayList<>();
public enum FilterMode {
STARTS_WITH,
MATCHES,
CONTAINS
}
public enum ActionMode {
REPLACE,
IGNORE
}
public static class Ignore {
@Path("search")
@SpecComment("The text to search for in the message")
@@ -42,15 +53,4 @@ public class MessageIgnoreConfig {
public ActionMode action = ActionMode.REPLACE;
}
public enum FilterMode {
STARTS_WITH,
MATCHES,
CONTAINS
}
public enum ActionMode {
REPLACE,
IGNORE
}
}

View File

@@ -13,19 +13,24 @@ import lombok.Setter;
public class SDLinkAccount {
@Id
@Getter @Setter
@Getter
@Setter
private String uuid;
@Getter @Setter
@Getter
@Setter
private String username;
@Getter @Setter
@Getter
@Setter
private String discordID;
@Getter @Setter
@Getter
@Setter
private String verifyCode;
@Getter @Setter
@Getter
@Setter
private boolean isOffline;
}

View File

@@ -35,30 +35,18 @@ import java.util.concurrent.TimeUnit;
*/
public class BotController {
// Public instance of this class that can be called anywhere
public static BotController INSTANCE;
// Thread Execution Manager
public static final ScheduledExecutorService taskManager = Executors.newScheduledThreadPool(Runtime.getRuntime().availableProcessors());
// Required Variables
private JDA _jda;
// Public instance of this class that can be called anywhere
public static BotController INSTANCE;
private final EventWaiter eventWaiter = new EventWaiter();
private final Logger logger;
/**
* Construct a new instance of this class
* @param logger A constructed {@link Logger} that the bot will use
*/
public static void newInstance(Logger logger) {
if (INSTANCE != null) {
INSTANCE.shutdownBot(false);
}
new BotController(logger);
}
// Required Variables
private JDA _jda;
/**
* INTERNAL
*
* @param logger A constructed {@link Logger} that the bot will use
*/
private BotController(Logger logger) {
@@ -91,6 +79,18 @@ public class BotController {
EmbedManager.init();
}
/**
* Construct a new instance of this class
*
* @param logger A constructed {@link Logger} that the bot will use
*/
public static void newInstance(Logger logger) {
if (INSTANCE != null) {
INSTANCE.shutdownBot(false);
}
new BotController(logger);
}
/**
* Start the bot and handle all the startup work
*/
@@ -171,6 +171,7 @@ public class BotController {
/**
* Shutdown the Bot, optionally forcing a shutdown
*
* @param forced Should the shutdown be forced
*/
public void shutdownBot(boolean forced) {

View File

@@ -52,6 +52,7 @@ public class CommandManager {
/**
* INTERNAL. Used to register slash commands
*
* @param client The Discord Command Client instance
*/
public void register(CommandClient client) {

View File

@@ -17,7 +17,7 @@ public abstract class SDLinkSlashCommand extends SlashCommand {
this.guildOnly = true;
if (requiresPerms) {
this.userPermissions = new Permission[] { Permission.MANAGE_SERVER };
this.userPermissions = new Permission[]{Permission.MANAGE_SERVER};
}
}

View File

@@ -61,7 +61,7 @@ public class PlayerListSlashCommand extends SDLinkSlashCommand {
StringBuilder sb = new StringBuilder();
count.getAndIncrement();
builder.clear();
builder.setTitle("Online Players - Page " + count.get() + "/" + (int)Math.ceil(((float)players.size() / 10)));
builder.setTitle("Online Players - Page " + count.get() + "/" + (int) Math.ceil(((float) players.size() / 10)));
builder.setColor(Color.GREEN);
p.forEach(account -> {

View File

@@ -30,13 +30,6 @@ public class ServerStatusSlashCommand extends SDLinkSlashCommand {
this.guildOnly = true;
}
@Override
protected void execute(SlashCommandEvent event) {
event.deferReply(true).queue();
Button refreshBtn = Button.danger("sdrefreshbtn", "Refresh");
event.getHook().sendMessageEmbeds(runStatusCommand()).addActionRow(refreshBtn).queue();
}
public static MessageEmbed runStatusCommand() {
SystemInfo systemInfo = new SystemInfo();
HardwareAbstractionLayer hal = systemInfo.getHardware();
@@ -107,4 +100,11 @@ public class ServerStatusSlashCommand extends SDLinkSlashCommand {
return builder.build();
}
@Override
protected void execute(SlashCommandEvent event) {
event.deferReply(true).queue();
Button refreshBtn = Button.danger("sdrefreshbtn", "Refresh");
event.getHook().sendMessageEmbeds(runStatusCommand()).addActionRow(refreshBtn).queue();
}
}

View File

@@ -55,7 +55,7 @@ public class ViewVerifiedAccounts extends SDLinkSlashCommand {
MessageUtil.listBatches(accounts, 10).forEach(itm -> {
count.getAndIncrement();
builder.clear();
builder.setTitle("Verified Accounts - Page " + count + "/" + (int)Math.ceil(((float)accounts.size() / 10)));
builder.setTitle("Verified Accounts - Page " + count + "/" + (int) Math.ceil(((float) accounts.size() / 10)));
builder.setColor(Color.GREEN);
StringBuilder sBuilder = new StringBuilder();

View File

@@ -25,6 +25,7 @@ public class BotReadyHooks {
/**
* Update the bot activity
*
* @param event The {@link ReadyEvent}
*/
public static void startActivityUpdates(ReadyEvent event) {

View File

@@ -19,9 +19,8 @@ import java.util.HashMap;
*/
public class ChannelManager {
private static StandardGuildMessageChannel consoleChannel;
private static final HashMap<MessageDestination, Pair<StandardGuildMessageChannel, Boolean>> channelMap = new HashMap<>();
private static StandardGuildMessageChannel consoleChannel;
/**
* Load configured channel, while always defaulting back to ChatChannel for channels that aren't configured

View File

@@ -27,22 +27,22 @@ public class PermissionChecker {
// Base Permissions required by the bot to operate
private static final List<Permission> BOT_PERMS = new ArrayList<>() {{
add(Permission.NICKNAME_CHANGE);
add(Permission.MANAGE_WEBHOOKS);
add(Permission.MESSAGE_SEND);
add(Permission.MESSAGE_EMBED_LINKS);
add(Permission.MESSAGE_HISTORY);
add(Permission.MESSAGE_EXT_EMOJI);
add(Permission.MANAGE_ROLES);
add(Permission.MESSAGE_MANAGE);
add(Permission.NICKNAME_CHANGE);
add(Permission.MANAGE_WEBHOOKS);
add(Permission.MESSAGE_SEND);
add(Permission.MESSAGE_EMBED_LINKS);
add(Permission.MESSAGE_HISTORY);
add(Permission.MESSAGE_EXT_EMOJI);
add(Permission.MANAGE_ROLES);
add(Permission.MESSAGE_MANAGE);
}};
// Basic channel permissions required by all channels
private static final List<Permission> BASE_CHANNEL_PERMS = new ArrayList<>() {{
add(Permission.VIEW_CHANNEL);
add(Permission.MESSAGE_SEND);
add(Permission.MESSAGE_EMBED_LINKS);
add(Permission.MANAGE_WEBHOOKS);
add(Permission.VIEW_CHANNEL);
add(Permission.MESSAGE_SEND);
add(Permission.MESSAGE_EMBED_LINKS);
add(Permission.MANAGE_WEBHOOKS);
}};
/**

View File

@@ -28,6 +28,7 @@ public class RoleManager {
/**
* Check and load the roles required by the bot
*
* @param errCount
* @param builder
*/
@@ -55,10 +56,11 @@ public class RoleManager {
/**
* Load a role from either a Name or ID
* @param errCount Counter holding the current error count
* @param builder String builder that is used to build the error messages
*
* @param errCount Counter holding the current error count
* @param builder String builder that is used to build the error messages
* @param roleIdentifier Log identifier for the role being loaded
* @param roleID The ID or Name of the role to load
* @param roleID The ID or Name of the role to load
* @return The role that matched or NULL
*/
private static Role getRole(AtomicInteger errCount, StringBuilder builder, String roleIdentifier, String roleID) {

View File

@@ -19,8 +19,8 @@ import java.util.HashMap;
*/
public class WebhookManager {
private static WebhookClient chatWebhookClient, eventWebhookClient, consoleWebhookClient;
private static final HashMap<MessageDestination, WebhookClient> clientMap = new HashMap<>();
private static WebhookClient chatWebhookClient, eventWebhookClient, consoleWebhookClient;
/**
* Load configured webhook clients

View File

@@ -10,14 +10,8 @@ package com.hypherionmc.sdlink.core.messaging;
*/
public class Result {
enum Type {
ERROR,
SUCCESS
}
private final Type type;
private final String message;
private Result(Type type, String message) {
this.type = type;
this.message = message;
@@ -39,4 +33,9 @@ public class Result {
return message;
}
enum Type {
ERROR,
SUCCESS
}
}

View File

@@ -148,6 +148,7 @@ public final class DiscordMessage {
/**
* Build an embed with the supplied information
*
* @param withAuthor Should the author be appended to the embed. Not used for Webhooks
*/
private EmbedBuilder buildEmbed(boolean withAuthor, String key) {

View File

@@ -24,6 +24,7 @@ public final class DiscordMessageBuilder {
/**
* Construct a discord message
*
* @param messageType The type of message being sent
*/
public DiscordMessageBuilder(MessageType messageType) {

View File

@@ -21,13 +21,20 @@ import java.util.List;
public interface IMinecraftHelper {
void discordMessageReceived(Member member, String message);
Result checkWhitelisting();
Pair<Integer, Integer> getPlayerCounts();
List<MinecraftAccount> getOnlinePlayers();
long getServerUptime();
String getServerVersion();
Result executeMinecraftCommand(String command, int permLevel, MessageReceivedEvent event, @Nullable SDLinkAccount account);
boolean isOnlineMode();
void banPlayer(MinecraftAccount acc);
}

View File

@@ -22,19 +22,10 @@ import java.util.Random;
*/
public final class EncryptionUtil {
public static EncryptionUtil INSTANCE = getInstance();
private final boolean canRun;
private final boolean canRun; public static EncryptionUtil INSTANCE = getInstance();
// Instance of the Encryptor Used
private final StandardPBEStringEncryptor encryptor;
private static EncryptionUtil getInstance() {
if (INSTANCE == null) {
INSTANCE = new EncryptionUtil();
}
return INSTANCE;
}
private EncryptionUtil() {
String encCode = "";
@@ -63,8 +54,16 @@ public final class EncryptionUtil {
BotController.INSTANCE.getLogger().error("Failed to initialize encryption system. Your config values will not be encrypted!");
}
private static EncryptionUtil getInstance() {
if (INSTANCE == null) {
INSTANCE = new EncryptionUtil();
}
return INSTANCE;
}
/**
* Will Encrypt the string passed into it, if it's not already encrypted
*
* @param input The string to be encrypted
* @return The encrypted string
*/
@@ -82,6 +81,7 @@ public final class EncryptionUtil {
/**
* Decrypts an encrypted string
*
* @param input The encrypted String
* @return The Plain Text String
*/
@@ -120,4 +120,6 @@ public final class EncryptionUtil {
return RandomStringUtils.random(new Random().nextInt(40), true, true);
}
}

View File

@@ -35,9 +35,9 @@ import java.util.Date;
public class LogReader extends AbstractAppender {
public static String logs = "";
private static boolean isDevEnv = false;
private long time;
private Thread messageScheduler;
private static boolean isDevEnv = false;
protected LogReader(String name, Filter filter) {
super(name, filter, null, true, new Property[0]);

View File

@@ -35,6 +35,7 @@ public class MessageUtil {
/**
* Split a large list of items into smaller sublists. This is to help with Discord limits on pagination
*
* @param source The list of objects to split
* @param length How many entries are allowed per sub-list
*/

View File

@@ -15,8 +15,8 @@ import com.hypherionmc.sdlink.core.discord.BotController;
//TODO Remove this on release
public class Profiler {
private long startTime;
private final String profilerName;
private long startTime;
private boolean hasStarted = false;
private String message = "";

View File

@@ -12,6 +12,7 @@ public class SystemUtils {
/**
* Convert Bytes into a human-readable format, like 1GB
* From https://stackoverflow.com/a/3758880
*
* @param bytes The Size in Bytes
* @return The size formatted in KB, MB, GB, TB, PB etc
*/
@@ -34,6 +35,7 @@ public class SystemUtils {
/**
* Convert Seconds into a Timestamp
*
* @param sec Input in seconds
*/
public static String secondsToTimestamp(long sec) {
@@ -55,7 +57,8 @@ public class SystemUtils {
try {
Long.parseLong(input);
return true;
} catch (NumberFormatException ignored){}
} catch (NumberFormatException ignored) {
}
return false;
}
}