mirror of
https://github.com/darksaid98/Carbon.git
synced 2026-12-01 22:15:08 +00:00
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:
56 files changed
+1624
-574
No files matched your search
@@ -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;
|
||||
}
|
||||
|
||||
}
|
||||
+22
@@ -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
|
||||
);
|
||||
|
||||
}
|
||||
+78
@@ -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");
|
||||
|
||||
|
||||
+51
@@ -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;
|
||||
}
|
||||
|
||||
}
|
||||
+43
@@ -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;
|
||||
}
|
||||
|
||||
}
|
||||
+29
@@ -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());
|
||||
}
|
||||
|
||||
}
|
||||
+24
@@ -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()));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
Reference in new issue
Block a user