Merge pull request #233 from Hexaoxide/user-rewrite

This commit is contained in:
Josua Parks authored and GitHub committed 2023-03-26 12:05:42 -07:00
commit 29d4744254
98 files changed
+2746 -1894

No files matched your search

@@ -23,6 +23,7 @@ import java.nio.file.Path;
import java.util.UUID;
import net.draycia.carbon.api.channels.ChannelRegistry;
import net.draycia.carbon.api.events.CarbonEventHandler;
import net.draycia.carbon.api.users.UserManager;
import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.text.Component;
import net.kyori.moonshine.message.IMessageRenderer;
@@ -91,6 +92,14 @@ public interface CarbonChat {
*/
CarbonServer server();
/**
* The user manager.
*
* @return the user manager
* @since 2.1.0
*/
UserManager<?> userManager();
/**
* The registry that channels are registered to.
*
@@ -20,13 +20,10 @@
package net.draycia.carbon.api;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
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;
/**
@@ -56,27 +53,11 @@ public interface CarbonServer extends Audience {
/**
* Manager used to load/obtain and save {@link CarbonPlayer CarbonPlayers}.
*
* @deprecated Use {@link CarbonChat#userManager} (internal code: inject the UserManager)
* @return the user manager
* @since 2.1.0
*/
@Deprecated(forRemoval = true)
UserManager<? extends CarbonPlayer> userManager();
/**
* Obtains the desired user's UUID.
*
* @param username the user's username
* @return the user's UUID
* @since 2.0.0
*/
CompletableFuture<@Nullable UUID> resolveUUID(final String username);
/**
* Obtains the desired player's name.
*
* @param uuid the user's UUID
* @return the user's name
* @since 2.0.0
*/
CompletableFuture<@Nullable String> resolveName(final UUID uuid);
}
@@ -340,6 +340,9 @@ public interface CarbonPlayer extends Audience, Identified {
* A list of all the channels the player has left
* using the leave command.
*
* <p>The returned collection is immutable, use
* {@link #joinChannel(ChatChannel)} and {@link #leaveChannel(ChatChannel)} to mutate.</p>
*
* @return a list of the channels.
* @since 2.1.0
*/
@@ -21,6 +21,7 @@ package net.draycia.carbon.api.users;
import net.kyori.adventure.text.Component;
import org.checkerframework.checker.nullness.qual.MonotonicNonNull;
import org.jetbrains.annotations.ApiStatus;
/**
* The result of a player data operation.
@@ -29,6 +30,8 @@ import org.checkerframework.checker.nullness.qual.MonotonicNonNull;
* @param reason the reason of the result, typically empty unless {@link #player} is null
* @since 2.0.0
*/
@Deprecated(forRemoval = true)
@ApiStatus.Internal
public record ComponentPlayerResult<C extends CarbonPlayer>(@MonotonicNonNull C player, Component reason) {
}
@@ -21,6 +21,8 @@ package net.draycia.carbon.api.users;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.util.ComponentMessageThrowable;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.framework.qual.DefaultQualifier;
@@ -35,28 +37,25 @@ public interface UserManager<C extends CarbonPlayer> {
/**
* Loads and returns a {@link CarbonPlayer} with the given {@link UUID}.
*
* @deprecated use {@link #user(UUID)} instead
* @param uuid the player's uuid
* @return the result
* @since 2.0.0
*/
CompletableFuture<ComponentPlayerResult<C>> carbonPlayer(final UUID uuid);
@Deprecated(forRemoval = true)
default CompletableFuture<ComponentPlayerResult<C>> carbonPlayer(final UUID uuid) {
return this.user(uuid)
.thenApply(user -> new ComponentPlayerResult<>(user, Component.empty()))
.exceptionally(thr -> new ComponentPlayerResult<>(null, ComponentMessageThrowable.getOrConvertMessage(thr)));
}
/**
* Saves the {@link CarbonPlayer} and returns the result.
* Loads and returns the CarbonPlayer with the corresponding uuid.
*
* @param player the player to save
* @return the result
* @since 2.0.0
* @param uuid the player's id
* @return the player
* @since 2.1.0
*/
CompletableFuture<ComponentPlayerResult<C>> savePlayer(final C player);
/**
* Saves the {@link CarbonPlayer}, returns the result, and invalidates the player entry.
*
* @param player the player to save
* @return the result
* @since 2.0.0
*/
CompletableFuture<ComponentPlayerResult<C>> saveAndInvalidatePlayer(final C player);
CompletableFuture<C> user(UUID uuid);
}
+1 -1
View File
@@ -38,7 +38,7 @@ fun ShadowJar.standardRelocations() {
//relocateDependency("org.apache")
relocateDependency("ninja.egg82.messenger")
relocateDependency("org.antlr")
relocateDependency("com.github.luben")
//relocateDependency("com.github.luben")
//relocateDependency("io.netty")
relocateDependency("io.nats")
relocateDependency("com.rabbitmq")
+1
View File
@@ -21,6 +21,7 @@ dependencies {
// Other
api(libs.guice)
api(libs.assistedInject)
compileOnlyApi(libs.luckPermsApi)
// Storage
@@ -0,0 +1,196 @@
/*
* 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.Injector;
import com.google.inject.Provider;
import java.nio.file.Path;
import java.util.UUID;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import net.draycia.carbon.api.CarbonChat;
import net.draycia.carbon.api.CarbonServer;
import net.draycia.carbon.api.events.CarbonEventHandler;
import net.draycia.carbon.api.users.CarbonPlayer;
import net.draycia.carbon.common.channels.CarbonChannelRegistry;
import net.draycia.carbon.common.command.commands.ExecutionCoordinatorHolder;
import net.draycia.carbon.common.listeners.RadiusListener;
import net.draycia.carbon.common.messages.CarbonMessages;
import net.draycia.carbon.common.messaging.MessagingManager;
import net.draycia.carbon.common.users.ProfileCache;
import net.draycia.carbon.common.users.ProfileResolver;
import net.draycia.carbon.common.users.UserManagerInternal;
import net.draycia.carbon.common.util.CloudUtils;
import net.draycia.carbon.common.util.ConcurrentUtil;
import net.draycia.carbon.common.util.ListenerUtils;
import net.draycia.carbon.common.util.PlayerUtils;
import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.text.Component;
import net.kyori.moonshine.message.IMessageRenderer;
import ninja.egg82.messenger.services.PacketService;
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;
@DefaultQualifier(NonNull.class)
public abstract class CarbonChatInternal<C extends CarbonPlayer> implements CarbonChat {
private final UUID serverId;
private final Injector injector;
private final Logger logger;
private final Path dataDirectory;
private final ScheduledExecutorService periodicTasks;
private final ProfileCache profileCache;
private final ProfileResolver profileResolver;
private final UserManagerInternal<C> userManager;
private final ExecutionCoordinatorHolder commandExecutor;
private final CarbonServer carbonServer;
private final CarbonMessages carbonMessages;
private final CarbonEventHandler eventHandler;
private final CarbonChannelRegistry channelRegistry;
private final IMessageRenderer<Audience, String, Component, Component> renderer;
private final Provider<MessagingManager> messagingManager;
protected CarbonChatInternal(
final Injector injector,
final Logger logger,
final Path dataDirectory,
final ScheduledExecutorService periodicTasks,
final ProfileCache profileCache,
final ProfileResolver profileResolver,
final UserManagerInternal<C> userManager,
final ExecutionCoordinatorHolder commandExecutor,
final CarbonServer carbonServer,
final CarbonMessages carbonMessages,
final CarbonEventHandler eventHandler,
final CarbonChannelRegistry channelRegistry,
final IMessageRenderer<Audience, String, Component, Component> renderer,
final Provider<MessagingManager> messagingManagerProvider
) {
this.serverId = UUID.randomUUID();
this.injector = injector;
this.logger = logger;
this.dataDirectory = dataDirectory;
this.periodicTasks = periodicTasks;
this.profileCache = profileCache;
this.profileResolver = profileResolver;
this.userManager = userManager;
this.commandExecutor = commandExecutor;
this.carbonServer = carbonServer;
this.carbonMessages = carbonMessages;
this.eventHandler = eventHandler;
this.channelRegistry = channelRegistry;
this.renderer = renderer;
this.messagingManager = messagingManagerProvider;
}
protected void init() {
// Listeners
ListenerUtils.registerCommonListeners(this.injector);
this.injector.getInstance(RadiusListener.class);
// Commands
// This is a bit awkward looking
CloudUtils.loadCommands(this.injector);
final var commandSettings = CloudUtils.loadCommandSettings(this.injector);
CloudUtils.registerCommands(commandSettings);
this.periodicTasks.scheduleAtFixedRate(
() -> PlayerUtils.saveLoggedInPlayers(this.carbonServer, this.userManager, this.logger),
5,
5,
TimeUnit.MINUTES
);
this.periodicTasks.scheduleAtFixedRate(
this.profileCache::save,
15,
15,
TimeUnit.MINUTES
);
this.periodicTasks.scheduleAtFixedRate(
this.userManager::cleanup,
30,
30,
TimeUnit.SECONDS
);
// Load channels
this.channelRegistry().loadConfigChannels(this.carbonMessages);
}
protected void shutdown() {
ConcurrentUtil.shutdownExecutor(this.periodicTasks, TimeUnit.MILLISECONDS, 500);
this.profileCache.save();
this.profileResolver.shutdown();
this.userManager.shutdown();
this.commandExecutor.shutdown();
}
@Override
public UUID serverId() {
return this.serverId;
}
@Override
public Path dataDirectory() {
return this.dataDirectory;
}
@Override
public Logger logger() {
return this.logger;
}
@Override
public CarbonServer server() {
return this.carbonServer;
}
@Override
public UserManagerInternal<C> userManager() {
return this.userManager;
}
@Override
public CarbonEventHandler eventHandler() {
return this.eventHandler;
}
@Override
public CarbonChannelRegistry channelRegistry() {
return this.channelRegistry;
}
@Override
public <T extends Audience> IMessageRenderer<T, String, Component, Component> messageRenderer() {
return (IMessageRenderer<T, String, Component, Component>) this.renderer;
}
@Override
public @Nullable PacketService packetService() {
return this.messagingManager.get().packetService();
}
public Injector injector() {
return this.injector;
}
}
@@ -23,12 +23,16 @@ import com.google.inject.AbstractModule;
import com.google.inject.Injector;
import com.google.inject.Provides;
import com.google.inject.Singleton;
import com.google.inject.assistedinject.FactoryModuleBuilder;
import io.leangen.geantyref.TypeToken;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.ScheduledExecutorService;
import net.draycia.carbon.api.channels.ChannelRegistry;
import net.draycia.carbon.api.users.UserManager;
import net.draycia.carbon.api.events.CarbonEventHandler;
import net.draycia.carbon.common.channels.CarbonChannelRegistry;
import net.draycia.carbon.common.command.ArgumentFactory;
import net.draycia.carbon.common.command.commands.ExecutionCoordinatorHolder;
import net.draycia.carbon.common.config.ConfigFactory;
import net.draycia.carbon.common.messages.CarbonMessageSender;
import net.draycia.carbon.common.messages.CarbonMessageSource;
@@ -40,16 +44,20 @@ import net.draycia.carbon.common.messages.placeholders.ComponentPlaceholderResol
import net.draycia.carbon.common.messages.placeholders.KeyPlaceholderResolver;
import net.draycia.carbon.common.messages.placeholders.StringPlaceholderResolver;
import net.draycia.carbon.common.messages.placeholders.UUIDPlaceholderResolver;
import net.draycia.carbon.common.users.Backing;
import net.draycia.carbon.common.users.CarbonPlayerCommon;
import net.draycia.carbon.common.users.UserManagerInternal;
import net.draycia.carbon.common.users.db.mysql.MySQLUserManager;
import net.draycia.carbon.common.users.db.postgresql.PostgreSQLUserManager;
import net.draycia.carbon.common.users.json.JSONUserManager;
import net.draycia.carbon.common.util.ConcurrentUtil;
import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.key.Key;
import net.kyori.adventure.text.Component;
import net.kyori.moonshine.Moonshine;
import net.kyori.moonshine.exception.scan.UnscannableMethodException;
import net.kyori.moonshine.message.IMessageRenderer;
import org.apache.logging.log4j.Logger;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.framework.qual.DefaultQualifier;
@@ -57,18 +65,29 @@ import org.checkerframework.framework.qual.DefaultQualifier;
public final class CarbonCommonModule extends AbstractModule {
@Provides
@Backing
@Singleton
public UserManager<CarbonPlayerCommon> userManager(
final ConfigFactory configFactory,
final Injector injector
) {
public UserManagerInternal<CarbonPlayerCommon> userManager(final ConfigFactory configFactory, final Injector injector) {
return switch (Objects.requireNonNull(configFactory.primaryConfig()).storageType()) {
case MYSQL -> MySQLUserManager.manager(configFactory.primaryConfig().databaseSettings());
case PSQL -> PostgreSQLUserManager.manager(configFactory.primaryConfig().databaseSettings());
case MYSQL -> injector.getInstance(MySQLUserManager.Factory.class).create();
case PSQL -> injector.getInstance(PostgreSQLUserManager.Factory.class).create();
default -> injector.getInstance(JSONUserManager.class);
};
}
@Provides
@PeriodicTasks
@Singleton
public ScheduledExecutorService periodicTasksExecutor(final Logger logger) {
return ConcurrentUtil.createPeriodicTasksPool(logger);
}
@Provides
@Singleton
public CarbonEventHandler eventHandler() {
return new CarbonEventHandler();
}
@Provides
@Singleton
public CarbonMessages carbonMessages(
@@ -96,8 +115,15 @@ public final class CarbonCommonModule extends AbstractModule {
.create(this.getClass().getClassLoader());
}
@Provides
@Singleton
public ExecutionCoordinatorHolder executionCoordinatorHolder(final Logger logger) {
return ExecutionCoordinatorHolder.create(logger);
}
@Override
protected void configure() {
this.install(new FactoryModuleBuilder().build(ArgumentFactory.class));
this.bind(ChannelRegistry.class).to(CarbonChannelRegistry.class);
}
@@ -24,9 +24,13 @@ import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.nio.file.Path;
/**
* Injection binding annotation for the {@link Path} which is Carbon's data directory.
*/
@BindingAnnotation
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.PARAMETER, ElementType.FIELD})
public @interface ForCarbon {
public @interface DataDirectory {
}
@@ -0,0 +1,37 @@
/*
* 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.BindingAnnotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.concurrent.ScheduledExecutorService;
/**
* Injection binding annotation for the {@link ScheduledExecutorService} used for
* periodic tasks.
*/
@BindingAnnotation
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.PARAMETER, ElementType.FIELD, ElementType.METHOD})
public @interface PeriodicTasks {
}
@@ -46,9 +46,10 @@ import net.draycia.carbon.api.CarbonChatProvider;
import net.draycia.carbon.api.channels.ChannelRegistry;
import net.draycia.carbon.api.channels.ChatChannel;
import net.draycia.carbon.api.events.CarbonChatEvent;
import net.draycia.carbon.api.events.CarbonEventHandler;
import net.draycia.carbon.api.users.CarbonPlayer;
import net.draycia.carbon.api.util.KeyedRenderer;
import net.draycia.carbon.common.ForCarbon;
import net.draycia.carbon.common.DataDirectory;
import net.draycia.carbon.common.command.Commander;
import net.draycia.carbon.common.command.PlayerCommander;
import net.draycia.carbon.common.config.ConfigFactory;
@@ -57,7 +58,6 @@ import net.draycia.carbon.common.events.ChannelRegisterEvent;
import net.draycia.carbon.common.messages.CarbonMessages;
import net.draycia.carbon.common.messaging.packets.ChatMessagePacket;
import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.identity.Identity;
import net.kyori.adventure.key.Key;
import net.kyori.adventure.text.Component;
import net.kyori.registry.DefaultedRegistryGetter;
@@ -105,13 +105,14 @@ public class CarbonChannelRegistry implements ChannelRegistry, DefaultedRegistry
@Inject
public CarbonChannelRegistry(
@ForCarbon final Path dataDirectory,
@DataDirectory final Path dataDirectory,
final Injector injector,
final Logger logger,
final ConfigFactory configFactory,
final CarbonMessages carbonMessages,
//final BasicChatChannel basicChannel,
final CarbonChat carbonChat
final CarbonChat carbonChat,
final CarbonEventHandler events
) {
this.configChannelDir = dataDirectory.resolve("channels");
this.injector = injector;
@@ -121,9 +122,7 @@ public class CarbonChannelRegistry implements ChannelRegistry, DefaultedRegistry
//this.basicChannel = basicChannel;
this.carbonChat = carbonChat;
carbonChat.eventHandler().subscribe(CarbonReloadEvent.class, event -> {
this.reloadRegisteredConfigChannels();
});
events.subscribe(CarbonReloadEvent.class, event -> this.reloadRegisteredConfigChannels());
}
public static ConfigurationTransformation.Versioned versioned() {
@@ -318,7 +317,6 @@ public class CarbonChannelRegistry implements ChannelRegistry, DefaultedRegistry
final var renderers = new ArrayList<KeyedRenderer>();
renderers.add(keyedRenderer(Key.key("carbon", "default"), channel));
// TODO: add previewing when cloud/adventure support it
final var chatEvent = new CarbonChatEvent(sender, Component.text(plainMessage), recipients, renderers, channel, false);
final var result = this.carbonChat.eventHandler().emit(chatEvent);
@@ -338,10 +336,8 @@ public class CarbonChannelRegistry implements ChannelRegistry, DefaultedRegistry
renderedMessage = renderer.render(sender, sender, renderedMessage, chatEvent.message());
}
final Identity identity = sender.hasPermission("carbon.hideidentity") ? Identity.nil() : sender.identity();
for (final Audience recipient : chatEvent.recipients()) {
recipient.sendMessage(identity, renderedMessage);
recipient.sendMessage(renderedMessage);
}
final @Nullable PacketService packetService = this.carbonChat.packetService();
@@ -353,7 +349,6 @@ public class CarbonChannelRegistry implements ChannelRegistry, DefaultedRegistry
packetService.queuePacket(new ChatMessagePacket(this.carbonChat.serverId(), sender.uuid(),
configChatChannel.permission(), channel.key(), sender.username(), format,
Map.of("username", sender.username(), "message", plainMessage)));
packetService.flushQueue();
}
}
}
@@ -0,0 +1,31 @@
/*
* 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.command;
import net.draycia.carbon.common.command.argument.CarbonPlayerArgument;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.framework.qual.DefaultQualifier;
@DefaultQualifier(NonNull.class)
public interface ArgumentFactory {
CarbonPlayerArgument.Builder carbonPlayer(String name);
}
@@ -32,95 +32,47 @@ import cloud.commandframework.captions.CaptionVariable;
import cloud.commandframework.context.CommandContext;
import cloud.commandframework.exceptions.parsing.NoInputProvidedException;
import cloud.commandframework.exceptions.parsing.ParserException;
import com.google.inject.Inject;
import com.google.inject.assistedinject.Assisted;
import com.google.inject.assistedinject.AssistedInject;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.CompletableFuture;
import java.util.function.BiFunction;
import net.draycia.carbon.api.CarbonChatProvider;
import net.draycia.carbon.api.users.CarbonPlayer;
import net.draycia.carbon.api.users.UserManager;
import net.draycia.carbon.common.command.Commander;
import net.draycia.carbon.common.messages.CarbonMessages;
import net.draycia.carbon.common.users.ProfileResolver;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.checkerframework.framework.qual.DefaultQualifier;
/**
* Argument that parses into a {@link CarbonPlayer}.
*/
@SuppressWarnings("unused")
@DefaultQualifier(NonNull.class)
public final class CarbonPlayerArgument extends CommandArgument<Commander, CarbonPlayer> {
private CarbonPlayerArgument(
final boolean required,
final @NonNull String name,
final @NonNull String defaultValue,
final @Nullable BiFunction<@NonNull CommandContext<Commander>, @NonNull String,
@NonNull List<@NonNull String>> suggestionsProvider,
final @NonNull ArgumentDescription defaultDescription,
final @NonNull CarbonMessages carbonMessages
final String name,
final String defaultValue,
final @Nullable BiFunction<CommandContext<Commander>, String,
List<String>> suggestionsProvider,
final ArgumentDescription defaultDescription,
final CarbonPlayerParser parser
) {
super(required, name, new CarbonPlayerParser(carbonMessages), defaultValue, CarbonPlayer.class, suggestionsProvider, defaultDescription);
}
/**
* Create a new builder.
*
* @param name name of the component
* @return created builder
*/
public static @NonNull Builder builder(final @NonNull String name) {
return new Builder(name);
}
/**
* Create a new required command component.
*
* @param name component name
* @return created component
*/
public static @NonNull CommandArgument<Commander, CarbonPlayer> of(final @NonNull String name) {
return CarbonPlayerArgument.builder(name).asRequired().build();
}
/**
* Create a new optional command component.
*
* @param name component name
* @return created component
*/
public static @NonNull CommandArgument<Commander, CarbonPlayer> optional(final @NonNull String name) {
return CarbonPlayerArgument.builder(name).asOptional().build();
}
/**
* Create a new required command component with a default value.
*
* @param name component name
* @param defaultCarbonPlayer default player
* @return created component
*/
public static @NonNull CommandArgument<Commander, CarbonPlayer> optional(
final @NonNull String name,
final @NonNull String defaultCarbonPlayer
) {
return CarbonPlayerArgument.builder(name).asOptionalWithDefault(defaultCarbonPlayer).build();
super(required, name, parser, defaultValue, CarbonPlayer.class, suggestionsProvider, defaultDescription);
}
public static final class Builder extends CommandArgument.TypedBuilder<Commander, CarbonPlayer, Builder> {
private CarbonMessages carbonMessages;
private final CarbonPlayerParser parser;
private Builder(final @NonNull String name) {
@AssistedInject
private Builder(final @Assisted String name, final CarbonPlayerParser parser) {
super(CarbonPlayer.class, name);
}
/**
* Set the message service.
*
* @param carbonMessages the message service
* @return builder instance
*/
public Builder withMessages(final @NonNull CarbonMessages carbonMessages) {
this.carbonMessages = carbonMessages;
return this;
this.parser = parser;
}
/**
@@ -129,14 +81,14 @@ public final class CarbonPlayerArgument extends CommandArgument<Commander, Carbo
* @return constructed component
*/
@Override
public @NonNull CarbonPlayerArgument build() {
public CarbonPlayerArgument build() {
return new CarbonPlayerArgument(
this.isRequired(),
this.getName(),
this.getDefaultValue(),
this.getSuggestionsProvider(),
this.getDefaultDescription(),
this.carbonMessages
this.parser
);
}
@@ -144,19 +96,27 @@ public final class CarbonPlayerArgument extends CommandArgument<Commander, Carbo
public static final class CarbonPlayerParser implements ArgumentParser<Commander, CarbonPlayer> {
private final @NonNull CarbonMessages carbonMessages;
private final PlayerSuggestions suggestions;
private final UserManager<?> userManager;
private final ProfileResolver profileResolver;
public CarbonPlayerParser(final @NonNull CarbonMessages carbonMessages) {
this.carbonMessages = carbonMessages;
@Inject
private CarbonPlayerParser(
final PlayerSuggestions suggestions,
final UserManager<?> userManager,
final ProfileResolver profileResolver
) {
this.suggestions = suggestions;
this.userManager = userManager;
this.profileResolver = profileResolver;
}
@Override
@SuppressWarnings("deprecation")
public @NonNull ArgumentParseResult<CarbonPlayer> parse(
final @NonNull CommandContext<Commander> commandContext,
final @NonNull Queue<@NonNull String> inputQueue
public ArgumentParseResult<CarbonPlayer> parse(
final CommandContext<Commander> commandContext,
final Queue<String> inputQueue
) {
final String input = inputQueue.peek();
final @Nullable String input = inputQueue.peek();
if (input == null) {
return ArgumentParseResult.failure(new NoInputProvidedException(
@@ -165,29 +125,27 @@ public final class CarbonPlayerArgument extends CommandArgument<Commander, Carbo
));
}
return CarbonChatProvider.carbonChat().server().resolveUUID(input).thenApply(uuid -> {
final @Nullable CarbonPlayer join = this.profileResolver.resolveUUID(input, commandContext.isSuggestions()).thenCompose(uuid -> {
if (uuid == null) {
return ArgumentParseResult.<CarbonPlayer>failure(new CarbonPlayerParseException(input, commandContext, this.carbonMessages));
return CompletableFuture.completedFuture(null);
}
final var playerResult = CarbonChatProvider.carbonChat().server().userManager().carbonPlayer(uuid).join();
if (playerResult.player() == null) {
return ArgumentParseResult.<CarbonPlayer>failure(new CarbonPlayerParseException(input, commandContext, this.carbonMessages));
}
inputQueue.remove();
return ArgumentParseResult.<CarbonPlayer>success(playerResult.player());
return this.userManager.user(uuid);
}).join();
if (join == null) {
return ArgumentParseResult.failure(new CarbonPlayerParseException(input, commandContext));
}
inputQueue.remove();
return ArgumentParseResult.success(join);
}
@Override
public @NonNull List<@NonNull String> suggestions(
final @NonNull CommandContext<Commander> commandContext,
final @NonNull String input
public List<String> suggestions(
final CommandContext<Commander> commandContext,
final String input
) {
throw new UnsupportedOperationException("Suggestions provider must be overridden.");
return this.suggestions.apply(commandContext, input);
}
}
@@ -203,13 +161,12 @@ public final class CarbonPlayerArgument extends CommandArgument<Commander, Carbo
/**
* Construct a new CarbonPlayer parse exception.
*
* @param input string input
* @param input string input
* @param context command context
*/
public CarbonPlayerParseException(
final @NonNull String input,
final @NonNull CommandContext<?> context,
final @NonNull CarbonMessages carbonMessages
final String input,
final CommandContext<?> context
) {
super(
CarbonPlayerParser.class,
@@ -225,7 +182,7 @@ public final class CarbonPlayerArgument extends CommandArgument<Commander, Carbo
*
* @return string value
*/
public @NonNull String input() {
public String input() {
return this.input;
}
@@ -27,7 +27,6 @@ import com.google.inject.Inject;
import java.util.UUID;
import net.draycia.carbon.api.CarbonChat;
import net.draycia.carbon.api.users.CarbonPlayer;
import net.draycia.carbon.api.users.ComponentPlayerResult;
import net.draycia.carbon.api.util.SourcedAudience;
import net.draycia.carbon.common.command.CarbonCommand;
import net.draycia.carbon.common.command.CommandSettings;
@@ -100,9 +99,8 @@ public class ContinueCommand extends CarbonCommand {
return;
}
final ComponentPlayerResult<? extends CarbonPlayer> result = this.carbonChat.server()
.userManager().carbonPlayer(whisperTarget).join();
final @MonotonicNonNull CarbonPlayer recipient = result.player();
final @MonotonicNonNull CarbonPlayer recipient = this.carbonChat
.userManager().user(whisperTarget).join();
if (sender.equals(recipient)) {
this.carbonMessages.whisperSelfError(sender, CarbonPlayer.renderName(sender));
@@ -111,7 +109,7 @@ public class ContinueCommand extends CarbonCommand {
if (!recipient.online() || !sender.awareOf(recipient) && !sender.hasPermission("carbon.whisper.vanished")) {
final var rawNameInput = CloudUtils.rawInputByMatchingName(handler.getRawInput(), recipient);
final var exception = new CarbonPlayerArgument.CarbonPlayerParseException(rawNameInput, handler, this.carbonMessages);
final var exception = new CarbonPlayerArgument.CarbonPlayerParseException(rawNameInput, handler);
this.carbonMessages.errorCommandArgumentParsing(sender, CloudUtils.message(exception));
return;
@@ -25,12 +25,11 @@ import cloud.commandframework.minecraft.extras.RichDescription;
import com.google.inject.Inject;
import java.util.ArrayList;
import net.draycia.carbon.api.users.CarbonPlayer;
import net.draycia.carbon.common.command.ArgumentFactory;
import net.draycia.carbon.common.command.CarbonCommand;
import net.draycia.carbon.common.command.CommandSettings;
import net.draycia.carbon.common.command.Commander;
import net.draycia.carbon.common.command.PlayerCommander;
import net.draycia.carbon.common.command.argument.CarbonPlayerArgument;
import net.draycia.carbon.common.command.argument.PlayerSuggestions;
import net.draycia.carbon.common.messages.CarbonMessages;
import net.kyori.adventure.key.Key;
import net.kyori.adventure.text.Component;
@@ -44,17 +43,17 @@ public class DebugCommand extends CarbonCommand {
final CommandManager<Commander> commandManager;
final CarbonMessages carbonMessages;
final PlayerSuggestions playerSuggestions;
private final ArgumentFactory argumentFactory;
@Inject
public DebugCommand(
final CommandManager<Commander> commandManager,
final CarbonMessages carbonMessages,
final PlayerSuggestions playerSuggestions
final ArgumentFactory argumentFactory
) {
this.commandManager = commandManager;
this.carbonMessages = carbonMessages;
this.playerSuggestions = playerSuggestions;
this.argumentFactory = argumentFactory;
}
@Override
@@ -70,7 +69,7 @@ public class DebugCommand extends CarbonCommand {
@Override
public void init() {
final var command = this.commandManager.commandBuilder(this.commandSettings().name(), this.commandSettings().aliases())
.argument(CarbonPlayerArgument.builder("player").withMessages(this.carbonMessages).withSuggestionsProvider(this.playerSuggestions).asOptional(),
.argument(this.argumentFactory.carbonPlayer("player").asOptional(),
RichDescription.of(this.carbonMessages.commandDebugArgumentPlayer()))
.permission("carbon.debug")
.senderType(PlayerCommander.class)
@@ -0,0 +1,55 @@
/*
* 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.command.commands;
import cloud.commandframework.CommandTree;
import cloud.commandframework.execution.AsynchronousCommandExecutionCoordinator;
import cloud.commandframework.execution.CommandExecutionCoordinator;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import net.draycia.carbon.common.command.Commander;
import net.draycia.carbon.common.util.ConcurrentUtil;
import org.apache.logging.log4j.Logger;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.framework.qual.DefaultQualifier;
@DefaultQualifier(NonNull.class)
public record ExecutionCoordinatorHolder(
Function<CommandTree<Commander>, CommandExecutionCoordinator<Commander>> executionCoordinator,
ExecutorService executorService
) {
public void shutdown() {
ConcurrentUtil.shutdownExecutor(this.executorService, TimeUnit.MILLISECONDS, 50);
}
public static ExecutionCoordinatorHolder create(final Logger logger) {
final ExecutorService executorService = Executors.newFixedThreadPool(4, ConcurrentUtil.carbonThreadFactory(logger, "Commands"));
return new ExecutionCoordinatorHolder(
AsynchronousCommandExecutionCoordinator.<Commander>builder()
.withExecutor(executorService)
.build(),
executorService
);
}
}
@@ -24,15 +24,13 @@ import cloud.commandframework.arguments.standard.UUIDArgument;
import cloud.commandframework.minecraft.extras.MinecraftExtrasMetaKeys;
import cloud.commandframework.minecraft.extras.RichDescription;
import com.google.inject.Inject;
import java.util.Objects;
import net.draycia.carbon.api.CarbonChat;
import net.draycia.carbon.api.users.CarbonPlayer;
import net.draycia.carbon.common.command.ArgumentFactory;
import net.draycia.carbon.common.command.CarbonCommand;
import net.draycia.carbon.common.command.CommandSettings;
import net.draycia.carbon.common.command.Commander;
import net.draycia.carbon.common.command.PlayerCommander;
import net.draycia.carbon.common.command.argument.CarbonPlayerArgument;
import net.draycia.carbon.common.command.argument.PlayerSuggestions;
import net.draycia.carbon.common.messages.CarbonMessages;
import net.kyori.adventure.key.Key;
import org.checkerframework.checker.nullness.qual.NonNull;
@@ -44,19 +42,19 @@ public class IgnoreCommand extends CarbonCommand {
final CarbonChat carbonChat;
final CommandManager<Commander> commandManager;
final CarbonMessages carbonMessages;
final PlayerSuggestions playerSuggestions;
private final ArgumentFactory argumentFactory;
@Inject
public IgnoreCommand(
final CarbonChat carbonChat,
final CommandManager<Commander> commandManager,
final CarbonMessages carbonMessages,
final PlayerSuggestions playerSuggestions
final ArgumentFactory argumentFactory
) {
this.carbonChat = carbonChat;
this.commandManager = commandManager;
this.carbonMessages = carbonMessages;
this.playerSuggestions = playerSuggestions;
this.argumentFactory = argumentFactory;
}
@Override
@@ -72,7 +70,7 @@ public class IgnoreCommand extends CarbonCommand {
@Override
public void init() {
final var command = this.commandManager.commandBuilder(this.commandSettings().name(), this.commandSettings().aliases())
.argument(CarbonPlayerArgument.builder("player").withMessages(this.carbonMessages).withSuggestionsProvider(this.playerSuggestions).asOptional(),
.argument(this.argumentFactory.carbonPlayer("player").asOptional(),
RichDescription.of(this.carbonMessages.commandIgnoreArgumentPlayer()))
.flag(this.commandManager.flagBuilder("uuid")
.withAliases("u")
@@ -89,8 +87,7 @@ public class IgnoreCommand extends CarbonCommand {
if (handler.contains("player")) {
target = handler.get("player");
} else if (handler.flags().contains("uuid")) {
final var result = this.carbonChat.server().userManager().carbonPlayer(handler.get("uuid")).join();
target = Objects.requireNonNull(result.player(), "No player found for UUID.");
target = this.carbonChat.userManager().user(handler.get("uuid")).join();
} else {
this.carbonMessages.ignoreTargetInvalid(sender);
return;
@@ -31,7 +31,6 @@ import net.draycia.carbon.common.command.CarbonCommand;
import net.draycia.carbon.common.command.CommandSettings;
import net.draycia.carbon.common.command.Commander;
import net.draycia.carbon.common.command.PlayerCommander;
import net.draycia.carbon.common.command.argument.PlayerSuggestions;
import net.draycia.carbon.common.messages.CarbonMessages;
import net.draycia.carbon.common.util.ChannelUtils;
import net.kyori.adventure.key.Key;
@@ -45,19 +44,16 @@ public class JoinCommand extends CarbonCommand {
final CarbonChat carbonChat;
final CommandManager<Commander> commandManager;
final CarbonMessages carbonMessages;
final PlayerSuggestions playerSuggestions;
@Inject
public JoinCommand(
final CarbonChat carbonChat,
final CommandManager<Commander> commandManager,
final CarbonMessages carbonMessages,
final PlayerSuggestions playerSuggestions
final CarbonMessages carbonMessages
) {
this.carbonChat = carbonChat;
this.commandManager = commandManager;
this.carbonMessages = carbonMessages;
this.playerSuggestions = playerSuggestions;
}
@Override
@@ -31,7 +31,6 @@ import net.draycia.carbon.common.command.CarbonCommand;
import net.draycia.carbon.common.command.CommandSettings;
import net.draycia.carbon.common.command.Commander;
import net.draycia.carbon.common.command.PlayerCommander;
import net.draycia.carbon.common.command.argument.PlayerSuggestions;
import net.draycia.carbon.common.messages.CarbonMessages;
import net.draycia.carbon.common.util.ChannelUtils;
import net.kyori.adventure.key.Key;
@@ -45,19 +44,16 @@ public class LeaveCommand extends CarbonCommand {
final CarbonChat carbonChat;
final CommandManager<Commander> commandManager;
final CarbonMessages carbonMessages;
final PlayerSuggestions playerSuggestions;
@Inject
public LeaveCommand(
final CarbonChat carbonChat,
final CommandManager<Commander> commandManager,
final CarbonMessages carbonMessages,
final PlayerSuggestions playerSuggestions
final CarbonMessages carbonMessages
) {
this.carbonChat = carbonChat;
this.commandManager = commandManager;
this.carbonMessages = carbonMessages;
this.playerSuggestions = playerSuggestions;
}
@Override
@@ -24,15 +24,13 @@ import cloud.commandframework.arguments.standard.UUIDArgument;
import cloud.commandframework.minecraft.extras.MinecraftExtrasMetaKeys;
import cloud.commandframework.minecraft.extras.RichDescription;
import com.google.inject.Inject;
import java.util.Objects;
import net.draycia.carbon.api.CarbonChat;
import net.draycia.carbon.api.users.CarbonPlayer;
import net.draycia.carbon.common.command.ArgumentFactory;
import net.draycia.carbon.common.command.CarbonCommand;
import net.draycia.carbon.common.command.CommandSettings;
import net.draycia.carbon.common.command.Commander;
import net.draycia.carbon.common.command.PlayerCommander;
import net.draycia.carbon.common.command.argument.CarbonPlayerArgument;
import net.draycia.carbon.common.command.argument.PlayerSuggestions;
import net.draycia.carbon.common.messages.CarbonMessages;
import net.kyori.adventure.key.Key;
import org.checkerframework.checker.nullness.qual.NonNull;
@@ -44,19 +42,19 @@ public class MuteCommand extends CarbonCommand {
final CarbonChat carbonChat;
final CommandManager<Commander> commandManager;
final CarbonMessages carbonMessages;
final PlayerSuggestions playerSuggestions;
private final ArgumentFactory argumentFactory;
@Inject
public MuteCommand(
final CarbonChat carbonChat,
final CommandManager<Commander> commandManager,
final CarbonMessages carbonMessages,
final PlayerSuggestions playerSuggestions
final ArgumentFactory argumentFactory
) {
this.carbonChat = carbonChat;
this.commandManager = commandManager;
this.carbonMessages = carbonMessages;
this.playerSuggestions = playerSuggestions;
this.argumentFactory = argumentFactory;
}
@Override
@@ -72,7 +70,7 @@ public class MuteCommand extends CarbonCommand {
@Override
public void init() {
final var command = this.commandManager.commandBuilder(this.commandSettings().name(), this.commandSettings().aliases())
.argument(CarbonPlayerArgument.builder("player").withMessages(this.carbonMessages).withSuggestionsProvider(this.playerSuggestions).asOptional(),
.argument(this.argumentFactory.carbonPlayer("player").asOptional(),
RichDescription.of(this.carbonMessages.commandMuteArgumentPlayer()))
.flag(this.commandManager.flagBuilder("uuid")
.withAliases("u")
@@ -89,8 +87,7 @@ public class MuteCommand extends CarbonCommand {
if (handler.contains("player")) {
target = handler.get("player");
} else if (handler.flags().contains("uuid")) {
final var result = this.carbonChat.server().userManager().carbonPlayer(handler.get("uuid")).join();
target = Objects.requireNonNull(result.player(), "No player found for UUID.");
target = this.carbonChat.userManager().user(handler.get("uuid")).join();
} else {
this.carbonMessages.muteNoTarget(sender);
// TODO: send command syntax
@@ -24,15 +24,13 @@ import cloud.commandframework.arguments.standard.UUIDArgument;
import cloud.commandframework.minecraft.extras.MinecraftExtrasMetaKeys;
import cloud.commandframework.minecraft.extras.RichDescription;
import com.google.inject.Inject;
import java.util.Objects;
import net.draycia.carbon.api.CarbonChat;
import net.draycia.carbon.api.users.CarbonPlayer;
import net.draycia.carbon.common.command.ArgumentFactory;
import net.draycia.carbon.common.command.CarbonCommand;
import net.draycia.carbon.common.command.CommandSettings;
import net.draycia.carbon.common.command.Commander;
import net.draycia.carbon.common.command.PlayerCommander;
import net.draycia.carbon.common.command.argument.CarbonPlayerArgument;
import net.draycia.carbon.common.command.argument.PlayerSuggestions;
import net.draycia.carbon.common.messages.CarbonMessages;
import net.kyori.adventure.key.Key;
import org.checkerframework.checker.nullness.qual.NonNull;
@@ -44,19 +42,19 @@ public class MuteInfoCommand extends CarbonCommand {
final CarbonChat carbonChat;
final CommandManager<Commander> commandManager;
final CarbonMessages carbonMessages;
final PlayerSuggestions playerSuggestions;
private final ArgumentFactory argumentFactory;
@Inject
public MuteInfoCommand(
final CarbonChat carbonChat,
final CommandManager<Commander> commandManager,
final CarbonMessages carbonMessages,
final PlayerSuggestions playerSuggestions
final ArgumentFactory argumentFactory
) {
this.carbonChat = carbonChat;
this.commandManager = commandManager;
this.carbonMessages = carbonMessages;
this.playerSuggestions = playerSuggestions;
this.argumentFactory = argumentFactory;
}
@Override
@@ -72,7 +70,7 @@ public class MuteInfoCommand extends CarbonCommand {
@Override
public void init() {
final var command = this.commandManager.commandBuilder(this.commandSettings().name(), this.commandSettings().aliases())
.argument(CarbonPlayerArgument.builder("player").withMessages(this.carbonMessages).withSuggestionsProvider(this.playerSuggestions).asOptional(),
.argument(this.argumentFactory.carbonPlayer("player").asOptional(),
RichDescription.of(this.carbonMessages.commandMuteInfoArgumentPlayer()))
.flag(this.commandManager.flagBuilder("uuid")
.withAliases("u")
@@ -89,8 +87,7 @@ public class MuteInfoCommand extends CarbonCommand {
if (handler.contains("player")) {
target = handler.get("player");
} else if (handler.flags().contains("uuid")) {
final var result = this.carbonChat.server().userManager().carbonPlayer(handler.get("uuid")).join();
target = Objects.requireNonNull(result.player(), "No player found for UUID.");
target = this.carbonChat.userManager().user(handler.get("uuid")).join();
} else {
target = sender;
}
@@ -28,12 +28,11 @@ import com.google.inject.Inject;
import java.util.function.Supplier;
import net.draycia.carbon.api.users.CarbonPlayer;
import net.draycia.carbon.common.channels.ConfigChatChannel;
import net.draycia.carbon.common.command.ArgumentFactory;
import net.draycia.carbon.common.command.CarbonCommand;
import net.draycia.carbon.common.command.CommandSettings;
import net.draycia.carbon.common.command.Commander;
import net.draycia.carbon.common.command.PlayerCommander;
import net.draycia.carbon.common.command.argument.CarbonPlayerArgument;
import net.draycia.carbon.common.command.argument.PlayerSuggestions;
import net.draycia.carbon.common.messages.CarbonMessages;
import net.draycia.carbon.common.util.CloudUtils;
import net.kyori.adventure.audience.Audience;
@@ -47,17 +46,17 @@ public class NicknameCommand extends CarbonCommand {
final CommandManager<Commander> commandManager;
final CarbonMessages carbonMessages;
final PlayerSuggestions playerSuggestions;
private final ArgumentFactory argumentFactory;
@Inject
public NicknameCommand(
final CommandManager<Commander> commandManager,
final CarbonMessages carbonMessages,
final PlayerSuggestions playerSuggestions
final ArgumentFactory argumentFactory
) {
this.commandManager = commandManager;
this.carbonMessages = carbonMessages;
this.playerSuggestions = playerSuggestions;
this.argumentFactory = argumentFactory;
}
@Override
@@ -75,12 +74,7 @@ public class NicknameCommand extends CarbonCommand {
// TODO: Allow UUID input for target player
final var selfRoot = this.commandManager.commandBuilder(this.commandSettings().name(), this.commandSettings().aliases());
final var othersRoot = selfRoot.literal("player")
.argument(
CarbonPlayerArgument.builder("player")
.withMessages(this.carbonMessages)
.withSuggestionsProvider(this.playerSuggestions),
RichDescription.of(this.carbonMessages.commandNicknameArgumentPlayer())
);
.argument(this.argumentFactory.carbonPlayer("player"), RichDescription.of(this.carbonMessages.commandNicknameArgumentPlayer()));
// Check nickname
this.commandManager.command(selfRoot.permission("carbon.nickname")
@@ -27,7 +27,6 @@ import com.google.inject.Inject;
import java.util.UUID;
import net.draycia.carbon.api.CarbonChat;
import net.draycia.carbon.api.users.CarbonPlayer;
import net.draycia.carbon.api.users.ComponentPlayerResult;
import net.draycia.carbon.api.util.SourcedAudience;
import net.draycia.carbon.common.command.CarbonCommand;
import net.draycia.carbon.common.command.CommandSettings;
@@ -100,8 +99,7 @@ public class ReplyCommand extends CarbonCommand {
return;
}
final ComponentPlayerResult<? extends CarbonPlayer> result = this.carbonChat.server().userManager().carbonPlayer(replyTarget).join();
final @MonotonicNonNull CarbonPlayer recipient = result.player();
final @MonotonicNonNull CarbonPlayer recipient = this.carbonChat.userManager().user(replyTarget).join();
if (sender.equals(recipient)) {
this.carbonMessages.whisperSelfError(sender, CarbonPlayer.renderName(sender));
@@ -110,7 +108,7 @@ public class ReplyCommand extends CarbonCommand {
if (!recipient.online() || !sender.awareOf(recipient) && !sender.hasPermission("carbon.whisper.vanished")) {
final var rawNameInput = CloudUtils.rawInputByMatchingName(handler.getRawInput(), recipient);
final var exception = new CarbonPlayerArgument.CarbonPlayerParseException(rawNameInput, handler, this.carbonMessages);
final var exception = new CarbonPlayerArgument.CarbonPlayerParseException(rawNameInput, handler);
this.carbonMessages.errorCommandArgumentParsing(sender, CloudUtils.message(exception));
return;
@@ -24,15 +24,13 @@ import cloud.commandframework.arguments.standard.UUIDArgument;
import cloud.commandframework.minecraft.extras.MinecraftExtrasMetaKeys;
import cloud.commandframework.minecraft.extras.RichDescription;
import com.google.inject.Inject;
import java.util.Objects;
import net.draycia.carbon.api.CarbonChat;
import net.draycia.carbon.api.users.CarbonPlayer;
import net.draycia.carbon.common.command.ArgumentFactory;
import net.draycia.carbon.common.command.CarbonCommand;
import net.draycia.carbon.common.command.CommandSettings;
import net.draycia.carbon.common.command.Commander;
import net.draycia.carbon.common.command.PlayerCommander;
import net.draycia.carbon.common.command.argument.CarbonPlayerArgument;
import net.draycia.carbon.common.command.argument.PlayerSuggestions;
import net.draycia.carbon.common.messages.CarbonMessages;
import net.kyori.adventure.key.Key;
import org.checkerframework.checker.nullness.qual.NonNull;
@@ -44,19 +42,19 @@ public class UnignoreCommand extends CarbonCommand {
final CarbonChat carbonChat;
final CommandManager<Commander> commandManager;
final CarbonMessages carbonMessages;
final PlayerSuggestions playerSuggestions;
private final ArgumentFactory argumentFactory;
@Inject
public UnignoreCommand(
final CarbonChat carbonChat,
final CommandManager<Commander> commandManager,
final CarbonMessages carbonMessages,
final PlayerSuggestions playerSuggestions
final ArgumentFactory argumentFactory
) {
this.carbonChat = carbonChat;
this.commandManager = commandManager;
this.carbonMessages = carbonMessages;
this.playerSuggestions = playerSuggestions;
this.argumentFactory = argumentFactory;
}
@Override
@@ -73,7 +71,7 @@ public class UnignoreCommand extends CarbonCommand {
public void init() {
final var command = this.commandManager.commandBuilder(this.commandSettings().name(), this.commandSettings().aliases())
// TODO: Filter, and only show muted players, but allow inputting any player name.
.argument(CarbonPlayerArgument.builder("player").withMessages(this.carbonMessages).withSuggestionsProvider(this.playerSuggestions).asOptional(),
.argument(this.argumentFactory.carbonPlayer("player").asOptional(),
RichDescription.of(this.carbonMessages.commandUnignoreArgumentPlayer()))
.flag(this.commandManager.flagBuilder("uuid")
.withAliases("u")
@@ -90,8 +88,7 @@ public class UnignoreCommand extends CarbonCommand {
if (handler.contains("player")) {
target = handler.get("player");
} else if (handler.flags().contains("uuid")) {
final var result = this.carbonChat.server().userManager().carbonPlayer(handler.get("uuid")).join();
target = Objects.requireNonNull(result.player(), "No player found for UUID.");
target = this.carbonChat.userManager().user(handler.get("uuid")).join();
} else {
this.carbonMessages.ignoreTargetInvalid(sender);
return;
@@ -24,15 +24,13 @@ import cloud.commandframework.arguments.standard.UUIDArgument;
import cloud.commandframework.minecraft.extras.MinecraftExtrasMetaKeys;
import cloud.commandframework.minecraft.extras.RichDescription;
import com.google.inject.Inject;
import java.util.Objects;
import net.draycia.carbon.api.CarbonChat;
import net.draycia.carbon.api.users.CarbonPlayer;
import net.draycia.carbon.common.command.ArgumentFactory;
import net.draycia.carbon.common.command.CarbonCommand;
import net.draycia.carbon.common.command.CommandSettings;
import net.draycia.carbon.common.command.Commander;
import net.draycia.carbon.common.command.PlayerCommander;
import net.draycia.carbon.common.command.argument.CarbonPlayerArgument;
import net.draycia.carbon.common.command.argument.PlayerSuggestions;
import net.draycia.carbon.common.messages.CarbonMessages;
import net.kyori.adventure.key.Key;
import org.checkerframework.checker.nullness.qual.NonNull;
@@ -44,19 +42,19 @@ public class UnmuteCommand extends CarbonCommand {
final CarbonChat carbonChat;
final CommandManager<Commander> commandManager;
final CarbonMessages carbonMessages;
final PlayerSuggestions playerSuggestions;
private final ArgumentFactory argumentFactory;
@Inject
public UnmuteCommand(
final CarbonChat carbonChat,
final CommandManager<Commander> commandManager,
final CarbonMessages carbonMessages,
final PlayerSuggestions playerSuggestions
final ArgumentFactory argumentFactory
) {
this.carbonChat = carbonChat;
this.commandManager = commandManager;
this.carbonMessages = carbonMessages;
this.playerSuggestions = playerSuggestions;
this.argumentFactory = argumentFactory;
}
@Override
@@ -72,7 +70,7 @@ public class UnmuteCommand extends CarbonCommand {
@Override
public void init() {
final var command = this.commandManager.commandBuilder(this.commandSettings().name(), this.commandSettings().aliases())
.argument(CarbonPlayerArgument.builder("player").withMessages(this.carbonMessages).withSuggestionsProvider(this.playerSuggestions).asOptional(),
.argument(this.argumentFactory.carbonPlayer("player").asOptional(),
RichDescription.of(this.carbonMessages.commandUnmuteArgumentPlayer()))
.flag(this.commandManager.flagBuilder("uuid")
.withAliases("u")
@@ -89,8 +87,7 @@ public class UnmuteCommand extends CarbonCommand {
if (handler.contains("player")) {
target = handler.get("player");
} else if (handler.flags().contains("uuid")) {
final var result = this.carbonChat.server().userManager().carbonPlayer(handler.get("uuid")).join();
target = Objects.requireNonNull(result.player(), "No player found for UUID.");
target = this.carbonChat.userManager().user(handler.get("uuid")).join();
} else {
this.carbonMessages.unmuteNoTarget(sender);
// TODO: send command syntax
@@ -25,16 +25,16 @@ import cloud.commandframework.minecraft.extras.MinecraftExtrasMetaKeys;
import cloud.commandframework.minecraft.extras.RichDescription;
import com.google.inject.Inject;
import java.util.Objects;
import net.draycia.carbon.api.CarbonChat;
import net.draycia.carbon.api.users.CarbonPlayer;
import net.draycia.carbon.api.users.UserManager;
import net.draycia.carbon.common.command.ArgumentFactory;
import net.draycia.carbon.common.command.CarbonCommand;
import net.draycia.carbon.common.command.CommandSettings;
import net.draycia.carbon.common.command.Commander;
import net.draycia.carbon.common.command.PlayerCommander;
import net.draycia.carbon.common.command.argument.CarbonPlayerArgument;
import net.draycia.carbon.common.command.argument.PlayerSuggestions;
import net.draycia.carbon.common.messages.CarbonMessages;
import net.draycia.carbon.common.users.CarbonPlayerCommon;
import net.draycia.carbon.common.users.ProfileResolver;
import net.draycia.carbon.common.users.WrappedCarbonPlayer;
import net.kyori.adventure.key.Key;
import org.checkerframework.checker.nullness.qual.NonNull;
@@ -43,22 +43,25 @@ import org.checkerframework.framework.qual.DefaultQualifier;
@DefaultQualifier(NonNull.class)
public class UpdateUsernameCommand extends CarbonCommand {
final CarbonChat carbonChat;
private final UserManager<?> userManager;
final CommandManager<Commander> commandManager;
final CarbonMessages messageService;
final PlayerSuggestions playerSuggestions;
private final ArgumentFactory argumentFactory;
private final ProfileResolver profileResolver;
@Inject
public UpdateUsernameCommand(
final CarbonChat carbonChat,
final UserManager<?> userManager,
final CommandManager<Commander> commandManager,
final CarbonMessages messageService,
final PlayerSuggestions playerSuggestions
final ArgumentFactory argumentFactory,
final ProfileResolver profileResolver
) {
this.carbonChat = carbonChat;
this.userManager = userManager;
this.commandManager = commandManager;
this.messageService = messageService;
this.playerSuggestions = playerSuggestions;
this.argumentFactory = argumentFactory;
this.profileResolver = profileResolver;
}
@Override
@@ -74,7 +77,7 @@ public class UpdateUsernameCommand extends CarbonCommand {
@Override
public void init() {
final var command = this.commandManager.commandBuilder(this.commandSettings().name(), this.commandSettings().aliases())
.argument(CarbonPlayerArgument.builder("player").withMessages(this.messageService).withSuggestionsProvider(this.playerSuggestions).asOptional(),
.argument(this.argumentFactory.carbonPlayer("player").asOptional(),
RichDescription.of(this.messageService.commandUpdateUsernameArgumentPlayer()))
.flag(this.commandManager.flagBuilder("uuid")
.withAliases("u")
@@ -91,8 +94,7 @@ public class UpdateUsernameCommand extends CarbonCommand {
if (handler.contains("player")) {
target = handler.get("player");
} else if (handler.flags().contains("uuid")) {
final var result = this.carbonChat.server().userManager().carbonPlayer(handler.get("uuid")).join();
target = Objects.requireNonNull(result.player(), "No player found for UUID.");
target = this.userManager.user(handler.get("uuid")).join();
} else {
target = sender;
}
@@ -106,7 +108,7 @@ public class UpdateUsernameCommand extends CarbonCommand {
this.messageService.usernameFetching(sender);
final CarbonPlayer finalTarget = target;
this.carbonChat.server().resolveName(target.uuid()).thenAccept(name -> {
this.profileResolver.resolveName(target.uuid()).thenAccept(name -> {
Objects.requireNonNull(name, "Unable to fetch username for player.");
((CarbonPlayerCommon) finalTarget).username(name);
@@ -27,12 +27,12 @@ import com.google.inject.Inject;
import net.draycia.carbon.api.CarbonChat;
import net.draycia.carbon.api.users.CarbonPlayer;
import net.draycia.carbon.api.util.SourcedAudience;
import net.draycia.carbon.common.command.ArgumentFactory;
import net.draycia.carbon.common.command.CarbonCommand;
import net.draycia.carbon.common.command.CommandSettings;
import net.draycia.carbon.common.command.Commander;
import net.draycia.carbon.common.command.PlayerCommander;
import net.draycia.carbon.common.command.argument.CarbonPlayerArgument;
import net.draycia.carbon.common.command.argument.PlayerSuggestions;
import net.draycia.carbon.common.config.ConfigFactory;
import net.draycia.carbon.common.messages.CarbonMessages;
import net.draycia.carbon.common.util.CloudUtils;
@@ -49,7 +49,7 @@ public class WhisperCommand extends CarbonCommand {
final CarbonChat carbonChat;
final CommandManager<Commander> commandManager;
final CarbonMessages carbonMessages;
final PlayerSuggestions playerSuggestions;
private final ArgumentFactory argumentFactory;
final ConfigFactory configFactory;
@Inject
@@ -57,13 +57,13 @@ public class WhisperCommand extends CarbonCommand {
final CarbonChat carbonChat,
final CommandManager<Commander> commandManager,
final CarbonMessages carbonMessages,
final PlayerSuggestions playerSuggestions,
final ArgumentFactory argumentFactory,
final ConfigFactory configFactory
) {
this.carbonChat = carbonChat;
this.commandManager = commandManager;
this.carbonMessages = carbonMessages;
this.playerSuggestions = playerSuggestions;
this.argumentFactory = argumentFactory;
this.configFactory = configFactory;
}
@@ -80,7 +80,7 @@ public class WhisperCommand extends CarbonCommand {
@Override
public void init() {
final var command = this.commandManager.commandBuilder(this.commandSettings().name(), this.commandSettings().aliases())
.argument(CarbonPlayerArgument.builder("player").withMessages(this.carbonMessages).withSuggestionsProvider(this.playerSuggestions).asRequired(),
.argument(this.argumentFactory.carbonPlayer("player").asRequired(),
RichDescription.of(this.carbonMessages.commandWhisperArgumentPlayer()))
.argument(StringArgument.greedy("message"),
RichDescription.of(this.carbonMessages.commandWhisperArgumentMessage()))
@@ -105,7 +105,7 @@ public class WhisperCommand extends CarbonCommand {
if (!recipient.online() || !sender.awareOf(recipient) && !sender.hasPermission("carbon.whisper.vanished")) {
final var rawNameInput = CloudUtils.rawInputByMatchingName(handler.getRawInput(), recipient);
final var exception = new CarbonPlayerArgument.CarbonPlayerParseException(rawNameInput, handler, this.carbonMessages);
final var exception = new CarbonPlayerArgument.CarbonPlayerParseException(rawNameInput, handler);
this.carbonMessages.errorCommandArgumentParsing(sender, CloudUtils.message(exception));
return;
@@ -24,8 +24,8 @@ import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Locale;
import net.draycia.carbon.api.CarbonChat;
import net.draycia.carbon.common.ForCarbon;
import net.draycia.carbon.api.events.CarbonEventHandler;
import net.draycia.carbon.common.DataDirectory;
import net.draycia.carbon.common.events.CarbonReloadEvent;
import net.draycia.carbon.common.serialisation.gson.LocaleSerializerConfigurate;
import net.kyori.adventure.serializer.configurate4.ConfigurateComponentSerializer;
@@ -47,16 +47,14 @@ public class ConfigFactory {
@Inject
public ConfigFactory(
final CarbonChat carbonChat,
@ForCarbon final Path dataDirectory,
final CarbonEventHandler events,
@DataDirectory final Path dataDirectory,
final LocaleSerializerConfigurate locale
) {
this.dataDirectory = dataDirectory;
this.locale = locale;
carbonChat.eventHandler().subscribe(CarbonReloadEvent.class, event -> {
this.reloadPrimaryConfig();
});
events.subscribe(CarbonReloadEvent.class, event -> this.reloadPrimaryConfig());
}
public @Nullable PrimaryConfig reloadPrimaryConfig() {
@@ -20,8 +20,8 @@
package net.draycia.carbon.common.listeners;
import com.google.inject.Inject;
import net.draycia.carbon.api.CarbonChat;
import net.draycia.carbon.api.events.CarbonChatEvent;
import net.draycia.carbon.api.events.CarbonEventHandler;
import net.draycia.carbon.api.users.CarbonPlayer;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.framework.qual.DefaultQualifier;
@@ -30,10 +30,8 @@ import org.checkerframework.framework.qual.DefaultQualifier;
public class DeafenHandler {
@Inject
public DeafenHandler(
final CarbonChat carbonChat
) {
carbonChat.eventHandler().subscribe(CarbonChatEvent.class, 0, false, event -> {
public DeafenHandler(final CarbonEventHandler events) {
events.subscribe(CarbonChatEvent.class, 0, false, event -> {
if (!event.sender().deafened()) {
return;
}
@@ -20,8 +20,8 @@
package net.draycia.carbon.common.listeners;
import com.google.inject.Inject;
import net.draycia.carbon.api.CarbonChat;
import net.draycia.carbon.api.events.CarbonChatEvent;
import net.draycia.carbon.api.events.CarbonEventHandler;
import net.draycia.carbon.api.users.CarbonPlayer;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.framework.qual.DefaultQualifier;
@@ -30,10 +30,8 @@ import org.checkerframework.framework.qual.DefaultQualifier;
public class IgnoreHandler {
@Inject
public IgnoreHandler(
final CarbonChat carbonChat
) {
carbonChat.eventHandler().subscribe(CarbonChatEvent.class, 0, false, event -> {
public IgnoreHandler(final CarbonEventHandler events) {
events.subscribe(CarbonChatEvent.class, 0, false, event -> {
event.recipients().removeIf(entry -> entry instanceof CarbonPlayer carbonPlayer &&
carbonPlayer.ignoring(event.sender()));
});
@@ -20,18 +20,16 @@
package net.draycia.carbon.common.listeners;
import com.google.inject.Inject;
import net.draycia.carbon.api.CarbonChat;
import net.draycia.carbon.api.events.CarbonChatEvent;
import net.draycia.carbon.api.events.CarbonEventHandler;
import net.draycia.carbon.api.util.InventorySlot;
import net.kyori.adventure.text.TextReplacementConfig;
public class ItemLinkHandler {
@Inject
public ItemLinkHandler(
final CarbonChat carbonChat
) {
carbonChat.eventHandler().subscribe(CarbonChatEvent.class, 1, false, event -> {
public ItemLinkHandler(final CarbonEventHandler events) {
events.subscribe(CarbonChatEvent.class, 1, false, event -> {
if (!event.sender().hasPermission("carbon.itemlink")) {
return;
}
@@ -0,0 +1,55 @@
/*
* 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.listeners;
import com.google.inject.Inject;
import java.util.Map;
import net.draycia.carbon.api.CarbonChat;
import net.draycia.carbon.api.events.CarbonChatEvent;
import net.draycia.carbon.api.events.CarbonEventHandler;
import net.draycia.carbon.common.channels.ConfigChatChannel;
import net.draycia.carbon.common.messaging.packets.ChatMessagePacket;
import net.kyori.adventure.text.minimessage.MiniMessage;
import ninja.egg82.messenger.services.PacketService;
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 MessagingHandler {
@Inject
public MessagingHandler(final CarbonChat carbonChat, final CarbonEventHandler events) {
events.subscribe(CarbonChatEvent.class, 1000, false, event -> {
final @Nullable PacketService packetService = carbonChat.packetService();
if (packetService != null) {
if (event.chatChannel() instanceof ConfigChatChannel configChatChannel) {
final @Nullable String format = configChatChannel.messageFormat(event.sender());
packetService.queuePacket(new ChatMessagePacket(carbonChat.serverId(), event.sender().uuid(),
configChatChannel.permission(), event.chatChannel().key(), event.sender().username(), format,
Map.of("username", event.sender().username(), "message", MiniMessage.miniMessage().serialize(event.message()))));
}
}
});
}
}
@@ -20,8 +20,8 @@
package net.draycia.carbon.common.listeners;
import com.google.inject.Inject;
import net.draycia.carbon.api.CarbonChat;
import net.draycia.carbon.api.events.CarbonChatEvent;
import net.draycia.carbon.api.events.CarbonEventHandler;
import net.draycia.carbon.api.users.CarbonPlayer;
import net.draycia.carbon.api.util.KeyedRenderer;
import net.draycia.carbon.common.messages.CarbonMessages;
@@ -47,13 +47,10 @@ public class MuteHandler {
});
@Inject
public MuteHandler(
final CarbonChat carbonChat,
final CarbonMessages carbonMessages
) {
public MuteHandler(final CarbonEventHandler events, final CarbonMessages carbonMessages) {
this.carbonMessages = carbonMessages;
carbonChat.eventHandler().subscribe(CarbonChatEvent.class, 100, false, event -> {
events.subscribe(CarbonChatEvent.class, 100, false, event -> {
if (!event.sender().muted()) {
return;
}
@@ -21,8 +21,8 @@ package net.draycia.carbon.common.listeners;
import com.google.inject.Inject;
import java.util.regex.Pattern;
import net.draycia.carbon.api.CarbonChat;
import net.draycia.carbon.api.events.CarbonChatEvent;
import net.draycia.carbon.api.events.CarbonEventHandler;
import net.draycia.carbon.api.users.CarbonPlayer;
import net.draycia.carbon.api.util.KeyedRenderer;
import net.draycia.carbon.common.config.ConfigFactory;
@@ -42,7 +42,7 @@ public class PingHandler {
private final KeyedRenderer renderer;
@Inject
public PingHandler(final CarbonChat carbonChat, final ConfigFactory configFactory) {
public PingHandler(final CarbonEventHandler events, final ConfigFactory configFactory) {
this.renderer = keyedRenderer(this.muteKey, (sender, recipient, message, originalMessage) -> {
if (!(recipient instanceof CarbonPlayer recipientPlayer)) {
return message;
@@ -62,7 +62,7 @@ public class PingHandler {
.build());
});
carbonChat.eventHandler().subscribe(CarbonChatEvent.class, 1, false, event -> {
events.subscribe(CarbonChatEvent.class, 1, false, event -> {
event.renderers().add(0, this.renderer);
});
}
@@ -20,8 +20,8 @@
package net.draycia.carbon.common.listeners;
import com.google.inject.Inject;
import net.draycia.carbon.api.CarbonChat;
import net.draycia.carbon.api.events.CarbonChatEvent;
import net.draycia.carbon.api.events.CarbonEventHandler;
import net.draycia.carbon.api.users.CarbonPlayer;
import net.draycia.carbon.common.messages.CarbonMessages;
import org.checkerframework.checker.nullness.qual.NonNull;
@@ -32,10 +32,10 @@ public class RadiusListener {
@Inject
public RadiusListener(
final CarbonChat carbonChat,
final CarbonEventHandler events,
final CarbonMessages carbonMessages
) {
carbonChat.eventHandler().subscribe(CarbonChatEvent.class, 0, false, event -> {
events.subscribe(CarbonChatEvent.class, 0, false, event -> {
if (event.chatChannel() == null || event.previewing()) {
return;
}
@@ -47,9 +47,9 @@ import java.util.Set;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import net.draycia.carbon.api.CarbonChat;
import net.draycia.carbon.api.events.CarbonEventHandler;
import net.draycia.carbon.api.users.CarbonPlayer;
import net.draycia.carbon.common.ForCarbon;
import net.draycia.carbon.common.DataDirectory;
import net.draycia.carbon.common.command.PlayerCommander;
import net.draycia.carbon.common.config.ConfigFactory;
import net.draycia.carbon.common.events.CarbonReloadEvent;
@@ -73,8 +73,8 @@ public final class CarbonMessageSource implements IMessageSource<Audience, Strin
@Inject
private CarbonMessageSource(
final CarbonChat carbonChat,
final @ForCarbon Path dataDirectory,
final CarbonEventHandler events,
final @DataDirectory Path dataDirectory,
final ConfigFactory configFactory,
final Logger logger
) throws IOException {
@@ -86,7 +86,7 @@ public final class CarbonMessageSource implements IMessageSource<Audience, Strin
this.reloadTranslations();
carbonChat.eventHandler().subscribe(CarbonReloadEvent.class, event -> {
events.subscribe(CarbonReloadEvent.class, event -> {
this.reloadTranslations();
});
}
@@ -22,7 +22,6 @@ package net.draycia.carbon.common.messaging;
import net.draycia.carbon.api.CarbonChatProvider;
import net.draycia.carbon.common.channels.CarbonChannelRegistry;
import net.draycia.carbon.common.messaging.packets.ChatMessagePacket;
import net.kyori.adventure.identity.Identity;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.minimessage.MiniMessage;
import net.kyori.adventure.text.minimessage.tag.Tag;
@@ -49,9 +48,12 @@ public final class CarbonChatPacketHandler extends AbstractMessagingHandler {
@Override
protected boolean handlePacket(final @NotNull Packet packet) {
if (!(packet instanceof ChatMessagePacket messagePacket)) {
this.logger.info("Messaging packet received - Not a ChatMessagePacket.");
return false;
}
this.logger.info("Messaging packet received");
final TagResolver.Builder tagResolver = TagResolver.builder();
for (final var entry : messagePacket.placeholders().entrySet()) {
@@ -64,7 +66,7 @@ public final class CarbonChatPacketHandler extends AbstractMessagingHandler {
for (final var recipient : CarbonChatProvider.carbonChat().server().players()) {
if (recipient.hasPermission(messagePacket.channelPermission() + ".see")) {
if (recipient.hasPermission("carbon.crossserver")) {
recipient.sendMessage(Identity.identity(messagePacket.userId()), component);
recipient.sendMessage(component);
}
}
}
@@ -25,7 +25,6 @@ import java.io.File;
import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import net.draycia.carbon.api.CarbonChat;
@@ -35,6 +34,8 @@ import net.draycia.carbon.common.channels.CarbonChannelRegistry;
import net.draycia.carbon.common.config.ConfigFactory;
import net.draycia.carbon.common.config.MessagingSettings;
import net.draycia.carbon.common.messaging.packets.ChatMessagePacket;
import net.draycia.carbon.common.util.ConcurrentUtil;
import net.draycia.carbon.common.util.ExceptionLoggingScheduledThreadPoolExecutor;
import ninja.egg82.messenger.MessagingService;
import ninja.egg82.messenger.NATSMessagingService;
import ninja.egg82.messenger.PacketManager;
@@ -58,8 +59,7 @@ public class MessagingManager {
private static final byte protocolVersion = 0;
private final ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor(10);
private final ScheduledExecutorService executorService;
private final PacketService packetService;
private MessagingService messagingService;
private final CarbonChat carbonChat;
@@ -80,6 +80,8 @@ public class MessagingManager {
PacketManager.register(ChatMessagePacket.class, ChatMessagePacket::new);
this.packetService = new PacketService(4, false, protocolVersion);
this.executorService = new ExceptionLoggingScheduledThreadPoolExecutor(10,
ConcurrentUtil.carbonThreadFactory(carbonChat.logger(), "MessagingManager"), carbonChat.logger());
this.carbonChat = carbonChat;
final MessagingHandlerImpl handlerImpl = new MessagingHandlerImpl(this.packetService);
@@ -143,12 +145,15 @@ public class MessagingManager {
final String channelName = "carbon-data";
if (!messagingSettings.enabled()) {
this.carbonChat.logger().info("Messaging services disabled in config. Cross-server will not work without this!");
this.messagingService = EMPTY_MESSAGING_SERVICE;
return;
}
switch (messagingSettings.brokerType()) {
case RABBITMQ -> {
this.carbonChat.logger().info("Initializing RabbitMQ Messaging services...");
final RabbitMQMessagingService.Builder builder = RabbitMQMessagingService.builder(packetService, name, channelName, this.carbonChat.serverId(), handlerImpl, 0L, false, packetDir)
.url(messagingSettings.url(), messagingSettings.port(), messagingSettings.vhost())
.timeout(5000);
@@ -160,6 +165,8 @@ public class MessagingManager {
this.messagingService = builder.build();
}
case NATS -> {
this.carbonChat.logger().info("Initializing NATS Messaging services...");
final NATSMessagingService.Builder builder = NATSMessagingService.builder(packetService, name, channelName, this.carbonChat.serverId(), handlerImpl, 0L, false, packetDir)
.url(messagingSettings.url(), messagingSettings.port())
.life(5000);
@@ -171,6 +178,8 @@ public class MessagingManager {
this.messagingService = builder.build();
}
case REDIS -> {
this.carbonChat.logger().info("Initializing Redis Messaging services...");
final RedisMessagingService.Builder builder = RedisMessagingService.builder(packetService, name, channelName, this.carbonChat.serverId(), handlerImpl, 0L, false, packetDir)
.url(messagingSettings.url(), messagingSettings.port());
@@ -0,0 +1,43 @@
/*
* 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.users;
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;
import net.draycia.carbon.api.users.UserManager;
import net.draycia.carbon.common.users.db.DatabaseUserManager;
import net.draycia.carbon.common.users.json.JSONUserManager;
/**
* Injection binding annotation for the backing {@link UserManagerInternal}
* (i.e. {@link JSONUserManager} or {@link DatabaseUserManager}),
* with the generic type of {@link CarbonPlayerCommon}.
*
* <p>Injecting {@link UserManagerInternal} or {@link UserManager} with a generic type of {@literal ?}, without this annotation,
* will inject the {@link PlatformUserManager}, which wraps the backing manager (this is generally what you want).</p>
*/
@BindingAnnotation
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.PARAMETER, ElementType.FIELD, ElementType.METHOD})
public @interface Backing {
}
@@ -0,0 +1,154 @@
/*
* 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.users;
import com.google.inject.MembersInjector;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Function;
import java.util.stream.Collectors;
import net.draycia.carbon.common.util.ConcurrentUtil;
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;
@DefaultQualifier(NonNull.class)
public abstract class CachingUserManager implements UserManagerInternal<CarbonPlayerCommon> {
protected final Logger logger;
protected final ExecutorService executor;
protected final ProfileResolver profileResolver;
private final MembersInjector<CarbonPlayerCommon> playerInjector;
private final ReentrantLock cacheLock;
private final Map<UUID, CompletableFuture<CarbonPlayerCommon>> cache;
protected CachingUserManager(
final Logger logger,
final ExecutorService executorService,
final ProfileResolver profileResolver,
final MembersInjector<CarbonPlayerCommon> playerInjector
) {
this.logger = logger;
this.executor = executorService;
this.profileResolver = profileResolver;
this.playerInjector = playerInjector;
this.cacheLock = new ReentrantLock();
this.cache = new HashMap<>();
}
protected abstract CarbonPlayerCommon loadOrCreate(UUID uuid);
@Override
public CompletableFuture<CarbonPlayerCommon> user(final UUID uuid) {
this.cacheLock.lock();
try {
return this.cache.computeIfAbsent(uuid, $ -> {
final CompletableFuture<CarbonPlayerCommon> future = CompletableFuture.supplyAsync(() -> {
final CarbonPlayerCommon player = this.loadOrCreate(uuid);
this.playerInjector.injectMembers(player);
return player;
}, this.executor);
this.attachPostLoad(uuid, future);
return future;
});
} finally {
this.cacheLock.unlock();
}
}
@Override
public void shutdown() {
this.cacheLock.lock();
try {
final Map<UUID, CompletableFuture<Void>> collect = List.copyOf(this.cache.keySet()).stream()
.collect(Collectors.toMap(Function.identity(), this::loggedOut));
for (final Map.Entry<UUID, CompletableFuture<Void>> entry : collect.entrySet()) {
try {
entry.getValue().join();
} catch (final Exception ex) {
this.logger.warn("Exception saving data for player with uuid " + entry.getKey());
}
}
ConcurrentUtil.shutdownExecutor(this.executor, TimeUnit.MILLISECONDS, 500);
} finally {
this.cacheLock.unlock();
}
}
@Override
public CompletableFuture<Void> loggedOut(final UUID uuid) {
this.cacheLock.lock();
try {
final @Nullable CompletableFuture<CarbonPlayerCommon> remove = this.cache.remove(uuid);
if (remove != null && remove.isDone()) { // don't need to save if it never finished loading
final @Nullable CarbonPlayerCommon join = remove.join();
if (join != null) {
return this.save(join);
}
}
return CompletableFuture.completedFuture(null);
} finally {
this.cacheLock.unlock();
}
}
@Override
public void cleanup() {
this.cacheLock.lock();
try {
for (final Map.Entry<UUID, CompletableFuture<CarbonPlayerCommon>> entry : Map.copyOf(this.cache).entrySet()) {
final @Nullable CarbonPlayerCommon getNow = entry.getValue().getNow(null);
if (getNow == null || !getNow.transientLoadedNeedsUnload()) {
continue;
}
this.cache.remove(entry.getKey());
this.save(getNow).exceptionally(thr -> {
this.logger.warn("Exception saving data for player {} with UUID {}", getNow.username(), getNow.uuid(), thr);
return null;
});
}
} finally {
this.cacheLock.unlock();
}
}
// Don't keep failed requests, so they can be retried on the next request
// The caller is expected to handle the error
private void attachPostLoad(final UUID uuid, final CompletableFuture<CarbonPlayerCommon> future) {
future.whenComplete((result, thr) -> {
if (result == null || thr != null) {
this.cacheLock.lock();
try {
this.cache.remove(uuid);
} finally {
this.cacheLock.unlock();
}
}
});
}
}
@@ -19,13 +19,17 @@
*/
package net.draycia.carbon.common.users;
import java.util.ArrayList;
import com.google.inject.Inject;
import java.time.Duration;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Stream;
import net.draycia.carbon.api.CarbonChat;
import net.draycia.carbon.api.CarbonChatProvider;
import net.draycia.carbon.api.channels.ChatChannel;
import net.draycia.carbon.api.users.CarbonPlayer;
import net.draycia.carbon.api.util.InventorySlot;
@@ -43,31 +47,34 @@ import org.jetbrains.annotations.NotNull;
@DefaultQualifier(NonNull.class)
public class CarbonPlayerCommon implements CarbonPlayer, ForwardingAudience.Single {
private final transient CarbonChat carbonChat = CarbonChatProvider.carbonChat();
private static final long KEEP_TRANSIENT_LOADS_FOR = Duration.ofMinutes(2).toMillis();
protected boolean muted = false;
protected boolean deafened = false;
private transient @MonotonicNonNull @Inject CarbonChat carbonChat;
private transient @MonotonicNonNull @Inject ProfileResolver profileResolver;
private transient long transientLoadedSince = -1;
protected @Nullable Key selectedChannel = null;
protected final PersistentUserProperty<Boolean> muted;
protected final PersistentUserProperty<Boolean> deafened;
protected final PersistentUserProperty<Key> selectedChannel;
// All players have these
protected transient @MonotonicNonNull String username = null;
protected @MonotonicNonNull UUID uuid;
// Display information
protected @Nullable Component displayName = null;
protected final PersistentUserProperty<Component> displayName;
// Whispers
protected transient @Nullable UUID lastWhisperTarget = null;
protected transient @Nullable UUID whisperReplyTarget = null;
// Administrative
protected boolean spying = false;
protected final PersistentUserProperty<Boolean> spying;
// Punishments
protected List<UUID> ignoredPlayers = new ArrayList<>();
protected final PersistentUserProperty<Set<UUID>> ignoredPlayers;
protected List<Key> leftChannels = new ArrayList<>();
protected final PersistentUserProperty<Set<Key>> leftChannels;
public CarbonPlayerCommon(
final boolean muted,
@@ -80,27 +87,54 @@ public class CarbonPlayerCommon implements CarbonPlayer, ForwardingAudience.Sing
final @Nullable UUID whisperReplyTarget,
final boolean spying
) {
this.muted = muted;
this.deafened = deafened;
this.selectedChannel = selectedChannel;
this.muted = PersistentUserProperty.of(muted);
this.deafened = PersistentUserProperty.of(deafened);
this.selectedChannel = PersistentUserProperty.of(selectedChannel);
this.username = username;
this.uuid = uuid;
this.displayName = displayName;
this.displayName = PersistentUserProperty.of(displayName);
this.lastWhisperTarget = lastWhisperTarget;
this.whisperReplyTarget = whisperReplyTarget;
this.spying = spying;
this.spying = PersistentUserProperty.of(spying);
this.ignoredPlayers = PersistentUserProperty.of(Collections.emptySet());
this.leftChannels = PersistentUserProperty.of(Collections.emptySet());
}
public CarbonPlayerCommon(
final String username,
final UUID uuid
) {
this.muted = PersistentUserProperty.of(false);
this.deafened = PersistentUserProperty.of(false);
this.selectedChannel = PersistentUserProperty.empty();
this.displayName = PersistentUserProperty.empty();
this.spying = PersistentUserProperty.of(false);
this.ignoredPlayers = PersistentUserProperty.of(Collections.emptySet());
this.leftChannels = PersistentUserProperty.of(Collections.emptySet());
this.username = username;
this.uuid = uuid;
}
public CarbonPlayerCommon() {
this.muted = PersistentUserProperty.of(false);
this.deafened = PersistentUserProperty.of(false);
this.selectedChannel = PersistentUserProperty.empty();
this.displayName = PersistentUserProperty.empty();
this.spying = PersistentUserProperty.of(false);
this.ignoredPlayers = PersistentUserProperty.of(Collections.emptySet());
this.leftChannels = PersistentUserProperty.of(Collections.emptySet());
}
public boolean needsSave() {
return Stream.of(
this.muted,
this.deafened,
this.selectedChannel,
this.displayName,
this.spying,
this.ignoredPlayers,
this.leftChannels
).anyMatch(PersistentUserProperty::changed);
}
@Override
@@ -119,20 +153,12 @@ public class CarbonPlayerCommon implements CarbonPlayer, ForwardingAudience.Sing
@Override
public @Nullable Component displayName() {
if (this.displayName != null) {
return this.displayName;
}
return null;
return this.displayName.orNull();
}
@Override
public void displayName(final @Nullable Component displayName) {
this.displayName = displayName;
if (this.carbonChat.server().userManager() instanceof SaveOnChange userManager) {
userManager.saveDisplayName(this.uuid(), displayName);
}
this.displayName.set(displayName);
}
@Override
@@ -152,25 +178,21 @@ public class CarbonPlayerCommon implements CarbonPlayer, ForwardingAudience.Sing
@Override
public boolean muted() {
return this.muted;
return this.muted.get();
}
@Override
public void muted(final boolean muted) {
this.muted = muted;
if (this.carbonChat.server().userManager() instanceof SaveOnChange userManager) {
userManager.saveMuted(this.uuid(), muted);
}
this.muted.set(muted);
}
public List<UUID> ignoredPlayers() {
return this.ignoredPlayers;
public Set<UUID> ignoredPlayers() {
return this.ignoredPlayers.get();
}
@Override
public boolean ignoring(final UUID player) {
return this.ignoredPlayers.contains(player);
return this.ignoredPlayers.get().contains(player);
}
@Override
@@ -178,23 +200,23 @@ public class CarbonPlayerCommon implements CarbonPlayer, ForwardingAudience.Sing
return this.ignoring(player.uuid());
}
public void ignoring(final UUID player, final boolean nowIgnoring, final boolean internal) {
final Set<UUID> newIgnored = new HashSet<>(this.ignoredPlayers.get());
if (nowIgnoring) {
newIgnored.add(player);
} else {
newIgnored.remove(player);
}
if (internal) {
this.ignoredPlayers.internalSet(Collections.unmodifiableSet(newIgnored));
} else {
this.ignoredPlayers.set(Collections.unmodifiableSet(newIgnored));
}
}
@Override
public void ignoring(final UUID player, final boolean nowIgnoring) {
if (nowIgnoring) {
if (!this.ignoredPlayers.contains(player)) {
this.ignoredPlayers.add(player);
}
} else {
this.ignoredPlayers.remove(player);
}
if (this.carbonChat.server().userManager() instanceof SaveOnChange userManager) {
if (nowIgnoring) {
userManager.addIgnore(this.uuid, player);
} else {
userManager.removeIgnore(this.uuid, player);
}
}
this.ignoring(player, nowIgnoring, false);
}
@Override
@@ -204,30 +226,22 @@ public class CarbonPlayerCommon implements CarbonPlayer, ForwardingAudience.Sing
@Override
public boolean deafened() {
return this.deafened;
return this.deafened.get();
}
@Override
public void deafened(final boolean deafened) {
this.deafened = deafened;
if (this.carbonChat.server().userManager() instanceof SaveOnChange userManager) {
userManager.saveDeafened(this.uuid(), deafened);
}
this.deafened.set(deafened);
}
@Override
public boolean spying() {
return this.spying;
return this.spying.get();
}
@Override
public void spying(final boolean spying) {
this.spying = spying;
if (this.carbonChat.server().userManager() instanceof SaveOnChange userManager) {
userManager.saveSpying(this.uuid(), spying);
}
this.spying.set(spying);
}
@Override
@@ -253,10 +267,6 @@ public class CarbonPlayerCommon implements CarbonPlayer, ForwardingAudience.Sing
@Override
public void whisperReplyTarget(final @Nullable UUID whisperReplyTarget) {
this.whisperReplyTarget = whisperReplyTarget;
if (this.carbonChat.server().userManager() instanceof SaveOnChange userManager) {
userManager.saveWhisperReplyTarget(this.uuid(), whisperReplyTarget);
}
}
@Override
@@ -267,10 +277,6 @@ public class CarbonPlayerCommon implements CarbonPlayer, ForwardingAudience.Sing
@Override
public void lastWhisperTarget(final @Nullable UUID lastWhisperTarget) {
this.lastWhisperTarget = lastWhisperTarget;
if (this.carbonChat.server().userManager() instanceof SaveOnChange userManager) {
userManager.saveLastWhisperTarget(this.uuid(), lastWhisperTarget);
}
}
@Override
@@ -285,23 +291,37 @@ public class CarbonPlayerCommon implements CarbonPlayer, ForwardingAudience.Sing
@Override
public List<Key> leftChannels() {
return this.leftChannels;
return List.copyOf(this.leftChannels.get());
}
public void joinChannel(final Key key, final boolean internal) {
final Set<Key> newKeys = new HashSet<>(this.leftChannels.get());
newKeys.remove(key);
if (internal) {
this.leftChannels.internalSet(Collections.unmodifiableSet(newKeys));
} else {
this.leftChannels.set(Collections.unmodifiableSet(newKeys));
}
}
@Override
public void joinChannel(final ChatChannel channel) {
this.leftChannels.remove(channel.key());
if (this.carbonChat.server().userManager() instanceof SaveOnChange userManager) {
userManager.removeLeftChannel(this.uuid(), channel.key());
this.joinChannel(channel.key(), false);
}
public void leaveChannel(final ChatChannel channel, final boolean internal) {
final Set<Key> newKeys = new HashSet<>(this.leftChannels.get());
newKeys.add(channel.key());
if (internal) {
this.leftChannels.internalSet(Collections.unmodifiableSet(newKeys));
} else {
this.leftChannels.set(Collections.unmodifiableSet(newKeys));
}
}
@Override
public void leaveChannel(final ChatChannel channel) {
this.leftChannels.add(channel.key());
if (this.carbonChat.server().userManager() instanceof SaveOnChange userManager) {
userManager.addLeftChannel(this.uuid(), channel.key());
}
this.leaveChannel(channel, false);
}
@Override
@@ -316,27 +336,23 @@ public class CarbonPlayerCommon implements CarbonPlayer, ForwardingAudience.Sing
@Override
public @Nullable ChatChannel selectedChannel() {
if (this.selectedChannel == null) {
if (!this.selectedChannel.hasValue()) {
return this.carbonChat.channelRegistry().defaultValue();
}
return this.carbonChat.channelRegistry().get(this.selectedChannel);
return this.carbonChat.channelRegistry().get(this.selectedChannel.get());
}
public @Nullable Key selectedChannelKey() {
return this.selectedChannel;
return this.selectedChannel.orNull();
}
@Override
public void selectedChannel(final @Nullable ChatChannel chatChannel) {
if (chatChannel == null) {
this.selectedChannel = null;
this.selectedChannel.set(null);
} else {
this.selectedChannel = chatChannel.key();
}
if (this.carbonChat.server().userManager() instanceof SaveOnChange userManager) {
userManager.saveSelectedChannel(this.uuid(), this.selectedChannel);
this.selectedChannel.set(chatChannel.key());
}
}
@@ -353,8 +369,10 @@ public class CarbonPlayerCommon implements CarbonPlayer, ForwardingAudience.Sing
@Override
public String username() {
if (this.username == null) {
this.username = Objects.requireNonNull(CarbonChatProvider.carbonChat().server()
.resolveName(this.uuid).join());
this.username = Objects.requireNonNull(
this.profileResolver.resolveName(this.uuid).join(),
"name"
);
}
return this.username;
@@ -364,9 +382,21 @@ public class CarbonPlayerCommon implements CarbonPlayer, ForwardingAudience.Sing
this.username = username;
}
public void markTransientLoaded(final boolean value) {
if (value) {
this.transientLoadedSince = System.currentTimeMillis();
} else {
this.transientLoadedSince = -1;
}
}
public boolean transientLoadedNeedsUnload() {
return this.transientLoadedSince != -1 && System.currentTimeMillis() - this.transientLoadedSince > KEEP_TRANSIENT_LOADS_FOR;
}
@Override
public boolean hasCustomDisplayName() {
return this.displayName != null;
return this.displayName.hasValue();
}
@Override
@@ -0,0 +1,244 @@
/*
* 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.users;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.TypeAdapter;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import com.google.inject.Inject;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import net.draycia.carbon.common.util.ConcurrentUtil;
import net.draycia.carbon.common.util.FastUuidSansHyphens;
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;
@DefaultQualifier(NonNull.class)
public final class MojangProfileResolver implements ProfileResolver {
private final HttpClient client;
private final Gson gson;
private final ExecutorService executorService;
private final Map<String, CompletableFuture<@Nullable BasicLookupResponse>> pendingUuidLookups = new HashMap<>();
private final Map<UUID, CompletableFuture<@Nullable BasicLookupResponse>> pendingUsernameLookups = new HashMap<>();
private final ProfileCache cache;
private final RateLimiter globalRateLimit;
private final RateLimiter uuidToProfileRateLimit;
@Inject
private MojangProfileResolver(final Logger logger, final ProfileCache cache) {
this.client = HttpClient.newHttpClient();
this.gson = new GsonBuilder()
.registerTypeAdapter(UUID.class, new UUIDTypeAdapter())
.create();
this.executorService = Executors.newFixedThreadPool(2, ConcurrentUtil.carbonThreadFactory(logger, "MojangProfileResolver"));
this.cache = cache;
this.globalRateLimit = new RateLimiter(600);
this.uuidToProfileRateLimit = new RateLimiter(200);
}
@Override
public synchronized CompletableFuture<@Nullable UUID> resolveUUID(final String username, final boolean cacheOnly) {
if (username.length() > 25 || username.length() < 1) { // Invalid names
return CompletableFuture.completedFuture(null);
}
if (cacheOnly || this.cache.hasCachedEntry(username)) {
return CompletableFuture.completedFuture(this.cache.cachedId(username));
}
return this.pendingUuidLookups.computeIfAbsent(username, $ -> {
if (!this.globalRateLimit.canSubmit()) {
return CompletableFuture.completedFuture(null);
}
final CompletableFuture<@Nullable BasicLookupResponse> mojangLookup = CompletableFuture.supplyAsync(() -> {
try {
final HttpRequest request = createRequest(
"https://api.mojang.com/users/profiles/minecraft/" + username);
return this.sendRequest(request);
} catch (final Exception e) {
throw new RuntimeException("Exception resolving UUID for name " + username, e);
}
}, this.executorService);
mojangLookup.whenComplete((result, $$$) -> {
synchronized (this) {
this.cache.cache(result == null ? null : result.id(), username);
this.pendingUuidLookups.remove(username);
}
});
return mojangLookup;
}).thenApply(response -> {
if (response == null) {
return null;
}
return response.id();
});
}
@Override
public synchronized CompletableFuture<@Nullable String> resolveName(final UUID uuid, final boolean cacheOnly) {
if (cacheOnly || this.cache.hasCachedEntry(uuid)) {
return CompletableFuture.completedFuture(this.cache.cachedName(uuid));
}
return this.pendingUsernameLookups.computeIfAbsent(uuid, $ -> {
final boolean globalLimited = !this.globalRateLimit.canSubmit();
final boolean nameLimited = !this.uuidToProfileRateLimit.canSubmit();
if (globalLimited || nameLimited) {
if (nameLimited && !globalLimited) {
// Add back to the global limit if we didn't actually make a request due to uuidToProfileRateLimit
this.globalRateLimit.available.getAndIncrement();
}
return CompletableFuture.completedFuture(null);
}
final CompletableFuture<@Nullable BasicLookupResponse> mojangLookup = CompletableFuture.supplyAsync(() -> {
try {
final HttpRequest request = createRequest(
"https://api.mojang.com/user/profile/" + uuid.toString().replace("-", ""));
return this.sendRequest(request);
} catch (final Exception e) {
throw new RuntimeException("Exception resolving name for UUID " + uuid, e);
}
}, this.executorService);
mojangLookup.whenComplete((result, $$$) -> {
synchronized (this) {
this.cache.cache(uuid, result == null ? null : result.name());
this.pendingUsernameLookups.remove(uuid);
}
});
return mojangLookup;
}).thenApply(response -> {
if (response == null) {
return null;
}
return response.name();
});
}
private static HttpRequest createRequest(final String uri) throws URISyntaxException {
return HttpRequest.newBuilder()
.uri(new URI(uri))
.GET()
.build();
}
private @Nullable BasicLookupResponse sendRequest(final HttpRequest request) throws IOException, InterruptedException {
final HttpResponse<String> response = this.client.send(request, HttpResponse.BodyHandlers.ofString());
if (response == null) {
throw new RuntimeException("Null response for request " + request);
} else if (response.statusCode() == 429) {
throw new RuntimeException("Got rate-limited by Mojang, could not fulfill request: " + request);
} else if (response.statusCode() == 404) {
// No such profile
return null;
} else if (response.statusCode() == 400) {
// Invalid name/UUID
return null;
} else if (response.statusCode() != 200) {
throw new RuntimeException("Received non-200 response code (" + response.statusCode() + ") for request " + request + ": " + response.body());
}
final BasicLookupResponse basicLookupResponse = this.gson.fromJson(response.body(), new TypeToken<BasicLookupResponse>() {}.getType());
if (basicLookupResponse == null) {
throw new RuntimeException("Malformed response body for request " + request + ": '" + response.body() + "'");
}
return basicLookupResponse;
}
@Override
public void shutdown() {
ConcurrentUtil.shutdownExecutor(this.executorService, TimeUnit.MILLISECONDS, 500);
this.globalRateLimit.shutdown();
this.uuidToProfileRateLimit.shutdown();
}
private record BasicLookupResponse(UUID id, String name) {
}
private static final class UUIDTypeAdapter extends TypeAdapter<UUID> {
private UUIDTypeAdapter() {
}
@Override
public void write(final JsonWriter out, final UUID value) throws IOException {
out.value(FastUuidSansHyphens.toString(value));
}
@Override
public UUID read(final JsonReader in) throws IOException {
final String input = in.nextString();
return FastUuidSansHyphens.parseUuid(input);
}
}
private static final class RateLimiter {
private final AtomicInteger available;
private final Timer timer;
private RateLimiter(final int perTenMinutes) {
this.timer = new Timer("CarbonChat " + this);
this.available = new AtomicInteger(perTenMinutes);
this.timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
RateLimiter.this.available.set(perTenMinutes);
}
}, 0L, Duration.ofMinutes(10).toMillis());
}
boolean canSubmit() {
return this.available.getAndDecrement() >= 0;
}
void shutdown() {
this.timer.cancel();
}
}
}
@@ -0,0 +1,104 @@
/*
* 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.users;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Objects;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.checkerframework.framework.qual.DefaultQualifier;
import org.jetbrains.annotations.ApiStatus;
@DefaultQualifier(NonNull.class)
public final class PersistentUserProperty<T> {
private @Nullable T value;
private boolean changed = false;
public PersistentUserProperty(final @Nullable T value) {
this.value = value;
}
/**
* Set the value without setting the changed flag. This is a hack.
*
* @param value value
*/
@ApiStatus.Internal
public void internalSet(final @Nullable T value) {
this.value = value;
}
public void set(final @Nullable T value) {
if (Objects.equals(value, this.value)) {
return;
}
this.value = value;
this.changed = true;
}
public T get() {
return Objects.requireNonNull(this.value, "value required but not present");
}
public boolean hasValue() {
return this.value != null;
}
public @Nullable T orNull() {
return this.value;
}
public boolean changed() {
return this.changed;
}
public static <T> PersistentUserProperty<T> of(final @Nullable T value) {
return new PersistentUserProperty<>(value);
}
public static <T> PersistentUserProperty<T> empty() {
return new PersistentUserProperty<>(null);
}
public static final class Serializer implements JsonSerializer<PersistentUserProperty<?>>, JsonDeserializer<PersistentUserProperty<?>> {
@Override
public PersistentUserProperty<?> deserialize(final JsonElement json, final Type typeOfT, final JsonDeserializationContext context) throws JsonParseException {
final Type propType = ((ParameterizedType) typeOfT).getActualTypeArguments()[0];
return new PersistentUserProperty<>(context.deserialize(json, propType));
}
@Override
public JsonElement serialize(final PersistentUserProperty<?> src, final Type typeOfSrc, final JsonSerializationContext context) {
final Type propType = ((ParameterizedType) typeOfSrc).getActualTypeArguments()[0];
return context.serialize(src.orNull(), propType);
}
}
}
@@ -0,0 +1,69 @@
/*
* 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.users;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.framework.qual.DefaultQualifier;
@DefaultQualifier(NonNull.class)
public abstract class PlatformUserManager<C extends WrappedCarbonPlayer> implements UserManagerInternal<C> {
private final UserManagerInternal<CarbonPlayerCommon> backingManager;
public PlatformUserManager(final UserManagerInternal<CarbonPlayerCommon> backingManager) {
this.backingManager = backingManager;
}
@Override
public CompletableFuture<C> user(final UUID uuid) {
return this.backingManager.user(uuid).thenApply(common -> {
final C wrapped = this.wrap(common);
this.updateTransientLoadedStatus(wrapped);
return wrapped;
});
}
protected abstract C wrap(final CarbonPlayerCommon common);
protected abstract void updateTransientLoadedStatus(C wrapped);
@Override
public void shutdown() {
this.backingManager.shutdown();
}
@Override
public CompletableFuture<Void> save(final C player) {
return this.backingManager.save(player.carbonPlayerCommon());
}
@Override
public CompletableFuture<Void> loggedOut(final UUID uuid) {
return this.backingManager.loggedOut(uuid);
}
@Override
public void cleanup() {
this.backingManager.cleanup();
}
}
@@ -0,0 +1,191 @@
/*
* 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.users;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Duration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import net.draycia.carbon.common.DataDirectory;
import net.draycia.carbon.common.serialisation.gson.UUIDSerializerGson;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.checkerframework.framework.qual.DefaultQualifier;
@DefaultQualifier(NonNull.class)
@Singleton
public final class ProfileCache {
private static final long REMOVE_AFTER = Duration.ofDays(7).toMillis();
private static final long REMOVE_NULL_IDS_AFTER = Duration.ofHours(1).toMillis();
private final Gson gson;
private final Path cacheFile;
private final Map<UUID, CacheEntry> byId;
private final Map<String, CacheEntry> byName;
private final Set<CacheEntry> entries;
private record CacheEntry(@Nullable UUID uuid, @Nullable String name, long updated) {
}
@Inject
private ProfileCache(final @DataDirectory Path dataDirectory) {
this.gson = new GsonBuilder()
.registerTypeAdapter(UUID.class, new UUIDSerializerGson())
.create();
this.cacheFile = dataDirectory.resolve("users/profile_cache.json");
this.byId = new HashMap<>();
this.byName = new HashMap<>();
this.entries = new HashSet<>();
this.load();
}
public synchronized @Nullable String cachedName(final UUID id) {
final @Nullable CacheEntry entry = this.byId.get(id);
if (entry == null) {
return null;
} else if (entry.updated() < cutoff()) {
return null;
}
return entry.name();
}
public synchronized @Nullable UUID cachedId(final String name) {
final @Nullable CacheEntry entry = this.byName.get(name);
if (entry == null) {
return null;
} else if (entry.updated() < cutoff()) {
return null;
}
return entry.uuid();
}
public synchronized boolean hasCachedEntry(final String name) {
final @Nullable CacheEntry entry = this.byName.get(name);
if (entry == null) {
return false;
}
return entry.updated() >= cutoff();
}
public synchronized boolean hasCachedEntry(final UUID uuid) {
final @Nullable CacheEntry entry = this.byId.get(uuid);
if (entry == null) {
return false;
}
return entry.updated() >= cutoff();
}
public synchronized void cache(final @Nullable UUID uuid, final @Nullable String name) {
final @Nullable CacheEntry r1 = uuid == null ? null : this.byId.remove(uuid);
final @Nullable CacheEntry r2 = name == null ? null : this.byName.remove(name);
if (r1 != null) {
this.entries.remove(r1);
}
if (r2 != null) {
this.entries.remove(r2);
}
final CacheEntry entry = new CacheEntry(uuid, name, System.currentTimeMillis());
this.entries.add(entry);
if (entry.name() != null) {
this.byName.put(entry.name(), entry);
}
if (entry.uuid() != null) {
this.byId.put(entry.uuid(), entry);
}
}
private synchronized void cleanup() {
final long cutoff = cutoff();
final long nullIdCutoff = nullIdCutoff();
for (final Iterator<CacheEntry> iterator = this.entries.iterator(); iterator.hasNext();) {
final CacheEntry entry = iterator.next();
if (entry.updated() < cutoff || entry.uuid() == null && entry.updated() < nullIdCutoff) {
iterator.remove();
if (entry.uuid() != null) {
this.byId.remove(entry.uuid());
}
if (entry.name() != null) {
this.byName.remove(entry.name());
}
}
}
}
private static long nullIdCutoff() {
return System.currentTimeMillis() - REMOVE_NULL_IDS_AFTER;
}
private static long cutoff() {
return System.currentTimeMillis() - REMOVE_AFTER;
}
private synchronized void load() {
this.entries.clear();
this.byId.clear();
this.byName.clear();
if (!Files.exists(this.cacheFile)) {
return;
}
try {
try (final BufferedReader reader = Files.newBufferedReader(this.cacheFile)) {
final Set<CacheEntry> load = this.gson.fromJson(reader, new TypeToken<Set<CacheEntry>>() {}.getType());
this.entries.addAll(load);
for (final CacheEntry entry : this.entries) {
if (entry.name() != null) {
this.byName.put(entry.name(), entry);
}
if (entry.uuid() != null) {
this.byId.put(entry.uuid(), entry);
}
}
}
} catch (final IOException ex) {
throw new RuntimeException("Failed to load cache", ex);
}
}
public synchronized void save() {
this.cleanup();
try {
Files.createDirectories(this.cacheFile.getParent());
try (final BufferedWriter writer = Files.newBufferedWriter(this.cacheFile)) {
this.gson.toJson(this.entries, writer);
}
} catch (final IOException ex) {
throw new RuntimeException("Failed to save cache", ex);
}
}
}
@@ -20,35 +20,26 @@
package net.draycia.carbon.common.users;
import java.util.UUID;
import net.kyori.adventure.key.Key;
import net.kyori.adventure.text.Component;
import java.util.concurrent.CompletableFuture;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.checkerframework.framework.qual.DefaultQualifier;
@DefaultQualifier(NonNull.class)
public interface SaveOnChange {
public interface ProfileResolver {
int saveDisplayName(final UUID id, final @Nullable Component displayName);
CompletableFuture<@Nullable UUID> resolveUUID(String username, boolean cacheOnly);
int saveMuted(final UUID id, final boolean muted);
default CompletableFuture<@Nullable UUID> resolveUUID(final String username) {
return this.resolveUUID(username, false);
}
int saveDeafened(final UUID id, final boolean deafened);
CompletableFuture<@Nullable String> resolveName(UUID uuid, boolean cacheOnly);
int saveSpying(final UUID id, final boolean spying);
default CompletableFuture<@Nullable String> resolveName(final UUID uuid) {
return this.resolveName(uuid, false);
}
int saveSelectedChannel(final UUID id, final @Nullable Key selectedChannel);
int saveLastWhisperTarget(final UUID id, final @Nullable UUID lastWhisperTarget);
int saveWhisperReplyTarget(final UUID id, final @Nullable UUID whisperReplyTarget);
int addIgnore(final UUID id, final UUID ignoredPlayer);
int removeIgnore(final UUID id, final UUID ignoredPlayer);
int addLeftChannel(final UUID id, final Key channel);
int removeLeftChannel(final UUID id, final Key channel);
void shutdown();
}
@@ -1,89 +0,0 @@
/*
* 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.users;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import net.draycia.carbon.api.CarbonChat;
import net.draycia.carbon.api.users.ComponentPlayerResult;
import net.draycia.carbon.api.users.UserManager;
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 static net.kyori.adventure.text.Component.text;
@DefaultQualifier(NonNull.class)
public class ProxiedCachingUserManager implements UserManager<CarbonPlayerCommon> {
private final Map<UUID, CarbonPlayerCommon> userCache = new ConcurrentHashMap<>();
private final UserManager<CarbonPlayerCommon> proxiedUserManager;
private final CarbonChat carbonChat;
public ProxiedCachingUserManager(final UserManager<CarbonPlayerCommon> proxiedUserManager, final CarbonChat carbonChat) {
this.proxiedUserManager = proxiedUserManager;
this.carbonChat = carbonChat;
}
@Override
public CompletableFuture<ComponentPlayerResult<CarbonPlayerCommon>> carbonPlayer(final UUID uuid) {
return CompletableFuture.supplyAsync(() -> {
final @Nullable CarbonPlayerCommon cachedPlayer = this.userCache.get(uuid);
if (cachedPlayer != null) {
return new ComponentPlayerResult<>(cachedPlayer, Component.empty());
}
final ComponentPlayerResult<CarbonPlayerCommon> result = this.proxiedUserManager.carbonPlayer(uuid).join();
if (result.player() != null) {
this.userCache.put(uuid, result.player());
return new ComponentPlayerResult<>(result.player(), Component.empty());
}
final @Nullable String name = this.carbonChat.server().resolveName(uuid).join();
if (name != null) {
final CarbonPlayerCommon player = new CarbonPlayerCommon(name, uuid);
this.userCache.put(uuid, player);
return new ComponentPlayerResult<>(player, Component.empty());
}
return new ComponentPlayerResult<>(null, text("Name not found for uuid!"));
});
}
@Override
public CompletableFuture<ComponentPlayerResult<CarbonPlayerCommon>> savePlayer(final CarbonPlayerCommon player) {
return this.proxiedUserManager.savePlayer(player);
}
@Override
public CompletableFuture<ComponentPlayerResult<CarbonPlayerCommon>> saveAndInvalidatePlayer(final CarbonPlayerCommon player) {
return this.proxiedUserManager.saveAndInvalidatePlayer(player);
}
}
@@ -0,0 +1,40 @@
/*
* 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.users;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import net.draycia.carbon.api.users.CarbonPlayer;
import net.draycia.carbon.api.users.UserManager;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.framework.qual.DefaultQualifier;
@DefaultQualifier(NonNull.class)
public interface UserManagerInternal<C extends CarbonPlayer> extends UserManager<C> {
void shutdown();
CompletableFuture<Void> save(C player);
CompletableFuture<Void> loggedOut(UUID uuid);
void cleanup();
}
@@ -19,35 +19,51 @@
*/
package net.draycia.carbon.common.users.db;
import com.google.inject.MembersInjector;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import net.draycia.carbon.api.users.ComponentPlayerResult;
import net.draycia.carbon.api.users.UserManager;
import java.util.concurrent.Executors;
import net.draycia.carbon.common.users.CachingUserManager;
import net.draycia.carbon.common.users.CarbonPlayerCommon;
import net.draycia.carbon.common.users.ProfileResolver;
import net.draycia.carbon.common.util.ConcurrentUtil;
import net.kyori.adventure.key.Key;
import org.apache.logging.log4j.Logger;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.framework.qual.DefaultQualifier;
import org.jdbi.v3.core.Jdbi;
import org.jdbi.v3.core.statement.PreparedBatch;
import org.jdbi.v3.core.statement.Update;
import static net.kyori.adventure.text.Component.empty;
@DefaultQualifier(NonNull.class)
public abstract class AbstractUserManager implements UserManager<CarbonPlayerCommon> {
public abstract class DatabaseUserManager extends CachingUserManager {
protected final Jdbi jdbi;
protected final QueriesLocator locator;
protected AbstractUserManager(final Jdbi jdbi, final QueriesLocator locator) {
protected DatabaseUserManager(
final Jdbi jdbi,
final QueriesLocator locator,
final Logger logger,
final ProfileResolver profileResolver,
final MembersInjector<CarbonPlayerCommon> playerInjector
) {
super(
logger,
Executors.newSingleThreadExecutor(ConcurrentUtil.carbonThreadFactory(logger, "DatabaseUserManager")),
profileResolver,
playerInjector
);
this.jdbi = jdbi;
this.locator = locator;
}
@Override
final public CompletableFuture<ComponentPlayerResult<CarbonPlayerCommon>> savePlayer(final CarbonPlayerCommon player) {
return CompletableFuture.supplyAsync(() -> this.jdbi.withHandle(handle -> {
public final CompletableFuture<Void> save(final CarbonPlayerCommon player) {
if (!player.needsSave()) {
return CompletableFuture.completedFuture(null);
}
return CompletableFuture.runAsync(() -> this.jdbi.withHandle(handle -> {
this.bindPlayerArguments(handle.createUpdate(this.locator.query("save-player")), player)
.execute();
@@ -70,9 +86,10 @@ public abstract class AbstractUserManager implements UserManager<CarbonPlayerCom
batch.execute();
}
// TODO: save ignoredplayers
return new ComponentPlayerResult<>(player, empty());
}));
return null;
}), this.executor);
}
abstract protected Update bindPlayerArguments(final Update update, final CarbonPlayerCommon player);
}
@@ -0,0 +1,44 @@
/*
* 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.users.db;
import java.sql.ResultSet;
import java.sql.SQLException;
import net.draycia.carbon.common.util.Strings;
import net.kyori.adventure.key.Key;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.intellij.lang.annotations.Subst;
import org.jdbi.v3.core.mapper.ColumnMapper;
import org.jdbi.v3.core.statement.StatementContext;
public class KeyColumnMapper implements ColumnMapper<Key> {
@Override
public Key map(final ResultSet rs, final int columnNumber, final StatementContext ctx) throws SQLException {
final @Nullable @Subst("key:value") String keyValue = Strings.trim(rs.getString(columnNumber));
if (keyValue != null) {
return Key.key(keyValue);
}
return null;
}
}
@@ -23,6 +23,7 @@ import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.UUID;
import net.draycia.carbon.common.users.CarbonPlayerCommon;
import net.draycia.carbon.common.util.Strings;
import net.kyori.adventure.key.Key;
import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer;
import org.checkerframework.checker.nullness.qual.Nullable;
@@ -34,17 +35,17 @@ public class MySQLPlayerRowMapper implements RowMapper<CarbonPlayerCommon> {
@Override
public CarbonPlayerCommon map(final ResultSet rs, final StatementContext ctx) throws SQLException {
final String id = rs.getString("id");
final @Nullable String lastWhisperTarget = rs.getString("lastwhispertarget");
final @Nullable String whisperReplyTarget = rs.getString("whisperreplytarget");
final @Nullable @Subst("carbon:global") String selectedChannel = rs.getString("selectedchannel");
final @Nullable String displayName = rs.getString("displayname");
final String id = Strings.trim(rs.getString("id"));
final @Nullable String lastWhisperTarget = Strings.trim(rs.getString("lastwhispertarget"));
final @Nullable String whisperReplyTarget = Strings.trim(rs.getString("whisperreplytarget"));
final @Nullable @Subst("carbon:global") String selectedChannel = Strings.trim(rs.getString("selectedchannel"));
final @Nullable String displayName = Strings.trim(rs.getString("displayname"));
return new CarbonPlayerCommon(
rs.getBoolean("muted"),
rs.getBoolean("deafened"),
selectedChannel == null ? null : Key.key(selectedChannel),
rs.getString("username"),
Strings.trim(rs.getString("username")),
UUID.fromString(id),
displayName == null ? null : GsonComponentSerializer.gson().deserialize(displayName),
lastWhisperTarget == null ? null : UUID.fromString(lastWhisperTarget),
@@ -1,66 +0,0 @@
/*
* 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.users.db.mysql;
import java.util.UUID;
import net.draycia.carbon.common.users.SaveOnChange;
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.jdbi.v3.sqlobject.statement.SqlUpdate;
@DefaultQualifier(NonNull.class)
public interface MySQLSaveOnChange extends SaveOnChange {
@SqlUpdate("UPDATE carbon_users SET displayname = :displayName WHERE id = UNHEX(REPLACE(:id, '-', ''))")
int saveDisplayName(final UUID id, final @Nullable Component displayName);
@SqlUpdate("UPDATE carbon_users SET muted = :muted WHERE id = UNHEX(REPLACE(:id, '-', ''))")
int saveMuted(final UUID id, final boolean muted);
@SqlUpdate("UPDATE carbon_users SET deafened = :deafened WHERE id = UNHEX(REPLACE(:id, '-', ''))")
int saveDeafened(final UUID id, final boolean deafened);
@SqlUpdate("UPDATE carbon_users SET spying = :spying WHERE id = UNHEX(REPLACE(:id, '-', ''))")
int saveSpying(final UUID id, final boolean spying);
@SqlUpdate("UPDATE carbon_users SET selectedchannel = :selectedChannel WHERE id = UNHEX(REPLACE(:id, '-', ''))")
int saveSelectedChannel(final UUID id, final @Nullable Key selectedChannel);
@SqlUpdate("UPDATE carbon_users SET lastwhispertarget = UNHEX(REPLACE(:lastWhisperTarget, '-', '')) WHERE id = UNHEX(REPLACE(:id, '-', ''))")
int saveLastWhisperTarget(final UUID id, final @Nullable UUID lastWhisperTarget);
@SqlUpdate("UPDATE carbon_users SET whisperreplytarget = UNHEX(REPLACE(:whisperReplyTarget, '-', '')) WHERE id = UNHEX(REPLACE(:id, '-', ''))")
int saveWhisperReplyTarget(final UUID id, final @Nullable UUID whisperReplyTarget);
@SqlUpdate("INSERT IGNORE INTO carbon_ignores (id, ignoredplayer) VALUES (UNHEX(REPLACE(:id, '-', '')), UNHEX(REPLACE(:ignoredPlayer, '-', '')))")
int addIgnore(final UUID id, final UUID ignoredPlayer);
@SqlUpdate("DELETE FROM carbon_ignores WHERE id = UNHEX(REPLACE(:id, '-', '')) AND ignoredplayer = UNHEX(REPLACE(:ignoredPlayer, '-', ''))")
int removeIgnore(final UUID id, final UUID ignoredPlayer);
@SqlUpdate("INSERT IGNORE INTO carbon_leftchannels (id, channel) VALUES (UNHEX(REPLACE(:id, '-', '')), :channel)")
int addLeftChannel(final UUID id, final Key channel);
@SqlUpdate("DELETE FROM carbon_leftchannels WHERE id = UNHEX(REPLACE(:id, '-', '')) AND channel = :channel")
int removeLeftChannel(final UUID id, final Key channel);
}
@@ -19,31 +19,30 @@
*/
package net.draycia.carbon.common.users.db.mysql;
import com.google.inject.Inject;
import com.google.inject.MembersInjector;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import javax.sql.DataSource;
import net.draycia.carbon.api.CarbonChat;
import net.draycia.carbon.api.CarbonChatProvider;
import net.draycia.carbon.api.channels.ChatChannel;
import net.draycia.carbon.api.users.ComponentPlayerResult;
import net.draycia.carbon.common.config.ConfigFactory;
import net.draycia.carbon.common.config.DatabaseSettings;
import net.draycia.carbon.common.users.CarbonPlayerCommon;
import net.draycia.carbon.common.users.SaveOnChange;
import net.draycia.carbon.common.users.db.AbstractUserManager;
import net.draycia.carbon.common.users.ProfileResolver;
import net.draycia.carbon.common.users.db.ComponentArgumentFactory;
import net.draycia.carbon.common.users.db.DBType;
import net.draycia.carbon.common.users.db.DatabaseUserManager;
import net.draycia.carbon.common.users.db.KeyArgumentFactory;
import net.draycia.carbon.common.users.db.KeyColumnMapper;
import net.draycia.carbon.common.users.db.QueriesLocator;
import net.draycia.carbon.common.util.ConcurrentUtil;
import net.kyori.adventure.key.Key;
import net.kyori.adventure.text.Component;
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;
@@ -52,100 +51,61 @@ import org.jdbi.v3.core.Jdbi;
import org.jdbi.v3.core.statement.Update;
import org.jdbi.v3.sqlobject.SqlObjectPlugin;
import static net.kyori.adventure.text.Component.empty;
import static net.kyori.adventure.text.Component.text;
// TODO: Dispatch updates using messaging system when users are modified
@DefaultQualifier(NonNull.class)
public final class MySQLUserManager extends AbstractUserManager implements SaveOnChange {
public final class MySQLUserManager extends DatabaseUserManager {
private final Map<UUID, CarbonPlayerCommon> userCache = Collections.synchronizedMap(new HashMap<>());
private MySQLUserManager(final Jdbi jdbi) {
super(jdbi, new QueriesLocator(DBType.MYSQL));
}
public static MySQLUserManager manager(
final DatabaseSettings databaseSettings
private MySQLUserManager(
final Jdbi jdbi,
final Logger logger,
final ProfileResolver profileResolver,
final MembersInjector<CarbonPlayerCommon> playerInjector
) {
try {
//Class.forName("org.postgresql.Driver");
Class.forName("org.mariadb.jdbc.Driver");
Class.forName("com.mysql.cj.jdbc.Driver"); // Manually loading this might not be necessary
} catch (final Exception exception) {
exception.printStackTrace();
}
final HikariConfig hikariConfig = new HikariConfig();
hikariConfig.setMaximumPoolSize(20);
hikariConfig.setJdbcUrl(databaseSettings.url());
hikariConfig.setUsername(databaseSettings.username());
hikariConfig.setPassword(databaseSettings.password());
final DataSource dataSource = new HikariDataSource(hikariConfig);
final Flyway flyway = Flyway.configure(CarbonChat.class.getClassLoader())
.baselineVersion("0")
.baselineOnMigrate(true)
.locations("queries/migrations/mysql")
.dataSource(dataSource)
.validateOnMigrate(true)
.load();
flyway.repair();
flyway.migrate();
final Jdbi jdbi = Jdbi.create(dataSource)
.registerArrayType(UUID.class, "uuid")
.registerArgument(new ComponentArgumentFactory())
.registerArgument(new KeyArgumentFactory())
.registerArgument(new MySQLUUIDArgumentFactory())
.registerRowMapper(new MySQLPlayerRowMapper())
.installPlugin(new SqlObjectPlugin());
return new MySQLUserManager(jdbi);
super(
jdbi,
new QueriesLocator(DBType.MYSQL),
logger,
profileResolver,
playerInjector
);
}
@Override
public CompletableFuture<ComponentPlayerResult<CarbonPlayerCommon>> carbonPlayer(final UUID uuid) {
return CompletableFuture.supplyAsync(() -> {
final var playerResult = this.userCache.computeIfAbsent(uuid, key -> this.jdbi.withHandle(handle -> {
final Optional<CarbonPlayerCommon> carbonPlayerCommon = handle.createQuery(this.locator.query("select-player"))
.bind("id", uuid)
.mapTo(CarbonPlayerCommon.class)
.findOne();
protected CarbonPlayerCommon loadOrCreate(final UUID uuid) {
return this.jdbi.withHandle(handle -> {
final Optional<CarbonPlayerCommon> carbonPlayerCommon = handle.createQuery(this.locator.query("select-player"))
.bind("id", uuid)
.mapTo(CarbonPlayerCommon.class)
.findOne();
if (carbonPlayerCommon.isEmpty()) {
// Player doesn't exist in the DB, create them!
final String name = Objects.requireNonNull(CarbonChatProvider.carbonChat().server().resolveName(uuid).join());
final CarbonPlayerCommon player = new CarbonPlayerCommon(name, uuid);
if (carbonPlayerCommon.isEmpty()) {
// Player doesn't exist in the DB, create them!
final String name = Objects.requireNonNull(this.profileResolver.resolveName(uuid).join());
final CarbonPlayerCommon player = new CarbonPlayerCommon(name, uuid);
this.bindPlayerArguments(handle.createUpdate(this.locator.query("insert-player")), player).execute();
this.bindPlayerArguments(handle.createUpdate(this.locator.query("insert-player")), player).execute();
return player;
}
return player;
}
handle.createQuery(this.locator.query("select-ignores"))
.bind("id", uuid)
.mapTo(UUID.class)
.forEach(ignoredPlayer -> carbonPlayerCommon.get().ignoredPlayers().add(ignoredPlayer));
handle.createQuery(this.locator.query("select-leftchannels"))
.bind("id", uuid)
.mapTo(Key.class)
.forEach(channel -> {
final @Nullable ChatChannel chatChannel = CarbonChatProvider.carbonChat()
.channelRegistry()
.get(channel);
if (chatChannel == null) {
return;
}
carbonPlayerCommon.get().leftChannels().add(channel);
});
return carbonPlayerCommon.get();
}));
return new ComponentPlayerResult<>(playerResult, empty());
}).completeOnTimeout(new ComponentPlayerResult<>(null, text("Timed out loading data of UUID [" + uuid + " ]")), 30, TimeUnit.SECONDS);
handle.createQuery(this.locator.query("select-ignores"))
.bind("id", uuid)
.mapTo(UUID.class)
.forEach(ignoredPlayer -> carbonPlayerCommon.get().ignoring(ignoredPlayer, true, true));
handle.createQuery(this.locator.query("select-leftchannels"))
.bind("id", uuid)
.mapTo(Key.class)
.forEach(channel -> {
final @Nullable ChatChannel chatChannel = CarbonChatProvider.carbonChat()
.channelRegistry()
.get(channel);
if (chatChannel == null) {
return;
}
carbonPlayerCommon.get().leaveChannel(chatChannel, true);
});
return carbonPlayerCommon.get();
});
}
@Override
@@ -162,68 +122,67 @@ public final class MySQLUserManager extends AbstractUserManager implements SaveO
.bind("spying", player.spying());
}
@Override
public CompletableFuture<ComponentPlayerResult<CarbonPlayerCommon>> saveAndInvalidatePlayer(final CarbonPlayerCommon player) {
return this.savePlayer(player).thenApply(result -> {
this.userCache.remove(player.uuid());
public static final class Factory {
return result;
});
}
private final DatabaseSettings databaseSettings;
private final Logger logger;
private final ProfileResolver profileResolver;
private final MembersInjector<CarbonPlayerCommon> playerInjector;
@Override
public int saveDisplayName(final UUID id, final @Nullable Component displayName) {
return this.jdbi.withExtension(MySQLSaveOnChange.class, changeSaver -> changeSaver.saveDisplayName(id, displayName));
}
@Inject
private Factory(
final ConfigFactory configFactory,
final Logger logger,
final ProfileResolver profileResolver,
final MembersInjector<CarbonPlayerCommon> playerInjector
) {
this.databaseSettings = configFactory.primaryConfig().databaseSettings();
this.logger = logger;
this.profileResolver = profileResolver;
this.playerInjector = playerInjector;
}
@Override
public int saveMuted(final UUID id, final boolean muted) {
return this.jdbi.withExtension(MySQLSaveOnChange.class, changeSaver -> changeSaver.saveMuted(id, muted));
}
public MySQLUserManager create() {
try {
//Class.forName("org.postgresql.Driver");
Class.forName("org.mariadb.jdbc.Driver");
Class.forName("com.mysql.cj.jdbc.Driver"); // Manually loading this might not be necessary
} catch (final Exception exception) {
exception.printStackTrace();
}
@Override
public int saveDeafened(final UUID id, final boolean deafened) {
return this.jdbi.withExtension(MySQLSaveOnChange.class, changeSaver -> changeSaver.saveDeafened(id, deafened));
}
final HikariConfig hikariConfig = new HikariConfig();
hikariConfig.setMaximumPoolSize(20);
hikariConfig.setJdbcUrl(this.databaseSettings.url());
hikariConfig.setUsername(this.databaseSettings.username());
hikariConfig.setPassword(this.databaseSettings.password());
hikariConfig.setThreadFactory(ConcurrentUtil.carbonThreadFactory(this.logger, "MySQLUserManagerHCP"));
@Override
public int saveSpying(final UUID id, final boolean spying) {
return this.jdbi.withExtension(MySQLSaveOnChange.class, changeSaver -> changeSaver.saveSpying(id, spying));
}
final DataSource dataSource = new HikariDataSource(hikariConfig);
@Override
public int saveSelectedChannel(final UUID id, final @Nullable Key selectedChannel) {
return this.jdbi.withExtension(MySQLSaveOnChange.class, changeSaver -> changeSaver.saveSelectedChannel(id, selectedChannel));
}
final Flyway flyway = Flyway.configure(CarbonChat.class.getClassLoader())
.baselineVersion("0")
.baselineOnMigrate(true)
.locations("queries/migrations/mysql")
.dataSource(dataSource)
.validateOnMigrate(true)
.load();
@Override
public int saveLastWhisperTarget(final UUID id, final @Nullable UUID lastWhisperTarget) {
return this.jdbi.withExtension(MySQLSaveOnChange.class, changeSaver -> changeSaver.saveLastWhisperTarget(id, lastWhisperTarget));
}
flyway.repair();
flyway.migrate();
@Override
public int saveWhisperReplyTarget(final UUID id, final @Nullable UUID whisperReplyTarget) {
return this.jdbi.withExtension(MySQLSaveOnChange.class, changeSaver -> changeSaver.saveWhisperReplyTarget(id, whisperReplyTarget));
}
final Jdbi jdbi = Jdbi.create(dataSource)
.registerArgument(new ComponentArgumentFactory())
.registerArgument(new KeyArgumentFactory())
.registerArgument(new MySQLUUIDArgumentFactory())
.registerArrayType(UUID.class, "uuid")
.registerColumnMapper(new KeyColumnMapper())
.registerRowMapper(new MySQLPlayerRowMapper())
.installPlugin(new SqlObjectPlugin());
@Override
public int addIgnore(final UUID id, final UUID ignoredPlayer) {
return this.jdbi.withExtension(MySQLSaveOnChange.class, changeSaver -> changeSaver.addIgnore(id, ignoredPlayer));
}
return new MySQLUserManager(jdbi, this.logger, this.profileResolver, this.playerInjector);
}
@Override
public int removeIgnore(final UUID id, final UUID ignoredPlayer) {
return this.jdbi.withExtension(MySQLSaveOnChange.class, changeSaver -> changeSaver.removeIgnore(id, ignoredPlayer));
}
@Override
public int addLeftChannel(final UUID id, final Key channel) {
return this.jdbi.withExtension(MySQLSaveOnChange.class, changeSaver -> changeSaver.addLeftChannel(id, channel));
}
@Override
public int removeLeftChannel(final UUID id, final Key channel) {
return this.jdbi.withExtension(MySQLSaveOnChange.class, changeSaver -> changeSaver.removeLeftChannel(id, channel));
}
}
@@ -23,6 +23,7 @@ import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.UUID;
import net.draycia.carbon.common.users.CarbonPlayerCommon;
import net.draycia.carbon.common.util.Strings;
import net.kyori.adventure.key.Key;
import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer;
import org.checkerframework.checker.nullness.qual.Nullable;
@@ -34,14 +35,14 @@ public class PostgreSQLPlayerRowMapper implements RowMapper<CarbonPlayerCommon>
@Override
public CarbonPlayerCommon map(final ResultSet rs, final StatementContext ctx) throws SQLException {
final @Nullable @Subst("carbon:global") String selectedChannel = rs.getString("selectedchannel");
final @Nullable String displayName = rs.getString("displayname");
final @Nullable @Subst("carbon:global") String selectedChannel = Strings.trim(rs.getString("selectedchannel"));
final @Nullable String displayName = Strings.trim(rs.getString("displayname"));
return new CarbonPlayerCommon(
rs.getBoolean("muted"),
rs.getBoolean("deafened"),
selectedChannel == null ? null : Key.key(selectedChannel),
rs.getString("username"),
Strings.trim(rs.getString("username")),
rs.getObject("id", UUID.class),
displayName == null ? null : GsonComponentSerializer.gson().deserialize(displayName),
rs.getObject("lastwhispertarget", UUID.class),
@@ -1,66 +0,0 @@
/*
* 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.users.db.postgresql;
import java.util.UUID;
import net.draycia.carbon.common.users.SaveOnChange;
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.jdbi.v3.sqlobject.statement.SqlUpdate;
@DefaultQualifier(NonNull.class)
public interface PostgreSQLSaveOnChange extends SaveOnChange {
@SqlUpdate("UPDATE carbon_users SET displayname = :displayName WHERE id = :id")
int saveDisplayName(final UUID id, final @Nullable Component displayName);
@SqlUpdate("UPDATE carbon_users SET muted = :muted WHERE id = :id")
int saveMuted(final UUID id, final boolean muted);
@SqlUpdate("UPDATE carbon_users SET deafened = :deafened WHERE id = :id")
int saveDeafened(final UUID id, final boolean deafened);
@SqlUpdate("UPDATE carbon_users SET spying = :spying WHERE id = :id")
int saveSpying(final UUID id, final boolean spying);
@SqlUpdate("UPDATE carbon_users SET selectedchannel = :selectedChannel WHERE id = :id")
int saveSelectedChannel(final UUID id, final @Nullable Key selectedChannel);
@SqlUpdate("UPDATE carbon_users SET lastwhispertarget = :lastWhisperTarget WHERE id = :id")
int saveLastWhisperTarget(final UUID id, final @Nullable UUID lastWhisperTarget);
@SqlUpdate("UPDATE carbon_users SET whisperreplytarget = :whisperReplyTarget WHERE id = :id")
int saveWhisperReplyTarget(final UUID id, final @Nullable UUID whisperReplyTarget);
@SqlUpdate("INSERT INTO carbon_ignores VALUES id = :id, ignoredplayer = :ignoredPlayer")
int addIgnore(final UUID id, final UUID ignoredPlayer);
@SqlUpdate("DELETE FROM carbon_ignores WHERE id = :id, ignoredplayer = :ignoredPlayer")
int removeIgnore(final UUID id, final UUID ignoredPlayer);
@SqlUpdate("INSERT INTO carbon_leftchannels VALUES id = :id, channel = :channel")
int addLeftChannel(final UUID id, final Key channel);
@SqlUpdate("DELETE FROM carbon_leftchannels WHERE id = :id, channel = :channel")
int removeLeftChannel(final UUID id, final Key channel);
}
@@ -19,30 +19,29 @@
*/
package net.draycia.carbon.common.users.db.postgresql;
import com.google.inject.Inject;
import com.google.inject.MembersInjector;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import javax.sql.DataSource;
import net.draycia.carbon.api.CarbonChat;
import net.draycia.carbon.api.CarbonChatProvider;
import net.draycia.carbon.api.channels.ChatChannel;
import net.draycia.carbon.api.users.ComponentPlayerResult;
import net.draycia.carbon.common.config.ConfigFactory;
import net.draycia.carbon.common.config.DatabaseSettings;
import net.draycia.carbon.common.users.CarbonPlayerCommon;
import net.draycia.carbon.common.users.SaveOnChange;
import net.draycia.carbon.common.users.db.AbstractUserManager;
import net.draycia.carbon.common.users.ProfileResolver;
import net.draycia.carbon.common.users.db.ComponentArgumentFactory;
import net.draycia.carbon.common.users.db.DBType;
import net.draycia.carbon.common.users.db.DatabaseUserManager;
import net.draycia.carbon.common.users.db.KeyArgumentFactory;
import net.draycia.carbon.common.users.db.KeyColumnMapper;
import net.draycia.carbon.common.users.db.QueriesLocator;
import net.draycia.carbon.common.util.ConcurrentUtil;
import net.kyori.adventure.key.Key;
import net.kyori.adventure.text.Component;
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;
@@ -53,102 +52,65 @@ import org.jdbi.v3.core.statement.Update;
import org.jdbi.v3.postgres.PostgresPlugin;
import org.jdbi.v3.sqlobject.SqlObjectPlugin;
import static net.kyori.adventure.text.Component.empty;
import static net.kyori.adventure.text.Component.text;
// TODO: Dispatch updates using messaging system when users are modified
@DefaultQualifier(NonNull.class)
public final class PostgreSQLUserManager extends AbstractUserManager implements SaveOnChange {
public final class PostgreSQLUserManager extends DatabaseUserManager {
private final Map<UUID, CarbonPlayerCommon> userCache = Collections.synchronizedMap(new HashMap<>());
private PostgreSQLUserManager(final Jdbi jdbi) {
super(jdbi, new QueriesLocator(DBType.POSTGRESQL));
}
public static PostgreSQLUserManager manager(final DatabaseSettings databaseSettings) {
try {
Class.forName("org.postgresql.Driver");
Flyway.configure().getPluginRegister().REGISTERED_PLUGINS.add(new PostgreSQLDatabaseType());
} catch (final Exception exception) {
exception.printStackTrace();
}
final HikariConfig hikariConfig = new HikariConfig();
hikariConfig.setMaximumPoolSize(20);
hikariConfig.setJdbcUrl(databaseSettings.url());
hikariConfig.setUsername(databaseSettings.username());
hikariConfig.setPassword(databaseSettings.password());
final DataSource dataSource = new HikariDataSource(hikariConfig);
Flyway.configure(CarbonChat.class.getClassLoader())
.baselineVersion("0")
.baselineOnMigrate(true)
.locations("queries/migrations/postgresql")
.dataSource(dataSource)
.validateOnMigrate(true)
.load()
.migrate();
final Jdbi jdbi = Jdbi.create(dataSource)
.registerArgument(new ComponentArgumentFactory())
.registerArgument(new KeyArgumentFactory())
.registerRowMapper(new PostgreSQLPlayerRowMapper())
.installPlugin(new SqlObjectPlugin())
.installPlugin(new PostgresPlugin());
return new PostgreSQLUserManager(jdbi);
private PostgreSQLUserManager(
final Jdbi jdbi,
final Logger logger,
final ProfileResolver profileResolver,
final MembersInjector<CarbonPlayerCommon> playerInjector
) {
super(
jdbi,
new QueriesLocator(DBType.POSTGRESQL),
logger,
profileResolver,
playerInjector
);
}
@Override
public CompletableFuture<ComponentPlayerResult<CarbonPlayerCommon>> carbonPlayer(final UUID uuid) {
return CompletableFuture.supplyAsync(() -> {
final @Nullable CarbonPlayerCommon cachedPlayer = this.userCache.get(uuid);
protected CarbonPlayerCommon loadOrCreate(final UUID uuid) {
return this.jdbi.withHandle(handle -> {
try {
final @Nullable CarbonPlayerCommon carbonPlayerCommon = handle.createQuery(this.locator.query("select-player"))
.bind("id", uuid)
.mapTo(CarbonPlayerCommon.class)
.first();
if (cachedPlayer != null) {
return new ComponentPlayerResult<>(cachedPlayer, empty());
handle.createQuery(this.locator.query("select-ignores"))
.bind("id", uuid)
.mapTo(UUID.class)
.forEach(ignoredPlayer -> carbonPlayerCommon.ignoring(ignoredPlayer, true, true));
handle.createQuery(this.locator.query("select-leftchannels"))
.bind("id", uuid)
.mapTo(Key.class)
.forEach(channel -> {
final @Nullable ChatChannel chatChannel = CarbonChatProvider.carbonChat()
.channelRegistry()
.get(channel);
if (chatChannel == null) {
return;
}
carbonPlayerCommon.leaveChannel(chatChannel, true);
});
return carbonPlayerCommon;
} catch (final IllegalStateException exception) {
// Player doesn't exist in the DB, create them!
final String name = Objects.requireNonNull(
this.profileResolver.resolveName(uuid).join());
final CarbonPlayerCommon player = new CarbonPlayerCommon(name, uuid);
this.bindPlayerArguments(handle.createUpdate(this.locator.query("insert-player")), player)
.execute();
return player;
}
return this.jdbi.withHandle(handle -> {
try {
final @Nullable CarbonPlayerCommon carbonPlayerCommon = handle.createQuery(this.locator.query("select-player"))
.bind("id", uuid)
.mapTo(CarbonPlayerCommon.class)
.first();
handle.createQuery(this.locator.query("select-ignores"))
.bind("id", uuid)
.mapTo(UUID.class)
.forEach(ignoredPlayer -> carbonPlayerCommon.ignoring(ignoredPlayer, true));
handle.createQuery(this.locator.query("select-leftchannels"))
.bind("id", uuid)
.mapTo(Key.class)
.forEach(channel -> {
final @Nullable ChatChannel chatChannel = CarbonChatProvider.carbonChat()
.channelRegistry()
.get(channel);
if (chatChannel == null) {
return;
}
carbonPlayerCommon.leftChannels().add(channel);
});
return new ComponentPlayerResult<>(carbonPlayerCommon, empty());
} catch (final IllegalStateException exception) {
// Player doesn't exist in the DB, create them!
final String name = Objects.requireNonNull(
CarbonChatProvider.carbonChat().server().resolveName(uuid).join());
final CarbonPlayerCommon player = new CarbonPlayerCommon(name, uuid);
this.bindPlayerArguments(handle.createUpdate(this.locator.query("insert-player")), player)
.execute();
return new ComponentPlayerResult<>(player, text(""));
}
});
}).completeOnTimeout(new ComponentPlayerResult<>(null, text("Timed out loading data of UUID [" + uuid + " ]")), 30, TimeUnit.SECONDS);
});
}
@Override
@@ -165,68 +127,63 @@ public final class PostgreSQLUserManager extends AbstractUserManager implements
.bind("spying", player.spying());
}
@Override
public CompletableFuture<ComponentPlayerResult<CarbonPlayerCommon>> saveAndInvalidatePlayer(final CarbonPlayerCommon player) {
return this.savePlayer(player).thenApply(result -> {
this.userCache.remove(player.uuid());
public static final class Factory {
return result;
});
}
private final DatabaseSettings databaseSettings;
private final Logger logger;
private final ProfileResolver profileResolver;
private final MembersInjector<CarbonPlayerCommon> playerInjector;
@Override
public int saveDisplayName(final UUID id, final @Nullable Component displayName) {
return this.jdbi.withExtension(PostgreSQLSaveOnChange.class, changeSaver -> changeSaver.saveDisplayName(id, displayName));
}
@Inject
private Factory(
final ConfigFactory configFactory,
final Logger logger,
final ProfileResolver profileResolver,
final MembersInjector<CarbonPlayerCommon> playerInjector
) {
this.databaseSettings = configFactory.primaryConfig().databaseSettings();
this.logger = logger;
this.profileResolver = profileResolver;
this.playerInjector = playerInjector;
}
@Override
public int saveMuted(final UUID id, final boolean muted) {
return this.jdbi.withExtension(PostgreSQLSaveOnChange.class, changeSaver -> changeSaver.saveMuted(id, muted));
}
public PostgreSQLUserManager create() {
try {
Class.forName("org.postgresql.Driver");
Flyway.configure().getPluginRegister().REGISTERED_PLUGINS.add(new PostgreSQLDatabaseType());
} catch (final Exception exception) {
exception.printStackTrace();
}
@Override
public int saveDeafened(final UUID id, final boolean deafened) {
return this.jdbi.withExtension(PostgreSQLSaveOnChange.class, changeSaver -> changeSaver.saveDeafened(id, deafened));
}
final HikariConfig hikariConfig = new HikariConfig();
hikariConfig.setMaximumPoolSize(20);
hikariConfig.setJdbcUrl(this.databaseSettings.url());
hikariConfig.setUsername(this.databaseSettings.username());
hikariConfig.setPassword(this.databaseSettings.password());
hikariConfig.setThreadFactory(ConcurrentUtil.carbonThreadFactory(this.logger, "PSQLUserManagerHCP"));
@Override
public int saveSpying(final UUID id, final boolean spying) {
return this.jdbi.withExtension(PostgreSQLSaveOnChange.class, changeSaver -> changeSaver.saveSpying(id, spying));
}
final DataSource dataSource = new HikariDataSource(hikariConfig);
@Override
public int saveSelectedChannel(final UUID id, final @Nullable Key selectedChannel) {
return this.jdbi.withExtension(PostgreSQLSaveOnChange.class, changeSaver -> changeSaver.saveSelectedChannel(id, selectedChannel));
}
Flyway.configure(CarbonChat.class.getClassLoader())
.baselineVersion("0")
.baselineOnMigrate(true)
.locations("queries/migrations/postgresql")
.dataSource(dataSource)
.validateOnMigrate(true)
.load()
.migrate();
@Override
public int saveLastWhisperTarget(final UUID id, final @Nullable UUID lastWhisperTarget) {
return this.jdbi.withExtension(PostgreSQLSaveOnChange.class, changeSaver -> changeSaver.saveLastWhisperTarget(id, lastWhisperTarget));
}
final Jdbi jdbi = Jdbi.create(dataSource)
.registerArgument(new ComponentArgumentFactory())
.registerArgument(new KeyArgumentFactory())
.registerColumnMapper(new KeyColumnMapper())
.registerRowMapper(new PostgreSQLPlayerRowMapper())
.installPlugin(new SqlObjectPlugin())
.installPlugin(new PostgresPlugin());
@Override
public int saveWhisperReplyTarget(final UUID id, final @Nullable UUID whisperReplyTarget) {
return this.jdbi.withExtension(PostgreSQLSaveOnChange.class, changeSaver -> changeSaver.saveWhisperReplyTarget(id, whisperReplyTarget));
}
return new PostgreSQLUserManager(jdbi, this.logger, this.profileResolver, this.playerInjector);
}
@Override
public int addIgnore(final UUID id, final UUID ignoredPlayer) {
return this.jdbi.withExtension(PostgreSQLSaveOnChange.class, changeSaver -> changeSaver.addIgnore(id, ignoredPlayer));
}
@Override
public int removeIgnore(final UUID id, final UUID ignoredPlayer) {
return this.jdbi.withExtension(PostgreSQLSaveOnChange.class, changeSaver -> changeSaver.removeIgnore(id, ignoredPlayer));
}
@Override
public int addLeftChannel(final UUID id, final Key channel) {
return this.jdbi.withExtension(PostgreSQLSaveOnChange.class, changeSaver -> changeSaver.addLeftChannel(id, channel));
}
@Override
public int removeLeftChannel(final UUID id, final Key channel) {
return this.jdbi.withExtension(PostgreSQLSaveOnChange.class, changeSaver -> changeSaver.removeLeftChannel(id, channel));
}
}
@@ -22,145 +22,119 @@ package net.draycia.carbon.common.users.json;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.MembersInjector;
import java.io.IOException;
import java.io.Reader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import net.draycia.carbon.api.CarbonChat;
import java.util.concurrent.Executors;
import net.draycia.carbon.api.CarbonChatProvider;
import net.draycia.carbon.api.channels.ChatChannel;
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.DataDirectory;
import net.draycia.carbon.common.serialisation.gson.ChatChannelSerializerGson;
import net.draycia.carbon.common.serialisation.gson.UUIDSerializerGson;
import net.draycia.carbon.common.users.CachingUserManager;
import net.draycia.carbon.common.users.CarbonPlayerCommon;
import net.draycia.carbon.common.users.PersistentUserProperty;
import net.draycia.carbon.common.users.ProfileResolver;
import net.draycia.carbon.common.util.ConcurrentUtil;
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<CarbonPlayerCommon> {
public class JSONUserManager extends CachingUserManager {
private final Logger logger;
private final Gson serializer;
private final Path userDirectory;
private final CarbonChat carbonChat;
private final Map<UUID, CarbonPlayerCommon> userCache = Collections.synchronizedMap(new HashMap<>());
@Inject
public JSONUserManager(
final @ForCarbon Path dataDirectory,
final Injector injector,
final @DataDirectory Path dataDirectory,
final Logger logger,
final CarbonChat carbonChat
final ProfileResolver profileResolver,
final MembersInjector<CarbonPlayerCommon> playerInjector,
final ChatChannelSerializerGson channelSerializer,
final UUIDSerializerGson uuidSerializer
) throws IOException {
this.logger = logger;
super(
logger,
Executors.newSingleThreadExecutor(ConcurrentUtil.carbonThreadFactory(logger, "JSONUserManager")),
profileResolver,
playerInjector
);
this.userDirectory = dataDirectory.resolve("users");
this.carbonChat = carbonChat;
Files.createDirectories(this.userDirectory);
this.serializer = GsonComponentSerializer.gson().populator()
.apply(new GsonBuilder())
.registerTypeAdapter(ChatChannel.class, injector.getInstance(ChatChannelSerializerGson.class))
.registerTypeAdapter(UUID.class, injector.getInstance(UUIDSerializerGson.class))
.registerTypeAdapter(ChatChannel.class, channelSerializer)
.registerTypeAdapter(UUID.class, uuidSerializer)
.registerTypeAdapter(PersistentUserProperty.class, new PersistentUserProperty.Serializer())
.setPrettyPrinting()
.create();
}
@Override
public CompletableFuture<ComponentPlayerResult<CarbonPlayerCommon>> carbonPlayer(final UUID uuid) {
return CompletableFuture.supplyAsync(() -> {
final @Nullable CarbonPlayerCommon cachedPlayer = this.userCache.get(uuid);
protected CarbonPlayerCommon loadOrCreate(final UUID uuid) {
final Path userFile = this.userFile(uuid);
if (cachedPlayer != null) {
return new ComponentPlayerResult<>(cachedPlayer, empty());
}
final Path userFile = this.userDirectory.resolve(uuid + ".json");
if (Files.exists(userFile)) {
try {
final @Nullable CarbonPlayerCommon player =
this.serializer.fromJson(Files.newBufferedReader(userFile), CarbonPlayerCommon.class);
if (player == null) {
return new ComponentPlayerResult<CarbonPlayerCommon>(null, text("Player file found but was empty."));
}
player.leftChannels().removeIf(channel -> CarbonChatProvider.carbonChat()
.channelRegistry()
.get(channel) == null);
this.userCache.put(uuid, player);
return new ComponentPlayerResult<>(player, empty());
} catch (final IOException exception) {
return new ComponentPlayerResult<CarbonPlayerCommon>(null, text(exception.getMessage()));
if (Files.exists(userFile)) {
try {
final @Nullable CarbonPlayerCommon player;
try (final Reader reader = Files.newBufferedReader(userFile)) {
player = this.serializer.fromJson(reader, CarbonPlayerCommon.class);
}
if (player == null) {
throw new IllegalStateException("Player file found but was empty.");
}
player.leftChannels().forEach(channel -> {
if (CarbonChatProvider.carbonChat()
.channelRegistry()
.get(channel) == null) {
player.joinChannel(channel, true);
}
});
return player;
} catch (final IOException exception) {
throw new RuntimeException(exception);
}
}
final String name = Objects.requireNonNull(
this.carbonChat.server().resolveName(uuid).join());
return new CarbonPlayerCommon(null /* Username will be resolved when requested */, uuid);
}
final CarbonPlayerCommon player = new CarbonPlayerCommon(name, uuid);
this.userCache.put(uuid, player);
return new ComponentPlayerResult<>(player, empty());
}).completeOnTimeout(new ComponentPlayerResult<>(null, text("Timed out loading data of UUID [" + uuid + " ]")), 30, TimeUnit.SECONDS);
private Path userFile(final UUID id) {
return this.userDirectory.resolve(id + ".json");
}
@Override
public CompletableFuture<ComponentPlayerResult<CarbonPlayerCommon>> savePlayer(final CarbonPlayerCommon player) {
return CompletableFuture.supplyAsync(() -> {
final Path userFile = this.userDirectory.resolve(player.uuid() + ".json");
public CompletableFuture<Void> save(final CarbonPlayerCommon player) {
if (!player.needsSave()) {
return CompletableFuture.completedFuture(null);
}
return CompletableFuture.runAsync(() -> {
final Path userFile = this.userFile(player.uuid());
try {
final String json = this.serializer.toJson(player);
if (json == null || json.isBlank()) {
return new ComponentPlayerResult<>(null, text("No data to save - toJson returned null or blank."));
throw new IllegalStateException("No data to save - toJson returned null or blank.");
}
if (!Files.exists(userFile)) {
Files.createFile(userFile);
}
Files.writeString(userFile, json,
StandardOpenOption.WRITE,
StandardOpenOption.TRUNCATE_EXISTING);
return new ComponentPlayerResult<>(player, text(String.format("Saving player data for [%s], [%s]",
player.username(), player.uuid())));
Files.writeString(userFile, json);
} catch (final IOException exception) {
this.logger.error("Exception caught while saving data for player [{}]", player.username());
exception.printStackTrace();
return new ComponentPlayerResult<>(null, text(exception.getMessage()));
throw new RuntimeException("Exception while saving data for player [%s]".formatted(player.username()), exception);
}
});
}
@Override
public CompletableFuture<ComponentPlayerResult<CarbonPlayerCommon>> saveAndInvalidatePlayer(final CarbonPlayerCommon player) {
return this.savePlayer(player).thenApply(result -> {
this.userCache.remove(player.uuid());
return result;
});
}, this.executor);
}
}
@@ -0,0 +1,66 @@
/*
* 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.util;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import org.apache.logging.log4j.Logger;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.framework.qual.DefaultQualifier;
@DefaultQualifier(NonNull.class)
public final class ConcurrentUtil {
private ConcurrentUtil() {
}
public static void shutdownExecutor(final ExecutorService service, final TimeUnit timeoutUnit, final long timeoutLength) {
service.shutdown();
boolean didShutdown;
try {
didShutdown = service.awaitTermination(timeoutLength, timeoutUnit);
} catch (final InterruptedException ignore) {
didShutdown = false;
}
if (!didShutdown) {
service.shutdownNow();
}
}
public static ThreadFactory carbonThreadFactory(final Logger logger, final String name) {
return new ThreadFactoryBuilder()
.setDaemon(true)
.setNameFormat("CarbonChat " + name + " Thread #%d")
.setUncaughtExceptionHandler((thread, thr) -> logger.warn("Uncaught exception on thread {}", thread.getName(), thr))
.build();
}
public static ScheduledExecutorService createPeriodicTasksPool(final Logger logger) {
return new ExceptionLoggingScheduledThreadPoolExecutor(
1,
carbonThreadFactory(logger, "Periodic Tasks"),
logger
);
}
}
@@ -0,0 +1,73 @@
/*
* 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.util;
import java.util.concurrent.Callable;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import org.apache.logging.log4j.Logger;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.framework.qual.DefaultQualifier;
@DefaultQualifier(NonNull.class)
public final class ExceptionLoggingScheduledThreadPoolExecutor extends ScheduledThreadPoolExecutor {
private final Logger logger;
public ExceptionLoggingScheduledThreadPoolExecutor(final int corePoolSize, final ThreadFactory threadFactory, final Logger logger) {
super(corePoolSize, threadFactory);
this.logger = logger;
}
@Override
public ScheduledFuture<?> schedule(final Runnable command, final long delay, final TimeUnit unit) {
return super.schedule(new ExceptionLoggingRunnable(command, this.logger), delay, unit);
}
@Override
public <V> ScheduledFuture<V> schedule(final Callable<V> callable, final long delay, final TimeUnit unit) {
throw new UnsupportedOperationException();
}
@Override
public ScheduledFuture<?> scheduleAtFixedRate(final Runnable command, final long initialDelay, final long period, final TimeUnit unit) {
return super.scheduleAtFixedRate(new ExceptionLoggingRunnable(command, this.logger), initialDelay, period, unit);
}
@Override
public ScheduledFuture<?> scheduleWithFixedDelay(final Runnable command, final long initialDelay, final long delay, final TimeUnit unit) {
return super.scheduleWithFixedDelay(new ExceptionLoggingRunnable(command, this.logger), initialDelay, delay, unit);
}
private record ExceptionLoggingRunnable(Runnable wrapped, Logger logger) implements Runnable {
@Override
public void run() {
try {
this.wrapped.run();
} catch (final Throwable thr) {
this.logger.error("Error executing task '{}'", this.wrapped, thr);
Exceptions.rethrow(thr);
}
}
}
}
@@ -0,0 +1,52 @@
/*
* 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.util;
import java.util.function.Consumer;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.framework.qual.DefaultQualifier;
@DefaultQualifier(NonNull.class)
public final class Exceptions {
private Exceptions() {
}
@SuppressWarnings("unchecked")
public static <X extends Throwable> RuntimeException rethrow(final Throwable t) throws X {
throw (X) t;
}
public static <T, X extends Throwable> Consumer<T> sneaky(final CheckedConsumer<T, X> consumer) {
return t -> {
try {
consumer.accept(t);
} catch (final Throwable thr) {
rethrow(thr);
}
};
}
@FunctionalInterface
public interface CheckedConsumer<T, X extends Throwable> {
void accept(T t) throws X;
}
}
@@ -24,6 +24,7 @@ import java.util.List;
import net.draycia.carbon.common.listeners.DeafenHandler;
import net.draycia.carbon.common.listeners.IgnoreHandler;
import net.draycia.carbon.common.listeners.ItemLinkHandler;
import net.draycia.carbon.common.listeners.MessagingHandler;
import net.draycia.carbon.common.listeners.MuteHandler;
import net.draycia.carbon.common.listeners.PingHandler;
@@ -34,7 +35,7 @@ public final class ListenerUtils {
}
public static final List<Class<?>> LISTENER_CLASSES = List.of(DeafenHandler.class, IgnoreHandler.class,
ItemLinkHandler.class, MuteHandler.class, PingHandler.class);
ItemLinkHandler.class, MessagingHandler.class, MuteHandler.class, PingHandler.class);
public static void registerCommonListeners(final Injector injector) {
for (final var listenerClass : LISTENER_CLASSES) {
@@ -22,10 +22,9 @@ package net.draycia.carbon.common.util;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import net.draycia.carbon.api.CarbonServer;
import net.draycia.carbon.api.users.ComponentPlayerResult;
import net.draycia.carbon.api.users.UserManager;
import net.draycia.carbon.common.users.CarbonPlayerCommon;
import net.draycia.carbon.common.users.WrappedCarbonPlayer;
import net.draycia.carbon.api.users.CarbonPlayer;
import net.draycia.carbon.common.users.UserManagerInternal;
import org.apache.logging.log4j.Logger;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.framework.qual.DefaultQualifier;
@@ -35,56 +34,27 @@ public final class PlayerUtils {
private PlayerUtils() {
}
public static List<CompletableFuture<ComponentPlayerResult<CarbonPlayerCommon>>> saveLoggedInPlayers(
@SuppressWarnings("unchecked")
public static <C extends CarbonPlayer> List<CompletableFuture<Void>> saveLoggedInPlayers(
final CarbonServer carbonServer,
final UserManager<CarbonPlayerCommon> userManager
final UserManagerInternal<C> userManager,
final Logger logger
) {
return carbonServer.players().stream()
.map(player -> savePlayer(carbonServer, userManager, (WrappedCarbonPlayer) player))
.map(player -> PlayerUtils.savePlayer(userManager, (C) player, logger))
.toList();
}
public static CompletableFuture<ComponentPlayerResult<CarbonPlayerCommon>> savePlayer(
final CarbonServer carbonServer,
final UserManager<CarbonPlayerCommon> userManager,
final WrappedCarbonPlayer player
public static <C extends CarbonPlayer> CompletableFuture<Void> savePlayer(
final UserManagerInternal<C> userManager,
final C player,
final Logger logger
) {
final var saveResult =
userManager.savePlayer(player.carbonPlayerCommon());
saveResult.thenAccept(result -> {
if (result.player() == null) {
carbonServer.console().sendMessage(result.reason());
}
});
saveResult.exceptionally(exception -> {
exception.getCause().printStackTrace();
final var saveResult = userManager.save(player);
saveResult.exceptionally(thr -> {
logger.warn("Exception saving data for player {} with UUID {}", player.username(), player.uuid(), thr);
return null;
});
return saveResult;
}
public static CompletableFuture<ComponentPlayerResult<CarbonPlayerCommon>> saveAndInvalidatePlayer(
final CarbonServer carbonServer,
final UserManager<CarbonPlayerCommon> userManager,
final WrappedCarbonPlayer player
) {
final var saveResult =
userManager.saveAndInvalidatePlayer(player.carbonPlayerCommon());
saveResult.thenAccept(result -> {
if (result.player() == null) {
carbonServer.console().sendMessage(result.reason());
}
});
saveResult.exceptionally(exception -> {
exception.getCause().printStackTrace();
return null;
});
return saveResult;
}
@@ -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.util;
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 Strings {
private Strings() {
}
public static @Nullable String trim(final @Nullable String s) {
return s == null ? null : s.trim();
}
}
+2 -2
View File
@@ -15,8 +15,8 @@ dependencies {
minecraft(libs.fabricMinecraft)
mappings(loom.officialMojangMappings())
modImplementation(libs.fabricLoader)
modImplementation("net.fabricmc.fabric-api:fabric-api:0.69.1+1.19.3")
modImplementation("net.fabricmc.fabric-api:fabric-api-deprecated:0.69.1+1.19.3") // LuckPerms needs to work at dev time
modImplementation("net.fabricmc.fabric-api:fabric-api:0.76.0+1.19.4")
modImplementation("net.fabricmc.fabric-api:fabric-api-deprecated:0.76.0+1.19.4") // LuckPerms needs to work at dev time
carbon(projects.carbonchatCommon) {
exclude("net.kyori", "adventure-api")
@@ -19,38 +19,33 @@
*/
package net.draycia.carbon.fabric;
import com.google.inject.Guice;
import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.TypeLiteral;
import com.google.inject.Provider;
import com.google.inject.Singleton;
import java.nio.file.Path;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import net.draycia.carbon.api.CarbonChat;
import net.draycia.carbon.api.CarbonChatProvider;
import java.util.concurrent.ScheduledExecutorService;
import net.draycia.carbon.api.CarbonServer;
import net.draycia.carbon.api.channels.ChannelRegistry;
import net.draycia.carbon.api.events.CarbonEventHandler;
import net.draycia.carbon.api.users.UserManager;
import net.draycia.carbon.common.CarbonChatInternal;
import net.draycia.carbon.common.DataDirectory;
import net.draycia.carbon.common.PeriodicTasks;
import net.draycia.carbon.common.channels.CarbonChannelRegistry;
import net.draycia.carbon.common.command.commands.ExecutionCoordinatorHolder;
import net.draycia.carbon.common.messages.CarbonMessages;
import net.draycia.carbon.common.messaging.MessagingManager;
import net.draycia.carbon.common.users.CarbonPlayerCommon;
import net.draycia.carbon.common.util.CloudUtils;
import net.draycia.carbon.common.util.ListenerUtils;
import net.draycia.carbon.common.util.PlayerUtils;
import net.draycia.carbon.common.users.ProfileCache;
import net.draycia.carbon.common.users.ProfileResolver;
import net.draycia.carbon.fabric.callback.ChatCallback;
import net.draycia.carbon.fabric.command.DeleteMessageCommand;
import net.draycia.carbon.fabric.listeners.FabricChatListener;
import net.draycia.carbon.fabric.listeners.FabricChatPreviewListener;
import net.draycia.carbon.fabric.listeners.FabricPlayerJoinListener;
import net.draycia.carbon.fabric.listeners.FabricPlayerLeaveListener;
import net.fabricmc.api.ModInitializer;
import net.draycia.carbon.fabric.listeners.FabricJoinQuitListener;
import net.draycia.carbon.fabric.users.CarbonPlayerFabric;
import net.fabricmc.fabric.api.event.lifecycle.v1.ServerLifecycleEvents;
import net.fabricmc.fabric.api.event.lifecycle.v1.ServerTickEvents;
import net.fabricmc.fabric.api.message.v1.ServerMessageDecoratorEvent;
import net.fabricmc.fabric.api.networking.v1.ServerPlayConnectionEvents;
import net.fabricmc.loader.api.FabricLoader;
import net.fabricmc.loader.api.ModContainer;
import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.text.Component;
import net.kyori.moonshine.message.IMessageRenderer;
@@ -58,145 +53,76 @@ import net.minecraft.core.registries.Registries;
import net.minecraft.network.chat.ChatType;
import net.minecraft.resources.ResourceKey;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.MinecraftServer;
import ninja.egg82.messenger.services.PacketService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.checkerframework.checker.nullness.qual.MonotonicNonNull;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.checkerframework.framework.qual.DefaultQualifier;
import static java.util.Objects.requireNonNull;
@DefaultQualifier(NonNull.class)
public final class CarbonChatFabric implements ModInitializer, CarbonChat {
private final CarbonEventHandler eventHandler = new CarbonEventHandler();
private @Nullable MinecraftServer minecraftServer;
private @MonotonicNonNull ModContainer modContainer;
private @MonotonicNonNull Injector injector;
private @MonotonicNonNull UserManager<CarbonPlayerCommon> userManager;
private @MonotonicNonNull Logger logger;
private @MonotonicNonNull CarbonServerFabric carbonServerFabric;
private @MonotonicNonNull CarbonMessages carbonMessages;
private @MonotonicNonNull ChannelRegistry channelRegistry;
private final UUID serverId = UUID.randomUUID();
@Singleton
public final class CarbonChatFabric extends CarbonChatInternal<CarbonPlayerFabric> {
public static ResourceKey<ChatType> CHAT_TYPE = ResourceKey.create(Registries.CHAT_TYPE, new ResourceLocation("carbon", "chat"));
private @MonotonicNonNull MessagingManager messagingManager = null;
@Inject
private CarbonChatFabric(
final Injector injector,
final Logger logger,
final @DataDirectory Path dataDirectory,
final @PeriodicTasks ScheduledExecutorService periodicTasks,
final ProfileCache profileCache,
final ProfileResolver profileResolver,
final FabricUserManager userManager,
final ExecutionCoordinatorHolder commandExecutor,
final CarbonServer carbonServer,
final CarbonMessages carbonMessages,
final CarbonEventHandler eventHandler,
final CarbonChannelRegistry channelRegistry,
final IMessageRenderer<Audience, String, Component, Component> renderer,
final Provider<MessagingManager> messagingManagerProvider
) {
super(
injector,
logger,
dataDirectory,
periodicTasks,
profileCache,
profileResolver,
userManager,
commandExecutor,
carbonServer,
carbonMessages,
eventHandler,
channelRegistry,
renderer,
messagingManagerProvider
);
}
@Override
public void onInitialize() {
this.modContainer = FabricLoader.getInstance().getModContainer("carbonchat").orElseThrow(() ->
new IllegalStateException("Could not find ModContainer for carbonchat."));
CarbonChatProvider.register(this);
this.logger = LogManager.getLogger(this.modContainer.getMetadata().getName());
this.injector = Guice.createInjector(new CarbonChatFabricModule(this, this.logger, this.dataDirectory()));
this.carbonMessages = this.injector.getInstance(CarbonMessages.class);
this.channelRegistry = this.injector.getInstance(ChannelRegistry.class);
this.carbonServerFabric = this.injector.getInstance(CarbonServerFabric.class);
this.userManager = this.injector.getInstance(com.google.inject.Key.get(new TypeLiteral<UserManager<CarbonPlayerCommon>>() {}));
this.init();
// Platform Listeners
this.registerChatListener();
this.registerServerLifecycleListeners();
this.registerPlayerStatusListeners();
this.registerTickListeners();
// Listeners
ListenerUtils.registerCommonListeners(this.injector);
// Commands
CloudUtils.loadCommands(this.injector);
final var commandSettings = CloudUtils.loadCommandSettings(this.injector);
CloudUtils.registerCommands(commandSettings);
this.injector.getInstance(DeleteMessageCommand.class).init();
// Load channels
((CarbonChannelRegistry) this.channelRegistry()).loadConfigChannels(this.carbonMessages);
this.injector().getInstance(DeleteMessageCommand.class).init();
}
private void registerChatListener() {
ChatCallback.setup();
ChatCallback.INSTANCE.registerListener(new FabricChatListener(this, this.channelRegistry));
ServerMessageDecoratorEvent.EVENT.register(ServerMessageDecoratorEvent.CONTENT_PHASE, this.injector.getInstance(FabricChatPreviewListener.class));
ChatCallback.INSTANCE.registerListener(new FabricChatListener(this, this.channelRegistry()));
ServerMessageDecoratorEvent.EVENT.register(ServerMessageDecoratorEvent.CONTENT_PHASE, this.injector().getInstance(FabricChatPreviewListener.class));
}
private void registerServerLifecycleListeners() {
ServerLifecycleEvents.SERVER_STARTING.register(server -> this.minecraftServer = server);
ServerLifecycleEvents.SERVER_STOPPING.register($ -> PlayerUtils.saveLoggedInPlayers(this.carbonServerFabric, this.userManager).forEach(CompletableFuture::join));
ServerLifecycleEvents.SERVER_STOPPED.register(server -> this.minecraftServer = null);
ServerLifecycleEvents.SERVER_STOPPED.register(server -> this.shutdown());
}
private void registerPlayerStatusListeners() {
ServerPlayConnectionEvents.DISCONNECT.register(this.injector.getInstance(FabricPlayerLeaveListener.class));
ServerPlayConnectionEvents.JOIN.register(this.injector.getInstance(FabricPlayerJoinListener.class));
}
private void registerTickListeners() {
final long saveDelay = 5 * 60 * 20; // 5 minutes
ServerTickEvents.END_SERVER_TICK.register(server -> {
if (server.getTickCount() != 0 && server.getTickCount() % saveDelay == 0) {
PlayerUtils.saveLoggedInPlayers(this.carbonServerFabric, this.userManager);
}
});
}
@Override
public UUID serverId() {
return this.serverId;
}
@Override
public @Nullable PacketService packetService() {
if (this.messagingManager == null) {
this.messagingManager = this.injector.getInstance(MessagingManager.class);
}
return this.messagingManager.packetService();
}
@Override
public Logger logger() {
return this.logger;
}
@Override
public Path dataDirectory() {
return FabricLoader.getInstance().getConfigDir().resolve(this.modContainer.getMetadata().getId());
}
@Override
public CarbonEventHandler eventHandler() {
return this.eventHandler;
}
@Override
public CarbonServer server() {
return this.carbonServerFabric;
}
@Override
public ChannelRegistry channelRegistry() {
return this.channelRegistry;
}
@Override
public <T extends Audience> IMessageRenderer<T, String, Component, Component> messageRenderer() {
return this.injector.getInstance(FabricMessageRenderer.class);
}
public MinecraftServer minecraftServer() {
return requireNonNull(this.minecraftServer, "Attempted to get the MinecraftServer instance when one is not active.");
}
public CarbonMessages carbonMessages() {
return this.carbonMessages;
final FabricJoinQuitListener listener = this.injector().getInstance(FabricJoinQuitListener.class);
ServerPlayConnectionEvents.DISCONNECT.register(listener);
ServerPlayConnectionEvents.JOIN.register(listener);
}
public boolean luckPermsLoaded() {
@@ -20,28 +20,37 @@
package net.draycia.carbon.fabric;
import cloud.commandframework.CommandManager;
import cloud.commandframework.execution.AsynchronousCommandExecutionCoordinator;
import cloud.commandframework.fabric.FabricServerCommandManager;
import cloud.commandframework.fabric.argument.FabricArgumentParsers;
import com.google.inject.AbstractModule;
import com.google.inject.Injector;
import com.google.inject.Provider;
import com.google.inject.Provides;
import com.google.inject.Singleton;
import com.google.inject.TypeLiteral;
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.api.util.SourcedAudience;
import net.draycia.carbon.common.CarbonCommonModule;
import net.draycia.carbon.common.ForCarbon;
import net.draycia.carbon.common.DataDirectory;
import net.draycia.carbon.common.command.Commander;
import net.draycia.carbon.common.command.argument.PlayerSuggestions;
import net.draycia.carbon.common.command.commands.ExecutionCoordinatorHolder;
import net.draycia.carbon.common.messages.CarbonMessages;
import net.draycia.carbon.common.users.ProfileResolver;
import net.draycia.carbon.common.users.UserManagerInternal;
import net.draycia.carbon.common.util.CloudUtils;
import net.draycia.carbon.fabric.command.FabricCommander;
import net.draycia.carbon.fabric.command.FabricPlayerCommander;
import net.draycia.carbon.fabric.users.FabricProfileResolver;
import net.fabricmc.loader.api.FabricLoader;
import net.fabricmc.loader.api.ModContainer;
import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.text.Component;
import net.kyori.moonshine.message.IMessageRenderer;
import net.minecraft.server.level.ServerPlayer;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.framework.qual.DefaultQualifier;
@@ -50,34 +59,34 @@ import org.checkerframework.framework.qual.DefaultQualifier;
public final class CarbonChatFabricModule extends AbstractModule {
private final Logger logger;
private final CarbonChatFabric carbonChat;
private final Path dataDirectory;
private final ModContainer modContainer;
CarbonChatFabricModule(
final CarbonChatFabric carbonChat,
final Logger logger,
final Path dataDirectory
) {
this.logger = logger;
this.carbonChat = carbonChat;
this.dataDirectory = dataDirectory;
CarbonChatFabricModule() {
final ModContainer modContainer = FabricLoader.getInstance().getModContainer("carbonchat")
.orElseThrow(() -> new IllegalStateException("Could not find ModContainer for carbonchat."));
this.modContainer = modContainer;
this.logger = LogManager.getLogger(modContainer.getMetadata().getName());
}
@Provides
@Singleton
public CommandManager<Commander> commandManager() {
public CommandManager<Commander> commandManager(
final ExecutionCoordinatorHolder executionCoordinatorHolder,
final Provider<CarbonChatFabric> carbonChat,
final CarbonMessages carbonMessages
) {
final FabricServerCommandManager<Commander> commandManager = new FabricServerCommandManager<>(
AsynchronousCommandExecutionCoordinator.<Commander>builder().build(),
executionCoordinatorHolder.executionCoordinator(),
commandSourceStack -> {
if (commandSourceStack.getEntity() instanceof ServerPlayer) {
return new FabricPlayerCommander(this.carbonChat, commandSourceStack);
return new FabricPlayerCommander(carbonChat.get(), commandSourceStack);
}
return FabricCommander.from(commandSourceStack);
},
commander -> ((FabricCommander) commander).commandSourceStack()
);
CloudUtils.decorateCommandManager(commandManager, this.carbonChat.carbonMessages());
CloudUtils.decorateCommandManager(commandManager, carbonMessages);
commandManager.brigadierManager().setNativeNumberSuggestions(false);
@@ -96,16 +105,25 @@ public final class CarbonChatFabricModule extends AbstractModule {
return injector.getInstance(FabricMessageRenderer.class);
}
@Provides
public PlayerSuggestions playerSuggestions(final MinecraftServerHolder serverHolder) {
return (ctx, input) -> serverHolder.requireServer().getPlayerList().getPlayers().stream()
.map(player -> player.getGameProfile().getName())
.toList();
}
@Override
public void configure() {
this.install(new CarbonCommonModule());
this.bind(CarbonChat.class).toInstance(this.carbonChat);
this.bind(CarbonChatFabric.class).toInstance(this.carbonChat);
this.bind(ModContainer.class).toInstance(this.modContainer);
this.bind(CarbonChat.class).to(CarbonChatFabric.class);
this.bind(Logger.class).toInstance(this.logger);
this.bind(Path.class).annotatedWith(ForCarbon.class).toInstance(this.dataDirectory);
this.bind(Path.class).annotatedWith(DataDirectory.class).toInstance(FabricLoader.getInstance().getConfigDir().resolve(this.modContainer.getMetadata().getId()));
this.bind(CarbonServer.class).to(CarbonServerFabric.class);
this.bind(PlayerSuggestions.class).toInstance(FabricArgumentParsers.<Commander>singlePlayerSelector()::suggestions);
this.bind(ProfileResolver.class).to(FabricProfileResolver.class);
this.bind(new TypeLiteral<UserManager<?>>() {}).to(FabricUserManager.class);
this.bind(new TypeLiteral<UserManagerInternal<?>>() {}).to(FabricUserManager.class);
}
}
@@ -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.fabric;
import com.google.inject.Guice;
import net.draycia.carbon.api.CarbonChatProvider;
import net.fabricmc.api.ModInitializer;
public class CarbonFabricBootstrap implements ModInitializer {
@Override
public void onInitialize() {
final CarbonChatFabric carbonChat = Guice.createInjector(new CarbonChatFabricModule())
.getInstance(CarbonChatFabric.class);
CarbonChatProvider.register(carbonChat);
carbonChat.onInitialize();
}
}
@@ -21,22 +21,16 @@ package net.draycia.carbon.fabric;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.Objects;
import net.draycia.carbon.api.CarbonServer;
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.users.CarbonPlayerCommon;
import net.draycia.carbon.fabric.users.CarbonPlayerFabric;
import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.audience.ForwardingAudience;
import net.kyori.adventure.platform.fabric.FabricServerAudiences;
import net.minecraft.server.level.ServerPlayer;
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;
@@ -44,38 +38,31 @@ import org.jetbrains.annotations.NotNull;
@DefaultQualifier(NonNull.class)
public final class CarbonServerFabric implements CarbonServer, ForwardingAudience.Single {
private final CarbonChatFabric carbonChatFabric;
private final UserManager<CarbonPlayerFabric> userManager;
private final MinecraftServerHolder serverHolder;
private final FabricUserManager userManager;
@Inject
private CarbonServerFabric(final CarbonChatFabric carbonChatFabric, final UserManager<CarbonPlayerCommon> userManager) {
this.carbonChatFabric = carbonChatFabric;
this.userManager = new FabricUserManager(userManager, carbonChatFabric);
private CarbonServerFabric(final MinecraftServerHolder serverHolder, final FabricUserManager userManager) {
this.serverHolder = serverHolder;
this.userManager = userManager;
}
@Override
public @NotNull Audience audience() {
return FabricServerAudiences.of(this.carbonChatFabric.minecraftServer()).all();
return FabricServerAudiences.of(this.serverHolder.requireServer()).all();
}
@Override
public Audience console() {
return this.carbonChatFabric.minecraftServer();
return this.serverHolder.requireServer().createCommandSourceStack();
}
@Override
public List<? extends CarbonPlayer> players() {
final var players = new ArrayList<CarbonPlayer>();
for (final var player : this.carbonChatFabric.minecraftServer().getPlayerList().getPlayers()) {
final ComponentPlayerResult<CarbonPlayerFabric> result = this.userManager.carbonPlayer(player.getUUID()).join();
if (result.player() != null) {
players.add(result.player());
}
}
return players;
return this.serverHolder.requireServer().getPlayerList().getPlayers().stream()
.map(serverPlayer -> this.userManager.user(serverPlayer.getUUID()).getNow(null))
.filter(Objects::nonNull)
.toList();
}
@Override
@@ -83,22 +70,4 @@ public final class CarbonServerFabric implements CarbonServer, ForwardingAudienc
return this.userManager;
}
@Override
public CompletableFuture<@Nullable UUID> resolveUUID(final String username) {
final @Nullable ServerPlayer serverPlayer = this.carbonChatFabric.minecraftServer().getPlayerList().getPlayerByName(username);
if (serverPlayer == null) {
return CompletableFuture.completedFuture(null);
}
return CompletableFuture.completedFuture(serverPlayer.getUUID());
}
@Override
public CompletableFuture<@Nullable String> resolveName(final UUID uuid) {
final @Nullable ServerPlayer serverPlayer = this.carbonChatFabric.minecraftServer().getPlayerList().getPlayer(uuid);
if (serverPlayer == null) {
return CompletableFuture.completedFuture(null);
}
return CompletableFuture.completedFuture(serverPlayer.getGameProfile().getName());
}
}
@@ -19,159 +19,43 @@
*/
package net.draycia.carbon.fabric;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import net.draycia.carbon.api.users.ComponentPlayerResult;
import net.draycia.carbon.api.users.UserManager;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
import net.draycia.carbon.common.users.Backing;
import net.draycia.carbon.common.users.CarbonPlayerCommon;
import net.draycia.carbon.common.users.SaveOnChange;
import net.draycia.carbon.common.users.PlatformUserManager;
import net.draycia.carbon.common.users.UserManagerInternal;
import net.draycia.carbon.fabric.users.CarbonPlayerFabric;
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 FabricUserManager implements UserManager<CarbonPlayerFabric>, SaveOnChange {
@Singleton
public final class FabricUserManager extends PlatformUserManager<CarbonPlayerFabric> {
protected final UserManager<CarbonPlayerCommon> proxiedUserManager;
private final CarbonChatFabric carbonChatFabric;
private final MinecraftServerHolder serverHolder;
private final Provider<CarbonChatFabric> carbonChat;
public FabricUserManager(final UserManager<CarbonPlayerCommon> proxiedUserManager, final CarbonChatFabric carbonChatFabric) {
this.proxiedUserManager = proxiedUserManager;
this.carbonChatFabric = carbonChatFabric;
@Inject
private FabricUserManager(
final @Backing UserManagerInternal<CarbonPlayerCommon> backingManager,
final MinecraftServerHolder serverHolder,
final Provider<CarbonChatFabric> carbonChat
) {
super(backingManager);
this.serverHolder = serverHolder;
this.carbonChat = carbonChat;
}
@Override
public CompletableFuture<ComponentPlayerResult<CarbonPlayerFabric>> carbonPlayer(final UUID uuid) {
return this.proxiedUserManager.carbonPlayer(uuid).thenApply(result -> {
if (result.player() == null) {
return new ComponentPlayerResult<>(null, result.reason());
}
return new ComponentPlayerResult<>(new CarbonPlayerFabric(result.player(), this.carbonChatFabric), result.reason());
});
protected CarbonPlayerFabric wrap(final CarbonPlayerCommon common) {
return new CarbonPlayerFabric(common, this.serverHolder, this.carbonChat);
}
@Override
public CompletableFuture<ComponentPlayerResult<CarbonPlayerFabric>> savePlayer(final CarbonPlayerFabric player) {
return this.proxiedUserManager.savePlayer(player.carbonPlayerCommon()).thenApply(result -> {
if (result.player() == null) {
return new ComponentPlayerResult<>(null, result.reason());
}
return new ComponentPlayerResult<>(new CarbonPlayerFabric(result.player(), this.carbonChatFabric), result.reason());
});
}
@Override
public CompletableFuture<ComponentPlayerResult<CarbonPlayerFabric>> saveAndInvalidatePlayer(final CarbonPlayerFabric player) {
return this.proxiedUserManager.saveAndInvalidatePlayer(player.carbonPlayerCommon()).thenApply(result -> {
if (result.player() == null) {
return new ComponentPlayerResult<>(null, result.reason());
}
return new ComponentPlayerResult<>(new CarbonPlayerFabric(result.player(), this.carbonChatFabric), result.reason());
});
}
@Override
public int saveDisplayName(final UUID id, final @Nullable Component component) {
if (this.proxiedUserManager instanceof SaveOnChange saveOnChange) {
return saveOnChange.saveDisplayName(id, component);
}
return -1;
}
@Override
public int saveMuted(final UUID id, final boolean muted) {
if (this.proxiedUserManager instanceof SaveOnChange saveOnChange) {
return saveOnChange.saveMuted(id, muted);
}
return -1;
}
@Override
public int saveDeafened(final UUID id, final boolean deafened) {
if (this.proxiedUserManager instanceof SaveOnChange saveOnChange) {
return saveOnChange.saveDeafened(id, deafened);
}
return -1;
}
@Override
public int saveSpying(final UUID id, final boolean spying) {
if (this.proxiedUserManager instanceof SaveOnChange saveOnChange) {
return saveOnChange.saveSpying(id, spying);
}
return -1;
}
@Override
public int saveSelectedChannel(final UUID id, final @Nullable Key selectedChannel) {
if (this.proxiedUserManager instanceof SaveOnChange saveOnChange) {
return saveOnChange.saveSelectedChannel(id, selectedChannel);
}
return -1;
}
@Override
public int saveLastWhisperTarget(final UUID id, final @Nullable UUID lastWhisperTarget) {
if (this.proxiedUserManager instanceof SaveOnChange saveOnChange) {
return saveOnChange.saveLastWhisperTarget(id, lastWhisperTarget);
}
return -1;
}
@Override
public int saveWhisperReplyTarget(final UUID id, final @Nullable UUID whisperReplyTarget) {
if (this.proxiedUserManager instanceof SaveOnChange saveOnChange) {
return saveOnChange.saveWhisperReplyTarget(id, whisperReplyTarget);
}
return -1;
}
@Override
public int addIgnore(final UUID id, final UUID ignoredPlayer) {
if (this.proxiedUserManager instanceof SaveOnChange saveOnChange) {
return saveOnChange.addIgnore(id, ignoredPlayer);
}
return -1;
}
@Override
public int removeIgnore(final UUID id, final UUID ignoredPlayer) {
if (this.proxiedUserManager instanceof SaveOnChange saveOnChange) {
return saveOnChange.removeIgnore(id, ignoredPlayer);
}
return -1;
}
@Override
public int addLeftChannel(final UUID id, final Key channel) {
if (this.proxiedUserManager instanceof SaveOnChange saveOnChange) {
return saveOnChange.addLeftChannel(id, channel);
}
return -1;
}
@Override
public int removeLeftChannel(final UUID id, final Key channel) {
if (this.proxiedUserManager instanceof SaveOnChange saveOnChange) {
return saveOnChange.removeLeftChannel(id, channel);
}
return -1;
protected void updateTransientLoadedStatus(final CarbonPlayerFabric wrapped) {
wrapped.carbonPlayerCommon().markTransientLoaded(wrapped.player().isEmpty());
}
}
@@ -0,0 +1,45 @@
/*
* 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.fabric;
import com.google.inject.Inject;
import java.util.Objects;
import net.fabricmc.fabric.api.event.lifecycle.v1.ServerLifecycleEvents;
import net.minecraft.server.MinecraftServer;
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 MinecraftServerHolder {
private @Nullable MinecraftServer server;
@Inject
private MinecraftServerHolder() {
ServerLifecycleEvents.SERVER_STARTING.register(server -> this.server = server);
ServerLifecycleEvents.SERVER_STOPPED.register(server -> this.server = null);
}
public MinecraftServer requireServer() {
return Objects.requireNonNull(this.server, "server requested when not active");
}
}
@@ -26,6 +26,7 @@ import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import net.draycia.carbon.common.util.ConcurrentUtil;
import net.fabricmc.fabric.api.event.lifecycle.v1.ServerLifecycleEvents;
import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.audience.MessageType;
@@ -33,7 +34,6 @@ import net.kyori.adventure.identity.Identity;
import net.kyori.adventure.text.Component;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.util.thread.NamedThreadFactory;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.checkerframework.checker.nullness.qual.MonotonicNonNull;
@@ -54,8 +54,8 @@ public enum ChatCallback {
private @Nullable ExecutorService chatExecutor;
private final List<Consumer<Chat>> listeners = new CopyOnWriteArrayList<>();
private void initExecutor() {
this.chatExecutor = Executors.newSingleThreadExecutor(new NamedThreadFactory("CarbonChat-Chat-Thread"));
private void initExecutor(final Logger logger) {
this.chatExecutor = Executors.newSingleThreadExecutor(ConcurrentUtil.carbonThreadFactory(logger, "Chat Handling"));
}
private void shutdownExecutor() {
@@ -114,7 +114,7 @@ public enum ChatCallback {
}
public static void setup() {
ServerLifecycleEvents.SERVER_STARTING.register(server -> INSTANCE.initExecutor());
ServerLifecycleEvents.SERVER_STARTING.register(server -> INSTANCE.initExecutor(LOGGER));
ServerLifecycleEvents.SERVER_STOPPED.register(server -> INSTANCE.shutdownExecutor());
}
@@ -22,7 +22,7 @@ package net.draycia.carbon.fabric.chat;
import net.draycia.carbon.api.CarbonChatProvider;
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.minecraft.server.level.ServerPlayer;
import org.checkerframework.checker.nullness.qual.MonotonicNonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
@@ -38,15 +38,9 @@ public class MessageRecipientFilter {
}
public boolean shouldFilterMessageTo(final ServerPlayer serverPlayer) {
final ComponentPlayerResult<? extends CarbonPlayer> authorResult = CarbonChatProvider.carbonChat().server().userManager().carbonPlayer(this.sender.getUUID()).join();
final ComponentPlayerResult<? extends CarbonPlayer> recipientResult = CarbonChatProvider.carbonChat().server().userManager().carbonPlayer(serverPlayer.getUUID()).join();
final @MonotonicNonNull CarbonPlayer author = authorResult.player();
final @MonotonicNonNull CarbonPlayer recipient = recipientResult.player();
if (author == null || recipient == null) {
return true; // TODO: should we filter messages when this happens?
}
final UserManager<? extends CarbonPlayer> userManager = CarbonChatProvider.carbonChat().userManager();
final CarbonPlayer author = userManager.user(this.sender.getUUID()).join();
final CarbonPlayer recipient = userManager.user(serverPlayer.getUUID()).join();
if (author.muted()) {
return true;
@@ -33,7 +33,6 @@ import java.util.stream.Stream;
import net.draycia.carbon.common.command.CarbonCommand;
import net.draycia.carbon.common.command.CommandSettings;
import net.draycia.carbon.common.command.Commander;
import net.draycia.carbon.common.command.argument.PlayerSuggestions;
import net.draycia.carbon.common.messages.CarbonMessages;
import net.draycia.carbon.fabric.CarbonChatFabric;
import net.draycia.carbon.fabric.mixin.MessageSignatureCacheAccessor;
@@ -52,19 +51,16 @@ public class DeleteMessageCommand extends CarbonCommand {
final CarbonChatFabric carbonChat;
final CommandManager<Commander> commandManager;
final CarbonMessages messageService;
final PlayerSuggestions playerSuggestions;
@Inject
public DeleteMessageCommand(
final CarbonChatFabric carbonChat,
final CommandManager<Commander> commandManager,
final CarbonMessages messageService,
final PlayerSuggestions playerSuggestions
final CarbonMessages messageService
) {
this.carbonChat = carbonChat;
this.commandManager = commandManager;
this.messageService = messageService;
this.playerSuggestions = playerSuggestions;
}
@Override
@@ -48,7 +48,7 @@ public record FabricPlayerCommander(
@Override
public CarbonPlayer carbonPlayer() {
return requireNonNull(
this.carbon.server().userManager().carbonPlayer(this.player().getUUID()).join().player(),
this.carbon.userManager().user(this.player().getUUID()).join(),
"No CarbonPlayer for logged in Player!"
);
}
@@ -27,7 +27,6 @@ import java.util.regex.Pattern;
import net.draycia.carbon.api.channels.ChannelRegistry;
import net.draycia.carbon.api.events.CarbonChatEvent;
import net.draycia.carbon.api.users.CarbonPlayer;
import net.draycia.carbon.api.users.ComponentPlayerResult;
import net.draycia.carbon.api.util.KeyedRenderer;
import net.draycia.carbon.fabric.CarbonChatFabric;
import net.draycia.carbon.fabric.callback.ChatCallback;
@@ -60,12 +59,7 @@ public class FabricChatListener implements Consumer<ChatCallback.Chat> {
@Override
public void accept(final ChatCallback.Chat chat) {
final var playerResult = this.carbonChatFabric.server().userManager().carbonPlayer(chat.sender().getUUID()).join();
final @Nullable CarbonPlayer sender = playerResult.player();
if (sender == null) {
return;
}
final @Nullable CarbonPlayer sender = this.carbonChatFabric.userManager().user(chat.sender().getUUID()).join();
var channel = requireNonNullElse(sender.selectedChannel(), this.channelRegistry.defaultValue());
final var originalMessage = chat.message();
@@ -123,9 +117,9 @@ public class FabricChatListener implements Consumer<ChatCallback.Chat> {
try {
final Optional<UUID> uuid = viewer.get(Identity.UUID);
if (uuid.isPresent()) {
final ComponentPlayerResult<? extends CarbonPlayer> targetPlayer = this.carbonChatFabric.server().userManager().carbonPlayer(uuid.get()).join();
final CarbonPlayer targetPlayer = this.carbonChatFabric.userManager().user(uuid.get()).join();
renderedMessage = renderer.render(sender, targetPlayer.player(), renderedMessage, chatEvent.message());
renderedMessage = renderer.render(sender, targetPlayer, renderedMessage, chatEvent.message());
} else {
renderedMessage = renderer.render(sender, viewer, renderedMessage, chatEvent.message());
}
@@ -70,12 +70,7 @@ public class FabricChatPreviewListener implements ChatDecorator {
return CompletableFuture.completedFuture(component);
}
final var playerResult = this.carbonChat.server().userManager().carbonPlayer(serverPlayer.getUUID()).join();
final @Nullable CarbonPlayer sender = playerResult.player();
if (sender == null) {
return CompletableFuture.completedFuture(component);
}
final @Nullable CarbonPlayer sender = this.carbonChat.userManager().user(serverPlayer.getUUID()).join();
var channel = requireNonNullElse(sender.selectedChannel(), this.channelRegistry.defaultValue());
@@ -22,35 +22,58 @@ package net.draycia.carbon.fabric.listeners;
import com.google.inject.Inject;
import java.util.List;
import net.draycia.carbon.common.config.ConfigFactory;
import net.draycia.carbon.common.users.ProfileCache;
import net.draycia.carbon.common.users.UserManagerInternal;
import net.fabricmc.fabric.api.networking.v1.PacketSender;
import net.fabricmc.fabric.api.networking.v1.ServerPlayConnectionEvents;
import net.minecraft.network.protocol.game.ClientboundCustomChatCompletionsPacket;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.network.ServerGamePacketListenerImpl;
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;
@DefaultQualifier(NonNull.class)
public class FabricPlayerJoinListener implements ServerPlayConnectionEvents.Join {
public class FabricJoinQuitListener implements ServerPlayConnectionEvents.Join, ServerPlayConnectionEvents.Disconnect {
private ConfigFactory configFactory;
private final ProfileCache profileCache;
private final Logger logger;
private final ConfigFactory configFactory;
private final UserManagerInternal<?> userManager;
@Inject
public FabricPlayerJoinListener(final ConfigFactory configFactory) {
public FabricJoinQuitListener(
final Logger logger,
final ConfigFactory configFactory,
final ProfileCache profileCache,
final UserManagerInternal<?> userManager
) {
this.logger = logger;
this.configFactory = configFactory;
this.profileCache = profileCache;
this.userManager = userManager;
}
@Override
public void onPlayReady(final ServerGamePacketListenerImpl handler, final PacketSender sender, final MinecraftServer server) {
this.profileCache.cache(handler.getPlayer().getUUID(), handler.getPlayer().getGameProfile().getName());
final @Nullable List<String> suggestions = this.configFactory.primaryConfig().customChatSuggestions();
if (suggestions == null || suggestions.isEmpty()) {
return;
}
sender.sendPacket(new ClientboundCustomChatCompletionsPacket(ClientboundCustomChatCompletionsPacket.Action.SET,
suggestions));
sender.sendPacket(new ClientboundCustomChatCompletionsPacket(ClientboundCustomChatCompletionsPacket.Action.SET, suggestions));
}
@Override
public void onPlayDisconnect(final ServerGamePacketListenerImpl handler, final MinecraftServer server) {
this.userManager.loggedOut(handler.getPlayer().getGameProfile().getId()).exceptionally(thr -> {
this.logger.warn("Exception saving data for player " + handler.getPlayer().getGameProfile().getName() + " with uuid " + handler.getPlayer().getGameProfile().getId());
return null;
});
}
}
@@ -1,60 +0,0 @@
/*
* 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.fabric.listeners;
import com.google.inject.Inject;
import net.draycia.carbon.api.CarbonChat;
import net.draycia.carbon.api.users.UserManager;
import net.draycia.carbon.common.users.CarbonPlayerCommon;
import net.draycia.carbon.common.util.PlayerUtils;
import net.draycia.carbon.fabric.users.CarbonPlayerFabric;
import net.fabricmc.fabric.api.networking.v1.ServerPlayConnectionEvents;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.network.ServerGamePacketListenerImpl;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.framework.qual.DefaultQualifier;
@DefaultQualifier(NonNull.class)
public class FabricPlayerLeaveListener implements ServerPlayConnectionEvents.Disconnect {
private final CarbonChat carbonChat;
private final UserManager<CarbonPlayerCommon> userManager;
@Inject
public FabricPlayerLeaveListener(
final CarbonChat carbonChat,
final UserManager<CarbonPlayerCommon> userManager
) {
this.carbonChat = carbonChat;
this.userManager = userManager;
}
@Override
public void onPlayDisconnect(final ServerGamePacketListenerImpl handler, final MinecraftServer server) {
this.carbonChat.server().userManager().carbonPlayer(handler.getPlayer().getUUID()).thenAccept(result -> {
if (result.player() == null) {
return;
}
PlayerUtils.saveAndInvalidatePlayer(this.carbonChat.server(), this.userManager, (CarbonPlayerFabric) result.player());
});
}
}
@@ -21,7 +21,6 @@ package net.draycia.carbon.fabric.mixin;
import net.draycia.carbon.api.CarbonChatProvider;
import net.draycia.carbon.api.users.CarbonPlayer;
import net.draycia.carbon.api.users.ComponentPlayerResult;
import net.draycia.carbon.fabric.CarbonChatFabric;
import net.draycia.carbon.fabric.callback.PlayerStatusMessageEvents;
import net.draycia.carbon.fabric.chat.MessageRecipientFilter;
@@ -70,8 +69,8 @@ abstract class ServerGamePacketListenerImplMixin implements ServerGamePacketList
@Redirect(method = "broadcastChatMessage", at = @At(value = "INVOKE", target = "Lnet/minecraft/server/players/PlayerList;broadcastChatMessage(Lnet/minecraft/network/chat/PlayerChatMessage;Lnet/minecraft/server/level/ServerPlayer;Lnet/minecraft/network/chat/ChatType$Bound;)V"))
private void broadcastChatMessage(final PlayerList instance, final PlayerChatMessage playerChatMessage, final ServerPlayer serverPlayer, final ChatType.Bound bound) {
// TODO: Get the channel the message was sent in, when the player uses /channel <message>
final ComponentPlayerResult<? extends CarbonPlayer> result = CarbonChatProvider.carbonChat().server().userManager().carbonPlayer(serverPlayer.getUUID()).join();
final MessageRecipientFilter filter = new MessageRecipientFilter(serverPlayer, result.player().selectedChannel());
final CarbonPlayer result = CarbonChatProvider.carbonChat().userManager().user(serverPlayer.getUUID()).join();
final MessageRecipientFilter filter = new MessageRecipientFilter(serverPlayer, result.selectedChannel());
for (final ServerPlayer player : this.server.getPlayerList().getPlayers()) {
if (filter.shouldFilterMessageTo(player)) {
@@ -19,6 +19,7 @@
*/
package net.draycia.carbon.fabric.users;
import com.google.inject.Provider;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
@@ -30,6 +31,7 @@ import net.draycia.carbon.api.util.InventorySlot;
import net.draycia.carbon.common.users.CarbonPlayerCommon;
import net.draycia.carbon.common.users.WrappedCarbonPlayer;
import net.draycia.carbon.fabric.CarbonChatFabric;
import net.draycia.carbon.fabric.MinecraftServerHolder;
import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.audience.ForwardingAudience;
import net.kyori.adventure.identity.Identity;
@@ -46,10 +48,12 @@ import org.checkerframework.framework.qual.DefaultQualifier;
public class CarbonPlayerFabric extends WrappedCarbonPlayer implements ForwardingAudience.Single {
private final CarbonPlayerCommon carbonPlayerCommon;
private final CarbonChatFabric carbonChatFabric;
private final MinecraftServerHolder serverHolder;
private final Provider<CarbonChatFabric> carbonChatFabric;
public CarbonPlayerFabric(final CarbonPlayerCommon carbonPlayerCommon, final CarbonChatFabric carbonChatFabric) {
public CarbonPlayerFabric(final CarbonPlayerCommon carbonPlayerCommon, final MinecraftServerHolder serverHolder, final Provider<CarbonChatFabric> carbonChatFabric) {
this.carbonPlayerCommon = carbonPlayerCommon;
this.serverHolder = serverHolder;
this.carbonChatFabric = carbonChatFabric;
}
@@ -58,9 +62,9 @@ public class CarbonPlayerFabric extends WrappedCarbonPlayer implements Forwardin
return this.player().orElseThrow();
}
private Optional<ServerPlayer> player() {
public Optional<ServerPlayer> player() {
return Optional.ofNullable(
this.carbonChatFabric.minecraftServer().getPlayerList()
this.serverHolder.requireServer().getPlayerList()
.getPlayer(this.carbonPlayerCommon.uuid())
);
}
@@ -109,7 +113,7 @@ public class CarbonPlayerFabric extends WrappedCarbonPlayer implements Forwardin
}
final @Nullable ServerPlayer player = this.player().orElse(null);
final @Nullable ServerPlayer otherPlayer = this.carbonChatFabric.minecraftServer()
final @Nullable ServerPlayer otherPlayer = this.serverHolder.requireServer()
.getPlayerList().getPlayer(other.uuid());
if (player == null || otherPlayer == null) {
@@ -130,7 +134,7 @@ public class CarbonPlayerFabric extends WrappedCarbonPlayer implements Forwardin
}
final Optional<ServerPlayer> player = this.player();
final @Nullable ServerPlayer otherPlayer = this.carbonChatFabric.minecraftServer()
final @Nullable ServerPlayer otherPlayer = this.serverHolder.requireServer()
.getPlayerList().getPlayer(other.uuid());
if (player.isEmpty() || otherPlayer == null) {
@@ -184,7 +188,7 @@ public class CarbonPlayerFabric extends WrappedCarbonPlayer implements Forwardin
@Override
public String primaryGroup() {
if (!this.carbonChatFabric.luckPermsLoaded()) {
if (!this.carbonChatFabric.get().luckPermsLoaded()) {
return "default";
}
@@ -193,7 +197,7 @@ public class CarbonPlayerFabric extends WrappedCarbonPlayer implements Forwardin
@Override
public List<String> groups() {
if (!this.carbonChatFabric.luckPermsLoaded()) {
if (!this.carbonChatFabric.get().luckPermsLoaded()) {
return List.of("default");
}
@@ -0,0 +1,72 @@
/*
* 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.fabric.users;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import net.draycia.carbon.common.users.MojangProfileResolver;
import net.draycia.carbon.common.users.ProfileResolver;
import net.draycia.carbon.fabric.MinecraftServerHolder;
import net.minecraft.server.level.ServerPlayer;
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 final class FabricProfileResolver implements ProfileResolver {
private final MinecraftServerHolder serverHolder;
private final ProfileResolver mojang;
@Inject
private FabricProfileResolver(final MinecraftServerHolder serverHolder, final MojangProfileResolver mojang) {
this.serverHolder = serverHolder;
this.mojang = mojang;
}
@Override
public CompletableFuture<@Nullable UUID> resolveUUID(final String username, final boolean cacheOnly) {
final @Nullable ServerPlayer online = this.serverHolder.requireServer().getPlayerList().getPlayerByName(username);
if (online != null) {
return CompletableFuture.completedFuture(online.getUUID());
}
return this.mojang.resolveUUID(username, cacheOnly);
}
@Override
public CompletableFuture<@Nullable String> resolveName(final UUID uuid, final boolean cacheOnly) {
final @Nullable ServerPlayer online = this.serverHolder.requireServer().getPlayerList().getPlayer(uuid);
if (online != null) {
return CompletableFuture.completedFuture(online.getGameProfile().getName());
}
return this.mojang.resolveName(uuid, cacheOnly);
}
@Override
public void shutdown() {
this.mojang.shutdown();
}
}
+1 -1
View File
@@ -16,7 +16,7 @@
"environment": "*",
"entrypoints": {
"main": [
"net.draycia.carbon.fabric.CarbonChatFabric"
"net.draycia.carbon.fabric.CarbonFabricBootstrap"
]
},
"mixins": [
+14 -10
View File
@@ -12,18 +12,18 @@ plugins:
versions:
indra: 3.0.1
licenser: 0.6.1
shadow: 7.1.2
adventure: 4.12.0
cloud: 1.8.0
shadow: 8.1.0
adventure: 4.13.0
cloud: 1.8.3
cloudSponge: 1.8.0-SNAPSHOT
configurate: 4.1.2
typesafeConfig: 1.4.1
checkerQual: 3.28.0
checkerQual: 3.32.0
stylecheck: 0.1
gson: 2.8.0
gson: 2.10
guava: 30.1-jre
bstats: 3.0.0
paperApi: 1.19.3-R0.1-SNAPSHOT
paperApi: 1.19.4-R0.1-SNAPSHOT
paperLib: 1.0.8-SNAPSHOT
kyoriEventApi: 5.0.0-SNAPSHOT
kyoriRegistry: 1.0.0-SNAPSHOT
@@ -32,9 +32,9 @@ versions:
guice: 5.1.0
velocityApi: 3.1.1
geantyref: 1.3.11
fabricMinecraft: 1.19.3
fabricLoader: 0.14.12
adventurePlatformFabric: 5.6.1
fabricMinecraft: 1.19.4
fabricLoader: 0.14.17
adventurePlatformFabric: 5.8.0
luckPermsApi: 5.3
essentialsx: 2.19.3
discordsrv: 1.26.0
@@ -185,6 +185,10 @@ dependencies:
group: com.google.inject
name: guice
version: { ref: guice }
assistedInject:
group: com.google.inject.extensions
name: guice-assistedinject
version: { ref: guice }
jdbiCore:
group: org.jdbi
@@ -297,7 +301,7 @@ dependencies:
name: indra-licenser-cadix
version: { ref: indra }
shadow:
group: gradle.plugin.com.github.johnrengelman
group: com.github.johnrengelman
name: shadow
version: { ref: shadow }
licenser:
Binary file not shown.
+1 -1
View File
@@ -1,6 +1,6 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.6-bin.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-8.0.2-bin.zip
networkTimeout=10000
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
Vendored
+2 -2
View File
@@ -144,7 +144,7 @@ if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC3045
# shellcheck disable=SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
@@ -152,7 +152,7 @@ if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC3045
# shellcheck disable=SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
+1 -1
View File
@@ -34,7 +34,7 @@ tasks {
relocateDependency("io.leangen.geantyref")
}
runServer {
minecraftVersion("1.19.3")
minecraftVersion("1.19.4")
}
}
@@ -21,185 +21,116 @@ package net.draycia.carbon.paper;
import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.Provider;
import com.google.inject.Singleton;
import github.scarsz.discordsrv.DiscordSRV;
import java.nio.file.Path;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import net.draycia.carbon.api.CarbonChat;
import java.util.concurrent.ScheduledExecutorService;
import net.draycia.carbon.api.CarbonServer;
import net.draycia.carbon.api.channels.ChannelRegistry;
import net.draycia.carbon.api.events.CarbonEventHandler;
import net.draycia.carbon.api.users.UserManager;
import net.draycia.carbon.common.ForCarbon;
import net.draycia.carbon.common.CarbonChatInternal;
import net.draycia.carbon.common.DataDirectory;
import net.draycia.carbon.common.PeriodicTasks;
import net.draycia.carbon.common.channels.CarbonChannelRegistry;
import net.draycia.carbon.common.listeners.RadiusListener;
import net.draycia.carbon.common.command.commands.ExecutionCoordinatorHolder;
import net.draycia.carbon.common.messages.CarbonMessages;
import net.draycia.carbon.common.messaging.MessagingManager;
import net.draycia.carbon.common.users.CarbonPlayerCommon;
import net.draycia.carbon.common.util.CloudUtils;
import net.draycia.carbon.common.util.ListenerUtils;
import net.draycia.carbon.common.util.PlayerUtils;
import net.draycia.carbon.common.users.ProfileCache;
import net.draycia.carbon.common.users.ProfileResolver;
import net.draycia.carbon.paper.hooks.DSRVChatHook;
import net.draycia.carbon.paper.listeners.DiscordMessageListener;
import net.draycia.carbon.paper.listeners.PaperChatListener;
import net.draycia.carbon.paper.listeners.PaperPlayerJoinListener;
import net.draycia.carbon.paper.messages.PaperMessageRenderer;
import net.draycia.carbon.paper.users.CarbonPlayerPaper;
import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.text.Component;
import net.kyori.moonshine.message.IMessageRenderer;
import ninja.egg82.messenger.services.PacketService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.bstats.bukkit.Metrics;
import org.bukkit.Bukkit;
import org.bukkit.event.Listener;
import org.bukkit.plugin.java.JavaPlugin;
import org.checkerframework.checker.nullness.qual.MonotonicNonNull;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.checkerframework.framework.qual.DefaultQualifier;
@DefaultQualifier(NonNull.class)
public final class CarbonChatPaper implements CarbonChat {
@Singleton
public final class CarbonChatPaper extends CarbonChatInternal<CarbonPlayerPaper> {
private static final Set<Class<? extends Listener>> LISTENER_CLASSES = Set.of(
PaperChatListener.class,
PaperPlayerJoinListener.class
);
private static final int BSTATS_PLUGIN_ID = 8720;
private final CarbonEventHandler eventHandler = new CarbonEventHandler();
private @MonotonicNonNull JavaPlugin plugin;
private @MonotonicNonNull Logger logger;
private @MonotonicNonNull Path dataDirectory;
private @MonotonicNonNull Injector injector;
private @MonotonicNonNull UserManager<CarbonPlayerCommon> userManager;
private @MonotonicNonNull CarbonServer carbonServer;
private @MonotonicNonNull CarbonMessages carbonMessages;
private @MonotonicNonNull ChannelRegistry channelRegistry;
private final UUID serverId = UUID.randomUUID();
private @MonotonicNonNull MessagingManager messagingManager = null;
CarbonChatPaper() {
}
private final JavaPlugin plugin;
@Inject
private void onLoad(
private CarbonChatPaper(
final Injector injector,
final JavaPlugin plugin,
final CarbonMessages carbonMessages,
final ChannelRegistry channelRegistry,
final CarbonEventHandler eventHandler,
final CarbonChannelRegistry channelRegistry,
final Provider<MessagingManager> messagingManager,
final CarbonServer carbonServer,
final UserManager<CarbonPlayerCommon> userManager,
@ForCarbon final Path dataDirectory
final PaperUserManager userManager,
@DataDirectory final Path dataDirectory,
@PeriodicTasks final ScheduledExecutorService periodicTasks,
final ProfileCache profileCache,
final ProfileResolver profileResolver,
final ExecutionCoordinatorHolder commandExecutor,
final IMessageRenderer<Audience, String, Component, Component> renderer
) {
this.logger = LogManager.getLogger("CarbonChat");
this.injector = injector;
super(
injector, LogManager.getLogger("CarbonChat"), dataDirectory,
periodicTasks,
profileCache,
profileResolver,
userManager,
commandExecutor,
carbonServer,
carbonMessages,
eventHandler,
channelRegistry,
renderer,
messagingManager
);
this.plugin = plugin;
this.carbonMessages = carbonMessages;
this.channelRegistry = channelRegistry;
this.carbonServer = carbonServer;
this.userManager = userManager;
this.dataDirectory = dataDirectory;
this.packetService();
}
void onEnable() {
final Metrics metrics = new Metrics(this.plugin, BSTATS_PLUGIN_ID);
this.init();
this.packetService();
for (final Class<? extends Listener> listenerClass : LISTENER_CLASSES) {
this.plugin.getServer().getPluginManager().registerEvents(
this.injector.getInstance(listenerClass),
this.injector().getInstance(listenerClass),
this.plugin
);
}
// Listeners
ListenerUtils.registerCommonListeners(this.injector);
this.injector.getInstance(RadiusListener.class);
// Commands
// This is a bit awkward looking
CloudUtils.loadCommands(this.injector);
final var commandSettings = CloudUtils.loadCommandSettings(this.injector);
CloudUtils.registerCommands(commandSettings);
// Player data saving
final long saveDelay = 5 * 60 * 20;
Bukkit.getScheduler().runTaskTimerAsynchronously(this.plugin,
() -> PlayerUtils.saveLoggedInPlayers(this.carbonServer, this.userManager), saveDelay, saveDelay);
// Load channels
((CarbonChannelRegistry) this.channelRegistry()).loadConfigChannels(this.carbonMessages);
this.discoverDiscordHooks();
}
private void discoverDiscordHooks() {
if (Bukkit.getPluginManager().isPluginEnabled("EssentialsDiscord")) {
final DiscordMessageListener discordMessageListener = this.injector.getInstance(DiscordMessageListener.class);
final DiscordMessageListener discordMessageListener = this.injector().getInstance(DiscordMessageListener.class);
Bukkit.getPluginManager().registerEvents(discordMessageListener, this.plugin);
discordMessageListener.init();
}
if (Bukkit.getPluginManager().isPluginEnabled("DiscordSRV")) {
this.logger.info("DiscordSRV found! Enabling hook.");
this.logger().info("DiscordSRV found! Enabling hook.");
DiscordSRV.getPlugin().getPluginHooks().add(new DSRVChatHook());
}
}
void onDisable() {
PlayerUtils.saveLoggedInPlayers(this.carbonServer, this.userManager).forEach(CompletableFuture::join);
}
@Override
public UUID serverId() {
return this.serverId;
}
@Override
public @Nullable PacketService packetService() {
if (this.messagingManager == null) {
this.messagingManager = this.injector.getInstance(MessagingManager.class);
}
return this.messagingManager.packetService();
}
@Override
public Logger logger() {
return this.logger;
}
@Override
public Path dataDirectory() {
return this.dataDirectory;
}
@Override
public CarbonServerPaper server() {
return (CarbonServerPaper) this.carbonServer;
}
@Override
public ChannelRegistry channelRegistry() {
return this.channelRegistry;
}
public CarbonMessages carbonMessages() {
return this.carbonMessages;
}
@Override
public @NonNull CarbonEventHandler eventHandler() {
return this.eventHandler;
}
@Override
public IMessageRenderer<Audience, String, Component, Component> messageRenderer() {
return this.injector.getInstance(PaperMessageRenderer.class);
this.shutdown();
}
public static boolean papiLoaded() {
@@ -22,25 +22,30 @@ package net.draycia.carbon.paper;
import cloud.commandframework.CommandManager;
import cloud.commandframework.brigadier.CloudBrigadierManager;
import cloud.commandframework.bukkit.parsers.PlayerArgument;
import cloud.commandframework.execution.AsynchronousCommandExecutionCoordinator;
import cloud.commandframework.paper.PaperCommandManager;
import com.google.inject.AbstractModule;
import com.google.inject.Injector;
import com.google.inject.Provides;
import com.google.inject.Singleton;
import com.google.inject.TypeLiteral;
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.api.util.SourcedAudience;
import net.draycia.carbon.common.CarbonCommonModule;
import net.draycia.carbon.common.ForCarbon;
import net.draycia.carbon.common.DataDirectory;
import net.draycia.carbon.common.command.Commander;
import net.draycia.carbon.common.command.argument.PlayerSuggestions;
import net.draycia.carbon.common.command.commands.ExecutionCoordinatorHolder;
import net.draycia.carbon.common.messages.CarbonMessages;
import net.draycia.carbon.common.users.ProfileResolver;
import net.draycia.carbon.common.users.UserManagerInternal;
import net.draycia.carbon.common.util.CloudUtils;
import net.draycia.carbon.paper.command.PaperCommander;
import net.draycia.carbon.paper.command.PaperPlayerCommander;
import net.draycia.carbon.paper.messages.PaperMessageRenderer;
import net.draycia.carbon.paper.users.PaperProfileResolver;
import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.text.Component;
import net.kyori.moonshine.message.IMessageRenderer;
@@ -58,28 +63,23 @@ public final class CarbonChatPaperModule extends AbstractModule {
private final Logger logger = LogManager.getLogger("CarbonChat");
private final CarbonPaperBootstrap bootstrap;
private final CarbonChat carbonChat;
CarbonChatPaperModule(
final CarbonPaperBootstrap bootstrap,
final CarbonChat carbonChat
) {
CarbonChatPaperModule(final CarbonPaperBootstrap bootstrap) {
this.bootstrap = bootstrap;
this.carbonChat = carbonChat;
}
@Provides
@Singleton
public CommandManager<Commander> commandManager(final CarbonServer server, final CarbonMessages messages) {
public CommandManager<Commander> commandManager(final UserManager<?> userManager, final CarbonMessages messages, final ExecutionCoordinatorHolder executionCoordinatorHolder) {
final PaperCommandManager<Commander> commandManager;
try {
commandManager = new PaperCommandManager<>(
this.bootstrap,
AsynchronousCommandExecutionCoordinator.<Commander>builder().build(),
executionCoordinatorHolder.executionCoordinator(),
commandSender -> {
if (commandSender instanceof Player player) {
return new PaperPlayerCommander(server, player);
return new PaperPlayerCommander(userManager, player);
}
return PaperCommander.from(commandSender);
},
@@ -116,21 +116,20 @@ public final class CarbonChatPaperModule extends AbstractModule {
return injector.getInstance(PaperMessageRenderer.class);
}
@Provides
public CarbonChat carbonChat() {
return this.carbonChat;
}
@Override
public void configure() {
this.install(new CarbonCommonModule());
this.bind(CarbonChat.class).to(CarbonChatPaper.class);
this.bind(JavaPlugin.class).toInstance(this.bootstrap);
this.bind(Server.class).toInstance(this.bootstrap.getServer());
this.bind(Logger.class).toInstance(this.logger);
this.bind(Path.class).annotatedWith(ForCarbon.class).toInstance(this.bootstrap.getDataFolder().toPath());
this.bind(Path.class).annotatedWith(DataDirectory.class).toInstance(this.bootstrap.getDataFolder().toPath());
this.bind(CarbonServer.class).to(CarbonServerPaper.class);
this.bind(PlayerSuggestions.class).toInstance(new PlayerArgument.PlayerParser<Commander>()::suggestions);
this.bind(ProfileResolver.class).to(PaperProfileResolver.class);
this.bind(new TypeLiteral<UserManager<?>>() {}).to(PaperUserManager.class);
this.bind(new TypeLiteral<UserManagerInternal<?>>() {}).to(PaperUserManager.class);
}
}
@@ -20,7 +20,6 @@
package net.draycia.carbon.paper;
import com.google.inject.Guice;
import com.google.inject.Injector;
import io.papermc.lib.PaperLib;
import java.util.logging.Level;
import net.draycia.carbon.api.CarbonChatProvider;
@@ -45,10 +44,9 @@ public final class CarbonPaperBootstrap extends JavaPlugin {
return;
}
this.carbonChat = new CarbonChatPaper();
final Injector injector = Guice.createInjector(new CarbonChatPaperModule(this, this.carbonChat));
this.carbonChat = Guice.createInjector(new CarbonChatPaperModule(this))
.getInstance(CarbonChatPaper.class);
CarbonChatProvider.register(this.carbonChat);
injector.injectMembers(this.carbonChat);
}
// null = success
@@ -21,23 +21,16 @@ package net.draycia.carbon.paper;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.Objects;
import net.draycia.carbon.api.CarbonServer;
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.users.CarbonPlayerCommon;
import net.draycia.carbon.paper.users.CarbonPlayerPaper;
import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.audience.ForwardingAudience;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.Server;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.checkerframework.framework.qual.DefaultQualifier;
@Singleton
@@ -45,12 +38,12 @@ import org.checkerframework.framework.qual.DefaultQualifier;
public final class CarbonServerPaper implements CarbonServer, ForwardingAudience.Single {
private final Server server;
private final UserManager<CarbonPlayerPaper> userManager;
private final PaperUserManager userManager;
@Inject
private CarbonServerPaper(final Server server, final UserManager<CarbonPlayerCommon> userManager) {
private CarbonServerPaper(final Server server, final PaperUserManager userManager) {
this.server = server;
this.userManager = new PaperUserManager(userManager);
this.userManager = userManager;
}
@Override
@@ -65,17 +58,10 @@ public final class CarbonServerPaper implements CarbonServer, ForwardingAudience
@Override
public List<? extends CarbonPlayer> players() {
final var players = new ArrayList<CarbonPlayer>();
for (final var player : this.server.getOnlinePlayers()) {
final ComponentPlayerResult<CarbonPlayerPaper> result = this.userManager.carbonPlayer(player.getUniqueId()).join();
if (result.player() != null) {
players.add(result.player());
}
}
return players;
return this.server.getOnlinePlayers().stream()
.map(bukkit -> this.userManager.user(bukkit.getUniqueId()).getNow(null))
.filter(Objects::nonNull)
.toList();
}
@Override
@@ -83,24 +69,4 @@ public final class CarbonServerPaper implements CarbonServer, ForwardingAudience
return this.userManager;
}
@Override
public CompletableFuture<@Nullable UUID> resolveUUID(final String username) {
// TODO: user cache?
return CompletableFuture.supplyAsync(() -> {
final OfflinePlayer offlinePlayer = Bukkit.getOfflinePlayer(username);
if (!offlinePlayer.hasPlayedBefore()) {
return null;
}
return offlinePlayer.getUniqueId();
});
}
@Override
public CompletableFuture<@Nullable String> resolveName(final UUID uuid) {
// TODO: user cache?
return CompletableFuture.supplyAsync(() -> Bukkit.getOfflinePlayer(uuid).getName());
}
}
@@ -19,158 +19,33 @@
*/
package net.draycia.carbon.paper;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import net.draycia.carbon.api.users.ComponentPlayerResult;
import net.draycia.carbon.api.users.UserManager;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import net.draycia.carbon.common.users.Backing;
import net.draycia.carbon.common.users.CarbonPlayerCommon;
import net.draycia.carbon.common.users.SaveOnChange;
import net.draycia.carbon.common.users.PlatformUserManager;
import net.draycia.carbon.common.users.UserManagerInternal;
import net.draycia.carbon.paper.users.CarbonPlayerPaper;
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 PaperUserManager implements UserManager<CarbonPlayerPaper>, SaveOnChange {
@Singleton
public final class PaperUserManager extends PlatformUserManager<CarbonPlayerPaper> {
protected final UserManager<CarbonPlayerCommon> proxiedUserManager;
public PaperUserManager(final UserManager<CarbonPlayerCommon> proxiedUserManager) {
this.proxiedUserManager = proxiedUserManager;
@Inject
private PaperUserManager(final @Backing UserManagerInternal<CarbonPlayerCommon> backingManager) {
super(backingManager);
}
@Override
public CompletableFuture<ComponentPlayerResult<CarbonPlayerPaper>> carbonPlayer(final UUID uuid) {
return this.proxiedUserManager.carbonPlayer(uuid).thenApply(result -> {
if (result.player() == null) {
return new ComponentPlayerResult<>(null, result.reason());
}
return new ComponentPlayerResult<>(new CarbonPlayerPaper(result.player()), result.reason());
});
protected CarbonPlayerPaper wrap(final CarbonPlayerCommon common) {
return new CarbonPlayerPaper(common);
}
@Override
public CompletableFuture<ComponentPlayerResult<CarbonPlayerPaper>> savePlayer(final CarbonPlayerPaper player) {
return this.proxiedUserManager.savePlayer(player.carbonPlayerCommon()).thenApply(result -> {
if (result.player() == null) {
return new ComponentPlayerResult<>(null, result.reason());
}
return new ComponentPlayerResult<>(new CarbonPlayerPaper(result.player()), result.reason());
});
}
@Override
public CompletableFuture<ComponentPlayerResult<CarbonPlayerPaper>> saveAndInvalidatePlayer(final CarbonPlayerPaper player) {
return this.proxiedUserManager.saveAndInvalidatePlayer(player.carbonPlayerCommon()).thenApply(result -> {
if (result.player() == null) {
return new ComponentPlayerResult<>(null, result.reason());
}
return new ComponentPlayerResult<>(new CarbonPlayerPaper(result.player()), result.reason());
});
}
@Override
public int saveDisplayName(final UUID id, final @Nullable Component component) {
if (this.proxiedUserManager instanceof SaveOnChange saveOnChange) {
return saveOnChange.saveDisplayName(id, component);
}
return -1;
}
@Override
public int saveMuted(final UUID id, final boolean muted) {
if (this.proxiedUserManager instanceof SaveOnChange saveOnChange) {
return saveOnChange.saveMuted(id, muted);
}
return -1;
}
@Override
public int saveDeafened(final UUID id, final boolean deafened) {
if (this.proxiedUserManager instanceof SaveOnChange saveOnChange) {
return saveOnChange.saveDeafened(id, deafened);
}
return -1;
}
@Override
public int saveSpying(final UUID id, final boolean spying) {
if (this.proxiedUserManager instanceof SaveOnChange saveOnChange) {
return saveOnChange.saveSpying(id, spying);
}
return -1;
}
@Override
public int saveSelectedChannel(final UUID id, final @Nullable Key selectedChannel) {
if (this.proxiedUserManager instanceof SaveOnChange saveOnChange) {
return saveOnChange.saveSelectedChannel(id, selectedChannel);
}
return -1;
}
@Override
public int saveLastWhisperTarget(final UUID id, final @Nullable UUID lastWhisperTarget) {
if (this.proxiedUserManager instanceof SaveOnChange saveOnChange) {
return saveOnChange.saveLastWhisperTarget(id, lastWhisperTarget);
}
return -1;
}
@Override
public int saveWhisperReplyTarget(final UUID id, final @Nullable UUID whisperReplyTarget) {
if (this.proxiedUserManager instanceof SaveOnChange saveOnChange) {
return saveOnChange.saveWhisperReplyTarget(id, whisperReplyTarget);
}
return -1;
}
@Override
public int addIgnore(final UUID id, final UUID ignoredPlayer) {
if (this.proxiedUserManager instanceof SaveOnChange saveOnChange) {
return saveOnChange.addIgnore(id, ignoredPlayer);
}
return -1;
}
@Override
public int removeIgnore(final UUID id, final UUID ignoredPlayer) {
if (this.proxiedUserManager instanceof SaveOnChange saveOnChange) {
return saveOnChange.removeIgnore(id, ignoredPlayer);
}
return -1;
}
@Override
public int addLeftChannel(final UUID id, final Key channel) {
if (this.proxiedUserManager instanceof SaveOnChange saveOnChange) {
return saveOnChange.addLeftChannel(id, channel);
}
return -1;
}
@Override
public int removeLeftChannel(final UUID id, final Key channel) {
if (this.proxiedUserManager instanceof SaveOnChange saveOnChange) {
return saveOnChange.removeLeftChannel(id, channel);
}
return -1;
protected void updateTransientLoadedStatus(final CarbonPlayerPaper wrapped) {
wrapped.carbonPlayerCommon().markTransientLoaded(wrapped.bukkitPlayer() == null);
}
}
@@ -19,8 +19,8 @@
*/
package net.draycia.carbon.paper.command;
import net.draycia.carbon.api.CarbonServer;
import net.draycia.carbon.api.users.CarbonPlayer;
import net.draycia.carbon.api.users.UserManager;
import net.draycia.carbon.common.command.PlayerCommander;
import net.kyori.adventure.audience.Audience;
import org.bukkit.command.CommandSender;
@@ -32,7 +32,7 @@ import static java.util.Objects.requireNonNull;
@DefaultQualifier(NonNull.class)
public record PaperPlayerCommander(
CarbonServer server,
UserManager<?> userManager,
Player player
) implements PlayerCommander, PaperCommander {
@@ -48,7 +48,7 @@ public record PaperPlayerCommander(
@Override
public CarbonPlayer carbonPlayer() {
return requireNonNull(this.server.userManager().carbonPlayer(this.player.getUniqueId()).join().player(), "No CarbonPlayer for logged in Player!");
return requireNonNull(this.userManager.user(this.player.getUniqueId()).join(), "No CarbonPlayer for logged in Player!");
}
@Override
@@ -59,19 +59,17 @@ public class DiscordMessageListener implements Listener {
return;
}
final var result = this.carbonChat.server().userManager().carbonPlayer(event.getUUID()).join();
final var result = this.carbonChat.userManager().user(event.getUUID()).join();
if (result.player() != null) {
var channel = result.player().selectedChannel();
var channel = result.selectedChannel();
if (channel == null) {
channel = this.carbonChat.channelRegistry().defaultValue();
}
final var messageType = this.channelMessageTypes.get(channel.key());
event.setType(messageType);
if (channel == null) {
channel = this.carbonChat.channelRegistry().defaultValue();
}
final var messageType = this.channelMessageTypes.get(channel.key());
event.setType(messageType);
}
@EventHandler
@@ -66,10 +66,9 @@ public final class PaperChatListener implements Listener {
@EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST)
public void onPaperChat(final @NonNull AsyncChatEvent event) {
final var playerResult = this.carbonChat.server().userManager().carbonPlayer(event.getPlayer().getUniqueId()).join();
final @Nullable CarbonPlayer sender = playerResult.player();
final @Nullable CarbonPlayer sender = this.carbonChat.userManager().user(event.getPlayer().getUniqueId()).join();
if (sender == null || event.viewers().isEmpty()) {
if (event.viewers().isEmpty()) {
return;
}
@@ -126,10 +125,7 @@ public final class PaperChatListener implements Listener {
final Audience recipientViewer;
if (recipientUUID.isPresent()) {
final var recipientResult = this.carbonChat.server().userManager().carbonPlayer(viewer.get(Identity.UUID).orElseThrow()).join();
final @Nullable CarbonPlayer recipient = recipientResult.player();
recipientViewer = requireNonNullElse(recipient, viewer);
recipientViewer = this.carbonChat.userManager().user(viewer.get(Identity.UUID).orElseThrow()).join();
} else {
recipientViewer = viewer;
}
@@ -21,11 +21,9 @@ package net.draycia.carbon.paper.listeners;
import com.google.inject.Inject;
import java.util.Optional;
import net.draycia.carbon.api.CarbonChat;
import net.draycia.carbon.api.users.UserManager;
import net.draycia.carbon.common.users.CarbonPlayerCommon;
import net.draycia.carbon.common.util.PlayerUtils;
import net.draycia.carbon.paper.users.CarbonPlayerPaper;
import net.draycia.carbon.common.users.ProfileCache;
import net.draycia.carbon.paper.PaperUserManager;
import org.apache.logging.log4j.Logger;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
@@ -38,41 +36,45 @@ import org.checkerframework.framework.qual.DefaultQualifier;
@DefaultQualifier(NonNull.class)
public class PaperPlayerJoinListener implements Listener {
private final CarbonChat carbonChat;
private final UserManager<CarbonPlayerCommon> userManager;
private final Logger logger;
private final ProfileCache profileCache;
private final PaperUserManager userManager;
@Inject
public PaperPlayerJoinListener(
final CarbonChat carbonChat,
final UserManager<CarbonPlayerCommon> userManager
final Logger logger,
final ProfileCache profileCache,
final PaperUserManager userManager
) {
this.carbonChat = carbonChat;
this.logger = logger;
this.profileCache = profileCache;
this.userManager = userManager;
}
@EventHandler(priority = EventPriority.LOWEST)
public void cacheProfile(final PlayerJoinEvent event) {
this.profileCache.cache(event.getPlayer().getUniqueId(), event.getPlayer().getName());
}
@EventHandler(priority = EventPriority.HIGH)
public void onJoin(final PlayerJoinEvent event) {
this.carbonChat.server().userManager().carbonPlayer(event.getPlayer().getUniqueId()).thenAccept(result -> {
if (result.player() == null) {
return;
}
Optional.ofNullable(result.player().displayName()).ifPresent(displayName -> {
this.userManager.user(event.getPlayer().getUniqueId()).thenAccept(result -> {
Optional.ofNullable(result.displayName()).ifPresent(displayName -> {
final Player player = event.getPlayer();
player.displayName(displayName);
player.playerListName(displayName);
});
}).exceptionally(thr -> {
this.logger.warn("Exception handling player join", thr);
return null;
});
}
@EventHandler(priority = EventPriority.HIGH)
public void onQuit(final PlayerQuitEvent event) {
this.carbonChat.server().userManager().carbonPlayer(event.getPlayer().getUniqueId()).thenAccept(result -> {
if (result.player() == null) {
return;
}
PlayerUtils.saveAndInvalidatePlayer(this.carbonChat.server(), this.userManager, (CarbonPlayerPaper) result.player());
this.userManager.loggedOut(event.getPlayer().getUniqueId()).exceptionally(thr -> {
this.logger.warn("Exception saving data for player " + event.getPlayer().getName() + " with uuid " + event.getPlayer().getUniqueId());
return null;
});
}
@@ -0,0 +1,72 @@
/*
* 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.paper.users;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import net.draycia.carbon.common.users.MojangProfileResolver;
import net.draycia.carbon.common.users.ProfileResolver;
import org.bukkit.Server;
import org.bukkit.entity.Player;
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 final class PaperProfileResolver implements ProfileResolver {
private final Server server;
private final ProfileResolver mojang;
@Inject
private PaperProfileResolver(final Server server, final MojangProfileResolver mojang) {
this.server = server;
this.mojang = mojang;
}
@Override
public CompletableFuture<@Nullable UUID> resolveUUID(final String username, final boolean cacheOnly) {
final @Nullable Player online = this.server.getPlayer(username);
if (online != null) {
return CompletableFuture.completedFuture(online.getUniqueId());
}
return this.mojang.resolveUUID(username, cacheOnly);
}
@Override
public CompletableFuture<@Nullable String> resolveName(final UUID uuid, final boolean cacheOnly) {
final @Nullable Player online = this.server.getPlayer(uuid);
if (online != null) {
return CompletableFuture.completedFuture(online.getName());
}
return this.mojang.resolveName(uuid, cacheOnly);
}
@Override
public void shutdown() {
this.mojang.shutdown();
}
}