work on 0.5.0
many changes, primarily refactoring warning: won't work yet
This commit is contained in:
parent
e2254f6c67
commit
e6f4fd527c
22 changed files with 477 additions and 1168 deletions
5
TODO.md
Normal file
5
TODO.md
Normal file
|
@ -0,0 +1,5 @@
|
||||||
|
- local maxmind
|
||||||
|
- account for real sun movement, not just time
|
||||||
|
- gh actions
|
||||||
|
- readd metrics
|
||||||
|
- fix realtime
|
8
pom.xml
8
pom.xml
|
@ -2,7 +2,7 @@
|
||||||
<modelVersion>4.0.0</modelVersion>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
<groupId>pl.minecon724</groupId>
|
<groupId>pl.minecon724</groupId>
|
||||||
<artifactId>realweather</artifactId>
|
<artifactId>realweather</artifactId>
|
||||||
<version>0.4.1</version>
|
<version>0.5.0-DEV</version>
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<maven.compiler.source>17</maven.compiler.source>
|
<maven.compiler.source>17</maven.compiler.source>
|
||||||
|
@ -20,19 +20,19 @@
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.spigotmc</groupId>
|
<groupId>org.spigotmc</groupId>
|
||||||
<artifactId>spigot-api</artifactId>
|
<artifactId>spigot-api</artifactId>
|
||||||
<version>1.20.1-R0.1-SNAPSHOT</version>
|
<version>1.20.4-R0.1-SNAPSHOT</version>
|
||||||
<scope>provided</scope>
|
<scope>provided</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.json</groupId>
|
<groupId>org.json</groupId>
|
||||||
<artifactId>json</artifactId>
|
<artifactId>json</artifactId>
|
||||||
<version>20230227</version>
|
<version>20231013</version>
|
||||||
<scope>provided</scope>
|
<scope>provided</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>com.maxmind.geoip2</groupId>
|
<groupId>com.maxmind.geoip2</groupId>
|
||||||
<artifactId>geoip2</artifactId>
|
<artifactId>geoip2</artifactId>
|
||||||
<version>4.1.0</version>
|
<version>4.2.0</version>
|
||||||
<scope>provided</scope>
|
<scope>provided</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
|
@ -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<String> 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<String> 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))
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -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;
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,6 +0,0 @@
|
||||||
package pl.minecon724.realweather;
|
|
||||||
|
|
||||||
public interface Provider {
|
|
||||||
public void init();
|
|
||||||
public WeatherState.State request_state(double lat, double lon);
|
|
||||||
}
|
|
|
@ -10,10 +10,14 @@ import org.bukkit.configuration.ConfigurationSection;
|
||||||
import org.bukkit.configuration.file.FileConfiguration;
|
import org.bukkit.configuration.file.FileConfiguration;
|
||||||
import org.bukkit.plugin.java.JavaPlugin;
|
import org.bukkit.plugin.java.JavaPlugin;
|
||||||
|
|
||||||
import pl.minecon724.realweather.commands.RealWeatherCommand;
|
import pl.minecon724.realweather.map.WorldMap;
|
||||||
import pl.minecon724.realweather.provider.OpenWeatherMapProvider;
|
|
||||||
import pl.minecon724.realweather.realtime.RTTask;
|
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 {
|
public class RW extends JavaPlugin {
|
||||||
FileConfiguration config;
|
FileConfiguration config;
|
||||||
|
@ -27,62 +31,19 @@ public class RW extends JavaPlugin {
|
||||||
saveDefaultConfig();
|
saveDefaultConfig();
|
||||||
config = getConfig();
|
config = getConfig();
|
||||||
|
|
||||||
ConfigurationSection weatherSec = config.getConfigurationSection("weather");
|
WorldMap worldMap = WorldMap.fromConfig(
|
||||||
ConfigurationSection providerSec = config.getConfigurationSection("provider");
|
config.getConfigurationSection("map")
|
||||||
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<String> 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")
|
|
||||||
);
|
);
|
||||||
|
|
||||||
|
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")) {
|
if (realtimeSec.getBoolean("enabled")) {
|
||||||
ZoneId zone;
|
ZoneId zone;
|
||||||
try {
|
try {
|
||||||
|
@ -97,11 +58,6 @@ public class RW extends JavaPlugin {
|
||||||
).runTaskTimer(this, 0, realtimeSec.getLong("interval"));
|
).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();
|
long end = System.currentTimeMillis();
|
||||||
this.getLogger().info( String.format( this.getName() + " enabled! (%s ms)", Long.toString( end-start ) ) );
|
this.getLogger().info( String.format( this.getName() + " enabled! (%s ms)", Long.toString( end-start ) ) );
|
||||||
}
|
}
|
||||||
|
|
|
@ -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;
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
49
src/main/java/pl/minecon724/realweather/map/GeoLocator.java
Normal file
49
src/main/java/pl/minecon724/realweather/map/GeoLocator.java
Normal file
|
@ -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()
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
37
src/main/java/pl/minecon724/realweather/map/Globe.java
Normal file
37
src/main/java/pl/minecon724/realweather/map/Globe.java
Normal file
|
@ -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;
|
||||||
|
}
|
||||||
|
}
|
98
src/main/java/pl/minecon724/realweather/map/WorldMap.java
Normal file
98
src/main/java/pl/minecon724/realweather/map/WorldMap.java
Normal file
|
@ -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
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,9 @@
|
||||||
|
package pl.minecon724.realweather.map.exceptions;
|
||||||
|
|
||||||
|
public class GeoIPException extends Exception {
|
||||||
|
|
||||||
|
public GeoIPException(String string) {
|
||||||
|
super(string);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -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 <a
|
|
||||||
* href="https://bstats.org/what-is-my-plugin-id">What is my plugin id?</a>
|
|
||||||
*/
|
|
||||||
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<JsonObjectBuilder> appendPlatformDataConsumer;
|
|
||||||
|
|
||||||
private final Consumer<JsonObjectBuilder> appendServiceDataConsumer;
|
|
||||||
|
|
||||||
private final Consumer<Runnable> submitTaskConsumer;
|
|
||||||
|
|
||||||
private final Supplier<Boolean> checkServiceEnabledSupplier;
|
|
||||||
|
|
||||||
private final BiConsumer<String, Throwable> errorLogger;
|
|
||||||
|
|
||||||
private final Consumer<String> infoLogger;
|
|
||||||
|
|
||||||
private final boolean logErrors;
|
|
||||||
|
|
||||||
private final boolean logSentData;
|
|
||||||
|
|
||||||
private final boolean logResponseStatusText;
|
|
||||||
|
|
||||||
private final Set<CustomChart> 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<JsonObjectBuilder> appendPlatformDataConsumer,
|
|
||||||
Consumer<JsonObjectBuilder> appendServiceDataConsumer,
|
|
||||||
Consumer<Runnable> submitTaskConsumer,
|
|
||||||
Supplier<Boolean> checkServiceEnabledSupplier,
|
|
||||||
BiConsumer<String, Throwable> errorLogger,
|
|
||||||
Consumer<String> 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<Map<String, Map<String, Integer>>> 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<Map<String, Map<String, Integer>>> callable) {
|
|
||||||
super(chartId);
|
|
||||||
this.callable = callable;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public JsonObjectBuilder.JsonObject getChartData() throws Exception {
|
|
||||||
JsonObjectBuilder valuesBuilder = new JsonObjectBuilder();
|
|
||||||
Map<String, Map<String, Integer>> map = callable.call();
|
|
||||||
if (map == null || map.isEmpty()) {
|
|
||||||
// Null = skip the chart
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
boolean reallyAllSkipped = true;
|
|
||||||
for (Map.Entry<String, Map<String, Integer>> entryValues : map.entrySet()) {
|
|
||||||
JsonObjectBuilder valueBuilder = new JsonObjectBuilder();
|
|
||||||
boolean allSkipped = true;
|
|
||||||
for (Map.Entry<String, Integer> 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<Map<String, Integer>> 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<Map<String, Integer>> callable) {
|
|
||||||
super(chartId);
|
|
||||||
this.callable = callable;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
protected JsonObjectBuilder.JsonObject getChartData() throws Exception {
|
|
||||||
JsonObjectBuilder valuesBuilder = new JsonObjectBuilder();
|
|
||||||
Map<String, Integer> map = callable.call();
|
|
||||||
if (map == null || map.isEmpty()) {
|
|
||||||
// Null = skip the chart
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
boolean allSkipped = true;
|
|
||||||
for (Map.Entry<String, Integer> 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<Map<String, Integer>> 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<Map<String, Integer>> callable) {
|
|
||||||
super(chartId);
|
|
||||||
this.callable = callable;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
protected JsonObjectBuilder.JsonObject getChartData() throws Exception {
|
|
||||||
JsonObjectBuilder valuesBuilder = new JsonObjectBuilder();
|
|
||||||
Map<String, Integer> map = callable.call();
|
|
||||||
if (map == null || map.isEmpty()) {
|
|
||||||
// Null = skip the chart
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
boolean allSkipped = true;
|
|
||||||
for (Map.Entry<String, Integer> 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<Map<String, Integer>> 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<Map<String, Integer>> callable) {
|
|
||||||
super(chartId);
|
|
||||||
this.callable = callable;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
protected JsonObjectBuilder.JsonObject getChartData() throws Exception {
|
|
||||||
JsonObjectBuilder valuesBuilder = new JsonObjectBuilder();
|
|
||||||
Map<String, Integer> map = callable.call();
|
|
||||||
if (map == null || map.isEmpty()) {
|
|
||||||
// Null = skip the chart
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
for (Map.Entry<String, Integer> 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<String, Throwable> 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<String> 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<String> 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<Map<String, int[]>> 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<Map<String, int[]>> callable) {
|
|
||||||
super(chartId);
|
|
||||||
this.callable = callable;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
protected JsonObjectBuilder.JsonObject getChartData() throws Exception {
|
|
||||||
JsonObjectBuilder valuesBuilder = new JsonObjectBuilder();
|
|
||||||
Map<String, int[]> map = callable.call();
|
|
||||||
if (map == null || map.isEmpty()) {
|
|
||||||
// Null = skip the chart
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
boolean allSkipped = true;
|
|
||||||
for (Map.Entry<String, int[]> 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<Integer> 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<Integer> 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.
|
|
||||||
*
|
|
||||||
* <p>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.
|
|
||||||
*
|
|
||||||
* <p>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.
|
|
||||||
*
|
|
||||||
* <p>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;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -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<World> worlds;
|
||||||
|
|
||||||
|
public GetStateTask(
|
||||||
|
Provider provider,
|
||||||
|
WorldMap worldMap,
|
||||||
|
List<World> 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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
|
@ -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"));
|
||||||
|
}
|
||||||
|
}
|
|
@ -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<String> 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<World>());
|
||||||
|
|
||||||
|
getStateTask.runTaskTimerAsynchronously(plugin, 0, 1200);
|
||||||
|
}
|
||||||
|
}
|
|
@ -1,4 +1,4 @@
|
||||||
package pl.minecon724.realweather;
|
package pl.minecon724.realweather.weather;
|
||||||
|
|
||||||
public class WeatherState {
|
public class WeatherState {
|
||||||
|
|
||||||
|
@ -14,9 +14,9 @@ public class WeatherState {
|
||||||
|
|
||||||
// Variables
|
// Variables
|
||||||
|
|
||||||
Condition condition;
|
private Condition condition;
|
||||||
ConditionLevel level;
|
private ConditionLevel level;
|
||||||
ConditionSimple simple;
|
private ConditionSimple simple;
|
||||||
|
|
||||||
// Constructor
|
// Constructor
|
||||||
|
|
||||||
|
@ -47,5 +47,17 @@ public class WeatherState {
|
||||||
this.simple = ConditionSimple.CLEAR;
|
this.simple = ConditionSimple.CLEAR;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public Condition getCondition() {
|
||||||
|
return condition;
|
||||||
|
}
|
||||||
|
|
||||||
|
public ConditionLevel getLevel() {
|
||||||
|
return level;
|
||||||
|
}
|
||||||
|
|
||||||
|
public ConditionSimple getSimple() {
|
||||||
|
return simple;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
|
@ -0,0 +1,5 @@
|
||||||
|
package pl.minecon724.realweather.weather.exceptions;
|
||||||
|
|
||||||
|
public class DisabledException extends Exception {
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,5 @@
|
||||||
|
package pl.minecon724.realweather.weather.exceptions;
|
||||||
|
|
||||||
|
public class ProviderException extends Exception {
|
||||||
|
|
||||||
|
}
|
|
@ -1,4 +1,4 @@
|
||||||
package pl.minecon724.realweather.provider;
|
package pl.minecon724.realweather.weather.provider;
|
||||||
|
|
||||||
import java.io.BufferedReader;
|
import java.io.BufferedReader;
|
||||||
import java.io.InputStream;
|
import java.io.InputStream;
|
||||||
|
@ -9,8 +9,7 @@ import java.nio.charset.Charset;
|
||||||
|
|
||||||
import org.json.JSONObject;
|
import org.json.JSONObject;
|
||||||
|
|
||||||
import pl.minecon724.realweather.Provider;
|
import pl.minecon724.realweather.weather.WeatherState.*;
|
||||||
import pl.minecon724.realweather.WeatherState.*;
|
|
||||||
|
|
||||||
public class OpenWeatherMapProvider implements Provider {
|
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();
|
JSONObject json = new JSONObject();
|
||||||
|
|
||||||
try {
|
try {
|
||||||
URL url = new URL(
|
URL url = new URL(
|
||||||
endpoint + String.format("/data/2.5/weather?lat=%s&lon=%s&appid=%s",
|
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();
|
InputStream is = url.openStream();
|
||||||
|
@ -153,4 +152,9 @@ public class OpenWeatherMapProvider implements Provider {
|
||||||
State state = new State(condition, level);
|
State state = new State(condition, level);
|
||||||
return state;
|
return state;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String getName() {
|
||||||
|
return "OpenWeatherMap";
|
||||||
|
}
|
||||||
}
|
}
|
|
@ -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();
|
||||||
|
}
|
|
@ -1,35 +1,12 @@
|
||||||
weather:
|
weather:
|
||||||
|
enabled: true
|
||||||
|
|
||||||
worlds:
|
worlds:
|
||||||
- world
|
- world
|
||||||
- second_world
|
- second_world
|
||||||
- third_world
|
- third_world
|
||||||
# "point" - static location
|
|
||||||
# "player" - player's IP location (fake weather)
|
|
||||||
# "map" - world resembles a real-world globe
|
|
||||||
source: 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:
|
|
||||||
# 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 = <scale> degrees
|
|
||||||
scale_lat: 0.009
|
|
||||||
# Longitude scale, 1 block = <scale> 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
|
|
||||||
|
|
||||||
provider:
|
provider:
|
||||||
# Weather provider
|
# Weather provider
|
||||||
choice: openweathermap
|
choice: openweathermap
|
||||||
# Configure it here
|
# Configure it here
|
||||||
|
@ -37,35 +14,60 @@ provider:
|
||||||
apiKey: 'd3d37fd3511ef1d4b44c7d574e9b56b8' # PLEASE get your own @ https://home.openweathermap.org/users/sign_up
|
apiKey: 'd3d37fd3511ef1d4b44c7d574e9b56b8' # PLEASE get your own @ https://home.openweathermap.org/users/sign_up
|
||||||
# More providers soon!
|
# More providers soon!
|
||||||
|
|
||||||
|
map:
|
||||||
|
# "point" - static location
|
||||||
|
# "player" - player's IP location (fake weather)
|
||||||
|
# "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_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
|
||||||
|
# 1 block = <scale> degrees
|
||||||
|
scale_latitude: 0.009
|
||||||
|
scale_longitude: 0.009
|
||||||
|
|
||||||
|
# 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:
|
realtime:
|
||||||
# warning: this removes sleep
|
# warning: this removes sleep
|
||||||
enabled: false
|
enabled: false
|
||||||
|
|
||||||
worlds:
|
worlds:
|
||||||
- world
|
- world
|
||||||
|
|
||||||
# "auto" to use server's timezone
|
# "auto" to use server's timezone
|
||||||
# Alternatively choose one of these: https://en.wikipedia.org/wiki/List_of_tz_database_time_zones#List
|
# 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'
|
timezone: 'auto'
|
||||||
|
|
||||||
# x day cycles / 24 hrs
|
# x day cycles / 24 hrs
|
||||||
timeScale: 1.0
|
timeScale: 1.0
|
||||||
|
|
||||||
# How often should we recalculate the time (in ticks)
|
# How often should we recalculate the time (in ticks)
|
||||||
# Very minimal impact on performance
|
# Very minimal impact on performance
|
||||||
interval: 1
|
interval: 1
|
||||||
|
|
||||||
settings:
|
# makes time visible to players not in sync with server
|
||||||
# Delay between rechecking weather
|
virtual: false
|
||||||
# in ticks, 20 is one second
|
|
||||||
# Shouldn't affect performance
|
|
||||||
timeBetweenRecheck: 600
|
|
||||||
# Whether to display an actionbar containing info
|
|
||||||
actionbar: true
|
|
||||||
|
|
||||||
# Advanced options
|
# if above true, locks the server's time (in ticks)
|
||||||
timeBeforeInitialRun: 0
|
# -1 to disable
|
||||||
debug: false
|
lock: 0
|
||||||
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%"
|
|
||||||
|
|
|
@ -4,9 +4,5 @@ api-version: 1.16
|
||||||
author: Minecon724
|
author: Minecon724
|
||||||
main: pl.minecon724.realweather.RW
|
main: pl.minecon724.realweather.RW
|
||||||
libraries:
|
libraries:
|
||||||
- org.json:json:20220320
|
- org.json:json:20231013
|
||||||
- com.maxmind.geoip2:geoip2:4.1.0
|
- com.maxmind.geoip2:geoip2:4.2.0
|
||||||
commands:
|
|
||||||
realweather:
|
|
||||||
alias: rw
|
|
||||||
description: RealWeather main command
|
|
Loading…
Reference in a new issue