feature: basic towny integration (#334)

Co-authored-by: Jason Penilla <[email protected]>
This commit is contained in:
Josh TaylorandJason Penilla authored and GitHub committed 2023-11-09 20:52:10 -07:00
1 parent a902fc56cd
commit b5431e542e
24 files changed
+755 -48

No files matched your search

@@ -35,6 +35,7 @@ import net.draycia.carbon.common.channels.CarbonChannelRegistry;
import net.draycia.carbon.common.command.CarbonCommand;
import net.draycia.carbon.common.command.ExecutionCoordinatorHolder;
import net.draycia.carbon.common.config.ConfigManager;
import net.draycia.carbon.common.integration.Integration;
import net.draycia.carbon.common.listeners.Listener;
import net.draycia.carbon.common.messages.CarbonMessages;
import net.draycia.carbon.common.messaging.MessagingManager;
@@ -122,6 +123,17 @@ public abstract class CarbonChatInternal implements CarbonChat {
TimeUnit.SECONDS
);
// Integration
final Set<Integration> integrations = this.injector().getInstance(Key.get(new TypeLiteral<>() {}));
for (final Integration integration : integrations) {
if (!integration.eligible()) {
continue;
}
integration.register();
}
// Load channels
this.channelRegistry().loadConfigChannels(this.carbonMessages);
@@ -0,0 +1,49 @@
/*
* CarbonChat
*
* Copyright (c) 2023 Josua Parks (Vicarious)
* Contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package net.draycia.carbon.common;
import com.google.inject.AbstractModule;
import com.google.inject.multibindings.Multibinder;
import net.draycia.carbon.common.integration.Integration;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.framework.qual.DefaultQualifier;
@DefaultQualifier(NonNull.class)
public abstract class CarbonPlatformModule extends AbstractModule {
@Override
protected void configure() {
this.configurePlatform();
this.configureIntegrations(
Multibinder.newSetBinder(this.binder(), Integration.class),
Multibinder.newSetBinder(this.binder(), Integration.ConfigMeta.class)
);
}
protected abstract void configurePlatform();
protected void configureIntegrations(
final Multibinder<Integration> integrations,
final Multibinder<Integration.ConfigMeta> configs
) {
}
}
@@ -33,13 +33,16 @@ import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Consumer;
import java.util.function.Supplier;
import net.draycia.carbon.api.channels.ChannelRegistry;
import net.draycia.carbon.api.channels.ChatChannel;
import net.draycia.carbon.api.event.CarbonEventHandler;
@@ -74,8 +77,6 @@ import org.spongepowered.configurate.transformation.ConfigurationTransformation;
@DefaultQualifier(NonNull.class)
public class CarbonChannelRegistry extends ChatListenerInternal implements ChannelRegistry {
private static final String PARTYCHAT_CONF = "partychat.conf";
private final Path configChannelDir;
private final Injector injector;
private final Logger logger;
@@ -83,6 +84,13 @@ public class CarbonChannelRegistry extends ChatListenerInternal implements Chann
private @MonotonicNonNull Key defaultKey;
private final CarbonMessages carbonMessages;
private final CarbonEventHandler eventHandler;
private final Map<String, SpecialHandler<?>> handlers = new HashMap<>();
private record SpecialHandler<T extends ConfigChatChannel>(Class<T> cls, Supplier<T> defaultSupplier) {}
public <T extends ConfigChatChannel> void registerSpecialConfigChannel(final String fileName, final Class<T> type) {
this.handlers.put(fileName, new SpecialHandler<>(type, () -> this.injector.getInstance(type)));
}
private volatile Registry<Key, ChatChannel> channelRegistry = Registry.create();
private final Set<Key> configChannels = ConcurrentHashMap.newKeySet();
@@ -106,6 +114,10 @@ public class CarbonChannelRegistry extends ChatListenerInternal implements Chann
this.carbonMessages = carbonMessages;
this.eventHandler = events;
if (config.primaryConfig().partyChat().enabled) {
this.registerSpecialConfigChannel(PartyChatChannel.FILE_NAME, PartyChatChannel.class);
}
events.subscribe(CarbonReloadEvent.class, -99, true, event -> this.reloadConfigChannels());
}
@@ -204,14 +216,10 @@ public class CarbonChannelRegistry extends ChatListenerInternal implements Chann
this.logger.info("Loading config channels...");
this.defaultKey = this.config.primaryConfig().defaultChannel();
final boolean party = this.config.primaryConfig().partyChat().enabled;
if (party) {
this.saveDefaultPartyConfig();
}
this.saveSpecialDefaults();
List<Path> channelConfigs = FileUtil.listDirectoryEntries(this.configChannelDir, "*.conf");
if (channelConfigs.isEmpty() ||
party && channelConfigs.size() == 1 && channelConfigs.get(0).getFileName().toString().equals(PARTYCHAT_CONF)) {
if (channelConfigs.size() == this.handlers.size()) {
this.saveDefaultChannelConfig();
channelConfigs = FileUtil.listDirectoryEntries(this.configChannelDir, "*.conf");
}
@@ -251,11 +259,29 @@ public class CarbonChannelRegistry extends ChatListenerInternal implements Chann
this.logger.info("Registered channels: [" + channels + "]");
}
private void saveSpecialDefaults() {
for (final Map.Entry<String, SpecialHandler<?>> e : this.handlers.entrySet()) {
final Path configFile = this.configChannelDir.resolve(e.getKey());
if (Files.isRegularFile(configFile)) {
continue;
}
try {
final ConfigChatChannel configChannel = e.getValue().defaultSupplier().get();
final ConfigurationLoader<?> loader = this.config.configurationLoader(FileUtil.mkParentDirs(configFile), ConfigManager.extractHeader(e.getValue().cls()));
final ConfigurationNode node = loader.createNode();
node.set(e.getValue().cls(), configChannel);
loader.save(node);
} catch (final IOException exception) {
throw Exceptions.rethrow(exception);
}
}
}
private void saveDefaultChannelConfig() {
try {
final Path configFile = this.configChannelDir.resolve("global.conf");
final ConfigChatChannel configChannel = this.injector.getInstance(ConfigChatChannel.class);
final ConfigurationLoader<?> loader = this.config.configurationLoader(FileUtil.mkParentDirs(configFile));
final ConfigurationLoader<?> loader = this.config.configurationLoader(FileUtil.mkParentDirs(configFile), ConfigManager.extractHeader(ConfigChatChannel.class));
final ConfigurationNode node = loader.createNode();
node.set(ConfigChatChannel.class, configChannel);
loader.save(node);
@@ -264,30 +290,12 @@ public class CarbonChannelRegistry extends ChatListenerInternal implements Chann
}
}
private void saveDefaultPartyConfig() {
final Path configFile = this.configChannelDir.resolve(PARTYCHAT_CONF);
if (Files.isRegularFile(configFile)) {
return;
}
try {
final ConfigChatChannel configChannel = this.injector.getInstance(PartyChatChannel.class);
final ConfigurationLoader<?> loader = this.config.configurationLoader(FileUtil.mkParentDirs(configFile));
final ConfigurationNode node = loader.createNode();
node.set(PartyChatChannel.class, configChannel);
loader.save(node);
} catch (final IOException exception) {
throw Exceptions.rethrow(exception);
}
}
private @Nullable ChatChannel loadChannel(final Path channelFile) {
final ConfigurationLoader<?> loader = this.config.configurationLoader(channelFile);
try {
final Class<? extends ConfigChatChannel> type = this.config.primaryConfig().partyChat().enabled && channelFile.getFileName().toString().equals(PARTYCHAT_CONF)
? PartyChatChannel.class
: ConfigChatChannel.class;
final @Nullable SpecialHandler<?> special = this.handlers.get(channelFile.getFileName().toString());
final Class<? extends ConfigChatChannel> type = special == null ? ConfigChatChannel.class : special.cls();
final ConfigurationLoader<?> loader = this.config.configurationLoader(channelFile, ConfigManager.extractHeader(type));
final ConfigurationNode loaded = updateNode(loader.load());
final @Nullable ConfigChatChannel channel = loaded.get(type);
if (channel == null) {
@@ -66,7 +66,7 @@ import static net.kyori.adventure.text.Component.text;
@DefaultQualifier(NonNull.class)
public class ConfigChatChannel implements ChatChannel {
private transient @MonotonicNonNull @Inject CarbonServer server;
protected transient @MonotonicNonNull @Inject CarbonServer server;
private transient @MonotonicNonNull @Inject CarbonMessageRenderer renderer;
@Comment("""
@@ -96,7 +96,7 @@ public class ConfigChatChannel implements ChatChannel {
private @Nullable String commandName = null;
private @Nullable List<String> commandAliases = Collections.emptyList();
protected @Nullable List<String> commandAliases = Collections.emptyList();
private transient @Nullable ConfigChannelMessages carbonMessages = null;
@@ -125,7 +125,6 @@ public class ConfigChatChannel implements ChatChannel {
@Override
public boolean shouldRegisterCommands() {
return Objects.requireNonNullElse(this.shouldRegisterCommands, true);
}
@Override
@@ -46,6 +46,8 @@ import org.spongepowered.configurate.objectmapping.ConfigSerializable;
@DefaultQualifier(NonNull.class)
public class PartyChatChannel extends ConfigChatChannel {
public static final String FILE_NAME = "partychat.conf";
private transient @MonotonicNonNull @Inject CarbonMessages messages;
public PartyChatChannel() {
@@ -0,0 +1,36 @@
/*
* CarbonChat
*
* Copyright (c) 2023 Josua Parks (Vicarious)
* Contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package net.draycia.carbon.common.config;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Tells Carbon's config loading logic to use {@link #value()}
* as the header in {@link org.spongepowered.configurate.ConfigurationOptions}
* when loading/saving this type as the root node of a document.
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface ConfigHeader {
String value();
}
@@ -21,14 +21,18 @@ package net.draycia.carbon.common.config;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import io.leangen.geantyref.GenericTypeReflector;
import java.io.IOException;
import java.lang.reflect.Type;
import java.nio.file.Path;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import net.draycia.carbon.api.event.CarbonEventHandler;
import net.draycia.carbon.common.DataDirectory;
import net.draycia.carbon.common.command.CommandSettings;
import net.draycia.carbon.common.event.events.CarbonReloadEvent;
import net.draycia.carbon.common.integration.Integration;
import net.draycia.carbon.common.serialisation.gson.LocaleSerializerConfigurate;
import net.draycia.carbon.common.util.FileUtil;
import net.kyori.adventure.key.Key;
@@ -57,6 +61,7 @@ public final class ConfigManager {
private final Path dataDirectory;
private final LocaleSerializerConfigurate locale;
private final Logger logger;
private final Set<Integration.ConfigMeta> integrations;
private volatile @MonotonicNonNull PrimaryConfig primaryConfig = null;
@@ -65,15 +70,29 @@ public final class ConfigManager {
final CarbonEventHandler events,
@DataDirectory final Path dataDirectory,
final LocaleSerializerConfigurate locale,
final Logger logger
final Logger logger,
final Set<Integration.ConfigMeta> integrations
) {
this.dataDirectory = dataDirectory;
this.locale = locale;
this.logger = logger;
this.integrations = integrations;
events.subscribe(CarbonReloadEvent.class, -100, true, event -> this.reloadPrimaryConfig());
}
public static @Nullable String extractHeader(final Type type) {
if (type instanceof Class<?> cls) {
final @Nullable ConfigHeader h = cls.getAnnotation(ConfigHeader.class);
if (h == null) {
return null;
}
return h.value();
} else {
return extractHeader(GenericTypeReflector.erase(type));
}
}
public void reloadPrimaryConfig() {
this.logger.info("Reloading configuration....");
final @Nullable PrimaryConfig load = this.load(PrimaryConfig.class, PRIMARY_CONFIG_FILE_NAME);
@@ -109,7 +128,7 @@ public final class ConfigManager {
return load.settings();
}
public ConfigurationLoader<?> configurationLoader(final Path file) {
public ConfigurationLoader<?> configurationLoader(final Path file, final @Nullable String header) {
return HoconConfigurationLoader.builder()
.prettyPrinting(true)
.defaultOptions(opts -> {
@@ -117,9 +136,11 @@ public final class ConfigManager {
ConfigurateComponentSerializer.configurate();
return opts.shouldCopyDefaults(true)
.header(header)
.serializers(serializerBuilder ->
serializerBuilder.registerAll(serializer.serializers())
.register(Locale.class, this.locale)
.register(IntegrationConfigContainer.class, new IntegrationConfigContainer.Serializer(this.integrations))
.registerAnnotatedObjects(ObjectMapper.factoryBuilder()
.addProcessor(Comment.class, overrideComments())
.build()));
@@ -145,7 +166,7 @@ public final class ConfigManager {
return null;
}
final var loader = this.configurationLoader(file);
final var loader = this.configurationLoader(file, extractHeader(clazz));
try {
final var node = loader.load();
@@ -0,0 +1,100 @@
/*
* CarbonChat
*
* Copyright (c) 2023 Josua Parks (Vicarious)
* Contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package net.draycia.carbon.common.config;
import java.lang.reflect.Type;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import net.draycia.carbon.common.integration.Integration;
import net.draycia.carbon.common.util.Exceptions;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.checkerframework.framework.qual.DefaultQualifier;
import org.spongepowered.configurate.BasicConfigurationNode;
import org.spongepowered.configurate.ConfigurationNode;
import org.spongepowered.configurate.ConfigurationOptions;
import org.spongepowered.configurate.serialize.SerializationException;
import org.spongepowered.configurate.serialize.TypeSerializer;
@DefaultQualifier(NonNull.class)
public final class IntegrationConfigContainer {
private final Map<String, Object> map = new HashMap<>();
@SuppressWarnings("unchecked")
public <C> C config(final Integration.ConfigMeta meta) {
return (C) Objects.requireNonNull(this.map.get(meta.name()));
}
public static final class Serializer implements TypeSerializer<IntegrationConfigContainer> {
private final List<Integration.ConfigMeta> sections;
public Serializer(final Set<Integration.ConfigMeta> integrations) {
this.sections = integrations.stream()
.sorted(Comparator.comparing(Integration.ConfigMeta::name))
.toList();
}
@Override
public IntegrationConfigContainer deserialize(final Type type, final ConfigurationNode node) throws SerializationException {
final IntegrationConfigContainer container = new IntegrationConfigContainer();
for (final Integration.ConfigMeta section : this.sections) {
final @Nullable Object value = node.node(section.name()).get(section.type());
Objects.requireNonNull(value);
container.map.put(section.name(), value);
}
return container;
}
@Override
public void serialize(final Type type, final @Nullable IntegrationConfigContainer obj, final ConfigurationNode node) throws SerializationException {
Objects.requireNonNull(obj);
for (final Object key : node.childrenMap().keySet()) {
node.removeChild(key);
}
for (final Integration.ConfigMeta section : this.sections) {
node.node(section.name()).set(section.type(), obj.map.get(section.name()));
}
}
@Override
public IntegrationConfigContainer emptyValue(final Type specificType, final ConfigurationOptions options) {
final IntegrationConfigContainer container = new IntegrationConfigContainer();
for (final Integration.ConfigMeta section : this.sections) {
final @Nullable Object value;
try {
value = options.serializers().get(section.type())
.deserialize(section.type(), BasicConfigurationNode.root());
} catch (final Exception e) {
throw Exceptions.rethrow(e);
}
Objects.requireNonNull(value);
container.map.put(section.name(), value);
}
return container;
}
}
}
@@ -98,17 +98,24 @@ public class PrimaryConfig {
private NicknameSettings nicknameSettings = new NicknameSettings();
private PartySettings partyChat = new PartySettings();
@Comment("Settings for integrations with other plugins/mods")
private IntegrationConfigContainer integrations;
@Comment("Whether Carbon should check for updates using the GitHub API on startup.")
private boolean updateChecker = true;
public PartySettings partyChat() {
return this.partyChat;
}
public IntegrationConfigContainer integrations() {
return this.integrations;
}
public NicknameSettings nickname() {
return this.nicknameSettings;
}
@Comment("Whether Carbon should check for updates using the GitHub API on startup.")
private boolean updateChecker = true;
public Locale defaultLocale() {
return this.defaultLocale;
}
@@ -0,0 +1,47 @@
/*
* CarbonChat
*
* Copyright (c) 2023 Josua Parks (Vicarious)
* Contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package net.draycia.carbon.common.integration;
import java.lang.reflect.Type;
import net.draycia.carbon.common.config.ConfigManager;
public interface Integration {
boolean eligible();
void register();
interface ConfigMeta {
Type type();
String name();
record ConfigMetaRecord(Type type, String name) implements ConfigMeta {}
}
static ConfigMeta configMeta(final String name, final Type type) {
return new ConfigMeta.ConfigMetaRecord(type, name);
}
default <C> C config(final ConfigManager configManager, final ConfigMeta meta) {
return configManager.primaryConfig().integrations().config(meta);
}
}
@@ -531,4 +531,19 @@ public interface CarbonMessages {
@Message("pagination.footer")
Component paginationFooter(int page, int pages, Component buttons);
/*
* =============================================================
* ======================= Integrations ========================
* =============================================================
*/
@Message("integrations.towny.cannot_use_alliance_channel")
void cannotUseAllianceChannel(Audience audience);
@Message("integrations.towny.cannot_use_nation_channel")
void cannotUseNationChannel(Audience audience);
@Message("integrations.towny.cannot_use_town_channel")
void cannotUseTownChannel(Audience audience);
}