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

@@ -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();
}
}