From e6f4fd527cd6dd9202e3f57d2ff2c39de796269b Mon Sep 17 00:00:00 2001 From: Minecon724 <39800107+Minecon724@users.noreply.github.com> Date: Sat, 13 Jan 2024 18:10:41 +0000 Subject: [PATCH] work on 0.5.0 many changes, primarily refactoring warning: won't work yet --- TODO.md | 5 + pom.xml | 8 +- .../minecon724/realweather/GetStateTask.java | 143 --- .../pl/minecon724/realweather/MapUtils.java | 23 - .../pl/minecon724/realweather/Provider.java | 6 - .../java/pl/minecon724/realweather/RW.java | 80 +- .../commands/RealWeatherCommand.java | 15 - .../realweather/map/GeoLocator.java | 49 + .../pl/minecon724/realweather/map/Globe.java | 37 + .../minecon724/realweather/map/WorldMap.java | 98 ++ .../map/exceptions/GeoIPException.java | 9 + .../realweather/thirdparty/Metrics.java | 863 ------------------ .../realweather/weather/GetStateTask.java | 73 ++ .../realweather/weather/Providers.java | 35 + .../realweather/weather/WeatherCommander.java | 64 ++ .../{ => weather}/WeatherState.java | 20 +- .../weather/exceptions/DisabledException.java | 5 + .../weather/exceptions/ProviderException.java | 5 + .../provider/OpenWeatherMapProvider.java | 14 +- .../weather/provider/Provider.java | 9 + src/main/resources/config.yml | 76 +- src/main/resources/plugin.yml | 8 +- 22 files changed, 477 insertions(+), 1168 deletions(-) create mode 100644 TODO.md delete mode 100644 src/main/java/pl/minecon724/realweather/GetStateTask.java delete mode 100644 src/main/java/pl/minecon724/realweather/MapUtils.java delete mode 100644 src/main/java/pl/minecon724/realweather/Provider.java delete mode 100644 src/main/java/pl/minecon724/realweather/commands/RealWeatherCommand.java create mode 100644 src/main/java/pl/minecon724/realweather/map/GeoLocator.java create mode 100644 src/main/java/pl/minecon724/realweather/map/Globe.java create mode 100644 src/main/java/pl/minecon724/realweather/map/WorldMap.java create mode 100644 src/main/java/pl/minecon724/realweather/map/exceptions/GeoIPException.java delete mode 100644 src/main/java/pl/minecon724/realweather/thirdparty/Metrics.java create mode 100644 src/main/java/pl/minecon724/realweather/weather/GetStateTask.java create mode 100644 src/main/java/pl/minecon724/realweather/weather/Providers.java create mode 100644 src/main/java/pl/minecon724/realweather/weather/WeatherCommander.java rename src/main/java/pl/minecon724/realweather/{ => weather}/WeatherState.java (74%) create mode 100644 src/main/java/pl/minecon724/realweather/weather/exceptions/DisabledException.java create mode 100644 src/main/java/pl/minecon724/realweather/weather/exceptions/ProviderException.java rename src/main/java/pl/minecon724/realweather/{ => weather}/provider/OpenWeatherMapProvider.java (91%) create mode 100644 src/main/java/pl/minecon724/realweather/weather/provider/Provider.java diff --git a/TODO.md b/TODO.md new file mode 100644 index 0000000..ca384fb --- /dev/null +++ b/TODO.md @@ -0,0 +1,5 @@ +- local maxmind +- account for real sun movement, not just time +- gh actions +- readd metrics +- fix realtime \ No newline at end of file diff --git a/pom.xml b/pom.xml index da0d33d..a90bac2 100644 --- a/pom.xml +++ b/pom.xml @@ -2,7 +2,7 @@ 4.0.0 pl.minecon724 realweather - 0.4.1 + 0.5.0-DEV 17 @@ -20,19 +20,19 @@ org.spigotmc spigot-api - 1.20.1-R0.1-SNAPSHOT + 1.20.4-R0.1-SNAPSHOT provided org.json json - 20230227 + 20231013 provided com.maxmind.geoip2 geoip2 - 4.1.0 + 4.2.0 provided diff --git a/src/main/java/pl/minecon724/realweather/GetStateTask.java b/src/main/java/pl/minecon724/realweather/GetStateTask.java deleted file mode 100644 index 6b2183b..0000000 --- a/src/main/java/pl/minecon724/realweather/GetStateTask.java +++ /dev/null @@ -1,143 +0,0 @@ -package pl.minecon724.realweather; - -import java.net.InetAddress; -import java.util.List; -import java.util.logging.Logger; - -import com.maxmind.geoip2.WebServiceClient; -import com.maxmind.geoip2.exception.AddressNotFoundException; -import com.maxmind.geoip2.model.CityResponse; -import com.maxmind.geoip2.record.Location; - -import net.md_5.bungee.api.ChatMessageType; -import net.md_5.bungee.api.chat.TextComponent; - -import org.bukkit.Bukkit; -import org.bukkit.WeatherType; -import org.bukkit.World; -import org.bukkit.entity.Player; -import org.bukkit.scheduler.BukkitRunnable; - -import pl.minecon724.realweather.WeatherState.ConditionSimple; -import pl.minecon724.realweather.WeatherState.State; - -public class GetStateTask extends BukkitRunnable { - - Provider provider; - String source; - double pointLatitude; - double pointLongitude; - List worlds; - Logger logger; - WebServiceClient client; - boolean debug, debugDox; - double scaleLat, scaleLon; - int onExceed; - boolean actionbar; - String actionbarInfo; - - MapUtils mapUtils = new MapUtils(); - - public GetStateTask( - Provider provider, String source, - double pointLatitude, double pointLongitude, - List worlds, Logger logger, - WebServiceClient client, - boolean debug, boolean debugDox, - double scaleLat, double scaleLon, - int onExceed, boolean actionbar, - String actionbarInfo - ) { - this.provider = provider; - this.source = source; - this.pointLatitude = pointLatitude; - this.pointLongitude = pointLongitude; - this.worlds = worlds; - this.logger = logger; - this.client = client; - this.debug = debug; - this.debugDox = debugDox; - this.scaleLat = scaleLat; - this.scaleLon = scaleLon; - this.onExceed = onExceed; - this.actionbar = actionbar; - this.actionbarInfo = actionbarInfo; - } - - // That's a lot of variables - - @Override - public void run() { - if (debug) logger.info("Refreshing weather by " + source); - if (source.equals("point")) { - State state = provider.request_state(pointLatitude, pointLongitude); - if (debug) logger.info(String.format("Provider returned state %s %s (%s)", state.condition.name(), state.level.name(), state.simple.name())); - for (String w : worlds) { - World world = Bukkit.getWorld(w); - if (world == null) continue; - world.setThundering(state.simple == ConditionSimple.THUNDER ? true : false); - world.setStorm(state.simple == ConditionSimple.CLEAR ? false : true); - } - if (actionbar) { - String[] data = {state.level.name(), state.condition.name()}; - for (Player p : Bukkit.getOnlinePlayers()) { - p.spigot().sendMessage(ChatMessageType.ACTION_BAR, TextComponent.fromLegacyText(ConfigUtils.parsePlaceholders("messages.actionbarInfo", actionbarInfo, data))); - } - } - } else if (source.equals("player")) { - InetAddress playerIp = null; - Player curr = null; - try { - Location location; - State state; - double lat, lon; - CityResponse city; - for (Player p : Bukkit.getOnlinePlayers()) { - curr = p; - playerIp = p.getAddress().getAddress(); - city = client.city(playerIp); - location = city.getLocation(); - lat = location.getLatitude(); - lon = location.getLongitude(); - if (debugDox) logger.info( String.format( "%s's real location is %f, %f", p.getName(), lat, lon )); - state = provider.request_state(lat, lon); - if (debug) logger.info( String.format( - "Provider returned state %s %s for %s", state.condition.name(), state.level.name(), p.getName() - )); - p.setPlayerWeather(state.simple == ConditionSimple.CLEAR ? WeatherType.CLEAR : WeatherType.DOWNFALL); - if (actionbar) { - String[] data = {state.level.name(), state.condition.name()}; - p.spigot().sendMessage(ChatMessageType.ACTION_BAR, TextComponent.fromLegacyText( - ConfigUtils.parsePlaceholders("messages.actionbarInfo", actionbarInfo, data)) - ); - } - } - } catch (AddressNotFoundException e) { - logger.warning(String.format("%s's IP address (%s) is not a public IP address, therefore we can't retrieve their location.", curr.getName(), playerIp.toString())); - logger.warning("Check your proxy settings if you believe that this is an error."); - } catch (Exception e) { - e.printStackTrace(); - } - } else if (source.equals("map")) { - double[] coords; - double lat, lon; - State state; - for (Player p : Bukkit.getOnlinePlayers()) { - coords = mapUtils.playerPosAsCoords(p.getLocation(), scaleLat, scaleLon, onExceed); - lon = coords[0]; - lat = coords[1]; - if (debug) logger.info( String.format( "%s's location is %f, %f", p.getName(), lat, lon )); - state = provider.request_state(lat, lon); - if (debug) logger.info( String.format( - "Provider returned state %s %s for %f, %f", state.condition.name(), state.level.name(), lat, lon - )); - if (actionbar) { - String[] data = {state.level.name(), state.condition.name()}; - p.spigot().sendMessage(ChatMessageType.ACTION_BAR, TextComponent.fromLegacyText( - ConfigUtils.parsePlaceholders("messages.actionbarInfo", actionbarInfo, data)) - ); - } - } - } - } -} diff --git a/src/main/java/pl/minecon724/realweather/MapUtils.java b/src/main/java/pl/minecon724/realweather/MapUtils.java deleted file mode 100644 index 615249b..0000000 --- a/src/main/java/pl/minecon724/realweather/MapUtils.java +++ /dev/null @@ -1,23 +0,0 @@ -package pl.minecon724.realweather; - -import org.bukkit.Location; - -public class MapUtils { - double wrapDouble(double min, double max, double val) { - return min + (val - min) % (max - min); - } - - public double[] playerPosAsCoords(Location loc, double scaleLat, double scaleLon, int onExceed) { - double[] out = new double[2]; - out[0] = loc.getX() * scaleLon; - out[1] = -loc.getZ() * scaleLat; - if (onExceed == 1) { - out[0] = Math.max(-180.0, Math.min(180.0, out[0])); - out[1] = Math.max(-90.0, Math.min(90.0, out[1])); - } else if (onExceed == 2) { - out[0] = wrapDouble(-180.0, 180.0, out[0]); - out[1] = wrapDouble(-90.0, 90.0, out[1]); - } - return out; - } -} diff --git a/src/main/java/pl/minecon724/realweather/Provider.java b/src/main/java/pl/minecon724/realweather/Provider.java deleted file mode 100644 index 3482eaf..0000000 --- a/src/main/java/pl/minecon724/realweather/Provider.java +++ /dev/null @@ -1,6 +0,0 @@ -package pl.minecon724.realweather; - -public interface Provider { - public void init(); - public WeatherState.State request_state(double lat, double lon); -} diff --git a/src/main/java/pl/minecon724/realweather/RW.java b/src/main/java/pl/minecon724/realweather/RW.java index 08d4570..6a90cba 100644 --- a/src/main/java/pl/minecon724/realweather/RW.java +++ b/src/main/java/pl/minecon724/realweather/RW.java @@ -10,10 +10,14 @@ import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.plugin.java.JavaPlugin; -import pl.minecon724.realweather.commands.RealWeatherCommand; -import pl.minecon724.realweather.provider.OpenWeatherMapProvider; +import pl.minecon724.realweather.map.WorldMap; import pl.minecon724.realweather.realtime.RTTask; -import pl.minecon724.realweather.thirdparty.Metrics; +import pl.minecon724.realweather.weather.GetStateTask; +import pl.minecon724.realweather.weather.WeatherCommander; +import pl.minecon724.realweather.weather.exceptions.DisabledException; +import pl.minecon724.realweather.weather.exceptions.ProviderException; +import pl.minecon724.realweather.weather.provider.OpenWeatherMapProvider; +import pl.minecon724.realweather.weather.provider.Provider; public class RW extends JavaPlugin { FileConfiguration config; @@ -27,62 +31,19 @@ public class RW extends JavaPlugin { saveDefaultConfig(); config = getConfig(); - ConfigurationSection weatherSec = config.getConfigurationSection("weather"); - ConfigurationSection providerSec = config.getConfigurationSection("provider"); - ConfigurationSection settingsSec = config.getConfigurationSection("settings"); - ConfigurationSection messagesSec = config.getConfigurationSection("messages"); - ConfigurationSection realtimeSec = config.getConfigurationSection("realtime"); - - String source = weatherSec.getString("source"); - ConfigurationSection point = weatherSec.getConfigurationSection("point"); - ConfigurationSection player = weatherSec.getConfigurationSection("player"); - ConfigurationSection map = weatherSec.getConfigurationSection("map"); - - double pointLatitude = point.getDouble("latitude"); - double pointLongitude = point.getDouble("longitude"); - List worlds = weatherSec.getStringList("worlds"); - - String choice = providerSec.getString("choice").toLowerCase(); - ConfigurationSection providerCfg = providerSec.getConfigurationSection(choice); - - if (providerCfg == null) { - this.getLogger().severe("Unknown provider: " + choice); - this.getLogger().info("The plugin will disable now"); - Bukkit.getPluginManager().disablePlugin(this); - } - - Provider provider = null; - if (choice.equals("openweathermap")) { - this.getLogger().info("Using OpenWeatherMap as the weather provider"); - provider = new OpenWeatherMapProvider( providerCfg.getString("apiKey") ); - } - provider.init(); - - if (source.equals("player")) { - this.getLogger().info("Initializing GeoLite2 by MaxMind because we need it for retrieving players real world locations."); - int accId = player.getInt("geolite2_accountId"); - String license = player.getString("geolite2_apiKey"); - client = new WebServiceClient.Builder(accId, license).host("geolite.info").build(); - } - - getCommand("realweather").setExecutor(new RealWeatherCommand()); - - double scale_lat = map.getDouble("scale_lat"); - double scale_lon = map.getDouble("scale_lon"); - int on_exceed = map.getInt("on_exceed"); - - boolean debug = settingsSec.getBoolean("debug"); - boolean debugDox = settingsSec.getBoolean("debugDox"); - - new GetStateTask( - provider, source, pointLatitude, pointLongitude, worlds, this.getLogger(), - client, debug, debugDox, scale_lat, scale_lon, on_exceed, - settingsSec.getBoolean("actionbar"), ConfigUtils.color(messagesSec.getString("actionbarInfo")) - ).runTaskTimerAsynchronously(this, - settingsSec.getLong("timeBeforeInitialRun"), - settingsSec.getLong("timeBetweenRecheck") + WorldMap worldMap = WorldMap.fromConfig( + config.getConfigurationSection("map") ); + WeatherCommander weatherCommander = new WeatherCommander(worldMap, this); + try { + weatherCommander.init( + config.getConfigurationSection("weather") + ); + } catch (DisabledException e) { + getLogger().info("Weather module disabled"); + } // we leave ProviderException + if (realtimeSec.getBoolean("enabled")) { ZoneId zone; try { @@ -96,11 +57,6 @@ public class RW extends JavaPlugin { realtimeSec.getStringList("worlds") ).runTaskTimer(this, 0, realtimeSec.getLong("interval")); } - - Metrics metrics = new Metrics(this, 15020); - metrics.addCustomChart(new Metrics.SimplePie("source_type", () -> { - return source; - })); long end = System.currentTimeMillis(); this.getLogger().info( String.format( this.getName() + " enabled! (%s ms)", Long.toString( end-start ) ) ); diff --git a/src/main/java/pl/minecon724/realweather/commands/RealWeatherCommand.java b/src/main/java/pl/minecon724/realweather/commands/RealWeatherCommand.java deleted file mode 100644 index 23572f2..0000000 --- a/src/main/java/pl/minecon724/realweather/commands/RealWeatherCommand.java +++ /dev/null @@ -1,15 +0,0 @@ -package pl.minecon724.realweather.commands; - -import org.bukkit.command.Command; -import org.bukkit.command.CommandExecutor; -import org.bukkit.command.CommandSender; - -public class RealWeatherCommand implements CommandExecutor { - - @Override - public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { - sender.sendMessage("TODO"); - return true; - } - -} diff --git a/src/main/java/pl/minecon724/realweather/map/GeoLocator.java b/src/main/java/pl/minecon724/realweather/map/GeoLocator.java new file mode 100644 index 0000000..af79592 --- /dev/null +++ b/src/main/java/pl/minecon724/realweather/map/GeoLocator.java @@ -0,0 +1,49 @@ +package pl.minecon724.realweather.map; + +import java.io.IOException; +import java.net.InetAddress; + +import com.maxmind.geoip2.WebServiceClient; +import com.maxmind.geoip2.exception.GeoIp2Exception; +import com.maxmind.geoip2.record.Location; + +import pl.minecon724.realweather.map.exceptions.GeoIPException; + +public class GeoLocator { + private WebServiceClient client; + + public GeoLocator(WebServiceClient client) { + this.client = client; + } + + public static GeoLocator fromConfig(int accountId, String apiKey) { + return new GeoLocator( + new WebServiceClient.Builder(accountId, apiKey) + .host("geolite.info").build() + ); + + } + + /** + * get location by IP + * @param address IP + * @return geolocation in vector + * @throws GeoIp2Exception + * @throws IOException + */ + public double[] getLocation(InetAddress address) + throws GeoIPException { + + Location location; + try { + location = client.city(address).getLocation(); + } catch (IOException | GeoIp2Exception e) { + throw new GeoIPException(e.getMessage()); + } + + return new double[] { + location.getLatitude(), + location.getLongitude() + }; + } +} diff --git a/src/main/java/pl/minecon724/realweather/map/Globe.java b/src/main/java/pl/minecon724/realweather/map/Globe.java new file mode 100644 index 0000000..9976c35 --- /dev/null +++ b/src/main/java/pl/minecon724/realweather/map/Globe.java @@ -0,0 +1,37 @@ +package pl.minecon724.realweather.map; + +import org.bukkit.Location; + +public class Globe { + double scaleLatitide, scaleLongitude; + boolean wrap; + + public Globe(double scaleLatitude, + double scaleLongitude, + boolean wrap) { + this.scaleLatitide = scaleLatitude; + this.scaleLongitude = scaleLongitude; + this.wrap = wrap; + } + + double wrapDouble(double min, double max, double val) { + return min + (val - min) % (max - min); + } + + public double[] playerPosAsCoords(Location loc) { + double[] out = new double[] { + loc.getX() * scaleLongitude, + -loc.getZ() * scaleLatitide + }; + + if (wrap) { + out[0] = Math.max(-180.0, Math.min(180.0, out[0])); + out[1] = Math.max(-90.0, Math.min(90.0, out[1])); + } else { + out[0] = wrapDouble(-180.0, 180.0, out[0]); + out[1] = wrapDouble(-90.0, 90.0, out[1]); + } + + return out; + } +} diff --git a/src/main/java/pl/minecon724/realweather/map/WorldMap.java b/src/main/java/pl/minecon724/realweather/map/WorldMap.java new file mode 100644 index 0000000..d1f13ad --- /dev/null +++ b/src/main/java/pl/minecon724/realweather/map/WorldMap.java @@ -0,0 +1,98 @@ +package pl.minecon724.realweather.map; + +import org.bukkit.configuration.ConfigurationSection; +import org.bukkit.entity.Player; + +import pl.minecon724.realweather.map.exceptions.GeoIPException; + +public class WorldMap { + private final Type type; + + private double[] point; + private GeoLocator geoLocator; + private Globe globe; + + public WorldMap(Type type, + double[] point, + GeoLocator geoLocator, + Globe globe) { + this.type = type; + this.point = point; + this.geoLocator = geoLocator; + this.globe = globe; + } + + public static WorldMap fromConfig(ConfigurationSection config) + throws IllegalArgumentException { + + Type type; + + try { + type = Type.valueOf(config.getString("type")); + } catch (NullPointerException e) { + throw new IllegalArgumentException("Invalid type"); + } + + double[] point = null; + GeoLocator geoLocator = null; + Globe globe = null; + + if (type == Type.POINT) { + point = new double[] { + config.getDouble("point.latitude"), + config.getDouble("point.longitude") + }; + + } else if (type == Type.PLAYER) { + geoLocator = GeoLocator.fromConfig( + config.getInt("player.geolite2_accountId"), + config.getString("player.geolite2_api_key") + ); + + } else if (type == Type.GLOBE) { + globe = new Globe( + config.getDouble("globe.scale_latitude"), + config.getDouble("globe.scale_longitude"), + config.getBoolean("globe.wrap") + ); + } + + WorldMap worldMap = new WorldMap(type, point, geoLocator, globe); + + return worldMap; + + } + + /** + * get player position as coords + * @param player the player + * @return latitude, longitude + * @throws GeoIPException + */ + public double[] getPosition(Player player) throws GeoIPException { + + switch (this.type) { + case POINT: + return point; + case PLAYER: + if (player.getAddress().getAddress().isAnyLocalAddress()) + throw new GeoIPException(player.getName() + "'s IP is local, check your proxy settings"); + + return geoLocator.getLocation( + player.getAddress().getAddress()); + case GLOBE: + return globe.playerPosAsCoords(player.getLocation()); + } + + // this wont happen because we cover each type + return null; + } + + public Type getType() { + return this.type; + } + + public static enum Type { + POINT, PLAYER, GLOBE + } +} diff --git a/src/main/java/pl/minecon724/realweather/map/exceptions/GeoIPException.java b/src/main/java/pl/minecon724/realweather/map/exceptions/GeoIPException.java new file mode 100644 index 0000000..33ebb8d --- /dev/null +++ b/src/main/java/pl/minecon724/realweather/map/exceptions/GeoIPException.java @@ -0,0 +1,9 @@ +package pl.minecon724.realweather.map.exceptions; + +public class GeoIPException extends Exception { + + public GeoIPException(String string) { + super(string); + } + +} diff --git a/src/main/java/pl/minecon724/realweather/thirdparty/Metrics.java b/src/main/java/pl/minecon724/realweather/thirdparty/Metrics.java deleted file mode 100644 index 9754de4..0000000 --- a/src/main/java/pl/minecon724/realweather/thirdparty/Metrics.java +++ /dev/null @@ -1,863 +0,0 @@ -/* - * This Metrics class was auto-generated and can be copied into your project if you are - * not using a build tool like Gradle or Maven for dependency management. - * - * IMPORTANT: You are not allowed to modify this class, except changing the package. - * - * Unallowed modifications include but are not limited to: - * - Remove the option for users to opt-out - * - Change the frequency for data submission - * - Obfuscate the code (every obfucator should allow you to make an exception for specific files) - * - Reformat the code (if you use a linter, add an exception) - * - * Violations will result in a ban of your plugin and account from bStats. - */ -package pl.minecon724.realweather.thirdparty; - -import java.io.BufferedReader; -import java.io.ByteArrayOutputStream; -import java.io.DataOutputStream; -import java.io.File; -import java.io.IOException; -import java.io.InputStreamReader; -import java.lang.reflect.Method; -import java.net.URL; -import java.nio.charset.StandardCharsets; -import java.util.Arrays; -import java.util.Collection; -import java.util.HashSet; -import java.util.Map; -import java.util.Objects; -import java.util.Set; -import java.util.UUID; -import java.util.concurrent.Callable; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.TimeUnit; -import java.util.function.BiConsumer; -import java.util.function.Consumer; -import java.util.function.Supplier; -import java.util.logging.Level; -import java.util.stream.Collectors; -import java.util.zip.GZIPOutputStream; -import javax.net.ssl.HttpsURLConnection; -import org.bukkit.Bukkit; -import org.bukkit.configuration.file.YamlConfiguration; -import org.bukkit.entity.Player; -import org.bukkit.plugin.Plugin; -import org.bukkit.plugin.java.JavaPlugin; - -public class Metrics { - - private final Plugin plugin; - - private final MetricsBase metricsBase; - - /** - * Creates a new Metrics instance. - * - * @param plugin Your plugin instance. - * @param serviceId The id of the service. It can be found at What is my plugin id? - */ - public Metrics(JavaPlugin plugin, int serviceId) { - this.plugin = plugin; - // Get the config file - File bStatsFolder = new File(plugin.getDataFolder().getParentFile(), "bStats"); - File configFile = new File(bStatsFolder, "config.yml"); - YamlConfiguration config = YamlConfiguration.loadConfiguration(configFile); - if (!config.isSet("serverUuid")) { - config.addDefault("enabled", true); - config.addDefault("serverUuid", UUID.randomUUID().toString()); - config.addDefault("logFailedRequests", false); - config.addDefault("logSentData", false); - config.addDefault("logResponseStatusText", false); - // Inform the server owners about bStats - config - .options() - .header( - "bStats (https://bStats.org) collects some basic information for plugin authors, like how\n" - + "many people use their plugin and their total player count. It's recommended to keep bStats\n" - + "enabled, but if you're not comfortable with this, you can turn this setting off. There is no\n" - + "performance penalty associated with having metrics enabled, and data sent to bStats is fully\n" - + "anonymous.") - .copyDefaults(true); - try { - config.save(configFile); - } catch (IOException ignored) { - } - } - // Load the data - boolean enabled = config.getBoolean("enabled", true); - String serverUUID = config.getString("serverUuid"); - boolean logErrors = config.getBoolean("logFailedRequests", false); - boolean logSentData = config.getBoolean("logSentData", false); - boolean logResponseStatusText = config.getBoolean("logResponseStatusText", false); - metricsBase = - new MetricsBase( - "bukkit", - serverUUID, - serviceId, - enabled, - this::appendPlatformData, - this::appendServiceData, - submitDataTask -> Bukkit.getScheduler().runTask(plugin, submitDataTask), - plugin::isEnabled, - (message, error) -> this.plugin.getLogger().log(Level.WARNING, message, error), - (message) -> this.plugin.getLogger().log(Level.INFO, message), - logErrors, - logSentData, - logResponseStatusText); - } - - /** - * Adds a custom chart. - * - * @param chart The chart to add. - */ - public void addCustomChart(CustomChart chart) { - metricsBase.addCustomChart(chart); - } - - private void appendPlatformData(JsonObjectBuilder builder) { - builder.appendField("playerAmount", getPlayerAmount()); - builder.appendField("onlineMode", Bukkit.getOnlineMode() ? 1 : 0); - builder.appendField("bukkitVersion", Bukkit.getVersion()); - builder.appendField("bukkitName", Bukkit.getName()); - builder.appendField("javaVersion", System.getProperty("java.version")); - builder.appendField("osName", System.getProperty("os.name")); - builder.appendField("osArch", System.getProperty("os.arch")); - builder.appendField("osVersion", System.getProperty("os.version")); - builder.appendField("coreCount", Runtime.getRuntime().availableProcessors()); - } - - private void appendServiceData(JsonObjectBuilder builder) { - builder.appendField("pluginVersion", plugin.getDescription().getVersion()); - } - - private int getPlayerAmount() { - try { - // Around MC 1.8 the return type was changed from an array to a collection, - // This fixes java.lang.NoSuchMethodError: - // org.bukkit.Bukkit.getOnlinePlayers()Ljava/util/Collection; - Method onlinePlayersMethod = Class.forName("org.bukkit.Server").getMethod("getOnlinePlayers"); - return onlinePlayersMethod.getReturnType().equals(Collection.class) - ? ((Collection) onlinePlayersMethod.invoke(Bukkit.getServer())).size() - : ((Player[]) onlinePlayersMethod.invoke(Bukkit.getServer())).length; - } catch (Exception e) { - // Just use the new method if the reflection failed - return Bukkit.getOnlinePlayers().size(); - } - } - - public static class MetricsBase { - - /** The version of the Metrics class. */ - public static final String METRICS_VERSION = "3.0.0"; - - private static final ScheduledExecutorService scheduler = - Executors.newScheduledThreadPool(1, task -> new Thread(task, "bStats-Metrics")); - - private static final String REPORT_URL = "https://bStats.org/api/v2/data/%s"; - - private final String platform; - - private final String serverUuid; - - private final int serviceId; - - private final Consumer appendPlatformDataConsumer; - - private final Consumer appendServiceDataConsumer; - - private final Consumer submitTaskConsumer; - - private final Supplier checkServiceEnabledSupplier; - - private final BiConsumer errorLogger; - - private final Consumer infoLogger; - - private final boolean logErrors; - - private final boolean logSentData; - - private final boolean logResponseStatusText; - - private final Set customCharts = new HashSet<>(); - - private final boolean enabled; - - /** - * Creates a new MetricsBase class instance. - * - * @param platform The platform of the service. - * @param serviceId The id of the service. - * @param serverUuid The server uuid. - * @param enabled Whether or not data sending is enabled. - * @param appendPlatformDataConsumer A consumer that receives a {@code JsonObjectBuilder} and - * appends all platform-specific data. - * @param appendServiceDataConsumer A consumer that receives a {@code JsonObjectBuilder} and - * appends all service-specific data. - * @param submitTaskConsumer A consumer that takes a runnable with the submit task. This can be - * used to delegate the data collection to a another thread to prevent errors caused by - * concurrency. Can be {@code null}. - * @param checkServiceEnabledSupplier A supplier to check if the service is still enabled. - * @param errorLogger A consumer that accepts log message and an error. - * @param infoLogger A consumer that accepts info log messages. - * @param logErrors Whether or not errors should be logged. - * @param logSentData Whether or not the sent data should be logged. - * @param logResponseStatusText Whether or not the response status text should be logged. - */ - public MetricsBase( - String platform, - String serverUuid, - int serviceId, - boolean enabled, - Consumer appendPlatformDataConsumer, - Consumer appendServiceDataConsumer, - Consumer submitTaskConsumer, - Supplier checkServiceEnabledSupplier, - BiConsumer errorLogger, - Consumer infoLogger, - boolean logErrors, - boolean logSentData, - boolean logResponseStatusText) { - this.platform = platform; - this.serverUuid = serverUuid; - this.serviceId = serviceId; - this.enabled = enabled; - this.appendPlatformDataConsumer = appendPlatformDataConsumer; - this.appendServiceDataConsumer = appendServiceDataConsumer; - this.submitTaskConsumer = submitTaskConsumer; - this.checkServiceEnabledSupplier = checkServiceEnabledSupplier; - this.errorLogger = errorLogger; - this.infoLogger = infoLogger; - this.logErrors = logErrors; - this.logSentData = logSentData; - this.logResponseStatusText = logResponseStatusText; - checkRelocation(); - if (enabled) { - // WARNING: Removing the option to opt-out will get your plugin banned from bStats - startSubmitting(); - } - } - - public void addCustomChart(CustomChart chart) { - this.customCharts.add(chart); - } - - private void startSubmitting() { - final Runnable submitTask = - () -> { - if (!enabled || !checkServiceEnabledSupplier.get()) { - // Submitting data or service is disabled - scheduler.shutdown(); - return; - } - if (submitTaskConsumer != null) { - submitTaskConsumer.accept(this::submitData); - } else { - this.submitData(); - } - }; - // Many servers tend to restart at a fixed time at xx:00 which causes an uneven distribution - // of requests on the - // bStats backend. To circumvent this problem, we introduce some randomness into the initial - // and second delay. - // WARNING: You must not modify and part of this Metrics class, including the submit delay or - // frequency! - // WARNING: Modifying this code will get your plugin banned on bStats. Just don't do it! - long initialDelay = (long) (1000 * 60 * (3 + Math.random() * 3)); - long secondDelay = (long) (1000 * 60 * (Math.random() * 30)); - scheduler.schedule(submitTask, initialDelay, TimeUnit.MILLISECONDS); - scheduler.scheduleAtFixedRate( - submitTask, initialDelay + secondDelay, 1000 * 60 * 30, TimeUnit.MILLISECONDS); - } - - private void submitData() { - final JsonObjectBuilder baseJsonBuilder = new JsonObjectBuilder(); - appendPlatformDataConsumer.accept(baseJsonBuilder); - final JsonObjectBuilder serviceJsonBuilder = new JsonObjectBuilder(); - appendServiceDataConsumer.accept(serviceJsonBuilder); - JsonObjectBuilder.JsonObject[] chartData = - customCharts.stream() - .map(customChart -> customChart.getRequestJsonObject(errorLogger, logErrors)) - .filter(Objects::nonNull) - .toArray(JsonObjectBuilder.JsonObject[]::new); - serviceJsonBuilder.appendField("id", serviceId); - serviceJsonBuilder.appendField("customCharts", chartData); - baseJsonBuilder.appendField("service", serviceJsonBuilder.build()); - baseJsonBuilder.appendField("serverUUID", serverUuid); - baseJsonBuilder.appendField("metricsVersion", METRICS_VERSION); - JsonObjectBuilder.JsonObject data = baseJsonBuilder.build(); - scheduler.execute( - () -> { - try { - // Send the data - sendData(data); - } catch (Exception e) { - // Something went wrong! :( - if (logErrors) { - errorLogger.accept("Could not submit bStats metrics data", e); - } - } - }); - } - - private void sendData(JsonObjectBuilder.JsonObject data) throws Exception { - if (logSentData) { - infoLogger.accept("Sent bStats metrics data: " + data.toString()); - } - String url = String.format(REPORT_URL, platform); - HttpsURLConnection connection = (HttpsURLConnection) new URL(url).openConnection(); - // Compress the data to save bandwidth - byte[] compressedData = compress(data.toString()); - connection.setRequestMethod("POST"); - connection.addRequestProperty("Accept", "application/json"); - connection.addRequestProperty("Connection", "close"); - connection.addRequestProperty("Content-Encoding", "gzip"); - connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length)); - connection.setRequestProperty("Content-Type", "application/json"); - connection.setRequestProperty("User-Agent", "Metrics-Service/1"); - connection.setDoOutput(true); - try (DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) { - outputStream.write(compressedData); - } - StringBuilder builder = new StringBuilder(); - try (BufferedReader bufferedReader = - new BufferedReader(new InputStreamReader(connection.getInputStream()))) { - String line; - while ((line = bufferedReader.readLine()) != null) { - builder.append(line); - } - } - if (logResponseStatusText) { - infoLogger.accept("Sent data to bStats and received response: " + builder); - } - } - - /** Checks that the class was properly relocated. */ - private void checkRelocation() { - // You can use the property to disable the check in your test environment - if (System.getProperty("bstats.relocatecheck") == null - || !System.getProperty("bstats.relocatecheck").equals("false")) { - // Maven's Relocate is clever and changes strings, too. So we have to use this little - // "trick" ... :D - final String defaultPackage = - new String(new byte[] {'o', 'r', 'g', '.', 'b', 's', 't', 'a', 't', 's'}); - final String examplePackage = - new String(new byte[] {'y', 'o', 'u', 'r', '.', 'p', 'a', 'c', 'k', 'a', 'g', 'e'}); - // We want to make sure no one just copy & pastes the example and uses the wrong package - // names - if (MetricsBase.class.getPackage().getName().startsWith(defaultPackage) - || MetricsBase.class.getPackage().getName().startsWith(examplePackage)) { - throw new IllegalStateException("bStats Metrics class has not been relocated correctly!"); - } - } - } - - /** - * Gzips the given string. - * - * @param str The string to gzip. - * @return The gzipped string. - */ - private static byte[] compress(final String str) throws IOException { - if (str == null) { - return null; - } - ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); - try (GZIPOutputStream gzip = new GZIPOutputStream(outputStream)) { - gzip.write(str.getBytes(StandardCharsets.UTF_8)); - } - return outputStream.toByteArray(); - } - } - - public static class DrilldownPie extends CustomChart { - - private final Callable>> callable; - - /** - * Class constructor. - * - * @param chartId The id of the chart. - * @param callable The callable which is used to request the chart data. - */ - public DrilldownPie(String chartId, Callable>> callable) { - super(chartId); - this.callable = callable; - } - - @Override - public JsonObjectBuilder.JsonObject getChartData() throws Exception { - JsonObjectBuilder valuesBuilder = new JsonObjectBuilder(); - Map> map = callable.call(); - if (map == null || map.isEmpty()) { - // Null = skip the chart - return null; - } - boolean reallyAllSkipped = true; - for (Map.Entry> entryValues : map.entrySet()) { - JsonObjectBuilder valueBuilder = new JsonObjectBuilder(); - boolean allSkipped = true; - for (Map.Entry valueEntry : map.get(entryValues.getKey()).entrySet()) { - valueBuilder.appendField(valueEntry.getKey(), valueEntry.getValue()); - allSkipped = false; - } - if (!allSkipped) { - reallyAllSkipped = false; - valuesBuilder.appendField(entryValues.getKey(), valueBuilder.build()); - } - } - if (reallyAllSkipped) { - // Null = skip the chart - return null; - } - return new JsonObjectBuilder().appendField("values", valuesBuilder.build()).build(); - } - } - - public static class AdvancedPie extends CustomChart { - - private final Callable> callable; - - /** - * Class constructor. - * - * @param chartId The id of the chart. - * @param callable The callable which is used to request the chart data. - */ - public AdvancedPie(String chartId, Callable> callable) { - super(chartId); - this.callable = callable; - } - - @Override - protected JsonObjectBuilder.JsonObject getChartData() throws Exception { - JsonObjectBuilder valuesBuilder = new JsonObjectBuilder(); - Map map = callable.call(); - if (map == null || map.isEmpty()) { - // Null = skip the chart - return null; - } - boolean allSkipped = true; - for (Map.Entry entry : map.entrySet()) { - if (entry.getValue() == 0) { - // Skip this invalid - continue; - } - allSkipped = false; - valuesBuilder.appendField(entry.getKey(), entry.getValue()); - } - if (allSkipped) { - // Null = skip the chart - return null; - } - return new JsonObjectBuilder().appendField("values", valuesBuilder.build()).build(); - } - } - - public static class MultiLineChart extends CustomChart { - - private final Callable> callable; - - /** - * Class constructor. - * - * @param chartId The id of the chart. - * @param callable The callable which is used to request the chart data. - */ - public MultiLineChart(String chartId, Callable> callable) { - super(chartId); - this.callable = callable; - } - - @Override - protected JsonObjectBuilder.JsonObject getChartData() throws Exception { - JsonObjectBuilder valuesBuilder = new JsonObjectBuilder(); - Map map = callable.call(); - if (map == null || map.isEmpty()) { - // Null = skip the chart - return null; - } - boolean allSkipped = true; - for (Map.Entry entry : map.entrySet()) { - if (entry.getValue() == 0) { - // Skip this invalid - continue; - } - allSkipped = false; - valuesBuilder.appendField(entry.getKey(), entry.getValue()); - } - if (allSkipped) { - // Null = skip the chart - return null; - } - return new JsonObjectBuilder().appendField("values", valuesBuilder.build()).build(); - } - } - - public static class SimpleBarChart extends CustomChart { - - private final Callable> callable; - - /** - * Class constructor. - * - * @param chartId The id of the chart. - * @param callable The callable which is used to request the chart data. - */ - public SimpleBarChart(String chartId, Callable> callable) { - super(chartId); - this.callable = callable; - } - - @Override - protected JsonObjectBuilder.JsonObject getChartData() throws Exception { - JsonObjectBuilder valuesBuilder = new JsonObjectBuilder(); - Map map = callable.call(); - if (map == null || map.isEmpty()) { - // Null = skip the chart - return null; - } - for (Map.Entry entry : map.entrySet()) { - valuesBuilder.appendField(entry.getKey(), new int[] {entry.getValue()}); - } - return new JsonObjectBuilder().appendField("values", valuesBuilder.build()).build(); - } - } - - public abstract static class CustomChart { - - private final String chartId; - - protected CustomChart(String chartId) { - if (chartId == null) { - throw new IllegalArgumentException("chartId must not be null"); - } - this.chartId = chartId; - } - - public JsonObjectBuilder.JsonObject getRequestJsonObject( - BiConsumer errorLogger, boolean logErrors) { - JsonObjectBuilder builder = new JsonObjectBuilder(); - builder.appendField("chartId", chartId); - try { - JsonObjectBuilder.JsonObject data = getChartData(); - if (data == null) { - // If the data is null we don't send the chart. - return null; - } - builder.appendField("data", data); - } catch (Throwable t) { - if (logErrors) { - errorLogger.accept("Failed to get data for custom chart with id " + chartId, t); - } - return null; - } - return builder.build(); - } - - protected abstract JsonObjectBuilder.JsonObject getChartData() throws Exception; - } - - public static class SimplePie extends CustomChart { - - private final Callable callable; - - /** - * Class constructor. - * - * @param chartId The id of the chart. - * @param callable The callable which is used to request the chart data. - */ - public SimplePie(String chartId, Callable callable) { - super(chartId); - this.callable = callable; - } - - @Override - protected JsonObjectBuilder.JsonObject getChartData() throws Exception { - String value = callable.call(); - if (value == null || value.isEmpty()) { - // Null = skip the chart - return null; - } - return new JsonObjectBuilder().appendField("value", value).build(); - } - } - - public static class AdvancedBarChart extends CustomChart { - - private final Callable> callable; - - /** - * Class constructor. - * - * @param chartId The id of the chart. - * @param callable The callable which is used to request the chart data. - */ - public AdvancedBarChart(String chartId, Callable> callable) { - super(chartId); - this.callable = callable; - } - - @Override - protected JsonObjectBuilder.JsonObject getChartData() throws Exception { - JsonObjectBuilder valuesBuilder = new JsonObjectBuilder(); - Map map = callable.call(); - if (map == null || map.isEmpty()) { - // Null = skip the chart - return null; - } - boolean allSkipped = true; - for (Map.Entry entry : map.entrySet()) { - if (entry.getValue().length == 0) { - // Skip this invalid - continue; - } - allSkipped = false; - valuesBuilder.appendField(entry.getKey(), entry.getValue()); - } - if (allSkipped) { - // Null = skip the chart - return null; - } - return new JsonObjectBuilder().appendField("values", valuesBuilder.build()).build(); - } - } - - public static class SingleLineChart extends CustomChart { - - private final Callable callable; - - /** - * Class constructor. - * - * @param chartId The id of the chart. - * @param callable The callable which is used to request the chart data. - */ - public SingleLineChart(String chartId, Callable callable) { - super(chartId); - this.callable = callable; - } - - @Override - protected JsonObjectBuilder.JsonObject getChartData() throws Exception { - int value = callable.call(); - if (value == 0) { - // Null = skip the chart - return null; - } - return new JsonObjectBuilder().appendField("value", value).build(); - } - } - - /** - * An extremely simple JSON builder. - * - *

While this class is neither feature-rich nor the most performant one, it's sufficient enough - * for its use-case. - */ - public static class JsonObjectBuilder { - - private StringBuilder builder = new StringBuilder(); - - private boolean hasAtLeastOneField = false; - - public JsonObjectBuilder() { - builder.append("{"); - } - - /** - * Appends a null field to the JSON. - * - * @param key The key of the field. - * @return A reference to this object. - */ - public JsonObjectBuilder appendNull(String key) { - appendFieldUnescaped(key, "null"); - return this; - } - - /** - * Appends a string field to the JSON. - * - * @param key The key of the field. - * @param value The value of the field. - * @return A reference to this object. - */ - public JsonObjectBuilder appendField(String key, String value) { - if (value == null) { - throw new IllegalArgumentException("JSON value must not be null"); - } - appendFieldUnescaped(key, "\"" + escape(value) + "\""); - return this; - } - - /** - * Appends an integer field to the JSON. - * - * @param key The key of the field. - * @param value The value of the field. - * @return A reference to this object. - */ - public JsonObjectBuilder appendField(String key, int value) { - appendFieldUnescaped(key, String.valueOf(value)); - return this; - } - - /** - * Appends an object to the JSON. - * - * @param key The key of the field. - * @param object The object. - * @return A reference to this object. - */ - public JsonObjectBuilder appendField(String key, JsonObject object) { - if (object == null) { - throw new IllegalArgumentException("JSON object must not be null"); - } - appendFieldUnescaped(key, object.toString()); - return this; - } - - /** - * Appends a string array to the JSON. - * - * @param key The key of the field. - * @param values The string array. - * @return A reference to this object. - */ - public JsonObjectBuilder appendField(String key, String[] values) { - if (values == null) { - throw new IllegalArgumentException("JSON values must not be null"); - } - String escapedValues = - Arrays.stream(values) - .map(value -> "\"" + escape(value) + "\"") - .collect(Collectors.joining(",")); - appendFieldUnescaped(key, "[" + escapedValues + "]"); - return this; - } - - /** - * Appends an integer array to the JSON. - * - * @param key The key of the field. - * @param values The integer array. - * @return A reference to this object. - */ - public JsonObjectBuilder appendField(String key, int[] values) { - if (values == null) { - throw new IllegalArgumentException("JSON values must not be null"); - } - String escapedValues = - Arrays.stream(values).mapToObj(String::valueOf).collect(Collectors.joining(",")); - appendFieldUnescaped(key, "[" + escapedValues + "]"); - return this; - } - - /** - * Appends an object array to the JSON. - * - * @param key The key of the field. - * @param values The integer array. - * @return A reference to this object. - */ - public JsonObjectBuilder appendField(String key, JsonObject[] values) { - if (values == null) { - throw new IllegalArgumentException("JSON values must not be null"); - } - String escapedValues = - Arrays.stream(values).map(JsonObject::toString).collect(Collectors.joining(",")); - appendFieldUnescaped(key, "[" + escapedValues + "]"); - return this; - } - - /** - * Appends a field to the object. - * - * @param key The key of the field. - * @param escapedValue The escaped value of the field. - */ - private void appendFieldUnescaped(String key, String escapedValue) { - if (builder == null) { - throw new IllegalStateException("JSON has already been built"); - } - if (key == null) { - throw new IllegalArgumentException("JSON key must not be null"); - } - if (hasAtLeastOneField) { - builder.append(","); - } - builder.append("\"").append(escape(key)).append("\":").append(escapedValue); - hasAtLeastOneField = true; - } - - /** - * Builds the JSON string and invalidates this builder. - * - * @return The built JSON string. - */ - public JsonObject build() { - if (builder == null) { - throw new IllegalStateException("JSON has already been built"); - } - JsonObject object = new JsonObject(builder.append("}").toString()); - builder = null; - return object; - } - - /** - * Escapes the given string like stated in https://www.ietf.org/rfc/rfc4627.txt. - * - *

This method escapes only the necessary characters '"', '\'. and '\u0000' - '\u001F'. - * Compact escapes are not used (e.g., '\n' is escaped as "\u000a" and not as "\n"). - * - * @param value The value to escape. - * @return The escaped value. - */ - private static String escape(String value) { - final StringBuilder builder = new StringBuilder(); - for (int i = 0; i < value.length(); i++) { - char c = value.charAt(i); - if (c == '"') { - builder.append("\\\""); - } else if (c == '\\') { - builder.append("\\\\"); - } else if (c <= '\u000F') { - builder.append("\\u000").append(Integer.toHexString(c)); - } else if (c <= '\u001F') { - builder.append("\\u00").append(Integer.toHexString(c)); - } else { - builder.append(c); - } - } - return builder.toString(); - } - - /** - * A super simple representation of a JSON object. - * - *

This class only exists to make methods of the {@link JsonObjectBuilder} type-safe and not - * allow a raw string inputs for methods like {@link JsonObjectBuilder#appendField(String, - * JsonObject)}. - */ - public static class JsonObject { - - private final String value; - - private JsonObject(String value) { - this.value = value; - } - - @Override - public String toString() { - return value; - } - } - } -} \ No newline at end of file diff --git a/src/main/java/pl/minecon724/realweather/weather/GetStateTask.java b/src/main/java/pl/minecon724/realweather/weather/GetStateTask.java new file mode 100644 index 0000000..4ba6bdb --- /dev/null +++ b/src/main/java/pl/minecon724/realweather/weather/GetStateTask.java @@ -0,0 +1,73 @@ +package pl.minecon724.realweather.weather; + +import java.util.List; +import java.util.logging.Logger; + +import org.bukkit.Bukkit; +import org.bukkit.WeatherType; +import org.bukkit.World; +import org.bukkit.entity.Player; +import org.bukkit.scheduler.BukkitRunnable; + +import pl.minecon724.realweather.map.WorldMap; +import pl.minecon724.realweather.map.WorldMap.Type; +import pl.minecon724.realweather.map.exceptions.GeoIPException; +import pl.minecon724.realweather.weather.WeatherState.ConditionSimple; +import pl.minecon724.realweather.weather.WeatherState.State; +import pl.minecon724.realweather.weather.provider.Provider; + +public class GetStateTask extends BukkitRunnable { + + Logger logger = Logger.getLogger("weather scheduler"); + + Provider provider; + WorldMap worldMap; + List worlds; + + public GetStateTask( + Provider provider, + WorldMap worldMap, + List worlds + ) { + this.provider = provider; + this.worldMap = worldMap; + this.worlds = worlds; + } + + // That's a lot of variables + + @Override + public void run() { + + if (worldMap.getType() == Type.POINT) { + double[] position; + try { + position = worldMap.getPosition(null); + } catch (GeoIPException e) { return; } + State state = provider.request_state(position); + + for (World world : worlds) { + if (world == null) return; + world.setThundering(state.getSimple() == ConditionSimple.THUNDER ? true : false); + world.setStorm(state.getSimple() == ConditionSimple.CLEAR ? false : true); + } + + } else { + for (Player player : Bukkit.getOnlinePlayers()) { + double[] position; + + try { + position = worldMap.getPosition(player); + } catch (GeoIPException e) { + logger.info("GeoIP error for " + player.getName()); + e.printStackTrace(); + continue; + } + + State state = provider.request_state(position); + player.setPlayerWeather(state.getSimple() == ConditionSimple.CLEAR ? WeatherType.CLEAR : WeatherType.DOWNFALL); + } + } + + } +} diff --git a/src/main/java/pl/minecon724/realweather/weather/Providers.java b/src/main/java/pl/minecon724/realweather/weather/Providers.java new file mode 100644 index 0000000..9983e03 --- /dev/null +++ b/src/main/java/pl/minecon724/realweather/weather/Providers.java @@ -0,0 +1,35 @@ +package pl.minecon724.realweather.weather; + +import org.bukkit.configuration.ConfigurationSection; + +import pl.minecon724.realweather.weather.exceptions.ProviderException; +import pl.minecon724.realweather.weather.provider.OpenWeatherMapProvider; +import pl.minecon724.realweather.weather.provider.Provider; + +public class Providers { + /** + * get Provider by name + * @param name name of provider + * @param config configuration of provider + * @return subclass of Provider or null if invalid + * @throws ProviderException + * @see Provider + */ + public static Provider getByName(String name, ConfigurationSection config) + throws ProviderException { + + switch (name) { + case "openweathermap": + return openWeatherMap(config); + } + + return null; + } + + public static OpenWeatherMapProvider openWeatherMap(ConfigurationSection config) + throws ProviderException { + + return new OpenWeatherMapProvider( + config.getString("apiKey")); + } +} diff --git a/src/main/java/pl/minecon724/realweather/weather/WeatherCommander.java b/src/main/java/pl/minecon724/realweather/weather/WeatherCommander.java new file mode 100644 index 0000000..d17c9b8 --- /dev/null +++ b/src/main/java/pl/minecon724/realweather/weather/WeatherCommander.java @@ -0,0 +1,64 @@ +package pl.minecon724.realweather.weather; + +import java.util.ArrayList; +import java.util.List; + +import org.bukkit.World; +import org.bukkit.configuration.ConfigurationSection; + +import pl.minecon724.realweather.RW; +import pl.minecon724.realweather.map.WorldMap; +import pl.minecon724.realweather.weather.exceptions.DisabledException; +import pl.minecon724.realweather.weather.exceptions.ProviderException; +import pl.minecon724.realweather.weather.provider.Provider; + +public class WeatherCommander { + WorldMap worldMap; + RW plugin; + + boolean enabled; + List worlds; + String providerName; + Provider provider; + ConfigurationSection providerConfig; + + GetStateTask getStateTask; + + public WeatherCommander(WorldMap worldMap, RW plugin) { + this.worldMap = worldMap; + this.plugin = plugin; + } + + /** + * Initialize weather commander + * @param config "weather" ConfigurationSection + * @throws DisabledException if disabled in config + * @throws ProviderException if invalid provider config + */ + public void init(ConfigurationSection config) + throws DisabledException, ProviderException { + enabled = config.getBoolean("enabled"); + + if (!enabled) + throw new DisabledException(); + + worlds = config.getStringList("worlds"); + + providerName = config.getString("provider.choice"); + + // this can be null + providerConfig = config.getConfigurationSection("provider") + .getConfigurationSection(providerName); + + provider = Providers.getByName(providerName, providerConfig); + provider.init(); + } + + public void start() { + getStateTask = new GetStateTask(provider, + worldMap, + new ArrayList()); + + getStateTask.runTaskTimerAsynchronously(plugin, 0, 1200); + } +} diff --git a/src/main/java/pl/minecon724/realweather/WeatherState.java b/src/main/java/pl/minecon724/realweather/weather/WeatherState.java similarity index 74% rename from src/main/java/pl/minecon724/realweather/WeatherState.java rename to src/main/java/pl/minecon724/realweather/weather/WeatherState.java index 3e58177..738c86c 100644 --- a/src/main/java/pl/minecon724/realweather/WeatherState.java +++ b/src/main/java/pl/minecon724/realweather/weather/WeatherState.java @@ -1,4 +1,4 @@ -package pl.minecon724.realweather; +package pl.minecon724.realweather.weather; public class WeatherState { @@ -14,9 +14,9 @@ public class WeatherState { // Variables - Condition condition; - ConditionLevel level; - ConditionSimple simple; + private Condition condition; + private ConditionLevel level; + private ConditionSimple simple; // Constructor @@ -47,5 +47,17 @@ public class WeatherState { this.simple = ConditionSimple.CLEAR; } } + + public Condition getCondition() { + return condition; + } + + public ConditionLevel getLevel() { + return level; + } + + public ConditionSimple getSimple() { + return simple; + } } } diff --git a/src/main/java/pl/minecon724/realweather/weather/exceptions/DisabledException.java b/src/main/java/pl/minecon724/realweather/weather/exceptions/DisabledException.java new file mode 100644 index 0000000..dde43be --- /dev/null +++ b/src/main/java/pl/minecon724/realweather/weather/exceptions/DisabledException.java @@ -0,0 +1,5 @@ +package pl.minecon724.realweather.weather.exceptions; + +public class DisabledException extends Exception { + +} diff --git a/src/main/java/pl/minecon724/realweather/weather/exceptions/ProviderException.java b/src/main/java/pl/minecon724/realweather/weather/exceptions/ProviderException.java new file mode 100644 index 0000000..27063af --- /dev/null +++ b/src/main/java/pl/minecon724/realweather/weather/exceptions/ProviderException.java @@ -0,0 +1,5 @@ +package pl.minecon724.realweather.weather.exceptions; + +public class ProviderException extends Exception { + +} diff --git a/src/main/java/pl/minecon724/realweather/provider/OpenWeatherMapProvider.java b/src/main/java/pl/minecon724/realweather/weather/provider/OpenWeatherMapProvider.java similarity index 91% rename from src/main/java/pl/minecon724/realweather/provider/OpenWeatherMapProvider.java rename to src/main/java/pl/minecon724/realweather/weather/provider/OpenWeatherMapProvider.java index d8cae5d..a077d40 100644 --- a/src/main/java/pl/minecon724/realweather/provider/OpenWeatherMapProvider.java +++ b/src/main/java/pl/minecon724/realweather/weather/provider/OpenWeatherMapProvider.java @@ -1,4 +1,4 @@ -package pl.minecon724.realweather.provider; +package pl.minecon724.realweather.weather.provider; import java.io.BufferedReader; import java.io.InputStream; @@ -9,8 +9,7 @@ import java.nio.charset.Charset; import org.json.JSONObject; -import pl.minecon724.realweather.Provider; -import pl.minecon724.realweather.WeatherState.*; +import pl.minecon724.realweather.weather.WeatherState.*; public class OpenWeatherMapProvider implements Provider { @@ -30,13 +29,13 @@ public class OpenWeatherMapProvider implements Provider { } } - public State request_state(double lat, double lon) { + public State request_state(double[] coords) { JSONObject json = new JSONObject(); try { URL url = new URL( endpoint + String.format("/data/2.5/weather?lat=%s&lon=%s&appid=%s", - Double.toString(lat), Double.toString(lon), apiKey + Double.toString(coords[0]), Double.toString(coords[1]), apiKey )); InputStream is = url.openStream(); @@ -153,4 +152,9 @@ public class OpenWeatherMapProvider implements Provider { State state = new State(condition, level); return state; } + + @Override + public String getName() { + return "OpenWeatherMap"; + } } diff --git a/src/main/java/pl/minecon724/realweather/weather/provider/Provider.java b/src/main/java/pl/minecon724/realweather/weather/provider/Provider.java new file mode 100644 index 0000000..7527300 --- /dev/null +++ b/src/main/java/pl/minecon724/realweather/weather/provider/Provider.java @@ -0,0 +1,9 @@ +package pl.minecon724.realweather.weather.provider; + +import pl.minecon724.realweather.weather.WeatherState; + +public interface Provider { + public void init(); + public WeatherState.State request_state(double[] coords); + public String getName(); +} diff --git a/src/main/resources/config.yml b/src/main/resources/config.yml index 3570e7c..905f94e 100644 --- a/src/main/resources/config.yml +++ b/src/main/resources/config.yml @@ -1,71 +1,73 @@ weather: + enabled: true + worlds: - world - second_world - third_world + + provider: + # Weather provider + choice: openweathermap + # Configure it here + openweathermap: + apiKey: 'd3d37fd3511ef1d4b44c7d574e9b56b8' # PLEASE get your own @ https://home.openweathermap.org/users/sign_up + # More providers soon! + +map: # "point" - static location # "player" - player's IP location (fake weather) - # "map" - world resembles a real-world globe - source: point + # "globe" - world resembles a real-world globe + type: point + point: latitude: 41.84201 longitude: -89.485937 + player: # Get your own @ https://www.maxmind.com/en/geolite2/signup geolite2_accountId: 710438 - geolite2_apiKey: 'qLeseHp4QNQcqRGn' - map: + geolite2_api_key: 'qLeseHp4QNQcqRGn' + + globe: # Valid latitude range: -90 to 90 # Valid longitude range: -180 to 180 # 1 degree of latitude and longitude is about 111 km # The defaults here assume 1 block = ~1 km - # Latitude scale, 1 block = degrees - scale_lat: 0.009 - # Longitude scale, 1 block = degrees - scale_lon: 0.009 - # What to do if player exceeds the range specified above - # 1 - do nothing (clamp to nearest allowed value) - # 2 - wrap the number - # for example; if a player's position on map converts to 94 degrees (out of bounds), it becomes -86 degrees - on_exceed: 2 + # 1 block = degrees + scale_latitude: 0.009 + scale_longitude: 0.009 -provider: - # Weather provider - choice: openweathermap - # Configure it here - openweathermap: - apiKey: 'd3d37fd3511ef1d4b44c7d574e9b56b8' # PLEASE get your own @ https://home.openweathermap.org/users/sign_up - # More providers soon! + # What to do if player exceeds the range specified above + # false - do nothing (clamp to nearest allowed value) + # true - wrap the number + # for example; if a player's position on map converts to 94 degrees (out of bounds), it becomes -86 degrees + wrap: true realtime: # warning: this removes sleep enabled: false + worlds: - world + # "auto" to use server's timezone # Alternatively choose one of these: https://en.wikipedia.org/wiki/List_of_tz_database_time_zones#List + # if "real" each player's timezone is varied based on where they are + # config from map.globe is used, also forces virtual + # WARNING: it is purely cosmetical timezone: 'auto' + # x day cycles / 24 hrs timeScale: 1.0 + # How often should we recalculate the time (in ticks) # Very minimal impact on performance interval: 1 -settings: - # Delay between rechecking weather - # in ticks, 20 is one second - # Shouldn't affect performance - timeBetweenRecheck: 600 - # Whether to display an actionbar containing info - actionbar: true + # makes time visible to players not in sync with server + virtual: false - # Advanced options - timeBeforeInitialRun: 0 - debug: false - debugAllowDox: false - -messages: - # settings.actionbar toggles this - # %weather_full% - full state description, such as "extreme thunder" - # %weather% - short state description, such as "rain" - actionbarInfo: "&b%weather_full%" + # if above true, locks the server's time (in ticks) + # -1 to disable + lock: 0 diff --git a/src/main/resources/plugin.yml b/src/main/resources/plugin.yml index 4206008..1842148 100644 --- a/src/main/resources/plugin.yml +++ b/src/main/resources/plugin.yml @@ -4,9 +4,5 @@ api-version: 1.16 author: Minecon724 main: pl.minecon724.realweather.RW libraries: - - org.json:json:20220320 - - com.maxmind.geoip2:geoip2:4.1.0 -commands: - realweather: - alias: rw - description: RealWeather main command \ No newline at end of file + - org.json:json:20231013 + - com.maxmind.geoip2:geoip2:4.2.0 \ No newline at end of file