realweather/src/main/java/eu/m724/realweather/updater/UpdateNotifier.java
2024-06-26 15:16:21 +02:00

70 lines
2.1 KiB
Java

package eu.m724.realweather.updater;
import java.io.IOException;
import java.util.concurrent.CompletionException;
import java.util.function.Consumer;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.plugin.Plugin;
import org.bukkit.scheduler.BukkitRunnable;
import eu.m724.jarupdater.Updater;
import eu.m724.jarupdater.object.Version;
import eu.m724.realweather.DebugLogger;
import eu.m724.realweather.GlobalConstants;
public class UpdateNotifier extends BukkitRunnable implements Listener { // TODO move this to jarupdater
private Updater updater;
private Consumer<Version> updateConsumer;
private Plugin plugin = GlobalConstants.getPlugin();
private Version latestVersion;
public UpdateNotifier(Updater updater, Consumer<Version> updateConsumer) {
this.updater = updater;
this.updateConsumer = updateConsumer;
}
public void register() {
this.runTaskTimerAsynchronously(plugin, 0, 432000); // 6h
plugin.getServer().getPluginManager().registerEvents(this, plugin);
}
@Override
public void run() {
DebugLogger.info("update task running", 2);
try {
latestVersion = updater.getLatestVersion().join();
} catch (CompletionException e) {
Throwable ex = e.getCause();
if (ex instanceof IOException)
DebugLogger.info("error trying to contact update server: %s", 0, ex.getMessage());
else e.printStackTrace();
}
if (latestVersion == null) return;
DebugLogger.info("RealWeather is outdated. /rwadmin update", 0);
for (Player player : plugin.getServer().getOnlinePlayers()) {
if (player.hasPermission("realweather.update.notify")) {
player.sendMessage("RealWeather is outdated. /rwadmin update");
}
}
updateConsumer.accept(latestVersion);
}
@EventHandler
public void onPlayerJoin(PlayerJoinEvent e) {
Player player = e.getPlayer();
if (latestVersion != null && player.hasPermission("realweather.update.notify")) {
player.sendMessage("RealWeather is outdated. /rwadmin update");
}
}
}