Refactor user stuff and start on channel stuff (#153)

Co-authored-by: Riley Park <[email protected]>
Co-authored-by: broccolai <[email protected]>
Co-authored-by: Jason Penilla <[email protected]>
This commit is contained in:
authored and GitHub committed 2021-07-01 15:53:17 -07:00
1 parent 715ba92264
commit 8854891e26
56 files changed
+1624 -574

No files matched your search

@@ -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();
}
@@ -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<ComponentPlayerResult> 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<ComponentPlayerResult> 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);
}
@@ -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<Key, ChatChannel> {
}
@@ -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<Boolean> supplier
) {
if (supplier.get()) {
return ALLOWED;
} else {
return denied(reason);
}
}
}
}
@@ -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<R extends ResultedCarbonEvent.Result> extends CarbonEvent {
/**
@@ -42,7 +45,7 @@ public interface ResultedCarbonEvent<R extends ResultedCarbonEvent.Result> exten
/**
* The reason of the result.<br>
* Typically only present if allowed is false.
* Typically empty unless allowed is false.
*
* @return the reason of the result
* @since 2.0.0
@@ -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<String> groups();
}
@@ -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) {
}
@@ -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<ComponentPlayerResult> 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<ComponentPlayerResult> savePlayer(final CarbonPlayer player);
}
@@ -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);
}
@@ -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<Commander> createCommandManager() {
final PaperCommandManager<Commander> commandManager;
@@ -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());
}
});
}
}
}
@@ -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);
}
}
@@ -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<CarbonPlayer>();
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<ComponentPlayerResult> 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<ComponentPlayerResult> player(final UUID uuid) {
return this.wrapPlayer(uuid);
}
private @Nullable CarbonPlayer player(final Player player) {
@Override
public CompletableFuture<ComponentPlayerResult> 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<ComponentPlayerResult> 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());
}
}
@@ -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!");
}
}
@@ -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;
@@ -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<String> 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();
}
}
@@ -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<UUID, @NonNull CarbonPlayer> 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());
}
}
+4
View File
@@ -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
@@ -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()) {
@@ -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);
}
}
@@ -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(),
@@ -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<Key, ChatChannel> implements ChannelRegistry, DefaultedRegistry<Key, ChatChannel> {
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<Path> 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<ConfigChatChannel> 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();
}
}
@@ -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<Audience> recipients(final CarbonPlayer sender) {
final List<Audience> 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<Audience> filterRecipients(final CarbonPlayer sender, final Set<Audience> 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<Audience> componentPlaceholderResolver = new ComponentPlaceholderResolver<>();
final UUIDPlaceholderResolver<Audience> uuidPlaceholderResolver = new UUIDPlaceholderResolver<>();
final CarbonMessageParser carbonMessageParser = new CarbonMessageParser();
final CarbonMessageSender carbonMessageSender = new CarbonMessageSender();
return Moonshine.<Audience>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;
}
}
@@ -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
);
}
@@ -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<String, Audience> {
// Map<String, String> -> Map<Group, Format>
// "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<String, String> defaults = Map.of("default", "<displayname>: <message>",
"console", "<username> - <uuid>: <message>");
// 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<Locale, Map<String, String>> locales = Map.of(Locale.US,
Map.of("default", "<displayname>: <message>"));
@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<String, String> 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");
}
}
@@ -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 <T> @Nullable T load(final Class<T> 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();
@@ -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
}
}
@@ -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<String, Component, Audience> {
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<Audience> 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<Audience> parsingContext) {
return MiniMessage.get().parse(message, parsingContext.placeholders());
}
@@ -51,13 +51,7 @@ public final class CarbonMessageSource implements IMessageSource<String, Audienc
this.pluginJar = pluginJar();
this.logger = logger;
final @Nullable Locale configLocale = Translator.parseLocale(primaryConfig.defaultLocale());
if (configLocale != null) {
this.defaultLocale = configLocale;
} else {
this.defaultLocale = Locale.ENGLISH;
}
this.defaultLocale = primaryConfig.defaultLocale();
final Path localeDirectory = dataDirectory.resolve("locale");
@@ -0,0 +1,51 @@
package net.draycia.carbon.common.serialisation.gson;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import java.lang.reflect.Type;
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.text.Component;
public class CarbonPlayerSerializerGson implements JsonSerializer<CarbonPlayerCommon>, JsonDeserializer<CarbonPlayer> {
@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;
}
}
@@ -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<ChatChannel> {
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;
}
}
@@ -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<Locale> {
@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());
}
}
@@ -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<UUID> {
@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());
}
}
@@ -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<String> 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;
}
}
@@ -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<UUID, CarbonPlayerCommon> 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<ComponentPlayerResult> 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<ComponentPlayerResult> 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()));
}
});
}
}
@@ -2,5 +2,5 @@ example.command.hello=<green>Hello from </green><plugin><green>!</green>
unsupported.legacy=<red>Legacy color codes have been detected in a message. This is not supported behavior. Message: '<message>'
placeholders.plugin=<#1DA3A6><bold>Carbon</bold></#1DA3A6>
test.phrase=English: Has anyone really been far even as decided to use even go want to do look more like?
channel.format.basic=<displayname>\: <message>
channel.format.basic=\ue238<displayname>\: <message>
@@ -2,4 +2,4 @@ example.command.hello=<green>Hello from </green><plugin><green>\!</green>
unsupported.legacy=<red>Legacy color codes have been detected in a message. This is not supported behavior. Message\: '<message>'
placeholders.plugin=<\#1DA3A6><bold>Carbon</bold></\#1DA3A6>
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=<displayname>\: <message>
channel.format.basic=\ue238<displayname>\: <message>
@@ -2,4 +2,4 @@ example.command.hello=<green>Hello from </green><plugin><green>\!</green>
unsupported.legacy=<red>Legacy color codes have been detected in a message. This is not supported behavior. Message\: '<message>'
placeholders.plugin=<\#1DA3A6><bold>Carbon</bold></\#1DA3A6>
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=<displayname>\: <message>
channel.format.basic=\ue238<displayname>\: <message>
+4
View File
@@ -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
+1 -1
View File
@@ -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)
@@ -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<Class<?>> 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<Server> 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<Server> 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<Commander> createCommandManager() {
final SpongeCommandManager<Commander> commandManager = new SpongeCommandManager<>(
@@ -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<Class<?>> 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<Server> event) {
}
}
@@ -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);
}
}
@@ -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<? extends CarbonPlayer> players() {
final var players = new ArrayList<CarbonPlayer>();
public Iterable<CarbonPlayerSponge> players() {
final var players = new ArrayList<CarbonPlayerSponge>();
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<ComponentPlayerResult> 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<ComponentPlayerResult> player(final UUID uuid) {
return this.wrapPlayer(uuid);
}
private @Nullable CarbonPlayer player(final Player player) {
@Override
public CompletableFuture<ComponentPlayerResult> 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<ComponentPlayerResult> 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()
);
}
}
@@ -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
@@ -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<KeyedRenderer>();
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()) {
@@ -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<ServerPlayer> 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<String> 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();
}
}
@@ -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<UUID, @NonNull CarbonPlayer> 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> 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<ServerPlayer> player = Sponge.server().player(username);
if (player.isEmpty()) {
return null;
}
return this.carbonPlayer(player.get().uniqueId());
}
}
@@ -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<Class<?>> 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
@@ -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<Class<?>> 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));
}
}
}
@@ -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);
}
}
@@ -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<CarbonPlayer>();
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<ComponentPlayerResult> 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<ComponentPlayerResult> player(final UUID uuid) {
return this.wrapPlayer(uuid);
}
private @Nullable CarbonPlayer player(final Player player) {
@Override
public CompletableFuture<ComponentPlayerResult> 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<ComponentPlayerResult> 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<String> 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<String> 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;
});
}
}
@@ -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!");
}
}
@@ -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) {
@@ -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<String> 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);
}
@@ -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<UUID, @NonNull CarbonPlayer> 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> 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> player = this.server.getPlayer(username);
if (player.isEmpty()) {
return null;
}
return this.carbonPlayer(player.get().getUniqueId());
}
}