Player saving done right

This commit is contained in:
Draycia committed 2021-09-30 18:52:59 -07:00
1 parent 3736377fd7
commit 9305da7d2d
21 files changed
+314 -257

No files matched your search

@@ -63,4 +63,7 @@ public interface CarbonChat {
IMessageRenderer<SourcedAudience, String, Component, Component> messageRenderer();
// TODO: Redis as MariaDB cache
// TODO: Adopt egg82/Messenger for use with databases?
}
@@ -40,7 +40,7 @@ public interface CarbonServer extends Audience {
* @return the result
* @since 2.0.0
*/
CompletableFuture<ComponentPlayerResult> player(final UUID uuid);
CompletableFuture<ComponentPlayerResult<CarbonPlayer>> player(final UUID uuid);
/**
* Obtains a {@link CarbonPlayer} instance for the specified username.
@@ -49,7 +49,7 @@ public interface CarbonServer extends Audience {
* @return the result
* @since 2.0.0
*/
CompletableFuture<ComponentPlayerResult> player(final String username);
CompletableFuture<ComponentPlayerResult<CarbonPlayer>> player(final String username);
/**
* Obtains the desired user's UUID.
@@ -10,6 +10,6 @@ import org.checkerframework.checker.nullness.qual.Nullable;
* @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) {
public record ComponentPlayerResult<C extends CarbonPlayer>(@Nullable C player, Component reason) {
}
@@ -11,7 +11,7 @@ import org.checkerframework.framework.qual.DefaultQualifier;
* @since 2.0.0
*/
@DefaultQualifier(NonNull.class)
public interface UserManager {
public interface UserManager<C extends CarbonPlayer> {
/**
* Loads and returns a {@link CarbonPlayer} with the given {@link UUID}.
@@ -20,7 +20,7 @@ public interface UserManager {
* @return the result
* @since 2.0.0
*/
CompletableFuture<ComponentPlayerResult> carbonPlayer(final UUID uuid);
CompletableFuture<ComponentPlayerResult<C>> carbonPlayer(final UUID uuid);
/**
* Saves the {@link CarbonPlayer} and returns the result.
@@ -29,6 +29,6 @@ public interface UserManager {
* @return the result
* @since 2.0.0
*/
CompletableFuture<ComponentPlayerResult> savePlayer(final CarbonPlayer player);
CompletableFuture<ComponentPlayerResult<C>> savePlayer(final C player);
}
@@ -3,6 +3,7 @@ package net.draycia.carbon.bukkit;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Singleton;
import com.google.inject.TypeLiteral;
import io.papermc.lib.PaperLib;
import java.nio.file.Path;
import java.util.Set;
@@ -15,7 +16,6 @@ import net.draycia.carbon.api.users.UserManager;
import net.draycia.carbon.api.util.SourcedAudience;
import net.draycia.carbon.bukkit.listeners.BukkitChatListener;
import net.draycia.carbon.bukkit.listeners.BukkitPlayerJoinListener;
import net.draycia.carbon.bukkit.users.CarbonPlayerBukkit;
import net.draycia.carbon.bukkit.util.BukkitMessageRenderer;
import net.draycia.carbon.common.channels.CarbonChannelRegistry;
import net.draycia.carbon.common.command.commands.ContinueCommand;
@@ -25,7 +25,8 @@ import net.draycia.carbon.common.command.commands.WhisperCommand;
import net.draycia.carbon.common.listeners.DeafenHandler;
import net.draycia.carbon.common.listeners.MuteHandler;
import net.draycia.carbon.common.messages.CarbonMessageService;
import net.kyori.adventure.audience.Audience;
import net.draycia.carbon.common.users.CarbonPlayerCommon;
import net.draycia.carbon.common.users.WrappedCarbonPlayer;
import net.kyori.adventure.text.Component;
import net.kyori.moonshine.message.IMessageRenderer;
import org.apache.logging.log4j.LogManager;
@@ -49,7 +50,7 @@ public final class CarbonChatBukkit extends JavaPlugin implements CarbonChat {
private static final int BSTATS_PLUGIN_ID = 8720;
private final CarbonEventHandler eventHandler = new CarbonEventHandler();
private @MonotonicNonNull Injector injector;
private @MonotonicNonNull UserManager userManager;
private @MonotonicNonNull UserManager<CarbonPlayerCommon> userManager;
private @MonotonicNonNull Logger logger;
private @MonotonicNonNull CarbonServerBukkit carbonServerBukkit;
private @MonotonicNonNull CarbonMessageService messageService;
@@ -77,7 +78,7 @@ public final class CarbonChatBukkit extends JavaPlugin implements CarbonChat {
this.messageService = this.injector.getInstance(CarbonMessageService.class);
this.channelRegistry = this.injector.getInstance(ChannelRegistry.class);
this.carbonServerBukkit = this.injector.getInstance(CarbonServerBukkit.class);
this.userManager = this.injector.getInstance(UserManager.class);
this.userManager = this.injector.getInstance(com.google.inject.Key.get(new TypeLiteral<UserManager<CarbonPlayerCommon>>() {}));
}
@Override
@@ -115,16 +116,24 @@ public final class CarbonChatBukkit extends JavaPlugin implements CarbonChat {
}
private void savePlayers() {
// TODO: move to common or CarbonServer?
for (final var player : this.server().players()) {
this.userManager().savePlayer(((CarbonPlayerBukkit) player).carbonPlayer()).thenAccept(result -> {
final var saveResult = this.userManager().savePlayer(((WrappedCarbonPlayer) player).carbonPlayerCommon());
saveResult.thenAccept(result -> {
if (result.player() == null) {
this.server().console().sendMessage(result.reason());
}
});
saveResult.exceptionally(exception -> {
exception.getCause().printStackTrace();
return null;
});
}
}
public UserManager userManager() {
public UserManager<CarbonPlayerCommon> userManager() {
return this.userManager;
}
@@ -29,12 +29,12 @@ import static net.kyori.adventure.text.Component.text;
public final class CarbonServerBukkit implements CarbonServer, ForwardingAudience.Single {
private final CarbonChatBukkit chatBukkitEntry;
private final UserManager userManager;
private final UserManager<CarbonPlayerCommon> userManager;
private final Map<UUID, CarbonPlayerBukkit> userCache = new ConcurrentHashMap<>();
@Inject
private CarbonServerBukkit(final CarbonChatBukkit chatBukkitEntry, final UserManager userManager) {
private CarbonServerBukkit(final CarbonChatBukkit chatBukkitEntry, final UserManager<CarbonPlayerCommon> userManager) {
this.chatBukkitEntry = chatBukkitEntry;
this.userManager = userManager;
}
@@ -54,7 +54,7 @@ public final class CarbonServerBukkit implements CarbonServer, ForwardingAudienc
final var players = new ArrayList<CarbonPlayer>();
for (final var player : this.chatBukkitEntry.getServer().getOnlinePlayers()) {
final @Nullable ComponentPlayerResult result = this.player(player).join();
final @Nullable ComponentPlayerResult<CarbonPlayer> result = this.player(player).join();
if (result.player() != null) {
players.add(result.player());
@@ -64,47 +64,46 @@ public final class CarbonServerBukkit implements CarbonServer, ForwardingAudienc
return players;
}
private CompletableFuture<ComponentPlayerResult> wrapPlayer(final UUID uuid) {
private CompletableFuture<ComponentPlayerResult<CarbonPlayer>> wrapPlayer(final UUID uuid) {
return CompletableFuture.supplyAsync(() -> {
final @Nullable CarbonPlayerBukkit cachedPlayer = this.userCache.get(uuid);
if (cachedPlayer != null) {
return new ComponentPlayerResult(cachedPlayer, Component.empty());
return new ComponentPlayerResult<>(cachedPlayer, Component.empty());
}
final ComponentPlayerResult result = this.userManager.carbonPlayer(uuid).join();
final ComponentPlayerResult<CarbonPlayerCommon> result = this.userManager.carbonPlayer(uuid).join();
if (result.player() != null) {
final CarbonPlayerBukkit carbonPlayerBukkit = new CarbonPlayerBukkit(result.player());
this.userCache.put(uuid, carbonPlayerBukkit);
return new ComponentPlayerResult(carbonPlayerBukkit, Component.empty());
return new ComponentPlayerResult<>(carbonPlayerBukkit, Component.empty());
}
final @Nullable String name = this.resolveName(uuid).join();
if (name != null) {
final CarbonPlayerCommon player = new CarbonPlayerCommon(null,
null, name, uuid);
final CarbonPlayerCommon player = new CarbonPlayerCommon(name, uuid);
final CarbonPlayerBukkit carbonPlayerBukkit = new CarbonPlayerBukkit(player);
this.userCache.put(uuid, carbonPlayerBukkit);
return new ComponentPlayerResult(carbonPlayerBukkit, Component.empty());
return new ComponentPlayerResult<>(carbonPlayerBukkit, Component.empty());
}
return new ComponentPlayerResult(null, text("Name not found for uuid!"));
return new ComponentPlayerResult<>(null, text("Name not found for uuid!"));
});
}
@Override
public CompletableFuture<ComponentPlayerResult> player(final UUID uuid) {
public CompletableFuture<ComponentPlayerResult<CarbonPlayer>> player(final UUID uuid) {
return this.wrapPlayer(uuid);
}
@Override
public CompletableFuture<ComponentPlayerResult> player(final String username) {
public CompletableFuture<ComponentPlayerResult<CarbonPlayer>> player(final String username) {
return CompletableFuture.supplyAsync(() -> {
final @Nullable UUID uuid = this.resolveUUID(username).join();
@@ -112,11 +111,11 @@ public final class CarbonServerBukkit implements CarbonServer, ForwardingAudienc
return this.player(uuid).join();
}
return new ComponentPlayerResult(null, text("No UUID found for name."));
return new ComponentPlayerResult<>(null, text("No UUID found for name."));
});
}
public CompletableFuture<ComponentPlayerResult> player(final Player player) {
public CompletableFuture<ComponentPlayerResult<CarbonPlayer>> player(final Player player) {
return this.player(player.getUniqueId());
}
@@ -6,6 +6,7 @@ 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.CarbonPlayer;
import net.draycia.carbon.api.users.ComponentPlayerResult;
import net.draycia.carbon.api.util.KeyedRenderer;
import net.draycia.carbon.bukkit.CarbonChatBukkit;
@@ -15,6 +16,7 @@ import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.checkerframework.framework.qual.DefaultQualifier;
import static java.util.Objects.requireNonNullElse;
@@ -37,7 +39,7 @@ public final class BukkitChatListener implements Listener {
@EventHandler
public void onPlayerChat(final @NonNull AsyncChatEvent event) {
final var playerResult = this.carbonChat.server().player(event.getPlayer().getUniqueId()).join();
final var sender = playerResult.player();
final @Nullable CarbonPlayer sender = playerResult.player();
if (sender == null) {
return;
@@ -10,7 +10,11 @@ import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.checkerframework.framework.qual.DefaultQualifier;
@DefaultQualifier(NonNull.class)
public class BukkitPlayerJoinListener implements Listener {
private final CarbonChat carbonChat;
@@ -27,14 +31,13 @@ public class BukkitPlayerJoinListener implements Listener {
@EventHandler(priority = EventPriority.LOWEST)
public void onPlayerLogin(final PlayerJoinEvent event) {
final ComponentPlayerResult result = this.carbonChat.server().player(event.getPlayer().getUniqueId()).join();
final ComponentPlayerResult<CarbonPlayer> result = this.carbonChat.server().player(event.getPlayer().getUniqueId()).join();
final @Nullable CarbonPlayer player = result.player();
if (result.player() == null) {
if (player == null) {
return;
}
final CarbonPlayer player = result.player();
// Don't show join messages when muted
if (this.primaryConfig.hideMutedJoinLeaveQuit() && player.muted()) {
event.joinMessage(null);
@@ -48,7 +51,7 @@ public class BukkitPlayerJoinListener implements Listener {
return;
}
final ComponentPlayerResult result = this.carbonChat.server().player(event.getPlayer().getUniqueId()).join();
final ComponentPlayerResult<CarbonPlayer> result = this.carbonChat.server().player(event.getPlayer().getUniqueId()).join();
if (result.player() == null) {
return;
@@ -4,14 +4,11 @@ import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
import java.util.UUID;
import net.draycia.carbon.api.channels.ChatChannel;
import net.draycia.carbon.api.users.CarbonPlayer;
import net.draycia.carbon.bukkit.util.BukkitCapabilities;
import net.draycia.carbon.common.users.CarbonPlayerCommon;
import net.draycia.carbon.common.users.WrappedCarbonPlayer;
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 net.milkbowl.vault.permission.Permission;
import org.bukkit.Bukkit;
@@ -23,17 +20,37 @@ import org.checkerframework.framework.qual.DefaultQualifier;
import org.jetbrains.annotations.NotNull;
@DefaultQualifier(NonNull.class)
public final class CarbonPlayerBukkit extends CarbonPlayerCommon implements ForwardingAudience.Single {
public final class CarbonPlayerBukkit extends WrappedCarbonPlayer implements ForwardingAudience.Single {
private final CarbonPlayer carbonPlayer;
private final CarbonPlayerCommon carbonPlayerCommon;
public CarbonPlayerBukkit(final CarbonPlayer carbonPlayer) {
this.carbonPlayer = carbonPlayer;
public CarbonPlayerBukkit(final CarbonPlayerCommon carbonPlayerCommon) {
this.carbonPlayerCommon = carbonPlayerCommon;
}
private @Nullable Player player() {
return Bukkit.getPlayer(this.carbonPlayerCommon.uuid());
}
@Override
public CarbonPlayerCommon carbonPlayerCommon() {
return this.carbonPlayerCommon;
}
@Override
public @NotNull Audience audience() {
final @Nullable Player player = this.player();
if (player == null) {
return Audience.empty();
}
return player;
}
@Override
public void displayName(final @Nullable Component displayName) {
this.carbonPlayer.displayName(displayName);
this.carbonPlayerCommon.displayName(displayName);
final @Nullable Player player = this.player();
@@ -49,7 +66,7 @@ public final class CarbonPlayerBukkit extends CarbonPlayerCommon implements Forw
@Override
public void temporaryDisplayName(final @Nullable Component displayName, final long expirationEpoch) {
this.carbonPlayer.temporaryDisplayName(displayName, expirationEpoch);
this.carbonPlayerCommon.temporaryDisplayName(displayName, expirationEpoch);
final @Nullable Player player = this.player();
@@ -64,42 +81,6 @@ public final class CarbonPlayerBukkit extends CarbonPlayerCommon implements Forw
}
}
@Override
public String username() {
return this.carbonPlayer.username();
}
@Override
public boolean hasCustomDisplayName() {
return this.carbonPlayer.hasCustomDisplayName();
}
@Override
public @Nullable Component displayName() {
return this.carbonPlayer.displayName();
}
@Override
public UUID uuid() {
return this.carbonPlayer.uuid();
}
@Override
public @NotNull Audience audience() {
final @Nullable Player player = this.player();
if (player == null) {
return Audience.empty();
}
return player;
}
@Override
public CarbonPlayer carbonPlayer() {
return this.carbonPlayer;
}
@Override
public Component createItemHoverComponent() {
final @Nullable Player player = this.player(); // This is temporary (it's not)
@@ -174,36 +155,6 @@ public final class CarbonPlayerBukkit extends CarbonPlayerCommon implements Forw
return List.of("default"); // TODO: implement
}
@Override
public boolean muted() {
return this.carbonPlayer.muted();
}
@Override
public void muted(final boolean muted) {
this.carbonPlayer.muted(muted);
}
@Override
public boolean deafened() {
return this.carbonPlayer.deafened();
}
@Override
public void deafened(final boolean deafened) {
this.carbonPlayer.deafened(deafened);
}
@Override
public boolean spying() {
return this.carbonPlayer.spying();
}
@Override
public void spying(final boolean spying) {
this.carbonPlayer.spying(spying);
}
@Override
public @Nullable Locale locale() {
final @Nullable Player player = this.player();
@@ -215,25 +166,6 @@ public final class CarbonPlayerBukkit extends CarbonPlayerCommon implements Forw
}
}
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 Identity identity() {
return this.carbonPlayer.identity();
}
@Override
public void sendMessageAsPlayer(String message) {
Bukkit.getScheduler().runTask(Bukkit.getPluginManager().getPlugin("CarbonChat"), () -> {
@@ -246,24 +178,4 @@ public final class CarbonPlayerBukkit extends CarbonPlayerCommon implements Forw
return this.player() != null;
}
@Override
public void whisperReplyTarget(@Nullable UUID uuid) {
this.carbonPlayer.whisperReplyTarget(uuid);
}
@Override
public @Nullable UUID whisperReplyTarget() {
return this.carbonPlayer.whisperReplyTarget();
}
@Override
public void lastWhisperTarget(@Nullable UUID uuid) {
this.carbonPlayer.lastWhisperTarget(uuid);
}
@Override
public @Nullable UUID lastWhisperTarget() {
return this.carbonPlayer.lastWhisperTarget();
}
}
@@ -20,6 +20,7 @@ import net.draycia.carbon.common.messages.ComponentPlaceholderResolver;
import net.draycia.carbon.common.messages.ReceiverResolver;
import net.draycia.carbon.common.messages.StringPlaceholderResolver;
import net.draycia.carbon.common.messages.UUIDPlaceholderResolver;
import net.draycia.carbon.common.users.CarbonPlayerCommon;
import net.draycia.carbon.common.users.JSONUserManager;
import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.text.Component;
@@ -36,7 +37,7 @@ public final class CarbonCommonModule extends AbstractModule {
@Provides
@Singleton
public UserManager userManager(
public UserManager<CarbonPlayerCommon> userManager(
final PrimaryConfig primaryConfig,
final Injector injector
) {
@@ -9,6 +9,7 @@ import java.time.Duration;
import java.time.Instant;
import java.time.Period;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalAmount;
import java.time.temporal.TemporalUnit;
import java.util.List;
import java.util.Locale;
@@ -149,21 +150,29 @@ public class NicknameCommand {
return instant.toEpochMilli();
}
private final List<TemporalUnit> temporalUnits = List.of(ChronoUnit.YEARS, ChronoUnit.MONTHS, ChronoUnit.WEEKS,
private final List<ChronoUnit> temporalUnits = List.of(ChronoUnit.YEARS, ChronoUnit.MONTHS, ChronoUnit.WEEKS,
ChronoUnit.DAYS, ChronoUnit.HOURS, ChronoUnit.MINUTES, ChronoUnit.SECONDS);
private String formatMillisDuration(final long millisSinceEpoch) {
final var millisBetween = millisSinceEpoch - System.currentTimeMillis();
var duration = Duration.ofMillis(millisBetween);
var period = Period.from(Duration.ofMillis(millisBetween)); // TODO: this doesn't work
var stringJoiner = new StringJoiner(", ");
for (final var temporalUnit : temporalUnits) {
final var count = duration.get(temporalUnit);
final var count = period.get(temporalUnit);
// Check if == 0 instead of > 0 in case the millisSinceEpoch refers to the past
// !! the distinction is important
if (count != 0) {
duration = duration.minus(count, temporalUnit);
period = switch (temporalUnit) {
case YEARS -> period.minusYears(count);
case MONTHS -> period.minusMonths(count);
case WEEKS -> period.minus(Period.ofWeeks((int)count));
case DAYS -> period.minusDays(count);
case HOURS, MINUTES, SECONDS -> period.minus(Duration.of(count, temporalUnit));
default -> period;
};
stringJoiner.add(String.format("%d %s", count, temporalUnit));
}
}
@@ -12,7 +12,11 @@ import net.draycia.carbon.common.command.Commander;
import net.draycia.carbon.common.command.PlayerCommander;
import net.draycia.carbon.common.messages.CarbonMessageService;
import org.checkerframework.checker.nullness.qual.MonotonicNonNull;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.checkerframework.framework.qual.DefaultQualifier;
@DefaultQualifier(NonNull.class)
public class ReplyCommand {
@Inject
@@ -29,14 +33,14 @@ public class ReplyCommand {
final CarbonPlayer sender = ((PlayerCommander)handler.getSender()).carbonPlayer();
final String message = handler.get("message");
final UUID replyTarget = sender.whisperReplyTarget();
final @Nullable UUID replyTarget = sender.whisperReplyTarget();
if (replyTarget == null) {
messageService.replyTargetNotSet(sender, sender.displayName());
return;
}
final ComponentPlayerResult result = carbonChat.server().player(replyTarget).join();
final ComponentPlayerResult<CarbonPlayer> result = carbonChat.server().player(replyTarget).join();
final @MonotonicNonNull CarbonPlayer recipient = result.player();
if (recipient == null) {
@@ -1,57 +0,0 @@
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;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.framework.qual.DefaultQualifier;
@DefaultQualifier(NonNull.class)
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();
if (player.hasCustomDisplayName()) {
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;
}
}
@@ -25,8 +25,12 @@ public class ChatChannelSerializerGson extends TypeAdapter<ChatChannel> {
}
@Override
public void write(final JsonWriter out, final ChatChannel value) throws IOException {
out.value(value.key().asString());
public void write(final JsonWriter out, final @Nullable ChatChannel value) throws IOException {
if (value == null) {
out.value((String)null);
} else {
out.value(value.key().asString());
}
}
@Override
@@ -37,7 +37,7 @@ public class LocaleSerializerConfigurate implements TypeSerializer<Locale> {
}
@Override
public void serialize(final Type type, @Nullable final Locale obj, final ConfigurationNode node) throws SerializationException {
public void serialize(final Type type, final @Nullable Locale obj, final ConfigurationNode node) throws SerializationException {
if (obj == null) {
node.set(null);
} else {
@@ -6,14 +6,19 @@ import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.util.UUID;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
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());
public void write(final JsonWriter jsonWriter, final @Nullable UUID uuid) throws IOException {
if (uuid != null) {
jsonWriter.value(uuid.toString());
} else {
jsonWriter.value((String)null);
}
}
@Override
@@ -19,25 +19,22 @@ import org.jetbrains.annotations.NotNull;
public class CarbonPlayerCommon implements CarbonPlayer, ForwardingAudience.Single {
protected boolean deafened = false;
protected @Nullable Component displayName;
protected @Nullable Component displayName = null;
protected @Nullable UUID lastWhisperTarget = null;
protected boolean muted = false;
protected @Nullable ChatChannel selectedChannel;
protected @Nullable ChatChannel selectedChannel = null;
protected boolean spying = false;
protected @Nullable Component temporaryDisplayName = null;
protected long temporaryDisplayNameExpiration = -1;
protected @MonotonicNonNull String username;
protected @MonotonicNonNull UUID uuid;
protected @Nullable UUID whisperReplyTarget = null;
protected @MonotonicNonNull String username;
protected @MonotonicNonNull UUID uuid;
public CarbonPlayerCommon(
final @Nullable Component displayName,
final @Nullable ChatChannel selectedChannel,
final String username,
final UUID uuid
) {
this.displayName = displayName;
this.selectedChannel = selectedChannel;
this.username = username;
this.uuid = uuid;
}
@@ -85,6 +82,16 @@ public class CarbonPlayerCommon implements CarbonPlayer, ForwardingAudience.Sing
this.temporaryDisplayNameExpiration = expirationEpoch;
}
@Override
public @Nullable Component temporaryDisplayName() {
return this.temporaryDisplayName;
}
@Override
public long temporaryDisplayNameExpiration() {
return this.temporaryDisplayNameExpiration;
}
@Override
public boolean hasPermission(final String permission) {
return false;
@@ -15,11 +15,9 @@ import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import net.draycia.carbon.api.CarbonChat;
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;
@@ -32,7 +30,7 @@ import static net.kyori.adventure.text.Component.empty;
import static net.kyori.adventure.text.Component.text;
@DefaultQualifier(NonNull.class)
public class JSONUserManager implements UserManager {
public class JSONUserManager implements UserManager<CarbonPlayerCommon> {
private final Logger logger;
private final Gson serializer;
@@ -56,75 +54,78 @@ public class JSONUserManager implements UserManager {
this.serializer = GsonComponentSerializer.gson().populator()
.apply(new GsonBuilder())
.registerTypeAdapter(CarbonPlayerCommon.class, injector.getInstance(CarbonPlayerSerializerGson.class))
.registerTypeAdapter(ChatChannel.class, injector.getInstance(ChatChannelSerializerGson.class))
.registerTypeAdapter(UUID.class, injector.getInstance(UUIDSerializerGson.class))
.setPrettyPrinting()
.create();
}
@Override
public CompletableFuture<ComponentPlayerResult> carbonPlayer(final UUID uuid) {
public CompletableFuture<ComponentPlayerResult<CarbonPlayerCommon>> carbonPlayer(final UUID uuid) {
return CompletableFuture.supplyAsync(() -> {
final @Nullable CarbonPlayerCommon cachedPlayer = this.userCache.get(uuid);
if (cachedPlayer != null) {
return new ComponentPlayerResult(cachedPlayer, empty());
return new ComponentPlayerResult<>(cachedPlayer, empty());
}
final Path userFile = this.userDirectory.resolve(uuid + ".json");
if (Files.exists(userFile)) {
try {
final CarbonPlayerCommon player =
final @Nullable CarbonPlayerCommon player =
this.serializer.fromJson(Files.newBufferedReader(userFile), CarbonPlayerCommon.class);
if (player == null) {
return new ComponentPlayerResult<>(null, text("Player file found but was empty."));
}
this.userCache.put(uuid, player);
// TODO: supply reason if fromJson returns null
return new ComponentPlayerResult(player, empty());
return new ComponentPlayerResult<>(player, empty());
} catch (final IOException exception) {
return new ComponentPlayerResult(null, text(exception.getMessage()));
return new ComponentPlayerResult<>(null, text(exception.getMessage()));
}
}
final String name = Objects.requireNonNull(
this.carbonChat.server().resolveName(uuid).join());
final CarbonPlayerCommon player = new CarbonPlayerCommon(null,
null, name, uuid);
final CarbonPlayerCommon player = new CarbonPlayerCommon(name, uuid);
this.userCache.put(uuid, player);
return new ComponentPlayerResult(player, empty());
return new ComponentPlayerResult<>(player, empty());
});
}
@Override
public CompletableFuture<ComponentPlayerResult> savePlayer(final CarbonPlayer player) {
public CompletableFuture<ComponentPlayerResult<CarbonPlayerCommon>> savePlayer(final CarbonPlayerCommon 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 {
final String json = this.serializer.toJson(player);
if (json == null || json.isBlank()) {
return new ComponentPlayerResult<>(null, text("No data to save - toJson returned null or blank."));
}
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);
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]",
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()));
return new ComponentPlayerResult<>(null, text(exception.getMessage()));
}
});
}
@@ -0,0 +1,162 @@
package net.draycia.carbon.common.users;
import net.draycia.carbon.api.channels.ChatChannel;
import net.draycia.carbon.api.users.CarbonPlayer;
import net.kyori.adventure.identity.Identity;
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 java.util.List;
import java.util.Locale;
import java.util.UUID;
@DefaultQualifier(NonNull.class)
public abstract class WrappedCarbonPlayer implements CarbonPlayer {
public abstract CarbonPlayerCommon carbonPlayerCommon();
@Override
public String username() {
return this.carbonPlayerCommon().username();
}
@Override
public boolean hasCustomDisplayName() {
return this.carbonPlayerCommon().hasCustomDisplayName();
}
@Override
public @Nullable Component displayName() {
return this.carbonPlayerCommon().displayName();
}
@Override
public void displayName(@Nullable Component displayName) {
this.carbonPlayerCommon().displayName(displayName);
}
@Override
public void temporaryDisplayName(@Nullable Component temporaryDisplayName, long expirationEpoch) {
this.carbonPlayerCommon().temporaryDisplayName(temporaryDisplayName, expirationEpoch);
}
@Override
public @Nullable Component temporaryDisplayName() {
return this.carbonPlayerCommon().temporaryDisplayName();
}
@Override
public long temporaryDisplayNameExpiration() {
return this.carbonPlayerCommon().temporaryDisplayNameExpiration();
}
@Override
public UUID uuid() {
return this.carbonPlayerCommon().uuid();
}
@Override
public Component createItemHoverComponent() {
return this.carbonPlayerCommon().createItemHoverComponent();
}
@Override
public @Nullable Locale locale() {
return this.carbonPlayerCommon().locale();
}
@Override
public @Nullable ChatChannel selectedChannel() {
return this.carbonPlayerCommon().selectedChannel();
}
@Override
public void selectedChannel(ChatChannel chatChannel) {
this.carbonPlayerCommon().selectedChannel(chatChannel);
}
// TODO: move to Permissible class or one similarly named?
@Override
public boolean hasPermission(String permission) {
return this.carbonPlayerCommon().hasPermission(permission);
}
@Override
public String primaryGroup() {
return this.carbonPlayerCommon().primaryGroup();
}
@Override
public List<String> groups() {
return this.carbonPlayerCommon().groups();
}
@Override
public boolean muted() {
return this.carbonPlayerCommon().muted();
}
@Override
public void muted(boolean muted) {
this.carbonPlayerCommon().muted(muted);
}
@Override
public boolean deafened() {
return this.carbonPlayerCommon().deafened();
}
@Override
public void deafened(boolean deafened) {
this.carbonPlayerCommon().deafened(deafened);
}
@Override
public boolean spying() {
return this.carbonPlayerCommon().spying();
}
@Override
public void spying(boolean spying) {
this.carbonPlayerCommon().spying(spying);
}
@Override
public void sendMessageAsPlayer(String message) {
this.carbonPlayerCommon().sendMessageAsPlayer(message);
}
@Override
public boolean online() {
return this.carbonPlayerCommon().online();
}
@Override
public @Nullable UUID whisperReplyTarget() {
return this.carbonPlayerCommon().whisperReplyTarget();
}
@Override
public void whisperReplyTarget(@Nullable UUID uuid) {
this.carbonPlayerCommon().whisperReplyTarget(uuid);
}
@Override
public @Nullable UUID lastWhisperTarget() {
return this.carbonPlayerCommon().lastWhisperTarget();
}
@Override
public void lastWhisperTarget(@Nullable UUID uuid) {
this.carbonPlayerCommon().lastWhisperTarget(uuid);
}
@Override
public @NotNull Identity identity() {
return this.carbonPlayerCommon().identity();
}
}
@@ -73,11 +73,6 @@ public final class CarbonPlayerSponge implements CarbonPlayer, ForwardingAudienc
});
}
@Override
public void temporaryDisplayName(@Nullable Component displayName) {
this.carbonPlayer.temporaryDisplayName(displayName);
}
@Override
public UUID uuid() {
return this.carbonPlayer.uuid();
@@ -82,9 +82,7 @@ public final class CarbonServerVelocity implements CarbonServer, ForwardingAudie
final @Nullable String name = this.resolveName(uuid).join();
if (name != null) {
final CarbonPlayerCommon player = new CarbonPlayerCommon(null,
null, name, uuid);
final CarbonPlayerCommon player = new CarbonPlayerCommon(name, uuid);
return new ComponentPlayerResult(new CarbonPlayerVelocity(this.server, player), Component.empty());
}