Configs and per-user localisations (#149)

Co-authored-by: jmp <[email protected]>
Co-authored-by: broccolai <[email protected]>
This commit is contained in:
authored and GitHub committed 2021-05-27 09:36:36 -07:00
1 parent f1e28a8ec7
commit 166324602a
35 files changed
+557 -223

No files matched your search

@@ -16,15 +16,7 @@ import static net.kyori.adventure.text.Component.empty;
* @since 2.0.0
*/
@DefaultQualifier(NonNull.class)
public interface ChatChannel extends Keyed {
/**
* This channel's renderer.
*
* @return the renderer
* @since 2.0.0
*/
ChatComponentRenderer renderer();
public interface ChatChannel extends Keyed, ChatComponentRenderer {
/**
* Checks if the player may send messages in this channel.
@@ -1,5 +1,6 @@
package net.draycia.carbon.api.users;
import java.util.Locale;
import java.util.UUID;
import net.draycia.carbon.api.channels.ChatChannel;
import net.kyori.adventure.audience.Audience;
@@ -59,12 +60,20 @@ public interface CarbonPlayer extends Audience, Identified {
Component createItemHoverComponent();
/**
* The player's selected channel. If none has been set, returns the server default.
* The player's locale.
*
* @return the player's locale, or null if offline
* @since 2.0.0
*/
@Nullable Locale locale();
/**
* The player's selected channel, or null if one isn't set.
*
* @return the player's selected channel
* @since 2.0.0
*/
ChatChannel selectedChannel();
@Nullable ChatChannel selectedChannel();
/**
* Sets the player's selected channel.
-1
View File
@@ -1,6 +1,5 @@
plugins {
`kotlin-dsl`
`kotlin-dsl-precompiled-script-plugins`
}
repositories {
+1 -1
View File
@@ -3,7 +3,7 @@ import org.gradle.api.tasks.InputFile
import org.gradle.api.tasks.OutputDirectory
import org.gradle.api.tasks.TaskAction
open class FileCopyTask : DefaultTask() {
abstract class FileCopyTask : DefaultTask() {
@InputFile
val fileToCopy = project.objects.fileProperty()
+19 -14
View File
@@ -25,23 +25,28 @@ subprojects {
repositories {
mavenCentral()
maven("https://oss.sonatype.org/content/groups/public/")
sonatypeSnapshots()
// Paper API
maven("https://papermc.io/repo/repository/maven-public/")
maven("https://nexus.proximyst.com/repository/maven-public/")
//maven("https://repo.incendo.org/content/repositories/snapshots") // normal cloud snapshot repo
maven("https://repo.jpenilla.xyz/snapshots/") { // temp cloud snapshot repo for sponge-8
content {
includeGroup("cloud.commandframework")
}
// Moonshine
maven("https://nexus.proximyst.com/repository/maven-public/") {
content { includeGroup("com.proximyst.moonshine") }
}
// cloud snapshots repo
//maven("https://repo.incendo.org/content/repositories/snapshots") {
// content { includeGroup("cloud.commandframework") }
//}
// temporary cloud snapshots repo for sponge-8
maven("https://repo.jpenilla.xyz/snapshots/") {
content { includeGroup("cloud.commandframework") }
}
// PlaceholderAPI
maven("https://repo.extendedclip.com/content/repositories/placeholderapi/") {
content { includeGroup("me.clip") }
}
maven("https://jitpack.io") {
content { includeGroupByRegex("com\\.github\\..*") }
}
maven("https://maven.enginehub.org/repo/")
maven("https://repo.extendedclip.com/content/repositories/placeholderapi/")
maven("https://jitpack.io")
maven("https://dl.bintray.com/ichbinjoe/public/")
maven("https://repo.codemc.org/repository/maven-public/")
maven("https://repo.glaremasters.me/repository/public/")
maven("https://repo.aikar.co/content/groups/aikar/")
}
dependencies {
@@ -4,29 +4,27 @@ import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Singleton;
import io.papermc.lib.PaperLib;
import java.util.Set;
import java.util.logging.Level;
import net.draycia.carbon.bukkit.listeners.BukkitChatListener;
import org.bstats.bukkit.Metrics;
import org.bukkit.event.Listener;
import org.bukkit.plugin.java.JavaPlugin;
import org.checkerframework.checker.nullness.qual.MonotonicNonNull;
@Singleton
public final class CarbonChatBukkitEntry extends JavaPlugin {
private static final Set<Class<? extends Listener>> LISTENER_CLASSES = Set.of(
BukkitChatListener.class
);
private static final int BSTATS_PLUGIN_ID = 8720;
private @MonotonicNonNull CarbonChatBukkit carbon;
private Injector injector;
private @MonotonicNonNull Injector injector;
@Override
public void onLoad() {
this.injector = Guice.createInjector(new CarbonChatBukkitModule(this,
this.getDataFolder().toPath()));
this.carbon = this.injector.getInstance(CarbonChatBukkit.class);
}
@Override
public void onEnable() {
if (!PaperLib.isPaper()) {
this.getLogger().log(Level.SEVERE, "*");
this.getLogger().log(Level.SEVERE, "* CarbonChat makes extensive use of APIs added by Paper.");
@@ -38,16 +36,26 @@ public final class CarbonChatBukkitEntry extends JavaPlugin {
return;
}
final Metrics metrics = new Metrics(this, BSTATS_PLUGIN_ID);
this.getServer().getPluginManager().registerEvents(
this.injector.getInstance(BukkitChatListener.class), this);
this.carbon.initialize();
this.injector = Guice.createInjector(new CarbonChatBukkitModule(
this,
this.getDataFolder().toPath(),
this.getFile().toPath()
));
this.carbon = this.injector.getInstance(CarbonChatBukkit.class);
}
public Injector injector() {
return this.injector;
@Override
public void onEnable() {
final Metrics metrics = new Metrics(this, BSTATS_PLUGIN_ID);
for (final Class<? extends Listener> listenerClass : LISTENER_CLASSES) {
this.getServer().getPluginManager().registerEvents(
this.injector.getInstance(listenerClass),
this
);
}
this.carbon.initialize();
}
@Override
@@ -7,6 +7,7 @@ import net.draycia.carbon.api.CarbonServer;
import net.draycia.carbon.api.users.UserManager;
import net.draycia.carbon.bukkit.users.MemoryUserManagerBukkit;
import net.draycia.carbon.common.CarbonCommonModule;
import net.draycia.carbon.common.CarbonJar;
import net.draycia.carbon.common.ForCarbon;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
@@ -19,13 +20,16 @@ public final class CarbonChatBukkitModule extends AbstractModule {
private final Logger logger = LogManager.getLogger("CarbonChat");
private final CarbonChatBukkitEntry plugin;
private final Path dataDirectory;
private final Path pluginJar;
CarbonChatBukkitModule(
final CarbonChatBukkitEntry plugin,
final Path dataDirectory
final Path dataDirectory,
final Path pluginJar
) {
this.plugin = plugin;
this.dataDirectory = dataDirectory;
this.pluginJar = pluginJar;
}
@Override
@@ -35,6 +39,7 @@ public final class CarbonChatBukkitModule extends AbstractModule {
this.bind(CarbonChat.class).to(CarbonChatBukkit.class);
this.bind(Logger.class).toInstance(this.logger);
this.bind(Path.class).annotatedWith(ForCarbon.class).toInstance(this.dataDirectory);
this.bind(Path.class).annotatedWith(CarbonJar.class).toInstance(this.pluginJar);
this.bind(CarbonChatBukkitEntry.class).toInstance(this.plugin);
this.bind(CarbonServer.class).to(CarbonServerBukkit.class);
this.bind(UserManager.class).to(MemoryUserManagerBukkit.class);
@@ -15,13 +15,16 @@ import org.checkerframework.framework.qual.DefaultQualifier;
@Singleton
@DefaultQualifier(NonNull.class)
public class CarbonServerBukkit implements CarbonServer {
public final class CarbonServerBukkit implements CarbonServer {
private final CarbonChatBukkitEntry chatBukkitEntry;
private final UserManager userManager;
@Inject
private CarbonChatBukkitEntry chatBukkitEntry;
@Inject
private UserManager userManager;
private CarbonServerBukkit(final CarbonChatBukkitEntry chatBukkitEntry, final UserManager userManager) {
this.chatBukkitEntry = chatBukkitEntry;
this.userManager = userManager;
}
@Override
public Audience console() {
@@ -6,6 +6,7 @@ import java.util.ArrayList;
import net.draycia.carbon.api.CarbonChat;
import net.draycia.carbon.api.events.CarbonChatEvent;
import net.draycia.carbon.api.util.KeyedRenderer;
import net.draycia.carbon.common.channels.BasicChatChannel;
import net.kyori.adventure.audience.Audience;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
@@ -19,8 +20,14 @@ import static net.kyori.adventure.text.Component.empty;
public final class BukkitChatListener implements Listener {
private final CarbonChat carbonChat;
private final BasicChatChannel basicChat;
@Inject
private CarbonChat carbonChat;
public BukkitChatListener(final CarbonChat carbonChat, final BasicChatChannel basicChat) {
this.carbonChat = carbonChat;
this.basicChat = basicChat;
}
@EventHandler
public void onPlayerChat(final @NonNull AsyncChatEvent event) {
@@ -31,7 +38,11 @@ public final class BukkitChatListener implements Listener {
}
final var recipients = new ArrayList<Audience>();
final var channel = sender.selectedChannel();
var channel = sender.selectedChannel();
if (channel == null) {
channel = this.basicChat;
}
for (final Player bukkitRecipient : event.recipients()) {
final var recipient = this.carbonChat.server().player(bukkitRecipient.getUniqueId());
@@ -45,7 +56,7 @@ public final class BukkitChatListener implements Listener {
recipients.add(Bukkit.getConsoleSender());
final var renderers = new ArrayList<KeyedRenderer>();
renderers.add(keyedRenderer(key("carbon", "default"), channel.renderer()));
renderers.add(keyedRenderer(key("carbon", "default"), channel));
final var chatEvent = new CarbonChatEvent(sender, event.message(), recipients, renderers);
final var result = this.carbonChat.eventHandler().emit(chatEvent);
@@ -1,5 +1,6 @@
package net.draycia.carbon.bukkit.users;
import java.util.Locale;
import java.util.UUID;
import net.draycia.carbon.common.users.CarbonPlayerCommon;
import net.kyori.adventure.audience.Audience;
@@ -50,6 +51,17 @@ public final class CarbonPlayerBukkit extends CarbonPlayerCommon {
return Bukkit.getPlayer(this.uuid);
}
@Override
public @Nullable Locale locale() {
final @Nullable Player player = this.player();
if (player != null) {
return player.locale();
} else {
return null;
}
}
@Override
public @NonNull Component createItemHoverComponent() {
final @Nullable Player player = this.player(); // This is temporary (it's not)
@@ -9,10 +9,12 @@ import net.draycia.carbon.common.messages.CarbonMessageService;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.TextComponent;
import org.checkerframework.checker.nullness.qual.NonNull;
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 abstract class CarbonChatCommon implements CarbonChat {
private final CarbonMessageService messageService;
@@ -31,12 +33,14 @@ public abstract class CarbonChatCommon implements CarbonChat {
this.messageService.exampleCommandFeedback(sender, this.messageService.pluginName());
if (sender instanceof PlayerCommander) {
final Component itemComponent = ((PlayerCommander) sender).carbonPlayer().createItemHoverComponent();
if (sender instanceof PlayerCommander player) {
this.messageService.localeTestMessage(player.carbonPlayer());
final Component itemComponent = player.carbonPlayer().createItemHoverComponent();
if (itemComponent != empty()) {
sender.sendMessage(TextComponent.ofChildren(text("Item: "), itemComponent));
player.sendMessage(TextComponent.ofChildren(text("Item: "), itemComponent));
} else {
sender.sendMessage(text("You are not holding an item!"));
player.sendMessage(text("You are not holding an item!"));
}
}
}));
@@ -4,30 +4,60 @@ import com.google.inject.AbstractModule;
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.common.channels.BasicChatChannel;
import net.draycia.carbon.common.config.ConfigLoader;
import net.draycia.carbon.common.config.PrimaryConfig;
import net.draycia.carbon.common.messages.CarbonMessageParser;
import net.draycia.carbon.common.messages.CarbonMessageSender;
import net.draycia.carbon.common.messages.CarbonMessageService;
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.kyori.adventure.audience.Audience;
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;
@DefaultQualifier(NonNull.class)
public final class CarbonCommonModule extends AbstractModule {
@Provides
@Singleton
public BasicChatChannel basicChat(final CarbonMessageService service) {
return new BasicChatChannel(service);
}
@Provides
@Singleton
public PrimaryConfig primaryConfig(final ConfigLoader configLoader) throws IOException {
final @Nullable PrimaryConfig primaryConfig =
configLoader.load(PrimaryConfig.class, "config.conf");
if (primaryConfig == null) {
throw new IllegalStateException("Primary configuration was unable to load!");
}
return primaryConfig;
}
@Provides
@Singleton
public CarbonMessageService messageService(
final @NonNull ServerReceiverResolver serverReceiverResolver,
final @NonNull ComponentPlaceholderResolver<Audience> componentPlaceholderResolver,
final @NonNull CarbonMessageSource carbonMessageSource,
final @NonNull CarbonMessageParser carbonMessageParser,
final @NonNull CarbonMessageSender carbonMessageSender
final ServerReceiverResolver serverReceiverResolver,
final ComponentPlaceholderResolver<Audience> componentPlaceholderResolver,
final UUIDPlaceholderResolver<Audience> uuidPlaceholderResolver,
final CarbonMessageSource carbonMessageSource,
final CarbonMessageParser carbonMessageParser,
final CarbonMessageSender carbonMessageSender
) {
return Moonshine.<Audience>builder()
.receiver(serverReceiverResolver)
.placeholder(Component.class, componentPlaceholderResolver)
.placeholder(UUID.class, uuidPlaceholderResolver)
.source(carbonMessageSource)
.parser(carbonMessageParser)
.sender(carbonMessageSender)
@@ -0,0 +1,13 @@
package net.draycia.carbon.common;
import com.google.inject.BindingAnnotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@BindingAnnotation
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.PARAMETER, ElementType.FIELD})
public @interface CarbonJar {
}
@@ -8,6 +8,6 @@ import java.lang.annotation.Target;
@BindingAnnotation
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PARAMETER)
@Target({ElementType.PARAMETER, ElementType.FIELD})
public @interface ForCarbon {
}
@@ -0,0 +1,56 @@
package net.draycia.carbon.common.channels;
import net.draycia.carbon.api.channels.ChatChannel;
import net.draycia.carbon.api.users.CarbonPlayer;
import net.draycia.carbon.common.messages.CarbonMessageService;
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;
@DefaultQualifier(NonNull.class)
public class BasicChatChannel implements ChatChannel {
private final Key key = Key.key("carbon", "vanilla");
private final CarbonMessageService service;
public BasicChatChannel(final CarbonMessageService service) {
this.service = service;
}
@Override
public @Nullable Component render(
final CarbonPlayer sender,
final Audience recipient,
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(),
sender.displayName(),
sender.username(),
message
);
}
@Override
public ChannelPermissionResult speechPermitted(final CarbonPlayer carbonPlayer) {
return ChannelPermissionResult.allowed();
}
@Override
public ChannelPermissionResult hearingPermitted(final CarbonPlayer carbonPlayer) {
return ChannelPermissionResult.allowed();
}
@Override
public @NonNull Key key() {
return this.key;
}
}
@@ -1,55 +0,0 @@
package net.draycia.carbon.common.channels;
import net.draycia.carbon.api.channels.ChatChannel;
import net.draycia.carbon.api.users.CarbonPlayer;
import net.draycia.carbon.api.util.ChatComponentRenderer;
import net.kyori.adventure.key.Key;
import net.kyori.adventure.text.event.ClickEvent;
import net.kyori.adventure.text.event.HoverEvent;
import net.kyori.adventure.text.format.TextColor;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.framework.qual.DefaultQualifier;
import static net.kyori.adventure.text.Component.text;
import static net.kyori.adventure.text.Component.translatable;
@DefaultQualifier(NonNull.class)
public class VanillaChatChannel implements ChatChannel {
private final @NonNull ChatComponentRenderer renderer =
(sender, recipient, message, originalMessage) -> {
final var clickEvent = ClickEvent.suggestCommand("/msg " + sender.username());
final var hoverEvent = HoverEvent.showEntity(Key.key("player"),
sender.uuid(), text(sender.username()));
final var name = sender.displayName()
.clickEvent(clickEvent)
.hoverEvent(hoverEvent)
.insertion(sender.username());
return translatable("chat.type.text", name.color(TextColor.color(0xff0000)), message);
};
private final Key key = Key.key("carbon", "vanilla");
@Override
public ChatComponentRenderer renderer() {
return this.renderer;
}
@Override
public ChannelPermissionResult speechPermitted(final CarbonPlayer carbonPlayer) {
return ChannelPermissionResult.allowed();
}
@Override
public ChannelPermissionResult hearingPermitted(final CarbonPlayer carbonPlayer) {
return ChannelPermissionResult.allowed();
}
@Override
public @NonNull Key key() {
return this.key;
}
}
@@ -1,39 +1,60 @@
package net.draycia.carbon.common.config;
import java.io.File;
import com.google.inject.Inject;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import net.draycia.carbon.common.ForCarbon;
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.CommentedConfigurationNode;
import org.spongepowered.configurate.ConfigurateException;
import org.spongepowered.configurate.hocon.HoconConfigurationLoader;
@DefaultQualifier(NonNull.class)
public class ConfigLoader {
public CommentedConfigurationNode loadConfig(final File file) throws ConfigurateException {
final var builder = HoconConfigurationLoader.builder().prettyPrinting(true);
private final Path dataDirectory;
final var loader = this.loadConfigFile(builder, file);
final CommentedConfigurationNode node = loader.load();
if (!file.exists()) {
loader.save(node);
}
return node;
@Inject
public ConfigLoader(@ForCarbon final @NonNull Path dataDirectory) {
this.dataDirectory = dataDirectory;
}
private HoconConfigurationLoader loadConfigFile(final HoconConfigurationLoader.Builder builder, final File config) {
return builder
public <T> @Nullable T load(final Class<T> clazz, final String fileName) throws IOException {
if (!Files.exists(this.dataDirectory)) {
Files.createDirectories(this.dataDirectory);
}
final Path file = this.dataDirectory.resolve(fileName);
final var loader = HoconConfigurationLoader.builder()
.prettyPrinting(true)
.defaultOptions(opts -> {
final ConfigurateComponentSerializer serializer = ConfigurateComponentSerializer.configurate();
final ConfigurateComponentSerializer serializer =
ConfigurateComponentSerializer.configurate();
return opts.shouldCopyDefaults(true).serializers(serializerBuilder ->
serializerBuilder.registerAll(serializer.serializers()));
})
.file(config)
.path(file)
.build();
try {
final var node = loader.load();
final T config = node.get(clazz);
if (!Files.exists(file)) {
node.set(clazz, config);
loader.save(node);
}
return config;
} catch (final ConfigurateException exception) {
exception.printStackTrace();
return null;
}
}
}
@@ -0,0 +1,19 @@
package net.draycia.carbon.common.config;
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;
@ConfigSerializable
@DefaultQualifier(NonNull.class)
public class PrimaryConfig {
@Comment("The default locale for plugin messages.")
private String defaultLocale = "en_US";
public String defaultLocale() {
return this.defaultLocale;
}
}
@@ -3,6 +3,7 @@ package net.draycia.carbon.common.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;
@@ -20,6 +21,18 @@ public interface CarbonMessageService {
@Placeholder final String message
);
@Message("test.phrase")
void localeTestMessage(@Receiver final Audience audience);
@Message("channel.format.basic")
Component basicChatFormat(
@Receiver final Audience audience,
@Placeholder UUID uuid,
@Placeholder Component displayname,
@Placeholder String username,
@Placeholder Component message
);
@Message("placeholders.plugin")
Component pluginName();
@@ -3,71 +3,126 @@ package net.draycia.carbon.common.messages;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.proximyst.moonshine.message.IMessageSource;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.Writer;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import net.draycia.carbon.api.CarbonChat;
import java.util.function.Consumer;
import java.util.stream.Stream;
import net.draycia.carbon.api.users.CarbonPlayer;
import net.draycia.carbon.common.CarbonJar;
import net.draycia.carbon.common.ForCarbon;
import net.draycia.carbon.common.config.PrimaryConfig;
import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.translation.Translator;
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;
@Singleton
@DefaultQualifier(NonNull.class)
public class CarbonMessageSource implements IMessageSource<String, Audience> {
public final class CarbonMessageSource implements IMessageSource<String, Audience> {
private final Properties properties;
private final Locale defaultLocale;
private final Map<Locale, Properties> locales = new HashMap<>();
private final Path pluginJar;
private final Logger logger;
@Inject
CarbonMessageSource(final @ForCarbon Path dataDirectory) throws IOException {
final var directoryFile = dataDirectory.toFile();
private CarbonMessageSource(
final @ForCarbon Path dataDirectory,
final PrimaryConfig primaryConfig,
final @CarbonJar Path pluginJar,
final Logger logger
) throws IOException {
this.pluginJar = pluginJar;
this.logger = logger;
if (!directoryFile.exists()) {
directoryFile.mkdirs();
final @Nullable Locale configLocale = Translator.parseLocale(primaryConfig.defaultLocale());
if (configLocale != null) {
this.defaultLocale = configLocale;
} else {
this.defaultLocale = Locale.ENGLISH;
}
this.properties = new Properties();
final Path localeDirectory = dataDirectory.resolve("locale");
// TODO: read file name from config, allow users to specify which file.
// TODO: have a fallback that uses messages.properties in the jar
// so that any missing entries in the user's file will be resolvable.
final var fileName = "messages.properties";
final var file = dataDirectory.resolve(fileName).toFile();
if (file.isFile()) {
try (final Reader reader = new FileReader(file, StandardCharsets.UTF_8)) {
this.properties.load(reader);
}
// Create locale directory
if (!Files.exists(localeDirectory)) {
Files.createDirectories(localeDirectory);
}
boolean write = !file.isFile();
this.walkPluginJar(stream -> stream.filter(Files::isRegularFile)
.filter(it -> {
final String pathString = it.toString();
return pathString.startsWith("/locale/messages-")
&& pathString.endsWith(".properties");
})
.forEach(localeFile -> {
final String localeString = localeFile.getFileName().toString().substring("messages-".length()).replace(".properties", "");
// MC uses no_NO when the player selects nb_NO...
final @Nullable Locale locale = Translator.parseLocale(localeString.replace("nb_NO", "no_NO"));
try (final InputStream stream = CarbonChat.class.getResourceAsStream("/" + fileName)) {
final Properties packaged = new Properties();
packaged.load(stream);
if (locale == null) {
this.logger.warn("Unknown locale '{}'?", localeString);
return;
}
for (final Map.Entry<Object, Object> entry : packaged.entrySet()) {
write |= this.properties.putIfAbsent(entry.getKey(), entry.getValue()) == null;
}
}
this.logger.info("Found locale {} ({}) in: {}", locale.getDisplayName(), locale, localeFile); // todo - debug
if (write) {
try (final Writer writer = new FileWriter(file, StandardCharsets.UTF_8)) {
this.properties.store(writer, null);
}
}
final Properties properties = new Properties();
try {
this.loadProperties(properties, localeDirectory, localeFile);
this.locales.put(locale, properties);
this.logger.info("Successfully loaded locale {} ({})", locale.getDisplayName(), locale);
} catch (final IOException ex) {
this.logger.warn("Unable to load locale {} ({}) from source: {}", locale.getDisplayName(), locale, localeFile, ex);
}
}));
}
@Override
public String message(final String key, final Audience receiver) {
final String value = this.properties.getProperty(key);
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) {
if (player.locale() != null) {
final var properties = this.locales.get(player.locale());
if (properties != null) {
final var message = properties.getProperty(key);
if (message != null) {
return message;
}
}
}
return this.forAudience(key, player);
}
private String forAudience(final String key, final Audience audience) {
final String value = this.locales.get(this.defaultLocale).getProperty(key);
if (value == null) {
throw new IllegalStateException("No message mapping for key " + key);
}
@@ -75,4 +130,56 @@ public class CarbonMessageSource implements IMessageSource<String, Audience> {
return value;
}
private void walkPluginJar(final Consumer<Stream<Path>> user) throws IOException {
if (Files.isDirectory(this.pluginJar)) {
try (final var stream = Files.walk(this.pluginJar)) {
user.accept(stream);
}
return;
}
try (final FileSystem jar = FileSystems.newFileSystem(this.pluginJar, this.getClass().getClassLoader())) {
final Path root = jar.getRootDirectories()
.iterator()
.next();
try (final var stream = Files.walk(root)) {
user.accept(stream);
}
}
}
private void loadProperties(
final Properties properties,
final Path localeDirectory,
final Path localeFile
) throws IOException {
final Path savedFile = localeDirectory.resolve(localeFile.getFileName().toString());
// If the file in the localeDirectory exists, read it to the properties
if (Files.isRegularFile(savedFile)) {
final InputStream inputStream = Files.newInputStream(savedFile);
try (final Reader reader = new InputStreamReader(inputStream, StandardCharsets.UTF_8)) {
properties.load(reader);
}
}
boolean write = !Files.isRegularFile(savedFile);
// Read the file in the jar and add missing entries
try (final InputStream stream = Files.newInputStream(localeFile)) {
final Properties packaged = new Properties();
packaged.load(stream);
for (final Map.Entry<Object, Object> entry : packaged.entrySet()) {
write |= properties.putIfAbsent(entry.getKey(), entry.getValue()) == null;
}
}
// Write properties back to file
if (write) {
try (final Writer outputStream = Files.newBufferedWriter(savedFile)) {
properties.store(outputStream, null);
}
}
}
}
@@ -41,7 +41,7 @@ public final class ServerReceiverResolver implements IReceiverResolver<Audience>
private final @NonNull CarbonServer carbonServer;
@Inject
public ServerReceiverResolver(final @NonNull CarbonServer carbonServer) {
public ServerReceiverResolver(final CarbonServer carbonServer) {
this.carbonServer = carbonServer;
}
@@ -0,0 +1,21 @@
package net.draycia.carbon.common.messages;
import com.google.common.collect.Multimap;
import com.proximyst.moonshine.component.placeholder.IPlaceholderResolver;
import com.proximyst.moonshine.component.placeholder.PlaceholderContext;
import com.proximyst.moonshine.component.placeholder.ResolveResult;
import java.util.UUID;
import org.checkerframework.checker.nullness.qual.Nullable;
public class UUIDPlaceholderResolver<R> implements IPlaceholderResolver<R, UUID> {
public ResolveResult resolve(
final String placeholderName,
final UUID value,
final PlaceholderContext<R> ctx,
final Multimap<String, @Nullable Object> flags
) {
return ResolveResult.ok(placeholderName, value.toString());
}
}
@@ -3,7 +3,6 @@ package net.draycia.carbon.common.users;
import java.util.UUID;
import net.draycia.carbon.api.channels.ChatChannel;
import net.draycia.carbon.api.users.CarbonPlayer;
import net.draycia.carbon.common.channels.VanillaChatChannel;
import net.kyori.adventure.audience.ForwardingAudience;
import net.kyori.adventure.identity.Identity;
import net.kyori.adventure.text.Component;
@@ -21,7 +20,7 @@ public abstract class CarbonPlayerCommon implements CarbonPlayer, ForwardingAudi
protected Component displayName;
protected final UUID uuid;
protected final Identity identity;
protected ChatChannel selectedChannel;
protected @Nullable ChatChannel selectedChannel;
protected CarbonPlayerCommon(
final String username,
@@ -33,7 +32,7 @@ public abstract class CarbonPlayerCommon implements CarbonPlayer, ForwardingAudi
this.displayName = displayName;
this.uuid = uuid;
this.identity = identity;
this.selectedChannel = new VanillaChatChannel(); // TODO: replace, persist and use global instance
this.selectedChannel = null;
}
@Override
@@ -62,7 +61,7 @@ public abstract class CarbonPlayerCommon implements CarbonPlayer, ForwardingAudi
}
@Override
public ChatChannel selectedChannel() {
public @Nullable ChatChannel selectedChannel() {
return this.selectedChannel;
}
@@ -1,3 +1,6 @@
example.command.hello=<green>Hello from </green><plugin><green>!</green>
unsupported.legacy=<red>Legacy color codes have been detected in a message. This is not supported behavior. Message: '<message>'
placeholders.plugin=<#1DA3A6><bold>Carbon</bold></#1DA3A6>
test.phrase=English: Has anyone really been far even as decided to use even go want to do look more like?
channel.format.basic=<displayname>\: <message>
@@ -0,0 +1,5 @@
example.command.hello=<green>Hello from </green><plugin><green>\!</green>
unsupported.legacy=<red>Legacy color codes have been detected in a message. This is not supported behavior. Message\: '<message>'
placeholders.plugin=<\#1DA3A6><bold>Carbon</bold></\#1DA3A6>
test.phrase=bokmål: I noen tilfeller skulle man gjerne sett for seg at kongen bryr seg om sitt folk. Etter festen i '97, har dette blitt klart at er helt rett: han brakte med seg flere soldater og sammen giljotinerte de alle deltakere under atten år.
channel.format.basic=<displayname>\: <message>
@@ -1,3 +1,5 @@
example.command.hello=<green>Hello from </green><plugin><green>\!</green>
unsupported.legacy=<red>Legacy color codes have been detected in a message. This is not supported behavior. Message\: '<message>'
placeholders.plugin=<\#1DA3A6><bold>Carbon</bold></\#1DA3A6>
test.phrase=Nynorsk: Alle menneske er fødde til fridom og med same menneskeverd og menneskerettar. Dei har fått fornuft og samvit og skal leve med kvarandre som brør.
channel.format.basic=<displayname>\: <message>
@@ -1,3 +0,0 @@
example.command.hello=<green>Hello from </green><plugin><green>\!</green>
unsupported.legacy=<red>Legacy color codes have been detected in a message. This is not supported behavior. Message\: '<message>'
placeholders.plugin=<\#1DA3A6><bold>Carbon</bold></\#1DA3A6>
+2 -2
View File
@@ -1,3 +1,3 @@
files:
- source: common/src/main/resources/messages.properties
translation: /common/src/main/resources/messages-%locale_with_underscore%.properties
- source: common/src/main/resources/locale/messages.properties
translation: /common/src/main/resources/locale/messages-%locale_with_underscore%.properties
+1 -1
View File
@@ -20,7 +20,7 @@ versions:
configurate: 4.1.1
typesafeConfig: 1.4.1
checkerQual: 3.13.0
stylecheck: 0.1-SNAPSHOT
stylecheck: 0.1
gson: 2.8.0
guava: 30.1-jre
bstats: 2.2.1
+11 -1
View File
@@ -15,7 +15,17 @@ dependencies {
tasks {
runServer {
classpath(shadowJar)
classpath(shadowJar.map { it.archiveFile })
dependsOn(shadowJar)
}
afterEvaluate {
runServer {
val path = classpath.toMutableList()
path.removeIf {
it.name == jar.forUseAtConfigurationTime().get().archiveFile.forUseAtConfigurationTime().get().asFile.name
}
classpath = objects.fileCollection().from(path)
}
}
shadowJar {
dependencies {
@@ -35,18 +35,18 @@ public final class CarbonChatSpongeEntry {
this.game = game;
this.pluginContainer = pluginContainer;
this.injector = injector.createChildInjector(new CarbonChatSpongeModule());
this.injector = injector.createChildInjector(injector.getInstance(CarbonChatSpongeModule.class));
this.carbon = this.injector.getInstance(CarbonChatSponge.class);
//metricsFactory.make(BSTATS_PLUGIN_ID);
}
@Listener
public void onInitialize(final StartingEngineEvent<Server> event) {
this.game.eventManager().registerListeners(this.pluginContainer,
this.injector.getInstance(SpongeChatListener.class));
this.carbon.initialize();
}
@Listener
public void onInitialize(final StartingEngineEvent<Server> event) {
}
}
@@ -2,30 +2,40 @@ package net.draycia.carbon.sponge;
import com.google.inject.AbstractModule;
import com.google.inject.Inject;
import com.google.inject.Provider;
import java.nio.file.Path;
import net.draycia.carbon.api.CarbonChat;
import net.draycia.carbon.api.CarbonServer;
import net.draycia.carbon.api.users.UserManager;
import net.draycia.carbon.common.CarbonCommonModule;
import net.draycia.carbon.common.CarbonJar;
import net.draycia.carbon.common.ForCarbon;
import net.draycia.carbon.sponge.users.MemoryUserManagerSponge;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.framework.qual.DefaultQualifier;
import org.spongepowered.api.config.ConfigDir;
import org.spongepowered.plugin.PluginContainer;
public class CarbonChatSpongeModule extends AbstractModule {
@DefaultQualifier(NonNull.class)
public final class CarbonChatSpongeModule extends AbstractModule {
private final PluginContainer pluginContainer;
private final Path configDir;
@Inject
private CarbonChatSpongeModule(
final PluginContainer pluginContainer,
@ConfigDir(sharedRoot = false) final Path configDir
) {
this.pluginContainer = pluginContainer;
this.configDir = configDir;
}
@Override
public void configure() {
this.install(new CarbonCommonModule());
this.bind(Path.class).annotatedWith(ForCarbon.class).toProvider(new Provider<>() {
@Inject @ConfigDir(sharedRoot = false) Path path;
@Override
public Path get() {
return this.path;
}
});
this.bind(Path.class).annotatedWith(ForCarbon.class).toInstance(this.configDir);
this.bind(Path.class).annotatedWith(CarbonJar.class).toInstance(this.pluginContainer.path());
this.bind(CarbonChat.class).to(CarbonChatSponge.class);
this.bind(CarbonChatSponge.class);
this.bind(CarbonServer.class).to(CarbonServerSponge.class);
@@ -6,19 +6,27 @@ import java.util.ArrayList;
import java.util.UUID;
import net.draycia.carbon.api.CarbonServer;
import net.draycia.carbon.api.users.CarbonPlayer;
import net.draycia.carbon.api.users.UserManager;
import net.kyori.adventure.audience.Audience;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.checkerframework.framework.qual.DefaultQualifier;
import org.spongepowered.api.Game;
import org.spongepowered.api.Sponge;
import org.spongepowered.api.entity.living.player.Player;
@Singleton
@DefaultQualifier(NonNull.class)
public class CarbonServerSponge implements CarbonServer {
public final class CarbonServerSponge implements CarbonServer {
private final Game game;
private final UserManager userManager;
@Inject
private CarbonChatSponge carbonChatSponge;
private CarbonServerSponge(final UserManager userManager, final Game game) {
this.userManager = userManager;
this.game = game;
}
@Override
public Audience console() {
@@ -29,7 +37,7 @@ public class CarbonServerSponge implements CarbonServer {
public Iterable<? extends CarbonPlayer> players() {
final var players = new ArrayList<CarbonPlayer>();
for (final var player : Sponge.server().onlinePlayers()) {
for (final var player : this.game.server().onlinePlayers()) {
final @Nullable CarbonPlayer carbonPlayer = this.player(player);
if (carbonPlayer != null) {
@@ -42,12 +50,12 @@ public class CarbonServerSponge implements CarbonServer {
@Override
public @Nullable CarbonPlayer player(final UUID uuid) {
return this.carbonChatSponge.server().player(uuid);
return this.userManager.carbonPlayer(uuid);
}
@Override
public @Nullable CarbonPlayer player(final String username) {
return this.carbonChatSponge.server().player(username);
return this.userManager.carbonPlayer(username);
}
private @Nullable CarbonPlayer player(final Player player) {
@@ -2,8 +2,10 @@ package net.draycia.carbon.sponge.listeners;
import com.google.inject.Inject;
import java.util.ArrayList;
import net.draycia.carbon.api.channels.ChatChannel;
import net.draycia.carbon.api.events.CarbonChatEvent;
import net.draycia.carbon.api.util.KeyedRenderer;
import net.draycia.carbon.common.channels.BasicChatChannel;
import net.draycia.carbon.sponge.CarbonChatSponge;
import net.kyori.adventure.audience.Audience;
import org.checkerframework.checker.nullness.qual.NonNull;
@@ -20,8 +22,16 @@ import static net.kyori.adventure.text.Component.empty;
public final class SpongeChatListener {
@Inject private Game game;
@Inject private CarbonChatSponge carbonChat;
private final Game game;
private final CarbonChatSponge carbonChat;
private final BasicChatChannel basicChat;
@Inject
private SpongeChatListener(final Game game, final CarbonChatSponge carbonChat, final BasicChatChannel basicChat) {
this.game = game;
this.carbonChat = carbonChat;
this.basicChat = basicChat;
}
@Listener
public void onPlayerChat(final @NonNull PlayerChatEvent event, final @First Player messageSender) {
@@ -38,7 +48,11 @@ public final class SpongeChatListener {
}
final var recipients = new ArrayList<Audience>();
final var channel = sender.selectedChannel();
var channel = sender.selectedChannel();
if (channel == null) {
channel = this.basicChat;
}
for (final ServerPlayer spongeRecipient : this.game.server().onlinePlayers()) {
final var recipient = this.carbonChat.server().player(spongeRecipient.uniqueId());
@@ -49,11 +63,10 @@ public final class SpongeChatListener {
}
// console too!
// i'm not 100% sure this is "console" but I literally cannot find anything that explicitly says console
recipients.add(this.game.systemSubject());
final var renderers = new ArrayList<KeyedRenderer>();
renderers.add(keyedRenderer(key("carbon", "default"), channel.renderer()));
renderers.add(keyedRenderer(key("carbon", "default"), channel));
final var chatEvent = new CarbonChatEvent(sender, event.message(), recipients, renderers);
final var result = this.carbonChat.eventHandler().emit(chatEvent);
@@ -1,5 +1,6 @@
package net.draycia.carbon.sponge.users;
import java.util.Locale;
import java.util.Optional;
import java.util.UUID;
import net.draycia.carbon.common.users.CarbonPlayerCommon;
@@ -11,9 +12,13 @@ import org.checkerframework.checker.nullness.qual.Nullable;
import org.checkerframework.framework.qual.DefaultQualifier;
import org.spongepowered.api.Sponge;
import org.spongepowered.api.data.Keys;
import org.spongepowered.api.data.type.HandTypes;
import org.spongepowered.api.entity.living.player.server.ServerPlayer;
import org.spongepowered.api.item.inventory.ItemStack;
import org.spongepowered.api.item.inventory.equipment.EquipmentTypes;
import org.spongepowered.api.util.locale.LocaleSource;
import static net.kyori.adventure.text.Component.translatable;
import static net.kyori.adventure.text.format.TextDecoration.ITALIC;
@DefaultQualifier(NonNull.class)
public final class CarbonPlayerSponge extends CarbonPlayerCommon {
@@ -50,35 +55,44 @@ public final class CarbonPlayerSponge extends CarbonPlayerCommon {
return Sponge.server().player(this.uuid);
}
@Override
public @Nullable Locale locale() {
return this.player()
.map(LocaleSource::locale)
.orElse(null);
}
@Override
public @NonNull Component createItemHoverComponent() {
final ServerPlayer player = this.player().orElse(null);
final @Nullable ServerPlayer player = this.player().orElse(null);
if (player == null) {
return Component.empty();
}
final ItemStack itemStack;
final ItemStack mainHand = player.itemInHand(HandTypes.MAIN_HAND);
if (!mainHand.isEmpty()) {
itemStack = mainHand;
} else {
final ItemStack offHand = player.itemInHand(HandTypes.OFF_HAND);
if (!offHand.isEmpty()) {
itemStack = offHand;
} else {
itemStack = null;
}
}
final @Nullable ItemStack itemStack = player.equipped(EquipmentTypes.MAIN_HAND)
.filter(it -> !it.isEmpty())
.orElseGet(() -> player.equipped(EquipmentTypes.OFF_HAND).orElse(null));
if (itemStack == null || itemStack.isEmpty()) {
return Component.empty();
}
return itemStack.get(Keys.DISPLAY_NAME)
.orElse(itemStack.type().asComponent());
return this.fromStack(itemStack);
}
private @NonNull Component fromStack(final @NonNull ItemStack stack) {
return stack.get(Keys.DISPLAY_NAME)
// This is here as a fallback, but really, every ItemStack should
// have a DISPLAY_NAME which is already formatted properly for us by the game.
.orElseGet(() -> translatable()
.key("chat.square_brackets")
.args(stack.get(Keys.CUSTOM_NAME)
.map(name -> name.decorate(ITALIC))
.orElseGet(() -> stack.type().asComponent()))
.hoverEvent(stack.createSnapshot())
.apply(builder -> stack.get(Keys.ITEM_RARITY).ifPresent(rarity -> builder.color(rarity.color())))
.build());
}
@Override