diff --git a/api/src/main/java/net/draycia/carbon/api/CarbonChat.java b/api/src/main/java/net/draycia/carbon/api/CarbonChat.java index 925f43ce..c76706b3 100644 --- a/api/src/main/java/net/draycia/carbon/api/CarbonChat.java +++ b/api/src/main/java/net/draycia/carbon/api/CarbonChat.java @@ -1,6 +1,7 @@ package net.draycia.carbon.api; import java.nio.file.Path; +import net.draycia.carbon.api.channels.ChannelRegistry; import net.draycia.carbon.api.events.CarbonEventHandler; import org.apache.logging.log4j.Logger; import org.checkerframework.checker.nullness.qual.NonNull; @@ -49,4 +50,12 @@ public interface CarbonChat { */ CarbonServer server(); + /** + * The registry that channels are registered to. + * + * @return the channel registry + * @since 2.0.0 + */ + ChannelRegistry channelRegistry(); + } diff --git a/api/src/main/java/net/draycia/carbon/api/CarbonServer.java b/api/src/main/java/net/draycia/carbon/api/CarbonServer.java index afa5a314..205dd734 100644 --- a/api/src/main/java/net/draycia/carbon/api/CarbonServer.java +++ b/api/src/main/java/net/draycia/carbon/api/CarbonServer.java @@ -1,7 +1,9 @@ package net.draycia.carbon.api; import java.util.UUID; +import java.util.concurrent.CompletableFuture; import net.draycia.carbon.api.users.CarbonPlayer; +import net.draycia.carbon.api.users.ComponentPlayerResult; import net.kyori.adventure.audience.Audience; import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.Nullable; @@ -35,18 +37,36 @@ public interface CarbonServer extends Audience { * Obtains a {@link CarbonPlayer} instance for the specified uuid. * * @param uuid the player's uuid - * @return the player + * @return the result * @since 2.0.0 */ - @Nullable CarbonPlayer player(final UUID uuid); + CompletableFuture player(final UUID uuid); /** * Obtains a {@link CarbonPlayer} instance for the specified username. * * @param username the player's username - * @return the player + * @return the result * @since 2.0.0 */ - @Nullable CarbonPlayer player(final String username); + CompletableFuture player(final String username); + + /** + * Obtains the desired user's UUID. + * + * @param username the user's username + * @return the user's UUID + * @since 2.0.0 + */ + CompletableFuture<@Nullable UUID> resolveUUID(final String username); + + /** + * Obtains the desired player's name. + * + * @param uuid the user's UUID + * @return the user's name + * @since 2.0.0 + */ + CompletableFuture<@Nullable String> resolveName(final UUID uuid); } diff --git a/api/src/main/java/net/draycia/carbon/api/channels/ChannelRegistry.java b/api/src/main/java/net/draycia/carbon/api/channels/ChannelRegistry.java new file mode 100644 index 00000000..8bb95ace --- /dev/null +++ b/api/src/main/java/net/draycia/carbon/api/channels/ChannelRegistry.java @@ -0,0 +1,12 @@ +package net.draycia.carbon.api.channels; + +import net.draycia.carbon.api.util.DefaultedKeyValueRegistry; +import net.kyori.adventure.key.Key; + +/** + * Registry for chat channels. + * + * @since 2.0.0 + */ +public interface ChannelRegistry extends DefaultedKeyValueRegistry { +} diff --git a/api/src/main/java/net/draycia/carbon/api/channels/ChatChannel.java b/api/src/main/java/net/draycia/carbon/api/channels/ChatChannel.java index f7158ed0..c7b3c634 100644 --- a/api/src/main/java/net/draycia/carbon/api/channels/ChatChannel.java +++ b/api/src/main/java/net/draycia/carbon/api/channels/ChatChannel.java @@ -2,6 +2,7 @@ package net.draycia.carbon.api.channels; import java.util.List; import java.util.Set; +import java.util.function.Supplier; import net.draycia.carbon.api.users.CarbonPlayer; import net.draycia.carbon.api.util.ChatComponentRenderer; import net.kyori.adventure.audience.Audience; @@ -88,6 +89,18 @@ public interface ChatChannel extends Keyed, ChatComponentRenderer { return new ChannelPermissionResult(false, reason); } + // TODO: redo this / reconsider this + public static ChannelPermissionResult allowedIf( + final Component reason, + final Supplier supplier + ) { + if (supplier.get()) { + return ALLOWED; + } else { + return denied(reason); + } + } + } } diff --git a/api/src/main/java/net/draycia/carbon/api/events/ResultedCarbonEvent.java b/api/src/main/java/net/draycia/carbon/api/events/ResultedCarbonEvent.java index e8262823..a06cddcf 100644 --- a/api/src/main/java/net/draycia/carbon/api/events/ResultedCarbonEvent.java +++ b/api/src/main/java/net/draycia/carbon/api/events/ResultedCarbonEvent.java @@ -1,12 +1,15 @@ package net.draycia.carbon.api.events; import net.kyori.adventure.text.Component; +import org.checkerframework.checker.nullness.qual.NonNull; +import org.checkerframework.framework.qual.DefaultQualifier; /** * Represents a {@link CarbonEvent} that has a result. * * @since 2.0.0 */ +@DefaultQualifier(NonNull.class) public interface ResultedCarbonEvent extends CarbonEvent { /** @@ -42,7 +45,7 @@ public interface ResultedCarbonEvent exten /** * The reason of the result.
- * Typically only present if allowed is false. + * Typically empty unless allowed is false. * * @return the reason of the result * @since 2.0.0 diff --git a/api/src/main/java/net/draycia/carbon/api/users/CarbonPlayer.java b/api/src/main/java/net/draycia/carbon/api/users/CarbonPlayer.java index ccca5700..f7a9a61c 100644 --- a/api/src/main/java/net/draycia/carbon/api/users/CarbonPlayer.java +++ b/api/src/main/java/net/draycia/carbon/api/users/CarbonPlayer.java @@ -1,5 +1,6 @@ package net.draycia.carbon.api.users; +import java.util.List; import java.util.Locale; import java.util.UUID; import net.draycia.carbon.api.channels.ChatChannel; @@ -92,4 +93,20 @@ public interface CarbonPlayer extends Audience, Identified { */ boolean hasPermission(final String permission); + /** + * Returns the player's primary group. + * + * @return the player's primary group + * @since 2.0.0 + */ + String primaryGroup(); + + /** + * Returns the complete list of groups the player is in. + * + * @return the groups the player is in + * @since 2.0.0 + */ + List groups(); + } diff --git a/api/src/main/java/net/draycia/carbon/api/users/ComponentPlayerResult.java b/api/src/main/java/net/draycia/carbon/api/users/ComponentPlayerResult.java new file mode 100644 index 00000000..9d522866 --- /dev/null +++ b/api/src/main/java/net/draycia/carbon/api/users/ComponentPlayerResult.java @@ -0,0 +1,15 @@ +package net.draycia.carbon.api.users; + +import net.kyori.adventure.text.Component; +import org.checkerframework.checker.nullness.qual.Nullable; + +/** + * The result of a player data operation. + * + * @param player the {@link CarbonPlayer}, or null if unsuccessful + * @param reason the reason of the result, typically empty unless {@link #player} is null + * @since 2.0.0 + */ +public record ComponentPlayerResult(@Nullable CarbonPlayer player, Component reason) { + +} diff --git a/api/src/main/java/net/draycia/carbon/api/users/UserManager.java b/api/src/main/java/net/draycia/carbon/api/users/UserManager.java index afe2ae28..7f2e88fb 100644 --- a/api/src/main/java/net/draycia/carbon/api/users/UserManager.java +++ b/api/src/main/java/net/draycia/carbon/api/users/UserManager.java @@ -1,12 +1,12 @@ package net.draycia.carbon.api.users; import java.util.UUID; +import java.util.concurrent.CompletableFuture; import org.checkerframework.checker.nullness.qual.NonNull; -import org.checkerframework.checker.nullness.qual.Nullable; import org.checkerframework.framework.qual.DefaultQualifier; /** - * Manager used to load and obtain {@link CarbonPlayer CarbonPlayers}. + * Manager used to load/obtain and save {@link CarbonPlayer CarbonPlayers}. * * @since 2.0.0 */ @@ -16,19 +16,19 @@ public interface UserManager { /** * Loads and returns a {@link CarbonPlayer} with the given {@link UUID}. * - * @param uuid The player's UUID. - * @return The {@link CarbonPlayer}, or null if the player doesn't exist. + * @param uuid the player's uuid + * @return the result * @since 2.0.0 */ - @Nullable CarbonPlayer carbonPlayer(final UUID uuid); + CompletableFuture carbonPlayer(final UUID uuid); /** - * Loads and returns a {@link CarbonPlayer} with the given username. + * Saves the {@link CarbonPlayer} and returns the result. * - * @param username The player's username. - * @return The {@link CarbonPlayer}, or null if the player doesn't exist. + * @param player the player to save + * @return the result * @since 2.0.0 */ - @Nullable CarbonPlayer carbonPlayer(final String username); + CompletableFuture savePlayer(final CarbonPlayer player); } diff --git a/api/src/main/java/net/draycia/carbon/api/util/KeyedRenderer.java b/api/src/main/java/net/draycia/carbon/api/util/KeyedRenderer.java index defec1b6..d47dc3b9 100644 --- a/api/src/main/java/net/draycia/carbon/api/util/KeyedRenderer.java +++ b/api/src/main/java/net/draycia/carbon/api/util/KeyedRenderer.java @@ -26,7 +26,7 @@ public interface KeyedRenderer extends Keyed, ChatComponentRenderer { * @return the keyed renderer * @since 2.0.0 */ - static KeyedRenderer keyedRenderer(final Key key, ChatComponentRenderer renderer) { + static KeyedRenderer keyedRenderer(final Key key, final ChatComponentRenderer renderer) { return new Impl(key, renderer); } diff --git a/bukkit/src/main/java/net/draycia/carbon/bukkit/CarbonChatBukkit.java b/bukkit/src/main/java/net/draycia/carbon/bukkit/CarbonChatBukkit.java index 5fa71ad3..8b760aa1 100644 --- a/bukkit/src/main/java/net/draycia/carbon/bukkit/CarbonChatBukkit.java +++ b/bukkit/src/main/java/net/draycia/carbon/bukkit/CarbonChatBukkit.java @@ -6,7 +6,8 @@ import cloud.commandframework.paper.PaperCommandManager; import com.google.inject.Inject; import com.google.inject.Singleton; import java.nio.file.Path; -import net.draycia.carbon.api.CarbonServer; +import net.draycia.carbon.api.CarbonChatProvider; +import net.draycia.carbon.api.channels.ChannelRegistry; import net.draycia.carbon.api.users.UserManager; import net.draycia.carbon.bukkit.command.BukkitCommander; import net.draycia.carbon.bukkit.command.BukkitPlayerCommander; @@ -25,21 +26,27 @@ public final class CarbonChatBukkit extends CarbonChatCommon { private final UserManager userManager; private final Logger logger; private final CarbonChatBukkitEntry plugin; - private final CarbonServer carbonServerBukkit; + private final CarbonServerBukkit carbonServerBukkit; + private final CarbonMessageService messageService; + private final ChannelRegistry channelRegistry; @Inject private CarbonChatBukkit( final CarbonChatBukkitEntry plugin, final Logger logger, - final CarbonServer carbonServerBukkit, + final CarbonServerBukkit carbonServerBukkit, final UserManager userManager, - final CarbonMessageService messageService + final CarbonMessageService messageService, + final ChannelRegistry channelRegistry ) { - super(messageService); this.userManager = userManager; this.logger = logger; this.plugin = plugin; this.carbonServerBukkit = carbonServerBukkit; + this.messageService = messageService; + this.channelRegistry = channelRegistry; + + CarbonChatProvider.register(this); } public UserManager userManager() { @@ -57,10 +64,20 @@ public final class CarbonChatBukkit extends CarbonChatCommon { } @Override - public CarbonServer server() { + public CarbonServerBukkit server() { return this.carbonServerBukkit; } + @Override + public ChannelRegistry channelRegistry() { + return this.channelRegistry; + } + + @Override + public CarbonMessageService messageService() { + return this.messageService; + } + @Override protected CommandManager createCommandManager() { final PaperCommandManager commandManager; diff --git a/bukkit/src/main/java/net/draycia/carbon/bukkit/CarbonChatBukkitEntry.java b/bukkit/src/main/java/net/draycia/carbon/bukkit/CarbonChatBukkitEntry.java index 8fd6f4b2..f1af1220 100644 --- a/bukkit/src/main/java/net/draycia/carbon/bukkit/CarbonChatBukkitEntry.java +++ b/bukkit/src/main/java/net/draycia/carbon/bukkit/CarbonChatBukkitEntry.java @@ -7,7 +7,10 @@ import io.papermc.lib.PaperLib; import java.util.Set; import java.util.logging.Level; import net.draycia.carbon.bukkit.listeners.BukkitChatListener; +import net.draycia.carbon.bukkit.users.CarbonPlayerBukkit; +import net.draycia.carbon.common.channels.CarbonChannelRegistry; import org.bstats.bukkit.Metrics; +import org.bukkit.Bukkit; import org.bukkit.event.Listener; import org.bukkit.plugin.java.JavaPlugin; import org.checkerframework.checker.nullness.qual.MonotonicNonNull; @@ -40,6 +43,7 @@ public final class CarbonChatBukkitEntry extends JavaPlugin { this, this.getDataFolder().toPath() )); + this.carbon = this.injector.getInstance(CarbonChatBukkit.class); } @@ -55,10 +59,28 @@ public final class CarbonChatBukkitEntry extends JavaPlugin { } this.carbon.initialize(); + + final long saveDelay = 5 * 60 * 20; + + Bukkit.getScheduler().scheduleAsyncRepeatingTask(this, + this::savePlayers, saveDelay, saveDelay); + + ((CarbonChannelRegistry) this.carbon.channelRegistry()).loadChannels(); } @Override public void onDisable() { + this.savePlayers(); + } + + private void savePlayers() { + for (final var player : this.carbon.server().players()) { + this.carbon.userManager().savePlayer(((CarbonPlayerBukkit) player).carbonPlayer()).thenAccept(result -> { + if (result.player() == null) { + this.carbon.server().console().sendMessage(result.reason()); + } + }); + } } } diff --git a/bukkit/src/main/java/net/draycia/carbon/bukkit/CarbonChatBukkitModule.java b/bukkit/src/main/java/net/draycia/carbon/bukkit/CarbonChatBukkitModule.java index f772793e..ab8e6178 100644 --- a/bukkit/src/main/java/net/draycia/carbon/bukkit/CarbonChatBukkitModule.java +++ b/bukkit/src/main/java/net/draycia/carbon/bukkit/CarbonChatBukkitModule.java @@ -4,8 +4,6 @@ import com.google.inject.AbstractModule; import java.nio.file.Path; import net.draycia.carbon.api.CarbonChat; import net.draycia.carbon.api.CarbonServer; -import net.draycia.carbon.api.users.UserManager; -import net.draycia.carbon.bukkit.users.MemoryUserManagerBukkit; import net.draycia.carbon.common.CarbonCommonModule; import net.draycia.carbon.common.ForCarbon; import org.apache.logging.log4j.LogManager; @@ -37,7 +35,6 @@ public final class CarbonChatBukkitModule extends AbstractModule { this.bind(Path.class).annotatedWith(ForCarbon.class).toInstance(this.dataDirectory); this.bind(CarbonChatBukkitEntry.class).toInstance(this.plugin); this.bind(CarbonServer.class).to(CarbonServerBukkit.class); - this.bind(UserManager.class).to(MemoryUserManagerBukkit.class); } } diff --git a/bukkit/src/main/java/net/draycia/carbon/bukkit/CarbonServerBukkit.java b/bukkit/src/main/java/net/draycia/carbon/bukkit/CarbonServerBukkit.java index 5412c321..ff573e39 100644 --- a/bukkit/src/main/java/net/draycia/carbon/bukkit/CarbonServerBukkit.java +++ b/bukkit/src/main/java/net/draycia/carbon/bukkit/CarbonServerBukkit.java @@ -4,16 +4,24 @@ import com.google.inject.Inject; import com.google.inject.Singleton; import java.util.ArrayList; import java.util.UUID; +import java.util.concurrent.CompletableFuture; import net.draycia.carbon.api.CarbonServer; import net.draycia.carbon.api.users.CarbonPlayer; +import net.draycia.carbon.api.users.ComponentPlayerResult; import net.draycia.carbon.api.users.UserManager; +import net.draycia.carbon.bukkit.users.CarbonPlayerBukkit; +import net.draycia.carbon.common.users.CarbonPlayerCommon; import net.kyori.adventure.audience.Audience; import net.kyori.adventure.audience.ForwardingAudience; +import net.kyori.adventure.text.Component; +import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.Nullable; import org.checkerframework.framework.qual.DefaultQualifier; +import static net.kyori.adventure.text.Component.text; + @Singleton @DefaultQualifier(NonNull.class) public final class CarbonServerBukkit implements CarbonServer, ForwardingAudience.Single { @@ -29,7 +37,7 @@ public final class CarbonServerBukkit implements CarbonServer, ForwardingAudienc @Override public Audience audience() { - return Audience.audience(this.console(), Audience.audience(this.players())); + return this.chatBukkitEntry.getServer(); } @Override @@ -42,28 +50,69 @@ public final class CarbonServerBukkit implements CarbonServer, ForwardingAudienc final var players = new ArrayList(); for (final var player : this.chatBukkitEntry.getServer().getOnlinePlayers()) { - final @Nullable CarbonPlayer carbonPlayer = this.player(player); + final @Nullable ComponentPlayerResult result = this.player(player).join(); - if (carbonPlayer != null) { - players.add(carbonPlayer); + if (result.player() != null) { + players.add(result.player()); } } return players; } - @Override - public @Nullable CarbonPlayer player(final UUID uuid) { - return this.userManager.carbonPlayer(uuid); + private CompletableFuture wrapPlayer(final UUID uuid) { + return this.userManager.carbonPlayer(uuid).thenCompose(result -> { + return CompletableFuture.supplyAsync(() -> { + if (result.player() != null) { + new ComponentPlayerResult(new CarbonPlayerBukkit(result.player()), Component.empty()); + } + + final @Nullable String name = this.resolveName(uuid).join(); + + if (name != null) { + final CarbonPlayerCommon player = new CarbonPlayerCommon(null, + null, name, uuid); + + return new ComponentPlayerResult(new CarbonPlayerBukkit(player), Component.empty()); + } + + return new ComponentPlayerResult(null, text("Name not found for uuid!")); + }); + }); } @Override - public @Nullable CarbonPlayer player(final String username) { - return this.userManager.carbonPlayer(username); + public CompletableFuture player(final UUID uuid) { + return this.wrapPlayer(uuid); } - private @Nullable CarbonPlayer player(final Player player) { + @Override + public CompletableFuture player(final String username) { + return CompletableFuture.supplyAsync(() -> { + final @Nullable UUID uuid = this.resolveUUID(username).join(); + + if (uuid != null) { + return this.player(uuid).join(); + } + + return new ComponentPlayerResult(null, text("No UUID found for name.")); + }); + } + + public CompletableFuture player(final Player player) { return this.player(player.getUniqueId()); } + @Override + public CompletableFuture<@Nullable UUID> resolveUUID(final String username) { + // TODO: user cache? + return CompletableFuture.supplyAsync(() -> Bukkit.getOfflinePlayer(username).getUniqueId()); + } + + @Override + public CompletableFuture<@Nullable String> resolveName(final UUID uuid) { + // TODO: user cache? + return CompletableFuture.supplyAsync(() -> Bukkit.getOfflinePlayer(uuid).getName()); + } + } diff --git a/bukkit/src/main/java/net/draycia/carbon/bukkit/command/BukkitPlayerCommander.java b/bukkit/src/main/java/net/draycia/carbon/bukkit/command/BukkitPlayerCommander.java index 98c2d2b6..2941b036 100644 --- a/bukkit/src/main/java/net/draycia/carbon/bukkit/command/BukkitPlayerCommander.java +++ b/bukkit/src/main/java/net/draycia/carbon/bukkit/command/BukkitPlayerCommander.java @@ -27,7 +27,7 @@ public record BukkitPlayerCommander( @Override public @NonNull CarbonPlayer carbonPlayer() { - return requireNonNull(this.carbon.server().player(this.player.getUniqueId()), "No CarbonPlayer for logged in Player!"); + return requireNonNull(this.carbon.server().player(this.player.getUniqueId()).join().player(), "No CarbonPlayer for logged in Player!"); } } diff --git a/bukkit/src/main/java/net/draycia/carbon/bukkit/listeners/BukkitChatListener.java b/bukkit/src/main/java/net/draycia/carbon/bukkit/listeners/BukkitChatListener.java index 9c3d5821..68b5dc58 100644 --- a/bukkit/src/main/java/net/draycia/carbon/bukkit/listeners/BukkitChatListener.java +++ b/bukkit/src/main/java/net/draycia/carbon/bukkit/listeners/BukkitChatListener.java @@ -4,10 +4,13 @@ import com.google.inject.Inject; import io.papermc.paper.event.player.AsyncChatEvent; import java.util.ArrayList; import net.draycia.carbon.api.CarbonChat; +import net.draycia.carbon.api.channels.ChannelRegistry; import net.draycia.carbon.api.events.CarbonChatEvent; +import net.draycia.carbon.api.users.ComponentPlayerResult; import net.draycia.carbon.api.util.KeyedRenderer; -import net.draycia.carbon.common.channels.BasicChatChannel; +import net.draycia.carbon.bukkit.CarbonChatBukkit; import net.kyori.adventure.text.Component; +import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.checkerframework.checker.nullness.qual.NonNull; @@ -19,24 +22,26 @@ import static net.kyori.adventure.text.Component.empty; public final class BukkitChatListener implements Listener { - private final CarbonChat carbonChat; - private final BasicChatChannel basicChat; + private final CarbonChatBukkit carbonChat; + private final ChannelRegistry registry; @Inject - public BukkitChatListener(final CarbonChat carbonChat, final BasicChatChannel basicChat) { - this.carbonChat = carbonChat; - this.basicChat = basicChat; + public BukkitChatListener(final CarbonChat carbonChat, final ChannelRegistry registry) { + this.carbonChat = (CarbonChatBukkit) carbonChat; + this.registry = registry; } @EventHandler public void onPlayerChat(final @NonNull AsyncChatEvent event) { - final var sender = this.carbonChat.server().player(event.getPlayer().getUniqueId()); + final var playerResult = this.carbonChat.server().player(event.getPlayer().getUniqueId()).join(); - if (sender == null) { + if (playerResult.player() == null) { return; } - final var channel = requireNonNullElse(sender.selectedChannel(), this.basicChat); + final var sender = playerResult.player(); + final var channel = requireNonNullElse(playerResult.player().selectedChannel(), + this.registry.defaultValue()); // TODO: option to specify if the channel should invoke ChatChannel#recipients // or ChatChannel#filterRecipients @@ -70,7 +75,12 @@ public final class BukkitChatListener implements Listener { Component component = message; for (final var renderer : chatEvent.renderers()) { - component = renderer.render(sender, viewer, component, message); + if (viewer instanceof Player player) { + final ComponentPlayerResult targetPlayer = this.carbonChat.server().player(player).join(); + component = renderer.render(playerResult.player(), targetPlayer.player(), component, message); + } else { + component = renderer.render(playerResult.player(), viewer, component, message); + } } return component; diff --git a/bukkit/src/main/java/net/draycia/carbon/bukkit/users/CarbonPlayerBukkit.java b/bukkit/src/main/java/net/draycia/carbon/bukkit/users/CarbonPlayerBukkit.java index 9317fa6d..2f3ba82a 100644 --- a/bukkit/src/main/java/net/draycia/carbon/bukkit/users/CarbonPlayerBukkit.java +++ b/bukkit/src/main/java/net/draycia/carbon/bukkit/users/CarbonPlayerBukkit.java @@ -1,9 +1,13 @@ package net.draycia.carbon.bukkit.users; +import java.util.List; import java.util.Locale; import java.util.UUID; +import net.draycia.carbon.api.channels.ChatChannel; +import net.draycia.carbon.api.users.CarbonPlayer; import net.draycia.carbon.common.users.CarbonPlayerCommon; import net.kyori.adventure.audience.Audience; +import net.kyori.adventure.audience.ForwardingAudience; import net.kyori.adventure.identity.Identity; import net.kyori.adventure.text.Component; import org.bukkit.Bukkit; @@ -14,18 +18,17 @@ import org.checkerframework.checker.nullness.qual.Nullable; import org.checkerframework.framework.qual.DefaultQualifier; @DefaultQualifier(NonNull.class) -public final class CarbonPlayerBukkit extends CarbonPlayerCommon { +public final class CarbonPlayerBukkit extends CarbonPlayerCommon implements ForwardingAudience.Single { - public CarbonPlayerBukkit( - final @NonNull String username, - final @NonNull UUID uuid - ) { - super(username, uuid, Identity.identity(uuid)); + private final CarbonPlayer carbonPlayer; + + public CarbonPlayerBukkit(final CarbonPlayer carbonPlayer) { + this.carbonPlayer = carbonPlayer; } @Override public void displayName(final @Nullable Component displayName) { - super.displayName(displayName); + this.carbonPlayer.displayName(displayName); final @Nullable Player player = this.player(); @@ -35,6 +38,21 @@ public final class CarbonPlayerBukkit extends CarbonPlayerCommon { } } + @Override + public String username() { + return this.carbonPlayer.username(); + } + + @Override + public Component displayName() { + return this.carbonPlayer.displayName(); + } + + @Override + public UUID uuid() { + return this.carbonPlayer.uuid(); + } + @Override public @NonNull Audience audience() { final @Nullable Player player = this.player(); @@ -46,19 +64,9 @@ public final class CarbonPlayerBukkit extends CarbonPlayerCommon { return player; } - private @Nullable Player player() { - return Bukkit.getPlayer(this.uuid); - } - @Override - public @Nullable Locale locale() { - final @Nullable Player player = this.player(); - - if (player != null) { - return player.locale(); - } else { - return null; - } + public CarbonPlayer carbonPlayer() { + return this.carbonPlayer; } @Override @@ -107,4 +115,44 @@ public final class CarbonPlayerBukkit extends CarbonPlayerCommon { return false; } + @Override + public String primaryGroup() { + return "default"; // TODO: implement + } + + @Override + public List groups() { + return List.of("default"); // TODO: implement + } + + @Override + public @Nullable Locale locale() { + final @Nullable Player player = this.player(); + + if (player != null) { + return player.locale(); + } else { + return null; + } + } + + private @Nullable Player player() { + return Bukkit.getPlayer(this.carbonPlayer.uuid()); + } + + @Override + public @Nullable ChatChannel selectedChannel() { + return this.carbonPlayer.selectedChannel(); + } + + @Override + public void selectedChannel(final ChatChannel chatChannel) { + this.carbonPlayer.selectedChannel(chatChannel); + } + + @Override + public @NonNull Identity identity() { + return this.carbonPlayer.identity(); + } + } diff --git a/bukkit/src/main/java/net/draycia/carbon/bukkit/users/MemoryUserManagerBukkit.java b/bukkit/src/main/java/net/draycia/carbon/bukkit/users/MemoryUserManagerBukkit.java deleted file mode 100644 index 0241568f..00000000 --- a/bukkit/src/main/java/net/draycia/carbon/bukkit/users/MemoryUserManagerBukkit.java +++ /dev/null @@ -1,51 +0,0 @@ -package net.draycia.carbon.bukkit.users; - -import com.google.inject.Singleton; -import java.util.HashMap; -import java.util.Map; -import java.util.UUID; -import net.draycia.carbon.api.users.CarbonPlayer; -import net.draycia.carbon.api.users.UserManager; -import org.bukkit.Bukkit; -import org.bukkit.entity.Player; -import org.checkerframework.checker.nullness.qual.NonNull; -import org.checkerframework.checker.nullness.qual.Nullable; - -/** - * This class should not be used. - * No data is persisted or saved. - * This exists merely as a placeholder. - */ -@Singleton -public final class MemoryUserManagerBukkit implements UserManager { - - private final @NonNull Map users = new HashMap<>(); - - @Override - public @Nullable CarbonPlayer carbonPlayer(final @NonNull UUID uuid) { - if (this.users.containsKey(uuid)) { - return this.users.get(uuid); - } - - final Player player = Bukkit.getPlayer(uuid); - - if (player == null) { - return null; - } - - return this.users.computeIfAbsent(player.getUniqueId(), key -> - new CarbonPlayerBukkit(player.getName(), player.getUniqueId())); - } - - @Override - public @Nullable CarbonPlayer carbonPlayer(final @NonNull String username) { - final Player player = Bukkit.getPlayer(username); - - if (player == null) { - return null; - } - - return this.carbonPlayer(player.getUniqueId()); - } - -} diff --git a/common/build.gradle.kts b/common/build.gradle.kts index 62e0be28..0ecf725a 100644 --- a/common/build.gradle.kts +++ b/common/build.gradle.kts @@ -7,9 +7,13 @@ dependencies { // Configs api(libs.configurateHocon) + api(libs.configurateGuice) api(libs.adventureSerializerConfigurate4) { isTransitive = false } + api(libs.adventureTextSerializerGson) { + isTransitive = false + } api(libs.typesafeConfig) // Other diff --git a/common/src/main/java/net/draycia/carbon/common/CarbonChatCommon.java b/common/src/main/java/net/draycia/carbon/common/CarbonChatCommon.java index 5f58cc45..b48121ed 100644 --- a/common/src/main/java/net/draycia/carbon/common/CarbonChatCommon.java +++ b/common/src/main/java/net/draycia/carbon/common/CarbonChatCommon.java @@ -17,11 +17,7 @@ import static net.kyori.adventure.text.Component.text; @DefaultQualifier(NonNull.class) public abstract class CarbonChatCommon implements CarbonChat { - private final CarbonMessageService messageService; - - protected CarbonChatCommon(final CarbonMessageService messageService) { - this.messageService = messageService; - } + public abstract CarbonMessageService messageService(); private final CarbonEventHandler eventHandler = new CarbonEventHandler(); @@ -31,10 +27,10 @@ public abstract class CarbonChatCommon implements CarbonChat { .handler(ctx -> { final Commander sender = ctx.getSender(); - this.messageService.exampleCommandFeedback(sender, this.messageService.pluginName()); + this.messageService().exampleCommandFeedback(sender, this.messageService().pluginName()); if (sender instanceof PlayerCommander player) { - this.messageService.localeTestMessage(player.carbonPlayer()); + this.messageService().localeTestMessage(player.carbonPlayer()); final Component itemComponent = player.carbonPlayer().createItemHoverComponent(); if (itemComponent != empty()) { diff --git a/common/src/main/java/net/draycia/carbon/common/CarbonCommonModule.java b/common/src/main/java/net/draycia/carbon/common/CarbonCommonModule.java index ce03581c..dddf43b3 100644 --- a/common/src/main/java/net/draycia/carbon/common/CarbonCommonModule.java +++ b/common/src/main/java/net/draycia/carbon/common/CarbonCommonModule.java @@ -1,11 +1,15 @@ package net.draycia.carbon.common; import com.google.inject.AbstractModule; +import com.google.inject.Injector; import com.google.inject.Provides; import com.google.inject.Singleton; import com.proximyst.moonshine.Moonshine; import java.io.IOException; import java.util.UUID; +import net.draycia.carbon.api.channels.ChannelRegistry; +import net.draycia.carbon.api.users.UserManager; +import net.draycia.carbon.common.channels.CarbonChannelRegistry; import net.draycia.carbon.common.config.ConfigLoader; import net.draycia.carbon.common.config.PrimaryConfig; import net.draycia.carbon.common.messages.CarbonMessageParser; @@ -15,6 +19,7 @@ import net.draycia.carbon.common.messages.CarbonMessageSource; import net.draycia.carbon.common.messages.ComponentPlaceholderResolver; import net.draycia.carbon.common.messages.ServerReceiverResolver; import net.draycia.carbon.common.messages.UUIDPlaceholderResolver; +import net.draycia.carbon.common.users.JSONUserManager; import net.kyori.adventure.audience.Audience; import net.kyori.adventure.text.Component; import org.checkerframework.checker.nullness.qual.NonNull; @@ -24,6 +29,19 @@ import org.checkerframework.framework.qual.DefaultQualifier; @DefaultQualifier(NonNull.class) public final class CarbonCommonModule extends AbstractModule { + @Provides + @Singleton + public UserManager userManager( + final PrimaryConfig primaryConfig, + final Injector injector + ) { + switch (primaryConfig.storageType()) { + default -> { + return injector.getInstance(JSONUserManager.class); + } + } + } + @Provides @Singleton public PrimaryConfig primaryConfig(final ConfigLoader configLoader) throws IOException { @@ -57,4 +75,9 @@ public final class CarbonCommonModule extends AbstractModule { .create(CarbonMessageService.class, this.getClass().getClassLoader()); } + @Override + protected void configure() { + this.bind(ChannelRegistry.class).to(CarbonChannelRegistry.class); + } + } diff --git a/common/src/main/java/net/draycia/carbon/common/channels/BasicChatChannel.java b/common/src/main/java/net/draycia/carbon/common/channels/BasicChatChannel.java index 43b98ab7..8baad697 100644 --- a/common/src/main/java/net/draycia/carbon/common/channels/BasicChatChannel.java +++ b/common/src/main/java/net/draycia/carbon/common/channels/BasicChatChannel.java @@ -20,7 +20,7 @@ import org.jetbrains.annotations.NotNull; @DefaultQualifier(NonNull.class) public final class BasicChatChannel implements ChatChannel { - private final Key key = Key.key("carbon", "vanilla"); + private final Key key = Key.key("carbon", "basic"); private final CarbonMessageService service; private final CarbonChat carbonChat; @@ -30,8 +30,8 @@ public final class BasicChatChannel implements ChatChannel { final CarbonMessageService service, final CarbonChat carbonChat ) { - this.service = service; this.carbonChat = carbonChat; + this.service = service; } @Override @@ -41,8 +41,6 @@ public final class BasicChatChannel implements ChatChannel { final Component message, final Component originalMessage ) { - // TODO: Once per-user is setup, use the service for the recipient? - // TODO: Or, have the MessageSource do the per-use for us. return this.service.basicChatFormat( recipient, sender.uuid(), diff --git a/common/src/main/java/net/draycia/carbon/common/channels/CarbonChannelRegistry.java b/common/src/main/java/net/draycia/carbon/common/channels/CarbonChannelRegistry.java new file mode 100644 index 00000000..8d0ed35a --- /dev/null +++ b/common/src/main/java/net/draycia/carbon/common/channels/CarbonChannelRegistry.java @@ -0,0 +1,148 @@ +package net.draycia.carbon.common.channels; + +import com.google.inject.Inject; +import com.google.inject.Injector; +import com.google.inject.Singleton; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Objects; +import java.util.stream.Stream; +import net.draycia.carbon.api.channels.ChannelRegistry; +import net.draycia.carbon.api.channels.ChatChannel; +import net.draycia.carbon.common.ForCarbon; +import net.draycia.carbon.common.config.ConfigLoader; +import net.draycia.carbon.common.config.PrimaryConfig; +import net.kyori.adventure.key.Key; +import net.kyori.registry.DefaultedRegistry; +import net.kyori.registry.RegistryImpl; +import org.apache.logging.log4j.Logger; +import org.checkerframework.checker.nullness.qual.NonNull; +import org.checkerframework.checker.nullness.qual.Nullable; +import org.checkerframework.framework.qual.DefaultQualifier; +import org.spongepowered.configurate.ConfigurateException; +import org.spongepowered.configurate.loader.ConfigurationLoader; +import org.spongepowered.configurate.objectmapping.ObjectMapper; +import org.spongepowered.configurate.serialize.SerializationException; + +@Singleton +@DefaultQualifier(NonNull.class) +public class CarbonChannelRegistry extends RegistryImpl implements ChannelRegistry, DefaultedRegistry { + + private final ConfigLoader configLoader; + private final Path dataDirectory; + private final Injector injector; + private final Logger logger; + private final PrimaryConfig primaryConfig; + + private Key defaultKey; + private ChatChannel basicChannel; + + @Inject + public CarbonChannelRegistry( + final ConfigLoader configLoader, + @ForCarbon final Path dataDirectory, + final Injector injector, + final Logger logger, + final PrimaryConfig primaryConfig + ) { + this.configLoader = configLoader; + this.dataDirectory = dataDirectory; + this.injector = injector; + this.logger = logger; + this.primaryConfig = primaryConfig; + } + + public void loadChannels() { + final Path channelDirectory = this.dataDirectory.resolve("channels"); + this.basicChannel = this.injector.getInstance(BasicChatChannel.class); + this.defaultKey = this.primaryConfig.defaultChannel(); + + if (!Files.exists(channelDirectory)) { + // folder doesn't exist, no channels setup + try { + Files.createDirectories(channelDirectory); + + this.register(this.basicChannel.key(), this.basicChannel); + + final Path configFile = channelDirectory.resolve("basic-channel.conf.example"); + + final var loader = this.configLoader.configurationLoader(configFile); + final var node = loader.load(); + + final var configChannel = this.injector.getInstance(ConfigChatChannel.class); + node.set(ConfigChatChannel.class, configChannel); + + loader.save(node); + + // TODO: create advanced-channel.conf.example + // TODO: log in console, "no channels found - adding example configs" + } catch (final IOException exception) { + exception.printStackTrace(); + } + + return; + } + + try (final Stream paths = Files.walk(channelDirectory)) { + paths.forEach(path -> { + final String fileName = path.getFileName().toString(); + + if (fileName.endsWith(".conf")) { + final @Nullable ChatChannel channel = this.loadChannel(path); + + if (channel != null) { + this.logger.info("Registering channel with key [" + channel.key() + "]"); + register(channel.key(), channel); + } + } + }); + } catch (final IOException exception) { + exception.printStackTrace(); + } + } + + private static ObjectMapper MAPPER; + + static { + try { + MAPPER = ObjectMapper.factory().get(ConfigChatChannel.class); + } catch (final SerializationException e) { + e.printStackTrace(); + } + } + + public @Nullable ChatChannel loadChannel(final Path channelFile) { + final ConfigurationLoader loader = this.configLoader.configurationLoader(channelFile); + + try { + return MAPPER.load(loader.load()); + } catch (final ConfigurateException exception) { + exception.printStackTrace(); + } + + return null; + } + + @Override + public @NonNull ChatChannel defaultValue() { + return Objects.requireNonNullElse(this.get(this.defaultKey), this.basicChannel); + } + + @Override + public @NonNull Key defaultKey() { + return this.defaultKey; + } + + @Override + public @NonNull ChatChannel getOrDefault(@NonNull final Key key) { + final @Nullable ChatChannel channel = this.get(key); + + if (channel != null) { + return channel; + } + + return this.defaultValue(); + } + +} diff --git a/common/src/main/java/net/draycia/carbon/common/channels/ConfigChatChannel.java b/common/src/main/java/net/draycia/carbon/common/channels/ConfigChatChannel.java new file mode 100644 index 00000000..8a798fa2 --- /dev/null +++ b/common/src/main/java/net/draycia/carbon/common/channels/ConfigChatChannel.java @@ -0,0 +1,141 @@ +package net.draycia.carbon.common.channels; + +import com.proximyst.moonshine.Moonshine; +import java.util.ArrayList; +import java.util.List; +import java.util.Set; +import java.util.UUID; +import net.draycia.carbon.api.CarbonChatProvider; +import net.draycia.carbon.api.channels.ChatChannel; +import net.draycia.carbon.api.users.CarbonPlayer; +import net.draycia.carbon.common.channels.messages.ConfigChannelMessageService; +import net.draycia.carbon.common.channels.messages.ConfigChannelMessageSource; +import net.draycia.carbon.common.messages.CarbonMessageParser; +import net.draycia.carbon.common.messages.CarbonMessageSender; +import net.draycia.carbon.common.messages.ComponentPlaceholderResolver; +import net.draycia.carbon.common.messages.ServerReceiverResolver; +import net.draycia.carbon.common.messages.UUIDPlaceholderResolver; +import net.kyori.adventure.audience.Audience; +import net.kyori.adventure.key.Key; +import net.kyori.adventure.text.Component; +import org.checkerframework.checker.nullness.qual.NonNull; +import org.checkerframework.checker.nullness.qual.Nullable; +import org.checkerframework.framework.qual.DefaultQualifier; +import org.jetbrains.annotations.NotNull; +import org.spongepowered.configurate.objectmapping.ConfigSerializable; +import org.spongepowered.configurate.objectmapping.meta.Comment; +import org.spongepowered.configurate.objectmapping.meta.Setting; + +import static net.kyori.adventure.text.Component.text; + +@ConfigSerializable +@DefaultQualifier(NonNull.class) +public final class ConfigChatChannel implements ChatChannel { + + @Comment(""" + The channel's key, used to track the channel. + The key can stay "carbon". + The value is what's used in commands, this is probably what you want to change. + """) + private Key key = Key.key("carbon", "basic"); + + @Comment(""" + The permission required to use the channel. + To read messages you must have the permission carbon.channel.basic.see + To send messages you must have the permission carbon.channel.basic.speak + If you want to give both, grant carbon.channel.basic or carbon.channel.basic.* + """) + private String permission = "carbon.channel.basic"; + + @Setting("format") + @Comment("The chat formats for this channel.") + private ConfigChannelMessageSource messageSource = new ConfigChannelMessageSource(); + + private transient @Nullable ConfigChannelMessageService messageService = null; + + @Override + public @NotNull Component render( + final CarbonPlayer sender, + final Audience recipient, + final Component message, + final Component originalMessage + ) { + return this.messageService().chatFormat( + recipient, + sender.uuid(), + sender.displayName(), + sender.username(), + message + ); + } + + @Override + public ChannelPermissionResult speechPermitted(final CarbonPlayer carbonPlayer) { + return ChannelPermissionResult.allowedIf(text("Insufficient permissions!"), () -> + carbonPlayer.hasPermission(this.permission + ".speak")); // carbon.channels.local.speak + } + + @Override + public ChannelPermissionResult hearingPermitted(final Audience audience) { + if (audience instanceof CarbonPlayer carbonPlayer) { + return ChannelPermissionResult.allowedIf(text("Insufficient permissions!"), () -> + carbonPlayer.hasPermission(this.permission + ".see")); // carbon.channels.local.see + } else { + return ChannelPermissionResult.allowed(); + } + } + + @Override + public List recipients(final CarbonPlayer sender) { + final List recipients = new ArrayList<>(); + + for (final CarbonPlayer player : CarbonChatProvider.carbonChat().server().players()) { + if (this.hearingPermitted(player).permitted()) { + recipients.add(player); + } + } + + // console too! + recipients.add(CarbonChatProvider.carbonChat().server().console()); + + return recipients; + } + + @Override + public Set filterRecipients(final CarbonPlayer sender, final Set recipients) { + recipients.removeIf(it -> !this.hearingPermitted(it).permitted()); + + return recipients; + } + + @Override + public @NonNull Key key() { + return this.key; + } + + private ConfigChannelMessageService createMessageService() { + final ServerReceiverResolver serverReceiverResolver = new ServerReceiverResolver(CarbonChatProvider.carbonChat().server()); + final ComponentPlaceholderResolver componentPlaceholderResolver = new ComponentPlaceholderResolver<>(); + final UUIDPlaceholderResolver uuidPlaceholderResolver = new UUIDPlaceholderResolver<>(); + final CarbonMessageParser carbonMessageParser = new CarbonMessageParser(); + final CarbonMessageSender carbonMessageSender = new CarbonMessageSender(); + + return Moonshine.builder() + .receiver(serverReceiverResolver) + .placeholder(Component.class, componentPlaceholderResolver) + .placeholder(UUID.class, uuidPlaceholderResolver) + .source(this.messageSource) + .parser(carbonMessageParser) + .sender(carbonMessageSender) + .create(ConfigChannelMessageService.class, this.getClass().getClassLoader()); + } + + private ConfigChannelMessageService messageService() { + if (this.messageService == null) { + this.messageService = this.createMessageService(); + } + + return this.messageService; + } + +} diff --git a/common/src/main/java/net/draycia/carbon/common/channels/messages/ConfigChannelMessageService.java b/common/src/main/java/net/draycia/carbon/common/channels/messages/ConfigChannelMessageService.java new file mode 100644 index 00000000..ec3a9527 --- /dev/null +++ b/common/src/main/java/net/draycia/carbon/common/channels/messages/ConfigChannelMessageService.java @@ -0,0 +1,22 @@ +package net.draycia.carbon.common.channels.messages; + +import com.proximyst.moonshine.annotation.Message; +import com.proximyst.moonshine.annotation.Placeholder; +import com.proximyst.moonshine.annotation.Receiver; +import java.util.UUID; +import net.kyori.adventure.audience.Audience; +import net.kyori.adventure.text.Component; + +public interface ConfigChannelMessageService { + + // TODO: locale placeholders? + @Message("channel.format") + Component chatFormat( + @Receiver final Audience audience, + @Placeholder UUID uuid, + @Placeholder Component displayname, + @Placeholder String username, + @Placeholder Component message + ); + +} diff --git a/common/src/main/java/net/draycia/carbon/common/channels/messages/ConfigChannelMessageSource.java b/common/src/main/java/net/draycia/carbon/common/channels/messages/ConfigChannelMessageSource.java new file mode 100644 index 00000000..bfd0d4c9 --- /dev/null +++ b/common/src/main/java/net/draycia/carbon/common/channels/messages/ConfigChannelMessageSource.java @@ -0,0 +1,78 @@ +package net.draycia.carbon.common.channels.messages; + +import com.proximyst.moonshine.message.IMessageSource; +import java.util.Locale; +import java.util.Map; +import net.draycia.carbon.api.users.CarbonPlayer; +import net.kyori.adventure.audience.Audience; +import org.checkerframework.checker.nullness.qual.NonNull; +import org.checkerframework.framework.qual.DefaultQualifier; +import org.spongepowered.configurate.objectmapping.ConfigSerializable; +import org.spongepowered.configurate.objectmapping.meta.Comment; +import org.spongepowered.configurate.objectmapping.meta.Setting; + +@ConfigSerializable +@DefaultQualifier(NonNull.class) +public class ConfigChannelMessageSource implements IMessageSource { + + // Map -> Map + // "default" key will be configurable but let's not worry about that for now + @Setting("basic") + @Comment(""" + Basic chat formats. + The "default" format is the main one you want to edit. + The "console" format is what's shown to console. + The keys are group names, the values are chat formats (MiniMessage). + """) + private Map defaults = Map.of("default", ": ", + "console", " - : "); + + // TODO: Move the default to the advanced config? + @Comment(""" + Per-Language chat formats. + You can safely delete this section if you don't want to use this feature. + Will fall back to the defaults section if no format was found for the player. + """) + private Map> locales = Map.of(Locale.US, + Map.of("default", ": ")); + + @Override + public String message(final String key, final Audience receiver) { + if (receiver instanceof CarbonPlayer player) { + return this.forPlayer(key, player); + } else { + return this.forAudience(key, receiver); + } + } + + private String forPlayer(final String key, final CarbonPlayer player) { + final Map formats = this.locales.get(player.locale()); + + if (formats != null) { + final String format = formats.get(player.primaryGroup()); + + if (format != null) { + return format; + } + + final String defaultFormat = formats.get("default"); + + if (defaultFormat != null) { + return defaultFormat; + } + } + + final String format = this.defaults.get(player.primaryGroup()); + + if (format != null) { + return format; + } + + return this.defaults.get("default"); + } + + private String forAudience(final String key, final Audience audience) { + return this.defaults.get("console"); + } + +} diff --git a/common/src/main/java/net/draycia/carbon/common/config/ConfigLoader.java b/common/src/main/java/net/draycia/carbon/common/config/ConfigLoader.java index 6f42549e..c1024580 100644 --- a/common/src/main/java/net/draycia/carbon/common/config/ConfigLoader.java +++ b/common/src/main/java/net/draycia/carbon/common/config/ConfigLoader.java @@ -1,25 +1,54 @@ package net.draycia.carbon.common.config; import com.google.inject.Inject; +import com.google.inject.Injector; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; +import java.util.Locale; import net.draycia.carbon.common.ForCarbon; +import net.draycia.carbon.common.serialisation.gson.LocaleSerializerConfigurate; import net.kyori.adventure.serializer.configurate4.ConfigurateComponentSerializer; import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.Nullable; import org.checkerframework.framework.qual.DefaultQualifier; import org.spongepowered.configurate.ConfigurateException; import org.spongepowered.configurate.hocon.HoconConfigurationLoader; +import org.spongepowered.configurate.loader.ConfigurationLoader; +import org.spongepowered.configurate.objectmapping.ObjectMapper; +import org.spongepowered.configurate.objectmapping.guice.GuiceObjectMapperProvider; @DefaultQualifier(NonNull.class) public class ConfigLoader { private final Path dataDirectory; + private final ObjectMapper.Factory mapper; @Inject - public ConfigLoader(@ForCarbon final @NonNull Path dataDirectory) { + public ConfigLoader( + @ForCarbon final Path dataDirectory, + final Injector injector + ) { this.dataDirectory = dataDirectory; + this.mapper = ObjectMapper.factoryBuilder() + .addDiscoverer(GuiceObjectMapperProvider.injectedObjectDiscoverer(injector)) + .build(); + } + + public ConfigurationLoader configurationLoader(final Path file) { + return HoconConfigurationLoader.builder() + .prettyPrinting(true) + .defaultOptions(opts -> { + final ConfigurateComponentSerializer serializer = + ConfigurateComponentSerializer.configurate(); + + return opts.shouldCopyDefaults(true).serializers(serializerBuilder -> + serializerBuilder.registerAll(serializer.serializers()) + .register(Locale.class, new LocaleSerializerConfigurate()) + ); + }) + .path(file) + .build(); } public @Nullable T load(final Class clazz, final String fileName) throws IOException { @@ -29,17 +58,7 @@ public class ConfigLoader { final Path file = this.dataDirectory.resolve(fileName); - final var loader = HoconConfigurationLoader.builder() - .prettyPrinting(true) - .defaultOptions(opts -> { - final ConfigurateComponentSerializer serializer = - ConfigurateComponentSerializer.configurate(); - - return opts.shouldCopyDefaults(true).serializers(serializerBuilder -> - serializerBuilder.registerAll(serializer.serializers())); - }) - .path(file) - .build(); + final var loader = this.configurationLoader(file); try { final var node = loader.load(); diff --git a/common/src/main/java/net/draycia/carbon/common/config/PrimaryConfig.java b/common/src/main/java/net/draycia/carbon/common/config/PrimaryConfig.java index 206e3bc3..6219d3cc 100644 --- a/common/src/main/java/net/draycia/carbon/common/config/PrimaryConfig.java +++ b/common/src/main/java/net/draycia/carbon/common/config/PrimaryConfig.java @@ -1,5 +1,7 @@ package net.draycia.carbon.common.config; +import java.util.Locale; +import net.kyori.adventure.key.Key; import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.framework.qual.DefaultQualifier; import org.spongepowered.configurate.objectmapping.ConfigSerializable; @@ -10,10 +12,30 @@ import org.spongepowered.configurate.objectmapping.meta.Comment; public class PrimaryConfig { @Comment("The default locale for plugin messages.") - private String defaultLocale = "en_US"; + private Locale defaultLocale = Locale.US; - public String defaultLocale() { + public Locale defaultLocale() { return this.defaultLocale; } + @Comment("The default channel that new players will be in when they join.") + private Key defaultChannel = Key.key("carbon", "basic"); + + public Key defaultChannel() { + return this.defaultChannel; + } + + @Comment("The service that will be used to store and load player information.") + private StorageType storageType = StorageType.JSON; + + public StorageType storageType() { + return this.storageType; + } + + public enum StorageType { + JSON, + MYSQL, + PSQL + } + } diff --git a/common/src/main/java/net/draycia/carbon/common/messages/CarbonMessageParser.java b/common/src/main/java/net/draycia/carbon/common/messages/CarbonMessageParser.java index 79059d2e..fd7c20d9 100644 --- a/common/src/main/java/net/draycia/carbon/common/messages/CarbonMessageParser.java +++ b/common/src/main/java/net/draycia/carbon/common/messages/CarbonMessageParser.java @@ -1,35 +1,16 @@ package net.draycia.carbon.common.messages; -import com.google.inject.Inject; import com.google.inject.Singleton; import com.proximyst.moonshine.message.IMessageParser; import com.proximyst.moonshine.message.ParsingContext; import net.kyori.adventure.audience.Audience; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.minimessage.MiniMessage; -import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer; @Singleton public class CarbonMessageParser implements IMessageParser { - private final CarbonMessageService messageService; - - private final boolean checkForLegacy = !Boolean.getBoolean("disableLegacyCheck"); - private final String legacyChar = String.valueOf(LegacyComponentSerializer.SECTION_CHAR); - - @Inject - public CarbonMessageParser(final CarbonMessageService messageService) { - this.messageService = messageService; - } - - public Component parse(String message, final ParsingContext parsingContext) { - if (this.checkForLegacy) { - if (message.contains(this.legacyChar)) { - message = message.replace(this.legacyChar, ""); - this.messageService.unsupportedLegacyChar(parsingContext.receiver(), message); - } - } - + public Component parse(final String message, final ParsingContext parsingContext) { return MiniMessage.get().parse(message, parsingContext.placeholders()); } diff --git a/common/src/main/java/net/draycia/carbon/common/messages/CarbonMessageSource.java b/common/src/main/java/net/draycia/carbon/common/messages/CarbonMessageSource.java index 3858a9a8..05ae0892 100644 --- a/common/src/main/java/net/draycia/carbon/common/messages/CarbonMessageSource.java +++ b/common/src/main/java/net/draycia/carbon/common/messages/CarbonMessageSource.java @@ -51,13 +51,7 @@ public final class CarbonMessageSource implements IMessageSource, JsonDeserializer { + + @Override + public CarbonPlayerCommon deserialize( + final JsonElement jsonElement, + final Type type, + final JsonDeserializationContext context + ) throws JsonParseException { + final JsonObject object = jsonElement.getAsJsonObject(); + + final Component displayName = context.deserialize(object.get("displayName"), Component.class); + final ChatChannel selectedChannel = context.deserialize(object.get("selectedChannel"), ChatChannel.class); + final String username = object.get("username").getAsString(); + final UUID uuid = context.deserialize(object.get("uuid"), UUID.class); + + return new CarbonPlayerCommon(displayName, selectedChannel, username, uuid); + } + + @Override + public JsonElement serialize( + final CarbonPlayerCommon player, + final Type type, + final JsonSerializationContext context + ) { + final JsonObject object = new JsonObject(); + + object.add("displayName", context.serialize(player.displayName())); + object.add("selectedChannel", context.serialize(player.selectedChannel())); + object.add("username", context.serialize(player.username())); + object.add("uuid", context.serialize(player.uuid())); + + return object; + } + +} diff --git a/common/src/main/java/net/draycia/carbon/common/serialisation/gson/ChatChannelSerializerGson.java b/common/src/main/java/net/draycia/carbon/common/serialisation/gson/ChatChannelSerializerGson.java new file mode 100644 index 00000000..f206eaa3 --- /dev/null +++ b/common/src/main/java/net/draycia/carbon/common/serialisation/gson/ChatChannelSerializerGson.java @@ -0,0 +1,43 @@ +package net.draycia.carbon.common.serialisation.gson; + +import com.google.gson.TypeAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import com.google.inject.Inject; +import java.io.IOException; +import net.draycia.carbon.api.channels.ChannelRegistry; +import net.draycia.carbon.api.channels.ChatChannel; +import org.checkerframework.checker.nullness.qual.NonNull; +import org.checkerframework.checker.nullness.qual.Nullable; +import org.checkerframework.framework.qual.DefaultQualifier; + +import static net.kyori.adventure.key.Key.key; + +@DefaultQualifier(NonNull.class) +public class ChatChannelSerializerGson extends TypeAdapter { + + private final ChannelRegistry registry; + + @Inject + public ChatChannelSerializerGson(final ChannelRegistry registry) { + this.registry = registry; + } + + @Override + public void write(final JsonWriter out, final ChatChannel value) throws IOException { + out.value(value.key().asString()); + } + + @Override + @SuppressWarnings("PatternValidation") // the input is variable + public @Nullable ChatChannel read(final JsonReader in) throws IOException { + final @Nullable String channelName = in.nextString(); + + if (channelName != null) { + return this.registry.get(key(channelName)); + } + + return null; + } + +} diff --git a/common/src/main/java/net/draycia/carbon/common/serialisation/gson/LocaleSerializerConfigurate.java b/common/src/main/java/net/draycia/carbon/common/serialisation/gson/LocaleSerializerConfigurate.java new file mode 100644 index 00000000..49810a47 --- /dev/null +++ b/common/src/main/java/net/draycia/carbon/common/serialisation/gson/LocaleSerializerConfigurate.java @@ -0,0 +1,29 @@ +package net.draycia.carbon.common.serialisation.gson; + +import java.lang.reflect.Type; +import java.util.Locale; +import net.kyori.adventure.translation.Translator; +import org.checkerframework.checker.nullness.qual.Nullable; +import org.spongepowered.configurate.ConfigurationNode; +import org.spongepowered.configurate.serialize.SerializationException; +import org.spongepowered.configurate.serialize.TypeSerializer; + +public class LocaleSerializerConfigurate implements TypeSerializer { + + @Override + public Locale deserialize(final Type type, final ConfigurationNode node) throws SerializationException { + final String value = node.getString(); + + if (value == null) { + throw new SerializationException("value cannot be null!"); + } + + return Translator.parseLocale(value); + } + + @Override + public void serialize(final Type type, @Nullable final Locale obj, final ConfigurationNode node) throws SerializationException { + node.set(obj.toLanguageTag()); + } + +} diff --git a/common/src/main/java/net/draycia/carbon/common/serialisation/gson/UUIDSerializerGson.java b/common/src/main/java/net/draycia/carbon/common/serialisation/gson/UUIDSerializerGson.java new file mode 100644 index 00000000..6199d236 --- /dev/null +++ b/common/src/main/java/net/draycia/carbon/common/serialisation/gson/UUIDSerializerGson.java @@ -0,0 +1,24 @@ +package net.draycia.carbon.common.serialisation.gson; + +import com.google.gson.TypeAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; +import java.util.UUID; +import org.checkerframework.checker.nullness.qual.NonNull; +import org.checkerframework.framework.qual.DefaultQualifier; + +@DefaultQualifier(NonNull.class) +public class UUIDSerializerGson extends TypeAdapter { + + @Override + public void write(final JsonWriter jsonWriter, final UUID uuid) throws IOException { + jsonWriter.value(uuid.toString()); + } + + @Override + public UUID read(final JsonReader jsonReader) throws IOException { + return UUID.fromString(jsonReader.nextString()); + } + +} diff --git a/common/src/main/java/net/draycia/carbon/common/users/CarbonPlayerCommon.java b/common/src/main/java/net/draycia/carbon/common/users/CarbonPlayerCommon.java index 442f85d0..02237d19 100644 --- a/common/src/main/java/net/draycia/carbon/common/users/CarbonPlayerCommon.java +++ b/common/src/main/java/net/draycia/carbon/common/users/CarbonPlayerCommon.java @@ -1,8 +1,11 @@ package net.draycia.carbon.common.users; +import java.util.List; +import java.util.Locale; import java.util.UUID; import net.draycia.carbon.api.channels.ChatChannel; import net.draycia.carbon.api.users.CarbonPlayer; +import net.kyori.adventure.audience.Audience; import net.kyori.adventure.audience.ForwardingAudience; import net.kyori.adventure.identity.Identity; import net.kyori.adventure.text.Component; @@ -14,28 +17,41 @@ import static java.util.Objects.requireNonNullElseGet; import static net.kyori.adventure.text.Component.text; @DefaultQualifier(NonNull.class) -public abstract class CarbonPlayerCommon implements CarbonPlayer, ForwardingAudience.Single { +public class CarbonPlayerCommon implements CarbonPlayer, ForwardingAudience.Single { - protected final String username; protected @Nullable Component displayName; - protected final UUID uuid; - protected final Identity identity; protected @Nullable ChatChannel selectedChannel; + protected String username; + protected UUID uuid; - protected CarbonPlayerCommon( + public CarbonPlayerCommon( + final @Nullable Component displayName, + final @Nullable ChatChannel selectedChannel, final String username, - final UUID uuid, - final Identity identity + final UUID uuid ) { + this.displayName = displayName; + this.selectedChannel = selectedChannel; this.username = username; this.uuid = uuid; - this.identity = identity; - this.selectedChannel = null; + } + + public CarbonPlayerCommon() { + } @Override - public String username() { - return this.username; + public @NonNull Audience audience() { + return Audience.empty(); + } + + protected CarbonPlayer carbonPlayer() { + return this; + } + + @Override + public Component createItemHoverComponent() { + return Component.empty(); } @Override @@ -49,13 +65,28 @@ public abstract class CarbonPlayerCommon implements CarbonPlayer, ForwardingAudi } @Override - public Identity identity() { - return this.identity; + public boolean hasPermission(final String permission) { + return false; } @Override - public UUID uuid() { - return this.uuid; + public String primaryGroup() { + return "default"; // TODO: implement + } + + @Override + public List groups() { + return List.of("default"); // TODO: implement + } + + @Override + public Identity identity() { + return Identity.identity(this.uuid); + } + + @Override + public @Nullable Locale locale() { + return Locale.getDefault(); } @Override @@ -68,4 +99,14 @@ public abstract class CarbonPlayerCommon implements CarbonPlayer, ForwardingAudi this.selectedChannel = chatChannel; } + @Override + public String username() { + return this.username; + } + + @Override + public UUID uuid() { + return this.uuid; + } + } diff --git a/common/src/main/java/net/draycia/carbon/common/users/JSONUserManager.java b/common/src/main/java/net/draycia/carbon/common/users/JSONUserManager.java new file mode 100644 index 00000000..5bda0a06 --- /dev/null +++ b/common/src/main/java/net/draycia/carbon/common/users/JSONUserManager.java @@ -0,0 +1,123 @@ +package net.draycia.carbon.common.users; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.inject.Inject; +import com.google.inject.Injector; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardOpenOption; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ConcurrentHashMap; +import net.draycia.carbon.api.channels.ChatChannel; +import net.draycia.carbon.api.users.CarbonPlayer; +import net.draycia.carbon.api.users.ComponentPlayerResult; +import net.draycia.carbon.api.users.UserManager; +import net.draycia.carbon.common.ForCarbon; +import net.draycia.carbon.common.serialisation.gson.CarbonPlayerSerializerGson; +import net.draycia.carbon.common.serialisation.gson.ChatChannelSerializerGson; +import net.draycia.carbon.common.serialisation.gson.UUIDSerializerGson; +import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer; +import org.apache.logging.log4j.Logger; +import org.checkerframework.checker.nullness.qual.NonNull; +import org.checkerframework.checker.nullness.qual.Nullable; +import org.checkerframework.framework.qual.DefaultQualifier; + +import static net.kyori.adventure.text.Component.empty; +import static net.kyori.adventure.text.Component.text; + +@DefaultQualifier(NonNull.class) +public class JSONUserManager implements UserManager { + + private final Path dataDirectory; + private final Injector injector; + private final Logger logger; + private final Gson serializer; + private final Path userDirectory; + + private final Map userCache = new ConcurrentHashMap<>(); + + @Inject + public JSONUserManager( + final @ForCarbon Path dataDirectory, + final Injector injector, + final Logger logger + ) throws IOException { + this.dataDirectory = dataDirectory; + this.injector = injector; + this.logger = logger; + this.userDirectory = this.dataDirectory.resolve("users"); + + Files.createDirectories(this.userDirectory); + + this.serializer = GsonComponentSerializer.gson().populator() + .apply(new GsonBuilder()) + .registerTypeAdapter(CarbonPlayerCommon.class, this.injector.getInstance(CarbonPlayerSerializerGson.class)) + .registerTypeAdapter(ChatChannel.class, this.injector.getInstance(ChatChannelSerializerGson.class)) + .registerTypeAdapter(UUID.class, this.injector.getInstance(UUIDSerializerGson.class)) + .create(); + } + + @Override + public CompletableFuture carbonPlayer(final UUID uuid) { + return CompletableFuture.supplyAsync(() -> { + final @Nullable CarbonPlayerCommon cachedPlayer = this.userCache.get(uuid); + + if (cachedPlayer != null) { + return new ComponentPlayerResult(cachedPlayer, empty()); + } + + final Path userFile = this.userDirectory.resolve(uuid + ".json"); + + if (Files.exists(userFile)) { + try { + final CarbonPlayerCommon player = + this.serializer.fromJson(Files.newBufferedReader(userFile), CarbonPlayerCommon.class); + + this.userCache.put(uuid, player); + + // TODO: supply reason if fromJson returns null + return new ComponentPlayerResult(player, empty()); + } catch (final IOException exception) { + return new ComponentPlayerResult(null, text(exception.getMessage())); + } + } + + return new ComponentPlayerResult(null, text("No save file found for player.")); + }); + } + + @Override + public CompletableFuture savePlayer(final CarbonPlayer player) { + return CompletableFuture.supplyAsync(() -> { + this.logger.info("Saving player data for [{}], [{}]", player.username(), player.uuid()); + final Path userFile = this.userDirectory.resolve(player.uuid() + ".json"); + + try { + if (!Files.exists(userFile)) { + Files.createFile(userFile); + } + + try { + final String json = this.serializer.toJson(player, CarbonPlayerCommon.class); + + Files.writeString(userFile, json, + StandardOpenOption.WRITE, + StandardOpenOption.TRUNCATE_EXISTING); + } catch (final ClassCastException exception) { + exception.printStackTrace(); + } + + return new ComponentPlayerResult(player, text(String.format("Saving player data for [%s], [%s]", + player.username(), player.uuid()))); + } catch (final IOException exception) { + exception.printStackTrace(); + return new ComponentPlayerResult(null, text(exception.getMessage())); + } + }); + } + +} diff --git a/common/src/main/resources/locale/messages-en_US.properties b/common/src/main/resources/locale/messages-en_US.properties index cf65b6fe..c7708bc1 100644 --- a/common/src/main/resources/locale/messages-en_US.properties +++ b/common/src/main/resources/locale/messages-en_US.properties @@ -2,5 +2,5 @@ example.command.hello=Hello from ! unsupported.legacy=Legacy color codes have been detected in a message. This is not supported behavior. Message: '' placeholders.plugin=<#1DA3A6>Carbon test.phrase=English: Has anyone really been far even as decided to use even go want to do look more like? -channel.format.basic=\: +channel.format.basic=\ue238\: diff --git a/common/src/main/resources/locale/messages-nb_NO.properties b/common/src/main/resources/locale/messages-nb_NO.properties index 7d8469e0..4f81ba4f 100644 --- a/common/src/main/resources/locale/messages-nb_NO.properties +++ b/common/src/main/resources/locale/messages-nb_NO.properties @@ -2,4 +2,4 @@ example.command.hello=Hello from \! unsupported.legacy=Legacy color codes have been detected in a message. This is not supported behavior. Message\: '' placeholders.plugin=<\#1DA3A6>Carbon test.phrase=bokmål: I noen tilfeller skulle man gjerne sett for seg at kongen bryr seg om sitt folk. Etter festen i '97, har dette blitt klart at er helt rett: han brakte med seg flere soldater og sammen giljotinerte de alle deltakere under atten år. -channel.format.basic=\: +channel.format.basic=\ue238\: diff --git a/common/src/main/resources/locale/messages-nn_NO.properties b/common/src/main/resources/locale/messages-nn_NO.properties index 90b0760a..2d3b1a4a 100644 --- a/common/src/main/resources/locale/messages-nn_NO.properties +++ b/common/src/main/resources/locale/messages-nn_NO.properties @@ -2,4 +2,4 @@ example.command.hello=Hello from \! unsupported.legacy=Legacy color codes have been detected in a message. This is not supported behavior. Message\: '' placeholders.plugin=<\#1DA3A6>Carbon test.phrase=Nynorsk: Alle menneske er fødde til fridom og med same menneskeverd og menneskerettar. Dei har fått fornuft og samvit og skal leve med kvarandre som brør. -channel.format.basic=\: +channel.format.basic=\ue238\: diff --git a/gradle/libs.versions.yml b/gradle/libs.versions.yml index 9a3ac26e..57abd2f6 100644 --- a/gradle/libs.versions.yml +++ b/gradle/libs.versions.yml @@ -105,6 +105,10 @@ dependencies: group: org.spongepowered name: configurate-core version: { ref: configurate } + configurateGuice: + group: org.spongepowered + name: configurate-extra-guice + version: { ref: configurate } configurateHocon: group: org.spongepowered name: configurate-hocon diff --git a/sponge/build.gradle.kts b/sponge/build.gradle.kts index fe69e195..5c1d1384 100644 --- a/sponge/build.gradle.kts +++ b/sponge/build.gradle.kts @@ -31,7 +31,7 @@ sponge { plugin(rootProject.name.toLowerCase(Locale.ROOT)) { loader(PluginLoaders.JAVA_PLAIN) displayName(rootProject.name) - mainClass("net.draycia.carbon.sponge.CarbonChatSpongeEntry") + mainClass("net.draycia.carbon.sponge.CarbonChatSponge") description(project.description) links { homepage(GITHUB_REPO_URL) diff --git a/sponge/src/main/java/net/draycia/carbon/sponge/CarbonChatSponge.java b/sponge/src/main/java/net/draycia/carbon/sponge/CarbonChatSponge.java index e55b13ad..a08243bd 100644 --- a/sponge/src/main/java/net/draycia/carbon/sponge/CarbonChatSponge.java +++ b/sponge/src/main/java/net/draycia/carbon/sponge/CarbonChatSponge.java @@ -4,48 +4,110 @@ import cloud.commandframework.CommandManager; import cloud.commandframework.execution.AsynchronousCommandExecutionCoordinator; import cloud.commandframework.sponge.SpongeCommandManager; import com.google.inject.Inject; -import com.google.inject.Singleton; +import com.google.inject.Injector; import java.nio.file.Path; -import net.draycia.carbon.api.CarbonServer; +import java.util.Set; +import java.util.concurrent.TimeUnit; +import net.draycia.carbon.api.CarbonChatProvider; +import net.draycia.carbon.api.channels.ChannelRegistry; import net.draycia.carbon.api.users.UserManager; import net.draycia.carbon.common.CarbonChatCommon; -import net.draycia.carbon.common.ForCarbon; +import net.draycia.carbon.common.channels.CarbonChannelRegistry; import net.draycia.carbon.common.command.Commander; import net.draycia.carbon.common.messages.CarbonMessageService; import net.draycia.carbon.sponge.command.SpongeCommander; import net.draycia.carbon.sponge.command.SpongePlayerCommander; +import net.draycia.carbon.sponge.listeners.SpongeChatListener; import org.apache.logging.log4j.Logger; import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.framework.qual.DefaultQualifier; +import org.spongepowered.api.Game; +import org.spongepowered.api.Server; +import org.spongepowered.api.Sponge; +import org.spongepowered.api.config.ConfigDir; import org.spongepowered.api.entity.living.player.server.ServerPlayer; +import org.spongepowered.api.event.Listener; +import org.spongepowered.api.event.lifecycle.StartingEngineEvent; +import org.spongepowered.api.event.lifecycle.StoppingEngineEvent; +import org.spongepowered.api.scheduler.Task; import org.spongepowered.plugin.PluginContainer; +import org.spongepowered.plugin.jvm.Plugin; -// TODO: this class should die +@Plugin("carbonchat") @DefaultQualifier(NonNull.class) -@Singleton public final class CarbonChatSponge extends CarbonChatCommon { - private final UserManager userManager; - private final Logger logger; + private static final Set> LISTENER_CLASSES = Set.of( + SpongeChatListener.class + ); + private static final int BSTATS_PLUGIN_ID = 11279; + + private final CarbonMessageService messageService; private final CarbonServerSponge carbonServerSponge; + private final ChannelRegistry channelRegistry; + private final Game game; + private final Injector injector; + private final Logger logger; private final Path dataDirectory; private final PluginContainer pluginContainer; + private final UserManager userManager; @Inject - private CarbonChatSponge( + public CarbonChatSponge( + //final Metrics.Factory metricsFactory, + final Game game, final PluginContainer pluginContainer, + final Injector injector, final Logger logger, - final @ForCarbon Path dataDirectory, - final CarbonServerSponge carbonServerSponge, - final UserManager userManager, - final CarbonMessageService messageService + @ConfigDir(sharedRoot = false) final Path dataDirectory ) { - super(messageService); - this.userManager = userManager; - this.logger = logger; - this.carbonServerSponge = carbonServerSponge; - this.dataDirectory = dataDirectory; + CarbonChatProvider.register(this); + + this.game = game; this.pluginContainer = pluginContainer; + + this.injector = injector.createChildInjector(new CarbonChatSpongeModule( + this, dataDirectory)); + + this.logger = logger; + this.messageService = this.injector.getInstance(CarbonMessageService.class); + this.channelRegistry = this.injector.getInstance(ChannelRegistry.class); + this.carbonServerSponge = this.injector.getInstance(CarbonServerSponge.class); + this.userManager = this.injector.getInstance(UserManager.class); + this.dataDirectory = dataDirectory; + + for (final Class clazz : LISTENER_CLASSES) { + this.game.eventManager().registerListeners(this.pluginContainer, this.injector.getInstance(clazz)); + } + //metricsFactory.make(BSTATS_PLUGIN_ID); + + this.initialize(); + } + + @Listener + public void onInitialize(final StartingEngineEvent event) { + Sponge.asyncScheduler().submit(Task.builder() + .interval(5, TimeUnit.MINUTES) + .plugin(this.pluginContainer) + .execute(this::savePlayers) + .build()); + + ((CarbonChannelRegistry) this.channelRegistry()).loadChannels(); + } + + @Listener + public void onDisable(final StoppingEngineEvent event) { + this.savePlayers(); + } + + private void savePlayers() { + for (final var player : this.server().players()) { + this.userManager().savePlayer(player.carbonPlayer()).thenAccept(result -> { + if (result.player() == null) { + this.server().console().sendMessage(result.reason()); + } + }); + } } public UserManager userManager() { @@ -63,10 +125,20 @@ public final class CarbonChatSponge extends CarbonChatCommon { } @Override - public CarbonServer server() { + public CarbonServerSponge server() { return this.carbonServerSponge; } + @Override + public ChannelRegistry channelRegistry() { + return this.channelRegistry; + } + + @Override + public CarbonMessageService messageService() { + return this.messageService; + } + @Override protected CommandManager createCommandManager() { final SpongeCommandManager commandManager = new SpongeCommandManager<>( diff --git a/sponge/src/main/java/net/draycia/carbon/sponge/CarbonChatSpongeEntry.java b/sponge/src/main/java/net/draycia/carbon/sponge/CarbonChatSpongeEntry.java deleted file mode 100644 index 917216fc..00000000 --- a/sponge/src/main/java/net/draycia/carbon/sponge/CarbonChatSpongeEntry.java +++ /dev/null @@ -1,57 +0,0 @@ -package net.draycia.carbon.sponge; - -import com.google.inject.Inject; -import com.google.inject.Injector; -import java.util.Set; -import net.draycia.carbon.sponge.listeners.SpongeChatListener; -import org.checkerframework.checker.nullness.qual.MonotonicNonNull; -import org.checkerframework.checker.nullness.qual.NonNull; -import org.checkerframework.framework.qual.DefaultQualifier; -import org.spongepowered.api.Game; -import org.spongepowered.api.Server; -import org.spongepowered.api.event.Listener; -import org.spongepowered.api.event.lifecycle.StartingEngineEvent; -import org.spongepowered.plugin.PluginContainer; -import org.spongepowered.plugin.jvm.Plugin; - -@Plugin("carbonchat") -@DefaultQualifier(NonNull.class) -public final class CarbonChatSpongeEntry { - - private static final Set> LISTENER_CLASSES = Set.of( - SpongeChatListener.class - ); - private static final int BSTATS_PLUGIN_ID = 11279; - - private final @MonotonicNonNull CarbonChatSponge carbon; - private final Game game; - private final Injector injector; - - private final PluginContainer pluginContainer; - - @Inject - public CarbonChatSpongeEntry( - //final Metrics.Factory metricsFactory, - final Game game, - final PluginContainer pluginContainer, - final Injector injector - ) { - this.game = game; - this.pluginContainer = pluginContainer; - - this.injector = injector.createChildInjector(injector.getInstance(CarbonChatSpongeModule.class)); - this.carbon = this.injector.getInstance(CarbonChatSponge.class); - - for (final Class clazz : LISTENER_CLASSES) { - this.game.eventManager().registerListeners(this.pluginContainer, this.injector.getInstance(clazz)); - } - //metricsFactory.make(BSTATS_PLUGIN_ID); - - this.carbon.initialize(); - } - - @Listener - public void onInitialize(final StartingEngineEvent event) { - } - -} diff --git a/sponge/src/main/java/net/draycia/carbon/sponge/CarbonChatSpongeModule.java b/sponge/src/main/java/net/draycia/carbon/sponge/CarbonChatSpongeModule.java index a88b4f34..20761a54 100644 --- a/sponge/src/main/java/net/draycia/carbon/sponge/CarbonChatSpongeModule.java +++ b/sponge/src/main/java/net/draycia/carbon/sponge/CarbonChatSpongeModule.java @@ -1,31 +1,25 @@ package net.draycia.carbon.sponge; import com.google.inject.AbstractModule; -import com.google.inject.Inject; import java.nio.file.Path; import net.draycia.carbon.api.CarbonChat; import net.draycia.carbon.api.CarbonServer; -import net.draycia.carbon.api.users.UserManager; import net.draycia.carbon.common.CarbonCommonModule; import net.draycia.carbon.common.ForCarbon; -import net.draycia.carbon.sponge.users.MemoryUserManagerSponge; import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.framework.qual.DefaultQualifier; -import org.spongepowered.api.config.ConfigDir; -import org.spongepowered.plugin.PluginContainer; @DefaultQualifier(NonNull.class) public final class CarbonChatSpongeModule extends AbstractModule { - private final PluginContainer pluginContainer; + private final CarbonChatSponge carbonChatSponge; private final Path configDir; - @Inject - private CarbonChatSpongeModule( - final PluginContainer pluginContainer, - @ConfigDir(sharedRoot = false) final Path configDir + public CarbonChatSpongeModule( + final CarbonChatSponge carbonChatSponge, + final Path configDir ) { - this.pluginContainer = pluginContainer; + this.carbonChatSponge = carbonChatSponge; this.configDir = configDir; } @@ -34,10 +28,8 @@ public final class CarbonChatSpongeModule extends AbstractModule { this.install(new CarbonCommonModule()); this.bind(Path.class).annotatedWith(ForCarbon.class).toInstance(this.configDir); - this.bind(CarbonChat.class).to(CarbonChatSponge.class); - this.bind(CarbonChatSponge.class); + this.bind(CarbonChat.class).toInstance(this.carbonChatSponge); this.bind(CarbonServer.class).to(CarbonServerSponge.class); - this.bind(UserManager.class).to(MemoryUserManagerSponge.class); } } diff --git a/sponge/src/main/java/net/draycia/carbon/sponge/CarbonServerSponge.java b/sponge/src/main/java/net/draycia/carbon/sponge/CarbonServerSponge.java index b67f89ec..6abe8c97 100644 --- a/sponge/src/main/java/net/draycia/carbon/sponge/CarbonServerSponge.java +++ b/sponge/src/main/java/net/draycia/carbon/sponge/CarbonServerSponge.java @@ -4,17 +4,23 @@ import com.google.inject.Inject; import com.google.inject.Singleton; import java.util.ArrayList; import java.util.UUID; +import java.util.concurrent.CompletableFuture; import net.draycia.carbon.api.CarbonServer; -import net.draycia.carbon.api.users.CarbonPlayer; +import net.draycia.carbon.api.users.ComponentPlayerResult; import net.draycia.carbon.api.users.UserManager; +import net.draycia.carbon.common.users.CarbonPlayerCommon; +import net.draycia.carbon.sponge.users.CarbonPlayerSponge; import net.kyori.adventure.audience.Audience; import net.kyori.adventure.audience.ForwardingAudience; +import net.kyori.adventure.text.Component; import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.Nullable; import org.checkerframework.framework.qual.DefaultQualifier; import org.spongepowered.api.Game; import org.spongepowered.api.Sponge; -import org.spongepowered.api.entity.living.player.Player; +import org.spongepowered.api.entity.living.player.server.ServerPlayer; + +import static net.kyori.adventure.text.Component.text; @Singleton @DefaultQualifier(NonNull.class) @@ -25,47 +31,91 @@ public final class CarbonServerSponge implements CarbonServer, ForwardingAudienc @Inject private CarbonServerSponge(final UserManager userManager, final Game game) { - this.userManager = userManager; this.game = game; + this.userManager = userManager; } @Override public Audience audience() { - return Audience.audience(this.console(), Audience.audience(this.players())); + return this.game.server(); } @Override public Audience console() { - return Sponge.systemSubject(); + return this.game.systemSubject(); } @Override - public Iterable players() { - final var players = new ArrayList(); + public Iterable players() { + final var players = new ArrayList(); - for (final var player : this.game.server().onlinePlayers()) { - final @Nullable CarbonPlayer carbonPlayer = this.player(player); + for (final var player : Sponge.server().onlinePlayers()) { + final ComponentPlayerResult result = this.player(player).join(); - if (carbonPlayer != null) { - players.add(carbonPlayer); + if (result.player() != null) { + players.add((CarbonPlayerSponge) result.player()); } } return players; } - @Override - public @Nullable CarbonPlayer player(final UUID uuid) { - return this.userManager.carbonPlayer(uuid); + private CompletableFuture wrapPlayer(final UUID uuid) { + return this.userManager.carbonPlayer(uuid).thenCompose(result -> { + return CompletableFuture.supplyAsync(() -> { + if (result.player() != null) { + new ComponentPlayerResult(new CarbonPlayerSponge(result.player()), Component.empty()); + } + + final @Nullable String name = this.resolveName(uuid).join(); + + if (name != null) { + final CarbonPlayerCommon player = new CarbonPlayerCommon(null, + null, name, uuid); + + return new ComponentPlayerResult(new CarbonPlayerSponge(player), Component.empty()); + } + + return new ComponentPlayerResult(null, text("Name not found for uuid!")); + }); + }); } @Override - public @Nullable CarbonPlayer player(final String username) { - return this.userManager.carbonPlayer(username); + public CompletableFuture player(final UUID uuid) { + return this.wrapPlayer(uuid); } - private @Nullable CarbonPlayer player(final Player player) { + @Override + public CompletableFuture player(final String username) { + return CompletableFuture.supplyAsync(() -> { + final @Nullable UUID uuid = this.resolveUUID(username).join(); + + if (uuid != null) { + return this.player(uuid).join(); + } + + return new ComponentPlayerResult(null, text("No UUID found for name.")); + }); + } + + public CompletableFuture player(final ServerPlayer player) { return this.player(player.uniqueId()); } + @Override + public CompletableFuture<@Nullable UUID> resolveUUID(final String username) { + // TODO: user cache? + return CompletableFuture.supplyAsync(() -> + Sponge.server().gameProfileManager().basicProfile(username).join().uuid() + ); + } + + @Override + public CompletableFuture<@Nullable String> resolveName(final UUID uuid) { + return CompletableFuture.supplyAsync(() -> + Sponge.server().gameProfileManager().basicProfile(uuid).join().name().get() + ); + } + } diff --git a/sponge/src/main/java/net/draycia/carbon/sponge/command/SpongePlayerCommander.java b/sponge/src/main/java/net/draycia/carbon/sponge/command/SpongePlayerCommander.java index c386686d..730c0deb 100644 --- a/sponge/src/main/java/net/draycia/carbon/sponge/command/SpongePlayerCommander.java +++ b/sponge/src/main/java/net/draycia/carbon/sponge/command/SpongePlayerCommander.java @@ -18,7 +18,7 @@ public record SpongePlayerCommander( @Override public @NonNull CarbonPlayer carbonPlayer() { - return requireNonNull(this.carbon.server().player(this.player.uniqueId()), "No CarbonPlayer for logged in Player!"); + return requireNonNull(this.carbon.server().player(this.player.uniqueId()).join().player(), "No CarbonPlayer for logged in Player!"); } @Override diff --git a/sponge/src/main/java/net/draycia/carbon/sponge/listeners/SpongeChatListener.java b/sponge/src/main/java/net/draycia/carbon/sponge/listeners/SpongeChatListener.java index 1ddd3afb..fed43a96 100644 --- a/sponge/src/main/java/net/draycia/carbon/sponge/listeners/SpongeChatListener.java +++ b/sponge/src/main/java/net/draycia/carbon/sponge/listeners/SpongeChatListener.java @@ -3,14 +3,17 @@ package net.draycia.carbon.sponge.listeners; import com.google.inject.Inject; import java.util.ArrayList; import java.util.Optional; +import net.draycia.carbon.api.CarbonChat; +import net.draycia.carbon.api.channels.ChannelRegistry; import net.draycia.carbon.api.events.CarbonChatEvent; +import net.draycia.carbon.api.users.ComponentPlayerResult; import net.draycia.carbon.api.util.KeyedRenderer; -import net.draycia.carbon.common.channels.BasicChatChannel; import net.draycia.carbon.sponge.CarbonChatSponge; import net.kyori.adventure.audience.Audience; import net.kyori.adventure.text.Component; import org.checkerframework.checker.nullness.qual.NonNull; import org.spongepowered.api.entity.living.player.Player; +import org.spongepowered.api.entity.living.player.server.ServerPlayer; import org.spongepowered.api.event.Listener; import org.spongepowered.api.event.filter.cause.First; import org.spongepowered.api.event.message.PlayerChatEvent; @@ -23,43 +26,45 @@ import static net.kyori.adventure.text.Component.empty; public final class SpongeChatListener { private final CarbonChatSponge carbonChat; - private final BasicChatChannel basicChat; + private final ChannelRegistry registry; @Inject private SpongeChatListener( - final CarbonChatSponge carbonChat, - final BasicChatChannel basicChat + final CarbonChat carbonChat, + final ChannelRegistry registry ) { - this.carbonChat = carbonChat; - this.basicChat = basicChat; + this.carbonChat = (CarbonChatSponge) carbonChat; + this.registry = registry; } @Listener public void onPlayerChat(final @NonNull PlayerChatEvent event, final @First Player source) { - final var sender = this.carbonChat.server().player(source.uniqueId()); + final var playerResult = this.carbonChat.server().player(source.uniqueId()).join(); - if (sender == null) { + if (playerResult.player() == null) { + this.carbonChat.server().console().sendMessage(playerResult.reason()); return; } - final var channel = requireNonNullElse(sender.selectedChannel(), this.basicChat); + final var channel = requireNonNullElse(playerResult.player().selectedChannel(), + this.registry.defaultValue()); // TODO: option to specify if the channel should invoke ChatChannel#recipients // or ChatChannel#filterRecipients // for now we will just always invoke ChatChannel#recipients - final var recipients = channel.recipients(sender); + final var recipients = channel.recipients(playerResult.player()); final var renderers = new ArrayList(); renderers.add(keyedRenderer(key("carbon", "default"), channel)); - final var chatEvent = new CarbonChatEvent(sender, event.message(), recipients, renderers); - final var result = this.carbonChat.eventHandler().emit(chatEvent); + final var chatEvent = new CarbonChatEvent(playerResult.player(), event.message(), recipients, renderers); + final var eventResult = this.carbonChat.eventHandler().emit(chatEvent); - if (!result.wasSuccessful()) { + if (!eventResult.wasSuccessful()) { final var message = chatEvent.result().reason(); if (!message.equals(empty())) { - sender.sendMessage(message); + playerResult.player().sendMessage(message); } return; @@ -67,7 +72,8 @@ public final class SpongeChatListener { try { event.setAudience(Audience.audience(chatEvent.recipients())); - } catch (final UnsupportedOperationException ignored) { + } catch (final UnsupportedOperationException exception) { + exception.printStackTrace(); // Do we log something here? Would get spammy fast. } @@ -75,7 +81,12 @@ public final class SpongeChatListener { Component component = message; for (final var renderer : chatEvent.renderers()) { - component = renderer.render(sender, target, component, message); + if (target instanceof ServerPlayer serverPlayer) { + final ComponentPlayerResult targetPlayer = this.carbonChat.server().player(serverPlayer).join(); + component = renderer.render(playerResult.player(), targetPlayer.player(), component, message); + } else { + component = renderer.render(playerResult.player(), target, component, message); + } } if (component == Component.empty()) { diff --git a/sponge/src/main/java/net/draycia/carbon/sponge/users/CarbonPlayerSponge.java b/sponge/src/main/java/net/draycia/carbon/sponge/users/CarbonPlayerSponge.java index 88d34db5..4f7e4379 100644 --- a/sponge/src/main/java/net/draycia/carbon/sponge/users/CarbonPlayerSponge.java +++ b/sponge/src/main/java/net/draycia/carbon/sponge/users/CarbonPlayerSponge.java @@ -1,10 +1,13 @@ package net.draycia.carbon.sponge.users; +import java.util.List; import java.util.Locale; import java.util.Optional; import java.util.UUID; -import net.draycia.carbon.common.users.CarbonPlayerCommon; +import net.draycia.carbon.api.channels.ChatChannel; +import net.draycia.carbon.api.users.CarbonPlayer; import net.kyori.adventure.audience.Audience; +import net.kyori.adventure.audience.ForwardingAudience; import net.kyori.adventure.identity.Identity; import net.kyori.adventure.text.Component; import org.checkerframework.checker.nullness.qual.NonNull; @@ -21,18 +24,38 @@ import static net.kyori.adventure.text.Component.translatable; import static net.kyori.adventure.text.format.TextDecoration.ITALIC; @DefaultQualifier(NonNull.class) -public final class CarbonPlayerSponge extends CarbonPlayerCommon { +public final class CarbonPlayerSponge implements CarbonPlayer, ForwardingAudience.Single { - public CarbonPlayerSponge( - final @NonNull String username, - final @NonNull UUID uuid - ) { - super(username, uuid, Identity.identity(uuid)); + private final CarbonPlayer carbonPlayer; + + public CarbonPlayerSponge(final CarbonPlayer carbonPlayer) { + this.carbonPlayer = carbonPlayer; + } + + public CarbonPlayer carbonPlayer() { + return this.carbonPlayer; + } + + @Override + public @NonNull Audience audience() { + return this.player() + .map(player -> (Audience) player) + .orElseGet(Audience::empty); + } + + @Override + public String username() { + return this.carbonPlayer.username(); + } + + @Override + public Component displayName() { + return this.carbonPlayer.displayName(); } @Override public void displayName(final @Nullable Component displayName) { - super.displayName(displayName); + this.carbonPlayer.displayName(displayName); this.player().ifPresent(player -> { if (displayName != null) { @@ -44,21 +67,12 @@ public final class CarbonPlayerSponge extends CarbonPlayerCommon { } @Override - public @NonNull Audience audience() { - return this.player() - .map(player -> (Audience) player) - .orElseGet(Audience::empty); + public UUID uuid() { + return this.carbonPlayer.uuid(); } private @NonNull Optional player() { - return Sponge.server().player(this.uuid); - } - - @Override - public @Nullable Locale locale() { - return this.player() - .map(LocaleSource::locale) - .orElse(null); + return Sponge.server().player(this.carbonPlayer.uuid()); } @Override @@ -99,11 +113,40 @@ public final class CarbonPlayerSponge extends CarbonPlayerCommon { final var player = this.player(); // Ignore inspection. Don't make code harder to read, IntelliJ. - if (player.isPresent()) { - return player.get().hasPermission(permission); - } + return player.map(serverPlayer -> serverPlayer.hasPermission(permission)) + .orElse(false); + } - return false; + @Override + public String primaryGroup() { + return "default"; // TODO: implement + } + + @Override + public List groups() { + return List.of("default"); // TODO: implement + } + + @Override + public @Nullable Locale locale() { + return this.player() + .map(LocaleSource::locale) + .orElse(null); + } + + @Override + public @Nullable ChatChannel selectedChannel() { + return this.carbonPlayer.selectedChannel(); + } + + @Override + public void selectedChannel(final ChatChannel chatChannel) { + this.carbonPlayer.selectedChannel(chatChannel); + } + + @Override + public @NonNull Identity identity() { + return this.carbonPlayer.identity(); } } diff --git a/sponge/src/main/java/net/draycia/carbon/sponge/users/MemoryUserManagerSponge.java b/sponge/src/main/java/net/draycia/carbon/sponge/users/MemoryUserManagerSponge.java deleted file mode 100644 index 2cb676c8..00000000 --- a/sponge/src/main/java/net/draycia/carbon/sponge/users/MemoryUserManagerSponge.java +++ /dev/null @@ -1,54 +0,0 @@ -package net.draycia.carbon.sponge.users; - -import com.google.inject.Singleton; -import java.util.HashMap; -import java.util.Map; -import java.util.Optional; -import java.util.UUID; -import net.draycia.carbon.api.users.CarbonPlayer; -import net.draycia.carbon.api.users.UserManager; -import org.checkerframework.checker.nullness.qual.NonNull; -import org.checkerframework.checker.nullness.qual.Nullable; -import org.spongepowered.api.Sponge; -import org.spongepowered.api.entity.living.player.server.ServerPlayer; - -/** - * This class should not be used. - * No data is persisted or saved. - * This exists merely as a placeholder. - */ -@Singleton -public final class MemoryUserManagerSponge implements UserManager { - - private final @NonNull Map users = new HashMap<>(); - - @Override - public @Nullable CarbonPlayer carbonPlayer(final @NonNull UUID uuid) { - if (this.users.containsKey(uuid)) { - return this.users.get(uuid); - } - - final Optional serverPlayer = Sponge.server().player(uuid); - - if (serverPlayer.isEmpty()) { - return null; - } - - final ServerPlayer player = serverPlayer.get(); - - return this.users.computeIfAbsent(player.uniqueId(), key -> - new CarbonPlayerSponge(player.name(), player.uniqueId())); - } - - @Override - public @Nullable CarbonPlayer carbonPlayer(final @NonNull String username) { - final Optional player = Sponge.server().player(username); - - if (player.isEmpty()) { - return null; - } - - return this.carbonPlayer(player.get().uniqueId()); - } - -} diff --git a/velocity/src/main/java/net/draycia/carbon/velocity/CarbonChatVelocity.java b/velocity/src/main/java/net/draycia/carbon/velocity/CarbonChatVelocity.java index 161acb0e..8e6c776a 100644 --- a/velocity/src/main/java/net/draycia/carbon/velocity/CarbonChatVelocity.java +++ b/velocity/src/main/java/net/draycia/carbon/velocity/CarbonChatVelocity.java @@ -4,45 +4,94 @@ import cloud.commandframework.CommandManager; import cloud.commandframework.execution.AsynchronousCommandExecutionCoordinator; import cloud.commandframework.velocity.VelocityCommandManager; import com.google.inject.Inject; +import com.google.inject.Injector; +import com.velocitypowered.api.event.Subscribe; +import com.velocitypowered.api.event.proxy.ProxyInitializeEvent; +import com.velocitypowered.api.plugin.Plugin; import com.velocitypowered.api.plugin.PluginContainer; +import com.velocitypowered.api.plugin.annotation.DataDirectory; import com.velocitypowered.api.proxy.Player; import com.velocitypowered.api.proxy.ProxyServer; +import java.net.URISyntaxException; import java.nio.file.Path; -import net.draycia.carbon.api.CarbonServer; +import java.util.Set; +import net.draycia.carbon.api.CarbonChatProvider; +import net.draycia.carbon.api.channels.ChannelRegistry; import net.draycia.carbon.common.CarbonChatCommon; -import net.draycia.carbon.common.ForCarbon; +import net.draycia.carbon.common.channels.CarbonChannelRegistry; import net.draycia.carbon.common.command.Commander; import net.draycia.carbon.common.messages.CarbonMessageService; import net.draycia.carbon.velocity.command.VelocityCommander; import net.draycia.carbon.velocity.command.VelocityPlayerCommander; +import net.draycia.carbon.velocity.listeners.VelocityChatListener; +import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.framework.qual.DefaultQualifier; +@Plugin( + id = "$[ID]", + name = "$[NAME]", + version = "$[VERSION]", + description = "$[DESCRIPTION]", + url = "$[URL]", + authors = {"Draycia"} +) @DefaultQualifier(NonNull.class) public class CarbonChatVelocity extends CarbonChatCommon { - private final Logger logger; - private final CarbonServer server; + private static final Set> LISTENER_CLASSES = Set.of( + VelocityChatListener.class + ); + private final Path dataDirectory; - private final PluginContainer pluginContainer; private final ProxyServer proxyServer; + private final PluginContainer pluginContainer; + private final Logger logger; + private final Injector injector; + + private final CarbonMessageService messageService; + private final ChannelRegistry channelRegistry; + private final CarbonServerVelocity carbonServer; @Inject public CarbonChatVelocity( - final Logger logger, - final CarbonServer server, - @ForCarbon final Path dataDirectory, - final CarbonMessageService messageService, + @DataDirectory final Path dataDirectory, + final ProxyServer proxyServer, final PluginContainer pluginContainer, - final ProxyServer proxyServer + final Injector injector ) { - super(messageService); - this.logger = logger; - this.server = server; + CarbonChatProvider.register(this); + this.dataDirectory = dataDirectory; - this.pluginContainer = pluginContainer; this.proxyServer = proxyServer; + this.pluginContainer = pluginContainer; + this.logger = LogManager.getLogger(this.pluginContainer.getDescription().getId()); + + final CarbonChatVelocityModule carbonVelocityModule; + + try { + carbonVelocityModule = new CarbonChatVelocityModule(this.logger, this.dataDirectory); + } catch (final URISyntaxException ex) { + throw new RuntimeException(ex); + } + + this.injector = injector.createChildInjector(carbonVelocityModule); + + this.messageService = injector.getInstance(CarbonMessageService.class); + this.channelRegistry = injector.getInstance(ChannelRegistry.class); + this.carbonServer = injector.getInstance(CarbonServerVelocity.class); + } + + @Subscribe + public void onProxyInitialization(final ProxyInitializeEvent event) { + super.initialize(); + + for (final Class clazz : LISTENER_CLASSES) { + this.proxyServer.getEventManager().register(this, this.injector.getInstance(clazz)); + } + + ((CarbonChannelRegistry) this.channelRegistry()).loadChannels(); } @Override @@ -56,8 +105,18 @@ public class CarbonChatVelocity extends CarbonChatCommon { } @Override - public CarbonServer server() { - return this.server; + public CarbonServerVelocity server() { + return this.carbonServer; + } + + @Override + public ChannelRegistry channelRegistry() { + return this.channelRegistry; + } + + @Override + public CarbonMessageService messageService() { + return this.messageService; } @Override diff --git a/velocity/src/main/java/net/draycia/carbon/velocity/CarbonChatVelocityEntry.java b/velocity/src/main/java/net/draycia/carbon/velocity/CarbonChatVelocityEntry.java deleted file mode 100644 index 2c85fac1..00000000 --- a/velocity/src/main/java/net/draycia/carbon/velocity/CarbonChatVelocityEntry.java +++ /dev/null @@ -1,73 +0,0 @@ -package net.draycia.carbon.velocity; - -import com.google.inject.Inject; -import com.google.inject.Injector; -import com.velocitypowered.api.event.Subscribe; -import com.velocitypowered.api.event.proxy.ProxyInitializeEvent; -import com.velocitypowered.api.plugin.Plugin; -import com.velocitypowered.api.plugin.PluginContainer; -import com.velocitypowered.api.plugin.annotation.DataDirectory; -import com.velocitypowered.api.proxy.ProxyServer; -import java.net.URISyntaxException; -import java.nio.file.Path; -import java.util.Set; -import net.draycia.carbon.velocity.listeners.VelocityChatListener; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.checkerframework.checker.nullness.qual.NonNull; -import org.checkerframework.framework.qual.DefaultQualifier; - -@Plugin( - id = "$[ID]", - name = "$[NAME]", - version = "$[VERSION]", - description = "$[DESCRIPTION]", - url = "$[URL]", - authors = {"Draycia"} -) -@DefaultQualifier(NonNull.class) -public class CarbonChatVelocityEntry { - - private static final Set> LISTENER_CLASSES = Set.of( - VelocityChatListener.class - ); - - private final Path dataDirectory; - private final ProxyServer server; - private final PluginContainer pluginContainer; - private final CarbonChatVelocity carbon; - private final Injector injector; - private final Logger logger; - - @Inject - public CarbonChatVelocityEntry( - @DataDirectory final Path dataDirectory, - final ProxyServer server, - final PluginContainer pluginContainer, - final Injector injector - ) { - this.dataDirectory = dataDirectory; - this.server = server; - this.pluginContainer = pluginContainer; - this.logger = LogManager.getLogger(this.pluginContainer.getDescription().getId()); - - final CarbonChatVelocityModule carbonVelocityModule; - try { - carbonVelocityModule = new CarbonChatVelocityModule(this.logger, this.dataDirectory); - } catch (final URISyntaxException ex) { - throw new RuntimeException(ex); - } - this.injector = injector.createChildInjector(carbonVelocityModule); - - this.carbon = this.injector.getInstance(CarbonChatVelocity.class); - } - - @Subscribe - public void onProxyInitialization(final ProxyInitializeEvent event) { - this.carbon.initialize(); - for (final Class clazz : LISTENER_CLASSES) { - this.server.getEventManager().register(this, this.injector.getInstance(clazz)); - } - } - -} diff --git a/velocity/src/main/java/net/draycia/carbon/velocity/CarbonChatVelocityModule.java b/velocity/src/main/java/net/draycia/carbon/velocity/CarbonChatVelocityModule.java index 815bfa42..3275f54a 100644 --- a/velocity/src/main/java/net/draycia/carbon/velocity/CarbonChatVelocityModule.java +++ b/velocity/src/main/java/net/draycia/carbon/velocity/CarbonChatVelocityModule.java @@ -3,14 +3,10 @@ package net.draycia.carbon.velocity; import com.google.inject.AbstractModule; import java.net.URISyntaxException; import java.nio.file.Path; -import java.nio.file.Paths; import net.draycia.carbon.api.CarbonChat; import net.draycia.carbon.api.CarbonServer; -import net.draycia.carbon.api.users.UserManager; import net.draycia.carbon.common.CarbonCommonModule; -import net.draycia.carbon.common.CarbonJar; import net.draycia.carbon.common.ForCarbon; -import net.draycia.carbon.velocity.users.MemoryUserManagerVelocity; import org.apache.logging.log4j.Logger; import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.framework.qual.DefaultQualifier; @@ -20,7 +16,6 @@ public final class CarbonChatVelocityModule extends AbstractModule { private final Logger logger; private final Path dataDirectory; - private final Path pluginJar; CarbonChatVelocityModule( final Logger logger, @@ -28,8 +23,6 @@ public final class CarbonChatVelocityModule extends AbstractModule { ) throws URISyntaxException { this.logger = logger; this.dataDirectory = dataDirectory; - this.pluginJar = Paths.get(CarbonChatVelocityEntry.class - .getProtectionDomain().getCodeSource().getLocation().toURI()); } @Override @@ -39,9 +32,7 @@ public final class CarbonChatVelocityModule extends AbstractModule { this.bind(CarbonChat.class).to(CarbonChatVelocity.class); this.bind(Logger.class).toInstance(this.logger); this.bind(Path.class).annotatedWith(ForCarbon.class).toInstance(this.dataDirectory); - this.bind(Path.class).annotatedWith(CarbonJar.class).toInstance(this.pluginJar); this.bind(CarbonServer.class).to(CarbonServerVelocity.class); - this.bind(UserManager.class).to(MemoryUserManagerVelocity.class); } } diff --git a/velocity/src/main/java/net/draycia/carbon/velocity/CarbonServerVelocity.java b/velocity/src/main/java/net/draycia/carbon/velocity/CarbonServerVelocity.java index ada2292b..050c10ee 100644 --- a/velocity/src/main/java/net/draycia/carbon/velocity/CarbonServerVelocity.java +++ b/velocity/src/main/java/net/draycia/carbon/velocity/CarbonServerVelocity.java @@ -1,25 +1,45 @@ package net.draycia.carbon.velocity; +import com.google.gson.Gson; +import com.google.gson.JsonArray; +import com.google.gson.JsonObject; import com.google.inject.Inject; import com.velocitypowered.api.proxy.Player; import com.velocitypowered.api.proxy.ProxyServer; +import com.velocitypowered.api.util.UuidUtils; +import java.io.IOException; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; import java.util.ArrayList; import java.util.UUID; +import java.util.concurrent.CompletableFuture; import net.draycia.carbon.api.CarbonServer; import net.draycia.carbon.api.users.CarbonPlayer; +import net.draycia.carbon.api.users.ComponentPlayerResult; import net.draycia.carbon.api.users.UserManager; +import net.draycia.carbon.common.users.CarbonPlayerCommon; +import net.draycia.carbon.velocity.users.CarbonPlayerVelocity; import net.kyori.adventure.audience.Audience; import net.kyori.adventure.audience.ForwardingAudience; +import net.kyori.adventure.text.Component; import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.Nullable; import org.checkerframework.framework.qual.DefaultQualifier; +import static net.kyori.adventure.text.Component.text; + @DefaultQualifier(NonNull.class) public final class CarbonServerVelocity implements CarbonServer, ForwardingAudience.Single { private final ProxyServer server; private final UserManager userManager; + private final HttpClient client = HttpClient.newHttpClient(); + private final Gson gson = new Gson(); + @Inject private CarbonServerVelocity(final ProxyServer server, final UserManager userManager) { this.server = server; @@ -41,28 +61,107 @@ public final class CarbonServerVelocity implements CarbonServer, ForwardingAudie final var players = new ArrayList(); for (final var player : this.server.getAllPlayers()) { - final @Nullable CarbonPlayer carbonPlayer = this.player(player); + final @Nullable ComponentPlayerResult carbonPlayer = this.player(player).join(); - if (carbonPlayer != null) { - players.add(carbonPlayer); + if (carbonPlayer.player() != null) { + players.add(carbonPlayer.player()); } } return players; } - @Override - public @Nullable CarbonPlayer player(final UUID uuid) { - return this.userManager.carbonPlayer(uuid); + private CompletableFuture wrapPlayer(final UUID uuid) { + return this.userManager.carbonPlayer(uuid).thenCompose(result -> { + return CompletableFuture.supplyAsync(() -> { + if (result.player() != null) { + new ComponentPlayerResult(new CarbonPlayerVelocity(this.server, result.player()), Component.empty()); + } + + final @Nullable String name = this.resolveName(uuid).join(); + + if (name != null) { + final CarbonPlayerCommon player = new CarbonPlayerCommon(null, + null, name, uuid); + + return new ComponentPlayerResult(new CarbonPlayerVelocity(this.server, player), Component.empty()); + } + + return new ComponentPlayerResult(null, text("Name not found for uuid!")); + }); + }); } @Override - public @Nullable CarbonPlayer player(final String username) { - return this.userManager.carbonPlayer(username); + public CompletableFuture player(final UUID uuid) { + return this.wrapPlayer(uuid); } - private @Nullable CarbonPlayer player(final Player player) { + @Override + public CompletableFuture player(final String username) { + return CompletableFuture.supplyAsync(() -> { + final @Nullable UUID uuid = this.resolveUUID(username).join(); + + if (uuid != null) { + return this.player(uuid).join(); + } + + return new ComponentPlayerResult(null, text("No UUID found for name.")); + }); + } + + public CompletableFuture player(final Player player) { return this.player(player.getUniqueId()); } + @Override + public CompletableFuture<@Nullable UUID> resolveUUID(final String username) { + return CompletableFuture.supplyAsync(() -> { + try { + final HttpRequest request = HttpRequest + .newBuilder(new URI("https://api.mojang.com/users/profiles/minecraft/" + username)) + .GET() + .build(); + + final HttpResponse response = + this.client.send(request, HttpResponse.BodyHandlers.ofString()); + final String mojangResponse = response.body(); + + final JsonArray jsonArray = this.gson.fromJson(mojangResponse, JsonObject.class).getAsJsonArray(); + final JsonObject json = (JsonObject) jsonArray.get(1); + + return UuidUtils.fromUndashed(json.get("uuid").getAsString()); + } catch (final URISyntaxException | IOException | InterruptedException e) { + e.printStackTrace(); + } + + return null; + }); + } + + @Override + public CompletableFuture<@Nullable String> resolveName(final UUID uuid) { + return CompletableFuture.supplyAsync(() -> { + try { + final HttpRequest request = HttpRequest + .newBuilder(new URI("https://sessionserver.mojang.com/session/minecraft/profile/" + UuidUtils.toUndashed(uuid))) + .GET() + .build(); + + final HttpResponse response = + this.client.send(request, HttpResponse.BodyHandlers.ofString()); + final String mojangResponse = response.body(); + + final JsonArray jsonArray = this.gson.fromJson(mojangResponse, JsonObject.class).getAsJsonArray(); + final JsonObject json = (JsonObject) jsonArray.get(1); + + return json.get("name").getAsString(); + } catch (final URISyntaxException | IOException | InterruptedException e) { + e.printStackTrace(); + } + + return null; + }); + } + } diff --git a/velocity/src/main/java/net/draycia/carbon/velocity/command/VelocityPlayerCommander.java b/velocity/src/main/java/net/draycia/carbon/velocity/command/VelocityPlayerCommander.java index 47dfab48..367608e1 100644 --- a/velocity/src/main/java/net/draycia/carbon/velocity/command/VelocityPlayerCommander.java +++ b/velocity/src/main/java/net/draycia/carbon/velocity/command/VelocityPlayerCommander.java @@ -29,7 +29,7 @@ public record VelocityPlayerCommander( @Override public CarbonPlayer carbonPlayer() { - return requireNonNull(this.carbon.server().player(this.player.getUniqueId()), "No CarbonPlayer for logged in Player!"); + return requireNonNull(this.carbon.server().player(this.player.getUniqueId()).join().player(), "No CarbonPlayer for logged in Player!"); } } diff --git a/velocity/src/main/java/net/draycia/carbon/velocity/listeners/VelocityChatListener.java b/velocity/src/main/java/net/draycia/carbon/velocity/listeners/VelocityChatListener.java index 0476f86c..aa430a22 100644 --- a/velocity/src/main/java/net/draycia/carbon/velocity/listeners/VelocityChatListener.java +++ b/velocity/src/main/java/net/draycia/carbon/velocity/listeners/VelocityChatListener.java @@ -3,13 +3,17 @@ package net.draycia.carbon.velocity.listeners; import com.google.inject.Inject; import com.velocitypowered.api.event.Subscribe; import com.velocitypowered.api.event.player.PlayerChatEvent; +import com.velocitypowered.api.proxy.Player; import java.util.ArrayList; import net.draycia.carbon.api.CarbonChat; +import net.draycia.carbon.api.channels.ChannelRegistry; import net.draycia.carbon.api.events.CarbonChatEvent; +import net.draycia.carbon.api.users.ComponentPlayerResult; import net.draycia.carbon.api.util.KeyedRenderer; -import net.draycia.carbon.common.channels.BasicChatChannel; +import net.draycia.carbon.velocity.CarbonChatVelocity; import org.checkerframework.checker.nullness.qual.NonNull; +import static java.util.Objects.requireNonNullElse; import static net.draycia.carbon.api.util.KeyedRenderer.keyedRenderer; import static net.kyori.adventure.key.Key.key; import static net.kyori.adventure.text.Component.empty; @@ -17,28 +21,27 @@ import static net.kyori.adventure.text.Component.text; public final class VelocityChatListener { - private final CarbonChat carbonChat; - private final BasicChatChannel basicChat; + private final CarbonChatVelocity carbonChat; + private final ChannelRegistry registry; @Inject - private VelocityChatListener(final CarbonChat carbonChat, final BasicChatChannel basicChat) { - this.carbonChat = carbonChat; - this.basicChat = basicChat; + private VelocityChatListener(final CarbonChat carbonChat, final ChannelRegistry registry) { + this.carbonChat = (CarbonChatVelocity) carbonChat; + this.registry = registry; } @Subscribe public void onPlayerChat(final @NonNull PlayerChatEvent event) { - final var sender = this.carbonChat.server().player(event.getPlayer().getUniqueId()); + final var playerResult = this.carbonChat.server().player(event.getPlayer().getUniqueId()).join(); - if (sender == null) { + if (playerResult.player() == null) { return; } - var channel = sender.selectedChannel(); + final var sender = playerResult.player(); - if (channel == null) { - channel = this.basicChat; - } + final var channel = requireNonNullElse(playerResult.player().selectedChannel(), + this.registry.defaultValue()); final var recipients = channel.recipients(sender); @@ -55,6 +58,13 @@ public final class VelocityChatListener { for (final var renderer : chatEvent.renderers()) { component = renderer.render(sender, recipient, chatEvent.message(), chatEvent.originalMessage()); + + if (recipient instanceof Player player) { + final ComponentPlayerResult targetPlayer = this.carbonChat.server().player(player).join(); + component = renderer.render(playerResult.player(), targetPlayer.player(), component, chatEvent.message()); + } else { + component = renderer.render(playerResult.player(), recipient, component, chatEvent.message()); + } } if (component != null) { diff --git a/velocity/src/main/java/net/draycia/carbon/velocity/users/CarbonPlayerVelocity.java b/velocity/src/main/java/net/draycia/carbon/velocity/users/CarbonPlayerVelocity.java index ff755f96..b8ae4c4c 100644 --- a/velocity/src/main/java/net/draycia/carbon/velocity/users/CarbonPlayerVelocity.java +++ b/velocity/src/main/java/net/draycia/carbon/velocity/users/CarbonPlayerVelocity.java @@ -2,8 +2,11 @@ package net.draycia.carbon.velocity.users; import com.velocitypowered.api.proxy.Player; import com.velocitypowered.api.proxy.ProxyServer; +import java.util.List; import java.util.Locale; import java.util.UUID; +import net.draycia.carbon.api.channels.ChatChannel; +import net.draycia.carbon.api.users.CarbonPlayer; import net.draycia.carbon.common.users.CarbonPlayerCommon; import net.kyori.adventure.audience.Audience; import net.kyori.adventure.identity.Identity; @@ -16,14 +19,26 @@ import org.checkerframework.framework.qual.DefaultQualifier; public final class CarbonPlayerVelocity extends CarbonPlayerCommon { private final ProxyServer server; - - public CarbonPlayerVelocity( - final String username, - final UUID uuid, - final ProxyServer server - ) { - super(username, uuid, Identity.identity(uuid)); + private final CarbonPlayer carbonPlayer; + + public CarbonPlayerVelocity(final ProxyServer server, final CarbonPlayer carbonPlayer) { this.server = server; + this.carbonPlayer = carbonPlayer; + } + + @Override + public String username() { + return this.carbonPlayer.username(); + } + + @Override + public Component displayName() { + return this.carbonPlayer.displayName(); + } + + @Override + public UUID uuid() { + return this.carbonPlayer.uuid(); } @Override @@ -37,6 +52,36 @@ public final class CarbonPlayerVelocity extends CarbonPlayerCommon { return player; } + @Override + public String primaryGroup() { + return "default"; // TODO: implement + } + + @Override + public List groups() { + return List.of("default"); // TODO: implement + } + + @Override + public @Nullable ChatChannel selectedChannel() { + return this.carbonPlayer.selectedChannel(); + } + + @Override + public void selectedChannel(final ChatChannel chatChannel) { + this.carbonPlayer.selectedChannel(chatChannel); + } + + @Override + public @NonNull Identity identity() { + return this.carbonPlayer.identity(); + } + + @Override + public CarbonPlayer carbonPlayer() { + return this.carbonPlayer; + } + private @Nullable Player player() { return this.server.getPlayer(this.uuid).orElse(null); } diff --git a/velocity/src/main/java/net/draycia/carbon/velocity/users/MemoryUserManagerVelocity.java b/velocity/src/main/java/net/draycia/carbon/velocity/users/MemoryUserManagerVelocity.java deleted file mode 100644 index 3fe44113..00000000 --- a/velocity/src/main/java/net/draycia/carbon/velocity/users/MemoryUserManagerVelocity.java +++ /dev/null @@ -1,60 +0,0 @@ -package net.draycia.carbon.velocity.users; - -import com.google.inject.Inject; -import com.google.inject.Singleton; -import com.velocitypowered.api.proxy.Player; -import com.velocitypowered.api.proxy.ProxyServer; -import java.util.HashMap; -import java.util.Map; -import java.util.Optional; -import java.util.UUID; -import net.draycia.carbon.api.users.CarbonPlayer; -import net.draycia.carbon.api.users.UserManager; -import org.checkerframework.checker.nullness.qual.NonNull; -import org.checkerframework.checker.nullness.qual.Nullable; - -/** - * This class should not be used. - * No data is persisted or saved. - * This exists merely as a placeholder. - */ -@Singleton -public final class MemoryUserManagerVelocity implements UserManager { - - private final ProxyServer server; - - private final @NonNull Map users = new HashMap<>(); - - @Inject - public MemoryUserManagerVelocity(final ProxyServer server) { - this.server = server; - } - - @Override - public @Nullable CarbonPlayer carbonPlayer(final @NonNull UUID uuid) { - if (this.users.containsKey(uuid)) { - return this.users.get(uuid); - } - - final Optional player = this.server.getPlayer(uuid); - - if (player.isEmpty()) { - return null; - } - - return this.users.computeIfAbsent(player.get().getUniqueId(), key -> - new CarbonPlayerVelocity(player.get().getUsername(), player.get().getUniqueId(), this.server)); - } - - @Override - public @Nullable CarbonPlayer carbonPlayer(final @NonNull String username) { - final Optional player = this.server.getPlayer(username); - - if (player.isEmpty()) { - return null; - } - - return this.carbonPlayer(player.get().getUniqueId()); - } - -}