26 Commits
v1.3.0 ... main

Author SHA1 Message Date
Jack
f99eceb46f make time/weather command checks more strict (closes #19) 2025-06-22 23:30:50 -04:00
Jack
df9b8f1fcd Merge pull request #18 from Karotte128/main
fix SunriseSunsetRequest to use right config values
2025-05-29 00:51:17 -04:00
Karotte128
6f5f69ee9e fix SunriseSunsetRequest to use right config variables 2025-02-22 22:09:51 +01:00
Jack
333325c4e0 Clean up fixed calculateWorldTime method 2024-08-06 21:10:22 -04:00
Jack
c83fe91f4e Merge pull request #12 from hunter232/main
Closes #11
2024-08-06 21:03:21 -04:00
Hunter Richardson
6fb3745d64 fixted bug where time was only ever set to sunrise or sunset [result of integer(long) division was either 0 or 1] 2024-08-02 11:55:20 -04:00
Jack
23b64653a8 add ANOTHER missing URISyntaxException catch (they're hiding from me ig) 2024-07-23 23:38:53 -04:00
Jack
5ef5db1cd5 change line endings 2024-07-23 23:37:07 -04:00
Jack
bb14509fbd change line endings 2024-07-23 23:35:23 -04:00
Jack
92b92b5969 use new PluginMeta instead of getDescription 2024-07-23 23:26:43 -04:00
Jack
8280d9b78c use setGameRule instead of setGameRuleValue 2024-07-23 23:26:25 -04:00
Jack
cca328c5ee remove deprecated code and use modern methods/classes/code where applicable 2024-07-23 23:23:11 -04:00
Jack
d2796f7992 move project to Java 21 and the 1.21 Paper API 2024-07-23 23:04:32 -04:00
Jack
c4c5ca7558 updated current features in README 2024-07-23 18:23:00 -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
16 changed files with 342 additions and 170 deletions

View File

@@ -1,6 +1,6 @@
name: Bug report name: Bug report
description: Report problems/issues here description: Report problems/issues here
labels: bug labels: [bug]
body: body:
- type: checkboxes - type: checkboxes
attributes: attributes:

View File

@@ -1,6 +1,6 @@
name: Feature request name: Feature request
description: Use this to request new features and/or changes description: Use this to request new features and/or changes
labels: enhancement labels: [enhancement]
body: body:
- type: checkboxes - type: checkboxes
attributes: attributes:

View File

@@ -1 +1,3 @@
#file: noinspection YAMLSchemaValidation
#IntelliJ IDEA interprets this as another issue template so the above line is required
blank_issues_enabled: false blank_issues_enabled: false

View File

@@ -1,2 +1,2 @@
language: java language: java
jdk: openjdk17 jdk: openjdk21

View File

@@ -9,6 +9,7 @@ ___
- Supports all Minecraft versions from 1.7+ - Supports all Minecraft versions from 1.7+
- Constant time syncing (including custom or real-world sunrise/sunset times) - Constant time syncing (including custom or real-world sunrise/sunset times)
- Weather syncing (rain/snow and thunder) - Weather syncing (rain/snow and thunder)
- Enable/disable specific worlds
**Upcoming Features:** **Upcoming Features:**
- [ ] Commands - [ ] Commands

View File

@@ -1,33 +1,45 @@
plugins { plugins {
id 'java' id 'java'
id 'com.github.johnrengelman.shadow' version '8.1.1' id 'io.github.goooler.shadow' version '8.1.8' // TODO: Temporarily using fork
} }
group = 'io.github.Jack1424' group = 'io.github.jack1424'
version = '1.3.0' version = '2.0.0-DEV'
repositories { repositories {
mavenCentral() mavenCentral()
maven { maven {
name = 'papermc-repo' name = "papermc-repo"
url = 'https://repo.papermc.io/repository/maven-public/' url = "https://repo.papermc.io/repository/maven-public/"
} }
maven { maven {
name = 'sonatype' name = "sonatype"
url = 'https://oss.sonatype.org/content/groups/public/' url = "https://oss.sonatype.org/content/groups/public/"
} }
} }
dependencies { dependencies {
compileOnly("io.papermc.paper:paper-api:1.21-R0.1-SNAPSHOT")
implementation("org.bstats:bstats-bukkit:3.0.2") implementation("org.bstats:bstats-bukkit:3.0.2")
implementation("org.bukkit:bukkit:1.13-R0.1-SNAPSHOT")
} }
shadowJar { shadowJar {
relocate('org.bstats', 'io.github.jack1424.realtimeweather') relocate('org.bstats', 'io.github.jack1424.realTimeWeather')
} }
def targetJavaVersion = 11 tasks.jar {
manifest {
attributes["paperweight-mappings-namespace"] = "mojang"
}
}
tasks.shadowJar {
manifest {
attributes["paperweight-mappings-namespace"] = "mojang"
}
}
def targetJavaVersion = 21
java { java {
def javaVersion = JavaVersion.toVersion(targetJavaVersion) def javaVersion = JavaVersion.toVersion(targetJavaVersion)
sourceCompatibility = javaVersion sourceCompatibility = javaVersion
@@ -38,8 +50,10 @@ java {
} }
tasks.withType(JavaCompile).configureEach { tasks.withType(JavaCompile).configureEach {
options.encoding = 'UTF-8'
if (targetJavaVersion >= 10 || JavaVersion.current().isJava10Compatible()) { if (targetJavaVersion >= 10 || JavaVersion.current().isJava10Compatible()) {
options.release = targetJavaVersion options.release.set(targetJavaVersion)
} }
} }

0
gradlew vendored Executable file → Normal file
View File

View File

@@ -1,16 +1,19 @@
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;
import javax.naming.ConfigurationException; import javax.naming.ConfigurationException;
import java.io.IOException; import java.io.IOException;
import java.net.URISyntaxException;
import java.time.LocalTime; import java.time.LocalTime;
import java.time.ZoneId; 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 +21,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 +37,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 +71,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 +95,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 +126,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 +271,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;
} }
@@ -262,7 +343,7 @@ public class ConfigManager {
} catch (NullPointerException e) { } catch (NullPointerException e) {
throw new ConfigurationException("The APIKey cannot be blank"); throw new ConfigurationException("The APIKey cannot be blank");
} }
catch (IOException | ParseException e) { catch (IOException | ParseException | URISyntaxException e) {
rtw.getLogger().severe(e.getMessage()); rtw.getLogger().severe(e.getMessage());
throw new ConfigurationException("There was an error when validating this APIKey (this does not mean that the API key is invalid)"); throw new ConfigurationException("There was an error when validating this APIKey (this does not mean that the API key is invalid)");
} }

