diff --git a/.gitignore b/.gitignore index 68b6a914..cfbf48c4 100644 --- a/.gitignore +++ b/.gitignore @@ -118,3 +118,8 @@ run/ !gradle-wrapper.jar /build-output-final/ /target/ + +# Don't include generated test suite files +/test/servers/ +/test/HuskSync +/test/config.yml \ No newline at end of file diff --git a/LICENSE b/LICENSE index 7a4a3ea2..8dc622b9 100644 --- a/LICENSE +++ b/LICENSE @@ -16,7 +16,7 @@ "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the + "control" means (i) the power, direct or indirect, to saveCause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. @@ -95,7 +95,7 @@ (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and - (b) You must cause any modified files to carry prominent notices + (b) You must saveCause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works diff --git a/README.md b/README.md index 34ffb477..4fcad8ca 100644 --- a/README.md +++ b/README.md @@ -26,12 +26,12 @@


-**HuskSync** is a modern, cross-server player data synchronisation system that enables the comprehensive synchronisation of your user's data across multiple proxied servers. It does this by making use of Redis and MySQL to optimally cache data while players change servers. +**HuskSync** is a modern, cross-server player data synchronization system that enables the comprehensive synchronization of your user's data across multiple proxied servers. It does this by making use of Redis and MySQL to optimally cache data while players change servers. ## Features -**⭐ Seamless synchronisation** — Utilises optimised Redis caching when players change server to sync player data super quickly for a seamless experience. +**⭐ Seamless synchronization** — Utilises optimised Redis caching when players change server to sync player data super quickly for a seamless experience. -**⭐ Complete player synchronisation** — Sync inventories, Ender Chests, health, hunger, effects, advancements, statistics, locked maps & [more](https://william278.net/docs/husksync/sync-features)—no data left behind! +**⭐ Complete player synchronization** — Sync inventories, Ender Chests, health, hunger, effects, advancements, statistics, locked maps & [more](https://william278.net/docs/husksync/sync-features)—no data left behind! **⭐ Backup, restore & rotate** — Something gone wrong? Restore players back to a previous data state. Rotate and manage data snapshots in-game! diff --git a/build.gradle b/build.gradle index 66d1c5f8..6a385620 100644 --- a/build.gradle +++ b/build.gradle @@ -19,7 +19,6 @@ ext { set 'mysql_driver_version', mysql_driver_version.toString() set 'mariadb_driver_version', mariadb_driver_version.toString() set 'snappy_version', snappy_version.toString() - set 'commons_text_version', commons_text_version.toString() } import org.apache.tools.ant.filters.ReplaceTokens @@ -39,16 +38,18 @@ allprojects { mavenLocal() mavenCentral() maven { url 'https://hub.spigotmc.org/nexus/content/repositories/snapshots/' } + maven { url 'https://repo.codemc.io/repository/maven-public/' } maven { url 'https://repo.minebench.de/' } maven { url 'https://repo.alessiodp.com/releases/' } - maven { url 'https://repo.mattstudios.me/artifactory/public/' } maven { url 'https://jitpack.io' } + maven { url 'https://mvn-repo.arim.space/lesser-gpl3/' } maven { url 'https://libraries.minecraft.net/' } - maven { url 'https://william278.net/releases/' } + maven { url 'https://repo.william278.net/releases/' } } dependencies { testImplementation 'org.junit.jupiter:junit-jupiter-api:5.10.0' + testImplementation 'org.junit.jupiter:junit-jupiter-params:5.10.0' testImplementation 'org.junit.jupiter:junit-jupiter-engine:5.10.0' } diff --git a/bukkit/build.gradle b/bukkit/build.gradle index 24b5db59..547a61a6 100644 --- a/bukkit/build.gradle +++ b/bukkit/build.gradle @@ -1,23 +1,27 @@ dependencies { implementation project(path: ':common') + implementation 'org.bstats:bstats-bukkit:3.0.2' implementation 'net.william278:mpdbdataconverter:1.0.1' implementation 'net.william278:hsldataconverter:1.0' - implementation 'net.william278:MapDataAPI:1.0.2' - implementation 'net.william278:AndJam:1.0.2' + implementation 'net.william278:mapdataapi:1.0.3' + implementation 'net.william278:andjam:1.0.2' implementation 'me.lucko:commodore:2.2' implementation 'net.kyori:adventure-platform-bukkit:4.3.0' implementation 'dev.triumphteam:triumph-gui:3.1.5' + implementation 'space.arim.morepaperlib:morepaperlib:0.4.3' + implementation 'de.tr7zw:item-nbt-api:2.12.0-RC1' compileOnly 'org.spigotmc:spigot-api:1.16.5-R0.1-SNAPSHOT' compileOnly 'commons-io:commons-io:2.13.0' + compileOnly 'org.json:json:20230618' compileOnly 'de.themoep:minedown-adventure:1.7.2-SNAPSHOT' compileOnly 'dev.dejvokep:boosted-yaml:1.3.1' compileOnly 'com.zaxxer:HikariCP:5.0.1' - compileOnly 'redis.clients:jedis:' + jedis_version compileOnly 'net.william278:DesertWell:2.0.4' - compileOnly 'net.william278:Annotaml:2.0.1' + compileOnly 'net.william278:annotaml:2.0.7' compileOnly 'net.william278:AdvancementAPI:97a9583413' + compileOnly "redis.clients:jedis:$jedis_version" } shadowJar { @@ -26,7 +30,11 @@ shadowJar { } relocate 'org.apache.commons.io', 'net.william278.husksync.libraries.commons.io' + relocate 'org.apache.commons.text', 'net.william278.husksync.libraries.commons.text' + relocate 'org.apache.commons.lang3', 'net.william278.husksync.libraries.commons.lang3' relocate 'com.google.gson', 'net.william278.husksync.libraries.gson' + relocate 'org.json', 'net.william278.husksync.libraries.json' + relocate 'com.fatboyindustrial', 'net.william278.husktowns.libraries' relocate 'de.themoep', 'net.william278.husksync.libraries' relocate 'net.kyori', 'net.william278.husksync.libraries' relocate 'org.jetbrains', 'net.william278.husksync.libraries' @@ -37,7 +45,7 @@ shadowJar { relocate 'net.william278.paginedown', 'net.william278.husksync.libraries.paginedown' relocate 'net.william278.mapdataapi', 'net.william278.husksync.libraries.mapdataapi' relocate 'net.william278.andjam', 'net.william278.husksync.libraries.andjam' - relocate 'net.querz', 'net.william278.husksync.libraries.nbt' + relocate 'net.querz', 'net.william278.husksync.libraries.nbtparser' relocate 'net.roxeez', 'net.william278.husksync.libraries' relocate 'me.lucko.commodore', 'net.william278.husksync.libraries.commodore' @@ -47,4 +55,6 @@ shadowJar { relocate 'net.william278.mpdbconverter', 'net.william278.husksync.libraries.mpdbconverter' relocate 'net.william278.hslmigrator', 'net.william278.husksync.libraries.hslconverter' relocate 'net.william278.annotaml', 'net.william278.husksync.libraries.annotaml' + relocate 'space.arim.morepaperlib', 'net.william278.husksync.libraries.paperlib' + relocate 'de.tr7zw.changeme.nbtapi', 'net.william278.husksync.libraries.nbtapi' } \ No newline at end of file diff --git a/bukkit/src/main/java/net/william278/husksync/BukkitHuskSync.java b/bukkit/src/main/java/net/william278/husksync/BukkitHuskSync.java index e62be5a7..9c9a5a42 100644 --- a/bukkit/src/main/java/net/william278/husksync/BukkitHuskSync.java +++ b/bukkit/src/main/java/net/william278/husksync/BukkitHuskSync.java @@ -19,253 +19,215 @@ package net.william278.husksync; +import com.google.gson.Gson; import net.kyori.adventure.platform.bukkit.BukkitAudiences; -import net.william278.annotaml.Annotaml; import net.william278.desertwell.util.Version; +import net.william278.husksync.adapter.DataAdapter; +import net.william278.husksync.adapter.GsonAdapter; +import net.william278.husksync.adapter.SnappyGsonAdapter; +import net.william278.husksync.api.BukkitHuskSyncAPI; import net.william278.husksync.command.BukkitCommand; -import net.william278.husksync.command.BukkitCommandType; -import net.william278.husksync.command.Permission; import net.william278.husksync.config.Locales; import net.william278.husksync.config.Settings; -import net.william278.husksync.data.CompressedDataAdapter; -import net.william278.husksync.data.DataAdapter; -import net.william278.husksync.data.JsonDataAdapter; +import net.william278.husksync.data.BukkitSerializer; +import net.william278.husksync.data.Data; +import net.william278.husksync.data.Identifier; +import net.william278.husksync.data.Serializer; import net.william278.husksync.database.Database; import net.william278.husksync.database.MySqlDatabase; -import net.william278.husksync.event.BukkitEventCannon; -import net.william278.husksync.event.EventCannon; +import net.william278.husksync.event.BukkitEventDispatcher; import net.william278.husksync.hook.PlanHook; import net.william278.husksync.listener.BukkitEventListener; import net.william278.husksync.listener.EventListener; import net.william278.husksync.migrator.LegacyMigrator; import net.william278.husksync.migrator.Migrator; import net.william278.husksync.migrator.MpdbMigrator; -import net.william278.husksync.player.BukkitPlayer; -import net.william278.husksync.player.OnlineUser; import net.william278.husksync.redis.RedisManager; +import net.william278.husksync.user.BukkitUser; +import net.william278.husksync.user.ConsoleUser; +import net.william278.husksync.user.OnlineUser; +import net.william278.husksync.util.BukkitLegacyConverter; +import net.william278.husksync.util.BukkitMapPersister; +import net.william278.husksync.util.BukkitTask; +import net.william278.husksync.util.LegacyConverter; import org.bstats.bukkit.Metrics; import org.bukkit.Bukkit; -import org.bukkit.command.PluginCommand; import org.bukkit.entity.Player; -import org.bukkit.permissions.PermissionDefault; -import org.bukkit.plugin.Plugin; +import org.bukkit.map.MapView; import org.bukkit.plugin.java.JavaPlugin; import org.jetbrains.annotations.NotNull; +import space.arim.morepaperlib.MorePaperLib; +import space.arim.morepaperlib.commands.CommandRegistration; +import space.arim.morepaperlib.scheduling.AsynchronousScheduler; +import space.arim.morepaperlib.scheduling.GracefulScheduling; +import space.arim.morepaperlib.scheduling.RegionalScheduler; -import java.io.File; -import java.io.IOException; -import java.lang.reflect.InvocationTargetException; import java.util.*; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.ConcurrentHashMap; import java.util.logging.Level; import java.util.stream.Collectors; -public class BukkitHuskSync extends JavaPlugin implements HuskSync { +public class BukkitHuskSync extends JavaPlugin implements HuskSync, BukkitTask.Supplier, BukkitEventDispatcher, + BukkitMapPersister { /** * Metrics ID for HuskSync on Bukkit. */ private static final int METRICS_ID = 13140; + private static final String PLATFORM_TYPE_ID = "bukkit"; + private Database database; private RedisManager redisManager; private EventListener eventListener; private DataAdapter dataAdapter; - private EventCannon eventCannon; + private Map> serializers; + private Map> playerCustomDataStore; private Settings settings; private Locales locales; private List availableMigrators; - + private LegacyConverter legacyConverter; + private Map mapViews; private BukkitAudiences audiences; - private static BukkitHuskSync instance; - - /** - * (Internal use only) Returns the instance of the implementing Bukkit plugin - * - * @return the instance of the Bukkit plugin - */ - public static BukkitHuskSync getInstance() { - return instance; - } - - @Override - public void onLoad() { - instance = this; - } + private MorePaperLib paperLib; + private AsynchronousScheduler asyncScheduler; + private RegionalScheduler regionalScheduler; + private Gson gson; @Override public void onEnable() { - // Initialize HuskSync - final AtomicBoolean initialized = new AtomicBoolean(true); - try { - // Create adventure audience - this.audiences = BukkitAudiences.create(this); - - // Load settings and locales - log(Level.INFO, "Loading plugin configuration settings & locales..."); - initialized.set(reload().join()); - if (initialized.get()) { - log(Level.INFO, "Successfully loaded plugin configuration settings & locales"); - } else { - throw new HuskSyncInitializationException("Failed to load plugin configuration settings and/or locales"); - } - - // Prepare data adapter + // Initial plugin setup + this.gson = createGson(); + this.audiences = BukkitAudiences.create(this); + this.paperLib = new MorePaperLib(this); + this.availableMigrators = new ArrayList<>(); + this.serializers = new LinkedHashMap<>(); + this.playerCustomDataStore = new ConcurrentHashMap<>(); + this.mapViews = new ConcurrentHashMap<>(); + + // Load settings and locales + initialize("plugin config & locale files", (plugin) -> this.loadConfigs()); + + // Prepare data adapter + initialize("data adapter", (plugin) -> { if (settings.doCompressData()) { - dataAdapter = new CompressedDataAdapter(); + dataAdapter = new SnappyGsonAdapter(this); } else { - dataAdapter = new JsonDataAdapter(); + dataAdapter = new GsonAdapter(this); } + }); - // Prepare event cannon - eventCannon = new BukkitEventCannon(); + // Prepare serializers + initialize("data serializers", (plugin) -> { + registerSerializer(Identifier.INVENTORY, new BukkitSerializer.Inventory(this)); + registerSerializer(Identifier.ENDER_CHEST, new BukkitSerializer.EnderChest(this)); + registerSerializer(Identifier.ADVANCEMENTS, new BukkitSerializer.Advancements(this)); + registerSerializer(Identifier.LOCATION, new BukkitSerializer.Location(this)); + registerSerializer(Identifier.HEALTH, new BukkitSerializer.Health(this)); + registerSerializer(Identifier.HUNGER, new BukkitSerializer.Hunger(this)); + registerSerializer(Identifier.GAME_MODE, new BukkitSerializer.GameMode(this)); + registerSerializer(Identifier.POTION_EFFECTS, new BukkitSerializer.PotionEffects(this)); + registerSerializer(Identifier.STATISTICS, new BukkitSerializer.Statistics(this)); + registerSerializer(Identifier.EXPERIENCE, new BukkitSerializer.Experience(this)); + registerSerializer(Identifier.PERSISTENT_DATA, new BukkitSerializer.PersistentData(this)); + }); - // Prepare migrators - availableMigrators = new ArrayList<>(); + // Setup available migrators + initialize("data migrators/converters", (plugin) -> { availableMigrators.add(new LegacyMigrator(this)); - final Plugin mySqlPlayerDataBridge = Bukkit.getPluginManager().getPlugin("MySqlPlayerDataBridge"); - if (mySqlPlayerDataBridge != null) { - availableMigrators.add(new MpdbMigrator(this, mySqlPlayerDataBridge)); + if (isDependencyLoaded("MySqlPlayerDataBridge")) { + availableMigrators.add(new MpdbMigrator(this)); } + legacyConverter = new BukkitLegacyConverter(this); + }); - // Prepare database connection + // Initialize the database + initialize(getSettings().getDatabaseType().getDisplayName() + " database connection", (plugin) -> { this.database = new MySqlDatabase(this); - log(Level.INFO, String.format("Attempting to establish connection to the %s database...", - settings.getDatabaseType().getDisplayName())); this.database.initialize(); - if (initialized.get()) { - log(Level.INFO, String.format("Successfully established a connection to the %s database", - settings.getDatabaseType().getDisplayName())); - } else { - throw new HuskSyncInitializationException("Failed to establish a connection to the database. " + - "Please check the supplied database credentials in the config file"); - } + }); - // Prepare redis connection + // Prepare redis connection + initialize("Redis server connection", (plugin) -> { this.redisManager = new RedisManager(this); - log(Level.INFO, "Attempting to establish connection to the Redis server..."); - initialized.set(this.redisManager.initialize()); - if (initialized.get()) { - log(Level.INFO, "Successfully established a connection to the Redis server"); - } else { - throw new HuskSyncInitializationException("Failed to establish a connection to the Redis server. " + - "Please check the supplied Redis credentials in the config file"); - } + this.redisManager.initialize(); + }); - // Register events - log(Level.INFO, "Registering events..."); - this.eventListener = new BukkitEventListener(this); - log(Level.INFO, "Successfully registered events listener"); - - // Register permissions - log(Level.INFO, "Registering permissions & commands..."); - Arrays.stream(Permission.values()).forEach(permission -> getServer().getPluginManager() - .addPermission(new org.bukkit.permissions.Permission(permission.node, switch (permission.defaultAccess) { - case EVERYONE -> PermissionDefault.TRUE; - case NOBODY -> PermissionDefault.FALSE; - case OPERATORS -> PermissionDefault.OP; - }))); - - // Register commands - for (final BukkitCommandType bukkitCommandType : BukkitCommandType.values()) { - final PluginCommand pluginCommand = getCommand(bukkitCommandType.commandBase.command); - if (pluginCommand != null) { - new BukkitCommand(bukkitCommandType.commandBase, this).register(pluginCommand); - } - } - log(Level.INFO, "Successfully registered permissions & commands"); + // Register events + initialize("events", (plugin) -> this.eventListener = new BukkitEventListener(this)); - // Hook into plan - if (Bukkit.getPluginManager().getPlugin("Plan") != null) { - log(Level.INFO, "Enabling Plan integration..."); + // Register commands + initialize("commands", (plugin) -> BukkitCommand.Type.registerCommands(this)); + + // Register plugin hooks + initialize("hooks", (plugin) -> { + if (isDependencyLoaded("Plan") && getSettings().usePlanHook()) { new PlanHook(this).hookIntoPlan(); - log(Level.INFO, "Plan integration enabled!"); } + }); - // Hook into bStats metrics - try { - new Metrics(this, METRICS_ID); - } catch (final Exception e) { - log(Level.WARNING, "Skipped bStats metrics initialization due to an exception."); - } + // Register API + initialize("api", (plugin) -> BukkitHuskSyncAPI.register(this)); - // Check for updates - if (settings.doCheckForUpdates()) { - log(Level.INFO, "Checking for updates..."); - getLatestVersionIfOutdated().thenAccept(newestVersion -> - newestVersion.ifPresent(newVersion -> log(Level.WARNING, - "An update is available for HuskSync, v" + newVersion - + " (Currently running v" + getPluginVersion() + ")"))); - } - } catch (IllegalStateException exception) { - log(Level.SEVERE, """ - *************************************************** - - Failed to initialize HuskSync! - - *************************************************** - The plugin was disabled due to an error. Please check - the logs below for details. - No user data will be synchronised. - *************************************************** - Caused by: %error_message% - """ - .replaceAll("%error_message%", exception.getMessage())); - initialized.set(false); - } catch (Exception exception) { - log(Level.SEVERE, "An unhandled exception occurred initializing HuskSync!", exception); - initialized.set(false); - } finally { - // Validate initialization - if (initialized.get()) { - log(Level.INFO, "Successfully enabled HuskSync v" + getPluginVersion()); - } else { - log(Level.SEVERE, "Failed to initialize HuskSync. The plugin will now be disabled"); - getServer().getPluginManager().disablePlugin(this); - } - } + // Hook into bStats and check for updates + initialize("metrics", (plugin) -> this.registerMetrics(METRICS_ID)); + this.checkForUpdates(); } @Override public void onDisable() { + // Handle shutdown if (this.eventListener != null) { this.eventListener.handlePluginDisable(); } + + // Unregister API and cancel tasks + BukkitHuskSyncAPI.unregister(); + this.cancelTasks(); + + // Complete shutdown log(Level.INFO, "Successfully disabled HuskSync v" + getPluginVersion()); } @Override - public @NotNull Set getOnlineUsers() { - return Bukkit.getOnlinePlayers().stream().map(BukkitPlayer::adapt).collect(Collectors.toSet()); + @NotNull + public Set getOnlineUsers() { + return Bukkit.getOnlinePlayers().stream() + .map(player -> BukkitUser.adapt(player, this)) + .collect(Collectors.toSet()); } @Override - public @NotNull Optional getOnlineUser(@NotNull UUID uuid) { + @NotNull + public Optional getOnlineUser(@NotNull UUID uuid) { final Player player = Bukkit.getPlayer(uuid); if (player == null) { return Optional.empty(); } - return Optional.of(BukkitPlayer.adapt(player)); + return Optional.of(BukkitUser.adapt(player, this)); } @Override - public @NotNull Database getDatabase() { + @NotNull + public Database getDatabase() { return database; } @Override - public @NotNull RedisManager getRedisManager() { + @NotNull + public RedisManager getRedisManager() { return redisManager; } + @NotNull @Override - public @NotNull DataAdapter getDataAdapter() { + public DataAdapter getDataAdapter() { return dataAdapter; } + @NotNull @Override - public @NotNull EventCannon getEventCannon() { - return eventCannon; + public Map> getSerializers() { + return serializers; } @NotNull @@ -274,16 +236,57 @@ public class BukkitHuskSync extends JavaPlugin implements HuskSync { return availableMigrators; } + @NotNull @Override - public @NotNull Settings getSettings() { + public Map getPlayerCustomDataStore(@NotNull OnlineUser user) { + if (playerCustomDataStore.containsKey(user.getUuid())) { + return playerCustomDataStore.get(user.getUuid()); + } + final Map data = new HashMap<>(); + playerCustomDataStore.put(user.getUuid(), data); + return data; + } + + @Override + @NotNull + public Settings getSettings() { return settings; } @Override - public @NotNull Locales getLocales() { + public void setSettings(@NotNull Settings settings) { + this.settings = settings; + } + + @Override + @NotNull + public Locales getLocales() { return locales; } + @Override + public void setLocales(@NotNull Locales locales) { + this.locales = locales; + } + + @Override + public boolean isDependencyLoaded(@NotNull String name) { + return Bukkit.getPluginManager().getPlugin(name) != null; + } + + // Register bStats metrics + public void registerMetrics(int metricsId) { + if (!getPluginVersion().getMetadata().isBlank()) { + return; + } + + try { + new Metrics(this, metricsId); + } catch (Throwable e) { + log(Level.WARNING, "Failed to register bStats metrics (" + e.getMessage() + ")"); + } + } + @Override public void log(@NotNull Level level, @NotNull String message, @NotNull Throwable... throwable) { if (throwable.length > 0) { @@ -293,6 +296,12 @@ public class BukkitHuskSync extends JavaPlugin implements HuskSync { } } + @NotNull + @Override + public ConsoleUser getConsole() { + return new ConsoleUser(audiences.console()); + } + @NotNull @Override public Version getPluginVersion() { @@ -305,39 +314,65 @@ public class BukkitHuskSync extends JavaPlugin implements HuskSync { return Version.fromString(Bukkit.getBukkitVersion()); } - /** - * Returns the adventure Bukkit audiences - * - * @return The adventure Bukkit audiences - */ @NotNull - public BukkitAudiences getAudiences() { - return audiences; + @Override + public String getPlatformType() { + return PLATFORM_TYPE_ID; + } + + @Override + public Optional getLegacyConverter() { + return Optional.of(legacyConverter); } + @NotNull @Override public Set getLockedPlayers() { return this.eventListener.getLockedPlayers(); } + @NotNull @Override - public CompletableFuture reload() { - return CompletableFuture.supplyAsync(() -> { - try { - // Load plugin settings - this.settings = Annotaml.create(new File(getDataFolder(), "config.yml"), new Settings()).get(); - - // Load locales from language preset default - final Locales languagePresets = Annotaml.create(Locales.class, - Objects.requireNonNull(getResource("locales/" + settings.getLanguage() + ".yml"))).get(); - this.locales = Annotaml.create(new File(getDataFolder(), "messages_" + settings.getLanguage() + ".yml"), - languagePresets).get(); - return true; - } catch (IOException | NullPointerException | InvocationTargetException | IllegalAccessException | - InstantiationException e) { - log(Level.SEVERE, "Failed to load data from the config", e); - return false; - } - }); + public Gson getGson() { + return gson; } + + @NotNull + public Map getMapViews() { + return mapViews; + } + + @NotNull + public GracefulScheduling getScheduler() { + return paperLib.scheduling(); + } + + @NotNull + public AsynchronousScheduler getAsyncScheduler() { + return asyncScheduler == null + ? asyncScheduler = getScheduler().asyncScheduler() : asyncScheduler; + } + + @NotNull + public RegionalScheduler getRegionalScheduler() { + return regionalScheduler == null + ? regionalScheduler = getScheduler().globalRegionalScheduler() : regionalScheduler; + } + + @NotNull + public BukkitAudiences getAudiences() { + return audiences; + } + + @NotNull + public CommandRegistration getCommandRegistrar() { + return paperLib.commandRegistration(); + } + + @Override + @NotNull + public HuskSync getPlugin() { + return this; + } + } diff --git a/bukkit/src/main/java/net/william278/husksync/api/BukkitHuskSyncAPI.java b/bukkit/src/main/java/net/william278/husksync/api/BukkitHuskSyncAPI.java new file mode 100644 index 00000000..6abf75c0 --- /dev/null +++ b/bukkit/src/main/java/net/william278/husksync/api/BukkitHuskSyncAPI.java @@ -0,0 +1,270 @@ +/* + * This file is part of HuskSync, licensed under the Apache License 2.0. + * + * Copyright (c) William278 + * Copyright (c) contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.william278.husksync.api; + +import net.william278.desertwell.util.ThrowingConsumer; +import net.william278.husksync.BukkitHuskSync; +import net.william278.husksync.data.BukkitData; +import net.william278.husksync.data.DataHolder; +import net.william278.husksync.user.BukkitUser; +import net.william278.husksync.user.OnlineUser; +import net.william278.husksync.user.User; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.ApiStatus; +import org.jetbrains.annotations.NotNull; + +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.function.Consumer; + +/** + * The HuskSync API implementation for the Bukkit platform + *

+ * Retrieve an instance of the API class via {@link #getInstance()}. + */ +@SuppressWarnings("unused") +public class BukkitHuskSyncAPI extends HuskSyncAPI { + + // Instance of the plugin + private static BukkitHuskSyncAPI instance; + + /** + * (Internal use only) - Constructor, instantiating the API. + */ + @ApiStatus.Internal + private BukkitHuskSyncAPI(@NotNull BukkitHuskSync plugin) { + super(plugin); + } + + /** + * Entrypoint to the HuskSync API - returns an instance of the API + * + * @return instance of the HuskSync API + * @since 3.0 + */ + @NotNull + public static BukkitHuskSyncAPI getInstance() { + if (instance == null) { + throw new NotRegisteredException(); + } + return instance; + } + + /** + * (Internal use only) - Register the API for this platform. + * + * @param plugin the plugin instance + * @since 3.0 + */ + @ApiStatus.Internal + public static void register(@NotNull BukkitHuskSync plugin) { + instance = new BukkitHuskSyncAPI(plugin); + } + + /** + * (Internal use only) - Unregister the API for this platform. + */ + @ApiStatus.Internal + public static void unregister() { + instance = null; + } + + /** + * Returns a {@link OnlineUser} instance for the given bukkit {@link Player}. + * + * @param player the bukkit player to get the {@link OnlineUser} instance for + * @return the {@link OnlineUser} instance for the given bukkit {@link Player} + * @since 2.0 + */ + @NotNull + public BukkitUser getUser(@NotNull Player player) { + return BukkitUser.adapt(player, plugin); + } + + /** + * Get the current {@link BukkitData.Items.Inventory} of the given {@link User} + * + * @param user the user to get the inventory of + * @return the {@link BukkitData.Items.Inventory} of the given {@link User} + * @since 3.0 + */ + public CompletableFuture> getCurrentInventory(@NotNull User user) { + return getCurrentData(user).thenApply(data -> data.flatMap(DataHolder::getInventory) + .map(BukkitData.Items.Inventory.class::cast)); + } + + /** + * Get the current {@link BukkitData.Items.Inventory} of the given {@link Player} + * + * @param user the user to get the inventory of + * @return the {@link BukkitData.Items.Inventory} of the given {@link Player} + * @since 3.0 + */ + public CompletableFuture> getCurrentInventoryContents(@NotNull User user) { + return getCurrentInventory(user) + .thenApply(inventory -> inventory.map(BukkitData.Items.Inventory::getContents)); + } + + /** + * Set the current {@link BukkitData.Items.Inventory} of the given {@link User} + * + * @param user the user to set the inventory of + * @param contents the contents to set the inventory to + * @since 3.0 + */ + public void setCurrentInventory(@NotNull User user, @NotNull BukkitData.Items.Inventory contents) { + editCurrentData(user, dataHolder -> dataHolder.setInventory(contents)); + } + + /** + * Set the current {@link BukkitData.Items.Inventory} of the given {@link User} + * + * @param user the user to set the inventory of + * @param contents the contents to set the inventory to + * @since 3.0 + */ + public void setCurrentInventoryContents(@NotNull User user, @NotNull ItemStack[] contents) { + editCurrentData( + user, + dataHolder -> dataHolder.getInventory().ifPresent( + inv -> inv.setContents(adaptItems(contents)) + ) + ); + } + + /** + * Edit the current {@link BukkitData.Items.Inventory} of the given {@link User} + * + * @param user the user to edit the inventory of + * @param editor the editor to apply to the inventory + * @since 3.0 + */ + public void editCurrentInventory(@NotNull User user, ThrowingConsumer editor) { + editCurrentData(user, dataHolder -> dataHolder.getInventory() + .map(BukkitData.Items.Inventory.class::cast) + .ifPresent(editor)); + } + + /** + * Edit the current {@link BukkitData.Items.Inventory} of the given {@link User} + * + * @param user the user to edit the inventory of + * @param editor the editor to apply to the inventory + * @since 3.0 + */ + public void editCurrentInventoryContents(@NotNull User user, ThrowingConsumer editor) { + editCurrentData(user, dataHolder -> dataHolder.getInventory() + .map(BukkitData.Items.Inventory.class::cast) + .ifPresent(inventory -> editor.accept(inventory.getContents()))); + } + + /** + * Get the current {@link BukkitData.Items.EnderChest} of the given {@link User} + * + * @param user the user to get the ender chest of + * @return the {@link BukkitData.Items.EnderChest} of the given {@link User}, or {@link Optional#empty()} if the + * user data could not be found + * @since 3.0 + */ + public CompletableFuture> getCurrentEnderChest(@NotNull User user) { + return getCurrentData(user).thenApply(data -> data.flatMap(DataHolder::getEnderChest) + .map(BukkitData.Items.EnderChest.class::cast)); + } + + /** + * Get the current {@link BukkitData.Items.EnderChest} of the given {@link Player} + * + * @param user the user to get the ender chest of + * @return the {@link BukkitData.Items.EnderChest} of the given {@link Player}, or {@link Optional#empty()} if the + * user data could not be found + * @since 3.0 + */ + public CompletableFuture> getCurrentEnderChestContents(@NotNull User user) { + return getCurrentEnderChest(user) + .thenApply(enderChest -> enderChest.map(BukkitData.Items.EnderChest::getContents)); + } + + /** + * Set the current {@link BukkitData.Items.EnderChest} of the given {@link User} + * + * @param user the user to set the ender chest of + * @param contents the contents to set the ender chest to + * @since 3.0 + */ + public void setCurrentEnderChest(@NotNull User user, @NotNull BukkitData.Items.EnderChest contents) { + editCurrentData(user, dataHolder -> dataHolder.setEnderChest(contents)); + } + + /** + * Set the current {@link BukkitData.Items.EnderChest} of the given {@link User} + * + * @param user the user to set the ender chest of + * @param contents the contents to set the ender chest to + * @since 3.0 + */ + public void setCurrentEnderChestContents(@NotNull User user, @NotNull ItemStack[] contents) { + editCurrentData( + user, + dataHolder -> dataHolder.getEnderChest().ifPresent( + enderChest -> enderChest.setContents(adaptItems(contents)) + ) + ); + } + + /** + * Edit the current {@link BukkitData.Items.EnderChest} of the given {@link User} + * + * @param user the user to edit the ender chest of + * @param editor the editor to apply to the ender chest + * @since 3.0 + */ + public void editCurrentEnderChest(@NotNull User user, Consumer editor) { + editCurrentData(user, dataHolder -> dataHolder.getEnderChest() + .map(BukkitData.Items.EnderChest.class::cast) + .ifPresent(editor)); + } + + /** + * Edit the current {@link BukkitData.Items.EnderChest} of the given {@link User} + * + * @param user the user to edit the ender chest of + * @param editor the editor to apply to the ender chest + * @since 3.0 + */ + public void editCurrentEnderChestContents(@NotNull User user, Consumer editor) { + editCurrentData(user, dataHolder -> dataHolder.getEnderChest() + .map(BukkitData.Items.EnderChest.class::cast) + .ifPresent(enderChest -> editor.accept(enderChest.getContents()))); + } + + /** + * Adapts an array of {@link ItemStack} to a {@link BukkitData.Items} instance + * + * @param contents the contents to adapt + * @return the adapted {@link BukkitData.Items} instance + * @since 3.0 + */ + @NotNull + public BukkitData.Items adaptItems(@NotNull ItemStack[] contents) { + return BukkitData.Items.ItemArray.adapt(contents); + } + +} diff --git a/bukkit/src/main/java/net/william278/husksync/api/HuskSyncAPI.java b/bukkit/src/main/java/net/william278/husksync/api/HuskSyncAPI.java deleted file mode 100644 index 0b5f7116..00000000 --- a/bukkit/src/main/java/net/william278/husksync/api/HuskSyncAPI.java +++ /dev/null @@ -1,226 +0,0 @@ -/* - * This file is part of HuskSync, licensed under the Apache License 2.0. - * - * Copyright (c) William278 - * Copyright (c) contributors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.william278.husksync.api; - -import net.william278.husksync.BukkitHuskSync; -import net.william278.husksync.data.*; -import net.william278.husksync.player.BukkitPlayer; -import net.william278.husksync.player.OnlineUser; -import net.william278.husksync.player.User; -import org.bukkit.entity.Player; -import org.bukkit.inventory.ItemStack; -import org.bukkit.potion.PotionEffect; -import org.jetbrains.annotations.NotNull; - -import java.util.Optional; -import java.util.concurrent.CompletableFuture; - -/** - * The HuskSync API implementation for the Bukkit platform, providing methods to access and modify player {@link UserData} held by {@link User}s. - *

- * Retrieve an instance of the API class via {@link #getInstance()}. - */ -@SuppressWarnings("unused") -public class HuskSyncAPI extends BaseHuskSyncAPI { - - /** - * (Internal use only) - Instance of the API class - */ - private static final HuskSyncAPI INSTANCE = new HuskSyncAPI(); - - /** - * (Internal use only) - Constructor, instantiating the API - */ - private HuskSyncAPI() { - super(BukkitHuskSync.getInstance()); - } - - /** - * Entrypoint to the HuskSync API - returns an instance of the API - * - * @return instance of the HuskSync API - */ - public static @NotNull HuskSyncAPI getInstance() { - return INSTANCE; - } - - /** - * Returns a {@link User} instance for the given bukkit {@link Player}. - * - * @param player the bukkit player to get the {@link User} instance for - * @return the {@link User} instance for the given bukkit {@link Player} - * @since 2.0 - */ - @NotNull - public OnlineUser getUser(@NotNull Player player) { - return BukkitPlayer.adapt(player); - } - - /** - * Set the inventory in the database of the given {@link User} to the given {@link ItemStack} contents - * - * @param user the {@link User} to set the inventory of - * @param inventoryContents the {@link ItemStack} contents to set the inventory to - * @return future returning void when complete - * @since 2.0 - */ - public CompletableFuture setInventoryData(@NotNull User user, @NotNull ItemStack[] inventoryContents) { - return CompletableFuture.runAsync(() -> getUserData(user).thenAccept(userData -> - userData.ifPresent(data -> serializeItemStackArray(inventoryContents) - .thenAccept(serializedInventory -> { - data.getInventory().orElse(ItemData.empty()).serializedItems = serializedInventory; - setUserData(user, data).join(); - })))); - } - - /** - * Set the inventory in the database of the given {@link User} to the given {@link BukkitInventoryMap} contents - * - * @param user the {@link User} to set the inventory of - * @param inventoryMap the {@link BukkitInventoryMap} contents to set the inventory to - * @return future returning void when complete - * @since 2.0 - */ - public CompletableFuture setInventoryData(@NotNull User user, @NotNull BukkitInventoryMap inventoryMap) { - return setInventoryData(user, inventoryMap.getContents()); - } - - /** - * Set the Ender Chest in the database of the given {@link User} to the given {@link ItemStack} contents - * - * @param user the {@link User} to set the Ender Chest of - * @param enderChestContents the {@link ItemStack} contents to set the Ender Chest to - * @return future returning void when complete - * @since 2.0 - */ - public CompletableFuture setEnderChestData(@NotNull User user, @NotNull ItemStack[] enderChestContents) { - return CompletableFuture.runAsync(() -> getUserData(user).thenAccept(userData -> - userData.ifPresent(data -> serializeItemStackArray(enderChestContents) - .thenAccept(serializedInventory -> { - data.getEnderChest().orElse(ItemData.empty()).serializedItems = serializedInventory; - setUserData(user, data).join(); - })))); - } - - /** - * Returns a {@link BukkitInventoryMap} for the given {@link User}, containing their current inventory item data - * - * @param user the {@link User} to get the {@link BukkitInventoryMap} for - * @return future returning the {@link BukkitInventoryMap} for the given {@link User} if they exist, - * otherwise an empty {@link Optional} - * @apiNote If the {@link UserData} does not contain an inventory (i.e. inventory synchronisation is disabled), the - * returned {@link BukkitInventoryMap} will be equivalent an empty inventory. - * @since 2.0 - */ - public CompletableFuture> getPlayerInventory(@NotNull User user) { - return CompletableFuture.supplyAsync(() -> getUserData(user).join() - .map(userData -> deserializeInventory(userData.getInventory() - .orElse(ItemData.empty()).serializedItems).join())); - } - - /** - * Returns the {@link ItemStack}s array contents of the given {@link User}'s Ender Chest data - * - * @param user the {@link User} to get the Ender Chest contents of - * @return future returning the {@link ItemStack} array of Ender Chest items for the user if they exist, - * otherwise an empty {@link Optional} - * @apiNote If the {@link UserData} does not contain an Ender Chest (i.e. Ender Chest synchronisation is disabled), - * the returned {@link BukkitInventoryMap} will be equivalent to an empty inventory. - * @since 2.0 - */ - public CompletableFuture> getPlayerEnderChest(@NotNull User user) { - return CompletableFuture.supplyAsync(() -> getUserData(user).join() - .map(userData -> deserializeItemStackArray(userData.getEnderChest() - .orElse(ItemData.empty()).serializedItems).join())); - } - - /** - * Deserialize a Base-64 encoded inventory array string into a {@link ItemStack} array. - * - * @param serializedItemStackArray The Base-64 encoded inventory array string. - * @return The deserialized {@link ItemStack} array. - * @throws DataSerializationException If an error occurs during deserialization. - * @since 2.0 - */ - public CompletableFuture deserializeItemStackArray(@NotNull String serializedItemStackArray) - throws DataSerializationException { - return CompletableFuture.supplyAsync(() -> BukkitSerializer - .deserializeItemStackArray(serializedItemStackArray).join()); - } - - /** - * Deserialize a serialized {@link ItemStack} array of player inventory contents into a {@link BukkitInventoryMap} - * - * @param serializedInventory The serialized {@link ItemStack} array of player inventory contents. - * @return A {@link BukkitInventoryMap} of the deserialized {@link ItemStack} contents array - * @throws DataSerializationException If an error occurs during deserialization. - * @since 2.0 - */ - public CompletableFuture deserializeInventory(@NotNull String serializedInventory) - throws DataSerializationException { - return CompletableFuture.supplyAsync(() -> BukkitSerializer - .deserializeInventory(serializedInventory).join()); - } - - /** - * Serialize an {@link ItemStack} array into a Base-64 encoded string. - * - * @param itemStacks The {@link ItemStack} array to serialize. - * @return The serialized Base-64 encoded string. - * @throws DataSerializationException If an error occurs during serialization. - * @see #deserializeItemStackArray(String) - * @see ItemData - * @since 2.0 - */ - public CompletableFuture serializeItemStackArray(@NotNull ItemStack[] itemStacks) - throws DataSerializationException { - return CompletableFuture.supplyAsync(() -> BukkitSerializer.serializeItemStackArray(itemStacks).join()); - } - - /** - * Deserialize a Base-64 encoded potion effect array string into a {@link PotionEffect} array. - * - * @param serializedPotionEffectArray The Base-64 encoded potion effect array string. - * @return The deserialized {@link PotionEffect} array. - * @throws DataSerializationException If an error occurs during deserialization. - * @since 2.0 - */ - public CompletableFuture deserializePotionEffectArray(@NotNull String serializedPotionEffectArray) - throws DataSerializationException { - return CompletableFuture.supplyAsync(() -> BukkitSerializer - .deserializePotionEffectArray(serializedPotionEffectArray).join()); - } - - /** - * Serialize a {@link PotionEffect} array into a Base-64 encoded string. - * - * @param potionEffects The {@link PotionEffect} array to serialize. - * @return The serialized Base-64 encoded string. - * @throws DataSerializationException If an error occurs during serialization. - * @see #deserializePotionEffectArray(String) - * @see PotionEffectData - * @since 2.0 - */ - public CompletableFuture serializePotionEffectArray(@NotNull PotionEffect[] potionEffects) - throws DataSerializationException { - return CompletableFuture.supplyAsync(() -> BukkitSerializer.serializePotionEffectArray(potionEffects).join()); - } - -} diff --git a/bukkit/src/main/java/net/william278/husksync/command/BrigadierUtil.java b/bukkit/src/main/java/net/william278/husksync/command/BrigadierUtil.java index fbac0c9d..8b35ac38 100644 --- a/bukkit/src/main/java/net/william278/husksync/command/BrigadierUtil.java +++ b/bukkit/src/main/java/net/william278/husksync/command/BrigadierUtil.java @@ -22,28 +22,38 @@ package net.william278.husksync.command; import me.lucko.commodore.CommodoreProvider; import me.lucko.commodore.file.CommodoreFileReader; import net.william278.husksync.BukkitHuskSync; -import org.bukkit.command.PluginCommand; import org.jetbrains.annotations.NotNull; import java.io.IOException; import java.io.InputStream; import java.util.logging.Level; -/** - * Used for registering Brigadier hooks on platforms that support commodore for rich command syntax - */ public class BrigadierUtil { - protected static void registerCommodore(@NotNull BukkitHuskSync plugin, @NotNull PluginCommand pluginCommand, - @NotNull CommandBase command) { - // Register command descriptions via commodore (brigadier wrapper) - try (InputStream pluginFile = plugin.getResource("commodore/" + command.command + ".commodore")) { - CommodoreProvider.getCommodore(plugin).register(pluginCommand, - CommodoreFileReader.INSTANCE.parse(pluginFile), - player -> player.hasPermission(command.permission)); + /** + * Uses commodore to register command completions. + * + * @param plugin instance of the registering Bukkit plugin + * @param bukkitCommand the Bukkit PluginCommand to register completions for + * @param command the {@link Command} to register completions for + */ + protected static void registerCommodore(@NotNull BukkitHuskSync plugin, + @NotNull org.bukkit.command.Command bukkitCommand, + @NotNull Command command) { + final InputStream commodoreFile = plugin.getResource( + "commodore/" + bukkitCommand.getName() + ".commodore" + ); + if (commodoreFile == null) { + return; + } + try { + CommodoreProvider.getCommodore(plugin).register(bukkitCommand, + CommodoreFileReader.INSTANCE.parse(commodoreFile), + player -> player.hasPermission(command.getPermission())); } catch (IOException e) { - plugin.log(Level.SEVERE, - "Failed to load " + command.command + ".commodore command definitions", e); + plugin.log(Level.SEVERE, String.format( + "Failed to read command commodore completions for %s", bukkitCommand.getName()), e + ); } } diff --git a/bukkit/src/main/java/net/william278/husksync/command/BukkitCommand.java b/bukkit/src/main/java/net/william278/husksync/command/BukkitCommand.java index 178ac885..5229d11b 100644 --- a/bukkit/src/main/java/net/william278/husksync/command/BukkitCommand.java +++ b/bukkit/src/main/java/net/william278/husksync/command/BukkitCommand.java @@ -19,77 +19,146 @@ package net.william278.husksync.command; + import me.lucko.commodore.CommodoreProvider; import net.william278.husksync.BukkitHuskSync; -import net.william278.husksync.player.BukkitPlayer; -import org.bukkit.command.*; +import net.william278.husksync.user.BukkitUser; +import net.william278.husksync.user.CommandUser; +import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; +import org.bukkit.permissions.Permission; +import org.bukkit.permissions.PermissionDefault; +import org.bukkit.plugin.PluginManager; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.util.Collections; -import java.util.List; - -/** - * Bukkit executor that implements and executes {@link CommandBase}s - */ -public class BukkitCommand implements CommandExecutor, TabExecutor { +import java.util.*; +import java.util.function.Function; - /** - * The {@link CommandBase} that will be executed - */ - protected final CommandBase command; +public class BukkitCommand extends org.bukkit.command.Command { - /** - * The implementing plugin - */ private final BukkitHuskSync plugin; + private final Command command; - public BukkitCommand(@NotNull CommandBase command, @NotNull BukkitHuskSync implementor) { + public BukkitCommand(@NotNull Command command, @NotNull BukkitHuskSync plugin) { + super(command.getName(), command.getDescription(), command.getUsage(), command.getAliases()); this.command = command; - this.plugin = implementor; + this.plugin = plugin; } - /** - * Registers a {@link PluginCommand} to this implementation - * - * @param pluginCommand {@link PluginCommand} to register - */ - public void register(@NotNull PluginCommand pluginCommand) { - pluginCommand.setExecutor(this); - pluginCommand.setTabCompleter(this); - pluginCommand.setPermission(command.permission); - pluginCommand.setDescription(command.getDescription()); - if (CommodoreProvider.isSupported()) { - BrigadierUtil.registerCommodore(plugin, pluginCommand, command); - } + @Override + public boolean execute(@NotNull CommandSender sender, @NotNull String commandLabel, @NotNull String[] args) { + this.command.onExecuted(sender instanceof Player p ? BukkitUser.adapt(p, plugin) : plugin.getConsole(), args); + return true; } + @NotNull @Override - public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, - @NotNull String label, @NotNull String[] args) { - if (sender instanceof Player player) { - this.command.onExecute(BukkitPlayer.adapt(player), args); - } else { - if (this.command instanceof ConsoleExecutable consoleExecutable) { - consoleExecutable.onConsoleExecute(args); - } else { - plugin.getLocales().getLocale("error_in_game_command_only") - .ifPresent(locale -> plugin.getAudiences().sender(sender) - .sendMessage(locale.toComponent())); - } + public List tabComplete(@NotNull CommandSender sender, @NotNull String alias, + @NotNull String[] args) throws IllegalArgumentException { + if (!(this.command instanceof TabProvider provider)) { + return List.of(); + } + final CommandUser user = sender instanceof Player p ? BukkitUser.adapt(p, plugin) : plugin.getConsole(); + if (getPermission() == null || user.hasPermission(getPermission())) { + return provider.getSuggestions(user, args); + } + return List.of(); + } + + public void register() { + // Register with bukkit + plugin.getCommandRegistrar().getServerCommandMap().register("husksync", this); + + // Register permissions + BukkitCommand.addPermission( + plugin, + command.getPermission(), + command.getUsage(), + BukkitCommand.getPermissionDefault(command.isOperatorCommand()) + ); + final List childNodes = command.getAdditionalPermissions() + .entrySet().stream() + .map((entry) -> BukkitCommand.addPermission( + plugin, + entry.getKey(), + "", + BukkitCommand.getPermissionDefault(entry.getValue())) + ) + .filter(Objects::nonNull) + .toList(); + if (!childNodes.isEmpty()) { + BukkitCommand.addPermission( + plugin, + command.getPermission("*"), + command.getUsage(), + PermissionDefault.FALSE, + childNodes.toArray(new Permission[0]) + ); + } + + // Register commodore TAB completion + if (CommodoreProvider.isSupported() && plugin.getSettings().doBrigadierTabCompletion()) { + BrigadierUtil.registerCommodore(plugin, this, command); } - return true; } @Nullable - @Override - public List onTabComplete(@NotNull CommandSender sender, @NotNull Command command, - @NotNull String alias, @NotNull String[] args) { - if (this.command instanceof TabCompletable tabCompletable) { - return tabCompletable.onTabComplete(args); + protected static Permission addPermission(@NotNull BukkitHuskSync plugin, @NotNull String node, + @NotNull String description, @NotNull PermissionDefault permissionDefault, + @NotNull Permission... children) { + final Map childNodes = Arrays.stream(children) + .map(Permission::getName) + .collect(HashMap::new, (map, child) -> map.put(child, true), HashMap::putAll); + + final PluginManager manager = plugin.getServer().getPluginManager(); + if (manager.getPermission(node) != null) { + return null; + } + + Permission permission; + if (description.isEmpty()) { + permission = new Permission(node, permissionDefault, childNodes); + } else { + permission = new Permission(node, description, permissionDefault, childNodes); } - return Collections.emptyList(); + manager.addPermission(permission); + + return permission; } + @NotNull + protected static PermissionDefault getPermissionDefault(boolean isOperatorCommand) { + return isOperatorCommand ? PermissionDefault.OP : PermissionDefault.TRUE; + } + + /** + * Commands available on the Bukkit HuskSync implementation + */ + public enum Type { + + HUSKSYNC_COMMAND(HuskSyncCommand::new), + USERDATA_COMMAND(UserDataCommand::new), + INVENTORY_COMMAND(InventoryCommand::new), + ENDER_CHEST_COMMAND(EnderChestCommand::new); + + public final Function commandSupplier; + + Type(@NotNull Function supplier) { + this.commandSupplier = supplier; + } + + @NotNull + public Command createCommand(@NotNull BukkitHuskSync plugin) { + return commandSupplier.apply(plugin); + } + + public static void registerCommands(@NotNull BukkitHuskSync plugin) { + Arrays.stream(values()) + .map((type) -> type.createCommand(plugin)) + .forEach((command) -> new BukkitCommand(command, plugin).register()); + } + + + } } diff --git a/bukkit/src/main/java/net/william278/husksync/command/BukkitCommandType.java b/bukkit/src/main/java/net/william278/husksync/command/BukkitCommandType.java deleted file mode 100644 index a69e0229..00000000 --- a/bukkit/src/main/java/net/william278/husksync/command/BukkitCommandType.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * This file is part of HuskSync, licensed under the Apache License 2.0. - * - * Copyright (c) William278 - * Copyright (c) contributors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.william278.husksync.command; - -import net.william278.husksync.BukkitHuskSync; -import org.jetbrains.annotations.NotNull; - -/** - * Commands available on the Bukkit HuskSync implementation - */ -public enum BukkitCommandType { - - HUSKSYNC_COMMAND(new HuskSyncCommand(BukkitHuskSync.getInstance())), - USERDATA_COMMAND(new UserDataCommand(BukkitHuskSync.getInstance())), - INVENTORY_COMMAND(new InventoryCommand(BukkitHuskSync.getInstance())), - ENDER_CHEST_COMMAND(new EnderChestCommand(BukkitHuskSync.getInstance())); - - public final CommandBase commandBase; - - BukkitCommandType(@NotNull CommandBase commandBase) { - this.commandBase = commandBase; - } -} diff --git a/bukkit/src/main/java/net/william278/husksync/data/BukkitData.java b/bukkit/src/main/java/net/william278/husksync/data/BukkitData.java new file mode 100644 index 00000000..7416306f --- /dev/null +++ b/bukkit/src/main/java/net/william278/husksync/data/BukkitData.java @@ -0,0 +1,1093 @@ +/* + * This file is part of HuskSync, licensed under the Apache License 2.0. + * + * Copyright (c) William278 + * Copyright (c) contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.william278.husksync.data; + +import com.google.gson.annotations.SerializedName; +import de.tr7zw.changeme.nbtapi.NBTCompound; +import de.tr7zw.changeme.nbtapi.NBTPersistentDataContainer; +import net.william278.desertwell.util.ThrowingConsumer; +import net.william278.husksync.BukkitHuskSync; +import net.william278.husksync.HuskSync; +import net.william278.husksync.adapter.Adaptable; +import net.william278.husksync.user.BukkitUser; +import org.apache.commons.lang.NotImplementedException; +import org.bukkit.Bukkit; +import org.bukkit.GameRule; +import org.bukkit.Material; +import org.bukkit.Statistic; +import org.bukkit.advancement.AdvancementProgress; +import org.bukkit.attribute.Attribute; +import org.bukkit.attribute.AttributeInstance; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.Player; +import org.bukkit.event.inventory.InventoryType; +import org.bukkit.inventory.ItemStack; +import org.bukkit.persistence.PersistentDataContainer; +import org.bukkit.potion.PotionEffect; +import org.bukkit.potion.PotionEffectType; +import org.jetbrains.annotations.ApiStatus; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.*; +import java.util.logging.Level; +import java.util.stream.Collectors; + +public abstract class BukkitData implements Data { + + @Override + public final void apply(@NotNull UserDataHolder dataHolder, @NotNull HuskSync plugin) { + final BukkitUser user = (BukkitUser) dataHolder; + try { + this.apply(user, (BukkitHuskSync) plugin); + } catch (Throwable e) { + plugin.log(Level.WARNING, String.format("[%s] Failed to apply %s data object; skipping", + user.getUsername(), this.getClass().getSimpleName()), e); + } + } + + public abstract void apply(@NotNull BukkitUser user, @NotNull BukkitHuskSync plugin) throws IllegalStateException; + + public static abstract class Items extends BukkitData implements Data.Items { + + private final ItemStack[] contents; + + private Items(@NotNull ItemStack[] contents) { + this.contents = Arrays.stream(contents) + .map(i -> i == null || i.getType() == Material.AIR ? null : i) + .toArray(ItemStack[]::new); + } + + @NotNull + @Override + public Stack[] getStack() { + return Arrays.stream(contents) + .map(stack -> stack != null ? new Stack( + stack.getType().getKey().toString(), + stack.getAmount(), + stack.hasItemMeta() ? (Objects.requireNonNull( + stack.getItemMeta()).hasDisplayName() ? stack.getItemMeta().getDisplayName() : null) + : null, + stack.hasItemMeta() ? (Objects.requireNonNull( + stack.getItemMeta()).hasLore() ? stack.getItemMeta().getLore() : null) + : null, + stack.hasItemMeta() && Objects.requireNonNull(stack.getItemMeta()).hasEnchants() ? + stack.getItemMeta().getEnchants().keySet().stream() + .map(enchantment -> enchantment.getKey().getKey()) + .toList() + : List.of() + ) : null) + .toArray(Stack[]::new); + } + + @Override + public void clear() { + Arrays.fill(contents, null); + } + + @Override + public void setContents(@NotNull Data.Items contents) { + System.arraycopy( + ((BukkitData.Items) contents).getContents(), + 0, this.contents, + 0, this.contents.length + ); + } + + @SuppressWarnings("unused") + public void setContents(@NotNull ItemStack[] contents) { + System.arraycopy(contents, 0, this.contents, 0, this.contents.length); + } + + @NotNull + public ItemStack[] getContents() { + return contents; + } + + @Override + public boolean equals(Object obj) { + if (obj instanceof BukkitData.Items items) { + return Arrays.equals(contents, items.getContents()); + } + return false; + } + + public static class Inventory extends BukkitData.Items implements Data.Items.Inventory { + + public static final int INVENTORY_SLOT_COUNT = 41; + private int heldItemSlot; + + private Inventory(@NotNull ItemStack[] contents, int heldItemSlot) { + super(contents); + this.heldItemSlot = heldItemSlot; + } + + @NotNull + public static BukkitData.Items.Inventory from(@NotNull ItemStack[] contents, int heldItemSlot) { + return new BukkitData.Items.Inventory(contents, heldItemSlot); + } + + @NotNull + public static BukkitData.Items.Inventory empty() { + return new BukkitData.Items.Inventory(new ItemStack[INVENTORY_SLOT_COUNT], 0); + } + + @Override + public int getSlotCount() { + return INVENTORY_SLOT_COUNT; + } + + @Override + public void apply(@NotNull BukkitUser user, @NotNull BukkitHuskSync plugin) throws IllegalStateException { + final Player player = user.getPlayer(); + this.clearInventoryCraftingSlots(player); + player.setItemOnCursor(null); + player.getInventory().setContents(plugin.setMapViews(getContents())); + player.updateInventory(); + player.getInventory().setHeldItemSlot(heldItemSlot); + } + + private void clearInventoryCraftingSlots(@NotNull Player player) { + final org.bukkit.inventory.Inventory inventory = player.getOpenInventory().getTopInventory(); + if (inventory.getType() == InventoryType.CRAFTING) { + for (int slot = 0; slot < 5; slot++) { + inventory.setItem(slot, null); + } + } + } + + @Override + public int getHeldItemSlot() { + return heldItemSlot; + } + + @Override + public void setHeldItemSlot(int heldItemSlot) throws IllegalArgumentException { + if (heldItemSlot < 0 || heldItemSlot > 8) { + throw new IllegalArgumentException("Held item slot must be between 0 and 8"); + } + this.heldItemSlot = heldItemSlot; + } + + } + + public static class EnderChest extends BukkitData.Items implements Data.Items.EnderChest { + + public static final int ENDER_CHEST_SLOT_COUNT = 27; + + private EnderChest(@NotNull ItemStack[] contents) { + super(contents); + } + + @NotNull + public static BukkitData.Items.EnderChest adapt(@NotNull ItemStack[] items) { + return new BukkitData.Items.EnderChest(items); + } + + @NotNull + public static BukkitData.Items.EnderChest empty() { + return new BukkitData.Items.EnderChest(new ItemStack[ENDER_CHEST_SLOT_COUNT]); + } + + @Override + public void apply(@NotNull BukkitUser user, @NotNull BukkitHuskSync plugin) throws IllegalStateException { + user.getPlayer().getEnderChest().setContents(plugin.setMapViews(getContents())); + } + + } + + public static class ItemArray extends BukkitData.Items implements Data.Items { + + private ItemArray(@NotNull ItemStack[] contents) { + super(contents); + } + + @NotNull + public static ItemArray adapt(@NotNull Collection drops) { + return new ItemArray(drops.toArray(ItemStack[]::new)); + } + + @NotNull + public static ItemArray adapt(@NotNull ItemStack[] drops) { + return new ItemArray(drops); + } + + @Override + public void apply(@NotNull BukkitUser user, @NotNull BukkitHuskSync plugin) throws IllegalStateException { + throw new NotImplementedException("A generic item array cannot be applied to a player"); + } + + } + + } + + public static class PotionEffects extends BukkitData implements Data.PotionEffects { + + private final Collection effects; + + private PotionEffects(@NotNull Collection effects) { + this.effects = effects; + } + + @NotNull + public static BukkitData.PotionEffects from(@NotNull Collection effects) { + return new BukkitData.PotionEffects(effects); + } + + @NotNull + public static BukkitData.PotionEffects adapt(@NotNull Collection effects) { + return from( + effects.stream() + .map(effect -> new PotionEffect( + Objects.requireNonNull( + PotionEffectType.getByName(effect.type()), + "Invalid potion effect type" + ), + effect.duration(), + effect.amplifier(), + effect.isAmbient(), + effect.showParticles(), + effect.hasIcon() + )) + .toList() + ); + } + + @NotNull + @SuppressWarnings("unused") + public static BukkitData.PotionEffects empty() { + return new BukkitData.PotionEffects(List.of()); + } + + @Override + public void apply(@NotNull BukkitUser user, @NotNull BukkitHuskSync plugin) throws IllegalStateException { + final Player player = user.getPlayer(); + for (PotionEffect effect : player.getActivePotionEffects()) { + player.removePotionEffect(effect.getType()); + } + for (PotionEffect effect : this.getEffects()) { + player.addPotionEffect(effect); + } + } + + @NotNull + @Override + public List getActiveEffects() { + return effects.stream() + .map(potionEffect -> new Effect( + potionEffect.getType().getName().toLowerCase(Locale.ENGLISH), + potionEffect.getAmplifier(), + potionEffect.getDuration(), + potionEffect.isAmbient(), + potionEffect.hasParticles(), + potionEffect.hasIcon() + )) + .toList(); + } + + @NotNull + public Collection getEffects() { + return effects; + } + + } + + public static class Advancements extends BukkitData implements Data.Advancements { + + private List completed; + + private Advancements(@NotNull List advancements) { + this.completed = advancements; + } + + // Iterate through the server advancement set and add all advancements to the list + @NotNull + public static BukkitData.Advancements adapt(@NotNull Player player) { + final List advancements = new ArrayList<>(); + forEachAdvancement(advancement -> { + final AdvancementProgress advancementProgress = player.getAdvancementProgress(advancement); + final Map awardedCriteria = new HashMap<>(); + + advancementProgress.getAwardedCriteria().forEach(criteriaKey -> awardedCriteria.put(criteriaKey, + advancementProgress.getDateAwarded(criteriaKey))); + + // Only save the advancement if criteria has been completed + if (!awardedCriteria.isEmpty()) { + advancements.add(Advancement.adapt(advancement.getKey().toString(), awardedCriteria)); + } + }); + return new BukkitData.Advancements(advancements); + } + + @NotNull + public static BukkitData.Advancements from(@NotNull List advancements) { + return new BukkitData.Advancements(advancements); + } + + @Override + public void apply(@NotNull BukkitUser user, @NotNull BukkitHuskSync plugin) throws IllegalStateException { + plugin.runAsync(() -> forEachAdvancement(advancement -> { + final Player player = user.getPlayer(); + final AdvancementProgress progress = player.getAdvancementProgress(advancement); + final Optional record = completed.stream() + .filter(r -> r.getKey().equals(advancement.getKey().toString())) + .findFirst(); + if (record.isEmpty()) { + this.setAdvancement(plugin, advancement, player, List.of(), progress.getAwardedCriteria()); + return; + } + + final Map criteria = record.get().getCompletedCriteria(); + this.setAdvancement( + plugin, advancement, player, + criteria.keySet().stream().filter(key -> !progress.getAwardedCriteria().contains(key)).toList(), + progress.getAwardedCriteria().stream().filter(key -> !criteria.containsKey(key)).toList() + ); + })); + } + + private void setAdvancement(@NotNull HuskSync plugin, + @NotNull org.bukkit.advancement.Advancement advancement, @NotNull Player player, + @NotNull Collection toAward, @NotNull Collection toRevoke) { + plugin.runSync(() -> { + // Track player exp level & progress + final int expLevel = player.getLevel(); + final float expProgress = player.getExp(); + boolean gameRuleUpdated = false; + if (Boolean.TRUE.equals(player.getWorld().getGameRuleValue(GameRule.ANNOUNCE_ADVANCEMENTS))) { + player.getWorld().setGameRule(GameRule.ANNOUNCE_ADVANCEMENTS, false); + gameRuleUpdated = true; + } + + // Award and revoke advancement criteria + final AdvancementProgress progress = player.getAdvancementProgress(advancement); + toAward.forEach(progress::awardCriteria); + toRevoke.forEach(progress::revokeCriteria); + + // Set player experience and level (prevent advancement awards applying twice), reset game rule + if (!toAward.isEmpty() && player.getLevel() != expLevel || player.getExp() != expProgress) { + player.setLevel(expLevel); + player.setExp(expProgress); + } + if (gameRuleUpdated) { + player.getWorld().setGameRule(GameRule.ANNOUNCE_ADVANCEMENTS, true); + } + }); + } + + // Performs a consuming function for every advancement registered on the server + private static void forEachAdvancement(@NotNull ThrowingConsumer consumer) { + Bukkit.getServer().advancementIterator().forEachRemaining(consumer); + } + + @NotNull + @Override + public List getCompleted() { + return completed; + } + + @Override + public void setCompleted(@NotNull List completed) { + this.completed = completed; + } + + } + + public static class Location extends BukkitData implements Data.Location, Adaptable { + @SerializedName("x") + private double x; + @SerializedName("y") + private double y; + @SerializedName("z") + private double z; + @SerializedName("yaw") + private float yaw; + @SerializedName("pitch") + private float pitch; + @SerializedName("world") + private World world; + + private Location(double x, double y, double z, float yaw, float pitch, @NotNull World world) { + this.x = x; + this.y = y; + this.z = z; + this.yaw = yaw; + this.pitch = pitch; + this.world = world; + } + + @SuppressWarnings("unused") + private Location() { + } + + @NotNull + public static BukkitData.Location from(double x, double y, double z, + float yaw, float pitch, @NotNull World world) { + return new BukkitData.Location(x, y, z, yaw, pitch, world); + } + + @NotNull + public static BukkitData.Location adapt(@NotNull org.bukkit.Location location) { + return from( + location.getX(), + location.getY(), + location.getZ(), + location.getYaw(), + location.getPitch(), + new World( + Objects.requireNonNull(location.getWorld(), "World is null").getName(), + location.getWorld().getUID(), + location.getWorld().getEnvironment().name() + ) + ); + } + + @Override + public void apply(@NotNull BukkitUser user, @NotNull BukkitHuskSync plugin) throws IllegalStateException { + try { + final org.bukkit.Location location = new org.bukkit.Location( + Bukkit.getWorld(world.name()), x, y, z, yaw, pitch + ); + user.getPlayer().teleport(location); + } catch (Throwable e) { + throw new IllegalStateException("Failed to apply location", e); + } + } + + @Override + public double getX() { + return x; + } + + @Override + public void setX(double x) { + this.x = x; + } + + @Override + public double getY() { + return y; + } + + @Override + public void setY(double y) { + this.y = y; + } + + @Override + public double getZ() { + return z; + } + + @Override + public void setZ(double z) { + this.z = z; + } + + @Override + public float getYaw() { + return yaw; + } + + @Override + public void setYaw(float yaw) { + this.yaw = yaw; + } + + @Override + public float getPitch() { + return pitch; + } + + @Override + public void setPitch(float pitch) { + this.pitch = pitch; + } + + @NotNull + @Override + public World getWorld() { + return world; + } + + @Override + public void setWorld(@NotNull World world) { + this.world = world; + } + + } + + public static class Statistics extends BukkitData implements Data.Statistics { + private Map untypedStatistics; + private Map> blockStatistics; + private Map> itemStatistics; + private Map> entityStatistics; + + private Statistics(@NotNull Map genericStatistics, + @NotNull Map> blockStatistics, + @NotNull Map> itemStatistics, + @NotNull Map> entityStatistics) { + this.untypedStatistics = genericStatistics; + this.blockStatistics = blockStatistics; + this.itemStatistics = itemStatistics; + this.entityStatistics = entityStatistics; + } + + @SuppressWarnings("unused") + private Statistics() { + } + + @NotNull + public static BukkitData.Statistics adapt(@NotNull Player player) { + return new BukkitData.Statistics( + // Generic (untyped) stats + Arrays.stream(Statistic.values()) + .filter(stat -> stat.getType() == Statistic.Type.UNTYPED) + .filter(stat -> player.getStatistic(stat) != 0) + .map(stat -> Map.entry(stat, player.getStatistic(stat))) + .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)), + + // Block stats + Arrays.stream(Statistic.values()) + .filter(stat -> stat.getType() == Statistic.Type.BLOCK) + .map(stat -> Map.entry(stat, Arrays.stream(Material.values()) + .filter(Material::isBlock) + .filter(material -> player.getStatistic(stat, material) != 0) + .map(material -> Map.entry(material, player.getStatistic(stat, material))) + .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)))) + .filter(entry -> !entry.getValue().isEmpty()) + .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)), + + // Item stats + Arrays.stream(Statistic.values()) + .filter(stat -> stat.getType() == Statistic.Type.ITEM) + .map(stat -> Map.entry(stat, Arrays.stream(Material.values()) + .filter(Material::isItem) + .filter(material -> player.getStatistic(stat, material) != 0) + .map(material -> Map.entry(material, player.getStatistic(stat, material))) + .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)))) + .filter(entry -> !entry.getValue().isEmpty()) + .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)), + + // Entity stats + Arrays.stream(Statistic.values()) + .filter(stat -> stat.getType() == Statistic.Type.ENTITY) + .map(stat -> Map.entry(stat, Arrays.stream(EntityType.values()) + .filter(EntityType::isAlive) + .filter(entityType -> player.getStatistic(stat, entityType) != 0) + .map(entityType -> Map.entry(entityType, player.getStatistic(stat, entityType))) + .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)))) + .filter(entry -> !entry.getValue().isEmpty()) + .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)) + ); + } + + @NotNull + public static BukkitData.Statistics from(@NotNull StatisticsMap stats) { + return new BukkitData.Statistics( + stats.genericStats().entrySet().stream().collect(Collectors.toMap( + entry -> matchStatistic(entry.getKey()), + Map.Entry::getValue + )), + stats.blockStats().entrySet().stream().collect(Collectors.toMap( + entry -> matchStatistic(entry.getKey()), + entry -> entry.getValue().entrySet().stream().collect(Collectors.toMap( + blockEntry -> Material.matchMaterial(blockEntry.getKey()), + Map.Entry::getValue + )) + )), + stats.itemStats().entrySet().stream().collect(Collectors.toMap( + entry -> matchStatistic(entry.getKey()), + entry -> entry.getValue().entrySet().stream().collect(Collectors.toMap( + itemEntry -> Material.matchMaterial(itemEntry.getKey()), + Map.Entry::getValue + )) + )), + stats.entityStats().entrySet().stream().collect(Collectors.toMap( + entry -> matchStatistic(entry.getKey()), + entry -> entry.getValue().entrySet().stream().collect(Collectors.toMap( + entityEntry -> matchEntityType(entityEntry.getKey()), + Map.Entry::getValue + )) + )) + ); + } + + @NotNull + public static BukkitData.Statistics from(@NotNull Map genericStats, + @NotNull Map> blockStats, + @NotNull Map> itemStats, + @NotNull Map> entityStats) { + return new BukkitData.Statistics(genericStats, blockStats, itemStats, entityStats); + } + + @NotNull + @ApiStatus.Internal + public static StatisticsMap createStatisticsMap(@NotNull Map genericStats, + @NotNull Map> blockStats, + @NotNull Map> itemStats, + @NotNull Map> entityStats) { + return new StatisticsMap(genericStats, blockStats, itemStats, entityStats); + } + + @NotNull + private static Statistic matchStatistic(@NotNull String key) { + return Arrays.stream(Statistic.values()) + .filter(stat -> stat.getKey().toString().equals(key)) + .findFirst() + .orElseThrow(() -> new IllegalArgumentException(String.format("Invalid statistic key: %s", key))); + } + + @NotNull + private static EntityType matchEntityType(@NotNull String key) { + return Arrays.stream(EntityType.values()) + .filter(entityType -> entityType.getKey().toString().equals(key)) + .findFirst() + .orElseThrow(() -> new IllegalArgumentException(String.format("Invalid entity type key: %s", key))); + } + + @Override + public void apply(@NotNull BukkitUser user, @NotNull BukkitHuskSync plugin) throws IllegalStateException { + untypedStatistics.forEach((stat, value) -> applyStat(user, stat, null, value)); + blockStatistics.forEach((stat, m) -> m.forEach((block, value) -> applyStat(user, stat, block, value))); + itemStatistics.forEach((stat, m) -> m.forEach((item, value) -> applyStat(user, stat, item, value))); + entityStatistics.forEach((stat, m) -> m.forEach((entity, value) -> applyStat(user, stat, entity, value))); + } + + private void applyStat(@NotNull UserDataHolder user, @NotNull Statistic stat, @Nullable Object type, int value) { + try { + final Player player = ((BukkitUser) user).getPlayer(); + if (type == null) { + player.setStatistic(stat, value); + } else if (type instanceof Material) { + player.setStatistic(stat, (Material) type, value); + } else if (type instanceof EntityType) { + player.setStatistic(stat, (EntityType) type, value); + } + } catch (IllegalArgumentException ignored) { + } + } + + @NotNull + @Override + public Map getGenericStatistics() { + return untypedStatistics.entrySet().stream().collect( + TreeMap::new, + (m, e) -> m.put(e.getKey().getKey().toString(), e.getValue()), TreeMap::putAll + ); + } + + @NotNull + @Override + public Map> getBlockStatistics() { + return blockStatistics.entrySet().stream().collect( + TreeMap::new, + (m, e) -> m.put(e.getKey().getKey().toString(), e.getValue().entrySet().stream().collect( + TreeMap::new, + (m2, e2) -> m2.put(e2.getKey().getKey().toString(), e2.getValue()), TreeMap::putAll + )), TreeMap::putAll + ); + } + + @NotNull + @Override + public Map> getItemStatistics() { + return itemStatistics.entrySet().stream().collect( + TreeMap::new, + (m, e) -> m.put(e.getKey().getKey().toString(), e.getValue().entrySet().stream().collect( + TreeMap::new, + (m2, e2) -> m2.put(e2.getKey().getKey().toString(), e2.getValue()), TreeMap::putAll + )), TreeMap::putAll + ); + } + + @NotNull + @Override + public Map> getEntityStatistics() { + return entityStatistics.entrySet().stream().collect( + TreeMap::new, + (m, e) -> m.put(e.getKey().getKey().toString(), e.getValue().entrySet().stream().collect( + TreeMap::new, + (m2, e2) -> m2.put(e2.getKey().getKey().toString(), e2.getValue()), TreeMap::putAll + )), TreeMap::putAll + ); + } + + @NotNull + protected StatisticsMap getStatisticsSet() { + return new StatisticsMap( + getGenericStatistics(), + getBlockStatistics(), + getItemStatistics(), + getEntityStatistics() + ); + } + + public record StatisticsMap( + @SerializedName("generic") @NotNull Map genericStats, + @SerializedName("blocks") @NotNull Map> blockStats, + @SerializedName("items") @NotNull Map> itemStats, + @SerializedName("entities") @NotNull Map> entityStats + ) { + } + + } + + public static class PersistentData extends BukkitData implements Data.PersistentData { + private final NBTCompound persistentData; + + private PersistentData(@NotNull NBTCompound persistentData) { + this.persistentData = persistentData; + } + + @NotNull + public static BukkitData.PersistentData adapt(@NotNull PersistentDataContainer persistentData) { + return new BukkitData.PersistentData(new NBTPersistentDataContainer(persistentData)); + } + + @NotNull + public static BukkitData.PersistentData from(@NotNull NBTCompound compound) { + return new BukkitData.PersistentData(compound); + } + + @Override + public void apply(@NotNull BukkitUser user, @NotNull BukkitHuskSync plugin) throws IllegalStateException { + final NBTPersistentDataContainer container = new NBTPersistentDataContainer( + user.getPlayer().getPersistentDataContainer() + ); + container.clearNBT(); + container.mergeCompound(persistentData); + } + + @NotNull + public NBTCompound getPersistentData() { + return persistentData; + } + + } + + public static class Health extends BukkitData implements Data.Health, Adaptable { + @SerializedName("health") + private double health; + @SerializedName("max_health") + private double maxHealth; + @SerializedName("health_scale") + private double healthScale; + + private Health(double health, double maxHealth, double healthScale) { + this.health = health; + this.maxHealth = maxHealth; + this.healthScale = healthScale; + } + + @SuppressWarnings("unused") + private Health() { + } + + @NotNull + public static BukkitData.Health from(double health, double maxHealth, double healthScale) { + return new BukkitData.Health(health, maxHealth, healthScale); + } + + @NotNull + public static BukkitData.Health adapt(@NotNull Player player) { + return from( + player.getHealth(), + Objects.requireNonNull(player.getAttribute(Attribute.GENERIC_MAX_HEALTH), + "Missing max health attribute").getValue(), + player.getHealthScale() + ); + } + + @Override + public void apply(@NotNull BukkitUser user, @NotNull BukkitHuskSync plugin) throws IllegalStateException { + final Player player = user.getPlayer(); + + // Set base max health + final AttributeInstance maxHealthAttribute = Objects.requireNonNull( + player.getAttribute(Attribute.GENERIC_MAX_HEALTH), "Missing max health attribute"); + double currentMaxHealth = maxHealthAttribute.getBaseValue(); + if (maxHealth != 0d) { + maxHealthAttribute.setBaseValue(maxHealth); + currentMaxHealth = maxHealth; + } + + // Set health + final double currentHealth = player.getHealth(); + if (health != currentHealth) { + final double healthToSet = currentHealth > currentMaxHealth ? currentMaxHealth : health; + try { + player.setHealth(Math.min(healthToSet, currentMaxHealth)); + } catch (IllegalArgumentException e) { + plugin.log(Level.WARNING, "Failed to set player health", e); + } + } + + // Set health scale + try { + if (healthScale != 0d) { + player.setHealthScale(healthScale); + } else { + player.setHealthScale(maxHealth); + } + player.setHealthScaled(healthScale != 0D); + } catch (IllegalArgumentException e) { + plugin.log(Level.WARNING, "Failed to set player health scale", e); + } + } + + @Override + public double getHealth() { + return health; + } + + @Override + public void setHealth(double health) { + this.health = health; + } + + @Override + public double getMaxHealth() { + return maxHealth; + } + + @Override + public void setMaxHealth(double maxHealth) { + this.maxHealth = maxHealth; + } + + @Override + public double getHealthScale() { + return healthScale; + } + + @Override + public void setHealthScale(double healthScale) { + this.healthScale = healthScale; + } + + } + + public static class Hunger extends BukkitData implements Data.Hunger, Adaptable { + + @SerializedName("food_level") + private int foodLevel; + @SerializedName("saturation") + private float saturation; + @SerializedName("exhaustion") + private float exhaustion; + + private Hunger(int foodLevel, float saturation, float exhaustion) { + this.foodLevel = foodLevel; + this.saturation = saturation; + this.exhaustion = exhaustion; + } + + @SuppressWarnings("unused") + private Hunger() { + } + + @NotNull + public static BukkitData.Hunger adapt(@NotNull Player player) { + return from(player.getFoodLevel(), player.getSaturation(), player.getExhaustion()); + } + + @NotNull + public static BukkitData.Hunger from(int foodLevel, float saturation, float exhaustion) { + return new BukkitData.Hunger(foodLevel, saturation, exhaustion); + } + + @Override + public void apply(@NotNull BukkitUser user, @NotNull BukkitHuskSync plugin) throws IllegalStateException { + final Player player = user.getPlayer(); + player.setFoodLevel(foodLevel); + player.setSaturation(saturation); + player.setExhaustion(exhaustion); + } + + @Override + public int getFoodLevel() { + return foodLevel; + } + + @Override + public void setFoodLevel(int foodLevel) { + this.foodLevel = foodLevel; + } + + @Override + public float getSaturation() { + return saturation; + } + + @Override + public void setSaturation(float saturation) { + this.saturation = saturation; + } + + @Override + public float getExhaustion() { + return exhaustion; + } + + @Override + public void setExhaustion(float exhaustion) { + this.exhaustion = exhaustion; + } + } + + public static class Experience extends BukkitData implements Data.Experience, Adaptable { + + @SerializedName("total_experience") + private int totalExperience; + + @SerializedName("exp_level") + private int expLevel; + + @SerializedName("exp_progress") + private float expProgress; + + private Experience(int totalExperience, int expLevel, float expProgress) { + this.totalExperience = totalExperience; + this.expLevel = expLevel; + this.expProgress = expProgress; + } + + @SuppressWarnings("unused") + private Experience() { + } + + @NotNull + public static BukkitData.Experience from(int totalExperience, int expLevel, float expProgress) { + return new BukkitData.Experience(totalExperience, expLevel, expProgress); + } + + @NotNull + public static BukkitData.Experience adapt(@NotNull Player player) { + return from(player.getTotalExperience(), player.getLevel(), player.getExp()); + } + + @Override + public void apply(@NotNull BukkitUser user, @NotNull BukkitHuskSync plugin) throws IllegalStateException { + final Player player = user.getPlayer(); + player.setTotalExperience(totalExperience); + player.setLevel(expLevel); + player.setExp(expProgress); + } + + @Override + public int getTotalExperience() { + return totalExperience; + } + + @Override + public void setTotalExperience(int totalExperience) { + this.totalExperience = totalExperience; + } + + @Override + public int getExpLevel() { + return expLevel; + } + + @Override + public void setExpLevel(int expLevel) { + this.expLevel = expLevel; + } + + @Override + public float getExpProgress() { + return expProgress; + } + + @Override + public void setExpProgress(float expProgress) { + this.expProgress = expProgress; + } + + } + + public static class GameMode extends BukkitData implements Data.GameMode, Adaptable { + + @SerializedName("game_mode") + private String gameMode; + @SerializedName("allow_flight") + private boolean allowFlight; + @SerializedName("is_flying") + private boolean isFlying; + + private GameMode(@NotNull String gameMode, boolean allowFlight, boolean isFlying) { + this.gameMode = gameMode; + this.allowFlight = allowFlight; + this.isFlying = isFlying; + } + + @NotNull + public static BukkitData.GameMode from(@NotNull String gameMode, boolean allowFlight, boolean isFlying) { + return new BukkitData.GameMode(gameMode, allowFlight, isFlying); + } + + @NotNull + public static BukkitData.GameMode adapt(@NotNull Player player) { + return from(player.getGameMode().name(), player.getAllowFlight(), player.isFlying()); + } + + @Override + public void apply(@NotNull BukkitUser user, @NotNull BukkitHuskSync plugin) throws IllegalStateException { + final Player player = user.getPlayer(); + player.setGameMode(org.bukkit.GameMode.valueOf(gameMode)); + player.setAllowFlight(allowFlight); + player.setFlying(isFlying); + } + + @NotNull + @Override + public String getGameMode() { + return gameMode; + } + + @Override + public void setGameMode(@NotNull String gameMode) { + this.gameMode = gameMode; + } + + @Override + public boolean getAllowFlight() { + return allowFlight; + } + + @Override + public void setAllowFlight(boolean allowFlight) { + this.allowFlight = allowFlight; + } + + @Override + public boolean getIsFlying() { + return isFlying; + } + + @Override + public void setIsFlying(boolean isFlying) { + this.isFlying = isFlying; + } + + } + +} diff --git a/bukkit/src/main/java/net/william278/husksync/data/BukkitInventoryMap.java b/bukkit/src/main/java/net/william278/husksync/data/BukkitInventoryMap.java deleted file mode 100644 index 7175e1c4..00000000 --- a/bukkit/src/main/java/net/william278/husksync/data/BukkitInventoryMap.java +++ /dev/null @@ -1,147 +0,0 @@ -/* - * This file is part of HuskSync, licensed under the Apache License 2.0. - * - * Copyright (c) William278 - * Copyright (c) contributors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.william278.husksync.data; - -import org.bukkit.inventory.ItemStack; -import org.jetbrains.annotations.NotNull; - -import java.util.Optional; - -/** - * A mapped player inventory, providing methods to easily access a player's inventory. - */ -@SuppressWarnings("unused") -public class BukkitInventoryMap { - - public static final int INVENTORY_SLOT_COUNT = 41; - - private ItemStack[] contents; - - /** - * Creates a new mapped inventory from the given contents. - * - * @param contents the contents of the inventory - */ - protected BukkitInventoryMap(ItemStack[] contents) { - this.contents = contents; - } - - /** - * Gets the contents of the inventory. - * - * @return the contents of the inventory - */ - public ItemStack[] getContents() { - return contents; - } - - /** - * Set the contents of the inventory. - * - * @param contents the contents of the inventory - */ - public void setContents(ItemStack[] contents) { - this.contents = contents; - } - - /** - * Gets the size of the inventory. - * - * @return the size of the inventory - */ - public int getSize() { - return contents.length; - } - - /** - * Gets the item at the given index. - * - * @param index the index of the item to get - * @return the item at the given index - */ - public Optional getItemAt(int index) { - if (contents.length >= index) { - if (contents[index] == null) { - return Optional.empty(); - } - return Optional.of(contents[index]); - } - return Optional.empty(); - } - - /** - * Sets the item at the given index. - * - * @param itemStack the item to set at the given index - * @param index the index of the item to set - * @throws IllegalArgumentException if the index is out of bounds - */ - public void setItemAt(@NotNull ItemStack itemStack, int index) throws IllegalArgumentException { - contents[index] = itemStack; - } - - /** - * Returns the main inventory contents. - * - * @return the main inventory contents - */ - public ItemStack[] getInventory() { - final ItemStack[] inventory = new ItemStack[36]; - System.arraycopy(contents, 0, inventory, 0, Math.min(contents.length, inventory.length)); - return inventory; - } - - public ItemStack[] getHotbar() { - final ItemStack[] armor = new ItemStack[9]; - for (int i = 0; i <= 9; i++) { - armor[i] = getItemAt(i).orElse(null); - } - return armor; - } - - public Optional getOffHand() { - return getItemAt(40); - } - - public Optional getHelmet() { - return getItemAt(39); - } - - public Optional getChestplate() { - return getItemAt(38); - } - - public Optional getLeggings() { - return getItemAt(37); - } - - public Optional getBoots() { - return getItemAt(36); - } - - public ItemStack[] getArmor() { - final ItemStack[] armor = new ItemStack[4]; - for (int i = 36; i < 40; i++) { - armor[i - 36] = getItemAt(i).orElse(null); - } - return armor; - } - -} diff --git a/bukkit/src/main/java/net/william278/husksync/data/BukkitMapHandler.java b/bukkit/src/main/java/net/william278/husksync/data/BukkitMapHandler.java deleted file mode 100644 index f603aac4..00000000 --- a/bukkit/src/main/java/net/william278/husksync/data/BukkitMapHandler.java +++ /dev/null @@ -1,233 +0,0 @@ -/* - * This file is part of HuskSync, licensed under the Apache License 2.0. - * - * Copyright (c) William278 - * Copyright (c) contributors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.william278.husksync.data; - -import net.william278.husksync.BukkitHuskSync; -import net.william278.mapdataapi.MapData; -import org.bukkit.Bukkit; -import org.bukkit.Material; -import org.bukkit.NamespacedKey; -import org.bukkit.entity.Player; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.meta.MapMeta; -import org.bukkit.map.*; -import org.bukkit.persistence.PersistentDataType; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -import java.awt.*; -import java.io.IOException; -import java.util.Objects; -import java.util.concurrent.ExecutionException; -import java.util.logging.Level; - -/** - * Handles the persistence of {@link MapData} into {@link ItemStack}s. - */ -public class BukkitMapHandler { - - private static final BukkitHuskSync plugin = BukkitHuskSync.getInstance(); - private static final NamespacedKey MAP_DATA_KEY = new NamespacedKey(plugin, "map_data"); - - /** - * Get the {@link MapData} from the given {@link ItemStack} and persist it in its' data container - * - * @param itemStack the {@link ItemStack} to get the {@link MapData} from - */ - @SuppressWarnings("ConstantConditions") - public static void persistMapData(@Nullable ItemStack itemStack) { - if (itemStack == null || itemStack.getType() != Material.FILLED_MAP) { - return; - } - final MapMeta mapMeta = (MapMeta) itemStack.getItemMeta(); - if (mapMeta == null || !mapMeta.hasMapView()) { - return; - } - - // Get the map view from the map - final MapView mapView; - try { - mapView = Bukkit.getScheduler().callSyncMethod(plugin, mapMeta::getMapView).get(); - if (mapView == null || !mapView.isLocked() || mapView.isVirtual()) { - return; - } - } catch (InterruptedException | ExecutionException e) { - plugin.getLogger().log(Level.WARNING, "Failed to save map data for a player", e); - return; - } - - // Get the map data - plugin.debug("Rendering map view onto canvas for locked map"); - final LockedMapCanvas canvas = new LockedMapCanvas(mapView); - for (MapRenderer renderer : mapView.getRenderers()) { - renderer.render(mapView, canvas, Bukkit.getServer() - .getOnlinePlayers().stream() - .findAny() - .orElse(null)); - } - - // Save the extracted rendered map data - plugin.debug("Saving pixel canvas data for locked map"); - if (!mapMeta.getPersistentDataContainer().has(MAP_DATA_KEY, PersistentDataType.BYTE_ARRAY)) { - mapMeta.getPersistentDataContainer().set(MAP_DATA_KEY, PersistentDataType.BYTE_ARRAY, - canvas.extractMapData().toBytes()); - itemStack.setItemMeta(mapMeta); - } - } - - /** - * Set the map data of the given {@link ItemStack} to the given {@link MapData}, applying a map view to the item stack - * - * @param itemStack the {@link ItemStack} to set the map data of - */ - public static void setMapRenderer(@Nullable ItemStack itemStack) { - if (itemStack == null || itemStack.getType() != Material.FILLED_MAP) { - return; - } - - final MapMeta mapMeta = (MapMeta) itemStack.getItemMeta(); - if (mapMeta == null) { - return; - } - - if (!itemStack.getItemMeta().getPersistentDataContainer().has(MAP_DATA_KEY, PersistentDataType.BYTE_ARRAY)) { - return; - } - - try { - final byte[] serializedData = itemStack.getItemMeta().getPersistentDataContainer() - .get(MAP_DATA_KEY, PersistentDataType.BYTE_ARRAY); - final MapData mapData = MapData.fromByteArray(Objects.requireNonNull(serializedData)); - plugin.debug("Setting deserialized map data for an item stack"); - - // Create a new map view renderer with the map data color at each pixel - final MapView view = Bukkit.createMap(Bukkit.getWorlds().get(0)); - view.getRenderers().clear(); - view.addRenderer(new PersistentMapRenderer(mapData)); - view.setLocked(true); - view.setScale(MapView.Scale.NORMAL); - view.setTrackingPosition(false); - view.setUnlimitedTracking(false); - mapMeta.setMapView(view); - itemStack.setItemMeta(mapMeta); - plugin.debug("Successfully applied renderer to map item stack"); - } catch (IOException | NullPointerException e) { - plugin.getLogger().log(Level.WARNING, "Failed to deserialize map data for a player", e); - } - } - - /** - * A {@link MapRenderer} that can be used to render persistently serialized {@link MapData} to a {@link MapView} - */ - public static class PersistentMapRenderer extends MapRenderer { - - private final MapData mapData; - - private PersistentMapRenderer(@NotNull MapData mapData) { - super(false); - this.mapData = mapData; - } - - @Override - public void render(@NotNull MapView map, @NotNull MapCanvas canvas, @NotNull Player player) { - for (int i = 0; i < 128; i++) { - for (int j = 0; j < 128; j++) { - // We set the pixels in this order to avoid the map being rendered upside down - canvas.setPixel(j, i, (byte) mapData.getColorAt(i, j)); - } - } - } - } - - /** - * A {@link MapCanvas} implementation used for pre-rendering maps to be converted into {@link MapData} - */ - public static class LockedMapCanvas implements MapCanvas { - - private final MapView mapView; - private final int[][] pixels = new int[128][128]; - private MapCursorCollection cursors; - - private LockedMapCanvas(@NotNull MapView mapView) { - this.mapView = mapView; - } - - @NotNull - @Override - public MapView getMapView() { - return mapView; - } - - @NotNull - @Override - public MapCursorCollection getCursors() { - return cursors == null ? (cursors = new MapCursorCollection()) : cursors; - } - - @Override - public void setCursors(@NotNull MapCursorCollection cursors) { - this.cursors = cursors; - } - - @Override - public void setPixel(int x, int y, byte color) { - pixels[x][y] = color; - } - - @Override - public byte getPixel(int x, int y) { - return (byte) pixels[x][y]; - } - - @Override - public byte getBasePixel(int x, int y) { - return getPixel(x, y); - } - - @Override - public void drawImage(int x, int y, @NotNull Image image) { - // Not implemented - } - - @Override - public void drawText(int x, int y, @NotNull MapFont font, @NotNull String text) { - // Not implemented - } - - @NotNull - private String getDimension() { - return mapView.getWorld() == null ? "minecraft:overworld" - : switch (mapView.getWorld().getEnvironment()) { - case NETHER -> "minecraft:the_nether"; - case THE_END -> "minecraft:the_end"; - default -> "minecraft:overworld"; - }; - } - - /** - * Extract the map data from the canvas. Must be rendered first - * @return the extracted map data - */ - @NotNull - private MapData extractMapData() { - return MapData.fromPixels(pixels, getDimension(), (byte) 2); - } - } -} diff --git a/bukkit/src/main/java/net/william278/husksync/data/BukkitPersistentTypeMapping.java b/bukkit/src/main/java/net/william278/husksync/data/BukkitPersistentTypeMapping.java deleted file mode 100644 index 4102842f..00000000 --- a/bukkit/src/main/java/net/william278/husksync/data/BukkitPersistentTypeMapping.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * This file is part of HuskSync, licensed under the Apache License 2.0. - * - * Copyright (c) William278 - * Copyright (c) contributors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.william278.husksync.data; - -import org.bukkit.NamespacedKey; -import org.bukkit.entity.Player; -import org.bukkit.persistence.PersistentDataContainer; -import org.bukkit.persistence.PersistentDataType; -import org.jetbrains.annotations.NotNull; - -import java.util.Objects; -import java.util.Optional; - -public record BukkitPersistentTypeMapping(PersistentDataTagType type, PersistentDataType bukkitType) { - - public static final BukkitPersistentTypeMapping[] PRIMITIVE_TYPE_MAPPINGS = new BukkitPersistentTypeMapping[]{ - new BukkitPersistentTypeMapping<>(PersistentDataTagType.BYTE, PersistentDataType.BYTE), - new BukkitPersistentTypeMapping<>(PersistentDataTagType.SHORT, PersistentDataType.SHORT), - new BukkitPersistentTypeMapping<>(PersistentDataTagType.INTEGER, PersistentDataType.INTEGER), - new BukkitPersistentTypeMapping<>(PersistentDataTagType.LONG, PersistentDataType.LONG), - new BukkitPersistentTypeMapping<>(PersistentDataTagType.FLOAT, PersistentDataType.FLOAT), - new BukkitPersistentTypeMapping<>(PersistentDataTagType.DOUBLE, PersistentDataType.DOUBLE), - new BukkitPersistentTypeMapping<>(PersistentDataTagType.STRING, PersistentDataType.STRING), - new BukkitPersistentTypeMapping<>(PersistentDataTagType.BYTE_ARRAY, PersistentDataType.BYTE_ARRAY), - new BukkitPersistentTypeMapping<>(PersistentDataTagType.INTEGER_ARRAY, PersistentDataType.INTEGER_ARRAY), - new BukkitPersistentTypeMapping<>(PersistentDataTagType.LONG_ARRAY, PersistentDataType.LONG_ARRAY), - new BukkitPersistentTypeMapping<>(PersistentDataTagType.TAG_CONTAINER_ARRAY, PersistentDataType.TAG_CONTAINER_ARRAY), - new BukkitPersistentTypeMapping<>(PersistentDataTagType.TAG_CONTAINER, PersistentDataType.TAG_CONTAINER) - }; - - public BukkitPersistentTypeMapping(@NotNull PersistentDataTagType type, @NotNull PersistentDataType bukkitType) { - this.type = type; - this.bukkitType = bukkitType; - } - - @NotNull - public PersistentDataTag getContainerValue(@NotNull PersistentDataContainer container, @NotNull NamespacedKey key) throws NullPointerException { - return new PersistentDataTag<>(type, Objects.requireNonNull(container.get(key, bukkitType))); - } - - public void setContainerValue(@NotNull PersistentDataContainerData container, @NotNull Player player, @NotNull NamespacedKey key) throws NullPointerException { - container.getTagValue(key.toString(), bukkitType.getComplexType()) - .ifPresent(value -> player.getPersistentDataContainer().set(key, bukkitType, value)); - } - - public static Optional> getMapping(@NotNull PersistentDataTagType type) { - for (BukkitPersistentTypeMapping mapping : PRIMITIVE_TYPE_MAPPINGS) { - if (mapping.type().equals(type)) { - return Optional.of(mapping); - } - } - return Optional.empty(); - } - - -} diff --git a/bukkit/src/main/java/net/william278/husksync/data/BukkitSerializer.java b/bukkit/src/main/java/net/william278/husksync/data/BukkitSerializer.java index 1c4b57ac..0f6e0232 100644 --- a/bukkit/src/main/java/net/william278/husksync/data/BukkitSerializer.java +++ b/bukkit/src/main/java/net/william278/husksync/data/BukkitSerializer.java @@ -19,235 +19,247 @@ package net.william278.husksync.data; -import net.william278.husksync.BukkitHuskSync; -import net.william278.husksync.config.Settings; +import com.google.gson.reflect.TypeToken; +import de.tr7zw.changeme.nbtapi.NBT; +import de.tr7zw.changeme.nbtapi.NBTContainer; +import de.tr7zw.changeme.nbtapi.iface.ReadWriteNBT; +import net.william278.husksync.HuskSync; +import net.william278.husksync.adapter.Adaptable; +import net.william278.husksync.api.HuskSyncAPI; import org.bukkit.inventory.ItemStack; -import org.bukkit.potion.PotionEffect; -import org.bukkit.util.io.BukkitObjectInputStream; -import org.bukkit.util.io.BukkitObjectOutputStream; +import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; -import org.yaml.snakeyaml.external.biz.base64Coder.Base64Coder; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.util.Map; -import java.util.concurrent.CompletableFuture; -import java.util.logging.Level; +import java.util.List; + +import static net.william278.husksync.data.BukkitData.Items.Inventory.INVENTORY_SLOT_COUNT; public class BukkitSerializer { - /** - * Returns a serialized array of {@link ItemStack}s - * - * @param inventoryContents The contents of the inventory - * @return The serialized inventory contents - */ - public static CompletableFuture serializeItemStackArray(@NotNull ItemStack[] inventoryContents) - throws DataSerializationException { - return CompletableFuture.supplyAsync(() -> { - // Return an empty string if there is no inventory item data to serialize - if (inventoryContents.length == 0) { - return ""; - } - - // Create an output stream that will be encoded into base 64 - ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream(); - - try (BukkitObjectOutputStream bukkitOutputStream = new BukkitObjectOutputStream(byteOutputStream)) { - // Define the length of the inventory array to serialize - bukkitOutputStream.writeInt(inventoryContents.length); - - // Write each serialize each ItemStack to the output stream - final boolean persistLockedMaps = BukkitHuskSync.getInstance().getSettings().getSynchronizationFeature(Settings.SynchronizationFeature.LOCKED_MAPS); - for (ItemStack inventoryItem : inventoryContents) { - if (persistLockedMaps) { - BukkitMapHandler.persistMapData(inventoryItem); - } - bukkitOutputStream.writeObject(serializeItemStack(inventoryItem)); - } - - // Return encoded data, using the encoder from SnakeYaml to get a ByteArray conversion - return Base64Coder.encodeLines(byteOutputStream.toByteArray()); - } catch (IOException e) { - BukkitHuskSync.getInstance().log(Level.SEVERE, "Failed to serialize item stack data", e); - throw new DataSerializationException("Failed to serialize item stack data", e); - } - }); + protected final HuskSync plugin; + + private BukkitSerializer(@NotNull HuskSync plugin) { + this.plugin = plugin; } - /** - * Returns a {@link BukkitInventoryMap} from a serialized array of ItemStacks representing the contents of a player's inventory. - * - * @param serializedPlayerInventory The serialized {@link ItemStack} inventory array - * @return The deserialized ItemStacks, mapped for convenience as a {@link BukkitInventoryMap} - * @throws DataSerializationException If the serialized item stack array could not be deserialized - */ - public static CompletableFuture deserializeInventory(@NotNull String serializedPlayerInventory) - throws DataSerializationException { - return CompletableFuture.supplyAsync(() -> new BukkitInventoryMap(deserializeItemStackArray(serializedPlayerInventory).join())); + @SuppressWarnings("unused") + public BukkitSerializer(@NotNull HuskSyncAPI api) { + this.plugin = api.getPlugin(); } - /** - * Returns an array of ItemStacks from serialized inventory data. - * - * @param serializeItemStackArray The serialized {@link ItemStack} array - * @return The deserialized array of {@link ItemStack}s - * @throws DataSerializationException If the serialized item stack array could not be deserialized - * @implNote Empty slots will be represented by {@code null} - */ - public static CompletableFuture deserializeItemStackArray(@NotNull String serializeItemStackArray) - throws DataSerializationException { - return CompletableFuture.supplyAsync(() -> { - // Return empty array if there is no inventory data (set the player as having an empty inventory) - if (serializeItemStackArray.isEmpty()) { - return new ItemStack[0]; - } - - // Create a byte input stream to read the serialized data - try (ByteArrayInputStream byteInputStream = new ByteArrayInputStream(Base64Coder.decodeLines(serializeItemStackArray))) { - try (BukkitObjectInputStream bukkitInputStream = new BukkitObjectInputStream(byteInputStream)) { - // Read the length of the Bukkit input stream and set the length of the array to this value - ItemStack[] inventoryContents = new ItemStack[bukkitInputStream.readInt()]; - - // Set the ItemStacks in the array from deserialized ItemStack data - int slotIndex = 0; - final boolean persistLockedMaps = BukkitHuskSync.getInstance().getSettings().getSynchronizationFeature(Settings.SynchronizationFeature.LOCKED_MAPS); - for (ItemStack ignored : inventoryContents) { - final ItemStack deserialized = deserializeItemStack(bukkitInputStream.readObject()); - if (persistLockedMaps) { - BukkitMapHandler.setMapRenderer(deserialized); - } - inventoryContents[slotIndex] = deserialized; - slotIndex++; - } - - // Return the finished, serialized inventory contents - return inventoryContents; - } - } catch (IOException | ClassNotFoundException e) { - BukkitHuskSync.getInstance().log(Level.SEVERE, "Failed to deserialize item stack data", e); - throw new DataSerializationException("Failed to deserialize item stack data", e); - } - }); + @ApiStatus.Internal + @NotNull + public HuskSync getPlugin() { + return plugin; } - /** - * Returns the serialized version of an {@link ItemStack} as a string to object Map - * - * @param item The {@link ItemStack} to serialize - * @return The serialized {@link ItemStack} - */ - @Nullable - private static Map serializeItemStack(@Nullable ItemStack item) { - return item != null ? item.serialize() : null; + public static class Inventory extends BukkitSerializer implements Serializer { + private static final String ITEMS_TAG = "items"; + private static final String HELD_ITEM_SLOT_TAG = "held_item_slot"; + + public Inventory(@NotNull HuskSync plugin) { + super(plugin); + } + + @Override + public BukkitData.Items.Inventory deserialize(@NotNull String serialized) throws DeserializationException { + final ReadWriteNBT root = NBT.parseNBT(serialized); + final ItemStack[] items = root.getItemStackArray(ITEMS_TAG); + final int heldItemSlot = root.getInteger(HELD_ITEM_SLOT_TAG); + return BukkitData.Items.Inventory.from( + items == null ? new ItemStack[INVENTORY_SLOT_COUNT] : items, + heldItemSlot + ); + } + + @NotNull + @Override + public String serialize(@NotNull BukkitData.Items.Inventory data) throws SerializationException { + final ReadWriteNBT root = NBT.createNBTObject(); + root.setItemStackArray(ITEMS_TAG, data.getContents()); + root.setInteger(HELD_ITEM_SLOT_TAG, data.getHeldItemSlot()); + return root.toString(); + } + } - /** - * Returns the deserialized {@link ItemStack} from the Object read from the {@link BukkitObjectInputStream} - * - * @param serializedItemStack The serialized item stack; a String-Object map - * @return The deserialized {@link ItemStack} - */ - @SuppressWarnings("unchecked") // Ignore the "Unchecked cast" warning - @Nullable - private static ItemStack deserializeItemStack(@Nullable Object serializedItemStack) { - return serializedItemStack != null ? ItemStack.deserialize((Map) serializedItemStack) : null; + public static class EnderChest extends BukkitSerializer implements Serializer { + + public EnderChest(@NotNull HuskSync plugin) { + super(plugin); + } + + @Override + public BukkitData.Items.EnderChest deserialize(@NotNull String serialized) throws DeserializationException { + final ItemStack[] items = NBT.itemStackArrayFromNBT(NBT.parseNBT(serialized)); + return items == null ? BukkitData.Items.EnderChest.empty() : BukkitData.Items.EnderChest.adapt(items); + } + + @NotNull + @Override + public String serialize(@NotNull BukkitData.Items.EnderChest data) throws SerializationException { + return NBT.itemStackArrayToNBT(data.getContents()).toString(); + } } - /** - * Returns a serialized array of {@link PotionEffect}s - * - * @param potionEffects The potion effect array - * @return The serialized potion effects - */ - public static CompletableFuture serializePotionEffectArray(@NotNull PotionEffect[] potionEffects) throws DataSerializationException { - return CompletableFuture.supplyAsync(() -> { - // Return an empty string if there are no effects to serialize - if (potionEffects.length == 0) { - return ""; - } - - // Create an output stream that will be encoded into base 64 - ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream(); - - try (BukkitObjectOutputStream bukkitOutputStream = new BukkitObjectOutputStream(byteOutputStream)) { - // Define the length of the potion effect array to serialize - bukkitOutputStream.writeInt(potionEffects.length); - - // Write each serialize each PotionEffect to the output stream - for (PotionEffect potionEffect : potionEffects) { - bukkitOutputStream.writeObject(serializePotionEffect(potionEffect)); - } - - // Return encoded data, using the encoder from SnakeYaml to get a ByteArray conversion - return Base64Coder.encodeLines(byteOutputStream.toByteArray()); - } catch (IOException e) { - BukkitHuskSync.getInstance().log(Level.SEVERE, "Failed to serialize potion effect data", e); - throw new DataSerializationException("Failed to serialize potion effect data", e); - } - }); + public static class PotionEffects extends BukkitSerializer implements Serializer { + + private static final TypeToken> TYPE = new TypeToken<>() { + }; + + public PotionEffects(@NotNull HuskSync plugin) { + super(plugin); + } + + @Override + public BukkitData.PotionEffects deserialize(@NotNull String serialized) throws DeserializationException { + return BukkitData.PotionEffects.adapt( + plugin.getGson().fromJson(serialized, TYPE.getType()) + ); + } + + @NotNull + @Override + public String serialize(@NotNull BukkitData.PotionEffects element) throws SerializationException { + return plugin.getGson().toJson(element.getActiveEffects()); + } + } - /** - * Returns an array of ItemStacks from serialized potion effect data - * - * @param potionEffectData The serialized {@link PotionEffect} array - * @return The {@link PotionEffect}s - */ - public static CompletableFuture deserializePotionEffectArray(@NotNull String potionEffectData) throws DataSerializationException { - return CompletableFuture.supplyAsync(() -> { - // Return empty array if there is no potion effect data (don't apply any effects to the player) - if (potionEffectData.isEmpty()) { - return new PotionEffect[0]; - } - - // Create a byte input stream to read the serialized data - try (ByteArrayInputStream byteInputStream = new ByteArrayInputStream(Base64Coder.decodeLines(potionEffectData))) { - try (BukkitObjectInputStream bukkitInputStream = new BukkitObjectInputStream(byteInputStream)) { - // Read the length of the Bukkit input stream and set the length of the array to this value - PotionEffect[] potionEffects = new PotionEffect[bukkitInputStream.readInt()]; - - // Set the potion effects in the array from deserialized PotionEffect data - int potionIndex = 0; - for (PotionEffect ignored : potionEffects) { - potionEffects[potionIndex] = deserializePotionEffect(bukkitInputStream.readObject()); - potionIndex++; - } - - // Return the finished, serialized potion effect array - return potionEffects; - } - } catch (IOException | ClassNotFoundException e) { - BukkitHuskSync.getInstance().log(Level.SEVERE, "Failed to deserialize potion effect data", e); - throw new DataSerializationException("Failed to deserialize potion effects", e); - } - }); + public static class Advancements extends BukkitSerializer implements Serializer { + + private static final TypeToken> TYPE = new TypeToken<>() { + }; + + public Advancements(@NotNull HuskSync plugin) { + super(plugin); + } + + @Override + public BukkitData.Advancements deserialize(@NotNull String serialized) throws DeserializationException { + return BukkitData.Advancements.from( + plugin.getGson().fromJson(serialized, TYPE.getType()) + ); + } + + @NotNull + @Override + public String serialize(@NotNull BukkitData.Advancements element) throws SerializationException { + return plugin.getGson().toJson(element.getCompleted()); + } } - /** - * Returns the serialized version of an {@link ItemStack} as a string to object Map - * - * @param potionEffect The {@link ItemStack} to serialize - * @return The serialized {@link ItemStack} - */ - @Nullable - private static Map serializePotionEffect(@Nullable PotionEffect potionEffect) { - return potionEffect != null ? potionEffect.serialize() : null; + public static class Location extends BukkitSerializer implements Serializer { + + public Location(@NotNull HuskSync plugin) { + super(plugin); + } + + @Override + public BukkitData.Location deserialize(@NotNull String serialized) throws DeserializationException { + return plugin.getDataAdapter().fromJson(serialized, BukkitData.Location.class); + } + + @NotNull + @Override + public String serialize(@NotNull BukkitData.Location element) throws SerializationException { + return plugin.getDataAdapter().toJson(element); + } } - /** - * Returns the deserialized {@link PotionEffect} from the Object read from the {@link BukkitObjectInputStream} - * - * @param serializedPotionEffect The serialized potion effect; a String-Object map - * @return The deserialized {@link PotionEffect} - */ - @SuppressWarnings("unchecked") // Ignore the "Unchecked cast" warning - @Nullable - private static PotionEffect deserializePotionEffect(@Nullable Object serializedPotionEffect) { - return serializedPotionEffect != null ? new PotionEffect((Map) serializedPotionEffect) : null; + public static class Statistics extends BukkitSerializer implements Serializer { + + public Statistics(@NotNull HuskSync plugin) { + super(plugin); + } + + @Override + public BukkitData.Statistics deserialize(@NotNull String serialized) throws DeserializationException { + return BukkitData.Statistics.from(plugin.getGson().fromJson( + serialized, + BukkitData.Statistics.StatisticsMap.class + )); + } + + @NotNull + @Override + public String serialize(@NotNull BukkitData.Statistics element) throws SerializationException { + return plugin.getGson().toJson(element.getStatisticsSet()); + } + } + public static class PersistentData extends BukkitSerializer implements Serializer { + + public PersistentData(@NotNull HuskSync plugin) { + super(plugin); + } + + @Override + public BukkitData.PersistentData deserialize(@NotNull String serialized) throws DeserializationException { + return BukkitData.PersistentData.from(new NBTContainer(serialized)); + } + + @NotNull + @Override + public String serialize(@NotNull BukkitData.PersistentData element) throws SerializationException { + return element.getPersistentData().toString(); + } + + } + + public static class Health extends Json implements Serializer { + + public Health(@NotNull HuskSync plugin) { + super(plugin, BukkitData.Health.class); + } + + } + + public static class Hunger extends Json implements Serializer { + + public Hunger(@NotNull HuskSync plugin) { + super(plugin, BukkitData.Hunger.class); + } + + } + + public static class Experience extends Json implements Serializer { + + public Experience(@NotNull HuskSync plugin) { + super(plugin, BukkitData.Experience.class); + } + + } + + public static class GameMode extends Json implements Serializer { + + public GameMode(@NotNull HuskSync plugin) { + super(plugin, BukkitData.GameMode.class); + } + + } + + public static abstract class Json extends BukkitSerializer implements Serializer { + + private final Class type; + + protected Json(@NotNull HuskSync plugin, Class type) { + super(plugin); + this.type = type; + } + + @Override + public T deserialize(@NotNull String serialized) throws DeserializationException { + return plugin.getDataAdapter().fromJson(serialized, type); + } + + @NotNull + @Override + public String serialize(@NotNull T element) throws SerializationException { + return plugin.getDataAdapter().toJson(element); + } + + } } diff --git a/bukkit/src/main/java/net/william278/husksync/data/BukkitUserDataHolder.java b/bukkit/src/main/java/net/william278/husksync/data/BukkitUserDataHolder.java new file mode 100644 index 00000000..7754ad8d --- /dev/null +++ b/bukkit/src/main/java/net/william278/husksync/data/BukkitUserDataHolder.java @@ -0,0 +1,151 @@ +/* + * This file is part of HuskSync, licensed under the Apache License 2.0. + * + * Copyright (c) William278 + * Copyright (c) contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.william278.husksync.data; + +import net.william278.husksync.BukkitHuskSync; +import net.william278.husksync.util.BukkitMapPersister; +import org.bukkit.entity.Player; +import org.bukkit.inventory.PlayerInventory; +import org.jetbrains.annotations.NotNull; + +import java.util.Map; +import java.util.Optional; + +public interface BukkitUserDataHolder extends UserDataHolder { + + @Override + default Optional getData(@NotNull Identifier id) { + if (!id.isCustom()) { + return switch (id.getKeyValue()) { + case "inventory" -> getInventory(); + case "ender_chest" -> getEnderChest(); + case "potion_effects" -> getPotionEffects(); + case "advancements" -> getAdvancements(); + case "location" -> getLocation(); + case "statistics" -> getStatistics(); + case "health" -> getHealth(); + case "hunger" -> getHunger(); + case "experience" -> getExperience(); + case "game_mode" -> getGameMode(); + case "persistent_data" -> getPersistentData(); + default -> throw new IllegalStateException(String.format("Unexpected data type: %s", id)); + }; + } + return Optional.ofNullable(getCustomDataStore().get(id)); + } + + @Override + default void setData(@NotNull Identifier id, @NotNull Data data) { + if (id.isCustom()) { + getCustomDataStore().put(id, data); + } + UserDataHolder.super.setData(id, data); + } + + @NotNull + @Override + default Optional getInventory() { + if ((isDead() && !getPlugin().getSettings().doSynchronizeDeadPlayersChangingServer())) { + return Optional.of(BukkitData.Items.Inventory.empty()); + } + final PlayerInventory inventory = getBukkitPlayer().getInventory(); + return Optional.of(BukkitData.Items.Inventory.from( + getMapPersister().persistLockedMaps(inventory.getContents(), getBukkitPlayer()), + inventory.getHeldItemSlot() + )); + } + + @NotNull + @Override + default Optional getEnderChest() { + return Optional.of(BukkitData.Items.EnderChest.adapt( + getMapPersister().persistLockedMaps(getBukkitPlayer().getEnderChest().getContents(), getBukkitPlayer()) + )); + } + + @NotNull + @Override + default Optional getPotionEffects() { + return Optional.of(BukkitData.PotionEffects.from(getBukkitPlayer().getActivePotionEffects())); + } + + @NotNull + @Override + default Optional getAdvancements() { + return Optional.of(BukkitData.Advancements.adapt(getBukkitPlayer())); + } + + @NotNull + @Override + default Optional getLocation() { + return Optional.of(BukkitData.Location.adapt(getBukkitPlayer().getLocation())); + } + + @NotNull + @Override + default Optional getStatistics() { + return Optional.of(BukkitData.Statistics.adapt(getBukkitPlayer())); + } + + @NotNull + @Override + default Optional getHealth() { + return Optional.of(BukkitData.Health.adapt(getBukkitPlayer())); + } + + @NotNull + @Override + default Optional getHunger() { + return Optional.of(BukkitData.Hunger.adapt(getBukkitPlayer())); + } + + @NotNull + @Override + default Optional getExperience() { + return Optional.of(BukkitData.Experience.adapt(getBukkitPlayer())); + } + + @NotNull + @Override + default Optional getGameMode() { + return Optional.of(BukkitData.GameMode.adapt(getBukkitPlayer())); + } + + @NotNull + @Override + default Optional getPersistentData() { + return Optional.of(BukkitData.PersistentData.adapt(getBukkitPlayer().getPersistentDataContainer())); + } + + boolean isDead(); + + @NotNull + Player getBukkitPlayer(); + + @NotNull + Map getCustomDataStore(); + + @NotNull + default BukkitMapPersister getMapPersister() { + return (BukkitHuskSync) getPlugin(); + } + + +} diff --git a/bukkit/src/main/java/net/william278/husksync/event/BukkitDataSaveEvent.java b/bukkit/src/main/java/net/william278/husksync/event/BukkitDataSaveEvent.java index 2a8ef3cd..4159dcba 100644 --- a/bukkit/src/main/java/net/william278/husksync/event/BukkitDataSaveEvent.java +++ b/bukkit/src/main/java/net/william278/husksync/event/BukkitDataSaveEvent.java @@ -19,9 +19,9 @@ package net.william278.husksync.event; -import net.william278.husksync.data.DataSaveCause; -import net.william278.husksync.data.UserData; -import net.william278.husksync.player.User; +import net.william278.husksync.HuskSync; +import net.william278.husksync.data.DataSnapshot; +import net.william278.husksync.user.User; import org.bukkit.event.Cancellable; import org.bukkit.event.HandlerList; import org.jetbrains.annotations.NotNull; @@ -29,16 +29,15 @@ import org.jetbrains.annotations.NotNull; @SuppressWarnings("unused") public class BukkitDataSaveEvent extends BukkitEvent implements DataSaveEvent, Cancellable { private static final HandlerList HANDLER_LIST = new HandlerList(); - private boolean cancelled = false; - private UserData userData; + private final HuskSync plugin; + private final DataSnapshot.Packed snapshot; private final User user; - private final DataSaveCause saveCause; + private boolean cancelled = false; - protected BukkitDataSaveEvent(@NotNull User user, @NotNull UserData userData, - @NotNull DataSaveCause saveCause) { + protected BukkitDataSaveEvent(@NotNull User user, @NotNull DataSnapshot.Packed snapshot, @NotNull HuskSync plugin) { this.user = user; - this.userData = userData; - this.saveCause = saveCause; + this.snapshot = snapshot; + this.plugin = plugin; } @Override @@ -58,18 +57,15 @@ public class BukkitDataSaveEvent extends BukkitEvent implements DataSaveEvent, C } @Override - public @NotNull UserData getUserData() { - return userData; - } - - @Override - public void setUserData(@NotNull UserData userData) { - this.userData = userData; + @NotNull + public DataSnapshot.Packed getData() { + return snapshot; } + @NotNull @Override - public @NotNull DataSaveCause getSaveCause() { - return saveCause; + public HuskSync getPlugin() { + return plugin; } @NotNull diff --git a/bukkit/src/main/java/net/william278/husksync/event/BukkitEvent.java b/bukkit/src/main/java/net/william278/husksync/event/BukkitEvent.java index 5e3a54e2..29ec1ccf 100644 --- a/bukkit/src/main/java/net/william278/husksync/event/BukkitEvent.java +++ b/bukkit/src/main/java/net/william278/husksync/event/BukkitEvent.java @@ -19,14 +19,10 @@ package net.william278.husksync.event; -import net.william278.husksync.BukkitHuskSync; -import org.bukkit.Bukkit; import org.bukkit.event.Event; import org.bukkit.event.HandlerList; import org.jetbrains.annotations.NotNull; -import java.util.concurrent.CompletableFuture; - @SuppressWarnings("unused") public abstract class BukkitEvent extends Event implements net.william278.husksync.event.Event { @@ -35,21 +31,6 @@ public abstract class BukkitEvent extends Event implements net.william278.husksy protected BukkitEvent() { } - @Override - public CompletableFuture fire() { - final CompletableFuture eventFireFuture = new CompletableFuture<>(); - // Don't fire events while the server is shutting down - if (!BukkitHuskSync.getInstance().isEnabled()) { - eventFireFuture.complete(this); - } else { - Bukkit.getScheduler().runTask(BukkitHuskSync.getInstance(), () -> { - Bukkit.getServer().getPluginManager().callEvent(this); - eventFireFuture.complete(this); - }); - } - return eventFireFuture; - } - @NotNull @Override public HandlerList getHandlers() { diff --git a/bukkit/src/main/java/net/william278/husksync/event/BukkitEventCannon.java b/bukkit/src/main/java/net/william278/husksync/event/BukkitEventCannon.java deleted file mode 100644 index 5bf3c9c5..00000000 --- a/bukkit/src/main/java/net/william278/husksync/event/BukkitEventCannon.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * This file is part of HuskSync, licensed under the Apache License 2.0. - * - * Copyright (c) William278 - * Copyright (c) contributors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.william278.husksync.event; - -import net.william278.husksync.data.DataSaveCause; -import net.william278.husksync.data.UserData; -import net.william278.husksync.player.BukkitPlayer; -import net.william278.husksync.player.OnlineUser; -import net.william278.husksync.player.User; -import org.jetbrains.annotations.NotNull; - -import java.util.concurrent.CompletableFuture; - -public class BukkitEventCannon extends EventCannon { - - public BukkitEventCannon() { - } - - @Override - public CompletableFuture firePreSyncEvent(@NotNull OnlineUser user, @NotNull UserData userData) { - return new BukkitPreSyncEvent(((BukkitPlayer) user).getPlayer(), userData).fire(); - } - - @Override - public CompletableFuture fireDataSaveEvent(@NotNull User user, @NotNull UserData userData, - @NotNull DataSaveCause saveCause) { - return new BukkitDataSaveEvent(user, userData, saveCause).fire(); - } - - @Override - public void fireSyncCompleteEvent(@NotNull OnlineUser user) { - new BukkitSyncCompleteEvent(((BukkitPlayer) user).getPlayer()).fire(); - } - -} diff --git a/bukkit/src/main/java/net/william278/husksync/event/BukkitEventDispatcher.java b/bukkit/src/main/java/net/william278/husksync/event/BukkitEventDispatcher.java new file mode 100644 index 00000000..28a78eae --- /dev/null +++ b/bukkit/src/main/java/net/william278/husksync/event/BukkitEventDispatcher.java @@ -0,0 +1,54 @@ +/* + * This file is part of HuskSync, licensed under the Apache License 2.0. + * + * Copyright (c) William278 + * Copyright (c) contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.william278.husksync.event; + +import net.william278.husksync.data.DataSnapshot; +import net.william278.husksync.user.OnlineUser; +import net.william278.husksync.user.User; +import org.bukkit.Bukkit; +import org.jetbrains.annotations.NotNull; + +public interface BukkitEventDispatcher extends EventDispatcher { + + @Override + default boolean fireIsCancelled(@NotNull T event) { + Bukkit.getPluginManager().callEvent((org.bukkit.event.Event) event); + return event instanceof Cancellable cancellable && cancellable.isCancelled(); + } + + @NotNull + @Override + default PreSyncEvent getPreSyncEvent(@NotNull OnlineUser user, @NotNull DataSnapshot.Packed data) { + return new BukkitPreSyncEvent(user, data, getPlugin()); + } + + @NotNull + @Override + default DataSaveEvent getDataSaveEvent(@NotNull User user, @NotNull DataSnapshot.Packed data) { + return new BukkitDataSaveEvent(user, data, getPlugin()); + } + + @NotNull + @Override + default SyncCompleteEvent getSyncCompleteEvent(@NotNull OnlineUser user) { + return new BukkitSyncCompleteEvent(user, getPlugin()); + } + +} diff --git a/bukkit/src/main/java/net/william278/husksync/event/BukkitPlayerEvent.java b/bukkit/src/main/java/net/william278/husksync/event/BukkitPlayerEvent.java index 8664a0f5..6b0df5bd 100644 --- a/bukkit/src/main/java/net/william278/husksync/event/BukkitPlayerEvent.java +++ b/bukkit/src/main/java/net/william278/husksync/event/BukkitPlayerEvent.java @@ -19,40 +19,25 @@ package net.william278.husksync.event; -import net.william278.husksync.BukkitHuskSync; -import net.william278.husksync.player.BukkitPlayer; -import net.william278.husksync.player.OnlineUser; -import org.bukkit.Bukkit; -import org.bukkit.entity.Player; +import net.william278.husksync.user.OnlineUser; import org.bukkit.event.HandlerList; import org.jetbrains.annotations.NotNull; -import java.util.concurrent.CompletableFuture; - @SuppressWarnings("unused") public abstract class BukkitPlayerEvent extends BukkitEvent implements PlayerEvent { private static final HandlerList HANDLER_LIST = new HandlerList(); - protected final Player player; + protected final OnlineUser player; - protected BukkitPlayerEvent(@NotNull Player player) { + protected BukkitPlayerEvent(@NotNull OnlineUser player) { this.player = player; } @Override + @NotNull public OnlineUser getUser() { - return BukkitPlayer.adapt(player); - } - - @Override - public CompletableFuture fire() { - final CompletableFuture eventFireFuture = new CompletableFuture<>(); - Bukkit.getScheduler().runTask(BukkitHuskSync.getInstance(), () -> { - Bukkit.getServer().getPluginManager().callEvent(this); - eventFireFuture.complete(this); - }); - return eventFireFuture; + return player; } @NotNull diff --git a/bukkit/src/main/java/net/william278/husksync/event/BukkitPreSyncEvent.java b/bukkit/src/main/java/net/william278/husksync/event/BukkitPreSyncEvent.java index a0ce94b8..9d5431e3 100644 --- a/bukkit/src/main/java/net/william278/husksync/event/BukkitPreSyncEvent.java +++ b/bukkit/src/main/java/net/william278/husksync/event/BukkitPreSyncEvent.java @@ -19,8 +19,9 @@ package net.william278.husksync.event; -import net.william278.husksync.data.UserData; -import org.bukkit.entity.Player; +import net.william278.husksync.HuskSync; +import net.william278.husksync.data.DataSnapshot; +import net.william278.husksync.user.OnlineUser; import org.bukkit.event.Cancellable; import org.bukkit.event.HandlerList; import org.jetbrains.annotations.NotNull; @@ -28,12 +29,14 @@ import org.jetbrains.annotations.NotNull; @SuppressWarnings("unused") public class BukkitPreSyncEvent extends BukkitPlayerEvent implements PreSyncEvent, Cancellable { private static final HandlerList HANDLER_LIST = new HandlerList(); + private final HuskSync plugin; + private final DataSnapshot.Packed data; private boolean cancelled = false; - private UserData userData; - protected BukkitPreSyncEvent(@NotNull Player player, @NotNull UserData userData) { + protected BukkitPreSyncEvent(@NotNull OnlineUser player, @NotNull DataSnapshot.Packed data, @NotNull HuskSync plugin) { super(player); - this.userData = userData; + this.data = data; + this.plugin = plugin; } @Override @@ -47,13 +50,15 @@ public class BukkitPreSyncEvent extends BukkitPlayerEvent implements PreSyncEven } @Override - public @NotNull UserData getUserData() { - return userData; + @NotNull + public DataSnapshot.Packed getData() { + return data; } + @NotNull @Override - public void setUserData(@NotNull UserData userData) { - this.userData = userData; + public HuskSync getPlugin() { + return plugin; } @NotNull diff --git a/bukkit/src/main/java/net/william278/husksync/event/BukkitSyncCompleteEvent.java b/bukkit/src/main/java/net/william278/husksync/event/BukkitSyncCompleteEvent.java index 18abd1b5..840c08c8 100644 --- a/bukkit/src/main/java/net/william278/husksync/event/BukkitSyncCompleteEvent.java +++ b/bukkit/src/main/java/net/william278/husksync/event/BukkitSyncCompleteEvent.java @@ -19,7 +19,8 @@ package net.william278.husksync.event; -import org.bukkit.entity.Player; +import net.william278.husksync.HuskSync; +import net.william278.husksync.user.OnlineUser; import org.bukkit.event.HandlerList; import org.jetbrains.annotations.NotNull; @@ -27,7 +28,7 @@ import org.jetbrains.annotations.NotNull; public class BukkitSyncCompleteEvent extends BukkitPlayerEvent implements SyncCompleteEvent { private static final HandlerList HANDLER_LIST = new HandlerList(); - protected BukkitSyncCompleteEvent(@NotNull Player player) { + protected BukkitSyncCompleteEvent(@NotNull OnlineUser player, @NotNull HuskSync plugin) { super(player); } diff --git a/bukkit/src/main/java/net/william278/husksync/listener/BukkitDeathEventListener.java b/bukkit/src/main/java/net/william278/husksync/listener/BukkitDeathEventListener.java index 5bb2db75..b6418a1e 100644 --- a/bukkit/src/main/java/net/william278/husksync/listener/BukkitDeathEventListener.java +++ b/bukkit/src/main/java/net/william278/husksync/listener/BukkitDeathEventListener.java @@ -19,7 +19,6 @@ package net.william278.husksync.listener; -import net.william278.husksync.config.Settings; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; @@ -28,25 +27,25 @@ import org.jetbrains.annotations.NotNull; public interface BukkitDeathEventListener extends Listener { - boolean handleEvent(@NotNull Settings.EventType type, @NotNull Settings.EventPriority priority); + boolean handleEvent(@NotNull EventListener.ListenerType type, @NotNull EventListener.Priority priority); @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) default void onPlayerDeathHighest(@NotNull PlayerDeathEvent event) { - if (handleEvent(Settings.EventType.DEATH_LISTENER, Settings.EventPriority.HIGHEST)) { + if (handleEvent(EventListener.ListenerType.DEATH_LISTENER, EventListener.Priority.HIGHEST)) { handlePlayerDeath(event); } } @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) default void onPlayerDeath(@NotNull PlayerDeathEvent event) { - if (handleEvent(Settings.EventType.DEATH_LISTENER, Settings.EventPriority.NORMAL)) { + if (handleEvent(EventListener.ListenerType.DEATH_LISTENER, EventListener.Priority.NORMAL)) { handlePlayerDeath(event); } } @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) default void onPlayerDeathLowest(@NotNull PlayerDeathEvent event) { - if (handleEvent(Settings.EventType.DEATH_LISTENER, Settings.EventPriority.LOWEST)) { + if (handleEvent(EventListener.ListenerType.DEATH_LISTENER, EventListener.Priority.LOWEST)) { handlePlayerDeath(event); } } diff --git a/bukkit/src/main/java/net/william278/husksync/listener/BukkitEventListener.java b/bukkit/src/main/java/net/william278/husksync/listener/BukkitEventListener.java index 516f6732..432a1b67 100644 --- a/bukkit/src/main/java/net/william278/husksync/listener/BukkitEventListener.java +++ b/bukkit/src/main/java/net/william278/husksync/listener/BukkitEventListener.java @@ -20,12 +20,10 @@ package net.william278.husksync.listener; import net.william278.husksync.BukkitHuskSync; -import net.william278.husksync.config.Settings; -import net.william278.husksync.data.BukkitInventoryMap; -import net.william278.husksync.data.BukkitSerializer; -import net.william278.husksync.data.ItemData; -import net.william278.husksync.player.BukkitPlayer; -import net.william278.husksync.player.OnlineUser; +import net.william278.husksync.HuskSync; +import net.william278.husksync.data.BukkitData; +import net.william278.husksync.user.BukkitUser; +import net.william278.husksync.user.OnlineUser; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.bukkit.entity.Projectile; @@ -46,12 +44,10 @@ import org.bukkit.event.player.PlayerDropItemEvent; import org.bukkit.event.player.PlayerInteractEntityEvent; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.event.world.WorldSaveEvent; -import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; import java.util.List; import java.util.Locale; -import java.util.concurrent.CompletableFuture; import java.util.stream.Collectors; public class BukkitEventListener extends EventListener implements BukkitJoinEventListener, BukkitQuitEventListener, @@ -65,54 +61,57 @@ public class BukkitEventListener extends EventListener implements BukkitJoinEven } @Override - public boolean handleEvent(@NotNull Settings.EventType type, @NotNull Settings.EventPriority priority) { + public boolean handleEvent(@NotNull ListenerType type, @NotNull Priority priority) { return plugin.getSettings().getEventPriority(type).equals(priority); } @Override - public void handlePlayerQuit(@NotNull BukkitPlayer bukkitPlayer) { - final Player player = bukkitPlayer.getPlayer(); - if (!bukkitPlayer.isLocked() && !player.getItemOnCursor().getType().isAir()) { + public void handlePlayerQuit(@NotNull BukkitUser bukkitUser) { + final Player player = bukkitUser.getPlayer(); + if (!bukkitUser.isLocked() && !player.getItemOnCursor().getType().isAir()) { player.getWorld().dropItem(player.getLocation(), player.getItemOnCursor()); player.setItemOnCursor(null); } - super.handlePlayerQuit(bukkitPlayer); + super.handlePlayerQuit(bukkitUser); } @Override - public void handlePlayerJoin(@NotNull BukkitPlayer bukkitPlayer) { - super.handlePlayerJoin(bukkitPlayer); + public void handlePlayerJoin(@NotNull BukkitUser bukkitUser) { + super.handlePlayerJoin(bukkitUser); } @Override public void handlePlayerDeath(@NotNull PlayerDeathEvent event) { - final OnlineUser user = BukkitPlayer.adapt(event.getEntity()); + final OnlineUser user = BukkitUser.adapt(event.getEntity(), plugin); // If the player is locked or the plugin disabling, clear their drops - if (cancelPlayerEvent(user.uuid)) { + if (cancelPlayerEvent(user.getUuid())) { event.getDrops().clear(); return; } // Handle saving player data snapshots on death - if (!plugin.getSettings().doSaveOnDeath()) return; + if (!plugin.getSettings().doSaveOnDeath()) { + return; + } - // Truncate the drops list to the inventory size and save the player's inventory - final int maxInventorySize = BukkitInventoryMap.INVENTORY_SLOT_COUNT; + // Truncate the dropped items list to the inventory size and save the player's inventory + final int maxInventorySize = BukkitData.Items.Inventory.INVENTORY_SLOT_COUNT; if (event.getDrops().size() > maxInventorySize) { event.getDrops().subList(maxInventorySize, event.getDrops().size()).clear(); } - BukkitSerializer.serializeItemStackArray(event.getDrops().toArray(new ItemStack[0])) - .thenAccept(serializedDrops -> super.saveOnPlayerDeath(user, new ItemData(serializedDrops))); + super.saveOnPlayerDeath(user, BukkitData.Items.ItemArray.adapt(event.getDrops())); } @EventHandler(ignoreCancelled = true) public void onWorldSave(@NotNull WorldSaveEvent event) { - // Handle saving player data snapshots when the world saves - if (!plugin.getSettings().doSaveOnWorldSave()) return; + if (!plugin.getSettings().doSaveOnWorldSave()) { + return; + } - CompletableFuture.runAsync(() -> super.saveOnWorldSave(event.getWorld().getPlayers() - .stream().map(BukkitPlayer::adapt) + // Handle saving player data snapshots when the world saves + plugin.runAsync(() -> super.saveOnWorldSave(event.getWorld().getPlayers() + .stream().map(player -> BukkitUser.adapt(player, plugin)) .collect(Collectors.toList()))); } @@ -186,12 +185,18 @@ public class BukkitEventListener extends EventListener implements BukkitJoinEven @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) public void onPermissionCommand(@NotNull PlayerCommandPreprocessEvent event) { - String[] commandArgs = event.getMessage().substring(1).split(" "); - String commandLabel = commandArgs[0].toLowerCase(Locale.ENGLISH); + final String[] commandArgs = event.getMessage().substring(1).split(" "); + final String commandLabel = commandArgs[0].toLowerCase(Locale.ENGLISH); if (blacklistedCommands.contains("*") || blacklistedCommands.contains(commandLabel)) { event.setCancelled(cancelPlayerEvent(event.getPlayer().getUniqueId())); } } + @NotNull + @Override + public HuskSync getPlugin() { + return plugin; + } + } diff --git a/bukkit/src/main/java/net/william278/husksync/listener/BukkitJoinEventListener.java b/bukkit/src/main/java/net/william278/husksync/listener/BukkitJoinEventListener.java index a2f69776..26144419 100644 --- a/bukkit/src/main/java/net/william278/husksync/listener/BukkitJoinEventListener.java +++ b/bukkit/src/main/java/net/william278/husksync/listener/BukkitJoinEventListener.java @@ -19,8 +19,8 @@ package net.william278.husksync.listener; -import net.william278.husksync.config.Settings; -import net.william278.husksync.player.BukkitPlayer; +import net.william278.husksync.HuskSync; +import net.william278.husksync.user.BukkitUser; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; @@ -29,29 +29,32 @@ import org.jetbrains.annotations.NotNull; public interface BukkitJoinEventListener extends Listener { - boolean handleEvent(@NotNull Settings.EventType type, @NotNull Settings.EventPriority priority); + boolean handleEvent(@NotNull EventListener.ListenerType type, @NotNull EventListener.Priority priority); @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) default void onPlayerJoinHighest(@NotNull PlayerJoinEvent event) { - if (handleEvent(Settings.EventType.JOIN_LISTENER, Settings.EventPriority.HIGHEST)) { - handlePlayerJoin(BukkitPlayer.adapt(event.getPlayer())); + if (handleEvent(EventListener.ListenerType.JOIN_LISTENER, EventListener.Priority.HIGHEST)) { + handlePlayerJoin(BukkitUser.adapt(event.getPlayer(), getPlugin())); } } @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) default void onPlayerJoin(@NotNull PlayerJoinEvent event) { - if (handleEvent(Settings.EventType.JOIN_LISTENER, Settings.EventPriority.NORMAL)) { - handlePlayerJoin(BukkitPlayer.adapt(event.getPlayer())); + if (handleEvent(EventListener.ListenerType.JOIN_LISTENER, EventListener.Priority.NORMAL)) { + handlePlayerJoin(BukkitUser.adapt(event.getPlayer(), getPlugin())); } } @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) default void onPlayerJoinLowest(@NotNull PlayerJoinEvent event) { - if (handleEvent(Settings.EventType.JOIN_LISTENER, Settings.EventPriority.LOWEST)) { - handlePlayerJoin(BukkitPlayer.adapt(event.getPlayer())); + if (handleEvent(EventListener.ListenerType.JOIN_LISTENER, EventListener.Priority.LOWEST)) { + handlePlayerJoin(BukkitUser.adapt(event.getPlayer(), getPlugin())); } } - void handlePlayerJoin(@NotNull BukkitPlayer player); + void handlePlayerJoin(@NotNull BukkitUser player); + + @NotNull + HuskSync getPlugin(); } diff --git a/bukkit/src/main/java/net/william278/husksync/listener/BukkitQuitEventListener.java b/bukkit/src/main/java/net/william278/husksync/listener/BukkitQuitEventListener.java index 133513f7..c0eec1c4 100644 --- a/bukkit/src/main/java/net/william278/husksync/listener/BukkitQuitEventListener.java +++ b/bukkit/src/main/java/net/william278/husksync/listener/BukkitQuitEventListener.java @@ -19,8 +19,8 @@ package net.william278.husksync.listener; -import net.william278.husksync.config.Settings; -import net.william278.husksync.player.BukkitPlayer; +import net.william278.husksync.HuskSync; +import net.william278.husksync.user.BukkitUser; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; @@ -29,29 +29,32 @@ import org.jetbrains.annotations.NotNull; public interface BukkitQuitEventListener extends Listener { - boolean handleEvent(@NotNull Settings.EventType type, @NotNull Settings.EventPriority priority); + boolean handleEvent(@NotNull EventListener.ListenerType type, @NotNull EventListener.Priority priority); @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) default void onPlayerQuitHighest(@NotNull PlayerQuitEvent event) { - if (handleEvent(Settings.EventType.QUIT_LISTENER, Settings.EventPriority.HIGHEST)) { - handlePlayerQuit(BukkitPlayer.adapt(event.getPlayer())); + if (handleEvent(EventListener.ListenerType.QUIT_LISTENER, EventListener.Priority.HIGHEST)) { + handlePlayerQuit(BukkitUser.adapt(event.getPlayer(), getPlugin())); } } @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) default void onPlayerQuit(@NotNull PlayerQuitEvent event) { - if (handleEvent(Settings.EventType.QUIT_LISTENER, Settings.EventPriority.NORMAL)) { - handlePlayerQuit(BukkitPlayer.adapt(event.getPlayer())); + if (handleEvent(EventListener.ListenerType.QUIT_LISTENER, EventListener.Priority.NORMAL)) { + handlePlayerQuit(BukkitUser.adapt(event.getPlayer(), getPlugin())); } } @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) default void onPlayerQuitLowest(@NotNull PlayerQuitEvent event) { - if (handleEvent(Settings.EventType.QUIT_LISTENER, Settings.EventPriority.LOWEST)) { - handlePlayerQuit(BukkitPlayer.adapt(event.getPlayer())); + if (handleEvent(EventListener.ListenerType.QUIT_LISTENER, EventListener.Priority.LOWEST)) { + handlePlayerQuit(BukkitUser.adapt(event.getPlayer(), getPlugin())); } } - void handlePlayerQuit(@NotNull BukkitPlayer player); + void handlePlayerQuit(@NotNull BukkitUser player); + + @NotNull + HuskSync getPlugin(); } diff --git a/bukkit/src/main/java/net/william278/husksync/migrator/LegacyMigrator.java b/bukkit/src/main/java/net/william278/husksync/migrator/LegacyMigrator.java index bd6e2335..5487d6e7 100644 --- a/bukkit/src/main/java/net/william278/husksync/migrator/LegacyMigrator.java +++ b/bukkit/src/main/java/net/william278/husksync/migrator/LegacyMigrator.java @@ -23,14 +23,16 @@ import com.zaxxer.hikari.HikariDataSource; import me.william278.husksync.bukkit.data.DataSerializer; import net.william278.hslmigrator.HSLConverter; import net.william278.husksync.HuskSync; -import net.william278.husksync.data.*; -import net.william278.husksync.player.User; +import net.william278.husksync.data.BukkitData; +import net.william278.husksync.data.Data; +import net.william278.husksync.data.DataSnapshot; +import net.william278.husksync.user.User; +import net.william278.husksync.util.BukkitLegacyConverter; import org.bukkit.Material; import org.bukkit.Statistic; import org.bukkit.entity.EntityType; import org.jetbrains.annotations.NotNull; -import java.io.IOException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; @@ -51,8 +53,6 @@ public class LegacyMigrator extends Migrator { private String sourcePlayersTable; private String sourceDataTable; - private final String minecraftVersion; - public LegacyMigrator(@NotNull HuskSync plugin) { super(plugin); this.hslConverter = HSLConverter.getInstance(); @@ -63,17 +63,16 @@ public class LegacyMigrator extends Migrator { this.sourceDatabase = plugin.getSettings().getMySqlDatabase(); this.sourcePlayersTable = "husksync_players"; this.sourceDataTable = "husksync_data"; - this.minecraftVersion = plugin.getMinecraftVersion().toString(); } @Override public CompletableFuture start() { plugin.log(Level.INFO, "Starting migration of legacy HuskSync v1.x data..."); final long startTime = System.currentTimeMillis(); - return CompletableFuture.supplyAsync(() -> { + return plugin.supplyAsync(() -> { // Wipe the existing database, preparing it for data import plugin.log(Level.INFO, "Preparing existing database (wiping)..."); - plugin.getDatabase().wipeDatabase().join(); + plugin.getDatabase().wipeDatabase(); plugin.log(Level.INFO, "Successfully wiped user data database (took " + (System.currentTimeMillis() - startTime) + "ms)"); // Create jdbc driver connection url @@ -135,23 +134,25 @@ public class LegacyMigrator extends Migrator { plugin.log(Level.INFO, "Converting HuskSync 1.x data to the new user data format (this might take a while)..."); final AtomicInteger playersConverted = new AtomicInteger(); - dataToMigrate.forEach(data -> data.toUserData(hslConverter, minecraftVersion).thenAccept(convertedData -> { - plugin.getDatabase().ensureUser(data.user()).thenRun(() -> - plugin.getDatabase().setUserData(data.user(), convertedData, DataSaveCause.LEGACY_MIGRATION) - .exceptionally(exception -> { - plugin.log(Level.SEVERE, "Failed to migrate legacy data for " + data.user().username + ": " + exception.getMessage()); - return null; - })).join(); + dataToMigrate.forEach(data -> { + final DataSnapshot.Packed convertedData = data.toUserData(hslConverter, plugin); + plugin.getDatabase().ensureUser(data.user()); + try { + plugin.getDatabase().addSnapshot(data.user(), convertedData); + } catch (Throwable e) { + plugin.log(Level.SEVERE, "Failed to migrate legacy data for " + data.user().getUsername() + ": " + e.getMessage()); + return; + } playersConverted.getAndIncrement(); if (playersConverted.get() % 50 == 0) { plugin.log(Level.INFO, "Converted legacy data for " + playersConverted + " players..."); } - }).join()); + }); plugin.log(Level.INFO, "Migration complete for " + dataToMigrate.size() + " users in " + ((System.currentTimeMillis() - startTime) / 1000) + " seconds!"); return true; - } catch (Exception e) { - plugin.log(Level.SEVERE, "Error while migrating legacy data: " + e.getMessage() + " - are your source database credentials correct?"); + } catch (Throwable e) { + plugin.log(Level.SEVERE, "Error while migrating legacy data: " + e.getMessage() + " - are your source database credentials correct?", e); return false; } }); @@ -197,10 +198,10 @@ public class LegacyMigrator extends Migrator { }) { plugin.log(Level.INFO, getHelpMenu()); plugin.log(Level.INFO, "Successfully set " + args[0] + " to " + - obfuscateDataString(args[1])); + obfuscateDataString(args[1])); } else { plugin.log(Level.INFO, "Invalid operation, could not set " + args[0] + " to " + - obfuscateDataString(args[1]) + " (is it a valid option?)"); + obfuscateDataString(args[1]) + " (is it a valid option?)"); } } else { plugin.log(Level.INFO, getHelpMenu()); @@ -227,11 +228,11 @@ public class LegacyMigrator extends Migrator { This will migrate all user data from HuskSync v1.x to HuskSync v2.x's new format. To perform the migration, please follow the steps below carefully. - + [!] Existing data in the database will be wiped. [!] - + STEP 1] Please ensure no players are on any servers. - + STEP 2] HuskSync will need to connect to the database used to hold the existing, legacy HuskSync data. If this is the same database as the one you are @@ -251,12 +252,12 @@ public class LegacyMigrator extends Migrator { using the command: "husksync migrate legacy set " (e.g.: "husksync migrate legacy set host 1.2.3.4") - + STEP 3] HuskSync will migrate data into the database tables configures in the config.yml file of this server. Please make sure you're happy with this before proceeding. - + STEP 4] To start the migration, please run: "husksync migrate legacy start" """.replaceAll(Pattern.quote("%source_host%"), obfuscateDataString(sourceHost)) @@ -277,54 +278,69 @@ public class LegacyMigrator extends Migrator { @NotNull String serializedAdvancements, @NotNull String serializedLocation) { @NotNull - public CompletableFuture toUserData(@NotNull HSLConverter converter, - @NotNull String minecraftVersion) { - return CompletableFuture.supplyAsync(() -> { - try { - final DataSerializer.StatisticData legacyStatisticData = converter - .deserializeStatisticData(serializedStatistics); - final StatisticsData convertedStatisticData = new StatisticsData( - convertStatisticMap(legacyStatisticData.untypedStatisticValues()), - convertMaterialStatisticMap(legacyStatisticData.blockStatisticValues()), - convertMaterialStatisticMap(legacyStatisticData.itemStatisticValues()), - convertEntityStatisticMap(legacyStatisticData.entityStatisticValues())); - - final List convertedAdvancements = converter - .deserializeAdvancementData(serializedAdvancements) - .stream().map(data -> new AdvancementData(data.key(), data.criteriaMap())).toList(); - - final DataSerializer.PlayerLocation legacyLocationData = converter - .deserializePlayerLocationData(serializedLocation); - final LocationData convertedLocationData = new LocationData( - legacyLocationData == null ? "world" : legacyLocationData.worldName(), - UUID.randomUUID(), - "NORMAL", - legacyLocationData == null ? 0d : legacyLocationData.x(), - legacyLocationData == null ? 64d : legacyLocationData.y(), - legacyLocationData == null ? 0d : legacyLocationData.z(), - legacyLocationData == null ? 90f : legacyLocationData.yaw(), - legacyLocationData == null ? 180f : legacyLocationData.pitch()); - - return UserData.builder(minecraftVersion) - .setStatus(new StatusData(health, maxHealth, healthScale, hunger, saturation, - saturationExhaustion, selectedSlot, totalExp, expLevel, expProgress, gameMode, isFlying)) - .setInventory(new ItemData(serializedInventory)) - .setEnderChest(new ItemData(serializedEnderChest)) - .setPotionEffects(new PotionEffectData(serializedPotionEffects)) - .setAdvancements(convertedAdvancements) - .setStatistics(convertedStatisticData) - .setLocation(convertedLocationData) - .build(); - } catch (IOException e) { - throw new RuntimeException(e); - } - }); + public DataSnapshot.Packed toUserData(@NotNull HSLConverter converter, @NotNull HuskSync plugin) { + try { + final DataSerializer.StatisticData stats = converter.deserializeStatisticData(serializedStatistics); + final DataSerializer.PlayerLocation loc = converter.deserializePlayerLocationData(serializedLocation); + final BukkitLegacyConverter adapter = (BukkitLegacyConverter) plugin.getLegacyConverter() + .orElseThrow(() -> new IllegalStateException("Legacy converter not present")); + + return DataSnapshot.builder(plugin) + // Inventory + .inventory(BukkitData.Items.Inventory.from( + adapter.deserializeLegacyItemStacks(serializedInventory), + selectedSlot + )) + + // Ender chest + .enderChest(BukkitData.Items.EnderChest.adapt( + adapter.deserializeLegacyItemStacks(serializedEnderChest) + )) + + // Location + .location(BukkitData.Location.from( + loc == null ? 0d : loc.x(), + loc == null ? 64d : loc.y(), + loc == null ? 0d : loc.z(), + loc == null ? 90f : loc.yaw(), + loc == null ? 180f : loc.pitch(), + new Data.Location.World( + loc == null ? "world" : loc.worldName(), + UUID.randomUUID(), "NORMAL" + ))) + + // Advancements + .advancements(BukkitData.Advancements.from(converter + .deserializeAdvancementData(serializedAdvancements).stream() + .map(data -> Data.Advancements.Advancement.adapt(data.key(), data.criteriaMap())) + .toList())) + + // Stats + .statistics(BukkitData.Statistics.from( + BukkitData.Statistics.createStatisticsMap( + convertStatisticMap(stats.untypedStatisticValues()), + convertMaterialStatisticMap(stats.blockStatisticValues()), + convertMaterialStatisticMap(stats.itemStatisticValues()), + convertEntityStatisticMap(stats.entityStatisticValues()) + ))) + + // Health, hunger, experience & game mode + .health(BukkitData.Health.from(health, maxHealth, healthScale)) + .hunger(BukkitData.Hunger.from(hunger, saturation, saturationExhaustion)) + .experience(BukkitData.Experience.from(totalExp, expLevel, expProgress)) + .gameMode(BukkitData.GameMode.from(gameMode, isFlying, isFlying)) + + // Build & pack into new format + .saveCause(DataSnapshot.SaveCause.LEGACY_MIGRATION).buildAndPack(); + } catch (Throwable e) { + throw new IllegalStateException(e); + } } private Map convertStatisticMap(@NotNull HashMap rawMap) { final HashMap convertedMap = new HashMap<>(); for (Map.Entry entry : rawMap.entrySet()) { - convertedMap.put(entry.getKey().toString(), entry.getValue()); + convertedMap.put(entry.getKey().getKey().toString(), entry.getValue()); } return convertedMap; } @@ -333,8 +349,8 @@ public class LegacyMigrator extends Migrator { final Map> convertedMap = new HashMap<>(); for (Map.Entry> entry : rawMap.entrySet()) { for (Map.Entry materialEntry : entry.getValue().entrySet()) { - convertedMap.computeIfAbsent(entry.getKey().toString(), k -> new HashMap<>()) - .put(materialEntry.getKey().toString(), materialEntry.getValue()); + convertedMap.computeIfAbsent(entry.getKey().getKey().toString(), k -> new HashMap<>()) + .put(materialEntry.getKey().getKey().toString(), materialEntry.getValue()); } } return convertedMap; @@ -344,8 +360,8 @@ public class LegacyMigrator extends Migrator { final Map> convertedMap = new HashMap<>(); for (Map.Entry> entry : rawMap.entrySet()) { for (Map.Entry materialEntry : entry.getValue().entrySet()) { - convertedMap.computeIfAbsent(entry.getKey().toString(), k -> new HashMap<>()) - .put(materialEntry.getKey().toString(), materialEntry.getValue()); + convertedMap.computeIfAbsent(entry.getKey().getKey().toString(), k -> new HashMap<>()) + .put(materialEntry.getKey().getKey().toString(), materialEntry.getValue()); } } return convertedMap; diff --git a/bukkit/src/main/java/net/william278/husksync/migrator/MpdbMigrator.java b/bukkit/src/main/java/net/william278/husksync/migrator/MpdbMigrator.java index 8b929c88..c039d13b 100644 --- a/bukkit/src/main/java/net/william278/husksync/migrator/MpdbMigrator.java +++ b/bukkit/src/main/java/net/william278/husksync/migrator/MpdbMigrator.java @@ -21,30 +21,28 @@ package net.william278.husksync.migrator; import com.zaxxer.hikari.HikariDataSource; import net.william278.husksync.BukkitHuskSync; -import net.william278.husksync.data.*; -import net.william278.husksync.player.User; +import net.william278.husksync.HuskSync; +import net.william278.husksync.data.BukkitData; +import net.william278.husksync.data.DataSnapshot; +import net.william278.husksync.user.User; import net.william278.mpdbconverter.MPDBConverter; import org.bukkit.Bukkit; import org.bukkit.event.inventory.InventoryType; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; -import org.bukkit.plugin.Plugin; import org.jetbrains.annotations.NotNull; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; -import java.util.ArrayList; -import java.util.List; -import java.util.Locale; -import java.util.UUID; +import java.util.*; import java.util.concurrent.CompletableFuture; import java.util.concurrent.atomic.AtomicInteger; import java.util.logging.Level; import java.util.regex.Pattern; /** - * A migrator for migrating MySQLPlayerDataBridge data to HuskSync {@link UserData} + * A migrator for migrating MySQLPlayerDataBridge data to HuskSync {@link DataSnapshot}s */ public class MpdbMigrator extends Migrator { @@ -57,11 +55,13 @@ public class MpdbMigrator extends Migrator { private String sourceInventoryTable; private String sourceEnderChestTable; private String sourceExperienceTable; - private final String minecraftVersion; - public MpdbMigrator(@NotNull BukkitHuskSync plugin, @NotNull Plugin mySqlPlayerDataBridge) { + public MpdbMigrator(@NotNull BukkitHuskSync plugin) { super(plugin); - this.mpdbConverter = MPDBConverter.getInstance(mySqlPlayerDataBridge); + this.mpdbConverter = MPDBConverter.getInstance(Objects.requireNonNull( + Bukkit.getPluginManager().getPlugin("MySQLPlayerDataBridge"), + "MySQLPlayerDataBridge dependency not found!" + )); this.sourceHost = plugin.getSettings().getMySqlHost(); this.sourcePort = plugin.getSettings().getMySqlPort(); this.sourceUsername = plugin.getSettings().getMySqlUsername(); @@ -70,7 +70,6 @@ public class MpdbMigrator extends Migrator { this.sourceInventoryTable = "mpdb_inventory"; this.sourceEnderChestTable = "mpdb_enderchest"; this.sourceExperienceTable = "mpdb_experience"; - this.minecraftVersion = plugin.getMinecraftVersion().toString(); } @@ -78,10 +77,10 @@ public class MpdbMigrator extends Migrator { public CompletableFuture start() { plugin.log(Level.INFO, "Starting migration from MySQLPlayerDataBridge to HuskSync..."); final long startTime = System.currentTimeMillis(); - return CompletableFuture.supplyAsync(() -> { + return plugin.supplyAsync(() -> { // Wipe the existing database, preparing it for data import plugin.log(Level.INFO, "Preparing existing database (wiping)..."); - plugin.getDatabase().wipeDatabase().join(); + plugin.getDatabase().wipeDatabase(); plugin.log(Level.INFO, "Successfully wiped user data database (took " + (System.currentTimeMillis() - startTime) + "ms)"); // Create jdbc driver connection url @@ -133,18 +132,15 @@ public class MpdbMigrator extends Migrator { plugin.log(Level.INFO, "Converting raw MySQLPlayerDataBridge data to HuskSync user data (this might take a while)..."); final AtomicInteger playersConverted = new AtomicInteger(); - dataToMigrate.forEach(data -> data.toUserData(mpdbConverter, minecraftVersion).thenAccept(convertedData -> { - plugin.getDatabase().ensureUser(data.user()).thenRun(() -> - plugin.getDatabase().setUserData(data.user(), convertedData, DataSaveCause.MPDB_MIGRATION)) - .exceptionally(exception -> { - plugin.log(Level.SEVERE, "Failed to migrate MySQLPlayerDataBridge data for " + data.user().username + ": " + exception.getMessage()); - return null; - }).join(); + dataToMigrate.forEach(data -> { + final DataSnapshot.Packed convertedData = data.toUserData(mpdbConverter, plugin); + plugin.getDatabase().ensureUser(data.user()); + plugin.getDatabase().addSnapshot(data.user(), convertedData); playersConverted.getAndIncrement(); if (playersConverted.get() % 50 == 0) { plugin.log(Level.INFO, "Converted MySQLPlayerDataBridge data for " + playersConverted + " players..."); } - }).join()); + }); plugin.log(Level.INFO, "Migration complete for " + dataToMigrate.size() + " users in " + ((System.currentTimeMillis() - startTime) / 1000) + " seconds!"); return true; } catch (Exception e) { @@ -198,10 +194,10 @@ public class MpdbMigrator extends Migrator { }) { plugin.log(Level.INFO, getHelpMenu()); plugin.log(Level.INFO, "Successfully set " + args[0] + " to " + - obfuscateDataString(args[1])); + obfuscateDataString(args[1])); } else { plugin.log(Level.INFO, "Invalid operation, could not set " + args[0] + " to " + - obfuscateDataString(args[1]) + " (is it a valid option?)"); + obfuscateDataString(args[1]) + " (is it a valid option?)"); } } else { plugin.log(Level.INFO, getHelpMenu()); @@ -227,14 +223,14 @@ public class MpdbMigrator extends Migrator { === MySQLPlayerDataBridge Migration Wizard ========== This will migrate inventories, ender chests and XP from the MySQLPlayerDataBridge plugin to HuskSync. - + To prevent excessive migration times, other non-vital data will not be transferred. - + [!] Existing data in the database will be wiped. [!] - + STEP 1] Please ensure no players are on any servers. - + STEP 2] HuskSync will need to connect to the database used to hold the source MySQLPlayerDataBridge data. Please check these database parameters are OK: @@ -250,12 +246,12 @@ public class MpdbMigrator extends Migrator { using the command: "husksync migrate mpdb set " (e.g.: "husksync migrate mpdb set host 1.2.3.4") - + STEP 3] HuskSync will migrate data into the database tables configures in the config.yml file of this server. Please make sure you're happy with this before proceeding. - + STEP 4] To start the migration, please run: "husksync migrate mpdb start" """.replaceAll(Pattern.quote("%source_host%"), obfuscateDataString(sourceHost)) @@ -279,38 +275,43 @@ public class MpdbMigrator extends Migrator { * @param expProgress The player's current XP progress * @param totalExp The player's total XP score */ - private record MpdbData(@NotNull User user, @NotNull String serializedInventory, - @NotNull String serializedArmor, @NotNull String serializedEnderChest, - int expLevel, float expProgress, int totalExp) { + private record MpdbData( + @NotNull User user, + @NotNull String serializedInventory, + @NotNull String serializedArmor, + @NotNull String serializedEnderChest, + int expLevel, + float expProgress, + int totalExp + ) { + /** - * Converts exported MySQLPlayerDataBridge data into HuskSync's {@link UserData} object format + * Converts exported MySQLPlayerDataBridge data into HuskSync's {@link DataSnapshot} object format * * @param converter The {@link MPDBConverter} to use for converting to {@link ItemStack}s - * @return A {@link CompletableFuture} that will resolve to the converted {@link UserData} object + * @return A {@link CompletableFuture} that will resolve to the converted {@link DataSnapshot} object */ @NotNull - public CompletableFuture toUserData(@NotNull MPDBConverter converter, - @NotNull String minecraftVersion) { - return CompletableFuture.supplyAsync(() -> { - // Combine inventory and armour - final Inventory inventory = Bukkit.createInventory(null, InventoryType.PLAYER); - inventory.setContents(converter.getItemStackFromSerializedData(serializedInventory)); - final ItemStack[] armor = converter.getItemStackFromSerializedData(serializedArmor).clone(); - for (int i = 36; i < 36 + armor.length; i++) { - inventory.setItem(i, armor[i - 36]); - } + public DataSnapshot.Packed toUserData(@NotNull MPDBConverter converter, @NotNull HuskSync plugin) { + // Combine inventory and armor + final Inventory inventory = Bukkit.createInventory(null, InventoryType.PLAYER); + inventory.setContents(converter.getItemStackFromSerializedData(serializedInventory)); + final ItemStack[] armor = converter.getItemStackFromSerializedData(serializedArmor).clone(); + for (int i = 36; i < 36 + armor.length; i++) { + inventory.setItem(i, armor[i - 36]); + } + final ItemStack[] enderChest = converter.getItemStackFromSerializedData(serializedEnderChest); - // Create user data record - return UserData.builder(minecraftVersion) - .setStatus(new StatusData(20, 20, 0, 20, 10, - 1, 0, totalExp, expLevel, expProgress, "SURVIVAL", - false)) - .setInventory(new ItemData(BukkitSerializer.serializeItemStackArray(inventory.getContents()).join())) - .setEnderChest(new ItemData(BukkitSerializer.serializeItemStackArray(converter - .getItemStackFromSerializedData(serializedEnderChest)).join())) - .build(); - }); + // Create user data record + return DataSnapshot.builder(plugin) + .inventory(BukkitData.Items.Inventory.from(inventory.getContents(), 0)) + .enderChest(BukkitData.Items.EnderChest.adapt(enderChest)) + .experience(BukkitData.Experience.from(totalExp, expLevel, expProgress)) + .gameMode(BukkitData.GameMode.from("SURVIVAL", false, false)) + .saveCause(DataSnapshot.SaveCause.MPDB_MIGRATION) + .buildAndPack(); } + } } diff --git a/bukkit/src/main/java/net/william278/husksync/player/BukkitPlayer.java b/bukkit/src/main/java/net/william278/husksync/player/BukkitPlayer.java deleted file mode 100644 index a44beb13..00000000 --- a/bukkit/src/main/java/net/william278/husksync/player/BukkitPlayer.java +++ /dev/null @@ -1,655 +0,0 @@ -/* - * This file is part of HuskSync, licensed under the Apache License 2.0. - * - * Copyright (c) William278 - * Copyright (c) contributors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.william278.husksync.player; - -import de.themoep.minedown.adventure.MineDown; -import dev.triumphteam.gui.builder.gui.StorageBuilder; -import dev.triumphteam.gui.guis.Gui; -import dev.triumphteam.gui.guis.StorageGui; -import net.kyori.adventure.audience.Audience; -import net.roxeez.advancement.display.FrameType; -import net.william278.andjam.Toast; -import net.william278.desertwell.util.Version; -import net.william278.husksync.BukkitHuskSync; -import net.william278.husksync.config.Settings; -import net.william278.husksync.data.*; -import org.bukkit.*; -import org.bukkit.advancement.Advancement; -import org.bukkit.advancement.AdvancementProgress; -import org.bukkit.attribute.Attribute; -import org.bukkit.entity.EntityType; -import org.bukkit.entity.Player; -import org.bukkit.event.inventory.InventoryType; -import org.bukkit.event.player.PlayerTeleportEvent; -import org.bukkit.inventory.Inventory; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.PlayerInventory; -import org.bukkit.persistence.PersistentDataContainer; -import org.bukkit.potion.PotionEffect; -import org.bukkit.potion.PotionEffectType; -import org.jetbrains.annotations.NotNull; - -import java.util.*; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicReference; -import java.util.logging.Level; - -/** - * Bukkit implementation of an {@link OnlineUser} - */ -public class BukkitPlayer extends OnlineUser { - - private final BukkitHuskSync plugin; - private final Player player; - - private BukkitPlayer(@NotNull Player player) { - super(player.getUniqueId(), player.getName()); - this.plugin = BukkitHuskSync.getInstance(); - this.player = player; - } - - @NotNull - public static BukkitPlayer adapt(@NotNull Player player) { - return new BukkitPlayer(player); - } - - public Player getPlayer() { - return player; - } - - @Override - public CompletableFuture getStatus() { - return CompletableFuture.supplyAsync(() -> { - final double maxHealth = getMaxHealth(player); - return new StatusData(Math.min(player.getHealth(), maxHealth), - maxHealth, - player.isHealthScaled() ? player.getHealthScale() : 0d, - player.getFoodLevel(), - player.getSaturation(), - player.getExhaustion(), - player.getInventory().getHeldItemSlot(), - player.getTotalExperience(), - player.getLevel(), - player.getExp(), - player.getGameMode().name(), - player.getAllowFlight() && player.isFlying()); - }); - } - - @Override - public CompletableFuture setStatus(@NotNull StatusData statusData, @NotNull Settings settings) { - return CompletableFuture.runAsync(() -> { - // Set max health - double currentMaxHealth = Objects.requireNonNull(player.getAttribute(Attribute.GENERIC_MAX_HEALTH)).getBaseValue(); - if (settings.getSynchronizationFeature(Settings.SynchronizationFeature.MAX_HEALTH)) { - if (statusData.maxHealth != 0d) { - Objects.requireNonNull(player.getAttribute(Attribute.GENERIC_MAX_HEALTH)) - .setBaseValue(statusData.maxHealth); - currentMaxHealth = statusData.maxHealth; - } - } - if (settings.getSynchronizationFeature(Settings.SynchronizationFeature.HEALTH)) { - // Set health - final double currentHealth = player.getHealth(); - if (statusData.health != currentHealth) { - final double healthToSet = currentHealth > currentMaxHealth ? currentMaxHealth : statusData.health; - final double maxHealth = currentMaxHealth; - Bukkit.getScheduler().runTask(plugin, () -> { - try { - player.setHealth(Math.min(healthToSet, maxHealth)); - } catch (IllegalArgumentException e) { - plugin.getLogger().log(Level.WARNING, - "Failed to set health of player " + player.getName() + " to " + healthToSet); - } - }); - } - - // Set health scale - try { - if (statusData.healthScale != 0d) { - player.setHealthScale(statusData.healthScale); - } else { - player.setHealthScale(statusData.maxHealth); - } - player.setHealthScaled(statusData.healthScale != 0D); - } catch (IllegalArgumentException e) { - plugin.getLogger().log(Level.WARNING, - "Failed to set health scale of player " + player.getName() + " to " + statusData.healthScale); - } - } - if (settings.getSynchronizationFeature(Settings.SynchronizationFeature.HUNGER)) { - player.setFoodLevel(statusData.hunger); - player.setSaturation(statusData.saturation); - player.setExhaustion(statusData.saturationExhaustion); - } - if (settings.getSynchronizationFeature(Settings.SynchronizationFeature.INVENTORIES)) { - player.getInventory().setHeldItemSlot(statusData.selectedItemSlot); - } - if (settings.getSynchronizationFeature(Settings.SynchronizationFeature.EXPERIENCE)) { - player.setTotalExperience(statusData.totalExperience); - player.setLevel(statusData.expLevel); - player.setExp(statusData.expProgress); - } - if (settings.getSynchronizationFeature(Settings.SynchronizationFeature.GAME_MODE)) { - Bukkit.getScheduler().runTask(plugin, () -> - player.setGameMode(GameMode.valueOf(statusData.gameMode))); - } - if (settings.getSynchronizationFeature(Settings.SynchronizationFeature.LOCATION)) { - Bukkit.getScheduler().runTask(plugin, () -> { - if (statusData.isFlying) { - player.setAllowFlight(true); - player.setFlying(true); - } - player.setFlying(false); - }); - } - }); - } - - @Override - public CompletableFuture getInventory() { - final PlayerInventory inventory = player.getInventory(); - if (inventory.isEmpty()) { - return CompletableFuture.completedFuture(ItemData.empty()); - } - return BukkitSerializer.serializeItemStackArray(inventory.getContents()) - .thenApply(ItemData::new); - } - - @Override - public CompletableFuture setInventory(@NotNull ItemData itemData) { - return BukkitSerializer.deserializeInventory(itemData.serializedItems).thenApplyAsync(contents -> { - final CompletableFuture inventorySetFuture = new CompletableFuture<>(); - Bukkit.getScheduler().runTask(plugin, () -> { - this.clearInventoryCraftingSlots(); - player.setItemOnCursor(null); - player.getInventory().setContents(contents.getContents()); - player.updateInventory(); - inventorySetFuture.complete(null); - }); - return inventorySetFuture.join(); - }); - } - - // Clears any items the player may have in the crafting slots of their inventory - private void clearInventoryCraftingSlots() { - final Inventory inventory = player.getOpenInventory().getTopInventory(); - if (inventory.getType() == InventoryType.CRAFTING) { - for (int slot = 0; slot < 5; slot++) { - inventory.setItem(slot, null); - } - } - } - - @Override - public CompletableFuture getEnderChest() { - final Inventory enderChest = player.getEnderChest(); - if (enderChest.isEmpty()) { - return CompletableFuture.completedFuture(ItemData.empty()); - } - return BukkitSerializer.serializeItemStackArray(enderChest.getContents()) - .thenApply(ItemData::new); - } - - @Override - public CompletableFuture setEnderChest(@NotNull ItemData enderChestData) { - return BukkitSerializer.deserializeItemStackArray(enderChestData.serializedItems).thenApplyAsync(contents -> { - final CompletableFuture enderChestSetFuture = new CompletableFuture<>(); - Bukkit.getScheduler().runTask(plugin, () -> { - player.getEnderChest().setContents(contents); - enderChestSetFuture.complete(null); - }); - return enderChestSetFuture.join(); - }); - } - - @Override - public CompletableFuture getPotionEffects() { - return BukkitSerializer.serializePotionEffectArray(player.getActivePotionEffects() - .toArray(new PotionEffect[0])).thenApply(PotionEffectData::new); - } - - @Override - public CompletableFuture setPotionEffects(@NotNull PotionEffectData potionEffectData) { - return BukkitSerializer.deserializePotionEffectArray(potionEffectData.serializedPotionEffects) - .thenApplyAsync(effects -> { - final CompletableFuture potionEffectsSetFuture = new CompletableFuture<>(); - Bukkit.getScheduler().runTask(plugin, () -> { - for (PotionEffect effect : player.getActivePotionEffects()) { - player.removePotionEffect(effect.getType()); - } - for (PotionEffect effect : effects) { - player.addPotionEffect(effect); - } - potionEffectsSetFuture.complete(null); - }); - return potionEffectsSetFuture.join(); - }); - } - - @Override - public CompletableFuture> getAdvancements() { - return CompletableFuture.supplyAsync(() -> { - final Iterator serverAdvancements = Bukkit.getServer().advancementIterator(); - final ArrayList advancementData = new ArrayList<>(); - - // Iterate through the server advancement set and add all advancements to the list - serverAdvancements.forEachRemaining(advancement -> { - final AdvancementProgress advancementProgress = player.getAdvancementProgress(advancement); - final Map awardedCriteria = new HashMap<>(); - - advancementProgress.getAwardedCriteria().forEach(criteriaKey -> awardedCriteria.put(criteriaKey, - advancementProgress.getDateAwarded(criteriaKey))); - - // Only save the advancement if criteria has been completed - if (!awardedCriteria.isEmpty()) { - advancementData.add(new AdvancementData(advancement.getKey().toString(), awardedCriteria)); - } - }); - return advancementData; - }); - } - - @Override - public CompletableFuture setAdvancements(@NotNull List advancementData) { - return CompletableFuture.runAsync(() -> Bukkit.getScheduler().runTask(plugin, () -> { - - // Temporarily disable advancement announcing if needed - boolean announceAdvancementUpdate = false; - if (Boolean.TRUE.equals(player.getWorld().getGameRuleValue(GameRule.ANNOUNCE_ADVANCEMENTS))) { - player.getWorld().setGameRule(GameRule.ANNOUNCE_ADVANCEMENTS, false); - announceAdvancementUpdate = true; - } - final boolean finalAnnounceAdvancementUpdate = announceAdvancementUpdate; - - // Save current experience and level - final int experienceLevel = player.getLevel(); - final float expProgress = player.getExp(); - - // Determines whether the experience might have changed warranting an update - final AtomicBoolean correctExperience = new AtomicBoolean(false); - - // Run asynchronously as advancement setting is expensive - CompletableFuture.runAsync(() -> { - // Apply the advancements to the player - final Iterator serverAdvancements = Bukkit.getServer().advancementIterator(); - while (serverAdvancements.hasNext()) { - // Iterate through all advancements - final Advancement advancement = serverAdvancements.next(); - final AdvancementProgress playerProgress = player.getAdvancementProgress(advancement); - - advancementData.stream().filter(record -> record.key.equals(advancement.getKey().toString())).findFirst().ifPresentOrElse( - // Award all criteria that the player does not have that they do on the cache - record -> { - record.completedCriteria.keySet().stream() - .filter(criterion -> !playerProgress.getAwardedCriteria().contains(criterion)) - .forEach(criterion -> { - Bukkit.getScheduler().runTask(plugin, - () -> player.getAdvancementProgress(advancement).awardCriteria(criterion)); - correctExperience.set(true); - }); - - // Revoke all criteria that the player does have but should not - new ArrayList<>(playerProgress.getAwardedCriteria()).stream().filter(criterion -> !record.completedCriteria.containsKey(criterion)) - .forEach(criterion -> Bukkit.getScheduler().runTask(plugin, - () -> player.getAdvancementProgress(advancement).revokeCriteria(criterion))); - - }, - // Revoke the criteria as the player shouldn't have any - () -> new ArrayList<>(playerProgress.getAwardedCriteria()).forEach(criterion -> - Bukkit.getScheduler().runTask(plugin, - () -> player.getAdvancementProgress(advancement).revokeCriteria(criterion)))); - - // Update the player's experience in case the advancement changed that - if (correctExperience.get()) { - player.setLevel(experienceLevel); - player.setExp(expProgress); - correctExperience.set(false); - } - } - - // Re-enable announcing advancements (back on main thread again) - Bukkit.getScheduler().runTask(plugin, () -> { - if (finalAnnounceAdvancementUpdate) { - player.getWorld().setGameRule(GameRule.ANNOUNCE_ADVANCEMENTS, true); - } - }); - }); - })); - } - - @Override - public CompletableFuture getStatistics() { - return CompletableFuture.supplyAsync(() -> { - final Map untypedStatisticValues = new HashMap<>(); - final Map> blockStatisticValues = new HashMap<>(); - final Map> itemStatisticValues = new HashMap<>(); - final Map> entityStatisticValues = new HashMap<>(); - - for (Statistic statistic : Statistic.values()) { - switch (statistic.getType()) { - case ITEM -> { - final Map itemValues = new HashMap<>(); - Arrays.stream(Material.values()).filter(Material::isItem) - .filter(itemMaterial -> (player.getStatistic(statistic, itemMaterial)) != 0) - .forEach(itemMaterial -> itemValues.put(itemMaterial.name(), - player.getStatistic(statistic, itemMaterial))); - if (!itemValues.isEmpty()) { - itemStatisticValues.put(statistic.name(), itemValues); - } - } - case BLOCK -> { - final Map blockValues = new HashMap<>(); - Arrays.stream(Material.values()).filter(Material::isBlock) - .filter(blockMaterial -> (player.getStatistic(statistic, blockMaterial)) != 0) - .forEach(blockMaterial -> blockValues.put(blockMaterial.name(), - player.getStatistic(statistic, blockMaterial))); - if (!blockValues.isEmpty()) { - blockStatisticValues.put(statistic.name(), blockValues); - } - } - case ENTITY -> { - final Map entityValues = new HashMap<>(); - Arrays.stream(EntityType.values()).filter(EntityType::isAlive) - .filter(entityType -> (player.getStatistic(statistic, entityType)) != 0) - .forEach(entityType -> entityValues.put(entityType.name(), - player.getStatistic(statistic, entityType))); - if (!entityValues.isEmpty()) { - entityStatisticValues.put(statistic.name(), entityValues); - } - } - case UNTYPED -> { - if (player.getStatistic(statistic) != 0) { - untypedStatisticValues.put(statistic.name(), player.getStatistic(statistic)); - } - } - } - } - - return new StatisticsData(untypedStatisticValues, blockStatisticValues, - itemStatisticValues, entityStatisticValues); - }); - } - - @Override - public CompletableFuture setStatistics(@NotNull StatisticsData statisticsData) { - return CompletableFuture.runAsync(() -> { - // Set generic statistics - for (String statistic : statisticsData.untypedStatistics.keySet()) { - try { - player.setStatistic(Statistic.valueOf(statistic), statisticsData.untypedStatistics.get(statistic)); - } catch (IllegalArgumentException e) { - plugin.getLogger().log(Level.WARNING, - "Failed to set generic statistic " + statistic + " for " + username); - } - } - - // Set block statistics - for (String statistic : statisticsData.blockStatistics.keySet()) { - for (String blockMaterial : statisticsData.blockStatistics.get(statistic).keySet()) { - try { - player.setStatistic(Statistic.valueOf(statistic), Material.valueOf(blockMaterial), - statisticsData.blockStatistics.get(statistic).get(blockMaterial)); - } catch (IllegalArgumentException e) { - plugin.getLogger().log(Level.WARNING, - "Failed to set " + blockMaterial + " statistic " + statistic + " for " + username); - } - } - } - - // Set item statistics - for (String statistic : statisticsData.itemStatistics.keySet()) { - for (String itemMaterial : statisticsData.itemStatistics.get(statistic).keySet()) { - try { - player.setStatistic(Statistic.valueOf(statistic), Material.valueOf(itemMaterial), - statisticsData.itemStatistics.get(statistic).get(itemMaterial)); - } catch (IllegalArgumentException e) { - plugin.getLogger().log(Level.WARNING, - "Failed to set " + itemMaterial + " statistic " + statistic + " for " + username); - } - } - } - - // Set entity statistics - for (String statistic : statisticsData.entityStatistics.keySet()) { - for (String entityType : statisticsData.entityStatistics.get(statistic).keySet()) { - try { - player.setStatistic(Statistic.valueOf(statistic), EntityType.valueOf(entityType), - statisticsData.entityStatistics.get(statistic).get(entityType)); - } catch (IllegalArgumentException e) { - plugin.getLogger().log(Level.WARNING, - "Failed to set " + entityType + " statistic " + statistic + " for " + username); - } - } - } - }); - } - - @Override - public CompletableFuture getLocation() { - return CompletableFuture.supplyAsync(() -> - new LocationData(player.getWorld().getName(), player.getWorld().getUID(), player.getWorld().getEnvironment().name(), - player.getLocation().getX(), player.getLocation().getY(), player.getLocation().getZ(), - player.getLocation().getYaw(), player.getLocation().getPitch())); - } - - @Override - public CompletableFuture setLocation(@NotNull LocationData locationData) { - final CompletableFuture teleportFuture = new CompletableFuture<>(); - AtomicReference bukkitWorld = new AtomicReference<>(Bukkit.getWorld(locationData.worldName)); - if (bukkitWorld.get() == null) { - bukkitWorld.set(Bukkit.getWorld(locationData.worldUuid)); - } - if (bukkitWorld.get() == null) { - Bukkit.getWorlds().stream().filter(world -> world.getEnvironment() == World.Environment - .valueOf(locationData.worldEnvironment)).findFirst().ifPresent(bukkitWorld::set); - } - if (bukkitWorld.get() != null) { - Bukkit.getScheduler().runTask(plugin, () -> { - player.teleport(new Location(bukkitWorld.get(), - locationData.x, locationData.y, locationData.z, - locationData.yaw, locationData.pitch), PlayerTeleportEvent.TeleportCause.PLUGIN); - teleportFuture.complete(null); - }); - } - return teleportFuture; - } - - @Override - public CompletableFuture getPersistentDataContainer() { - final Map> persistentDataMap = new HashMap<>(); - final PersistentDataContainer container = player.getPersistentDataContainer(); - return CompletableFuture.supplyAsync(() -> { - container.getKeys().forEach(key -> { - BukkitPersistentTypeMapping type = null; - for (BukkitPersistentTypeMapping dataType : BukkitPersistentTypeMapping.PRIMITIVE_TYPE_MAPPINGS) { - if (container.has(key, dataType.bukkitType())) { - type = dataType; - break; - } - } - if (type != null) { - persistentDataMap.put(key.toString(), type.getContainerValue(container, key)); - } - }); - return new PersistentDataContainerData(persistentDataMap); - }).exceptionally(throwable -> { - plugin.log(Level.WARNING, - "Could not read " + player.getName() + "'s persistent data map, skipping!"); - throwable.printStackTrace(); - return new PersistentDataContainerData(new HashMap<>()); - }); - } - - @Override - public CompletableFuture setPersistentDataContainer(@NotNull PersistentDataContainerData container) { - return CompletableFuture.runAsync(() -> { - player.getPersistentDataContainer().getKeys().forEach(namespacedKey -> - player.getPersistentDataContainer().remove(namespacedKey)); - container.getTags().forEach(keyString -> { - final NamespacedKey key = NamespacedKey.fromString(keyString); - if (key != null) { - container.getTagType(keyString) - .flatMap(BukkitPersistentTypeMapping::getMapping) - .ifPresentOrElse(mapping -> mapping.setContainerValue(container, player, key), - () -> plugin.log(Level.WARNING, - "Could not set " + player.getName() + "'s persistent data key " + keyString + - " as it has an invalid type. Skipping!")); - } - }); - }).exceptionally(throwable -> { - plugin.log(Level.WARNING, - "Could not write " + player.getName() + "'s persistent data map, skipping!"); - throwable.printStackTrace(); - return null; - }); - } - - - @Override - @NotNull - public Audience getAudience() { - return plugin.getAudiences().player(player); - } - - @Override - public boolean isOffline() { - try { - return player == null; - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @NotNull - @Override - public Version getMinecraftVersion() { - return Version.fromString(Bukkit.getBukkitVersion()); - } - - @Override - public boolean hasPermission(@NotNull String node) { - return player.hasPermission(node); - } - - @Override - public CompletableFuture> showMenu(@NotNull ItemData itemData, boolean editable, - int minimumRows, @NotNull MineDown title) { - final CompletableFuture> updatedData = new CompletableFuture<>(); - - // Deserialize the item data to be shown and show it in a triumph GUI - BukkitSerializer.deserializeItemStackArray(itemData.serializedItems).thenAccept(items -> { - // Build the GUI and populate with items - final int itemCount = items.length; - final StorageBuilder guiBuilder = Gui.storage() - .title(title.toComponent()) - .rows(Math.max(minimumRows, (int) Math.ceil(itemCount / 9.0))) - .disableAllInteractions() - .enableOtherActions(); - final StorageGui gui = editable ? guiBuilder.enableAllInteractions().create() : guiBuilder.create(); - for (int i = 0; i < itemCount; i++) { - if (items[i] != null) { - gui.getInventory().setItem(i, items[i]); - } - } - - // Complete the future with updated data (if editable) when the GUI is closed - gui.setCloseGuiAction(event -> { - if (!editable) { - updatedData.complete(Optional.empty()); - return; - } - - // Get and save the updated items - final ItemStack[] updatedItems = Arrays.copyOf(event.getPlayer().getOpenInventory() - .getTopInventory().getContents().clone(), itemCount); - BukkitSerializer.serializeItemStackArray(updatedItems).thenAccept(serializedItems -> { - if (serializedItems.equals(itemData.serializedItems)) { - updatedData.complete(Optional.empty()); - return; - } - updatedData.complete(Optional.of(new ItemData(serializedItems))); - }); - }); - - // Display the GUI (synchronously; on the main server thread) - Bukkit.getScheduler().runTask(plugin, () -> gui.open(player)); - }).exceptionally(throwable -> { - // Handle exceptions - updatedData.completeExceptionally(throwable); - return null; - }); - return updatedData; - } - - @Override - public boolean isDead() { - return player.getHealth() <= 0; - } - - @Override - public void sendToast(@NotNull MineDown title, @NotNull MineDown description, - @NotNull String iconMaterial, @NotNull String backgroundType) { - try { - final Material material = Material.matchMaterial(iconMaterial); - Toast.builder(plugin) - .setTitle(title.toComponent()) - .setDescription(description.toComponent()) - .setIcon(material != null ? material : Material.BARRIER) - .setFrameType(FrameType.valueOf(backgroundType)) - .build() - .show(player); - } catch (Exception e) { - e.printStackTrace(); - } - } - - /** - * Returns a {@link Player}'s maximum health, minus any health boost effects - * - * @param player The {@link Player} to get the maximum health of - * @return The {@link Player}'s max health - */ - private static double getMaxHealth(@NotNull Player player) { - double maxHealth = Objects.requireNonNull(player.getAttribute(Attribute.GENERIC_MAX_HEALTH)).getBaseValue(); - - // If the player has additional health bonuses from synchronised potion effects, subtract these from this number as they are synchronised separately - if (player.hasPotionEffect(PotionEffectType.HEALTH_BOOST) && maxHealth > 20D) { - PotionEffect healthBoostEffect = player.getPotionEffect(PotionEffectType.HEALTH_BOOST); - assert healthBoostEffect != null; - double healthBoostBonus = 4 * (healthBoostEffect.getAmplifier() + 1); - maxHealth -= healthBoostBonus; - } - return maxHealth; - } - - @Override - public boolean isLocked() { - return plugin.getLockedPlayers().contains(player.getUniqueId()); - } - - @Override - public boolean isNpc() { - return player.hasMetadata("NPC"); - } - -} diff --git a/bukkit/src/main/java/net/william278/husksync/user/BukkitUser.java b/bukkit/src/main/java/net/william278/husksync/user/BukkitUser.java new file mode 100644 index 00000000..27c07d36 --- /dev/null +++ b/bukkit/src/main/java/net/william278/husksync/user/BukkitUser.java @@ -0,0 +1,152 @@ +/* + * This file is part of HuskSync, licensed under the Apache License 2.0. + * + * Copyright (c) William278 + * Copyright (c) contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.william278.husksync.user; + +import de.themoep.minedown.adventure.MineDown; +import dev.triumphteam.gui.builder.gui.StorageBuilder; +import dev.triumphteam.gui.guis.Gui; +import dev.triumphteam.gui.guis.StorageGui; +import net.kyori.adventure.audience.Audience; +import net.roxeez.advancement.display.FrameType; +import net.william278.andjam.Toast; +import net.william278.husksync.BukkitHuskSync; +import net.william278.husksync.HuskSync; +import net.william278.husksync.data.BukkitData; +import net.william278.husksync.data.BukkitUserDataHolder; +import net.william278.husksync.data.Data; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.ApiStatus; +import org.jetbrains.annotations.NotNull; + +import java.util.Arrays; +import java.util.function.Consumer; +import java.util.logging.Level; + +/** + * Bukkit platform implementation of an {@link OnlineUser} + */ +public class BukkitUser extends OnlineUser implements BukkitUserDataHolder { + + private final HuskSync plugin; + private final Player player; + + private BukkitUser(@NotNull Player player, @NotNull HuskSync plugin) { + super(player.getUniqueId(), player.getName()); + this.player = player; + this.plugin = plugin; + } + + @NotNull + @ApiStatus.Internal + public static BukkitUser adapt(@NotNull Player player, @NotNull HuskSync plugin) { + return new BukkitUser(player, plugin); + } + + /** + * Get the Bukkit {@link Player} instance of this user + * + * @return the {@link Player} instance + * @since 3.0 + */ + @NotNull + public Player getPlayer() { + return player; + } + + @Override + public boolean isOffline() { + return player == null || !player.isOnline(); + } + + @NotNull + @Override + public Audience getAudience() { + return ((BukkitHuskSync) plugin).getAudiences().player(player); + } + + @Override + public void sendToast(@NotNull MineDown title, @NotNull MineDown description, + @NotNull String iconMaterial, @NotNull String backgroundType) { + try { + final Material material = Material.matchMaterial(iconMaterial); + Toast.builder((BukkitHuskSync) plugin) + .setTitle(title.toComponent()) + .setDescription(description.toComponent()) + .setIcon(material != null ? material : Material.BARRIER) + .setFrameType(FrameType.valueOf(backgroundType)) + .build() + .show(player); + } catch (Throwable e) { + plugin.log(Level.WARNING, "Failed to send toast to player " + player.getName(), e); + } + } + + @Override + public void showGui(@NotNull Data.Items items, @NotNull MineDown title, boolean editable, int size, + @NotNull Consumer onClose) { + final ItemStack[] contents = ((BukkitData.Items) items).getContents(); + final StorageBuilder builder = Gui.storage().rows((int) Math.ceil(size / 9.0d)); + if (!editable) { + builder.disableAllInteractions(); + } + final StorageGui gui = builder.enableOtherActions() + .apply(a -> a.getInventory().setContents(contents)) + .title(title.toComponent()).create(); + gui.setCloseGuiAction((close) -> onClose.accept(BukkitData.Items.ItemArray.adapt( + Arrays.stream(close.getInventory().getContents()).limit(size).toArray(ItemStack[]::new) + ))); + plugin.runSync(() -> gui.open(player)); + } + + @Override + public boolean hasPermission(@NotNull String node) { + return player.hasPermission(node); + } + + @Override + public boolean isDead() { + return player.getHealth() <= 0; + } + + @Override + public boolean isLocked() { + return plugin.getLockedPlayers().contains(player.getUniqueId()); + } + + @Override + public boolean isNpc() { + return player.hasMetadata("NPC"); + } + + @NotNull + @Override + public Player getBukkitPlayer() { + return player; + } + + @NotNull + @Override + @ApiStatus.Internal + public HuskSync getPlugin() { + return plugin; + } +} diff --git a/bukkit/src/main/java/net/william278/husksync/util/BukkitLegacyConverter.java b/bukkit/src/main/java/net/william278/husksync/util/BukkitLegacyConverter.java new file mode 100644 index 00000000..56be8c18 --- /dev/null +++ b/bukkit/src/main/java/net/william278/husksync/util/BukkitLegacyConverter.java @@ -0,0 +1,279 @@ +/* + * This file is part of HuskSync, licensed under the Apache License 2.0. + * + * Copyright (c) William278 + * Copyright (c) contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.william278.husksync.util; + +import net.william278.husksync.HuskSync; +import net.william278.husksync.adapter.DataAdapter; +import net.william278.husksync.data.BukkitData; +import net.william278.husksync.data.Data; +import net.william278.husksync.data.DataSnapshot; +import net.william278.husksync.data.Identifier; +import org.bukkit.Material; +import org.bukkit.Statistic; +import org.bukkit.entity.EntityType; +import org.bukkit.inventory.ItemStack; +import org.bukkit.util.io.BukkitObjectInputStream; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.json.JSONArray; +import org.json.JSONObject; +import org.yaml.snakeyaml.external.biz.base64Coder.Base64Coder; + +import java.io.ByteArrayInputStream; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.*; + +public class BukkitLegacyConverter extends LegacyConverter { + + public BukkitLegacyConverter(@NotNull HuskSync plugin) { + super(plugin); + } + + @NotNull + @Override + public DataSnapshot.Packed convert(@NotNull byte[] data) throws DataAdapter.AdaptionException { + final JSONObject object = new JSONObject(plugin.getDataAdapter().bytesToString(data)); + final int version = object.getInt("format_version"); + if (version != 3) { + throw new DataAdapter.AdaptionException(String.format( + "Unsupported legacy data format version: %s. Please downgrade to an earlier version of HuskSync, " + + "perform a manual legacy migration, then attempt to upgrade again.", version + )); + } + + // Read legacy data from the JSON object + final DataSnapshot.Builder builder = DataSnapshot.builder(plugin) + .saveCause(DataSnapshot.SaveCause.CONVERTED_FROM_V2) + .data(readStatusData(object)); + readInventory(object).ifPresent(builder::inventory); + readEnderChest(object).ifPresent(builder::enderChest); + readLocation(object).ifPresent(builder::location); + readAdvancements(object).ifPresent(builder::advancements); + readStatistics(object).ifPresent(builder::statistics); + return builder.buildAndPack(); + } + + @NotNull + private Map readStatusData(@NotNull JSONObject object) { + if (!object.has("status_data")) { + return Map.of(); + } + + final JSONObject status = object.getJSONObject("status_data"); + final HashMap containers = new HashMap<>(); + if (shouldImport(Identifier.HEALTH)) { + containers.put(Identifier.HEALTH, BukkitData.Health.from( + status.getDouble("health"), + status.getDouble("max_health"), + status.getDouble("health_scale") + )); + } + if (shouldImport(Identifier.HUNGER)) { + containers.put(Identifier.HUNGER, BukkitData.Hunger.from( + status.getInt("hunger"), + status.getFloat("saturation"), + status.getFloat("saturation_exhaustion") + )); + } + if (shouldImport(Identifier.EXPERIENCE)) { + containers.put(Identifier.EXPERIENCE, BukkitData.Experience.from( + status.getInt("total_experience"), + status.getInt("experience_level"), + status.getFloat("experience_progress") + )); + } + if (shouldImport(Identifier.GAME_MODE)) { + containers.put(Identifier.GAME_MODE, BukkitData.GameMode.from( + status.getString("game_mode"), + status.getBoolean("is_flying"), + status.getBoolean("is_flying") + )); + } + return containers; + } + + @NotNull + private Optional readInventory(@NotNull JSONObject object) { + if (!object.has("inventory") || !shouldImport(Identifier.INVENTORY)) { + return Optional.empty(); + } + + final JSONObject inventoryData = object.getJSONObject("inventory"); + return Optional.of(BukkitData.Items.Inventory.from( + deserializeLegacyItemStacks(inventoryData.getString("serialized_items")), 0 + )); + } + + @NotNull + private Optional readEnderChest(@NotNull JSONObject object) { + if (!object.has("ender_chest") || !shouldImport(Identifier.ENDER_CHEST)) { + return Optional.empty(); + } + + final JSONObject inventoryData = object.getJSONObject("ender_chest"); + return Optional.of(BukkitData.Items.EnderChest.adapt( + deserializeLegacyItemStacks(inventoryData.getString("serialized_items")) + )); + } + + @NotNull + private Optional readLocation(@NotNull JSONObject object) { + if (!object.has("location") || !shouldImport(Identifier.LOCATION)) { + return Optional.empty(); + } + + final JSONObject locationData = object.getJSONObject("location"); + return Optional.of(BukkitData.Location.from( + locationData.getDouble("x"), + locationData.getDouble("y"), + locationData.getDouble("z"), + locationData.getFloat("yaw"), + locationData.getFloat("pitch"), + new Data.Location.World( + locationData.getString("world_name"), + UUID.fromString(locationData.getString("world_uuid")), + locationData.getString("world_environment") + ) + )); + } + + @NotNull + private Optional readAdvancements(@NotNull JSONObject object) { + if (!object.has("advancements") || !shouldImport(Identifier.ADVANCEMENTS)) { + return Optional.empty(); + } + + final JSONArray advancements = object.getJSONArray("advancements"); + final List converted = new ArrayList<>(); + advancements.iterator().forEachRemaining(o -> { + final JSONObject advancement = (JSONObject) JSONObject.wrap(o); + final String key = advancement.getString("key"); + + final JSONObject criteria = advancement.getJSONObject("completed_criteria"); + final Map criteriaMap = new LinkedHashMap<>(); + criteria.keys().forEachRemaining(criteriaKey -> criteriaMap.put( + criteriaKey, parseDate(criteria.getString(criteriaKey))) + ); + converted.add(Data.Advancements.Advancement.adapt(key, criteriaMap)); + }); + + return Optional.of(BukkitData.Advancements.from(converted)); + } + + @NotNull + private Optional readStatistics(@NotNull JSONObject object) { + if (!object.has("statistics") || !shouldImport(Identifier.ADVANCEMENTS)) { + return Optional.empty(); + } + + final JSONObject stats = object.getJSONObject("statistics"); + return Optional.of(readStatisticMaps( + stats.getJSONObject("untyped_statistics"), + stats.getJSONObject("block_statistics"), + stats.getJSONObject("item_statistics"), + stats.getJSONObject("entity_statistics") + )); + } + + @NotNull + private BukkitData.Statistics readStatisticMaps(@NotNull JSONObject untyped, @NotNull JSONObject blocks, + @NotNull JSONObject items, @NotNull JSONObject entities) { + final Map genericStats = new HashMap<>(); + untyped.keys().forEachRemaining(stat -> genericStats.put(Statistic.valueOf(stat), untyped.getInt(stat))); + + final Map> blockStats = new HashMap<>(); + blocks.keys().forEachRemaining(stat -> { + final JSONObject blockStat = blocks.getJSONObject(stat); + final Map blockMap = new HashMap<>(); + blockStat.keys().forEachRemaining(block -> blockMap.put(Material.valueOf(block), blockStat.getInt(block))); + blockStats.put(Statistic.valueOf(stat), blockMap); + }); + + final Map> itemStats = new HashMap<>(); + items.keys().forEachRemaining(stat -> { + final JSONObject itemStat = items.getJSONObject(stat); + final Map itemMap = new HashMap<>(); + itemStat.keys().forEachRemaining(item -> itemMap.put(Material.valueOf(item), itemStat.getInt(item))); + itemStats.put(Statistic.valueOf(stat), itemMap); + }); + + final Map> entityStats = new HashMap<>(); + entities.keys().forEachRemaining(stat -> { + final JSONObject entityStat = entities.getJSONObject(stat); + final Map entityMap = new HashMap<>(); + entityStat.keys().forEachRemaining(entity -> entityMap.put(EntityType.valueOf(entity), entityStat.getInt(entity))); + entityStats.put(Statistic.valueOf(stat), entityMap); + }); + + return BukkitData.Statistics.from(genericStats, blockStats, itemStats, entityStats); + } + + // Deserialize a legacy item stack array + @NotNull + public ItemStack[] deserializeLegacyItemStacks(@NotNull String items) { + // Return an empty array if there is no inventory data (set the player as having an empty inventory) + if (items.isEmpty()) { + return new ItemStack[0]; + } + + // Create a byte input stream to read the serialized data + try (ByteArrayInputStream byteInputStream = new ByteArrayInputStream(Base64Coder.decodeLines(items))) { + try (BukkitObjectInputStream bukkitInputStream = new BukkitObjectInputStream(byteInputStream)) { + // Read the length of the Bukkit input stream and set the length of the array to this value + final ItemStack[] inventoryContents = new ItemStack[bukkitInputStream.readInt()]; + + // Set the ItemStacks in the array from deserialized ItemStack data + int slotIndex = 0; + for (ItemStack ignored : inventoryContents) { + final ItemStack deserialized = deserializeLegacyItemStack(bukkitInputStream.readObject()); + inventoryContents[slotIndex] = deserialized; + slotIndex++; + } + + // Return the converted contents + return inventoryContents; + } + } catch (Throwable e) { + throw new DataAdapter.AdaptionException("Failed to deserialize legacy item stack data", e); + } + } + + // Deserialize a single legacy item stack + @Nullable + private static ItemStack deserializeLegacyItemStack(@Nullable Object serializedItemStack) { + return serializedItemStack != null ? ItemStack.deserialize((Map) serializedItemStack) : null; + } + + + private boolean shouldImport(@NotNull Identifier type) { + return plugin.getSettings().isSyncFeatureEnabled(type); + } + + @NotNull + private Date parseDate(@NotNull String dateString) { + try { + return new SimpleDateFormat().parse(dateString); + } catch (ParseException e) { + return new Date(); + } + } + +} diff --git a/bukkit/src/main/java/net/william278/husksync/util/BukkitMapPersister.java b/bukkit/src/main/java/net/william278/husksync/util/BukkitMapPersister.java new file mode 100644 index 00000000..aa98fd9b --- /dev/null +++ b/bukkit/src/main/java/net/william278/husksync/util/BukkitMapPersister.java @@ -0,0 +1,378 @@ +/* + * This file is part of HuskSync, licensed under the Apache License 2.0. + * + * Copyright (c) William278 + * Copyright (c) contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.william278.husksync.util; + +import de.tr7zw.changeme.nbtapi.NBT; +import de.tr7zw.changeme.nbtapi.iface.ReadWriteNBT; +import de.tr7zw.changeme.nbtapi.iface.ReadableNBT; +import net.william278.husksync.HuskSync; +import net.william278.mapdataapi.MapBanner; +import net.william278.mapdataapi.MapData; +import org.bukkit.Bukkit; +import org.bukkit.Material; +import org.bukkit.World; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.MapMeta; +import org.bukkit.map.*; +import org.jetbrains.annotations.ApiStatus; +import org.jetbrains.annotations.NotNull; + +import java.awt.*; +import java.util.List; +import java.util.*; +import java.util.function.Function; +import java.util.logging.Level; + +public interface BukkitMapPersister { + + // The map used to store HuskSync data in ItemStack NBT + String MAP_DATA_KEY = "husksync:persisted_locked_map"; + // The key used to store the serialized map data in NBT + String MAP_PIXEL_DATA_KEY = "canvas_data"; + // The key used to store the map of World UIDs to MapView IDs in NBT + String MAP_VIEW_ID_MAPPINGS_KEY = "id_mappings"; + + /** + * Persist locked maps in an array of {@link ItemStack}s + * + * @param items the array of {@link ItemStack}s to persist locked maps in + * @param delegateRenderer the player to delegate the rendering of map pixel canvases to + * @return the array of {@link ItemStack}s with locked maps persisted to serialized NBT + */ + @NotNull + default ItemStack[] persistLockedMaps(@NotNull ItemStack[] items, @NotNull Player delegateRenderer) { + if (!getPlugin().getSettings().doPersistLockedMaps()) { + return items; + } + return forEachMap(items, map -> this.persistMapView(map, delegateRenderer)); + } + + /** + * Apply persisted locked maps to an array of {@link ItemStack}s + * + * @param items the array of {@link ItemStack}s to apply persisted locked maps to + * @return the array of {@link ItemStack}s with persisted locked maps applied + */ + @NotNull + default ItemStack[] setMapViews(@NotNull ItemStack[] items) { + if (!getPlugin().getSettings().doPersistLockedMaps()) { + return items; + } + return forEachMap(items, this::applyMapView); + } + + // Perform an operation on each map in an array of ItemStacks + @NotNull + private ItemStack[] forEachMap(@NotNull ItemStack[] items, @NotNull Function function) { + for (int i = 0; i < items.length; i++) { + final ItemStack item = items[i]; + if (item == null) { + continue; + } + if (item.getType() == Material.FILLED_MAP && item.hasItemMeta()) { + items[i] = function.apply(item); + } + } + return items; + } + + @NotNull + private ItemStack persistMapView(@NotNull ItemStack map, @NotNull Player delegateRenderer) { + final MapMeta meta = Objects.requireNonNull((MapMeta) map.getItemMeta()); + if (!meta.hasMapView()) { + return map; + } + final MapView view = meta.getMapView(); + if (view == null || view.getWorld() == null || !view.isLocked() || view.isVirtual()) { + return map; + } + + NBT.modify(map, nbt -> { + // Don't save the map's data twice + if (nbt.hasTag(MAP_DATA_KEY)) { + return; + } + + // Render the map + final PersistentMapCanvas canvas = new PersistentMapCanvas(view); + for (MapRenderer renderer : view.getRenderers()) { + renderer.render(view, canvas, delegateRenderer); + getPlugin().debug(String.format("Rendered locked map canvas to view (#%s)", view.getId())); + } + + // Persist map data + final ReadWriteNBT mapData = nbt.getOrCreateCompound(MAP_DATA_KEY); + final String worldUid = view.getWorld().getUID().toString(); + mapData.setByteArray(MAP_PIXEL_DATA_KEY, canvas.extractMapData().toBytes()); + nbt.getOrCreateCompound(MAP_VIEW_ID_MAPPINGS_KEY).setInteger(worldUid, view.getId()); + getPlugin().debug(String.format("Saved data for locked map (#%s, UID: %s)", view.getId(), worldUid)); + }); + return map; + } + + @NotNull + private ItemStack applyMapView(@NotNull ItemStack map) { + final MapMeta meta = Objects.requireNonNull((MapMeta) map.getItemMeta()); + NBT.get(map, nbt -> { + if (!nbt.hasTag(MAP_DATA_KEY)) { + return nbt; + } + final ReadableNBT mapData = nbt.getCompound(MAP_DATA_KEY); + + // Search for an existing map view + final ReadableNBT mapIds = nbt.getCompound(MAP_VIEW_ID_MAPPINGS_KEY); + Optional world = Optional.empty(); + for (String worldUid : mapIds.getKeys()) { + world = Bukkit.getWorlds().stream() + .map(w -> w.getUID().toString()).filter(u -> u.equals(worldUid)) + .findFirst(); + if (world.isPresent()) { + break; + } + } + if (world.isPresent()) { + final String uid = world.get(); + final Optional existingView = this.getMapView(mapIds.getInteger(uid)); + if (existingView.isPresent()) { + final MapView view = existingView.get(); + view.setLocked(true); + meta.setMapView(view); + map.setItemMeta(meta); + getPlugin().debug(String.format("View exists (#%s); updated map (UID: %s)", view.getId(), uid)); + return nbt; + } + } + + // Read the pixel data and generate a map view otherwise + final MapData canvasData; + try { + getPlugin().debug("Deserializing map data from NBT and generating view..."); + canvasData = MapData.fromByteArray(mapData.getByteArray(MAP_PIXEL_DATA_KEY)); + } catch (Throwable e) { + getPlugin().log(Level.WARNING, "Failed to deserialize map data from NBT", e); + return nbt; + } + + // Add a renderer to the map with the data + final MapView view = generateRenderedMap(canvasData); + final String worldUid = getDefaultMapWorld().getUID().toString(); + meta.setMapView(view); + map.setItemMeta(meta); + + // Set the map view ID in NBT + NBT.modify(map, editable -> { + editable.getCompound(MAP_VIEW_ID_MAPPINGS_KEY).setInteger(worldUid, view.getId()); + }); + getPlugin().debug(String.format("Generated view (#%s) and updated map (UID: %s)", view.getId(), worldUid)); + return nbt; + }); + return map; + } + + // Sets the renderer of a map, and returns the generated MapView + @NotNull + private MapView generateRenderedMap(@NotNull MapData canvasData) { + final MapView view = Bukkit.createMap(getDefaultMapWorld()); + view.getRenderers().clear(); + + // Create a new map view renderer with the map data color at each pixel + view.addRenderer(new PersistentMapRenderer(canvasData)); + view.setLocked(true); + view.setScale(MapView.Scale.NORMAL); + view.setTrackingPosition(false); + view.setUnlimitedTracking(false); + + // Set the view to the map and return it + setMapView(view); + return view; + } + + @NotNull + private static World getDefaultMapWorld() { + final World world = Bukkit.getWorlds().get(0); + if (world == null) { + throw new IllegalStateException("No worlds are loaded on the server!"); + } + return world; + } + + default Optional getMapView(int id) { + return getMapViews().containsKey(id) ? Optional.of(getMapViews().get(id)) : Optional.empty(); + } + + default void setMapView(@NotNull MapView view) { + getMapViews().put(view.getId(), view); + } + + /** + * A {@link MapRenderer} that can be used to render persistently serialized {@link MapData} to a {@link MapView} + */ + class PersistentMapRenderer extends MapRenderer { + + private final MapData canvasData; + + private PersistentMapRenderer(@NotNull MapData canvasData) { + super(false); + this.canvasData = canvasData; + } + + @Override + public void render(@NotNull MapView map, @NotNull MapCanvas canvas, @NotNull Player player) { + // We set the pixels in this order to avoid the map being rendered upside down + for (int i = 0; i < 128; i++) { + for (int j = 0; j < 128; j++) { + canvas.setPixel(j, i, (byte) canvasData.getColorAt(i, j)); + } + } + + // Set the map banners and markers + final MapCursorCollection cursors = canvas.getCursors(); + canvasData.getBanners().forEach(banner -> cursors.addCursor(createBannerCursor(banner))); + canvas.setCursors(cursors); + } + } + + @NotNull + private static MapCursor createBannerCursor(@NotNull MapBanner banner) { + return new MapCursor( + (byte) banner.getPosition().getX(), + (byte) banner.getPosition().getZ(), + (byte) 0, + switch (banner.getColor().toLowerCase(Locale.ENGLISH)) { + case "white" -> MapCursor.Type.BANNER_WHITE; + case "orange" -> MapCursor.Type.BANNER_ORANGE; + case "magenta" -> MapCursor.Type.BANNER_MAGENTA; + case "light_blue" -> MapCursor.Type.BANNER_LIGHT_BLUE; + case "yellow" -> MapCursor.Type.BANNER_YELLOW; + case "lime" -> MapCursor.Type.BANNER_LIME; + case "pink" -> MapCursor.Type.BANNER_PINK; + case "gray" -> MapCursor.Type.BANNER_GRAY; + case "light_gray" -> MapCursor.Type.BANNER_LIGHT_GRAY; + case "cyan" -> MapCursor.Type.BANNER_CYAN; + case "purple" -> MapCursor.Type.BANNER_PURPLE; + case "blue" -> MapCursor.Type.BANNER_BLUE; + case "brown" -> MapCursor.Type.BANNER_BROWN; + case "green" -> MapCursor.Type.BANNER_GREEN; + case "red" -> MapCursor.Type.BANNER_RED; + default -> MapCursor.Type.BANNER_BLACK; + }, + true, + banner.getText().isEmpty() ? null : banner.getText() + ); + } + + /** + * A {@link MapCanvas} implementation used for pre-rendering maps to be converted into {@link MapData} + */ + class PersistentMapCanvas implements MapCanvas { + + private final MapView mapView; + private final int[][] pixels = new int[128][128]; + private MapCursorCollection cursors; + + private PersistentMapCanvas(@NotNull MapView mapView) { + this.mapView = mapView; + } + + @NotNull + @Override + public MapView getMapView() { + return mapView; + } + + @NotNull + @Override + public MapCursorCollection getCursors() { + return cursors == null ? (cursors = new MapCursorCollection()) : cursors; + } + + @Override + public void setCursors(@NotNull MapCursorCollection cursors) { + this.cursors = cursors; + } + + @Override + public void setPixel(int x, int y, byte color) { + pixels[x][y] = color; + } + + @Override + public byte getPixel(int x, int y) { + return (byte) pixels[x][y]; + } + + @Override + public byte getBasePixel(int x, int y) { + return getPixel(x, y); + } + + @Override + public void drawImage(int x, int y, @NotNull Image image) { + // Not implemented + } + + @Override + public void drawText(int x, int y, @NotNull MapFont font, @NotNull String text) { + // Not implemented + } + + @NotNull + private String getDimension() { + return mapView.getWorld() != null ? switch (mapView.getWorld().getEnvironment()) { + case NETHER -> "minecraft:the_nether"; + case THE_END -> "minecraft:the_end"; + default -> "minecraft:overworld"; + } : "minecraft:overworld"; + } + + /** + * Extract the map data from the canvas. Must be rendered first + * + * @return the extracted map data + */ + @NotNull + private MapData extractMapData() { + final List banners = new ArrayList<>(); + for (int i = 0; i < getCursors().size(); i++) { + final MapCursor cursor = getCursors().getCursor(i); + final String type = cursor.getType().name().toLowerCase(Locale.ENGLISH); + if (type.startsWith("banner_")) { + banners.add(new MapBanner( + type.replaceAll("banner_", ""), + cursor.getCaption() == null ? "" : cursor.getCaption(), + cursor.getX(), + mapView.getWorld() != null ? mapView.getWorld().getSeaLevel() : 128, + cursor.getY() + )); + } + } + return MapData.fromPixels(pixels, getDimension(), (byte) 2, banners, List.of()); + } + } + + @NotNull + Map getMapViews(); + + @ApiStatus.Internal + @NotNull + HuskSync getPlugin(); + +} diff --git a/bukkit/src/main/java/net/william278/husksync/util/BukkitTask.java b/bukkit/src/main/java/net/william278/husksync/util/BukkitTask.java new file mode 100644 index 00000000..a9381425 --- /dev/null +++ b/bukkit/src/main/java/net/william278/husksync/util/BukkitTask.java @@ -0,0 +1,172 @@ +/* + * This file is part of HuskSync, licensed under the Apache License 2.0. + * + * Copyright (c) William278 + * Copyright (c) contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.william278.husksync.util; + +import net.william278.husksync.BukkitHuskSync; +import net.william278.husksync.HuskSync; +import org.jetbrains.annotations.NotNull; +import space.arim.morepaperlib.scheduling.AsynchronousScheduler; +import space.arim.morepaperlib.scheduling.RegionalScheduler; +import space.arim.morepaperlib.scheduling.ScheduledTask; + +import java.time.Duration; +import java.time.temporal.ChronoUnit; + +public interface BukkitTask extends Task { + + class Sync extends Task.Sync implements BukkitTask { + + private ScheduledTask task; + + protected Sync(@NotNull HuskSync plugin, @NotNull Runnable runnable, long delayTicks) { + super(plugin, runnable, delayTicks); + } + + @Override + public void cancel() { + if (task != null && !cancelled) { + task.cancel(); + } + super.cancel(); + } + + @Override + public void run() { + if (isPluginDisabled()) { + runnable.run(); + return; + } + if (cancelled) { + return; + } + + final RegionalScheduler scheduler = ((BukkitHuskSync) getPlugin()).getRegionalScheduler(); + if (delayTicks > 0) { + this.task = scheduler.runDelayed(runnable, delayTicks); + } else { + this.task = scheduler.run(runnable); + } + } + } + + class Async extends Task.Async implements BukkitTask { + + private ScheduledTask task; + + protected Async(@NotNull HuskSync plugin, @NotNull Runnable runnable, long delayTicks) { + super(plugin, runnable, delayTicks); + } + + @Override + public void cancel() { + if (task != null && !cancelled) { + task.cancel(); + } + super.cancel(); + } + + @Override + public void run() { + if (isPluginDisabled()) { + runnable.run(); + return; + } + if (cancelled) { + return; + } + + final AsynchronousScheduler scheduler = ((BukkitHuskSync) getPlugin()).getAsyncScheduler(); + if (delayTicks > 0) { + plugin.debug("Running async task with delay of " + delayTicks + " ticks"); + this.task = scheduler.runDelayed( + runnable, + Duration.of(delayTicks * 50L, ChronoUnit.MILLIS) + ); + } else { + this.task = scheduler.run(runnable); + } + } + } + + class Repeating extends Task.Repeating implements BukkitTask { + + private ScheduledTask task; + + protected Repeating(@NotNull HuskSync plugin, @NotNull Runnable runnable, long repeatingTicks) { + super(plugin, runnable, repeatingTicks); + } + + @Override + public void cancel() { + if (task != null && !cancelled) { + task.cancel(); + } + super.cancel(); + } + + @Override + public void run() { + if (isPluginDisabled()) { + return; + } + + if (!cancelled) { + final AsynchronousScheduler scheduler = ((BukkitHuskSync) getPlugin()).getAsyncScheduler(); + this.task = scheduler.runAtFixedRate( + runnable, Duration.ZERO, + Duration.of(repeatingTicks * 50L, ChronoUnit.MILLIS) + ); + } + } + } + + // Returns if the Bukkit HuskSync plugin is disabled + default boolean isPluginDisabled() { + return !((BukkitHuskSync) getPlugin()).isEnabled(); + } + + interface Supplier extends Task.Supplier { + + @NotNull + @Override + default Task.Sync getSyncTask(@NotNull Runnable runnable, long delayTicks) { + return new Sync(getPlugin(), runnable, delayTicks); + } + + @NotNull + @Override + default Task.Async getAsyncTask(@NotNull Runnable runnable, long delayTicks) { + return new Async(getPlugin(), runnable, delayTicks); + } + + @NotNull + @Override + default Task.Repeating getRepeatingTask(@NotNull Runnable runnable, long repeatingTicks) { + return new Repeating(getPlugin(), runnable, repeatingTicks); + } + + @Override + default void cancelTasks() { + ((BukkitHuskSync) getPlugin()).getScheduler().cancelGlobalTasks(); + } + + } + +} \ No newline at end of file diff --git a/bukkit/src/main/resources/plugin.yml b/bukkit/src/main/resources/plugin.yml index b337a9eb..07051d89 100644 --- a/bukkit/src/main/resources/plugin.yml +++ b/bukkit/src/main/resources/plugin.yml @@ -12,19 +12,4 @@ libraries: - 'redis.clients:jedis:${jedis_version}' - 'com.mysql:mysql-connector-j:${mysql_driver_version}' - 'org.mariadb.jdbc:mariadb-java-client:${mariadb_driver_version}' - - 'org.xerial.snappy:snappy-java:${snappy_version}' - - 'org.apache.commons:commons-text:${commons_text_version}' - -commands: - husksync: - usage: '/ ' - description: 'Manage the HuskSync plugin' - userdata: - usage: '/ [version_uuid]' - description: 'View, manage & restore player userdata' - inventory: - usage: '/ [version_uuid]' - description: 'View & edit a player''s inventory' - enderchest: - usage: '/ [version_uuid]' - description: 'View & edit a player''s Ender Chest' \ No newline at end of file + - 'org.xerial.snappy:snappy-java:${snappy_version}' \ No newline at end of file diff --git a/common/build.gradle b/common/build.gradle index 81f85f22..a21899eb 100644 --- a/common/build.gradle +++ b/common/build.gradle @@ -1,40 +1,33 @@ +plugins { + id 'java-library' +} + dependencies { - implementation 'commons-io:commons-io:2.13.0' - implementation 'de.themoep:minedown-adventure:1.7.2-SNAPSHOT' - implementation 'net.kyori:adventure-api:4.14.0' - implementation 'com.google.code.gson:gson:2.10.1' - implementation 'dev.dejvokep:boosted-yaml:1.3.1' - implementation 'net.william278:Annotaml:2.0.1' - implementation 'net.william278:DesertWell:2.0.4' - implementation 'net.william278:PagineDown:1.1' - implementation('com.zaxxer:HikariCP:5.0.1') { + api 'commons-io:commons-io:2.13.0' + api 'org.apache.commons:commons-text:1.10.0' + api 'de.themoep:minedown-adventure:1.7.2-SNAPSHOT' + api 'net.kyori:adventure-api:4.14.0' + api 'org.json:json:20230618' + api 'com.google.code.gson:gson:2.10.1' + api 'com.fatboyindustrial.gson-javatime-serialisers:gson-javatime-serialisers:1.1.2' + api 'dev.dejvokep:boosted-yaml:1.3.1' + api 'net.william278:annotaml:2.0.7' + api 'net.william278:DesertWell:2.0.4' + api 'net.william278:PagineDown:1.1' + api('com.zaxxer:HikariCP:5.0.1') { exclude module: 'slf4j-api' } compileOnly 'org.jetbrains:annotations:24.0.1' compileOnly 'com.github.plan-player-analytics:Plan:5.5.2272' - compileOnly 'redis.clients:jedis:' + jedis_version - compileOnly 'org.xerial.snappy:snappy-java:' + snappy_version - compileOnly 'org.apache.commons:commons-text:' + commons_text_version + compileOnly "redis.clients:jedis:$jedis_version" + compileOnly "com.mysql:mysql-connector-j:$mysql_driver_version" + compileOnly "org.mariadb.jdbc:mariadb-java-client:$mariadb_driver_version" + compileOnly "org.xerial.snappy:snappy-java:$snappy_version" testImplementation 'com.github.plan-player-analytics:Plan:5.5.2272' - testImplementation 'redis.clients:jedis:' + jedis_version - testImplementation 'org.xerial.snappy:snappy-java:' + snappy_version - testImplementation 'org.apache.commons:commons-text:' + commons_text_version + testImplementation "redis.clients:jedis:$jedis_version" + testImplementation "org.xerial.snappy:snappy-java:$snappy_version" testCompileOnly 'dev.dejvokep:boosted-yaml:1.3.1' testCompileOnly 'org.jetbrains:annotations:24.0.1' -} - -shadowJar { - relocate 'org.apache.commons.io', 'net.william278.husksync.libraries.commons.io' - relocate 'com.google.gson', 'net.william278.husksync.libraries.gson' - relocate 'de.themoep', 'net.william278.husksync.libraries' - relocate 'net.kyori', 'net.william278.husksync.libraries' - relocate 'org.jetbrains', 'net.william278.husksync.libraries' - relocate 'org.intellij', 'net.william278.husksync.libraries' - relocate 'com.zaxxer', 'net.william278.husksync.libraries' - relocate 'dev.dejvokep', 'net.william278.husksync.libraries' - relocate 'net.william278.desertwell', 'net.william278.husksync.libraries.desertwell' - relocate 'net.william278.paginedown', 'net.william278.husksync.libraries.paginedown' - relocate 'net.william278.annotaml', 'net.william278.husksync.libraries.annotaml' } \ No newline at end of file diff --git a/common/src/main/java/net/william278/husksync/HuskSync.java b/common/src/main/java/net/william278/husksync/HuskSync.java index a579ff57..6c8324b0 100644 --- a/common/src/main/java/net/william278/husksync/HuskSync.java +++ b/common/src/main/java/net/william278/husksync/HuskSync.java @@ -19,31 +19,40 @@ package net.william278.husksync; +import com.fatboyindustrial.gsonjavatime.Converters; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import net.william278.annotaml.Annotaml; +import net.william278.desertwell.util.ThrowingConsumer; import net.william278.desertwell.util.UpdateChecker; import net.william278.desertwell.util.Version; +import net.william278.husksync.adapter.DataAdapter; import net.william278.husksync.config.Locales; import net.william278.husksync.config.Settings; -import net.william278.husksync.data.DataAdapter; +import net.william278.husksync.data.Data; +import net.william278.husksync.data.Identifier; +import net.william278.husksync.data.Serializer; import net.william278.husksync.database.Database; -import net.william278.husksync.event.EventCannon; +import net.william278.husksync.event.EventDispatcher; import net.william278.husksync.migrator.Migrator; -import net.william278.husksync.player.OnlineUser; import net.william278.husksync.redis.RedisManager; +import net.william278.husksync.user.ConsoleUser; +import net.william278.husksync.user.OnlineUser; +import net.william278.husksync.util.LegacyConverter; +import net.william278.husksync.util.Task; import org.jetbrains.annotations.NotNull; import java.io.File; +import java.io.IOException; import java.io.InputStream; -import java.util.List; -import java.util.Optional; -import java.util.Set; -import java.util.UUID; -import java.util.concurrent.CompletableFuture; +import java.lang.reflect.InvocationTargetException; +import java.util.*; import java.util.logging.Level; /** * Abstract implementation of the HuskSync plugin. */ -public interface HuskSync { +public interface HuskSync extends Task.Supplier, EventDispatcher { int SPIGOT_RESOURCE_ID = 97144; @@ -81,21 +90,45 @@ public interface HuskSync { @NotNull RedisManager getRedisManager(); + @NotNull + DataAdapter getDataAdapter(); + /** - * Returns the data adapter implementation - * - * @return the {@link DataAdapter} implementation + * Returns the data serializer for the given {@link Identifier} */ @NotNull - DataAdapter getDataAdapter(); + Map> getSerializers(); /** - * Returns the event firing cannon + * Register a data serializer for the given {@link Identifier} * - * @return the {@link EventCannon} implementation + * @param identifier the {@link Identifier} + * @param serializer the {@link Serializer} + */ + default void registerSerializer(@NotNull Identifier identifier, + @NotNull Serializer serializer) { + if (identifier.isCustom()) { + log(Level.INFO, String.format("Registered custom data type: %s", identifier)); + } + getSerializers().put(identifier, (Serializer) serializer); + } + + /** + * Get the {@link Identifier} for the given key + */ + default Optional getIdentifier(@NotNull String key) { + return getSerializers().keySet().stream().filter(identifier -> identifier.toString().equals(key)).findFirst(); + } + + /** + * Get the set of registered data types + * + * @return the set of registered data types */ @NotNull - EventCannon getEventCannon(); + default Set getRegisteredDataTypes() { + return getSerializers().keySet(); + } /** * Returns a list of available data {@link Migrator}s @@ -105,6 +138,25 @@ public interface HuskSync { @NotNull List getAvailableMigrators(); + @NotNull + Map getPlayerCustomDataStore(@NotNull OnlineUser user); + + /** + * Initialize a faucet of the plugin. + * + * @param name the name of the faucet + * @param runner a runnable for initializing the faucet + */ + default void initialize(@NotNull String name, @NotNull ThrowingConsumer runner) { + log(Level.INFO, "Initializing " + name + "..."); + try { + runner.accept(this); + } catch (Throwable e) { + throw new FailedToLoadException("Failed to initialize " + name, e); + } + log(Level.INFO, "Successfully initialized " + name); + } + /** * Returns the plugin {@link Settings} * @@ -113,6 +165,8 @@ public interface HuskSync { @NotNull Settings getSettings(); + void setSettings(@NotNull Settings settings); + /** * Returns the plugin {@link Locales} * @@ -121,6 +175,16 @@ public interface HuskSync { @NotNull Locales getLocales(); + void setLocales(@NotNull Locales locales); + + /** + * Returns if a dependency is loaded + * + * @param name the name of the dependency + * @return {@code true} if the dependency is loaded, {@code false} otherwise + */ + boolean isDependencyLoaded(@NotNull String name); + /** * Get a resource as an {@link InputStream} from the plugin jar * @@ -129,6 +193,14 @@ public interface HuskSync { */ InputStream getResource(@NotNull String name); + /** + * Returns the plugin data folder + * + * @return the plugin data folder as a {@link File} + */ + @NotNull + File getDataFolder(); + /** * Log a message to the console * @@ -146,10 +218,18 @@ public interface HuskSync { */ default void debug(@NotNull String message, @NotNull Throwable... throwable) { if (getSettings().doDebugLogging()) { - log(Level.INFO, "[DEBUG] " + message, throwable); + log(Level.INFO, String.format("[DEBUG] %s", message), throwable); } } + /** + * Get the console user + * + * @return the {@link ConsoleUser} + */ + @NotNull + ConsoleUser getConsole(); + /** * Returns the plugin version * @@ -159,44 +239,103 @@ public interface HuskSync { Version getPluginVersion(); /** - * Returns the plugin data folder + * Returns the Minecraft version implementation * - * @return the plugin data folder as a {@link File} + * @return the Minecraft {@link Version} */ @NotNull - File getDataFolder(); + Version getMinecraftVersion(); /** - * Returns a future returning the latest plugin {@link Version} if the plugin is out-of-date + * Returns the platform type * - * @return a {@link CompletableFuture} returning the latest {@link Version} if the current one is out-of-date + * @return the platform type */ - default CompletableFuture> getLatestVersionIfOutdated() { + @NotNull + String getPlatformType(); + + /** + * Returns the legacy data converter, if it exists + * + * @return the {@link LegacyConverter} + */ + Optional getLegacyConverter(); + + /** + * Reloads the {@link Settings} and {@link Locales} from their respective config files. + */ + default void loadConfigs() { + try { + // Load settings + setSettings(Annotaml.create(new File(getDataFolder(), "config.yml"), Settings.class).get()); + + // Load locales from language preset default + final Locales languagePresets = Annotaml.create( + Locales.class, + Objects.requireNonNull(getResource(String.format("locales/%s.yml", getSettings().getLanguage()))) + ).get(); + setLocales(Annotaml.create(new File( + getDataFolder(), + String.format("messages_%s.yml", getSettings().getLanguage()) + ), languagePresets).get()); + } catch (IOException | InvocationTargetException | InstantiationException | IllegalAccessException e) { + throw new FailedToLoadException("Failed to load config or message files", e); + } + } + + @NotNull + default UpdateChecker getUpdateChecker() { return UpdateChecker.builder() .currentVersion(getPluginVersion()) .endpoint(UpdateChecker.Endpoint.SPIGOT) - .resource(Integer.toString(SPIGOT_RESOURCE_ID)).build() - .check() - .thenApply(checked -> checked.isUpToDate() - ? Optional.empty() - : Optional.of(checked.getLatestVersion())); + .resource(Integer.toString(SPIGOT_RESOURCE_ID)) + .build(); + } + + default void checkForUpdates() { + if (getSettings().doCheckForUpdates()) { + getUpdateChecker().check().thenAccept(checked -> { + if (!checked.isUpToDate()) { + log(Level.WARNING, String.format( + "A new version of HuskSync is available: v%s (running v%s)", + checked.getLatestVersion(), getPluginVersion()) + ); + } + }); + } } - /** - * Returns the Minecraft version implementation - * - * @return the Minecraft {@link Version} - */ @NotNull - Version getMinecraftVersion(); + Set getLockedPlayers(); + + @NotNull + Gson getGson(); + + @NotNull + default Gson createGson() { + return Converters.registerOffsetDateTime(new GsonBuilder()).create(); + } /** - * Reloads the {@link Settings} and {@link Locales} from their respective config files - * - * @return a {@link CompletableFuture} that will be completed when the plugin reload is complete and if it was successful + * An exception indicating the plugin has been accessed before it has been registered. */ - CompletableFuture reload(); + final class FailedToLoadException extends IllegalStateException { - Set getLockedPlayers(); + private static final String FORMAT = """ + HuskSync has failed to load! The plugin will not be enabled and no data will be synchronized. + Please make sure the plugin has been setup correctly (https://william278.net/docs/husksync/setup): + + 1) Make sure you've entered your MySQL or MariaDB database details correctly in config.yml + 2) Make sure your Redis server details are also correct in config.yml + 3) Make sure your config is up-to-date (https://william278.net/docs/husksync/config-files) + 4) Check the error below for more details + + Caused by: %s"""; + + FailedToLoadException(@NotNull String message, @NotNull Throwable cause) { + super(String.format(FORMAT, message), cause); + } + + } } diff --git a/common/src/main/java/net/william278/husksync/data/DataAdaptionException.java b/common/src/main/java/net/william278/husksync/adapter/Adaptable.java similarity index 70% rename from common/src/main/java/net/william278/husksync/data/DataAdaptionException.java rename to common/src/main/java/net/william278/husksync/adapter/Adaptable.java index c88f158b..4742fe1d 100644 --- a/common/src/main/java/net/william278/husksync/data/DataAdaptionException.java +++ b/common/src/main/java/net/william278/husksync/adapter/Adaptable.java @@ -17,14 +17,8 @@ * limitations under the License. */ -package net.william278.husksync.data; +package net.william278.husksync.adapter; -/** - * Indicates an error occurred during {@link UserData} adaptation to and from (compressed) json. - */ -public class DataAdaptionException extends RuntimeException { - protected DataAdaptionException(String message, Throwable cause) { - super(message, cause); - } +public interface Adaptable { } diff --git a/common/src/main/java/net/william278/husksync/adapter/DataAdapter.java b/common/src/main/java/net/william278/husksync/adapter/DataAdapter.java new file mode 100644 index 00000000..53ea2b19 --- /dev/null +++ b/common/src/main/java/net/william278/husksync/adapter/DataAdapter.java @@ -0,0 +1,108 @@ +/* + * This file is part of HuskSync, licensed under the Apache License 2.0. + * + * Copyright (c) William278 + * Copyright (c) contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.william278.husksync.adapter; + +import org.jetbrains.annotations.NotNull; + +import java.nio.charset.StandardCharsets; + +/** + * An adapter that adapts data to and from a portable byte array. + */ +public interface DataAdapter { + + /** + * Converts an {@link Adaptable} to a string. + * + * @param data The {@link Adaptable} to adapt + * @param The type of the {@link Adaptable} + * @return The string + * @throws AdaptionException If an error occurred during adaptation. + */ + @NotNull + default String toString(@NotNull A data) throws AdaptionException { + return new String(this.toBytes(data), StandardCharsets.UTF_8); + } + + /** + * Converts an {@link Adaptable} to a byte array. + * + * @param data The {@link Adaptable} to adapt + * @param The type of the {@link Adaptable} + * @return The byte array + * @throws AdaptionException If an error occurred during adaptation. + */ + byte[] toBytes(@NotNull A data) throws AdaptionException; + + /** + * Converts a JSON string to an {@link Adaptable}. + * + * @param data The JSON string to adapt. + * @param type The class type of the {@link Adaptable} to adapt to. + * @param The type of the {@link Adaptable} + * @return The {@link Adaptable} + * @throws AdaptionException If an error occurred during adaptation. + */ + @NotNull + A fromJson(@NotNull String data, @NotNull Class type) throws AdaptionException; + + /** + * Converts an {@link Adaptable} to a JSON string. + * + * @param data The {@link Adaptable} to adapt + * @param The type of the {@link Adaptable} + * @return The JSON string + * @throws AdaptionException If an error occurred during adaptation. + */ + @NotNull + String toJson(@NotNull A data) throws AdaptionException; + + /** + * Converts a byte array to an {@link Adaptable}. + * + * @param data The byte array to adapt. + * @param type The class type of the {@link Adaptable} to adapt to. + * @param The type of the {@link Adaptable} + * @return The {@link Adaptable} + * @throws AdaptionException If an error occurred during adaptation. + */ + A fromBytes(@NotNull byte[] data, @NotNull Class type) throws AdaptionException; + + /** + * Converts a byte array to a string, including decompression if required. + * + * @param bytes The byte array to convert + * @return the string form of the bytes + */ + @NotNull + String bytesToString(byte[] bytes); + + final class AdaptionException extends IllegalStateException { + static final String FORMAT = "An exception occurred when adapting serialized/deserialized data: %s"; + + public AdaptionException(@NotNull String message, @NotNull Throwable cause) { + super(String.format(FORMAT, message), cause); + } + + public AdaptionException(@NotNull String message) { + super(String.format(FORMAT, message)); + } + } +} \ No newline at end of file diff --git a/common/src/main/java/net/william278/husksync/adapter/GsonAdapter.java b/common/src/main/java/net/william278/husksync/adapter/GsonAdapter.java new file mode 100644 index 00000000..ba3d0514 --- /dev/null +++ b/common/src/main/java/net/william278/husksync/adapter/GsonAdapter.java @@ -0,0 +1,72 @@ +/* + * This file is part of HuskSync, licensed under the Apache License 2.0. + * + * Copyright (c) William278 + * Copyright (c) contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.william278.husksync.adapter; + +import net.william278.husksync.HuskSync; +import org.jetbrains.annotations.NotNull; + +import java.nio.charset.StandardCharsets; + +public class GsonAdapter implements DataAdapter { + + private final HuskSync plugin; + + public GsonAdapter(@NotNull HuskSync plugin) { + this.plugin = plugin; + } + + @Override + public byte[] toBytes(@NotNull A data) throws AdaptionException { + return this.toJson(data).getBytes(StandardCharsets.UTF_8); + } + + @NotNull + @Override + public String toJson(@NotNull A data) throws AdaptionException { + try { + return plugin.getGson().toJson(data); + } catch (Throwable e) { + throw new AdaptionException("Failed to adapt data to JSON via Gson", e); + } + } + + @Override + @NotNull + public A fromBytes(@NotNull byte[] data, @NotNull Class type) throws AdaptionException { + return this.fromJson(new String(data, StandardCharsets.UTF_8), type); + } + + @NotNull + @Override + public String bytesToString(byte[] bytes) { + return new String(bytes, StandardCharsets.UTF_8); + } + + @Override + @NotNull + public A fromJson(@NotNull String data, @NotNull Class type) throws AdaptionException { + try { + return plugin.getGson().fromJson(data, type); + } catch (Throwable e) { + throw new AdaptionException("Failed to adapt data from JSON via Gson", e); + } + } + +} diff --git a/common/src/main/java/net/william278/husksync/adapter/SnappyGsonAdapter.java b/common/src/main/java/net/william278/husksync/adapter/SnappyGsonAdapter.java new file mode 100644 index 00000000..22af6ce0 --- /dev/null +++ b/common/src/main/java/net/william278/husksync/adapter/SnappyGsonAdapter.java @@ -0,0 +1,68 @@ +/* + * This file is part of HuskSync, licensed under the Apache License 2.0. + * + * Copyright (c) William278 + * Copyright (c) contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.william278.husksync.adapter; + +import net.william278.husksync.HuskSync; +import org.jetbrains.annotations.NotNull; +import org.xerial.snappy.Snappy; + +import java.io.IOException; + +public class SnappyGsonAdapter extends GsonAdapter { + + public SnappyGsonAdapter(@NotNull HuskSync plugin) { + super(plugin); + } + + @NotNull + @Override + public byte[] toBytes(@NotNull A data) throws AdaptionException { + try { + return Snappy.compress(super.toBytes(data)); + } catch (IOException e) { + throw new AdaptionException("Failed to compress data through Snappy", e); + } + } + + @NotNull + @Override + public A fromBytes(@NotNull byte[] data, @NotNull Class type) throws AdaptionException { + try { + return super.fromBytes(decompressBytes(data), type); + } catch (IOException e) { + throw new AdaptionException("Failed to decompress data through Snappy", e); + } + } + + @Override + @NotNull + public String bytesToString(byte[] bytes) { + try { + return super.bytesToString(decompressBytes(bytes)); + } catch (IOException e) { + throw new AdaptionException("Failed to decompress data through Snappy", e); + } + } + + private byte[] decompressBytes(byte[] bytes) throws IOException { + return Snappy.uncompress(bytes); + } + +} diff --git a/common/src/main/java/net/william278/husksync/api/BaseHuskSyncAPI.java b/common/src/main/java/net/william278/husksync/api/BaseHuskSyncAPI.java deleted file mode 100644 index 70caae4b..00000000 --- a/common/src/main/java/net/william278/husksync/api/BaseHuskSyncAPI.java +++ /dev/null @@ -1,157 +0,0 @@ -/* - * This file is part of HuskSync, licensed under the Apache License 2.0. - * - * Copyright (c) William278 - * Copyright (c) contributors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.william278.husksync.api; - -import net.william278.husksync.HuskSync; -import net.william278.husksync.data.DataSaveCause; -import net.william278.husksync.data.UserData; -import net.william278.husksync.data.UserDataSnapshot; -import net.william278.husksync.player.OnlineUser; -import net.william278.husksync.player.User; -import org.jetbrains.annotations.NotNull; - -import java.util.List; -import java.util.Optional; -import java.util.UUID; -import java.util.concurrent.CompletableFuture; - -/** - * The base implementation of the HuskSync API, containing cross-platform API calls. - *

- * This class should not be used directly, but rather through platform-specific extending API classes. - */ -@SuppressWarnings("unused") -public abstract class BaseHuskSyncAPI { - - /** - * (Internal use only) - Instance of the implementing plugin. - */ - protected final HuskSync plugin; - - protected BaseHuskSyncAPI(@NotNull HuskSync plugin) { - this.plugin = plugin; - } - - /** - * Returns a {@link User} by the given player's account {@link UUID}, if they exist. - * - * @param uuid the unique id of the player to get the {@link User} instance for - * @return future returning the {@link User} instance for the given player's unique id if they exist, otherwise an empty {@link Optional} - * @apiNote The player does not have to be online - * @since 2.0 - */ - public final CompletableFuture> getUser(@NotNull UUID uuid) { - return plugin.getDatabase().getUser(uuid); - } - - /** - * Returns a {@link User} by the given player's username (case-insensitive), if they exist. - * - * @param username the username of the {@link User} instance for - * @return future returning the {@link User} instance for the given player's username if they exist, - * otherwise an empty {@link Optional} - * @apiNote The player does not have to be online, though their username has to be the username - * they had when they last joined the server. - * @since 2.0 - */ - public final CompletableFuture> getUser(@NotNull String username) { - return plugin.getDatabase().getUserByName(username); - } - - /** - * Returns a {@link User}'s current {@link UserData} - * - * @param user the {@link User} to get the {@link UserData} for - * @return future returning the {@link UserData} for the given {@link User} if they exist, otherwise an empty {@link Optional} - * @apiNote If the user is not online on the implementing bukkit server, - * the {@link UserData} returned will be their last database-saved UserData. - *

- * Because of this, if the user is online on another server on the network, - * then the {@link UserData} returned by this method will not necessarily reflective of - * their current state - * @since 2.0 - */ - public final CompletableFuture> getUserData(@NotNull User user) { - return CompletableFuture.supplyAsync(() -> { - if (user instanceof OnlineUser) { - return ((OnlineUser) user).getUserData(plugin).join(); - } else { - return plugin.getDatabase().getCurrentUserData(user).join().map(UserDataSnapshot::userData); - } - }); - } - - /** - * Sets the {@link UserData} to the database for the given {@link User}. - *

- * If the user is online and on the same cluster, their data will be updated in game. - * - * @param user the {@link User} to set the {@link UserData} for - * @param userData the {@link UserData} to set for the given {@link User} - * @return future returning void when complete - * @since 2.0 - */ - public final CompletableFuture setUserData(@NotNull User user, @NotNull UserData userData) { - return CompletableFuture.runAsync(() -> - plugin.getDatabase().setUserData(user, userData, DataSaveCause.API) - .thenRun(() -> plugin.getRedisManager().sendUserDataUpdate(user, userData).join())); - } - - /** - * Saves the {@link UserData} of an {@link OnlineUser} to the database - * - * @param user the {@link OnlineUser} to save the {@link UserData} of - * @return future returning void when complete - * @since 2.0 - */ - public final CompletableFuture saveUserData(@NotNull OnlineUser user) { - return CompletableFuture.runAsync(() -> user.getUserData(plugin) - .thenAccept(optionalUserData -> optionalUserData.ifPresent( - userData -> plugin.getDatabase().setUserData(user, userData, DataSaveCause.API).join()))); - } - - /** - * Returns the saved {@link UserDataSnapshot} records for the given {@link User} - * - * @param user the {@link User} to get the {@link UserDataSnapshot} for - * @return future returning a list {@link UserDataSnapshot} for the given {@link User} if they exist, - * otherwise an empty {@link Optional} - * @apiNote The length of the list of VersionedUserData will correspond to the configured - * {@code max_user_data_records} config option - * @since 2.0 - */ - public final CompletableFuture> getSavedUserData(@NotNull User user) { - return CompletableFuture.supplyAsync(() -> plugin.getDatabase().getUserData(user).join()); - } - - /** - * Returns the JSON string representation of the given {@link UserData} - * - * @param userData the {@link UserData} to get the JSON string representation of - * @param prettyPrint whether to pretty print the JSON string - * @return the JSON string representation of the given {@link UserData} - * @since 2.0 - */ - @NotNull - public final String getUserDataJson(@NotNull UserData userData, boolean prettyPrint) { - return plugin.getDataAdapter().toJson(userData, prettyPrint); - } - -} diff --git a/common/src/main/java/net/william278/husksync/api/HuskSyncAPI.java b/common/src/main/java/net/william278/husksync/api/HuskSyncAPI.java new file mode 100644 index 00000000..a0d832f0 --- /dev/null +++ b/common/src/main/java/net/william278/husksync/api/HuskSyncAPI.java @@ -0,0 +1,458 @@ +/* + * This file is part of HuskSync, licensed under the Apache License 2.0. + * + * Copyright (c) William278 + * Copyright (c) contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.william278.husksync.api; + +import net.william278.desertwell.util.ThrowingConsumer; +import net.william278.husksync.HuskSync; +import net.william278.husksync.adapter.Adaptable; +import net.william278.husksync.data.Data; +import net.william278.husksync.data.DataSnapshot; +import net.william278.husksync.data.Identifier; +import net.william278.husksync.data.Serializer; +import net.william278.husksync.user.OnlineUser; +import net.william278.husksync.user.User; +import org.jetbrains.annotations.ApiStatus; +import org.jetbrains.annotations.NotNull; + +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.CompletableFuture; + +/** + * The base implementation of the HuskSync API, containing cross-platform API calls. + *

+ * This class should not be used directly, but rather through platform-specific extending API classes. + * + * @since 2.0 + */ +@SuppressWarnings("unused") +public abstract class HuskSyncAPI { + + /** + * (Internal use only) - Instance of the implementing plugin. + */ + protected final HuskSync plugin; + + /** + * (Internal use only) - Constructor, instantiating the base API class. + */ + @ApiStatus.Internal + protected HuskSyncAPI(@NotNull HuskSync plugin) { + this.plugin = plugin; + } + + /** + * Get a {@link User} by their UUID + * + * @param uuid The UUID of the user to get + * @return A future containing the user, or an empty optional if the user doesn't exist + * @since 3.0 + */ + @NotNull + public CompletableFuture> getUser(@NotNull UUID uuid) { + return plugin.supplyAsync(() -> plugin.getDatabase().getUser(uuid)); + } + + /** + * Get a {@link User} by their username + * + * @param username The username of the user to get + * @return A future containing the user, or an empty optional if the user doesn't exist + * @since 3.0 + */ + @NotNull + public CompletableFuture> getUser(@NotNull String username) { + return plugin.supplyAsync(() -> plugin.getDatabase().getUserByName(username)); + } + + /** + * Create a new data snapshot of an {@link OnlineUser}'s data. + * + * @param user The user to create the snapshot of + * @return The snapshot of the user's data + * @since 3.0 + */ + @NotNull + public DataSnapshot.Packed createSnapshot(@NotNull OnlineUser user) { + return snapshotBuilder().saveCause(DataSnapshot.SaveCause.API).buildAndPack(); + } + + /** + * Get a {@link User}'s current data, as a {@link DataSnapshot.Unpacked} + *

+ * If the user is online, this will create a new snapshot of their data with the {@code API} data save cause. + *

+ * If the user is offline, this will return the latest snapshot of their data if that exists + * (an empty optional will be returned otherwise). + * + * @param user The user to get the data of + * @return A future containing the user's current data, or an empty optional if the user has no data + * @since 3.0 + */ + public CompletableFuture> getCurrentData(@NotNull User user) { + return plugin.getRedisManager() + .getUserData(UUID.randomUUID(), user) + .thenApply(data -> data.or(() -> plugin.getDatabase().getLatestSnapshot(user))) + .thenApply(data -> data.map(snapshot -> snapshot.unpack(plugin))); + } + + /** + * Set a user's current data. + *

+ * This will update the user's data in the database (creating a new snapshot) and send a data update, + * updating the user if they are online. + * + * @param user The user to set the data of + * @param data The data to set + * @since 3.0 + */ + public void setCurrentData(@NotNull User user, @NotNull DataSnapshot data) { + plugin.runAsync(() -> { + final DataSnapshot.Packed packed = data instanceof DataSnapshot.Unpacked unpacked + ? unpacked.pack(plugin) : (DataSnapshot.Packed) data; + addSnapshot(user, packed); + plugin.getRedisManager().sendUserDataUpdate(user, packed); + }); + } + + /** + * Edit a user's current data. + *

+ * This will update the user's data in the database (creating a new snapshot) and send a data update, + * updating the user if they are online. + * + * @param user The user to edit the data of + * @param editor The editor function + * @since 3.0 + */ + public void editCurrentData(@NotNull User user, @NotNull ThrowingConsumer editor) { + getCurrentData(user).thenAccept(optional -> optional.ifPresent(data -> { + editor.accept(data); + setCurrentData(user, data); + })); + } + + /** + * Get a list of all saved data snapshots for a user + * + * @param user The user to get the data snapshots of + * @return The user's data snapshots + * @since 3.0 + */ + public CompletableFuture> getSnapshots(@NotNull User user) { + return plugin.supplyAsync( + () -> plugin.getDatabase().getAllSnapshots(user).stream() + .map(snapshot -> snapshot.unpack(plugin)) + .toList() + ); + } + + /** + * Get a specific data snapshot for a user + * + * @param user The user to get the data snapshot of + * @param versionId The version ID of the snapshot to get + * @return The user's data snapshot, or an empty optional if the user has no data + * @see #getSnapshots(User) + * @since 3.0 + */ + public CompletableFuture> getSnapshot(@NotNull User user, @NotNull UUID versionId) { + return plugin.supplyAsync( + () -> plugin.getDatabase().getSnapshot(user, versionId).stream() + .map(snapshot -> snapshot.unpack(plugin)) + .toList() + ); + } + + /** + * Edit a data snapshot for a user + * + * @param user The user to edit the snapshot of + * @param versionId The version ID of the snapshot to edit + * @param editor The editor function + * @since 3.0 + */ + public void editSnapshot(@NotNull User user, @NotNull UUID versionId, + @NotNull ThrowingConsumer editor) { + plugin.runAsync(() -> plugin.getDatabase().getSnapshot(user, versionId).ifPresent(snapshot -> { + final DataSnapshot.Unpacked unpacked = snapshot.unpack(plugin); + editor.accept(unpacked); + plugin.getDatabase().updateSnapshot(user, unpacked.pack(plugin)); + })); + } + + /** + * Get the latest data snapshot for a user that has been saved in the database. + *

+ * Not to be confused with {@link #getCurrentData(User)}, which will return the current data of a user + * if they are online (this method will only return their latest saved snapshot). + *

+ * + * @param user The user to get the latest data snapshot of + * @return The user's latest data snapshot, or an empty optional if the user has no data + * @since 3.0 + */ + public CompletableFuture> getLatestSnapshot(@NotNull User user) { + return plugin.supplyAsync( + () -> plugin.getDatabase().getLatestSnapshot(user).map(snapshot -> snapshot.unpack(plugin)) + ); + } + + /** + * Edit the latest data snapshot for a user + * + * @param user The user to edit the latest snapshot of + * @param editor The editor function + * @since 3.0 + */ + public void editLatestSnapshot(@NotNull User user, @NotNull ThrowingConsumer editor) { + plugin.runAsync(() -> plugin.getDatabase().getLatestSnapshot(user).ifPresent(snapshot -> { + final DataSnapshot.Unpacked unpacked = snapshot.unpack(plugin); + editor.accept(unpacked); + plugin.getDatabase().updateSnapshot(user, unpacked.pack(plugin)); + })); + } + + /** + * Adds a data snapshot to the database + * + * @param user The user to save the data for + * @param snapshot The snapshot to save + * @since 3.0 + */ + public void addSnapshot(@NotNull User user, @NotNull DataSnapshot snapshot) { + plugin.runAsync(() -> plugin.getDatabase().addSnapshot( + user, snapshot instanceof DataSnapshot.Unpacked unpacked + ? unpacked.pack(plugin) : (DataSnapshot.Packed) snapshot + )); + } + + /** + * Update an existing data snapshot in the database. + * Not to be confused with {@link #addSnapshot(User, DataSnapshot)}, which will add a new snapshot if one + * snapshot doesn't exist. + * + * @param user The user to update the snapshot of + * @param snapshot The snapshot to update + * @since 3.0 + */ + public void updateSnapshot(@NotNull User user, @NotNull DataSnapshot snapshot) { + plugin.runAsync(() -> plugin.getDatabase().updateSnapshot( + user, snapshot instanceof DataSnapshot.Unpacked unpacked + ? unpacked.pack(plugin) : (DataSnapshot.Packed) snapshot + )); + } + + /** + * Pin a data snapshot, preventing it from being rotated + * + * @param user The user to pin the snapshot of + * @param snapshotVersion The version ID of the snapshot to pin + * @since 3.0 + */ + public void pinSnapshot(@NotNull User user, @NotNull UUID snapshotVersion) { + plugin.runAsync(() -> plugin.getDatabase().pinSnapshot(user, snapshotVersion)); + } + + /** + * Unpin a data snapshot, allowing it to be rotated + * + * @param user The user to unpin the snapshot of + * @param snapshotVersion The version ID of the snapshot to unpin + * @since 3.0 + */ + public void unpinSnapshot(@NotNull User user, @NotNull UUID snapshotVersion) { + plugin.runAsync(() -> plugin.getDatabase().unpinSnapshot(user, snapshotVersion)); + } + + /** + * Delete a data snapshot from the database + * + * @param user The user to delete the snapshot of + * @param versionId The version ID of the snapshot to delete + * @return A future which will complete with true if the snapshot was deleted, or false if it wasn't + * (e.g., if the snapshot didn't exist) + * @since 3.0 + */ + public CompletableFuture deleteSnapshot(@NotNull User user, @NotNull UUID versionId) { + return plugin.supplyAsync(() -> plugin.getDatabase().deleteSnapshot(user, versionId)); + } + + /** + * Delete a data snapshot from the database + * + * @param user The user to delete the snapshot of + * @param snapshot The snapshot to delete + * @return A future which will complete with true if the snapshot was deleted, or false if it wasn't + * (e.g., if the snapshot hasn't been saved to the database yet) + * @since 3.0 + */ + public CompletableFuture deleteSnapshot(@NotNull User user, @NotNull DataSnapshot snapshot) { + return deleteSnapshot(user, snapshot.getId()); + } + + /** + * Registers a new custom data type serializer. + *

+ * This allows for custom {@link Data} types to be persisted in {@link DataSnapshot}s. To register + * a new data type, you must provide a {@link Serializer} for serializing and deserializing the data type + * and invoke this method. + *

+ * You'll need to do this on every server you wish to sync data between. On servers where the registered + * data type is not present, the data will be ignored and snapshots created on that server will not + * contain the data. + * + * @param identifier The identifier of the data type to register. + * Create one using {@code Identifier.from(Key.of("your_plugin_name", "key"))} + * @param serializer An implementation of {@link Serializer} for serializing and deserializing the {@link Data} + * @param A type extending {@link Data}; this will represent the data being held. + */ + public void registerDataSerializer(@NotNull Identifier identifier, + @NotNull Serializer serializer) { + plugin.registerSerializer(identifier, serializer); + } + + /** + * Get a {@link DataSnapshot.Unpacked} from a {@link DataSnapshot.Packed} + * + * @param unpacked The unpacked snapshot + * @return The packed snapshot + * @since 3.0 + */ + @NotNull + public DataSnapshot.Packed packSnapshot(@NotNull DataSnapshot.Unpacked unpacked) { + return unpacked.pack(plugin); + } + + /** + * Get a {@link DataSnapshot.Unpacked} from a {@link DataSnapshot.Packed} + * + * @param packed The packed snapshot + * @return The unpacked snapshot + * @since 3.0 + */ + @NotNull + public DataSnapshot.Unpacked unpackSnapshot(@NotNull DataSnapshot.Packed packed) { + return packed.unpack(plugin); + } + + /** + * Unpack, edit, and repack a data snapshot. + *

+ * This won't save the snapshot to the database; it'll just edit the data snapshot in place. + * + * @param packed The packed snapshot + * @param editor An editor function for editing the unpacked snapshot + * @return The edited packed snapshot + * @since 3.0 + */ + @NotNull + public DataSnapshot.Packed editPackedSnapshot(@NotNull DataSnapshot.Packed packed, + @NotNull ThrowingConsumer editor) { + final DataSnapshot.Unpacked unpacked = packed.unpack(plugin); + editor.accept(unpacked); + return unpacked.pack(plugin); + } + + /** + * Get the estimated size of a {@link DataSnapshot} in bytes + * + * @param snapshot The snapshot to get the size of + * @return The size of the snapshot in bytes + * @since 3.0 + */ + public int getSnapshotFileSize(@NotNull DataSnapshot snapshot) { + return (snapshot instanceof DataSnapshot.Packed packed) + ? packed.getFileSize(plugin) + : ((DataSnapshot.Unpacked) snapshot).pack(plugin).getFileSize(plugin); + } + + /** + * Get a builder for creating a new data snapshot + * + * @return The builder + * @since 3.0 + */ + @NotNull + public DataSnapshot.Builder snapshotBuilder() { + return DataSnapshot.builder(plugin).saveCause(DataSnapshot.SaveCause.API); + } + + /** + * Deserialize a JSON string to an {@link Adaptable} + * + * @param serialized The serialized JSON string + * @param type The type of the element + * @param The type of the element + * @return The deserialized element + * @throws Serializer.DeserializationException If the element could not be deserialized + */ + @NotNull + public T deserializeData(@NotNull String serialized, Class type) + throws Serializer.DeserializationException { + return plugin.getDataAdapter().fromJson(serialized, type); + } + + /** + * Serialize an {@link Adaptable} to a JSON string + * + * @param element The element to serialize + * @param The type of the element + * @return The serialized JSON string + * @throws Serializer.SerializationException If the element could not be serialized + */ + @NotNull + public String serializeData(@NotNull T element) + throws Serializer.SerializationException { + return plugin.getDataAdapter().toJson(element); + } + + /** + * (Internal use only) - Get the plugin instance + * + * @return The plugin instance + */ + @ApiStatus.Internal + public HuskSync getPlugin() { + return plugin; + } + + /** + * An exception indicating the plugin has been accessed before it has been registered. + */ + static final class NotRegisteredException extends IllegalStateException { + + private static final String MESSAGE = """ + Could not access the HuskSync API as it has not yet been registered. This could be because: + 1) HuskSync has failed to enable successfully + 2) Your plugin isn't set to load after HuskSync has + (Check if it set as a (soft)depend in plugin.yml or to load: BEFORE in paper-plugin.yml?) + 3) You are attempting to access HuskSync on plugin construction/before your plugin has enabled. + 4) You have shaded HuskSync into your plugin jar and need to fix your maven/gradle/build script + to only include HuskSync as a dependency and not as a shaded dependency."""; + + NotRegisteredException() { + super(MESSAGE); + } + + } + +} diff --git a/common/src/main/java/net/william278/husksync/command/Command.java b/common/src/main/java/net/william278/husksync/command/Command.java new file mode 100644 index 00000000..5e9fb59b --- /dev/null +++ b/common/src/main/java/net/william278/husksync/command/Command.java @@ -0,0 +1,84 @@ +/* + * This file is part of HuskSync, licensed under the Apache License 2.0. + * + * Copyright (c) William278 + * Copyright (c) contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.william278.husksync.command; + +import net.william278.husksync.HuskSync; +import net.william278.husksync.user.CommandUser; +import org.jetbrains.annotations.NotNull; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public abstract class Command extends Node { + + private final String usage; + private final Map additionalPermissions; + + protected Command(@NotNull String name, @NotNull List aliases, @NotNull String usage, + @NotNull HuskSync plugin) { + super(name, aliases, plugin); + this.usage = usage; + this.additionalPermissions = new HashMap<>(); + } + + @Override + public final void onExecuted(@NotNull CommandUser executor, @NotNull String[] args) { + if (!executor.hasPermission(getPermission())) { + plugin.getLocales().getLocale("error_no_permission") + .ifPresent(executor::sendMessage); + return; + } + plugin.runAsync(() -> this.execute(executor, args)); + } + + public abstract void execute(@NotNull CommandUser executor, @NotNull String[] args); + + @NotNull + public final String getRawUsage() { + return usage; + } + + @NotNull + public final String getUsage() { + return "/" + getName() + " " + getRawUsage(); + } + + public final void addAdditionalPermissions(@NotNull Map permissions) { + permissions.forEach((permission, value) -> this.additionalPermissions.put(getPermission(permission), value)); + } + + @NotNull + public final Map getAdditionalPermissions() { + return additionalPermissions; + } + + @NotNull + public String getDescription() { + return plugin.getLocales().getRawLocale(getName() + "_command_description") + .orElse(getUsage()); + } + + @NotNull + public final HuskSync getPlugin() { + return plugin; + } + +} \ No newline at end of file diff --git a/common/src/main/java/net/william278/husksync/command/CommandBase.java b/common/src/main/java/net/william278/husksync/command/CommandBase.java deleted file mode 100644 index d4fb126a..00000000 --- a/common/src/main/java/net/william278/husksync/command/CommandBase.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * This file is part of HuskSync, licensed under the Apache License 2.0. - * - * Copyright (c) William278 - * Copyright (c) contributors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.william278.husksync.command; - -import net.william278.husksync.HuskSync; -import net.william278.husksync.player.OnlineUser; -import org.jetbrains.annotations.NotNull; - -/** - * Represents an abstract cross-platform representation for a plugin command - */ -public abstract class CommandBase { - - /** - * The input string to match for this command - */ - public final String command; - - /** - * The permission node required to use this command - */ - public final String permission; - - /** - * Alias input strings for this command - */ - public final String[] aliases; - - /** - * Instance of the implementing plugin - */ - public final HuskSync plugin; - - - public CommandBase(@NotNull String command, @NotNull Permission permission, @NotNull HuskSync implementor, String... aliases) { - this.command = command; - this.permission = permission.node; - this.plugin = implementor; - this.aliases = aliases; - } - - /** - * Fires when the command is executed - * - * @param player {@link OnlineUser} executing the command - * @param args Command arguments - */ - public abstract void onExecute(@NotNull OnlineUser player, @NotNull String[] args); - - /** - * Returns the localised description string of this command - * - * @return the command description - */ - public String getDescription() { - return plugin.getLocales().getRawLocale(command + "_command_description") - .orElse("A HuskSync command"); - } - -} diff --git a/common/src/main/java/net/william278/husksync/command/EnderChestCommand.java b/common/src/main/java/net/william278/husksync/command/EnderChestCommand.java index c7071d41..ea09088f 100644 --- a/common/src/main/java/net/william278/husksync/command/EnderChestCommand.java +++ b/common/src/main/java/net/william278/husksync/command/EnderChestCommand.java @@ -21,112 +21,72 @@ package net.william278.husksync.command; import de.themoep.minedown.adventure.MineDown; import net.william278.husksync.HuskSync; -import net.william278.husksync.data.DataSaveCause; -import net.william278.husksync.data.UserData; -import net.william278.husksync.data.UserDataBuilder; -import net.william278.husksync.data.UserDataSnapshot; -import net.william278.husksync.player.OnlineUser; -import net.william278.husksync.player.User; +import net.william278.husksync.data.Data; +import net.william278.husksync.data.DataSnapshot; +import net.william278.husksync.user.OnlineUser; +import net.william278.husksync.user.User; import org.jetbrains.annotations.NotNull; -import java.text.SimpleDateFormat; +import java.time.format.DateTimeFormatter; import java.util.List; -import java.util.Locale; import java.util.Optional; -import java.util.UUID; -import java.util.concurrent.CompletableFuture; -import java.util.logging.Level; -import java.util.stream.Collectors; -public class EnderChestCommand extends CommandBase implements TabCompletable { +public class EnderChestCommand extends ItemsCommand { - public EnderChestCommand(@NotNull HuskSync implementor) { - super("enderchest", Permission.COMMAND_ENDER_CHEST, implementor, "echest", "openechest"); + public EnderChestCommand(@NotNull HuskSync plugin) { + super(plugin, List.of("enderchest", "echest", "openechest")); } @Override - public void onExecute(@NotNull OnlineUser player, @NotNull String[] args) { - if (args.length == 0 || args.length > 2) { - plugin.getLocales().getLocale("error_invalid_syntax", "/enderchest ") - .ifPresent(player::sendMessage); + protected void showItems(@NotNull OnlineUser viewer, @NotNull DataSnapshot.Unpacked snapshot, + @NotNull User user, boolean allowEdit) { + final Optional optionalEnderChest = snapshot.getEnderChest(); + if (optionalEnderChest.isEmpty()) { + plugin.getLocales().getLocale("error_no_data_to_display") + .ifPresent(viewer::sendMessage); return; } - plugin.getDatabase().getUserByName(args[0].toLowerCase(Locale.ENGLISH)).thenAccept(optionalUser -> - optionalUser.ifPresentOrElse(user -> { - if (args.length == 2) { - // View user data by specified UUID - try { - final UUID versionUuid = UUID.fromString(args[1]); - plugin.getDatabase().getUserData(user, versionUuid).thenAccept(data -> data.ifPresentOrElse( - userData -> showEnderChestMenu(player, userData, user, false), - () -> plugin.getLocales().getLocale("error_invalid_version_uuid") - .ifPresent(player::sendMessage))); - } catch (IllegalArgumentException e) { - plugin.getLocales().getLocale("error_invalid_syntax", - "/enderchest [version_uuid]").ifPresent(player::sendMessage); - } - } else { - // View (and edit) the latest user data - plugin.getDatabase().getCurrentUserData(user).thenAccept(optionalData -> optionalData.ifPresentOrElse( - versionedUserData -> showEnderChestMenu(player, versionedUserData, user, - player.hasPermission(Permission.COMMAND_ENDER_CHEST_EDIT.node)), - () -> plugin.getLocales().getLocale("error_no_data_to_display") - .ifPresent(player::sendMessage))); - } - }, () -> plugin.getLocales().getLocale("error_invalid_player") - .ifPresent(player::sendMessage))); - } - private void showEnderChestMenu(@NotNull OnlineUser player, @NotNull UserDataSnapshot userDataSnapshot, - @NotNull User dataOwner, boolean allowEdit) { - CompletableFuture.runAsync(() -> { - final UserData data = userDataSnapshot.userData(); - data.getEnderChest().ifPresent(itemData -> { - // Show message - plugin.getLocales().getLocale("ender_chest_viewer_opened", dataOwner.username, - new SimpleDateFormat("MMM dd yyyy, HH:mm:ss.sss") - .format(userDataSnapshot.versionTimestamp())) - .ifPresent(player::sendMessage); + // Display opening message + plugin.getLocales().getLocale("ender_chest_viewer_opened", user.getUsername(), + snapshot.getTimestamp().format(DateTimeFormatter.ofPattern("dd/MM/yyyy, HH:mm"))) + .ifPresent(viewer::sendMessage); - // Show inventory menu - player.showMenu(itemData, allowEdit, 3, plugin.getLocales() - .getLocale("ender_chest_viewer_menu_title", dataOwner.username) - .orElse(new MineDown("Ender Chest Viewer"))) - .exceptionally(throwable -> { - plugin.log(Level.WARNING, "Exception displaying inventory menu to " + player.username, throwable); - return Optional.empty(); - }) - .thenAccept(dataOnClose -> { - if (dataOnClose.isEmpty() || !allowEdit) { - return; - } + // Show GUI + final Data.Items.EnderChest enderChest = optionalEnderChest.get(); + viewer.showGui( + enderChest, + plugin.getLocales().getLocale("ender_chest_viewer_menu_title", user.getUsername()) + .orElse(new MineDown(String.format("%s's Ender Chest", user.getUsername()))), + allowEdit, + enderChest.getSlotCount(), + (itemsOnClose) -> { + if (allowEdit && !enderChest.equals(itemsOnClose)) { + plugin.runAsync(() -> this.updateItems(viewer, itemsOnClose, user)); + } + } + ); + } - // Create the updated data - final UserDataBuilder builder = UserData.builder(plugin.getMinecraftVersion()); - data.getStatus().ifPresent(builder::setStatus); - data.getAdvancements().ifPresent(builder::setAdvancements); - data.getLocation().ifPresent(builder::setLocation); - data.getPersistentDataContainer().ifPresent(builder::setPersistentDataContainer); - data.getStatistics().ifPresent(builder::setStatistics); - data.getPotionEffects().ifPresent(builder::setPotionEffects); - data.getInventory().ifPresent(builder::setInventory); - builder.setEnderChest(dataOnClose.get()); + // Creates a new snapshot with the updated enderChest + @SuppressWarnings("DuplicatedCode") + private void updateItems(@NotNull OnlineUser viewer, @NotNull Data.Items.Items items, @NotNull User user) { + final Optional latestData = plugin.getDatabase().getLatestSnapshot(user); + if (latestData.isEmpty()) { + plugin.getLocales().getLocale("error_no_data_to_display") + .ifPresent(viewer::sendMessage); + return; + } - // Set the updated data - final UserData updatedUserData = builder.build(); - plugin.getDatabase() - .setUserData(dataOwner, updatedUserData, DataSaveCause.INVENTORY_COMMAND) - .thenRun(() -> plugin.getRedisManager().sendUserDataUpdate(dataOwner, updatedUserData)); - }); - }); + // Create and pack the snapshot with the updated enderChest + final DataSnapshot.Packed snapshot = latestData.get().copy(); + snapshot.edit(plugin, (data) -> { + data.setSaveCause(DataSnapshot.SaveCause.ENDERCHEST_COMMAND); + data.setPinned(plugin.getSettings().doAutoPin(DataSnapshot.SaveCause.ENDERCHEST_COMMAND)); + data.getEnderChest().ifPresent(enderChest -> enderChest.setContents(items)); }); - } - - @Override - public List onTabComplete(@NotNull String[] args) { - return plugin.getOnlineUsers().stream().map(user -> user.username) - .filter(argument -> argument.startsWith(args.length >= 1 ? args[0] : "")) - .sorted().collect(Collectors.toList()); + plugin.getDatabase().addSnapshot(user, snapshot); + plugin.getRedisManager().sendUserDataUpdate(user, snapshot); } } diff --git a/common/src/main/java/net/william278/husksync/command/ConsoleExecutable.java b/common/src/main/java/net/william278/husksync/command/Executable.java similarity index 75% rename from common/src/main/java/net/william278/husksync/command/ConsoleExecutable.java rename to common/src/main/java/net/william278/husksync/command/Executable.java index d633285a..cc7890a7 100644 --- a/common/src/main/java/net/william278/husksync/command/ConsoleExecutable.java +++ b/common/src/main/java/net/william278/husksync/command/Executable.java @@ -19,18 +19,11 @@ package net.william278.husksync.command; +import net.william278.husksync.user.CommandUser; import org.jetbrains.annotations.NotNull; -/** - * Interface providing console execution of commands - */ -public interface ConsoleExecutable { +public interface Executable { - /** - * What to do when console executes a command - * - * @param args command argument strings - */ - void onConsoleExecute(@NotNull String[] args); + void onExecuted(@NotNull CommandUser executor, @NotNull String[] args); } diff --git a/common/src/main/java/net/william278/husksync/command/HuskSyncCommand.java b/common/src/main/java/net/william278/husksync/command/HuskSyncCommand.java index 06f233c0..e6154a9f 100644 --- a/common/src/main/java/net/william278/husksync/command/HuskSyncCommand.java +++ b/common/src/main/java/net/william278/husksync/command/HuskSyncCommand.java @@ -23,26 +23,39 @@ import de.themoep.minedown.adventure.MineDown; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.format.TextColor; import net.william278.desertwell.about.AboutMenu; +import net.william278.desertwell.util.UpdateChecker; import net.william278.husksync.HuskSync; import net.william278.husksync.migrator.Migrator; -import net.william278.husksync.player.OnlineUser; +import net.william278.husksync.user.CommandUser; +import net.william278.husksync.user.OnlineUser; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import java.util.*; import java.util.logging.Level; import java.util.stream.Collectors; -public class HuskSyncCommand extends CommandBase implements TabCompletable, ConsoleExecutable { +public class HuskSyncCommand extends Command implements TabProvider { - private final String[] SUB_COMMANDS = {"update", "about", "reload", "migrate"}; + private static final Map SUB_COMMANDS = Map.of( + "about", false, + "reload", true, + "migrate", true, + "update", true + ); + + private final UpdateChecker updateChecker; private final AboutMenu aboutMenu; - public HuskSyncCommand(@NotNull HuskSync implementor) { - super("husksync", Permission.COMMAND_HUSKSYNC, implementor); + public HuskSyncCommand(@NotNull HuskSync plugin) { + super("husksync", List.of(), "[" + String.join("|", SUB_COMMANDS.keySet()) + "]", plugin); + addAdditionalPermissions(SUB_COMMANDS); + + this.updateChecker = plugin.getUpdateChecker(); this.aboutMenu = AboutMenu.builder() .title(Component.text("HuskSync")) .description(Component.text("A modern, cross-server player data synchronization system")) - .version(implementor.getPluginVersion()) + .version(plugin.getPluginVersion()) .credits("Author", AboutMenu.Credit.of("William278").description("Click to visit website").url("https://william278.net")) .credits("Contributors", @@ -68,123 +81,104 @@ public class HuskSyncCommand extends CommandBase implements TabCompletable, Cons } @Override - public void onExecute(@NotNull OnlineUser player, @NotNull String[] args) { - if (args.length < 1) { - sendAboutMenu(player); + public void execute(@NotNull CommandUser executor, @NotNull String[] args) { + final String subCommand = parseStringArg(args, 0).orElse("about").toLowerCase(Locale.ENGLISH); + if (SUB_COMMANDS.containsKey(subCommand) && !executor.hasPermission(getPermission(subCommand))) { + plugin.getLocales().getLocale("error_no_permission") + .ifPresent(executor::sendMessage); return; } - switch (args[0].toLowerCase(Locale.ENGLISH)) { - case "update", "version" -> { - if (!player.hasPermission(Permission.COMMAND_HUSKSYNC_UPDATE.node)) { - plugin.getLocales().getLocale("error_no_permission").ifPresent(player::sendMessage); - return; + + switch (subCommand) { + case "about" -> executor.sendMessage(aboutMenu.toComponent()); + case "reload" -> { + try { + plugin.loadConfigs(); + plugin.getLocales().getLocale("reload_complete").ifPresent(executor::sendMessage); + } catch (Throwable e) { + executor.sendMessage(new MineDown( + "[Error:](#ff3300) [Failed to reload the plugin. Check console for errors.](#ff7e5e)" + )); + plugin.log(Level.SEVERE, "Failed to reload the plugin", e); } - plugin.getLatestVersionIfOutdated().thenAccept(newestVersion -> - newestVersion.ifPresentOrElse( - newVersion -> player.sendMessage( - new MineDown("[HuskSync](#00fb9a bold) [| A new version of HuskSync is available!" - + " (v" + newVersion + " (Running: v" + plugin.getPluginVersion() + ")](#00fb9a)")), - () -> player.sendMessage( - new MineDown("[HuskSync](#00fb9a bold) [| HuskSync is up-to-date." - + " (Running: v" + plugin.getPluginVersion() + ")](#00fb9a)")))); } - case "about", "info" -> sendAboutMenu(player); - case "reload" -> { - if (!player.hasPermission(Permission.COMMAND_HUSKSYNC_RELOAD.node)) { - plugin.getLocales().getLocale("error_no_permission").ifPresent(player::sendMessage); + case "migrate" -> { + if (executor instanceof OnlineUser) { + plugin.getLocales().getLocale("error_console_command_only") + .ifPresent(executor::sendMessage); return; } - plugin.reload(); - plugin.getLocales().getLocale("reload_complete").ifPresent(player::sendMessage); + this.handleMigrationCommand(args); } - case "migrate" -> - plugin.getLocales().getLocale("error_console_command_only").ifPresent(player::sendMessage); - default -> plugin.getLocales().getLocale("error_invalid_syntax", - "/husksync ") - .ifPresent(player::sendMessage); + case "update" -> updateChecker.check().thenAccept(checked -> { + if (checked.isUpToDate()) { + plugin.getLocales().getLocale("up_to_date", plugin.getPluginVersion().toString()) + .ifPresent(executor::sendMessage); + return; + } + plugin.getLocales().getLocale("update_available", checked.getLatestVersion().toString(), + plugin.getPluginVersion().toString()).ifPresent(executor::sendMessage); + }); + default -> plugin.getLocales().getLocale("error_invalid_syntax", getUsage()) + .ifPresent(executor::sendMessage); } } - @Override - public void onConsoleExecute(@NotNull String[] args) { - if (args.length < 1) { - plugin.log(Level.INFO, "Console usage: \"husksync \""); + // Handle a migration console command input + private void handleMigrationCommand(@NotNull String[] args) { + if (args.length < 2) { + plugin.log(Level.INFO, + "Please choose a migrator, then run \"husksync migrate \""); + this.logMigratorList(); return; } - switch (args[0].toLowerCase(Locale.ENGLISH)) { - case "update", "version" -> plugin.getLatestVersionIfOutdated().thenAccept(newestVersion -> - newestVersion.ifPresentOrElse(newVersion -> plugin.log(Level.WARNING, - "An update is available for HuskSync, v" + newVersion - + " (Running v" + plugin.getPluginVersion() + ")"), - () -> plugin.log(Level.INFO, - "HuskSync is up to date" + - " (Running v" + plugin.getPluginVersion() + ")"))); - case "about", "info" -> aboutMenu.toString().lines().forEach(line -> plugin.log(Level.INFO, line)); - case "reload" -> { - plugin.reload(); - plugin.log(Level.INFO, "Reloaded config & message files."); + + final Optional selectedMigrator = plugin.getAvailableMigrators().stream() + .filter(available -> available.getIdentifier().equalsIgnoreCase(args[1])) + .findFirst(); + selectedMigrator.ifPresentOrElse(migrator -> { + if (args.length < 3) { + plugin.log(Level.INFO, migrator.getHelpMenu()); + return; } - case "migrate" -> { - if (args.length < 2) { - plugin.log(Level.INFO, - "Please choose a migrator, then run \"husksync migrate \""); - logMigratorsList(); - return; - } - final Optional selectedMigrator = plugin.getAvailableMigrators().stream().filter(availableMigrator -> - availableMigrator.getIdentifier().equalsIgnoreCase(args[1])).findFirst(); - selectedMigrator.ifPresentOrElse(migrator -> { - if (args.length < 3) { - plugin.log(Level.INFO, migrator.getHelpMenu()); - return; + switch (args[2]) { + case "start" -> migrator.start().thenAccept(succeeded -> { + if (succeeded) { + plugin.log(Level.INFO, "Migration completed successfully!"); + } else { + plugin.log(Level.WARNING, "Migration failed!"); } - switch (args[2]) { - case "start" -> migrator.start().thenAccept(succeeded -> { - if (succeeded) { - plugin.log(Level.INFO, "Migration completed successfully!"); - } else { - plugin.log(Level.WARNING, "Migration failed!"); - } - }); - case "set" -> migrator.handleConfigurationCommand(Arrays.copyOfRange(args, 3, args.length)); - default -> plugin.log(Level.INFO, - "Invalid syntax. Console usage: \"husksync migrate " + args[1] + " "); - } - }, () -> { - plugin.log(Level.INFO, - "Please specify a valid migrator.\n" + - "If a migrator is not available, please verify that you meet the prerequisites to use it."); - logMigratorsList(); }); + case "set" -> migrator.handleConfigurationCommand(Arrays.copyOfRange(args, 3, args.length)); + default -> plugin.log(Level.INFO, String.format( + "Invalid syntax. Console usage: \"husksync migrate %s ", args[1] + )); } - default -> plugin.log(Level.INFO, - "Invalid syntax. Console usage: \"husksync \""); - } + }, () -> { + plugin.log(Level.INFO, + "Please specify a valid migrator.\n" + + "If a migrator is not available, please verify that you meet the prerequisites to use it."); + this.logMigratorList(); + }); } - private void logMigratorsList() { - plugin.log(Level.INFO, - "List of available migrators:\nMigrator ID / Migrator Name:\n" + + // Log the list of available migrators + private void logMigratorList() { + plugin.log(Level.INFO, String.format( + "List of available migrators:\nMigrator ID / Migrator Name:\n%s", plugin.getAvailableMigrators().stream() - .map(migrator -> migrator.getIdentifier() + " - " + migrator.getName()) - .collect(Collectors.joining("\n"))); + .map(migrator -> String.format("%s - %s", migrator.getIdentifier(), migrator.getName())) + .collect(Collectors.joining("\n")) + )); } + @Nullable @Override - public List onTabComplete(@NotNull String[] args) { - if (args.length <= 1) { - return Arrays.stream(SUB_COMMANDS) - .filter(argument -> argument.startsWith(args.length == 1 ? args[0] : "")) - .sorted().collect(Collectors.toList()); - } - return Collections.emptyList(); + public List suggest(@NotNull CommandUser user, @NotNull String[] args) { + return switch (args.length) { + case 0, 1 -> SUB_COMMANDS.keySet().stream().sorted().toList(); + default -> null; + }; } - private void sendAboutMenu(@NotNull OnlineUser player) { - if (!player.hasPermission(Permission.COMMAND_HUSKSYNC_ABOUT.node)) { - plugin.getLocales().getLocale("error_no_permission").ifPresent(player::sendMessage); - return; - } - player.sendMessage(aboutMenu.toComponent()); - } } diff --git a/common/src/main/java/net/william278/husksync/command/InventoryCommand.java b/common/src/main/java/net/william278/husksync/command/InventoryCommand.java index 9d1fa651..3cfa93e6 100644 --- a/common/src/main/java/net/william278/husksync/command/InventoryCommand.java +++ b/common/src/main/java/net/william278/husksync/command/InventoryCommand.java @@ -21,111 +21,72 @@ package net.william278.husksync.command; import de.themoep.minedown.adventure.MineDown; import net.william278.husksync.HuskSync; -import net.william278.husksync.data.DataSaveCause; -import net.william278.husksync.data.UserData; -import net.william278.husksync.data.UserDataBuilder; -import net.william278.husksync.data.UserDataSnapshot; -import net.william278.husksync.player.OnlineUser; -import net.william278.husksync.player.User; +import net.william278.husksync.data.Data; +import net.william278.husksync.data.DataSnapshot; +import net.william278.husksync.user.OnlineUser; +import net.william278.husksync.user.User; import org.jetbrains.annotations.NotNull; -import java.text.SimpleDateFormat; +import java.time.format.DateTimeFormatter; import java.util.List; -import java.util.Locale; import java.util.Optional; -import java.util.UUID; -import java.util.concurrent.CompletableFuture; -import java.util.logging.Level; -import java.util.stream.Collectors; -public class InventoryCommand extends CommandBase implements TabCompletable { +public class InventoryCommand extends ItemsCommand { - public InventoryCommand(@NotNull HuskSync implementor) { - super("inventory", Permission.COMMAND_INVENTORY, implementor, "invsee", "openinv"); + public InventoryCommand(@NotNull HuskSync plugin) { + super(plugin, List.of("inventory", "invsee", "openinv")); } @Override - public void onExecute(@NotNull OnlineUser player, @NotNull String[] args) { - if (args.length == 0 || args.length > 2) { - plugin.getLocales().getLocale("error_invalid_syntax", "/inventory ") - .ifPresent(player::sendMessage); + protected void showItems(@NotNull OnlineUser viewer, @NotNull DataSnapshot.Unpacked snapshot, + @NotNull User user, boolean allowEdit) { + final Optional optionalInventory = snapshot.getInventory(); + if (optionalInventory.isEmpty()) { + plugin.getLocales().getLocale("error_no_data_to_display") + .ifPresent(viewer::sendMessage); return; } - plugin.getDatabase().getUserByName(args[0].toLowerCase(Locale.ENGLISH)).thenAccept(optionalUser -> - optionalUser.ifPresentOrElse(user -> { - if (args.length == 2) { - // View user data by specified UUID - try { - final UUID versionUuid = UUID.fromString(args[1]); - plugin.getDatabase().getUserData(user, versionUuid).thenAccept(data -> data.ifPresentOrElse( - userData -> showInventoryMenu(player, userData, user, false), - () -> plugin.getLocales().getLocale("error_invalid_version_uuid") - .ifPresent(player::sendMessage))); - } catch (IllegalArgumentException e) { - plugin.getLocales().getLocale("error_invalid_syntax", - "/inventory [version_uuid]").ifPresent(player::sendMessage); - } - } else { - // View (and edit) the latest user data - plugin.getDatabase().getCurrentUserData(user).thenAccept(optionalData -> optionalData.ifPresentOrElse( - versionedUserData -> showInventoryMenu(player, versionedUserData, user, - player.hasPermission(Permission.COMMAND_INVENTORY_EDIT.node)), - () -> plugin.getLocales().getLocale("error_no_data_to_display") - .ifPresent(player::sendMessage))); - } - }, () -> plugin.getLocales().getLocale("error_invalid_player") - .ifPresent(player::sendMessage))); - } - private void showInventoryMenu(@NotNull OnlineUser player, @NotNull UserDataSnapshot userDataSnapshot, - @NotNull User dataOwner, boolean allowEdit) { - CompletableFuture.runAsync(() -> { - final UserData data = userDataSnapshot.userData(); - data.getInventory().ifPresent(itemData -> { - // Show message - plugin.getLocales().getLocale("inventory_viewer_opened", dataOwner.username, - new SimpleDateFormat("MMM dd yyyy, HH:mm:ss.sss") - .format(userDataSnapshot.versionTimestamp())) - .ifPresent(player::sendMessage); + // Display opening message + plugin.getLocales().getLocale("inventory_viewer_opened", user.getUsername(), + snapshot.getTimestamp().format(DateTimeFormatter.ofPattern("dd/MM/yyyy, HH:mm"))) + .ifPresent(viewer::sendMessage); - // Show inventory menu - player.showMenu(itemData, allowEdit, 5, plugin.getLocales() - .getLocale("inventory_viewer_menu_title", dataOwner.username) - .orElse(new MineDown("Inventory Viewer"))) - .exceptionally(throwable -> { - plugin.log(Level.WARNING, "Exception displaying inventory menu to " + player.username, throwable); - return Optional.empty(); - }) - .thenAccept(dataOnClose -> { - if (dataOnClose.isEmpty() || !allowEdit) { - return; - } + // Show GUI + final Data.Items.Inventory inventory = optionalInventory.get(); + viewer.showGui( + inventory, + plugin.getLocales().getLocale("inventory_viewer_menu_title", user.getUsername()) + .orElse(new MineDown(String.format("%s's Inventory", user.getUsername()))), + allowEdit, + inventory.getSlotCount(), + (itemsOnClose) -> { + if (allowEdit && !inventory.equals(itemsOnClose)) { + plugin.runAsync(() -> this.updateItems(viewer, itemsOnClose, user)); + } + } + ); + } - // Create the updated data - final UserDataBuilder builder = UserData.builder(plugin.getMinecraftVersion()); - data.getStatus().ifPresent(builder::setStatus); - data.getAdvancements().ifPresent(builder::setAdvancements); - data.getLocation().ifPresent(builder::setLocation); - data.getPersistentDataContainer().ifPresent(builder::setPersistentDataContainer); - data.getStatistics().ifPresent(builder::setStatistics); - data.getPotionEffects().ifPresent(builder::setPotionEffects); - data.getEnderChest().ifPresent(builder::setEnderChest); - builder.setInventory(dataOnClose.get()); + // Creates a new snapshot with the updated inventory + @SuppressWarnings("DuplicatedCode") + private void updateItems(@NotNull OnlineUser viewer, @NotNull Data.Items.Items items, @NotNull User user) { + final Optional latestData = plugin.getDatabase().getLatestSnapshot(user); + if (latestData.isEmpty()) { + plugin.getLocales().getLocale("error_no_data_to_display") + .ifPresent(viewer::sendMessage); + return; + } - // Set the updated data - final UserData updatedUserData = builder.build(); - plugin.getDatabase() - .setUserData(dataOwner, updatedUserData, DataSaveCause.INVENTORY_COMMAND) - .thenRun(() -> plugin.getRedisManager().sendUserDataUpdate(dataOwner, updatedUserData)); - }); - }); + // Create and pack the snapshot with the updated inventory + final DataSnapshot.Packed snapshot = latestData.get().copy(); + snapshot.edit(plugin, (data) -> { + data.setSaveCause(DataSnapshot.SaveCause.INVENTORY_COMMAND); + data.setPinned(plugin.getSettings().doAutoPin(DataSnapshot.SaveCause.INVENTORY_COMMAND)); + data.getInventory().ifPresent(inventory -> inventory.setContents(items)); }); + plugin.getDatabase().addSnapshot(user, snapshot); + plugin.getRedisManager().sendUserDataUpdate(user, snapshot); } - @Override - public List onTabComplete(@NotNull String[] args) { - return plugin.getOnlineUsers().stream().map(user -> user.username) - .filter(argument -> argument.startsWith(args.length >= 1 ? args[0] : "")) - .sorted().collect(Collectors.toList()); - } } diff --git a/common/src/main/java/net/william278/husksync/command/ItemsCommand.java b/common/src/main/java/net/william278/husksync/command/ItemsCommand.java new file mode 100644 index 00000000..c8687141 --- /dev/null +++ b/common/src/main/java/net/william278/husksync/command/ItemsCommand.java @@ -0,0 +1,108 @@ +/* + * This file is part of HuskSync, licensed under the Apache License 2.0. + * + * Copyright (c) William278 + * Copyright (c) contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.william278.husksync.command; + +import net.william278.husksync.HuskSync; +import net.william278.husksync.data.DataSnapshot; +import net.william278.husksync.user.CommandUser; +import net.william278.husksync.user.OnlineUser; +import net.william278.husksync.user.User; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; + +public abstract class ItemsCommand extends Command implements TabProvider { + + protected ItemsCommand(@NotNull HuskSync plugin, @NotNull List aliases) { + super(aliases.get(0), aliases.subList(1, aliases.size()), " [version_uuid]", plugin); + setOperatorCommand(true); + addAdditionalPermissions(Map.of("edit", true)); + } + + + @Override + public void execute(@NotNull CommandUser executor, @NotNull String[] args) { + if (!(executor instanceof OnlineUser player)) { + plugin.getLocales().getLocale("error_in_game_command_only") + .ifPresent(executor::sendMessage); + return; + } + + // Find the user to view the items for + final Optional optionalUser = parseStringArg(args, 0) + .flatMap(name -> plugin.getDatabase().getUserByName(name)); + if (optionalUser.isEmpty()) { + plugin.getLocales().getLocale( + args.length >= 1 ? "error_invalid_player" : "error_invalid_syntax", getUsage() + ).ifPresent(player::sendMessage); + return; + } + + // Show the user data + final User user = optionalUser.get(); + parseUUIDArg(args, 1).ifPresentOrElse( + version -> this.showSnapshotItems(player, user, version), + () -> this.showLatestItems(player, user) + ); + } + + // View (and edit) the latest user data + private void showLatestItems(@NotNull OnlineUser viewer, @NotNull User user) { + plugin.getRedisManager().getUserData(user.getUuid(), user).thenAccept(data -> data + .or(() -> plugin.getDatabase().getLatestSnapshot(user)) + .ifPresentOrElse( + snapshot -> this.showItems( + viewer, snapshot.unpack(plugin), user, + viewer.hasPermission(getPermission("edit")) + ), + () -> plugin.getLocales().getLocale("error_no_data_to_display") + .ifPresent(viewer::sendMessage) + )); + } + + // View a specific version of the user data + private void showSnapshotItems(@NotNull OnlineUser viewer, @NotNull User user, @NotNull UUID version) { + plugin.getDatabase().getSnapshot(user, version) + .ifPresentOrElse( + snapshot -> this.showItems( + viewer, snapshot.unpack(plugin), user, false + ), + () -> plugin.getLocales().getLocale("error_invalid_version_uuid") + .ifPresent(viewer::sendMessage) + ); + } + + // Show a GUI menu with the correct item data from the snapshot + protected abstract void showItems(@NotNull OnlineUser viewer, @NotNull DataSnapshot.Unpacked snapshot, + @NotNull User user, boolean allowEdit); + + @Nullable + @Override + public List suggest(@NotNull CommandUser executor, @NotNull String[] args) { + return switch (args.length) { + case 0, 1 -> plugin.getOnlineUsers().stream().map(User::getUsername).toList(); + default -> null; + }; + } +} diff --git a/common/src/main/java/net/william278/husksync/command/Node.java b/common/src/main/java/net/william278/husksync/command/Node.java new file mode 100644 index 00000000..86635e2f --- /dev/null +++ b/common/src/main/java/net/william278/husksync/command/Node.java @@ -0,0 +1,105 @@ +/* + * This file is part of HuskSync, licensed under the Apache License 2.0. + * + * Copyright (c) William278 + * Copyright (c) contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.william278.husksync.command; + +import net.william278.husksync.HuskSync; +import org.jetbrains.annotations.NotNull; + +import java.util.List; +import java.util.Optional; +import java.util.StringJoiner; +import java.util.UUID; + +public abstract class Node implements Executable { + + protected static final String PERMISSION_PREFIX = "husksync.command"; + + protected final HuskSync plugin; + private final String name; + private final List aliases; + private boolean operatorCommand = false; + + protected Node(@NotNull String name, @NotNull List aliases, @NotNull HuskSync plugin) { + if (name.isBlank()) { + throw new IllegalArgumentException("Command name cannot be blank"); + } + this.name = name; + this.aliases = aliases; + this.plugin = plugin; + } + + @NotNull + public String getName() { + return name; + } + + @NotNull + public List getAliases() { + return aliases; + } + + @NotNull + public String getPermission(@NotNull String... child) { + final StringJoiner joiner = new StringJoiner(".") + .add(PERMISSION_PREFIX) + .add(getName()); + for (final String node : child) { + joiner.add(node); + } + return joiner.toString().trim(); + } + + public boolean isOperatorCommand() { + return operatorCommand; + } + + public void setOperatorCommand(boolean operatorCommand) { + this.operatorCommand = operatorCommand; + } + + protected Optional parseStringArg(@NotNull String[] args, int index) { + if (args.length > index) { + return Optional.of(args[index]); + } + return Optional.empty(); + } + + protected Optional parseIntArg(@NotNull String[] args, int index) { + return parseStringArg(args, index).flatMap(arg -> { + try { + return Optional.of(Integer.parseInt(arg)); + } catch (NumberFormatException e) { + return Optional.empty(); + } + }); + } + + protected Optional parseUUIDArg(@NotNull String[] args, int index) { + return parseStringArg(args, index).flatMap(arg -> { + try { + return Optional.of(UUID.fromString(arg)); + } catch (IllegalArgumentException e) { + return Optional.empty(); + } + }); + } + + +} \ No newline at end of file diff --git a/common/src/main/java/net/william278/husksync/command/Permission.java b/common/src/main/java/net/william278/husksync/command/Permission.java deleted file mode 100644 index 93af4228..00000000 --- a/common/src/main/java/net/william278/husksync/command/Permission.java +++ /dev/null @@ -1,120 +0,0 @@ -/* - * This file is part of HuskSync, licensed under the Apache License 2.0. - * - * Copyright (c) William278 - * Copyright (c) contributors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.william278.husksync.command; - -import org.jetbrains.annotations.NotNull; - -/** - * Static plugin permission nodes required to execute commands - */ -public enum Permission { - - /* - * /husksync command permissions - */ - - /** - * Lets the user use the {@code /husksync} command (subcommand permissions required) - */ - COMMAND_HUSKSYNC("husksync.command.husksync", DefaultAccess.EVERYONE), - /** - * Lets the user view plugin info {@code /husksync info} - */ - COMMAND_HUSKSYNC_ABOUT("husksync.command.husksync.info", DefaultAccess.EVERYONE), - /** - * Lets the user reload the plugin {@code /husksync reload} - */ - COMMAND_HUSKSYNC_RELOAD("husksync.command.husksync.reload", DefaultAccess.OPERATORS), - /** - * Lets the user view the plugin version and check for updates {@code /husksync update} - */ - COMMAND_HUSKSYNC_UPDATE("husksync.command.husksync.update", DefaultAccess.OPERATORS), - - /* - * /userdata command permissions - */ - - /** - * Lets the user view user data {@code /userdata view/list (player) (version_uuid)} - */ - COMMAND_USER_DATA("husksync.command.userdata", DefaultAccess.OPERATORS), - /** - * Lets the user restore and delete user data {@code /userdata restore/delete (player) (version_uuid)} - */ - COMMAND_USER_DATA_MANAGE("husksync.command.userdata.manage", DefaultAccess.OPERATORS), - - /** - * Lets the user dump user data to a file or the web {@code /userdata dump (player) (version_uuid)} - */ - COMMAND_USER_DATA_DUMP("husksync.command.userdata.dump", DefaultAccess.NOBODY), - - /* - * /inventory command permissions - */ - - /** - * Lets the user use the {@code /inventory (player)} command and view offline players' inventories - */ - COMMAND_INVENTORY("husksync.command.inventory", DefaultAccess.OPERATORS), - /** - * Lets the user edit the contents of offline players' inventories - */ - COMMAND_INVENTORY_EDIT("husksync.command.inventory.edit", DefaultAccess.OPERATORS), - - /* - * /enderchest command permissions - */ - - /** - * Lets the user use the {@code /enderchest (player)} command and view offline players' ender chests - */ - COMMAND_ENDER_CHEST("husksync.command.enderchest", DefaultAccess.OPERATORS), - /** - * Lets the user edit the contents of offline players' ender chests - */ - COMMAND_ENDER_CHEST_EDIT("husksync.command.enderchest.edit", DefaultAccess.OPERATORS); - - - public final String node; - public final DefaultAccess defaultAccess; - - Permission(@NotNull String node, @NotNull DefaultAccess defaultAccess) { - this.node = node; - this.defaultAccess = defaultAccess; - } - - /** - * Identifies who gets what permissions by default - */ - public enum DefaultAccess { - /** - * Everyone gets this permission node by default - */ - EVERYONE, - /** - * Nobody gets this permission node by default - */ - NOBODY, - /** - * Server operators ({@code /op}) get this permission node by default - */ - OPERATORS - } -} diff --git a/common/src/main/java/net/william278/husksync/command/TabCompletable.java b/common/src/main/java/net/william278/husksync/command/TabCompletable.java deleted file mode 100644 index a7e7e183..00000000 --- a/common/src/main/java/net/william278/husksync/command/TabCompletable.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * This file is part of HuskSync, licensed under the Apache License 2.0. - * - * Copyright (c) William278 - * Copyright (c) contributors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.william278.husksync.command; - -import org.jetbrains.annotations.NotNull; - -import java.util.List; - -/** - * Interface providing tab completions for a command - */ -public interface TabCompletable { - - /** - * What should be returned when the player or console attempts to TAB-complete a command - * - * @param args Current command arguments - * @return List of String arguments to offer TAB suggestions - */ - List onTabComplete(@NotNull String[] args); - -} diff --git a/common/src/main/java/net/william278/husksync/command/TabProvider.java b/common/src/main/java/net/william278/husksync/command/TabProvider.java new file mode 100644 index 00000000..48c2b72b --- /dev/null +++ b/common/src/main/java/net/william278/husksync/command/TabProvider.java @@ -0,0 +1,50 @@ +/* + * This file is part of HuskSync, licensed under the Apache License 2.0. + * + * Copyright (c) William278 + * Copyright (c) contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.william278.husksync.command; + +import net.william278.husksync.user.CommandUser; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.List; + +public interface TabProvider { + + @Nullable + List suggest(@NotNull CommandUser user, @NotNull String[] args); + + @NotNull + default List getSuggestions(@NotNull CommandUser user, @NotNull String[] args) { + List suggestions = suggest(user, args); + if (suggestions == null) { + suggestions = List.of(); + } + return filter(suggestions, args); + } + + @NotNull + default List filter(@NotNull List suggestions, @NotNull String[] args) { + return suggestions.stream() + .filter(suggestion -> args.length == 0 || suggestion.toLowerCase() + .startsWith(args[args.length - 1].toLowerCase().trim())) + .toList(); + } + +} \ No newline at end of file diff --git a/common/src/main/java/net/william278/husksync/command/UserDataCommand.java b/common/src/main/java/net/william278/husksync/command/UserDataCommand.java index 518df8fd..3bc55343 100644 --- a/common/src/main/java/net/william278/husksync/command/UserDataCommand.java +++ b/common/src/main/java/net/william278/husksync/command/UserDataCommand.java @@ -20,309 +20,216 @@ package net.william278.husksync.command; import net.william278.husksync.HuskSync; -import net.william278.husksync.data.DataSaveCause; -import net.william278.husksync.data.UserData; -import net.william278.husksync.player.OnlineUser; +import net.william278.husksync.data.DataSnapshot; +import net.william278.husksync.user.CommandUser; +import net.william278.husksync.user.User; import net.william278.husksync.util.DataDumper; import net.william278.husksync.util.DataSnapshotList; +import net.william278.husksync.util.DataSnapshotOverview; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import java.io.IOException; import java.util.*; -import java.util.concurrent.CompletableFuture; import java.util.logging.Level; -import java.util.stream.Collectors; -public class UserDataCommand extends CommandBase implements TabCompletable { +public class UserDataCommand extends Command implements TabProvider { - private final String[] COMMAND_ARGUMENTS = {"view", "list", "delete", "restore", "pin", "dump"}; + private static final Map SUB_COMMANDS = Map.of( + "view", false, + "list", false, + "delete", true, + "restore", true, + "pin", true, + "dump", true + ); - public UserDataCommand(@NotNull HuskSync implementor) { - super("userdata", Permission.COMMAND_USER_DATA, implementor, "playerdata"); + public UserDataCommand(@NotNull HuskSync plugin) { + super("userdata", List.of("playerdata"), String.format( + "<%s> [username] [version_uuid]", String.join("/", SUB_COMMANDS.keySet()) + ), plugin); + setOperatorCommand(true); + addAdditionalPermissions(SUB_COMMANDS); } @Override - public void onExecute(@NotNull OnlineUser player, @NotNull String[] args) { - if (args.length < 1) { - plugin.getLocales().getLocale("error_invalid_syntax", - "/userdata [version_uuid]") - .ifPresent(player::sendMessage); + public void execute(@NotNull CommandUser executor, @NotNull String[] args) { + final String subCommand = parseStringArg(args, 0).orElse("view").toLowerCase(Locale.ENGLISH); + final Optional optionalUser = parseStringArg(args, 1) + .flatMap(name -> plugin.getDatabase().getUserByName(name)) + .or(() -> parseStringArg(args, 0).flatMap(name -> plugin.getDatabase().getUserByName(name))) + .or(() -> args.length < 2 && executor instanceof User userExecutor + ? Optional.of(userExecutor) : Optional.empty()); + final Optional optionalUuid = parseUUIDArg(args, 2).or(() -> parseUUIDArg(args, 1)); + if (optionalUser.isEmpty()) { + plugin.getLocales().getLocale("error_invalid_player") + .ifPresent(executor::sendMessage); return; } - switch (args[0].toLowerCase(Locale.ENGLISH)) { - case "view" -> { - if (args.length < 2) { - plugin.getLocales().getLocale("error_invalid_syntax", - "/userdata view [version_uuid]") - .ifPresent(player::sendMessage); - return; - } - final String username = args[1]; - if (args.length >= 3) { - try { - final UUID versionUuid = UUID.fromString(args[2]); - CompletableFuture.runAsync(() -> plugin.getDatabase() - .getUserByName(username.toLowerCase(Locale.ENGLISH)) - .thenAccept(optionalUser -> optionalUser - .ifPresentOrElse(user -> plugin.getDatabase().getUserData(user, versionUuid) - .thenAccept(data -> data.ifPresentOrElse( - userData -> userData.displayDataOverview(player, user, plugin.getLocales()), - () -> plugin.getLocales().getLocale("error_invalid_version_uuid") - .ifPresent(player::sendMessage))), - () -> plugin.getLocales().getLocale("error_invalid_player") - .ifPresent(player::sendMessage)))); - } catch (IllegalArgumentException e) { - plugin.getLocales().getLocale("error_invalid_syntax", - "/userdata view [version_uuid]") - .ifPresent(player::sendMessage); - } - } else { - CompletableFuture.runAsync(() -> plugin.getDatabase() - .getUserByName(username.toLowerCase(Locale.ENGLISH)) - .thenAccept(optionalUser -> optionalUser - .ifPresentOrElse(user -> plugin.getDatabase().getCurrentUserData(user) - .thenAccept(latestData -> latestData.ifPresentOrElse( - userData -> userData.displayDataOverview(player, user, plugin.getLocales()), - () -> plugin.getLocales().getLocale("error_no_data_to_display") - .ifPresent(player::sendMessage))), - () -> plugin.getLocales().getLocale("error_invalid_player") - .ifPresent(player::sendMessage)))); - } - } + final User user = optionalUser.get(); + switch (subCommand) { + case "view" -> optionalUuid.ifPresentOrElse( + // Show the specified snapshot + version -> plugin.getDatabase().getSnapshot(user, version).ifPresentOrElse( + data -> DataSnapshotOverview.of( + data.unpack(plugin), data.getFileSize(plugin), user, plugin + ).show(executor), + () -> plugin.getLocales().getLocale("error_invalid_version_uuid") + .ifPresent(executor::sendMessage)), + + // Show the latest snapshot + () -> plugin.getDatabase().getLatestSnapshot(user).ifPresentOrElse( + data -> DataSnapshotOverview.of( + data.unpack(plugin), data.getFileSize(plugin), user, plugin + ).show(executor), + () -> plugin.getLocales().getLocale("error_no_data_to_display") + .ifPresent(executor::sendMessage)) + ); + case "list" -> { - if (!player.hasPermission(Permission.COMMAND_USER_DATA_MANAGE.node)) { - plugin.getLocales().getLocale("error_no_permission").ifPresent(player::sendMessage); - return; - } - if (args.length < 2) { - plugin.getLocales().getLocale("error_invalid_syntax", - "/userdata list [page]") - .ifPresent(player::sendMessage); + // Check if there is data to display + final List dataList = plugin.getDatabase().getAllSnapshots(user); + if (dataList.isEmpty()) { + plugin.getLocales().getLocale("error_no_data_to_display") + .ifPresent(executor::sendMessage); return; } - final String username = args[1]; - CompletableFuture.runAsync(() -> plugin.getDatabase() - .getUserByName(username.toLowerCase(Locale.ENGLISH)) - .thenAccept(optionalUser -> optionalUser.ifPresentOrElse( - user -> plugin.getDatabase().getUserData(user).thenAccept(dataList -> { - // Check if there is data to display - if (dataList.isEmpty()) { - plugin.getLocales().getLocale("error_no_data_to_display") - .ifPresent(player::sendMessage); - return; - } - // Determine page to display - int page = 1; - if (args.length >= 3) { - try { - page = Integer.parseInt(args[2]); - } catch (NumberFormatException e) { - plugin.getLocales().getLocale("error_invalid_syntax", - "/userdata list [page]") - .ifPresent(player::sendMessage); - return; - } - } - - // Show the list to the player - DataSnapshotList.create(dataList, user, plugin.getLocales()) - .displayPage(player, page); - }), - () -> plugin.getLocales().getLocale("error_invalid_player") - .ifPresent(player::sendMessage)))); + // Show the list to the player + DataSnapshotList.create(dataList, user, plugin).displayPage( + executor, + parseIntArg(args, 2).or(() -> parseIntArg(args, 1)).orElse(1) + ); } + case "delete" -> { - if (!player.hasPermission(Permission.COMMAND_USER_DATA_MANAGE.node)) { - plugin.getLocales().getLocale("error_no_permission").ifPresent(player::sendMessage); - return; - } - // Delete user data by specified UUID - if (args.length < 3) { + if (optionalUuid.isEmpty()) { plugin.getLocales().getLocale("error_invalid_syntax", "/userdata delete ") - .ifPresent(player::sendMessage); + .ifPresent(executor::sendMessage); return; } - final String username = args[1]; - try { - final UUID versionUuid = UUID.fromString(args[2]); - CompletableFuture.runAsync(() -> plugin.getDatabase() - .getUserByName(username.toLowerCase(Locale.ENGLISH)) - .thenAccept(optionalUser -> optionalUser.ifPresentOrElse( - user -> plugin.getDatabase().deleteUserData(user, versionUuid).thenAccept(deleted -> { - if (deleted) { - plugin.getLocales().getLocale("data_deleted", - versionUuid.toString().split("-")[0], - versionUuid.toString(), - user.username, - user.uuid.toString()) - .ifPresent(player::sendMessage); - } else { - plugin.getLocales().getLocale("error_invalid_version_uuid") - .ifPresent(player::sendMessage); - } - }), - () -> plugin.getLocales().getLocale("error_invalid_player") - .ifPresent(player::sendMessage)))); - } catch (IllegalArgumentException e) { - plugin.getLocales().getLocale("error_invalid_syntax", - "/userdata delete ") - .ifPresent(player::sendMessage); + + // Delete user data by specified UUID + final UUID version = optionalUuid.get(); + if (!plugin.getDatabase().deleteSnapshot(user, version)) { + plugin.getLocales().getLocale("error_invalid_version_uuid") + .ifPresent(executor::sendMessage); + return; } + + plugin.getLocales().getLocale("data_deleted", + version.toString().split("-")[0], + version.toString(), + user.getUsername(), + user.getUuid().toString()) + .ifPresent(executor::sendMessage); } + case "restore" -> { - if (!player.hasPermission(Permission.COMMAND_USER_DATA_MANAGE.node)) { - plugin.getLocales().getLocale("error_no_permission").ifPresent(player::sendMessage); + if (optionalUuid.isEmpty()) { + plugin.getLocales().getLocale("error_invalid_syntax", + "/userdata delete ") + .ifPresent(executor::sendMessage); return; } - // Get user data by specified uuid and username - if (args.length < 3) { - plugin.getLocales().getLocale("error_invalid_syntax", - "/userdata restore ") - .ifPresent(player::sendMessage); + + // Restore user data by specified UUID + final Optional optionalData = plugin.getDatabase().getSnapshot(user, optionalUuid.get()); + if (optionalData.isEmpty()) { + plugin.getLocales().getLocale("error_invalid_version_uuid") + .ifPresent(executor::sendMessage); return; } - final String username = args[1]; - try { - final UUID versionUuid = UUID.fromString(args[2]); - CompletableFuture.runAsync(() -> plugin.getDatabase() - .getUserByName(username.toLowerCase(Locale.ENGLISH)) - .thenAccept(optionalUser -> optionalUser.ifPresentOrElse( - user -> plugin.getDatabase().getUserData(user, versionUuid).thenAccept(data -> { - if (data.isEmpty()) { - plugin.getLocales().getLocale("error_invalid_version_uuid") - .ifPresent(player::sendMessage); - return; - } - // Restore users with a minimum of one health (prevent restoring players with <=0 health) - final UserData userData = data.get().userData(); - userData.getStatus().ifPresent(status -> status.health = Math.max(1, status.health)); + // Restore users with a minimum of one health (prevent restoring players with <=0 health) + final DataSnapshot.Packed data = optionalData.get().copy(); + data.edit(plugin, (unpacked -> { + unpacked.getHealth().ifPresent(status -> status.setHealth(Math.max(1, status.getHealth()))); + unpacked.setSaveCause(DataSnapshot.SaveCause.BACKUP_RESTORE); + unpacked.setPinned(plugin.getSettings().doAutoPin(DataSnapshot.SaveCause.BACKUP_RESTORE)); + })); - // Set the users data and send a message - plugin.getDatabase().setUserData(user, userData, DataSaveCause.BACKUP_RESTORE); - plugin.getRedisManager().sendUserDataUpdate(user, data.get().userData()).join(); - plugin.getLocales().getLocale("data_restored", - user.username, - user.uuid.toString(), - versionUuid.toString().split("-")[0], - versionUuid.toString()) - .ifPresent(player::sendMessage); - }), - () -> plugin.getLocales().getLocale("error_invalid_player") - .ifPresent(player::sendMessage)))); - } catch (IllegalArgumentException e) { - plugin.getLocales().getLocale("error_invalid_syntax", - "/userdata restore ") - .ifPresent(player::sendMessage); - } + // Set the user's data and send a message + plugin.getDatabase().addSnapshot(user, data); + plugin.getRedisManager().sendUserDataUpdate(user, data); + plugin.getLocales().getLocale("data_restored", user.getUsername(), user.getUuid().toString(), + data.getShortId(), data.getId().toString()).ifPresent(executor::sendMessage); } + case "pin" -> { - if (!player.hasPermission(Permission.COMMAND_USER_DATA_MANAGE.node)) { - plugin.getLocales().getLocale("error_no_permission").ifPresent(player::sendMessage); - return; - } - if (args.length < 3) { + if (optionalUuid.isEmpty()) { plugin.getLocales().getLocale("error_invalid_syntax", "/userdata pin ") - .ifPresent(player::sendMessage); + .ifPresent(executor::sendMessage); return; } - final String username = args[1]; - try { - final UUID versionUuid = UUID.fromString(args[2]); - CompletableFuture.runAsync(() -> plugin.getDatabase() - .getUserByName(username.toLowerCase(Locale.ENGLISH)) - .thenAccept(optionalUser -> optionalUser.ifPresentOrElse( - user -> plugin.getDatabase().getUserData(user, versionUuid).thenAccept( - optionalUserData -> optionalUserData.ifPresentOrElse(userData -> { - if (userData.pinned()) { - plugin.getDatabase().unpinUserData(user, versionUuid).join(); - plugin.getLocales().getLocale("data_unpinned", - versionUuid.toString().split("-")[0], - versionUuid.toString(), - user.username, - user.uuid.toString()) - .ifPresent(player::sendMessage); - } else { - plugin.getDatabase().pinUserData(user, versionUuid).join(); - plugin.getLocales().getLocale("data_pinned", - versionUuid.toString().split("-")[0], - versionUuid.toString(), - user.username, - user.uuid.toString()) - .ifPresent(player::sendMessage); - } - }, () -> plugin.getLocales().getLocale("error_invalid_version_uuid") - .ifPresent(player::sendMessage))), - () -> plugin.getLocales().getLocale("error_invalid_player") - .ifPresent(player::sendMessage)))); - } catch (IllegalArgumentException e) { - plugin.getLocales().getLocale("error_invalid_syntax", - "/userdata pin ") - .ifPresent(player::sendMessage); + // Check that the data exists + final Optional optionalData = plugin.getDatabase().getSnapshot(user, optionalUuid.get()); + if (optionalData.isEmpty()) { + plugin.getLocales().getLocale("error_invalid_version_uuid") + .ifPresent(executor::sendMessage); + return; + } + + // Pin or unpin the data + final DataSnapshot.Packed data = optionalData.get(); + if (data.isPinned()) { + plugin.getDatabase().unpinSnapshot(user, data.getId()); + } else { + plugin.getDatabase().pinSnapshot(user, data.getId()); } + plugin.getLocales().getLocale(data.isPinned() ? "data_unpinned" : "data_pinned", data.getShortId(), + data.getId().toString(), user.getUsername(), user.getUuid().toString()) + .ifPresent(executor::sendMessage); } + case "dump" -> { - if (!player.hasPermission(Permission.COMMAND_USER_DATA_DUMP.node)) { - plugin.getLocales().getLocale("error_no_permission").ifPresent(player::sendMessage); - return; - } - if (args.length < 3) { + if (optionalUuid.isEmpty()) { plugin.getLocales().getLocale("error_invalid_syntax", "/userdata dump ") - .ifPresent(player::sendMessage); + .ifPresent(executor::sendMessage); + return; + } + + // Determine dump type + final boolean webDump = parseStringArg(args, 3) + .map(arg -> arg.equalsIgnoreCase("web")) + .orElse(false); + final Optional data = plugin.getDatabase().getSnapshot(user, optionalUuid.get()); + if (data.isEmpty()) { + plugin.getLocales().getLocale("error_invalid_version_uuid") + .ifPresent(executor::sendMessage); return; } - final boolean toWeb = args.length > 3 && args[3].equalsIgnoreCase("web"); - final String username = args[1]; + // Dump the data + final DataSnapshot.Packed userData = data.get(); + final DataDumper dumper = DataDumper.create(userData, user, plugin); try { - final UUID versionUuid = UUID.fromString(args[2]); - CompletableFuture.runAsync(() -> plugin.getDatabase() - .getUserByName(username.toLowerCase(Locale.ENGLISH)) - .thenAccept(optionalUser -> optionalUser.ifPresentOrElse( - user -> plugin.getDatabase().getUserData(user, versionUuid).thenAccept( - optionalUserData -> optionalUserData.ifPresentOrElse(userData -> { - try { - final DataDumper dumper = DataDumper.create(userData, user, plugin); - final String result = toWeb ? dumper.toWeb() : dumper.toFile(); - plugin.getLocales().getLocale("data_dumped", versionUuid.toString() - .split("-")[0], user.username, result) - .ifPresent(player::sendMessage); - } catch (IOException e) { - plugin.log(Level.SEVERE, "Failed to dump user data", e); - } - }, () -> plugin.getLocales().getLocale("error_invalid_version_uuid") - .ifPresent(player::sendMessage))), - () -> plugin.getLocales().getLocale("error_invalid_player") - .ifPresent(player::sendMessage)))); - } catch (IllegalArgumentException e) { - plugin.getLocales().getLocale("error_invalid_syntax", - "/userdata dump ") - .ifPresent(player::sendMessage); + plugin.getLocales().getLocale("data_dumped", userData.getShortId(), user.getUsername(), + (webDump ? dumper.toWeb() : dumper.toFile())).ifPresent(executor::sendMessage); + } catch (Throwable e) { + plugin.log(Level.SEVERE, "Failed to dump user data", e); } } + + default -> plugin.getLocales().getLocale("error_invalid_syntax", getUsage()) + .ifPresent(executor::sendMessage); } } + @Nullable @Override - public List onTabComplete(@NotNull String[] args) { - switch (args.length) { - case 0, 1 -> { - return Arrays.stream(COMMAND_ARGUMENTS) - .filter(argument -> argument.startsWith(args.length == 1 ? args[0] : "")) - .sorted().collect(Collectors.toList()); - } - case 2 -> { - return plugin.getOnlineUsers().stream().map(user -> user.username) - .filter(argument -> argument.startsWith(args[1])) - .sorted().collect(Collectors.toList()); - } - } - return Collections.emptyList(); + public List suggest(@NotNull CommandUser executor, @NotNull String[] args) { + return switch (args.length) { + case 0, 1 -> SUB_COMMANDS.keySet().stream().sorted().toList(); + case 2 -> plugin.getOnlineUsers().stream().map(User::getUsername).toList(); + case 4 -> parseStringArg(args, 0) + .map(arg -> arg.equalsIgnoreCase("dump") ? List.of("web", "file") : null) + .orElse(null); + default -> null; + }; } } diff --git a/common/src/main/java/net/william278/husksync/config/Locales.java b/common/src/main/java/net/william278/husksync/config/Locales.java index 361142ac..d72d8653 100644 --- a/common/src/main/java/net/william278/husksync/config/Locales.java +++ b/common/src/main/java/net/william278/husksync/config/Locales.java @@ -50,7 +50,7 @@ public class Locales { public Map rawLocales = new HashMap<>(); /** - * Returns a raw, un-formatted locale loaded from the locales file + * Returns a raw, unformatted locale loaded from the Locales file * * @param localeId String identifier of the locale, corresponding to a key in the file * @return An {@link Optional} containing the locale corresponding to the id, if it exists @@ -60,12 +60,12 @@ public class Locales { } /** - * Returns a raw, un-formatted locale loaded from the locales file, with replacements applied + * Returns a raw, unformatted locale loaded from the Locales file, with replacements applied *

* Note that replacements will not be MineDown-escaped; use {@link #escapeMineDown(String)} to escape replacements * * @param localeId String identifier of the locale, corresponding to a key in the file - * @param replacements Ordered array of replacement strings to fill in placeholders with + * @param replacements An ordered array of replacement strings to fill in placeholders with * @return An {@link Optional} containing the replacement-applied locale corresponding to the id, if it exists */ public Optional getRawLocale(@NotNull String localeId, @NotNull String... replacements) { @@ -73,7 +73,7 @@ public class Locales { } /** - * Returns a MineDown-formatted locale from the locales file + * Returns a MineDown-formatted locale from the Locales file * * @param localeId String identifier of the locale, corresponding to a key in the file * @return An {@link Optional} containing the formatted locale corresponding to the id, if it exists @@ -83,12 +83,12 @@ public class Locales { } /** - * Returns a MineDown-formatted locale from the locales file, with replacements applied + * Returns a MineDown-formatted locale from the Locales file, with replacements applied *

* Note that replacements will be MineDown-escaped before application * * @param localeId String identifier of the locale, corresponding to a key in the file - * @param replacements Ordered array of replacement strings to fill in placeholders with + * @param replacements An ordered array of replacement strings to fill in placeholders with * @return An {@link Optional} containing the replacement-applied, formatted locale corresponding to the id, if it exists */ public Optional getLocale(@NotNull String localeId, @NotNull String... replacements) { @@ -100,7 +100,7 @@ public class Locales { * Apply placeholder replacements to a raw locale * * @param rawLocale The raw, unparsed locale - * @param replacements Ordered array of replacement strings to fill in placeholders with + * @param replacements An ordered array of replacement strings to fill in placeholders with * @return the raw locale, with inserted placeholders */ @NotNull @@ -189,4 +189,25 @@ public class Locales { public Locales() { } + /** + * Determines the slot a system notification should be displayed in + */ + public enum NotificationSlot { + /** + * Displays the notification in the action bar + */ + ACTION_BAR, + /** + * Displays the notification in the chat + */ + CHAT, + /** + * Displays the notification in an Advancement Toast + */ + TOAST, + /** + * Does not display the notification + */ + NONE + } } diff --git a/common/src/main/java/net/william278/husksync/config/Settings.java b/common/src/main/java/net/william278/husksync/config/Settings.java index b8d0c475..95120caa 100644 --- a/common/src/main/java/net/william278/husksync/config/Settings.java +++ b/common/src/main/java/net/william278/husksync/config/Settings.java @@ -22,7 +22,10 @@ package net.william278.husksync.config; import net.william278.annotaml.YamlComment; import net.william278.annotaml.YamlFile; import net.william278.annotaml.YamlKey; +import net.william278.husksync.data.DataSnapshot; +import net.william278.husksync.data.Identifier; import net.william278.husksync.database.Database; +import net.william278.husksync.listener.EventListener; import org.jetbrains.annotations.NotNull; import java.util.*; @@ -36,30 +39,43 @@ import java.util.*; ┃ Developed by William278 ┃ ┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ ┣╸ Information: https://william278.net/project/husksync - ┗╸ Documentation: https://william278.net/docs/husksync""", - versionField = "config_version", versionNumber = 4) + ┣╸ Config Help: https://william278.net/docs/husksync/config-file/ + ┗╸ Documentation: https://william278.net/docs/husksync""") public class Settings { // Top-level settings + @YamlComment("Locale of the default language file to use. Docs: https://william278.net/docs/huskhomes/translations") @YamlKey("language") private String language = "en-gb"; + @YamlComment("Whether to automatically check for plugin updates on startup") @YamlKey("check_for_updates") private boolean checkForUpdates = true; + @YamlComment("Specify a common ID for grouping servers running HuskSync. " + + "Don't modify this unless you know what you're doing!") @YamlKey("cluster_id") private String clusterId = ""; + @YamlComment("Enable development debug logging") @YamlKey("debug_logging") private boolean debugLogging = false; + @YamlComment("Whether to provide modern, rich TAB suggestions for commands (if available)") + @YamlKey("brigadier_tab_completion") + private boolean brigadierTabCompletion = false; + + @YamlComment("Whether to enable the Player Analytics hook. Docs: https://william278.net/docs/husksync/plan-hook") + @YamlKey("enable_plan_hook") + private boolean enablePlanHook = true; + // Database settings @YamlComment("Type of database to use (MYSQL, MARIADB)") @YamlKey("database.type") private Database.Type databaseType = Database.Type.MYSQL; - - @YamlComment("Database connection settings") + + @YamlComment("Specify credentials here for your MYSQL or MARIADB database") @YamlKey("database.credentials.host") private String mySqlHost = "localhost"; @@ -76,9 +92,13 @@ public class Settings { private String mySqlPassword = "pa55w0rd"; @YamlKey("database.credentials.parameters") - private String mySqlConnectionParameters = "?autoReconnect=true&useSSL=false"; + private String mySqlConnectionParameters = "?autoReconnect=true" + + "&useSSL=false" + + "&useUnicode=true" + + "&characterEncoding=UTF-8"; - @YamlComment("MySQL connection pool properties") + @YamlComment("MYSQL / MARIADB database Hikari connection pool properties. " + + "Don't modify this unless you know what you're doing!") @YamlKey("database.connection_pool.maximum_pool_size") private int mySqlConnectionPoolSize = 10; @@ -94,12 +114,13 @@ public class Settings { @YamlKey("database.connection_pool.connection_timeout") private long mySqlConnectionPoolTimeout = 5000; + @YamlComment("Names of tables to use on your database. Don't modify this unless you know what you're doing!") @YamlKey("database.table_names") private Map tableNames = TableName.getDefaults(); // Redis settings - @YamlComment("Redis connection settings") + @YamlComment("Specify the credentials of your Redis database here. Set \"password\" to '' if you don't have one") @YamlKey("redis.credentials.host") private String redisHost = "localhost"; @@ -114,42 +135,75 @@ public class Settings { // Synchronization settings - @YamlComment("Synchronization settings") + @YamlComment("The number of data snapshot backups that should be kept at once per user") @YamlKey("synchronization.max_user_data_snapshots") - private int maxUserDataSnapshots = 5; - + private int maxUserDataSnapshots = 16; + + @YamlComment("Number of hours between new snapshots being saved as backups (Use \"0\" to backup all snapshots)") + @YamlKey("synchronization.snapshot_backup_frequency") + private int snapshotBackupFrequency = 4; + + @YamlComment("List of save cause IDs for which a snapshot will be automatically pinned (so it won't be rotated)." + + " Docs: https://william278.net/docs/husksync/data-rotation#save-causes") + @YamlKey("synchronization.auto_pinned_save_causes") + private List autoPinnedSaveCauses = List.of( + DataSnapshot.SaveCause.INVENTORY_COMMAND.name(), + DataSnapshot.SaveCause.ENDERCHEST_COMMAND.name(), + DataSnapshot.SaveCause.BACKUP_RESTORE.name(), + DataSnapshot.SaveCause.CONVERTED_FROM_V2.name(), + DataSnapshot.SaveCause.LEGACY_MIGRATION.name(), + DataSnapshot.SaveCause.MPDB_MIGRATION.name() + ); + + @YamlComment("Whether to create a snapshot for users on a world when the server saves that world") @YamlKey("synchronization.save_on_world_save") private boolean saveOnWorldSave = true; + @YamlComment("Whether to create a snapshot for users when they die (containing their death drops)") @YamlKey("synchronization.save_on_death") private boolean saveOnDeath = false; + @YamlComment("Whether to save empty death drops for users when they die") @YamlKey("synchronization.save_empty_drops_on_death") private boolean saveEmptyDropsOnDeath = true; + @YamlComment("Whether to use the snappy data compression algorithm. Keep on unless you know what you're doing") @YamlKey("synchronization.compress_data") private boolean compressData = true; + @YamlComment("Where to display sync notifications (ACTION_BAR, CHAT, TOAST or NONE)") @YamlKey("synchronization.notification_display_slot") - private NotificationDisplaySlot notificationDisplaySlot = NotificationDisplaySlot.ACTION_BAR; + private Locales.NotificationSlot notificationSlot = Locales.NotificationSlot.ACTION_BAR; - @YamlKey("synchronization.synchronise_dead_players_changing_server") - private boolean synchroniseDeadPlayersChangingServer = true; + @YamlComment("(Experimental) Persist Cartography Table locked maps to let them be viewed on any server") + @YamlKey("synchronization.persist_locked_maps") + private boolean persistLockedMaps = false; + @YamlComment("Whether dead players who log out and log in to a different server should have their items saved. " + + "You may need to modify this if you're using the keepInventory gamerule.") + @YamlKey("synchronization.synchronize_dead_players_changing_server") + private boolean synchronizeDeadPlayersChangingServer = true; + + @YamlComment("How long, in milliseconds, this server should wait for a response from the redis server before " + + "pulling data from the database instead (i.e., if the user did not change servers).") @YamlKey("synchronization.network_latency_milliseconds") private int networkLatencyMilliseconds = 500; + @YamlComment("Which data types to synchronize (Docs: https://william278.net/docs/husksync/sync-features)") @YamlKey("synchronization.features") - private Map synchronizationFeatures = SynchronizationFeature.getDefaults(); + private Map synchronizationFeatures = Identifier.getConfigMap(); + @YamlComment("Commands which should be blocked before a player has finished syncing (Use * to block all commands)") @YamlKey("synchronization.blacklisted_commands_while_locked") private List blacklistedCommandsWhileLocked = new ArrayList<>(List.of("*")); + @YamlComment("Event priorities for listeners (HIGHEST, NORMAL, LOWEST). Change if you encounter plugin conflicts") @YamlKey("synchronization.event_priorities") - private Map synchronizationEventPriorities = EventType.getDefaults(); + private Map syncEventPriorities = EventListener.ListenerType.getDefaults(); // Zero-args constructor for instantiation via Annotaml + @SuppressWarnings("unused") public Settings() { } @@ -172,6 +226,13 @@ public class Settings { return debugLogging; } + public boolean doBrigadierTabCompletion() { + return brigadierTabCompletion; + } + + public boolean usePlanHook() { + return enablePlanHook; + } @NotNull public Database.Type getDatabaseType() { @@ -246,7 +307,7 @@ public class Settings { return redisPassword; } - public boolean isRedisUseSsl() { + public boolean redisUseSsl() { return redisUseSsl; } @@ -254,6 +315,10 @@ public class Settings { return maxUserDataSnapshots; } + public int getBackupFrequency() { + return snapshotBackupFrequency; + } + public boolean doSaveOnWorldSave() { return saveOnWorldSave; } @@ -270,13 +335,21 @@ public class Settings { return compressData; } + public boolean doAutoPin(@NotNull DataSnapshot.SaveCause cause) { + return autoPinnedSaveCauses.contains(cause.name()); + } + @NotNull - public NotificationDisplaySlot getNotificationDisplaySlot() { - return notificationDisplaySlot; + public Locales.NotificationSlot getNotificationDisplaySlot() { + return notificationSlot; + } + + public boolean doPersistLockedMaps() { + return persistLockedMaps; } - public boolean isSynchroniseDeadPlayersChangingServer() { - return synchroniseDeadPlayersChangingServer; + public boolean doSynchronizeDeadPlayersChangingServer() { + return synchronizeDeadPlayersChangingServer; } public int getNetworkLatencyMilliseconds() { @@ -288,8 +361,8 @@ public class Settings { return synchronizationFeatures; } - public boolean getSynchronizationFeature(@NotNull SynchronizationFeature feature) { - return getSynchronizationFeatures().getOrDefault(feature.name().toLowerCase(Locale.ENGLISH), feature.enabledByDefault); + public boolean isSyncFeatureEnabled(@NotNull Identifier id) { + return id.isCustom() || getSynchronizationFeatures().getOrDefault(id.getKeyValue(), id.isEnabledByDefault()); } @NotNull @@ -298,12 +371,11 @@ public class Settings { } @NotNull - public EventPriority getEventPriority(@NotNull Settings.EventType eventType) { + public EventListener.Priority getEventPriority(@NotNull EventListener.ListenerType type) { try { - return EventPriority.valueOf(synchronizationEventPriorities.get(eventType.name().toLowerCase(Locale.ENGLISH))); + return EventListener.Priority.valueOf(syncEventPriorities.get(type.name().toLowerCase(Locale.ENGLISH))); } catch (IllegalArgumentException e) { - e.printStackTrace(); - return EventPriority.NORMAL; + return EventListener.Priority.NORMAL; } } @@ -334,111 +406,4 @@ public class Settings { } } - /** - * Determines the slot a system notification should be displayed in - */ - public enum NotificationDisplaySlot { - /** - * Displays the notification in the action bar - */ - ACTION_BAR, - /** - * Displays the notification in the chat - */ - CHAT, - /** - * Displays the notification in an advancement toast - */ - TOAST, - /** - * Does not display the notification - */ - NONE - } - - /** - * Represents enabled synchronisation features - */ - public enum SynchronizationFeature { - INVENTORIES(true), - ENDER_CHESTS(true), - HEALTH(true), - MAX_HEALTH(true), - HUNGER(true), - EXPERIENCE(true), - POTION_EFFECTS(true), - ADVANCEMENTS(true), - GAME_MODE(true), - STATISTICS(true), - PERSISTENT_DATA_CONTAINER(false), - LOCKED_MAPS(false), - LOCATION(false); - - private final boolean enabledByDefault; - - SynchronizationFeature(boolean enabledByDefault) { - this.enabledByDefault = enabledByDefault; - } - - @NotNull - private Map.Entry toEntry() { - return Map.entry(name().toLowerCase(Locale.ENGLISH), enabledByDefault); - } - - @SuppressWarnings("unchecked") - @NotNull - private static Map getDefaults() { - return Map.ofEntries(Arrays.stream(values()) - .map(SynchronizationFeature::toEntry) - .toArray(Map.Entry[]::new)); - } - } - - /** - * Represents events that HuskSync listens to, with a configurable priority listener - */ - public enum EventType { - JOIN_LISTENER(EventPriority.LOWEST), - QUIT_LISTENER(EventPriority.LOWEST), - DEATH_LISTENER(EventPriority.NORMAL); - - private final EventPriority defaultPriority; - - EventType(@NotNull EventPriority defaultPriority) { - this.defaultPriority = defaultPriority; - } - - @NotNull - private Map.Entry toEntry() { - return Map.entry(name().toLowerCase(Locale.ENGLISH), defaultPriority.name()); - } - - - @SuppressWarnings("unchecked") - @NotNull - private static Map getDefaults() { - return Map.ofEntries(Arrays.stream(values()) - .map(EventType::toEntry) - .toArray(Map.Entry[]::new)); - } - } - - /** - * Represents priorities for events that HuskSync listens to - */ - public enum EventPriority { - /** - * Listens and processes the event execution last - */ - HIGHEST, - /** - * Listens in between {@link #HIGHEST} and {@link #LOWEST} priority marked - */ - NORMAL, - /** - * Listens and processes the event execution first - */ - LOWEST - } - } diff --git a/common/src/main/java/net/william278/husksync/data/AdvancementData.java b/common/src/main/java/net/william278/husksync/data/AdvancementData.java deleted file mode 100644 index 738a8013..00000000 --- a/common/src/main/java/net/william278/husksync/data/AdvancementData.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * This file is part of HuskSync, licensed under the Apache License 2.0. - * - * Copyright (c) William278 - * Copyright (c) contributors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.william278.husksync.data; - -import com.google.gson.annotations.SerializedName; -import org.jetbrains.annotations.NotNull; - -import java.util.Date; -import java.util.Map; - -/** - * A mapped piece of advancement data - */ -public class AdvancementData { - - /** - * The advancement namespaced key - */ - @SerializedName("key") - public String key; - - /** - * A map of completed advancement criteria to when it was completed - */ - @SerializedName("completed_criteria") - public Map completedCriteria; - - public AdvancementData(@NotNull String key, @NotNull Map awardedCriteria) { - this.key = key; - this.completedCriteria = awardedCriteria; - } - - @SuppressWarnings("unused") - protected AdvancementData() { - } -} diff --git a/common/src/main/java/net/william278/husksync/data/CompressedDataAdapter.java b/common/src/main/java/net/william278/husksync/data/CompressedDataAdapter.java deleted file mode 100644 index 76d0f44e..00000000 --- a/common/src/main/java/net/william278/husksync/data/CompressedDataAdapter.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * This file is part of HuskSync, licensed under the Apache License 2.0. - * - * Copyright (c) William278 - * Copyright (c) contributors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.william278.husksync.data; - -import org.jetbrains.annotations.NotNull; -import org.xerial.snappy.Snappy; - -import java.io.IOException; - -public class CompressedDataAdapter extends JsonDataAdapter { - - @Override - public byte[] toBytes(@NotNull UserData data) throws DataAdaptionException { - try { - return Snappy.compress(super.toBytes(data)); - } catch (IOException e) { - throw new DataAdaptionException("Failed to compress data", e); - } - } - - @Override - public @NotNull UserData fromBytes(byte[] data) throws DataAdaptionException { - try { - return super.fromBytes(Snappy.uncompress(data)); - } catch (IOException e) { - throw new DataAdaptionException("Failed to decompress data", e); - } - } -} diff --git a/common/src/main/java/net/william278/husksync/data/Data.java b/common/src/main/java/net/william278/husksync/data/Data.java new file mode 100644 index 00000000..e192a4fb --- /dev/null +++ b/common/src/main/java/net/william278/husksync/data/Data.java @@ -0,0 +1,368 @@ +/* + * This file is part of HuskSync, licensed under the Apache License 2.0. + * + * Copyright (c) William278 + * Copyright (c) contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.william278.husksync.data; + +import com.google.gson.annotations.SerializedName; +import net.william278.husksync.HuskSync; +import net.william278.husksync.user.OnlineUser; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.*; +import java.util.stream.Collectors; + +/** + * A piece of data, held by a {@link DataHolder} + */ +@SuppressWarnings("unused") +public interface Data { + + /** + * Apply (set) this data container to the given {@link OnlineUser} + * + * @param user the user to apply this element to + * @param plugin the plugin instance + */ + void apply(@NotNull UserDataHolder user, @NotNull HuskSync plugin); + + /** + * A data container holding data for: + *

    + *
  • Inventories
  • + *
  • Ender Chests
  • + *
+ */ + interface Items extends Data { + + @NotNull + Stack[] getStack(); + + default int getSlotCount() { + return getStack().length; + } + + record Stack(@NotNull String material, int amount, @Nullable String name, + @Nullable List lore, @NotNull List enchantments) { + + } + + default boolean isEmpty() { + return Arrays.stream(getStack()).allMatch(Objects::isNull) || getStack().length == 0; + } + + void clear(); + + void setContents(@NotNull Items contents); + + /** + * A data container holding data for inventories and selected hotbar slot + */ + interface Inventory extends Items { + + int getHeldItemSlot(); + + void setHeldItemSlot(int heldItemSlot) throws IllegalArgumentException; + + default Optional getHelmet() { + return Optional.ofNullable(getStack()[39]); + } + + default Optional getChestplate() { + return Optional.ofNullable(getStack()[38]); + } + + default Optional getLeggings() { + return Optional.ofNullable(getStack()[37]); + } + + default Optional getBoots() { + return Optional.ofNullable(getStack()[36]); + } + + default Optional getOffHand() { + return Optional.ofNullable(getStack()[40]); + } + } + + /** + * Data container holding data for ender chests + */ + interface EnderChest extends Items { + + } + + } + + /** + * Data container holding data for potion effects + */ + interface PotionEffects extends Data { + + @NotNull + List getActiveEffects(); + + /** + * Represents a potion effect + * + * @param type the type of potion effect + * @param amplifier the amplifier of the potion effect + * @param duration the duration of the potion effect + * @param isAmbient whether the potion effect is ambient + * @param showParticles whether the potion effect shows particles + * @param hasIcon whether the potion effect displays a HUD icon + */ + record Effect(@SerializedName("type") @NotNull String type, + @SerializedName("amplifier") int amplifier, + @SerializedName("duration") int duration, + @SerializedName("is_ambient") boolean isAmbient, + @SerializedName("show_particles") boolean showParticles, + @SerializedName("has_icon") boolean hasIcon) { + + } + + } + + /** + * Data container holding data for advancements + */ + interface Advancements extends Data { + + @NotNull + List getCompleted(); + + @NotNull + default List getCompletedExcludingRecipes() { + return getCompleted().stream() + .filter(advancement -> !advancement.getKey().startsWith("minecraft:recipe")) + .collect(Collectors.toList()); + } + + void setCompleted(@NotNull List completed); + + class Advancement { + @SerializedName("key") + private String key; + + @SerializedName("completed_criteria") + private Map completedCriteria; + + private Advancement(@NotNull String key, @NotNull Map completedCriteria) { + this.key = key; + this.completedCriteria = adaptDateMap(completedCriteria); + } + + @SuppressWarnings("unused") + private Advancement() { + } + + @NotNull + public static Advancement adapt(@NotNull String key, @NotNull Map completedCriteria) { + return new Advancement(key, completedCriteria); + } + + @NotNull + private static Map adaptDateMap(@NotNull Map dateMap) { + return dateMap.entrySet().stream() + .collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue().getTime())); + } + + @NotNull + private static Map adaptLongMap(@NotNull Map dateMap) { + return dateMap.entrySet().stream() + .collect(Collectors.toMap(Map.Entry::getKey, e -> new Date(e.getValue()))); + } + + @NotNull + public String getKey() { + return key; + } + + public void setKey(@NotNull String key) { + this.key = key; + } + + public Map getCompletedCriteria() { + return adaptLongMap(completedCriteria); + } + + public void setCompletedCriteria(Map completedCriteria) { + this.completedCriteria = adaptDateMap(completedCriteria); + } + } + + } + + /** + * Data container holding data for the player's location + */ + interface Location extends Data { + double getX(); + + void setX(double x); + + double getY(); + + void setY(double y); + + double getZ(); + + void setZ(double z); + + float getYaw(); + + void setYaw(float yaw); + + float getPitch(); + + void setPitch(float pitch); + + @NotNull + World getWorld(); + + void setWorld(@NotNull World world); + + record World( + @SerializedName("name") @NotNull String name, + @SerializedName("uuid") @NotNull UUID uuid, + @SerializedName("environment") @NotNull String environment + ) { + } + } + + /** + * Data container holding data for statistics + */ + interface Statistics extends Data { + @NotNull + Map getGenericStatistics(); + + @NotNull + Map> getBlockStatistics(); + + @NotNull + Map> getItemStatistics(); + + @NotNull + Map> getEntityStatistics(); + } + + /** + * Data container holding data for persistent data containers + */ + interface PersistentData extends Data { + + } + + /** + * A data container holding data for: + *
    + *
  • Health
  • + *
  • Max Health
  • + *
  • Health Scale
  • + *
+ */ + interface Health extends Data { + double getHealth(); + + void setHealth(double health); + + double getMaxHealth(); + + void setMaxHealth(double maxHealth); + + double getHealthScale(); + + void setHealthScale(double healthScale); + } + + /** + * A data container holding data for: + *
    + * + *
  • Food Level
  • + *
  • Saturation
  • + *
  • Exhaustion
  • + *
+ */ + interface Hunger extends Data { + + int getFoodLevel(); + + void setFoodLevel(int foodLevel); + + float getSaturation(); + + void setSaturation(float saturation); + + float getExhaustion(); + + void setExhaustion(float exhaustion); + + } + + /** + * A data container holding data for: + *
    + *
  • Total experience
  • + *
  • Experience level
  • + *
  • Experience progress
  • + *
+ */ + interface Experience extends Data { + + int getTotalExperience(); + + void setTotalExperience(int totalExperience); + + int getExpLevel(); + + void setExpLevel(int expLevel); + + float getExpProgress(); + + void setExpProgress(float expProgress); + } + + /** + * A data container holding data for: + *
    + *
  • Game mode
  • + *
  • Allow flight
  • + *
  • Is flying
  • + *
+ */ + interface GameMode extends Data { + + @NotNull + String getGameMode(); + + void setGameMode(@NotNull String gameMode); + + boolean getAllowFlight(); + + void setAllowFlight(boolean allowFlight); + + boolean getIsFlying(); + + void setIsFlying(boolean isFlying); + } + + +} diff --git a/common/src/main/java/net/william278/husksync/data/DataAdapter.java b/common/src/main/java/net/william278/husksync/data/DataAdapter.java deleted file mode 100644 index 8e568b33..00000000 --- a/common/src/main/java/net/william278/husksync/data/DataAdapter.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * This file is part of HuskSync, licensed under the Apache License 2.0. - * - * Copyright (c) William278 - * Copyright (c) contributors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.william278.husksync.data; - -import org.jetbrains.annotations.NotNull; - -/** - * An adapter that adapts {@link UserData} to and from a portable byte array. - */ -public interface DataAdapter { - - /** - * Converts {@link UserData} to a byte array - * - * @param data The {@link UserData} to adapt - * @return The byte array. - * @throws DataAdaptionException If an error occurred during adaptation. - */ - byte[] toBytes(@NotNull UserData data) throws DataAdaptionException; - - /** - * Serializes {@link UserData} to a JSON string. - * - * @param data The {@link UserData} to serialize - * @param pretty Whether to pretty print the JSON. - * @return The output json string. - * @throws DataAdaptionException If an error occurred during adaptation. - */ - @NotNull - String toJson(@NotNull UserData data, boolean pretty) throws DataAdaptionException; - - /** - * Converts a byte array to {@link UserData}. - * - * @param data The byte array to adapt. - * @return The {@link UserData}. - * @throws DataAdaptionException If an error occurred during adaptation, such as if the byte array is invalid. - */ - @NotNull - UserData fromBytes(final byte[] data) throws DataAdaptionException; - -} diff --git a/common/src/main/java/net/william278/husksync/data/DataHolder.java b/common/src/main/java/net/william278/husksync/data/DataHolder.java new file mode 100644 index 00000000..2fa1cae8 --- /dev/null +++ b/common/src/main/java/net/william278/husksync/data/DataHolder.java @@ -0,0 +1,140 @@ +/* + * This file is part of HuskSync, licensed under the Apache License 2.0. + * + * Copyright (c) William278 + * Copyright (c) contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.william278.husksync.data; + +import org.jetbrains.annotations.NotNull; + +import java.util.Map; +import java.util.Optional; + +@SuppressWarnings("unused") +public interface DataHolder { + + @NotNull + Map getData(); + + default Optional getData(@NotNull Identifier identifier) { + return Optional.ofNullable(getData().get(identifier)); + } + + default void setData(@NotNull Identifier identifier, @NotNull Data data) { + getData().put(identifier, data); + } + + @NotNull + default Optional getInventory() { + return getData(Identifier.INVENTORY).map(Data.Items.Inventory.class::cast); + } + + default void setInventory(@NotNull Data.Items.Inventory inventory) { + setData(Identifier.INVENTORY, inventory); + } + + @NotNull + default Optional getEnderChest() { + return getData(Identifier.ENDER_CHEST).map(Data.Items.EnderChest.class::cast); + } + + default void setEnderChest(@NotNull Data.Items.EnderChest enderChest) { + setData(Identifier.ENDER_CHEST, enderChest); + } + + @NotNull + default Optional getPotionEffects() { + return getData(Identifier.POTION_EFFECTS).map(Data.PotionEffects.class::cast); + } + + default void setPotionEffects(@NotNull Data.PotionEffects potionEffects) { + setData(Identifier.POTION_EFFECTS, potionEffects); + } + + @NotNull + default Optional getAdvancements() { + return getData(Identifier.ADVANCEMENTS).map(Data.Advancements.class::cast); + } + + default void setAdvancements(@NotNull Data.Advancements advancements) { + setData(Identifier.ADVANCEMENTS, advancements); + } + + @NotNull + default Optional getLocation() { + return Optional.ofNullable((Data.Location) getData().get(Identifier.LOCATION)); + } + + default void setLocation(@NotNull Data.Location location) { + getData().put(Identifier.LOCATION, location); + } + + @NotNull + default Optional getStatistics() { + return Optional.ofNullable((Data.Statistics) getData().get(Identifier.STATISTICS)); + } + + default void setStatistics(@NotNull Data.Statistics statistics) { + getData().put(Identifier.STATISTICS, statistics); + } + + @NotNull + default Optional getHealth() { + return Optional.ofNullable((Data.Health) getData().get(Identifier.HEALTH)); + } + + default void setHealth(@NotNull Data.Health health) { + getData().put(Identifier.HEALTH, health); + } + + @NotNull + default Optional getHunger() { + return Optional.ofNullable((Data.Hunger) getData().get(Identifier.HUNGER)); + } + + default void setHunger(@NotNull Data.Hunger hunger) { + getData().put(Identifier.HUNGER, hunger); + } + + @NotNull + default Optional getExperience() { + return Optional.ofNullable((Data.Experience) getData().get(Identifier.EXPERIENCE)); + } + + default void setExperience(@NotNull Data.Experience experience) { + getData().put(Identifier.EXPERIENCE, experience); + } + + @NotNull + default Optional getGameMode() { + return Optional.ofNullable((Data.GameMode) getData().get(Identifier.GAME_MODE)); + } + + default void setGameMode(@NotNull Data.GameMode gameMode) { + getData().put(Identifier.GAME_MODE, gameMode); + } + + @NotNull + default Optional getPersistentData() { + return Optional.ofNullable((Data.PersistentData) getData().get(Identifier.PERSISTENT_DATA)); + } + + default void setPersistentData(@NotNull Data.PersistentData persistentData) { + getData().put(Identifier.PERSISTENT_DATA, persistentData); + } + +} diff --git a/common/src/main/java/net/william278/husksync/data/DataSaveCause.java b/common/src/main/java/net/william278/husksync/data/DataSaveCause.java deleted file mode 100644 index 7b4c8671..00000000 --- a/common/src/main/java/net/william278/husksync/data/DataSaveCause.java +++ /dev/null @@ -1,130 +0,0 @@ -/* - * This file is part of HuskSync, licensed under the Apache License 2.0. - * - * Copyright (c) William278 - * Copyright (c) contributors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.william278.husksync.data; - -import net.william278.husksync.api.BaseHuskSyncAPI; -import net.william278.husksync.config.Locales; -import net.william278.husksync.player.OnlineUser; -import net.william278.husksync.player.User; -import org.jetbrains.annotations.NotNull; - -import java.util.Locale; - -/** - * Identifies the cause of a player data save. - * - * @implNote This enum is saved in the database. - *

- * Cause names have a max length of 32 characters. - */ -public enum DataSaveCause { - - /** - * Indicates data saved when a player disconnected from the server (either to change servers, or to log off) - * - * @since 2.0 - */ - DISCONNECT, - /** - * Indicates data saved when the world saved - * - * @since 2.0 - */ - WORLD_SAVE, - /** - * Indicates data saved when the user died - * - * @since 2.1 - */ - DEATH, - /** - * Indicates data saved when the server shut down - * - * @since 2.0 - */ - SERVER_SHUTDOWN, - /** - * Indicates data was saved by editing inventory contents via the {@code /inventory} command - * - * @since 2.0 - */ - INVENTORY_COMMAND, - /** - * Indicates data was saved by editing Ender Chest contents via the {@code /enderchest} command - * - * @since 2.0 - */ - ENDERCHEST_COMMAND, - /** - * Indicates data was saved by restoring it from a previous version - * - * @since 2.0 - */ - BACKUP_RESTORE, - /** - * Indicates data was saved by an API call - * - * @see BaseHuskSyncAPI#saveUserData(OnlineUser) - * @see BaseHuskSyncAPI#setUserData(User, UserData) - * @since 2.0 - */ - API, - /** - * Indicates data was saved from being imported from MySQLPlayerDataBridge - * - * @since 2.0 - */ - MPDB_MIGRATION, - /** - * Indicates data was saved from being imported from a legacy version (v1.x) - * - * @since 2.0 - */ - LEGACY_MIGRATION, - /** - * Indicates data was saved by an unknown cause. - *

- * This should not be used and is only used for error handling purposes. - * - * @since 2.0 - */ - UNKNOWN; - - /** - * Returns a {@link DataSaveCause} by name. - * - * @return the {@link DataSaveCause} or {@link #UNKNOWN} if the name is not valid. - */ - @NotNull - public static DataSaveCause getCauseByName(@NotNull String name) { - for (DataSaveCause cause : values()) { - if (cause.name().equalsIgnoreCase(name)) { - return cause; - } - } - return UNKNOWN; - } - - @NotNull - public String getDisplayName() { - return Locales.truncate(name().toLowerCase(Locale.ENGLISH), 10); - } - -} diff --git a/common/src/main/java/net/william278/husksync/data/DataSnapshot.java b/common/src/main/java/net/william278/husksync/data/DataSnapshot.java new file mode 100644 index 00000000..e1fafb2c --- /dev/null +++ b/common/src/main/java/net/william278/husksync/data/DataSnapshot.java @@ -0,0 +1,819 @@ +/* + * This file is part of HuskSync, licensed under the Apache License 2.0. + * + * Copyright (c) William278 + * Copyright (c) contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.william278.husksync.data; + +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; +import de.themoep.minedown.adventure.MineDown; +import net.william278.desertwell.util.Version; +import net.william278.husksync.HuskSync; +import net.william278.husksync.adapter.Adaptable; +import net.william278.husksync.adapter.DataAdapter; +import net.william278.husksync.config.Locales; +import org.jetbrains.annotations.ApiStatus; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.time.OffsetDateTime; +import java.util.*; +import java.util.function.Consumer; +import java.util.stream.Collectors; + +/** + * A snapshot of a {@link DataHolder} at a given time. + * + * @since 3.0 + */ +public class DataSnapshot { + + /* + * Current version of the snapshot data format. + * HuskSync v3.0 uses v4; HuskSync v2.0 uses v3. HuskSync v1.0 uses v1 or v2 + */ + protected static final int CURRENT_FORMAT_VERSION = 4; + + @SerializedName("id") + protected UUID id; + + @SerializedName("pinned") + protected boolean pinned; + + @SerializedName("timestamp") + protected OffsetDateTime timestamp; + + @SerializedName("save_cause") + protected SaveCause saveCause; + + @SerializedName("minecraft_version") + protected String minecraftVersion; + + @SerializedName("platform_type") + protected String platformType; + + @SerializedName("format_version") + protected int formatVersion; + + @SerializedName("data") + protected Map data; + + private DataSnapshot(@NotNull UUID id, boolean pinned, @NotNull OffsetDateTime timestamp, + @NotNull SaveCause saveCause, @NotNull Map data, + @NotNull Version minecraftVersion, @NotNull String platformType, int formatVersion) { + this.id = id; + this.pinned = pinned; + this.timestamp = timestamp; + this.saveCause = saveCause; + this.data = data; + this.minecraftVersion = minecraftVersion.toStringWithoutMetadata(); + this.platformType = platformType; + this.formatVersion = formatVersion; + } + + @SuppressWarnings("unused") + private DataSnapshot() { + } + + @NotNull + @ApiStatus.Internal + public static DataSnapshot.Builder builder(@NotNull HuskSync plugin) { + return new Builder(plugin); + } + + @NotNull + @ApiStatus.Internal + public static DataSnapshot.Packed deserialize(@NotNull HuskSync plugin, byte[] data) throws IllegalStateException { + final DataSnapshot.Packed snapshot = plugin.getDataAdapter().fromBytes(data, DataSnapshot.Packed.class); + if (snapshot.getMinecraftVersion().compareTo(plugin.getMinecraftVersion()) > 0) { + throw new IllegalStateException(String.format("Cannot set data for user because the Minecraft version of " + + "their user data (%s) is newer than the server's Minecraft version (%s)." + + "Please ensure each server is running the same version of Minecraft.", + snapshot.getMinecraftVersion(), plugin.getMinecraftVersion())); + } + if (snapshot.getFormatVersion() > CURRENT_FORMAT_VERSION) { + throw new IllegalStateException(String.format("Cannot set data for user because the format version of " + + "their user data (%s) is newer than the current format version (%s). " + + "Please ensure each server is running the latest version of HuskSync.", + snapshot.getFormatVersion(), CURRENT_FORMAT_VERSION)); + } + if (snapshot.getFormatVersion() < CURRENT_FORMAT_VERSION) { + if (plugin.getLegacyConverter().isPresent()) { + return plugin.getLegacyConverter().get().convert(data); + } + throw new IllegalStateException(String.format( + "No legacy converter to convert format version: %s", snapshot.getFormatVersion() + )); + } + if (!snapshot.getPlatformType().equalsIgnoreCase(plugin.getPlatformType())) { + throw new IllegalStateException(String.format("Cannot set data for user because the platform type of " + + "their user data (%s) is different to the server platform type (%s). " + + "Please ensure each server is running the same platform type.", + snapshot.getPlatformType(), plugin.getPlatformType())); + } + return snapshot; + } + + /** + * Return the ID of the snapshot + * + * @return The snapshot ID + * @since 3.0 + */ + @NotNull + public UUID getId() { + return id; + } + + /** + * Get the short display ID of the snapshot + * + * @return The short display ID + * @since 3.0 + */ + @NotNull + public String getShortId() { + return id.toString().substring(0, 8); + } + + /** + * Get whether the snapshot is pinned + * + * @return Whether the snapshot is pinned + * @since 3.0 + */ + public boolean isPinned() { + return pinned; + } + + /** + * Set whether the snapshot is pinned + * + * @param pinned Whether the snapshot is pinned + * @since 3.0 + */ + public void setPinned(boolean pinned) { + this.pinned = pinned; + } + + /** + * Get why the snapshot was created + * + * @return The {@link SaveCause data save cause} of the snapshot + * @since 3.0 + */ + @NotNull + public SaveCause getSaveCause() { + return saveCause; + } + + /** + * Set why the snapshot was created + * + * @param saveCause The {@link SaveCause data save cause} of the snapshot + * @since 3.0 + */ + public void setSaveCause(SaveCause saveCause) { + this.saveCause = saveCause; + } + + /** + * Get when the snapshot was created + * + * @return The {@link OffsetDateTime timestamp} of the snapshot + * @since 3.0 + */ + @NotNull + public OffsetDateTime getTimestamp() { + return timestamp; + } + + /** + * Get the Minecraft version of the server when the Snapshot was created + * + * @return The Minecraft version of the server when the Snapshot was created + * @since 3.0 + */ + @NotNull + public Version getMinecraftVersion() { + return Version.fromString(minecraftVersion); + } + + /** + * Get the platform type of the server when the Snapshot was created + * + * @return The platform type of the server when the Snapshot was created (e.g. {@code "bukkit"}) + * @since 3.0 + */ + @NotNull + public String getPlatformType() { + return platformType; + } + + /** + * Get the format version of the snapshot (indicating the version of HuskSync that created it) + *
    + *
  • 1: HuskSync v1.0+
  • + *
  • 2: HuskSync v1.5+
  • + *
  • 3: HuskSync v2.0+
  • + *
  • 4: HuskSync v3.0+
  • + *
+ * + * @return The format version of the snapshot + * @since 3.0 + */ + public int getFormatVersion() { + return formatVersion; + } + + /** + * A packed {@link DataSnapshot} that has not been deserialized. + * + * @since 3.0 + */ + public static class Packed extends DataSnapshot implements Adaptable { + + protected Packed(@NotNull UUID id, boolean pinned, @NotNull OffsetDateTime timestamp, + @NotNull SaveCause saveCause, @NotNull Map data, + @NotNull Version minecraftVersion, @NotNull String platformType, int formatVersion) { + super(id, pinned, timestamp, saveCause, data, minecraftVersion, platformType, formatVersion); + } + + @SuppressWarnings("unused") + private Packed() { + } + + @ApiStatus.Internal + public void edit(@NotNull HuskSync plugin, @NotNull Consumer editor) { + final Unpacked data = unpack(plugin); + editor.accept(data); + this.pinned = data.isPinned(); + this.saveCause = data.getSaveCause(); + this.data = data.serializeData(plugin); + } + + /** + * Create a copy of this snapshot at the current system timestamp with a new ID + * + * @return The copied snapshot (with a new ID, with a timestamp of the current system time) + */ + @NotNull + public Packed copy() { + return new Packed( + UUID.randomUUID(), pinned, OffsetDateTime.now(), saveCause, data, + getMinecraftVersion(), platformType, formatVersion + ); + } + + @NotNull + @ApiStatus.Internal + public byte[] asBytes(@NotNull HuskSync plugin) throws DataAdapter.AdaptionException { + return plugin.getDataAdapter().toBytes(this); + } + + @NotNull + @ApiStatus.Internal + public String asJson(@NotNull HuskSync plugin) throws DataAdapter.AdaptionException { + return plugin.getDataAdapter().toJson(this); + } + + @ApiStatus.Internal + public int getFileSize(@NotNull HuskSync plugin) { + return asBytes(plugin).length; + } + + @NotNull + public DataSnapshot.Unpacked unpack(@NotNull HuskSync plugin) { + return new Unpacked( + id, pinned, timestamp, saveCause, data, + getMinecraftVersion(), platformType, formatVersion, plugin + ); + } + + } + + /** + * An unpacked {@link DataSnapshot}. + * + * @since 3.0 + */ + public static class Unpacked extends DataSnapshot implements DataHolder { + + @Expose(serialize = false, deserialize = false) + private final Map deserialized; + + private Unpacked(@NotNull UUID id, boolean pinned, @NotNull OffsetDateTime timestamp, + @NotNull SaveCause saveCause, @NotNull Map data, + @NotNull Version minecraftVersion, @NotNull String platformType, int formatVersion, + @NotNull HuskSync plugin) { + super(id, pinned, timestamp, saveCause, data, minecraftVersion, platformType, formatVersion); + this.deserialized = deserializeData(plugin); + } + + private Unpacked(@NotNull UUID id, boolean pinned, @NotNull OffsetDateTime timestamp, + @NotNull SaveCause saveCause, @NotNull Map data, + @NotNull Version minecraftVersion, @NotNull String platformType, int formatVersion) { + super(id, pinned, timestamp, saveCause, Map.of(), minecraftVersion, platformType, formatVersion); + this.deserialized = data; + } + + @NotNull + @ApiStatus.Internal + private Map deserializeData(@NotNull HuskSync plugin) { + return data.entrySet().stream() + .map((entry) -> plugin.getIdentifier(entry.getKey()).map(id -> Map.entry( + id, plugin.getSerializers().get(id).deserialize(entry.getValue()) + )).orElse(null)) + .filter(Objects::nonNull) + .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); + } + + @NotNull + @ApiStatus.Internal + private Map serializeData(@NotNull HuskSync plugin) { + return deserialized.entrySet().stream() + .map((entry) -> Map.entry(entry.getKey().toString(), + Objects.requireNonNull( + plugin.getSerializers().get(entry.getKey()), + String.format("No serializer found for %s", entry.getKey()) + ).serialize(entry.getValue()))) + .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); + } + + /** + * Get the data the snapshot is holding + * + * @return The data map + * @since 3.0 + */ + @NotNull + public Map getData() { + return deserialized; + } + + /** + * Pack the {@link DataSnapshot} into a {@link DataSnapshot.Packed packed} snapshot + * + * @param plugin The HuskSync plugin instance + * @return The packed snapshot + * @since 3.0 + */ + @NotNull + @ApiStatus.Internal + public DataSnapshot.Packed pack(@NotNull HuskSync plugin) { + return new DataSnapshot.Packed( + id, pinned, timestamp, saveCause, serializeData(plugin), + getMinecraftVersion(), platformType, formatVersion + ); + } + + } + + /** + * A builder for {@link DataSnapshot}s. + * + * @since 3.0 + */ + @SuppressWarnings("unused") + public static class Builder { + + private final HuskSync plugin; + private SaveCause saveCause; + private boolean pinned; + private OffsetDateTime timestamp; + private final Map data; + + private Builder(@NotNull HuskSync plugin) { + this.plugin = plugin; + this.pinned = false; + this.data = new HashMap<>(); + this.timestamp = OffsetDateTime.now(); + } + + /** + * Set the cause of the data save + * + * @param saveCause The cause of the data save + * @return The builder + * @apiNote If the {@link SaveCause data save cause} specified is configured to auto-pin, then the value of + * {@link #pinned(boolean)} will be ignored + * @since 3.0 + */ + @NotNull + public Builder saveCause(@NotNull SaveCause saveCause) { + this.saveCause = saveCause; + return this; + } + + /** + * Set whether the data should be pinned + * + * @param pinned Whether the data should be pinned + * @return The builder + * @apiNote If the {@link SaveCause data save cause} specified is configured to auto-pin, this will be ignored + * @since 3.0 + */ + @NotNull + public Builder pinned(boolean pinned) { + this.pinned = pinned; + return this; + } + + /** + * Set the timestamp of the snapshot. + * By default, this is the current server time. + * The timestamp passed to this method cannot be in the future. + *

+ * Note that this will affect the rotation of data snapshots in the database if unpinned, + * as well as the order snapshots appear in the list. + * + * @param timestamp The timestamp + * @return The builder + * @throws IllegalArgumentException if the timestamp is in the future + * @since 3.0 + */ + @NotNull + public Builder timestamp(@NotNull OffsetDateTime timestamp) { + if (timestamp.isAfter(OffsetDateTime.now())) { + throw new IllegalArgumentException("Data snapshots cannot have a timestamp set in the future"); + } + this.timestamp = timestamp; + return this; + } + + /** + * Set the data for a given identifier + * + * @param identifier The identifier + * @param data The data + * @return The builder + * @since 3.0 + */ + @NotNull + public Builder data(@NotNull Identifier identifier, @NotNull Data data) { + this.data.put(identifier, data); + return this; + } + + /** + * Set a map of data to the snapshot + * + * @param data The data + * @return The builder + * @since 3.0 + */ + @NotNull + public Builder data(@NotNull Map data) { + this.data.putAll(data); + return this; + } + + /** + * Set the inventory contents of the snapshot + *

+ * Equivalent to {@code data(Identifier.INVENTORY, inventory)} + *

+ * + * @param inventory The inventory contents + * @return The builder + * @since 3.0 + */ + @NotNull + public Builder inventory(@NotNull Data.Items.Inventory inventory) { + return data(Identifier.INVENTORY, inventory); + } + + /** + * Set the Ender Chest contents of the snapshot + *

+ * Equivalent to {@code data(Identifier.ENDER_CHEST, inventory)} + *

+ * + * @param enderChest The Ender Chest contents + * @return The builder + * @since 3.0 + */ + @NotNull + public Builder enderChest(@NotNull Data.Items.EnderChest enderChest) { + return data(Identifier.ENDER_CHEST, enderChest); + } + + /** + * Set the potion effects of the snapshot + *

+ * Equivalent to {@code data(Identifier.POTION_EFFECTS, potionEffects)} + *

+ * + * @param potionEffects The potion effects + * @return The builder + * @since 3.0 + */ + @NotNull + public Builder potionEffects(@NotNull Data.PotionEffects potionEffects) { + return data(Identifier.POTION_EFFECTS, potionEffects); + } + + /** + * Set the advancements of the snapshot + *

+ * Equivalent to {@code data(Identifier.ADVANCEMENTS, advancements)} + *

+ * + * @param advancements The advancements + * @return The builder + * @since 3.0 + */ + @NotNull + public Builder advancements(@NotNull Data.Advancements advancements) { + return data(Identifier.ADVANCEMENTS, advancements); + } + + /** + * Set the location of the snapshot + *

+ * Equivalent to {@code data(Identifier.LOCATION, location)} + *

+ * + * @param location The location + * @return The builder + * @since 3.0 + */ + @NotNull + public Builder location(@NotNull Data.Location location) { + return data(Identifier.LOCATION, location); + } + + /** + * Set the statistics of the snapshot + *

+ * Equivalent to {@code data(Identifier.STATISTICS, statistics)} + *

+ * + * @param statistics The statistics + * @return The builder + * @since 3.0 + */ + @NotNull + public Builder statistics(@NotNull Data.Statistics statistics) { + return data(Identifier.STATISTICS, statistics); + } + + /** + * Set the health of the snapshot + *

+ * Equivalent to {@code data(Identifier.HEALTH, health)} + *

+ * + * @param health The health + * @return The builder + * @since 3.0 + */ + @NotNull + public Builder health(@NotNull Data.Health health) { + return data(Identifier.HEALTH, health); + } + + /** + * Set the hunger of the snapshot + *

+ * Equivalent to {@code data(Identifier.HUNGER, hunger)} + *

+ * + * @param hunger The hunger + * @return The builder + * @since 3.0 + */ + @NotNull + public Builder hunger(@NotNull Data.Hunger hunger) { + return data(Identifier.HUNGER, hunger); + } + + /** + * Set the experience of the snapshot + *

+ * Equivalent to {@code data(Identifier.EXPERIENCE, experience)} + *

+ * + * @param experience The experience + * @return The builder + * @since 3.0 + */ + @NotNull + public Builder experience(@NotNull Data.Experience experience) { + return data(Identifier.EXPERIENCE, experience); + } + + /** + * Set the game mode of the snapshot + *

+ * Equivalent to {@code data(Identifier.GAME_MODE, gameMode)} + *

+ * + * @param gameMode The game mode + * @return The builder + * @since 3.0 + */ + @NotNull + public Builder gameMode(@NotNull Data.GameMode gameMode) { + return data(Identifier.GAME_MODE, gameMode); + } + + /** + * Set the persistent data container of the snapshot + *

+ * Equivalent to {@code data(Identifier.PERSISTENT_DATA, persistentData)} + *

+ * + * @param persistentData The persistent data container data + * @return The builder + * @since 3.0 + */ + @NotNull + public Builder persistentData(@NotNull Data.PersistentData persistentData) { + return data(Identifier.PERSISTENT_DATA, persistentData); + } + + /** + * Build the {@link DataSnapshot} + * + * @return The {@link DataSnapshot.Unpacked snapshot} + * @throws IllegalStateException If no save cause is specified + * @since 3.0 + */ + @NotNull + public DataSnapshot.Unpacked build() throws IllegalStateException { + if (saveCause == null) { + throw new IllegalStateException("Cannot build DataSnapshot without a save cause"); + } + return new Unpacked( + UUID.randomUUID(), + pinned || plugin.getSettings().doAutoPin(saveCause), + timestamp, + saveCause, + data, + plugin.getMinecraftVersion(), + plugin.getPlatformType(), + DataSnapshot.CURRENT_FORMAT_VERSION + ); + } + + /** + * Build and pack the {@link DataSnapshot} + * + * @return The {@link DataSnapshot.Packed snapshot} + * @throws IllegalStateException If no save cause is specified + * @since 3.0 + */ + @NotNull + public DataSnapshot.Packed buildAndPack() throws IllegalStateException { + return build().pack(plugin); + } + + } + + /** + * Identifies the cause of a player data save. + * + * @implNote This enum is saved in the database. + *

+ * Cause names have a max length of 32 characters. + */ + public enum SaveCause { + + /** + * Indicates data saved when a player disconnected from the server (either to change servers, or to log off) + * + * @since 2.0 + */ + DISCONNECT, + /** + * Indicates data saved when the world saved + * + * @since 2.0 + */ + WORLD_SAVE, + /** + * Indicates data saved when the user died + * + * @since 2.1 + */ + DEATH, + /** + * Indicates data saved when the server shut down + * + * @since 2.0 + */ + SERVER_SHUTDOWN, + /** + * Indicates data was saved by editing inventory contents via the {@code /inventory} command + * + * @since 2.0 + */ + INVENTORY_COMMAND, + /** + * Indicates data was saved by editing Ender Chest contents via the {@code /enderchest} command + * + * @since 2.0 + */ + ENDERCHEST_COMMAND, + /** + * Indicates data was saved by restoring it from a previous version + * + * @since 2.0 + */ + BACKUP_RESTORE, + /** + * Indicates data was saved by an API call + * + * @since 2.0 + */ + API, + /** + * Indicates data was saved from being imported from MySQLPlayerDataBridge + * + * @since 2.0 + */ + MPDB_MIGRATION, + /** + * Indicates data was saved from being imported from a legacy version (v1.x -> v2.x) + * + * @since 2.0 + */ + LEGACY_MIGRATION, + /** + * Indicates data was saved from being imported from a legacy version (v2.x -> v3.x) + * + * @since 3.0 + */ + CONVERTED_FROM_V2; + + @NotNull + public String getDisplayName() { + return Locales.truncate(name().toLowerCase(Locale.ENGLISH) + .replaceAll("_", " "), 18); + } + + } + + /** + * Represents the cause of a player having their data updated. + */ + public enum UpdateCause { + /** + * Indicates the data was updated by a synchronization process + * + * @since 3.0 + */ + SYNCHRONIZED("synchronization_complete", "synchronization_failed"), + /** + * Indicates the data was updated by a user joining the server + * + * @since 3.0 + */ + NEW_USER("user_registration_complete", null), + /** + * Indicates the data was updated by a data update process (management command, API, etc.) + * + * @since 3.0 + */ + UPDATED("data_update_complete", "data_update_failed"); + + private final String completedLocale; + private final String failureLocale; + + UpdateCause(@Nullable String completedLocale, @Nullable String failureLocale) { + this.completedLocale = completedLocale; + this.failureLocale = failureLocale; + } + + public Optional getCompletedLocale(@NotNull HuskSync plugin) { + if (completedLocale != null) { + return plugin.getLocales().getLocale(completedLocale); + } + return Optional.empty(); + } + + public Optional getFailedLocale(@NotNull HuskSync plugin) { + if (failureLocale != null) { + return plugin.getLocales().getLocale(failureLocale); + } + return Optional.empty(); + } + + } +} diff --git a/common/src/main/java/net/william278/husksync/data/Identifier.java b/common/src/main/java/net/william278/husksync/data/Identifier.java new file mode 100644 index 00000000..1279cdd9 --- /dev/null +++ b/common/src/main/java/net/william278/husksync/data/Identifier.java @@ -0,0 +1,177 @@ +/* + * This file is part of HuskSync, licensed under the Apache License 2.0. + * + * Copyright (c) William278 + * Copyright (c) contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.william278.husksync.data; + +import net.kyori.adventure.key.InvalidKeyException; +import net.kyori.adventure.key.Key; +import org.intellij.lang.annotations.Subst; +import org.jetbrains.annotations.ApiStatus; +import org.jetbrains.annotations.NotNull; + +import java.util.Map; +import java.util.stream.Stream; + +/** + * Identifiers of different types of {@link Data}s + */ +public class Identifier { + + public static Identifier INVENTORY = huskSync("inventory", true); + public static Identifier ENDER_CHEST = huskSync("ender_chest", true); + public static Identifier POTION_EFFECTS = huskSync("potion_effects", true); + public static Identifier ADVANCEMENTS = huskSync("advancements", true); + public static Identifier LOCATION = huskSync("location", false); + public static Identifier STATISTICS = huskSync("statistics", true); + public static Identifier HEALTH = huskSync("health", true); + public static Identifier HUNGER = huskSync("hunger", true); + public static Identifier EXPERIENCE = huskSync("experience", true); + public static Identifier GAME_MODE = huskSync("game_mode", true); + public static Identifier PERSISTENT_DATA = huskSync("persistent_data", true); + + private final Key key; + private final boolean configDefault; + + private Identifier(@NotNull Key key, boolean configDefault) { + this.key = key; + this.configDefault = configDefault; + } + + /** + * Create an identifier from a {@link Key} + * + * @param key the key + * @return the identifier + * @since 3.0 + */ + @NotNull + public static Identifier from(@NotNull Key key) { + if (key.namespace().equals("husksync")) { + throw new IllegalArgumentException("You cannot register a key with \"husksync\" as the namespace!"); + } + return new Identifier(key, true); + } + + /** + * Create an identifier from a namespace and value + * + * @param plugin the namespace + * @param name the value + * @return the identifier + * @since 3.0 + */ + @NotNull + public static Identifier from(@Subst("plugin") @NotNull String plugin, @Subst("null") @NotNull String name) { + return from(Key.key(plugin, name)); + } + + @NotNull + private static Identifier huskSync(@Subst("null") @NotNull String name, + boolean configDefault) throws InvalidKeyException { + return new Identifier(Key.key("husksync", name), configDefault); + } + + @NotNull + @SuppressWarnings("unused") + private static Identifier parse(@NotNull String key) throws InvalidKeyException { + return huskSync(key, true); + } + + public boolean isEnabledByDefault() { + return configDefault; + } + + @NotNull + private Map.Entry getConfigEntry() { + return Map.entry(getKeyValue(), configDefault); + } + + /** + * (Internal use only) - Get a map of the default config entries for all HuskSync identifiers + * + * @return a map of all the config entries + * @since 3.0 + */ + @NotNull + @ApiStatus.Internal + @SuppressWarnings("unchecked") + public static Map getConfigMap() { + return Map.ofEntries(Stream.of( + INVENTORY, ENDER_CHEST, POTION_EFFECTS, ADVANCEMENTS, LOCATION, + STATISTICS, HEALTH, HUNGER, EXPERIENCE, GAME_MODE, PERSISTENT_DATA + ) + .map(Identifier::getConfigEntry) + .toArray(Map.Entry[]::new)); + } + + /** + * Get the namespace of the identifier + * + * @return the namespace + */ + @NotNull + public String getKeyNamespace() { + return key.namespace(); + } + + /** + * Get the value of the identifier + * + * @return the value + */ + @NotNull + public String getKeyValue() { + return key.value(); + } + + /** + * Returns {@code true} if the identifier is a custom (non-HuskSync) identifier + * + * @return {@code false} if {@link #getKeyNamespace()} returns "husksync"; {@code true} otherwise + */ + public boolean isCustom() { + return !getKeyNamespace().equals("husksync"); + } + + /** + * Returns the identifier as a string (the key) + * + * @return the identifier as a string + */ + @NotNull + @Override + public String toString() { + return key.asString(); + } + + /** + * Returns {@code true} if the given object is an identifier with the same key as this identifier + * + * @param obj the object to compare + * @return {@code true} if the given object is an identifier with the same key as this identifier + */ + @Override + public boolean equals(Object obj) { + if (obj instanceof Identifier other) { + return key.equals(other.key); + } + return false; + } + +} diff --git a/common/src/main/java/net/william278/husksync/data/ItemData.java b/common/src/main/java/net/william278/husksync/data/ItemData.java deleted file mode 100644 index 86dc014f..00000000 --- a/common/src/main/java/net/william278/husksync/data/ItemData.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * This file is part of HuskSync, licensed under the Apache License 2.0. - * - * Copyright (c) William278 - * Copyright (c) contributors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.william278.husksync.data; - -import com.google.gson.annotations.SerializedName; -import org.jetbrains.annotations.NotNull; - -/** - * Stores information about the contents of a player's inventory or Ender Chest. - */ -public class ItemData { - - /** - * A Base-64 string of platform-serialized items - */ - @SerializedName("serialized_items") - public String serializedItems; - - /** - * Get an empty item data object, representing an empty inventory or Ender Chest - * - * @return an empty item data object - */ - @NotNull - public static ItemData empty() { - return new ItemData(""); - } - - public ItemData(@NotNull final String serializedItems) { - this.serializedItems = serializedItems; - } - - @SuppressWarnings("unused") - protected ItemData() { - } - - /** - * Check if the item data is empty - * - * @return {@code true} if the item data is empty; {@code false} otherwise - */ - public boolean isEmpty() { - return serializedItems.isEmpty(); - } - -} diff --git a/common/src/main/java/net/william278/husksync/data/JsonDataAdapter.java b/common/src/main/java/net/william278/husksync/data/JsonDataAdapter.java deleted file mode 100644 index 2162ca5e..00000000 --- a/common/src/main/java/net/william278/husksync/data/JsonDataAdapter.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * This file is part of HuskSync, licensed under the Apache License 2.0. - * - * Copyright (c) William278 - * Copyright (c) contributors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.william278.husksync.data; - -import com.google.gson.GsonBuilder; -import com.google.gson.JsonSyntaxException; -import org.jetbrains.annotations.NotNull; - -import java.nio.charset.StandardCharsets; - -public class JsonDataAdapter implements DataAdapter { - - @Override - public byte[] toBytes(@NotNull UserData data) throws DataAdaptionException { - return toJson(data, false).getBytes(StandardCharsets.UTF_8); - } - - @Override - public @NotNull String toJson(@NotNull UserData data, boolean pretty) throws DataAdaptionException { - return (pretty ? new GsonBuilder().setPrettyPrinting() : new GsonBuilder()).create().toJson(data); - } - - @Override - public @NotNull UserData fromBytes(byte[] data) throws DataAdaptionException { - try { - return new GsonBuilder().create().fromJson(new String(data, StandardCharsets.UTF_8), UserData.class); - } catch (JsonSyntaxException e) { - throw new DataAdaptionException("Failed to parse JSON data", e); - } - } -} diff --git a/common/src/main/java/net/william278/husksync/data/LocationData.java b/common/src/main/java/net/william278/husksync/data/LocationData.java deleted file mode 100644 index 0d263acd..00000000 --- a/common/src/main/java/net/william278/husksync/data/LocationData.java +++ /dev/null @@ -1,92 +0,0 @@ -/* - * This file is part of HuskSync, licensed under the Apache License 2.0. - * - * Copyright (c) William278 - * Copyright (c) contributors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.william278.husksync.data; - -import com.google.gson.annotations.SerializedName; -import org.jetbrains.annotations.NotNull; - -import java.util.UUID; - -/** - * Stores information about a player's location - */ -public class LocationData { - - /** - * Name of the world on the server - */ - @SerializedName("world_name") - public String worldName; - /** - * Unique id of the world - */ - @SerializedName("world_uuid") - public UUID worldUuid; - /** - * The environment type of the world (one of "NORMAL", "NETHER", "THE_END") - */ - @SerializedName("world_environment") - public String worldEnvironment; - - /** - * The x coordinate of the location - */ - @SerializedName("x") - public double x; - /** - * The y coordinate of the location - */ - @SerializedName("y") - public double y; - /** - * The z coordinate of the location - */ - @SerializedName("z") - public double z; - - /** - * The location's facing yaw angle - */ - @SerializedName("yaw") - public float yaw; - /** - * The location's facing pitch angle - */ - @SerializedName("pitch") - public float pitch; - - public LocationData(@NotNull String worldName, @NotNull UUID worldUuid, - @NotNull String worldEnvironment, - double x, double y, double z, - float yaw, float pitch) { - this.worldName = worldName; - this.worldUuid = worldUuid; - this.worldEnvironment = worldEnvironment; - this.x = x; - this.y = y; - this.z = z; - this.yaw = yaw; - this.pitch = pitch; - } - - @SuppressWarnings("unused") - protected LocationData() { - } -} diff --git a/common/src/main/java/net/william278/husksync/data/PersistentDataContainerData.java b/common/src/main/java/net/william278/husksync/data/PersistentDataContainerData.java deleted file mode 100644 index 44c5784e..00000000 --- a/common/src/main/java/net/william278/husksync/data/PersistentDataContainerData.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * This file is part of HuskSync, licensed under the Apache License 2.0. - * - * Copyright (c) William278 - * Copyright (c) contributors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.william278.husksync.data; - -import com.google.gson.annotations.SerializedName; -import org.jetbrains.annotations.NotNull; - -import java.util.Map; -import java.util.Optional; -import java.util.Set; - -/** - * Store's a user's persistent data container, holding a map of plugin-set persistent values - */ -public class PersistentDataContainerData { - - /** - * Map of namespaced key strings to a byte array representing the persistent data - */ - @SerializedName("persistent_data_map") - protected Map> persistentDataMap; - - public PersistentDataContainerData(@NotNull Map> persistentDataMap) { - this.persistentDataMap = persistentDataMap; - } - - @SuppressWarnings("unused") - protected PersistentDataContainerData() { - } - - public Optional getTagValue(@NotNull String tagName, @NotNull Class tagClass) { - if (!persistentDataMap.containsKey(tagName)) { - return Optional.empty(); - } - - // If the tag cannot be cast to the specified class, return an empty optional - final boolean canCast = tagClass.isAssignableFrom(persistentDataMap.get(tagName).value.getClass()); - if (!canCast) { - return Optional.empty(); - } - - return Optional.of(tagClass.cast(persistentDataMap.get(tagName).value)); - } - - public Optional getTagType(@NotNull String tagType) { - if (persistentDataMap.containsKey(tagType)) { - return PersistentDataTagType.getDataType(persistentDataMap.get(tagType).type); - } - return Optional.empty(); - } - - public Set getTags() { - return persistentDataMap.keySet(); - } - -} diff --git a/common/src/main/java/net/william278/husksync/data/PersistentDataTag.java b/common/src/main/java/net/william278/husksync/data/PersistentDataTag.java deleted file mode 100644 index 9601d6c6..00000000 --- a/common/src/main/java/net/william278/husksync/data/PersistentDataTag.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * This file is part of HuskSync, licensed under the Apache License 2.0. - * - * Copyright (c) William278 - * Copyright (c) contributors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.william278.husksync.data; - -import org.jetbrains.annotations.NotNull; - -import java.util.Optional; - -/** - * Represents a persistent data tag set by a plugin. - */ -public class PersistentDataTag { - - /** - * The enumerated primitive data type name value of the tag - */ - protected String type; - - /** - * The value of the tag - */ - public T value; - - public PersistentDataTag(@NotNull PersistentDataTagType type, @NotNull T value) { - this.type = type.name(); - this.value = value; - } - - @SuppressWarnings("unused") - private PersistentDataTag() { - } - - public Optional getType() { - return PersistentDataTagType.getDataType(type); - } - -} diff --git a/common/src/main/java/net/william278/husksync/data/PersistentDataTagType.java b/common/src/main/java/net/william278/husksync/data/Serializer.java similarity index 57% rename from common/src/main/java/net/william278/husksync/data/PersistentDataTagType.java rename to common/src/main/java/net/william278/husksync/data/Serializer.java index 56300dd6..2da2b14e 100644 --- a/common/src/main/java/net/william278/husksync/data/PersistentDataTagType.java +++ b/common/src/main/java/net/william278/husksync/data/Serializer.java @@ -21,34 +21,24 @@ package net.william278.husksync.data; import org.jetbrains.annotations.NotNull; -import java.util.Optional; +public interface Serializer { -/** - * Represents the type of a {@link PersistentDataTag} - */ -public enum PersistentDataTagType { - - BYTE, - SHORT, - INTEGER, - LONG, - FLOAT, - DOUBLE, - STRING, - BYTE_ARRAY, - INTEGER_ARRAY, - LONG_ARRAY, - TAG_CONTAINER_ARRAY, - TAG_CONTAINER; - - - public static Optional getDataType(@NotNull String typeName) { - for (PersistentDataTagType type : values()) { - if (type.name().equalsIgnoreCase(typeName)) { - return Optional.of(type); - } + T deserialize(@NotNull String serialized) throws DeserializationException; + + @NotNull + String serialize(@NotNull T element) throws SerializationException; + + static final class DeserializationException extends IllegalStateException { + DeserializationException(@NotNull String message, @NotNull Throwable cause) { + super(message, cause); } - return Optional.empty(); } + static final class SerializationException extends IllegalStateException { + SerializationException(@NotNull String message, @NotNull Throwable cause) { + super(message, cause); + } + } + + } diff --git a/common/src/main/java/net/william278/husksync/data/StatisticsData.java b/common/src/main/java/net/william278/husksync/data/StatisticsData.java deleted file mode 100644 index 1486b0ab..00000000 --- a/common/src/main/java/net/william278/husksync/data/StatisticsData.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * This file is part of HuskSync, licensed under the Apache License 2.0. - * - * Copyright (c) William278 - * Copyright (c) contributors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.william278.husksync.data; - -import com.google.gson.annotations.SerializedName; -import org.jetbrains.annotations.NotNull; - -import java.util.Map; - -/** - * Stores information about a player's statistics - */ -public class StatisticsData { - - /** - * Map of generic statistic names to their values - */ - @SerializedName("untyped_statistics") - public Map untypedStatistics; - - /** - * Map of block type statistics to a map of material types to values - */ - @SerializedName("block_statistics") - public Map> blockStatistics; - - /** - * Map of item type statistics to a map of material types to values - */ - @SerializedName("item_statistics") - public Map> itemStatistics; - - /** - * Map of entity type statistics to a map of entity types to values - */ - @SerializedName("entity_statistics") - public Map> entityStatistics; - - public StatisticsData(@NotNull Map untypedStatistics, - @NotNull Map> blockStatistics, - @NotNull Map> itemStatistics, - @NotNull Map> entityStatistics) { - this.untypedStatistics = untypedStatistics; - this.blockStatistics = blockStatistics; - this.itemStatistics = itemStatistics; - this.entityStatistics = entityStatistics; - } - - @SuppressWarnings("unused") - protected StatisticsData() { - } - -} diff --git a/common/src/main/java/net/william278/husksync/data/StatusData.java b/common/src/main/java/net/william278/husksync/data/StatusData.java deleted file mode 100644 index b5e193be..00000000 --- a/common/src/main/java/net/william278/husksync/data/StatusData.java +++ /dev/null @@ -1,123 +0,0 @@ -/* - * This file is part of HuskSync, licensed under the Apache License 2.0. - * - * Copyright (c) William278 - * Copyright (c) contributors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.william278.husksync.data; - -import com.google.gson.annotations.SerializedName; - -/** - * Stores status information about a player - */ -public class StatusData { - - /** - * The player's health points - */ - @SerializedName("health") - public double health; - - /** - * The player's maximum health points - */ - @SerializedName("max_health") - public double maxHealth; - - /** - * The player's health scaling factor - */ - @SerializedName("health_scale") - public double healthScale; - - /** - * The player's hunger points - */ - @SerializedName("hunger") - public int hunger; - - /** - * The player's saturation points - */ - @SerializedName("saturation") - public float saturation; - - /** - * The player's saturation exhaustion points - */ - @SerializedName("saturation_exhaustion") - public float saturationExhaustion; - - /** - * The player's currently selected item slot - */ - @SerializedName("selected_item_slot") - public int selectedItemSlot; - - /** - * The player's total experience points

- * (not to be confused with experience level - this is the "points" value shown on the death screen) - */ - @SerializedName("total_experience") - public int totalExperience; - - /** - * The player's experience level (shown on the exp bar) - */ - @SerializedName("experience_level") - public int expLevel; - - /** - * The player's progress to their next experience level - */ - @SerializedName("experience_progress") - public float expProgress; - - /** - * The player's game mode string (one of "SURVIVAL", "CREATIVE", "ADVENTURE", "SPECTATOR") - */ - @SerializedName("game_mode") - public String gameMode; - - /** - * If the player is currently flying - */ - @SerializedName("is_flying") - public boolean isFlying; - - public StatusData(final double health, final double maxHealth, final double healthScale, - final int hunger, final float saturation, final float saturationExhaustion, - final int selectedItemSlot, final int totalExperience, final int expLevel, - final float expProgress, final String gameMode, final boolean isFlying) { - this.health = health; - this.maxHealth = maxHealth; - this.healthScale = healthScale; - this.hunger = hunger; - this.saturation = saturation; - this.saturationExhaustion = saturationExhaustion; - this.selectedItemSlot = selectedItemSlot; - this.totalExperience = totalExperience; - this.expLevel = expLevel; - this.expProgress = expProgress; - this.gameMode = gameMode; - this.isFlying = isFlying; - } - - @SuppressWarnings("unused") - protected StatusData() { - } -} diff --git a/common/src/main/java/net/william278/husksync/data/StatusDataFlag.java b/common/src/main/java/net/william278/husksync/data/StatusDataFlag.java deleted file mode 100644 index 249b9fe1..00000000 --- a/common/src/main/java/net/william278/husksync/data/StatusDataFlag.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * This file is part of HuskSync, licensed under the Apache License 2.0. - * - * Copyright (c) William278 - * Copyright (c) contributors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.william278.husksync.data; - -import net.william278.husksync.config.Settings; -import org.jetbrains.annotations.NotNull; - -import java.util.Arrays; -import java.util.List; - -/** - * Flags for setting {@link StatusData}, indicating which elements should be synced - * - * @deprecated Use the more direct {@link Settings#getSynchronizationFeature(Settings.SynchronizationFeature)} instead - */ -@Deprecated(since = "2.1") -public enum StatusDataFlag { - - SET_HEALTH(Settings.SynchronizationFeature.HEALTH), - SET_MAX_HEALTH(Settings.SynchronizationFeature.MAX_HEALTH), - SET_HUNGER(Settings.SynchronizationFeature.HUNGER), - SET_EXPERIENCE(Settings.SynchronizationFeature.EXPERIENCE), - SET_GAME_MODE(Settings.SynchronizationFeature.GAME_MODE), - SET_FLYING(Settings.SynchronizationFeature.LOCATION), - SET_SELECTED_ITEM_SLOT(Settings.SynchronizationFeature.INVENTORIES); - - private final Settings.SynchronizationFeature feature; - - StatusDataFlag(@NotNull Settings.SynchronizationFeature feature) { - this.feature = feature; - } - - /** - * Returns all status data flags - * - * @return all status data flags as a list - * @deprecated Use {@link Settings#getSynchronizationFeature(Settings.SynchronizationFeature)} instead - */ - @NotNull - @Deprecated(since = "2.1") - @SuppressWarnings("unused") - public static List getAll() { - return Arrays.stream(StatusDataFlag.values()).toList(); - } - - /** - * Returns all status data flags that are enabled for setting as per the {@link Settings} - * - * @param settings the settings to use for determining which flags are enabled - * @return all status data flags that are enabled for setting - * @deprecated Use {@link Settings#getSynchronizationFeature(Settings.SynchronizationFeature)} instead - */ - @NotNull - @Deprecated(since = "2.1") - public static List getFromSettings(@NotNull Settings settings) { - return Arrays.stream(StatusDataFlag.values()).filter( - flag -> settings.getSynchronizationFeature(flag.feature)).toList(); - } - -} diff --git a/common/src/main/java/net/william278/husksync/data/UserData.java b/common/src/main/java/net/william278/husksync/data/UserData.java deleted file mode 100644 index ada18f4c..00000000 --- a/common/src/main/java/net/william278/husksync/data/UserData.java +++ /dev/null @@ -1,376 +0,0 @@ -/* - * This file is part of HuskSync, licensed under the Apache License 2.0. - * - * Copyright (c) William278 - * Copyright (c) contributors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.william278.husksync.data; - -import com.google.gson.annotations.SerializedName; -import net.william278.desertwell.util.Version; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -import java.util.List; -import java.util.Optional; - -/** - * Stores data about a user - */ -public class UserData { - - /** - * Indicates the version of the {@link UserData} format being used. - *

- * This value is to be incremented whenever the format changes. - */ - public static final int CURRENT_FORMAT_VERSION = 3; - - /** - * Stores the user's status data, including health, food, etc. - */ - @SerializedName("status") - @Nullable - protected StatusData statusData; - - /** - * Stores the user's inventory contents - */ - @SerializedName("inventory") - @Nullable - protected ItemData inventoryData; - - /** - * Stores the user's ender chest contents - */ - @SerializedName("ender_chest") - @Nullable - protected ItemData enderChestData; - - /** - * Store's the user's potion effects - */ - @SerializedName("potion_effects") - @Nullable - protected PotionEffectData potionEffectData; - - /** - * Stores the set of this user's advancements - */ - @SerializedName("advancements") - @Nullable - protected List advancementData; - - /** - * Stores the user's set of statistics - */ - @SerializedName("statistics") - @Nullable - protected StatisticsData statisticData; - - /** - * Store's the user's world location and coordinates - */ - @SerializedName("location") - @Nullable - protected LocationData locationData; - - /** - * Stores the user's serialized persistent data container, which contains metadata keys applied by other plugins - */ - @SerializedName("persistent_data_container") - @Nullable - protected PersistentDataContainerData persistentDataContainerData; - - /** - * Stores the version of Minecraft this data was generated in - */ - @SerializedName("minecraft_version") - @NotNull - protected String minecraftVersion; - - /** - * Stores the version of the data format being used - */ - @SerializedName("format_version") - protected int formatVersion = CURRENT_FORMAT_VERSION; - - /** - * Create a new {@link UserData} object with the provided data - * - * @param statusData the user's status data ({@link StatusData}) - * @param inventoryData the user's inventory data ({@link ItemData}) - * @param enderChestData the user's ender chest data ({@link ItemData}) - * @param potionEffectData the user's potion effect data ({@link PotionEffectData}) - * @param advancementData the user's advancement data ({@link AdvancementData}) - * @param statisticData the user's statistic data ({@link StatisticsData}) - * @param locationData the user's location data ({@link LocationData}) - * @param persistentDataContainerData the user's persistent data container data ({@link PersistentDataContainerData}) - * @param minecraftVersion the version of Minecraft this data was generated in (e.g. {@code "1.19.2"}) - * @deprecated see {@link #builder(String)} or {@link #builder(Version)} to create a {@link UserDataBuilder}, which - * you can use to {@link UserDataBuilder#build()} a {@link UserData} instance with - */ - @Deprecated(since = "2.1") - public UserData(@Nullable StatusData statusData, @Nullable ItemData inventoryData, - @Nullable ItemData enderChestData, @Nullable PotionEffectData potionEffectData, - @Nullable List advancementData, @Nullable StatisticsData statisticData, - @Nullable LocationData locationData, @Nullable PersistentDataContainerData persistentDataContainerData, - @NotNull String minecraftVersion) { - this.statusData = statusData; - this.inventoryData = inventoryData; - this.enderChestData = enderChestData; - this.potionEffectData = potionEffectData; - this.advancementData = advancementData; - this.statisticData = statisticData; - this.locationData = locationData; - this.persistentDataContainerData = persistentDataContainerData; - this.minecraftVersion = minecraftVersion; - } - - // Empty constructor to facilitate json serialization - @SuppressWarnings("unused") - protected UserData() { - } - - /** - * Gets the {@link StatusData} from this user data - * - * @return the {@link StatusData} of this user data - * @since 2.0 - * @deprecated Use {@link #getStatus()}, which returns an optional instead - */ - @Nullable - @Deprecated(since = "2.1") - public StatusData getStatusData() { - return statusData; - } - - /** - * Gets the {@link StatusData} from this user data - * - * @return an optional containing the {@link StatusData} if it is present in this user data - * @since 2.1 - */ - public Optional getStatus() { - return Optional.ofNullable(statusData); - } - - /** - * Gets the {@link ItemData} representing the player's inventory from this user data - * - * @return the inventory {@link ItemData} of this user data - * @since 2.0 - * @deprecated Use {@link #getInventory()}, which returns an optional instead - */ - @Nullable - @Deprecated(since = "2.1") - public ItemData getInventoryData() { - return inventoryData; - } - - /** - * Gets the {@link ItemData} representing the player's inventory from this user data - * - * @return an optional containing the inventory {@link ItemData} if it is present in this user data - * @since 2.1 - */ - public Optional getInventory() { - return Optional.ofNullable(inventoryData); - } - - /** - * Gets the {@link ItemData} representing the player's ender chest from this user data - * - * @return the ender chest {@link ItemData} of this user data - * @since 2.0 - * @deprecated Use {@link #getEnderChest()}, which returns an optional instead - */ - @Nullable - @Deprecated(since = "2.1") - public ItemData getEnderChestData() { - return enderChestData; - } - - /** - * Gets the {@link ItemData} representing the player's ender chest from this user data - * - * @return an optional containing the ender chest {@link ItemData} if it is present in this user data - * @since 2.1 - */ - public Optional getEnderChest() { - return Optional.ofNullable(enderChestData); - } - - /** - * Gets the {@link PotionEffectData} representing player status effects from this user data - * - * @return the {@link PotionEffectData} of this user data - * @since 2.0 - * @deprecated Use {@link #getPotionEffects()}, which returns an optional instead - */ - @Nullable - @Deprecated(since = "2.1") - public PotionEffectData getPotionEffectsData() { - return potionEffectData; - } - - /** - * Gets the {@link PotionEffectData} representing the player's potion effects from this user data - * - * @return an optional containing {@link PotionEffectData} if it is present in this user data - * @since 2.1 - */ - public Optional getPotionEffects() { - return Optional.ofNullable(potionEffectData); - } - - /** - * Gets the list of {@link AdvancementData} from this user data - * - * @return the {@link AdvancementData} of this user data - * @since 2.0 - * @deprecated Use {@link #getAdvancements()}, which returns an optional instead - */ - @Nullable - @Deprecated(since = "2.1") - public List getAdvancementData() { - return advancementData; - } - - /** - * Gets a list of {@link AdvancementData} representing the player's advancements from this user data - * - * @return an optional containing a {@link List} of {@link AdvancementData} if it is present in this user data - * @since 2.1 - */ - public Optional> getAdvancements() { - return Optional.ofNullable(advancementData); - } - - /** - * Gets the {@link StatisticsData} representing player statistics from this user data - * - * @return the {@link StatisticsData} of this user data - * @since 2.0 - * @deprecated Use {@link #getStatistics()}, which returns an optional instead - */ - @Nullable - @Deprecated(since = "2.1") - public StatisticsData getStatisticsData() { - return statisticData; - } - - /** - * Gets {@link StatisticsData} representing player statistics from this user data - * - * @return an optional containing player {@link StatisticsData} if it is present in this user data - * @since 2.1 - */ - public Optional getStatistics() { - return Optional.ofNullable(statisticData); - } - - /** - * Gets the {@link LocationData} representing the player location from this user data - * - * @return the inventory {@link LocationData} of this user data - * @since 2.0 - * @deprecated Use {@link #getLocation()}, which returns an optional instead - */ - @Nullable - @Deprecated(since = "2.1") - public LocationData getLocationData() { - return locationData; - } - - /** - * Gets {@link LocationData} representing the player location from this user data - * - * @return an optional containing player {@link LocationData} if it is present in this user data - * @since 2.1 - */ - public Optional getLocation() { - return Optional.ofNullable(locationData); - } - - /** - * Gets the {@link PersistentDataContainerData} from this user data - * - * @return the {@link PersistentDataContainerData} of this user data - * @since 2.0 - * @deprecated Use {@link #getPersistentDataContainer()}, which returns an optional instead - */ - @Nullable - @Deprecated(since = "2.1") - public PersistentDataContainerData getPersistentDataContainerData() { - return persistentDataContainerData; - } - - /** - * Gets {@link PersistentDataContainerData} from this user data - * - * @return an optional containing the player's {@link PersistentDataContainerData} if it is present in this user data - * @since 2.1 - */ - public Optional getPersistentDataContainer() { - return Optional.ofNullable(persistentDataContainerData); - } - - /** - * Get the version of Minecraft this data was generated in - * - * @return the version of Minecraft this data was generated in - */ - @NotNull - public String getMinecraftVersion() { - return minecraftVersion; - } - - /** - * Gets the version of the data format being used - * - * @return the version of the data format being used - */ - public int getFormatVersion() { - return formatVersion; - } - - /** - * Get a new {@link UserDataBuilder} for creating {@link UserData} - * - * @param minecraftVersion the version of Minecraft this data was generated in (e.g. {@code "1.19.2"}) - * @return a UserData {@link UserDataBuilder} instance - * @since 2.1 - */ - @NotNull - public static UserDataBuilder builder(@NotNull String minecraftVersion) { - return new UserDataBuilder(minecraftVersion); - } - - /** - * Get a new {@link UserDataBuilder} for creating {@link UserData} - * - * @param minecraftVersion a {@link Version} object, representing the Minecraft version this data was generated in - * @return a UserData {@link UserDataBuilder} instance - * @since 2.1 - */ - @NotNull - public static UserDataBuilder builder(@NotNull Version minecraftVersion) { - return builder(minecraftVersion.toStringWithoutMetadata()); - } - - -} diff --git a/common/src/main/java/net/william278/husksync/data/UserDataBuilder.java b/common/src/main/java/net/william278/husksync/data/UserDataBuilder.java deleted file mode 100644 index 6a1e998a..00000000 --- a/common/src/main/java/net/william278/husksync/data/UserDataBuilder.java +++ /dev/null @@ -1,159 +0,0 @@ -/* - * This file is part of HuskSync, licensed under the Apache License 2.0. - * - * Copyright (c) William278 - * Copyright (c) contributors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.william278.husksync.data; - -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -import java.util.List; - -/** - * A builder utility for creating {@link UserData} instances - * - * @since 2.1 - */ -@SuppressWarnings("UnusedReturnValue") -public class UserDataBuilder { - - @NotNull - private final UserData userData; - - protected UserDataBuilder(@NotNull String minecraftVersion) { - this.userData = new UserData(); - this.userData.minecraftVersion = minecraftVersion; - } - - /** - * Set the {@link StatusData} to this {@link UserData} - * - * @param status the {@link StatusData} to set - * @return this {@link UserDataBuilder} - * @since 2.1 - */ - @NotNull - public UserDataBuilder setStatus(@NotNull StatusData status) { - this.userData.statusData = status; - return this; - } - - /** - * Set the inventory {@link ItemData} to this {@link UserData} - * - * @param inventoryData the inventory {@link ItemData} to set - * @return this {@link UserDataBuilder} - * @since 2.1 - */ - @NotNull - public UserDataBuilder setInventory(@Nullable ItemData inventoryData) { - this.userData.inventoryData = inventoryData; - return this; - } - - /** - * Set the ender chest {@link ItemData} to this {@link UserData} - * - * @param enderChestData the ender chest {@link ItemData} to set - * @return this {@link UserDataBuilder} - * @since 2.1 - */ - @NotNull - public UserDataBuilder setEnderChest(@Nullable ItemData enderChestData) { - this.userData.enderChestData = enderChestData; - return this; - } - - /** - * Set the {@link List} of {@link ItemData} to this {@link UserData} - * - * @param potionEffectData the {@link List} of {@link ItemData} to set - * @return this {@link UserDataBuilder} - * @since 2.1 - */ - @NotNull - public UserDataBuilder setPotionEffects(@Nullable PotionEffectData potionEffectData) { - this.userData.potionEffectData = potionEffectData; - return this; - } - - /** - * Set the {@link List} of {@link ItemData} to this {@link UserData} - * - * @param advancementData the {@link List} of {@link ItemData} to set - * @return this {@link UserDataBuilder} - * @since 2.1 - */ - @NotNull - public UserDataBuilder setAdvancements(@Nullable List advancementData) { - this.userData.advancementData = advancementData; - return this; - } - - /** - * Set the {@link StatisticsData} to this {@link UserData} - * - * @param statisticData the {@link StatisticsData} to set - * @return this {@link UserDataBuilder} - * @since 2.1 - */ - @NotNull - public UserDataBuilder setStatistics(@Nullable StatisticsData statisticData) { - this.userData.statisticData = statisticData; - return this; - } - - - /** - * Set the {@link LocationData} to this {@link UserData} - * - * @param locationData the {@link LocationData} to set - * @return this {@link UserDataBuilder} - * @since 2.1 - */ - @NotNull - public UserDataBuilder setLocation(@Nullable LocationData locationData) { - this.userData.locationData = locationData; - return this; - } - - /** - * Set the {@link PersistentDataContainerData} to this {@link UserData} - * - * @param persistentDataContainerData the {@link PersistentDataContainerData} to set - * @return this {@link UserDataBuilder} - * @since 2.1 - */ - @NotNull - public UserDataBuilder setPersistentDataContainer(@Nullable PersistentDataContainerData persistentDataContainerData) { - this.userData.persistentDataContainerData = persistentDataContainerData; - return this; - } - - /** - * Build and get the {@link UserData} instance - * - * @return the {@link UserData} instance - * @since 2.1 - */ - @NotNull - public UserData build() { - return this.userData; - } - -} diff --git a/common/src/main/java/net/william278/husksync/data/UserDataHolder.java b/common/src/main/java/net/william278/husksync/data/UserDataHolder.java new file mode 100644 index 00000000..e1a00d0f --- /dev/null +++ b/common/src/main/java/net/william278/husksync/data/UserDataHolder.java @@ -0,0 +1,167 @@ +/* + * This file is part of HuskSync, licensed under the Apache License 2.0. + * + * Copyright (c) William278 + * Copyright (c) contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.william278.husksync.data; + +import net.william278.desertwell.util.ThrowingConsumer; +import net.william278.husksync.HuskSync; +import org.jetbrains.annotations.ApiStatus; +import org.jetbrains.annotations.NotNull; + +import java.util.HashMap; +import java.util.Map; + +/** + * A holder of data in the form of {@link Data}s, which can be synced + */ +public interface UserDataHolder extends DataHolder { + + /** + * Get the data that is enabled for syncing in the config + * + * @return the data that is enabled for syncing + * @since 3.0 + */ + @Override + @NotNull + default Map getData() { + return getPlugin().getRegisteredDataTypes().stream() + .filter(type -> type.isCustom() || getPlugin().getSettings().isSyncFeatureEnabled(type)) + .map(id -> Map.entry(id, getData(id))) + .filter(data -> data.getValue().isPresent()) + .collect(HashMap::new, (map, data) -> map.put(data.getKey(), data.getValue().get()), HashMap::putAll); + } + + /** + * Apply the data for the given {@link Identifier} to the holder. + *

+ * This will be performed synchronously on the main server thread; it will not happen instantly. + * + * @param identifier the {@link Identifier} to set the data for + * @param data the {@link Data} to set + * @since 3.0 + */ + @Override + default void setData(@NotNull Identifier identifier, @NotNull Data data) { + getPlugin().runSync(() -> data.apply(this, getPlugin())); + } + + /** + * Create a serialized data snapshot of this data owner + * + * @param saveCause the cause of the snapshot + * @return the snapshot + * @since 3.0 + */ + @NotNull + default DataSnapshot.Packed createSnapshot(@NotNull DataSnapshot.SaveCause saveCause) { + return DataSnapshot.builder(getPlugin()).data(this.getData()).saveCause(saveCause).buildAndPack(); + } + + /** + * Deserialize and apply a data snapshot to this data owner + *

+ * This method will deserialize the data on the current thread, then synchronously apply it on + * the main server thread. + *

+ * The {@code runAfter} callback function will be run after the snapshot has been applied. + * + * @param snapshot the snapshot to apply + * @param runAfter the function to run asynchronously after the snapshot has been applied + * @since 3.0 + */ + default void applySnapshot(@NotNull DataSnapshot.Packed snapshot, @NotNull ThrowingConsumer runAfter) { + final HuskSync plugin = getPlugin(); + final DataSnapshot.Unpacked unpacked = snapshot.unpack(plugin); + plugin.runSync(() -> { + unpacked.getData().forEach((type, data) -> { + if (plugin.getSettings().isSyncFeatureEnabled(type)) { + if (type.isCustom()) { + getCustomDataStore().put(type, data); + } + data.apply(this, plugin); + } + }); + plugin.runAsync(() -> runAfter.accept(this)); + }); + } + + @Override + default void setInventory(@NotNull Data.Items.Inventory inventory) { + this.setData(Identifier.INVENTORY, inventory); + } + + @Override + default void setEnderChest(@NotNull Data.Items.EnderChest enderChest) { + this.setData(Identifier.ENDER_CHEST, enderChest); + } + + @Override + default void setPotionEffects(@NotNull Data.PotionEffects potionEffects) { + this.setData(Identifier.POTION_EFFECTS, potionEffects); + } + + @Override + default void setAdvancements(@NotNull Data.Advancements advancements) { + this.setData(Identifier.ADVANCEMENTS, advancements); + } + + @Override + default void setLocation(@NotNull Data.Location location) { + this.setData(Identifier.LOCATION, location); + } + + @Override + default void setStatistics(@NotNull Data.Statistics statistics) { + this.setData(Identifier.STATISTICS, statistics); + } + + @Override + default void setHealth(@NotNull Data.Health health) { + this.setData(Identifier.HEALTH, health); + } + + @Override + default void setHunger(@NotNull Data.Hunger hunger) { + this.setData(Identifier.HUNGER, hunger); + } + + @Override + default void setExperience(@NotNull Data.Experience experience) { + this.setData(Identifier.EXPERIENCE, experience); + } + + @Override + default void setGameMode(@NotNull Data.GameMode gameMode) { + this.setData(Identifier.GAME_MODE, gameMode); + } + + @Override + default void setPersistentData(@NotNull Data.PersistentData persistentData) { + this.setData(Identifier.PERSISTENT_DATA, persistentData); + } + + @NotNull + Map getCustomDataStore(); + + @NotNull + @ApiStatus.Internal + HuskSync getPlugin(); + +} diff --git a/common/src/main/java/net/william278/husksync/data/UserDataSnapshot.java b/common/src/main/java/net/william278/husksync/data/UserDataSnapshot.java deleted file mode 100644 index c7d088f9..00000000 --- a/common/src/main/java/net/william278/husksync/data/UserDataSnapshot.java +++ /dev/null @@ -1,145 +0,0 @@ -/* - * This file is part of HuskSync, licensed under the Apache License 2.0. - * - * Copyright (c) William278 - * Copyright (c) contributors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.william278.husksync.data; - -import net.william278.husksync.command.Permission; -import net.william278.husksync.config.Locales; -import net.william278.husksync.player.OnlineUser; -import net.william278.husksync.player.User; -import org.jetbrains.annotations.NotNull; - -import java.text.SimpleDateFormat; -import java.util.*; - -/** - * Represents a uniquely versioned and timestamped snapshot of a user's data, including why it was saved. - * - * @param versionUUID The unique identifier for this user data version - * @param versionTimestamp An epoch milliseconds timestamp of when this data was created - * @param userData The {@link UserData} that has been versioned - * @param cause The {@link DataSaveCause} that caused this data to be saved - */ -public record UserDataSnapshot(@NotNull UUID versionUUID, @NotNull Date versionTimestamp, - @NotNull DataSaveCause cause, boolean pinned, - @NotNull UserData userData) implements Comparable { - - /** - * Version {@link UserData} into a {@link UserDataSnapshot}, assigning it a random {@link UUID} and the current timestamp {@link Date} - *

- * Note that this method will set {@code cause} to {@link DataSaveCause#API} - * - * @param userData The {@link UserData} to version - * @return A new {@link UserDataSnapshot} - * @implNote This isn't used to version data that is going to be set to a database to prevent UUID collisions.

- * Database implementations should instead use their own UUID generation functions. - */ - public static UserDataSnapshot create(@NotNull UserData userData) { - return new UserDataSnapshot(UUID.randomUUID(), new Date(), - DataSaveCause.API, false, userData); - } - - /** - * Display a menu in chat to an {@link OnlineUser} about this {@link UserDataSnapshot} for a {@link User dataOwner} - * - * @param user The {@link OnlineUser} to display the menu to - * @param dataOwner The {@link User} whose data this snapshot captures a state of - * @param locales The {@link Locales} to use for displaying the menu - */ - public void displayDataOverview(@NotNull OnlineUser user, @NotNull User dataOwner, @NotNull Locales locales) { - // Title message, timestamp, owner and cause. - locales.getLocale("data_manager_title", versionUUID().toString().split("-")[0], - versionUUID().toString(), dataOwner.username, dataOwner.uuid.toString()) - .ifPresent(user::sendMessage); - locales.getLocale("data_manager_timestamp", - new SimpleDateFormat("MMM dd yyyy, HH:mm:ss.sss").format(versionTimestamp())) - .ifPresent(user::sendMessage); - if (pinned()) { - locales.getLocale("data_manager_pinned").ifPresent(user::sendMessage); - } - locales.getLocale("data_manager_cause", cause().name().toLowerCase(Locale.ENGLISH).replaceAll("_", " ")) - .ifPresent(user::sendMessage); - - // User status data, if present in the snapshot - userData().getStatus() - .flatMap(statusData -> locales.getLocale("data_manager_status", - Integer.toString((int) statusData.health), - Integer.toString((int) statusData.maxHealth), - Integer.toString(statusData.hunger), - Integer.toString(statusData.expLevel), - statusData.gameMode.toLowerCase(Locale.ENGLISH))) - .ifPresent(user::sendMessage); - - // Advancement and statistic data, if both are present in the snapshot - userData().getAdvancements() - .flatMap(advancementData -> userData().getStatistics() - .flatMap(statisticsData -> locales.getLocale("data_manager_advancements_statistics", - Integer.toString(advancementData.size()), - generateAdvancementPreview(advancementData, locales), - String.format("%.2f", (((statisticsData.untypedStatistics.getOrDefault( - "PLAY_ONE_MINUTE", 0)) / 20d) / 60d) / 60d)))) - .ifPresent(user::sendMessage); - - if (user.hasPermission(Permission.COMMAND_INVENTORY.node) - && user.hasPermission(Permission.COMMAND_ENDER_CHEST.node)) { - locales.getLocale("data_manager_item_buttons", dataOwner.username, versionUUID().toString()) - .ifPresent(user::sendMessage); - } - if (user.hasPermission(Permission.COMMAND_USER_DATA_MANAGE.node)) { - locales.getLocale("data_manager_management_buttons", dataOwner.username, versionUUID().toString()) - .ifPresent(user::sendMessage); - } - if (user.hasPermission(Permission.COMMAND_USER_DATA_DUMP.node)) { - locales.getLocale("data_manager_system_buttons", dataOwner.username, versionUUID().toString()) - .ifPresent(user::sendMessage); - } - } - - @NotNull - private String generateAdvancementPreview(@NotNull List advancementData, @NotNull Locales locales) { - final StringJoiner joiner = new StringJoiner("\n"); - final List advancementsToPreview = advancementData.stream().filter(dataItem -> - !dataItem.key.startsWith("minecraft:recipes/")).toList(); - final int PREVIEW_SIZE = 8; - for (int i = 0; i < advancementsToPreview.size(); i++) { - joiner.add(advancementsToPreview.get(i).key); - if (i >= PREVIEW_SIZE) { - break; - } - } - final int remainingAdvancements = advancementsToPreview.size() - PREVIEW_SIZE; - if (remainingAdvancements > 0) { - joiner.add(locales.getRawLocale("data_manager_advancements_preview_remaining", - Integer.toString(remainingAdvancements)).orElse("+" + remainingAdvancements + "…")); - } - return joiner.toString(); - } - - /** - * Compare UserData by creation timestamp - * - * @param other the other UserData to be compared - * @return the comparison result; the more recent UserData is greater than the less recent UserData - */ - @Override - public int compareTo(@NotNull UserDataSnapshot other) { - return Long.compare(this.versionTimestamp.getTime(), other.versionTimestamp.getTime()); - } - -} diff --git a/common/src/main/java/net/william278/husksync/database/Database.java b/common/src/main/java/net/william278/husksync/database/Database.java index c6cd47d4..b6dc6995 100644 --- a/common/src/main/java/net/william278/husksync/database/Database.java +++ b/common/src/main/java/net/william278/husksync/database/Database.java @@ -21,20 +21,20 @@ package net.william278.husksync.database; import net.william278.husksync.HuskSync; import net.william278.husksync.config.Settings; -import net.william278.husksync.data.DataSaveCause; -import net.william278.husksync.data.UserData; -import net.william278.husksync.data.UserDataSnapshot; -import net.william278.husksync.migrator.Migrator; -import net.william278.husksync.player.User; +import net.william278.husksync.data.DataSnapshot; +import net.william278.husksync.data.DataSnapshot.SaveCause; +import net.william278.husksync.data.UserDataHolder; +import net.william278.husksync.user.User; +import org.jetbrains.annotations.Blocking; import org.jetbrains.annotations.NotNull; import java.io.IOException; import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.UUID; -import java.util.concurrent.CompletableFuture; /** * An abstract representation of the plugin database, storing player data. @@ -57,17 +57,19 @@ public abstract class Database { * @throws IOException if the resource could not be read */ @SuppressWarnings("SameParameterValue") + @NotNull protected final String[] getSchemaStatements(@NotNull String schemaFileName) throws IOException { return formatStatementTables(new String(Objects.requireNonNull(plugin.getResource(schemaFileName)) .readAllBytes(), StandardCharsets.UTF_8)).split(";"); } /** - * Format all table name placeholder strings in a SQL statement + * Format all table name placeholder strings in an SQL statement * - * @param sql the SQL statement with un-formatted table name placeholders + * @param sql the SQL statement with unformatted table name placeholders * @return the formatted statement, with table placeholders replaced with the correct names */ + @NotNull protected final String formatStatementTables(@NotNull String sql) { return sql.replaceAll("%users_table%", plugin.getSettings().getTableName(Settings.TableName.USERS)) .replaceAll("%user_data_table%", plugin.getSettings().getTableName(Settings.TableName.USER_DATA)); @@ -75,57 +77,67 @@ public abstract class Database { /** * Initialize the database and ensure tables are present; create tables if they do not exist. + * + * @throws IllegalStateException if the database could not be initialized */ - public abstract void initialize(); + @Blocking + public abstract void initialize() throws IllegalStateException; /** * Ensure a {@link User} has an entry in the database and that their username is up-to-date * * @param user The {@link User} to ensure - * @return A future returning void when complete */ - public abstract CompletableFuture ensureUser(@NotNull User user); + @Blocking + public abstract void ensureUser(@NotNull User user); /** * Get a player by their Minecraft account {@link UUID} * * @param uuid Minecraft account {@link UUID} of the {@link User} to get - * @return A future returning an optional with the {@link User} present if they exist + * @return An optional with the {@link User} present if they exist */ - public abstract CompletableFuture> getUser(@NotNull UUID uuid); + @Blocking + public abstract Optional getUser(@NotNull UUID uuid); /** * Get a user by their username (case-insensitive) * * @param username Username of the {@link User} to get (case-insensitive) - * @return A future returning an optional with the {@link User} present if they exist + * @return An optional with the {@link User} present if they exist */ - public abstract CompletableFuture> getUserByName(@NotNull String username); + @Blocking + public abstract Optional getUserByName(@NotNull String username); + /** - * Get the current uniquely versioned user data for a given user, if it exists. + * Get the latest data snapshot for a user. * - * @param user the user to get data for - * @return an optional containing the {@link UserDataSnapshot}, if it exists, or an empty optional if it does not + * @param user The user to get data for + * @return an optional containing the {@link DataSnapshot}, if it exists, or an empty optional if it does not */ - public abstract CompletableFuture> getCurrentUserData(@NotNull User user); + @Blocking + public abstract Optional getLatestSnapshot(@NotNull User user); /** - * Get all {@link UserDataSnapshot} entries for a user from the database. + * Get all {@link DataSnapshot} entries for a user from the database. * * @param user The user to get data for - * @return A future returning a list of a user's {@link UserDataSnapshot} entries + * @return The list of a user's {@link DataSnapshot} entries */ - public abstract CompletableFuture> getUserData(@NotNull User user); + @Blocking + @NotNull + public abstract List getAllSnapshots(@NotNull User user); /** - * Gets a specific {@link UserDataSnapshot} entry for a user from the database, by its UUID. + * Gets a specific {@link DataSnapshot} entry for a user from the database, by its UUID. * * @param user The user to get data for - * @param versionUuid The UUID of the {@link UserDataSnapshot} entry to get - * @return A future returning an optional containing the {@link UserDataSnapshot}, if it exists, or an empty optional if it does not + * @param versionUuid The UUID of the {@link DataSnapshot} entry to get + * @return An optional containing the {@link DataSnapshot}, if it exists */ - public abstract CompletableFuture> getUserData(@NotNull User user, @NotNull UUID versionUuid); + @Blocking + public abstract Optional getSnapshot(@NotNull User user, @NotNull UUID versionUuid); /** * (Internal) Prune user data for a given user to the maximum value as configured. @@ -133,61 +145,131 @@ public abstract class Database { * @param user The user to prune data for * @implNote Data snapshots marked as {@code pinned} are exempt from rotation */ - protected abstract void rotateUserData(@NotNull User user); + @Blocking + protected abstract void rotateSnapshots(@NotNull User user); /** - * Deletes a specific {@link UserDataSnapshot} entry for a user from the database, by its UUID. + * Deletes a specific {@link DataSnapshot} entry for a user from the database, by its UUID. * * @param user The user to get data for - * @param versionUuid The UUID of the {@link UserDataSnapshot} entry to delete - * @return A future returning void when complete + * @param versionUuid The UUID of the {@link DataSnapshot} entry to delete */ - public abstract CompletableFuture deleteUserData(@NotNull User user, @NotNull UUID versionUuid); + @Blocking + public abstract boolean deleteSnapshot(@NotNull User user, @NotNull UUID versionUuid); /** - * Save user data to the database

+ * Save user data to the database + *

* This will remove the oldest data for the user if the amount of data exceeds the limit as configured * * @param user The user to add data for - * @param userData The {@link UserData} to set. The implementation should version it with a random UUID and the current timestamp during insertion. - * @return A future returning void when complete - * @see UserDataSnapshot#create(UserData) + * @param snapshot The {@link DataSnapshot} to set. + * The implementation should version it with a random UUID and the current timestamp during insertion. + * @see UserDataHolder#createSnapshot(SaveCause) */ - public abstract CompletableFuture setUserData(@NotNull User user, @NotNull UserData userData, @NotNull DataSaveCause dataSaveCause); + @Blocking + public void addSnapshot(@NotNull User user, @NotNull DataSnapshot.Packed snapshot) { + if (snapshot.getSaveCause() != SaveCause.SERVER_SHUTDOWN) { + plugin.fireEvent( + plugin.getDataSaveEvent(user, snapshot), + (event) -> this.addAndRotateSnapshot(user, snapshot) + ); + return; + } + + this.addAndRotateSnapshot(user, snapshot); + } /** - * Pin a saved {@link UserDataSnapshot} by given version UUID, setting it's {@code pinned} state to {@code true}. + * Internal - Save user data to the database. This will: + *
    + *
  1. Delete their most recent snapshot, if it was created before the backup frequency time
  2. + *
  3. Create the snapshot
  4. + *
  5. Rotate snapshot backups
  6. + *
* - * @param user The user to pin the data for - * @param versionUuid The UUID of the user's {@link UserDataSnapshot} entry to pin - * @return A future returning a boolean; {@code true} if the operation completed successfully, {@code false} if it failed - * @see UserDataSnapshot#pinned() + * @param user The user to add data for + * @param snapshot The {@link DataSnapshot} to set. + */ + @Blocking + private void addAndRotateSnapshot(@NotNull User user, @NotNull DataSnapshot.Packed snapshot) { + final int backupFrequency = plugin.getSettings().getBackupFrequency(); + if (!snapshot.isPinned() && backupFrequency > 0) { + this.rotateLatestSnapshot(user, snapshot.getTimestamp().minusHours(backupFrequency)); + } + this.createSnapshot(user, snapshot); + this.rotateSnapshots(user); + } + + /** + * Deletes the most recent data snapshot by the given {@link User user} + * The snapshot must have been created after {@link OffsetDateTime time} and NOT be pinned + * Facilities the backup frequency feature, reducing redundant snapshots from being saved longer than needed + * + * @param user The user to delete a snapshot for + * @param within The time to delete a snapshot after */ - public abstract CompletableFuture pinUserData(@NotNull User user, @NotNull UUID versionUuid); + @Blocking + protected abstract void rotateLatestSnapshot(@NotNull User user, @NotNull OffsetDateTime within); /** - * Unpin a saved {@link UserDataSnapshot} by given version UUID, setting it's {@code pinned} state to {@code false}. + * Internal - Create user data in the database + * + * @param user The user to add data for + * @param data The {@link DataSnapshot} to set. + */ + @Blocking + protected abstract void createSnapshot(@NotNull User user, @NotNull DataSnapshot.Packed data); + + /** + * Update a saved {@link DataSnapshot} by given version UUID + * + * @param user The user whose data snapshot + * @param snapshot The {@link DataSnapshot} to update + */ + @Blocking + public abstract void updateSnapshot(@NotNull User user, @NotNull DataSnapshot.Packed snapshot); + + /** + * Unpin a saved {@link DataSnapshot} by given version UUID, setting it's {@code pinned} state to {@code false}. * * @param user The user to unpin the data for - * @param versionUuid The UUID of the user's {@link UserDataSnapshot} entry to unpin - * @return A future returning a boolean; {@code true} if the operation completed successfully, {@code false} if it failed - * @see UserDataSnapshot#pinned() + * @param versionUuid The UUID of the user's {@link DataSnapshot} entry to unpin + * @see DataSnapshot#isPinned() */ - public abstract CompletableFuture unpinUserData(@NotNull User user, @NotNull UUID versionUuid); + @Blocking + public final void unpinSnapshot(@NotNull User user, @NotNull UUID versionUuid) { + this.getSnapshot(user, versionUuid).ifPresent(data -> { + data.edit(plugin, (snapshot) -> snapshot.setPinned(false)); + this.updateSnapshot(user, data); + }); + } /** - * Wipes all {@link UserData} entries from the database. - * This should never be used, except when preparing tables for migration. + * Pin a saved {@link DataSnapshot} by given version UUID, setting it's {@code pinned} state to {@code true}. * - * @return A future returning void when complete - * @see Migrator#start() + * @param user The user to pin the data for + * @param versionUuid The UUID of the user's {@link DataSnapshot} entry to pin + */ + @Blocking + public final void pinSnapshot(@NotNull User user, @NotNull UUID versionUuid) { + this.getSnapshot(user, versionUuid).ifPresent(data -> { + data.edit(plugin, (snapshot) -> snapshot.setPinned(true)); + this.updateSnapshot(user, data); + }); + } + + /** + * Wipes all {@link User} entries from the database. + * This should only be used when preparing tables for a data migration. */ - public abstract CompletableFuture wipeDatabase(); + @Blocking + public abstract void wipeDatabase(); /** * Close the database connection */ - public abstract void close(); + public abstract void terminate(); /** * Identifies types of databases diff --git a/common/src/main/java/net/william278/husksync/database/MySqlDatabase.java b/common/src/main/java/net/william278/husksync/database/MySqlDatabase.java index 987ba7fc..412756b8 100644 --- a/common/src/main/java/net/william278/husksync/database/MySqlDatabase.java +++ b/common/src/main/java/net/william278/husksync/database/MySqlDatabase.java @@ -21,20 +21,17 @@ package net.william278.husksync.database; import com.zaxxer.hikari.HikariDataSource; import net.william278.husksync.HuskSync; -import net.william278.husksync.data.DataAdaptionException; -import net.william278.husksync.data.DataSaveCause; -import net.william278.husksync.data.UserData; -import net.william278.husksync.data.UserDataSnapshot; -import net.william278.husksync.event.DataSaveEvent; -import net.william278.husksync.player.User; +import net.william278.husksync.adapter.DataAdapter; +import net.william278.husksync.data.DataSnapshot; +import net.william278.husksync.user.User; +import org.jetbrains.annotations.Blocking; import org.jetbrains.annotations.NotNull; import java.io.ByteArrayInputStream; import java.io.IOException; import java.sql.*; -import java.util.Date; +import java.time.OffsetDateTime; import java.util.*; -import java.util.concurrent.CompletableFuture; import java.util.logging.Level; public class MySqlDatabase extends Database { @@ -46,8 +43,7 @@ public class MySqlDatabase extends Database { public MySqlDatabase(@NotNull HuskSync plugin) { super(plugin); - this.flavor = plugin.getSettings().getDatabaseType() == Type.MARIADB - ? "mariadb" : "mysql"; + this.flavor = plugin.getSettings().getDatabaseType().getProtocol(); this.driverClass = plugin.getSettings().getDatabaseType() == Type.MARIADB ? "org.mariadb.jdbc.Driver" : "com.mysql.cj.jdbc.Driver"; } @@ -58,10 +54,16 @@ public class MySqlDatabase extends Database { * @return The {@link Connection} to the MySQL database * @throws SQLException if the connection fails for some reason */ + @Blocking + @NotNull private Connection getConnection() throws SQLException { + if (dataSource == null) { + throw new IllegalStateException("The database has not been initialized"); + } return dataSource.getConnection(); } + @Blocking @Override public void initialize() throws IllegalStateException { // Initialize the Hikari pooled connection @@ -124,192 +126,175 @@ public class MySqlDatabase extends Database { } } + @Blocking @Override - public CompletableFuture ensureUser(@NotNull User user) { - return getUser(user.uuid).thenAccept(optionalUser -> - optionalUser.ifPresentOrElse(existingUser -> { - if (!existingUser.username.equals(user.username)) { - // Update a user's name if it has changed in the database - try (Connection connection = getConnection()) { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - UPDATE `%users_table%` - SET `username`=? - WHERE `uuid`=?"""))) { + public void ensureUser(@NotNull User user) { + getUser(user.getUuid()).ifPresentOrElse( + existingUser -> { + if (!existingUser.getUsername().equals(user.getUsername())) { + // Update a user's name if it has changed in the database + try (Connection connection = getConnection()) { + try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" + UPDATE `%users_table%` + SET `username`=? + WHERE `uuid`=?"""))) { - statement.setString(1, user.username); - statement.setString(2, existingUser.uuid.toString()); - statement.executeUpdate(); - } - plugin.log(Level.INFO, "Updated " + user.username + "'s name in the database (" + existingUser.username + " -> " + user.username + ")"); - } catch (SQLException e) { - plugin.log(Level.SEVERE, "Failed to update a user's name on the database", e); - } + statement.setString(1, user.getUsername()); + statement.setString(2, existingUser.getUuid().toString()); + statement.executeUpdate(); } - }, - () -> { - // Insert new player data into the database - try (Connection connection = getConnection()) { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - INSERT INTO `%users_table%` (`uuid`,`username`) - VALUES (?,?);"""))) { + plugin.log(Level.INFO, "Updated " + user.getUsername() + "'s name in the database (" + existingUser.getUsername() + " -> " + user.getUsername() + ")"); + } catch (SQLException e) { + plugin.log(Level.SEVERE, "Failed to update a user's name on the database", e); + } + } + }, + () -> { + // Insert new player data into the database + try (Connection connection = getConnection()) { + try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" + INSERT INTO `%users_table%` (`uuid`,`username`) + VALUES (?,?);"""))) { - statement.setString(1, user.uuid.toString()); - statement.setString(2, user.username); - statement.executeUpdate(); - } - } catch (SQLException e) { - plugin.log(Level.SEVERE, "Failed to insert a user into the database", e); - } - })); + statement.setString(1, user.getUuid().toString()); + statement.setString(2, user.getUsername()); + statement.executeUpdate(); + } + } catch (SQLException e) { + plugin.log(Level.SEVERE, "Failed to insert a user into the database", e); + } + } + ); } + @Blocking @Override - public CompletableFuture> getUser(@NotNull UUID uuid) { - return CompletableFuture.supplyAsync(() -> { - try (Connection connection = getConnection()) { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - SELECT `uuid`, `username` - FROM `%users_table%` - WHERE `uuid`=?"""))) { + public Optional getUser(@NotNull UUID uuid) { + try (Connection connection = getConnection()) { + try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" + SELECT `uuid`, `username` + FROM `%users_table%` + WHERE `uuid`=?"""))) { - statement.setString(1, uuid.toString()); + statement.setString(1, uuid.toString()); - final ResultSet resultSet = statement.executeQuery(); - if (resultSet.next()) { - return Optional.of(new User(UUID.fromString(resultSet.getString("uuid")), - resultSet.getString("username"))); - } + final ResultSet resultSet = statement.executeQuery(); + if (resultSet.next()) { + return Optional.of(new User(UUID.fromString(resultSet.getString("uuid")), + resultSet.getString("username"))); } - } catch (SQLException e) { - plugin.log(Level.SEVERE, "Failed to fetch a user from uuid from the database", e); } - return Optional.empty(); - }); + } catch (SQLException e) { + plugin.log(Level.SEVERE, "Failed to fetch a user from uuid from the database", e); + } + return Optional.empty(); } + @Blocking @Override - public CompletableFuture> getUserByName(@NotNull String username) { - return CompletableFuture.supplyAsync(() -> { - try (Connection connection = getConnection()) { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - SELECT `uuid`, `username` - FROM `%users_table%` - WHERE `username`=?"""))) { - statement.setString(1, username); + public Optional getUserByName(@NotNull String username) { + try (Connection connection = getConnection()) { + try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" + SELECT `uuid`, `username` + FROM `%users_table%` + WHERE `username`=?"""))) { + statement.setString(1, username); - final ResultSet resultSet = statement.executeQuery(); - if (resultSet.next()) { - return Optional.of(new User(UUID.fromString(resultSet.getString("uuid")), - resultSet.getString("username"))); - } + final ResultSet resultSet = statement.executeQuery(); + if (resultSet.next()) { + return Optional.of(new User(UUID.fromString(resultSet.getString("uuid")), + resultSet.getString("username"))); } - } catch (SQLException e) { - plugin.log(Level.SEVERE, "Failed to fetch a user by name from the database", e); } - return Optional.empty(); - }); + } catch (SQLException e) { + plugin.log(Level.SEVERE, "Failed to fetch a user by name from the database", e); + } + return Optional.empty(); } + @Blocking @Override - public CompletableFuture> getCurrentUserData(@NotNull User user) { - return CompletableFuture.supplyAsync(() -> { - try (Connection connection = getConnection()) { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - SELECT `version_uuid`, `timestamp`, `save_cause`, `pinned`, `data` - FROM `%user_data_table%` - WHERE `player_uuid`=? - ORDER BY `timestamp` DESC - LIMIT 1;"""))) { - statement.setString(1, user.uuid.toString()); - final ResultSet resultSet = statement.executeQuery(); - if (resultSet.next()) { - final Blob blob = resultSet.getBlob("data"); - final byte[] dataByteArray = blob.getBytes(1, (int) blob.length()); - blob.free(); - return Optional.of(new UserDataSnapshot( - UUID.fromString(resultSet.getString("version_uuid")), - Date.from(resultSet.getTimestamp("timestamp").toInstant()), - DataSaveCause.getCauseByName(resultSet.getString("save_cause")), - resultSet.getBoolean("pinned"), - plugin.getDataAdapter().fromBytes(dataByteArray))); - } + public Optional getLatestSnapshot(@NotNull User user) { + try (Connection connection = getConnection()) { + try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" + SELECT `version_uuid`, `timestamp`, `save_cause`, `pinned`, `data` + FROM `%user_data_table%` + WHERE `player_uuid`=? + ORDER BY `timestamp` DESC + LIMIT 1;"""))) { + statement.setString(1, user.getUuid().toString()); + final ResultSet resultSet = statement.executeQuery(); + if (resultSet.next()) { + final Blob blob = resultSet.getBlob("data"); + final byte[] dataByteArray = blob.getBytes(1, (int) blob.length()); + blob.free(); + return Optional.of(DataSnapshot.deserialize(plugin, dataByteArray)); } - } catch (SQLException | DataAdaptionException e) { - plugin.log(Level.SEVERE, "Failed to fetch a user's current user data from the database", e); } - return Optional.empty(); - }); + } catch (SQLException | DataAdapter.AdaptionException e) { + plugin.log(Level.SEVERE, "Failed to fetch a user's current user data from the database", e); + } + return Optional.empty(); } + @Blocking @Override - public CompletableFuture> getUserData(@NotNull User user) { - return CompletableFuture.supplyAsync(() -> { - final List retrievedData = new ArrayList<>(); - try (Connection connection = getConnection()) { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - SELECT `version_uuid`, `timestamp`, `save_cause`, `pinned`, `data` - FROM `%user_data_table%` - WHERE `player_uuid`=? - ORDER BY `timestamp` DESC;"""))) { - statement.setString(1, user.uuid.toString()); - final ResultSet resultSet = statement.executeQuery(); - while (resultSet.next()) { - final Blob blob = resultSet.getBlob("data"); - final byte[] dataByteArray = blob.getBytes(1, (int) blob.length()); - blob.free(); - final UserDataSnapshot data = new UserDataSnapshot( - UUID.fromString(resultSet.getString("version_uuid")), - Date.from(resultSet.getTimestamp("timestamp").toInstant()), - DataSaveCause.getCauseByName(resultSet.getString("save_cause")), - resultSet.getBoolean("pinned"), - plugin.getDataAdapter().fromBytes(dataByteArray)); - retrievedData.add(data); - } - return retrievedData; + @NotNull + public List getAllSnapshots(@NotNull User user) { + final List retrievedData = new ArrayList<>(); + try (Connection connection = getConnection()) { + try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" + SELECT `version_uuid`, `timestamp`, `save_cause`, `pinned`, `data` + FROM `%user_data_table%` + WHERE `player_uuid`=? + ORDER BY `timestamp` DESC;"""))) { + statement.setString(1, user.getUuid().toString()); + final ResultSet resultSet = statement.executeQuery(); + while (resultSet.next()) { + final Blob blob = resultSet.getBlob("data"); + final byte[] dataByteArray = blob.getBytes(1, (int) blob.length()); + blob.free(); + retrievedData.add(DataSnapshot.deserialize(plugin, dataByteArray)); } - } catch (SQLException | DataAdaptionException e) { - plugin.log(Level.SEVERE, "Failed to fetch a user's current user data from the database", e); + return retrievedData; } - return retrievedData; - }); + } catch (SQLException | DataAdapter.AdaptionException e) { + plugin.log(Level.SEVERE, "Failed to fetch a user's current user data from the database", e); + } + return retrievedData; } + @Blocking @Override - public CompletableFuture> getUserData(@NotNull User user, @NotNull UUID versionUuid) { - return CompletableFuture.supplyAsync(() -> { - try (Connection connection = getConnection()) { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - SELECT `version_uuid`, `timestamp`, `save_cause`, `pinned`, `data` - FROM `%user_data_table%` - WHERE `player_uuid`=? AND `version_uuid`=? - ORDER BY `timestamp` DESC - LIMIT 1;"""))) { - statement.setString(1, user.uuid.toString()); - statement.setString(2, versionUuid.toString()); - final ResultSet resultSet = statement.executeQuery(); - if (resultSet.next()) { - final Blob blob = resultSet.getBlob("data"); - final byte[] dataByteArray = blob.getBytes(1, (int) blob.length()); - blob.free(); - return Optional.of(new UserDataSnapshot( - UUID.fromString(resultSet.getString("version_uuid")), - Date.from(resultSet.getTimestamp("timestamp").toInstant()), - DataSaveCause.getCauseByName(resultSet.getString("save_cause")), - resultSet.getBoolean("pinned"), - plugin.getDataAdapter().fromBytes(dataByteArray))); - } + public Optional getSnapshot(@NotNull User user, @NotNull UUID versionUuid) { + try (Connection connection = getConnection()) { + try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" + SELECT `version_uuid`, `timestamp`, `save_cause`, `pinned`, `data` + FROM `%user_data_table%` + WHERE `player_uuid`=? AND `version_uuid`=? + ORDER BY `timestamp` DESC + LIMIT 1;"""))) { + statement.setString(1, user.getUuid().toString()); + statement.setString(2, versionUuid.toString()); + final ResultSet resultSet = statement.executeQuery(); + if (resultSet.next()) { + final Blob blob = resultSet.getBlob("data"); + final byte[] dataByteArray = blob.getBytes(1, (int) blob.length()); + blob.free(); + return Optional.of(DataSnapshot.deserialize(plugin, dataByteArray)); } - } catch (SQLException | DataAdaptionException e) { - plugin.log(Level.SEVERE, "Failed to fetch specific user data by UUID from the database", e); } - return Optional.empty(); - }); + } catch (SQLException | DataAdapter.AdaptionException e) { + plugin.log(Level.SEVERE, "Failed to fetch specific user data by UUID from the database", e); + } + return Optional.empty(); } + @Blocking @Override - protected void rotateUserData(@NotNull User user) { - final List unpinnedUserData = getUserData(user).join().stream() - .filter(dataSnapshot -> !dataSnapshot.pinned()).toList(); + protected void rotateSnapshots(@NotNull User user) { + final List unpinnedUserData = getAllSnapshots(user).stream() + .filter(dataSnapshot -> !dataSnapshot.isPinned()).toList(); if (unpinnedUserData.size() > plugin.getSettings().getMaxUserDataSnapshots()) { try (Connection connection = getConnection()) { try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" @@ -319,7 +304,7 @@ public class MySqlDatabase extends Database { ORDER BY `timestamp` ASC LIMIT %entry_count%;""".replace("%entry_count%", Integer.toString(unpinnedUserData.size() - plugin.getSettings().getMaxUserDataSnapshots()))))) { - statement.setString(1, user.uuid.toString()); + statement.setString(1, user.getUuid().toString()); statement.executeUpdate(); } } catch (SQLException e) { @@ -328,105 +313,97 @@ public class MySqlDatabase extends Database { } } + @Blocking @Override - public CompletableFuture deleteUserData(@NotNull User user, @NotNull UUID versionUuid) { - return CompletableFuture.supplyAsync(() -> { - try (Connection connection = getConnection()) { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - DELETE FROM `%user_data_table%` - WHERE `player_uuid`=? AND `version_uuid`=? - LIMIT 1;"""))) { - statement.setString(1, user.uuid.toString()); - statement.setString(2, versionUuid.toString()); - return statement.executeUpdate() > 0; - } - } catch (SQLException e) { - plugin.log(Level.SEVERE, "Failed to delete specific user data from the database", e); + public boolean deleteSnapshot(@NotNull User user, @NotNull UUID versionUuid) { + try (Connection connection = getConnection()) { + try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" + DELETE FROM `%user_data_table%` + WHERE `player_uuid`=? AND `version_uuid`=? + LIMIT 1;"""))) { + statement.setString(1, user.getUuid().toString()); + statement.setString(2, versionUuid.toString()); + return statement.executeUpdate() > 0; } - return false; - }); + } catch (SQLException e) { + plugin.log(Level.SEVERE, "Failed to delete specific user data from the database", e); + } + return false; } + @Blocking @Override - public CompletableFuture setUserData(@NotNull User user, @NotNull UserData userData, - @NotNull DataSaveCause saveCause) { - return CompletableFuture.runAsync(() -> { - final DataSaveEvent dataSaveEvent = (DataSaveEvent) plugin.getEventCannon().fireDataSaveEvent(user, - userData, saveCause).join(); - if (!dataSaveEvent.isCancelled()) { - final UserData finalData = dataSaveEvent.getUserData(); - try (Connection connection = getConnection()) { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - INSERT INTO `%user_data_table%` - (`player_uuid`,`version_uuid`,`timestamp`,`save_cause`,`data`) - VALUES (?,UUID(),NOW(),?,?);"""))) { - statement.setString(1, user.uuid.toString()); - statement.setString(2, saveCause.name()); - statement.setBlob(3, new ByteArrayInputStream( - plugin.getDataAdapter().toBytes(finalData))); - statement.executeUpdate(); - } - } catch (SQLException | DataAdaptionException e) { - plugin.log(Level.SEVERE, "Failed to set user data in the database", e); - } + protected void rotateLatestSnapshot(@NotNull User user, @NotNull OffsetDateTime within) { + try (Connection connection = getConnection()) { + try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" + DELETE FROM `%user_data_table%` + WHERE `player_uuid`=? AND `timestamp`>? AND `pinned` IS FALSE + ORDER BY `timestamp` ASC + LIMIT 1;"""))) { + statement.setString(1, user.getUuid().toString()); + statement.setTimestamp(2, Timestamp.from(within.toInstant())); + statement.executeUpdate(); } - this.rotateUserData(user); - }); + } catch (SQLException e) { + plugin.log(Level.SEVERE, "Failed to delete a user's data from the database", e); + } } + @Blocking @Override - public CompletableFuture pinUserData(@NotNull User user, @NotNull UUID versionUuid) { - return CompletableFuture.runAsync(() -> { - try (Connection connection = getConnection()) { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - UPDATE `%user_data_table%` - SET `pinned`=TRUE - WHERE `player_uuid`=? AND `version_uuid`=? - LIMIT 1;"""))) { - statement.setString(1, user.uuid.toString()); - statement.setString(2, versionUuid.toString()); - statement.executeUpdate(); - } - } catch (SQLException e) { - plugin.log(Level.SEVERE, "Failed to pin user data in the database", e); + protected void createSnapshot(@NotNull User user, @NotNull DataSnapshot.Packed data) { + try (Connection connection = getConnection()) { + try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" + INSERT INTO `%user_data_table%` + (`player_uuid`,`version_uuid`,`timestamp`,`save_cause`,`pinned`,`data`) + VALUES (?,?,?,?,?,?);"""))) { + statement.setString(1, user.getUuid().toString()); + statement.setString(2, data.getId().toString()); + statement.setTimestamp(3, Timestamp.from(data.getTimestamp().toInstant())); + statement.setString(4, data.getSaveCause().name()); + statement.setBoolean(5, data.isPinned()); + statement.setBlob(6, new ByteArrayInputStream(data.asBytes(plugin))); + statement.executeUpdate(); } - }); + } catch (SQLException | DataAdapter.AdaptionException e) { + plugin.log(Level.SEVERE, "Failed to set user data in the database", e); + } } + @Blocking @Override - public CompletableFuture unpinUserData(@NotNull User user, @NotNull UUID versionUuid) { - return CompletableFuture.runAsync(() -> { - try (Connection connection = getConnection()) { - try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" - UPDATE `%user_data_table%` - SET `pinned`=FALSE - WHERE `player_uuid`=? AND `version_uuid`=? - LIMIT 1;"""))) { - statement.setString(1, user.uuid.toString()); - statement.setString(2, versionUuid.toString()); - statement.executeUpdate(); - } - } catch (SQLException e) { - plugin.log(Level.SEVERE, "Failed to unpin user data in the database", e); + public void updateSnapshot(@NotNull User user, @NotNull DataSnapshot.Packed data) { + try (Connection connection = getConnection()) { + try (PreparedStatement statement = connection.prepareStatement(formatStatementTables(""" + UPDATE `%user_data_table%` + SET `save_cause`=?,`pinned`=?,`data`=? + WHERE `player_uuid`=? AND `version_uuid`=? + LIMIT 1;"""))) { + statement.setString(1, data.getSaveCause().name()); + statement.setBoolean(2, data.isPinned()); + statement.setBlob(3, new ByteArrayInputStream(data.asBytes(plugin))); + statement.setString(4, user.getUuid().toString()); + statement.setString(5, data.getId().toString()); + statement.executeUpdate(); } - }); + } catch (SQLException e) { + plugin.log(Level.SEVERE, "Failed to pin user data in the database", e); + } } @Override - public CompletableFuture wipeDatabase() { - return CompletableFuture.runAsync(() -> { - try (Connection connection = getConnection()) { - try (Statement statement = connection.createStatement()) { - statement.executeUpdate(formatStatementTables("DELETE FROM `%user_data_table%`;")); - } - } catch (SQLException e) { - plugin.log(Level.SEVERE, "Failed to wipe the database", e); + public void wipeDatabase() { + try (Connection connection = getConnection()) { + try (Statement statement = connection.createStatement()) { + statement.executeUpdate(formatStatementTables("DELETE FROM `%user_data_table%`;")); } - }); + } catch (SQLException e) { + plugin.log(Level.SEVERE, "Failed to wipe the database", e); + } } @Override - public void close() { + public void terminate() { if (dataSource != null) { if (!dataSource.isClosed()) { dataSource.close(); diff --git a/common/src/main/java/net/william278/husksync/event/CancellableEvent.java b/common/src/main/java/net/william278/husksync/event/Cancellable.java similarity index 89% rename from common/src/main/java/net/william278/husksync/event/CancellableEvent.java rename to common/src/main/java/net/william278/husksync/event/Cancellable.java index 7dc7f79c..ef0becd5 100644 --- a/common/src/main/java/net/william278/husksync/event/CancellableEvent.java +++ b/common/src/main/java/net/william278/husksync/event/Cancellable.java @@ -19,9 +19,9 @@ package net.william278.husksync.event; -public interface CancellableEvent extends Event { +@SuppressWarnings("unused") +public interface Cancellable extends Event { - @SuppressWarnings("BooleanMethodIsAlwaysInverted") default boolean isCancelled() { return false; } diff --git a/common/src/main/java/net/william278/husksync/event/DataSaveEvent.java b/common/src/main/java/net/william278/husksync/event/DataSaveEvent.java index 7e9be813..567131f8 100644 --- a/common/src/main/java/net/william278/husksync/event/DataSaveEvent.java +++ b/common/src/main/java/net/william278/husksync/event/DataSaveEvent.java @@ -19,21 +19,34 @@ package net.william278.husksync.event; -import net.william278.husksync.data.DataSaveCause; -import net.william278.husksync.data.UserData; -import net.william278.husksync.player.User; +import net.william278.husksync.HuskSync; +import net.william278.husksync.data.DataSnapshot; +import net.william278.husksync.user.User; +import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; -public interface DataSaveEvent extends CancellableEvent { +import java.util.function.Consumer; + +@SuppressWarnings("unused") +public interface DataSaveEvent extends Cancellable { + + @NotNull + User getUser(); @NotNull - UserData getUserData(); + DataSnapshot.Packed getData(); - void setUserData(@NotNull UserData userData); + default void editData(@NotNull Consumer editor) { + getData().edit(getPlugin(), editor); + } - @NotNull User getUser(); + @NotNull + default DataSnapshot.SaveCause getSaveCause() { + return getData().getSaveCause(); + } @NotNull - DataSaveCause getSaveCause(); + @ApiStatus.Internal + HuskSync getPlugin(); } diff --git a/common/src/main/java/net/william278/husksync/event/Event.java b/common/src/main/java/net/william278/husksync/event/Event.java index f7ec6eb2..698abea3 100644 --- a/common/src/main/java/net/william278/husksync/event/Event.java +++ b/common/src/main/java/net/william278/husksync/event/Event.java @@ -19,10 +19,6 @@ package net.william278.husksync.event; -import java.util.concurrent.CompletableFuture; - public interface Event { - CompletableFuture fire(); - } diff --git a/common/src/main/java/net/william278/husksync/event/EventCannon.java b/common/src/main/java/net/william278/husksync/event/EventCannon.java deleted file mode 100644 index ac4779d4..00000000 --- a/common/src/main/java/net/william278/husksync/event/EventCannon.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * This file is part of HuskSync, licensed under the Apache License 2.0. - * - * Copyright (c) William278 - * Copyright (c) contributors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.william278.husksync.event; - -import net.william278.husksync.data.DataSaveCause; -import net.william278.husksync.data.UserData; -import net.william278.husksync.player.OnlineUser; -import net.william278.husksync.player.User; -import org.jetbrains.annotations.NotNull; - -import java.util.concurrent.CompletableFuture; - -/** - * Used to fire plugin {@link Event}s - */ -public abstract class EventCannon { - - protected EventCannon() { - } - - /** - * Fires a {@link PreSyncEvent} - * - * @param user The user to fire the event for - * @param userData The user data to fire the event with - * @return A future that will be completed when the event is fired - */ - public abstract CompletableFuture firePreSyncEvent(@NotNull OnlineUser user, @NotNull UserData userData); - - /** - * Fires a {@link DataSaveEvent} - * - * @param user The user to fire the event for - * @param userData The user data to fire the event with - * @return A future that will be completed when the event is fired - */ - public abstract CompletableFuture fireDataSaveEvent(@NotNull User user, @NotNull UserData userData, - - @NotNull DataSaveCause saveCause); - - /** - * Fires a {@link SyncCompleteEvent} - * - * @param user The user to fire the event for - */ - public abstract void fireSyncCompleteEvent(@NotNull OnlineUser user); - -} diff --git a/common/src/main/java/net/william278/husksync/event/EventDispatcher.java b/common/src/main/java/net/william278/husksync/event/EventDispatcher.java new file mode 100644 index 00000000..2b6c5f42 --- /dev/null +++ b/common/src/main/java/net/william278/husksync/event/EventDispatcher.java @@ -0,0 +1,72 @@ +/* + * This file is part of HuskSync, licensed under the Apache License 2.0. + * + * Copyright (c) William278 + * Copyright (c) contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.william278.husksync.event; + +import net.william278.husksync.HuskSync; +import net.william278.husksync.data.DataSnapshot; +import net.william278.husksync.user.OnlineUser; +import net.william278.husksync.user.User; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.function.Consumer; + +/** + * Used to fire plugin {@link Event}s + */ +public interface EventDispatcher { + + /** + * Fire an event synchronously, then run a callback asynchronously. + * + * @param event The event to fire + * @param callback The callback to run after the event has been fired + * @param The material of event to fire + */ + default void fireEvent(@NotNull T event, @Nullable Consumer callback) { + getPlugin().runSync(() -> { + if (!fireIsCancelled(event) && callback != null) { + getPlugin().runAsync(() -> callback.accept(event)); + } + }); + } + + /** + * Fire an event on this thread, and return whether the event was canceled. + * + * @param event The event to fire + * @param The material of event to fire + * @return Whether the event was canceled + */ + boolean fireIsCancelled(@NotNull T event); + + @NotNull + PreSyncEvent getPreSyncEvent(@NotNull OnlineUser user, @NotNull DataSnapshot.Packed userData); + + @NotNull + DataSaveEvent getDataSaveEvent(@NotNull User user, @NotNull DataSnapshot.Packed saveCause); + + @NotNull + SyncCompleteEvent getSyncCompleteEvent(@NotNull OnlineUser user); + + @NotNull + HuskSync getPlugin(); + +} diff --git a/common/src/main/java/net/william278/husksync/event/PlayerEvent.java b/common/src/main/java/net/william278/husksync/event/PlayerEvent.java index c381e479..8146a292 100644 --- a/common/src/main/java/net/william278/husksync/event/PlayerEvent.java +++ b/common/src/main/java/net/william278/husksync/event/PlayerEvent.java @@ -19,10 +19,12 @@ package net.william278.husksync.event; -import net.william278.husksync.player.OnlineUser; +import net.william278.husksync.user.OnlineUser; +import org.jetbrains.annotations.NotNull; public interface PlayerEvent extends Event { + @NotNull OnlineUser getUser(); } diff --git a/common/src/main/java/net/william278/husksync/event/PreSyncEvent.java b/common/src/main/java/net/william278/husksync/event/PreSyncEvent.java index e5e27fc2..c47352d5 100644 --- a/common/src/main/java/net/william278/husksync/event/PreSyncEvent.java +++ b/common/src/main/java/net/william278/husksync/event/PreSyncEvent.java @@ -19,14 +19,30 @@ package net.william278.husksync.event; -import net.william278.husksync.data.UserData; +import net.william278.husksync.HuskSync; +import net.william278.husksync.data.DataSnapshot; +import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; -public interface PreSyncEvent extends CancellableEvent { +import java.util.function.Consumer; + +@SuppressWarnings("unused") +public interface PreSyncEvent extends PlayerEvent { @NotNull - UserData getUserData(); + DataSnapshot.Packed getData(); + + default void editData(@NotNull Consumer editor) { + getData().edit(getPlugin(), editor); + } - void setUserData(@NotNull UserData userData); + @NotNull + default DataSnapshot.SaveCause getSaveCause() { + return getData().getSaveCause(); + } + + @NotNull + @ApiStatus.Internal + HuskSync getPlugin(); } diff --git a/common/src/main/java/net/william278/husksync/hook/PlanDataExtension.java b/common/src/main/java/net/william278/husksync/hook/PlanDataExtension.java deleted file mode 100644 index 89b6a7db..00000000 --- a/common/src/main/java/net/william278/husksync/hook/PlanDataExtension.java +++ /dev/null @@ -1,240 +0,0 @@ -/* - * This file is part of HuskSync, licensed under the Apache License 2.0. - * - * Copyright (c) William278 - * Copyright (c) contributors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.william278.husksync.hook; - -import com.djrapitops.plan.extension.CallEvents; -import com.djrapitops.plan.extension.DataExtension; -import com.djrapitops.plan.extension.ElementOrder; -import com.djrapitops.plan.extension.FormatType; -import com.djrapitops.plan.extension.annotation.*; -import com.djrapitops.plan.extension.icon.Color; -import com.djrapitops.plan.extension.icon.Family; -import com.djrapitops.plan.extension.icon.Icon; -import com.djrapitops.plan.extension.table.Table; -import com.djrapitops.plan.extension.table.TableColumnFormat; -import net.william278.husksync.HuskSync; -import net.william278.husksync.data.UserDataSnapshot; -import net.william278.husksync.player.User; -import org.jetbrains.annotations.NotNull; - -import java.util.Date; -import java.util.Locale; -import java.util.Optional; -import java.util.UUID; -import java.util.concurrent.CompletableFuture; -import java.util.regex.Pattern; - -@TabInfo( - tab = "Current Status", - iconName = "id-card", - iconFamily = Family.SOLID, - elementOrder = {ElementOrder.VALUES, ElementOrder.TABLE, ElementOrder.GRAPH} -) -@TabInfo( - tab = "Data Snapshots", - iconName = "clipboard-list", - iconFamily = Family.SOLID, - elementOrder = {ElementOrder.VALUES, ElementOrder.TABLE, ElementOrder.GRAPH} -) -@TabOrder({"Current Status", "Data Snapshots"}) -@PluginInfo( - name = "HuskSync", - iconName = "exchange-alt", - iconFamily = Family.SOLID, - color = Color.LIGHT_BLUE -) -@SuppressWarnings("unused") -public class PlanDataExtension implements DataExtension { - - private HuskSync plugin; - - private static final String UNKNOWN_STRING = "N/A"; - - private static final String PINNED_HTML_STRING = "📍 "; - - protected PlanDataExtension(@NotNull HuskSync plugin) { - this.plugin = plugin; - } - - protected PlanDataExtension() { - } - - @Override - public CallEvents[] callExtensionMethodsOn() { - return new CallEvents[]{ - CallEvents.PLAYER_JOIN, - CallEvents.PLAYER_LEAVE - }; - } - - private CompletableFuture> getCurrentUserData(@NotNull UUID uuid) { - return CompletableFuture.supplyAsync(() -> { - final Optional optionalUser = plugin.getDatabase().getUser(uuid).join(); - if (optionalUser.isPresent()) { - return plugin.getDatabase().getCurrentUserData(optionalUser.get()).join(); - } - return Optional.empty(); - }); - } - - @BooleanProvider( - text = "Has Synced", - description = "Whether this user has saved, synchronised data.", - iconName = "exchange-alt", - iconFamily = Family.SOLID, - conditionName = "hasSynced", - hidden = true - ) - @Tab("Current Status") - public boolean getUserHasSynced(@NotNull UUID uuid) { - return getCurrentUserData(uuid).join().isPresent(); - } - - @Conditional("hasSynced") - @NumberProvider( - text = "Sync Time", - description = "The last time the user had their data synced with the server.", - iconName = "clock", - iconFamily = Family.SOLID, - format = FormatType.DATE_SECOND, - priority = 6 - ) - @Tab("Current Status") - public long getCurrentDataTimestamp(@NotNull UUID uuid) { - return getCurrentUserData(uuid).join().map( - versionedUserData -> versionedUserData.versionTimestamp().getTime()) - .orElse(new Date().getTime()); - } - - @Conditional("hasSynced") - @StringProvider( - text = "Version ID", - description = "ID of the data version that the user is currently using.", - iconName = "bolt", - iconFamily = Family.SOLID, - priority = 5 - ) - @Tab("Current Status") - public String getCurrentDataId(@NotNull UUID uuid) { - return getCurrentUserData(uuid).join() - .map(versionedUserData -> versionedUserData.versionUUID().toString() - .split(Pattern.quote("-"))[0]) - .orElse(UNKNOWN_STRING); - } - - @Conditional("hasSynced") - @StringProvider( - text = "Health", - description = "The number of health points out of the max health points this player currently has.", - iconName = "heart", - iconFamily = Family.SOLID, - priority = 4 - ) - @Tab("Current Status") - public String getHealth(@NotNull UUID uuid) { - return getCurrentUserData(uuid).join() - .flatMap(versionedUserData -> versionedUserData.userData().getStatus()) - .map(statusData -> (int) statusData.health + "/" + (int) statusData.maxHealth) - .orElse(UNKNOWN_STRING); - } - - @Conditional("hasSynced") - @NumberProvider( - text = "Hunger", - description = "The number of hunger points this player currently has.", - iconName = "drumstick-bite", - iconFamily = Family.SOLID, - priority = 3 - ) - @Tab("Current Status") - public long getHunger(@NotNull UUID uuid) { - return getCurrentUserData(uuid).join() - .flatMap(versionedUserData -> versionedUserData.userData().getStatus()) - .map(statusData -> (long) statusData.hunger) - .orElse(0L); - } - - @Conditional("hasSynced") - @NumberProvider( - text = "Experience Level", - description = "The number of experience levels this player currently has.", - iconName = "hat-wizard", - iconFamily = Family.SOLID, - priority = 2 - ) - @Tab("Current Status") - public long getExperienceLevel(@NotNull UUID uuid) { - return getCurrentUserData(uuid).join() - .flatMap(versionedUserData -> versionedUserData.userData().getStatus()) - .map(statusData -> (long) statusData.expLevel) - .orElse(0L); - } - - @Conditional("hasSynced") - @StringProvider( - text = "Game Mode", - description = "The game mode this player is currently in.", - iconName = "gamepad", - iconFamily = Family.SOLID, - priority = 1 - ) - @Tab("Current Status") - public String getGameMode(@NotNull UUID uuid) { - return getCurrentUserData(uuid).join() - .flatMap(versionedUserData -> versionedUserData.userData().getStatus()) - .map(status -> status.gameMode) - .orElse(UNKNOWN_STRING); - } - - @Conditional("hasSynced") - @NumberProvider( - text = "Advancements", - description = "The number of advancements & recipes the player has progressed in.", - iconName = "award", - iconFamily = Family.SOLID - ) - @Tab("Current Status") - public long getAdvancementsCompleted(@NotNull UUID playerUUID) { - return getCurrentUserData(playerUUID).join() - .flatMap(versionedUserData -> versionedUserData.userData().getAdvancements()) - .map(advancementsData -> (long) advancementsData.size()) - .orElse(0L); - } - - @Conditional("hasSynced") - @TableProvider(tableColor = Color.LIGHT_BLUE) - @Tab("Data Snapshots") - public Table getDataSnapshots(@NotNull UUID playerUUID) { - final Table.Factory dataSnapshotsTable = Table.builder() - .columnOne("Time", new Icon(Family.SOLID, "clock", Color.NONE)) - .columnOneFormat(TableColumnFormat.DATE_SECOND) - .columnTwo("ID", new Icon(Family.SOLID, "bolt", Color.NONE)) - .columnThree("Cause", new Icon(Family.SOLID, "flag", Color.NONE)) - .columnFour("Pinned", new Icon(Family.SOLID, "thumbtack", Color.NONE)); - plugin.getDatabase().getUser(playerUUID).join().ifPresent(user -> - plugin.getDatabase().getUserData(user).join().forEach(versionedUserData -> dataSnapshotsTable.addRow( - versionedUserData.versionTimestamp().getTime(), - versionedUserData.versionUUID().toString().split("-")[0], - versionedUserData.cause().name().toLowerCase(Locale.ENGLISH).replaceAll("_", " "), - versionedUserData.pinned() ? PINNED_HTML_STRING + "Pinned" : "Unpinned" - ))); - return dataSnapshotsTable.build(); - } -} diff --git a/common/src/main/java/net/william278/husksync/hook/PlanHook.java b/common/src/main/java/net/william278/husksync/hook/PlanHook.java index b0786f59..6b2581c5 100644 --- a/common/src/main/java/net/william278/husksync/hook/PlanHook.java +++ b/common/src/main/java/net/william278/husksync/hook/PlanHook.java @@ -20,10 +20,22 @@ package net.william278.husksync.hook; import com.djrapitops.plan.capability.CapabilityService; -import com.djrapitops.plan.extension.ExtensionService; +import com.djrapitops.plan.extension.*; +import com.djrapitops.plan.extension.annotation.*; +import com.djrapitops.plan.extension.icon.Color; +import com.djrapitops.plan.extension.icon.Family; +import com.djrapitops.plan.extension.icon.Icon; +import com.djrapitops.plan.extension.table.Table; +import com.djrapitops.plan.extension.table.TableColumnFormat; import net.william278.husksync.HuskSync; +import net.william278.husksync.data.Data; +import net.william278.husksync.data.DataHolder; +import net.william278.husksync.data.DataSnapshot; import org.jetbrains.annotations.NotNull; +import java.time.OffsetDateTime; +import java.util.Optional; +import java.util.UUID; import java.util.logging.Level; public class PlanHook { @@ -50,6 +62,7 @@ public class PlanHook { private void registerDataExtension() { try { ExtensionService.getInstance().register(new PlanDataExtension(plugin)); + plugin.log(Level.INFO, "Registered HuskSync Plan data extension"); } catch (IllegalStateException | IllegalArgumentException e) { plugin.log(Level.WARNING, "Failed to register Plan data extension: " + e.getMessage(), e); } @@ -64,4 +77,199 @@ public class PlanHook { }); } + @TabInfo( + tab = "Current Status", + iconName = "id-card", + iconFamily = Family.SOLID, + elementOrder = {ElementOrder.VALUES, ElementOrder.TABLE, ElementOrder.GRAPH} + ) + @TabInfo( + tab = "Data Snapshots", + iconName = "clipboard-list", + iconFamily = Family.SOLID, + elementOrder = {ElementOrder.VALUES, ElementOrder.TABLE, ElementOrder.GRAPH} + ) + @TabOrder({"Current Status", "Data Snapshots"}) + @PluginInfo( + name = "HuskSync", + iconName = "exchange-alt", + iconFamily = Family.SOLID, + color = Color.LIGHT_BLUE + ) + @SuppressWarnings("unused") + public static class PlanDataExtension implements DataExtension { + + private HuskSync plugin; + + private static final String UNKNOWN_STRING = "N/A"; + + private static final String PINNED_HTML_STRING = "📍 "; + + protected PlanDataExtension(@NotNull HuskSync plugin) { + this.plugin = plugin; + } + + protected PlanDataExtension() { + } + + @Override + public CallEvents[] callExtensionMethodsOn() { + return new CallEvents[]{ + CallEvents.PLAYER_JOIN, + CallEvents.PLAYER_LEAVE + }; + } + + // Get the user's latest data snapshot + private Optional getLatestSnapshot(@NotNull UUID uuid) { + return plugin.getDatabase().getUser(uuid) + .flatMap(user -> plugin.getDatabase().getLatestSnapshot(user)) + .map(snapshot -> snapshot.unpack(plugin)); + } + + @BooleanProvider( + text = "Has Synced", + description = "Whether this user has saved, synchronized data.", + iconName = "exchange-alt", + iconFamily = Family.SOLID, + conditionName = "hasSynced", + hidden = true + ) + @Tab("Current Status") + public boolean getUserHasSynced(@NotNull UUID uuid) { + return getLatestSnapshot(uuid).isPresent(); + } + + @Conditional("hasSynced") + @NumberProvider( + text = "Sync Time", + description = "The last time the user had their data synced with the server.", + iconName = "clock", + iconFamily = Family.SOLID, + format = FormatType.DATE_SECOND, + priority = 6 + ) + @Tab("Current Status") + public long getCurrentDataTimestamp(@NotNull UUID uuid) { + return getLatestSnapshot(uuid) + .map(DataSnapshot::getTimestamp) + .orElse(OffsetDateTime.now()) + .toEpochSecond(); + } + + @Conditional("hasSynced") + @StringProvider( + text = "Version ID", + description = "ID of the data version that the user is currently using.", + iconName = "bolt", + iconFamily = Family.SOLID, + priority = 5 + ) + @Tab("Current Status") + public String getCurrentDataId(@NotNull UUID uuid) { + return getLatestSnapshot(uuid) + .map(DataSnapshot::getShortId) + .orElse(UNKNOWN_STRING); + } + + @Conditional("hasSynced") + @StringProvider( + text = "Health", + description = "The number of health points out of the max health points this player currently has.", + iconName = "heart", + iconFamily = Family.SOLID, + priority = 4 + ) + @Tab("Current Status") + public String getHealth(@NotNull UUID uuid) { + return getLatestSnapshot(uuid) + .flatMap(DataHolder::getHealth) + .map(health -> String.format("%s / %s", health.getHealth(), health.getMaxHealth())) + .orElse(UNKNOWN_STRING); + } + + @Conditional("hasSynced") + @NumberProvider( + text = "Hunger", + description = "The number of hunger points this player currently has.", + iconName = "drumstick-bite", + iconFamily = Family.SOLID, + priority = 3 + ) + @Tab("Current Status") + public long getHunger(@NotNull UUID uuid) { + return getLatestSnapshot(uuid) + .flatMap(DataHolder::getHunger) + .map(Data.Hunger::getFoodLevel) + .orElse(20); + } + + @Conditional("hasSynced") + @NumberProvider( + text = "Experience Level", + description = "The number of experience levels this player currently has.", + iconName = "hat-wizard", + iconFamily = Family.SOLID, + priority = 2 + ) + @Tab("Current Status") + public long getExperienceLevel(@NotNull UUID uuid) { + return getLatestSnapshot(uuid) + .flatMap(DataHolder::getExperience) + .map(Data.Experience::getExpLevel) + .orElse(0); + } + + @Conditional("hasSynced") + @StringProvider( + text = "Game Mode", + description = "The game mode this player is currently in.", + iconName = "gamepad", + iconFamily = Family.SOLID, + priority = 1 + ) + @Tab("Current Status") + public String getGameMode(@NotNull UUID uuid) { + return getLatestSnapshot(uuid) + .flatMap(DataHolder::getGameMode) + .map(Data.GameMode::getGameMode) + .orElse(UNKNOWN_STRING); + } + + @Conditional("hasSynced") + @NumberProvider( + text = "Advancements", + description = "The number of advancements & recipes the player has progressed in.", + iconName = "award", + iconFamily = Family.SOLID + ) + @Tab("Current Status") + public long getAdvancementsCompleted(@NotNull UUID playerUUID) { + return getLatestSnapshot(playerUUID) + .flatMap(DataHolder::getAdvancements) + .map(Data.Advancements::getCompleted) + .stream().count(); + } + + @Conditional("hasSynced") + @TableProvider(tableColor = Color.LIGHT_BLUE) + @Tab("Data Snapshots") + public Table getDataSnapshots(@NotNull UUID playerUUID) { + final Table.Factory dataSnapshotsTable = Table.builder() + .columnOne("Time", new Icon(Family.SOLID, "clock", Color.NONE)) + .columnOneFormat(TableColumnFormat.DATE_SECOND) + .columnTwo("ID", new Icon(Family.SOLID, "bolt", Color.NONE)) + .columnThree("Cause", new Icon(Family.SOLID, "flag", Color.NONE)) + .columnFour("Pinned", new Icon(Family.SOLID, "thumbtack", Color.NONE)); + plugin.getDatabase().getUser(playerUUID).ifPresent(user -> + plugin.getDatabase().getAllSnapshots(user).forEach(snapshot -> dataSnapshotsTable.addRow( + snapshot.getTimestamp().toEpochSecond(), + snapshot.getShortId(), + snapshot.getSaveCause().getDisplayName(), + snapshot.isPinned() ? PINNED_HTML_STRING + "Pinned" : "Unpinned" + )) + ); + return dataSnapshotsTable.build(); + } + } } diff --git a/common/src/main/java/net/william278/husksync/listener/EventListener.java b/common/src/main/java/net/william278/husksync/listener/EventListener.java index 5dba45eb..695b4378 100644 --- a/common/src/main/java/net/william278/husksync/listener/EventListener.java +++ b/common/src/main/java/net/william278/husksync/listener/EventListener.java @@ -19,22 +19,16 @@ package net.william278.husksync.listener; -import de.themoep.minedown.adventure.MineDown; import net.william278.husksync.HuskSync; -import net.william278.husksync.data.DataSaveCause; -import net.william278.husksync.data.ItemData; -import net.william278.husksync.player.OnlineUser; +import net.william278.husksync.data.Data; +import net.william278.husksync.data.DataSnapshot; +import net.william278.husksync.user.OnlineUser; +import net.william278.husksync.util.Task; import org.jetbrains.annotations.NotNull; -import java.util.HashSet; -import java.util.List; -import java.util.Set; -import java.util.UUID; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicInteger; +import java.util.*; +import java.util.concurrent.atomic.AtomicLong; +import java.util.concurrent.atomic.AtomicReference; import java.util.logging.Level; /** @@ -42,13 +36,11 @@ import java.util.logging.Level; */ public abstract class EventListener { - /** - * The plugin instance - */ + // The plugin instance protected final HuskSync plugin; /** - * Set of UUIDs of "locked players", for which events will be cancelled. + * Set of UUIDs of "locked players", for which events will be canceled. *

* Players are locked while their items are being set (on join) or saved (on quit) */ @@ -66,7 +58,7 @@ public abstract class EventListener { } /** - * Handle a player joining the server (including players switching from another proxied server) + * Handle a player joining the server (including players switching from another server on the network) * * @param user The {@link OnlineUser} to handle */ @@ -74,92 +66,51 @@ public abstract class EventListener { if (user.isNpc()) { return; } + lockedPlayers.add(user.getUuid()); - lockedPlayers.add(user.uuid); - CompletableFuture.runAsync(() -> { - try { - // Hold reading data for the network latency threshold, to ensure the source server has set the redis key - Thread.sleep(Math.max(0, plugin.getSettings().getNetworkLatencyMilliseconds())); - } catch (InterruptedException e) { - plugin.log(Level.SEVERE, "An exception occurred handling a player join", e); - } finally { - plugin.getRedisManager().getUserServerSwitch(user).thenAccept(changingServers -> { - if (!changingServers) { - // Fetch from the database if the user isn't changing servers - setUserFromDatabase(user).thenAccept(succeeded -> handleSynchronisationCompletion(user, succeeded)); - } else { - final int TIME_OUT_MILLISECONDS = 3200; - CompletableFuture.runAsync(() -> { - final AtomicInteger currentMilliseconds = new AtomicInteger(0); - final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(); - - // Set the user as soon as the source server has set the data to redis - executor.scheduleAtFixedRate(() -> { - if (user.isOffline()) { - executor.shutdown(); - return; - } - if (disabling || currentMilliseconds.get() > TIME_OUT_MILLISECONDS) { - executor.shutdown(); - setUserFromDatabase(user).thenAccept( - succeeded -> handleSynchronisationCompletion(user, succeeded)); - return; - } - plugin.getRedisManager().getUserData(user).thenAccept(redisUserData -> - redisUserData.ifPresent(redisData -> { - user.setData(redisData, plugin) - .thenAccept(succeeded -> handleSynchronisationCompletion(user, succeeded)).join(); - executor.shutdown(); - })).join(); - currentMilliseconds.addAndGet(200); - }, 0, 200L, TimeUnit.MILLISECONDS); - }); - } - }); + plugin.runAsyncDelayed(() -> { + // Fetch from the database if the user isn't changing servers + if (!plugin.getRedisManager().getUserServerSwitch(user)) { + this.setUserFromDatabase(user); + return; } - }); + + // Set the user as soon as the source server has set the data to redis + final long MAX_ATTEMPTS = 16L; + final AtomicLong timesRun = new AtomicLong(0L); + final AtomicReference task = new AtomicReference<>(); + final Runnable runnable = () -> { + if (user.isOffline()) { + task.get().cancel(); + return; + } + if (disabling || timesRun.getAndIncrement() > MAX_ATTEMPTS) { + task.get().cancel(); + this.setUserFromDatabase(user); + return; + } + + plugin.getRedisManager().getUserData(user).ifPresent(redisData -> { + task.get().cancel(); + user.applySnapshot(redisData, DataSnapshot.UpdateCause.SYNCHRONIZED); + }); + }; + task.set(plugin.getRepeatingTask(runnable, 10)); + task.get().run(); + + }, Math.max(0, plugin.getSettings().getNetworkLatencyMilliseconds() / 50L)); } /** * Set a user's data from the database * * @param user The user to set the data for - * @return Whether the data was successfully set - */ - private CompletableFuture setUserFromDatabase(@NotNull OnlineUser user) { - return plugin.getDatabase().getCurrentUserData(user).thenApply(databaseUserData -> { - if (databaseUserData.isPresent()) { - return user.setData(databaseUserData.get().userData(), plugin).join(); - } - return true; - }); - } - - /** - * Handle a player's synchronization completion - * - * @param user The {@link OnlineUser} to handle - * @param succeeded Whether the synchronization succeeded */ - private void handleSynchronisationCompletion(@NotNull OnlineUser user, boolean succeeded) { - if (succeeded) { - switch (plugin.getSettings().getNotificationDisplaySlot()) { - case CHAT -> plugin.getLocales().getLocale("synchronisation_complete") - .ifPresent(user::sendMessage); - case ACTION_BAR -> plugin.getLocales().getLocale("synchronisation_complete") - .ifPresent(user::sendActionBar); - case TOAST -> plugin.getLocales().getLocale("synchronisation_complete") - .ifPresent(locale -> user.sendToast(locale, new MineDown(""), - "minecraft:bell", "TASK")); - } - plugin.getDatabase().ensureUser(user).join(); - lockedPlayers.remove(user.uuid); - plugin.getEventCannon().fireSyncCompleteEvent(user); - } else { - plugin.getLocales().getLocale("synchronisation_failed") - .ifPresent(user::sendMessage); - plugin.getDatabase().ensureUser(user).join(); - } + private void setUserFromDatabase(@NotNull OnlineUser user) { + plugin.getDatabase().getLatestSnapshot(user).ifPresentOrElse( + snapshot -> user.applySnapshot(snapshot, DataSnapshot.UpdateCause.SYNCHRONIZED), + () -> user.completeSync(true, DataSnapshot.UpdateCause.NEW_USER, plugin) + ); } /** @@ -168,28 +119,27 @@ public abstract class EventListener { * @param user The {@link OnlineUser} to handle */ protected final void handlePlayerQuit(@NotNull OnlineUser user) { - // Players quitting have their data manually saved by the plugin disable hook + // Players quitting have their data manually saved when the plugin is disabled if (disabling) { return; } + // Don't sync players awaiting synchronization - if (lockedPlayers.contains(user.uuid) || user.isNpc()) { + if (lockedPlayers.contains(user.getUuid()) || user.isNpc()) { return; } - // Handle asynchronous disconnection - lockedPlayers.add(user.uuid); - CompletableFuture.runAsync(() -> plugin.getRedisManager().setUserServerSwitch(user) - .thenRun(() -> user.getUserData(plugin).thenAccept( - optionalUserData -> optionalUserData.ifPresent(userData -> plugin.getRedisManager() - .setUserData(user, userData).thenRun(() -> plugin.getDatabase() - .setUserData(user, userData, DataSaveCause.DISCONNECT))))) - .exceptionally(throwable -> { - plugin.log(Level.SEVERE, - "An exception occurred handling a player disconnection"); - throwable.printStackTrace(); - return null; - }).join()); + // Handle disconnection + try { + lockedPlayers.add(user.getUuid()); + plugin.getRedisManager().setUserServerSwitch(user).thenRun(() -> { + final DataSnapshot.Packed data = user.createSnapshot(DataSnapshot.SaveCause.DISCONNECT); + plugin.getRedisManager().setUserData(user, data); + plugin.getDatabase().addSnapshot(user, data); + }); + } catch (Throwable e) { + plugin.log(Level.SEVERE, "An exception occurred handling a player disconnection", e); + } } /** @@ -202,10 +152,10 @@ public abstract class EventListener { return; } usersInWorld.stream() - .filter(user -> !lockedPlayers.contains(user.uuid) && !user.isNpc()) - .forEach(user -> user.getUserData(plugin) - .thenAccept(data -> data.ifPresent(userData -> plugin.getDatabase() - .setUserData(user, userData, DataSaveCause.WORLD_SAVE)))); + .filter(user -> !lockedPlayers.contains(user.getUuid()) && !user.isNpc()) + .forEach(user -> plugin.getDatabase().addSnapshot( + user, user.createSnapshot(DataSnapshot.SaveCause.WORLD_SAVE) + )); } /** @@ -214,24 +164,22 @@ public abstract class EventListener { * @param user The user who died * @param drops The items that this user would have dropped */ - protected void saveOnPlayerDeath(@NotNull OnlineUser user, @NotNull ItemData drops) { - if (disabling || !plugin.getSettings().doSaveOnDeath() || lockedPlayers.contains(user.uuid) || user.isNpc() - || (!plugin.getSettings().doSaveEmptyDropsOnDeath() && drops.isEmpty())) { + protected void saveOnPlayerDeath(@NotNull OnlineUser user, @NotNull Data.Items drops) { + if (disabling || !plugin.getSettings().doSaveOnDeath() || lockedPlayers.contains(user.getUuid()) || user.isNpc() + || (!plugin.getSettings().doSaveEmptyDropsOnDeath() && drops.isEmpty())) { return; } - user.getUserData(plugin) - .thenAccept(data -> data.ifPresent(userData -> { - userData.getInventory().orElse(ItemData.empty()).serializedItems = drops.serializedItems; - plugin.getDatabase().setUserData(user, userData, DataSaveCause.DEATH); - })); + final DataSnapshot.Packed snapshot = user.createSnapshot(DataSnapshot.SaveCause.DEATH); + snapshot.edit(plugin, (data -> data.getInventory().ifPresent(inventory -> inventory.setContents(drops)))); + plugin.getDatabase().addSnapshot(user, snapshot); } /** - * Determine whether a player event should be cancelled + * Determine whether a player event should be canceled * * @param userUuid The UUID of the user to check - * @return Whether the event should be cancelled + * @return Whether the event should be canceled */ protected final boolean cancelPlayerEvent(@NotNull UUID userUuid) { return disabling || lockedPlayers.contains(userUuid); @@ -245,21 +193,65 @@ public abstract class EventListener { // Save data for all online users plugin.getOnlineUsers().stream() - .filter(user -> !lockedPlayers.contains(user.uuid) && !user.isNpc()) + .filter(user -> !lockedPlayers.contains(user.getUuid()) && !user.isNpc()) .forEach(user -> { - lockedPlayers.add(user.uuid); - user.getUserData(plugin).join() - .ifPresent(userData -> plugin.getDatabase() - .setUserData(user, userData, DataSaveCause.SERVER_SHUTDOWN).join()); + lockedPlayers.add(user.getUuid()); + plugin.getDatabase().addSnapshot(user, user.createSnapshot(DataSnapshot.SaveCause.SERVER_SHUTDOWN)); }); // Close outstanding connections - plugin.getDatabase().close(); - plugin.getRedisManager().close(); + plugin.getDatabase().terminate(); + plugin.getRedisManager().terminate(); } public final Set getLockedPlayers() { return this.lockedPlayers; } + /** + * Represents priorities for events that HuskSync listens to + */ + public enum Priority { + /** + * Listens and processes the event execution last + */ + HIGHEST, + /** + * Listens in between {@link #HIGHEST} and {@link #LOWEST} priority marked + */ + NORMAL, + /** + * Listens and processes the event execution first + */ + LOWEST + } + + /** + * Represents events that HuskSync listens to, with a configurable priority listener + */ + public enum ListenerType { + JOIN_LISTENER(Priority.LOWEST), + QUIT_LISTENER(Priority.LOWEST), + DEATH_LISTENER(Priority.NORMAL); + + private final Priority defaultPriority; + + ListenerType(@NotNull EventListener.Priority defaultPriority) { + this.defaultPriority = defaultPriority; + } + + @NotNull + private Map.Entry toEntry() { + return Map.entry(name().toLowerCase(), defaultPriority.name()); + } + + + @SuppressWarnings("unchecked") + @NotNull + public static Map getDefaults() { + return Map.ofEntries(Arrays.stream(values()) + .map(ListenerType::toEntry) + .toArray(Map.Entry[]::new)); + } + } } diff --git a/common/src/main/java/net/william278/husksync/migrator/Migrator.java b/common/src/main/java/net/william278/husksync/migrator/Migrator.java index 1b12d007..c9389055 100644 --- a/common/src/main/java/net/william278/husksync/migrator/Migrator.java +++ b/common/src/main/java/net/william278/husksync/migrator/Migrator.java @@ -20,13 +20,12 @@ package net.william278.husksync.migrator; import net.william278.husksync.HuskSync; -import net.william278.husksync.data.UserData; import org.jetbrains.annotations.NotNull; import java.util.concurrent.CompletableFuture; /** - * A migrator that migrates data from other data formats to HuskSync's {@link UserData} format + * A migrator that migrates data from other data formats to HuskSync's format */ public abstract class Migrator { diff --git a/common/src/main/java/net/william278/husksync/player/OnlineUser.java b/common/src/main/java/net/william278/husksync/player/OnlineUser.java deleted file mode 100644 index 1da48a20..00000000 --- a/common/src/main/java/net/william278/husksync/player/OnlineUser.java +++ /dev/null @@ -1,423 +0,0 @@ -/* - * This file is part of HuskSync, licensed under the Apache License 2.0. - * - * Copyright (c) William278 - * Copyright (c) contributors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.william278.husksync.player; - -import de.themoep.minedown.adventure.MineDown; -import de.themoep.minedown.adventure.MineDownParser; -import net.kyori.adventure.audience.Audience; -import net.kyori.adventure.text.Component; -import net.william278.desertwell.util.Version; -import net.william278.husksync.HuskSync; -import net.william278.husksync.config.Settings; -import net.william278.husksync.data.*; -import net.william278.husksync.event.PreSyncEvent; -import org.jetbrains.annotations.NotNull; - -import java.util.*; -import java.util.concurrent.CompletableFuture; -import java.util.logging.Level; - -/** - * Represents a logged-in {@link User} - */ -public abstract class OnlineUser extends User { - - public OnlineUser(@NotNull UUID uuid, @NotNull String username) { - super(uuid, username); - } - - /** - * Get the player's {@link StatusData} - * - * @return the player's {@link StatusData} - */ - public abstract CompletableFuture getStatus(); - - /** - * Set the player's {@link StatusData} - * - * @param statusData the player's {@link StatusData} - * @param statusDataFlags the flags to use for setting the status data - * @return a future returning void when complete - * @deprecated Use {@link #setStatus(StatusData, Settings)} instead - */ - @Deprecated(since = "2.1") - public final CompletableFuture setStatus(@NotNull StatusData statusData, - @NotNull List statusDataFlags) { - final Settings settings = new Settings(); - settings.getSynchronizationFeatures().put(Settings.SynchronizationFeature.HEALTH.name().toLowerCase(Locale.ENGLISH), statusDataFlags.contains(StatusDataFlag.SET_HEALTH)); - settings.getSynchronizationFeatures().put(Settings.SynchronizationFeature.MAX_HEALTH.name().toLowerCase(Locale.ENGLISH), statusDataFlags.contains(StatusDataFlag.SET_MAX_HEALTH)); - settings.getSynchronizationFeatures().put(Settings.SynchronizationFeature.HUNGER.name().toLowerCase(Locale.ENGLISH), statusDataFlags.contains(StatusDataFlag.SET_HUNGER)); - settings.getSynchronizationFeatures().put(Settings.SynchronizationFeature.EXPERIENCE.name().toLowerCase(Locale.ENGLISH), statusDataFlags.contains(StatusDataFlag.SET_EXPERIENCE)); - settings.getSynchronizationFeatures().put(Settings.SynchronizationFeature.INVENTORIES.name().toLowerCase(Locale.ENGLISH), statusDataFlags.contains(StatusDataFlag.SET_SELECTED_ITEM_SLOT)); - settings.getSynchronizationFeatures().put(Settings.SynchronizationFeature.LOCATION.name().toLowerCase(Locale.ENGLISH), statusDataFlags.contains(StatusDataFlag.SET_GAME_MODE) || statusDataFlags.contains(StatusDataFlag.SET_FLYING)); - return setStatus(statusData, settings); - } - - /** - * Set the player's {@link StatusData} - * - * @param statusData the player's {@link StatusData} - * @param settings settings, containing information about which features should be synced - * @return a future returning void when complete - */ - public abstract CompletableFuture setStatus(@NotNull StatusData statusData, @NotNull Settings settings); - - /** - * Get the player's inventory {@link ItemData} contents - * - * @return The player's inventory {@link ItemData} contents - */ - public abstract CompletableFuture getInventory(); - - /** - * Set the player's {@link ItemData} - * - * @param itemData The player's {@link ItemData} - * @return a future returning void when complete - */ - public abstract CompletableFuture setInventory(@NotNull ItemData itemData); - - /** - * Get the player's ender chest {@link ItemData} contents - * - * @return The player's ender chest {@link ItemData} contents - */ - public abstract CompletableFuture getEnderChest(); - - /** - * Set the player's {@link ItemData} - * - * @param enderChestData The player's {@link ItemData} - * @return a future returning void when complete - */ - public abstract CompletableFuture setEnderChest(@NotNull ItemData enderChestData); - - - /** - * Get the player's {@link PotionEffectData} - * - * @return The player's {@link PotionEffectData} - */ - public abstract CompletableFuture getPotionEffects(); - - /** - * Set the player's {@link PotionEffectData} - * - * @param potionEffectData The player's {@link PotionEffectData} - * @return a future returning void when complete - */ - public abstract CompletableFuture setPotionEffects(@NotNull PotionEffectData potionEffectData); - - /** - * Get the player's set of {@link AdvancementData} - * - * @return the player's set of {@link AdvancementData} - */ - public abstract CompletableFuture> getAdvancements(); - - /** - * Set the player's {@link AdvancementData} - * - * @param advancementData List of the player's {@link AdvancementData} - * @return a future returning void when complete - */ - public abstract CompletableFuture setAdvancements(@NotNull List advancementData); - - /** - * Get the player's {@link StatisticsData} - * - * @return The player's {@link StatisticsData} - */ - public abstract CompletableFuture getStatistics(); - - /** - * Set the player's {@link StatisticsData} - * - * @param statisticsData The player's {@link StatisticsData} - * @return a future returning void when complete - */ - public abstract CompletableFuture setStatistics(@NotNull StatisticsData statisticsData); - - /** - * Get the player's {@link LocationData} - * - * @return the player's {@link LocationData} - */ - public abstract CompletableFuture getLocation(); - - /** - * Set the player's {@link LocationData} - * - * @param locationData the player's {@link LocationData} - * @return a future returning void when complete - */ - public abstract CompletableFuture setLocation(@NotNull LocationData locationData); - - /** - * Get the player's {@link PersistentDataContainerData} - * - * @return The player's {@link PersistentDataContainerData} when fetched - */ - public abstract CompletableFuture getPersistentDataContainer(); - - /** - * Set the player's {@link PersistentDataContainerData} - * - * @param persistentDataContainerData The player's {@link PersistentDataContainerData} to set - * @return A future returning void when complete - */ - public abstract CompletableFuture setPersistentDataContainer(@NotNull PersistentDataContainerData persistentDataContainerData); - - /** - * Indicates if the player has gone offline - * - * @return {@code true} if the player has left the server; {@code false} otherwise - */ - public abstract boolean isOffline(); - - /** - * Returns the implementing Minecraft server version - * - * @return The Minecraft server version - */ - @NotNull - public abstract Version getMinecraftVersion(); - - /** - * Get the player's adventure {@link Audience} - * - * @return the player's {@link Audience} - */ - @NotNull - public abstract Audience getAudience(); - - /** - * Send a message to this player - * - * @param component the {@link Component} message to send - */ - public void sendMessage(@NotNull Component component) { - getAudience().sendMessage(component); - } - - /** - * Dispatch a MineDown-formatted message to this player - * - * @param mineDown the parsed {@link MineDown} to send - */ - public void sendMessage(@NotNull MineDown mineDown) { - sendMessage(mineDown - .disable(MineDownParser.Option.SIMPLE_FORMATTING) - .replace().toComponent()); - } - - /** - * Dispatch a MineDown-formatted action bar message to this player - * - * @param mineDown the parsed {@link MineDown} to send - */ - public void sendActionBar(@NotNull MineDown mineDown) { - getAudience().sendActionBar(mineDown - .disable(MineDownParser.Option.SIMPLE_FORMATTING) - .replace().toComponent()); - } - - /** - * Dispatch a toast message to this player - * - * @param title the title of the toast - * @param description the description of the toast - * @param iconMaterial the namespace-keyed material to use as an icon of the toast - * @param backgroundType the background ("ToastType") of the toast - */ - public abstract void sendToast(@NotNull MineDown title, @NotNull MineDown description, - @NotNull String iconMaterial, @NotNull String backgroundType); - - /** - * Returns if the player has the permission node - * - * @param node The permission node string - * @return {@code true} if the player has permission node; {@code false} otherwise - */ - public abstract boolean hasPermission(@NotNull String node); - - /** - * Show a GUI chest menu to the player, containing the given {@link ItemData} - * - * @param itemData Item data to be shown in the GUI - * @param editable If the player should be able to remove, replace and move around the items - * @param minimumRows The minimum number of rows to show in the chest menu - * @param title The title of the chest menu, as a {@link MineDown} locale - * @return A future returning the {@link ItemData} in the chest menu when the player closes it - * @since 2.1 - */ - public abstract CompletableFuture> showMenu(@NotNull ItemData itemData, boolean editable, - int minimumRows, @NotNull MineDown title); - - /** - * Returns true if the player is dead - * - * @return true if the player is dead - */ - public abstract boolean isDead(); - - /** - * Apply {@link UserData} to a player, updating their inventory, status, statistics, etc. as per the config. - *

- * This will only set data that is enabled as per the enabled settings in the config file. - * Data present in the {@link UserData} object, but not enabled to be set in the config, will be ignored. - * - * @param plugin The plugin instance - * @return a future returning a boolean when complete; if the sync was successful, the future will return {@code true}. - */ - public final CompletableFuture setData(@NotNull UserData data, @NotNull HuskSync plugin) { - return CompletableFuture.supplyAsync(() -> { - // Prevent synchronising user data from newer versions of Minecraft - if (Version.fromString(data.getMinecraftVersion()).compareTo(plugin.getMinecraftVersion()) > 0) { - plugin.log(Level.SEVERE, "Cannot set data for " + username + - " because the Minecraft version of their user data (" + data.getMinecraftVersion() + - ") is newer than the server's Minecraft version (" + plugin.getMinecraftVersion() + ")."); - return false; - } - // Prevent synchronising user data from newer versions of the plugin - if (data.getFormatVersion() > UserData.CURRENT_FORMAT_VERSION) { - plugin.log(Level.SEVERE, "Cannot set data for " + username + - " because the format version of their user data (v" + data.getFormatVersion() + - ") is newer than the current format version (v" + UserData.CURRENT_FORMAT_VERSION + ")."); - return false; - } - - // Fire the PreSyncEvent - final PreSyncEvent preSyncEvent = (PreSyncEvent) plugin.getEventCannon().firePreSyncEvent(this, data).join(); - final UserData finalData = preSyncEvent.getUserData(); - final List> dataSetOperations = new ArrayList<>() {{ - if (!isOffline() && !preSyncEvent.isCancelled()) { - final Settings settings = plugin.getSettings(); - if (settings.getSynchronizationFeature(Settings.SynchronizationFeature.INVENTORIES)) { - finalData.getInventory().ifPresent(itemData -> add(setInventory(itemData))); - } - if (settings.getSynchronizationFeature(Settings.SynchronizationFeature.ENDER_CHESTS)) { - finalData.getEnderChest().ifPresent(itemData -> add(setEnderChest(itemData))); - } - finalData.getStatus().ifPresent(statusData -> add(setStatus(statusData, settings))); - if (settings.getSynchronizationFeature(Settings.SynchronizationFeature.POTION_EFFECTS)) { - finalData.getPotionEffects().ifPresent(potionEffectData -> add(setPotionEffects(potionEffectData))); - } - if (settings.getSynchronizationFeature(Settings.SynchronizationFeature.ADVANCEMENTS)) { - finalData.getAdvancements().ifPresent(advancementData -> add(setAdvancements(advancementData))); - } - if (settings.getSynchronizationFeature(Settings.SynchronizationFeature.STATISTICS)) { - finalData.getStatistics().ifPresent(statisticData -> add(setStatistics(statisticData))); - } - if (settings.getSynchronizationFeature(Settings.SynchronizationFeature.LOCATION)) { - finalData.getLocation().ifPresent(locationData -> add(setLocation(locationData))); - } - if (settings.getSynchronizationFeature(Settings.SynchronizationFeature.PERSISTENT_DATA_CONTAINER)) { - finalData.getPersistentDataContainer().ifPresent(persistentDataContainerData -> - add(setPersistentDataContainer(persistentDataContainerData))); - } - } - }}; - // Apply operations in parallel, join when complete - return CompletableFuture.allOf(dataSetOperations.toArray(new CompletableFuture[0])).thenApply(unused -> true) - .exceptionally(exception -> { - // Handle synchronisation exceptions - plugin.log(Level.SEVERE, "Failed to set data for player " + username + " (" + exception.getMessage() + ")"); - exception.printStackTrace(); - return false; - }).join(); - }); - - } - - /** - * Get the player's current {@link UserData} in an {@link Optional}. - *

- * Since v2.1, this method will respect the data synchronisation settings; user data will only be as big as the - * enabled synchronisation values set in the config file - *

- * Also note that if the {@code SYNCHRONIZATION_SAVE_DEAD_PLAYER_INVENTORIES} ConfigOption has been set, - * the user's inventory will only be returned if the player is alive. - *

- * If the user data could not be returned due to an exception, the optional will return empty - * - * @param plugin The plugin instance - */ - public final CompletableFuture> getUserData(@NotNull HuskSync plugin) { - return CompletableFuture.supplyAsync(() -> { - final UserDataBuilder builder = UserData.builder(getMinecraftVersion()); - final List> dataGetOperations = new ArrayList<>() {{ - if (!isOffline()) { - final Settings settings = plugin.getSettings(); - if (settings.getSynchronizationFeature(Settings.SynchronizationFeature.INVENTORIES)) { - if (isDead() && settings.isSynchroniseDeadPlayersChangingServer()) { - plugin.debug("Player " + username + " is dead, so their inventory will be set to empty."); - add(CompletableFuture.runAsync(() -> builder.setInventory(ItemData.empty()))); - } else { - add(getInventory().thenAccept(builder::setInventory)); - } - } - if (settings.getSynchronizationFeature(Settings.SynchronizationFeature.ENDER_CHESTS)) { - add(getEnderChest().thenAccept(builder::setEnderChest)); - } - add(getStatus().thenAccept(builder::setStatus)); - if (settings.getSynchronizationFeature(Settings.SynchronizationFeature.POTION_EFFECTS)) { - add(getPotionEffects().thenAccept(builder::setPotionEffects)); - } - if (settings.getSynchronizationFeature(Settings.SynchronizationFeature.ADVANCEMENTS)) { - add(getAdvancements().thenAccept(builder::setAdvancements)); - } - if (settings.getSynchronizationFeature(Settings.SynchronizationFeature.STATISTICS)) { - add(getStatistics().thenAccept(builder::setStatistics)); - } - if (settings.getSynchronizationFeature(Settings.SynchronizationFeature.LOCATION)) { - add(getLocation().thenAccept(builder::setLocation)); - } - if (settings.getSynchronizationFeature(Settings.SynchronizationFeature.PERSISTENT_DATA_CONTAINER)) { - add(getPersistentDataContainer().thenAccept(builder::setPersistentDataContainer)); - } - } - }}; - - // Apply operations in parallel, join when complete - CompletableFuture.allOf(dataGetOperations.toArray(new CompletableFuture[0])).join(); - return Optional.of(builder.build()); - }).exceptionally(exception -> { - plugin.log(Level.SEVERE, "Failed to get user data from online player " + username + " (" + exception.getMessage() + ")"); - exception.printStackTrace(); - return Optional.empty(); - }); - } - - /** - * Get if the player is locked - * - * @return the player's locked status - */ - public abstract boolean isLocked(); - - /** - * Get if the player is a NPC - * - * @return if the player is a NPC with metadata - */ - public abstract boolean isNpc(); -} diff --git a/common/src/main/java/net/william278/husksync/redis/RedisKeyType.java b/common/src/main/java/net/william278/husksync/redis/RedisKeyType.java index fc069cad..7ba8f9fb 100644 --- a/common/src/main/java/net/william278/husksync/redis/RedisKeyType.java +++ b/common/src/main/java/net/william278/husksync/redis/RedisKeyType.java @@ -28,14 +28,24 @@ public enum RedisKeyType { DATA_UPDATE(10), SERVER_SWITCH(10); - public final int timeToLive; + private final int timeToLive; RedisKeyType(int timeToLive) { this.timeToLive = timeToLive; } @NotNull - public String getKeyPrefix() { - return RedisManager.KEY_NAMESPACE.toLowerCase(Locale.ENGLISH) + ":" + RedisManager.clusterId.toLowerCase(Locale.ENGLISH) + ":" + name().toLowerCase(Locale.ENGLISH); + public String getKeyPrefix(@NotNull String clusterId) { + return String.format( + "%s:%s:%s", + RedisManager.KEY_NAMESPACE.toLowerCase(Locale.ENGLISH), + clusterId.toLowerCase(Locale.ENGLISH), + name().toLowerCase(Locale.ENGLISH) + ); } + + public int getTimeToLive() { + return timeToLive; + } + } diff --git a/common/src/main/java/net/william278/husksync/redis/RedisManager.java b/common/src/main/java/net/william278/husksync/redis/RedisManager.java index 990b554c..fe298a19 100644 --- a/common/src/main/java/net/william278/husksync/redis/RedisManager.java +++ b/common/src/main/java/net/william278/husksync/redis/RedisManager.java @@ -19,21 +19,24 @@ package net.william278.husksync.redis; -import de.themoep.minedown.adventure.MineDown; import net.william278.husksync.HuskSync; -import net.william278.husksync.data.UserData; -import net.william278.husksync.player.User; +import net.william278.husksync.data.DataSnapshot; +import net.william278.husksync.user.User; +import org.jetbrains.annotations.Blocking; import org.jetbrains.annotations.NotNull; -import redis.clients.jedis.*; +import redis.clients.jedis.Jedis; +import redis.clients.jedis.JedisPool; +import redis.clients.jedis.JedisPoolConfig; +import redis.clients.jedis.JedisPubSub; import redis.clients.jedis.exceptions.JedisException; import java.nio.charset.StandardCharsets; import java.text.SimpleDateFormat; -import java.util.Arrays; -import java.util.Date; -import java.util.Optional; -import java.util.UUID; +import java.util.*; import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.TimeUnit; +import java.util.logging.Level; /** * Manages the connection to the Redis server, handling the caching of user data @@ -41,146 +44,180 @@ import java.util.concurrent.CompletableFuture; public class RedisManager extends JedisPubSub { protected static final String KEY_NAMESPACE = "husksync:"; - protected static String clusterId = ""; + private final HuskSync plugin; - private final JedisPoolConfig jedisPoolConfig; - private final String redisHost; - private final int redisPort; - private final String redisPassword; - private final boolean redisUseSsl; + private final String clusterId; private JedisPool jedisPool; + private final Map>> pendingRequests; public RedisManager(@NotNull HuskSync plugin) { this.plugin = plugin; - clusterId = plugin.getSettings().getClusterId(); - - // Set redis credentials - this.redisHost = plugin.getSettings().getRedisHost(); - this.redisPort = plugin.getSettings().getRedisPort(); - this.redisPassword = plugin.getSettings().getRedisPassword(); - this.redisUseSsl = plugin.getSettings().isRedisUseSsl(); - - // Configure the jedis pool - this.jedisPoolConfig = new JedisPoolConfig(); - this.jedisPoolConfig.setMaxIdle(0); - this.jedisPoolConfig.setTestOnBorrow(true); - this.jedisPoolConfig.setTestOnReturn(true); + this.clusterId = plugin.getSettings().getClusterId(); + this.pendingRequests = new ConcurrentHashMap<>(); } /** * Initialize the redis connection pool - * - * @return a future returning void when complete */ - public boolean initialize() { - if (redisPassword.isBlank()) { - jedisPool = new JedisPool(jedisPoolConfig, redisHost, redisPort, 0, redisUseSsl); - } else { - jedisPool = new JedisPool(jedisPoolConfig, redisHost, redisPort, 0, redisPassword, redisUseSsl); - } + @Blocking + public void initialize() throws IllegalStateException { + final String password = plugin.getSettings().getRedisPassword(); + final String host = plugin.getSettings().getRedisHost(); + final int port = plugin.getSettings().getRedisPort(); + final boolean useSSL = plugin.getSettings().redisUseSsl(); + + // Create the jedis pool + final JedisPoolConfig config = new JedisPoolConfig(); + config.setMaxIdle(0); + config.setTestOnBorrow(true); + config.setTestOnReturn(true); + this.jedisPool = password.isEmpty() + ? new JedisPool(config, host, port, 0, useSSL) + : new JedisPool(config, host, port, 0, password, useSSL); + + // Ping the server to check the connection try { jedisPool.getResource().ping(); } catch (JedisException e) { - return false; + throw new IllegalStateException("Failed to establish connection with the Redis server. " + + "Please check the supplied credentials in the config file", e); } - CompletableFuture.runAsync(this::subscribe); - return true; + + // Subscribe using a thread (rather than a task) + new Thread(this::subscribe, "husksync:redis_subscriber").start(); } + @Blocking private void subscribe() { - try (final Jedis subscriber = redisPassword.isBlank() ? new Jedis(redisHost, redisPort, 0, redisUseSsl) : - new Jedis(redisHost, redisPort, DefaultJedisClientConfig.builder() - .password(redisPassword).timeoutMillis(0).ssl(redisUseSsl).build())) { - subscriber.connect(); - subscriber.subscribe(this, Arrays.stream(RedisMessageType.values()) - .map(RedisMessageType::getMessageChannel) - .toArray(String[]::new)); + try (Jedis jedis = jedisPool.getResource()) { + jedis.subscribe( + this, + Arrays.stream(RedisMessageType.values()) + .map(type -> type.getMessageChannel(clusterId)) + .toArray(String[]::new) + ); } } @Override public void onMessage(@NotNull String channel, @NotNull String message) { - final RedisMessageType messageType = RedisMessageType.getTypeFromChannel(channel).orElse(null); - if (messageType != RedisMessageType.UPDATE_USER_DATA) { + final RedisMessageType messageType = RedisMessageType.getTypeFromChannel(channel, clusterId).orElse(null); + if (messageType == null) { return; } - final RedisMessage redisMessage = RedisMessage.fromJson(message); - plugin.getOnlineUser(redisMessage.targetUserUuid).ifPresent(user -> { - final UserData userData = plugin.getDataAdapter().fromBytes(redisMessage.data); - user.setData(userData, plugin).thenAccept(succeeded -> { - if (succeeded) { - switch (plugin.getSettings().getNotificationDisplaySlot()) { - case CHAT -> plugin.getLocales().getLocale("data_update_complete") - .ifPresent(user::sendMessage); - case ACTION_BAR -> plugin.getLocales().getLocale("data_update_complete") - .ifPresent(user::sendActionBar); - case TOAST -> plugin.getLocales().getLocale("data_update_complete") - .ifPresent(locale -> user.sendToast(locale, new MineDown(""), - "minecraft:bell", "TASK")); - } - plugin.getEventCannon().fireSyncCompleteEvent(user); - } else { - plugin.getLocales().getLocale("data_update_failed") - .ifPresent(user::sendMessage); + final RedisMessage redisMessage = RedisMessage.fromJson(plugin, message); + switch (messageType) { + case UPDATE_USER_DATA -> plugin.getOnlineUser(redisMessage.getTargetUuid()).ifPresent( + user -> user.applySnapshot( + DataSnapshot.deserialize(plugin, redisMessage.getPayload()), + DataSnapshot.UpdateCause.UPDATED + ) + ); + case REQUEST_USER_DATA -> plugin.getOnlineUser(redisMessage.getTargetUuid()).ifPresent( + user -> RedisMessage.create( + UUID.fromString(new String(redisMessage.getPayload(), StandardCharsets.UTF_8)), + user.createSnapshot(DataSnapshot.SaveCause.INVENTORY_COMMAND).asBytes(plugin) + ).dispatch(plugin, RedisMessageType.RETURN_USER_DATA) + ); + case RETURN_USER_DATA -> { + final CompletableFuture> future = pendingRequests.get( + redisMessage.getTargetUuid() + ); + if (future != null) { + future.complete(Optional.of(DataSnapshot.deserialize(plugin, redisMessage.getPayload()))); + pendingRequests.remove(redisMessage.getTargetUuid()); } - }); - }); + } + } } + @Blocking protected void sendMessage(@NotNull String channel, @NotNull String message) { try (Jedis jedis = jedisPool.getResource()) { jedis.publish(channel, message); } } - public CompletableFuture sendUserDataUpdate(@NotNull User user, @NotNull UserData userData) { - return CompletableFuture.runAsync(() -> { - final RedisMessage redisMessage = new RedisMessage(user.uuid, plugin.getDataAdapter().toBytes(userData)); - redisMessage.dispatch(this, RedisMessageType.UPDATE_USER_DATA); + public void sendUserDataUpdate(@NotNull User user, @NotNull DataSnapshot.Packed data) { + plugin.runAsync(() -> { + final RedisMessage redisMessage = RedisMessage.create(user.getUuid(), data.asBytes(plugin)); + redisMessage.dispatch(plugin, RedisMessageType.UPDATE_USER_DATA); + }); + } + + public CompletableFuture> getUserData(@NotNull UUID requestId, @NotNull User user) { + return plugin.getOnlineUser(user.getUuid()) + .map(online -> CompletableFuture.completedFuture( + Optional.of(online.createSnapshot(DataSnapshot.SaveCause.API))) + ) + .orElse(this.requestData(requestId, user)); + } + + private CompletableFuture> requestData(@NotNull UUID requestId, @NotNull User user) { + final CompletableFuture> future = new CompletableFuture<>(); + pendingRequests.put(requestId, future); + plugin.runAsync(() -> { + final RedisMessage redisMessage = RedisMessage.create( + user.getUuid(), + requestId.toString().getBytes(StandardCharsets.UTF_8) + ); + redisMessage.dispatch(plugin, RedisMessageType.REQUEST_USER_DATA); }); + return future.orTimeout( + plugin.getSettings().getNetworkLatencyMilliseconds(), + TimeUnit.MILLISECONDS + ) + .exceptionally(throwable -> { + pendingRequests.remove(requestId); + return Optional.empty(); + }); } /** * Set a user's data to the Redis server * - * @param user the user to set data for - * @param userData the user's data to set - * @return a future returning void when complete + * @param user the user to set data for + * @param data the user's data to set */ - public CompletableFuture setUserData(@NotNull User user, @NotNull UserData userData) { - try { - return CompletableFuture.runAsync(() -> { - try (Jedis jedis = jedisPool.getResource()) { - // Set the user's data as a compressed byte array of the json using Snappy - jedis.setex(getKey(RedisKeyType.DATA_UPDATE, user.uuid), - RedisKeyType.DATA_UPDATE.timeToLive, - plugin.getDataAdapter().toBytes(userData)); - - // Debug logging - plugin.debug("[" + user.username + "] Set " + RedisKeyType.DATA_UPDATE.name() - + " key to redis at: " + - new SimpleDateFormat("mm:ss.SSS").format(new Date())); - } - }); - } catch (Exception e) { - e.printStackTrace(); - } - return null; + public void setUserData(@NotNull User user, @NotNull DataSnapshot.Packed data) { + plugin.runAsync(() -> { + try (Jedis jedis = jedisPool.getResource()) { + jedis.setex( + getKey(RedisKeyType.DATA_UPDATE, user.getUuid(), clusterId), + RedisKeyType.DATA_UPDATE.getTimeToLive(), + data.asBytes(plugin) + ); + plugin.debug(String.format("[%s] Set %s key to redis at: %s", user.getUsername(), + RedisKeyType.DATA_UPDATE.name(), new SimpleDateFormat("mm:ss.SSS").format(new Date()))); + } catch (Throwable e) { + plugin.log(Level.SEVERE, "An exception occurred setting a user's server switch", e); + } + }); } + /** + * Set a user's server switch to the Redis server + * + * @param user the user to set the server switch for + * @return a future returning void when complete + */ public CompletableFuture setUserServerSwitch(@NotNull User user) { - return CompletableFuture.runAsync(() -> { + final CompletableFuture future = new CompletableFuture<>(); + plugin.runAsync(() -> { try (Jedis jedis = jedisPool.getResource()) { - jedis.setex(getKey(RedisKeyType.SERVER_SWITCH, user.uuid), - RedisKeyType.SERVER_SWITCH.timeToLive, new byte[0]); - plugin.debug("[" + user.username + "] Set " + RedisKeyType.SERVER_SWITCH.name() - + " key to redis at: " + - new SimpleDateFormat("mm:ss.SSS").format(new Date())); - } catch (Exception e) { - e.printStackTrace(); + jedis.setex( + getKey(RedisKeyType.SERVER_SWITCH, user.getUuid(), clusterId), + RedisKeyType.SERVER_SWITCH.getTimeToLive(), new byte[0] + ); + future.complete(null); + plugin.debug(String.format("[%s] Set %s key to redis at: %s", user.getUsername(), + RedisKeyType.SERVER_SWITCH.name(), new SimpleDateFormat("mm:ss.SSS").format(new Date()))); + } catch (Throwable e) { + plugin.log(Level.SEVERE, "An exception occurred setting a user's server switch", e); } }); + return future; } /** @@ -189,68 +226,65 @@ public class RedisManager extends JedisPubSub { * @param user The user to fetch data for * @return The user's data, if it's present on the database. Otherwise, an empty optional. */ - public CompletableFuture> getUserData(@NotNull User user) { - return CompletableFuture.supplyAsync(() -> { - try (Jedis jedis = jedisPool.getResource()) { - final byte[] key = getKey(RedisKeyType.DATA_UPDATE, user.uuid); - final byte[] dataByteArray = jedis.get(key); - if (dataByteArray == null) { - plugin.debug("[" + user.username + "] Could not read " + - RedisKeyType.DATA_UPDATE.name() + " key from redis at: " + - new SimpleDateFormat("mm:ss.SSS").format(new Date())); - return Optional.empty(); - } - plugin.debug("[" + user.username + "] Successfully read " - + RedisKeyType.DATA_UPDATE.name() + " key from redis at: " + - new SimpleDateFormat("mm:ss.SSS").format(new Date())); - - // Consume the key (delete from redis) - jedis.del(key); - - // Use Snappy to decompress the json - return Optional.of(plugin.getDataAdapter().fromBytes(dataByteArray)); - } catch (Exception e) { - e.printStackTrace(); + public Optional getUserData(@NotNull User user) { + try (Jedis jedis = jedisPool.getResource()) { + final byte[] key = getKey(RedisKeyType.DATA_UPDATE, user.getUuid(), clusterId); + final byte[] dataByteArray = jedis.get(key); + if (dataByteArray == null) { + plugin.debug("[" + user.getUsername() + "] Could not read " + + RedisKeyType.DATA_UPDATE.name() + " key from redis at: " + + new SimpleDateFormat("mm:ss.SSS").format(new Date())); return Optional.empty(); } - }); - } + plugin.debug("[" + user.getUsername() + "] Successfully read " + + RedisKeyType.DATA_UPDATE.name() + " key from redis at: " + + new SimpleDateFormat("mm:ss.SSS").format(new Date())); - public CompletableFuture getUserServerSwitch(@NotNull User user) { - return CompletableFuture.supplyAsync(() -> { - try (Jedis jedis = jedisPool.getResource()) { - final byte[] key = getKey(RedisKeyType.SERVER_SWITCH, user.uuid); - final byte[] readData = jedis.get(key); - if (readData == null) { - plugin.debug("[" + user.username + "] Could not read " + - RedisKeyType.SERVER_SWITCH.name() + " key from redis at: " + - new SimpleDateFormat("mm:ss.SSS").format(new Date())); - return false; - } - plugin.debug("[" + user.username + "] Successfully read " - + RedisKeyType.SERVER_SWITCH.name() + " key from redis at: " + - new SimpleDateFormat("mm:ss.SSS").format(new Date())); + // Consume the key (delete from redis) + jedis.del(key); + + // Use Snappy to decompress the json + return Optional.of(DataSnapshot.deserialize(plugin, dataByteArray)); + } catch (Throwable e) { + plugin.log(Level.SEVERE, "An exception occurred fetching a user's data from redis", e); + return Optional.empty(); + } + } - // Consume the key (delete from redis) - jedis.del(key); - return true; - } catch (Exception e) { - e.printStackTrace(); + public boolean getUserServerSwitch(@NotNull User user) { + try (Jedis jedis = jedisPool.getResource()) { + final byte[] key = getKey(RedisKeyType.SERVER_SWITCH, user.getUuid(), clusterId); + final byte[] readData = jedis.get(key); + if (readData == null) { + plugin.debug("[" + user.getUsername() + "] Could not read " + + RedisKeyType.SERVER_SWITCH.name() + " key from redis at: " + + new SimpleDateFormat("mm:ss.SSS").format(new Date())); return false; } - }); + plugin.debug("[" + user.getUsername() + "] Successfully read " + + RedisKeyType.SERVER_SWITCH.name() + " key from redis at: " + + new SimpleDateFormat("mm:ss.SSS").format(new Date())); + + // Consume the key (delete from redis) + jedis.del(key); + return true; + } catch (Throwable e) { + plugin.log(Level.SEVERE, "An exception occurred fetching a user's server switch from redis", e); + return false; + } } - public void close() { + public void terminate() { if (jedisPool != null) { if (!jedisPool.isClosed()) { jedisPool.close(); } } + this.unsubscribe(); } - private static byte[] getKey(@NotNull RedisKeyType keyType, @NotNull UUID uuid) { - return (keyType.getKeyPrefix() + ":" + uuid).getBytes(StandardCharsets.UTF_8); + private static byte[] getKey(@NotNull RedisKeyType keyType, @NotNull UUID uuid, @NotNull String clusterId) { + return String.format("%s:%s", keyType.getKeyPrefix(clusterId), uuid).getBytes(StandardCharsets.UTF_8); } } diff --git a/common/src/main/java/net/william278/husksync/redis/RedisMessage.java b/common/src/main/java/net/william278/husksync/redis/RedisMessage.java index 54cccb6a..da9275e6 100644 --- a/common/src/main/java/net/william278/husksync/redis/RedisMessage.java +++ b/common/src/main/java/net/william278/husksync/redis/RedisMessage.java @@ -19,34 +19,62 @@ package net.william278.husksync.redis; -import com.google.gson.GsonBuilder; import com.google.gson.JsonSyntaxException; +import com.google.gson.annotations.SerializedName; +import net.william278.husksync.HuskSync; +import net.william278.husksync.adapter.Adaptable; import org.jetbrains.annotations.NotNull; import java.util.UUID; -import java.util.concurrent.CompletableFuture; -public class RedisMessage { +public class RedisMessage implements Adaptable { - public UUID targetUserUuid; - public byte[] data; + @SerializedName("target_uuid") + private UUID targetUuid; + @SerializedName("payload") + private byte[] payload; - public RedisMessage(@NotNull UUID targetUserUuid, byte[] message) { - this.targetUserUuid = targetUserUuid; - this.data = message; + private RedisMessage(@NotNull UUID targetUuid, byte[] message) { + this.setTargetUuid(targetUuid); + this.setPayload(message); } + @SuppressWarnings("unused") public RedisMessage() { } - public void dispatch(@NotNull RedisManager redisManager, @NotNull RedisMessageType type) { - CompletableFuture.runAsync(() -> redisManager.sendMessage(type.getMessageChannel(), - new GsonBuilder().create().toJson(this))); + @NotNull + public static RedisMessage create(@NotNull UUID targetUuid, byte[] message) { + return new RedisMessage(targetUuid, message); + } + + @NotNull + public static RedisMessage fromJson(@NotNull HuskSync plugin, @NotNull String json) throws JsonSyntaxException { + return plugin.getGson().fromJson(json, RedisMessage.class); + } + + public void dispatch(@NotNull HuskSync plugin, @NotNull RedisMessageType type) { + plugin.runAsync(() -> plugin.getRedisManager().sendMessage( + type.getMessageChannel(plugin.getSettings().getClusterId()), + plugin.getGson().toJson(this) + )); } @NotNull - public static RedisMessage fromJson(@NotNull String json) throws JsonSyntaxException { - return new GsonBuilder().create().fromJson(json, RedisMessage.class); + public UUID getTargetUuid() { + return targetUuid; + } + + public void setTargetUuid(@NotNull UUID targetUuid) { + this.targetUuid = targetUuid; + } + + public byte[] getPayload() { + return payload; + } + + public void setPayload(byte[] payload) { + this.payload = payload; } } \ No newline at end of file diff --git a/common/src/main/java/net/william278/husksync/redis/RedisMessageType.java b/common/src/main/java/net/william278/husksync/redis/RedisMessageType.java index a8ba7b2e..7153aa3c 100644 --- a/common/src/main/java/net/william278/husksync/redis/RedisMessageType.java +++ b/common/src/main/java/net/william278/husksync/redis/RedisMessageType.java @@ -27,17 +27,24 @@ import java.util.Optional; public enum RedisMessageType { - UPDATE_USER_DATA; + UPDATE_USER_DATA, + REQUEST_USER_DATA, + RETURN_USER_DATA; @NotNull - public String getMessageChannel() { - return RedisManager.KEY_NAMESPACE.toLowerCase(Locale.ENGLISH) + ":" + RedisManager.clusterId.toLowerCase(Locale.ENGLISH) - + ":" + name().toLowerCase(Locale.ENGLISH); + public String getMessageChannel(@NotNull String clusterId) { + return String.format( + "%s:%s:%s", + RedisManager.KEY_NAMESPACE.toLowerCase(Locale.ENGLISH), + clusterId.toLowerCase(Locale.ENGLISH), + name().toLowerCase(Locale.ENGLISH) + ); } - public static Optional getTypeFromChannel(@NotNull String messageChannel) { - return Arrays.stream(values()).filter(messageType -> messageType.getMessageChannel() - .equalsIgnoreCase(messageChannel)).findFirst(); + public static Optional getTypeFromChannel(@NotNull String channel, @NotNull String clusterId) { + return Arrays.stream(values()) + .filter(messageType -> messageType.getMessageChannel(clusterId).equalsIgnoreCase(channel)) + .findFirst(); } } \ No newline at end of file diff --git a/common/src/main/java/net/william278/husksync/HuskSyncInitializationException.java b/common/src/main/java/net/william278/husksync/user/CommandUser.java similarity index 59% rename from common/src/main/java/net/william278/husksync/HuskSyncInitializationException.java rename to common/src/main/java/net/william278/husksync/user/CommandUser.java index de75a0e4..c4db8540 100644 --- a/common/src/main/java/net/william278/husksync/HuskSyncInitializationException.java +++ b/common/src/main/java/net/william278/husksync/user/CommandUser.java @@ -17,15 +17,26 @@ * limitations under the License. */ -package net.william278.husksync; +package net.william278.husksync.user; +import de.themoep.minedown.adventure.MineDown; +import net.kyori.adventure.audience.Audience; +import net.kyori.adventure.text.Component; import org.jetbrains.annotations.NotNull; -/** - * Indicates an exception occurred while initializing the HuskSync plugin - */ -public class HuskSyncInitializationException extends IllegalStateException { - public HuskSyncInitializationException(@NotNull String message) { - super(message); +public interface CommandUser { + + @NotNull + Audience getAudience(); + + boolean hasPermission(@NotNull String permission); + + default void sendMessage(@NotNull Component component) { + getAudience().sendMessage(component); } + + default void sendMessage(@NotNull MineDown mineDown) { + this.sendMessage(mineDown.toComponent()); + } + } diff --git a/common/src/main/java/net/william278/husksync/data/PotionEffectData.java b/common/src/main/java/net/william278/husksync/user/ConsoleUser.java similarity index 62% rename from common/src/main/java/net/william278/husksync/data/PotionEffectData.java rename to common/src/main/java/net/william278/husksync/user/ConsoleUser.java index afe1d599..fe89c93b 100644 --- a/common/src/main/java/net/william278/husksync/data/PotionEffectData.java +++ b/common/src/main/java/net/william278/husksync/user/ConsoleUser.java @@ -17,25 +17,28 @@ * limitations under the License. */ -package net.william278.husksync.data; +package net.william278.husksync.user; -import com.google.gson.annotations.SerializedName; +import net.kyori.adventure.audience.Audience; import org.jetbrains.annotations.NotNull; -/** - * Stores potion effect data - */ -public class PotionEffectData { +public final class ConsoleUser implements CommandUser { - @SerializedName("serialized_potion_effects") - public String serializedPotionEffects; + @NotNull + private final Audience audience; - public PotionEffectData(@NotNull final String serializedPotionEffects) { - this.serializedPotionEffects = serializedPotionEffects; + public ConsoleUser(@NotNull Audience console) { + this.audience = console; } - @SuppressWarnings("unused") - protected PotionEffectData() { + @Override + @NotNull + public Audience getAudience() { + return audience; } + @Override + public boolean hasPermission(@NotNull String permission) { + return true; + } } diff --git a/common/src/main/java/net/william278/husksync/user/OnlineUser.java b/common/src/main/java/net/william278/husksync/user/OnlineUser.java new file mode 100644 index 00000000..4f28de4c --- /dev/null +++ b/common/src/main/java/net/william278/husksync/user/OnlineUser.java @@ -0,0 +1,188 @@ +/* + * This file is part of HuskSync, licensed under the Apache License 2.0. + * + * Copyright (c) William278 + * Copyright (c) contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.william278.husksync.user; + +import de.themoep.minedown.adventure.MineDown; +import de.themoep.minedown.adventure.MineDownParser; +import net.kyori.adventure.audience.Audience; +import net.kyori.adventure.text.Component; +import net.william278.husksync.HuskSync; +import net.william278.husksync.data.Data; +import net.william278.husksync.data.DataSnapshot; +import net.william278.husksync.data.Identifier; +import net.william278.husksync.data.UserDataHolder; +import org.jetbrains.annotations.NotNull; + +import java.util.Map; +import java.util.UUID; +import java.util.function.Consumer; + +/** + * Represents a logged-in {@link User} + */ +public abstract class OnlineUser extends User implements CommandUser, UserDataHolder { + + public OnlineUser(@NotNull UUID uuid, @NotNull String username) { + super(uuid, username); + } + + /** + * Indicates if the player has gone offline + * + * @return {@code true} if the player has left the server; {@code false} otherwise + */ + public abstract boolean isOffline(); + + /** + * Get the player's adventure {@link Audience} + * + * @return the player's {@link Audience} + */ + @NotNull + public abstract Audience getAudience(); + + /** + * Send a message to this player + * + * @param component the {@link Component} message to send + */ + public void sendMessage(@NotNull Component component) { + getAudience().sendMessage(component); + } + + /** + * Dispatch a MineDown-formatted message to this player + * + * @param mineDown the parsed {@link MineDown} to send + */ + public void sendMessage(@NotNull MineDown mineDown) { + sendMessage(mineDown + .disable(MineDownParser.Option.SIMPLE_FORMATTING) + .replace().toComponent()); + } + + /** + * Dispatch a MineDown-formatted action bar message to this player + * + * @param mineDown the parsed {@link MineDown} to send + */ + public void sendActionBar(@NotNull MineDown mineDown) { + getAudience().sendActionBar(mineDown + .disable(MineDownParser.Option.SIMPLE_FORMATTING) + .replace().toComponent()); + } + + /** + * Dispatch a toast message to this player + * + * @param title the title of the toast + * @param description the description of the toast + * @param iconMaterial the namespace-keyed material to use as an hasIcon of the toast + * @param backgroundType the background ("ToastType") of the toast + */ + public abstract void sendToast(@NotNull MineDown title, @NotNull MineDown description, + @NotNull String iconMaterial, @NotNull String backgroundType); + + /** + * Show a GUI chest menu to the user + * + * @param items the items to fill the menu with + * @param title the title of the menu + * @param editable whether the menu is editable (items can be removed or added) + * @param size the size of the menu + * @param onClose the action to perform when the menu is closed + */ + public abstract void showGui(@NotNull Data.Items.Items items, @NotNull MineDown title, boolean editable, int size, + @NotNull Consumer onClose); + + /** + * Returns if the player has the permission node + * + * @param node The permission node string + * @return {@code true} if the player has permission node; {@code false} otherwise + */ + public abstract boolean hasPermission(@NotNull String node); + + + /** + * Set a player's status from a {@link DataSnapshot} + * + * @param snapshot The {@link DataSnapshot} to set the player's status from + */ + public void applySnapshot(@NotNull DataSnapshot.Packed snapshot, @NotNull DataSnapshot.UpdateCause cause) { + getPlugin().fireEvent(getPlugin().getPreSyncEvent(this, snapshot), (event) -> { + if (!isOffline()) { + UserDataHolder.super.applySnapshot( + event.getData(), (owner) -> completeSync(true, cause, getPlugin()) + ); + } + }); + } + + /** + * Handle a player's synchronization completion + * + * @param succeeded Whether the synchronization succeeded + * @param plugin The plugin instance + */ + public void completeSync(boolean succeeded, @NotNull DataSnapshot.UpdateCause cause, @NotNull HuskSync plugin) { + if (succeeded) { + switch (plugin.getSettings().getNotificationDisplaySlot()) { + case CHAT -> cause.getCompletedLocale(plugin).ifPresent(this::sendMessage); + case ACTION_BAR -> cause.getCompletedLocale(plugin).ifPresent(this::sendActionBar); + case TOAST -> cause.getCompletedLocale(plugin) + .ifPresent(locale -> this.sendToast( + locale, new MineDown(""), + "minecraft:bell", + "TASK" + )); + } + plugin.fireEvent( + plugin.getSyncCompleteEvent(this), + (event) -> plugin.getLockedPlayers().remove(getUuid()) + ); + } else { + cause.getFailedLocale(plugin).ifPresent(this::sendMessage); + } + + // Ensure the user is in the database + plugin.getDatabase().ensureUser(this); + } + + @NotNull + @Override + public Map getCustomDataStore() { + return getPlugin().getPlayerCustomDataStore(this); + } + + /** + * Get if the player is locked + * + * @return the player's locked status + */ + public abstract boolean isLocked(); + + /** + * Get if the player is a NPC + * + * @return if the player is a NPC with metadata + */ + public abstract boolean isNpc(); +} diff --git a/common/src/main/java/net/william278/husksync/player/User.java b/common/src/main/java/net/william278/husksync/user/User.java similarity index 72% rename from common/src/main/java/net/william278/husksync/player/User.java rename to common/src/main/java/net/william278/husksync/user/User.java index aea20411..19c4bbc1 100644 --- a/common/src/main/java/net/william278/husksync/player/User.java +++ b/common/src/main/java/net/william278/husksync/user/User.java @@ -17,37 +17,48 @@ * limitations under the License. */ -package net.william278.husksync.player; +package net.william278.husksync.user; import org.jetbrains.annotations.NotNull; import java.util.UUID; /** - * Represents a user who has their data synchronised by HuskSync + * Represents a user who has their data synchronized by HuskSync */ public class User { - /** - * The user's unique account ID - */ - public final UUID uuid; + private final UUID uuid; - /** - * The user's username - */ - public final String username; + private final String username; public User(@NotNull UUID uuid, @NotNull String username) { this.username = username; this.uuid = uuid; } + /** + * Get the user's unique account ID + */ + @NotNull + public UUID getUuid() { + return uuid; + } + + /** + * Get the user's username + */ + @NotNull + public String getUsername() { + return username; + } + @Override public boolean equals(Object object) { if (object instanceof User other) { - return this.uuid.equals(other.uuid); + return this.getUuid().equals(other.getUuid()); } return super.equals(object); } + } diff --git a/common/src/main/java/net/william278/husksync/util/DataDumper.java b/common/src/main/java/net/william278/husksync/util/DataDumper.java index 31975a98..44ee1092 100644 --- a/common/src/main/java/net/william278/husksync/util/DataDumper.java +++ b/common/src/main/java/net/william278/husksync/util/DataDumper.java @@ -22,8 +22,8 @@ package net.william278.husksync.util; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import net.william278.husksync.HuskSync; -import net.william278.husksync.data.UserDataSnapshot; -import net.william278.husksync.player.User; +import net.william278.husksync.data.DataSnapshot; +import net.william278.husksync.user.User; import org.jetbrains.annotations.NotNull; import java.io.*; @@ -31,38 +31,37 @@ import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; -import java.text.SimpleDateFormat; +import java.time.format.DateTimeFormatter; import java.util.Locale; import java.util.StringJoiner; import java.util.logging.Level; /** - * Utility class for dumping {@link UserDataSnapshot}s to a file or as a paste on the web + * Utility class for dumping {@link DataSnapshot}s to a file or as a paste on the web */ public class DataDumper { private static final String LOGS_SITE_ENDPOINT = "https://api.mclo.gs/1/log"; private final HuskSync plugin; - private final UserDataSnapshot dataSnapshot; + private final DataSnapshot.Packed snapshot; private final User user; - private DataDumper(@NotNull UserDataSnapshot dataSnapshot, - @NotNull User user, @NotNull HuskSync implementor) { - this.dataSnapshot = dataSnapshot; + private DataDumper(@NotNull DataSnapshot.Packed snapshot, @NotNull User user, @NotNull HuskSync implementor) { + this.snapshot = snapshot; this.user = user; this.plugin = implementor; } /** - * Create a {@link DataDumper} of the given {@link UserDataSnapshot} + * Create a {@link DataDumper} of the given {@link DataSnapshot} * - * @param dataSnapshot The {@link UserDataSnapshot} to dump + * @param dataSnapshot The {@link DataSnapshot} to dump * @param user The {@link User} whose data is being dumped * @param plugin The implementing {@link HuskSync} plugin - * @return A {@link DataDumper} for the given {@link UserDataSnapshot} + * @return A {@link DataDumper} for the given {@link DataSnapshot} */ - public static DataDumper create(@NotNull UserDataSnapshot dataSnapshot, + public static DataDumper create(@NotNull DataSnapshot.Packed dataSnapshot, @NotNull User user, @NotNull HuskSync plugin) { return new DataDumper(dataSnapshot, user, plugin); } @@ -75,7 +74,7 @@ public class DataDumper { @Override @NotNull public String toString() { - return plugin.getDataAdapter().toJson(dataSnapshot.userData(), true); + return snapshot.asJson(plugin); } @NotNull @@ -128,7 +127,7 @@ public class DataDumper { } /** - * Dump the {@link UserDataSnapshot} to a file and return the file name + * Dump the {@link DataSnapshot} to a file and return the file name * * @return the relative path of the file the data was dumped to */ @@ -182,11 +181,11 @@ public class DataDumper { @NotNull private String getFileName() { return new StringJoiner("_") - .add(user.username) - .add(new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss").format(dataSnapshot.versionTimestamp())) - .add(dataSnapshot.cause().name().toLowerCase(Locale.ENGLISH)) - .add(dataSnapshot.versionUUID().toString().split("-")[0]) - + ".json"; + .add(user.getUsername()) + .add(snapshot.getTimestamp().format(DateTimeFormatter.ofPattern("yyyy-MM-dd_HH-mm-ss"))) + .add(snapshot.getSaveCause().name().toLowerCase(Locale.ENGLISH)) + .add(snapshot.getShortId()) + + ".json"; } } diff --git a/common/src/main/java/net/william278/husksync/util/DataSnapshotList.java b/common/src/main/java/net/william278/husksync/util/DataSnapshotList.java index 6af99bcf..aecc1706 100644 --- a/common/src/main/java/net/william278/husksync/util/DataSnapshotList.java +++ b/common/src/main/java/net/william278/husksync/util/DataSnapshotList.java @@ -19,19 +19,19 @@ package net.william278.husksync.util; -import net.william278.husksync.config.Locales; -import net.william278.husksync.data.UserDataSnapshot; -import net.william278.husksync.player.OnlineUser; -import net.william278.husksync.player.User; +import net.william278.husksync.HuskSync; +import net.william278.husksync.data.DataSnapshot; +import net.william278.husksync.user.CommandUser; +import net.william278.husksync.user.User; import net.william278.paginedown.PaginatedList; import org.jetbrains.annotations.NotNull; -import java.text.SimpleDateFormat; +import java.time.format.DateTimeFormatter; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; /** - * Represents a chat-viewable paginated list of {@link UserDataSnapshot}s + * Represents a chat-viewable paginated list of {@link net.william278.husksync.data.DataSnapshot}s */ public class DataSnapshotList { @@ -41,46 +41,52 @@ public class DataSnapshotList { @NotNull private final PaginatedList paginatedList; - private DataSnapshotList(@NotNull List snapshots, @NotNull User dataOwner, - @NotNull Locales locales) { + private DataSnapshotList(@NotNull List snapshots, @NotNull User dataOwner, + @NotNull HuskSync plugin) { final AtomicInteger snapshotNumber = new AtomicInteger(1); this.paginatedList = PaginatedList.of(snapshots.stream() - .map(snapshot -> locales.getRawLocale("data_list_item", + .map(snapshot -> plugin.getLocales() + .getRawLocale("data_list_item", getNumberIcon(snapshotNumber.getAndIncrement()), - new SimpleDateFormat("MMM dd yyyy, HH:mm:ss.sss") - .format(snapshot.versionTimestamp()), - snapshot.versionUUID().toString().split("-")[0], - snapshot.versionUUID().toString(), - snapshot.cause().getDisplayName(), - dataOwner.username, - snapshot.pinned() ? "※" : " ") - .orElse("• " + snapshot.versionUUID())).toList(), - locales.getBaseChatList(6) - .setHeaderFormat(locales.getRawLocale("data_list_title", dataOwner.username, + dataOwner.getUsername(), + snapshot.getId().toString(), + snapshot.getShortId(), + snapshot.isPinned() ? "※" : " ", + snapshot.getTimestamp().format(DateTimeFormatter + .ofPattern("dd/MM/yyyy, HH:mm")), + snapshot.getTimestamp().format(DateTimeFormatter + .ofPattern("MMM dd yyyy, HH:mm:ss.SSS")), + snapshot.getSaveCause().getDisplayName(), + String.format("%.2fKiB", snapshot.getFileSize(plugin) / 1024f)) + .orElse("• " + snapshot.getId())).toList(), + plugin.getLocales().getBaseChatList(6) + .setHeaderFormat(plugin.getLocales() + .getRawLocale("data_list_title", dataOwner.getUsername(), "%first_item_on_page_index%", "%last_item_on_page_index%", "%total_items%") .orElse("")) - .setCommand("/husksync:userdata list " + dataOwner.username) + .setCommand("/husksync:userdata list " + dataOwner.getUsername()) .build()); } /** - * Create a new {@link DataSnapshotList} from a list of {@link UserDataSnapshot}s + * Create a new {@link DataSnapshotList} from a list of {@link DataSnapshot}s * - * @param snapshots The list of {@link UserDataSnapshot}s to display - * @param user The {@link User} who owns the {@link UserDataSnapshot}s - * @param locales The {@link Locales} instance - * @return A new {@link DataSnapshotList}, to be viewed with {@link #displayPage(OnlineUser, int)} + * @param snapshots The list of {@link DataSnapshot}s to display + * @param user The {@link User} who owns the {@link DataSnapshot}s + * @param plugin The instance of the plugin + * @return A new {@link DataSnapshotList}, to be viewed with {@link #displayPage(CommandUser, int)} */ - public static DataSnapshotList create(@NotNull List snapshots, @NotNull User user, - @NotNull Locales locales) { - return new DataSnapshotList(snapshots, user, locales); + @NotNull + public static DataSnapshotList create(@NotNull List snapshots, @NotNull User user, + @NotNull HuskSync plugin) { + return new DataSnapshotList(snapshots, user, plugin); } /** - * Get an icon for the given snapshot number, via {@link #CIRCLED_NUMBER_ICONS} + * Get an hasIcon for the given snapshot number, via {@link #CIRCLED_NUMBER_ICONS} * * @param number the snapshot number - * @return the icon for the given snapshot number + * @return the hasIcon for the given snapshot number */ private static String getNumberIcon(int number) { if (number < 1 || number > 20) { @@ -90,12 +96,12 @@ public class DataSnapshotList { } /** - * Display a page of the list of {@link UserDataSnapshot} to the user + * Display a page of the list of {@link DataSnapshot} to the user * * @param onlineUser The online user to display the message to * @param page The page number to display */ - public void displayPage(@NotNull OnlineUser onlineUser, int page) { + public void displayPage(@NotNull CommandUser onlineUser, int page) { onlineUser.sendMessage(paginatedList.getNearestValidPage(page)); } diff --git a/common/src/main/java/net/william278/husksync/util/DataSnapshotOverview.java b/common/src/main/java/net/william278/husksync/util/DataSnapshotOverview.java new file mode 100644 index 00000000..b82c520d --- /dev/null +++ b/common/src/main/java/net/william278/husksync/util/DataSnapshotOverview.java @@ -0,0 +1,135 @@ +/* + * This file is part of HuskSync, licensed under the Apache License 2.0. + * + * Copyright (c) William278 + * Copyright (c) contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.william278.husksync.util; + +import net.william278.husksync.HuskSync; +import net.william278.husksync.config.Locales; +import net.william278.husksync.data.Data; +import net.william278.husksync.data.DataSnapshot; +import net.william278.husksync.user.CommandUser; +import net.william278.husksync.user.User; +import org.jetbrains.annotations.NotNull; + +import java.time.format.DateTimeFormatter; +import java.util.List; +import java.util.Locale; +import java.util.Optional; +import java.util.StringJoiner; + +public class DataSnapshotOverview { + + private final HuskSync plugin; + private final User dataOwner; + private final DataSnapshot.Unpacked snapshot; + private final long snapshotSize; + + private DataSnapshotOverview(@NotNull DataSnapshot.Unpacked snapshot, long snapshotSize, + @NotNull User dataOwner, @NotNull HuskSync plugin) { + this.snapshot = snapshot; + this.snapshotSize = snapshotSize; + this.dataOwner = dataOwner; + this.plugin = plugin; + } + + @NotNull + public static DataSnapshotOverview of(@NotNull DataSnapshot.Unpacked snapshot, long snapshotSize, + @NotNull User dataOwner, @NotNull HuskSync plugin) { + return new DataSnapshotOverview(snapshot, snapshotSize, dataOwner, plugin); + } + + public void show(@NotNull CommandUser user) { + // Title message, timestamp, owner and cause. + final Locales locales = plugin.getLocales(); + locales.getLocale("data_manager_title", snapshot.getShortId(), snapshot.getId().toString(), + dataOwner.getUsername(), dataOwner.getUuid().toString()) + .ifPresent(user::sendMessage); + locales.getLocale("data_manager_timestamp", + snapshot.getTimestamp().format(DateTimeFormatter.ofPattern("MMM dd yyyy, HH:mm:ss.SSS")), + snapshot.getTimestamp().toString()) + .ifPresent(user::sendMessage); + if (snapshot.isPinned()) { + locales.getLocale("data_manager_pinned") + .ifPresent(user::sendMessage); + } + locales.getLocale("data_manager_cause", snapshot.getSaveCause().getDisplayName()) + .ifPresent(user::sendMessage); + + // User status data, if present in the snapshot + final Optional health = snapshot.getHealth(); + final Optional food = snapshot.getHunger(); + final Optional experience = snapshot.getExperience(); + final Optional gameMode = snapshot.getGameMode(); + if (health.isPresent() && food.isPresent() && experience.isPresent() && gameMode.isPresent()) { + locales.getLocale("data_manager_status", + Integer.toString((int) health.get().getHealth()), + Integer.toString((int) health.get().getMaxHealth()), + Integer.toString(food.get().getFoodLevel()), + Integer.toString(experience.get().getExpLevel()), + gameMode.get().getGameMode().toLowerCase(Locale.ENGLISH)) + .ifPresent(user::sendMessage); + } + + // Snapshot size + locales.getLocale("data_manager_size", String.format("%.2fKiB", snapshotSize / 1024f)) + .ifPresent(user::sendMessage); + + // Advancement and statistic data, if both are present in the snapshot + snapshot.getAdvancements() + .flatMap(advancementData -> snapshot.getStatistics() + .flatMap(statisticsData -> locales.getLocale("data_manager_advancements_statistics", + Integer.toString(advancementData.getCompletedExcludingRecipes().size()), + generateAdvancementPreview(advancementData.getCompletedExcludingRecipes(), locales), + String.format("%.2f", (((statisticsData.getGenericStatistics().getOrDefault( + "minecraft:play_one_minute", 0)) / 20d) / 60d) / 60d)))) + .ifPresent(user::sendMessage); + + if (user.hasPermission("husksync.command.inventory.edit") + && user.hasPermission("husksync.command.enderchest.edit")) { + locales.getLocale("data_manager_item_buttons", dataOwner.getUsername(), snapshot.getId().toString()) + .ifPresent(user::sendMessage); + } + locales.getLocale("data_manager_management_buttons", dataOwner.getUsername(), snapshot.getId().toString()) + .ifPresent(user::sendMessage); + if (user.hasPermission("husksync.command.userdata.dump")) { + locales.getLocale("data_manager_system_buttons", dataOwner.getUsername(), snapshot.getId().toString()) + .ifPresent(user::sendMessage); + } + } + + @NotNull + private String generateAdvancementPreview(@NotNull List advancementData, @NotNull Locales locales) { + final StringJoiner joiner = new StringJoiner("\n"); + final int PREVIEW_SIZE = 8; + for (int i = 0; i < advancementData.size(); i++) { + joiner.add(advancementData.get(i).getKey()); + if (i >= PREVIEW_SIZE) { + break; + } + } + final int remaining = advancementData.size() - PREVIEW_SIZE; + if (remaining > 0) { + joiner.add(locales.getRawLocale("data_manager_advancements_preview_remaining", + Integer.toString(remaining)) + .orElse(String.format("+%s…", remaining))); + } + return joiner.toString(); + } + +} diff --git a/common/src/main/java/net/william278/husksync/data/DataSerializationException.java b/common/src/main/java/net/william278/husksync/util/LegacyConverter.java similarity index 62% rename from common/src/main/java/net/william278/husksync/data/DataSerializationException.java rename to common/src/main/java/net/william278/husksync/util/LegacyConverter.java index 75474d5a..9702a0bb 100644 --- a/common/src/main/java/net/william278/husksync/data/DataSerializationException.java +++ b/common/src/main/java/net/william278/husksync/util/LegacyConverter.java @@ -17,18 +17,22 @@ * limitations under the License. */ -package net.william278.husksync.data; +package net.william278.husksync.util; +import net.william278.husksync.HuskSync; +import net.william278.husksync.adapter.DataAdapter; +import net.william278.husksync.data.DataSnapshot; import org.jetbrains.annotations.NotNull; -/** - * Indicates an error occurred during Base-64 serialization and deserialization of data. - *

- * For example, an exception deserializing {@link ItemData} item stack or {@link PotionEffectData} potion effect arrays - */ -public class DataSerializationException extends RuntimeException { - protected DataSerializationException(@NotNull String message, @NotNull Throwable cause) { - super(message, cause); +public abstract class LegacyConverter { + + protected final HuskSync plugin; + + protected LegacyConverter(@NotNull HuskSync plugin) { + this.plugin = plugin; } + @NotNull + public abstract DataSnapshot.Packed convert(@NotNull byte[] data) throws DataAdapter.AdaptionException; + } diff --git a/common/src/main/java/net/william278/husksync/util/Task.java b/common/src/main/java/net/william278/husksync/util/Task.java new file mode 100644 index 00000000..6daf6905 --- /dev/null +++ b/common/src/main/java/net/william278/husksync/util/Task.java @@ -0,0 +1,144 @@ +/* + * This file is part of HuskSync, licensed under the Apache License 2.0. + * + * Copyright (c) William278 + * Copyright (c) contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.william278.husksync.util; + +import net.william278.husksync.HuskSync; +import org.jetbrains.annotations.NotNull; + +import java.util.concurrent.CompletableFuture; + +public interface Task extends Runnable { + + abstract class Base implements Task { + + protected final HuskSync plugin; + protected final Runnable runnable; + protected boolean cancelled = false; + + protected Base(@NotNull HuskSync plugin, @NotNull Runnable runnable) { + this.plugin = plugin; + this.runnable = runnable; + } + + public void cancel() { + cancelled = true; + } + + @NotNull + @Override + public HuskSync getPlugin() { + return plugin; + } + + } + + abstract class Async extends Base { + + protected long delayTicks; + + protected Async(@NotNull HuskSync plugin, @NotNull Runnable runnable, long delayTicks) { + super(plugin, runnable); + this.delayTicks = delayTicks; + } + + } + + abstract class Sync extends Base { + + protected long delayTicks; + + protected Sync(@NotNull HuskSync plugin, @NotNull Runnable runnable, long delayTicks) { + super(plugin, runnable); + this.delayTicks = delayTicks; + } + + } + + abstract class Repeating extends Base { + + protected final long repeatingTicks; + + protected Repeating(@NotNull HuskSync plugin, @NotNull Runnable runnable, long repeatingTicks) { + super(plugin, runnable); + this.repeatingTicks = repeatingTicks; + } + + } + + @SuppressWarnings("UnusedReturnValue") + interface Supplier { + + @NotNull + Task.Sync getSyncTask(@NotNull Runnable runnable, long delayTicks); + + @NotNull + Task.Async getAsyncTask(@NotNull Runnable runnable, long delayTicks); + + @NotNull + Task.Repeating getRepeatingTask(@NotNull Runnable runnable, long repeatingTicks); + + @NotNull + default Task.Sync runSyncDelayed(@NotNull Runnable runnable, long delayTicks) { + final Task.Sync task = getSyncTask(runnable, delayTicks); + task.run(); + return task; + } + + default Task.Async runAsyncDelayed(@NotNull Runnable runnable, long delayTicks) { + final Task.Async task = getAsyncTask(runnable, delayTicks); + task.run(); + return task; + } + + @NotNull + default Task.Sync runSync(@NotNull Runnable runnable) { + return runSyncDelayed(runnable, 0); + } + + @NotNull + default Task.Async runAsync(@NotNull Runnable runnable) { + final Task.Async task = getAsyncTask(runnable, 0); + task.run(); + return task; + } + + default CompletableFuture supplyAsync(@NotNull java.util.function.Supplier supplier) { + final CompletableFuture future = new CompletableFuture<>(); + runAsync(() -> { + try { + future.complete(supplier.get()); + } catch (Throwable throwable) { + future.completeExceptionally(throwable); + } + }); + return future; + } + + void cancelTasks(); + + @NotNull + HuskSync getPlugin(); + + } + + @NotNull + HuskSync getPlugin(); + +} \ No newline at end of file diff --git a/common/src/main/resources/database/mysql_schema.sql b/common/src/main/resources/database/mysql_schema.sql index 3da68c3f..efef8797 100644 --- a/common/src/main/resources/database/mysql_schema.sql +++ b/common/src/main/resources/database/mysql_schema.sql @@ -1,3 +1,9 @@ +# Set the storage engine +SET DEFAULT_STORAGE_ENGINE = INNODB; + +# Enable foreign key constraints +SET FOREIGN_KEY_CHECKS = 1; + # Create the users table if it does not exist CREATE TABLE IF NOT EXISTS `%users_table%` ( @@ -5,7 +11,8 @@ CREATE TABLE IF NOT EXISTS `%users_table%` `username` varchar(16) NOT NULL, PRIMARY KEY (`uuid`) -); +) CHARACTER SET utf8 + COLLATE utf8_unicode_ci; # Create the user data table if it does not exist CREATE TABLE IF NOT EXISTS `%user_data_table%` @@ -18,4 +25,5 @@ CREATE TABLE IF NOT EXISTS `%user_data_table%` `data` longblob NOT NULL, PRIMARY KEY (`version_uuid`, `player_uuid`), FOREIGN KEY (`player_uuid`) REFERENCES `%users_table%` (`uuid`) ON DELETE CASCADE -); \ No newline at end of file +) CHARACTER SET utf8 + COLLATE utf8_unicode_ci; \ No newline at end of file diff --git a/common/src/main/resources/locales/bg-bg.yml b/common/src/main/resources/locales/bg-bg.yml index 162547f0..4bc4b394 100644 --- a/common/src/main/resources/locales/bg-bg.yml +++ b/common/src/main/resources/locales/bg-bg.yml @@ -1,31 +1,25 @@ -synchronisation_complete: '[⏵ Данните синхронизирани!](#00fb9a)' -synchronisation_failed: '[⏵ Провалихме се да синхронизираме Вашите данни! Моля свържете се с администратор.](#ff7e5e)' -reload_complete: '[HuskSync](#00fb9a bold) [| Презаредихме конфигурацията и файловете със съобщения.](#00fb9a)' -error_invalid_syntax: '[Грешка:](#ff3300) [Неправилен синтаксис. Използвайте: %1%](#ff7e5e)' -error_invalid_player: '[Грешка:](#ff3300) [Не можахме да открием играч с това име.](#ff7e5e)' -error_no_permission: '[Грешка:](#ff3300) [Нямате право да използвате тази команда](#ff7e5e)' -error_console_command_only: '[Грешка:](#ff3300) [Тази команда може да бъде използвана единствено през конзолата](#ff7e5e)' -error_in_game_command_only: 'Грешка: Тази команда може да бъде използвана само от играта.' -error_no_data_to_display: '[Грешка:](#ff3300) [Не можахме да открием никакви данни за потребителя, които да покажем.](#ff7e5e)' -error_invalid_version_uuid: '[Грешка:](#ff3300) [Не можахме да открием никакви потребителски данни за тази версия на това UUID.](#ff7e5e)' +synchronization_complete: '[⏵ Данните синхронизирани!](#00fb9a)' +synchronization_failed: '[⏵ Провалихме се да синхронизираме Вашите данни! Моля свържете се с администратор.](#ff7e5e)' inventory_viewer_menu_title: '&0Инвентара на %1%' ender_chest_viewer_menu_title: '&0Ендър Сандъка на %1%' inventory_viewer_opened: '[Преглеждане снапшота на](#00fb9a) [%1%](#00fb9a bold) [ инвентар от ⌚ %2%](#00fb9a)' ender_chest_viewer_opened: '[Преглеждане снапшота на](#00fb9a) [%1%](#00fb9a bold) [ Ендър Сандък от ⌚ %2%](#00fb9a)' data_update_complete: '[🔔 Вашите данни бяха обновени!](#00fb9a)' data_update_failed: '[🔔 Провалихме се да обновим Вашите данни! Моля свържете се с администратор.](#ff7e5e)' +user_registration_complete: '[⭐ User registration complete!](#00fb9a)' data_manager_title: '[Преглеждане потребителският снапшот](#00fb9a) [%1%](#00fb9a show_text=&7Версия на UUID:\n&8%2%) [за](#00fb9a) [%3%](#00fb9a bold show_text=&7UUID на Играча:\n&8%4%)[:](#00fb9a)' data_manager_timestamp: '[⌚ %1%](#ffc43b-#f5c962 show_text=&7Клеймо на Версията:\n&8Когато данните са били запазени)' data_manager_pinned: '[※ Закачен снапшот](#d8ff2b show_text=&7Закачен:\n&8Снапшота на този потребител няма да бъде автоматично завъртан.)' -data_manager_cause: '[⚑ %1%](#23a825-#36f539 show_text=&7Причина на Запазване:\n&8Какво е накарало данните да бъдат запазени)\n' -data_manager_status: '[%1%](red)[/](gray)[%2%](red)[×](gray)[❤](red show_text=&7Точки кръв) [%3%](yellow)[×](gray)[🍖](yellow show_text=&7Точки глад) [ʟᴠ](green)[.](gray)[%4%](green show_text=&7Ниво опит) [🏹 %5%](dark_aqua show_text=&7Режим на игра)' +data_manager_cause: '[⚑ %1%](#23a825-#36f539 show_text=&7Причина на Запазване:\n&8Какво е накарало данните да бъдат запазени)' +data_manager_size: '[⏏ %1%](color=#62a9f5-#7ab8fa show_text=&7Snapshot size:\n&8Estimated file size of the snapshot (in KiB))\n' +data_manger_status: '[%1%](red)[/](gray)[%2%](red)[×](gray)[❤](red show_text=&7Точки кръв) [%3%](yellow)[×](gray)[🍖](yellow show_text=&7Точки глад) [ʟᴠ](green)[.](gray)[%4%](green show_text=&7Ниво опит) [🏹 %5%](dark_aqua show_text=&7Режим на игра)' data_manager_advancements_statistics: '[⭐ Напредъци: %1%](color=#ffc43b-#f5c962 show_text=&7Напредъци, в които имате прогрес:\n&8%2%) [⌛ Изиграно Време: %3%ʜʀs](color=#62a9f5-#7ab8fa show_text=&7Изиграно време в играта\n&8⚠ Базирано на статистики от играта)\n' data_manager_item_buttons: '[View:](gray) [[🪣 Инвентар…]](color=#a17b5f-#f5b98c show_text=&7Натиснете, за да прегледате run_command=/inventory %1% %2%) [[⌀ Ендър Сандък…]](#b649c4-#d254ff show_text=&7Натиснете, за да проверите run_command=/enderchest %1% %2%)' data_manager_management_buttons: '[Управление:](gray) [[❌ Изтрий…]](#ff3300 show_text=&7Натиснете, за да изтриете този снапшот от потребителски данни.\n&8Това няма да засегне текущите данни на потребителя.\n&#ff3300&⚠ Това не може да бъде отменено! suggest_command=/husksync:userdata delete %1% %2%) [[⏪ Възстанови…]](#00fb9a show_text=&7Натиснете, за да възстановите тези потребителски данни.\n&8Това ще зададе данните на потребителя на този снапшот.\n&#ff3300&⚠ Текущите данни на %1% ще бъдат пренаписани! suggest_command=/husksync:userdata restore %1% %2%) [[※ Закачи/Откачи…]](#d8ff2b show_text=&7Натиснете, за да закачите или откачите този снапшот с потребителски данни\n&8Закачените снапшоти няма да бъдат автоматично завъртани run_command=/userdata pin %1% %2%)' data_manager_system_buttons: '[System:](gray) [[⏷ File Dump…]](dark_gray show_text=&7Click to dump this raw user data snapshot to a file.\n&8Data dumps can be found in ~/plugins/HuskSync/dumps/ run_command=/husksync:userdata dump %1% %2% file) [[☂ Web Dump…]](dark_gray show_text=&7Click to dump this raw user data snapshot to the mc-logs service\n&8You will be provided with a URL containing the data. run_command=/husksync:userdata dump %1% %2% web)' -data_manager_advancements_preview_remaining: '&7и още %1%…' +data_manager_advancements_preview_remaining: 'и още %1%…' data_list_title: '[Лист от](#00fb9a) [снапшоти на данните на потребителя](#00fb9a) [%1%](#00fb9a bold show_text=&7UUID: %2%)\n' -data_list_item: '[%1%](gray show_text=&7Снапшот с данни %3% run_command=/userdata view %6% %4%) [%7%](#d8ff2b show_text=&7Закачен:\n&8Закачените снапшоти няма да бъдат автоматично завъртани. run_command=/userdata view %6% %4%) [%2%](color=#ffc43b-#f5c962 show_text=&7Клеймо на Версията:&7\n&8Когато данните са били запазени run_command=/userdata view %6% %4%) [⚡ %3%](color=#62a9f5-#7ab8fa show_text=&7Версия на UUID:&7\n&8%4% run_command=/userdata view %6% %4%) [⚑ %5%](#23a825-#36f539 show_text=&7Причина на Запазване:\n&8Какво е накарало данните да бъдат запазени run_command=/userdata view %6% %4%)' +data_list_item: '[%1%](gray show_text=&7User Data Snapshot for %2%&8⚡ %4% run_command=/userdata view %2% %3%) [%5%](#d8ff2b show_text=&7Pinned:\n&8Pinned snapshots won''t be automatically rotated. run_command=/userdata view %2% %3%) [%6%](color=#ffc43b-#f5c962 show_text=&7Version timestamp:&7\n&8When the data was saved\n&8%7% run_command=/userdata view %2% %3%) [⚑ %8%](#23a825-#36f539 show_text=&7Save cause:\n&8What caused the data to be saved run_command=/userdata view %2% %3%) [⏏ %9%](color=#62a9f5-#7ab8fa show_text=&7Snapshot size:&7\n&8Estimated file size of the snapshot (in KiB) run_command=/userdata view %2% %3%)' data_deleted: '[❌ Успешно изтрихме снапшота с потребителски данни](#00fb9a) [%1%](#00fb9a show_text=&7Версия на UUID:\n&8%2%) [за](#00fb9a) [%3%.](#00fb9a show_text=&7UUID на Играча:\n&8%4%)' data_restored: '[⏪ Успешно възстановихме](#00fb9a) [текущите потребителски данни за](#00fb9a) [%1%](#00fb9a show_text=&7UUID на Играча:\n&8%2%) [от снапшот](#00fb9a) [%3%.](#00fb9a show_text=&7Версия на UUID:\n&8%4%)' data_pinned: '[※ Успешно закачихме снапшота с потребителски данни](#00fb9a) [%1%](#00fb9a show_text=&7Версия на UUID:\n&8%2%) [за](#00fb9a) [%3%.](#00fb9a show_text=&7UUID на Играча:\n&8%4%)' @@ -38,4 +32,18 @@ list_page_jumpers: '(%1%)' list_page_jumper_button: '[%1%](show_text=&7Jump to page %1% run_command=%2% %1%)' list_page_jumper_current_page: '[%1%](#00fb9a)' list_page_jumper_separator: ' ' -list_page_jumper_group_separator: '…' \ No newline at end of file +list_page_jumper_group_separator: '…' +up_to_date: '[HuskSync](#00fb9a bold) [| You are running the latest version of HuskSync (v%1%).](#00fb9a)' +update_available: '[HuskSync](#ff7e5e bold) [| A new version of HuskSync is available: v%1% (running: v%2%).](#ff7e5e)' +reload_complete: '[HuskSync](#00fb9a bold) [| Презаредихме конфигурацията и файловете със съобщения.](#00fb9a)\n[⚠ Ensure config files are up-to-date on all servers!](#00fb9a)\n[A restart is needed for config changes to take effect.](#00fb9a italic)' +error_invalid_syntax: '[Грешка:](#ff3300) [Неправилен синтаксис. Използвайте:](#ff7e5e) [%1%](#ff7e5e italic show_text=&#ff7e5e&Click to suggest suggest_command=%1%)' +error_invalid_player: '[Грешка:](#ff3300) [Не можахме да открием играч с това име.](#ff7e5e)' +error_no_permission: '[Грешка:](#ff3300) [Нямате право да използвате тази команда](#ff7e5e)' +error_console_command_only: '[Грешка:](#ff3300) [Тази команда може да бъде използвана единствено през конзолата](#ff7e5e)' +error_in_game_command_only: 'Грешка: Тази команда може да бъде използвана само от играта.' +error_no_data_to_display: '[Грешка:](#ff3300) [Не можахме да открием никакви данни за потребителя, които да покажем.](#ff7e5e)' +error_invalid_version_uuid: '[Грешка:](#ff3300) [Не можахме да открием никакви потребителски данни за тази версия на това UUID.](#ff7e5e)' +husksync_command_description: 'Manage the HuskSync plugin' +userdata_command_description: 'View, manage & restore player userdata' +inventory_command_description: 'View & edit a player''s inventory' +enderchest_command_description: 'View & edit a player''s Ender Chest' \ No newline at end of file diff --git a/common/src/main/resources/locales/de-de.yml b/common/src/main/resources/locales/de-de.yml index 0703c1a4..c642af66 100644 --- a/common/src/main/resources/locales/de-de.yml +++ b/common/src/main/resources/locales/de-de.yml @@ -1,31 +1,25 @@ -synchronisation_complete: '[⏵ Daten synchronisiert!](#00fb9a)' -synchronisation_failed: '[⏵ Ein Fehler ist beim Synchronisieren deiner Daten aufgetreten! Bitte kontaktiere einen Administrator.](#ff7e5e)' -reload_complete: '[HuskSync](#00fb9a bold) [| Die Konfigurations- und Sprachdateien wurden neu geladen.](#00fb9a)' -error_invalid_syntax: '[Fehler:](#ff3300) [Falsche Syntax. Nutze: %1%](#ff7e5e)' -error_invalid_player: '[Fehler:](#ff3300) [Es konnte kein Spieler mit diesem Namen gefunden werden.](#ff7e5e)' -error_no_permission: '[Fehler:](#ff3300) [Du hast nicht die benötigten Berechtigungen um diesen Befehl auszuführen](#ff7e5e)' -error_console_command_only: '[Fehler:](#ff3300) [Dieser Befehl kann nur über die Konsole ausgeführt werden.](#ff7e5e)' -error_in_game_command_only: 'Fehler: Dieser Befehl kann nur im Spiel genutzt werden.' -error_no_data_to_display: '[Fehler:](#ff3300) [Es konnten keine Nutzerdaten zum Anzeigen gefunden werden.](#ff7e5e)' -error_invalid_version_uuid: '[Fehler:](#ff3300) [Es konnten keine Nutzerdaten für diese Versions-UUID gefunden werden.](#ff7e5e)' +synchronization_complete: '[⏵ Daten synchronisiert!](#00fb9a)' +synchronization_failed: '[⏵ Ein Fehler ist beim Synchronisieren deiner Daten aufgetreten! Bitte kontaktiere einen Administrator.](#ff7e5e)' inventory_viewer_menu_title: '&0Inventar von %1%' ender_chest_viewer_menu_title: '&0Endertruhe von %1%' inventory_viewer_opened: '[Du siehst den Schnappschuss des Inventares von](#00fb9a) [%1%](#00fb9a bold) [von ⌚ %2%](#00fb9a)' ender_chest_viewer_opened: '[Du siehst den Schnappschuss der Endertruhe von](#00fb9a) [%1%](#00fb9a bold) [von ⌚ %2%](#00fb9a)' data_update_complete: '[🔔 Deine Daten wurden aktualisiert!](#00fb9a)' data_update_failed: '[🔔 Ein Fehler ist beim Aktualisieren deiner Daten aufgetreten! Bitte kontaktiere einen Administrator.](#ff7e5e)' +user_registration_complete: '[⭐ User registration complete!](#00fb9a)' data_manager_title: '[Du siehst den Nutzerdaten-Schnappschuss](#00fb9a) [%1%](#00fb9a show_text=&7Versions-UUID:\n&8%2%) [für %3%](#00fb9a bold show_text=&7Spieler-UUID:\n&8%4%)[:](#00fb9a)' data_manager_timestamp: '[⌚ %1%](#ffc43b-#f5c962 show_text=&7Versions-Zeitstempel:\n&8Zeitpunkt der Speicherung der Daten)' data_manager_pinned: '[※ Schnappschuss angeheftet](#d8ff2b show_text=&7Angeheftet:\n&8Dieser Nutzerdaten-Schnappschuss wird nicht automatisch rotiert.)' -data_manager_cause: '[⚑ %1%](#23a825-#36f539 show_text=&7Speicherungsgrund:\n&8Der Grund für das Speichern der Daten)\n' -data_manager_status: '[%1%](red)[/](gray)[%2%](red)[×](gray)[❤](red show_text=&7Lebenspunkte) [%3%](yellow)[×](gray)[🍖](yellow show_text=&7Hungerpunkte) [ʟᴠ](green)[.](gray)[%4%](green show_text=&7XP-Level) [🏹 %5%](dark_aqua show_text=&7Spielmodus)' +data_manager_cause: '[⚑ %1%](#23a825-#36f539 show_text=&7Speicherungsgrund:\n&8Der Grund für das Speichern der Daten)' +data_manager_size: '[⏏ %1%](color=#62a9f5-#7ab8fa show_text=&7Snapshot size:\n&8Estimated file size of the snapshot (in KiB))\n' +data_manger_status: '[%1%](red)[/](gray)[%2%](red)[×](gray)[❤](red show_text=&7Lebenspunkte) [%3%](yellow)[×](gray)[🍖](yellow show_text=&7Hungerpunkte) [ʟᴠ](green)[.](gray)[%4%](green show_text=&7XP-Level) [🏹 %5%](dark_aqua show_text=&7Spielmodus)' data_manager_advancements_statistics: '[⭐ Erfolge: %1%](color=#ffc43b-#f5c962 show_text=&7Erfolge in denen du Fortschritt gemacht hast:\n&8%2%) [⌛ Spielzeit: %3%ʜʀs](color=#62a9f5-#7ab8fa show_text=&7Deine verbrachte Zeit im Spiel\n&8⚠ Basierend auf Spielstatistiken)\n' data_manager_item_buttons: '[Sehen:](gray) [[🪣 Inventar…]](color=#a17b5f-#f5b98c show_text=&7Klicke zum Ansehen run_command=/inventory %1% %2%) [[⌀ Endertruhe…]](#b649c4-#d254ff show_text=&7Klicke zum Ansehen run_command=/enderchest %1% %2%)' data_manager_management_buttons: '[Verwalten:](gray) [[❌ Löschen…]](#ff3300 show_text=&7Klicke, um diesen Nutzerdaten-Schnappschuss zu löschen.\n&8Dies betrifft nicht die aktuellen Nutzerdaten.\n&#ff3300&⚠ Dieser Schritt kann nicht rückgängig gemacht werden! suggest_command=/husksync:userdata delete %1% %2%) [[⏪ Wiederherstellen…]](#00fb9a show_text=&7Klicke, um die Nutzerdaten wiederherzustellen.\n&8Dies wird die Nutzerdaten auf den Stand des Schnappschusses setzen.\n&#ff3300&⚠ Die aktuellen Nutzerdaten von %1% werden überschrieben! suggest_command=/husksync:userdata restore %1% %2%) [[※ Anheften/Loslösen…]](#d8ff2b show_text=&7Klicke, um diesen Nutzerdaten-Schnappschuss anzuheften oder loszulösen\n&8Angeheftete Nutzerdaten-Schnappschüsse werden nicht automatisch rotiert run_command=/userdata pin %1% %2%)' data_manager_system_buttons: '[System:](gray) [[⏷ Daten-Dump…]](dark_gray show_text=&7Klicke, um diesen rohen Nutzerdaten-Schnappschuss in eine Datei zu speichern.\n&8Daten-Dumps können unter ~/plugins/HuskSync/dumps/ gefunden werden. run_command=/husksync:userdata dump %1% %2% file) [[☂ Web-Dump…]](dark_gray show_text=&7Klicke, um diesen rohen Nutzerdaten-Schnappschuss auf den mc-logs Service hochzuladen.\n&8Du erhältst dann eine URL, die die Daten enthält. run_command=/husksync:userdata dump %1% %2% web)' -data_manager_advancements_preview_remaining: '&7und %1% weitere…' +data_manager_advancements_preview_remaining: 'und %1% weitere…' data_list_title: '[Nutzerdaten-Schnappschüsse von %1%:](#00fb9a) [(%2%-%3% von](#00fb9a) [%4%](#00fb9a bold)[)](#00fb9a)\n' -data_list_item: '[%1%](gray show_text=&7Daten-Schnappschuss %3% run_command=/userdata view %6% %4%) [%7%](#d8ff2b show_text=&7Angeheftet:\n&8Angeheftete Schnappschüsse werden nicht automatisch rotiert. run_command=/userdata view %6% %4%) [%2%](color=#ffc43b-#f5c962 show_text=&7Versions-Zeitstempel:&7\n&8Zeitpunkt der Speicherung der Daten run_command=/userdata view %6% %4%) [⚡ %3%](color=#62a9f5-#7ab8fa show_text=&7Versions-UUID:&7\n&8%4% run_command=/userdata view %6% %4%) [⚑ %5%](#23a825-#36f539 show_text=&7Speicherungsgrund:\n&8Der Grund für das Speichern der Daten run_command=/userdata view %6% %4%)' +data_list_item: '[%1%](gray show_text=&7User Data Snapshot for %2%&8⚡ %4% run_command=/userdata view %2% %3%) [%5%](#d8ff2b show_text=&7Pinned:\n&8Pinned snapshots won''t be automatically rotated. run_command=/userdata view %2% %3%) [%6%](color=#ffc43b-#f5c962 show_text=&7Version timestamp:&7\n&8When the data was saved\n&8%7% run_command=/userdata view %2% %3%) [⚑ %8%](#23a825-#36f539 show_text=&7Save cause:\n&8What caused the data to be saved run_command=/userdata view %2% %3%) [⏏ %9%](color=#62a9f5-#7ab8fa show_text=&7Snapshot size:&7\n&8Estimated file size of the snapshot (in KiB) run_command=/userdata view %2% %3%)' data_deleted: '[❌ Nutzerdaten-Schnappschuss erfolgreich gelöscht](#00fb9a) [%1%](#00fb9a show_text=&7Version UUID:\n&8%2%) [für](#00fb9a) [%3%.](#00fb9a show_text=&7Player UUID:\n&8%4%)' data_restored: '[⏪ Erfgreich wiederhergestellt](#00fb9a) [Aktuelle Nutzerdaten des Schnappschusses von %1%](#00fb9a show_text=&7Spieler-UUID:\n&8%2%) [%3%.](#00fb9a show_text=&7Versions-UUID:\n&8%4%)' data_pinned: '[※ Nutzerdaten-Schnappschuss erfolgreich angepinnt](#00fb9a) [%1%](#00fb9a show_text=&7Versions-UUID:\n&8%2%) [für](#00fb9a) [%3%.](#00fb9a show_text=&7Spieler-UUID:\n&8%4%)' @@ -39,3 +33,17 @@ list_page_jumper_button: '[%1%](show_text=&7Springe zu Seite %1% run_command=%2% list_page_jumper_current_page: '[%1%](#00fb9a)' list_page_jumper_separator: ' ' list_page_jumper_group_separator: '…' +reload_complete: '[HuskSync](#00fb9a bold) [| Die Konfigurations- und Sprachdateien wurden neu geladen.](#00fb9a)\n[⚠ Ensure config files are up-to-date on all servers!](#00fb9a)\n[A restart is needed for config changes to take effect.](#00fb9a italic)' +up_to_date: '[HuskSync](#00fb9a bold) [| You are running the latest version of HuskSync (v%1%).](#00fb9a)' +update_available: '[HuskSync](#ff7e5e bold) [| A new version of HuskSync is available: v%1% (running: v%2%).](#ff7e5e)' +error_invalid_syntax: '[Fehler:](#ff3300) [Falsche Syntax. Nutze:](#ff7e5e) [%1%](#ff7e5e italic show_text=&#ff7e5e&Click to suggest suggest_command=%1%)' +error_invalid_player: '[Fehler:](#ff3300) [Es konnte kein Spieler mit diesem Namen gefunden werden.](#ff7e5e)' +error_no_permission: '[Fehler:](#ff3300) [Du hast nicht die benötigten Berechtigungen um diesen Befehl auszuführen](#ff7e5e)' +error_console_command_only: '[Fehler:](#ff3300) [Dieser Befehl kann nur über die Konsole ausgeführt werden.](#ff7e5e)' +error_in_game_command_only: 'Fehler: Dieser Befehl kann nur im Spiel genutzt werden.' +error_no_data_to_display: '[Fehler:](#ff3300) [Es konnten keine Nutzerdaten zum Anzeigen gefunden werden.](#ff7e5e)' +error_invalid_version_uuid: '[Fehler:](#ff3300) [Es konnten keine Nutzerdaten für diese Versions-UUID gefunden werden.](#ff7e5e)' +husksync_command_description: 'Manage the HuskSync plugin' +userdata_command_description: 'View, manage & restore player userdata' +inventory_command_description: 'View & edit a player''s inventory' +enderchest_command_description: 'View & edit a player''s Ender Chest' \ No newline at end of file diff --git a/common/src/main/resources/locales/en-gb.yml b/common/src/main/resources/locales/en-gb.yml index bb2453b9..9b21a1bd 100644 --- a/common/src/main/resources/locales/en-gb.yml +++ b/common/src/main/resources/locales/en-gb.yml @@ -1,31 +1,25 @@ -synchronisation_complete: '[⏵ Data synchronised!](#00fb9a)' -synchronisation_failed: '[⏵ Failed to synchronise your data! Please contact an administrator.](#ff7e5e)' -reload_complete: '[HuskSync](#00fb9a bold) [| Reloaded config and message files.](#00fb9a)' -error_invalid_syntax: '[Error:](#ff3300) [Incorrect syntax. Usage: %1%](#ff7e5e)' -error_invalid_player: '[Error:](#ff3300) [Could not find a player by that name.](#ff7e5e)' -error_no_permission: '[Error:](#ff3300) [You do not have permission to execute this command](#ff7e5e)' -error_console_command_only: '[Error:](#ff3300) [That command can only be run through console](#ff7e5e)' -error_in_game_command_only: 'Error: That command can only be used in-game.' -error_no_data_to_display: '[Error:](#ff3300) [Could not find any user data to display.](#ff7e5e)' -error_invalid_version_uuid: '[Error:](#ff3300) [Could not find any user data for that version UUID.](#ff7e5e)' +synchronization_complete: '[⏵ Data synchronized!](#00fb9a)' +synchronization_failed: '[⏵ Failed to synchronize your data! Please contact an administrator.](#ff7e5e)' inventory_viewer_menu_title: '&0%1%''s Inventory' ender_chest_viewer_menu_title: '&0%1%''s Ender Chest' inventory_viewer_opened: '[Viewing snapshot of](#00fb9a) [%1%](#00fb9a bold)[''s inventory as of ⌚ %2%](#00fb9a)' ender_chest_viewer_opened: '[Viewing snapshot of](#00fb9a) [%1%](#00fb9a bold)[''s Ender Chest as of ⌚ %2%](#00fb9a)' data_update_complete: '[🔔 Your data has been updated!](#00fb9a)' data_update_failed: '[🔔 Failed to update your data! Please contact an administrator.](#ff7e5e)' +user_registration_complete: '[⭐ User registration complete!](#00fb9a)' data_manager_title: '[Viewing user data snapshot](#00fb9a) [%1%](#00fb9a show_text=&7Version UUID:\n&8%2%) [for](#00fb9a) [%3%](#00fb9a bold show_text=&7Player UUID:\n&8%4%)[:](#00fb9a)' data_manager_timestamp: '[⌚ %1%](#ffc43b-#f5c962 show_text=&7Version timestamp:\n&8When the data was saved)' data_manager_pinned: '[※ Snapshot pinned](#d8ff2b show_text=&7Pinned:\n&8This user data snapshot won''t be automatically rotated.)' -data_manager_cause: '[⚑ %1%](#23a825-#36f539 show_text=&7Save cause:\n&8What caused the data to be saved)\n' -data_manager_status: '[%1%](red)[/](gray)[%2%](red)[×](gray)[❤](red show_text=&7Health points) [%3%](yellow)[×](gray)[🍖](yellow show_text=&7Hunger points) [ʟᴠ](green)[.](gray)[%4%](green show_text=&7XP level) [🏹 %5%](dark_aqua show_text=&7Game mode)' +data_manager_cause: '[⚑ %1%](#23a825-#36f539 show_text=&7Save cause:\n&8What caused the data to be saved)' +data_manager_size: '[⏏ %1%](color=#62a9f5-#7ab8fa show_text=&7Snapshot size:\n&8Estimated file size of the snapshot (in KiB))\n' +data_manger_status: '[%1%](red)[/](gray)[%2%](red)[×](gray)[❤](red show_text=&7Health points) [%3%](yellow)[×](gray)[🍖](yellow show_text=&7Hunger points) [ʟᴠ](green)[.](gray)[%4%](green show_text=&7XP level) [🏹 %5%](dark_aqua show_text=&7Game mode)' data_manager_advancements_statistics: '[⭐ Advancements: %1%](color=#ffc43b-#f5c962 show_text=&7Advancements you have progress in:\n&8%2%) [⌛ Play Time: %3%ʜʀs](color=#62a9f5-#7ab8fa show_text=&7In-game play time\n&8⚠ Based on in-game statistics)\n' data_manager_item_buttons: '[View:](gray) [[🪣 Inventory…]](color=#a17b5f-#f5b98c show_text=&7Click to view run_command=/inventory %1% %2%) [[⌀ Ender Chest…]](#b649c4-#d254ff show_text=&7Click to view run_command=/enderchest %1% %2%)' data_manager_management_buttons: '[Manage:](gray) [[❌ Delete…]](#ff3300 show_text=&7Click to delete this snapshot of user data.\n&8This will not affect the user''s current data.\n&#ff3300&⚠ This cannot be undone! suggest_command=/husksync:userdata delete %1% %2%) [[⏪ Restore…]](#00fb9a show_text=&7Click to restore this user data.\n&8This will set the user''s data to this snapshot.\n&#ff3300&⚠ %1%''s current data will be overwritten! suggest_command=/husksync:userdata restore %1% %2%) [[※ Pin/Unpin…]](#d8ff2b show_text=&7Click to pin or unpin this user data snapshot\n&8Pinned snapshots won''t be automatically rotated run_command=/userdata pin %1% %2%)' data_manager_system_buttons: '[System:](gray) [[⏷ File Dump…]](dark_gray show_text=&7Click to dump this raw user data snapshot to a file.\n&8Data dumps can be found in ~/plugins/HuskSync/dumps/ run_command=/husksync:userdata dump %1% %2% file) [[☂ Web Dump…]](dark_gray show_text=&7Click to dump this raw user data snapshot to the mc-logs service\n&8You will be provided with a URL containing the data. run_command=/husksync:userdata dump %1% %2% web)' -data_manager_advancements_preview_remaining: '&7and %1% more…' +data_manager_advancements_preview_remaining: 'and %1% more…' data_list_title: '[%1%''s user data snapshots:](#00fb9a) [(%2%-%3% of](#00fb9a) [%4%](#00fb9a bold)[)](#00fb9a)\n' -data_list_item: '[%1%](gray show_text=&7Data snapshot %3% run_command=/userdata view %6% %4%) [%7%](#d8ff2b show_text=&7Pinned:\n&8Pinned snapshots won''t be automatically rotated. run_command=/userdata view %6% %4%) [%2%](color=#ffc43b-#f5c962 show_text=&7Version timestamp:&7\n&8When the data was saved run_command=/userdata view %6% %4%) [⚡ %3%](color=#62a9f5-#7ab8fa show_text=&7Version UUID:&7\n&8%4% run_command=/userdata view %6% %4%) [⚑ %5%](#23a825-#36f539 show_text=&7Save cause:\n&8What caused the data to be saved run_command=/userdata view %6% %4%)' +data_list_item: '[%1%](gray show_text=&7User Data Snapshot for %2%&8⚡ %4% run_command=/userdata view %2% %3%) [%5%](#d8ff2b show_text=&7Pinned:\n&8Pinned snapshots won''t be automatically rotated. run_command=/userdata view %2% %3%) [%6%](color=#ffc43b-#f5c962 show_text=&7Version timestamp:&7\n&8When the data was saved\n&8%7% run_command=/userdata view %2% %3%) [⚑ %8%](#23a825-#36f539 show_text=&7Save cause:\n&8What caused the data to be saved run_command=/userdata view %2% %3%) [⏏ %9%](color=#62a9f5-#7ab8fa show_text=&7Snapshot size:&7\n&8Estimated file size of the snapshot (in KiB) run_command=/userdata view %2% %3%)' data_deleted: '[❌ Successfully deleted user data snapshot](#00fb9a) [%1%](#00fb9a show_text=&7Version UUID:\n&8%2%) [for](#00fb9a) [%3%.](#00fb9a show_text=&7Player UUID:\n&8%4%)' data_restored: '[⏪ Successfully restored](#00fb9a) [%1%](#00fb9a show_text=&7Player UUID:\n&8%2%)[''s current user data from snapshot](#00fb9a) [%3%.](#00fb9a show_text=&7Version UUID:\n&8%4%)' data_pinned: '[※ Successfully pinned user data snapshot](#00fb9a) [%1%](#00fb9a show_text=&7Version UUID:\n&8%2%) [for](#00fb9a) [%3%.](#00fb9a show_text=&7Player UUID:\n&8%4%)' @@ -38,4 +32,18 @@ list_page_jumpers: '(%1%)' list_page_jumper_button: '[%1%](show_text=&7Jump to page %1% run_command=%2% %1%)' list_page_jumper_current_page: '[%1%](#00fb9a)' list_page_jumper_separator: ' ' -list_page_jumper_group_separator: '…' \ No newline at end of file +list_page_jumper_group_separator: '…' +up_to_date: '[HuskSync](#00fb9a bold) [| You are running the latest version of HuskSync (v%1%).](#00fb9a)' +update_available: '[HuskSync](#ff7e5e bold) [| A new version of HuskSync is available: v%1% (running: v%2%).](#ff7e5e)' +reload_complete: '[HuskSync](#00fb9a bold) [| Reloaded config and message files.](#00fb9a)\n[⚠ Ensure config files are up-to-date on all servers!](#00fb9a)\n[A restart is needed for config changes to take effect.](#00fb9a italic)' +error_invalid_syntax: '[Error:](#ff3300) [Incorrect syntax. Usage:](#ff7e5e) [%1%](#ff7e5e italic show_text=&#ff7e5e&Click to suggest suggest_command=%1%)' +error_invalid_player: '[Error:](#ff3300) [Could not find a player by that name.](#ff7e5e)' +error_no_permission: '[Error:](#ff3300) [You do not have permission to execute this command](#ff7e5e)' +error_console_command_only: '[Error:](#ff3300) [That command can only be run through console](#ff7e5e)' +error_in_game_command_only: 'Error: That command can only be used in-game.' +error_no_data_to_display: '[Error:](#ff3300) [Could not find any user data to display.](#ff7e5e)' +error_invalid_version_uuid: '[Error:](#ff3300) [Could not find any user data for that version UUID.](#ff7e5e)' +husksync_command_description: 'Manage the HuskSync plugin' +userdata_command_description: 'View, manage & restore player userdata' +inventory_command_description: 'View & edit a player''s inventory' +enderchest_command_description: 'View & edit a player''s Ender Chest' \ No newline at end of file diff --git a/common/src/main/resources/locales/es-es.yml b/common/src/main/resources/locales/es-es.yml index 411eeac2..0d5e4db5 100644 --- a/common/src/main/resources/locales/es-es.yml +++ b/common/src/main/resources/locales/es-es.yml @@ -1,31 +1,25 @@ -synchronisation_complete: '[⏵ ¡Datos sincronizados!](#00fb9a)' -synchronisation_failed: '[⏵ Fallo al sincronizar los datos, por favor, contacte con un administrador.](#ff7e5e)' -reload_complete: '[HuskSync](#00fb9a bold) [| Recargada la configuración y los archivos de lenguaje.](#00fb9a)' -error_invalid_syntax: '[Error:](#ff3300) [Sintanxis incorrecta. Usa: %1%](#ff7e5e)' -error_invalid_player: '[Error:](#ff3300) [No se ha podido encontrar un jugador con ese nombre.](#ff7e5e)' -error_no_permission: '[Error:](#ff3300) [No tienes permisos para ejecutar este comando.](#ff7e5e)' -error_console_command_only: '[Error:](#ff3300) [Este comando solo se puede ejecutar desde la consola.](#ff7e5e)' -error_in_game_command_only: 'Error: Ese comando solo se puede utilizar desde el juego.' -error_no_data_to_display: '[Error:](#ff3300) [No se ha podido encontrar informacion sobre el jugador.](#ff7e5e)' -error_invalid_version_uuid: '[Error:](#ff3300) [No se ha podido encontrar informacion sobre la UUID de ese jugador.](#ff7e5e)' +synchronization_complete: '[⏵ ¡Datos sincronizados!](#00fb9a)' +synchronization_failed: '[⏵ Fallo al sincronizar los datos, por favor, contacte con un administrador.](#ff7e5e)' inventory_viewer_menu_title: '&0%1% Inventario de:' ender_chest_viewer_menu_title: '&0%1% Enderchest de:' inventory_viewer_opened: '[Viendo una snapshot de](#00fb9a) [%1%](#00fb9a bold) [Inventario a partir de ⌚ %2%](#00fb9a)' ender_chest_viewer_opened: '[Viendo una snapshot de](#00fb9a) [%1%](#00fb9a bold) [Enderchest a partir de ⌚ %2%](#00fb9a)' data_update_complete: '[🔔 ¡Tus datos han sido actualizados!](#00fb9a)' data_update_failed: '[🔔 Error al actualizar tus datos, por favor, contacte con un administrador.](#ff7e5e)' +user_registration_complete: '[⭐ User registration complete!](#00fb9a)' data_manager_title: '[Viendo una snapshot sobre la informacion del jugador](#00fb9a) [%1%](#00fb9a show_text=&7Version UUID:\n&8%2%) [for](#00fb9a) [%3%](#00fb9a bold show_text=&7Player UUID:\n&8%4%)[:](#00fb9a)' data_manager_timestamp: '[⌚ %1%](#ffc43b-#f5c962 show_text=&7Version del registro:\n&8Cuando los datos se han guardado)' data_manager_pinned: '[※ Snapshot anclada](#d8ff2b show_text=&Anclado:\n&8La informacion de este jugador no se rotará automaticamente.)' -data_manager_cause: '[⚑ %1%](#23a825-#36f539 show_text=&7Motivo del guardado:\n&8Lo que ha causado que se guarde)\n' -data_manager_status: '[%1%](red)[/](gray)[%2%](red)[×](gray)[❤](red show_text=&7Puntos de vida) [%3%](yellow)[×](gray)[🍖](yellow show_text=&7Puntos de hambre) [ʟᴠ](green)[.](gray)[%4%](green show_text=&7Nivel de exp) [🏹 %5%](dark_aqua show_text=&7Gamemode)' +data_manager_cause: '[⚑ %1%](#23a825-#36f539 show_text=&7Motivo del guardado:\n&8Lo que ha causado que se guarde)' +data_manager_size: '[⏏ %1%](color=#62a9f5-#7ab8fa show_text=&7Snapshot size:\n&8Estimated file size of the snapshot (in KiB))\n' +data_manger_status: '[%1%](red)[/](gray)[%2%](red)[×](gray)[❤](red show_text=&7Puntos de vida) [%3%](yellow)[×](gray)[🍖](yellow show_text=&7Puntos de hambre) [ʟᴠ](green)[.](gray)[%4%](green show_text=&7Nivel de exp) [🏹 %5%](dark_aqua show_text=&7Gamemode)' data_manager_advancements_statistics: '[⭐ Logros: %1%](color=#ffc43b-#f5c962 show_text=&7Logros que has conseguido:\n&8%2%) [⌛ Tiempo de juego: %3%ʜʀs](color=#62a9f5-#7ab8fa show_text=&7In-game play time\n&8⚠ Based on in-game statistics)\n' data_manager_item_buttons: '[View:](gray) [[🪣 Inventario…]](color=#a17b5f-#f5b98c show_text=&7Click para ver run_command=/inventory %1% %2%) [[⌀ Enderchest…]](#b649c4-#d254ff show_text=&7Click para ver run_command=/enderchest %1% %2%)' data_manager_management_buttons: '[Manage:](gray) [[❌ Borrar…]](#ff3300 show_text=&7Click para borrar la snapshot del usuario.\n&8Esto no afectará a la informacion actual del jugador.\n&#ff3300&⚠ ¡Esto no se puede deshacer! suggest_command=/husksync:userdata delete %1% %2%) [[⏪ Restaurar…]](#00fb9a show_text=&7Click para restaurar la informacion de este usuario.\n&8Esto hará que la informacion actual cambie por esta snapshot.\n&#ff3300&⚠ %1% la informacion actual será sustituida! suggest_command=/husksync:userdata restore %1% %2%) [[※ Pin/Unpin…]](#d8ff2b show_text=&7Click para anclar/desanclar esta snapshot\n&8Las snapshot ancladas no seran rotadas automaticamente run_command=/userdata pin %1% %2%)' data_manager_system_buttons: '[System:](gray) [[⏷ File Dump…]](dark_gray show_text=&7Click to dump this raw user data snapshot to a file.\n&8Data dumps can be found in ~/plugins/HuskSync/dumps/ run_command=/husksync:userdata dump %1% %2% file) [[☂ Web Dump…]](dark_gray show_text=&7Click to dump this raw user data snapshot to the mc-logs service\n&8You will be provided with a URL containing the data. run_command=/husksync:userdata dump %1% %2% web)' -data_manager_advancements_preview_remaining: '&7y %1% más…' +data_manager_advancements_preview_remaining: 'y %1% más…' data_list_title: '[%1%''s user data snapshots:](#00fb9a) [(%2%-%3% of](#00fb9a) [%4%](#00fb9a bold)[)](#00fb9a)\n' -data_list_item: '[%1%](gray show_text=&7Informacion de la snapshot %3% run_command=/userdata view %6% %4%) [%7%](#d8ff2b show_text=&7Anclado:\n&8Las snapshot ancladas no serán rotadas automaticamente. run_command=/userdata view %6% %4%) [%2%](color=#ffc43b-#f5c962 show_text=&7Version Tiempo:&7\n&8When the data was saved run_command=/userdata view %6% %4%) [⚡ %3%](color=#62a9f5-#7ab8fa show_text=&7Version UUID:&7\n&8%4% run_command=/userdata view %6% %4%) [⚑ %5%](#23a825-#36f539 show_text=&7Causa del guardado:\n&8Lo que sea que haya hecho que se guarde run_command=/userdata view %6% %4%)' +data_list_item: '[%1%](gray show_text=&7User Data Snapshot for %2%&8⚡ %4% run_command=/userdata view %2% %3%) [%5%](#d8ff2b show_text=&7Pinned:\n&8Pinned snapshots won''t be automatically rotated. run_command=/userdata view %2% %3%) [%6%](color=#ffc43b-#f5c962 show_text=&7Version timestamp:&7\n&8When the data was saved\n&8%7% run_command=/userdata view %2% %3%) [⚑ %8%](#23a825-#36f539 show_text=&7Save cause:\n&8What caused the data to be saved run_command=/userdata view %2% %3%) [⏏ %9%](color=#62a9f5-#7ab8fa show_text=&7Snapshot size:&7\n&8Estimated file size of the snapshot (in KiB) run_command=/userdata view %2% %3%)' data_deleted: '[❌ Se ha eliminado correctamente la snapshot del usuario](#00fb9a) [%1%](#00fb9a show_text=&7Version UUID:\n&8%2%) [for](#00fb9a) [%3%.](#00fb9a show_text=&7Player UUID:\n&8%4%)' data_restored: '[⏪ Restaurado correctamente](#00fb9a) [%1%](#00fb9a show_text=&7UUID del jugador:\n&8%2%)[Informacion actual de la snapshot del jugador](#00fb9a) [%3%.](#00fb9a show_text=&7Version UUID:\n&8%4%)' data_pinned: '[※ Se ha anclado perfectamente la snapshot del jugador](#00fb9a) [%1%](#00fb9a show_text=&7Version UUID:\n&8%2%) [for](#00fb9a) [%3%.](#00fb9a show_text=&7UUID del usuario:\n&8%4%)' @@ -38,4 +32,18 @@ list_page_jumpers: '(%1%)' list_page_jumper_button: '[%1%](show_text=&7Jump to page %1% run_command=%2% %1%)' list_page_jumper_current_page: '[%1%](#00fb9a)' list_page_jumper_separator: ' ' -list_page_jumper_group_separator: '…' \ No newline at end of file +list_page_jumper_group_separator: '…' +up_to_date: '[HuskSync](#00fb9a bold) [| You are running the latest version of HuskSync (v%1%).](#00fb9a)' +update_available: '[HuskSync](#ff7e5e bold) [| A new version of HuskSync is available: v%1% (running: v%2%).](#ff7e5e)' +reload_complete: '[HuskSync](#00fb9a bold) [| Recargada la configuración y los archivos de lenguaje.](#00fb9a)\n[⚠ Ensure config files are up-to-date on all servers!](#00fb9a)\n[A restart is needed for config changes to take effect.](#00fb9a italic)' +error_invalid_syntax: '[Error:](#ff3300) [Sintanxis incorrecta. Usa:](#ff7e5e) [%1%](#ff7e5e italic show_text=&#ff7e5e&Click to suggest suggest_command=%1%)' +error_invalid_player: '[Error:](#ff3300) [No se ha podido encontrar un jugador con ese nombre.](#ff7e5e)' +error_no_permission: '[Error:](#ff3300) [No tienes permisos para ejecutar este comando.](#ff7e5e)' +error_console_command_only: '[Error:](#ff3300) [Este comando solo se puede ejecutar desde la consola.](#ff7e5e)' +error_in_game_command_only: 'Error: Ese comando solo se puede utilizar desde el juego.' +error_no_data_to_display: '[Error:](#ff3300) [No se ha podido encontrar informacion sobre el jugador.](#ff7e5e)' +error_invalid_version_uuid: '[Error:](#ff3300) [No se ha podido encontrar informacion sobre la UUID de ese jugador.](#ff7e5e)' +husksync_command_description: 'Manage the HuskSync plugin' +userdata_command_description: 'View, manage & restore player userdata' +inventory_command_description: 'View & edit a player''s inventory' +enderchest_command_description: 'View & edit a player''s Ender Chest' \ No newline at end of file diff --git a/common/src/main/resources/locales/it-it.yml b/common/src/main/resources/locales/it-it.yml index ad67efb3..ae656be3 100644 --- a/common/src/main/resources/locales/it-it.yml +++ b/common/src/main/resources/locales/it-it.yml @@ -1,31 +1,25 @@ -synchronisation_complete: '[⏵ Dati sincronizzati!](#00fb9a)' -synchronisation_failed: '[⏵ Sincronizzazione fallita! Perfavore contatta un amministratore.](#ff7e5e)' -reload_complete: '[HuskSync](#00fb9a bold) [| Configurazione e messaggi ricaricati.](#00fb9a)' -error_invalid_syntax: '[Errore:](#ff3300) [Sintassi errata. Usa: %1%](#ff7e5e)' -error_invalid_player: '[Errore:](#ff3300) [Impossibile trovare un giocatore con questo nome.](#ff7e5e)' -error_no_permission: '[Errore:](#ff3300) [Non hai il permesso di usare questo comando](#ff7e5e)' -error_console_command_only: '[Errore:](#ff3300) [Questo comando può essere eseguito solo dalla](#ff7e5e)' -error_in_game_command_only: 'Errore: That command can only be used in-game.' -error_no_data_to_display: '[Errore:](#ff3300) [Impossibile trovare dati da visualizzare.](#ff7e5e)' -error_invalid_version_uuid: '[Errore:](#ff3300) [Impossibile trovare dati utente per questa versione di UUID.](#ff7e5e)' +synchronization_complete: '[⏵ Dati sincronizzati!](#00fb9a)' +synchronization_failed: '[⏵ Sincronizzazione fallita! Perfavore contatta un amministratore.](#ff7e5e)' inventory_viewer_menu_title: '&0Inventario di %1%' ender_chest_viewer_menu_title: '&0Enderchest di %1%' inventory_viewer_opened: '[Stai vedendo l''istantanea di](#00fb9a) [%1%](#00fb9a bold) [inventario del ⌚ %2%](#00fb9a)' ender_chest_viewer_opened: '[Stai vedendo l''istantanea di](#00fb9a) [%1%](#00fb9a bold) [Ender Chest del ⌚ %2%](#00fb9a)' data_update_complete: '[🔔 I tuoi dati sono stati aggiornati!](#00fb9a)' data_update_failed: '[🔔 Aggiornamento dei tuoi dati fallito! Perfavore contatta un amministratore.](#ff7e5e)' +user_registration_complete: '[⭐ User registration complete!](#00fb9a)' data_manager_title: '[Stai vedendo l''istantanea](#00fb9a) [%1%](#00fb9a show_text=&7Versione di UUID:\n&8%2%) [di](#00fb9a) [%3%](#00fb9a bold show_text=&7Player UUID:\n&8%4%)[:](#00fb9a)' data_manager_timestamp: '[⌚ %1%](#ffc43b-#f5c962 show_text=&7:\n&8Quando i dati sono stati salvati)' data_manager_pinned: '[※ Istantanea fissata](#d8ff2b show_text=&7Pinned:\n&8Quest''istantanea non sarà cancellata automaticamente.)' -data_manager_cause: '[⚑ %1%](#23a825-#36f539 show_text=&7Save cause:\n&8Cosa ha causato il salvataggio dei dati)\n' -data_manager_status: '[%1%](red)[/](gray)[%2%](red)[×](gray)[❤](red show_text=&7Vita) [%3%](yellow)[×](gray)[🍖](yellow show_text=&7Fame) [ʟᴠ](green)[.](gray)[%4%](green show_text=&7Livello di XP) [🏹 %5%](dark_aqua show_text=&7Modalità di gioco)' +data_manager_cause: '[⚑ %1%](#23a825-#36f539 show_text=&7Save cause:\n&8Cosa ha causato il salvataggio dei dati)' +data_manager_size: '[⏏ %1%](color=#62a9f5-#7ab8fa show_text=&7Snapshot size:\n&8Estimated file size of the snapshot (in KiB))\n' +data_manger_status: '[%1%](red)[/](gray)[%2%](red)[×](gray)[❤](red show_text=&7Vita) [%3%](yellow)[×](gray)[🍖](yellow show_text=&7Fame) [ʟᴠ](green)[.](gray)[%4%](green show_text=&7Livello di XP) [🏹 %5%](dark_aqua show_text=&7Modalità di gioco)' data_manager_advancements_statistics: '[⭐ Progressi: %1%](color=#ffc43b-#f5c962 show_text=&7Progressi compiuti in:\n&8%2%) [⌛ Tempo di gioco: %3%ʜʀs](color=#62a9f5-#7ab8fa show_text=&7Tempo di gioco\n&8⚠ Basato sulle statistiche di gioco)\n' data_manager_item_buttons: '[View:](gray) [[🪣 Inventario…]](color=#a17b5f-#f5b98c show_text=&7Clicca per visualizzare run_command=/inventory %1% %2%) [[⌀ Ender Chest…]](#b649c4-#d254ff show_text=&7Clicca per visualizzare run_command=/enderchest %1% %2%)' data_manager_management_buttons: '[Gestisci:](gray) [[❌ Cancella…]](#ff3300 show_text=&7Fare clic per eliminare questa istantanea.\n&8Questo non influisce sui dati attuali dell''utente.\n&#ff3300&⚠ Questo non può essere annullato! suggest_command=/husksync:userdata delete %1% %2%) [[⏪ Ripristina…]](#00fb9a show_text=&7Clicca per ripristinare i dati dell''utente.\n&8I dati dell''utente saranno ripristinati a quest''istantanea.\n&#ff3300&⚠ I dati di %1% saranno sovrascritti! suggest_command=/husksync:userdata restore %1% %2%) [[※ fissa/sblocca...]](#d8ff2b show_text=&7Clicca per fissare o sbloccare quest''istantanea\n&8Le istantanee fissate non saranno cancellate automaticamente run_command=/userdata pin %1% %2%)' data_manager_system_buttons: '[Sistema:](gray) [[⏷ Dump del File…]](dark_gray show_text=&7Clicca per ottenere il dump dei dati del giocatore.\n&8I dati salvati sono posizioanti nella cartella ~/plugins/HuskSync/dumps/ run_command=/husksync:userdata dump %1% %2% file) [[☂ Dump su Web…]](dark_gray show_text=&7Clicca per ottenere il dump del file su mc-logs\n&8 Ti verrà consegnato l''url per visionare il dump. run_command=/husksync:userdata dump %1% %2% web)' -data_manager_advancements_preview_remaining: '&7e %1% altro…' +data_manager_advancements_preview_remaining: 'e %1% altro…' data_list_title: '[Lista delle istantanee di %1%:](#00fb9a) [(%2%-%3% of](#00fb9a) [%4%](#00fb9a bold)[)](#00fb9a)\n' -data_list_item: '[%1%](gray show_text=&7Istantanea dei dati %3% run_command=/userdata view %6% %4%) [%7%](#d8ff2b show_text=&7Fissato:\n&8Le istantanee fissate non saranno cancellate automaticamente. run_command=/userdata view %6% %4%) [%2%](color=#ffc43b-#f5c962 show_text=&7Timestamp della versione:&7\n&8Quando i dati sono stati salvati run_command=/userdata view %6% %4%) [⚡ %3%](color=#62a9f5-#7ab8fa show_text=&7Versione di UUID:&7\n&8%4% run_command=/userdata view %6% %4%) [⚑ %5%](#23a825-#36f539 show_text=&7Causa del salvataggio:\n&8Cosa ha causato il salvataggio dei dati run_command=/userdata view %6% %4%)' +data_list_item: '[%1%](gray show_text=&7User Data Snapshot for %2%&8⚡ %4% run_command=/userdata view %2% %3%) [%5%](#d8ff2b show_text=&7Pinned:\n&8Pinned snapshots won''t be automatically rotated. run_command=/userdata view %2% %3%) [%6%](color=#ffc43b-#f5c962 show_text=&7Version timestamp:&7\n&8When the data was saved\n&8%7% run_command=/userdata view %2% %3%) [⚑ %8%](#23a825-#36f539 show_text=&7Save cause:\n&8What caused the data to be saved run_command=/userdata view %2% %3%) [⏏ %9%](color=#62a9f5-#7ab8fa show_text=&7Snapshot size:&7\n&8Estimated file size of the snapshot (in KiB) run_command=/userdata view %2% %3%)' data_deleted: '[❌ Istantanea eliminata con successo](#00fb9a) [%1%](#00fb9a show_text=&7Versione di UUID:\n&8%2%) [per](#00fb9a) [%3%.](#00fb9a show_text=&7Player UUID:\n&8%4%)' data_restored: '[⏪ Ripristato con successo](#00fb9a) [Dati dall''istantanea di](#00fb9a)[%1%](#00fb9a show_text=&7Player UUID:\n&8%2%) [%3%.](#00fb9a show_text=&7Versione di UUID:\n&8%4%)' data_pinned: '[※ Instantanea fissata](#00fb9a) [%1%](#00fb9a show_text=&7Versione di UUID:\n&8%2%) [per](#00fb9a) [%3%.](#00fb9a show_text=&7Player UUID:\n&8%4%)' @@ -39,3 +33,17 @@ list_page_jumper_button: '[%1%](show_text=&7Vai alla pagina %1% run_command=%2% list_page_jumper_current_page: '[%1%](#00fb9a)' list_page_jumper_separator: ' ' list_page_jumper_group_separator: '…' +up_to_date: '[HuskSync](#00fb9a bold) [| Il plugin è all''ultima versione disponibile (v%1%).](#00fb9a)' +update_available: '[HuskSync](#ff7e5e bold) [| Disponibile una nuova versione: v%1% (running: v%2%).](#ff7e5e)' +reload_complete: '[HuskSync](#00fb9a bold) [| Configurazione e messaggi ricaricati.](#00fb9a)\n[⚠ Ensure config files are up-to-date on all servers!](#00fb9a)\n[A restart is needed for config changes to take effect.](#00fb9a italic)' +error_invalid_syntax: '[Errore:](#ff3300) [Sintassi errata. Usa:](#ff7e5e) [%1%](#ff7e5e italic show_text=&#ff7e5e&Click to suggest suggest_command=%1%)' +error_invalid_player: '[Errore:](#ff3300) [Impossibile trovare un giocatore con questo nome.](#ff7e5e)' +error_no_permission: '[Errore:](#ff3300) [Non hai il permesso di usare questo comando](#ff7e5e)' +error_console_command_only: '[Errore:](#ff3300) [Questo comando può essere eseguito solo dalla](#ff7e5e)' +error_in_game_command_only: 'Errore: That command can only be used in-game.' +error_no_data_to_display: '[Errore:](#ff3300) [Impossibile trovare dati da visualizzare.](#ff7e5e)' +error_invalid_version_uuid: '[Errore:](#ff3300) [Impossibile trovare dati utente per questa versione di UUID.](#ff7e5e)' +husksync_command_description: 'Manage the HuskSync plugin' +userdata_command_description: 'View, manage & restore player userdata' +inventory_command_description: 'View & edit a player''s inventory' +enderchest_command_description: 'View & edit a player''s Ender Chest' \ No newline at end of file diff --git a/common/src/main/resources/locales/ja-jp.yml b/common/src/main/resources/locales/ja-jp.yml index f0b51241..89704925 100644 --- a/common/src/main/resources/locales/ja-jp.yml +++ b/common/src/main/resources/locales/ja-jp.yml @@ -1,31 +1,25 @@ -synchronisation_complete: '[⏵データが同期されました!](#00fb9a)' -synchronisation_failed: '[⏵ Failed to synchronise your data! Please contact an administrator.](#ff7e5e)' -reload_complete: '[HuskSync](#00fb9a bold) [| 設定ファイルとメッセージファイルを再読み込みしました。](#00fb9a)' -error_invalid_syntax: '[Error:](#ff3300) [構文が正しくありません。使用法: %1%](#ff7e5e)' -error_invalid_player: '[Error:](#ff3300) [そのプレイヤーは見つかりませんでした](#ff7e5e)' -error_no_permission: '[Error:](#ff3300) [このコマンドを実行する権限がありません](#ff7e5e)' -error_console_command_only: '[Error:](#ff3300) [そのコマンドは%1%コンソールからのみ実行できます](#ff7e5e)' -error_in_game_command_only: 'Error: That command can only be used in-game.' -error_no_data_to_display: '[Error:](#ff3300) [Could not find any user data to display.](#ff7e5e)' -error_invalid_version_uuid: '[Error:](#ff3300) [Could not find any user data for that version UUID.](#ff7e5e)' +synchronization_complete: '[⏵データが同期されました!](#00fb9a)' +synchronization_failed: '[⏵ Failed to synchronize your data! Please contact an administrator.](#ff7e5e)' inventory_viewer_menu_title: '&0%1%''s Inventory' ender_chest_viewer_menu_title: '&0%1%''s Ender Chest' inventory_viewer_opened: '[Viewing snapshot of](#00fb9a) [%1%](#00fb9a bold)[''s inventory as of ⌚ %2%](#00fb9a)' ender_chest_viewer_opened: '[Viewing snapshot of](#00fb9a) [%1%](#00fb9a bold)[''s Ender Chest as of ⌚ %2%](#00fb9a)' data_update_complete: '[🔔 Your data has been updated!](#00fb9a)' data_update_failed: '[🔔 Failed to update your data! Please contact an administrator.](#ff7e5e)' +user_registration_complete: '[⭐ User registration complete!](#00fb9a)' data_manager_title: '[Viewing user data snapshot](#00fb9a) [%1%](#00fb9a show_text=&7Version UUID:\n&8%2%) [for](#00fb9a) [%3%](#00fb9a bold show_text=&7Player UUID:\n&8%4%)[:](#00fb9a)' data_manager_timestamp: '[⌚ %1%](#ffc43b-#f5c962 show_text=&7Version timestamp:\n&8When the data was saved)' data_manager_pinned: '[※ Snapshot pinned](#d8ff2b show_text=&7Pinned:\n&8This user data snapshot won''t be automatically rotated.)' -data_manager_cause: '[⚑ %1%](#23a825-#36f539 show_text=&7Save cause:\n&8What caused the data to be saved)\n' -data_manager_status: '[%1%](red)[/](gray)[%2%](red)[×](gray)[❤](red show_text=&7Health points) [%3%](yellow)[×](gray)[🍖](yellow show_text=&7Hunger points) [ʟᴠ](green)[.](gray)[%4%](green show_text=&7XP level) [🏹 %5%](dark_aqua show_text=&7Game mode)' +data_manager_cause: '[⚑ %1%](#23a825-#36f539 show_text=&7Save cause:\n&8What caused the data to be saved)' +data_manager_size: '[⏏ %1%](color=#62a9f5-#7ab8fa show_text=&7Snapshot size:\n&8Estimated file size of the snapshot (in KiB))\n' +data_manger_status: '[%1%](red)[/](gray)[%2%](red)[×](gray)[❤](red show_text=&7Health points) [%3%](yellow)[×](gray)[🍖](yellow show_text=&7Hunger points) [ʟᴠ](green)[.](gray)[%4%](green show_text=&7XP level) [🏹 %5%](dark_aqua show_text=&7Game mode)' data_manager_advancements_statistics: '[⭐ Advancements: %1%](color=#ffc43b-#f5c962 show_text=&7Advancements you have progress in:\n&8%2%) [⌛ Play Time: %3%ʜʀs](color=#62a9f5-#7ab8fa show_text=&7In-game play time\n&8⚠ Based on in-game statistics)\n' data_manager_item_buttons: '[View:](gray) [[🪣 Inventory…]](color=#a17b5f-#f5b98c show_text=&7Click to view run_command=/inventory %1% %2%) [[⌀ Ender Chest…]](#b649c4-#d254ff show_text=&7Click to view run_command=/enderchest %1% %2%)' data_manager_management_buttons: '[Manage:](gray) [[❌ Delete…]](#ff3300 show_text=&7Click to delete this snapshot of user data.\n&8This will not affect the user''s current data.\n&#ff3300&⚠ This cannot be undone! suggest_command=/husksync:userdata delete %1% %2%) [[⏪ Restore…]](#00fb9a show_text=&7Click to restore this user data.\n&8This will set the user''s data to this snapshot.\n&#ff3300&⚠ %1%''s current data will be overwritten! suggest_command=/husksync:userdata restore %1% %2%) [[※ Pin/Unpin…]](#d8ff2b show_text=&7Click to pin or unpin this user data snapshot\n&8Pinned snapshots won''t be automatically rotated run_command=/userdata pin %1% %2%)' data_manager_system_buttons: '[System:](gray) [[⏷ File Dump…]](dark_gray show_text=&7Click to dump this raw user data snapshot to a file.\n&8Data dumps can be found in ~/plugins/HuskSync/dumps/ run_command=/husksync:userdata dump %1% %2% file) [[☂ Web Dump…]](dark_gray show_text=&7Click to dump this raw user data snapshot to the mc-logs service\n&8You will be provided with a URL containing the data. run_command=/husksync:userdata dump %1% %2% web)' -data_manager_advancements_preview_remaining: '&7and %1% more…' +data_manager_advancements_preview_remaining: 'and %1% more…' data_list_title: '[%1%''s user data snapshots:](#00fb9a) [(%2%-%3% of](#00fb9a) [%4%](#00fb9a bold)[)](#00fb9a)\n' -data_list_item: '[%1%](gray show_text=&7Data snapshot %3% run_command=/userdata view %6% %4%) [%7%](#d8ff2b show_text=&7Pinned:\n&8Pinned snapshots won''t be automatically rotated. run_command=/userdata view %6% %4%) [%2%](color=#ffc43b-#f5c962 show_text=&7Version timestamp:&7\n&8When the data was saved run_command=/userdata view %6% %4%) [⚡ %3%](color=#62a9f5-#7ab8fa show_text=&7Version UUID:&7\n&8%4% run_command=/userdata view %6% %4%) [⚑ %5%](#23a825-#36f539 show_text=&7Save cause:\n&8What caused the data to be saved run_command=/userdata view %6% %4%)' +data_list_item: '[%1%](gray show_text=&7User Data Snapshot for %2%&8⚡ %4% run_command=/userdata view %2% %3%) [%5%](#d8ff2b show_text=&7Pinned:\n&8Pinned snapshots won''t be automatically rotated. run_command=/userdata view %2% %3%) [%6%](color=#ffc43b-#f5c962 show_text=&7Version timestamp:&7\n&8When the data was saved\n&8%7% run_command=/userdata view %2% %3%) [⚑ %8%](#23a825-#36f539 show_text=&7Save cause:\n&8What caused the data to be saved run_command=/userdata view %2% %3%) [⏏ %9%](color=#62a9f5-#7ab8fa show_text=&7Snapshot size:&7\n&8Estimated file size of the snapshot (in KiB) run_command=/userdata view %2% %3%)' data_deleted: '[❌ Successfully deleted user data snapshot](#00fb9a) [%1%](#00fb9a show_text=&7Version UUID:\n&8%2%) [for](#00fb9a) [%3%.](#00fb9a show_text=&7Player UUID:\n&8%4%)' data_restored: '[⏪ Successfully restored](#00fb9a) [%1%](#00fb9a show_text=&7Player UUID:\n&8%2%)[''s current user data from snapshot](#00fb9a) [%3%.](#00fb9a show_text=&7Version UUID:\n&8%4%)' data_pinned: '[※ Successfully pinned user data snapshot](#00fb9a) [%1%](#00fb9a show_text=&7Version UUID:\n&8%2%) [for](#00fb9a) [%3%.](#00fb9a show_text=&7Player UUID:\n&8%4%)' @@ -38,4 +32,18 @@ list_page_jumpers: '(%1%)' list_page_jumper_button: '[%1%](show_text=&7Jump to page %1% run_command=%2% %1%)' list_page_jumper_current_page: '[%1%](#00fb9a)' list_page_jumper_separator: ' ' -list_page_jumper_group_separator: '…' \ No newline at end of file +list_page_jumper_group_separator: '…' +up_to_date: '[HuskSync](#00fb9a bold) [| HuskSyncの最新バージョンを実行しています(v%1%).](#00fb9a)' +update_available: '[HuskSync](#ff7e5e bold) [| HuskSyncの最新バージョンが更新されています: v%1% (running: v%2%).](#ff7e5e)' +reload_complete: '[HuskSync](#00fb9a bold) [| 設定ファイルとメッセージファイルを再読み込みしました。](#00fb9a)\n[⚠ Ensure config files are up-to-date on all servers!](#00fb9a)\n[A restart is needed for config changes to take effect.](#00fb9a italic)' +error_invalid_syntax: '[Error:](#ff3300) [構文が正しくありません。使用法:](#ff7e5e) [%1%](#ff7e5e italic show_text=&#ff7e5e&Click to suggest suggest_command=%1%)' +error_invalid_player: '[Error:](#ff3300) [そのプレイヤーは見つかりませんでした](#ff7e5e)' +error_no_permission: '[Error:](#ff3300) [このコマンドを実行する権限がありません](#ff7e5e)' +error_console_command_only: '[Error:](#ff3300) [そのコマンドは%1%コンソールからのみ実行できます](#ff7e5e)' +error_in_game_command_only: 'Error: That command can only be used in-game.' +error_no_data_to_display: '[Error:](#ff3300) [Could not find any user data to display.](#ff7e5e)' +error_invalid_version_uuid: '[Error:](#ff3300) [Could not find any user data for that version UUID.](#ff7e5e)' +husksync_command_description: 'Manage the HuskSync plugin' +userdata_command_description: 'View, manage & restore player userdata' +inventory_command_description: 'View & edit a player''s inventory' +enderchest_command_description: 'View & edit a player''s Ender Chest' \ No newline at end of file diff --git a/common/src/main/resources/locales/pt-br.yml b/common/src/main/resources/locales/pt-br.yml index 296d7f6e..b029551c 100644 --- a/common/src/main/resources/locales/pt-br.yml +++ b/common/src/main/resources/locales/pt-br.yml @@ -1,31 +1,25 @@ -synchronisation_complete: '[⏵ Dados sincronizados!](#00fb9a)' -synchronisation_failed: '[⏵ Falha na sincronização de seus dados! Por favor entre em contato com um administrador.](#ff7e5e)' -reload_complete: '[HuskSync](#00fb9a bold) [| Arquivos de configuração e mensagens recarregados.](#00fb9a)' -error_invalid_syntax: '[Error:](#ff3300) [Sintaxe incorreta. Utilize: %1%](#ff7e5e)' -error_invalid_player: '[Error:](#ff3300) [Não foi possível encontrar um jogador com esse nome.](#ff7e5e)' -error_no_permission: '[Error:](#ff3300) [Você não tem permissão para executar este comando](#ff7e5e)' -error_console_command_only: '[Error:](#ff3300) [Esse comando só pode ser executado através do console](#ff7e5e)' -error_in_game_command_only: 'Error: Esse comando só pode ser usado dentro do jogo.' -error_no_data_to_display: '[Error:](#ff3300) [Não encontramos nenhuma informação deste jogador para exibir.](#ff7e5e)' -error_invalid_version_uuid: '[Error:](#ff3300) [Não foi possível encontrar nenhuma informação deste jogador para essa versão UUID.](#ff7e5e)' +synchronization_complete: '[⏵ Dados sincronizados!](#00fb9a)' +synchronization_failed: '[⏵ Falha na sincronização de seus dados! Por favor entre em contato com um administrador.](#ff7e5e)' inventory_viewer_menu_title: '&0%1%''s Inventory' ender_chest_viewer_menu_title: '&0%1%''s Ender Chest' inventory_viewer_opened: '[Visualizando snapshot de](#00fb9a) [%1%](#00fb9a bold) [''s inventory a partir de ⌚ %2%](#00fb9a)' ender_chest_viewer_opened: '[Visualizando snapshot de](#00fb9a) [%1%](#00fb9a bold) [''s Ender Chest a partir de ⌚ %2%](#00fb9a)' data_update_complete: '[🔔 Seus dados foram atualizados!](#00fb9a)' data_update_failed: '[🔔 Falha na atualização de seus dados! Por favor entre em contato com um administrador.](#ff7e5e)' +user_registration_complete: '[⭐ User registration complete!](#00fb9a)' data_manager_title: '[Visualizando snapshot dos dados do usuário](#00fb9a) [%1%](#00fb9a show_text=&7Version UUID:\n&8%2%) [for](#00fb9a) [%3%](#00fb9a bold show_text=&7Player UUID:\n&8%4%)[:](#00fb9a)' data_manager_timestamp: '[⌚ %1%](#ffc43b-#f5c962 show_text=&7Version timestamp:\n&8Quando os dados foram salvos)' data_manager_pinned: '[※ Snapshot marcada](#d8ff2b show_text=&7Marcada:\n&8Essa snapshot de dados do usuário não será girada automaticamente.)' -data_manager_cause: '[⚑ %1%](#23a825-#36f539 show_text=&7Causa do salvamento:\n&8O motivo para que os dados fossem salvos)\n' -data_manager_status: '[%1%](red)[/](gray)[%2%](red)[×](gray)[❤](red show_text=&7Pontos de Vida) [%3%](yellow)[×](gray)[🍖](yellow show_text=&7Pontos de vida) [ʟᴠ](green)[.](gray)[%4%](green show_text=&7XP level) [🏹 %5%](dark_aqua show_text=&7Game mode)' +data_manager_cause: '[⚑ %1%](#23a825-#36f539 show_text=&7Causa do salvamento:\n&8O motivo para que os dados fossem salvos)' +data_manager_size: '[⏏ %1%](color=#62a9f5-#7ab8fa show_text=&7Snapshot size:\n&8Estimated file size of the snapshot (in KiB))\n' +data_manger_status: '[%1%](red)[/](gray)[%2%](red)[×](gray)[❤](red show_text=&7Pontos de Vida) [%3%](yellow)[×](gray)[🍖](yellow show_text=&7Pontos de vida) [ʟᴠ](green)[.](gray)[%4%](green show_text=&7XP level) [🏹 %5%](dark_aqua show_text=&7Game mode)' data_manager_advancements_statistics: '[⭐ Progressos: %1%](color=#ffc43b-#f5c962 show_text=&7Progressos que você tem realizado em:\n&8%2%) [⌛ Tempo de jogo: %3%ʜʀs](color=#62a9f5-#7ab8fa show_text=&7Tempo de jogo dentro do jogo\n&8⚠ Com base em estatísticas dentro do jogo)\n' data_manager_item_buttons: '[View:](gray) [[🪣 Inventory…]](color=#a17b5f-#f5b98c show_text=&7Clique para ver run_command=/inventory %1% %2%) [[⌀ Ender Chest…]](#b649c4-#d254ff show_text=&7Clique para ver run_command=/enderchest %1% %2%)' data_manager_management_buttons: '[Gerenciar:](gray) [[❌ Deletar…]](#ff3300 show_text=&7Clique para deletar esta snapshot de dados do usuário\n&8Isto não afetará os dados atuais do usuário.\n&#ff3300&⚠ Isto não pode ser desfeito! suggest_command=/husksync:userdata delete %1% %2%) [[⏪ Restaurar…]](#00fb9a show_text=&7Clique para restaurar estes dados do usuário.\n&8Isto substituirá os dados atuais do usuário para os da snapshot.\n&#ff3300&⚠ %1%''s os dados atuais serão substituídos! suggest_command=/husksync:userdata restore %1% %2%) [[※ Marcar/Desmarcar…]](#d8ff2b show_text=&7Clique para marcar ou desmarcar este snapshot de dados do usuário\n&8Snapshots marcadas não serão giradas automaticamente run_command=/userdata pin %1% %2%)' data_manager_system_buttons: '[System:](gray) [[⏷ File Dump…]](dark_gray show_text=&7Click to dump this raw user data snapshot to a file.\n&8Data dumps can be found in ~/plugins/HuskSync/dumps/ run_command=/husksync:userdata dump %1% %2% file) [[☂ Web Dump…]](dark_gray show_text=&7Click to dump this raw user data snapshot to the mc-logs service\n&8You will be provided with a URL containing the data. run_command=/husksync:userdata dump %1% %2% web)' -data_manager_advancements_preview_remaining: '&7e %1% mais…' +data_manager_advancements_preview_remaining: 'e %1% mais…' data_list_title: '[%1%''s user data snapshots:](#00fb9a) [(%2%-%3% of](#00fb9a) [%4%](#00fb9a bold)[)](#00fb9a)\n' -data_list_item: '[%1%](gray show_text=&7Snapshot data %3% run_command=/userdata view %6% %4%) [%7%](#d8ff2b show_text=&7Marcado:\n&8Snapshots marcadas não serão giradas automaticamente. run_command=/userdata view %6% %4%) [%2%](color=#ffc43b-#f5c962 show_text=&7Version timestamp:&7\n&8Quando os dados foram salvos run_command=/userdata view %6% %4%) [⚡ %3%](color=#62a9f5-#7ab8fa show_text=&7Version UUID:&7\n&8%4% run_command=/userdata view %6% %4%) [⚑ %5%](#23a825-#36f539 show_text=&7Causa do salvamento:\n&8O motivo para que os dados fossem salvos run_command=/userdata view %6% %4%)' +data_list_item: '[%1%](gray show_text=&7User Data Snapshot for %2%&8⚡ %4% run_command=/userdata view %2% %3%) [%5%](#d8ff2b show_text=&7Pinned:\n&8Pinned snapshots won''t be automatically rotated. run_command=/userdata view %2% %3%) [%6%](color=#ffc43b-#f5c962 show_text=&7Version timestamp:&7\n&8When the data was saved\n&8%7% run_command=/userdata view %2% %3%) [⚑ %8%](#23a825-#36f539 show_text=&7Save cause:\n&8What caused the data to be saved run_command=/userdata view %2% %3%) [⏏ %9%](color=#62a9f5-#7ab8fa show_text=&7Snapshot size:&7\n&8Estimated file size of the snapshot (in KiB) run_command=/userdata view %2% %3%)' data_deleted: '[❌ Snapshot de dados do usuário deletada com sucesso](#00fb9a) [%1%](#00fb9a show_text=&7Version UUID:\n&8%2%) [for](#00fb9a) [%3%.](#00fb9a show_text=&7Player UUID:\n&8%4%)' data_restored: '[⏪ Restaurada com sucesso](#00fb9a) [%1%](#00fb9a show_text=&7Player UUID:\n&8%2%)[''s current user data from snapshot](#00fb9a) [%3%.](#00fb9a show_text=&7Version UUID:\n&8%4%)' data_pinned: '[※ Snapshot de dados do usuário marcada com sucesso](#00fb9a) [%1%](#00fb9a show_text=&7Version UUID:\n&8%2%) [for](#00fb9a) [%3%.](#00fb9a show_text=&7Player UUID:\n&8%4%)' @@ -38,4 +32,18 @@ list_page_jumpers: '(%1%)' list_page_jumper_button: '[%1%](show_text=&7Jump to page %1% run_command=%2% %1%)' list_page_jumper_current_page: '[%1%](#00fb9a)' list_page_jumper_separator: ' ' -list_page_jumper_group_separator: '…' \ No newline at end of file +list_page_jumper_group_separator: '…' +up_to_date: '[HuskSync](#00fb9a bold) [| You are running the latest version of HuskSync (v%1%).](#00fb9a)' +update_available: '[HuskSync](#ff7e5e bold) [| A new version of HuskSync is available: v%1% (running: v%2%).](#ff7e5e)' +reload_complete: '[HuskSync](#00fb9a bold) [| Arquivos de configuração e mensagens recarregados.](#00fb9a)\n[⚠ Ensure config files are up-to-date on all servers!](#00fb9a)\n[A restart is needed for config changes to take effect.](#00fb9a italic)' +error_invalid_syntax: '[Error:](#ff3300) [Sintaxe incorreta. Utilize:](#ff7e5e) [%1%](#ff7e5e italic show_text=&#ff7e5e&Click to suggest suggest_command=%1%)' +error_invalid_player: '[Error:](#ff3300) [Não foi possível encontrar um jogador com esse nome.](#ff7e5e)' +error_no_permission: '[Error:](#ff3300) [Você não tem permissão para executar este comando](#ff7e5e)' +error_console_command_only: '[Error:](#ff3300) [Esse comando só pode ser executado através do console](#ff7e5e)' +error_in_game_command_only: 'Error: Esse comando só pode ser usado dentro do jogo.' +error_no_data_to_display: '[Error:](#ff3300) [Não encontramos nenhuma informação deste jogador para exibir.](#ff7e5e)' +error_invalid_version_uuid: '[Error:](#ff3300) [Não foi possível encontrar nenhuma informação deste jogador para essa versão UUID.](#ff7e5e)' +husksync_command_description: 'Manage the HuskSync plugin' +userdata_command_description: 'View, manage & restore player userdata' +inventory_command_description: 'View & edit a player''s inventory' +enderchest_command_description: 'View & edit a player''s Ender Chest' \ No newline at end of file diff --git a/common/src/main/resources/locales/uk-ua.yml b/common/src/main/resources/locales/uk-ua.yml index 03f0d81c..c6438974 100644 --- a/common/src/main/resources/locales/uk-ua.yml +++ b/common/src/main/resources/locales/uk-ua.yml @@ -1,31 +1,25 @@ -synchronisation_complete: '[⏵ Дані синхронізовано!](#00fb9a)' -synchronisation_failed: '[⏵ Failed to synchronise your data! Please contact an administrator.](#ff7e5e)' -reload_complete: '[HuskSync](#00fb9a bold) [| Перезавантажено конфіґ та файли повідомлень.](#00fb9a)' -error_invalid_syntax: '[Помилка:](#ff3300) [Неправильний синтакс. Використання: %1%](#ff7e5e)' -error_invalid_player: '[Помилка:](#ff3300) [Гравця не знайдено](#ff7e5e)' -error_no_permission: '[Помилка:](#ff3300) [Ввас немає дозволу на використання цієї команди](#ff7e5e)' -error_console_command_only: '[Помилка:](#ff3300) [Ця команда може бути використана лише з допомогою %1% консолі](#ff7e5e)' -error_in_game_command_only: 'Error: That command can only be used in-game.' -error_no_data_to_display: '[Error:](#ff3300) [Could not find any user data to display.](#ff7e5e)' -error_invalid_version_uuid: '[Error:](#ff3300) [Could not find any user data for that version UUID.](#ff7e5e)' +synchronization_complete: '[⏵ Дані синхронізовано!](#00fb9a)' +synchronization_failed: '[⏵ Failed to synchronize your data! Please contact an administrator.](#ff7e5e)' inventory_viewer_menu_title: '&0%1%''s Inventory' ender_chest_viewer_menu_title: '&0%1%''s Ender Chest' inventory_viewer_opened: '[Viewing snapshot of](#00fb9a) [%1%](#00fb9a bold)[''s inventory as of ⌚ %2%](#00fb9a)' ender_chest_viewer_opened: '[Viewing snapshot of](#00fb9a) [%1%](#00fb9a bold)[''s Ender Chest as of ⌚ %2%](#00fb9a)' data_update_complete: '[🔔 Your data has been updated!](#00fb9a)' data_update_failed: '[🔔 Failed to update your data! Please contact an administrator.](#ff7e5e)' +user_registration_complete: '[⭐ User registration complete!](#00fb9a)' data_manager_title: '[Viewing user data snapshot](#00fb9a) [%1%](#00fb9a show_text=&7Version UUID:\n&8%2%) [for](#00fb9a) [%3%](#00fb9a bold show_text=&7Player UUID:\n&8%4%)[:](#00fb9a)' data_manager_timestamp: '[⌚ %1%](#ffc43b-#f5c962 show_text=&7Version timestamp:\n&8When the data was saved)' data_manager_pinned: '[※ Snapshot pinned](#d8ff2b show_text=&7Pinned:\n&8This user data snapshot won''t be automatically rotated.)' -data_manager_cause: '[⚑ %1%](#23a825-#36f539 show_text=&7Save cause:\n&8What caused the data to be saved)\n' -data_manager_status: '[%1%](red)[/](gray)[%2%](red)[×](gray)[❤](red show_text=&7Health points) [%3%](yellow)[×](gray)[🍖](yellow show_text=&7Hunger points) [ʟᴠ](green)[.](gray)[%4%](green show_text=&7XP level) [🏹 %5%](dark_aqua show_text=&7Game mode)' +data_manager_cause: '[⚑ %1%](#23a825-#36f539 show_text=&7Save cause:\n&8What caused the data to be saved)' +data_manager_size: '[⏏ %1%](color=#62a9f5-#7ab8fa show_text=&7Snapshot size:\n&8Estimated file size of the snapshot (in KiB))\n' +data_manger_status: '[%1%](red)[/](gray)[%2%](red)[×](gray)[❤](red show_text=&7Health points) [%3%](yellow)[×](gray)[🍖](yellow show_text=&7Hunger points) [ʟᴠ](green)[.](gray)[%4%](green show_text=&7XP level) [🏹 %5%](dark_aqua show_text=&7Game mode)' data_manager_advancements_statistics: '[⭐ Advancements: %1%](color=#ffc43b-#f5c962 show_text=&7Advancements you have progress in:\n&8%2%) [⌛ Play Time: %3%ʜʀs](color=#62a9f5-#7ab8fa show_text=&7In-game play time\n&8⚠ Based on in-game statistics)\n' data_manager_item_buttons: '[View:](gray) [[🪣 Inventory…]](color=#a17b5f-#f5b98c show_text=&7Click to view run_command=/inventory %1% %2%) [[⌀ Ender Chest…]](#b649c4-#d254ff show_text=&7Click to view run_command=/enderchest %1% %2%)' data_manager_management_buttons: '[Manage:](gray) [[❌ Delete…]](#ff3300 show_text=&7Click to delete this snapshot of user data.\n&8This will not affect the user''s current data.\n&#ff3300&⚠ This cannot be undone! suggest_command=/husksync:userdata delete %1% %2%) [[⏪ Restore…]](#00fb9a show_text=&7Click to restore this user data.\n&8This will set the user''s data to this snapshot.\n&#ff3300&⚠ %1%''s current data will be overwritten! suggest_command=/husksync:userdata restore %1% %2%) [[※ Pin/Unpin…]](#d8ff2b show_text=&7Click to pin or unpin this user data snapshot\n&8Pinned snapshots won''t be automatically rotated run_command=/userdata pin %1% %2%)' data_manager_system_buttons: '[System:](gray) [[⏷ File Dump…]](dark_gray show_text=&7Click to dump this raw user data snapshot to a file.\n&8Data dumps can be found in ~/plugins/HuskSync/dumps/ run_command=/husksync:userdata dump %1% %2% file) [[☂ Web Dump…]](dark_gray show_text=&7Click to dump this raw user data snapshot to the mc-logs service\n&8You will be provided with a URL containing the data. run_command=/husksync:userdata dump %1% %2% web)' -data_manager_advancements_preview_remaining: '&7and %1% more…' +data_manager_advancements_preview_remaining: 'and %1% more…' data_list_title: '[%1%''s user data snapshots:](#00fb9a) [(%2%-%3% of](#00fb9a) [%4%](#00fb9a bold)[)](#00fb9a)\n' -data_list_item: '[%1%](gray show_text=&7Data snapshot %3% run_command=/userdata view %6% %4%) [%7%](#d8ff2b show_text=&7Pinned:\n&8Pinned snapshots won''t be automatically rotated. run_command=/userdata view %6% %4%) [%2%](color=#ffc43b-#f5c962 show_text=&7Version timestamp:&7\n&8When the data was saved run_command=/userdata view %6% %4%) [⚡ %3%](color=#62a9f5-#7ab8fa show_text=&7Version UUID:&7\n&8%4% run_command=/userdata view %6% %4%) [⚑ %5%](#23a825-#36f539 show_text=&7Save cause:\n&8What caused the data to be saved run_command=/userdata view %6% %4%)' +data_list_item: '[%1%](gray show_text=&7User Data Snapshot for %2%&8⚡ %4% run_command=/userdata view %2% %3%) [%5%](#d8ff2b show_text=&7Pinned:\n&8Pinned snapshots won''t be automatically rotated. run_command=/userdata view %2% %3%) [%6%](color=#ffc43b-#f5c962 show_text=&7Version timestamp:&7\n&8When the data was saved\n&8%7% run_command=/userdata view %2% %3%) [⚑ %8%](#23a825-#36f539 show_text=&7Save cause:\n&8What caused the data to be saved run_command=/userdata view %2% %3%) [⏏ %9%](color=#62a9f5-#7ab8fa show_text=&7Snapshot size:&7\n&8Estimated file size of the snapshot (in KiB) run_command=/userdata view %2% %3%)' data_deleted: '[❌ Successfully deleted user data snapshot](#00fb9a) [%1%](#00fb9a show_text=&7Version UUID:\n&8%2%) [for](#00fb9a) [%3%.](#00fb9a show_text=&7Player UUID:\n&8%4%)' data_restored: '[⏪ Successfully restored](#00fb9a) [%1%](#00fb9a show_text=&7Player UUID:\n&8%2%)[''s current user data from snapshot](#00fb9a) [%3%.](#00fb9a show_text=&7Version UUID:\n&8%4%)' data_pinned: '[※ Successfully pinned user data snapshot](#00fb9a) [%1%](#00fb9a show_text=&7Version UUID:\n&8%2%) [for](#00fb9a) [%3%.](#00fb9a show_text=&7Player UUID:\n&8%4%)' @@ -38,4 +32,18 @@ list_page_jumpers: '(%1%)' list_page_jumper_button: '[%1%](show_text=&7Jump to page %1% run_command=%2% %1%)' list_page_jumper_current_page: '[%1%](#00fb9a)' list_page_jumper_separator: ' ' -list_page_jumper_group_separator: '…' \ No newline at end of file +list_page_jumper_group_separator: '…' +up_to_date: '[HuskSync](#00fb9a bold) [| You are running the latest version of HuskSync (v%1%).](#00fb9a)' +update_available: '[HuskSync](#ff7e5e bold) [| A new version of HuskSync is available: v%1% (running: v%2%).](#ff7e5e)' +reload_complete: '[HuskSync](#00fb9a bold) [| Перезавантажено конфіґ та файли повідомлень.](#00fb9a)\n[⚠ Ensure config files are up-to-date on all servers!](#00fb9a)\n[A restart is needed for config changes to take effect.](#00fb9a italic)' +error_invalid_syntax: '[Помилка:](#ff3300) [Неправильний синтакс. Використання:](#ff7e5e) [%1%](#ff7e5e italic show_text=&#ff7e5e&Click to suggest suggest_command=%1%)' +error_invalid_player: '[Помилка:](#ff3300) [Гравця не знайдено](#ff7e5e)' +error_no_permission: '[Помилка:](#ff3300) [Ввас немає дозволу на використання цієї команди](#ff7e5e)' +error_console_command_only: '[Помилка:](#ff3300) [Ця команда може бути використана лише з допомогою %1% консолі](#ff7e5e)' +error_in_game_command_only: 'Error: That command can only be used in-game.' +error_no_data_to_display: '[Error:](#ff3300) [Could not find any user data to display.](#ff7e5e)' +error_invalid_version_uuid: '[Error:](#ff3300) [Could not find any user data for that version UUID.](#ff7e5e)' +husksync_command_description: 'Manage the HuskSync plugin' +userdata_command_description: 'View, manage & restore player userdata' +inventory_command_description: 'View & edit a player''s inventory' +enderchest_command_description: 'View & edit a player''s Ender Chest' \ No newline at end of file diff --git a/common/src/main/resources/locales/zh-cn.yml b/common/src/main/resources/locales/zh-cn.yml index 62fca778..61224f0e 100644 --- a/common/src/main/resources/locales/zh-cn.yml +++ b/common/src/main/resources/locales/zh-cn.yml @@ -1,31 +1,25 @@ -synchronisation_complete: '[⏵ 数据同步完成!](#00fb9a)' -synchronisation_failed: '[⏵ 无法同步数据! 请联系管理员.](#ff7e5e)' -reload_complete: '[HuskSync](#00fb9a bold) [| 插件配置和语言文件已重载.](#00fb9a)' -error_invalid_syntax: ':](#ff3300) [格式错误, 使用方法: %1%](#ff7e5e)' -error_invalid_player: '[错误:](#ff3300) [无法找到目标玩家.](#ff7e5e)' -error_no_permission: '[错误:](#ff3300) [你没有执行此指令的权限](#ff7e5e)' -error_console_command_only: '[错误:](#ff3300) [该指令只能在控制台运行](#ff7e5e)' -error_in_game_command_only: 'Error: 该指令只能在游戏内运行.' -error_no_data_to_display: '[错误:](#ff3300) [无法找到用户数据显示.](#ff7e5e)' -error_invalid_version_uuid: '[错误:](#ff3300) [无法找到该备份的 UUID .](#ff7e5e)' +synchronization_complete: '[⏵ 数据同步完成!](#00fb9a)' +synchronization_failed: '[⏵ 无法同步数据! 请联系管理员.](#ff7e5e)' inventory_viewer_menu_title: '&0%1% 的背包' ender_chest_viewer_menu_title: '&0%1% 的末影箱' inventory_viewer_opened: '[正在查看玩家](#00fb9a) [%1%](#00fb9a bold) [于 ⌚ %2% 的背包备份](#00fb9a)' ender_chest_viewer_opened: '[正在查看玩家](#00fb9a) [%1%](#00fb9a bold) [于 ⌚ %2% 的末影箱备份](#00fb9a)' data_update_complete: '[🔔 你的用户数据已更新!](#00fb9a)' data_update_failed: '[🔔 无法更新你的用户数据! 请联系管理员.](#ff7e5e)' +user_registration_complete: '[⭐ User registration complete!](#00fb9a)' data_manager_title: '[正在查看玩家](#00fb9a) [%3%](#00fb9a bold show_text=&7玩家 UUID:\n&8%4%) [的数据备份](#00fb9a) [%1%](#00fb9a show_text=&7备份版本 UUID:\n&8%2%) [:](#00fb9a)' data_manager_timestamp: '[⌚ %1%](#ffc43b-#f5c962 show_text=&7备份时间:\n&7何时保存了此数据)' data_manager_pinned: '[※ 置顶备份](#d8ff2b show_text=&7置顶:\n&8此数据备份不会按照备份时间自动排序.)' -data_manager_cause: '[⚑ %1%](#23a825-#36f539 show_text=&7备份原因:\n&7为何保存了此数据)\n' -data_manager_status: '[%1%](red)[/](gray)[%2%](red)[×](gray)[❤](red show_text=&7血量) [%3%](yellow)[×](gray)[🍖](yellow show_text=&7饱食度) [ʟᴠ](green)[.](gray)[%4%](green show_text=&7经验等级) [🏹 %5%](dark_aqua show_text=&7游戏模式)' +data_manager_cause: '[⚑ %1%](#23a825-#36f539 show_text=&7备份原因:\n&7为何保存了此数据)' +data_manager_size: '[⏏ %1%](color=#62a9f5-#7ab8fa show_text=&7Snapshot size:\n&8Estimated file size of the snapshot (in KiB))\n' +data_manger_status: '[%1%](red)[/](gray)[%2%](red)[×](gray)[❤](red show_text=&7血量) [%3%](yellow)[×](gray)[🍖](yellow show_text=&7饱食度) [ʟᴠ](green)[.](gray)[%4%](green show_text=&7经验等级) [🏹 %5%](dark_aqua show_text=&7游戏模式)' data_manager_advancements_statistics: '[⭐ 成就: %1%](color=#ffc43b-#f5c962 show_text=&7%2%) [⌛ 游玩时间: %3%ʜʀs](color=#62a9f5-#7ab8fa show_text=&7⚠ 基于游戏内的统计)\n' data_manager_item_buttons: '[View:](gray) [[🪣 背包…]](color=#a17b5f-#f5b98c show_text=&7点击查看 run_command=/inventory %1% %2%) [[⌀ 末影箱…]](#b649c4-#d254ff show_text=&7点击查看 run_command=/enderchest %1% %2%)' data_manager_management_buttons: '[Manage:](gray) [[❌ 删除…]](#ff3300 show_text=&7点击删除此数据备份.\n这不会影响玩家当前的数据.\n&#ff3300&⚠ 此操作不可撤销! suggest_command=/husksync:userdata delete %1% %2%) [[⏪ 恢复…]](#00fb9a show_text=&7点击让玩家恢复到此数据备份.\n这将会使玩家的数据恢复到这个备份.\n&#ff3300&⚠ %1% 当前的用户数据会被备份数据所覆盖! suggest_command=/husksync:userdata restore %1% %2%) [[※ Pin/Unpin…]](#d8ff2b show_text=&7Click to pin or unpin this user data snapshot\n&8Pinned snapshots won''t be automatically rotated run_command=/userdata pin %1% %2%)' data_manager_system_buttons: '[System:](gray) [[⏷ File Dump…]](dark_gray show_text=&7Click to dump this raw user data snapshot to a file.\n&8Data dumps can be found in ~/plugins/HuskSync/dumps/ run_command=/husksync:userdata dump %1% %2% file) [[☂ Web Dump…]](dark_gray show_text=&7Click to dump this raw user data snapshot to the mc-logs service\n&8You will be provided with a URL containing the data. run_command=/husksync:userdata dump %1% %2% web)' -data_manager_advancements_preview_remaining: '&7还有 %1% …' +data_manager_advancements_preview_remaining: '还有 %1% …' data_list_title: '[%1%''s user data snapshots:](#00fb9a) [(%2%-%3% of](#00fb9a) [%4%](#00fb9a bold)[)](#00fb9a)\n' -data_list_item: '[%1%](gray show_text=&7备份 %3% run_command=/userdata view %6% %4%) [%2%](color=#ffc43b-#f5c962 show_text=&7备份时间&7\n&8何时保存了此数据 run_command=/userdata view %6% %4%) [⚡ %3%](color=#62a9f5-#7ab8fa show_text=&7备份版本 UUID:&7\n&8%4% run_command=/userdata view %6% %4%) [⚑ %5%](#23a825-#36f539 show_text=&7备份原因\n&8为何保存了此数据 run_command=/userdata view %6% %4%)' +data_list_item: '[%1%](gray show_text=&7User Data Snapshot for %2%&8⚡ %4% run_command=/userdata view %2% %3%) [%5%](#d8ff2b show_text=&7Pinned:\n&8Pinned snapshots won''t be automatically rotated. run_command=/userdata view %2% %3%) [%6%](color=#ffc43b-#f5c962 show_text=&7Version timestamp:&7\n&8When the data was saved\n&8%7% run_command=/userdata view %2% %3%) [⚑ %8%](#23a825-#36f539 show_text=&7Save cause:\n&8What caused the data to be saved run_command=/userdata view %2% %3%) [⏏ %9%](color=#62a9f5-#7ab8fa show_text=&7Snapshot size:&7\n&8Estimated file size of the snapshot (in KiB) run_command=/userdata view %2% %3%)' data_deleted: '[❌ 成功删除玩家](#00fb9a) [%3%](#00fb9a show_text=&7玩家 UUID:\n&7%4%) [的数据备份](#00fb9a) [%1%.](#00fb9a show_text=&7备份版本 UUID:\n&7%2%)' data_restored: '[⏪ 成功恢复玩家](#00fb9a) [%1%](#00fb9a show_text=&7玩家 UUID:\n&7%2%)[的数据备份](#00fb9a) [%3%.](#00fb9a show_text=&7备份版本 UUID:\n&7%4%)' data_pinned: '[※ 成功置顶玩家](#00fb9a) [%3%](#00fb9a show_text=&7玩家 UUID:\n&8%4%) [的数据备份](#00fb9a) [%1%.](#00fb9a show_text=&7备份版本 UUID:\n&8%2%)' @@ -38,4 +32,18 @@ list_page_jumpers: '(%1%)' list_page_jumper_button: '[%1%](show_text=&7Jump to page %1% run_command=%2% %1%)' list_page_jumper_current_page: '[%1%](#00fb9a)' list_page_jumper_separator: ' ' -list_page_jumper_group_separator: '…' \ No newline at end of file +list_page_jumper_group_separator: '…' +up_to_date: '[HuskSync](#00fb9a bold) [| 你正在使用最新版本的HuskSync (v%1%)](#00fb9a)' +update_available: '[HuskSync](#ff7e5e bold) [| 一个新版本的HuskSync已经可以更新: v%1% (当前: v%2%)](#ff7e5e)' +reload_complete: '[HuskSync](#00fb9a bold) [| 插件配置和语言文件已重载.](#00fb9a)\n[⚠ Ensure config files are up-to-date on all servers!](#00fb9a)\n[A restart is needed for config changes to take effect.](#00fb9a italic)' +error_invalid_syntax: ':](#ff3300) [格式错误, 使用方法:](#ff7e5e) [%1%](#ff7e5e italic show_text=&#ff7e5e&Click to suggest suggest_command=%1%)' +error_invalid_player: '[错误:](#ff3300) [无法找到目标玩家.](#ff7e5e)' +error_no_permission: '[错误:](#ff3300) [你没有执行此指令的权限](#ff7e5e)' +error_console_command_only: '[错误:](#ff3300) [该指令只能在控制台运行](#ff7e5e)' +error_in_game_command_only: 'Error: 该指令只能在游戏内运行.' +error_no_data_to_display: '[错误:](#ff3300) [无法找到用户数据显示.](#ff7e5e)' +error_invalid_version_uuid: '[错误:](#ff3300) [无法找到该备份的 UUID .](#ff7e5e)' +husksync_command_description: 'Manage the HuskSync plugin' +userdata_command_description: 'View, manage & restore player userdata' +inventory_command_description: 'View & edit a player''s inventory' +enderchest_command_description: 'View & edit a player''s Ender Chest' \ No newline at end of file diff --git a/common/src/main/resources/locales/zh-tw.yml b/common/src/main/resources/locales/zh-tw.yml index 84544d31..64e96ff5 100644 --- a/common/src/main/resources/locales/zh-tw.yml +++ b/common/src/main/resources/locales/zh-tw.yml @@ -1,41 +1,49 @@ -synchronisation_complete: '[⏵資料已同步!](#00fb9a)' -synchronisation_failed: '[⏵ 無法同步您的資料! 請聯繫管理員](#ff7e5e)' -reload_complete: '[HuskSync](#00fb9a bold) [| 已重新載入配置和訊息文件](#00fb9a)' -error_invalid_syntax: '[錯誤:](#ff3300) [語法不正確,用法: %1%](#ff7e5e)' -error_invalid_player: '[錯誤:](#ff3300) [找不到這位玩家](#ff7e5e)' -error_no_permission: '[錯誤:](#ff3300) [您沒有權限執行這個指令](#ff7e5e)' -error_console_command_only: '[錯誤:](#ff3300) [該指令只能透過 控制台 執行](#ff7e5e)' -error_in_game_command_only: '[錯誤:](#ff3300) [該指令只能在遊戲內執行](#ff7e5e)' -error_no_data_to_display: '[錯誤:](#ff3300) [找不到任何可顯示的用戶資訊.](#ff7e5e)' -error_invalid_version_uuid: '[錯誤:](#ff3300) [找不到正確的 Version UUID.](#ff7e5e)' +synchronization_complete: '[⏵資料已同步!](#00fb9a)' +synchronization_failed: '[⏵ 無法同步您的資料! 請聯繫管理員](#ff7e5e)' inventory_viewer_menu_title: '&0%1% 的背包' ender_chest_viewer_menu_title: '&0%1% 的終界箱' inventory_viewer_opened: '[查看](#00fb9a) [%1%](#00fb9a bold) [於 ⌚ %2% 的背包快照資料](#00fb9a)' ender_chest_viewer_opened: '[查看](#00fb9a) [%1%](#00fb9a bold) [於 ⌚ %2% 的終界箱快照資料](#00fb9a)' data_update_complete: '[🔔 你的資料已更新!](#00fb9a)' data_update_failed: '[🔔 無法更新您的資料! 請聯繫管理員](#ff7e5e)' +user_registration_complete: '[⭐ User registration complete!](#00fb9a)' data_manager_title: '[查看](#00fb9a) [%3%](#00fb9a bold show_text=&7玩家 UUID:\n&8%4%) [的快照:](#00fb9a) [%1%](#00fb9a show_text=&7Version UUID:\n&8%2%) [:](#00fb9a)' data_manager_timestamp: '[⌚ %1%](#ffc43b-#f5c962 show_text=&7快照時間:\n&8何時保存的資料)' data_manager_pinned: '[※ 被標記的快照](#d8ff2b show_text=&7標記:\n&8此快照資料不會自動輪換更新)' -data_manager_cause: '[⚑ %1%](#23a825-#36f539 show_text=&7保存原因:\n&8保存此快照的原因)\n' -data_manager_status: '[%1%](red)[/](gray)[%2%](red)[×](gray)[❤](red show_text=&7血量) [%3%](yellow)[×](gray)[🍖](yellow show_text=&7飽食度) [ʟᴠ](green)[.](gray)[%4%](green show_text=&7經驗等級) [🏹 %5%](dark_aqua show_text=&7遊戲模式)' +data_manager_cause: '[⚑ %1%](#23a825-#36f539 show_text=&7保存原因:\n&8保存此快照的原因)' +data_manager_size: '[⏏ %1%](color=#62a9f5-#7ab8fa show_text=&7Snapshot size:\n&8Estimated file size of the snapshot (in KiB))\n' +data_manger_status: '[%1%](red)[/](gray)[%2%](red)[×](gray)[❤](red show_text=&7血量) [%3%](yellow)[×](gray)[🍖](yellow show_text=&7飽食度) [ʟᴠ](green)[.](gray)[%4%](green show_text=&7經驗等級) [🏹 %5%](dark_aqua show_text=&7遊戲模式)' data_manager_advancements_statistics: '[⭐ 成就: %1%](color=#ffc43b-#f5c962 show_text=&7已獲得的成就:\n&8%2%) [⌛ 遊戲時間: %3%ʜʀs](color=#62a9f5-#7ab8fa show_text=&7遊戲內的遊玩時間\n&8⚠ 根據遊戲內統計)\n' data_manager_item_buttons: '[查看:](gray) [[🪣 背包…]](color=#a17b5f-#f5b98c show_text=&7點擊查看 run_command=/inventory %1% %2%) [[⌀ 終界箱…]](#b649c4-#d254ff show_text=&7點擊查看 run_command=/enderchest %1% %2%)' data_manager_management_buttons: '[管理:](gray) [[❌ 刪除…]](#ff3300 show_text=&7點擊刪除這個快照\n&8這不會影像目前玩家的資料\n&#ff3300&⚠ 此操作不能取消! suggest_command=/husksync:userdata delete %1% %2%) [[⏪ 恢復…]](#00fb9a show_text=&7點擊將玩家資料覆蓋為此快照\n&8這將導致玩家的資料會被此快照覆蓋\n&#ff3300&⚠ %1% 當前的資料將被覆蓋! suggest_command=/husksync:userdata restore %1% %2%) [[※ 標記…]](#d8ff2b show_text=&7點擊切換標記狀態\n&8被標記的快照將不會自動輪換更新 run_command=/userdata pin %1% %2%)' data_manager_system_buttons: '[系統:](gray) [[⏷ 本地轉存…]](dark_gray show_text=&7點擊將此玩家資料快照轉存到本地文件中\n&8轉存的資料可以在以下路徑找到 ~/plugins/HuskSync/dumps/ run_command=/husksync:userdata dump %1% %2% file) [[☂ 雲端轉存…]](dark_gray show_text=&7點擊將此玩家資料快照轉存到 mc-logs 服務\n&8您將獲得一個包含資料的 URL. run_command=/husksync:userdata dump %1% %2% web)' -data_manager_advancements_preview_remaining: '&7還有 %1% …' +data_manager_advancements_preview_remaining: '還有 %1% …' data_list_title: '[%1% 的玩家資料快照:](#00fb9a) [(%2%-%3% 共](#00fb9a) [%4%](#00fb9a bold)[)](#00fb9a)\n' -data_list_item: '[%1%](gray show_text=&7快照名稱: %3% run_command=/userdata view %6% %4%) [%7%](#d8ff2b show_text=&7標記:\n&8被標記的快照不會自動輪換更新 run_command=/userdata view %6% %4%) [%2%](color=#ffc43b-#f5c962 show_text=&7時間戳:&7\n&8資料保存時間 run_command=/userdata view %6% %4%) [⚡ %3%](color=#62a9f5-#7ab8fa show_text=&7Version UUID:&7\n&8%4% run_command=/userdata view %6% %4%) [⚑ %5%](#23a825-#36f539 show_text=&7保存原因:\n&8保存此快照的原因 run_command=/userdata view %6% %4%)' +data_list_item: '[%1%](gray show_text=&7User Data Snapshot for %2%&8⚡ %4% run_command=/userdata view %2% %3%) [%5%](#d8ff2b show_text=&7Pinned:\n&8Pinned snapshots won''t be automatically rotated. run_command=/userdata view %2% %3%) [%6%](color=#ffc43b-#f5c962 show_text=&7Version timestamp:&7\n&8When the data was saved\n&8%7% run_command=/userdata view %2% %3%) [⚑ %8%](#23a825-#36f539 show_text=&7Save cause:\n&8What caused the data to be saved run_command=/userdata view %2% %3%) [⏏ %9%](color=#62a9f5-#7ab8fa show_text=&7Snapshot size:&7\n&8Estimated file size of the snapshot (in KiB) run_command=/userdata view %2% %3%)' data_deleted: '[❌ 成功刪除:](#00fb9a) [%3%](#00fb9a show_text=&7玩家 UUID:\n&8%4%) [的快照:](#00fb9a) [%1%](#00fb9a show_text=&7Version UUID:\n&8%2%)' data_restored: '[⏪ 成功將玩家](#00fb9a) [%1%](#00fb9a show_text=&7玩家 UUID:\n&8%2%)[的資料恢復為 快照:](#00fb9a) [%3%.](#00fb9a show_text=&7Version UUID:\n&8%4%)' data_pinned: '[※ 成功標記](#00fb9a) [%3%](#00fb9a show_text=&7玩家 UUID:\n&8%4%) [的快照:](#00fb9a) [%1%](#00fb9a show_text=&7Version UUID:\n&8%2%)' data_unpinned: '[※ 成功解除](#00fb9a) [%3%](#00fb9a show_text=&7玩家 UUID:\n&8%4%) [快照:](#00fb9a) [%1%](#00fb9a show_text=&7Version UUID:\n&8%2%) [的標記](#00fb9a)' data_dumped: '[☂ 成功將 %2% 資料快照 %1% 儲存至:](#00fb9a) &7%3%' -list_footer: \n%1%[頁面](#00fb9a) [%2%](#00fb9a)/[%3%](#00fb9a)%4% %5% +list_footer: '\n%1%[頁面](#00fb9a) [%2%](#00fb9a)/[%3%](#00fb9a)%4% %5%' list_previous_page_button: '[◀](white show_text=&7查看上一頁 run_command=%2% %1%) ' list_next_page_button: ' [▶](white show_text=&7查看下一頁 run_command=%2% %1%)' -list_page_jumpers: (%1%) +list_page_jumpers: '(%1%)' list_page_jumper_button: '[%1%](show_text=&7跳至第 %1% 頁 run_command=%2% %1%)' list_page_jumper_current_page: '[%1%](#00fb9a)' list_page_jumper_separator: ' ' -list_page_jumper_group_separator: … +list_page_jumper_group_separator: '…' +up_to_date: '[HuskSync](#00fb9a bold) [| 您運行的是最新版本的 HuskSync (v%1%).](#00fb9a)' +update_available: '[HuskSync](#ff7e5e bold) [| 發現可用的新版本: v%1% (running: v%2%).](#ff7e5e)' +reload_complete: '[HuskSync](#00fb9a bold) [| 已重新載入配置和訊息文件](#00fb9a)\n[⚠ Ensure config files are up-to-date on all servers!](#00fb9a)\n[A restart is needed for config changes to take effect.](#00fb9a italic)' +error_invalid_syntax: '[錯誤:](#ff3300) [語法不正確,用法:](#ff7e5e) [%1%](#ff7e5e italic show_text=&#ff7e5e&Click to suggest suggest_command=%1%)' +error_invalid_player: '[錯誤:](#ff3300) [找不到這位玩家](#ff7e5e)' +error_no_permission: '[錯誤:](#ff3300) [您沒有權限執行這個指令](#ff7e5e)' +error_console_command_only: '[錯誤:](#ff3300) [該指令只能透過 控制台 執行](#ff7e5e)' +error_in_game_command_only: '[錯誤:](#ff3300) [該指令只能在遊戲內執行](#ff7e5e)' +error_no_data_to_display: '[錯誤:](#ff3300) [找不到任何可顯示的用戶資訊.](#ff7e5e)' +error_invalid_version_uuid: '[錯誤:](#ff3300) [找不到正確的 Version UUID.](#ff7e5e)' +husksync_command_description: 'Manage the HuskSync plugin' +userdata_command_description: 'View, manage & restore player userdata' +inventory_command_description: 'View & edit a player''s inventory' +enderchest_command_description: 'View & edit a player''s Ender Chest' \ No newline at end of file diff --git a/common/src/test/java/net/william278/husksync/DummyHuskSync.java b/common/src/test/java/net/william278/husksync/DummyHuskSync.java deleted file mode 100644 index 1a444e99..00000000 --- a/common/src/test/java/net/william278/husksync/DummyHuskSync.java +++ /dev/null @@ -1,134 +0,0 @@ -/* - * This file is part of HuskSync, licensed under the Apache License 2.0. - * - * Copyright (c) William278 - * Copyright (c) contributors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.william278.husksync; - -import net.william278.desertwell.util.Version; -import net.william278.husksync.config.Locales; -import net.william278.husksync.config.Settings; -import net.william278.husksync.data.DataAdapter; -import net.william278.husksync.database.Database; -import net.william278.husksync.event.EventCannon; -import net.william278.husksync.migrator.Migrator; -import net.william278.husksync.player.OnlineUser; -import net.william278.husksync.redis.RedisManager; -import org.jetbrains.annotations.NotNull; - -import java.io.File; -import java.io.InputStream; -import java.util.List; -import java.util.Optional; -import java.util.Set; -import java.util.UUID; -import java.util.concurrent.CompletableFuture; -import java.util.logging.Level; - -public class DummyHuskSync implements HuskSync { - @Override - @NotNull - public Set getOnlineUsers() { - return Set.of(); - } - - @Override - @NotNull - public Optional getOnlineUser(@NotNull UUID uuid) { - return Optional.empty(); - } - - @Override - @NotNull - public Database getDatabase() { - throw new UnsupportedOperationException(); - } - - @Override - @NotNull - public RedisManager getRedisManager() { - throw new UnsupportedOperationException(); - } - - @Override - @NotNull - public DataAdapter getDataAdapter() { - throw new UnsupportedOperationException(); - } - - @Override - @NotNull - public EventCannon getEventCannon() { - throw new UnsupportedOperationException(); - } - - @Override - @NotNull - public List getAvailableMigrators() { - return List.of(); - } - - @Override - @NotNull - public Settings getSettings() { - return new Settings(); - } - - @Override - @NotNull - public Locales getLocales() { - return new Locales(); - } - - @Override - public InputStream getResource(@NotNull String name) { - throw new UnsupportedOperationException(); - } - - @Override - public void log(@NotNull Level level, @NotNull String message, @NotNull Throwable... throwable) { - System.out.println(message); - } - - @Override - @NotNull - public Version getPluginVersion() { - return Version.fromString("1.0.0"); - } - - @Override - @NotNull - public File getDataFolder() { - return new File("."); - } - - @Override - @NotNull - public Version getMinecraftVersion() { - return Version.fromString("1.16.2"); - } - - @Override - public CompletableFuture reload() { - return CompletableFuture.supplyAsync(() -> true); - } - - @Override - public Set getLockedPlayers() { - return Set.of(); - } -} diff --git a/common/src/test/java/net/william278/husksync/config/LocalesTests.java b/common/src/test/java/net/william278/husksync/config/LocalesTests.java new file mode 100644 index 00000000..cb5ab5ca --- /dev/null +++ b/common/src/test/java/net/william278/husksync/config/LocalesTests.java @@ -0,0 +1,81 @@ +/* + * This file is part of HuskSync, licensed under the Apache License 2.0. + * + * Copyright (c) William278 + * Copyright (c) contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.william278.husksync.config; + +import net.william278.annotaml.Annotaml; +import org.jetbrains.annotations.NotNull; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.lang.reflect.InvocationTargetException; +import java.net.URL; +import java.util.Objects; +import java.util.Set; +import java.util.stream.Stream; + +@DisplayName("Locales Tests") +public class LocalesTests { + + private Locales englishLocales; + + @BeforeEach + @DisplayName("Test Loading English Locales") + @Test + public void testLoadEnglishLocales() { + try (InputStream locales = LocalesTests.class.getClassLoader().getResourceAsStream("locales/en-gb.yml")) { + Assertions.assertNotNull(locales, "en-gb.yml is missing from the locales folder"); + englishLocales = Annotaml.create(Locales.class, locales).get(); + } catch (IOException | InvocationTargetException | InstantiationException | IllegalAccessException e) { + throw new RuntimeException(e); + } + } + + @ParameterizedTest(name = "{1} Locales") + @DisplayName("Test All Locale Keys Present") + @MethodSource("provideLocaleFiles") + public void testAllLocaleKeysPresent(@NotNull File file, @SuppressWarnings("unused") @NotNull String keyName) { + try { + final Set fileKeys = Annotaml.create(file, Locales.class).get().rawLocales.keySet(); + englishLocales.rawLocales.keySet() + .forEach(key -> Assertions.assertTrue(fileKeys.contains(key), + "Locale key " + key + " is missing from " + file.getName())); + } catch (IOException | InvocationTargetException | InstantiationException | IllegalAccessException e) { + throw new RuntimeException(e); + } + } + + @NotNull + private static Stream provideLocaleFiles() { + URL url = LocalesTests.class.getClassLoader().getResource("locales"); + Assertions.assertNotNull(url, "locales folder is missing"); + return Stream.of(Objects.requireNonNull(new File(url.getPath()) + .listFiles(file -> file.getName().endsWith("yml") && !file.getName().equals("en-gb.yml")))) + .map(file -> Arguments.of(file, file.getName().replace(".yml", ""))); + } + +} \ No newline at end of file diff --git a/common/src/test/java/net/william278/husksync/data/DataAdaptionTests.java b/common/src/test/java/net/william278/husksync/data/DataAdaptionTests.java deleted file mode 100644 index b4727a60..00000000 --- a/common/src/test/java/net/william278/husksync/data/DataAdaptionTests.java +++ /dev/null @@ -1,105 +0,0 @@ -/* - * This file is part of HuskSync, licensed under the Apache License 2.0. - * - * Copyright (c) William278 - * Copyright (c) contributors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.william278.husksync.data; - -import net.william278.husksync.DummyHuskSync; -import net.william278.husksync.player.DummyPlayer; -import net.william278.husksync.player.OnlineUser; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - -import java.nio.charset.StandardCharsets; -import java.util.HashMap; -import java.util.concurrent.atomic.AtomicReference; - -/** - * Tests for the data system {@link DataAdapter} - */ -public class DataAdaptionTests { - - @Test - public void testJsonDataAdapter() { - final OnlineUser dummyUser = DummyPlayer.create(); - dummyUser.getUserData(new DummyHuskSync()).join().ifPresent(dummyUserData -> { - final DataAdapter dataAdapter = new JsonDataAdapter(); - final byte[] data = dataAdapter.toBytes(dummyUserData); - final UserData deserializedUserData = dataAdapter.fromBytes(data); - - // Assert all deserialized data is equal to the original data - Assertions.assertTrue(dummyUserData.getInventory().isPresent()); - Assertions.assertTrue(deserializedUserData.getInventory().isPresent()); - Assertions.assertEquals(dummyUserData.getInventory().get().serializedItems, deserializedUserData.getInventory().get().serializedItems); - Assertions.assertEquals(dummyUserData.getFormatVersion(), deserializedUserData.getFormatVersion()); - }); - } - - @Test - public void testJsonFormat() { - final OnlineUser dummyUser = DummyPlayer.create(); - final String expectedJson = "{\"status\":{\"health\":20.0,\"max_health\":20.0,\"health_scale\":0.0,\"hunger\":20,\"saturation\":5.0,\"saturation_exhaustion\":5.0,\"selected_item_slot\":1,\"total_experience\":100,\"experience_level\":1,\"experience_progress\":1.0,\"game_mode\":\"SURVIVAL\",\"is_flying\":false},\"inventory\":{\"serialized_items\":\"\"},\"ender_chest\":{\"serialized_items\":\"\"},\"potion_effects\":{\"serialized_potion_effects\":\"\"},\"advancements\":[],\"statistics\":{\"untyped_statistics\":{},\"block_statistics\":{},\"item_statistics\":{},\"entity_statistics\":{}},\"minecraft_version\":\"1.19\",\"format_version\":3}"; - AtomicReference json = new AtomicReference<>(); - dummyUser.getUserData(new DummyHuskSync()).join().ifPresent(dummyUserData -> { - final DataAdapter dataAdapter = new JsonDataAdapter(); - final byte[] data = dataAdapter.toBytes(dummyUserData); - json.set(new String(data, StandardCharsets.UTF_8)); - }); - Assertions.assertEquals(expectedJson, json.get()); - } - - @Test - public void testCompressedDataAdapter() { - final OnlineUser dummyUser = DummyPlayer.create(); - dummyUser.getUserData(new DummyHuskSync()).join().ifPresent(dummyUserData -> { - final DataAdapter dataAdapter = new CompressedDataAdapter(); - final byte[] data = dataAdapter.toBytes(dummyUserData); - final UserData deserializedUserData = dataAdapter.fromBytes(data); - - // Assert all deserialized data is equal to the original data - Assertions.assertTrue(dummyUserData.getInventory().isPresent()); - Assertions.assertTrue(deserializedUserData.getInventory().isPresent()); - Assertions.assertEquals(dummyUserData.getInventory().get().serializedItems, deserializedUserData.getInventory().get().serializedItems); - Assertions.assertEquals(dummyUserData.getFormatVersion(), deserializedUserData.getFormatVersion()); - }); - } - - private String getTestSerializedPersistentDataContainer() { - final HashMap> persistentDataTest = new HashMap<>(); - persistentDataTest.put("husksync:byte_test", new PersistentDataTag<>(PersistentDataTagType.BYTE, 0x01)); - persistentDataTest.put("husksync:double_test", new PersistentDataTag<>(PersistentDataTagType.DOUBLE, 2d)); - persistentDataTest.put("husksync:string_test", new PersistentDataTag<>(PersistentDataTagType.STRING, "test")); - persistentDataTest.put("husksync:int_test", new PersistentDataTag<>(PersistentDataTagType.INTEGER, 3)); - persistentDataTest.put("husksync:long_test", new PersistentDataTag<>(PersistentDataTagType.LONG, 4L)); - persistentDataTest.put("husksync:float_test", new PersistentDataTag<>(PersistentDataTagType.FLOAT, 5f)); - persistentDataTest.put("husksync:short_test", new PersistentDataTag<>(PersistentDataTagType.SHORT, 6)); - final PersistentDataContainerData persistentDataContainerData = new PersistentDataContainerData(persistentDataTest); - - final DataAdapter dataAdapter = new JsonDataAdapter(); - UserData userData = new UserData(); - userData.persistentDataContainerData = persistentDataContainerData; - return dataAdapter.toJson(userData, false); - } - - @Test - public void testPersistentDataContainerSerialization() { - Assertions.assertEquals(getTestSerializedPersistentDataContainer(), "{\"persistent_data_container\":{\"persistent_data_map\":{\"husksync:int_test\":{\"type\":\"INTEGER\",\"value\":3},\"husksync:string_test\":{\"type\":\"STRING\",\"value\":\"test\"},\"husksync:long_test\":{\"type\":\"LONG\",\"value\":4},\"husksync:byte_test\":{\"type\":\"BYTE\",\"value\":1},\"husksync:short_test\":{\"type\":\"SHORT\",\"value\":6},\"husksync:double_test\":{\"type\":\"DOUBLE\",\"value\":2.0},\"husksync:float_test\":{\"type\":\"FLOAT\",\"value\":5.0}}},\"format_version\":3}"); - } - - -} diff --git a/common/src/test/java/net/william278/husksync/hook/PlanHookTests.java b/common/src/test/java/net/william278/husksync/hook/PlanDataExtensionTests.java similarity index 71% rename from common/src/test/java/net/william278/husksync/hook/PlanHookTests.java rename to common/src/test/java/net/william278/husksync/hook/PlanDataExtensionTests.java index df12b4f2..000e59a3 100644 --- a/common/src/test/java/net/william278/husksync/hook/PlanHookTests.java +++ b/common/src/test/java/net/william278/husksync/hook/PlanDataExtensionTests.java @@ -20,19 +20,16 @@ package net.william278.husksync.hook; import com.djrapitops.plan.extension.extractor.ExtensionExtractor; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; -/** - * Tests for the {@link PlanHook} and {@link PlanDataExtension} implementation - */ -public class PlanHookTests { +@DisplayName("Plan Hook Tests") +public class PlanDataExtensionTests { - /** - * Throws IllegalArgumentException if there is an implementation error or warning. - */ @Test - public void testExtensionImplementationErrors() { - new ExtensionExtractor(new PlanDataExtension()).validateAnnotations(); + @DisplayName("Test Plan Hook Implementation") + public void testPlanHookImplementation() { + new ExtensionExtractor(new PlanHook.PlanDataExtension()).validateAnnotations(); } -} +} \ No newline at end of file diff --git a/common/src/test/java/net/william278/husksync/player/DummyPlayer.java b/common/src/test/java/net/william278/husksync/player/DummyPlayer.java deleted file mode 100644 index 3dd4378b..00000000 --- a/common/src/test/java/net/william278/husksync/player/DummyPlayer.java +++ /dev/null @@ -1,205 +0,0 @@ -/* - * This file is part of HuskSync, licensed under the Apache License 2.0. - * - * Copyright (c) William278 - * Copyright (c) contributors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.william278.husksync.player; - -import de.themoep.minedown.adventure.MineDown; -import net.kyori.adventure.audience.Audience; -import net.william278.desertwell.util.Version; -import net.william278.husksync.config.Settings; -import net.william278.husksync.data.*; -import org.jetbrains.annotations.NotNull; - -import java.util.*; -import java.util.concurrent.CompletableFuture; - -public class DummyPlayer extends OnlineUser { - - private DummyPlayer() { - super(UUID.fromString("00000000-0000-0000-0000-000000000000"), - "DummyPlayer"); - } - - public static DummyPlayer create() { - return new DummyPlayer(); - } - - @Override - public CompletableFuture getStatus() { - return CompletableFuture.supplyAsync(() -> new StatusData(20, 20, 0, - 20, 5, 5, 1, - 100, 1, 1f, "SURVIVAL", false)); - } - - @Override - public CompletableFuture setStatus(@NotNull StatusData statusData, @NotNull Settings settings) { - return CompletableFuture.runAsync(() -> { - // do nothing - }); - } - - @Override - public CompletableFuture getInventory() { - return CompletableFuture.supplyAsync(() -> new ItemData("")); - } - - @Override - public CompletableFuture setInventory(@NotNull ItemData itemData) { - return CompletableFuture.runAsync(() -> { - // do nothing - }); - } - - @Override - public CompletableFuture getEnderChest() { - return CompletableFuture.supplyAsync(() -> new ItemData("")); - } - - @Override - public CompletableFuture setEnderChest(@NotNull ItemData enderChestData) { - return CompletableFuture.runAsync(() -> { - // do nothing - }); - } - - @Override - public CompletableFuture getPotionEffects() { - return CompletableFuture.supplyAsync(() -> new PotionEffectData("")); - } - - @Override - public CompletableFuture setPotionEffects(@NotNull PotionEffectData potionEffectData) { - return CompletableFuture.runAsync(() -> { - // do nothing - }); - } - - @Override - public CompletableFuture> getAdvancements() { - return CompletableFuture.supplyAsync(ArrayList::new); - } - - @Override - public CompletableFuture setAdvancements(@NotNull List advancementData) { - return CompletableFuture.runAsync(() -> { - // do nothing - }); - } - - @Override - public CompletableFuture getStatistics() { - return CompletableFuture.supplyAsync(() -> new StatisticsData(new HashMap<>(), - new HashMap<>(), new HashMap<>(), new HashMap<>())); - } - - @Override - public CompletableFuture setStatistics(@NotNull StatisticsData statisticsData) { - return CompletableFuture.runAsync(() -> { - // do nothing - }); - } - - @Override - public CompletableFuture getLocation() { - return CompletableFuture.supplyAsync(() -> new LocationData("dummy_world", - UUID.fromString("00000000-0000-0000-0000-000000000000"), - "NORMAL", 0, 64, 0, 90f, 180f)); - } - - @Override - public CompletableFuture setLocation(@NotNull LocationData locationData) { - return CompletableFuture.runAsync(() -> { - // do nothing - }); - } - - @Override - public CompletableFuture getPersistentDataContainer() { - return CompletableFuture.supplyAsync(() -> new PersistentDataContainerData(new HashMap<>())); - } - - @Override - public CompletableFuture setPersistentDataContainer(@NotNull PersistentDataContainerData persistentDataContainerData) { - return CompletableFuture.runAsync(() -> { - // do nothing - }); - } - - @Override - public boolean isOffline() { - return false; - } - - @NotNull - @Override - public Version getMinecraftVersion() { - return Version.fromString("1.19-beta123456"); - } - - @Override - @NotNull - public Audience getAudience() { - return Audience.empty(); - } - - @Override - public void sendMessage(@NotNull MineDown mineDown) { - // do nothing - } - - @Override - public void sendActionBar(@NotNull MineDown mineDown) { - // do nothing - } - - @Override - public void sendToast(@NotNull MineDown title, @NotNull MineDown description, - @NotNull String iconMaterial, @NotNull String backgroundType) { - // do nothing - } - - @Override - public boolean hasPermission(@NotNull String node) { - return true; - } - - @Override - public CompletableFuture> showMenu(@NotNull ItemData itemData, boolean editable, - int minimumRows, @NotNull MineDown title) { - // do nothing - return CompletableFuture.completedFuture(Optional.empty()); - } - - - @Override - public boolean isDead() { - return false; - } - - @Override - public boolean isLocked() { - return false; - } - - @Override - public boolean isNpc() { - return false; - } - -} diff --git a/docs/API-Events.md b/docs/API-Events.md index b6605dad..edfecadf 100644 --- a/docs/API-Events.md +++ b/docs/API-Events.md @@ -1,12 +1,12 @@ -HuskSync provides three API events your plugin can listen to when certain parts of the data synchronisation process are performed. These events deal in HuskSync class types, so you may want to familiarize yourself with the [API basics](API) first. Two of the events can be cancelled (thus aborting the synchronisation process at certain stages) and some of the events expose methods letting you affect their outcome (such as modifying the data that is saved during the process). +HuskSync provides three API events your plugin can listen to when certain parts of the data synchronization process are performed. These events deal with HuskSync class types, so you may want to familiarize yourself with the [API basics](API) first. Two of the events can be cancelled (thus aborting the synchronization process at certain stages), and some events expose methods letting you affect their outcome (such as modifying the data that is saved during the process). -Consult the Javadocs for more information -- and don't forget to register your listener when listening for these event calls. Please note that carrying out expensive blocking operations during these events is strongly discouraged as this may affect plugin performance. +Consult the Javadocs for more information—and don't forget to register your listener when listening for these event calls. Please note that carrying out expensive blocking operations during these events is strongly discouraged as this may affect plugin performance. ## List of API Events | Bukkit Event class | Cancellable | Description | |---------------------------|:-----------:|---------------------------------------------------------------------------------------------| -| `BukkitDataSaveEvent` | ✅ | Called when player data snapshot is created, saved and cached due to a DataSaveCause | -| `BukkitPreSync` | ✅ | Called before a player has their data updated from the cache or database, just after login | -| `BukkitSyncCompleteEvent` | ❌ | Called once a player has completed their data synchronisation on login successfully† | +| `BukkitDataSaveEvent` | ✅ | Called when player data snapshot is created, saved and cached due to a DataSaveCause | +| `BukkitPreSyncEvent` | ✅ | Called before a player has their data updated from the cache or database, just after login | +| `BukkitSyncCompleteEvent` | ❌ | Called once a player has completed their data synchronization on login successfully† | -†This can also fire when a user's data is updated while the player is logged in; i.e. when an admin rolls back the user, updates their inventory or Ender Chest through the respective commands, or when an API call is made forcing the user to have their data updated. \ No newline at end of file +†This can also fire when a user's data is updated while the player is logged in; i.e., when an admin rolls back the user, updates their inventory or Ender Chest through the respective commands, or when an API call is made forcing the user to have their data updated. diff --git a/docs/UserData-API.md b/docs/API-v2.md similarity index 73% rename from docs/UserData-API.md rename to docs/API-v2.md index 5fc78400..ee41a19c 100644 --- a/docs/UserData-API.md +++ b/docs/API-v2.md @@ -1,69 +1,18 @@ -HuskSync provides an API for fetching and retrieving `UserData`; a snapshot of a user's synchronization. +> **Warning:** API v2 is no longer supported or compatible with HuskSync v3.0. See [[Data Snapshot API]] for the equivalent v3 API. 🚨 -This page assumes you've read the [[API]] introduction and have imported the HuskSync API into your repository. +HuskSync v2.0 provides an API for fetching and retrieving `UserData`; a snapshot of a user's synchronization. -## Table of contents -1. Creating a class to interface with the API -2. Checking if HuskSync is present and creating the hook -3. Getting an instance of the API -4. Getting a user by UUID -5. Getting a user's data -6. Getting a user's data -7. Getting a user's inventory contents -8. Updating a user's data +This page assumes you've read the general [[API]] introduction and imported HuskSync (v2.x) into your project, and added it as a dependency. -## 1. Creating a class to interface with the API -- Unless your plugin completely relies on HuskSync, you shouldn't put HuskSync API calls into your main class, otherwise if HuskSync is not installed you'll encounter `ClassNotFoundException`s +🚨 HuskSync API v2 only targets HuskSync v2.0-2.2.8. It is **not compatible with HuskSync v3.0+**. The equivalent API for HuskSync v3 is the [[Data Snapshot API]]. -```java -public class HuskSyncAPIHook { - - public HuskSyncAPIHook() { - // Ready to do stuff with the API - } - -} -``` -## 2. Checking if HuskSync is present and creating the hook -- Check to make sure the HuskSync plugin is present before instantiating the API hook class - -```java -public class MyPlugin extends JavaPlugin { - - public HuskSyncAPIHook huskSyncAPIHook; - - @Override - public void onEnable() { - if (Bukkit.getPluginManager().getPlugin("HuskSync") != null) { - this.huskSyncAPIHook = new HuskSyncAPIHook(); - } - } -} -``` +## Table of Contents +1. [Getting a user by UUID](#1-getting-a-user-by-uuid) +2. [Getting a user's data](#2-getting-a-users-data) +3. [Getting a user's inventory contents](#3-getting-a-users-inventory-contents) +4. [Updating a user's data](#4-updating-a-users-data) -## 3. Getting an instance of the API -- You can now get the API instance by calling `HuskSyncAPI#getInstance()` - -```java -import net.william278.husksync.api.HuskSyncAPI; - -public class HuskSyncAPIHook { - - private final HuskSyncAPI huskSyncAPI; - - public HuskSyncAPIHook() { - this.huskSyncAPI = HuskSyncAPI.getInstance(); - } - -} -``` - -## 4. CompletableFuture and Optional basics -- HuskSync's API methods return `CompletableFuture`s and `Optional`s. -- A `CompletableFuture` is an asynchronous callback mechanism. The method will be processed asynchronously and the data returned when it has been retrieved. While you can use `CompletableFuture#join()` to block the thread until the future has finished processing, it's smarter to use `CompletableFuture#thenAccept(data -> {})` to do what you want to do with the `data` you requested after it has asynchronously been retrieved, to prevent lag. -- An `Optional` is a null-safe representation of data, or no data. You can check if the Optional is empty via `Optional#isEmpty()` (which will be returned by the API if no data could be found for the call you made). If the optional does contain data, you can get it via `Optional#get()`. - -## 5. Getting a user by UUID +## 1. Getting a user by UUID - HuskSync has a `User` object, representing a user saved in the database. You can retrieve a user using `HuskSyncAPI#getUser(uuid)` - If you have an online `org.bukkit.Player` object, you can use `BukkitPlayer#adapt(player)` to get an `OnlineUser` (extends `User`), representing a logged-in user. @@ -75,7 +24,6 @@ public class HuskSyncAPIHook { public HuskSyncAPIHook() { this.huskSyncAPI = HuskSyncAPI.getInstance(); } - public void logUserName(UUID uuid) { // getUser() returns a CompletableFuture supplying an Optional @@ -87,14 +35,14 @@ public class HuskSyncAPIHook { return; } // The User object has two fields; uuid and username. - System.out.println("User name is: " + optionalUser.get().username); + System.out.println("User name is: %s", optionalUser.get().username); }); } } ``` -## 6. Getting a user's data +## 2. Getting a user's data - With a `User` object, we can now call `HuskSyncAPI#getUserData()` to fetch their latest data - The `UserData` object contains eight data "modules", each holding certain parts of information. - UserData does not have to contain any single data "module"; the modules contained in a given UserData object when user data is saved by the plugin are determined by the plugin config settings. @@ -130,7 +78,7 @@ public class HuskSyncAPIHook { Optional statusData = optionalUserData.get().getStatus(); // Print the health from the fields, if the user has a status object statusData.ifPresent(status -> { - System.out.println(user.username + "'s health: " + status.health + "/" + status.maxHealth); + System.out.println("%s's health: %d/%d", user.username, status.health, status.maxHealth); }); } }); @@ -139,7 +87,7 @@ public class HuskSyncAPIHook { } ``` -## 7. Getting a user's inventory contents +## 3. Getting a user's inventory contents - The API provides methods for deserialzing `ItemData` used to hold Base 64 serialized inventory and ender chest `ItemStack` array contents into actual `ItemStack` array data. - For deserialziing inventories, use `HuskSyncAPI#deserializeInventory(serializedItems)` - For deserialziing ender chests, use `HuskSyncAPI#deserializeItemStackArray(serializedItems)` @@ -212,7 +160,7 @@ private void printEnderChestItems(User user) { -## 8. Updating a user's data +## 4. Updating a user's data - You can use `HuskSyncAPI#setUserData(user, userData)` to set a user's modified data to the database. - If you need to modify user data every time it's updated, you may want to look at listening to one of HuskSync's provided events instead. - You can use `HuskSyncAPI#serializeItemStackArray(itemStack[])` to serialize an array of ItemStacks into Base 64. @@ -233,7 +181,7 @@ public class HuskSyncAPIHook { // This returns a CompletableFuture that will invoke #thenRun() when it has completed huskSyncAPI.setUserData(user, data).thenRun(() -> { - System.out.println("Healed " + user.username + "!"); + System.out.println("Healed %s!", user.username); }); } }); diff --git a/docs/API.md b/docs/API.md index ee31e87f..ef39ae8f 100644 --- a/docs/API.md +++ b/docs/API.md @@ -1,13 +1,14 @@ -The HuskSync API provides methods for retrieving and updating user data, as well as a number of events for tracking when user data is synced and saved. +The HuskSync API (v3) provides methods for retrieving and updating [data snapshots](Data-Snapshot-API), a number of [[API Events]] for tracking when user data is synced and saved, and infrastructure for registering serializers to [synchronise custom data types](Custom-Data-API). ## Compatibility [![Maven](https://repo.william278.net/api/badge/latest/releases/net/william278/husksync?color=00fb9a&name=Maven&prefix=v)](https://repo.william278.net/#/releases/net/william278/husksync/) The HuskSync API shares version numbering with the plugin itself for consistency and convenience. Please note minor and patch plugin releases may make API additions and deprecations, but will not introduce breaking changes without notice. -| API Version | HuskSync Versions | Supported | +| API Version | HuskSync Versions | Supported | |:-----------:|:--------------------:|:---------:| -| v2.x | _v2.0—Current_ | ✅ | +| v3.x | _v3.0—Current_ | ✅ | +| v2.x | _v2.0—v2.2.8_ | ❌ | | v1.x | _v1.0—v1.4.1_ | ❌️ |
@@ -16,10 +17,15 @@ The HuskSync API shares version numbering with the plugin itself for consistency HuskSync versions prior to `v2.2.5` are distributed on [JitPack](https://jitpack.io/#/net/william278/HuskSync), and you will need to use the `https://jitpack.io` repository instead.
-## Table of contents -1. Adding the API to your project -2. Adding HuskSync as a dependency -3. Next steps +## Table of Contents +1. [API Introduction](#api-introduction) + 1. [Setup with Maven](#11-setup-with-maven) + 2. [Setup with Gradle](#12-setup-with-gradle) +2. [Creating a class to interface with the API](#3-creating-a-class-to-interface-with-the-api) +3. [Checking if HuskSync is present and creating the hook](#4-checking-if-husksync-is-present-and-creating-the-hook) +4. [Getting an instance of the API](#5-getting-an-instance-of-the-api) +5. [CompletableFuture and Optional basics](#6-completablefuture-and-optional-basics) +6. [Next steps](#7-next-steps) ## API Introduction ### 1.1 Setup with Maven @@ -80,7 +86,59 @@ softdepend: # Or, use 'depend' here - HuskSync ``` -### 3. Next steps +## 3. Creating a class to interface with the API +- Unless your plugin completely relies on HuskSync, you shouldn't put HuskSync API calls into your main class, otherwise if HuskSync is not installed you'll encounter `ClassNotFoundException`s + +```java +public class HuskSyncAPIHook { + + public HuskSyncAPIHook() { + // Ready to do stuff with the API + } + +} +``` +## 4. Checking if HuskSync is present and creating the hook +- Check to make sure the HuskSync plugin is present before instantiating the API hook class + +```java +public class MyPlugin extends JavaPlugin { + + public HuskSyncAPIHook huskSyncAPIHook; + + @Override + public void onEnable() { + if (Bukkit.getPluginManager().getPlugin("HuskSync") != null) { + this.huskSyncAPIHook = new HuskSyncAPIHook(); + } + } +} +``` + +## 5. Getting an instance of the API +- You can now get the API instance by calling `HuskSyncAPI#getInstance()` + +```java +import net.william278.husksync.api.BukkitHuskSyncAPI; + +public class HuskSyncAPIHook { + + private final HuskSyncAPI huskSyncAPI; + + public HuskSyncAPIHook() { + this.huskSyncAPI = HuskSyncAPI.getInstance(); + } + +} +``` + +## 6. CompletableFuture and Optional basics +- HuskSync's API methods often deal with `CompletableFuture`s and `Optional`s. +- A `CompletableFuture` is an asynchronous callback mechanism. The method will be processed asynchronously and the data returned when it has been retrieved. While you can use `CompletableFuture#join()` to block the thread until the future has finished processing, it's smarter to use `CompletableFuture#thenAccept(data -> {})` to do what you want to do with the `data` you requested after it has asynchronously been retrieved, to prevent lag. +- An `Optional` is a null-safe representation of data, or no data. You can check if the Optional is empty via `Optional#isEmpty()` (which will be returned by the API if no data could be found for the call you made). If the optional does contain data, you can get it via `Optional#get(). + +### 7. Next steps Now that you've got everything ready, you can start doing stuff with the HuskSync API! -- [[UserData API]] — Get data snapshots and update current user data +- [[Data Snapshot API]] — Get, edit, create & delete data snapshots and update players +- [[Custom Data API]] — Register custom data types to sync your plugin's data with HuskSync - [[API Events]] — Listen to, cancel and modify the result of data synchronization events \ No newline at end of file diff --git a/docs/Commands.md b/docs/Commands.md index c5ab087b..cbab7b47 100644 --- a/docs/Commands.md +++ b/docs/Commands.md @@ -1,17 +1,97 @@ -This page contains a table of HuskSync commands and their required permission nodes. +This page contains a table of HuskSync commands and their required permission nodes. You can also use wildcard patterns for each command, such as `husksync.command..*` to grant access to all sub-commands. -| Command | Description | Permission | -|-----------------------------------------------|--------------------------------------|--------------------------------------| -| `/husksync` | Use `/husksync` subcommands | `husksync.command.husksync` | -| `/husksync info` | View plugin information | `husksync.command.husksync info` | -| `/husksync reload` | Reload config & message files | `husksync.command.husksync.reload` | -| `/husksync update` | Check if an update is available | `husksync.command.husksync.update` | -| `/husksync migrate [args]` | Migrate user data | _Console-only_ | -| `/userdata view [version_uuid]` | View a snapshot of user data | `husksync.command.userdata` | -| `/userdata restore ` | Restore a snapshot of user data | `husksync.command.userdata.manage` | -| `/userdata delete ` | Delete a snapshot of user data | `husksync.command.userdata.manage` | -| `/userdata pin ` | Pin a snapshot of user data | `husksync.command.userdata.manage` | -| `/inventory [version_uuid]` | View a user's inventory contents | `husksync.command.inventory`† | -| `/enderchest [version_uuid]` | View a user's ender chest contents | `husksync.command.enderchest`†| - -† The respective `husksync.command.inventory.edit` and `husksync.command.enderchest.edit` permission node is required to be able to edit a user's inventory/ender chest using the interface. \ No newline at end of file + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
CommandDescriptionPermission
/husksync/husksyncView & manage plugin system informationhusksync.command.husksync
/husksync aboutView information about the pluginhusksync.command.husksync.about
/husksync reloadReload the plugin configurationhusksync.command.husksync.reload
/husksync migrateMigrate data from other plugins/legacy versions(Console-only)
/husksync updateCheck for plugin updateshusksync.command.husksync.update
/userdata/userdataView & manage user data snapshotshusksync.command.userdata
/userdata listView a list of a player's data snapshotshusksync.command.userdata.list
/userdata viewView a player's user data snapshothusksync.command.userdata.view
/userdata restoreRestore a data snapshot for a userhusksync.command.userdata.restore
/userdata deleteDelete user data snapshotshusksync.command.userdata.delete
/userdata pinPin and unpin a user data snapshotshusksync.command.userdata.pin
/userdata dumpDump a user data snapshothusksync.command.userdata.dump
/inventoryView the inventory of a user/a data snapshothusksync.command.inventory
Edit the contents of a user's current inventoryhusksync.command.inventory.edit
/enderchestView the Ender Chest of a user/a data snapshothusksync.command.enderchest
Edit the contents of a user's current Ender Chesthusksync.command.enderchest.edit
\ No newline at end of file diff --git a/docs/Config-File.md b/docs/Config-File.md index 9e57b9ea..f19284db 100644 --- a/docs/Config-File.md +++ b/docs/Config-File.md @@ -10,65 +10,98 @@ This page contains the configuration file reference for HuskSync. The config fil # ┃ Developed by William278 ┃ # ┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ # ┣╸ Information: https://william278.net/project/husksync +# ┣╸ Config Help: https://william278.net/docs/husksync/config-file/ # ┗╸ Documentation: https://william278.net/docs/husksync +# Locale of the default language file to use. Docs: https://william278.net/docs/huskhomes/translations language: en-gb +# Whether to automatically check for plugin updates on startup check_for_updates: true +# Specify a common ID for grouping servers running HuskSync. Don't modify this unless you know what you're doing! cluster_id: '' +# Enable development debug logging debug_logging: false +# Whether to provide modern, rich TAB suggestions for commands (if available) +brigadier_tab_completion: false +# Whether to enable the Player Analytics hook. Docs: https://william278.net/docs/husksync/plan-hook +enable_plan_hook: true database: + # Type of database to use (MYSQL, MARIADB) + type: MYSQL credentials: - # Database connection settings + # Specify credentials here for your MYSQL or MARIADB database host: localhost port: 3306 database: HuskSync username: root password: pa55w0rd - parameters: ?autoReconnect=true&useSSL=false + parameters: ?autoReconnect=true&useSSL=false&useUnicode=true&characterEncoding=UTF-8 connection_pool: - # MySQL connection pool properties + # MYSQL / MARIADB database Hikari connection pool properties. Don't modify this unless you know what you're doing! maximum_pool_size: 10 minimum_idle: 10 maximum_lifetime: 1800000 keepalive_time: 0 connection_timeout: 5000 + # Names of tables to use on your database. Don't modify this unless you know what you're doing! table_names: users: husksync_users user_data: husksync_user_data redis: credentials: - # Redis connection settings + # Specify the credentials of your Redis database here. Set "password" to '' if you don't have one host: localhost port: 6379 password: '' use_ssl: false synchronization: - # Synchronization settings - max_user_data_snapshots: 5 + # The number of data snapshot backups that should be kept at once per user + max_user_data_snapshots: 16 + # Number of hours between new snapshots being saved as backups (Use "0" to backup all snapshots) + snapshot_backup_frequency: 4 + # List of save cause IDs for which a snapshot will be automatically pinned (so it won't be rotated). Docs: https://william278.net/docs/husksync/data-rotation#save-causes + auto_pinned_save_causes: + - INVENTORY_COMMAND + - ENDERCHEST_COMMAND + - BACKUP_RESTORE + - CONVERTED_FROM_V2 + - LEGACY_MIGRATION + - MPDB_MIGRATION + # Whether to create a snapshot for users on a world when the server saves that world save_on_world_save: true + # Whether to create a snapshot for users when they die (containing their death drops) save_on_death: false + # Whether to save empty death drops for users when they die save_empty_drops_on_death: true + # Whether to use the snappy data compression algorithm. Keep on unless you know what you're doing compress_data: true + # Where to display sync notifications (ACTION_BAR, CHAT, TOAST or NONE) notification_display_slot: ACTION_BAR - synchronise_dead_players_changing_server: true + # (Experimental) Persist Cartography Table locked maps to let them be viewed on any server + persist_locked_maps: false + # Whether dead players who log out and log in to a different server should have their items saved. You may need to modify this if you're using the keepInventory gamerule. + synchronize_dead_players_changing_server: true + # How long, in milliseconds, this server should wait for a response from the redis server before pulling data from the database instead (i.e., if the user did not change servers). network_latency_milliseconds: 500 + # Which data types to synchronize (Docs: https://william278.net/docs/husksync/sync-features) features: - health: true - statistics: true - persistent_data_container: false hunger: true - ender_chests: true - advancements: true - location: false + persistent_data: false + inventory: true game_mode: true - potion_effects: true - locked_maps: false - inventories: true - max_health: true + advancements: true experience: true - blacklisted_commands_while_locked: [] + ender_chest: true + potion_effects: true + location: false + statistics: true + health: true + # Commands which should be blocked before a player has finished syncing (Use * to block all commands) + blacklisted_commands_while_locked: + - '*' + # Event priorities for listeners (HIGHEST, NORMAL, LOWEST). Change if you encounter plugin conflicts event_priorities: - join_listener: LOWEST quit_listener: LOWEST + join_listener: LOWEST death_listener: NORMAL ``` diff --git a/docs/Custom-Data-API.md b/docs/Custom-Data-API.md new file mode 100644 index 00000000..d2e438ad --- /dev/null +++ b/docs/Custom-Data-API.md @@ -0,0 +1,131 @@ +HuskSync allows you to save and synchronize custom data through the existing versatile DataSnapshot format. This page assumes you've read the [[API]] introduction and are familiar with the aforementioned [[Data Snapshot API]]. + +To do this, you create and register an implementation of a platform `Data` class (e.g., `BukkitData`) and a corresponding `Serializer` class (e.g., `BukkitSerializer`). You can then apply your custom data type to a user using the `OnlineUser#setData(Identifier, Data)` method. + +> **Note:** Before you begin, consider if this is what you'd like to do. For simpler/smaller data sync tasks you may wish to consider using the PersistentDataContainer API format instead, which is a bit more portable if you decide to exit the HuskSync ecosystem. + +## Table of Contents +1. [Extending the BukkitData Class](#1-extending-the-bukkitdata-class) + 1. [Implementing Adaptable](#11-implementing-adaptable) +2. [Extending the BukkitSerializer Class](#2-extending-the-bukkitserializer-class) +3. [Identifiers and registering our Serializer](#3-identifiers--registering-our-serializer) +4. [Setting and Getting our Data to/from a User](#4-setting-and-getting-our-data-tofrom-a-user) + +## 1. Extending the BukkitData Class +* HuskSync provides a `Data` interface that you must implement that will represent your custom data. +* On the Bukkit platform, you should create a class that `extends` `BukkitData`. This class has method to implement: `#apply(BukkitUser, BukkitHuskSync)`, which will be called when the data needs to be applied to the player. +* You can use the `BukkitUser` class to get the `Player` object of the user. Avoid using the `BukkitHuskSync` class as this is for accessing plugin internals. + +
+Code Example — LoginParticleData class + +```java +// An example of a BukkitData class that you could use in a cosmetic plugin to store player particle data. +public class LoginParticleData extends BukkitData { + + private String particleId; + private int numberOfParticles; + + public LoginParticleData(String particleId, int numberOfParticles) { + this.particleId = particleId; + this.numberOfParticles = numberOfParticles; + } + + // This method is called whenever a user has their data applied. + // If you just want to use HuskSync to sync data used elsewhere, you don't have to do anything here, of course + @Override + public void apply(BukkitUser user, BukkitHuskSync plugin) { + final Player player = user.getPlayer(); + + // Let's use the Bukkit API to spawn some particles when a user's data is applied (e.g. when they login). + player.spawnParticle(Particle.valueOf(particleId), player.getLocation(), numberOfParticles); + } + +} +``` +
+ +### 1.1 Implementing Adaptable +* HuskSync provides the `Adaptable` marker interface to make it easier to Serialize and Deserialize your data using Gson (needed in the next step). +* I strongly advise implementing `Adaptable`. This requires a zero-arg constructor. Note that you _cannot_ serialize proprietary data types or `final` fields using `Adaptable`. + +
+Code Example — Adaptable LoginParticleData class + +```java +// We've implemented Adaptable here to make it easier to serialize and deserialize our data using Gson. +public class LoginParticleData extends BukkitData implements Adaptable { + + private String particleId; + private int numberOfParticles; + + public LoginParticleData(String particleId, int numberOfParticles) { + this.particleId = particleId; + this.numberOfParticles = numberOfParticles; + } + + @SuppressWarnings("unused") // Suppress compiler warnings + private LoginParticleData() { + // This is required for the Adaptable interface so that Gson can intantiate the class when deserializing. + } + + @Override + public void apply(BukkitUser user, BukkitHuskSync plugin) { + user.getPlayer().spawnParticle(Particle.valueOf(particleId), player.getLocation(), numberOfParticles); + } + +} +``` +
+ +## 2. Extending the BukkitSerializer Class +* To store your `Data`, you'll need to provide a `Serializer` class that will be used to serialize and deserialize your `Data` to and from a java `String` that can later be converted to a byte array and compressed/stored by HuskSync. + * For instance, you'd need a class like: `public class LoginParticleSerializer extends BukkitSerializer implements Serializer` to serialize the previous example. + * You'd then need to implement the `Serializer` interface, which has two methods: `#serialize(T)` and `#deserialize(String)`. +* If you made your class `Adaptable` as per above HuskSync also provides a `BukkitSerializer.Json` class which you can extend to create a simple serializer using Gson. + * This is the recommended way of creating a serializer, though, if you're dealing with NBT data, you may wish to implement a base Serializer with your own methods. + +```java +// An example of a BukkitSerializer class that you could use in a cosmetic plugin to store player particle data. +public class LoginParticleSerializer extends BukkitSerializer.Json implements Serializer { + + // We need to create a constructor that takes our instance of the API + public GameMode(@NotNull HuskSyncAPI api) { + super(api, LoginParticleData.class); // We pass the class type here so that Gson knows what class we're serializing + } + +} +``` + +## 3. Identifiers & registering our Serializer +* Now that we have our `Data` and `Serializer` classes, we need to register them with HuskSync. +* To do this, we register an `Identifier` with HuskSync. This is a unique identifier key for your data type. + * Use `Identifer#from(String, String)` or `Identifier#from(Key)` to create an identifier from a namespace-value pair or an adventure `Key` object. +* Make sure that the plugin you're writing registers the serializer on every server so that HuskSync will serialize the data. + +```java +// Create an identifier for our data (you may wish to store this somewhere where it can be accessed statically) +public static Identifier LOGIN_PARTICLES_ID = Identifier.from("myplugin", "login_particles"); + +// (...) + +// Register our serializer +huskSyncAPI.registerSerializer(LOGIN_PARTICLES_ID, new LoginParticleSerializer(HuskSyncAPI.getInstance())); +``` + +## 4. Setting and getting our Data to/from a User +* Now that we've registered our `Data` and `Serializer` classes, we can set our data to a user, applying it to them. +* To do this, we use the `OnlineUser#setData(Identifier, Data)` method. + * This method will apply the data to the user, and store the data to the plugin player custom data map, to allow the data to be retrieved later and be saved to snapshots. +* Snapshots created on servers where the data type is registered will now contain our data and synchronise between instances! + +```java +// Create an instance of our data +LoginParticleData loginParticleData = new LoginParticleData("FIREWORKS_SPARK", 10); + +// Set the data to a player +huskSyncAPI.getUser(player).setData(LOGIN_PARTICLES_ID, loginParticleData); + +// Get our data from a player +LoginParticleData loginParticleData = (LoginParticleData) huskSyncAPI.getUser(player).getData(LOGIN_PARTICLES_ID); +``` \ No newline at end of file diff --git a/docs/Data-Rotation.md b/docs/Data-Rotation.md index 274ea5be..1203f577 100644 --- a/docs/Data-Rotation.md +++ b/docs/Data-Rotation.md @@ -8,26 +8,29 @@ Each user data snapshot has: - a timestamp (when it was created) - a save cause (why it was created) - a flag to indicate if the snapshot has been pinned (preventing it from being rotated) +- a map of saved data -By default, HuskSync will store 5 user data snapshots about a user (including their latest snapshot). After that, when a new user snapshot is set, the oldest snapshot will automatically be deleted. You can change the number of snapshots to keep by changing the `max_user_data_snapshots` setting in the `config.yml` file (minimum 1). +By default, HuskSync will automatically replace the user's current snapshot in the database if it has been less than 4 hours since the last snapshot was created. This can be changed in the `config.yml` file by changing the `snapshot_backup_frequency` setting under `synchronization`. Setting this to "0" will save a new snapshot each time data is saved. -Pinned user data snapshots are exempt from being rotated and can only be deleted manually in-game. +HuskSync will keep the 16 most recent data snapshots for each user (including their current data). After that, when a new user snapshot is set, the oldest snapshot will automatically be deleted. You can change the number of snapshots to keep by changing the `max_user_data_snapshots` setting (minimum 1). + +Pinned user data snapshots are exempt from being replaced/rotated and can only be deleted manually in-game. ## Viewing user data -To view a list of a user's snapshots, use `/userdata list `. Their most recent snapshots will be listed from the database, from newest to oldest. You can click the buttons to navigate through their pages. +To view a list of a user's snapshots, use `/userdata list [username]`. Their most recent snapshots will be listed from the database, from newest to oldest. You can click the buttons to navigate through their pages. -[![Data snapshot list](https://raw.githubusercontent.com/WiIIiam278/HuskSync/master/images/data-snapshot-list.png)](#) +![Data snapshot list](https://raw.githubusercontent.com/WiIIiam278/HuskSync/master/images/data-snapshot-list.png) Snapshots marked with a star after the number have been pinned. Hover over it to view more information. -You can then click on the items in the list in chat to view an overview of each snapshot. Alternatively, to view a user's most recent data snapshot, use `/userdata view `. +You can then click on the items in the list in chat to view an overview of each snapshot. Alternatively, to view a user's most recent data snapshot, use `/userdata view [username]`. -[![Data snapshot viewer](https://raw.githubusercontent.com/WiIIiam278/HuskSync/master/images/data-snapshot-viewer.png)](#) +[Data snapshot viewer](https://raw.githubusercontent.com/WiIIiam278/HuskSync/master/images/data-snapshot-viewer.png) ## Managing user data You can use the "Manage" buttons to manage user data. These buttons will only appear if you have the userdata command manage permission. (See [[Commands]]) - Click on "Delete" to remove the data -- Click on "Restore" to restore the user data. If the user is online, their items and stats will be updated, otherwise they will be set to this data upon next login. +- Click on "Restore" to restore the user data. If the user is online, their items and stats will be updated, otherwise their data will be set to this snapshot upon their next login. - Click on "Pin" to pin the user data. An indicator will appear in the data viewer and list marking the snapshot as being pinned. ## Save causes @@ -39,7 +42,8 @@ Data save causes, marked with a 🚩 flag, indicate what caused the data to be s - **inventory command**: Indicates data was saved by editing inventory contents via the `/inventory` command - **enderchest command**: Indicates data was saved by editing Ender Chest contents via the `/enderchest` command - **backup restore**: Indicates data was saved by restoring it from a previous version -- **api**: Indicates data was saved by an [[API]] call +- **api**: Indicates data was saved by a call to the HuskSync [[API]] - **mpdb migration**: Indicates data was saved from being imported from MySQLPlayerDataBridge (See [[MPDB Migration]]) - **legacy migration**: Indicates data was saved from being imported from a legacy version (v1.x - See [[Legacy Migration]]) -- **unknown**: Indicates data was saved by an unknown cause. \ No newline at end of file +- **converted from v2**: Indicates data was automatically converted from HuskSync v2.0's data format +- **unknown**: Indicates data was saved by an unknown saveCause. \ No newline at end of file diff --git a/docs/Data-Snapshot-API.md b/docs/Data-Snapshot-API.md new file mode 100644 index 00000000..9480d4c0 --- /dev/null +++ b/docs/Data-Snapshot-API.md @@ -0,0 +1,458 @@ +HuskSync v3.0 provides an API for getting, creating, editing and deleting `DataSnapshot`s; a snapshot of a user at a given moment in time. This page will walk you through how to manipulate delete snapshots using the HuskSync API. + +This page assumes you have read the general [[API]] introduction and that you have both imported HuskSync (v3.x) into your project and added it as a dependency. + +## Table of Contents +1. [Getting a User](#1-getting-a-user) +2. [Getting DataSnapshots for a User](#2-getting-datasnapshots-for-a-user) + 1. [Getting a User's current data](#21-getting-a-users-current-data) + 2. [Getting a User's latest saved DataSnapshot](#22-getting-a-users-latest-saved-datasnapshot) + 3. [Getting a list of a User's saved DataSnapshots](#23-getting-a-list-of-a-users-saved-datasnapshots) +3. [Packing and Unpacking DataSnapshots](#3-packing-and-unpacking-datasnapshots) +4. [Getting and setting data in a DataSnapshot](#4-getting-and-setting-data-in-a-datasnapshot) + 1. [Data Types](#41-data-types) + 2. [Editing Health, Hunger, Experience, and GameMode data](#42-editing-health-hunger-experience-and-gamemode-data) + 3. [Editing Inventory and Ender Chest data](#43-editing-inventory-and-ender-chest-data) + 4. [Editing Location data](#44-editing-location-data) + 5. [Editing Advancement data](#45-editing-advancement-data) +5. [Creating new DataSnapshots](#5-creating-new-datasnapshots) + 1. [Creating a new snapshot from a player's current data](#51-creating-a-new-snapshot-from-a-players-current-data) + 2. [Creating a new snapshot from scratch](#52-creating-a-new-snapshot-from-scratch) +6. [Deleting DataSnapshots](#6-deleting-datasnapshots) + +## 1. Getting a User +* HuskSync has a `User` object, representing a user saved in the database. You can retrieve a user using `HuskSyncAPI#getUser(uuid)` + +
+Code Example — Getting a user by UUID + +```java +// getUser() returns a CompletableFuture supplying an Optional +huskSyncAPI.getUser(uuid).thenAccept(optionalUser -> { + // Check if we found a user by that UUID either online or on the database + if (optionalUser.isEmpty()) { + // If we didn't, we'll log that they don't exist + System.out.println("User does not exist!"); + return; + } + + // The User object provides methods for getting a user's UUID and username + System.out.println("Found %s", optionalUser.get().getUsername()); +}); +``` +
+ +* If you have an online `org.bukkit.Player` object, you can use `BukkitPlayer#adapt(player)` to get an `OnlineUser` (extends `User`), representing a logged-in user. + +
+Code Example — Getting an online user + +```java +// Get an online user +OnlineUser user = huskSyncAPI.getUser(player); +System.out.println("Hello, %s!", user.getUsername()); +``` +
+ +## 2. Getting DataSnapshots for a User +### 2.1 Getting a User's current data +* HuskSync provides a method for getting the user's current data. `HuskSyncAPI#getCurrentData(User)` returns a `CompletableFuture` supplying an `Optional`. +* This method will get the user's current data if they are online on the network, or their last saved data if they are offline (or, an empty optional if they user has never logged on). + +
+Code Example — Getting a user's current DataSnapshot + +```java +// Get a user's current data +huskSyncAPI.getCurrentData(user).thenAccept(optionalSnapshot -> { + if (optionalSnapshot.isEmpty()) { + System.out.println("Couldn't get data for %s", user.getUsername()); + return; + } + + // Get the snapshot, which you can then do stuff with + DataSnapshot.Unpacked snapshot = optionalSnapshot.get(); +}); +``` +
+ +### 2.2 Getting a User's latest saved DataSnapshot +* Note that the snapshot returned by the previous method _is not necessarily saved in the database_. +* If you want to get the user's last saved snapshot, use `HuskSyncAPI#getLatestSnapshot(User)` instead: + +
+Code Example — Getting a user's latest saved DataSnapshot + +```java +// Get a user's latest saved snapshot +huskSyncAPI.getLatestSnapshot(user).thenAccept(optionalSnapshot -> { + if (optionalSnapshot.isEmpty()) { + System.out.println("%s has no saved snapshots!", user.getUsername()); + return; + } + + // Get the snapshot, which you can then do stuff with + DataSnapshot.Unpacked snapshot = optionalSnapshot.get(); +}); +``` +
+ +### 2.3 Getting a list of a User's saved DataSnapshots +* If you want to get a list of all of a user's saved snapshots, you can use `HuskSyncAPI#getSnapshots(User)`. This method returns a `CompletableFuture` supplying an `Optional>`. + +
+Code Example — Getting all of a user's saved DataSnapshots + +```java +// Get a user's saved snapshots +huskSyncAPI.getSnapshots(user).thenAccept(optionalSnapshots -> { + if (optionalSnapshots.isEmpty()) { + System.out.println("%s has no saved snapshots!", user.getUsername()); + return; + } + + // Get the list of snapshots, which you can then do stuff with + List snapshots = optionalSnapshots.get(); +}); +``` +
+ +## 3. Packing and Unpacking DataSnapshots +* HuskSync provides two types of `DataSnapshot` objects: `DataSnapshot.Packed` and `DataSnapshot.Unpacked`. + - `DataSnapshot.Packed` is a snapshot that has had its data serialized into a byte map. This snapshot is ready to be saved in the database or set to Redis. + - `DataSnapshot.Unpacked` is a snapshot that has been unpacked from a `DataSnapshot.Packed` object. You can get, set, and manipulate data from these snapshots. +* Most of the time, you won't need to worry about this, as HuskSync typically deals with `Unpacked` snapshots. However, if you need to convert between the two (e.g., if you wish to copy the snapshot), you can use the `HuskSyncAPI#packSnapshot(DataSnapshot.Unpacked)` and `HuskSyncAPI#unpackSnapshot(DataSnapshot.Packed)` methods. +* The editor method `HuskSyncAPI#editPackedSnapshot(DataSnapshot.Packed, Consumer)` additionally provides a utility for unpacking, editing, then repacking a packed `DataSnapshot` object. + +
+Code Example — Packing and unpacking snapshots + +```java +// Get a user's current data +huskSyncAPI.getCurrentData(user).thenAccept(optionalSnapshot -> { + if (optionalSnapshot.isEmpty()) { + System.out.println("User does not exist!"); + return; + } + + // Get the snapshot + DataSnapshot.Unpacked snapshot = optionalSnapshot.get(); + + // Pack the snapshot + DataSnapshot.Packed packedSnapshot = huskSyncAPI.packSnapshot(snapshot); + // You can call #copy() on a packed snapshot to make a copy of it, which you can then edit + + // Unpack the snapshot again + DataSnapshot.Unpacked unpackedSnapshot = huskSyncAPI.unpackSnapshot(packedSnapshot); +}); +``` +
+ +## 4. Getting and setting data in a DataSnapshot +* Data within `DataSnapshot`s is represented by `Data` objects of different types; `Data.Items.Inventory` represents Inventory data, `Data.Health` represents a user's current/max health, `Data.Hunger` represents a user's current/max hunger, and so on. +* On Bukkit servers, `BukkitData` classes implement `Data` classes and provide utilities for converting between `Bukkit` and `HuskSync` data types. +* `DataSnapshot.Unpacked` provides methods for getting and setting `Data` in the snapshot, such as `DataSnapshot.Unpacked#getInventory()` (which returns an `Optional`) and `DataSnapshot.Unpacked#setHealth(Data.Health)`. + +### 4.1 Data Types +| Identifier Key | Description | Get Method | Set Method | +|----------------------------|--------------------------------------|-----------------------|------------------------| +| `husksync:inventory` | User inventories & held item slot | `#getInventory` | `#setInventory` | +| `husksync:ender_chest` | User Ender Chests | `#getEnderChest` | `#setEnderChest` | +| `husksync:potion_effects` | User active potion effects | `#getPotionEffects` | `#setPotionEffects` | +| `husksync:advancements` | User advancements | `#getAdvancements` | `#setAdvancements` | +| `husksync:location` | User location | `#getLocation` | `#setLocation` | +| `husksync:statistics` | User statistics | `#getStatistics` | `#setStatistics` | +| `husksync:health` | User health | `#getHealth` | `#setHealth` | +| `husksync:hunger` | User hunger, saturation & exhaustion | `#getHunger` | `#setHunger` | +| `husksync:experience` | User level, experience, and score | `#getExperience` | `#setExperience` | +| `husksync:game_mode` | User game mode and flight status | `#getGameMode` | `#setGameMode` | +| `husksync:persistent_data` | User persistent data container | `#getPersistentData` | `#setPersistentData` | +| Custom types; `plugin:foo` | Any custom data | `#getData(Identifer)` | `#setData(Identifier)` | + +* Plugin developers may supply their own `Data` classes for synchronisation & saving by implementing the `Data` interface and registering a `Serializer<>` for their class to an `Identifier`. See the [[Custom Data API]] page for more information. +* You can only get data from snapshots where a serializer has been registered for it on this server and, in the case of the built-in data types, where the sync feature has been enabled in the [[Config File]]. If you try to get data from a snapshot where the data type is not supported, you will get an empty `Optional`. + +### 4.2 Editing Health, Hunger, Experience, and GameMode data +* `DataSnapshot.Unpacked#getHealth()` returns an `Optional`, which you can then use to get the player's current and max health. +* `DataSnapshot.Unpacked#setHealth(Data.Health)` sets the player's current and max health. You can create a `Health` instance to pass on the Bukkit platform through `BukkitData.Health.from(double, double, double)`. +* Similar methods exist for Hunger, Experience, and GameMode data types +* Once you've updated the data in the snapshot, you can save it to the database using `HuskSyncAPI#setCurrentData(user, userData)`. + +
+Code Example — Getting and setting a player's health + +```java +// Get a user's current data +huskSyncAPI.getCurrentData(user).thenAccept(optionalSnapshot -> { + if (optionalSnapshot.isEmpty()) { + System.out.println("User does not exist!"); + return; + } + + // Get the player's health and game mode from the snapshot + DataSnapshot.Unpacked snapshot = optionalSnapshot.get(); + Optional healthOptional = snapshot.getHealth(); + if (healthOptional.isEmpty()) { + System.out.println("User has no health data!"); + return; + } + Optional gameModeOptional = snapshot.getGameMode(); + if (gameModeOptional.isEmpty()) { + System.out.println("User has no game mode data!"); + return; + } + // getExperience() and getHunger() work similarly + + // Get the health data + Data.Health health = healthOptional.get(); + double currentHealth = health.getCurrentHealth(); // Current health + double maxHealth = health.getMaxHealth(); // Max health + double healthScale = health.getHealthScale(); // Health scale (e.g., 20 for 20 hearts) + snapshot.setHealth(BukkitData.Health.from(20, 20, 20)); + + // Get the game mode data + Data.GameMode gameMode = gameModeOptional.get(); + String gameModeName = gameMode.getGameModeName(); // Game mode name (e.g., "SURVIVAL") + boolean isFlying = gameMode.isFlying(); // Whether the player is *currently* flying + boolean canFly = gameMode.canFly(); // Whether the player *can* fly + snapshot.setGameMode(BukkitData.GameMode.from("SURVIVAL", false, false)); + + // Save the snapshot - This will update the player if online and save the snapshot to the database + huskSyncAPI.setCurrentData(user, snapshot); +}); +``` +
+ +* To make this code more concise, we can use the `HuskSyncAPI#editCurrentData()` method to get the user's current data and perform an operation in a `Consumer` class. +* The result of editing the `DataSnapshot` object in the `Consumer` is then automatically passed to `HuskSyncAPI#setCurrentData()` to save the snapshot to the database and update the user if they are online + +
+Code Example — Editing a player's health + +```java +// Edit a user's current data +huskSyncAPI.editCurrentData(user, snapshot -> { + // Get the player's health + Optional healthOptional = snapshot.getHealth(); + if (healthOptional.isEmpty()) { + System.out.println("User has no health data!"); + return; + } + + // Get the health data + Data.Health health = healthOptional.get(); + + // Get the player's current health + double currentHealth = health.getCurrentHealth(); + + // Get the player's max health + double maxHealth = health.getMaxHealth(); + + // Set the player's health + snapshot.setHealth(BukkitData.Health.from(20, 20, 20)); +}); +``` +
+ +### 4.3 Editing Inventory and Ender Chest data +* We can get a player's inventory using `DataSnapshot.Unpacked#getInventory()`, which returns an `Optional`. You can also get the player's Ender Chest inventory using `DataSnapshot.Unpacked#getEnderChest()`. +* `Data.Items.Inventory` provides methods for the player's inventory, armor, offhand, and ender chest items as platform-agnostic `Stack` objects, which lets you view basic Item information, but does not expose their full NBT data. +* On Bukkit, simply cast a `Data.Items.(Inventory/EnderChest)` to a `BukkitData.Items.(Inventory/EnderChest)` to get access to the Bukkit `ItemStack[]` contents of the player's items, allowing you to edit the contents. + +
+Code Example — Getting and setting a player's inventory or Ender Chest + +```java +// Get a user's current data +huskSyncAPI.getCurrentData(user).thenAccept(optionalSnapshot -> { + if (optionalSnapshot.isEmpty()) { + System.out.println("User does not exist!"); + return; + } + + // Get the snapshot + DataSnapshot.Unpacked snapshot = optionalSnapshot.get(); + + // Get the player's inventory + Optional inventoryOptional = snapshot.getInventory(); + if (inventoryOptional.isEmpty()) { + System.out.println("User has no inventory data!"); + return; + } + + // Get the inventory data + Data.Items.Inventory inventory = inventoryOptional.get(); + + // Get the player's inventory contents + ItemStack[] inventoryContents = ((BukkitData.Items.Inventory) inventory).getContents(); + + // Set the player's inventory contents + ((BukkitData.Items.Inventory) inventory).setContents(inventoryContents); + + // Save the snapshot - This will update the player if online and save the snapshot to the database + huskSyncAPI.setCurrentData(user, snapshot); +}); +``` +
+ +* There also exist utility methods for both getting and setting just the player's current inventory or Ender Chest contents, if all you need to do is just update the player's inventory/Ender Chest. +* The Inventory methods are `#getCurrentInventory`, `#setCurrentInventory`, and `#editCurrentInventory`. For Ender chests, these are `#getCurrentEnderChest`, `#setCurrentEnderChest`, and `#editCurrentEnderChest`. There's also `Contents` methods that just deal with ItemStacks[], if you prefer. + +
+Code Example — Editing a player inventory + +```java +// Edit a user's current inventory +huskSyncAPI.editCurrentInventory(user, inventory -> { + // Get the player's inventory contents + ItemStack[] inventoryContents = ((BukkitData.Items.Inventory) inventory).getContents(); + + // The array of ItemStacks is a copy of the player's inventory contents (in 1.20.1, this is an array of length 42) + inventoryContents[0] = new ItemStack(Material.DIAMOND_SWORD); + inventoryContents[1] = null; // null = an empty slot + + // Set the player's inventory contents + ((BukkitData.Items.Inventory) inventory).setContents(inventoryContents); +}); +``` +
+ +### 4.4 Editing Location data +* HuskSync's support for player Locations is intended for mirrored world instances (such as RPG servers), and so is disabled by default in the plugin config. +* We can get a player's location using `DataSnapshot.Unpacked#getLocation()`, which returns an `Optional`. +* `Data.Location` provides methods for getting and setting the player's location, pitch, and yaw. We can also use the aforementioned `BukkitData` classes to set this using a `org.bukkit.Location`, and speed things along using the `HuskSyncAPI#editCurrentData` method. + +
+Code Example — Editing a player's location + +```java +// Edit a user's current data +huskSyncAPI.editCurrentData(user, snapshot -> { + // Get the player's location + Optional locationOptional = snapshot.getLocation(); + if (locationOptional.isEmpty()) { + System.out.println("User has no location data!"); + return; + } + + // Get the location data + Data.Location location = locationOptional.get(); + + // Get the player's location + org.bukkit.Location bukkitLocation = ((BukkitData.Location) location).getLocation(); + + // Set the player's location + ((BukkitData.Location) location).setLocation(bukkitLocation); +}); +``` +
+ +### 4.5 Editing Advancement data +* Advancements can be retrieved using `DataSnapshot.Unpacked#getAdvancements()`, which returns an `Optional`. +* `Data.Advancements` provides a wrapper for a list of `Data.Advancements.Advancement` objects, representing a map of a player's completed criteria when progressing to complete an advancement. +* You can add and remove advancements from the list, and set the list of advancements using `Data.Advancements#setAdvancements(List)`. + +
+Code Example — Editing a player's advancements + +```java +// Edit a user's current data +huskSyncAPI.editCurrentData(user, snapshot -> { + // Get the player's advancements + Optional advancementsOptional = snapshot.getAdvancements(); + if (advancementsOptional.isEmpty()) { + System.out.println("User has no advancements data!"); + return; + } + + // Get the advancements data + Data.Advancements advancements = advancementsOptional.get(); + + // Get the player's advancements + List playerAdvancements = new ArrayList<>(advancements.getAdvancements()); + + // Advancement progress is represented by completed critera entries, mapped to when said criteria was completed + Map criteria = Map.of("criteria_item_1", new Date()); + + // Add an advancement to the player's advancements + playerAdvancements.add(Data.Advancements.Advancement.adapt("foo:bar/baz", criteria)); + + // Remove all "recipe" advancements from the player's advancements + playerAdvancements.removeIf(advancement -> advancement.getIdentifier().startsWith("minecraft:recipes/")); + + // Set the player's advancements + advancements.setAdvancements(playerAdvancements); +}); +``` +
+ +## 5. Creating new DataSnapshots +* HuskSync provides methods for creating new snapshots; either by capturing a player's current data or by creating a new snapshot from scratch using a `DataSnapshot.Builder`. + +### 5.1 Creating a new snapshot from a player's current data +* You can create a new snapshot from a player's current data using `HuskSyncAPI#createSnapshot(OnlineUser)`, which returns a `DataSnapshot.Packed` with a save cause of `SaveCause.API`. + +
+Code Example — Capturing a player's current data into a Snapshot + +```java +// Create a new snapshot from a player's current data +final DataSnapshot.Packed data = huskSyncAPI.createSnapshot(user); + +// editPackedSnapshot() provides a utility for unpacking, editing, then repacking a DataSnapshot object +final DataSnapshot.Packed edited = huskSyncAPI.editPackedSnapshot(data, (unpacked) -> { + unpacked.setHealth(BukkitData.Health.from(10, 20, 20)); // Example - sets the user's health to 10 (5 hearts) +}); + +// Save the snapshot - This will save the snapshot to the database +huskSyncAPI.addSnapshot(edited); +``` +
+ +### 5.2 Creating a new snapshot from scratch +* You can create a new snapshot from scratch using a `DataSnapshot.Builder`. This is useful if you want to create a custom snapshot with specific data and apply it to a user. +* Get a new `DataSnapshot.Builder` using `HuskSyncAPI#snapshotBuilder()`. + +
+Code Example — Creating a new snapshot from scratch + +```java +// Create a new snapshot from scratch +final DataSnapshot.Builder builder = huskSyncAPI.snapshotBuilder(); + +// Create an empty inventory with a diamond sword in the first slot +final BukkitData.Items.Inventory inventory = BukkitData.Items.Inventory.empty(); +inventory.setContents(new ItemStack[] { new ItemStack(Material.DIAMOND_SWORD) }); +inventory.setHeldItemSlot(0); // Set the player's held item slot to the first slot + +// Use the builder to create, then pack, a new snapshot +final DataSnapshot.Packed packed = builder + .saveCause(SaveCause.API) // This is the default save cause, but you can change it if you want + .setTimestamp(OffsetDateTime.now().minusDays(3)) // Set the timestamp to 3 days ago + .setInventory(inventory) // Set the player's inventory + .setHealth(BukkitData.Health.from(10, 20, 20)) // Set the player to having 5 hearts + .buildAndPack(); // You can also call just #build() to get a DataSnapshot.Unpacked + +// Save the snapshot - This will save the snapshot to the database for a User +huskSyncAPI.addSnapshot(user, packed); +``` +
+ +## 6. Deleting DataSnapshots +* You can delete a snapshot using `HuskSyncAPI#deleteSnapshot(User, UUID)`, which will delete a snapshot from the database by its UUID. +* This method returns a CompletableFuture which will resolve to `true` if there was a snapshot with that UUID to delete, or `false` if there was no snapshot with that UUID to delete. + +
+Code Example — Deleting a snapshot + +```java +// Delete a snapshot +huskSyncAPI.deleteSnapshot(user, uuid).thenAccept(success -> { + if (success) { + System.out.println("Deleted snapshot with UUID %s", uuid); + } else { + System.out.println("No snapshot with UUID %s to delete", uuid); + } +}); +``` +
\ No newline at end of file diff --git a/docs/Dumping-UserData.md b/docs/Dumping-UserData.md index 039eca46..03a1a494 100644 --- a/docs/Dumping-UserData.md +++ b/docs/Dumping-UserData.md @@ -3,322 +3,43 @@ It's possible to dump user data snapshots to `json` objects as of HuskSync v2.1, This can be useful in debugging synchronization problems or for manually inspecting data. ## How-to guide -1. Grant yourself the special `husksync.command.userdata.dump` permission node. This is not set by default, even for operators. +1. Ensure you have the `husksync.command.userdata.dump` permission node. This is not set by default, even for operators. 2. Use the `/userdata list ` command to view a list of user data entries for a user. 3. Click on one of the user data entries for your chosen user. The data snapshot preview menu should appear, along with two new buttons at the bottom. -[![Data dumping buttons](https://raw.githubusercontent.com/WiIIiam278/HuskSync/master/images/data-dumping.png)](#) +![Data dumping buttons](https://raw.githubusercontent.com/WiIIiam278/HuskSync/master/images/data-dumping.png) ### Dumping to a file After clicking the "File Dump..." button (equivalent to `/userdata dump file`), a dump of this user data entry will be output in `~/plugins/HuskSync/dumps/`. -The name of the generated .json file will match the following format: `___.json` +The name of the generated .json file will match the following format: `___.json`
Example output file: William278_2022-10-12_21-46-37_disconnect_f7719f5c.json ```json { - "status": { - "health": 20.0, - "max_health": 20.0, - "health_scale": 0.0, - "hunger": 20, - "saturation": 0.0, - "saturation_exhaustion": 0.24399996, - "selected_item_slot": 1, - "total_experience": 0, - "experience_level": 0, - "experience_progress": 0.0, - "game_mode": "CREATIVE", - "is_flying": true - }, - "inventory": { - "serialized_items": "rO0ABXcEAAAAKXBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBzcgAXamF2YS51dGlsLkxp\r\nbmtlZEhhc2hNYXA0wE5cEGzA+wIAAVoAC2FjY2Vzc09yZGVyeHIAEWphdmEudXRpbC5IYXNoTWFw\r\nBQfawcMWYNEDAAJGAApsb2FkRmFjdG9ySQAJdGhyZXNob2xkeHA/QAAAAAAADHcIAAAAEAAAAAJ0\r\nAAF2c3IAEWphdmEubGFuZy5JbnRlZ2VyEuKgpPeBhzgCAAFJAAV2YWx1ZXhyABBqYXZhLmxhbmcu\r\nTnVtYmVyhqyVHQuU4IsCAAB4cAAADDB0AAR0eXBldAASTEVBVEhFUl9DSEVTVFBMQVRFeABwc3EA\r\nfgAAP0AAAAAAAAx3CAAAABAAAAADcQB+AANzcQB+AAQAAAwwcQB+AAd0AAdCRURST0NLdAAGYW1v\r\ndW50c3EAfgAEAAAAQHgAcHBwcHBwcA\u003d\u003d\r\n" - }, - "ender_chest": { - "serialized_items": "rO0ABXcEAAAAG3NyABdqYXZhLnV0aWwuTGlua2VkSGFzaE1hcDTATlwQbMD7AgABWgALYWNjZXNz\r\nT3JkZXJ4cgARamF2YS51dGlsLkhhc2hNYXAFB9rBwxZg0QMAAkYACmxvYWRGYWN0b3JJAAl0aHJl\r\nc2hvbGR4cD9AAAAAAAAMdwgAAAAQAAAAA3QAAXZzcgARamF2YS5sYW5nLkludGVnZXIS4qCk94GH\r\nOAIAAUkABXZhbHVleHIAEGphdmEubGFuZy5OdW1iZXKGrJUdC5TgiwIAAHhwAAAMMHQABHR5cGV0\r\nAA1TUFJVQ0VfUExBTktTdAAGYW1vdW50c3EAfgAEAAAAQHgAc3EAfgAAP0AAAAAAAAx3CAAAABAA\r\nAAADcQB+AANzcQB+AAQAAAwwcQB+AAd0AAdCRURST0NLcQB+AAlxAH4ACngAc3EAfgAAP0AAAAAA\r\nAAx3CAAAABAAAAADcQB+AANzcQB+AAQAAAwwcQB+AAdxAH4ADXEAfgAJcQB+AAp4AHNxAH4AAD9A\r\nAAAAAAAMdwgAAAAQAAAAA3EAfgADc3EAfgAEAAAMMHEAfgAHcQB+AA1xAH4ACXEAfgAKeABzcQB+\r\nAAA/QAAAAAAADHcIAAAAEAAAAANxAH4AA3NxAH4ABAAADDBxAH4AB3EAfgANcQB+AAlxAH4ACngA\r\nc3EAfgAAP0AAAAAAAAx3CAAAABAAAAADcQB+AANzcQB+AAQAAAwwcQB+AAdxAH4ADXEAfgAJcQB+\r\nAAp4AHNxAH4AAD9AAAAAAAAMdwgAAAAQAAAAA3EAfgADc3EAfgAEAAAMMHEAfgAHcQB+AA1xAH4A\r\nCXEAfgAKeABzcQB+AAA/QAAAAAAADHcIAAAAEAAAAANxAH4AA3NxAH4ABAAADDBxAH4AB3EAfgAN\r\ncQB+AAlxAH4ACngAc3EAfgAAP0AAAAAAAAx3CAAAABAAAAADcQB+AANzcQB+AAQAAAwwcQB+AAdx\r\nAH4ADXEAfgAJcQB+AAp4AHNxAH4AAD9AAAAAAAAMdwgAAAAQAAAAA3EAfgADc3EAfgAEAAAMMHEA\r\nfgAHcQB+AA1xAH4ACXEAfgAKeABzcQB+AAA/QAAAAAAADHcIAAAAEAAAAANxAH4AA3NxAH4ABAAA\r\nDDBxAH4AB3EAfgANcQB+AAlxAH4ACngAc3EAfgAAP0AAAAAAAAx3CAAAABAAAAADcQB+AANzcQB+\r\nAAQAAAwwcQB+AAdxAH4ADXEAfgAJcQB+AAp4AHNxAH4AAD9AAAAAAAAMdwgAAAAQAAAAA3EAfgAD\r\nc3EAfgAEAAAMMHEAfgAHcQB+AA1xAH4ACXEAfgAKeABzcQB+AAA/QAAAAAAADHcIAAAAEAAAAANx\r\nAH4AA3NxAH4ABAAADDBxAH4AB3EAfgANcQB+AAlxAH4ACngAc3EAfgAAP0AAAAAAAAx3CAAAABAA\r\nAAADcQB+AANzcQB+AAQAAAwwcQB+AAdxAH4ADXEAfgAJcQB+AAp4AHNxAH4AAD9AAAAAAAAMdwgA\r\nAAAQAAAAA3EAfgADc3EAfgAEAAAMMHEAfgAHcQB+AA1xAH4ACXEAfgAKeABzcQB+AAA/QAAAAAAA\r\nDHcIAAAAEAAAAANxAH4AA3NxAH4ABAAADDBxAH4AB3EAfgANcQB+AAlxAH4ACngAc3EAfgAAP0AA\r\nAAAAAAx3CAAAABAAAAADcQB+AANzcQB+AAQAAAwwcQB+AAdxAH4ADXEAfgAJcQB+AAp4AHNxAH4A\r\nAD9AAAAAAAAMdwgAAAAQAAAAA3EAfgADc3EAfgAEAAAMMHEAfgAHcQB+AA1xAH4ACXEAfgAKeABz\r\ncQB+AAA/QAAAAAAADHcIAAAAEAAAAANxAH4AA3NxAH4ABAAADDBxAH4AB3EAfgANcQB+AAlxAH4A\r\nCngAc3EAfgAAP0AAAAAAAAx3CAAAABAAAAADcQB+AANzcQB+AAQAAAwwcQB+AAdxAH4ADXEAfgAJ\r\ncQB+AAp4AHNxAH4AAD9AAAAAAAAMdwgAAAAQAAAAA3EAfgADc3EAfgAEAAAMMHEAfgAHcQB+AA1x\r\nAH4ACXEAfgAKeABzcQB+AAA/QAAAAAAADHcIAAAAEAAAAANxAH4AA3NxAH4ABAAADDBxAH4AB3EA\r\nfgANcQB+AAlxAH4ACngAc3EAfgAAP0AAAAAAAAx3CAAAABAAAAADcQB+AANzcQB+AAQAAAwwcQB+\r\nAAdxAH4ACHEAfgAJcQB+AAp4AHNxAH4AAD9AAAAAAAAMdwgAAAAQAAAAA3EAfgADc3EAfgAEAAAM\r\nMHEAfgAHcQB+AAhxAH4ACXEAfgAKeABzcQB+AAA/QAAAAAAADHcIAAAAEAAAAANxAH4AA3NxAH4A\r\nBAAADDBxAH4AB3EAfgAIcQB+AAlxAH4ACngAc3EAfgAAP0AAAAAAAAx3CAAAABAAAAADcQB+AANz\r\ncQB+AAQAAAwwcQB+AAdxAH4ACHEAfgAJcQB+AAp4AA\u003d\u003d\r\n" - }, - "potion_effects": { - "serialized_potion_effects": "" - }, - "advancements": [ - { - "key": "minecraft:recipes/transportation/mangrove_boat", - "completed_criteria": { - "in_water": "Oct 11, 2022, 10:07:07 PM" - } - }, - { - "key": "minecraft:recipes/redstone/spruce_button", - "completed_criteria": { - "has_planks": "Oct 11, 2022, 9:25:12 PM" - } - }, - { - "key": "minecraft:recipes/misc/iron_nugget_from_smelting", - "completed_criteria": { - "has_chainmail_leggings": "Oct 12, 2022, 5:43:37 PM" - } - }, - { - "key": "minecraft:recipes/redstone/spruce_pressure_plate", - "completed_criteria": { - "has_planks": "Oct 11, 2022, 9:25:12 PM" - } - }, - { - "key": "minecraft:recipes/redstone/warped_pressure_plate", - "completed_criteria": { - "has_planks": "Oct 12, 2022, 5:43:22 PM" - } - }, - { - "key": "minecraft:recipes/decorations/spruce_sign", - "completed_criteria": { - "has_planks": "Oct 11, 2022, 9:25:12 PM" - } - }, - { - "key": "minecraft:recipes/redstone/spruce_trapdoor", - "completed_criteria": { - "has_planks": "Oct 11, 2022, 9:25:12 PM" - } - }, - { - "key": "minecraft:recipes/building_blocks/warped_slab", - "completed_criteria": { - "has_planks": "Oct 12, 2022, 5:43:22 PM" - } - }, - { - "key": "minecraft:recipes/redstone/spruce_door", - "completed_criteria": { - "has_planks": "Oct 11, 2022, 9:25:12 PM" - } - }, - { - "key": "minecraft:recipes/redstone/spruce_fence_gate", - "completed_criteria": { - "has_planks": "Oct 11, 2022, 9:25:12 PM" - } - }, - { - "key": "minecraft:recipes/decorations/crafting_table", - "completed_criteria": { - "has_planks": "Oct 11, 2022, 9:25:12 PM" - } - }, - { - "key": "minecraft:recipes/decorations/chest", - "completed_criteria": { - "has_lots_of_items": "Oct 12, 2022, 5:43:42 PM" - } - }, - { - "key": "minecraft:story/shiny_gear", - "completed_criteria": { - "diamond_boots": "Oct 12, 2022, 5:43:36 PM" - } - }, - { - "key": "minecraft:recipes/misc/stick", - "completed_criteria": { - "has_planks": "Oct 11, 2022, 9:25:12 PM" - } - }, - { - "key": "minecraft:recipes/redstone/warped_fence_gate", - "completed_criteria": { - "has_planks": "Oct 12, 2022, 5:43:22 PM" - } - }, - { - "key": "minecraft:recipes/transportation/acacia_boat", - "completed_criteria": { - "in_water": "Oct 11, 2022, 10:07:07 PM" - } - }, - { - "key": "minecraft:recipes/misc/iron_nugget_from_blasting", - "completed_criteria": { - "has_chainmail_leggings": "Oct 12, 2022, 5:43:37 PM" - } - }, - { - "key": "minecraft:recipes/decorations/warped_fence", - "completed_criteria": { - "has_planks": "Oct 12, 2022, 5:43:22 PM" - } - }, - { - "key": "minecraft:adventure/adventuring_time", - "completed_criteria": { - "minecraft:beach": "Oct 12, 2022, 5:10:27 PM", - "minecraft:old_growth_pine_taiga": "Oct 12, 2022, 9:32:20 PM", - "minecraft:dark_forest": "Oct 11, 2022, 9:24:06 PM", - "minecraft:forest": "Oct 11, 2022, 10:06:58 PM", - "minecraft:taiga": "Oct 12, 2022, 8:58:59 PM", - "minecraft:river": "Oct 11, 2022, 10:07:07 PM", - "minecraft:stony_shore": "Oct 11, 2022, 9:23:59 PM", - "minecraft:snowy_plains": "Oct 11, 2022, 10:08:53 PM", - "minecraft:snowy_taiga": "Oct 12, 2022, 3:38:05 PM", - "minecraft:frozen_river": "Oct 11, 2022, 10:09:54 PM", - "minecraft:windswept_gravelly_hills": "Oct 12, 2022, 3:14:39 PM", - "minecraft:old_growth_spruce_taiga": "Oct 12, 2022, 9:42:12 PM", - "minecraft:snowy_beach": "Oct 11, 2022, 10:08:40 PM", - "minecraft:plains": "Oct 11, 2022, 10:07:07 PM" - } - }, - { - "key": "minecraft:recipes/decorations/barrel", - "completed_criteria": { - "has_planks": "Oct 11, 2022, 9:25:12 PM" - } - }, - { - "key": "minecraft:recipes/transportation/spruce_boat", - "completed_criteria": { - "in_water": "Oct 11, 2022, 10:07:07 PM" - } - }, - { - "key": "minecraft:recipes/redstone/redstone_from_smelting_redstone_ore", - "completed_criteria": { - "has_redstone_ore": "Oct 11, 2022, 10:21:34 PM" - } - }, - { - "key": "minecraft:recipes/transportation/birch_boat", - "completed_criteria": { - "in_water": "Oct 11, 2022, 10:07:07 PM" - } - }, - { - "key": "minecraft:recipes/decorations/spruce_fence", - "completed_criteria": { - "has_planks": "Oct 11, 2022, 9:25:12 PM" - } - }, - { - "key": "minecraft:recipes/building_blocks/spruce_stairs", - "completed_criteria": { - "has_planks": "Oct 11, 2022, 9:25:12 PM" - } - }, - { - "key": "minecraft:recipes/transportation/oak_boat", - "completed_criteria": { - "in_water": "Oct 11, 2022, 10:07:07 PM" - } - }, - { - "key": "minecraft:recipes/redstone/redstone_from_blasting_redstone_ore", - "completed_criteria": { - "has_redstone_ore": "Oct 11, 2022, 10:21:34 PM" - } - }, - { - "key": "minecraft:recipes/redstone/warped_button", - "completed_criteria": { - "has_planks": "Oct 12, 2022, 5:43:22 PM" - } - }, - { - "key": "minecraft:recipes/building_blocks/warped_stairs", - "completed_criteria": { - "has_planks": "Oct 12, 2022, 5:43:22 PM" - } - }, - { - "key": "minecraft:recipes/redstone/warped_trapdoor", - "completed_criteria": { - "has_planks": "Oct 12, 2022, 5:43:22 PM" - } - }, - { - "key": "minecraft:recipes/building_blocks/spruce_slab", - "completed_criteria": { - "has_planks": "Oct 11, 2022, 9:25:12 PM" - } - }, - { - "key": "minecraft:recipes/decorations/warped_sign", - "completed_criteria": { - "has_planks": "Oct 12, 2022, 5:43:22 PM" - } - }, - { - "key": "minecraft:recipes/transportation/jungle_boat", - "completed_criteria": { - "in_water": "Oct 11, 2022, 10:07:07 PM" - } - }, - { - "key": "minecraft:recipes/transportation/dark_oak_boat", - "completed_criteria": { - "in_water": "Oct 11, 2022, 10:07:07 PM" - } - }, - { - "key": "minecraft:recipes/redstone/warped_door", - "completed_criteria": { - "has_planks": "Oct 12, 2022, 5:43:22 PM" - } - } - ], - "statistics": { - "untyped_statistics": { - "LEAVE_GAME": 16, - "TOTAL_WORLD_TIME": 282633, - "CROUCH_ONE_CM": 43, - "WALK_UNDER_WATER_ONE_CM": 113, - "DEATHS": 4, - "WALK_ONE_CM": 7313, - "JUMP": 866, - "SPRINT_ONE_CM": 63807, - "DROP_COUNT": 9, - "WALK_ON_WATER_ONE_CM": 331, - "TIME_SINCE_DEATH": 282357, - "SNEAK_TIME": 95, - "FLY_ONE_CM": 584296, - "ENDERCHEST_OPENED": 2, - "PLAY_ONE_MINUTE": 282633, - "TIME_SINCE_REST": 282377 - }, - "block_statistics": {}, - "item_statistics": { - "PICKUP": { - "SUGAR_CANE": 2 - }, - "DROP": { - "SPRUCE_PLANKS": 70, - "TURTLE_HELMET": 1, - "DIAMOND_BOOTS": 1, - "BEDROCK": 1, - "CHAINMAIL_LEGGINGS": 1, - "MANGROVE_PROPAGULE": 1, - "LEATHER_CHESTPLATE": 1 - }, - "USE_ITEM": { - "TURTLE_HELMET": 1, - "DIAMOND_BOOTS": 1, - "GRASS_BLOCK": 5, - "ENDER_CHEST": 1, - "CHAINMAIL_LEGGINGS": 1, - "LEATHER_CHESTPLATE": 1 - } - }, - "entity_statistics": {} - }, - "persistent_data_container": { - "persistent_data_map": {} - }, - "minecraft_version": "1.19.2", - "format_version": 3 + "id": "209a56fd-efd0-4354-8f7c-e09f6d0673d8", + "pinned": false, + "timestamp": "2023-09-15T17:27:08.6768038+01:00", + "save_cause": "DISCONNECT", + "minecraft_version": "1.20.1", + "platform_type": "bukkit", + "format_version": 4, + "data": { + "husksync:statistics": "{\"generic\":{\"minecraft:fly_one_cm\":26261,\"minecraft:jump\":23,\"minecraft:leave_game\":3,\"minecraft:play_one_minute\":1904,\"minecraft:sneak_time\":7,\"minecraft:sprint_one_cm\":1849,\"minecraft:time_since_death\":1904,\"minecraft:time_since_rest\":1904,\"minecraft:total_world_time\":1904,\"minecraft:walk_one_cm\":414},\"blocks\":{},\"items\":{},\"entities\":{}}", + "husksync:experience": "{\"total_experience\":0,\"exp_level\":0,\"exp_progress\":0.0}", + "husksync:game_mode": "{\"game_mode\":\"CREATIVE\",\"allow_flight\":true,\"is_flying\":true}", + "husksync:advancements": "[{\"key\":\"minecraft:recipes/decorations/crafting_table\",\"completed_criteria\":{\"unlock_right_away\":1694795225426}},{\"key\":\"minecraft:adventure/adventuring_time\",\"completed_criteria\":{\"minecraft:old_growth_birch_forest\":1694795225478}}]", + "husksync:inventory": "{held_item_slot:0,items:{size:41}}", + "husksync:ender_chest": "{size:27}", + "husksync:potion_effects": "[]", + "husksync:hunger": "{\"food_level\":20,\"saturation\":5.0,\"exhaustion\":0.449}", + "husksync:health": "{\"health\":20.0,\"max_health\":20.0,\"health_scale\":20.0}" + } } ```
### Dumping to the web -The Web Dump... button (equivalent to `/userdata dump web`) will dump user data snapshot json data to the https://mclo.gs service and provide you with a link to the uploaded file. Note that the web dumping service may not work if your user data snapshot exceeds 10MB in file size. +The \[Web Dump...\] button (equivalent to `/userdata dump web`) will dump user data snapshot json data to the https://mclo.gs service and provide you with a link to the uploaded file. Note that the web dumping service may not work if your user data snapshot exceeds 10MB in file size. diff --git a/docs/FAQs.md b/docs/FAQs.md index 05a4f4cc..3c42df19 100644 --- a/docs/FAQs.md +++ b/docs/FAQs.md @@ -17,9 +17,9 @@ Modded items are not supported.
- Are MMOItems / SlimeFun items supported? + Are MMOItems / SlimeFun / ItemsAdder items supported? -No. MMOItems and SlimeFun are not compatible with HuskSync due to the way they inject data directly into item NBT rather than the Spigot API's plugin-agnostic PersistentDataContainer. +These plugins, which provide custom items, should be supported as of HuskSync v3.x; but do note we cannot guarantee compatibility with all methods of injecting custom data to create custom items. Be sure to test thoroughly before deploying on production!
@@ -35,9 +35,9 @@ HuskSync requires Redis to operate (for reasons demonstrated below). Redis is an ![System diagram](https://raw.githubusercontent.com/WiIIiam278/HuskSync/master/images/system-diagram.png) -HuskSync makes use of both MySQL and Redis for optimal data synchronisation. +HuskSync makes use of both MySQL and Redis for optimal data synchronization. -When a user changes servers, in addition to data being saved to MySQL, it is also cached via the Redis server with a temproary expiry key. When changing servers, the receiving server detects the key and sets the user data from Redis. When a player rejoins the network, the system fetches the last-saved data snapshot from the MySQL Database. +When a user changes servers, in addition to data being saved to MySQL, it is also cached via the Redis server with a temporary expiry key. When changing servers, the receiving server detects the key and sets the user data from Redis. When a player rejoins the network, the system fetches the last-saved data snapshot from the MySQL Database. This approach is able to dramatically improve both synchronization performance and reliability. A few other techniques are used to optimize this process, such as compressing the serialized user data json using Snappy. diff --git a/docs/Home.md b/docs/Home.md index 0c26ae7c..750a473a 100644 --- a/docs/Home.md +++ b/docs/Home.md @@ -1,5 +1,5 @@ # [![HuskSync banner](https://raw.githubusercontent.com/WiIIiam278/HuskSync/master/images/banner.png)](https://github.com/WiIIiam278/HuskSync) -Welcome! This is the plugin documentation for HuskSync v2.x+. Please click through to the topic you'd like to read about. +Welcome! This is the plugin documentation for HuskSync v3.x+. Please click through to the topic you'd like to read about. ## Guides * 📚 [[Setup]] @@ -18,14 +18,16 @@ Welcome! This is the plugin documentation for HuskSync v2.x+. Please click throu * ☂️ [[Dumping UserData]] * 📋 [[Event Priorities]] * ⚔️ [[Keep Inventory]] -* 📦 [[API]] - * 📝 [[UserData API]] +* 📦 [[API]] v3 + * 📝 [[Snapshot API]] + * 📝 [[Custom Data API]] * ❗ [[API Events]] +* 🕸️ [[API v2]] _(Legacy)_ ## Links * 💻 [GitHub](https://github.com/WiIIiam278/HuskSync) -* 📂 [Buy HuskSync](https://www.spigotmc.org/resources/husksync.97144/) - * 🛒 [Spigot](https://www.spigotmc.org/resources/husksync.97144/) +* 📂 [Buy HuskSync](https://william278.net/project/husksync/) + * 🚰 [Spigot](https://www.spigotmc.org/resources/husksync.97144/) * 🛒 [Polymart](https://polymart.org/resource/husksync.1634) - * 🛒 [Craftaro](https://craftaro.com/marketplace/product/husksync.758) + * ⚒️ [Craftaro](https://craftaro.com/marketplace/product/husksync.758) * 💬 [Discord Support](https://discord.gg/tVYhJfyDWG) \ No newline at end of file diff --git a/docs/Keep-Inventory.md b/docs/Keep-Inventory.md index 7cb54c38..9d6da1ae 100644 --- a/docs/Keep-Inventory.md +++ b/docs/Keep-Inventory.md @@ -1,4 +1,4 @@ -If your server uses the `keepInventory` gamerule, where players keep the contents of their inventory after dying, HuskSync's built-in snapshot-on-death and dead-player synchronisation features can cause a conflict leading to synchronisation issues. +If your server uses the `keepInventory` gamerule, where players keep the contents of their inventory after dying, HuskSync's built-in snapshot-on-death and dead-player synchronization features can saveCause a conflict leading to synchronization issues. To solve this issue, you will need to adjust three settings in your `config.yml` file, as described below. @@ -8,7 +8,7 @@ HuskSync has some special handling when players die, to account for scenarios wh * **Snapshot creation on death**—HuskSync can create a special snapshot for backup purposes when a player dies, formed by taking their drops and setting this to their inventory. When `keepInventory` is enabled, the player drops are empty, so this creates an inaccurate snapshot. This option is disabled by default. ## How can this be fixed? -You will need to set the `synchronization.save_on_death` (which controls making snapshots on death), `save_empty_drops_on_death` (which controls whether snapshots of players who have no items to drop should be created), and `synchronization.synchronise_dead_players_changing_server` (which controls whether to sync dead players when they change servers) options to `false` in `config.yml`. +You will need to set the `synchronization.save_on_death` (which controls making snapshots on death), `save_empty_drops_on_death` (which controls whether snapshots of players who have no items to drop should be created), and `synchronization.synchronize_dead_players_changing_server` (which controls whether to sync dead players when they change servers) options to `false` in `config.yml`.
Example in config.yml @@ -19,7 +19,7 @@ You will need to set the `synchronization.save_on_death` (which controls making save_on_death: false # <-- Set this to false save_empty_drops_on_death: false # <-- Set this to false # ... - synchronise_dead_players_changing_server: false # <-- Set this to false + synchronize_dead_players_changing_server: false # <-- Set this to false ```
diff --git a/docs/Legacy-Migration.md b/docs/Legacy-Migration.md index be00f3cf..46284065 100644 --- a/docs/Legacy-Migration.md +++ b/docs/Legacy-Migration.md @@ -1,15 +1,15 @@ -This guide will walk you through how to upgrade from HuskSync v1.4.x to HuskSync 2.x. +This guide will walk you through how to upgrade from HuskSync v1.4.x to HuskSync v2.x or v3.x. Data from HuskSync v2.x will automatically be imported into HuskSync v3.x. ## Requirements - MySQL Database with HuskSync v1.4.x data - - Migration from SQLite is not supported, as HuskSync v2.x requires a MySQL database and does not support SQLite. Appologies for the inconvenience. + - Migration from SQLite is not supported, as HuskSync v2.x requires a MySQL database and does not support SQLite. Apologies for the inconvenience. - If you're running v1.3.x or older, follow the update instructions to 1.4.x first before updating to 2.x. ## Migration Instructions ### 1. Uninstall HuskSync v1.x from all servers - Switch off all servers and your proxy -- Delete the jarfile from your `~/plugins/` folders on your Spigot servers -- Also delete the jarfile from your `~/plugins/` folders on your Proxy. HuskSync v2.x no longer requires a proxy plugin. +- Delete the .jar file from your `~/plugins/` folders on your Spigot servers +- Also delete the .jar file from your `~/plugins/` folders on your Proxy. HuskSync v2.x no longer requires a proxy plugin. - Delete (or make a copy and delete) all HuskSync config data folders (`~/plugins/HuskSync/`). HuskSync 2.x has a new config and messages file. ### 2. Install HuskSync v2.x on all Spigot servers @@ -26,5 +26,5 @@ This guide will walk you through how to upgrade from HuskSync v1.4.x to HuskSync - Run `husksync migrate legacy start` to begin the migration process. This may take some time, depending on the amount of data you're migrating. ### 5. Ensure the migration was successful -- HuskSync will notify in console when migration is complete. Verify that the migration went OK by logging in and using the `/userdata list ` command to see if the data was imported with the `legacy migration` cause. +- HuskSync will notify in console when migration is complete. Verify that the migration went OK by logging in and using the `/userdata list ` command to see if the data was imported with the `legacy migration` saveCause. - You can delete the old tables in the database if you want. Be careful to make sure you delete the right ones. By default the *new* table names are `husksync_users` and `husksync_user_data` and the *old* ones were `husksync_players` and `husksync_data`, but you may have changed these. \ No newline at end of file diff --git a/docs/MPDB-Migration.md b/docs/MPDB-Migration.md index fb499d89..3f7991fb 100644 --- a/docs/MPDB-Migration.md +++ b/docs/MPDB-Migration.md @@ -24,5 +24,5 @@ This guide will walk you through how to migrate from MySQLPlayerDataBridge (MPDB - Start your Spigot servers again. ### 5. Ensure the migration was successful -- Verify that the migration was successful by logging in and using the `/userdata list ` command to see if the data was imported with the `mpdb_migration` cause. +- Verify that the migration was successful by logging in and using the `/userdata list ` command to see if the data was imported with the `mpdb_migration` saveCause. - You can delete the old tables in the database if you want. Be careful to make sure you delete the correct ones. \ No newline at end of file diff --git a/docs/Plan-Hook.md b/docs/Plan-Hook.md index 85d702d8..5a2f84d6 100644 --- a/docs/Plan-Hook.md +++ b/docs/Plan-Hook.md @@ -1,6 +1,6 @@ HuskSync supports displaying information about user data on your [Player Analytics](https://github.com/plan-player-analytics/Plan) (Plan) web panel. -[![Plan hook screenshots](https://raw.githubusercontent.com/WiIIiam278/HuskSync/master/images/plan-hook.png)](#) +![Plan hook screenshots](https://raw.githubusercontent.com/WiIIiam278/HuskSync/master/images/plan-hook.png) ## Requirements - HuskSync v2.0+ diff --git a/docs/Setup.md b/docs/Setup.md index ffbe7439..61292721 100644 --- a/docs/Setup.md +++ b/docs/Setup.md @@ -11,15 +11,15 @@ This will walk you through installing HuskSync on your network of Spigot servers - You do not need to install HuskSync as a proxy plugin. ### 2. Restart servers - Start, then stop every server to let HuskSync generate the [[config file]]. -- HuskSync will throw an error in console and disable itself as it is unable to connect to the database. You haven't set the credentials yet, so this is expected. +- HuskSync will throw an error in the console and disable itself as it is unable to connect to the database. You haven't set the credentials yet, so this is expected. - Advanced users: If you'd prefer, you can just create one config.yml file and create symbolic links in each `/plugins/HuskSync/` folder to it to make updating it easier. -### 3. Enter MySQL & Redis database credentails +### 3. Enter MySQL & Redis database credentials - Navigate to the HuskSync config file on each server (`~/plugins/HuskSync/config.yml`) - Under `credentials` in the `database` section, enter the credentials of your MySQL Database. You shouldn't touch the `connection_pool` properties. -- Under `credentials` in the `redis` section, enter the credentails of your Redis Database. If your Redis server doesn't have a password, leave the password blank as it is. +- Under `credentials` in the `redis` section, enter the credentials of your Redis Database. If your Redis server doesn't have a password, leave the password blank as it is. - Unless you want to have multiple clusters of servers within your network, each with separate user data, do not change the value of `cluster_id`. ### 4. Start every server again -- Provided your MySQL and Redis credentials were correct, synchronisation should begin as soon as you start your servers again. +- Provided your MySQL and Redis credentials were correct, synchronization should begin as soon as you start your servers again. - If you need to import data from HuskSync v1.x or MySQLPlayerDataBridge, please see the guides below: - [[Legacy Migration]] - [[MPDB Migration]] \ No newline at end of file diff --git a/docs/Sync-Features.md b/docs/Sync-Features.md index d8634749..f1dcabe1 100644 --- a/docs/Sync-Features.md +++ b/docs/Sync-Features.md @@ -1,6 +1,6 @@ This page contains a list of the features HuskSync is and isn't able to syncrhonise on your server. -You can customise how much data HuskSync saves about a player by [turning each synchronisation feature on or off](#toggling-sync-features). When a synchronisation feature is turned off, HuskSync won't touch that part of a player's profile; in other words, the data they will inherit when changing servers will be read from their player data file on the local server. +You can customise how much data HuskSync saves about a player by [turning each synchronization feature on or off](#toggling-sync-features). When a synchronization feature is turned off, HuskSync won't touch that part of a player's profile; in other words, the data they will inherit when changing servers will be read from their player data file on the local server. ## Feature table ✅—Supported  ❌—Unsupported  ⚠️—Experimental @@ -18,7 +18,7 @@ You can customise how much data HuskSync saves about a player by [turning each s | Game modes | Player's current game mode | ✅ | | Statistics | Player's in-game stats (ESC -> Statistics) | ✅ | | Location | Player's current coordinate positon and world† | ✅ | -| Persistent Data Container | Custom plugin persistent data key map | ⚠️ | +| Persistent Data Container | Custom plugin persistent data key map | ✅️ | | Locked maps | Maps/treasure maps locked in a cartography table | ⚠️ | | Unlocked maps | Regular, unlocked maps/treasure maps ([why?](#map-syncing)) | ❌ | | Economy balances | Vault economy balance. ([why?](#economy-syncing)) | ❌ | @@ -27,48 +27,38 @@ What about modded items? Or custom item plugins such as MMOItems or SlimeFun? Th *Purpur's custom ender chest resizing feature is also supported. -†This is intended for servers that have mirrorred worlds across instances (such as RPG servers). With this option enabled, players will be placed at the same coordinates when changing servers. - -### PersistentDataContainer tags -The player [PersistentDataContainer](https://blog.jeff-media.com/persistent-data-container-the-better-alternative-to-nbt-tags/) is a part of the Spigot API that enables plugins to set custom data tags to players, entities & items and have them persist. HuskSync will synchronise this data cross-server. Plugins that use legacy or proprietary forms of saving data, such as by modifying NBT directly, may not correctly synchronise. - -### Custom enchantments -Plugins that add custom enchantments by registering them to ItemStacks through setting them via the [EnchantmentStorageMeta](https://hub.spigotmc.org/javadocs/spigot/org/bukkit/inventory/meta/EnchantmentStorageMeta.html) will work, but note that the plugin _must_ be lower on the load order than HuskSync; in other words, HuskSync should be on the plugin's `loadbefore:`. This is because Spigot's item serialization API requires that the plugin that registered the enchantment be online to serialize it due to how it reads from the enchantment registry and so if the plugin does not load before (and thus does not shut down after) HuskSync, it won't be able to serialize the custom enchantments in the event of a server shutdown with players online. +†This is intended for servers that have mirrored worlds across instances (such as RPG servers). With this option enabled, players will be placed at the same coordinates when changing servers. ### Map syncing -Map items are a special case, as their data is not stored in the item itself, but rather in the game world files. In addition to this, their data is dynamic and changes based on the updating of the world, something which can't be tracked across multiple instances. As a result, it's not possible to sync unlocked map items. - -However, experimental support for synchronising locked map items—that is, maps that have been locked in a cartography table—is currently available in development builds. This works by serializing its' map canvas pixel grid to the map item's persistent data container. +Map items are a special case, as their data is not stored in the item itself, but rather in the game world files. In addition to this, their data is dynamic and changes based on the updating of the world, something that can't be tracked across multiple instances. As a result, it's not possible to sync unlocked map items. Locked maps, however, are supported. This works by saving the pixel canvas grid to the map NBT itself, and generating virtual maps on the other servers. ### Economy syncing -Although it's a common request, HuskSync doesn't synchronise economy data for a number of reasons! +Although it's a common request, HuskSync doesn't synchronize economy data for a number of reasons! -I strongly recommend making use of economy plugins that have cross-server economy balance synchronisation built-in, of which there are a multitude of options available. Please see our [[FAQs]] section for more details on this decision. +I strongly recommend making use of economy plugins that have cross-server economy balance synchronization built-in, of which there are a multitude of options available. Please see our [[FAQs]] section for more details on this decision. ## Toggling Sync Features -All synchronization features, except location and locked map synchronising, are enabled by default. To toggle a feature, navigate to the `features:` section in the `synchronisation:` part of your `config.yml` file, and change the option to `true`/`false` respectively. +All synchronization features, except location and locked map synchronising, are enabled by default. To toggle a feature, navigate to the `features:` section in the `synchronization:` part of your `config.yml` file, and change the option to `true`/`false` respectively.
- Example in config.yml +Example in config.yml - ```yaml - synchronization: - # ... - features: - inventories: true - ender_chests: true - health: true - max_health: true - hunger: true - experience: true - potion_effects: true - advancements: true - game_mode: true - statistics: true - persistent_data_container: false - locked_maps: true - location: false - #... - ``` +```yaml +synchronization: + # ... + features: + health: true + statistics: true + location: false + potion_effects: true + ender_chest: true + experience: true + advancements: true + game_mode: true + inventory: true + persistent_data: true + hunger: true + #... +```
\ No newline at end of file diff --git a/docs/Troubleshooting.md b/docs/Troubleshooting.md index f297f6fb..284f0eae 100644 --- a/docs/Troubleshooting.md +++ b/docs/Troubleshooting.md @@ -9,13 +9,13 @@ This is most frequently caused by running a cracked "offline mode" network of se ### Cannot set data with newer Minecraft version than the server This is caused when you attempt to downgrade user data from a newer version of Minecraft to an older one, or when your Spigot servers are running mismatched Minecraft versions. -HuskSync will identify this and safely prevent the synchronisation from occuring. Your Spigot servers must be running the same version of both Minecraft and HuskSync. +HuskSync will identify this and safely prevent the synchronization from occuring. Your Spigot servers must be running the same version of both Minecraft and HuskSync. -### User data failing to synchronise +### User data failing to synchronize This can occur due to misaligned timings between your Spigot servers and your Redis server. HuskSync has a built in way of tuning this. Try continously increasing the `network_latency_milliseconds` option in your config to a higher value. -### Synchronisation issues with Keep Inventory enabled -On servers that use Keep Inventory move (where players keep their items when they die), you can run into synchronisation issues. See [[Keep Inventory]] for details on why this happens and how to resolve it. +### Synchronization issues with Keep Inventory enabled +On servers that use Keep Inventory move (where players keep their items when they die), you can run into synchronization issues. See [[Keep Inventory]] for details on why this happens and how to resolve it. ### Exceptions when compressing data via Snappy (lightweight Linux distros) Some lightweight Linux distros such as Alpine Linux (used on Pterodactyl) might not have the dependencies needed for the [Snappy](https://github.com/xerial/snappy-java) compressor. It's possible to disable data compression by changing `compress_data` to false in your config. Note that after changing this setting you will need to reset your database. Alternatively, find the right libraries for your distro! diff --git a/docs/_Sidebar.md b/docs/_Sidebar.md index ad197f43..504c74be 100644 --- a/docs/_Sidebar.md +++ b/docs/_Sidebar.md @@ -15,14 +15,16 @@ * ☂️ [[Dumping UserData]] * 📋 [[Event Priorities]] * ⚔️ [[Keep Inventory]] -* 📦 [[API]] - * 📝 [[UserData API]] +* 📦 [[API]] v3 + * 📝 [[Snapshot API]] + * 📝 [[Custom Data API]] * ❗ [[API Events]] +* 🕸️ [[API v2]] _(Legacy)_ ## Links * 💻 [GitHub](https://github.com/WiIIiam278/HuskSync) -* 📂 [Buy HuskSync](https://www.spigotmc.org/resources/husksync.97144/) - * 🛒 [Spigot](https://www.spigotmc.org/resources/husksync.97144/) +* 📂 [Buy HuskSync](https://william278.net/project/husksync/) + * 🚰 [Spigot](https://www.spigotmc.org/resources/husksync.97144/) * 🛒 [Polymart](https://polymart.org/resource/husksync.1634) - * 🛒 [Craftaro](https://craftaro.com/marketplace/product/husksync.758) + * ⚒️ [Craftaro](https://craftaro.com/marketplace/product/husksync.758) * 💬 [Discord Support](https://discord.gg/tVYhJfyDWG) \ No newline at end of file diff --git a/gradle.properties b/gradle.properties index 5f84c4de..adf307dd 100644 --- a/gradle.properties +++ b/gradle.properties @@ -3,12 +3,11 @@ org.gradle.jvmargs='-Dfile.encoding=UTF-8' org.gradle.daemon=true javaVersion=16 -plugin_version=2.2.8 +plugin_version=3.0 plugin_archive=husksync plugin_description=A modern, cross-server player data synchronization system -jedis_version=4.3.2 +jedis_version=5.0.0 mysql_driver_version=8.1.0 -mariadb_driver_version=3.1.4 -snappy_version=1.1.9.1 -commons_text_version=1.10.0 \ No newline at end of file +mariadb_driver_version=3.2.0 +snappy_version=1.1.10.3 \ No newline at end of file diff --git a/images/data-dumping.png b/images/data-dumping.png index 9f3fb79b..208dc630 100644 Binary files a/images/data-dumping.png and b/images/data-dumping.png differ diff --git a/images/data-snapshot-list.png b/images/data-snapshot-list.png index 9f47ac81..8516b5ad 100644 Binary files a/images/data-snapshot-list.png and b/images/data-snapshot-list.png differ diff --git a/images/data-snapshot-viewer.png b/images/data-snapshot-viewer.png index 6d2641d4..a1eadc33 100644 Binary files a/images/data-snapshot-viewer.png and b/images/data-snapshot-viewer.png differ diff --git a/images/rich-syntax-highlighting.png b/images/rich-syntax-highlighting.png index 86082c4e..baa1e5ed 100644 Binary files a/images/rich-syntax-highlighting.png and b/images/rich-syntax-highlighting.png differ diff --git a/plugin/build.gradle b/plugin/build.gradle index 32b9327e..ecaed565 100644 --- a/plugin/build.gradle +++ b/plugin/build.gradle @@ -1,6 +1,3 @@ dependencies { implementation project(path: ':bukkit', configuration: 'shadow') -} - -shadowJar { } \ No newline at end of file diff --git a/test/requirements.txt b/test/requirements.txt new file mode 100644 index 00000000..3f364414 --- /dev/null +++ b/test/requirements.txt @@ -0,0 +1,7 @@ +certifi==2023.7.22 +charset-normalizer==3.2.0 +colorama==0.4.6 +idna==3.4 +requests==2.31.0 +tqdm==4.66.1 +urllib3==2.0.4 diff --git a/test/spin_network.py b/test/spin_network.py new file mode 100644 index 00000000..f55fafbc --- /dev/null +++ b/test/spin_network.py @@ -0,0 +1,311 @@ +# This script creates a network of Minecraft servers for testing HuskSync on Windows +# Based on Carcass (https://github.com/WiIIiam278/carcass/) +# To spin up a network of servers, run this script with Python 3.8 or higher +# Run pip install -r requirements.txt to install the required packages +# Then use python ./spin_network.py to spin up the network +import os +import requests +import shutil +from tqdm import tqdm + + +# Parameters for starting a network of Minecraft servers +class Parameters: + root_dir = './servers/' + proxy_version = "1.20" + minecraft_version = '1.20.1' + eula_agreement = 'true' + + backend_names = ['alpha', 'beta'] + backend_ports = [25567, 25568] + backend_type = 'paper' + backend_ram = 2048 + backend_plugins = ['../target/HuskSync-Plugin-*.jar'] + backend_plugin_folders = ['./HuskSync'] + operator_names = ['William278'] + operator_uuids = ['5dfb0558-e306-44f4-bb9a-f9218d4eb787'] + + proxy_name = "proxy" + proxy_host = "0.0.0.0" + proxy_port = 25565 + proxy_type = "waterfall" + proxy_ram = 512 + proxy_plugins = [] + proxy_plugin_folders = [] + + just_update_plugins = False + + +def main(update=False): + # Create parameters object + parameters = Parameters() + parameters.just_update_plugins = update + + # Generate config + if os.path.exists("./config.yml"): + copy_husksync_config() + + # Update plugins if necessary + if parameters.just_update_plugins: + for name in parameters.backend_names: + plugin_dir = f"{parameters.root_dir}{name}/plugins" + + # Clear contents of the plugin_dir directory if it exists + if os.path.exists(plugin_dir): + shutil.rmtree(plugin_dir) + + # Create the plugin_dir directory if it doesn't exist + if not os.path.exists(plugin_dir): + os.makedirs(plugin_dir) + + # Copy plugins in + copy_plugins(parameters.backend_plugins, parameters.backend_plugin_folders, plugin_dir) + + # Start servers + start_servers(parameters) + return + + # Create all backend servers + for name, port in zip(parameters.backend_names, parameters.backend_ports): + create_backend_server(name, port, parameters) + + # Create the proxy server + create_proxy_server(parameters) + + # Start servers + start_servers(parameters) + + +def copy_husksync_config(): + # Copy ./config.yml to ./HuskSync/config.yml + if not os.path.exists("./HuskSync"): + os.makedirs("./HuskSync") + + shutil.copy("./config.yml", "./HuskSync/config.yml") + + +# Creates a backend server +def create_backend_server(name, port, parameters): + print(f"Creating {parameters.backend_type} backend server, {name}") + + # Create a folder for the server. If it exists, delete it. + server_dir = parameters.root_dir + name + if os.path.exists(f"{server_dir}"): + os.system(f"rm -rf {server_dir}") + if not os.path.exists(server_dir): + os.makedirs(server_dir) + + if parameters.backend_type == "paper": + # Create necessary subdirectories + create_subdirectories(["config", "plugins"], server_dir) + + # Download the latest paper for the version and place it in the server folder + server_jar = "paper.jar" + download_paper_build("paper", parameters.minecraft_version, + get_latest_paper_build_number("paper", parameters.minecraft_version), + f"{server_dir}/{server_jar}") + + # Create eula.text and set eula=true + with open(server_dir + "/eula.txt", "w") as file: + file.write(f"# Auto-generated eula.txt for server {name}\n") + file.write(f"eula={parameters.eula_agreement}") + + # Create the spigot.yml and enable BungeeCord + with open(server_dir + "/spigot.yml", "w") as file: + file.write(f"# Auto-generated spigot.yml for server {name}\n") + file.write(f"settings:\n") + file.write(f" bungeecord: true\n") + + # Create the paper-global.yml and enable BungeeCord + with open(server_dir + "/config/paper-global.yml", "w") as file: + file.write(f"# Auto-generated paper-global.yml for server {name}\n") + file.write(f"proxies:\n") + file.write(f" bungee-cord:\n") + file.write(f" online-mode: true\n") + + # Create the server.properties file + server_properties = server_dir + "/server.properties" + with open(server_properties, "w") as file: + file.write(f"# Auto-generated server.properties for server {name}\n") + file.write(f"# {parameters.backend_type} server\n") + file.write(f"server-port={port}\n") + file.write(f"motd=Server {name}\n") + file.write(f"enable-query=false\n") + file.write(f"enable-rcon=false\n") + file.write(f"spawn-protection=0\n") + file.write(f"online-mode=false\n") + + # Create operators file if needed + if len(parameters.operator_names) > 0 and len(parameters.operator_uuids) > 0: + with open(server_dir + "/ops.json", "w") as file: + file.write("[\n") + operator_count = min(len(parameters.operator_names), len(parameters.operator_uuids)) + for i in range(0, operator_count): + file.write(" {\n") + file.write(f" \"uuid\": \"{parameters.operator_uuids[i]}\",\n") + file.write(f" \"name\": \"{parameters.operator_names[i]}\",\n") + file.write(" \"level\": 4,\n") + file.write(" \"bypassesPlayerLimit\": false\n") + if i < operator_count - 1: + file.write(" },\n") + else: + file.write(" }\n") + file.write("]") + + # Copy plugins + copy_plugins(parameters.backend_plugins, parameters.backend_plugin_folders, f"{server_dir}/plugins") + + # Create start scripts + create_start_scripts(server_dir, + f"-Xms{parameters.backend_ram}M -Xmx{parameters.backend_ram}M -XX:+UseG1GC -XX:+ParallelRefProcEnabled -XX:MaxGCPauseMillis=200 -XX:+UnlockExperimentalVMOptions -XX:+DisableExplicitGC -XX:+AlwaysPreTouch -XX:G1NewSizePercent=30 -XX:G1MaxNewSizePercent=40 -XX:G1HeapRegionSize=8M -XX:G1ReservePercent=20 -XX:G1HeapWastePercent=5 -XX:G1MixedGCCountTarget=4 -XX:InitiatingHeapOccupancyPercent=15 -XX:G1MixedGCLiveThresholdPercent=90 -XX:G1RSetUpdatingPauseTimePercent=5 -XX:SurvivorRatio=32 -XX:+PerfDisableSharedMem -XX:MaxTenuringThreshold=1 -Dusing.aikars.flags=https://mcflags.emc.gs -Daikars.new.flags=true -jar ./{server_jar} --nogui") + +def create_proxy_server(parameters): + print(f"Creating {parameters.proxy_type} proxy server, {parameters.proxy_name}") + + # Create folder for the proxy + server_dir = parameters.root_dir + parameters.proxy_name + if os.path.exists(f"{server_dir}"): + os.system(f"rm -rf {server_dir}") + if not os.path.exists(server_dir): + os.makedirs(server_dir) + + if parameters.proxy_type == "waterfall": + # Create necessary subdirectories + create_subdirectories(["plugins"], server_dir) + + # Download the latest paper for the version and place it in the server folder + proxy_jar = "waterfall.jar" + download_paper_build("waterfall", parameters.proxy_version, + get_latest_paper_build_number("waterfall", parameters.proxy_version), + f"{server_dir}/{proxy_jar}") + + # Create the config.yml + with open(server_dir + "/config.yml", "w") as file: + file.write(f"# Auto-generated config.yml for proxy server {parameters.proxy_name}\n") + + # Write proxy settings + file.write(f"listeners:\n") + file.write(f"- query_port: {parameters.proxy_port}\n") + file.write(f" motd: '{parameters.proxy_version} Proxy Server'\n") + file.write(f" query_enabled: false\n") + file.write(f" proxy_protocol: false\n") + file.write(f" priorities:\n") + file.write(f" - {parameters.backend_names[0]}\n") + file.write(f" bind_local_address: true\n") + file.write(f" host: {parameters.proxy_host}:{parameters.proxy_port}\n") + file.write(f"ip_forward: true\n") + file.write(f"online_mode: true\n") + + # Write servers + file.write(f"servers:\n") + for i in range(len(parameters.backend_names)): + file.write(f" {parameters.backend_names[i]}:\n") + file.write( + f" motd: '&eBackend {parameters.backend_type} {parameters.backend_names[i]} (port {parameters.backend_ports[i]})'\n") + file.write(f" address: localhost:{parameters.backend_ports[i]}\n") + file.write(f" restricted: false\n") + + # Copy plugins + copy_plugins(parameters.proxy_plugins, parameters.proxy_plugin_folders, f"{server_dir}/plugins") + + # Create startup scripts + create_start_scripts(server_dir, + f"-Xms{parameters.proxy_ram}M -Xmx{parameters.proxy_ram}M -XX:+UseG1GC -XX:G1HeapRegionSize=4M -XX:+UnlockExperimentalVMOptions -XX:+ParallelRefProcEnabled -XX:+AlwaysPreTouch -jar ./{proxy_jar}") + + +# Fetches the latest build number for a paper project +def get_latest_paper_build_number(project, version_set): + url = f"https://api.papermc.io/v2/projects/{project}/versions/{version_set}/builds" + return requests.get(url).json()["builds"][-1]["build"] + + +# Downloads a paper build for a project to the target file +def download_paper_build(project, version_set, build_number, target_file): + url = f"https://api.papermc.io/v2/projects/{project}/versions/{version_set}/builds/{build_number}/downloads/{project}-{version_set}-{build_number}.jar" + requests.get(url, stream=True) + + with open(target_file, "wb") as file: + for chunk in tqdm(requests.get(url, stream=True).iter_content(chunk_size=1024)): + if chunk: + file.write(chunk) + file.flush() + + +# Creates subdirectories for a server +def create_subdirectories(sub_directories, parent_directory): + for subdirectory in sub_directories: + if not os.path.exists(parent_directory + "/" + subdirectory): + os.makedirs(parent_directory + "/" + subdirectory) + + +# Create batch and powershell start scripts +def create_start_scripts(server_directory, start_arguments): + with open(server_directory + "/start.bat", "w") as file: + file.write("@echo off\n") + file.write( + f"java {start_arguments}\n") + file.write("pause") + + with open(server_directory + "/start.ps1", "w") as file: + file.write(f"Set-Location -Path {server_directory}\n") + file.write(f"Start-Process java -ArgumentList '{start_arguments}'") + + +# Copies plugins and plugin folders from the source to the target +def copy_plugins(plugins, plugin_folders, plugins_folder): + # Copy each file from the plugin list to the server/plugins folder + for plugin in plugins: + # Skip if the plugin does not exist + if not os.path.exists(plugin): + # If the plugin name contains a *, find the plugin with the same name before the * + if "*" in plugin: + # Get the parent directory of the plugin by getting everything before the last / + parent_directory = plugin.rsplit("/", 1)[0] + plugin_name = plugin.split("*")[0].split("/")[-1] + if os.path.exists(parent_directory): + hit = False + for file in os.listdir(parent_directory): + if file.startswith(plugin_name): + shutil.copy(parent_directory + "/" + file, plugins_folder + "/" + file) + print(f"Copied plugin {file} to {plugins_folder}") + hit = True + break + if not hit: + print(f"Plugin jar file {plugin} could not be found, skipping copy") + continue + else: + print(f"Plugin jar file {plugin} is in an invalid directory, skipping copy") + continue + else: + print(f"Plugin jar file {plugin} does not exist, skipping copy") + continue + + shutil.copy(plugin, plugins_folder) + print(f"Copied plugin {plugin} to {plugins_folder}") + + # Copy each plugin data folder from the plugin list to the server/plugins folder + for folder in plugin_folders: + # Skip if the plugin does not exist + if not os.path.exists(folder): + print(f"Plugin data folder {folder} does not exist, skipping copy") + continue + # Copy the contents of the folder to a subdirectory of the server/plugins folder + shutil.copytree(folder, plugins_folder + "/" + folder.split("/")[-1]) + print(f"Copied plugin data folder {folder} to {plugins_folder}") + + +def start_servers(parameters): + start_server(f"{parameters.root_dir}{parameters.proxy_name}") + for name in parameters.backend_names: + start_server(f"{parameters.root_dir}{name}") + + +def start_server(server): + os.chdir(server) + os.system("start start.bat") + os.chdir("../../") + + +# Execute the main function +if __name__ == "__main__": + main(os.path.exists("./servers"))