More abstractions

- Abstracted UpdateCheckerTask
- Merged PluginProvider into the PluginManagers
This commit is contained in:
Frank van der Heijden 2020-07-05 16:07:36 +02:00
parent 23e8e80191
commit e67b20dee0
No known key found for this signature in database
GPG key ID: 26DA56488D314D11
40 changed files with 546 additions and 347 deletions

View file

@ -11,23 +11,19 @@ import java.util.Map;
import net.frankheijden.serverutils.bukkit.commands.CommandPlugins;
import net.frankheijden.serverutils.bukkit.commands.CommandServerUtils;
import net.frankheijden.serverutils.bukkit.entities.BukkitPlugin;
import net.frankheijden.serverutils.bukkit.listeners.MainListener;
import net.frankheijden.serverutils.bukkit.managers.VersionManager;
import net.frankheijden.serverutils.bukkit.listeners.BukkitListener;
import net.frankheijden.serverutils.bukkit.managers.BukkitPluginManager;
import net.frankheijden.serverutils.bukkit.entities.BukkitReflection;
import net.frankheijden.serverutils.bukkit.reflection.RCommandMap;
import net.frankheijden.serverutils.bukkit.reflection.RCraftServer;
import net.frankheijden.serverutils.bukkit.tasks.UpdateCheckerTask;
import net.frankheijden.serverutils.bukkit.utils.BukkitUtils;
import net.frankheijden.serverutils.common.ServerUtilsApp;
import net.frankheijden.serverutils.common.config.Config;
import net.frankheijden.serverutils.common.config.Messenger;
import net.frankheijden.serverutils.common.providers.PluginProvider;
import org.bstats.bukkit.Metrics;
import org.bukkit.Bukkit;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.defaults.PluginsCommand;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.java.JavaPlugin;
public class ServerUtils extends JavaPlugin implements CommandExecutor {
@ -46,7 +42,7 @@ public class ServerUtils extends JavaPlugin implements CommandExecutor {
instance = this;
this.plugin = new BukkitPlugin(this);
ServerUtilsApp.init(plugin);
ServerUtilsApp.init(this, plugin);
new Metrics(this, ServerUtilsApp.BSTATS_METRICS_ID);
new BukkitReflection();
@ -55,10 +51,10 @@ public class ServerUtils extends JavaPlugin implements CommandExecutor {
commandManager.registerCommand(new CommandServerUtils());
this.commandPlugins = null;
PluginProvider<Plugin> provider = plugin.getPluginProvider();
BukkitPluginManager manager = plugin.getPluginManager();
CommandCompletions<BukkitCommandCompletionContext> completions = commandManager.getCommandCompletions();
completions.registerAsyncCompletion("plugins", context -> provider.getPluginNames());
completions.registerAsyncCompletion("pluginJars", context -> provider.getPluginFileNames());
completions.registerAsyncCompletion("plugins", context -> manager.getPluginNames());
completions.registerAsyncCompletion("pluginJars", context -> manager.getPluginFileNames());
completions.registerAsyncCompletion("supportedConfigs ", context -> CommandServerUtils.getSupportedConfigs());
completions.registerAsyncCompletion("commands", context -> {
try {
@ -70,10 +66,9 @@ public class ServerUtils extends JavaPlugin implements CommandExecutor {
});
reload();
Bukkit.getPluginManager().registerEvents(new MainListener(), this);
Bukkit.getPluginManager().registerEvents(new BukkitListener(), this);
new VersionManager();
checkForUpdates();
ServerUtilsApp.checkForUpdates();
}
public static ServerUtils getInstance() {
@ -131,10 +126,4 @@ public class ServerUtils extends JavaPlugin implements CommandExecutor {
public PaperCommandManager getCommandManager() {
return commandManager;
}
private void checkForUpdates() {
if (Config.getInstance().getConfig().getBoolean("settings.check-updates")) {
UpdateCheckerTask.start(BukkitUtils.wrap(Bukkit.getConsoleSender()), true);
}
}
}

View file

@ -7,18 +7,16 @@ import co.aikar.commands.annotation.Default;
import co.aikar.commands.annotation.Description;
import co.aikar.commands.annotation.Subcommand;
import net.frankheijden.serverutils.bukkit.ServerUtils;
import net.frankheijden.serverutils.bukkit.managers.BukkitPluginManager;
import net.frankheijden.serverutils.bukkit.utils.BukkitUtils;
import net.frankheijden.serverutils.common.commands.Plugins;
import net.frankheijden.serverutils.common.config.Messenger;
import net.frankheijden.serverutils.common.providers.PluginProvider;
import org.bukkit.command.CommandSender;
import org.bukkit.plugin.Plugin;
@CommandAlias("plugins|pl")
public class CommandPlugins extends BaseCommand {
private static final PluginProvider<Plugin> provider = ServerUtils.getInstance().getPlugin().getPluginProvider();
private static final BukkitPluginManager manager = BukkitPluginManager.get();
/**
* Sends the plugin list to the sender, without plugin version.
@ -28,7 +26,7 @@ public class CommandPlugins extends BaseCommand {
@CommandPermission("serverutils.plugins")
@Description("Shows the plugins of this server.")
public void onPlugins(CommandSender sender) {
Plugins.sendPlugins(BukkitUtils.wrap(sender), provider.getPluginsSorted(), pl -> {
Plugins.sendPlugins(BukkitUtils.wrap(sender), manager.getPluginsSorted(), pl -> {
String format = "serverutils.plugins.format" + (pl.isEnabled() ? "" : "_disabled");
return Messenger.getMessage(format, "%plugin%", pl.getName());
});
@ -42,7 +40,7 @@ public class CommandPlugins extends BaseCommand {
@CommandPermission("serverutils.plugins.version")
@Description("Shows the plugins of this server with version.")
public void onPluginsWithVersion(CommandSender sender) {
Plugins.sendPlugins(BukkitUtils.wrap(sender), provider.getPluginsSorted(), pl -> {
Plugins.sendPlugins(BukkitUtils.wrap(sender), manager.getPluginsSorted(), pl -> {
String format = "serverutils.plugins.format" + (pl.isEnabled() ? "" : "_disabled");
String version = Messenger.getMessage("serverutils.plugins.version",
"%version%", pl.getDescription().getVersion());

View file

@ -19,7 +19,7 @@ import java.util.Set;
import net.frankheijden.serverutils.bukkit.ServerUtils;
import net.frankheijden.serverutils.bukkit.entities.BukkitLoadResult;
import net.frankheijden.serverutils.bukkit.managers.PluginManager;
import net.frankheijden.serverutils.bukkit.managers.BukkitPluginManager;
import net.frankheijden.serverutils.bukkit.reflection.RCraftServer;
import net.frankheijden.serverutils.bukkit.utils.BukkitUtils;
import net.frankheijden.serverutils.bukkit.utils.ReloadHandler;
@ -152,13 +152,13 @@ public class CommandServerUtils extends BaseCommand {
public void onLoadPlugin(CommandSender commandSender, String jarFile) {
ServerCommandSender sender = BukkitUtils.wrap(commandSender);
BukkitLoadResult loadResult = PluginManager.loadPlugin(jarFile);
BukkitLoadResult loadResult = BukkitPluginManager.get().loadPlugin(jarFile);
if (!loadResult.isSuccess()) {
loadResult.getResult().sendTo(sender, "load", jarFile);
return;
}
Result result = PluginManager.enablePlugin(loadResult.get());
Result result = BukkitPluginManager.get().enablePlugin(loadResult.get());
result.sendTo(sender, "load", jarFile);
}
@ -174,13 +174,13 @@ public class CommandServerUtils extends BaseCommand {
public void onUnloadPlugin(CommandSender commandSender, String pluginName) {
ServerCommandSender sender = BukkitUtils.wrap(commandSender);
Result disableResult = PluginManager.disablePlugin(pluginName);
Result disableResult = BukkitPluginManager.disablePlugin(pluginName);
if (disableResult != Result.SUCCESS && disableResult != Result.ALREADY_DISABLED) {
disableResult.sendTo(sender, "disabl", pluginName);
return;
}
CloseableResult result = PluginManager.unloadPlugin(pluginName);
CloseableResult result = BukkitPluginManager.get().unloadPlugin(pluginName);
result.getResult().sendTo(sender, "unload", pluginName);
result.tryClose();
}
@ -195,7 +195,7 @@ public class CommandServerUtils extends BaseCommand {
@CommandPermission("serverutils.reloadplugin")
@Description("Reloads a specified plugin.")
public void onReloadPlugin(CommandSender sender, String pluginName) {
CloseableResult result = PluginManager.reloadPlugin(pluginName);
CloseableResult result = BukkitPluginManager.get().reloadPlugin(pluginName);
result.getResult().sendTo(BukkitUtils.wrap(sender), "reload", pluginName);
result.tryClose();
}
@ -210,7 +210,7 @@ public class CommandServerUtils extends BaseCommand {
@CommandPermission("serverutils.enableplugin")
@Description("Enables the loaded plugin.")
public void onEnablePlugin(CommandSender sender, String pluginName) {
Result result = PluginManager.enablePlugin(pluginName);
Result result = BukkitPluginManager.get().enablePlugin(pluginName);
result.sendTo(BukkitUtils.wrap(sender), "enabl", pluginName);
}
@ -224,7 +224,7 @@ public class CommandServerUtils extends BaseCommand {
@CommandPermission("serverutils.disableplugin")
@Description("Disables the specified plugin.")
public void onDisablePlugin(CommandSender sender, String pluginName) {
Result result = PluginManager.disablePlugin(pluginName);
Result result = BukkitPluginManager.disablePlugin(pluginName);
result.sendTo(BukkitUtils.wrap(sender), "disabl", pluginName);
}
@ -309,7 +309,7 @@ public class CommandServerUtils extends BaseCommand {
public void onCommandInfo(CommandSender commandSender, String command) {
ServerCommandSender sender = BukkitUtils.wrap(commandSender);
Command cmd = PluginManager.getCommand(command);
Command cmd = BukkitPluginManager.getCommand(command);
if (cmd == null) {
Messenger.sendMessage(sender, "serverutils.commandinfo.not_exists");
return;

View file

@ -0,0 +1,25 @@
package net.frankheijden.serverutils.bukkit.entities;
import net.frankheijden.serverutils.bukkit.utils.BukkitUtils;
import net.frankheijden.serverutils.common.entities.ServerCommandSender;
import net.frankheijden.serverutils.common.providers.ChatProvider;
import net.md_5.bungee.api.ChatColor;
import org.bukkit.Bukkit;
public class BukkitChatProvider extends ChatProvider {
@Override
public ServerCommandSender getConsoleSender() {
return BukkitUtils.wrap(Bukkit.getConsoleSender());
}
@Override
public String color(String str) {
return ChatColor.translateAlternateColorCodes('&', str);
}
@Override
public void broadcast(String permission, String message) {
Bukkit.broadcast(message, permission);
}
}

View file

@ -1,12 +0,0 @@
package net.frankheijden.serverutils.bukkit.entities;
import net.frankheijden.serverutils.common.providers.ColorProvider;
import net.md_5.bungee.api.ChatColor;
public class BukkitColorProvider implements ColorProvider {
@Override
public String apply(String str) {
return ChatColor.translateAlternateColorCodes('&', str);
}
}

View file

@ -15,4 +15,9 @@ public class BukkitCommandSender implements ServerCommandSender {
public void sendMessage(String message) {
sender.sendMessage(message);
}
@Override
public boolean hasPermission(String permission) {
return sender.hasPermission(permission);
}
}

View file

@ -4,18 +4,19 @@ import java.io.File;
import java.util.logging.Logger;
import net.frankheijden.serverutils.bukkit.ServerUtils;
import net.frankheijden.serverutils.common.providers.ColorProvider;
import net.frankheijden.serverutils.common.providers.PluginProvider;
import net.frankheijden.serverutils.common.providers.ResourceProvider;
import net.frankheijden.serverutils.bukkit.managers.BukkitPluginManager;
import net.frankheijden.serverutils.bukkit.managers.BukkitTaskManager;
import net.frankheijden.serverutils.bukkit.managers.BukkitVersionManager;
import net.frankheijden.serverutils.common.entities.ServerUtilsPlugin;
import org.bukkit.plugin.Plugin;
public class BukkitPlugin extends ServerUtilsPlugin {
private final ServerUtils plugin;
private final PluginProvider<Plugin> pluginProvider;
private final ResourceProvider resourceProvider;
private final ColorProvider colorProvider;
private final BukkitPluginManager pluginManager;
private final BukkitTaskManager taskManager;
private final BukkitResourceProvider resourceProvider;
private final BukkitChatProvider chatProvider;
private final BukkitVersionManager versionManager;
/**
* Creates a new BukkitPlugin instance of ServerUtils.
@ -23,25 +24,37 @@ public class BukkitPlugin extends ServerUtilsPlugin {
*/
public BukkitPlugin(ServerUtils plugin) {
this.plugin = plugin;
this.pluginProvider = new BukkitPluginProvider(plugin);
this.pluginManager = new BukkitPluginManager(plugin);
this.taskManager = new BukkitTaskManager();
this.resourceProvider = new BukkitResourceProvider(plugin);
this.colorProvider = new BukkitColorProvider();
this.chatProvider = new BukkitChatProvider();
this.versionManager = new BukkitVersionManager(plugin);
}
@Override
@SuppressWarnings("unchecked")
public PluginProvider<Plugin> getPluginProvider() {
return pluginProvider;
public BukkitPluginManager getPluginManager() {
return pluginManager;
}
@Override
public ResourceProvider getResourceProvider() {
public BukkitTaskManager getTaskManager() {
return taskManager;
}
@Override
public BukkitResourceProvider getResourceProvider() {
return resourceProvider;
}
@Override
public ColorProvider getColorProvider() {
return colorProvider;
public BukkitChatProvider getChatProvider() {
return chatProvider;
}
@Override
public BukkitVersionManager getVersionManager() {
return versionManager;
}
@Override

View file

@ -1,34 +0,0 @@
package net.frankheijden.serverutils.bukkit.entities;
import net.frankheijden.serverutils.bukkit.ServerUtils;
import net.frankheijden.serverutils.common.providers.PluginProvider;
import org.bukkit.Bukkit;
import org.bukkit.plugin.Plugin;
import java.io.File;
import java.util.Arrays;
import java.util.List;
public class BukkitPluginProvider extends PluginProvider<Plugin> {
private final ServerUtils plugin;
public BukkitPluginProvider(ServerUtils plugin) {
this.plugin = plugin;
}
@Override
public File getPluginsFolder() {
return plugin.getDataFolder().getParentFile();
}
@Override
public List<Plugin> getPlugins() {
return Arrays.asList(Bukkit.getPluginManager().getPlugins());
}
@Override
public String getPluginName(Plugin plugin) {
return plugin.getName();
}
}

View file

@ -0,0 +1,21 @@
package net.frankheijden.serverutils.bukkit.listeners;
import net.frankheijden.serverutils.common.listeners.ServerListener;
import net.frankheijden.serverutils.bukkit.utils.BukkitUtils;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
public class BukkitListener implements Listener {
/**
* Called when a player joins the server.
* Used for sending an update message to the player, if enabled and has permission.
* @param event The PlayerJoinEvent.
*/
@EventHandler(priority = EventPriority.LOWEST)
public void onPlayerJoin(PlayerJoinEvent event) {
ServerListener.handleUpdate(BukkitUtils.wrap(event.getPlayer()));
}
}

View file

@ -1,31 +0,0 @@
package net.frankheijden.serverutils.bukkit.listeners;
import net.frankheijden.serverutils.bukkit.tasks.UpdateCheckerTask;
import net.frankheijden.serverutils.bukkit.utils.BukkitUtils;
import net.frankheijden.serverutils.common.config.Config;
import net.frankheijden.serverutils.common.config.YamlConfig;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
public class MainListener implements Listener {
private static final YamlConfig config = Config.getInstance().getConfig();
/**
* Called when a player joins the server.
* Used for sending an update message to the player, if enabled and has permission.
* @param event The PlayerJoinEvent.
*/
@EventHandler(priority = EventPriority.LOWEST)
public void onPlayerJoin(PlayerJoinEvent event) {
if (!config.getBoolean("settings.check-updates-login")) return;
Player player = event.getPlayer();
if (player.hasPermission("serverutils.notification.update")) {
UpdateCheckerTask.start(BukkitUtils.wrap(player));
}
}
}

View file

@ -2,6 +2,8 @@ package net.frankheijden.serverutils.bukkit.managers;
import java.io.Closeable;
import java.io.File;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@ -14,6 +16,7 @@ import net.frankheijden.serverutils.bukkit.reflection.RCraftingManager;
import net.frankheijden.serverutils.bukkit.reflection.RJavaPlugin;
import net.frankheijden.serverutils.bukkit.reflection.RPluginClassLoader;
import net.frankheijden.serverutils.bukkit.reflection.RSimplePluginManager;
import net.frankheijden.serverutils.common.managers.AbstractPluginManager;
import net.frankheijden.serverutils.common.entities.CloseableResult;
import net.frankheijden.serverutils.common.entities.Result;
import org.bukkit.Bukkit;
@ -26,14 +29,27 @@ import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.plugin.PluginLoader;
import org.bukkit.plugin.UnknownDependencyException;
public class PluginManager {
public class BukkitPluginManager extends AbstractPluginManager<Plugin> {
private final ServerUtils plugin;
private static BukkitPluginManager instance;
public BukkitPluginManager(ServerUtils plugin) {
this.plugin = plugin;
instance = this;
}
public static BukkitPluginManager get() {
return instance;
}
/**
* Loads the specified file as a plugin.
* @param jarFile The name of the file in the plugins/ folder.
* @return The result of the loading procedure.
*/
public static BukkitLoadResult loadPlugin(String jarFile) {
@Override
public BukkitLoadResult loadPlugin(String jarFile) {
return loadPlugin(new File(ServerUtils.getInstance().getDataFolder().getParent(), jarFile));
}
@ -42,7 +58,8 @@ public class PluginManager {
* @param file The file to be loaded.
* @return The result of the loading procedure.
*/
public static BukkitLoadResult loadPlugin(File file) {
@Override
public BukkitLoadResult loadPlugin(File file) {
if (!file.exists()) return new BukkitLoadResult(Result.NOT_EXISTS);
Plugin loadedPlugin = getLoadedPlugin(file);
@ -104,7 +121,8 @@ public class PluginManager {
* @param pluginName The plugin to unload.
* @return The result of the unload.
*/
public static CloseableResult unloadPlugin(String pluginName) {
@Override
public CloseableResult unloadPlugin(String pluginName) {
return unloadPlugin(Bukkit.getPluginManager().getPlugin(pluginName));
}
@ -113,7 +131,8 @@ public class PluginManager {
* @param plugin The plugin to unload.
* @return The result of the unload.
*/
public static CloseableResult unloadPlugin(Plugin plugin) {
@Override
public CloseableResult unloadPlugin(Plugin plugin) {
if (plugin == null) return new CloseableResult(Result.NOT_EXISTS);
Closeable closeable;
try {
@ -132,7 +151,7 @@ public class PluginManager {
* @param pluginName The plugin to enable.
* @return The result of the enabling.
*/
public static Result enablePlugin(String pluginName) {
public Result enablePlugin(String pluginName) {
return enablePlugin(Bukkit.getPluginManager().getPlugin(pluginName));
}
@ -141,7 +160,8 @@ public class PluginManager {
* @param plugin The plugin to enable.
* @return The result of the enabling.
*/
public static Result enablePlugin(Plugin plugin) {
@Override
public Result enablePlugin(Plugin plugin) {
if (plugin == null) return Result.NOT_EXISTS;
if (Bukkit.getPluginManager().isPluginEnabled(plugin.getName())) return Result.ALREADY_ENABLED;
Bukkit.getPluginManager().enablePlugin(plugin);
@ -156,7 +176,8 @@ public class PluginManager {
* @param pluginName The plugin to reload.
* @return The result of the reload.
*/
public static CloseableResult reloadPlugin(String pluginName) {
@Override
public CloseableResult reloadPlugin(String pluginName) {
Plugin plugin = Bukkit.getPluginManager().getPlugin(pluginName);
if (plugin == null) return new CloseableResult(Result.NOT_EXISTS);
return reloadPlugin(plugin);
@ -167,7 +188,8 @@ public class PluginManager {
* @param plugin The plugin to reload.
* @return The result of the reload.
*/
public static CloseableResult reloadPlugin(Plugin plugin) {
@Override
public CloseableResult reloadPlugin(Plugin plugin) {
Result disableResult = disablePlugin(plugin);
if (disableResult != Result.SUCCESS && disableResult != Result.ALREADY_DISABLED) {
return new CloseableResult(disableResult);
@ -293,8 +315,8 @@ public class PluginManager {
* @param pluginName The plugin name.
* @return The file, or null if invalid or not found.
*/
public static File getPluginFile(String pluginName) {
for (File file : ServerUtils.getInstance().getPlugin().getPluginProvider().getPluginJars()) {
public File getPluginFile(String pluginName) {
for (File file : getPluginJars()) {
PluginDescriptionFile descriptionFile;
try {
descriptionFile = getPluginDescription(file);
@ -306,4 +328,28 @@ public class PluginManager {
}
return null;
}
@Override
public File getPluginsFolder() {
return plugin.getDataFolder().getParentFile();
}
@Override
public List<Plugin> getPlugins() {
return Arrays.asList(Bukkit.getPluginManager().getPlugins());
}
@Override
public String getPluginName(Plugin plugin) {
return plugin.getName();
}
@Override
public File getPluginFile(Plugin plugin) {
try {
return RJavaPlugin.getFile(plugin);
} catch (ReflectiveOperationException ex) {
throw new RuntimeException("Error retrieving current plugin file", ex);
}
}
}

View file

@ -0,0 +1,13 @@
package net.frankheijden.serverutils.bukkit.managers;
import net.frankheijden.serverutils.bukkit.ServerUtils;
import net.frankheijden.serverutils.common.managers.AbstractTaskManager;
import org.bukkit.Bukkit;
public class BukkitTaskManager extends AbstractTaskManager {
@Override
public void runTaskAsynchronously(Runnable runnable) {
Bukkit.getScheduler().runTaskAsynchronously(ServerUtils.getInstance(), runnable);
}
}

View file

@ -0,0 +1,15 @@
package net.frankheijden.serverutils.bukkit.managers;
import net.frankheijden.serverutils.bukkit.ServerUtils;
import net.frankheijden.serverutils.common.managers.AbstractVersionManager;
public class BukkitVersionManager extends AbstractVersionManager {
/**
* Creates a new VersionManager instance.
* Used for automatic updating.
*/
public BukkitVersionManager(ServerUtils plugin) {
super(plugin.getDescription().getVersion());
}
}

View file

@ -1,45 +0,0 @@
package net.frankheijden.serverutils.bukkit.managers;
import net.frankheijden.serverutils.bukkit.ServerUtils;
public class VersionManager {
private static VersionManager instance;
private final ServerUtils plugin = ServerUtils.getInstance();
private final String currentVersion;
private String downloadedVersion;
/**
* Creates a new VersionManager instance.
* Used for automatic updating.
*/
public VersionManager() {
instance = this;
this.currentVersion = plugin.getDescription().getVersion();
this.downloadedVersion = currentVersion;
}
public static VersionManager getInstance() {
return instance;
}
public String getCurrentVersion() {
return currentVersion;
}
public String getDownloadedVersion() {
return downloadedVersion;
}
public boolean hasDownloaded() {
return !downloadedVersion.equals(currentVersion);
}
public boolean isDownloadedVersion(String version) {
return downloadedVersion.equals(version);
}
public void setDownloadedVersion(String downloadedVersion) {
this.downloadedVersion = downloadedVersion;
}
}

View file

@ -5,6 +5,7 @@ import static net.frankheijden.serverutils.common.reflection.ReflectionUtils.get
import static net.frankheijden.serverutils.common.reflection.ReflectionUtils.invoke;
import static net.frankheijden.serverutils.common.reflection.VersionParam.ALL_VERSIONS;
import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;
@ -20,7 +21,8 @@ public class RJavaPlugin {
try {
javaPluginClass = JavaPlugin.class;
methods = getAllMethods(javaPluginClass,
methodOf("getClassLoader", ALL_VERSIONS));
methodOf("getClassLoader", ALL_VERSIONS),
methodOf("getFile", ALL_VERSIONS));
} catch (Exception ex) {
ex.printStackTrace();
}
@ -29,4 +31,8 @@ public class RJavaPlugin {
public static ClassLoader getClassLoader(Object instance) throws InvocationTargetException, IllegalAccessException {
return (ClassLoader) invoke(methods, instance, "getClassLoader");
}
public static File getFile(Object instance) throws ReflectiveOperationException {
return (File) invoke(methods, instance, "getFile");
}
}

View file

@ -1,204 +0,0 @@
package net.frankheijden.serverutils.bukkit.tasks;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.logging.Level;
import net.frankheijden.serverutils.bukkit.ServerUtils;
import net.frankheijden.serverutils.bukkit.managers.PluginManager;
import net.frankheijden.serverutils.bukkit.managers.VersionManager;
import net.frankheijden.serverutils.common.config.Config;
import net.frankheijden.serverutils.common.config.Messenger;
import net.frankheijden.serverutils.common.config.YamlConfig;
import net.frankheijden.serverutils.common.entities.CloseableResult;
import net.frankheijden.serverutils.common.entities.ServerCommandSender;
import net.frankheijden.serverutils.common.utils.FileUtils;
import net.frankheijden.serverutils.common.utils.VersionUtils;
import org.bukkit.Bukkit;
import org.bukkit.plugin.java.JavaPlugin;
public class UpdateCheckerTask implements Runnable {
private static final ServerUtils plugin = ServerUtils.getInstance();
private static final YamlConfig config = Config.getInstance().getConfig();
private static final VersionManager versionManager = VersionManager.getInstance();
private final ServerCommandSender sender;
private final String currentVersion;
private final boolean startup;
private static final String GITHUB_LINK = "https://api.github.com/repos/FrankHeijden/ServerUtils/releases/latest";
private static final String UPDATE_CHECK_START = "Checking for updates...";
private static final String GENERAL_ERROR = "Error fetching new version of ServerUtils";
private static final String TRY_LATER = GENERAL_ERROR + ", please try again later!";
private static final String CONNECTION_ERROR = GENERAL_ERROR + ": (%s) %s (maybe check your connection?)";
private static final String UNAVAILABLE = GENERAL_ERROR + ": (%s) %s (no update available)";
private static final String UPDATE_AVAILABLE = "ServerUtils %s is available!";
private static final String DOWNLOAD_START = "Started downloading from \"%s\"...";
private static final String DOWNLOAD_ERROR = "Error downloading a new version of ServerUtils";
private static final String UPGRADE_SUCCESS = "Successfully upgraded ServerUtils to v%s!";
private static final String DOWNLOADED_RESTART = "Downloaded ServerUtils version v%s. Restarting plugin now...";
private static final String UP_TO_DATE = "We are up-to-date!";
private UpdateCheckerTask(ServerCommandSender sender, boolean startup) {
this.sender = sender;
this.currentVersion = plugin.getDescription().getVersion();
this.startup = startup;
}
public static void start(ServerCommandSender sender) {
start(sender, false);
}
public static void start(ServerCommandSender sender, boolean startup) {
UpdateCheckerTask task = new UpdateCheckerTask(sender, startup);
Bukkit.getScheduler().runTaskAsynchronously(plugin, task);
}
public boolean isStartupCheck() {
return this.startup;
}
@Override
public void run() {
if (isStartupCheck()) {
plugin.getLogger().info(UPDATE_CHECK_START);
}
JsonElement jsonElement;
try {
jsonElement = FileUtils.readJsonFromUrl(GITHUB_LINK);
} catch (ConnectException | UnknownHostException | SocketTimeoutException ex) {
plugin.getLogger().severe(String.format(CONNECTION_ERROR, ex.getClass().getSimpleName(), ex.getMessage()));
return;
} catch (FileNotFoundException ex) {
plugin.getLogger().severe(String.format(UNAVAILABLE, ex.getClass().getSimpleName(), ex.getMessage()));
return;
} catch (IOException ex) {
plugin.getLogger().log(Level.SEVERE, ex, () -> GENERAL_ERROR);
return;
}
if (jsonElement == null) {
plugin.getLogger().warning(TRY_LATER);
return;
}
JsonObject jsonObject = jsonElement.getAsJsonObject();
if (jsonObject.has("message")) {
plugin.getLogger().warning(jsonObject.get("message").getAsString());
return;
}
String githubVersion = getVersion(jsonObject);
String body = jsonObject.getAsJsonPrimitive("body").getAsString();
String downloadUrl = getDownloadUrl(jsonObject);
if (VersionUtils.isNewVersion(currentVersion, githubVersion)) {
if (isStartupCheck()) {
plugin.getLogger().info(String.format(UPDATE_AVAILABLE, githubVersion));
plugin.getLogger().info("Release info: " + body);
}
if (canDownloadPlugin()) {
if (isStartupCheck()) {
plugin.getLogger().info(String.format(DOWNLOAD_START, downloadUrl));
} else {
Messenger.sendMessage(sender, "serverutils.update.downloading",
"%old%", currentVersion,
"%new%", githubVersion,
"%info%", body);
}
downloadPlugin(githubVersion, downloadUrl);
tryReloadPlugin();
} else if (!isStartupCheck()) {
Messenger.sendMessage(sender, "serverutils.update.available",
"%old%", currentVersion,
"%new%", githubVersion,
"%info%", body);
}
} else if (versionManager.hasDownloaded()) {
Messenger.sendMessage(sender, "serverutils.update.success",
"%new%", versionManager.getDownloadedVersion());
} else if (isStartupCheck()) {
plugin.getLogger().info(UP_TO_DATE);
}
}
private String getVersion(JsonObject jsonObject) {
return jsonObject.getAsJsonPrimitive("tag_name").getAsString().replace("v", "");
}
private String getDownloadUrl(JsonObject jsonObject) {
JsonArray assets = jsonObject.getAsJsonArray("assets");
if (assets != null && assets.size() > 0) {
return assets.get(0).getAsJsonObject().getAsJsonPrimitive("browser_download_url").getAsString();
}
return null;
}
private boolean canDownloadPlugin() {
if (isStartupCheck()) return config.getBoolean("settings.download-at-startup-and-update");
return config.getBoolean("settings.download-updates");
}
private void downloadPlugin(String githubVersion, String downloadLink) {
if (versionManager.isDownloadedVersion(githubVersion)) {
broadcastDownloadStatus(githubVersion, false);
return;
}
if (downloadLink == null) {
broadcastDownloadStatus(githubVersion, true);
return;
}
try {
FileUtils.download(downloadLink, getPluginFile());
} catch (IOException ex) {
broadcastDownloadStatus(githubVersion, true);
throw new RuntimeException(DOWNLOAD_ERROR, ex);
}
versionManager.setDownloadedVersion(githubVersion);
}
private void tryReloadPlugin() {
String downloadedVersion = versionManager.getDownloadedVersion();
if (isStartupCheck()) {
plugin.getLogger().info(String.format(DOWNLOADED_RESTART, downloadedVersion));
CloseableResult result = PluginManager.reloadPlugin(plugin);
plugin.getLogger().info(String.format(UPGRADE_SUCCESS, downloadedVersion));
result.tryClose();
} else {
broadcastDownloadStatus(downloadedVersion, false);
}
}
private void broadcastDownloadStatus(String githubVersion, boolean isError) {
final String path = "serverutils.update." + (isError ? "failed" : "success");
Bukkit.getOnlinePlayers().forEach((p) -> {
if (p.hasPermission("serverutils.notification.update")) {
Messenger.sendMessage(sender, path, "%new%", githubVersion);
}
});
}
private File getPluginFile() {
try {
Method method = JavaPlugin.class.getDeclaredMethod("getFile");
method.setAccessible(true);
return (File) method.invoke(plugin);
} catch (ReflectiveOperationException ex) {
throw new RuntimeException("Error retrieving current plugin file", ex);
}
}
}