View File

@@ -1,4 +1,4 @@
package io.github.jack1424.realtimeweather; package io.github.jack1424.realTimeWeather;
import org.bukkit.World; import org.bukkit.World;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
@@ -13,13 +13,13 @@ 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)
public void onCommandPreprocess(PlayerCommandPreprocessEvent event) { public void onCommandPreprocess(PlayerCommandPreprocessEvent event) {
if ((config.getBlockTimeSetCommand() && config.isTimeEnabled() && event.getMessage().contains("time set")) if ((config.getBlockTimeSetCommand() && config.isTimeEnabled() && event.getMessage().toLowerCase().contains("time set "))
|| (config.getBlockWeatherCommand() && config.isWeatherEnabled() && event.getMessage().contains("weather"))) { || (config.getBlockWeatherCommand() && config.isWeatherEnabled() && event.getMessage().toLowerCase().contains("weather "))) {
event.setCancelled(true); event.setCancelled(true);
event.getPlayer().sendMessage("Command disabled by RealTimeWeather"); event.getPlayer().sendMessage("Command disabled by RealTimeWeather");
} }
@@ -27,8 +27,8 @@ public class EventHandlers implements Listener {
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void onConsoleCommand(ServerCommandEvent event) { public void onConsoleCommand(ServerCommandEvent event) {
if ((config.getBlockTimeSetCommand() && config.isTimeEnabled() && event.getCommand().contains("time set")) if ((config.getBlockTimeSetCommand() && config.isTimeEnabled() && event.getCommand().toLowerCase().contains("time set "))
|| (config.getBlockWeatherCommand() && config.isWeatherEnabled() && event.getCommand().contains("weather"))) { || (config.getBlockWeatherCommand() && config.isWeatherEnabled() && event.getCommand().toLowerCase().contains("weather "))) {
event.setCancelled(true); event.setCancelled(true);
event.getSender().sendMessage("Command disabled by RealTimeWeather"); event.getSender().sendMessage("Command disabled by RealTimeWeather");
} }

View File

@@ -1,8 +1,9 @@
package io.github.jack1424.realtimeweather; package io.github.jack1424.realTimeWeather;
import io.github.jack1424.realtimeweather.requests.*; import io.github.jack1424.realTimeWeather.requests.*;
import org.bstats.bukkit.Metrics; import org.bstats.bukkit.Metrics;
import org.bstats.charts.SimplePie; import org.bstats.charts.SimplePie;
import org.bukkit.GameRule;
import org.bukkit.World; import org.bukkit.World;
import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.plugin.java.JavaPlugin;
@@ -11,7 +12,6 @@ import java.time.LocalTime;
import java.util.Calendar; import java.util.Calendar;
import java.util.logging.Logger; import java.util.logging.Logger;
@SuppressWarnings("deprecation")
public final class RealTimeWeather extends JavaPlugin { public final class RealTimeWeather extends JavaPlugin {
private Logger logger; private Logger logger;
private ConfigManager config; private ConfigManager config;
@@ -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
@@ -52,9 +59,9 @@ public final class RealTimeWeather extends JavaPlugin {
debug("Re-enabling normal daylight and weather cycles..."); debug("Re-enabling normal daylight and weather cycles...");
if (config.isTimeEnabled()) if (config.isTimeEnabled())
world.setGameRuleValue("doDaylightCycle", "true"); world.setGameRule(GameRule.DO_DAYLIGHT_CYCLE, true);
if (config.isWeatherEnabled()) if (config.isWeatherEnabled())
world.setGameRuleValue("doWeatherCycle", "true"); world.setGameRule(GameRule.DO_WEATHER_CYCLE, true);
} }
logger.info("Stopping..."); logger.info("Stopping...");
@@ -70,19 +77,17 @@ 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.setGameRule(GameRule.DO_DAYLIGHT_CYCLE, 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 { try {
sunriseSunset = new SunriseSunsetRequestObject(config.getTimeZone(), config.getWeatherLatitude(), config.getWeatherLongitude()); sunriseSunset = new SunriseSunsetRequestObject(config.getTimeZone(), config.getSunriseSunsetLatitude(), config.getSunriseSunsetLongitude());
world.setTime(calculateWorldTime(cal, sunriseSunset.getSunriseTime(), sunriseSunset.getSunsetTime())); world.setTime(calculateWorldTime(cal, sunriseSunset.getSunriseTime(), sunriseSunset.getSunsetTime()));
} catch (Exception e) { } catch (Exception e) {
logger.severe(e.getMessage()); logger.severe(e.getMessage());
@@ -97,15 +102,19 @@ public final class RealTimeWeather extends JavaPlugin {
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; return;
} }
} else if (config.getSunriseSunset().equals("custom")) } else if (config.getSunriseSunset().equals("custom")) {
world.setTime(calculateWorldTime(cal, config.getSunriseCustomTime(), config.getSunsetCustomTime())); world.setTime(calculateWorldTime(cal, config.getSunriseCustomTime(), config.getSunsetCustomTime()));
else } 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"));
} }
}, 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.setGameRule(GameRule.DO_WEATHER_CYCLE, false);
world.setGameRuleValue("doWeatherCycle", "false");
debug("Enabling weather sync...");
getServer().getScheduler().scheduleSyncRepeatingTask(this, () -> { getServer().getScheduler().scheduleSyncRepeatingTask(this, () -> {
debug("Syncing weather..."); debug("Syncing weather...");
@@ -129,8 +135,7 @@ 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());
} }
@@ -156,19 +161,37 @@ 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() { @SuppressWarnings("UnstableApiUsage")
public String getUpdateCheck() {
String currentVersion = this.getPluginMeta().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,47 @@
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.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Scanner;
public class RequestFunctions {
public static Object makeRequest(String URLString) throws IOException, HTTPResponseException, ParseException, URISyntaxException {
int responseCode = getResponseCode(URLString);
if (responseCode > 399)
throw new HTTPResponseException(responseCode);
Scanner scanner = new Scanner(new URI(URLString).toURL().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, URISyntaxException {
URL url = new URI(URLString).toURL();
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")).getFirst()).get("version_number").toString();
}
public static class HTTPResponseException extends Exception {
public HTTPResponseException(int responseCode) {
super(String.valueOf(responseCode));
}
}
}

View File

@@ -1,14 +1,11 @@
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.URISyntaxException;
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;
@@ -19,24 +16,14 @@ import java.util.*;
public class SunriseSunsetRequestObject { 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, URISyntaxException {
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

@@ -0,0 +1,52 @@
package io.github.jack1424.realTimeWeather.requests;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.ParseException;
import javax.naming.ConfigurationException;
import java.io.IOException;
import java.net.ProtocolException;
import java.net.URISyntaxException;
public class WeatherRequestObject {
private boolean rain = false, thunder = false;
public WeatherRequestObject(String apiKey, String lat, String lon) throws IOException, ParseException, ConfigurationException, URISyntaxException {
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: ";
if (responseCode == 401)
throw new ConfigurationException(message + "API key invalid. Check the Wiki for troubleshooting steps.");
else
throw new ProtocolException(message + "Unknown error");
} else {
throw new IOException("Server/client error (HTTP error " + e.getMessage() + ")");
}
}
for (Object rawCondition : conditions) {
int id = Integer.parseInt(String.valueOf(((JSONObject) rawCondition).get("id")));
while (id >= 10)
id /= 10;
rain = id == 2 || id == 3 || id == 5 || id == 6;
thunder = id == 2;
}
}
public boolean isRaining() {
return rain;
}
public boolean isThundering() {
return thunder;
}
}

View File

@@ -1,66 +0,0 @@
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 javax.naming.ConfigurationException;
import javax.net.ssl.HttpsURLConnection;
import java.io.IOException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.Scanner;
public class WeatherRequestObject {
private boolean rain = false, thunder = false;
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));
HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
con.setRequestMethod("GET");
con.connect();
int responseCode = con.getResponseCode();
if (responseCode > 499) {
throw new ProtocolException("Server/client error (HTTP error " + responseCode + ")");
}
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) {
int id = Integer.parseInt(String.valueOf(((JSONObject) rawCondition).get("id")));
while (id >= 10)
id /= 10;
if (!rain)
rain = id == 2 || id == 3 || id == 5 || id == 6;
if (!thunder)
thunder = id == 2;
}
}
public boolean isRaining() {
return rain;
}
public boolean isThundering() {
return thunder;
}
}

View File

@@ -1,11 +1,37 @@
# RealTimeWeather Configuration File (v1.3.0) # RealTimeWeather Configuration File (v2.0.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
# # # #
@@ -71,10 +108,3 @@ 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

View File

@@ -1,7 +1,8 @@
main: io.github.jack1424.realTimeWeather.RealTimeWeather
name: RealTimeWeather name: RealTimeWeather
version: '${version}' version: '${version}'
description: Sync your server time and weather with the real world description: Sync your Minecraft server's time and weather with the real world
main: io.github.jack1424.realtimeweather.RealTimeWeather api-version: '1.21'
load: POSTWORLD load: POSTWORLD
authors: [Jack1424] author: Jack1424
website: https://github.com/Jack1424/RealTimeWeather website: github.com/Jack1424/RealTimeWeather