Reset command fixes

Now it's disabling and enabling the plugin
Some changes were made to handle this as well
Fixed main thread checks, the plugin may not be enabled in the main thread
This commit is contained in:
Norbi Peti 2018-07-20 12:43:17 +02:00
parent de857fef0b
commit 557eac2292
No known key found for this signature in database
GPG key ID: DBA4C4549A927E56
4 changed files with 53 additions and 35 deletions

View file

@ -42,7 +42,7 @@ public final class DPUtils {
public static <T> T perform(IRequest<T> action, long timeout, TimeUnit unit) throws TimeoutException, InterruptedException {
if (DiscordPlugin.SafeMode)
return null;
if (Thread.currentThread() == DiscordPlugin.mainThread) // TODO: Ignore shutdown message <--
if (Bukkit.isPrimaryThread()) // TODO: Ignore shutdown message <--
// throw new RuntimeException("Tried to wait for a Discord request on the main thread. This could cause lag.");
Bukkit.getLogger().warning("Waiting for a Discord request on the main thread!");
return RequestBuffer.request(action).get(timeout, unit); // Let the pros handle this
@ -55,7 +55,7 @@ public final class DPUtils {
public static <T> T perform(IRequest<T> action) {
if (DiscordPlugin.SafeMode)
return null;
if (Thread.currentThread() == DiscordPlugin.mainThread) // TODO: Ignore shutdown message <--
if (Bukkit.isPrimaryThread()) // TODO: Ignore shutdown message <--
// throw new RuntimeException("Tried to wait for a Discord request on the main thread. This could cause lag.");
Bukkit.getLogger().warning("Waiting for a Discord request on the main thread!");
return RequestBuffer.request(action).get(); // Let the pros handle this
@ -67,7 +67,7 @@ public final class DPUtils {
public static Void perform(IVoidRequest action) {
if (DiscordPlugin.SafeMode)
return null;
if (Thread.currentThread() == DiscordPlugin.mainThread)
if (Bukkit.isPrimaryThread())
throw new RuntimeException("Tried to wait for a Discord request on the main thread. This could cause lag.");
return RequestBuffer.request(action).get(); // Let the pros handle this
}

View file

@ -3,6 +3,7 @@ package buttondevteam.discordplugin;
import buttondevteam.discordplugin.commands.DiscordCommandBase;
import buttondevteam.discordplugin.listeners.*;
import buttondevteam.discordplugin.mccommands.DiscordMCCommandBase;
import buttondevteam.discordplugin.mccommands.ResetMCCommand;
import buttondevteam.lib.TBMCCoreAPI;
import buttondevteam.lib.chat.Channel;
import buttondevteam.lib.chat.TBMCChatAPI;
@ -42,7 +43,6 @@ import java.util.stream.Collectors;
public class DiscordPlugin extends JavaPlugin implements IListener<ReadyEvent> {
private static final String SubredditURL = "https://www.reddit.com/r/ChromaGamers";
private static boolean stop = false;
static Thread mainThread;
public static IDiscordClient dc;
public static DiscordPlugin plugin;
public static boolean SafeMode = true;
@ -52,6 +52,7 @@ public class DiscordPlugin extends JavaPlugin implements IListener<ReadyEvent> {
@SuppressWarnings("unchecked")
@Override
public void onEnable() {
stop = false; //If not the first time
try {
Bukkit.getLogger().info("Initializing DiscordPlugin...");
try {
@ -69,7 +70,6 @@ public class DiscordPlugin extends JavaPlugin implements IListener<ReadyEvent> {
cb.withToken(Files.readFirstLine(new File("TBMC", "Token.txt"), StandardCharsets.UTF_8));
dc = cb.login();
dc.getDispatcher().registerListener(this);
mainThread = Thread.currentThread();
} catch (Exception e) {
e.printStackTrace();
Bukkit.getPluginManager().disablePlugin(this);
@ -105,7 +105,7 @@ public class DiscordPlugin extends JavaPlugin implements IListener<ReadyEvent> {
}
if (mainServer == null || devServer == null)
return; // Retry
if (!TBMCCoreAPI.IsTestServer()) {
if (!TBMCCoreAPI.IsTestServer()) { //Don't change conditions here, see mainServer=devServer=null in onDisable()
botchannel = mainServer.getChannelByID(209720707188260864L); // bot
annchannel = mainServer.getChannelByID(126795071927353344L); // announcements
genchannel = mainServer.getChannelByID(125813020357165056L); // general
@ -157,7 +157,10 @@ public class DiscordPlugin extends JavaPlugin implements IListener<ReadyEvent> {
}
DiscordCommandBase.registerCommands();
if (getConfig().getBoolean("serverup", false)) {
if (ResetMCCommand.resetting)
ChromaBot.getInstance().sendMessage("", new EmbedBuilder().withColor(Color.CYAN)
.withTitle("Discord plugin restarted - chat connected.").build()); //Really important to note the chat, hmm
else if (getConfig().getBoolean("serverup", false)) {
ChromaBot.getInstance().sendMessage("", new EmbedBuilder().withColor(Color.YELLOW)
.withTitle("Server recovered from a crash - chat connected.").build());
val thr = new Throwable(
@ -167,6 +170,9 @@ public class DiscordPlugin extends JavaPlugin implements IListener<ReadyEvent> {
} else
ChromaBot.getInstance().sendMessage("", new EmbedBuilder().withColor(Color.GREEN)
.withTitle("Server started - chat connected.").build());
ResetMCCommand.resetting = false; //This is the last event handling this flag
getConfig().set("serverup", true);
saveConfig();
DPUtils.performNoWait(() -> {
@ -237,6 +243,7 @@ public class DiscordPlugin extends JavaPlugin implements IListener<ReadyEvent> {
stop = true;
for (val entry : MCChatListener.ConnectedSenders.entrySet())
MCListener.callEventExcludingSome(new PlayerQuitEvent(entry.getValue(), ""));
MCChatListener.ConnectedSenders.clear();
getConfig().set("lastannouncementtime", lastannouncementtime);
getConfig().set("lastseentime", lastseentime);
getConfig().set("serverup", false);
@ -256,18 +263,22 @@ public class DiscordPlugin extends JavaPlugin implements IListener<ReadyEvent> {
saveConfig();
MCChatListener.forAllMCChat(ch -> {
try {
DiscordPlugin.sendMessageToChannelWait(ch, "",
new EmbedBuilder().withColor(Restart ? Color.ORANGE : Color.RED)
.withTitle(Restart ? "Server restarting" : "Server stopping")
.withDescription(
Bukkit.getOnlinePlayers().size() > 0
? (DPUtils
.sanitizeString(Bukkit.getOnlinePlayers().stream()
.map(Player::getDisplayName).collect(Collectors.joining(", ")))
+ (Bukkit.getOnlinePlayers().size() == 1 ? " was " : " were ")
+ "asked *politely* to leave the server for a bit.")
: "")
.build(), 5, TimeUnit.SECONDS);
if (ResetMCCommand.resetting)
DiscordPlugin.sendMessageToChannelWait(ch, "",
new EmbedBuilder().withColor(Color.ORANGE).withTitle("Discord plugin restarting").build());
else
DiscordPlugin.sendMessageToChannelWait(ch, "",
new EmbedBuilder().withColor(Restart ? Color.ORANGE : Color.RED)
.withTitle(Restart ? "Server restarting" : "Server stopping")
.withDescription(
Bukkit.getOnlinePlayers().size() > 0
? (DPUtils
.sanitizeString(Bukkit.getOnlinePlayers().stream()
.map(Player::getDisplayName).collect(Collectors.joining(", ")))
+ (Bukkit.getOnlinePlayers().size() == 1 ? " was " : " were ")
+ "asked *politely* to leave the server for a bit.")
: "")
.build(), 5, TimeUnit.SECONDS);
} catch (TimeoutException | InterruptedException e) {
e.printStackTrace();
}
@ -279,6 +290,8 @@ public class DiscordPlugin extends JavaPlugin implements IListener<ReadyEvent> {
ChromaBot.delete();
dc.changePresence(StatusType.IDLE, ActivityType.PLAYING, "Chromacraft"); //No longer using the same account for testing
dc.logout();
mainServer = devServer = null; //Fetch servers and channels again
sent = false;
} catch (Exception e) {
TBMCCoreAPI.SendException("An error occured while disabling DiscordPlugin!", e);
}

View file

@ -138,7 +138,7 @@ public class MCChatListener implements Listener, IListener<MessageReceivedEvent>
}
val iterator = lastmsgCustom.iterator();
while (iterator.hasNext()) { //TODO: Add cmd to fix mcchat
while (iterator.hasNext()) {
val lmd = iterator.next();
if ((e.isFromcmd() || isdifferentchannel.test(lmd.channel)) //Test if msg is from Discord
&& e.getChannel().ID.equals(lmd.mcchannel.ID) //If it's from a command, the command msg has been deleted, so we need to send it
@ -362,6 +362,14 @@ public class MCChatListener implements Listener, IListener<MessageReceivedEvent>
if (wait)
recthread.join(5000);
}
lastmsgdata = null;
lastmsgPerUser.clear();
lastmsgCustom.clear();
lastmsgfromd.clear();
ConnectedSenders.clear();
lastlist = lastlistp = ListC = 0;
UnconnectedSenders.clear();
recthread = sendthread = null;
} catch (InterruptedException e) {
e.printStackTrace(); //This thread shouldn't be interrupted
}

View file

@ -1,7 +1,6 @@
package buttondevteam.discordplugin.mccommands;
import buttondevteam.discordplugin.DiscordPlugin;
import buttondevteam.discordplugin.listeners.MCChatListener;
import buttondevteam.lib.chat.CommandClass;
import buttondevteam.lib.chat.TBMCCommandBase;
import org.bukkit.Bukkit;
@ -9,27 +8,25 @@ import org.bukkit.command.CommandSender;
@CommandClass(path = "discord reset", modOnly = true)
public class ResetMCCommand extends TBMCCommandBase { //Not player-only, so not using DiscordMCCommandBase
public static boolean resetting = false;
@Override
public boolean OnCommand(CommandSender sender, String s, String[] strings) {
Bukkit.getScheduler().runTaskAsynchronously(DiscordPlugin.plugin, () -> {
sender.sendMessage("§bStopping MCChatListener...");
DiscordPlugin.SafeMode = true;
MCChatListener.stop(true);
if (DiscordPlugin.dc.isLoggedIn()) {
sender.sendMessage("§bLogging out...");
DiscordPlugin.dc.logout();
} else
sender.sendMessage("§bWe're not logged in.");
sender.sendMessage("§bLogging in...");
DiscordPlugin.dc.login();
DiscordPlugin.SafeMode = false;
sender.sendMessage("§bChromaBot has been reset!");
resetting = true; //Turned off after sending enable message (ReadyEvent)
sender.sendMessage("§bDisabling DiscordPlugin...");
Bukkit.getPluginManager().disablePlugin(DiscordPlugin.plugin);
sender.sendMessage("§bEnabling DiscordPlugin...");
Bukkit.getPluginManager().enablePlugin(DiscordPlugin.plugin);
sender.sendMessage("§bReset finished!");
});
return false;
return true;
}
@Override
public String[] GetHelpText(String s) {
return new String[0];
return new String[]{ //
"§6---- Reset ChromaBot ----", //
"This command stops the Minecraft chat and relogs the bot." //
};
}
}