[CHORE] Code Cleanup

This commit is contained in:
2023-08-06 12:19:33 +02:00
parent 3a49f97154
commit de63a25496
12 changed files with 40 additions and 234 deletions

View File

@@ -4,8 +4,9 @@ plugins {
id 'maven-publish' id 'maven-publish'
id "com.diffplug.spotless" version "6.13.0" id "com.diffplug.spotless" version "6.13.0"
} }
apply plugin: 'java' apply plugin: 'java'
java.toolchain.languageVersion = JavaLanguageVersion.of(16) java.toolchain.languageVersion = JavaLanguageVersion.of(17)
group 'com.hypherionmc.sdlink' group 'com.hypherionmc.sdlink'
version = "${version_major}.${version_minor}.${version_patch}" version = "${version_major}.${version_minor}.${version_patch}"
@@ -144,7 +145,7 @@ spotless {
tasks.withType(JavaCompile).configureEach { tasks.withType(JavaCompile).configureEach {
it.options.encoding = 'UTF-8' it.options.encoding = 'UTF-8'
it.options.release = 16 it.options.release = 17
} }
tasks.withType(GenerateModuleMetadata) { tasks.withType(GenerateModuleMetadata) {

View File

@@ -1,6 +1,6 @@
version_major=0 version_major=0
version_minor=0 version_minor=0
version_patch=16 version_patch=17
shade_group=com.hypherionmc.sdlink.shaded. shade_group=com.hypherionmc.sdlink.shaded.

View File

@@ -102,22 +102,6 @@ public class MinecraftAccount {
return sdlinkDatabase.findById(uuid, SDLinkAccount.class); return sdlinkDatabase.findById(uuid, SDLinkAccount.class);
} }
public String getUsername() {
return username;
}
public UUID getUuid() {
return uuid;
}
public boolean isValid() {
return isValid;
}
public boolean isOffline() {
return isOffline;
}
/** /**
* Link a Minecraft account to a discord account * Link a Minecraft account to a discord account
* @param member The discord user * @param member The discord user
@@ -336,11 +320,11 @@ public class MinecraftAccount {
System.out.println("[AutoWhiteList] Has Auto Role: " + hasAutoRole); System.out.println("[AutoWhiteList] Has Auto Role: " + hasAutoRole);
} }
return hasAutoRole; return hasAutoRole && !account.getDiscordID().isEmpty();
} }
} }
return !SDLinkConfig.INSTANCE.whitelistingAndLinking.accountLinking.accountLinking; return false;
} }
/** /**
@@ -388,7 +372,23 @@ public class MinecraftAccount {
return BotController.INSTANCE.getJDA().getUserById(storedAccount.getDiscordID()); return BotController.INSTANCE.getJDA().getUserById(storedAccount.getDiscordID());
} }
// Helper Methods public String getUsername() {
return username;
}
public UUID getUuid() {
return uuid;
}
public boolean isValid() {
return isValid;
}
public boolean isOffline() {
return isOffline;
}
//<editor-fold desc="Helper Methods">
private static Pair<String, UUID> fetchPlayer(String name) { private static Pair<String, UUID> fetchPlayer(String name) {
try { try {
BufferedReader read = new BufferedReader(new InputStreamReader(new URL("https://api.mojang.com/users/profiles/minecraft/" + name).openStream())); BufferedReader read = new BufferedReader(new InputStreamReader(new URL("https://api.mojang.com/users/profiles/minecraft/" + name).openStream()));
@@ -425,5 +425,5 @@ public class MinecraftAccount {
private static Pair<String, UUID> offlinePlayer(String offlineName) { private static Pair<String, UUID> offlinePlayer(String offlineName) {
return Pair.of(offlineName, UUID.nameUUIDFromBytes(("OfflinePlayer:" + offlineName).getBytes(StandardCharsets.UTF_8))); return Pair.of(offlineName, UUID.nameUUIDFromBytes(("OfflinePlayer:" + offlineName).getBytes(StandardCharsets.UTF_8)));
} }
//</editor-fold>
} }

View File

@@ -24,7 +24,7 @@ public class SDLinkConfig extends ModuleConfig {
// DO NOT REMOVE TRANSIENT HERE... OTHERWISE, THE STUPID CONFIG LIBRARY // DO NOT REMOVE TRANSIENT HERE... OTHERWISE, THE STUPID CONFIG LIBRARY
// WILL TRY TO WRITE THESE TO THE CONFIG // WILL TRY TO WRITE THESE TO THE CONFIG
public transient static SDLinkConfig INSTANCE; public transient static SDLinkConfig INSTANCE;
public transient static int configVer = 8; public transient static int configVer = 9;
@Path("general") @Path("general")
@SpecComment("General Mod Config") @SpecComment("General Mod Config")
@@ -54,10 +54,6 @@ public class SDLinkConfig extends ModuleConfig {
@SpecComment("Configure Whitelisting and Account Linking through the bot") @SpecComment("Configure Whitelisting and Account Linking through the bot")
public LinkAndWhitelistConfigSettings whitelistingAndLinking = new LinkAndWhitelistConfigSettings(); public LinkAndWhitelistConfigSettings whitelistingAndLinking = new LinkAndWhitelistConfigSettings();
@Path("botCommands")
@SpecComment("Enable or Disable certain bot commands")
public BotCommandsConfig botCommands = new BotCommandsConfig();
@Path("minecraftCommands") @Path("minecraftCommands")
@SpecComment("Execute Minecraft commands in Discord") @SpecComment("Execute Minecraft commands in Discord")
public MinecraftCommands linkedCommands = new MinecraftCommands(); public MinecraftCommands linkedCommands = new MinecraftCommands();

View File

@@ -1,28 +0,0 @@
/*
* This file is part of sdlink-core, licensed under the MIT License (MIT).
* Copyright HypherionSA and Contributors
*/
package com.hypherionmc.sdlink.core.config.impl;
import me.hypherionmc.moonconfig.core.conversion.Path;
import me.hypherionmc.moonconfig.core.conversion.SpecComment;
/**
* @author HypherionSA
* Config Structure to allow disabling some bot commands
*/
public class BotCommandsConfig {
@Path("allowPlayerList")
@SpecComment("Enable/Disable the Player List command")
public boolean allowPlayerList = true;
@Path("allowServerStatus")
@SpecComment("Enable/Disable the Server Status command")
public boolean allowServerStatus = true;
@Path("allowHelpCommand")
@SpecComment("Enable/Disable the Help command")
public boolean allowHelpCommand = true;
}

View File

@@ -55,6 +55,10 @@ public class LinkAndWhitelistConfigSettings {
@SpecComment("Automatically link Minecraft and Discord Accounts when a user is whitelisted") @SpecComment("Automatically link Minecraft and Discord Accounts when a user is whitelisted")
public boolean linkedWhitelist = false; public boolean linkedWhitelist = false;
@Path("autoWhitelist")
@SpecComment("Allow automatically whitelisting and de-whitelisting users with autoWhitelistRoles")
public boolean autoWhitelist = false;
@Path("autoWhitelistRoles") @Path("autoWhitelistRoles")
@SpecComment("Users with linked discord accounts, that contain any of these roles will be automatically whitelisted") @SpecComment("Users with linked discord accounts, that contain any of these roles will be automatically whitelisted")
public List<String> autoWhitelistRoles = new ArrayList<>(); public List<String> autoWhitelistRoles = new ArrayList<>();

View File

@@ -1,36 +0,0 @@
/*
* This file is part of sdlink-core, licensed under the MIT License (MIT).
* Copyright HypherionSA and Contributors
*/
package com.hypherionmc.sdlink.core.config.impl;
/**
* @author HypherionSA
* Main Config Structure to control Discord -> MC Commands
*/
/*public class LinkedCommandsConfig {
@Path("enabled")
@SpecComment("Should linked commands be enabled")
public boolean enabled = false;
@Path("commands")
@SpecComment("Commands to be linked")
public List<Command> commands = new ArrayList<>();
public static class Command {
@Path("mcCommand")
@SpecComment("The Minecraft Command. Use %args% to pass everything after the discordCommand to Minecraft")
public String mcCommand;
@Path("discordCommand")
@SpecComment("The command slug in discord. To be used as /mc slug")
public String discordCommand;
@Path("discordRole")
@SpecComment("Discord Role Name of ID of the role that is allowed to execute this command. If empty, all players will be allowed to use this command")
public String discordRole;
}
}
*/

View File

@@ -54,23 +54,13 @@ public class CommandManager {
} }
// Enable the Server Status command // Enable the Server Status command
if (SDLinkConfig.INSTANCE.botCommands.allowServerStatus) { commands.add(new ServerStatusSlashCommand());
commands.add(new ServerStatusSlashCommand());
}
// Enable the Player List command // Enable the Player List command
if (SDLinkConfig.INSTANCE.botCommands.allowPlayerList) { commands.add(new PlayerListSlashCommand());
commands.add(new PlayerListSlashCommand());
}
// Enable the Help command // Enable the Help command
if (SDLinkConfig.INSTANCE.botCommands.allowHelpCommand) { commands.add(new HelpSlashCommand());
commands.add(new HelpSlashCommand());
}
if (SDLinkConfig.INSTANCE.linkedCommands.enabled) {
//commands.add(new MCSlashCommand());
}
} }
/** /**

View File

@@ -13,13 +13,6 @@ import com.jagrosh.jdautilities.command.SlashCommand;
public abstract class SDLinkSlashCommand extends SlashCommand { public abstract class SDLinkSlashCommand extends SlashCommand {
public SDLinkSlashCommand(boolean requiresPerms) { public SDLinkSlashCommand(boolean requiresPerms) {
/*if (requiresPerms) {
if (RoleManager.getStaffRole() != null) {
this.requiredRole = RoleManager.getStaffRole().getName();
} else {
this.userPermissions = new Permission[] { Permission.ADMINISTRATOR, Permission.KICK_MEMBERS };
}
}*/
this.guildOnly = true; this.guildOnly = true;
} }

