17 Commits
v1.3.0 ... v1

Author SHA1 Message Date
Jack
9b34da0fdf change version to 1.4.1 2024-08-06 21:28:00 -04:00
Jack
51664841a6 forgot to update line 164... (my bad) 2024-08-06 21:25:30 -04:00
Jack
ae32363e0f Port fix in #12 to legacy 2024-08-06 21:12:54 -04:00
Jack
b1cc12ba85 Merge pull request #9 from Jack1424/main
Add v1.4.0 changes to legacy
2024-07-23 18:10:08 -04:00
Jack
d51c5f531f version set to 1.4.0 2024-07-23 17:54:46 -04:00
Jack
dfbd81146f moved some debug statements around 2024-07-23 17:53:43 -04:00
Jack
e3e09f24ac renamed RealTimeWeather.getConfigurator to getConfigManager 2024-07-23 17:53:22 -04:00
Jack
1ffa9d81bb added support for enabling/disabling time and weather sync in specific worlds (closes #7) 2024-07-23 17:52:43 -04:00
Jack
549541c74a moved updateCheckInterval and Debug to top of config.yml part 3 2024-07-23 17:51:23 -04:00
Jack
27dc240597 moved updateCheckInterval and Debug to top of config.yml 2024-07-23 17:50:34 -04:00
Jack
334471b37b moved updateCheckInterval and Debug to top of config.yml 2024-07-23 17:49:46 -04:00
Jack
796097f3e2 shortened task scheduling line for update checks 2024-07-23 02:30:39 -04:00
Jack
97bd8df2de removed unnecessary if statements from WeatherRequestObject 2024-07-23 02:28:28 -04:00
Jack
6db07a376b cleaned up some code 2024-07-23 02:27:39 -04:00
Jack
20bf2d74fc add update checks 2024-07-23 02:26:56 -04:00
Jack
36ddb10fe2 add RequestFunctions class 2024-07-23 02:25:45 -04:00
Jack
5a48428057 update README.md with legacy information 2024-06-28 18:07:47 -04:00
9 changed files with 260 additions and 109 deletions

View File

@@ -2,6 +2,11 @@
[![Build Status](https://app.travis-ci.com/Jack1424/RealTimeWeather.svg?branch=master)](https://app.travis-ci.com/Jack1424/RealTimeWeather) [![Build Status](https://app.travis-ci.com/Jack1424/RealTimeWeather.svg?branch=master)](https://app.travis-ci.com/Jack1424/RealTimeWeather)
### A lightweight Minecraft server plugin that allows you to sync your server's time and weather with the real world ### A lightweight Minecraft server plugin that allows you to sync your server's time and weather with the real world
## ⚠️ This is the legacy branch of RealTimeWeather ⚠️
**Only use legacy versions of RealTimeWeather (v1.x.x) if you NEED support for older versions of Minecraft.**
**If you don't need support for versions older than the most recent versions of Minecraft, don't use the legacy versions of this plugin.**
Legacy versions of RealTimeWeather will not receive as many (if any) updates.
___ ___
**Current Features:** **Current Features:**
- Lightweight - Lightweight
@@ -12,15 +17,13 @@ ___
**Upcoming Features:** **Upcoming Features:**
- [ ] Commands - [ ] Commands
- [ ] Multi-world support
- [ ] Folia support
## Installation ## Installation
Just download the [latest version](https://github.com/Jack1424/RealTimeWeather/releases/latest) of RTW and put it in your `plugins` directory. Just download the [latest version](https://github.com/Jack1424/RealTimeWeather/releases/) of **a legacy version** of RTW **(legacy versions are any version that starts with v1)** and put it in your `plugins` directory.
You'll need to run your server at least once to generate the configuration file. You'll need to run your server at least once to generate the configuration file.
After running (and then stopping) your server, simply change the values in the configuration file to what you'd like, and you're good to go. After running (and then stopping) your server, simply change the values in the configuration file to what you'd like, and you're good to go.
## Contributions/Support ## Contributions/Support
I'm open to any help/ideas that you have. Just open an issue or a pull request, and I'll be sure to look at it as soon as I can. Builds with `gradlew shadowJar`. **Legacy versions won't receive as many (if any) updates**, but I'm open to any help/ideas that you have. Just open an issue or a pull request, and I'll be sure to look at it as soon as I can. Builds with `gradlew shadowJar`.
License: GPL-3.0 License: GPL-3.0

View File

@@ -4,7 +4,7 @@ plugins {
} }
group = 'io.github.Jack1424' group = 'io.github.Jack1424'
version = '1.3.0' version = '1.4.1'
repositories { repositories {
mavenCentral() mavenCentral()

View File

@@ -1,6 +1,7 @@
package io.github.jack1424.realtimeweather; package io.github.jack1424.realtimeweather;
import io.github.jack1424.realtimeweather.requests.WeatherRequestObject; import io.github.jack1424.realtimeweather.requests.WeatherRequestObject;
import org.bukkit.World;
import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.FileConfiguration;
import org.json.simple.parser.ParseException; import org.json.simple.parser.ParseException;
@@ -11,6 +12,7 @@ import java.time.ZoneId;
import java.time.format.DateTimeFormatter; import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException; import java.time.format.DateTimeParseException;
import java.time.zone.ZoneRulesException; import java.time.zone.ZoneRulesException;
import java.util.HashSet;
import java.util.Objects; import java.util.Objects;
import java.util.TimeZone; import java.util.TimeZone;
@@ -18,9 +20,10 @@ public class ConfigManager {
private final RealTimeWeather rtw; private final RealTimeWeather rtw;
private final FileConfiguration configFile; private final FileConfiguration configFile;
private TimeZone timeZone; private TimeZone timeZone;
private boolean debug, timeEnabled, weatherEnabled, blockTimeSetCommand, blockWeatherCommand, disableBedsAtNight, disableBedsDuringThunder; private boolean debug, timeEnabled, weatherEnabled, timeSyncAllWorlds, weatherSyncAllWorlds, blockTimeSetCommand, blockWeatherCommand, disableBedsAtNight, disableBedsDuringThunder;
private long timeSyncInterval, weatherSyncInterval; private long updateCheckInterval, timeSyncInterval, weatherSyncInterval;
private String sunriseSunset, sunriseSunsetLatitude, sunriseSunsetLongitude, apiKey, weatherLatitude, weatherLongitude, disableBedsAtNightMessage, disableBedsDuringThunderMessage, sunriseCustomTime, sunsetCustomTime; private String sunriseSunset, sunriseSunsetLatitude, sunriseSunsetLongitude, apiKey, weatherLatitude, weatherLongitude, disableBedsAtNightMessage, disableBedsDuringThunderMessage, sunriseCustomTime, sunsetCustomTime;
private HashSet<World> timeSyncWorlds, weatherSyncWorlds;
public ConfigManager(RealTimeWeather rtw) { public ConfigManager(RealTimeWeather rtw) {
this.rtw = rtw; this.rtw = rtw;
@@ -33,6 +36,16 @@ public class ConfigManager {
setTimeEnabled(configFile.getBoolean("SyncTime")); setTimeEnabled(configFile.getBoolean("SyncTime"));
if (isTimeEnabled()) if (isTimeEnabled())
try { try {
timeSyncWorlds = new HashSet<>();
setTimeSyncAllWorlds(configFile.getBoolean("TimeSyncAllWorlds"));
if (getTimeSyncAllWorlds()) {
for (World world : rtw.getServer().getWorlds())
if (world.getEnvironment() == World.Environment.NORMAL)
addTimeSyncWorld(world.getName());
} else {
for (String worldName : configFile.getStringList("TimeSyncWorlds"))
addTimeSyncWorld(worldName);
}
setBlockTimeSetCommand(configFile.getBoolean("BlockTimeSetCommand")); setBlockTimeSetCommand(configFile.getBoolean("BlockTimeSetCommand"));
setDisableBedsAtNight(configFile.getBoolean("DisableBedsAtNight")); setDisableBedsAtNight(configFile.getBoolean("DisableBedsAtNight"));
setDisableBedsAtNightMessage(configFile.getString("DisableBedsAtNightMessage")); setDisableBedsAtNightMessage(configFile.getString("DisableBedsAtNightMessage"));
@@ -57,6 +70,16 @@ public class ConfigManager {
setWeatherEnabled(configFile.getBoolean("SyncWeather")); setWeatherEnabled(configFile.getBoolean("SyncWeather"));
if (isWeatherEnabled()) if (isWeatherEnabled())
try { try {
weatherSyncWorlds = new HashSet<>();
setWeatherSyncAllWorlds(configFile.getBoolean("WeatherSyncAllWorlds"));
if (getWeatherSyncAllWorlds()) {
for (World world : rtw.getServer().getWorlds())
if (world.getEnvironment() == World.Environment.NORMAL)
addWeatherSyncWorld(world.getName());
} else {
for (String worldName : configFile.getStringList("WeatherSyncWorlds"))
addWeatherSyncWorld(worldName);
}
setBlockWeatherCommand(configFile.getBoolean("BlockWeatherCommand")); setBlockWeatherCommand(configFile.getBoolean("BlockWeatherCommand"));
setDisableBedsDuringThunder(configFile.getBoolean("DisableBedsDuringThunder")); setDisableBedsDuringThunder(configFile.getBoolean("DisableBedsDuringThunder"));
setDisableBedsDuringThunderMessage(configFile.getString("DisableBedsDuringThunderMessage")); setDisableBedsDuringThunderMessage(configFile.getString("DisableBedsDuringThunderMessage"));
@@ -71,6 +94,17 @@ public class ConfigManager {
setWeatherEnabled(false); setWeatherEnabled(false);
} }
setUpdateCheckInterval(configFile.getLong("UpdateCheckInterval"));
}
public long getUpdateCheckInterval() {
return updateCheckInterval;
}
public void setUpdateCheckInterval(long value) {
updateCheckInterval = value;
rtw.debug("updateCheckInterval set to " + value);
} }
public boolean debugEnabled() { public boolean debugEnabled() {
@@ -91,6 +125,29 @@ public class ConfigManager {
rtw.debug("SyncTime set to " + value); rtw.debug("SyncTime set to " + value);
} }
public boolean getTimeSyncAllWorlds() {
return timeSyncAllWorlds;
}
public void setTimeSyncAllWorlds(boolean value) {
timeSyncAllWorlds = value;
rtw.debug("TimeSyncAllWorlds set to " + value);
}
public HashSet<World> getTimeSyncWorlds() {
return timeSyncWorlds;
}
public void addTimeSyncWorld(String worldName) throws ConfigurationException {
World world = rtw.getServer().getWorld(worldName);
if (world == null)
throw new ConfigurationException("World \"" + worldName + "\" cannot be found");
timeSyncWorlds.add(world);
rtw.debug("World \"" + worldName + "\" added to TimeSyncWorlds");
}
public boolean getBlockTimeSetCommand() { public boolean getBlockTimeSetCommand() {
return blockTimeSetCommand; return blockTimeSetCommand;
} }
@@ -213,6 +270,29 @@ public class ConfigManager {
rtw.debug("SyncWeather set to " + value); rtw.debug("SyncWeather set to " + value);
} }
public boolean getWeatherSyncAllWorlds() {
return weatherSyncAllWorlds;
}
public void setWeatherSyncAllWorlds(boolean value) {
weatherSyncAllWorlds = value;
rtw.debug("WeatherSyncAllWorlds set to " + value);
}
public HashSet<World> getWeatherSyncWorlds() {
return weatherSyncWorlds;
}
public void addWeatherSyncWorld(String worldName) throws ConfigurationException {
World world = rtw.getServer().getWorld(worldName);
if (world == null)
throw new ConfigurationException("World \"" + worldName + "\" cannot be found");
weatherSyncWorlds.add(world);
rtw.debug("World \"" + worldName + "\" added to WeatherSyncWorlds");
}
public boolean getBlockWeatherCommand() { public boolean getBlockWeatherCommand() {
return blockWeatherCommand; return blockWeatherCommand;
} }

View File

@@ -13,7 +13,7 @@ public class EventHandlers implements Listener {
private final ConfigManager config; private final ConfigManager config;
public EventHandlers(RealTimeWeather rtw) { public EventHandlers(RealTimeWeather rtw) {
config = rtw.getConfigurator(); config = rtw.getConfigManager();
} }
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)

View File

@@ -43,6 +43,13 @@ public final class RealTimeWeather extends JavaPlugin {
metrics.addCustomChart(new SimplePie("time_sync_enabled", () -> String.valueOf(config.isTimeEnabled()))); metrics.addCustomChart(new SimplePie("time_sync_enabled", () -> String.valueOf(config.isTimeEnabled())));
logger.info("Started!"); logger.info("Started!");
logger.info("Checking for updates...");
logger.info(getUpdateCheck());
long updateCheckInterval = config.getUpdateCheckInterval();
if (config.getUpdateCheckInterval() > 0)
getServer().getScheduler().scheduleSyncRepeatingTask(this, () -> logger.info(getUpdateCheck()), updateCheckInterval, updateCheckInterval);
} }
@Override @Override
@@ -70,42 +77,44 @@ public final class RealTimeWeather extends JavaPlugin {
if (config.getSunriseSunset().equals("custom")) if (config.getSunriseSunset().equals("custom"))
debug("Using custom sunrise/sunset times. Sunrise: " + config.getSunriseCustomTime() + ", Sunset: " + config.getSunsetCustomTime()); debug("Using custom sunrise/sunset times. Sunrise: " + config.getSunriseCustomTime() + ", Sunset: " + config.getSunsetCustomTime());
for (World world : getServer().getWorlds()) for (World world : config.getTimeSyncWorlds())
if (world.getEnvironment().equals(World.Environment.NORMAL)) world.setGameRuleValue("doDaylightCycle", "false");
world.setGameRuleValue("doDaylightCycle", "false");
getServer().getScheduler().scheduleSyncRepeatingTask(this, () -> { getServer().getScheduler().scheduleSyncRepeatingTask(this, () -> {
if (config.isTimeEnabled()) { if (config.isTimeEnabled()) {
Calendar cal = Calendar.getInstance(config.getTimeZone()); Calendar cal = Calendar.getInstance(config.getTimeZone());
for (World world : getServer().getWorlds()) for (World world : config.getTimeSyncWorlds())
if (world.getEnvironment().equals(World.Environment.NORMAL)) if (config.getSunriseSunset().equals("real")) {
if (config.getSunriseSunset().equals("real")) { SunriseSunsetRequestObject sunriseSunset;
SunriseSunsetRequestObject sunriseSunset; try {
sunriseSunset = new SunriseSunsetRequestObject(config.getTimeZone(), config.getWeatherLatitude(), config.getWeatherLongitude());
world.setTime(calculateWorldTime(cal, sunriseSunset.getSunriseTime(), sunriseSunset.getSunsetTime()));
} catch (Exception e) {
logger.severe(e.getMessage());
logger.severe("Error getting sunrise/sunset times, using default sunrise/sunset times");
try { try {
sunriseSunset = new SunriseSunsetRequestObject(config.getTimeZone(), config.getWeatherLatitude(), config.getWeatherLongitude()); config.setSunriseSunset("default");
world.setTime(calculateWorldTime(cal, sunriseSunset.getSunriseTime(), sunriseSunset.getSunsetTime())); } catch (ConfigurationException ex) {
} catch (Exception e) { throw new RuntimeException(ex);
logger.severe(e.getMessage());
logger.severe("Error getting sunrise/sunset times, using default sunrise/sunset times");
try {
config.setSunriseSunset("default");
} catch (ConfigurationException ex) {
throw new RuntimeException(ex);
}
world.setTime(calculateWorldTime(cal, "5:02:27 AM", "6:36:36 PM"));
return;
} }
} else if (config.getSunriseSunset().equals("custom"))
world.setTime(calculateWorldTime(cal, config.getSunriseCustomTime(), config.getSunsetCustomTime()));
else
world.setTime(calculateWorldTime(cal, "5:02:27 AM", "6:36:36 PM")); world.setTime(calculateWorldTime(cal, "5:02:27 AM", "6:36:36 PM"));
return;
}
} else if (config.getSunriseSunset().equals("custom")) {
world.setTime(calculateWorldTime(cal, config.getSunriseCustomTime(), config.getSunsetCustomTime()));
} else
world.setTime(calculateWorldTime(cal, "5:02:27 AM", "6:36:36 PM"));
} }
}, 0L, config.getTimeSyncInterval()); }, 0L, config.getTimeSyncInterval());
debug("Weather sync enabled");
} }
private void setupWeather() { private void setupWeather() {
debug("Enabling weather sync...");
try { try {
new WeatherRequestObject(config.getAPIKey(), config.getWeatherLatitude(), config.getWeatherLongitude()); new WeatherRequestObject(config.getAPIKey(), config.getWeatherLatitude(), config.getWeatherLongitude());
} catch (Exception e) { } catch (Exception e) {
@@ -116,11 +125,8 @@ public final class RealTimeWeather extends JavaPlugin {
return; return;
} }
for (World world : getServer().getWorlds()) for (World world : config.getWeatherSyncWorlds())
if (world.getEnvironment().equals(World.Environment.NORMAL)) world.setGameRuleValue("doWeatherCycle", "false");
world.setGameRuleValue("doWeatherCycle", "false");
debug("Enabling weather sync...");
getServer().getScheduler().scheduleSyncRepeatingTask(this, () -> { getServer().getScheduler().scheduleSyncRepeatingTask(this, () -> {
debug("Syncing weather..."); debug("Syncing weather...");
@@ -129,11 +135,10 @@ public final class RealTimeWeather extends JavaPlugin {
WeatherRequestObject request = new WeatherRequestObject(config.getAPIKey(), config.getWeatherLatitude(), config.getWeatherLongitude()); WeatherRequestObject request = new WeatherRequestObject(config.getAPIKey(), config.getWeatherLatitude(), config.getWeatherLongitude());
debug("Setting weather (Rain: " + request.isRaining() + ", Thunder: " + request.isThundering() + ")..."); debug("Setting weather (Rain: " + request.isRaining() + ", Thunder: " + request.isThundering() + ")...");
for (World world : getServer().getWorlds()) for (World world : config.getWeatherSyncWorlds()) {
if (world.getEnvironment().equals(World.Environment.NORMAL)) { world.setStorm(request.isRaining());
world.setStorm(request.isRaining()); world.setThundering(request.isThundering());
world.setThundering(request.isThundering()); }
}
} catch (Exception e) { } catch (Exception e) {
logger.severe("There was an error when attempting to get weather information"); logger.severe("There was an error when attempting to get weather information");
debug(e.getMessage()); debug(e.getMessage());
@@ -156,19 +161,36 @@ public final class RealTimeWeather extends JavaPlugin {
sunsetMinutes += 720; sunsetMinutes += 720;
LocalTime currentTime = LocalTime.of(cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE)); LocalTime currentTime = LocalTime.of(cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE));
int currentMinutes = currentTime.getHour() * 60 + currentTime.getMinute(); double currentMinutes = currentTime.getHour() * 60 + currentTime.getMinute();
if (currentMinutes >= sunriseMinutes && currentMinutes < sunsetMinutes) { if (currentMinutes >= sunriseMinutes && currentMinutes < sunsetMinutes) {
return ((currentMinutes - sunriseMinutes) / (sunsetMinutes - sunriseMinutes) * 13569) + 23041; return (long) (((currentMinutes - sunriseMinutes) / (sunsetMinutes - sunriseMinutes)) * 13569) + 23041;
} else { } else {
if (currentMinutes < sunriseMinutes) { if (currentMinutes < sunriseMinutes)
currentMinutes += 1440; currentMinutes += 1440;
}
return ((currentMinutes - sunsetMinutes) / (1440 - sunsetMinutes + sunriseMinutes) * 13569) + 12610; return (long) (((currentMinutes - sunsetMinutes) / (1440 - sunsetMinutes + sunriseMinutes)) * 13569) + 12610;
} }
} }
public ConfigManager getConfigurator() { public String getUpdateCheck() {
String currentVersion = this.getDescription().getVersion();
String latestVersion;
try {
debug("Getting latest version...");
latestVersion = RequestFunctions.getLatestVersion();
} catch (Exception exception) {
debug(exception.getMessage());
return "There was an error getting the latest version";
}
if (currentVersion.equals(latestVersion)) {
return String.format("RealTimeWeather (v%s) is up to date!", currentVersion);
} else
return String.format("RealTimeWeather (v%s) is outdated! v%s is the latest version.", currentVersion, latestVersion);
}
public ConfigManager getConfigManager() {
return config; return config;
} }

View File

@@ -0,0 +1,45 @@
package io.github.jack1424.realtimeweather.requests;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Scanner;
public class RequestFunctions {
public static Object makeRequest(String URLString) throws IOException, HTTPResponseException, ParseException {
int responseCode = getResponseCode(URLString);
if (responseCode > 399)
throw new HTTPResponseException(responseCode);
Scanner scanner = new Scanner(new URL(URLString).openStream());
StringBuilder response = new StringBuilder();
while (scanner.hasNextLine())
response.append(scanner.nextLine());
scanner.close();
return new JSONParser().parse(response.toString());
}
public static int getResponseCode(String URLString) throws IOException {
URL url = new URL(URLString);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
con.connect();
return con.getResponseCode();
}
public static String getLatestVersion() throws Exception {
return ((JSONObject) ((JSONArray) makeRequest("https://api.modrinth.com/v2/project/WRA6ODcm/version")).get(0)).get("version_number").toString();
}
public static class HTTPResponseException extends Exception {
public HTTPResponseException(int responseCode) {
super(String.valueOf(responseCode));
}
}
}

View File

@@ -1,14 +1,10 @@
package io.github.jack1424.realtimeweather.requests; package io.github.jack1424.realtimeweather.requests;
import org.json.simple.JSONObject; import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException; import org.json.simple.parser.ParseException;
import javax.naming.ConfigurationException; import javax.naming.ConfigurationException;
import javax.net.ssl.HttpsURLConnection;
import java.io.IOException; import java.io.IOException;
import java.net.ProtocolException;
import java.net.URL;
import java.time.LocalDate; import java.time.LocalDate;
import java.time.LocalTime; import java.time.LocalTime;
import java.time.ZoneId; import java.time.ZoneId;
@@ -20,23 +16,13 @@ public class SunriseSunsetRequestObject {
private String sunriseTime, sunsetTime; private String sunriseTime, sunsetTime;
public SunriseSunsetRequestObject(TimeZone timeZone, String lat, String lon) throws IOException, ParseException, ConfigurationException { public SunriseSunsetRequestObject(TimeZone timeZone, String lat, String lon) throws IOException, ParseException, ConfigurationException {
URL url = new URL(String.format("https://api.sunrisesunset.io/json?lat=%s&lng=%s&timezone=UTC", lat, lon)); JSONObject response;
try {
HttpsURLConnection con = (HttpsURLConnection) url.openConnection(); response = (JSONObject) ((JSONObject) RequestFunctions.makeRequest(String.format("https://api.sunrisesunset.io/json?lat=%s&lng=%s&timezone=UTC", lat, lon))).get("results");
con.setRequestMethod("GET"); } catch (RequestFunctions.HTTPResponseException e) {
con.connect(); throw new IOException("Server/client error (HTTP error " + e.getMessage() + ")");
int responseCode = con.getResponseCode();
if (responseCode > 399)
throw new ProtocolException("Server/client error (HTTP error " + responseCode + ")");
Scanner scanner = new Scanner(url.openStream());
StringBuilder data = new StringBuilder();
while (scanner.hasNext()) {
data.append(scanner.nextLine());
} }
scanner.close();
JSONObject response = (JSONObject) ((JSONObject) new JSONParser().parse(data.toString())).get("results");
sunriseTime = response.get("sunrise").toString(); sunriseTime = response.get("sunrise").toString();
sunsetTime = response.get("sunset").toString(); sunsetTime = response.get("sunset").toString();

View File

@@ -2,57 +2,42 @@ package io.github.jack1424.realtimeweather.requests;
import org.json.simple.JSONArray; import org.json.simple.JSONArray;
import org.json.simple.JSONObject; import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException; import org.json.simple.parser.ParseException;
import javax.naming.ConfigurationException; import javax.naming.ConfigurationException;
import javax.net.ssl.HttpsURLConnection;
import java.io.IOException; import java.io.IOException;
import java.net.ProtocolException; import java.net.ProtocolException;
import java.net.URL;
import java.util.Scanner;
public class WeatherRequestObject { public class WeatherRequestObject {
private boolean rain = false, thunder = false; private boolean rain = false, thunder = false;
public WeatherRequestObject(String apiKey, String lat, String lon) throws IOException, ParseException, ConfigurationException { public WeatherRequestObject(String apiKey, String lat, String lon) throws IOException, ParseException, ConfigurationException {
URL url = new URL(String.format("https://api.openweathermap.org/data/2.5/weather?lat=%s&lon=%s&appid=%s", lat, lon, apiKey)); JSONArray conditions;
try {
conditions = (JSONArray) ((JSONObject) RequestFunctions.makeRequest(String.format("https://api.openweathermap.org/data/2.5/weather?lat=%s&lon=%s&appid=%s", lat, lon, apiKey))).get("weather");
} catch (RequestFunctions.HTTPResponseException e) {
int responseCode = Integer.parseInt(e.getMessage());
if (responseCode > 499) {
throw new ProtocolException("Server/client error (HTTP error " + responseCode + ")");
} else if (responseCode > 399) {
String message = "Error when getting weather information: ";
HttpsURLConnection con = (HttpsURLConnection) url.openConnection(); if (responseCode == 401)
con.setRequestMethod("GET"); throw new ConfigurationException(message + "API key invalid. Check the Wiki for troubleshooting steps.");
con.connect(); else
int responseCode = con.getResponseCode(); throw new ProtocolException(message + "Unknown error");
if (responseCode > 499) { } else {
throw new ProtocolException("Server/client error (HTTP error " + responseCode + ")"); throw new IOException("Server/client error (HTTP error " + e.getMessage() + ")");
}
} }
else if (responseCode > 399) {
String message = "Error when getting weather information: ";
if (responseCode == 401)
throw new ConfigurationException(message + "API key invalid. Check the Wiki for troubleshooting steps.");
else
throw new ProtocolException(message + "Unknown error");
}
Scanner scanner = new Scanner(url.openStream());
StringBuilder data = new StringBuilder();
while (scanner.hasNext()) {
data.append(scanner.nextLine());
}
scanner.close();
JSONArray conditions = (JSONArray) ((JSONObject) new JSONParser().parse(data.toString())).get("weather");
for (Object rawCondition : conditions) { for (Object rawCondition : conditions) {
int id = Integer.parseInt(String.valueOf(((JSONObject) rawCondition).get("id"))); int id = Integer.parseInt(String.valueOf(((JSONObject) rawCondition).get("id")));
while (id >= 10) while (id >= 10)
id /= 10; id /= 10;
if (!rain) rain = id == 2 || id == 3 || id == 5 || id == 6;
rain = id == 2 || id == 3 || id == 5 || id == 6; thunder = id == 2;
if (!thunder)
thunder = id == 2;
} }
} }

View File

@@ -1,11 +1,37 @@
# RealTimeWeather Configuration File (v1.3.0) # RealTimeWeather Configuration File (v1.4.0)
# You can find detailed instructions at: https://github.com/Jack1424/RealTimeWeather/wiki#editing-the-configuration-file # You can find detailed instructions at: https://github.com/Jack1424/RealTimeWeather/wiki#editing-the-configuration-file
######################################## Real Time Weather Settings ##################################################
# By default, RealTimeWeather will check if an update is available every 24 hours (1734000 ticks) #
# You can change the interval here (or set to 0 to disable update checks) #
# If this is disabled, RealTimeWeather will still check for updates on startup #
# You can find a handy tick calculator here: https://mapmaking.fr/tick/ #
UpdateCheckInterval: 1734000
#
# Set to true for various console messages when time and weather sync are executed #
# This is useful if the plugin is not working, and you want to find out what's wrong #
# This will also provide error messages even when an error is caught and managed by RTM #
# Note: There will be no messages during a time sync because they happen very frequently #
# Note: Unhandled plugin errors will still be logged regardless of the debug value #
Debug: false
######################################################################################################################
################################# TIME SYNC SETTINGS ################################################################# ################################# TIME SYNC SETTINGS #################################################################
# Set to true to enable time syncing, or false to disable # # Set to true to enable time syncing, or false to disable #
# All time-related settings will be ignored if this is set to false # # All time-related settings will be ignored if this is set to false #
SyncTime: false SyncTime: false
# # # #
# By default, RealTimeWeather will apply the time sync settings below to all worlds #
# End and nether worlds will not be synced #
# If you ony want to enable time syncing in some worlds on your server, set this to false #
TimeSyncAllWorlds: true
# #
# List the worlds that you want RealTimeWeather to sync the time in #
# End and nether worlds will not be synced #
# This only works if TimeSyncAllWorlds is set to false #
TimeSyncWorlds:
- world
# #
# Set to false to enable the /time set command (not recommended) # # Set to false to enable the /time set command (not recommended) #
BlockTimeSetCommand: true BlockTimeSetCommand: true
# # # #
@@ -45,6 +71,17 @@ SunsetCustomTime: '6:36:36 PM'
# All weather-related settings will be ignored if this is set to false # # All weather-related settings will be ignored if this is set to false #
SyncWeather: false SyncWeather: false
# # # #
# By default, RealTimeWeather will apply the weather sync settings below to all worlds #
# End and nether worlds will not be synced #
# If you ony want to enable weather syncing in some worlds on your server, set this to false #
WeatherSyncAllWorlds: true
# #
# List the worlds that you want RealTimeWeather to sync the weather in #
# End and nether worlds will not be synced #
# This only works if WeatherSyncAllWorlds is set to false #
WeatherSyncWorlds:
- world
# #
# Set to false to enable the /weather command (not recommended) # # Set to false to enable the /weather command (not recommended) #
BlockWeatherCommand: true BlockWeatherCommand: true
# # # #
@@ -70,11 +107,4 @@ APIKey: 'API_KEY'
WeatherLatitude: '0' WeatherLatitude: '0'
WeatherLongitude: '0' WeatherLongitude: '0'
# # # #
###################################################################################################################### ######################################################################################################################
# Set to true for various console messages when time and weather sync are executed
# This is useful if the plugin is not working, and you want to find out what's wrong
# This will also provide error messages even when an error is caught and managed by RTM
# Note: There will be no messages during a time sync because they happen very frequently
# Note: Unhandled plugin errors will still be logged regardless of the debug value
Debug: false