[CHORE] Nuke whitelist and account linking system

This commit is contained in:
2023-10-20 18:26:41 +02:00
parent 28778c3b8d
commit d089a214ba
30 changed files with 37 additions and 1380 deletions

View File

@@ -4,17 +4,7 @@
*/ */
package com.hypherionmc.sdlink.core.accounts; package com.hypherionmc.sdlink.core.accounts;
import com.hypherionmc.sdlink.core.config.SDLinkConfig;
import com.hypherionmc.sdlink.core.database.SDLinkAccount;
import com.hypherionmc.sdlink.core.discord.BotController;
import com.hypherionmc.sdlink.core.managers.RoleManager;
import com.hypherionmc.sdlink.core.messaging.Result;
import com.hypherionmc.sdlink.core.services.SDLinkPlatform;
import com.mojang.authlib.GameProfile; import com.mojang.authlib.GameProfile;
import net.dv8tion.jda.api.entities.Guild;
import net.dv8tion.jda.api.entities.Member;
import net.dv8tion.jda.api.entities.User;
import net.dv8tion.jda.api.entities.UserSnowflake;
import org.apache.commons.lang3.tuple.Pair; import org.apache.commons.lang3.tuple.Pair;
import org.json.JSONException; import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
@@ -29,8 +19,6 @@ import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.UUID; import java.util.UUID;
import static com.hypherionmc.sdlink.core.managers.DatabaseManager.sdlinkDatabase;
/** /**
* @author HypherionSA * @author HypherionSA
* Represents a Minecraft Account. Used for communication between this library and minecraft * Represents a Minecraft Account. Used for communication between this library and minecraft
@@ -97,290 +85,7 @@ public class MinecraftAccount {
return standard(profile.getName()); return standard(profile.getName());
} }
public static SDLinkAccount getStoredFromUUID(String uuid) { // TODO Verification
sdlinkDatabase.reloadCollection("accounts");
return sdlinkDatabase.findById(uuid, SDLinkAccount.class);
}
/**
* Link a Minecraft account to a discord account
* @param member The discord user
* @param guild The server the command is run from
*/
public Result linkAccount(Member member, Guild guild) {
return this.linkAccount(member, guild, true);
}
public Result linkAccount(Member member, Guild guild, boolean updateNick) {
if (getStoredAccount() == null) {
return Result.error("We couldn't link your Minecraft and Discord Accounts together. If this error persists, please ask a staff member for help");
}
SDLinkAccount account = getStoredAccount();
account.setDiscordID(member.getId());
account.setAddedBy(member.getId());
account.setAccountLinkCode("");
try {
sdlinkDatabase.upsert(account);
String suffix = this.username;
int availableChars = 32 - suffix.length();
String nickname = member.getEffectiveName();
if (nickname.length() > availableChars) {
nickname = nickname.substring(0, availableChars - 3) + "...";
}
String finalnickname = SDLinkConfig.INSTANCE.whitelistingAndLinking.accountLinking.nicknameFormat.replace("%nick%", nickname).replace("%mcname%", suffix);
if (finalnickname.length() > 32) {
finalnickname = finalnickname.substring(0, 28) + "...";
}
if (SDLinkConfig.INSTANCE.whitelistingAndLinking.accountLinking.changeNickname && updateNick) {
try {
member.modifyNickname(finalnickname).queue();
} catch (Exception e) {
if (SDLinkConfig.INSTANCE.generalConfig.debugging) {
e.printStackTrace();
}
}
}
try {
if (RoleManager.getLinkedRole() != null) {
guild.addRoleToMember(UserSnowflake.fromId(member.getId()), RoleManager.getLinkedRole()).queue();
}
} catch (Exception e) {
e.printStackTrace();
}
return Result.success("Your Discord and MC accounts have been linked");
} catch (Exception e) {
e.printStackTrace();
}
return Result.error("Failed to complete account linking. Please inform the server owner");
}
/**
* Unlink a previously linked Discord and Minecraft Account
*/
public Result unlinkAccount(Member member, Guild guild) {
SDLinkAccount account = getStoredAccount();
if (account == null)
return Result.error("No such account found in database");
try {
sdlinkDatabase.remove(account, SDLinkAccount.class);
try {
if (RoleManager.getLinkedRole() != null && member.getRoles().contains(RoleManager.getLinkedRole())) {
guild.removeRoleFromMember(member, RoleManager.getLinkedRole()).queue();
}
} catch (Exception e) {
e.printStackTrace();
}
return Result.success("Your discord and Minecraft accounts are no longer linked");
} catch (Exception e) {
e.printStackTrace();
}
return Result.error("We could not unlink your discord and Minecraft accounts. Please inform the server owner");
}
/**
* Check if account database contains linking information
* and a valid discord user for this account
*/
public boolean isAccountLinked() {
SDLinkAccount account = getStoredAccount();
if (account == null)
return false;
User discordUser = getDiscordUser();
return discordUser != null;
}
/**
* Whitelist a Player on Minecraft and store the info the database
* @param member The Discord Member that executed the command
* @param guild The Discord Server the command was executed in
*/
public Result whitelistAccount(Member member, Guild guild) {
if (getStoredAccount() == null) {
return Result.error("We couldn't link your Minecraft and Discord Accounts together. If this error persists, please ask a staff member for help");
}
SDLinkAccount account = getStoredAccount();
account.setAddedBy(member.getId());
account.setWhitelistCode("");
try {
if (!SDLinkPlatform.minecraftHelper.whitelistPlayer(MinecraftAccount.standard(account.getUsername())).isError()) {
account.setWhitelisted(true);
sdlinkDatabase.upsert(account);
// Auto Linking is enabled, so we link the Discord and MC accounts
if (SDLinkConfig.INSTANCE.whitelistingAndLinking.whitelisting.linkedWhitelist) {
this.linkAccount(member, guild);
}
try {
if (RoleManager.getWhitelistedRole() != null) {
guild.addRoleToMember(member, RoleManager.getWhitelistedRole()).queue();
}
} catch (Exception e) {
e.printStackTrace();
}
return Result.success("Your account has been whitelisted");
} else {
return Result.error("Account is already whitelisted on the Minecraft server");
}
} catch (Exception e) {
e.printStackTrace();
}
return Result.error("Failed to complete whitelisting. Please inform the server owner");
}
/**
* Remove a previously whitelisted account from Minecraft and the database
*/
public Result unwhitelistAccount(Member member, Guild guild) {
SDLinkAccount account = getStoredAccount();
if (account == null)
return Result.error("No such account found in database");
try {
MinecraftAccount minecraftAccount = MinecraftAccount.standard(account.getUsername());
Result whitelistResult = SDLinkPlatform.minecraftHelper.unWhitelistPlayer(minecraftAccount);
if (whitelistResult.isError()) {
return whitelistResult;
} else {
account.setWhitelisted(false);
sdlinkDatabase.upsert(account);
// Auto Linking is enabled. So we unlink the account
if (SDLinkConfig.INSTANCE.whitelistingAndLinking.whitelisting.linkedWhitelist) {
this.unlinkAccount(member, guild);
}
try {
if (RoleManager.getWhitelistedRole() != null && member.getRoles().contains(RoleManager.getWhitelistedRole())) {
guild.removeRoleFromMember(member, RoleManager.getWhitelistedRole()).queue();
}
} catch (Exception e) {
e.printStackTrace();
}
return Result.success("Your account has been removed from the whitelist");
}
} catch (Exception e) {
e.printStackTrace();
}
return Result.error("We could not unwhitelist your account. Please inform the server owner");
}
/**
* Check if the player is whitelisted on the MC server and if the database
* contains an entry for this player
*/
public boolean isAccountWhitelisted() {
SDLinkAccount account = getStoredAccount();
if (account == null)
return false;
return !SDLinkPlatform.minecraftHelper.isPlayerWhitelisted(MinecraftAccount.standard(account.getUsername())).isError() && account.isWhitelisted();
}
public boolean isAutoWhitelisted() {
SDLinkAccount account = getStoredAccount();
if (account == null)
return false;
if (SDLinkConfig.INSTANCE.whitelistingAndLinking.accountLinking.accountLinking) {
User discordUser = getDiscordUser();
if (SDLinkConfig.INSTANCE.generalConfig.debugging) {
System.out.println("[AutoWhiteList] Discord User Null: " + (discordUser == null));
}
if (discordUser != null) {
Member m = BotController.INSTANCE.getJDA().getGuilds().get(0).getMemberById(discordUser.getId());
if (SDLinkConfig.INSTANCE.generalConfig.debugging) {
System.out.println("[AutoWhiteList] Discord Member Null: " + (m == null));
}
if (m == null)
return false;
boolean hasAutoRole = m.getRoles().stream().anyMatch(r -> RoleManager.getAutoWhitelistRoles().contains(r));
if (SDLinkConfig.INSTANCE.generalConfig.debugging) {
System.out.println("[AutoWhiteList] Has Auto Role: " + hasAutoRole);
}
return hasAutoRole && !account.getDiscordID().isEmpty();
}
}
return false;
}
/**
* Retrieve the stored account from the database
*/
public SDLinkAccount getStoredAccount() {
sdlinkDatabase.reloadCollection("accounts");
SDLinkAccount account = sdlinkDatabase.findById(this.uuid.toString(), SDLinkAccount.class);
return account == null ? newDBEntry() : account;
}
/**
* Construct a new Database Entry for this account.
* Must only be used when a new entry is required
*/
public SDLinkAccount newDBEntry() {
SDLinkAccount account = new SDLinkAccount();
account.setOffline(this.isOffline);
account.setUUID(this.uuid.toString());
account.setWhitelisted(false);
account.setUsername(this.username);
return account;
}
/**
* Get the Discord Account name this player is linked to
*/
public String getDiscordName() {
SDLinkAccount storedAccount = getStoredAccount();
if (storedAccount == null || storedAccount.getDiscordID() == null || storedAccount.getDiscordID().isEmpty())
return "Unlinked";
User discordUser = BotController.INSTANCE.getJDA().getUserById(storedAccount.getDiscordID());
return discordUser == null ? "Unlinked" : discordUser.getName();
}
/**
* Get the Discord User this player is linked to
*/
public User getDiscordUser() {
SDLinkAccount storedAccount = getStoredAccount();
if (storedAccount == null || storedAccount.getDiscordID() == null || storedAccount.getDiscordID().isEmpty())
return null;
return BotController.INSTANCE.getJDA().getUserById(storedAccount.getDiscordID());
}
public String getUsername() { public String getUsername() {
return username; return username;

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 = 10; public transient static int configVer = 11;
@Path("general") @Path("general")
@SpecComment("General Mod Config") @SpecComment("General Mod Config")
@@ -50,9 +50,7 @@ public class SDLinkConfig extends ModuleConfig {
@SpecComment("Change in which channel messages appear") @SpecComment("Change in which channel messages appear")
public MessageChannelConfig messageDestinations = new MessageChannelConfig(); public MessageChannelConfig messageDestinations = new MessageChannelConfig();
@Path("whitelistingAndLinking") // TODO Verification Config
@SpecComment("Configure Whitelisting and Account Linking through the bot")
public LinkAndWhitelistConfigSettings whitelistingAndLinking = new LinkAndWhitelistConfigSettings();
@Path("minecraftCommands") @Path("minecraftCommands")
@SpecComment("Execute Minecraft commands in Discord") @SpecComment("Execute Minecraft commands in Discord")

View File

@@ -1,70 +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;
import java.util.ArrayList;
import java.util.List;
/**
* @author HypherionSA
* Config Structure to control Whitelisting and Account Linking
*/
public class LinkAndWhitelistConfigSettings {
@Path("whiteListing")
@SpecComment("Control how the bot handles Whitelisting Players, if at all")
public Whitelisting whitelisting = new Whitelisting();
@Path("accountLinking")
@SpecComment("Control how the bot handles Discord -> MC Account Linking, if at all")
public AccountLinking accountLinking = new AccountLinking();
public static class AccountLinking {
@Path("accountlinking")
@SpecComment("Allow users to Link their MC and Discord accounts")
public boolean accountLinking = false;
@Path("linkedRole")
@SpecComment("If a role ID (or name) is defined here, it will be assigned to players when their MC and Discord accounts are linked")
public String linkedRole = "";
@Path("requireLinking")
@SpecComment("Require users to link their Discord and Minecraft accounts before joining the server")
public boolean requireLinking = false;
@Path("changeNickname")
@SpecComment("Allow nickname changes on account linking")
public boolean changeNickname = true;
@Path("nicknameFormat")
@SpecComment("The nickname format to use for linked accounts, when changeNickname is enabled. %nick% for current nickname/name and %mcname% for the minecraft name")
public String nicknameFormat = "%nick% [MC:%mcname%]";
}
public static class Whitelisting {
@Path("whitelisting")
@SpecComment("Should the bot be allowed to whitelist/un-whitelist players.")
public boolean whitelisting = false;
@Path("linkedWhitelist")
@SpecComment("Automatically link Minecraft and Discord Accounts when a user is whitelisted")
public boolean linkedWhitelist = false;
@Path("autoWhitelist")
@SpecComment("Allow automatically whitelisting and de-whitelisting users with autoWhitelistRoles. WARNING: You cannot use the regular whitelist commands if this is enabled")
public boolean autoWhitelist = false;
@Path("autoWhitelistRoles")
@SpecComment("Users with linked discord accounts, that contain any of these roles will be automatically whitelisted")
public List<String> autoWhitelistRoles = new ArrayList<>();
@Path("autoWhitelistRole")
@SpecComment("If a role ID (or name) is defined here, it will be assigned to players when they are whitelisted")
public String autoWhitelistRole = "";
}
}

View File

@@ -1,3 +1,7 @@
/*
* This file is part of sdlink-core, licensed under the MIT License (MIT).
* Copyright HypherionSA and Contributors
*/
package com.hypherionmc.sdlink.core.config.impl; package com.hypherionmc.sdlink.core.config.impl;
import me.hypherionmc.moonconfig.core.conversion.Path; import me.hypherionmc.moonconfig.core.conversion.Path;

View File

@@ -1,102 +0,0 @@
/*
* This file is part of sdlink-core, licensed under the MIT License (MIT).
* Copyright HypherionSA and Contributors
*/
package com.hypherionmc.sdlink.core.database;
import io.jsondb.annotation.Document;
import io.jsondb.annotation.Id;
/**
* @author HypherionSA
* JSON based database to hold accounts the bot has interacted with.
* This is used for Account Linking and Whitelisting
*/
@Document(collection = "accounts", schemaVersion = "1.0")
public class SDLinkAccount {
@Id
private String UUID;
private String username;
private String addedBy;
private String discordID;
private String accountLinkCode;
private String whitelistCode;
private boolean isWhitelisted;
private boolean isOffline;
public String getAccountLinkCode() {
if (accountLinkCode == null)
return "";
return accountLinkCode;
}
public boolean isOffline() {
return isOffline;
}
public boolean isWhitelisted() {
return isWhitelisted;
}
public String getDiscordID() {
if (discordID == null)
return "";
return discordID;
}
public String getAddedBy() {
if (addedBy == null)
return "";
return addedBy;
}
public String getUsername() {
if (username == null)
return "";
return username;
}
public String getUUID() {
if (UUID == null)
return "";
return UUID;
}
public String getWhitelistCode() {
if (whitelistCode == null)
return "";
return whitelistCode;
}
public void setAccountLinkCode(String accountLinkCode) {
this.accountLinkCode = accountLinkCode;
}
public void setAddedBy(String addedBy) {
this.addedBy = addedBy;
}
public void setDiscordID(String discordID) {
this.discordID = discordID;
}
public void setOffline(boolean offline) {
isOffline = offline;
}
public void setUsername(String username) {
this.username = username;
}
public void setUUID(String UUID) {
this.UUID = UUID;
}
public void setWhitelistCode(String whitelistCode) {
this.whitelistCode = whitelistCode;
}
public void setWhitelisted(boolean whitelisted) {
isWhitelisted = whitelisted;
}
}

View File

@@ -10,7 +10,6 @@ import com.hypherionmc.sdlink.core.discord.events.DiscordEventHandler;
import com.hypherionmc.sdlink.core.managers.DatabaseManager; import com.hypherionmc.sdlink.core.managers.DatabaseManager;
import com.hypherionmc.sdlink.core.managers.EmbedManager; import com.hypherionmc.sdlink.core.managers.EmbedManager;
import com.hypherionmc.sdlink.core.managers.WebhookManager; import com.hypherionmc.sdlink.core.managers.WebhookManager;
import com.hypherionmc.sdlink.core.services.SDLinkPlatform;
import com.hypherionmc.sdlink.core.util.EncryptionUtil; import com.hypherionmc.sdlink.core.util.EncryptionUtil;
import com.hypherionmc.sdlink.core.util.ThreadedEventManager; import com.hypherionmc.sdlink.core.util.ThreadedEventManager;
import com.jagrosh.jdautilities.command.CommandClient; import com.jagrosh.jdautilities.command.CommandClient;
@@ -193,12 +192,7 @@ public class BotController {
* Ensure that whitelisting is set up properly, so the bot can use the feature * Ensure that whitelisting is set up properly, so the bot can use the feature
*/ */
public void checkWhiteListing() { public void checkWhiteListing() {
if (!SDLinkConfig.INSTANCE.whitelistingAndLinking.whitelisting.whitelisting) // TODO Verification
return;
if (SDLinkPlatform.minecraftHelper.checkWhitelisting().isError()) {
getLogger().error("SDLink Whitelisting is enabled, but server side whitelisting is disabled");
}
} }
public Logger getLogger() { public Logger getLogger() {

View File

@@ -4,12 +4,9 @@
*/ */
package com.hypherionmc.sdlink.core.discord.commands; package com.hypherionmc.sdlink.core.discord.commands;
import com.hypherionmc.sdlink.core.config.SDLinkConfig;
import com.hypherionmc.sdlink.core.discord.commands.slash.general.HelpSlashCommand; import com.hypherionmc.sdlink.core.discord.commands.slash.general.HelpSlashCommand;
import com.hypherionmc.sdlink.core.discord.commands.slash.general.PlayerListSlashCommand; import com.hypherionmc.sdlink.core.discord.commands.slash.general.PlayerListSlashCommand;
import com.hypherionmc.sdlink.core.discord.commands.slash.general.ServerStatusSlashCommand; import com.hypherionmc.sdlink.core.discord.commands.slash.general.ServerStatusSlashCommand;
import com.hypherionmc.sdlink.core.discord.commands.slash.linking.*;
import com.hypherionmc.sdlink.core.discord.commands.slash.whitelist.*;
import com.jagrosh.jdautilities.command.CommandClient; import com.jagrosh.jdautilities.command.CommandClient;
import com.jagrosh.jdautilities.command.SlashCommand; import com.jagrosh.jdautilities.command.SlashCommand;
@@ -31,21 +28,7 @@ public class CommandManager {
} }
private void addCommands() { private void addCommands() {
// Register Account Linking commands, if linking is enabled // TODO Verification
if (SDLinkConfig.INSTANCE.whitelistingAndLinking.accountLinking.accountLinking) {
commands.add(new LinkAccountCommand());
commands.add(new ConfirmAccountLinkSlashCommand());
commands.add(new UnlinkAccountSlashCommand());
commands.add(new ViewLinkedAccountsCommand());
}
// Register Whitelist commands, if whitelisting is enabled
if (SDLinkConfig.INSTANCE.whitelistingAndLinking.whitelisting.whitelisting) {
commands.add(new WhitelistAccountCommand());
commands.add(new ConfirmWhitelistSlashCommand());
commands.add(new ViewWhitelistedAccountsSlashCommand());
commands.add(new UnWhitelistAccountSlashCommand());
}
// Enable the Server Status command // Enable the Server Status command
commands.add(new ServerStatusSlashCommand()); commands.add(new ServerStatusSlashCommand());
@@ -55,12 +38,6 @@ public class CommandManager {
// Enable the Help command // Enable the Help command
commands.add(new HelpSlashCommand()); commands.add(new HelpSlashCommand());
// Staff commands
commands.add(new StaffLinkCommand());
commands.add(new StaffUnlinkCommand());
commands.add(new StaffWhitelist());
commands.add(new StaffUnwhitelist());
} }
/** /**

View File

@@ -63,9 +63,7 @@ public class PlayerListSlashCommand extends SDLinkSlashCommand {
p.forEach(account -> { p.forEach(account -> {
sb.append("`").append(account.getUsername()).append("`"); sb.append("`").append(account.getUsername()).append("`");
if (account.getDiscordUser() != null) { // TODO Verification
sb.append(" - ").append(account.getDiscordUser().getAsMention());
}
sb.append("\r\n"); sb.append("\r\n");
}); });

View File

@@ -1,63 +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.linking;
import com.hypherionmc.sdlink.core.accounts.MinecraftAccount;
import com.hypherionmc.sdlink.core.database.SDLinkAccount;
import com.hypherionmc.sdlink.core.discord.commands.slash.SDLinkSlashCommand;
import com.hypherionmc.sdlink.core.messaging.Result;
import com.jagrosh.jdautilities.command.SlashCommandEvent;
import net.dv8tion.jda.api.interactions.commands.OptionType;
import net.dv8tion.jda.api.interactions.commands.build.OptionData;
import java.util.Collections;
import java.util.List;
import static com.hypherionmc.sdlink.core.managers.DatabaseManager.sdlinkDatabase;
/**
* @author HypherionSA
* Command to complete Discord -> MC Account Linking
*/
public class ConfirmAccountLinkSlashCommand extends SDLinkSlashCommand {
public ConfirmAccountLinkSlashCommand() {
super(false);
this.name = "confirmlink";
this.help = "Confirm your Minecraft Account to complete account linking";
this.options = Collections.singletonList(new OptionData(OptionType.INTEGER, "code", "The verification code from the Minecraft Kick Message").setRequired(true));
}
@Override
protected void execute(SlashCommandEvent event) {
int mcCode = event.getOption("code") != null ? event.getOption("code").getAsInt() : 0;
if (mcCode == 0) {
event.reply("You need to provide a verification code").setEphemeral(true).queue();
return;
}
sdlinkDatabase.reloadCollection("accounts");
List<SDLinkAccount> accounts = sdlinkDatabase.findAll(SDLinkAccount.class);
if (accounts.isEmpty()) {
event.reply("Sorry, but this server does not contain any stored players in its database").setEphemeral(true).queue();
return;
}
for (SDLinkAccount account : accounts) {
if (account.getAccountLinkCode().equalsIgnoreCase(String.valueOf(mcCode))) {
MinecraftAccount minecraftAccount = MinecraftAccount.standard(account.getUsername());
Result result = minecraftAccount.linkAccount(event.getMember(), event.getGuild());
event.reply(result.getMessage()).setEphemeral(true).queue();
return;
}
}
event.reply("Sorry, we could not verify your Minecraft account. Please try again").setEphemeral(true).queue();
}
}

View File

@@ -1,78 +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.linking;
import com.hypherionmc.sdlink.core.accounts.MinecraftAccount;
import com.hypherionmc.sdlink.core.database.SDLinkAccount;
import com.hypherionmc.sdlink.core.discord.commands.slash.SDLinkSlashCommand;
import com.hypherionmc.sdlink.core.util.SystemUtils;
import com.jagrosh.jdautilities.command.SlashCommandEvent;
import io.jsondb.InvalidJsonDbApiUsageException;
import net.dv8tion.jda.api.interactions.commands.OptionType;
import net.dv8tion.jda.api.interactions.commands.build.OptionData;
import java.util.Collections;
import static com.hypherionmc.sdlink.core.managers.DatabaseManager.sdlinkDatabase;
/**
* @author HypherionSA
* Command to start the Linking process of a Discord and MC Account
* This will generate the verification code the player needs to enter, to
* verify the account belongs to them
*/
public class LinkAccountCommand extends SDLinkSlashCommand {
public LinkAccountCommand() {
super(false);
this.name = "linkaccount";
this.help = "Start the process of linking your Discord and MC Accounts";
this.options = Collections.singletonList(new OptionData(OptionType.STRING, "mcname", "Your Minecraft Username").setRequired(true));
}
@Override
protected void execute(SlashCommandEvent event) {
String mcName = event.getOption("mcname") != null ? event.getOption("mcname").getAsString() : "";
if (mcName.isEmpty()) {
event.reply("You need to supply your Minecraft username").setEphemeral(true).queue();
return;
}
MinecraftAccount minecraftAccount = MinecraftAccount.standard(mcName);
String confirmCode = String.valueOf(SystemUtils.generateRandomJoinCode());
SDLinkAccount account = minecraftAccount.getStoredAccount();
if (account == null) {
account = minecraftAccount.newDBEntry();
account.setAccountLinkCode(confirmCode);
try {
sdlinkDatabase.insert(account);
event.reply("Please join the Minecraft server and check the Kick Message for your account link code. Then, run the command /confirmlink codehere to finish linking your accounts").setEphemeral(true).queue();
} catch (InvalidJsonDbApiUsageException e) {
e.printStackTrace();
event.reply("Could not start account linking process. Please notify the server owner").setEphemeral(true).queue();
}
} else {
if (account.getDiscordID() != null && !account.getDiscordID().isEmpty()) {
event.reply("Sorry, this Minecraft account is already linked to a discord account").setEphemeral(true).queue();
return;
}
account.setAccountLinkCode(confirmCode);
try {
sdlinkDatabase.upsert(account);
event.reply("Please join the Minecraft server and check the Kick Message for your account link code. Then, run the command /confirmlink codehere to finish linking your accounts").setEphemeral(true).queue();
} catch (InvalidJsonDbApiUsageException e) {
e.printStackTrace();
event.reply("Could not start account linking process. Please notify the server owner").setEphemeral(true).queue();
}
}
}
}

View File

@@ -1,47 +0,0 @@
package com.hypherionmc.sdlink.core.discord.commands.slash.linking;
import com.hypherionmc.sdlink.core.accounts.MinecraftAccount;
import com.hypherionmc.sdlink.core.discord.commands.slash.SDLinkSlashCommand;
import com.hypherionmc.sdlink.core.messaging.Result;
import com.jagrosh.jdautilities.command.SlashCommandEvent;
import net.dv8tion.jda.api.entities.Member;
import net.dv8tion.jda.api.entities.User;
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;
public class StaffLinkCommand extends SDLinkSlashCommand {
public StaffLinkCommand() {
super(true);
this.name = "stafflink";
this.help = "Allow staff members to link other minecraft players, without verification";
List<OptionData> options = new ArrayList<>() {{
add(new OptionData(OptionType.USER, "discorduser", "The discord user the minecraft account belongs to").setRequired(true));
add(new OptionData(OptionType.STRING, "mcname", "The minecraft account to link to the user").setRequired(true));
}};
this.options = options;
}
@Override
protected void execute(SlashCommandEvent event) {
String mcname = event.getOption("mcname").getAsString();
User user = event.getOption("discorduser").getAsUser();
Member member = event.getGuild().getMemberById(user.getId());
if (member == null) {
event.reply(user.getEffectiveName() + " is not a member of this discord server").setEphemeral(true).queue();
return;
}
MinecraftAccount minecraftAccount = MinecraftAccount.standard(mcname);
Result result = minecraftAccount.linkAccount(member, event.getGuild(), false);
event.reply(result.getMessage()).setEphemeral(true).queue();
}
}

View File

@@ -1,58 +0,0 @@
package com.hypherionmc.sdlink.core.discord.commands.slash.linking;
import com.hypherionmc.sdlink.core.accounts.MinecraftAccount;
import com.hypherionmc.sdlink.core.database.SDLinkAccount;
import com.hypherionmc.sdlink.core.discord.commands.slash.SDLinkSlashCommand;
import com.hypherionmc.sdlink.core.messaging.Result;
import com.jagrosh.jdautilities.command.SlashCommandEvent;
import net.dv8tion.jda.api.entities.Member;
import net.dv8tion.jda.api.entities.User;
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 static com.hypherionmc.sdlink.core.managers.DatabaseManager.sdlinkDatabase;
public class StaffUnlinkCommand extends SDLinkSlashCommand {
public StaffUnlinkCommand() {
super(false);
this.name = "staffunlink";
this.help = "Unlink another linked Discord and Minecraft account";
List<OptionData> options = new ArrayList<>() {{
add(new OptionData(OptionType.USER, "discorduser", "The discord user the minecraft account belongs to").setRequired(true));
add(new OptionData(OptionType.STRING, "mcname", "The minecraft account of the linked user").setRequired(true));
}};
this.options = options;
}
@Override
protected void execute(SlashCommandEvent event) {
sdlinkDatabase.reloadCollection("accounts");
List<SDLinkAccount> accounts = sdlinkDatabase.findAll(SDLinkAccount.class);
if (accounts.isEmpty()) {
event.reply("Sorry, but this server does not contain any stored players in its database").setEphemeral(true).queue();
return;
}
String mcname = event.getOption("mcname").getAsString();
User user = event.getOption("discorduser").getAsUser();
Member member = event.getGuild().getMemberById(user.getId());
if (member == null) {
event.reply(user.getEffectiveName() + " is not a member of this discord server").setEphemeral(true).queue();
return;
}
MinecraftAccount minecraftAccount = MinecraftAccount.standard(mcname);
Result result = minecraftAccount.unlinkAccount(member, event.getGuild());
event.reply(result.getMessage()).setEphemeral(true).queue();
}
}

View File

@@ -1,49 +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.linking;
import com.hypherionmc.sdlink.core.accounts.MinecraftAccount;
import com.hypherionmc.sdlink.core.database.SDLinkAccount;
import com.hypherionmc.sdlink.core.discord.commands.slash.SDLinkSlashCommand;
import com.hypherionmc.sdlink.core.messaging.Result;
import com.jagrosh.jdautilities.command.SlashCommandEvent;
import java.util.List;
import static com.hypherionmc.sdlink.core.managers.DatabaseManager.sdlinkDatabase;
/**
* @author HypherionSA
* Command to unlink a discord and minecraft account, that was previously linked
*/
public class UnlinkAccountSlashCommand extends SDLinkSlashCommand {
public UnlinkAccountSlashCommand() {
super(false);
this.name = "unlinkaccount";
this.help = "Unlink your previously linked Discord and Minecraft accounts";
}
@Override
protected void execute(SlashCommandEvent event) {
sdlinkDatabase.reloadCollection("accounts");
List<SDLinkAccount> accounts = sdlinkDatabase.findAll(SDLinkAccount.class);
if (accounts.isEmpty()) {
event.reply("Sorry, but this server does not contain any stored players in its database").setEphemeral(true).queue();
return;
}
for (SDLinkAccount account : accounts) {
if (account.getDiscordID() != null && account.getDiscordID().equalsIgnoreCase(event.getMember().getId())) {
MinecraftAccount minecraftAccount = MinecraftAccount.standard(account.getUsername());
Result result = minecraftAccount.unlinkAccount(event.getMember(), event.getGuild());
event.reply(result.getMessage()).setEphemeral(true).queue();
break;
}
}
}
}

View File

@@ -1,78 +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.linking;
import com.hypherionmc.sdlink.core.database.SDLinkAccount;
import com.hypherionmc.sdlink.core.discord.commands.slash.SDLinkSlashCommand;
import com.hypherionmc.sdlink.core.util.MessageUtil;
import com.jagrosh.jdautilities.command.SlashCommandEvent;
import com.jagrosh.jdautilities.menu.EmbedPaginator;
import net.dv8tion.jda.api.EmbedBuilder;
import net.dv8tion.jda.api.entities.Member;
import net.dv8tion.jda.api.entities.MessageEmbed;
import java.awt.*;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import static com.hypherionmc.sdlink.core.managers.DatabaseManager.sdlinkDatabase;
/**
* @author HypherionSA
* Staff Command to view a list of Linked Minecraft and Discord accounts
*/
public class ViewLinkedAccountsCommand extends SDLinkSlashCommand {
public ViewLinkedAccountsCommand() {
super(true);
this.name = "linkedaccounts";
this.help = "View a list of linked Discord and MC accounts";
}
@Override
protected void execute(SlashCommandEvent event) {
EmbedPaginator.Builder paginator = MessageUtil.defaultPaginator(event);
sdlinkDatabase.reloadCollection("accounts");
List<SDLinkAccount> accounts = sdlinkDatabase.findAll(SDLinkAccount.class);
EmbedBuilder builder = new EmbedBuilder();
ArrayList<MessageEmbed> pages = new ArrayList<>();
AtomicInteger count = new AtomicInteger();
if (accounts.isEmpty()) {
event.reply("There are no linked accounts for this discord").setEphemeral(true).queue();
return;
}
MessageUtil.listBatches(accounts, 10).forEach(itm -> {
count.getAndIncrement();
builder.clear();
builder.setTitle("Linked Accounts - Page " + count + "/" + (int)Math.ceil(((float)accounts.size() / 10)));
builder.setColor(Color.GREEN);
StringBuilder sBuilder = new StringBuilder();
itm.forEach(v -> {
Member member = null;
if (v.getDiscordID() != null && !v.getDiscordID().isEmpty()) {
member = event.getGuild().getMemberById(v.getDiscordID());
}
sBuilder.append(v.getUsername()).append(" -> ").append(member == null ? "Unlinked" : member.getAsMention()).append("\r\n");
});
builder.setDescription(sBuilder);
pages.add(builder.build());
});
paginator.setItems(pages);
EmbedPaginator embedPaginator = paginator.build();
event.replyEmbeds(pages.get(0)).setEphemeral(false).queue(success -> success.retrieveOriginal().queue(msg -> embedPaginator.paginate(msg, 1)));
}
}

View File

@@ -1,69 +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.whitelist;
import com.hypherionmc.sdlink.core.accounts.MinecraftAccount;
import com.hypherionmc.sdlink.core.config.SDLinkConfig;
import com.hypherionmc.sdlink.core.database.SDLinkAccount;
import com.hypherionmc.sdlink.core.discord.commands.slash.SDLinkSlashCommand;
import com.hypherionmc.sdlink.core.messaging.Result;
import com.jagrosh.jdautilities.command.SlashCommandEvent;
import net.dv8tion.jda.api.interactions.commands.OptionType;
import net.dv8tion.jda.api.interactions.commands.build.OptionData;
import java.util.Collections;
import java.util.List;
import static com.hypherionmc.sdlink.core.managers.DatabaseManager.sdlinkDatabase;
/**
* @author HypherionSA
* Command to confirm a Whitelist request
*/
public class ConfirmWhitelistSlashCommand extends SDLinkSlashCommand {
public ConfirmWhitelistSlashCommand() {
super(false);
this.name = "whitelistconfirm";
this.help = "Confirm your Minecraft Account to complete whitelisting";
this.options = Collections.singletonList(new OptionData(OptionType.INTEGER, "code", "The verification code from the Minecraft Kick Message").setRequired(true));
}
@Override
protected void execute(SlashCommandEvent event) {
if (SDLinkConfig.INSTANCE.whitelistingAndLinking.whitelisting.autoWhitelist) {
event.reply("Sorry, but this server uses auto-whitelisting based on roles. This command cannot be used").setEphemeral(true).queue();
return;
}
int mcCode = event.getOption("code") != null ? event.getOption("code").getAsInt() : 0;
if (mcCode == 0) {
event.reply("You need to provide a verification code").setEphemeral(true).queue();
return;
}
sdlinkDatabase.reloadCollection("accounts");
List<SDLinkAccount> accounts = sdlinkDatabase.findAll(SDLinkAccount.class);
if (accounts.isEmpty()) {
event.reply("Sorry, but this server does not contain any stored players in its database").setEphemeral(true).queue();
return;
}
for (SDLinkAccount account : accounts) {
if (account.getWhitelistCode().equalsIgnoreCase(String.valueOf(mcCode))) {
MinecraftAccount minecraftAccount = MinecraftAccount.standard(account.getUsername());
Result result = minecraftAccount.whitelistAccount(event.getMember(), event.getGuild());
event.reply(result.getMessage()).setEphemeral(true).queue();
return;
}
}
event.reply("Sorry, we could not verify your Minecraft account. Please try again").setEphemeral(true).queue();
}
}

View File

@@ -1,58 +0,0 @@
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.discord.commands.slash.SDLinkSlashCommand;
import com.hypherionmc.sdlink.core.messaging.Result;
import com.jagrosh.jdautilities.command.SlashCommandEvent;
import net.dv8tion.jda.api.entities.Member;
import net.dv8tion.jda.api.entities.User;
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 static com.hypherionmc.sdlink.core.managers.DatabaseManager.sdlinkDatabase;
public class StaffUnwhitelist extends SDLinkSlashCommand {
public StaffUnwhitelist() {
super(false);
this.name = "staffunwhitelist";
this.help = "Unwhitelist another linked Discord and Minecraft account";
List<OptionData> options = new ArrayList<>() {{
add(new OptionData(OptionType.USER, "discorduser", "The discord user the minecraft account belongs to").setRequired(true));
add(new OptionData(OptionType.STRING, "mcname", "The minecraft account of the whitelisted user").setRequired(true));
}};
this.options = options;
}
@Override
protected void execute(SlashCommandEvent event) {
sdlinkDatabase.reloadCollection("accounts");
List<SDLinkAccount> accounts = sdlinkDatabase.findAll(SDLinkAccount.class);
if (accounts.isEmpty()) {
event.reply("Sorry, but this server does not contain any stored players in its database").setEphemeral(true).queue();
return;
}
String mcname = event.getOption("mcname").getAsString();
User user = event.getOption("discorduser").getAsUser();
Member member = event.getGuild().getMemberById(user.getId());
if (member == null) {
event.reply(user.getEffectiveName() + " is not a member of this discord server").setEphemeral(true).queue();
return;
}
MinecraftAccount minecraftAccount = MinecraftAccount.standard(mcname);
Result result = minecraftAccount.unwhitelistAccount(member, event.getGuild());
event.reply(result.getMessage()).setEphemeral(true).queue();
}
}

View File

@@ -1,47 +0,0 @@
package com.hypherionmc.sdlink.core.discord.commands.slash.whitelist;
import com.hypherionmc.sdlink.core.accounts.MinecraftAccount;
import com.hypherionmc.sdlink.core.discord.commands.slash.SDLinkSlashCommand;
import com.hypherionmc.sdlink.core.messaging.Result;
import com.jagrosh.jdautilities.command.SlashCommandEvent;
import net.dv8tion.jda.api.entities.Member;
import net.dv8tion.jda.api.entities.User;
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;
public class StaffWhitelist extends SDLinkSlashCommand {
public StaffWhitelist() {
super(true);
this.name = "staffwhitelist";
this.help = "Allow staff members to whitelist other minecraft players, without verification";
List<OptionData> options = new ArrayList<>() {{
add(new OptionData(OptionType.USER, "discorduser", "The discord user the minecraft account belongs to").setRequired(true));
add(new OptionData(OptionType.STRING, "mcname", "The minecraft account to link to the user").setRequired(true));
}};
this.options = options;
}
@Override
protected void execute(SlashCommandEvent event) {
String mcname = event.getOption("mcname").getAsString();
User user = event.getOption("discorduser").getAsUser();
Member member = event.getGuild().getMemberById(user.getId());
if (member == null) {
event.reply(user.getEffectiveName() + " is not a member of this discord server").setEphemeral(true).queue();
return;
}
MinecraftAccount minecraftAccount = MinecraftAccount.standard(mcname);
Result result = minecraftAccount.whitelistAccount(member, event.getGuild());
event.reply(result.getMessage()).setEphemeral(true).queue();
}
}

View File

@@ -1,60 +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.whitelist;
import com.hypherionmc.sdlink.core.accounts.MinecraftAccount;
import com.hypherionmc.sdlink.core.config.SDLinkConfig;
import com.hypherionmc.sdlink.core.database.SDLinkAccount;
import com.hypherionmc.sdlink.core.discord.commands.slash.SDLinkSlashCommand;
import com.hypherionmc.sdlink.core.messaging.Result;
import com.hypherionmc.sdlink.core.services.SDLinkPlatform;
import com.jagrosh.jdautilities.command.SlashCommandEvent;
import java.util.List;
import static com.hypherionmc.sdlink.core.managers.DatabaseManager.sdlinkDatabase;
/**
* @author HypherionSA
* Remove a player from the whitelist, that was previously whitelisted through the bot
*/
public class UnWhitelistAccountSlashCommand extends SDLinkSlashCommand {
public UnWhitelistAccountSlashCommand() {
super(false);
this.name = "unwhitelist";
this.help = "Remove your previously whitelisted Minecraft account";
}
@Override
protected void execute(SlashCommandEvent event) {
if (SDLinkConfig.INSTANCE.whitelistingAndLinking.whitelisting.autoWhitelist) {
event.reply("Sorry, but this server uses auto-whitelisting based on roles. This command cannot be used").setEphemeral(true).queue();
return;
}
sdlinkDatabase.reloadCollection("accounts");
List<SDLinkAccount> accounts = sdlinkDatabase.findAll(SDLinkAccount.class);
if (accounts.isEmpty()) {
event.reply("Sorry, but this server does not contain any stored players in its database").setEphemeral(true).queue();
return;
}
for (SDLinkAccount account : accounts) {
if (account.getAddedBy().equalsIgnoreCase(event.getMember().getId())) {
MinecraftAccount minecraftAccount = MinecraftAccount.standard(account.getUsername());
if (SDLinkPlatform.minecraftHelper.isPlayerWhitelisted(minecraftAccount).isError()) {
event.reply("Your account is not whitelisted in Minecraft. Cannot remove your account").setEphemeral(true).queue();
} else {
Result result = minecraftAccount.unwhitelistAccount(event.getMember(), event.getGuild());
event.reply(result.getMessage()).setEphemeral(true).queue();
}
break;
}
}
}
}

View File

@@ -1,79 +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.whitelist;
import com.hypherionmc.sdlink.core.accounts.MinecraftAccount;
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.jagrosh.jdautilities.command.SlashCommandEvent;
import com.jagrosh.jdautilities.menu.EmbedPaginator;
import net.dv8tion.jda.api.EmbedBuilder;
import net.dv8tion.jda.api.entities.Member;
import net.dv8tion.jda.api.entities.MessageEmbed;
import java.awt.*;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import static com.hypherionmc.sdlink.core.managers.DatabaseManager.sdlinkDatabase;
/**
* @author HypherionSA
* Staff command to view whitelisted players on their server
* This list only contains players whitelisted using the bot
*/
public class ViewWhitelistedAccountsSlashCommand extends SDLinkSlashCommand {
public ViewWhitelistedAccountsSlashCommand() {
super(true);
this.name = "whitelisted";
this.help = "View a list of Whitelisted MC accounts";
}
@Override
protected void execute(SlashCommandEvent event) {
EmbedPaginator.Builder paginator = MessageUtil.defaultPaginator(event);
sdlinkDatabase.reloadCollection("accounts");
List<MinecraftAccount> players = SDLinkPlatform.minecraftHelper.getWhitelistedPlayers();
EmbedBuilder builder = new EmbedBuilder();
ArrayList<MessageEmbed> pages = new ArrayList<>();
AtomicInteger count = new AtomicInteger();
if (players.isEmpty()) {
event.reply("There are no whitelisted accounts for this discord").setEphemeral(true).queue();
return;
}
MessageUtil.listBatches(players, 10).forEach(itm -> {
count.getAndIncrement();
builder.clear();
builder.setTitle("Whitelisted Accounts - Page " + count + "/" + (int)Math.ceil(((float)players.size() / 10)));
builder.setColor(Color.GREEN);
StringBuilder sBuilder = new StringBuilder();
itm.forEach(v -> {
Member member = null;
if (v.getDiscordUser() != null) {
member = event.getGuild().getMemberById(v.getDiscordUser().getId());
}
sBuilder.append(v.getUsername()).append(" -> ").append(member == null ? "Unlinked" : member.getAsMention()).append("\r\n");
});
builder.setDescription(sBuilder);
pages.add(builder.build());
});
paginator.setItems(pages);
EmbedPaginator embedPaginator = paginator.build();
event.replyEmbeds(pages.get(0)).setEphemeral(false).queue(success -> success.retrieveOriginal().queue(msg -> embedPaginator.paginate(msg, 1)));
}
}

View File

@@ -1,86 +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.whitelist;
import com.hypherionmc.sdlink.core.accounts.MinecraftAccount;
import com.hypherionmc.sdlink.core.config.SDLinkConfig;
import com.hypherionmc.sdlink.core.database.SDLinkAccount;
import com.hypherionmc.sdlink.core.discord.commands.slash.SDLinkSlashCommand;
import com.hypherionmc.sdlink.core.services.SDLinkPlatform;
import com.hypherionmc.sdlink.core.util.SystemUtils;
import com.jagrosh.jdautilities.command.SlashCommandEvent;
import io.jsondb.InvalidJsonDbApiUsageException;
import net.dv8tion.jda.api.interactions.commands.OptionType;
import net.dv8tion.jda.api.interactions.commands.build.OptionData;
import java.util.Collections;
import static com.hypherionmc.sdlink.core.managers.DatabaseManager.sdlinkDatabase;
/**
* @author HypherionSA
* Command to start the Whitelisting process
* This will generate the verification code the player needs to enter, to
* verify the account belongs to them
*/
public class WhitelistAccountCommand extends SDLinkSlashCommand {
public WhitelistAccountCommand() {
super(false);
this.name = "whitelist";
this.help = "Start the process of Whitelisting your Minecraft Account";
this.options = Collections.singletonList(new OptionData(OptionType.STRING, "mcname", "Your Minecraft Username").setRequired(true));
}
@Override
protected void execute(SlashCommandEvent event) {
if (SDLinkConfig.INSTANCE.whitelistingAndLinking.whitelisting.autoWhitelist) {
event.reply("Sorry, but this server uses auto-whitelisting based on roles. This command cannot be used").setEphemeral(true).queue();
return;
}
String mcName = event.getOption("mcname") != null ? event.getOption("mcname").getAsString() : "";
if (mcName.isEmpty()) {
event.reply("You need to supply your Minecraft username").setEphemeral(true).queue();
return;
}
MinecraftAccount minecraftAccount = MinecraftAccount.standard(mcName);
String confirmCode = String.valueOf(SystemUtils.generateRandomJoinCode());
SDLinkAccount account = minecraftAccount.getStoredAccount();
if (account == null) {
account = minecraftAccount.newDBEntry();
account.setWhitelistCode(confirmCode);
try {
sdlinkDatabase.insert(account);
event.reply("Please join the Minecraft server and check the Kick Message for your account whitelist code. Then, run the command /whitelistconfirm codehere to finish whitelisting your account").setEphemeral(true).queue();
} catch (InvalidJsonDbApiUsageException e) {
e.printStackTrace();
event.reply("Could not start account whitelisting process. Please notify the server owner").setEphemeral(true).queue();
}
} else {
if (account.isWhitelisted() || !SDLinkPlatform.minecraftHelper.isPlayerWhitelisted(minecraftAccount).isError()) {
event.reply("Sorry, this Minecraft account is already whitelisted").setEphemeral(true).queue();
return;
}
account.setWhitelistCode(confirmCode);
try {
sdlinkDatabase.upsert(account);
event.reply("Please join the Minecraft server and check the Kick Message for your account whitelist code. Then, run the command /whitelistconfirm codehere to finish whitelisting your account").setEphemeral(true).queue();
} catch (InvalidJsonDbApiUsageException e) {
e.printStackTrace();
event.reply("Could not start account whitelisting process. Please notify the server owner").setEphemeral(true).queue();
}
}
}
}

View File

@@ -5,9 +5,6 @@
package com.hypherionmc.sdlink.core.discord.events; package com.hypherionmc.sdlink.core.discord.events;
import com.hypherionmc.craterlib.core.event.CraterEventBus; import com.hypherionmc.craterlib.core.event.CraterEventBus;
import com.hypherionmc.sdlink.core.accounts.MinecraftAccount;
import com.hypherionmc.sdlink.core.config.SDLinkConfig;
import com.hypherionmc.sdlink.core.database.SDLinkAccount;
import com.hypherionmc.sdlink.core.discord.BotController; import com.hypherionmc.sdlink.core.discord.BotController;
import com.hypherionmc.sdlink.core.discord.commands.slash.general.ServerStatusSlashCommand; import com.hypherionmc.sdlink.core.discord.commands.slash.general.ServerStatusSlashCommand;
import com.hypherionmc.sdlink.core.discord.hooks.BotReadyHooks; import com.hypherionmc.sdlink.core.discord.hooks.BotReadyHooks;
@@ -16,9 +13,7 @@ import com.hypherionmc.sdlink.core.discord.hooks.MinecraftCommandHook;
import com.hypherionmc.sdlink.core.events.SDLinkReadyEvent; import com.hypherionmc.sdlink.core.events.SDLinkReadyEvent;
import com.hypherionmc.sdlink.core.managers.CacheManager; import com.hypherionmc.sdlink.core.managers.CacheManager;
import com.hypherionmc.sdlink.core.managers.ChannelManager; import com.hypherionmc.sdlink.core.managers.ChannelManager;
import com.hypherionmc.sdlink.core.managers.DatabaseManager;
import com.hypherionmc.sdlink.core.managers.PermissionChecker; import com.hypherionmc.sdlink.core.managers.PermissionChecker;
import com.hypherionmc.sdlink.core.services.SDLinkPlatform;
import net.dv8tion.jda.api.JDA; import net.dv8tion.jda.api.JDA;
import net.dv8tion.jda.api.events.channel.ChannelCreateEvent; import net.dv8tion.jda.api.events.channel.ChannelCreateEvent;
import net.dv8tion.jda.api.events.channel.ChannelDeleteEvent; import net.dv8tion.jda.api.events.channel.ChannelDeleteEvent;
@@ -33,11 +28,6 @@ import net.dv8tion.jda.api.events.session.ReadyEvent;
import net.dv8tion.jda.api.hooks.ListenerAdapter; import net.dv8tion.jda.api.hooks.ListenerAdapter;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import java.util.List;
import java.util.Optional;
import static com.hypherionmc.sdlink.core.managers.DatabaseManager.sdlinkDatabase;
/** /**
* @author HypherionSA * @author HypherionSA
* Class to provide Hooks for Discord Events, such as message received, and login * Class to provide Hooks for Discord Events, such as message received, and login
@@ -139,26 +129,6 @@ public class DiscordEventHandler extends ListenerAdapter {
if (event.getUser().isBot()) if (event.getUser().isBot())
return; return;
if (!SDLinkConfig.INSTANCE.whitelistingAndLinking.whitelisting.whitelisting) // TODO Verification
return;
try {
List<SDLinkAccount> accounts = DatabaseManager.sdlinkDatabase.getCollection(SDLinkAccount.class);
Optional<SDLinkAccount> account = accounts.stream().filter(a -> a.getDiscordID().equalsIgnoreCase(event.getUser().getId())).findFirst();
account.ifPresent(a -> {
MinecraftAccount acc = MinecraftAccount.standard(a.getUsername());
if (acc != null) {
DatabaseManager.sdlinkDatabase.remove(a, SDLinkAccount.class);
SDLinkPlatform.minecraftHelper.banPlayer(acc);
sdlinkDatabase.reloadCollection("accounts");
}
});
} catch (Exception e) {
if (SDLinkConfig.INSTANCE.generalConfig.debugging) {
e.printStackTrace();
}
}
} }
} }

View File

@@ -1,18 +1,18 @@
/*
* This file is part of sdlink-core, licensed under the MIT License (MIT).
* Copyright HypherionSA and Contributors
*/
package com.hypherionmc.sdlink.core.discord.hooks; package com.hypherionmc.sdlink.core.discord.hooks;
import com.hypherionmc.sdlink.core.config.SDLinkConfig; import com.hypherionmc.sdlink.core.config.SDLinkConfig;
import com.hypherionmc.sdlink.core.database.SDLinkAccount;
import com.hypherionmc.sdlink.core.services.SDLinkPlatform; import com.hypherionmc.sdlink.core.services.SDLinkPlatform;
import net.dv8tion.jda.api.entities.ISnowflake; import net.dv8tion.jda.api.entities.ISnowflake;
import net.dv8tion.jda.api.events.message.MessageReceivedEvent; import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
import java.util.List; import java.util.List;
import java.util.Optional;
import java.util.Set; import java.util.Set;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import static com.hypherionmc.sdlink.core.managers.DatabaseManager.sdlinkDatabase;
public class MinecraftCommandHook { public class MinecraftCommandHook {
public static void discordMessageEvent(MessageReceivedEvent event) { public static void discordMessageEvent(MessageReceivedEvent event) {
@@ -26,19 +26,18 @@ public class MinecraftCommandHook {
roles.add(event.getMember().getIdLong()); roles.add(event.getMember().getIdLong());
roles.add(0L); roles.add(0L);
sdlinkDatabase.reloadCollection("accounts"); // TODO Verification
List<SDLinkAccount> accounts = sdlinkDatabase.findAll(SDLinkAccount.class);
Optional<SDLinkAccount> account = accounts.stream().filter(u -> u.getDiscordID().equals(event.getMember().getId())).findFirst();
Integer permLevel = SDLinkConfig.INSTANCE.linkedCommands.permissions.stream().filter(r -> roles.contains(Long.parseLong(r.role))).map(r -> r.permissionLevel).max(Integer::compareTo).orElse(-1); Integer permLevel = SDLinkConfig.INSTANCE.linkedCommands.permissions.stream().filter(r -> roles.contains(Long.parseLong(r.role))).map(r -> r.permissionLevel).max(Integer::compareTo).orElse(-1);
List<String> commands = SDLinkConfig.INSTANCE.linkedCommands.permissions.stream().filter(c -> roles.contains(Long.parseLong(c.role))).flatMap(c -> c.commands.stream()).filter(s -> !s.isEmpty()).toList(); List<String> commands = SDLinkConfig.INSTANCE.linkedCommands.permissions.stream().filter(c -> roles.contains(Long.parseLong(c.role))).flatMap(c -> c.commands.stream()).filter(s -> !s.isEmpty()).toList();
String raw = event.getMessage().getContentRaw().substring(SDLinkConfig.INSTANCE.linkedCommands.prefix.length()); String raw = event.getMessage().getContentRaw().substring(SDLinkConfig.INSTANCE.linkedCommands.prefix.length());
// TODO Verification
if (commands.stream().anyMatch(raw::startsWith)) { if (commands.stream().anyMatch(raw::startsWith)) {
SDLinkPlatform.minecraftHelper.executeMinecraftCommand(raw, Integer.MAX_VALUE, event, account.orElse(null)); SDLinkPlatform.minecraftHelper.executeMinecraftCommand(raw, Integer.MAX_VALUE, event, null);
} else { } else {
SDLinkPlatform.minecraftHelper.executeMinecraftCommand(raw, permLevel, event, account.orElse(null)); SDLinkPlatform.minecraftHelper.executeMinecraftCommand(raw, permLevel, event, null);
} }
} }
} }

View File

@@ -4,11 +4,8 @@
*/ */
package com.hypherionmc.sdlink.core.managers; package com.hypherionmc.sdlink.core.managers;
import com.hypherionmc.sdlink.core.database.SDLinkAccount;
import io.jsondb.JsonDBTemplate; import io.jsondb.JsonDBTemplate;
import java.util.Collections;
/** /**
* @author HypherionSA * @author HypherionSA
* Helper class to initialize the JSON database * Helper class to initialize the JSON database
@@ -18,14 +15,10 @@ public class DatabaseManager {
public static final JsonDBTemplate sdlinkDatabase = new JsonDBTemplate("sdlinkstorage", "com.hypherionmc.sdlink.core.database"); public static final JsonDBTemplate sdlinkDatabase = new JsonDBTemplate("sdlinkstorage", "com.hypherionmc.sdlink.core.database");
static { static {
sdlinkDatabase.setupDB(Collections.singleton(SDLinkAccount.class));
} }
public static void initialize() { public static void initialize() {
if (!sdlinkDatabase.collectionExists(SDLinkAccount.class)) { // Todo Verification
sdlinkDatabase.createCollection(SDLinkAccount.class);
}
sdlinkDatabase.reloadCollection("accounts");
} }
} }

View File

@@ -1,3 +1,7 @@
/*
* This file is part of sdlink-core, licensed under the MIT License (MIT).
* Copyright HypherionSA and Contributors
*/
package com.hypherionmc.sdlink.core.managers; package com.hypherionmc.sdlink.core.managers;
import com.google.gson.Gson; import com.google.gson.Gson;

View File

@@ -49,10 +49,6 @@ public class PermissionChecker {
* Run the permission checker to see if the bot has all the required permissions * Run the permission checker to see if the bot has all the required permissions
*/ */
public static void checkBotSetup() { public static void checkBotSetup() {
if (SDLinkConfig.INSTANCE.whitelistingAndLinking.accountLinking.changeNickname) {
BOT_PERMS.add(Permission.NICKNAME_MANAGE);
}
StringBuilder builder = new StringBuilder(); StringBuilder builder = new StringBuilder();
builder.append("\r\n").append("******************* Simple Discord Link Errors *******************").append("\r\n"); builder.append("\r\n").append("******************* Simple Discord Link Errors *******************").append("\r\n");
AtomicInteger errCount = new AtomicInteger(); AtomicInteger errCount = new AtomicInteger();

View File

@@ -4,7 +4,6 @@
*/ */
package com.hypherionmc.sdlink.core.managers; package com.hypherionmc.sdlink.core.managers;
import com.hypherionmc.sdlink.core.config.SDLinkConfig;
import com.hypherionmc.sdlink.core.discord.BotController; import com.hypherionmc.sdlink.core.discord.BotController;
import com.hypherionmc.sdlink.core.util.SystemUtils; import com.hypherionmc.sdlink.core.util.SystemUtils;
import net.dv8tion.jda.api.entities.Role; import net.dv8tion.jda.api.entities.Role;
@@ -20,9 +19,6 @@ import java.util.concurrent.atomic.AtomicInteger;
*/ */
public class RoleManager { public class RoleManager {
private static Role whitelistedRole;
private static Role linkedRole;
//private static final HashMap<String, Role> commandRoles = new HashMap<>();
private static final Set<Role> autoWhitelistRoles = new HashSet<>(); private static final Set<Role> autoWhitelistRoles = new HashSet<>();
/** /**
@@ -31,22 +27,7 @@ public class RoleManager {
* @param builder * @param builder
*/ */
public static void loadRequiredRoles(AtomicInteger errCount, StringBuilder builder) { public static void loadRequiredRoles(AtomicInteger errCount, StringBuilder builder) {
if (!SDLinkConfig.INSTANCE.whitelistingAndLinking.whitelisting.autoWhitelistRole.isEmpty()) { // TODO Verification Roles
whitelistedRole = getRole(errCount, builder, "Whitelist", SDLinkConfig.INSTANCE.whitelistingAndLinking.whitelisting.autoWhitelistRole);
}
if (!SDLinkConfig.INSTANCE.whitelistingAndLinking.accountLinking.linkedRole.isEmpty()) {
linkedRole = getRole(errCount, builder, "Linked Account", SDLinkConfig.INSTANCE.whitelistingAndLinking.accountLinking.linkedRole);
}
if (SDLinkConfig.INSTANCE.whitelistingAndLinking.whitelisting.whitelisting) {
SDLinkConfig.INSTANCE.whitelistingAndLinking.whitelisting.autoWhitelistRoles.forEach(r -> {
Role role = getRole(errCount, builder, "Auto Whitelist Role", r);
if (role != null)
autoWhitelistRoles.add(role);
});
}
} }
/** /**
@@ -84,20 +65,4 @@ public class RoleManager {
return null; return null;
} }
public static Role getLinkedRole() {
return linkedRole;
}
public static Role getWhitelistedRole() {
return whitelistedRole;
}
//public static HashMap<String, Role> getCommandRoles() {
//return commandRoles;
//}
public static Set<Role> getAutoWhitelistRoles() {
return autoWhitelistRoles;
}
} }

View File

@@ -246,8 +246,9 @@ public final class DiscordMessage {
} }
@Nonnull @Nonnull
private EmbedBuilder fromData(@Nonnull DataObject data) private EmbedBuilder fromData(@Nonnull DataObject data) {
{ // TODO Fix Error with empty URL links
Checks.notNull(data, "DataObject"); Checks.notNull(data, "DataObject");
EmbedBuilder builder = new EmbedBuilder(); EmbedBuilder builder = new EmbedBuilder();

View File

@@ -42,11 +42,7 @@ public final class DiscordMessageBuilder {
if (SDLinkConfig.INSTANCE.chatConfig.useLinkedNames && this.author != DiscordAuthor.SERVER) { if (SDLinkConfig.INSTANCE.chatConfig.useLinkedNames && this.author != DiscordAuthor.SERVER) {
MinecraftAccount account = MinecraftAccount.standard(author.getRawUsername()); MinecraftAccount account = MinecraftAccount.standard(author.getRawUsername());
User discordUser = account.getDiscordUser(); // TODO Verification
if (account != null && discordUser != null) {
this.author = DiscordAuthor.of(discordUser.getEffectiveName(), author.getUuid(), author.getRawUsername());
}
} }
return this; return this;

View File

@@ -1,3 +1,7 @@
/*
* This file is part of sdlink-core, licensed under the MIT License (MIT).
* Copyright HypherionSA and Contributors
*/
package com.hypherionmc.sdlink.core.messaging.embeds; package com.hypherionmc.sdlink.core.messaging.embeds;
import java.util.ArrayList; import java.util.ArrayList;

View File

@@ -5,7 +5,6 @@
package com.hypherionmc.sdlink.core.services.helpers; package com.hypherionmc.sdlink.core.services.helpers;
import com.hypherionmc.sdlink.core.accounts.MinecraftAccount; import com.hypherionmc.sdlink.core.accounts.MinecraftAccount;
import com.hypherionmc.sdlink.core.database.SDLinkAccount;
import com.hypherionmc.sdlink.core.messaging.Result; import com.hypherionmc.sdlink.core.messaging.Result;
import net.dv8tion.jda.api.entities.Member; import net.dv8tion.jda.api.entities.Member;
import net.dv8tion.jda.api.events.message.MessageReceivedEvent; import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
@@ -22,15 +21,13 @@ public interface IMinecraftHelper {
void discordMessageReceived(Member member, String message); void discordMessageReceived(Member member, String message);
Result checkWhitelisting(); Result checkWhitelisting();
Result isPlayerWhitelisted(MinecraftAccount account);
Result whitelistPlayer(MinecraftAccount account);
Result unWhitelistPlayer(MinecraftAccount account);
List<MinecraftAccount> getWhitelistedPlayers();
Pair<Integer, Integer> getPlayerCounts(); Pair<Integer, Integer> getPlayerCounts();
List<MinecraftAccount> getOnlinePlayers(); List<MinecraftAccount> getOnlinePlayers();
long getServerUptime(); long getServerUptime();
String getServerVersion(); String getServerVersion();
void executeMinecraftCommand(String command, int permLevel, MessageReceivedEvent event, @Nullable SDLinkAccount account); // TODO Verification
void executeMinecraftCommand(String command, int permLevel, MessageReceivedEvent event, @Nullable Object account);
boolean isOnlineMode(); boolean isOnlineMode();
void banPlayer(MinecraftAccount acc); void banPlayer(MinecraftAccount acc);
} }