View File

@@ -1,104 +0,0 @@
/*
* This file is part of sdlink-core, licensed under the MIT License (MIT).
* Copyright HypherionSA and Contributors
*/
package com.hypherionmc.sdlink.core.discord.commands.slash.mc;
/*import com.hypherionmc.sdlink.core.accounts.MinecraftAccount;
import com.hypherionmc.sdlink.core.config.SDLinkConfig;
import com.hypherionmc.sdlink.core.config.impl.LinkedCommandsConfig;
import com.hypherionmc.sdlink.core.database.SDLinkAccount;
import com.hypherionmc.sdlink.core.discord.commands.slash.SDLinkSlashCommand;
import com.hypherionmc.sdlink.core.managers.RoleManager;
import com.hypherionmc.sdlink.core.messaging.Result;
import com.hypherionmc.sdlink.core.services.SDLinkPlatform;
import com.jagrosh.jdautilities.command.SlashCommandEvent;
import net.dv8tion.jda.api.entities.Member;
import net.dv8tion.jda.api.entities.Role;
import net.dv8tion.jda.api.interactions.commands.OptionType;
import net.dv8tion.jda.api.interactions.commands.build.OptionData;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import static com.hypherionmc.sdlink.core.managers.DatabaseManager.sdlinkDatabase;
public class MCSlashCommand extends SDLinkSlashCommand {
public MCSlashCommand() {
super(false);
this.name = "mc";
this.help = "Execute Minecraft Command from Discord";
this.options = new ArrayList<>() {{
add(new OptionData(OptionType.STRING, "slug", "The discordCommand slug defined in the config").setRequired(true));
add(new OptionData(OptionType.STRING, "args0", "Additional arguments to pass to the %args% variable").setRequired(false));
add(new OptionData(OptionType.STRING, "args1", "Additional arguments to pass to the %args% variable").setRequired(false));
add(new OptionData(OptionType.STRING, "args2", "Additional arguments to pass to the %args% variable").setRequired(false));
add(new OptionData(OptionType.STRING, "args3", "Additional arguments to pass to the %args% variable").setRequired(false));
add(new OptionData(OptionType.STRING, "args4", "Additional arguments to pass to the %args% variable").setRequired(false));
add(new OptionData(OptionType.STRING, "args5", "Additional arguments to pass to the %args% variable").setRequired(false));
}};
}
@Override
protected void execute(SlashCommandEvent event) {
if (SDLinkConfig.INSTANCE.linkedCommands.enabled) {
String slug = event.getOption("slug") != null ? event.getOption("slug").getAsString() : "";
String args0 = event.getOption("args0") != null ? event.getOption("args0").getAsString() : "";
String args1 = event.getOption("args1") != null ? event.getOption("args1").getAsString() : "";
String args2 = event.getOption("args2") != null ? event.getOption("args2").getAsString() : "";
String args3 = event.getOption("args3") != null ? event.getOption("args3").getAsString() : "";
String args4 = event.getOption("args4") != null ? event.getOption("args4").getAsString() : "";
String args5 = event.getOption("args5") != null ? event.getOption("args5").getAsString() : "";
Optional<LinkedCommandsConfig.Command> linkedCommand = SDLinkConfig.INSTANCE.linkedCommands.commands.stream().filter(c -> c.discordCommand.equalsIgnoreCase(slug)).findFirst();
StringBuilder args = new StringBuilder();
if (!args0.isEmpty())
args.append(args0);
if (!args1.isEmpty())
args.append(" ").append(args1);
if (!args2.isEmpty())
args.append(" ").append(args2);
if (!args3.isEmpty())
args.append(" ").append(args3);
if (!args4.isEmpty())
args.append(" ").append(args4);
if (!args5.isEmpty())
args.append(" ").append(args5);
sdlinkDatabase.reloadCollection("accounts");
List<SDLinkAccount> accounts = sdlinkDatabase.findAll(SDLinkAccount.class);
Optional<SDLinkAccount> account = accounts.stream().filter(u -> u.getDiscordID().equals(event.getMember().getId())).findFirst();
linkedCommand.ifPresent(command -> {
if (!command.discordRole.isEmpty()) {
Role role = RoleManager.getCommandRoles().isEmpty() ? null : RoleManager.getCommandRoles().get(command.discordCommand);
boolean userRole = role != null && event.getMember().getRoles().stream().anyMatch(r -> r.getIdLong() == role.getIdLong());
if (userRole) {
executeCommand(event, command, args.toString(), event.getMember(), account.orElse(null));
} else {
event.reply("You need the " + role.getName() + " role to perform this action").setEphemeral(true).queue();
}
} else {
executeCommand(event, command, args.toString(), event.getMember(), account.orElse(null));
}
});
if (linkedCommand.isEmpty()) {
event.reply("Cannot find linked command " + slug).setEphemeral(true).queue();
}
} else {
event.reply("Linked commands are not enabled!").setEphemeral(true).queue();
}
}
private void executeCommand(SlashCommandEvent event, LinkedCommandsConfig.Command mcCommand, String args, Member member, SDLinkAccount account) {
Result result = SDLinkPlatform.minecraftHelper.executeMinecraftCommand(mcCommand.mcCommand, args, member, account);
event.reply(result.getMessage()).setEphemeral(true).queue();
}
}*/

View File

@@ -4,8 +4,10 @@
*/ */
package com.hypherionmc.sdlink.core.discord.commands.slash.whitelist; package com.hypherionmc.sdlink.core.discord.commands.slash.whitelist;
import com.hypherionmc.sdlink.core.accounts.MinecraftAccount;
import com.hypherionmc.sdlink.core.database.SDLinkAccount; import com.hypherionmc.sdlink.core.database.SDLinkAccount;
import com.hypherionmc.sdlink.core.discord.commands.slash.SDLinkSlashCommand; import com.hypherionmc.sdlink.core.discord.commands.slash.SDLinkSlashCommand;
import com.hypherionmc.sdlink.core.services.SDLinkPlatform;
import com.hypherionmc.sdlink.core.util.MessageUtil; import com.hypherionmc.sdlink.core.util.MessageUtil;
import com.jagrosh.jdautilities.command.SlashCommandEvent; import com.jagrosh.jdautilities.command.SlashCommandEvent;
import com.jagrosh.jdautilities.menu.EmbedPaginator; import com.jagrosh.jdautilities.menu.EmbedPaginator;
@@ -38,29 +40,29 @@ public class ViewWhitelistedAccountsSlashCommand extends SDLinkSlashCommand {
protected void execute(SlashCommandEvent event) { protected void execute(SlashCommandEvent event) {
EmbedPaginator.Builder paginator = MessageUtil.defaultPaginator(event); EmbedPaginator.Builder paginator = MessageUtil.defaultPaginator(event);
sdlinkDatabase.reloadCollection("accounts"); sdlinkDatabase.reloadCollection("accounts");
List<SDLinkAccount> accounts = sdlinkDatabase.findAll(SDLinkAccount.class).stream().filter(SDLinkAccount::isWhitelisted).toList(); List<MinecraftAccount> players = SDLinkPlatform.minecraftHelper.getWhitelistedPlayers();
EmbedBuilder builder = new EmbedBuilder(); EmbedBuilder builder = new EmbedBuilder();
ArrayList<MessageEmbed> pages = new ArrayList<>(); ArrayList<MessageEmbed> pages = new ArrayList<>();
AtomicInteger count = new AtomicInteger(); AtomicInteger count = new AtomicInteger();
if (accounts.isEmpty()) { if (players.isEmpty()) {
event.reply("There are no whitelisted accounts for this discord").setEphemeral(true).queue(); event.reply("There are no whitelisted accounts for this discord").setEphemeral(true).queue();
return; return;
} }
MessageUtil.listBatches(accounts, 10).forEach(itm -> { MessageUtil.listBatches(players, 10).forEach(itm -> {
count.getAndIncrement(); count.getAndIncrement();
builder.clear(); builder.clear();
builder.setTitle("Whitelisted Accounts - Page " + count + "/" + (int)Math.ceil(((float)accounts.size() / 10))); builder.setTitle("Whitelisted Accounts - Page " + count + "/" + (int)Math.ceil(((float)players.size() / 10)));
builder.setColor(Color.GREEN); builder.setColor(Color.GREEN);
StringBuilder sBuilder = new StringBuilder(); StringBuilder sBuilder = new StringBuilder();
itm.forEach(v -> { itm.forEach(v -> {
Member member = null; Member member = null;
if (v.getDiscordID() != null && !v.getDiscordID().isEmpty()) { if (v.getDiscordUser() != null) {
member = event.getGuild().getMemberById(v.getDiscordID()); member = event.getGuild().getMemberById(v.getDiscordUser().getId());
} }
sBuilder.append(v.getUsername()).append(" -> ").append(member == null ? "Unlinked" : member.getAsMention()).append("\r\n"); sBuilder.append(v.getUsername()).append(" -> ").append(member == null ? "Unlinked" : member.getAsMention()).append("\r\n");

View File

@@ -47,18 +47,6 @@ public class RoleManager {
autoWhitelistRoles.add(role); autoWhitelistRoles.add(role);
}); });
} }
/*if (SDLinkConfig.INSTANCE.linkedCommands.enabled) {
commandRoles.clear();
SDLinkConfig.INSTANCE.linkedCommands.permissions.forEach(cmd -> {
if (!cmd.role.isEmpty() && !cmd.role.equals("0")) {
Role role = getRole(errCount, builder, "Command Usage", cmd.role);
if (role != null) {
cmd.commands.forEach(c -> commandRoles.putIfAbsent(c, role));
}
}
});
}*/
} }
/** /**