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
97 files changed
+2744 -1892

No files matched your search

@@ -23,6 +23,7 @@ import java.nio.file.Path;
import java.util.UUID; import java.util.UUID;
import net.draycia.carbon.api.channels.ChannelRegistry; import net.draycia.carbon.api.channels.ChannelRegistry;
import net.draycia.carbon.api.events.CarbonEventHandler; import net.draycia.carbon.api.events.CarbonEventHandler;
import net.draycia.carbon.api.users.UserManager;
import net.kyori.adventure.audience.Audience; import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.text.Component; import net.kyori.adventure.text.Component;
import net.kyori.moonshine.message.IMessageRenderer; import net.kyori.moonshine.message.IMessageRenderer;
@@ -91,6 +92,14 @@ public interface CarbonChat {
*/ */
CarbonServer server(); CarbonServer server();
/**
* The user manager.
*
* @return the user manager
* @since 2.1.0
*/
UserManager<?> userManager();
/** /**
* The registry that channels are registered to. * The registry that channels are registered to.
* *
@@ -20,13 +20,10 @@
package net.draycia.carbon.api; package net.draycia.carbon.api;
import java.util.List; 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.CarbonPlayer;
import net.draycia.carbon.api.users.UserManager; import net.draycia.carbon.api.users.UserManager;
import net.kyori.adventure.audience.Audience; import net.kyori.adventure.audience.Audience;
import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.checkerframework.framework.qual.DefaultQualifier; 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}. * Manager used to load/obtain and save {@link CarbonPlayer CarbonPlayers}.
* *
* @deprecated Use {@link CarbonChat#userManager} (internal code: inject the UserManager)
* @return the user manager * @return the user manager
* @since 2.1.0 * @since 2.1.0
*/ */
@Deprecated(forRemoval = true)
UserManager<? extends CarbonPlayer> userManager(); 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 * A list of all the channels the player has left
* using the leave command. * 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. * @return a list of the channels.
* @since 2.1.0 * @since 2.1.0
*/ */
@@ -21,6 +21,7 @@ package net.draycia.carbon.api.users;
import net.kyori.adventure.text.Component; import net.kyori.adventure.text.Component;
import org.checkerframework.checker.nullness.qual.MonotonicNonNull; import org.checkerframework.checker.nullness.qual.MonotonicNonNull;
import org.jetbrains.annotations.ApiStatus;
/** /**
* The result of a player data operation. * 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 * @param reason the reason of the result, typically empty unless {@link #player} is null
* @since 2.0.0 * @since 2.0.0
*/ */
@Deprecated(forRemoval = true)
@ApiStatus.Internal
public record ComponentPlayerResult<C extends CarbonPlayer>(@MonotonicNonNull C player, Component reason) { 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.UUID;
import java.util.concurrent.CompletableFuture; 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.checker.nullness.qual.NonNull;
import org.checkerframework.framework.qual.DefaultQualifier; 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}. * Loads and returns a {@link CarbonPlayer} with the given {@link UUID}.
* *
* @deprecated use {@link #user(UUID)} instead
* @param uuid the player's uuid * @param uuid the player's uuid
* @return the result * @return the result
* @since 2.0.0 * @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 * @param uuid the player's id
* @return the result * @return the player
* @since 2.0.0 * @since 2.1.0
*/ */
CompletableFuture<ComponentPlayerResult<C>> savePlayer(final C player); CompletableFuture<C> user(UUID uuid);
/**
* 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);
} }
+1 -1
View File
@@ -38,7 +38,7 @@ fun ShadowJar.standardRelocations() {
//relocateDependency("org.apache") //relocateDependency("org.apache")
relocateDependency("ninja.egg82.messenger") relocateDependency("ninja.egg82.messenger")
relocateDependency("org.antlr") relocateDependency("org.antlr")
relocateDependency("com.github.luben") //relocateDependency("com.github.luben")
//relocateDependency("io.netty") //relocateDependency("io.netty")
relocateDependency("io.nats") relocateDependency("io.nats")
relocateDependency("com.rabbitmq") relocateDependency("com.rabbitmq")
+1
View File
@@ -21,6 +21,7 @@ dependencies {
// Other // Other
api(libs.guice) api(libs.guice)
api(libs.assistedInject)
compileOnlyApi(libs.luckPermsApi) compileOnlyApi(libs.luckPermsApi)
// Storage // 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.Injector;
import com.google.inject.Provides; import com.google.inject.Provides;
import com.google.inject.Singleton; import com.google.inject.Singleton;
import com.google.inject.assistedinject.FactoryModuleBuilder;
import io.leangen.geantyref.TypeToken; import io.leangen.geantyref.TypeToken;
import java.util.Objects; import java.util.Objects;
import java.util.UUID; import java.util.UUID;
import java.util.concurrent.ScheduledExecutorService;
import net.draycia.carbon.api.channels.ChannelRegistry; 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.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.config.ConfigFactory;
import net.draycia.carbon.common.messages.CarbonMessageSender; import net.draycia.carbon.common.messages.CarbonMessageSender;
import net.draycia.carbon.common.messages.CarbonMessageSource; 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.KeyPlaceholderResolver;
import net.draycia.carbon.common.messages.placeholders.StringPlaceholderResolver; import net.draycia.carbon.common.messages.placeholders.StringPlaceholderResolver;
import net.draycia.carbon.common.messages.placeholders.UUIDPlaceholderResolver; 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.CarbonPlayerCommon;
import net.draycia.carbon.common.users.UserManagerInternal;
import net.draycia.carbon.common.users.db.mysql.MySQLUserManager; import net.draycia.carbon.common.users.db.mysql.MySQLUserManager;
import net.draycia.carbon.common.users.db.postgresql.PostgreSQLUserManager; import net.draycia.carbon.common.users.db.postgresql.PostgreSQLUserManager;
import net.draycia.carbon.common.users.json.JSONUserManager; 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.audience.Audience;
import net.kyori.adventure.key.Key; import net.kyori.adventure.key.Key;
import net.kyori.adventure.text.Component; import net.kyori.adventure.text.Component;
import net.kyori.moonshine.Moonshine; import net.kyori.moonshine.Moonshine;
import net.kyori.moonshine.exception.scan.UnscannableMethodException; import net.kyori.moonshine.exception.scan.UnscannableMethodException;
import net.kyori.moonshine.message.IMessageRenderer; import net.kyori.moonshine.message.IMessageRenderer;
import org.apache.logging.log4j.Logger;
import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.framework.qual.DefaultQualifier; import org.checkerframework.framework.qual.DefaultQualifier;
@@ -57,18 +65,29 @@ import org.checkerframework.framework.qual.DefaultQualifier;
public final class CarbonCommonModule extends AbstractModule { public final class CarbonCommonModule extends AbstractModule {
@Provides @Provides
@Backing
@Singleton @Singleton
public UserManager<CarbonPlayerCommon> userManager( public UserManagerInternal<CarbonPlayerCommon> userManager(final ConfigFactory configFactory, final Injector injector) {
final ConfigFactory configFactory,
final Injector injector
) {
return switch (Objects.requireNonNull(configFactory.primaryConfig()).storageType()) { return switch (Objects.requireNonNull(configFactory.primaryConfig()).storageType()) {
case MYSQL -> MySQLUserManager.manager(configFactory.primaryConfig().databaseSettings()); case MYSQL -> injector.getInstance(MySQLUserManager.Factory.class).create();
case PSQL -> PostgreSQLUserManager.manager(configFactory.primaryConfig().databaseSettings()); case PSQL -> injector.getInstance(PostgreSQLUserManager.Factory.class).create();
default -> injector.getInstance(JSONUserManager.class); 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 @Provides
@Singleton @Singleton
public CarbonMessages carbonMessages( public CarbonMessages carbonMessages(
@@ -96,8 +115,15 @@ public final class CarbonCommonModule extends AbstractModule {
.create(this.getClass().getClassLoader()); .create(this.getClass().getClassLoader());
} }
@Provides
@Singleton
public ExecutionCoordinatorHolder executionCoordinatorHolder(final Logger logger) {
return ExecutionCoordinatorHolder.create(logger);
}
@Override @Override
protected void configure() { protected void configure() {
this.install(new FactoryModuleBuilder().build(ArgumentFactory.class));
this.bind(ChannelRegistry.class).to(CarbonChannelRegistry.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.Retention;
import java.lang.annotation.RetentionPolicy; import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target; import java.lang.annotation.Target;
import java.nio.file.Path;
/**
* Injection binding annotation for the {@link Path} which is Carbon's data directory.
*/
@BindingAnnotation @BindingAnnotation
@Retention(RetentionPolicy.RUNTIME) @Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.PARAMETER, ElementType.FIELD}) @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.ChannelRegistry;
import net.draycia.carbon.api.channels.ChatChannel; import net.draycia.carbon.api.channels.ChatChannel;
import net.draycia.carbon.api.events.CarbonChatEvent; 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.users.CarbonPlayer;
import net.draycia.carbon.api.util.KeyedRenderer; 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.Commander;
import net.draycia.carbon.common.command.PlayerCommander; import net.draycia.carbon.common.command.PlayerCommander;
import net.draycia.carbon.common.config.ConfigFactory; 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.messages.CarbonMessages;
import net.draycia.carbon.common.messaging.packets.ChatMessagePacket; import net.draycia.carbon.common.messaging.packets.ChatMessagePacket;
import net.kyori.adventure.audience.Audience; import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.identity.Identity;
import net.kyori.adventure.key.Key; import net.kyori.adventure.key.Key;
import net.kyori.adventure.text.Component; import net.kyori.adventure.text.Component;
import net.kyori.registry.DefaultedRegistryGetter; import net.kyori.registry.DefaultedRegistryGetter;
@@ -105,13 +105,14 @@ public class CarbonChannelRegistry implements ChannelRegistry, DefaultedRegistry
@Inject @Inject
public CarbonChannelRegistry( public CarbonChannelRegistry(
@ForCarbon final Path dataDirectory, @DataDirectory final Path dataDirectory,
final Injector injector, final Injector injector,
final Logger logger, final Logger logger,
final ConfigFactory configFactory, final ConfigFactory configFactory,
final CarbonMessages carbonMessages, final CarbonMessages carbonMessages,
//final BasicChatChannel basicChannel, //final BasicChatChannel basicChannel,
final CarbonChat carbonChat final CarbonChat carbonChat,
final CarbonEventHandler events
) { ) {
this.configChannelDir = dataDirectory.resolve("channels"); this.configChannelDir = dataDirectory.resolve("channels");
this.injector = injector; this.injector = injector;
@@ -121,9 +122,7 @@ public class CarbonChannelRegistry implements ChannelRegistry, DefaultedRegistry
//this.basicChannel = basicChannel; //this.basicChannel = basicChannel;
this.carbonChat = carbonChat; this.carbonChat = carbonChat;
carbonChat.eventHandler().subscribe(CarbonReloadEvent.class, event -> { events.subscribe(CarbonReloadEvent.class, event -> this.reloadRegisteredConfigChannels());
this.reloadRegisteredConfigChannels();
});
} }
public static ConfigurationTransformation.Versioned versioned() { public static ConfigurationTransformation.Versioned versioned() {
@@ -318,7 +317,6 @@ public class CarbonChannelRegistry implements ChannelRegistry, DefaultedRegistry
final var renderers = new ArrayList<KeyedRenderer>(); final var renderers = new ArrayList<KeyedRenderer>();
renderers.add(keyedRenderer(Key.key("carbon", "default"), channel)); 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 chatEvent = new CarbonChatEvent(sender, Component.text(plainMessage), recipients, renderers, channel, false);
final var result = this.carbonChat.eventHandler().emit(chatEvent); 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()); 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()) { for (final Audience recipient : chatEvent.recipients()) {
recipient.sendMessage(identity, renderedMessage); recipient.sendMessage(renderedMessage);
} }
final @Nullable PacketService packetService = this.carbonChat.packetService(); 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(), packetService.queuePacket(new ChatMessagePacket(this.carbonChat.serverId(), sender.uuid(),
configChatChannel.permission(), channel.key(), sender.username(), format, configChatChannel.permission(), channel.key(), sender.username(), format,
Map.of("username", sender.username(), "message", plainMessage))); 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.context.CommandContext;
import cloud.commandframework.exceptions.parsing.NoInputProvidedException; import cloud.commandframework.exceptions.parsing.NoInputProvidedException;
import cloud.commandframework.exceptions.parsing.ParserException; 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.List;
import java.util.Queue; import java.util.Queue;
import java.util.concurrent.CompletableFuture;
import java.util.function.BiFunction; import java.util.function.BiFunction;
import net.draycia.carbon.api.CarbonChatProvider;
import net.draycia.carbon.api.users.CarbonPlayer; 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.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.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable; import org.checkerframework.checker.nullness.qual.Nullable;
import org.checkerframework.framework.qual.DefaultQualifier;
/** /**
* Argument that parses into a {@link CarbonPlayer}. * Argument that parses into a {@link CarbonPlayer}.
*/ */
@SuppressWarnings("unused") @DefaultQualifier(NonNull.class)
public final class CarbonPlayerArgument extends CommandArgument<Commander, CarbonPlayer> { public final class CarbonPlayerArgument extends CommandArgument<Commander, CarbonPlayer> {
private CarbonPlayerArgument( private CarbonPlayerArgument(
final boolean required, final boolean required,
final @NonNull String name, final String name,
final @NonNull String defaultValue, final String defaultValue,
final @Nullable BiFunction<@NonNull CommandContext<Commander>, @NonNull String, final @Nullable BiFunction<CommandContext<Commander>, String,
@NonNull List<@NonNull String>> suggestionsProvider, List<String>> suggestionsProvider,
final @NonNull ArgumentDescription defaultDescription, final ArgumentDescription defaultDescription,
final @NonNull CarbonMessages carbonMessages final CarbonPlayerParser parser
) { ) {
super(required, name, new CarbonPlayerParser(carbonMessages), defaultValue, CarbonPlayer.class, suggestionsProvider, defaultDescription); super(required, name, parser, 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();
} }
public static final class Builder extends CommandArgument.TypedBuilder<Commander, CarbonPlayer, Builder> { 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); super(CarbonPlayer.class, name);
} this.parser = parser;
/**
* Set the message service.
*
* @param carbonMessages the message service
* @return builder instance
*/
public Builder withMessages(final @NonNull CarbonMessages carbonMessages) {
this.carbonMessages = carbonMessages;
return this;
} }
/** /**
@@ -129,14 +81,14 @@ public final class CarbonPlayerArgument extends CommandArgument<Commander, Carbo
* @return constructed component * @return constructed component
*/ */
@Override @Override
public @NonNull CarbonPlayerArgument build() { public CarbonPlayerArgument build() {
return new CarbonPlayerArgument( return new CarbonPlayerArgument(
this.isRequired(), this.isRequired(),
this.getName(), this.getName(),
this.getDefaultValue(), this.getDefaultValue(),
this.getSuggestionsProvider(), this.getSuggestionsProvider(),
this.getDefaultDescription(), 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> { 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) { @Inject
this.carbonMessages = carbonMessages; private CarbonPlayerParser(
final PlayerSuggestions suggestions,
final UserManager<?> userManager,
final ProfileResolver profileResolver
) {
this.suggestions = suggestions;
this.userManager = userManager;
this.profileResolver = profileResolver;
} }
@Override @Override
@SuppressWarnings("deprecation") public ArgumentParseResult<CarbonPlayer> parse(
public @NonNull ArgumentParseResult<CarbonPlayer> parse( final CommandContext<Commander> commandContext,
final @NonNull CommandContext<Commander> commandContext, final Queue<String> inputQueue
final @NonNull Queue<@NonNull String> inputQueue
) { ) {
final String input = inputQueue.peek(); final @Nullable String input = inputQueue.peek();
if (input == null) { if (input == null) {
return ArgumentParseResult.failure(new NoInputProvidedException( 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) { if (uuid == null) {
return ArgumentParseResult.<CarbonPlayer>failure(new CarbonPlayerParseException(input, commandContext, this.carbonMessages)); return CompletableFuture.completedFuture(null);
} }
return this.userManager.user(uuid);
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());
}).join(); }).join();
if (join == null) {
return ArgumentParseResult.failure(new CarbonPlayerParseException(input, commandContext));
}
inputQueue.remove();
return ArgumentParseResult.success(join);
} }
@Override @Override
public @NonNull List<@NonNull String> suggestions( public List<String> suggestions(
final @NonNull CommandContext<Commander> commandContext, final CommandContext<Commander> commandContext,
final @NonNull String input 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. * Construct a new CarbonPlayer parse exception.
* *
* @param input string input * @param input string input
* @param context command context * @param context command context
*/ */
public CarbonPlayerParseException( public CarbonPlayerParseException(
final @NonNull String input, final String input,
final @NonNull CommandContext<?> context, final CommandContext<?> context
final @NonNull CarbonMessages carbonMessages
) { ) {
super( super(
CarbonPlayerParser.class, CarbonPlayerParser.class,
@@ -225,7 +182,7 @@ public final class CarbonPlayerArgument extends CommandArgument<Commander, Carbo
* *
* @return string value * @return string value
*/ */
public @NonNull String input() { public String input() {
return this.input; return this.input;
} }
@@ -27,7 +27,6 @@ import com.google.inject.Inject;
import java.util.UUID; import java.util.UUID;
import net.draycia.carbon.api.CarbonChat; import net.draycia.carbon.api.CarbonChat;
import net.draycia.carbon.api.users.CarbonPlayer; 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.api.util.SourcedAudience;
import net.draycia.carbon.common.command.CarbonCommand; import net.draycia.carbon.common.command.CarbonCommand;
import net.draycia.carbon.common.command.CommandSettings; import net.draycia.carbon.common.command.CommandSettings;
@@ -100,9 +99,8 @@ public class ContinueCommand extends CarbonCommand {
return; return;
} }
final ComponentPlayerResult<? extends CarbonPlayer> result = this.carbonChat.server() final @MonotonicNonNull CarbonPlayer recipient = this.carbonChat
.userManager().carbonPlayer(whisperTarget).join(); .userManager().user(whisperTarget).join();
final @MonotonicNonNull CarbonPlayer recipient = result.player();
if (sender.equals(recipient)) { if (sender.equals(recipient)) {
this.carbonMessages.whisperSelfError(sender, CarbonPlayer.renderName(sender)); 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")) { if (!recipient.online() || !sender.awareOf(recipient) && !sender.hasPermission("carbon.whisper.vanished")) {
final var rawNameInput = CloudUtils.rawInputByMatchingName(handler.getRawInput(), recipient); 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)); this.carbonMessages.errorCommandArgumentParsing(sender, CloudUtils.message(exception));
return; return;
@@ -25,12 +25,11 @@ import cloud.commandframework.minecraft.extras.RichDescription;
import com.google.inject.Inject; import com.google.inject.Inject;
import java.util.ArrayList; import java.util.ArrayList;
import net.draycia.carbon.api.users.CarbonPlayer; 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.CarbonCommand;
import net.draycia.carbon.common.command.CommandSettings; import net.draycia.carbon.common.command.CommandSettings;
import net.draycia.carbon.common.command.Commander; import net.draycia.carbon.common.command.Commander;
import net.draycia.carbon.common.command.PlayerCommander; 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.messages.CarbonMessages;
import net.kyori.adventure.key.Key; import net.kyori.adventure.key.Key;
import net.kyori.adventure.text.Component; import net.kyori.adventure.text.Component;
@@ -44,17 +43,17 @@ public class DebugCommand extends CarbonCommand {
final CommandManager<Commander> commandManager; final CommandManager<Commander> commandManager;
final CarbonMessages carbonMessages; final CarbonMessages carbonMessages;
final PlayerSuggestions playerSuggestions; private final ArgumentFactory argumentFactory;
@Inject @Inject
public DebugCommand( public DebugCommand(
final CommandManager<Commander> commandManager, final CommandManager<Commander> commandManager,
final CarbonMessages carbonMessages, final CarbonMessages carbonMessages,
final PlayerSuggestions playerSuggestions final ArgumentFactory argumentFactory
) { ) {
this.commandManager = commandManager; this.commandManager = commandManager;
this.carbonMessages = carbonMessages; this.carbonMessages = carbonMessages;
this.playerSuggestions = playerSuggestions; this.argumentFactory = argumentFactory;
} }
@Override @Override
@@ -70,7 +69,7 @@ public class DebugCommand extends CarbonCommand {
@Override @Override
public void init() { public void init() {
final var command = this.commandManager.commandBuilder(this.commandSettings().name(), this.commandSettings().aliases()) 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())) RichDescription.of(this.carbonMessages.commandDebugArgumentPlayer()))
.permission("carbon.debug") .permission("carbon.debug")
.senderType(PlayerCommander.class) .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.MinecraftExtrasMetaKeys;
import cloud.commandframework.minecraft.extras.RichDescription; import cloud.commandframework.minecraft.extras.RichDescription;
import com.google.inject.Inject; import com.google.inject.Inject;
import java.util.Objects;
import net.draycia.carbon.api.CarbonChat; import net.draycia.carbon.api.CarbonChat;
import net.draycia.carbon.api.users.CarbonPlayer; 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.CarbonCommand;
import net.draycia.carbon.common.command.CommandSettings; import net.draycia.carbon.common.command.CommandSettings;
import net.draycia.carbon.common.command.Commander; import net.draycia.carbon.common.command.Commander;
import net.draycia.carbon.common.command.PlayerCommander; 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.messages.CarbonMessages;
import net.kyori.adventure.key.Key; import net.kyori.adventure.key.Key;
import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.NonNull;
@@ -44,19 +42,19 @@ public class IgnoreCommand extends CarbonCommand {
final CarbonChat carbonChat; final CarbonChat carbonChat;
final CommandManager<Commander> commandManager; final CommandManager<Commander> commandManager;
final CarbonMessages carbonMessages; final CarbonMessages carbonMessages;
final PlayerSuggestions playerSuggestions; private final ArgumentFactory argumentFactory;
@Inject @Inject
public IgnoreCommand( public IgnoreCommand(
final CarbonChat carbonChat, final CarbonChat carbonChat,
final CommandManager<Commander> commandManager, final CommandManager<Commander> commandManager,
final CarbonMessages carbonMessages, final CarbonMessages carbonMessages,
final PlayerSuggestions playerSuggestions final ArgumentFactory argumentFactory
) { ) {
this.carbonChat = carbonChat; this.carbonChat = carbonChat;
this.commandManager = commandManager; this.commandManager = commandManager;
this.carbonMessages = carbonMessages; this.carbonMessages = carbonMessages;
this.playerSuggestions = playerSuggestions; this.argumentFactory = argumentFactory;
} }
@Override @Override
@@ -72,7 +70,7 @@ public class IgnoreCommand extends CarbonCommand {
@Override @Override
public void init() { public void init() {
final var command = this.commandManager.commandBuilder(this.commandSettings().name(), this.commandSettings().aliases()) 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())) RichDescription.of(this.carbonMessages.commandIgnoreArgumentPlayer()))
.flag(this.commandManager.flagBuilder("uuid") .flag(this.commandManager.flagBuilder("uuid")
.withAliases("u") .withAliases("u")
@@ -89,8 +87,7 @@ public class IgnoreCommand extends CarbonCommand {
if (handler.contains("player")) { if (handler.contains("player")) {
target = handler.get("player"); target = handler.get("player");
} else if (handler.flags().contains("uuid")) { } else if (handler.flags().contains("uuid")) {
final var result = this.carbonChat.server().userManager().carbonPlayer(handler.get("uuid")).join(); target = this.carbonChat.userManager().user(handler.get("uuid")).join();
target = Objects.requireNonNull(result.player(), "No player found for UUID.");
} else { } else {
this.carbonMessages.ignoreTargetInvalid(sender); this.carbonMessages.ignoreTargetInvalid(sender);
return; 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.CommandSettings;
import net.draycia.carbon.common.command.Commander; import net.draycia.carbon.common.command.Commander;
import net.draycia.carbon.common.command.PlayerCommander; 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.messages.CarbonMessages;
import net.draycia.carbon.common.util.ChannelUtils; import net.draycia.carbon.common.util.ChannelUtils;
import net.kyori.adventure.key.Key; import net.kyori.adventure.key.Key;
@@ -45,19 +44,16 @@ public class JoinCommand extends CarbonCommand {
final CarbonChat carbonChat; final CarbonChat carbonChat;
final CommandManager<Commander> commandManager; final CommandManager<Commander> commandManager;
final CarbonMessages carbonMessages; final CarbonMessages carbonMessages;
final PlayerSuggestions playerSuggestions;
@Inject @Inject
public JoinCommand( public JoinCommand(
final CarbonChat carbonChat, final CarbonChat carbonChat,
final CommandManager<Commander> commandManager, final CommandManager<Commander> commandManager,
final CarbonMessages carbonMessages, final CarbonMessages carbonMessages
final PlayerSuggestions playerSuggestions
) { ) {
this.carbonChat = carbonChat; this.carbonChat = carbonChat;
this.commandManager = commandManager; this.commandManager = commandManager;
this.carbonMessages = carbonMessages; this.carbonMessages = carbonMessages;
this.playerSuggestions = playerSuggestions;
} }
@Override @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.CommandSettings;
import net.draycia.carbon.common.command.Commander; import net.draycia.carbon.common.command.Commander;
import net.draycia.carbon.common.command.PlayerCommander; 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.messages.CarbonMessages;
import net.draycia.carbon.common.util.ChannelUtils; import net.draycia.carbon.common.util.ChannelUtils;
import net.kyori.adventure.key.Key; import net.kyori.adventure.key.Key;
@@ -45,19 +44,16 @@ public class LeaveCommand extends CarbonCommand {
final CarbonChat carbonChat; final CarbonChat carbonChat;
final CommandManager<Commander> commandManager; final CommandManager<Commander> commandManager;
final CarbonMessages carbonMessages; final CarbonMessages carbonMessages;
final PlayerSuggestions playerSuggestions;
@Inject @Inject
public LeaveCommand( public LeaveCommand(
final CarbonChat carbonChat, final CarbonChat carbonChat,
final CommandManager<Commander> commandManager, final CommandManager<Commander> commandManager,
final CarbonMessages carbonMessages, final CarbonMessages carbonMessages
final PlayerSuggestions playerSuggestions
) { ) {
this.carbonChat = carbonChat; this.carbonChat = carbonChat;
this.commandManager = commandManager; this.commandManager = commandManager;
this.carbonMessages = carbonMessages; this.carbonMessages = carbonMessages;
this.playerSuggestions = playerSuggestions;
} }
@Override @Override
@@ -24,15 +24,13 @@ import cloud.commandframework.arguments.standard.UUIDArgument;
import cloud.commandframework.minecraft.extras.MinecraftExtrasMetaKeys; import cloud.commandframework.minecraft.extras.MinecraftExtrasMetaKeys;
import cloud.commandframework.minecraft.extras.RichDescription; import cloud.commandframework.minecraft.extras.RichDescription;
import com.google.inject.Inject; import com.google.inject.Inject;
import java.util.Objects;
import net.draycia.carbon.api.CarbonChat; import net.draycia.carbon.api.CarbonChat;
import net.draycia.carbon.api.users.CarbonPlayer; 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.CarbonCommand;
import net.draycia.carbon.common.command.CommandSettings; import net.draycia.carbon.common.command.CommandSettings;
import net.draycia.carbon.common.command.Commander; import net.draycia.carbon.common.command.Commander;
import net.draycia.carbon.common.command.PlayerCommander; 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.messages.CarbonMessages;
import net.kyori.adventure.key.Key; import net.kyori.adventure.key.Key;
import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.NonNull;
@@ -44,19 +42,19 @@ public class MuteCommand extends CarbonCommand {
final CarbonChat carbonChat; final CarbonChat carbonChat;
final CommandManager<Commander> commandManager; final CommandManager<Commander> commandManager;
final CarbonMessages carbonMessages; final CarbonMessages carbonMessages;
final PlayerSuggestions playerSuggestions; private final ArgumentFactory argumentFactory;
@Inject @Inject
public MuteCommand( public MuteCommand(
final CarbonChat carbonChat, final CarbonChat carbonChat,
final CommandManager<Commander> commandManager, final CommandManager<Commander> commandManager,
final CarbonMessages carbonMessages, final CarbonMessages carbonMessages,
final PlayerSuggestions playerSuggestions final ArgumentFactory argumentFactory
) { ) {
this.carbonChat = carbonChat; this.carbonChat = carbonChat;
this.commandManager = commandManager; this.commandManager = commandManager;
this.carbonMessages = carbonMessages; this.carbonMessages = carbonMessages;
this.playerSuggestions = playerSuggestions; this.argumentFactory = argumentFactory;
} }
@Override @Override
@@ -72,7 +70,7 @@ public class MuteCommand extends CarbonCommand {
@Override @Override
public void init() { public void init() {
final var command = this.commandManager.commandBuilder(this.commandSettings().name(), this.commandSettings().aliases()) 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())) RichDescription.of(this.carbonMessages.commandMuteArgumentPlayer()))
.flag(this.commandManager.flagBuilder("uuid") .flag(this.commandManager.flagBuilder("uuid")
.withAliases("u") .withAliases("u")
@@ -89,8 +87,7 @@ public class MuteCommand extends CarbonCommand {
if (handler.contains("player")) { if (handler.contains("player")) {
target = handler.get("player"); target = handler.get("player");
} else if (handler.flags().contains("uuid")) { } else if (handler.flags().contains("uuid")) {
final var result = this.carbonChat.server().userManager().carbonPlayer(handler.get("uuid")).join(); target = this.carbonChat.userManager().user(handler.get("uuid")).join();
target = Objects.requireNonNull(result.player(), "No player found for UUID.");
} else { } else {
this.carbonMessages.muteNoTarget(sender); this.carbonMessages.muteNoTarget(sender);
// TODO: send command syntax // 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.MinecraftExtrasMetaKeys;
import cloud.commandframework.minecraft.extras.RichDescription; import cloud.commandframework.minecraft.extras.RichDescription;
import com.google.inject.Inject; import com.google.inject.Inject;
import java.util.Objects;
import net.draycia.carbon.api.CarbonChat; import net.draycia.carbon.api.CarbonChat;
import net.draycia.carbon.api.users.CarbonPlayer; 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.CarbonCommand;
import net.draycia.carbon.common.command.CommandSettings; import net.draycia.carbon.common.command.CommandSettings;
import net.draycia.carbon.common.command.Commander; import net.draycia.carbon.common.command.Commander;
import net.draycia.carbon.common.command.PlayerCommander; 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.messages.CarbonMessages;
import net.kyori.adventure.key.Key; import net.kyori.adventure.key.Key;
import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.NonNull;
@@ -44,19 +42,19 @@ public class MuteInfoCommand extends CarbonCommand {
final CarbonChat carbonChat; final CarbonChat carbonChat;
final CommandManager<Commander> commandManager; final CommandManager<Commander> commandManager;
final CarbonMessages carbonMessages; final CarbonMessages carbonMessages;
final PlayerSuggestions playerSuggestions; private final ArgumentFactory argumentFactory;
@Inject @Inject
public MuteInfoCommand( public MuteInfoCommand(
final CarbonChat carbonChat, final CarbonChat carbonChat,
final CommandManager<Commander> commandManager, final CommandManager<Commander> commandManager,
final CarbonMessages carbonMessages, final CarbonMessages carbonMessages,
final PlayerSuggestions playerSuggestions final ArgumentFactory argumentFactory
) { ) {
this.carbonChat = carbonChat; this.carbonChat = carbonChat;
this.commandManager = commandManager; this.commandManager = commandManager;
this.carbonMessages = carbonMessages; this.carbonMessages = carbonMessages;
this.playerSuggestions = playerSuggestions; this.argumentFactory = argumentFactory;
} }
@Override @Override
@@ -72,7 +70,7 @@ public class MuteInfoCommand extends CarbonCommand {
@Override @Override
public void init() { public void init() {
final var command = this.commandManager.commandBuilder(this.commandSettings().name(), this.commandSettings().aliases()) 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())) RichDescription.of(this.carbonMessages.commandMuteInfoArgumentPlayer()))
.flag(this.commandManager.flagBuilder("uuid") .flag(this.commandManager.flagBuilder("uuid")
.withAliases("u") .withAliases("u")
@@ -89,8 +87,7 @@ public class MuteInfoCommand extends CarbonCommand {
if (handler.contains("player")) { if (handler.contains("player")) {
target = handler.get("player"); target = handler.get("player");
} else if (handler.flags().contains("uuid")) { } else if (handler.flags().contains("uuid")) {
final var result = this.carbonChat.server().userManager().carbonPlayer(handler.get("uuid")).join(); target = this.carbonChat.userManager().user(handler.get("uuid")).join();
target = Objects.requireNonNull(result.player(), "No player found for UUID.");
} else { } else {
target = sender; target = sender;
} }
@@ -28,12 +28,11 @@ import com.google.inject.Inject;
import java.util.function.Supplier; import java.util.function.Supplier;
import net.draycia.carbon.api.users.CarbonPlayer; import net.draycia.carbon.api.users.CarbonPlayer;
import net.draycia.carbon.common.channels.ConfigChatChannel; 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.CarbonCommand;
import net.draycia.carbon.common.command.CommandSettings; import net.draycia.carbon.common.command.CommandSettings;
import net.draycia.carbon.common.command.Commander; import net.draycia.carbon.common.command.Commander;
import net.draycia.carbon.common.command.PlayerCommander; 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.messages.CarbonMessages;
import net.draycia.carbon.common.util.CloudUtils; import net.draycia.carbon.common.util.CloudUtils;
import net.kyori.adventure.audience.Audience; import net.kyori.adventure.audience.Audience;
@@ -47,17 +46,17 @@ public class NicknameCommand extends CarbonCommand {
final CommandManager<Commander> commandManager; final CommandManager<Commander> commandManager;
final CarbonMessages carbonMessages; final CarbonMessages carbonMessages;
final PlayerSuggestions playerSuggestions; private final ArgumentFactory argumentFactory;
@Inject @Inject
public NicknameCommand( public NicknameCommand(
final CommandManager<Commander> commandManager, final CommandManager<Commander> commandManager,
final CarbonMessages carbonMessages, final CarbonMessages carbonMessages,
final PlayerSuggestions playerSuggestions final ArgumentFactory argumentFactory
) { ) {
this.commandManager = commandManager; this.commandManager = commandManager;
this.carbonMessages = carbonMessages; this.carbonMessages = carbonMessages;
this.playerSuggestions = playerSuggestions; this.argumentFactory = argumentFactory;
} }
@Override @Override
@@ -75,12 +74,7 @@ public class NicknameCommand extends CarbonCommand {
// TODO: Allow UUID input for target player // TODO: Allow UUID input for target player
final var selfRoot = this.commandManager.commandBuilder(this.commandSettings().name(), this.commandSettings().aliases()); final var selfRoot = this.commandManager.commandBuilder(this.commandSettings().name(), this.commandSettings().aliases());
final var othersRoot = selfRoot.literal("player") final var othersRoot = selfRoot.literal("player")
.argument( .argument(this.argumentFactory.carbonPlayer("player"), RichDescription.of(this.carbonMessages.commandNicknameArgumentPlayer()));
CarbonPlayerArgument.builder("player")
.withMessages(this.carbonMessages)
.withSuggestionsProvider(this.playerSuggestions),
RichDescription.of(this.carbonMessages.commandNicknameArgumentPlayer())
);
// Check nickname // Check nickname
this.commandManager.command(selfRoot.permission("carbon.nickname") this.commandManager.command(selfRoot.permission("carbon.nickname")
@@ -27,7 +27,6 @@ import com.google.inject.Inject;
import java.util.UUID; import java.util.UUID;
import net.draycia.carbon.api.CarbonChat; import net.draycia.carbon.api.CarbonChat;
import net.draycia.carbon.api.users.CarbonPlayer; 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.api.util.SourcedAudience;
import net.draycia.carbon.common.command.CarbonCommand; import net.draycia.carbon.common.command.CarbonCommand;
import net.draycia.carbon.common.command.CommandSettings; import net.draycia.carbon.common.command.CommandSettings;
@@ -100,8 +99,7 @@ public class ReplyCommand extends CarbonCommand {
return; return;
} }
final ComponentPlayerResult<? extends CarbonPlayer> result = this.carbonChat.server().userManager().carbonPlayer(replyTarget).join(); final @MonotonicNonNull CarbonPlayer recipient = this.carbonChat.userManager().user(replyTarget).join();
final @MonotonicNonNull CarbonPlayer recipient = result.player();
if (sender.equals(recipient)) { if (sender.equals(recipient)) {
this.carbonMessages.whisperSelfError(sender, CarbonPlayer.renderName(sender)); 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")) { if (!recipient.online() || !sender.awareOf(recipient) && !sender.hasPermission("carbon.whisper.vanished")) {
final var rawNameInput = CloudUtils.rawInputByMatchingName(handler.getRawInput(), recipient); 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)); this.carbonMessages.errorCommandArgumentParsing(sender, CloudUtils.message(exception));
return; return;
@@ -24,15 +24,13 @@ import cloud.commandframework.arguments.standard.UUIDArgument;
import cloud.commandframework.minecraft.extras.MinecraftExtrasMetaKeys; import cloud.commandframework.minecraft.extras.MinecraftExtrasMetaKeys;
import cloud.commandframework.minecraft.extras.RichDescription; import cloud.commandframework.minecraft.extras.RichDescription;
import com.google.inject.Inject; import com.google.inject.Inject;
import java.util.Objects;
import net.draycia.carbon.api.CarbonChat; import net.draycia.carbon.api.CarbonChat;
import net.draycia.carbon.api.users.CarbonPlayer; 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.CarbonCommand;
import net.draycia.carbon.common.command.CommandSettings; import net.draycia.carbon.common.command.CommandSettings;
import net.draycia.carbon.common.command.Commander; import net.draycia.carbon.common.command.Commander;
import net.draycia.carbon.common.command.PlayerCommander; 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.messages.CarbonMessages;
import net.kyori.adventure.key.Key; import net.kyori.adventure.key.Key;
import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.NonNull;
@@ -44,19 +42,19 @@ public class UnignoreCommand extends CarbonCommand {
final CarbonChat carbonChat; final CarbonChat carbonChat;
final CommandManager<Commander> commandManager; final CommandManager<Commander> commandManager;
final CarbonMessages carbonMessages; final CarbonMessages carbonMessages;
final PlayerSuggestions playerSuggestions; private final ArgumentFactory argumentFactory;
@Inject @Inject
public UnignoreCommand( public UnignoreCommand(
final CarbonChat carbonChat, final CarbonChat carbonChat,
final CommandManager<Commander> commandManager, final CommandManager<Commander> commandManager,
final CarbonMessages carbonMessages, final CarbonMessages carbonMessages,
final PlayerSuggestions playerSuggestions final ArgumentFactory argumentFactory
) { ) {
this.carbonChat = carbonChat; this.carbonChat = carbonChat;
this.commandManager = commandManager; this.commandManager = commandManager;
this.carbonMessages = carbonMessages; this.carbonMessages = carbonMessages;
this.playerSuggestions = playerSuggestions; this.argumentFactory = argumentFactory;
} }
@Override @Override
@@ -73,7 +71,7 @@ public class UnignoreCommand extends CarbonCommand {
public void init() { public void init() {
final var command = this.commandManager.commandBuilder(this.commandSettings().name(), this.commandSettings().aliases()) 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. // 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())) RichDescription.of(this.carbonMessages.commandUnignoreArgumentPlayer()))
.flag(this.commandManager.flagBuilder("uuid") .flag(this.commandManager.flagBuilder("uuid")
.withAliases("u") .withAliases("u")
@@ -90,8 +88,7 @@ public class UnignoreCommand extends CarbonCommand {
if (handler.contains("player")) { if (handler.contains("player")) {
target = handler.get("player"); target = handler.get("player");
} else if (handler.flags().contains("uuid")) { } else if (handler.flags().contains("uuid")) {
final var result = this.carbonChat.server().userManager().carbonPlayer(handler.get("uuid")).join(); target = this.carbonChat.userManager().user(handler.get("uuid")).join();
target = Objects.requireNonNull(result.player(), "No player found for UUID.");
} else { } else {
this.carbonMessages.ignoreTargetInvalid(sender); this.carbonMessages.ignoreTargetInvalid(sender);
return; return;
@@ -24,15 +24,13 @@ import cloud.commandframework.arguments.standard.UUIDArgument;
import cloud.commandframework.minecraft.extras.MinecraftExtrasMetaKeys; import cloud.commandframework.minecraft.extras.MinecraftExtrasMetaKeys;
import cloud.commandframework.minecraft.extras.RichDescription; import cloud.commandframework.minecraft.extras.RichDescription;
import com.google.inject.Inject; import com.google.inject.Inject;
import java.util.Objects;
import net.draycia.carbon.api.CarbonChat; import net.draycia.carbon.api.CarbonChat;
import net.draycia.carbon.api.users.CarbonPlayer; 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.CarbonCommand;
import net.draycia.carbon.common.command.CommandSettings; import net.draycia.carbon.common.command.CommandSettings;
import net.draycia.carbon.common.command.Commander; import net.draycia.carbon.common.command.Commander;
import net.draycia.carbon.common.command.PlayerCommander; 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.messages.CarbonMessages;
import net.kyori.adventure.key.Key; import net.kyori.adventure.key.Key;
import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.NonNull;
@@ -44,19 +42,19 @@ public class UnmuteCommand extends CarbonCommand {
final CarbonChat carbonChat; final CarbonChat carbonChat;
final CommandManager<Commander> commandManager; final CommandManager<Commander> commandManager;
final CarbonMessages carbonMessages; final CarbonMessages carbonMessages;
final PlayerSuggestions playerSuggestions; private final ArgumentFactory argumentFactory;
@Inject @Inject
public UnmuteCommand( public UnmuteCommand(
final CarbonChat carbonChat, final CarbonChat carbonChat,
final CommandManager<Commander> commandManager, final CommandManager<Commander> commandManager,
final CarbonMessages carbonMessages, final CarbonMessages carbonMessages,
final PlayerSuggestions playerSuggestions final ArgumentFactory argumentFactory
) { ) {
this.carbonChat = carbonChat; this.carbonChat = carbonChat;
this.commandManager = commandManager; this.commandManager = commandManager;
this.carbonMessages = carbonMessages; this.carbonMessages = carbonMessages;
this.playerSuggestions = playerSuggestions; this.argumentFactory = argumentFactory;
} }
@Override @Override
@@ -72,7 +70,7 @@ public class UnmuteCommand extends CarbonCommand {
@Override @Override
public void init() { public void init() {
final var command = this.commandManager.commandBuilder(this.commandSettings().name(), this.commandSettings().aliases()) 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())) RichDescription.of(this.carbonMessages.commandUnmuteArgumentPlayer()))
.flag(this.commandManager.flagBuilder("uuid") .flag(this.commandManager.flagBuilder("uuid")
.withAliases("u") .withAliases("u")
@@ -89,8 +87,7 @@ public class UnmuteCommand extends CarbonCommand {
if (handler.contains("player")) { if (handler.contains("player")) {
target = handler.get("player"); target = handler.get("player");
} else if (handler.flags().contains("uuid")) { } else if (handler.flags().contains("uuid")) {
final var result = this.carbonChat.server().userManager().carbonPlayer(handler.get("uuid")).join(); target = this.carbonChat.userManager().user(handler.get("uuid")).join();
target = Objects.requireNonNull(result.player(), "No player found for UUID.");
} else { } else {
this.carbonMessages.unmuteNoTarget(sender); this.carbonMessages.unmuteNoTarget(sender);
// TODO: send command syntax // TODO: send command syntax
@@ -25,16 +25,16 @@ import cloud.commandframework.minecraft.extras.MinecraftExtrasMetaKeys;
import cloud.commandframework.minecraft.extras.RichDescription; import cloud.commandframework.minecraft.extras.RichDescription;
import com.google.inject.Inject; import com.google.inject.Inject;
import java.util.Objects; import java.util.Objects;
import net.draycia.carbon.api.CarbonChat;
import net.draycia.carbon.api.users.CarbonPlayer; 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.CarbonCommand;
import net.draycia.carbon.common.command.CommandSettings; import net.draycia.carbon.common.command.CommandSettings;
import net.draycia.carbon.common.command.Commander; import net.draycia.carbon.common.command.Commander;
import net.draycia.carbon.common.command.PlayerCommander; 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.messages.CarbonMessages;
import net.draycia.carbon.common.users.CarbonPlayerCommon; import net.draycia.carbon.common.users.CarbonPlayerCommon;
import net.draycia.carbon.common.users.ProfileResolver;
import net.draycia.carbon.common.users.WrappedCarbonPlayer; import net.draycia.carbon.common.users.WrappedCarbonPlayer;
import net.kyori.adventure.key.Key; import net.kyori.adventure.key.Key;
import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.NonNull;
@@ -43,22 +43,25 @@ import org.checkerframework.framework.qual.DefaultQualifier;
@DefaultQualifier(NonNull.class) @DefaultQualifier(NonNull.class)
public class UpdateUsernameCommand extends CarbonCommand { public class UpdateUsernameCommand extends CarbonCommand {
final CarbonChat carbonChat; private final UserManager<?> userManager;
final CommandManager<Commander> commandManager; final CommandManager<Commander> commandManager;
final CarbonMessages messageService; final CarbonMessages messageService;
final PlayerSuggestions playerSuggestions; private final ArgumentFactory argumentFactory;
private final ProfileResolver profileResolver;
@Inject @Inject
public UpdateUsernameCommand( public UpdateUsernameCommand(
final CarbonChat carbonChat, final UserManager<?> userManager,
final CommandManager<Commander> commandManager, final CommandManager<Commander> commandManager,
final CarbonMessages messageService, final CarbonMessages messageService,
final PlayerSuggestions playerSuggestions final ArgumentFactory argumentFactory,
final ProfileResolver profileResolver
) { ) {
this.carbonChat = carbonChat; this.userManager = userManager;
this.commandManager = commandManager; this.commandManager = commandManager;
this.messageService = messageService; this.messageService = messageService;
this.playerSuggestions = playerSuggestions; this.argumentFactory = argumentFactory;
this.profileResolver = profileResolver;
} }
@Override @Override
@@ -74,7 +77,7 @@ public class UpdateUsernameCommand extends CarbonCommand {
@Override @Override
public void init() { public void init() {
final var command = this.commandManager.commandBuilder(this.commandSettings().name(), this.commandSettings().aliases()) 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())) RichDescription.of(this.messageService.commandUpdateUsernameArgumentPlayer()))
.flag(this.commandManager.flagBuilder("uuid") .flag(this.commandManager.flagBuilder("uuid")
.withAliases("u") .withAliases("u")
@@ -91,8 +94,7 @@ public class UpdateUsernameCommand extends CarbonCommand {
if (handler.contains("player")) { if (handler.contains("player")) {
target = handler.get("player"); target = handler.get("player");
} else if (handler.flags().contains("uuid")) { } else if (handler.flags().contains("uuid")) {
final var result = this.carbonChat.server().userManager().carbonPlayer(handler.get("uuid")).join(); target = this.userManager.user(handler.get("uuid")).join();
target = Objects.requireNonNull(result.player(), "No player found for UUID.");
} else { } else {
target = sender; target = sender;
} }
@@ -106,7 +108,7 @@ public class UpdateUsernameCommand extends CarbonCommand {
this.messageService.usernameFetching(sender); this.messageService.usernameFetching(sender);
final CarbonPlayer finalTarget = target; 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."); Objects.requireNonNull(name, "Unable to fetch username for player.");
((CarbonPlayerCommon) finalTarget).username(name); ((CarbonPlayerCommon) finalTarget).username(name);
@@ -27,12 +27,12 @@ import com.google.inject.Inject;
import net.draycia.carbon.api.CarbonChat; import net.draycia.carbon.api.CarbonChat;
import net.draycia.carbon.api.users.CarbonPlayer; import net.draycia.carbon.api.users.CarbonPlayer;
import net.draycia.carbon.api.util.SourcedAudience; 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.CarbonCommand;
import net.draycia.carbon.common.command.CommandSettings; import net.draycia.carbon.common.command.CommandSettings;
import net.draycia.carbon.common.command.Commander; import net.draycia.carbon.common.command.Commander;
import net.draycia.carbon.common.command.PlayerCommander; import net.draycia.carbon.common.command.PlayerCommander;
import net.draycia.carbon.common.command.argument.CarbonPlayerArgument; 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.config.ConfigFactory;
import net.draycia.carbon.common.messages.CarbonMessages; import net.draycia.carbon.common.messages.CarbonMessages;
import net.draycia.carbon.common.util.CloudUtils; import net.draycia.carbon.common.util.CloudUtils;
@@ -49,7 +49,7 @@ public class WhisperCommand extends CarbonCommand {
final CarbonChat carbonChat; final CarbonChat carbonChat;
final CommandManager<Commander> commandManager; final CommandManager<Commander> commandManager;
final CarbonMessages carbonMessages; final CarbonMessages carbonMessages;
final PlayerSuggestions playerSuggestions; private final ArgumentFactory argumentFactory;
final ConfigFactory configFactory; final ConfigFactory configFactory;
@Inject @Inject
@@ -57,13 +57,13 @@ public class WhisperCommand extends CarbonCommand {
final CarbonChat carbonChat, final CarbonChat carbonChat,
final CommandManager<Commander> commandManager, final CommandManager<Commander> commandManager,
final CarbonMessages carbonMessages, final CarbonMessages carbonMessages,
final PlayerSuggestions playerSuggestions, final ArgumentFactory argumentFactory,
final ConfigFactory configFactory final ConfigFactory configFactory
) { ) {
this.carbonChat = carbonChat; this.carbonChat = carbonChat;
this.commandManager = commandManager; this.commandManager = commandManager;
this.carbonMessages = carbonMessages; this.carbonMessages = carbonMessages;
this.playerSuggestions = playerSuggestions; this.argumentFactory = argumentFactory;
this.configFactory = configFactory; this.configFactory = configFactory;
} }
@@ -80,7 +80,7 @@ public class WhisperCommand extends CarbonCommand {
@Override @Override
public void init() { public void init() {
final var command = this.commandManager.commandBuilder(this.commandSettings().name(), this.commandSettings().aliases()) 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())) RichDescription.of(this.carbonMessages.commandWhisperArgumentPlayer()))
.argument(StringArgument.greedy("message"), .argument(StringArgument.greedy("message"),
RichDescription.of(this.carbonMessages.commandWhisperArgumentMessage())) 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")) { if (!recipient.online() || !sender.awareOf(recipient) && !sender.hasPermission("carbon.whisper.vanished")) {
final var rawNameInput = CloudUtils.rawInputByMatchingName(handler.getRawInput(), recipient); 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)); this.carbonMessages.errorCommandArgumentParsing(sender, CloudUtils.message(exception));
return; return;
@@ -24,8 +24,8 @@ import java.io.IOException;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.util.Locale; import java.util.Locale;
import net.draycia.carbon.api.CarbonChat; import net.draycia.carbon.api.events.CarbonEventHandler;
import net.draycia.carbon.common.ForCarbon; import net.draycia.carbon.common.DataDirectory;
import net.draycia.carbon.common.events.CarbonReloadEvent; import net.draycia.carbon.common.events.CarbonReloadEvent;
import net.draycia.carbon.common.serialisation.gson.LocaleSerializerConfigurate; import net.draycia.carbon.common.serialisation.gson.LocaleSerializerConfigurate;
import net.kyori.adventure.serializer.configurate4.ConfigurateComponentSerializer; import net.kyori.adventure.serializer.configurate4.ConfigurateComponentSerializer;
@@ -47,16 +47,14 @@ public class ConfigFactory {
@Inject @Inject
public ConfigFactory( public ConfigFactory(
final CarbonChat carbonChat, final CarbonEventHandler events,
@ForCarbon final Path dataDirectory, @DataDirectory final Path dataDirectory,
final LocaleSerializerConfigurate locale final LocaleSerializerConfigurate locale
) { ) {
this.dataDirectory = dataDirectory; this.dataDirectory = dataDirectory;
this.locale = locale; this.locale = locale;
carbonChat.eventHandler().subscribe(CarbonReloadEvent.class, event -> { events.subscribe(CarbonReloadEvent.class, event -> this.reloadPrimaryConfig());
this.reloadPrimaryConfig();
});
} }
public @Nullable PrimaryConfig reloadPrimaryConfig() { public @Nullable PrimaryConfig reloadPrimaryConfig() {
@@ -20,8 +20,8 @@
package net.draycia.carbon.common.listeners; package net.draycia.carbon.common.listeners;
import com.google.inject.Inject; import com.google.inject.Inject;
import net.draycia.carbon.api.CarbonChat;
import net.draycia.carbon.api.events.CarbonChatEvent; 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.users.CarbonPlayer;
import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.framework.qual.DefaultQualifier; import org.checkerframework.framework.qual.DefaultQualifier;
@@ -30,10 +30,8 @@ import org.checkerframework.framework.qual.DefaultQualifier;
public class DeafenHandler { public class DeafenHandler {
@Inject @Inject
public DeafenHandler( public DeafenHandler(final CarbonEventHandler events) {
final CarbonChat carbonChat events.subscribe(CarbonChatEvent.class, 0, false, event -> {
) {
carbonChat.eventHandler().subscribe(CarbonChatEvent.class, 0, false, event -> {
if (!event.sender().deafened()) { if (!event.sender().deafened()) {
return; return;
} }
@@ -20,8 +20,8 @@
package net.draycia.carbon.common.listeners; package net.draycia.carbon.common.listeners;
import com.google.inject.Inject; import com.google.inject.Inject;
import net.draycia.carbon.api.CarbonChat;
import net.draycia.carbon.api.events.CarbonChatEvent; 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.users.CarbonPlayer;
import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.framework.qual.DefaultQualifier; import org.checkerframework.framework.qual.DefaultQualifier;
@@ -30,10 +30,8 @@ import org.checkerframework.framework.qual.DefaultQualifier;
public class IgnoreHandler { public class IgnoreHandler {
@Inject @Inject
public IgnoreHandler( public IgnoreHandler(final CarbonEventHandler events) {
final CarbonChat carbonChat events.subscribe(CarbonChatEvent.class, 0, false, event -> {
) {
carbonChat.eventHandler().subscribe(CarbonChatEvent.class, 0, false, event -> {
event.recipients().removeIf(entry -> entry instanceof CarbonPlayer carbonPlayer && event.recipients().removeIf(entry -> entry instanceof CarbonPlayer carbonPlayer &&
carbonPlayer.ignoring(event.sender())); carbonPlayer.ignoring(event.sender()));
}); });
@@ -20,18 +20,16 @@
package net.draycia.carbon.common.listeners; package net.draycia.carbon.common.listeners;
import com.google.inject.Inject; import com.google.inject.Inject;
import net.draycia.carbon.api.CarbonChat;
import net.draycia.carbon.api.events.CarbonChatEvent; import net.draycia.carbon.api.events.CarbonChatEvent;
import net.draycia.carbon.api.events.CarbonEventHandler;
import net.draycia.carbon.api.util.InventorySlot; import net.draycia.carbon.api.util.InventorySlot;
import net.kyori.adventure.text.TextReplacementConfig; import net.kyori.adventure.text.TextReplacementConfig;
public class ItemLinkHandler { public class ItemLinkHandler {
@Inject @Inject
public ItemLinkHandler( public ItemLinkHandler(final CarbonEventHandler events) {
final CarbonChat carbonChat events.subscribe(CarbonChatEvent.class, 1, false, event -> {
) {
carbonChat.eventHandler().subscribe(CarbonChatEvent.class, 1, false, event -> {
if (!event.sender().hasPermission("carbon.itemlink")) { if (!event.sender().hasPermission("carbon.itemlink")) {
return; 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; package net.draycia.carbon.common.listeners;
import com.google.inject.Inject; import com.google.inject.Inject;
import net.draycia.carbon.api.CarbonChat;
import net.draycia.carbon.api.events.CarbonChatEvent; 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.users.CarbonPlayer;
import net.draycia.carbon.api.util.KeyedRenderer; import net.draycia.carbon.api.util.KeyedRenderer;
import net.draycia.carbon.common.messages.CarbonMessages; import net.draycia.carbon.common.messages.CarbonMessages;
@@ -47,13 +47,10 @@ public class MuteHandler {
}); });
@Inject @Inject
public MuteHandler( public MuteHandler(final CarbonEventHandler events, final CarbonMessages carbonMessages) {
final CarbonChat carbonChat,
final CarbonMessages carbonMessages
) {
this.carbonMessages = carbonMessages; this.carbonMessages = carbonMessages;
carbonChat.eventHandler().subscribe(CarbonChatEvent.class, 100, false, event -> { events.subscribe(CarbonChatEvent.class, 100, false, event -> {
if (!event.sender().muted()) { if (!event.sender().muted()) {
return; return;
} }
@@ -21,8 +21,8 @@ package net.draycia.carbon.common.listeners;
import com.google.inject.Inject; import com.google.inject.Inject;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import net.draycia.carbon.api.CarbonChat;
import net.draycia.carbon.api.events.CarbonChatEvent; 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.users.CarbonPlayer;
import net.draycia.carbon.api.util.KeyedRenderer; import net.draycia.carbon.api.util.KeyedRenderer;
import net.draycia.carbon.common.config.ConfigFactory; import net.draycia.carbon.common.config.ConfigFactory;
@@ -42,7 +42,7 @@ public class PingHandler {
private final KeyedRenderer renderer; private final KeyedRenderer renderer;
@Inject @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) -> { this.renderer = keyedRenderer(this.muteKey, (sender, recipient, message, originalMessage) -> {
if (!(recipient instanceof CarbonPlayer recipientPlayer)) { if (!(recipient instanceof CarbonPlayer recipientPlayer)) {
return message; return message;
@@ -62,7 +62,7 @@ public class PingHandler {
.build()); .build());
}); });
carbonChat.eventHandler().subscribe(CarbonChatEvent.class, 1, false, event -> { events.subscribe(CarbonChatEvent.class, 1, false, event -> {
event.renderers().add(0, this.renderer); event.renderers().add(0, this.renderer);
}); });
} }
@@ -20,8 +20,8 @@
package net.draycia.carbon.common.listeners; package net.draycia.carbon.common.listeners;
import com.google.inject.Inject; import com.google.inject.Inject;
import net.draycia.carbon.api.CarbonChat;
import net.draycia.carbon.api.events.CarbonChatEvent; 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.users.CarbonPlayer;
import net.draycia.carbon.common.messages.CarbonMessages; import net.draycia.carbon.common.messages.CarbonMessages;
import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.NonNull;
@@ -32,10 +32,10 @@ public class RadiusListener {
@Inject @Inject
public RadiusListener( public RadiusListener(
final CarbonChat carbonChat, final CarbonEventHandler events,
final CarbonMessages carbonMessages final CarbonMessages carbonMessages
) { ) {
carbonChat.eventHandler().subscribe(CarbonChatEvent.class, 0, false, event -> { events.subscribe(CarbonChatEvent.class, 0, false, event -> {
if (event.chatChannel() == null || event.previewing()) { if (event.chatChannel() == null || event.previewing()) {
return; return;
} }
@@ -47,9 +47,9 @@ import java.util.Set;
import java.util.function.Consumer; import java.util.function.Consumer;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import java.util.stream.Stream; 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.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.command.PlayerCommander;
import net.draycia.carbon.common.config.ConfigFactory; import net.draycia.carbon.common.config.ConfigFactory;
import net.draycia.carbon.common.events.CarbonReloadEvent; import net.draycia.carbon.common.events.CarbonReloadEvent;
@@ -73,8 +73,8 @@ public final class CarbonMessageSource implements IMessageSource<Audience, Strin
@Inject @Inject
private CarbonMessageSource( private CarbonMessageSource(
final CarbonChat carbonChat, final CarbonEventHandler events,
final @ForCarbon Path dataDirectory, final @DataDirectory Path dataDirectory,
final ConfigFactory configFactory, final ConfigFactory configFactory,
final Logger logger final Logger logger
) throws IOException { ) throws IOException {
@@ -86,7 +86,7 @@ public final class CarbonMessageSource implements IMessageSource<Audience, Strin
this.reloadTranslations(); this.reloadTranslations();
carbonChat.eventHandler().subscribe(CarbonReloadEvent.class, event -> { events.subscribe(CarbonReloadEvent.class, event -> {
this.reloadTranslations(); this.reloadTranslations();
}); });
} }
@@ -22,7 +22,6 @@ package net.draycia.carbon.common.messaging;
import net.draycia.carbon.api.CarbonChatProvider; import net.draycia.carbon.api.CarbonChatProvider;
import net.draycia.carbon.common.channels.CarbonChannelRegistry; import net.draycia.carbon.common.channels.CarbonChannelRegistry;
import net.draycia.carbon.common.messaging.packets.ChatMessagePacket; 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.Component;
import net.kyori.adventure.text.minimessage.MiniMessage; import net.kyori.adventure.text.minimessage.MiniMessage;
import net.kyori.adventure.text.minimessage.tag.Tag; import net.kyori.adventure.text.minimessage.tag.Tag;
@@ -49,9 +48,12 @@ public final class CarbonChatPacketHandler extends AbstractMessagingHandler {
@Override @Override
protected boolean handlePacket(final @NotNull Packet packet) { protected boolean handlePacket(final @NotNull Packet packet) {
if (!(packet instanceof ChatMessagePacket messagePacket)) { if (!(packet instanceof ChatMessagePacket messagePacket)) {
this.logger.info("Messaging packet received - Not a ChatMessagePacket.");
return false; return false;
} }
this.logger.info("Messaging packet received");
final TagResolver.Builder tagResolver = TagResolver.builder(); final TagResolver.Builder tagResolver = TagResolver.builder();
for (final var entry : messagePacket.placeholders().entrySet()) { 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()) { for (final var recipient : CarbonChatProvider.carbonChat().server().players()) {
if (recipient.hasPermission(messagePacket.channelPermission() + ".see")) { if (recipient.hasPermission(messagePacket.channelPermission() + ".see")) {
if (recipient.hasPermission("carbon.crossserver")) { 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.io.IOException;
import java.util.UUID; import java.util.UUID;
import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException; import java.util.concurrent.TimeoutException;
import net.draycia.carbon.api.CarbonChat; 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.ConfigFactory;
import net.draycia.carbon.common.config.MessagingSettings; import net.draycia.carbon.common.config.MessagingSettings;
import net.draycia.carbon.common.messaging.packets.ChatMessagePacket; 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.MessagingService;
import ninja.egg82.messenger.NATSMessagingService; import ninja.egg82.messenger.NATSMessagingService;
import ninja.egg82.messenger.PacketManager; import ninja.egg82.messenger.PacketManager;
@@ -58,8 +59,7 @@ public class MessagingManager {
private static final byte protocolVersion = 0; private static final byte protocolVersion = 0;
private final ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor(10); private final ScheduledExecutorService executorService;
private final PacketService packetService; private final PacketService packetService;
private MessagingService messagingService; private MessagingService messagingService;
private final CarbonChat carbonChat; private final CarbonChat carbonChat;
@@ -80,6 +80,8 @@ public class MessagingManager {
PacketManager.register(ChatMessagePacket.class, ChatMessagePacket::new); PacketManager.register(ChatMessagePacket.class, ChatMessagePacket::new);
this.packetService = new PacketService(4, false, protocolVersion); this.packetService = new PacketService(4, false, protocolVersion);
this.executorService = new ExceptionLoggingScheduledThreadPoolExecutor(10,
ConcurrentUtil.carbonThreadFactory(carbonChat.logger(), "MessagingManager"), carbonChat.logger());
this.carbonChat = carbonChat; this.carbonChat = carbonChat;
final MessagingHandlerImpl handlerImpl = new MessagingHandlerImpl(this.packetService); final MessagingHandlerImpl handlerImpl = new MessagingHandlerImpl(this.packetService);
@@ -143,12 +145,15 @@ public class MessagingManager {
final String channelName = "carbon-data"; final String channelName = "carbon-data";
if (!messagingSettings.enabled()) { if (!messagingSettings.enabled()) {
this.carbonChat.logger().info("Messaging services disabled in config. Cross-server will not work without this!");
this.messagingService = EMPTY_MESSAGING_SERVICE; this.messagingService = EMPTY_MESSAGING_SERVICE;
return; return;
} }
switch (messagingSettings.brokerType()) { switch (messagingSettings.brokerType()) {
case RABBITMQ -> { 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) final RabbitMQMessagingService.Builder builder = RabbitMQMessagingService.builder(packetService, name, channelName, this.carbonChat.serverId(), handlerImpl, 0L, false, packetDir)
.url(messagingSettings.url(), messagingSettings.port(), messagingSettings.vhost()) .url(messagingSettings.url(), messagingSettings.port(), messagingSettings.vhost())
.timeout(5000); .timeout(5000);
@@ -160,6 +165,8 @@ public class MessagingManager {
this.messagingService = builder.build(); this.messagingService = builder.build();
} }
case NATS -> { 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) final NATSMessagingService.Builder builder = NATSMessagingService.builder(packetService, name, channelName, this.carbonChat.serverId(), handlerImpl, 0L, false, packetDir)
.url(messagingSettings.url(), messagingSettings.port()) .url(messagingSettings.url(), messagingSettings.port())
.life(5000); .life(5000);
@@ -171,6 +178,8 @@ public class MessagingManager {
this.messagingService = builder.build(); this.messagingService = builder.build();
} }
case REDIS -> { 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) final RedisMessagingService.Builder builder = RedisMessagingService.builder(packetService, name, channelName, this.carbonChat.serverId(), handlerImpl, 0L, false, packetDir)
.url(messagingSettings.url(), messagingSettings.port()); .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; 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.List;
import java.util.Locale; import java.util.Locale;
import java.util.Objects; import java.util.Objects;
import java.util.Set;
import java.util.UUID; import java.util.UUID;
import java.util.stream.Stream;
import net.draycia.carbon.api.CarbonChat; import net.draycia.carbon.api.CarbonChat;
import net.draycia.carbon.api.CarbonChatProvider;
import net.draycia.carbon.api.channels.ChatChannel; import net.draycia.carbon.api.channels.ChatChannel;
import net.draycia.carbon.api.users.CarbonPlayer; import net.draycia.carbon.api.users.CarbonPlayer;
import net.draycia.carbon.api.util.InventorySlot; import net.draycia.carbon.api.util.InventorySlot;
@@ -43,31 +47,34 @@ import org.jetbrains.annotations.NotNull;
@DefaultQualifier(NonNull.class) @DefaultQualifier(NonNull.class)
public class CarbonPlayerCommon implements CarbonPlayer, ForwardingAudience.Single { 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; private transient @MonotonicNonNull @Inject CarbonChat carbonChat;
protected boolean deafened = false; 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 // All players have these
protected transient @MonotonicNonNull String username = null; protected transient @MonotonicNonNull String username = null;
protected @MonotonicNonNull UUID uuid; protected @MonotonicNonNull UUID uuid;
// Display information // Display information
protected @Nullable Component displayName = null; protected final PersistentUserProperty<Component> displayName;
// Whispers // Whispers
protected transient @Nullable UUID lastWhisperTarget = null; protected transient @Nullable UUID lastWhisperTarget = null;
protected transient @Nullable UUID whisperReplyTarget = null; protected transient @Nullable UUID whisperReplyTarget = null;
// Administrative // Administrative
protected boolean spying = false; protected final PersistentUserProperty<Boolean> spying;
// Punishments // 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( public CarbonPlayerCommon(
final boolean muted, final boolean muted,
@@ -80,27 +87,54 @@ public class CarbonPlayerCommon implements CarbonPlayer, ForwardingAudience.Sing
final @Nullable UUID whisperReplyTarget, final @Nullable UUID whisperReplyTarget,
final boolean spying final boolean spying
) { ) {
this.muted = muted; this.muted = PersistentUserProperty.of(muted);
this.deafened = deafened; this.deafened = PersistentUserProperty.of(deafened);
this.selectedChannel = selectedChannel; this.selectedChannel = PersistentUserProperty.of(selectedChannel);
this.username = username; this.username = username;
this.uuid = uuid; this.uuid = uuid;
this.displayName = displayName; this.displayName = PersistentUserProperty.of(displayName);
this.lastWhisperTarget = lastWhisperTarget; this.lastWhisperTarget = lastWhisperTarget;
this.whisperReplyTarget = whisperReplyTarget; 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( public CarbonPlayerCommon(
final String username, final String username,
final UUID uuid 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.username = username;
this.uuid = uuid; this.uuid = uuid;
} }
public CarbonPlayerCommon() { 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 @Override
@@ -119,20 +153,12 @@ public class CarbonPlayerCommon implements CarbonPlayer, ForwardingAudience.Sing
@Override @Override
public @Nullable Component displayName() { public @Nullable Component displayName() {
if (this.displayName != null) { return this.displayName.orNull();
return this.displayName;
}
return null;
} }
@Override @Override
public void displayName(final @Nullable Component displayName) { public void displayName(final @Nullable Component displayName) {
this.displayName = displayName; this.displayName.set(displayName);
if (this.carbonChat.server().userManager() instanceof SaveOnChange userManager) {
userManager.saveDisplayName(this.uuid(), displayName);
}
} }
@Override @Override
@@ -152,25 +178,21 @@ public class CarbonPlayerCommon implements CarbonPlayer, ForwardingAudience.Sing
@Override @Override
public boolean muted() { public boolean muted() {
return this.muted; return this.muted.get();
} }
@Override @Override
public void muted(final boolean muted) { public void muted(final boolean muted) {
this.muted = muted; this.muted.set(muted);
if (this.carbonChat.server().userManager() instanceof SaveOnChange userManager) {
userManager.saveMuted(this.uuid(), muted);
}
} }
public List<UUID> ignoredPlayers() { public Set<UUID> ignoredPlayers() {
return this.ignoredPlayers; return this.ignoredPlayers.get();
} }
@Override @Override
public boolean ignoring(final UUID player) { public boolean ignoring(final UUID player) {
return this.ignoredPlayers.contains(player); return this.ignoredPlayers.get().contains(player);
} }
@Override @Override
@@ -178,23 +200,23 @@ public class CarbonPlayerCommon implements CarbonPlayer, ForwardingAudience.Sing
return this.ignoring(player.uuid()); 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 @Override
public void ignoring(final UUID player, final boolean nowIgnoring) { public void ignoring(final UUID player, final boolean nowIgnoring) {
if (nowIgnoring) { this.ignoring(player, nowIgnoring, false);
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);
}
}
} }
@Override @Override
@@ -204,30 +226,22 @@ public class CarbonPlayerCommon implements CarbonPlayer, ForwardingAudience.Sing
@Override @Override
public boolean deafened() { public boolean deafened() {
return this.deafened; return this.deafened.get();
} }
@Override @Override
public void deafened(final boolean deafened) { public void deafened(final boolean deafened) {
this.deafened = deafened; this.deafened.set(deafened);
if (this.carbonChat.server().userManager() instanceof SaveOnChange userManager) {
userManager.saveDeafened(this.uuid(), deafened);
}
} }
@Override @Override
public boolean spying() { public boolean spying() {
return this.spying; return this.spying.get();
} }
@Override @Override
public void spying(final boolean spying) { public void spying(final boolean spying) {
this.spying = spying; this.spying.set(spying);
if (this.carbonChat.server().userManager() instanceof SaveOnChange userManager) {
userManager.saveSpying(this.uuid(), spying);
}
} }
@Override @Override
@@ -253,10 +267,6 @@ public class CarbonPlayerCommon implements CarbonPlayer, ForwardingAudience.Sing
@Override @Override
public void whisperReplyTarget(final @Nullable UUID whisperReplyTarget) { public void whisperReplyTarget(final @Nullable UUID whisperReplyTarget) {
this.whisperReplyTarget = whisperReplyTarget; this.whisperReplyTarget = whisperReplyTarget;
if (this.carbonChat.server().userManager() instanceof SaveOnChange userManager) {
userManager.saveWhisperReplyTarget(this.uuid(), whisperReplyTarget);
}
} }
@Override @Override
@@ -267,10 +277,6 @@ public class CarbonPlayerCommon implements CarbonPlayer, ForwardingAudience.Sing
@Override @Override
public void lastWhisperTarget(final @Nullable UUID lastWhisperTarget) { public void lastWhisperTarget(final @Nullable UUID lastWhisperTarget) {
this.lastWhisperTarget = lastWhisperTarget; this.lastWhisperTarget = lastWhisperTarget;
if (this.carbonChat.server().userManager() instanceof SaveOnChange userManager) {
userManager.saveLastWhisperTarget(this.uuid(), lastWhisperTarget);
}
} }
@Override @Override
@@ -285,23 +291,37 @@ public class CarbonPlayerCommon implements CarbonPlayer, ForwardingAudience.Sing
@Override @Override
public List<Key> leftChannels() { 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 @Override
public void joinChannel(final ChatChannel channel) { public void joinChannel(final ChatChannel channel) {
this.leftChannels.remove(channel.key()); this.joinChannel(channel.key(), false);
if (this.carbonChat.server().userManager() instanceof SaveOnChange userManager) { }
userManager.removeLeftChannel(this.uuid(), channel.key());
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 @Override
public void leaveChannel(final ChatChannel channel) { public void leaveChannel(final ChatChannel channel) {
this.leftChannels.add(channel.key()); this.leaveChannel(channel, false);
if (this.carbonChat.server().userManager() instanceof SaveOnChange userManager) {
userManager.addLeftChannel(this.uuid(), channel.key());
}
} }
@Override @Override
@@ -316,27 +336,23 @@ public class CarbonPlayerCommon implements CarbonPlayer, ForwardingAudience.Sing
@Override @Override
public @Nullable ChatChannel selectedChannel() { public @Nullable ChatChannel selectedChannel() {
if (this.selectedChannel == null) { if (!this.selectedChannel.hasValue()) {
return this.carbonChat.channelRegistry().defaultValue(); return this.carbonChat.channelRegistry().defaultValue();
} }
return this.carbonChat.channelRegistry().get(this.selectedChannel); return this.carbonChat.channelRegistry().get(this.selectedChannel.get());
} }
public @Nullable Key selectedChannelKey() { public @Nullable Key selectedChannelKey() {
return this.selectedChannel; return this.selectedChannel.orNull();
} }
@Override @Override
public void selectedChannel(final @Nullable ChatChannel chatChannel) { public void selectedChannel(final @Nullable ChatChannel chatChannel) {
if (chatChannel == null) { if (chatChannel == null) {
this.selectedChannel = null; this.selectedChannel.set(null);
} else { } else {
this.selectedChannel = chatChannel.key(); this.selectedChannel.set(chatChannel.key());
}
if (this.carbonChat.server().userManager() instanceof SaveOnChange userManager) {
userManager.saveSelectedChannel(this.uuid(), this.selectedChannel);
} }
} }
@@ -353,8 +369,10 @@ public class CarbonPlayerCommon implements CarbonPlayer, ForwardingAudience.Sing
@Override @Override
public String username() { public String username() {
if (this.username == null) { if (this.username == null) {
this.username = Objects.requireNonNull(CarbonChatProvider.carbonChat().server() this.username = Objects.requireNonNull(
.resolveName(this.uuid).join()); this.profileResolver.resolveName(this.uuid).join(),
"name"
);
} }
return this.username; return this.username;
@@ -364,9 +382,21 @@ public class CarbonPlayerCommon implements CarbonPlayer, ForwardingAudience.Sing
this.username = username; 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 @Override
public boolean hasCustomDisplayName() { public boolean hasCustomDisplayName() {
return this.displayName != null; return this.displayName.hasValue();
} }
@Override @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; package net.draycia.carbon.common.users;
import java.util.UUID; import java.util.UUID;
import net.kyori.adventure.key.Key; import java.util.concurrent.CompletableFuture;
import net.kyori.adventure.text.Component;
import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable; import org.checkerframework.checker.nullness.qual.Nullable;
import org.checkerframework.framework.qual.DefaultQualifier; import org.checkerframework.framework.qual.DefaultQualifier;
@DefaultQualifier(NonNull.class) @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); void shutdown();
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);
} }
@@ -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; package net.draycia.carbon.common.users.db;
import com.google.inject.MembersInjector;
import java.util.UUID; import java.util.UUID;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
import net.draycia.carbon.api.users.ComponentPlayerResult; import java.util.concurrent.Executors;
import net.draycia.carbon.api.users.UserManager; import net.draycia.carbon.common.users.CachingUserManager;
import net.draycia.carbon.common.users.CarbonPlayerCommon; 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 net.kyori.adventure.key.Key;
import org.apache.logging.log4j.Logger;
import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.framework.qual.DefaultQualifier; import org.checkerframework.framework.qual.DefaultQualifier;
import org.jdbi.v3.core.Jdbi; import org.jdbi.v3.core.Jdbi;
import org.jdbi.v3.core.statement.PreparedBatch; import org.jdbi.v3.core.statement.PreparedBatch;
import org.jdbi.v3.core.statement.Update; import org.jdbi.v3.core.statement.Update;
import static net.kyori.adventure.text.Component.empty;
@DefaultQualifier(NonNull.class) @DefaultQualifier(NonNull.class)
public abstract class AbstractUserManager implements UserManager<CarbonPlayerCommon> { public abstract class DatabaseUserManager extends CachingUserManager {
protected final Jdbi jdbi; protected final Jdbi jdbi;
protected final QueriesLocator locator; 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.jdbi = jdbi;
this.locator = locator; this.locator = locator;
} }
@Override @Override
final public CompletableFuture<ComponentPlayerResult<CarbonPlayerCommon>> savePlayer(final CarbonPlayerCommon player) { public final CompletableFuture<Void> save(final CarbonPlayerCommon player) {
return CompletableFuture.supplyAsync(() -> this.jdbi.withHandle(handle -> { if (!player.needsSave()) {
return CompletableFuture.completedFuture(null);
}
return CompletableFuture.runAsync(() -> this.jdbi.withHandle(handle -> {
this.bindPlayerArguments(handle.createUpdate(this.locator.query("save-player")), player) this.bindPlayerArguments(handle.createUpdate(this.locator.query("save-player")), player)
.execute(); .execute();
@@ -70,9 +86,10 @@ public abstract class AbstractUserManager implements UserManager<CarbonPlayerCom
batch.execute(); batch.execute();
} }
// TODO: save ignoredplayers // TODO: save ignoredplayers
return new ComponentPlayerResult<>(player, empty()); return null;
})); }), this.executor);
} }
abstract protected Update bindPlayerArguments(final Update update, final CarbonPlayerCommon player); 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.sql.SQLException;
import java.util.UUID; import java.util.UUID;
import net.draycia.carbon.common.users.CarbonPlayerCommon; import net.draycia.carbon.common.users.CarbonPlayerCommon;
import net.draycia.carbon.common.util.Strings;
import net.kyori.adventure.key.Key; import net.kyori.adventure.key.Key;
import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer; import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer;
import org.checkerframework.checker.nullness.qual.Nullable; import org.checkerframework.checker.nullness.qual.Nullable;
@@ -34,17 +35,17 @@ public class MySQLPlayerRowMapper implements RowMapper<CarbonPlayerCommon> {
@Override @Override
public CarbonPlayerCommon map(final ResultSet rs, final StatementContext ctx) throws SQLException { public CarbonPlayerCommon map(final ResultSet rs, final StatementContext ctx) throws SQLException {
final String id = rs.getString("id"); final String id = Strings.trim(rs.getString("id"));
final @Nullable String lastWhisperTarget = rs.getString("lastwhispertarget"); final @Nullable String lastWhisperTarget = Strings.trim(rs.getString("lastwhispertarget"));
final @Nullable String whisperReplyTarget = rs.getString("whisperreplytarget"); final @Nullable String whisperReplyTarget = Strings.trim(rs.getString("whisperreplytarget"));
final @Nullable @Subst("carbon:global") String selectedChannel = rs.getString("selectedchannel"); final @Nullable @Subst("carbon:global") String selectedChannel = Strings.trim(rs.getString("selectedchannel"));
final @Nullable String displayName = rs.getString("displayname"); final @Nullable String displayName = Strings.trim(rs.getString("displayname"));
return new CarbonPlayerCommon( return new CarbonPlayerCommon(
rs.getBoolean("muted"), rs.getBoolean("muted"),
rs.getBoolean("deafened"), rs.getBoolean("deafened"),
selectedChannel == null ? null : Key.key(selectedChannel), selectedChannel == null ? null : Key.key(selectedChannel),
rs.getString("username"), Strings.trim(rs.getString("username")),
UUID.fromString(id), UUID.fromString(id),
displayName == null ? null : GsonComponentSerializer.gson().deserialize(displayName), displayName == null ? null : GsonComponentSerializer.gson().deserialize(displayName),
lastWhisperTarget == null ? null : UUID.fromString(lastWhisperTarget), 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; 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.HikariConfig;
import com.zaxxer.hikari.HikariDataSource; import com.zaxxer.hikari.HikariDataSource;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects; import java.util.Objects;
import java.util.Optional; import java.util.Optional;
import java.util.UUID; import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import javax.sql.DataSource; import javax.sql.DataSource;
import net.draycia.carbon.api.CarbonChat; import net.draycia.carbon.api.CarbonChat;
import net.draycia.carbon.api.CarbonChatProvider; import net.draycia.carbon.api.CarbonChatProvider;
import net.draycia.carbon.api.channels.ChatChannel; 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.config.DatabaseSettings;
import net.draycia.carbon.common.users.CarbonPlayerCommon; import net.draycia.carbon.common.users.CarbonPlayerCommon;
import net.draycia.carbon.common.users.SaveOnChange; import net.draycia.carbon.common.users.ProfileResolver;
import net.draycia.carbon.common.users.db.AbstractUserManager;
import net.draycia.carbon.common.users.db.ComponentArgumentFactory; import net.draycia.carbon.common.users.db.ComponentArgumentFactory;
import net.draycia.carbon.common.users.db.DBType; 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.KeyArgumentFactory;
import net.draycia.carbon.common.users.db.KeyColumnMapper;
import net.draycia.carbon.common.users.db.QueriesLocator; 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.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.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable; import org.checkerframework.checker.nullness.qual.Nullable;
import org.checkerframework.framework.qual.DefaultQualifier; 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.core.statement.Update;
import org.jdbi.v3.sqlobject.SqlObjectPlugin; 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 // TODO: Dispatch updates using messaging system when users are modified
@DefaultQualifier(NonNull.class) @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,
private MySQLUserManager(final Jdbi jdbi) { final Logger logger,
super(jdbi, new QueriesLocator(DBType.MYSQL)); final ProfileResolver profileResolver,
} final MembersInjector<CarbonPlayerCommon> playerInjector
public static MySQLUserManager manager(
final DatabaseSettings databaseSettings
) { ) {
try { super(
//Class.forName("org.postgresql.Driver"); jdbi,
Class.forName("org.mariadb.jdbc.Driver"); new QueriesLocator(DBType.MYSQL),
Class.forName("com.mysql.cj.jdbc.Driver"); // Manually loading this might not be necessary logger,
} catch (final Exception exception) { profileResolver,
exception.printStackTrace(); playerInjector
} );
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);
} }
@Override @Override
public CompletableFuture<ComponentPlayerResult<CarbonPlayerCommon>> carbonPlayer(final UUID uuid) { protected CarbonPlayerCommon loadOrCreate(final UUID uuid) {
return CompletableFuture.supplyAsync(() -> { return this.jdbi.withHandle(handle -> {
final var playerResult = this.userCache.computeIfAbsent(uuid, key -> this.jdbi.withHandle(handle -> { final Optional<CarbonPlayerCommon> carbonPlayerCommon = handle.createQuery(this.locator.query("select-player"))
final Optional<CarbonPlayerCommon> carbonPlayerCommon = handle.createQuery(this.locator.query("select-player")) .bind("id", uuid)
.bind("id", uuid) .mapTo(CarbonPlayerCommon.class)
.mapTo(CarbonPlayerCommon.class) .findOne();
.findOne();
if (carbonPlayerCommon.isEmpty()) { if (carbonPlayerCommon.isEmpty()) {
// Player doesn't exist in the DB, create them! // Player doesn't exist in the DB, create them!
final String name = Objects.requireNonNull(CarbonChatProvider.carbonChat().server().resolveName(uuid).join()); final String name = Objects.requireNonNull(this.profileResolver.resolveName(uuid).join());
final CarbonPlayerCommon player = new CarbonPlayerCommon(name, uuid); 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")) handle.createQuery(this.locator.query("select-ignores"))
.bind("id", uuid) .bind("id", uuid)
.mapTo(UUID.class) .mapTo(UUID.class)
.forEach(ignoredPlayer -> carbonPlayerCommon.get().ignoredPlayers().add(ignoredPlayer)); .forEach(ignoredPlayer -> carbonPlayerCommon.get().ignoring(ignoredPlayer, true, true));
handle.createQuery(this.locator.query("select-leftchannels")) handle.createQuery(this.locator.query("select-leftchannels"))
.bind("id", uuid) .bind("id", uuid)
.mapTo(Key.class) .mapTo(Key.class)
.forEach(channel -> { .forEach(channel -> {
final @Nullable ChatChannel chatChannel = CarbonChatProvider.carbonChat() final @Nullable ChatChannel chatChannel = CarbonChatProvider.carbonChat()
.channelRegistry() .channelRegistry()
.get(channel); .get(channel);
if (chatChannel == null) { if (chatChannel == null) {
return; return;
} }
carbonPlayerCommon.get().leftChannels().add(channel); carbonPlayerCommon.get().leaveChannel(chatChannel, true);
}); });
return carbonPlayerCommon.get(); return carbonPlayerCommon.get();
})); });
return new ComponentPlayerResult<>(playerResult, empty());
}).completeOnTimeout(new ComponentPlayerResult<>(null, text("Timed out loading data of UUID [" + uuid + " ]")), 30, TimeUnit.SECONDS);
} }
@Override @Override
@@ -162,68 +122,67 @@ public final class MySQLUserManager extends AbstractUserManager implements SaveO
.bind("spying", player.spying()); .bind("spying", player.spying());
} }
@Override public static final class Factory {
public CompletableFuture<ComponentPlayerResult<CarbonPlayerCommon>> saveAndInvalidatePlayer(final CarbonPlayerCommon player) {
return this.savePlayer(player).thenApply(result -> {
this.userCache.remove(player.uuid());
return result; private final DatabaseSettings databaseSettings;
}); private final Logger logger;
} private final ProfileResolver profileResolver;
private final MembersInjector<CarbonPlayerCommon> playerInjector;
@Override @Inject
public int saveDisplayName(final UUID id, final @Nullable Component displayName) { private Factory(
return this.jdbi.withExtension(MySQLSaveOnChange.class, changeSaver -> changeSaver.saveDisplayName(id, displayName)); 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 MySQLUserManager create() {
public int saveMuted(final UUID id, final boolean muted) { try {
return this.jdbi.withExtension(MySQLSaveOnChange.class, changeSaver -> changeSaver.saveMuted(id, muted)); //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 final HikariConfig hikariConfig = new HikariConfig();
public int saveDeafened(final UUID id, final boolean deafened) { hikariConfig.setMaximumPoolSize(20);
return this.jdbi.withExtension(MySQLSaveOnChange.class, changeSaver -> changeSaver.saveDeafened(id, deafened)); hikariConfig.setJdbcUrl(this.databaseSettings.url());
} hikariConfig.setUsername(this.databaseSettings.username());
hikariConfig.setPassword(this.databaseSettings.password());
hikariConfig.setThreadFactory(ConcurrentUtil.carbonThreadFactory(this.logger, "MySQLUserManagerHCP"));
@Override final DataSource dataSource = new HikariDataSource(hikariConfig);
public int saveSpying(final UUID id, final boolean spying) {
return this.jdbi.withExtension(MySQLSaveOnChange.class, changeSaver -> changeSaver.saveSpying(id, spying));
}
@Override final Flyway flyway = Flyway.configure(CarbonChat.class.getClassLoader())
public int saveSelectedChannel(final UUID id, final @Nullable Key selectedChannel) { .baselineVersion("0")
return this.jdbi.withExtension(MySQLSaveOnChange.class, changeSaver -> changeSaver.saveSelectedChannel(id, selectedChannel)); .baselineOnMigrate(true)
} .locations("queries/migrations/mysql")
.dataSource(dataSource)
.validateOnMigrate(true)
.load();
@Override flyway.repair();
public int saveLastWhisperTarget(final UUID id, final @Nullable UUID lastWhisperTarget) { flyway.migrate();
return this.jdbi.withExtension(MySQLSaveOnChange.class, changeSaver -> changeSaver.saveLastWhisperTarget(id, lastWhisperTarget));
}
@Override final Jdbi jdbi = Jdbi.create(dataSource)
public int saveWhisperReplyTarget(final UUID id, final @Nullable UUID whisperReplyTarget) { .registerArgument(new ComponentArgumentFactory())
return this.jdbi.withExtension(MySQLSaveOnChange.class, changeSaver -> changeSaver.saveWhisperReplyTarget(id, whisperReplyTarget)); .registerArgument(new KeyArgumentFactory())
} .registerArgument(new MySQLUUIDArgumentFactory())
.registerArrayType(UUID.class, "uuid")
.registerColumnMapper(new KeyColumnMapper())
.registerRowMapper(new MySQLPlayerRowMapper())
.installPlugin(new SqlObjectPlugin());
@Override return new MySQLUserManager(jdbi, this.logger, this.profileResolver, this.playerInjector);
public int addIgnore(final UUID id, final UUID ignoredPlayer) { }
return this.jdbi.withExtension(MySQLSaveOnChange.class, changeSaver -> changeSaver.addIgnore(id, ignoredPlayer));
}
@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.sql.SQLException;
import java.util.UUID; import java.util.UUID;
import net.draycia.carbon.common.users.CarbonPlayerCommon; import net.draycia.carbon.common.users.CarbonPlayerCommon;
import net.draycia.carbon.common.util.Strings;
import net.kyori.adventure.key.Key; import net.kyori.adventure.key.Key;
import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer; import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer;
import org.checkerframework.checker.nullness.qual.Nullable; import org.checkerframework.checker.nullness.qual.Nullable;
@@ -34,14 +35,14 @@ public class PostgreSQLPlayerRowMapper implements RowMapper<CarbonPlayerCommon>
@Override @Override
public CarbonPlayerCommon map(final ResultSet rs, final StatementContext ctx) throws SQLException { public CarbonPlayerCommon map(final ResultSet rs, final StatementContext ctx) throws SQLException {
final @Nullable @Subst("carbon:global") String selectedChannel = rs.getString("selectedchannel"); final @Nullable @Subst("carbon:global") String selectedChannel = Strings.trim(rs.getString("selectedchannel"));
final @Nullable String displayName = rs.getString("displayname"); final @Nullable String displayName = Strings.trim(rs.getString("displayname"));
return new CarbonPlayerCommon( return new CarbonPlayerCommon(
rs.getBoolean("muted"), rs.getBoolean("muted"),
rs.getBoolean("deafened"), rs.getBoolean("deafened"),
selectedChannel == null ? null : Key.key(selectedChannel), selectedChannel == null ? null : Key.key(selectedChannel),
rs.getString("username"), Strings.trim(rs.getString("username")),
rs.getObject("id", UUID.class), rs.getObject("id", UUID.class),
displayName == null ? null : GsonComponentSerializer.gson().deserialize(displayName), displayName == null ? null : GsonComponentSerializer.gson().deserialize(displayName),
rs.getObject("lastwhispertarget", UUID.class), 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; 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.HikariConfig;
import com.zaxxer.hikari.HikariDataSource; import com.zaxxer.hikari.HikariDataSource;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects; import java.util.Objects;
import java.util.UUID; import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import javax.sql.DataSource; import javax.sql.DataSource;
import net.draycia.carbon.api.CarbonChat; import net.draycia.carbon.api.CarbonChat;
import net.draycia.carbon.api.CarbonChatProvider; import net.draycia.carbon.api.CarbonChatProvider;
import net.draycia.carbon.api.channels.ChatChannel; 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.config.DatabaseSettings;
import net.draycia.carbon.common.users.CarbonPlayerCommon; import net.draycia.carbon.common.users.CarbonPlayerCommon;
import net.draycia.carbon.common.users.SaveOnChange; import net.draycia.carbon.common.users.ProfileResolver;
import net.draycia.carbon.common.users.db.AbstractUserManager;
import net.draycia.carbon.common.users.db.ComponentArgumentFactory; import net.draycia.carbon.common.users.db.ComponentArgumentFactory;
import net.draycia.carbon.common.users.db.DBType; 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.KeyArgumentFactory;
import net.draycia.carbon.common.users.db.KeyColumnMapper;
import net.draycia.carbon.common.users.db.QueriesLocator; 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.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.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable; import org.checkerframework.checker.nullness.qual.Nullable;
import org.checkerframework.framework.qual.DefaultQualifier; 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.postgres.PostgresPlugin;
import org.jdbi.v3.sqlobject.SqlObjectPlugin; 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 // TODO: Dispatch updates using messaging system when users are modified
@DefaultQualifier(NonNull.class) @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,
private PostgreSQLUserManager(final Jdbi jdbi) { final Logger logger,
super(jdbi, new QueriesLocator(DBType.POSTGRESQL)); final ProfileResolver profileResolver,
} final MembersInjector<CarbonPlayerCommon> playerInjector
) {
public static PostgreSQLUserManager manager(final DatabaseSettings databaseSettings) { super(
try { jdbi,
Class.forName("org.postgresql.Driver"); new QueriesLocator(DBType.POSTGRESQL),
Flyway.configure().getPluginRegister().REGISTERED_PLUGINS.add(new PostgreSQLDatabaseType()); logger,
} catch (final Exception exception) { profileResolver,
exception.printStackTrace(); playerInjector
} );
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);
} }
@Override @Override
public CompletableFuture<ComponentPlayerResult<CarbonPlayerCommon>> carbonPlayer(final UUID uuid) { protected CarbonPlayerCommon loadOrCreate(final UUID uuid) {
return CompletableFuture.supplyAsync(() -> { return this.jdbi.withHandle(handle -> {
final @Nullable CarbonPlayerCommon cachedPlayer = this.userCache.get(uuid); try {
final @Nullable CarbonPlayerCommon carbonPlayerCommon = handle.createQuery(this.locator.query("select-player"))
.bind("id", uuid)
.mapTo(CarbonPlayerCommon.class)
.first();
if (cachedPlayer != null) { handle.createQuery(this.locator.query("select-ignores"))
return new ComponentPlayerResult<>(cachedPlayer, empty()); .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 @Override
@@ -165,68 +127,63 @@ public final class PostgreSQLUserManager extends AbstractUserManager implements
.bind("spying", player.spying()); .bind("spying", player.spying());
} }
@Override public static final class Factory {
public CompletableFuture<ComponentPlayerResult<CarbonPlayerCommon>> saveAndInvalidatePlayer(final CarbonPlayerCommon player) {
return this.savePlayer(player).thenApply(result -> {
this.userCache.remove(player.uuid());
return result; private final DatabaseSettings databaseSettings;
}); private final Logger logger;
} private final ProfileResolver profileResolver;
private final MembersInjector<CarbonPlayerCommon> playerInjector;
@Override @Inject
public int saveDisplayName(final UUID id, final @Nullable Component displayName) { private Factory(
return this.jdbi.withExtension(PostgreSQLSaveOnChange.class, changeSaver -> changeSaver.saveDisplayName(id, displayName)); 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 PostgreSQLUserManager create() {
public int saveMuted(final UUID id, final boolean muted) { try {
return this.jdbi.withExtension(PostgreSQLSaveOnChange.class, changeSaver -> changeSaver.saveMuted(id, muted)); Class.forName("org.postgresql.Driver");
} Flyway.configure().getPluginRegister().REGISTERED_PLUGINS.add(new PostgreSQLDatabaseType());
} catch (final Exception exception) {
exception.printStackTrace();
}
@Override final HikariConfig hikariConfig = new HikariConfig();
public int saveDeafened(final UUID id, final boolean deafened) { hikariConfig.setMaximumPoolSize(20);
return this.jdbi.withExtension(PostgreSQLSaveOnChange.class, changeSaver -> changeSaver.saveDeafened(id, deafened)); hikariConfig.setJdbcUrl(this.databaseSettings.url());
} hikariConfig.setUsername(this.databaseSettings.username());
hikariConfig.setPassword(this.databaseSettings.password());
hikariConfig.setThreadFactory(ConcurrentUtil.carbonThreadFactory(this.logger, "PSQLUserManagerHCP"));
@Override final DataSource dataSource = new HikariDataSource(hikariConfig);
public int saveSpying(final UUID id, final boolean spying) {
return this.jdbi.withExtension(PostgreSQLSaveOnChange.class, changeSaver -> changeSaver.saveSpying(id, spying));
}
@Override Flyway.configure(CarbonChat.class.getClassLoader())
public int saveSelectedChannel(final UUID id, final @Nullable Key selectedChannel) { .baselineVersion("0")
return this.jdbi.withExtension(PostgreSQLSaveOnChange.class, changeSaver -> changeSaver.saveSelectedChannel(id, selectedChannel)); .baselineOnMigrate(true)
} .locations("queries/migrations/postgresql")
.dataSource(dataSource)
.validateOnMigrate(true)
.load()
.migrate();
@Override final Jdbi jdbi = Jdbi.create(dataSource)
public int saveLastWhisperTarget(final UUID id, final @Nullable UUID lastWhisperTarget) { .registerArgument(new ComponentArgumentFactory())
return this.jdbi.withExtension(PostgreSQLSaveOnChange.class, changeSaver -> changeSaver.saveLastWhisperTarget(id, lastWhisperTarget)); .registerArgument(new KeyArgumentFactory())
} .registerColumnMapper(new KeyColumnMapper())
.registerRowMapper(new PostgreSQLPlayerRowMapper())
.installPlugin(new SqlObjectPlugin())
.installPlugin(new PostgresPlugin());
@Override return new PostgreSQLUserManager(jdbi, this.logger, this.profileResolver, this.playerInjector);
public int saveWhisperReplyTarget(final UUID id, final @Nullable UUID whisperReplyTarget) { }
return this.jdbi.withExtension(PostgreSQLSaveOnChange.class, changeSaver -> changeSaver.saveWhisperReplyTarget(id, whisperReplyTarget));
}
@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.Gson;
import com.google.gson.GsonBuilder; import com.google.gson.GsonBuilder;
import com.google.inject.Inject; import com.google.inject.Inject;
import com.google.inject.Injector; import com.google.inject.MembersInjector;
import java.io.IOException; import java.io.IOException;
import java.io.Reader;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Path; 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.UUID;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit; import java.util.concurrent.Executors;
import net.draycia.carbon.api.CarbonChat;
import net.draycia.carbon.api.CarbonChatProvider; import net.draycia.carbon.api.CarbonChatProvider;
import net.draycia.carbon.api.channels.ChatChannel; import net.draycia.carbon.api.channels.ChatChannel;
import net.draycia.carbon.api.users.ComponentPlayerResult; import net.draycia.carbon.common.DataDirectory;
import net.draycia.carbon.api.users.UserManager;
import net.draycia.carbon.common.ForCarbon;
import net.draycia.carbon.common.serialisation.gson.ChatChannelSerializerGson; import net.draycia.carbon.common.serialisation.gson.ChatChannelSerializerGson;
import net.draycia.carbon.common.serialisation.gson.UUIDSerializerGson; 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.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 net.kyori.adventure.text.serializer.gson.GsonComponentSerializer;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable; import org.checkerframework.checker.nullness.qual.Nullable;
import org.checkerframework.framework.qual.DefaultQualifier; 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) @DefaultQualifier(NonNull.class)
public class JSONUserManager implements UserManager<CarbonPlayerCommon> { public class JSONUserManager extends CachingUserManager {
private final Logger logger;
private final Gson serializer; private final Gson serializer;
private final Path userDirectory; private final Path userDirectory;
private final CarbonChat carbonChat;
private final Map<UUID, CarbonPlayerCommon> userCache = Collections.synchronizedMap(new HashMap<>());
@Inject @Inject
public JSONUserManager( public JSONUserManager(
final @ForCarbon Path dataDirectory, final @DataDirectory Path dataDirectory,
final Injector injector,
final Logger logger, final Logger logger,
final CarbonChat carbonChat final ProfileResolver profileResolver,
final MembersInjector<CarbonPlayerCommon> playerInjector,
final ChatChannelSerializerGson channelSerializer,
final UUIDSerializerGson uuidSerializer
) throws IOException { ) throws IOException {
this.logger = logger; super(
logger,
Executors.newSingleThreadExecutor(ConcurrentUtil.carbonThreadFactory(logger, "JSONUserManager")),
profileResolver,
playerInjector
);
this.userDirectory = dataDirectory.resolve("users"); this.userDirectory = dataDirectory.resolve("users");
this.carbonChat = carbonChat;
Files.createDirectories(this.userDirectory); Files.createDirectories(this.userDirectory);
this.serializer = GsonComponentSerializer.gson().populator() this.serializer = GsonComponentSerializer.gson().populator()
.apply(new GsonBuilder()) .apply(new GsonBuilder())
.registerTypeAdapter(ChatChannel.class, injector.getInstance(ChatChannelSerializerGson.class)) .registerTypeAdapter(ChatChannel.class, channelSerializer)
.registerTypeAdapter(UUID.class, injector.getInstance(UUIDSerializerGson.class)) .registerTypeAdapter(UUID.class, uuidSerializer)
.registerTypeAdapter(PersistentUserProperty.class, new PersistentUserProperty.Serializer())
.setPrettyPrinting() .setPrettyPrinting()
.create(); .create();
} }
@Override @Override
public CompletableFuture<ComponentPlayerResult<CarbonPlayerCommon>> carbonPlayer(final UUID uuid) { protected CarbonPlayerCommon loadOrCreate(final UUID uuid) {
return CompletableFuture.supplyAsync(() -> { final Path userFile = this.userFile(uuid);
final @Nullable CarbonPlayerCommon cachedPlayer = this.userCache.get(uuid);
if (cachedPlayer != null) { if (Files.exists(userFile)) {
return new ComponentPlayerResult<>(cachedPlayer, empty()); try {
} final @Nullable CarbonPlayerCommon player;
try (final Reader reader = Files.newBufferedReader(userFile)) {
final Path userFile = this.userDirectory.resolve(uuid + ".json"); player = this.serializer.fromJson(reader, CarbonPlayerCommon.class);
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 (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( return new CarbonPlayerCommon(null /* Username will be resolved when requested */, uuid);
this.carbonChat.server().resolveName(uuid).join()); }
final CarbonPlayerCommon player = new CarbonPlayerCommon(name, uuid); private Path userFile(final UUID id) {
return this.userDirectory.resolve(id + ".json");
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);
} }
@Override @Override
public CompletableFuture<ComponentPlayerResult<CarbonPlayerCommon>> savePlayer(final CarbonPlayerCommon player) { public CompletableFuture<Void> save(final CarbonPlayerCommon player) {
return CompletableFuture.supplyAsync(() -> { if (!player.needsSave()) {
final Path userFile = this.userDirectory.resolve(player.uuid() + ".json"); return CompletableFuture.completedFuture(null);
}
return CompletableFuture.runAsync(() -> {
final Path userFile = this.userFile(player.uuid());
try { try {
final String json = this.serializer.toJson(player); final String json = this.serializer.toJson(player);
if (json == null || json.isBlank()) { 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.writeString(userFile, json);
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())));
} catch (final IOException exception) { } catch (final IOException exception) {
this.logger.error("Exception caught while saving data for player [{}]", player.username()); throw new RuntimeException("Exception while saving data for player [%s]".formatted(player.username()), exception);
exception.printStackTrace();
return new ComponentPlayerResult<>(null, text(exception.getMessage()));
} }
}); }, this.executor);
}
@Override
public CompletableFuture<ComponentPlayerResult<CarbonPlayerCommon>> saveAndInvalidatePlayer(final CarbonPlayerCommon player) {
return this.savePlayer(player).thenApply(result -> {
this.userCache.remove(player.uuid());
return result;
});
} }
} }
@@ -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.DeafenHandler;
import net.draycia.carbon.common.listeners.IgnoreHandler; import net.draycia.carbon.common.listeners.IgnoreHandler;
import net.draycia.carbon.common.listeners.ItemLinkHandler; 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.MuteHandler;
import net.draycia.carbon.common.listeners.PingHandler; 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, 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) { public static void registerCommonListeners(final Injector injector) {
for (final var listenerClass : LISTENER_CLASSES) { for (final var listenerClass : LISTENER_CLASSES) {
@@ -22,10 +22,9 @@ package net.draycia.carbon.common.util;
import java.util.List; import java.util.List;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
import net.draycia.carbon.api.CarbonServer; import net.draycia.carbon.api.CarbonServer;
import net.draycia.carbon.api.users.ComponentPlayerResult; import net.draycia.carbon.api.users.CarbonPlayer;
import net.draycia.carbon.api.users.UserManager; import net.draycia.carbon.common.users.UserManagerInternal;
import net.draycia.carbon.common.users.CarbonPlayerCommon; import org.apache.logging.log4j.Logger;
import net.draycia.carbon.common.users.WrappedCarbonPlayer;
import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.framework.qual.DefaultQualifier; import org.checkerframework.framework.qual.DefaultQualifier;
@@ -35,56 +34,27 @@ public final class PlayerUtils {
private 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 CarbonServer carbonServer,
final UserManager<CarbonPlayerCommon> userManager final UserManagerInternal<C> userManager,
final Logger logger
) { ) {
return carbonServer.players().stream() return carbonServer.players().stream()
.map(player -> savePlayer(carbonServer, userManager, (WrappedCarbonPlayer) player)) .map(player -> PlayerUtils.savePlayer(userManager, (C) player, logger))
.toList(); .toList();
} }
public static CompletableFuture<ComponentPlayerResult<CarbonPlayerCommon>> savePlayer( public static <C extends CarbonPlayer> CompletableFuture<Void> savePlayer(
final CarbonServer carbonServer, final UserManagerInternal<C> userManager,
final UserManager<CarbonPlayerCommon> userManager, final C player,
final WrappedCarbonPlayer player final Logger logger
) { ) {
final var saveResult = final var saveResult = userManager.save(player);
userManager.savePlayer(player.carbonPlayerCommon()); saveResult.exceptionally(thr -> {
logger.warn("Exception saving data for player {} with UUID {}", player.username(), player.uuid(), thr);
saveResult.thenAccept(result -> {
if (result.player() == null) {
carbonServer.console().sendMessage(result.reason());
}
});
saveResult.exceptionally(exception -> {
exception.getCause().printStackTrace();
return null; 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; 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) minecraft(libs.fabricMinecraft)
mappings(loom.officialMojangMappings()) mappings(loom.officialMojangMappings())
modImplementation(libs.fabricLoader) modImplementation(libs.fabricLoader)
modImplementation("net.fabricmc.fabric-api:fabric-api:0.69.1+1.19.3") modImplementation("net.fabricmc.fabric-api:fabric-api:0.76.0+1.19.4")
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-deprecated:0.76.0+1.19.4") // LuckPerms needs to work at dev time
carbon(projects.carbonchatCommon) { carbon(projects.carbonchatCommon) {
exclude("net.kyori", "adventure-api") exclude("net.kyori", "adventure-api")
@@ -19,38 +19,33 @@
*/ */
package net.draycia.carbon.fabric; package net.draycia.carbon.fabric;
import com.google.inject.Guice; import com.google.inject.Inject;
import com.google.inject.Injector; 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.nio.file.Path;
import java.util.UUID; import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.CompletableFuture;
import net.draycia.carbon.api.CarbonChat;
import net.draycia.carbon.api.CarbonChatProvider;
import net.draycia.carbon.api.CarbonServer; 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.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.channels.CarbonChannelRegistry;
import net.draycia.carbon.common.command.commands.ExecutionCoordinatorHolder;
import net.draycia.carbon.common.messages.CarbonMessages; import net.draycia.carbon.common.messages.CarbonMessages;
import net.draycia.carbon.common.messaging.MessagingManager; import net.draycia.carbon.common.messaging.MessagingManager;
import net.draycia.carbon.common.users.CarbonPlayerCommon; import net.draycia.carbon.common.users.ProfileCache;
import net.draycia.carbon.common.util.CloudUtils; import net.draycia.carbon.common.users.ProfileResolver;
import net.draycia.carbon.common.util.ListenerUtils;
import net.draycia.carbon.common.util.PlayerUtils;
import net.draycia.carbon.fabric.callback.ChatCallback; import net.draycia.carbon.fabric.callback.ChatCallback;
import net.draycia.carbon.fabric.command.DeleteMessageCommand; import net.draycia.carbon.fabric.command.DeleteMessageCommand;
import net.draycia.carbon.fabric.listeners.FabricChatListener; import net.draycia.carbon.fabric.listeners.FabricChatListener;
import net.draycia.carbon.fabric.listeners.FabricChatPreviewListener; import net.draycia.carbon.fabric.listeners.FabricChatPreviewListener;
import net.draycia.carbon.fabric.listeners.FabricPlayerJoinListener; import net.draycia.carbon.fabric.listeners.FabricJoinQuitListener;
import net.draycia.carbon.fabric.listeners.FabricPlayerLeaveListener; import net.draycia.carbon.fabric.users.CarbonPlayerFabric;
import net.fabricmc.api.ModInitializer;
import net.fabricmc.fabric.api.event.lifecycle.v1.ServerLifecycleEvents; 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.message.v1.ServerMessageDecoratorEvent;
import net.fabricmc.fabric.api.networking.v1.ServerPlayConnectionEvents; import net.fabricmc.fabric.api.networking.v1.ServerPlayConnectionEvents;
import net.fabricmc.loader.api.FabricLoader; import net.fabricmc.loader.api.FabricLoader;
import net.fabricmc.loader.api.ModContainer;
import net.kyori.adventure.audience.Audience; import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.text.Component; import net.kyori.adventure.text.Component;
import net.kyori.moonshine.message.IMessageRenderer; 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.network.chat.ChatType;
import net.minecraft.resources.ResourceKey; import net.minecraft.resources.ResourceKey;
import net.minecraft.resources.ResourceLocation; 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.apache.logging.log4j.Logger;
import org.checkerframework.checker.nullness.qual.MonotonicNonNull;
import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.checkerframework.framework.qual.DefaultQualifier; import org.checkerframework.framework.qual.DefaultQualifier;
import static java.util.Objects.requireNonNull;
@DefaultQualifier(NonNull.class) @DefaultQualifier(NonNull.class)
public final class CarbonChatFabric implements ModInitializer, CarbonChat { @Singleton
public final class CarbonChatFabric extends CarbonChatInternal<CarbonPlayerFabric> {
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();
public static ResourceKey<ChatType> CHAT_TYPE = ResourceKey.create(Registries.CHAT_TYPE, new ResourceLocation("carbon", "chat")); 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() { public void onInitialize() {
this.modContainer = FabricLoader.getInstance().getModContainer("carbonchat").orElseThrow(() -> this.init();
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>>() {}));
// Platform Listeners // Platform Listeners
this.registerChatListener(); this.registerChatListener();
this.registerServerLifecycleListeners(); this.registerServerLifecycleListeners();
this.registerPlayerStatusListeners(); this.registerPlayerStatusListeners();
this.registerTickListeners();
// Listeners this.injector().getInstance(DeleteMessageCommand.class).init();
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);
} }
private void registerChatListener() { private void registerChatListener() {
ChatCallback.setup(); ChatCallback.setup();
ChatCallback.INSTANCE.registerListener(new FabricChatListener(this, this.channelRegistry)); ChatCallback.INSTANCE.registerListener(new FabricChatListener(this, this.channelRegistry()));
ServerMessageDecoratorEvent.EVENT.register(ServerMessageDecoratorEvent.CONTENT_PHASE, this.injector.getInstance(FabricChatPreviewListener.class)); ServerMessageDecoratorEvent.EVENT.register(ServerMessageDecoratorEvent.CONTENT_PHASE, this.injector().getInstance(FabricChatPreviewListener.class));
} }
private void registerServerLifecycleListeners() { private void registerServerLifecycleListeners() {
ServerLifecycleEvents.SERVER_STARTING.register(server -> this.minecraftServer = server); ServerLifecycleEvents.SERVER_STOPPED.register(server -> this.shutdown());
ServerLifecycleEvents.SERVER_STOPPING.register($ -> PlayerUtils.saveLoggedInPlayers(this.carbonServerFabric, this.userManager).forEach(CompletableFuture::join));
ServerLifecycleEvents.SERVER_STOPPED.register(server -> this.minecraftServer = null);
} }
private void registerPlayerStatusListeners() { private void registerPlayerStatusListeners() {
ServerPlayConnectionEvents.DISCONNECT.register(this.injector.getInstance(FabricPlayerLeaveListener.class)); final FabricJoinQuitListener listener = this.injector().getInstance(FabricJoinQuitListener.class);
ServerPlayConnectionEvents.JOIN.register(this.injector.getInstance(FabricPlayerJoinListener.class)); ServerPlayConnectionEvents.DISCONNECT.register(listener);
} ServerPlayConnectionEvents.JOIN.register(listener);
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;
} }
public boolean luckPermsLoaded() { public boolean luckPermsLoaded() {
@@ -20,28 +20,37 @@
package net.draycia.carbon.fabric; package net.draycia.carbon.fabric;
import cloud.commandframework.CommandManager; import cloud.commandframework.CommandManager;
import cloud.commandframework.execution.AsynchronousCommandExecutionCoordinator;
import cloud.commandframework.fabric.FabricServerCommandManager; import cloud.commandframework.fabric.FabricServerCommandManager;
import cloud.commandframework.fabric.argument.FabricArgumentParsers;
import com.google.inject.AbstractModule; import com.google.inject.AbstractModule;
import com.google.inject.Injector; import com.google.inject.Injector;
import com.google.inject.Provider;
import com.google.inject.Provides; import com.google.inject.Provides;
import com.google.inject.Singleton; import com.google.inject.Singleton;
import com.google.inject.TypeLiteral;
import java.nio.file.Path; import java.nio.file.Path;
import net.draycia.carbon.api.CarbonChat; import net.draycia.carbon.api.CarbonChat;
import net.draycia.carbon.api.CarbonServer; import net.draycia.carbon.api.CarbonServer;
import net.draycia.carbon.api.users.UserManager;
import net.draycia.carbon.api.util.SourcedAudience; import net.draycia.carbon.api.util.SourcedAudience;
import net.draycia.carbon.common.CarbonCommonModule; 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.Commander;
import net.draycia.carbon.common.command.argument.PlayerSuggestions; 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.common.util.CloudUtils;
import net.draycia.carbon.fabric.command.FabricCommander; import net.draycia.carbon.fabric.command.FabricCommander;
import net.draycia.carbon.fabric.command.FabricPlayerCommander; 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.audience.Audience;
import net.kyori.adventure.text.Component; import net.kyori.adventure.text.Component;
import net.kyori.moonshine.message.IMessageRenderer; import net.kyori.moonshine.message.IMessageRenderer;
import net.minecraft.server.level.ServerPlayer; import net.minecraft.server.level.ServerPlayer;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.framework.qual.DefaultQualifier; import org.checkerframework.framework.qual.DefaultQualifier;
@@ -50,34 +59,34 @@ import org.checkerframework.framework.qual.DefaultQualifier;
public final class CarbonChatFabricModule extends AbstractModule { public final class CarbonChatFabricModule extends AbstractModule {
private final Logger logger; private final Logger logger;
private final CarbonChatFabric carbonChat; private final ModContainer modContainer;
private final Path dataDirectory;
CarbonChatFabricModule( CarbonChatFabricModule() {
final CarbonChatFabric carbonChat, final ModContainer modContainer = FabricLoader.getInstance().getModContainer("carbonchat")
final Logger logger, .orElseThrow(() -> new IllegalStateException("Could not find ModContainer for carbonchat."));
final Path dataDirectory this.modContainer = modContainer;
) { this.logger = LogManager.getLogger(modContainer.getMetadata().getName());
this.logger = logger;
this.carbonChat = carbonChat;
this.dataDirectory = dataDirectory;
} }
@Provides @Provides
@Singleton @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<>( final FabricServerCommandManager<Commander> commandManager = new FabricServerCommandManager<>(
AsynchronousCommandExecutionCoordinator.<Commander>builder().build(), executionCoordinatorHolder.executionCoordinator(),
commandSourceStack -> { commandSourceStack -> {
if (commandSourceStack.getEntity() instanceof ServerPlayer) { if (commandSourceStack.getEntity() instanceof ServerPlayer) {
return new FabricPlayerCommander(this.carbonChat, commandSourceStack); return new FabricPlayerCommander(carbonChat.get(), commandSourceStack);
} }
return FabricCommander.from(commandSourceStack); return FabricCommander.from(commandSourceStack);
}, },
commander -> ((FabricCommander) commander).commandSourceStack() commander -> ((FabricCommander) commander).commandSourceStack()
); );
CloudUtils.decorateCommandManager(commandManager, this.carbonChat.carbonMessages()); CloudUtils.decorateCommandManager(commandManager, carbonMessages);
commandManager.brigadierManager().setNativeNumberSuggestions(false); commandManager.brigadierManager().setNativeNumberSuggestions(false);
@@ -96,16 +105,25 @@ public final class CarbonChatFabricModule extends AbstractModule {
return injector.getInstance(FabricMessageRenderer.class); 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 @Override
public void configure() { public void configure() {
this.install(new CarbonCommonModule()); this.install(new CarbonCommonModule());
this.bind(CarbonChat.class).toInstance(this.carbonChat); this.bind(ModContainer.class).toInstance(this.modContainer);
this.bind(CarbonChatFabric.class).toInstance(this.carbonChat); this.bind(CarbonChat.class).to(CarbonChatFabric.class);
this.bind(Logger.class).toInstance(this.logger); 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(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.Inject;
import com.google.inject.Singleton; import com.google.inject.Singleton;
import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.UUID; import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import net.draycia.carbon.api.CarbonServer; import net.draycia.carbon.api.CarbonServer;
import net.draycia.carbon.api.users.CarbonPlayer; 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.api.users.UserManager;
import net.draycia.carbon.common.users.CarbonPlayerCommon;
import net.draycia.carbon.fabric.users.CarbonPlayerFabric; import net.draycia.carbon.fabric.users.CarbonPlayerFabric;
import net.kyori.adventure.audience.Audience; import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.audience.ForwardingAudience; import net.kyori.adventure.audience.ForwardingAudience;
import net.kyori.adventure.platform.fabric.FabricServerAudiences; 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.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.checkerframework.framework.qual.DefaultQualifier; import org.checkerframework.framework.qual.DefaultQualifier;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
@@ -44,38 +38,31 @@ import org.jetbrains.annotations.NotNull;
@DefaultQualifier(NonNull.class) @DefaultQualifier(NonNull.class)
public final class CarbonServerFabric implements CarbonServer, ForwardingAudience.Single { public final class CarbonServerFabric implements CarbonServer, ForwardingAudience.Single {
private final CarbonChatFabric carbonChatFabric; private final MinecraftServerHolder serverHolder;
private final UserManager<CarbonPlayerFabric> userManager; private final FabricUserManager userManager;
@Inject @Inject
private CarbonServerFabric(final CarbonChatFabric carbonChatFabric, final UserManager<CarbonPlayerCommon> userManager) { private CarbonServerFabric(final MinecraftServerHolder serverHolder, final FabricUserManager userManager) {
this.carbonChatFabric = carbonChatFabric; this.serverHolder = serverHolder;
this.userManager = new FabricUserManager(userManager, carbonChatFabric); this.userManager = userManager;
} }
@Override @Override
public @NotNull Audience audience() { public @NotNull Audience audience() {
return FabricServerAudiences.of(this.carbonChatFabric.minecraftServer()).all(); return FabricServerAudiences.of(this.serverHolder.requireServer()).all();
} }
@Override @Override
public Audience console() { public Audience console() {
return this.carbonChatFabric.minecraftServer(); return this.serverHolder.requireServer().createCommandSourceStack();
} }
@Override @Override
public List<? extends CarbonPlayer> players() { public List<? extends CarbonPlayer> players() {
final var players = new ArrayList<CarbonPlayer>(); return this.serverHolder.requireServer().getPlayerList().getPlayers().stream()
.map(serverPlayer -> this.userManager.user(serverPlayer.getUUID()).getNow(null))
for (final var player : this.carbonChatFabric.minecraftServer().getPlayerList().getPlayers()) { .filter(Objects::nonNull)
final ComponentPlayerResult<CarbonPlayerFabric> result = this.userManager.carbonPlayer(player.getUUID()).join(); .toList();
if (result.player() != null) {
players.add(result.player());
}
}
return players;
} }
@Override @Override
@@ -83,22 +70,4 @@ public final class CarbonServerFabric implements CarbonServer, ForwardingAudienc
return this.userManager; 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; package net.draycia.carbon.fabric;
import java.util.UUID; import com.google.inject.Inject;
import java.util.concurrent.CompletableFuture; import com.google.inject.Provider;
import net.draycia.carbon.api.users.ComponentPlayerResult; import com.google.inject.Singleton;
import net.draycia.carbon.api.users.UserManager; import net.draycia.carbon.common.users.Backing;
import net.draycia.carbon.common.users.CarbonPlayerCommon; 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.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.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.checkerframework.framework.qual.DefaultQualifier; import org.checkerframework.framework.qual.DefaultQualifier;
@DefaultQualifier(NonNull.class) @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 MinecraftServerHolder serverHolder;
private final CarbonChatFabric carbonChatFabric; private final Provider<CarbonChatFabric> carbonChat;
public FabricUserManager(final UserManager<CarbonPlayerCommon> proxiedUserManager, final CarbonChatFabric carbonChatFabric) { @Inject
this.proxiedUserManager = proxiedUserManager; private FabricUserManager(
this.carbonChatFabric = carbonChatFabric; final @Backing UserManagerInternal<CarbonPlayerCommon> backingManager,
final MinecraftServerHolder serverHolder,
final Provider<CarbonChatFabric> carbonChat
) {
super(backingManager);
this.serverHolder = serverHolder;
this.carbonChat = carbonChat;
} }
@Override @Override
public CompletableFuture<ComponentPlayerResult<CarbonPlayerFabric>> carbonPlayer(final UUID uuid) { protected CarbonPlayerFabric wrap(final CarbonPlayerCommon common) {
return this.proxiedUserManager.carbonPlayer(uuid).thenApply(result -> { return new CarbonPlayerFabric(common, this.serverHolder, this.carbonChat);
if (result.player() == null) {
return new ComponentPlayerResult<>(null, result.reason());
}
return new ComponentPlayerResult<>(new CarbonPlayerFabric(result.player(), this.carbonChatFabric), result.reason());
});
} }
@Override @Override
public CompletableFuture<ComponentPlayerResult<CarbonPlayerFabric>> savePlayer(final CarbonPlayerFabric player) { protected void updateTransientLoadedStatus(final CarbonPlayerFabric wrapped) {
return this.proxiedUserManager.savePlayer(player.carbonPlayerCommon()).thenApply(result -> { wrapped.carbonPlayerCommon().markTransientLoaded(wrapped.player().isEmpty());
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;
} }
} }
@@ -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.Executors;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.function.Consumer; import java.util.function.Consumer;
import net.draycia.carbon.common.util.ConcurrentUtil;
import net.fabricmc.fabric.api.event.lifecycle.v1.ServerLifecycleEvents; import net.fabricmc.fabric.api.event.lifecycle.v1.ServerLifecycleEvents;
import net.kyori.adventure.audience.Audience; import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.audience.MessageType; import net.kyori.adventure.audience.MessageType;
@@ -33,7 +34,6 @@ import net.kyori.adventure.identity.Identity;
import net.kyori.adventure.text.Component; import net.kyori.adventure.text.Component;
import net.minecraft.server.MinecraftServer; import net.minecraft.server.MinecraftServer;
import net.minecraft.server.level.ServerPlayer; import net.minecraft.server.level.ServerPlayer;
import net.minecraft.util.thread.NamedThreadFactory;
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import org.checkerframework.checker.nullness.qual.MonotonicNonNull; import org.checkerframework.checker.nullness.qual.MonotonicNonNull;
@@ -54,8 +54,8 @@ public enum ChatCallback {
private @Nullable ExecutorService chatExecutor; private @Nullable ExecutorService chatExecutor;
private final List<Consumer<Chat>> listeners = new CopyOnWriteArrayList<>(); private final List<Consumer<Chat>> listeners = new CopyOnWriteArrayList<>();
private void initExecutor() { private void initExecutor(final Logger logger) {
this.chatExecutor = Executors.newSingleThreadExecutor(new NamedThreadFactory("CarbonChat-Chat-Thread")); this.chatExecutor = Executors.newSingleThreadExecutor(ConcurrentUtil.carbonThreadFactory(logger, "Chat Handling"));
} }
private void shutdownExecutor() { private void shutdownExecutor() {
@@ -114,7 +114,7 @@ public enum ChatCallback {
} }
public static void setup() { 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()); 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.CarbonChatProvider;
import net.draycia.carbon.api.channels.ChatChannel; import net.draycia.carbon.api.channels.ChatChannel;
import net.draycia.carbon.api.users.CarbonPlayer; 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 net.minecraft.server.level.ServerPlayer;
import org.checkerframework.checker.nullness.qual.MonotonicNonNull; import org.checkerframework.checker.nullness.qual.MonotonicNonNull;
import org.checkerframework.checker.nullness.qual.Nullable; import org.checkerframework.checker.nullness.qual.Nullable;
@@ -38,15 +38,9 @@ public class MessageRecipientFilter {
} }
public boolean shouldFilterMessageTo(final ServerPlayer serverPlayer) { public boolean shouldFilterMessageTo(final ServerPlayer serverPlayer) {
final ComponentPlayerResult<? extends CarbonPlayer> authorResult = CarbonChatProvider.carbonChat().server().userManager().carbonPlayer(this.sender.getUUID()).join(); final UserManager<? extends CarbonPlayer> userManager = CarbonChatProvider.carbonChat().userManager();
final ComponentPlayerResult<? extends CarbonPlayer> recipientResult = CarbonChatProvider.carbonChat().server().userManager().carbonPlayer(serverPlayer.getUUID()).join(); final CarbonPlayer author = userManager.user(this.sender.getUUID()).join();
final CarbonPlayer recipient = userManager.user(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?
}
if (author.muted()) { if (author.muted()) {
return true; return true;
@@ -33,7 +33,6 @@ import java.util.stream.Stream;
import net.draycia.carbon.common.command.CarbonCommand; import net.draycia.carbon.common.command.CarbonCommand;
import net.draycia.carbon.common.command.CommandSettings; import net.draycia.carbon.common.command.CommandSettings;
import net.draycia.carbon.common.command.Commander; 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.common.messages.CarbonMessages;
import net.draycia.carbon.fabric.CarbonChatFabric; import net.draycia.carbon.fabric.CarbonChatFabric;
import net.draycia.carbon.fabric.mixin.MessageSignatureCacheAccessor; import net.draycia.carbon.fabric.mixin.MessageSignatureCacheAccessor;
@@ -52,19 +51,16 @@ public class DeleteMessageCommand extends CarbonCommand {
final CarbonChatFabric carbonChat; final CarbonChatFabric carbonChat;
final CommandManager<Commander> commandManager; final CommandManager<Commander> commandManager;
final CarbonMessages messageService; final CarbonMessages messageService;
final PlayerSuggestions playerSuggestions;
@Inject @Inject
public DeleteMessageCommand( public DeleteMessageCommand(
final CarbonChatFabric carbonChat, final CarbonChatFabric carbonChat,
final CommandManager<Commander> commandManager, final CommandManager<Commander> commandManager,
final CarbonMessages messageService, final CarbonMessages messageService
final PlayerSuggestions playerSuggestions
) { ) {
this.carbonChat = carbonChat; this.carbonChat = carbonChat;
this.commandManager = commandManager; this.commandManager = commandManager;
this.messageService = messageService; this.messageService = messageService;
this.playerSuggestions = playerSuggestions;
} }
@Override @Override
@@ -48,7 +48,7 @@ public record FabricPlayerCommander(
@Override @Override
public CarbonPlayer carbonPlayer() { public CarbonPlayer carbonPlayer() {
return requireNonNull( 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!" "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.channels.ChannelRegistry;
import net.draycia.carbon.api.events.CarbonChatEvent; import net.draycia.carbon.api.events.CarbonChatEvent;
import net.draycia.carbon.api.users.CarbonPlayer; 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.api.util.KeyedRenderer;
import net.draycia.carbon.fabric.CarbonChatFabric; import net.draycia.carbon.fabric.CarbonChatFabric;
import net.draycia.carbon.fabric.callback.ChatCallback; import net.draycia.carbon.fabric.callback.ChatCallback;
@@ -60,12 +59,7 @@ public class FabricChatListener implements Consumer<ChatCallback.Chat> {
@Override @Override
public void accept(final ChatCallback.Chat chat) { public void accept(final ChatCallback.Chat chat) {
final var playerResult = this.carbonChatFabric.server().userManager().carbonPlayer(chat.sender().getUUID()).join(); final @Nullable CarbonPlayer sender = this.carbonChatFabric.userManager().user(chat.sender().getUUID()).join();
final @Nullable CarbonPlayer sender = playerResult.player();
if (sender == null) {
return;
}
var channel = requireNonNullElse(sender.selectedChannel(), this.channelRegistry.defaultValue()); var channel = requireNonNullElse(sender.selectedChannel(), this.channelRegistry.defaultValue());
final var originalMessage = chat.message(); final var originalMessage = chat.message();
@@ -123,9 +117,9 @@ public class FabricChatListener implements Consumer<ChatCallback.Chat> {
try { try {
final Optional<UUID> uuid = viewer.get(Identity.UUID); final Optional<UUID> uuid = viewer.get(Identity.UUID);
if (uuid.isPresent()) { 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 { } else {
renderedMessage = renderer.render(sender, viewer, renderedMessage, chatEvent.message()); renderedMessage = renderer.render(sender, viewer, renderedMessage, chatEvent.message());
} }
@@ -70,12 +70,7 @@ public class FabricChatPreviewListener implements ChatDecorator {
return CompletableFuture.completedFuture(component); return CompletableFuture.completedFuture(component);
} }
final var playerResult = this.carbonChat.server().userManager().carbonPlayer(serverPlayer.getUUID()).join(); final @Nullable CarbonPlayer sender = this.carbonChat.userManager().user(serverPlayer.getUUID()).join();
final @Nullable CarbonPlayer sender = playerResult.player();
if (sender == null) {
return CompletableFuture.completedFuture(component);
}
var channel = requireNonNullElse(sender.selectedChannel(), this.channelRegistry.defaultValue()); var channel = requireNonNullElse(sender.selectedChannel(), this.channelRegistry.defaultValue());
@@ -22,35 +22,58 @@ package net.draycia.carbon.fabric.listeners;
import com.google.inject.Inject; import com.google.inject.Inject;
import java.util.List; import java.util.List;
import net.draycia.carbon.common.config.ConfigFactory; 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.PacketSender;
import net.fabricmc.fabric.api.networking.v1.ServerPlayConnectionEvents; import net.fabricmc.fabric.api.networking.v1.ServerPlayConnectionEvents;
import net.minecraft.network.protocol.game.ClientboundCustomChatCompletionsPacket; import net.minecraft.network.protocol.game.ClientboundCustomChatCompletionsPacket;
import net.minecraft.server.MinecraftServer; import net.minecraft.server.MinecraftServer;
import net.minecraft.server.network.ServerGamePacketListenerImpl; 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.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable; import org.checkerframework.checker.nullness.qual.Nullable;
import org.checkerframework.framework.qual.DefaultQualifier; import org.checkerframework.framework.qual.DefaultQualifier;
@DefaultQualifier(NonNull.class) @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 @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.configFactory = configFactory;
this.profileCache = profileCache;
this.userManager = userManager;
} }
@Override @Override
public void onPlayReady(final ServerGamePacketListenerImpl handler, final PacketSender sender, final MinecraftServer server) { 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(); final @Nullable List<String> suggestions = this.configFactory.primaryConfig().customChatSuggestions();
if (suggestions == null || suggestions.isEmpty()) { if (suggestions == null || suggestions.isEmpty()) {
return; return;
} }
sender.sendPacket(new ClientboundCustomChatCompletionsPacket(ClientboundCustomChatCompletionsPacket.Action.SET, sender.sendPacket(new ClientboundCustomChatCompletionsPacket(ClientboundCustomChatCompletionsPacket.Action.SET, suggestions));
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.CarbonChatProvider;
import net.draycia.carbon.api.users.CarbonPlayer; 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.CarbonChatFabric;
import net.draycia.carbon.fabric.callback.PlayerStatusMessageEvents; import net.draycia.carbon.fabric.callback.PlayerStatusMessageEvents;
import net.draycia.carbon.fabric.chat.MessageRecipientFilter; 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")) @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) { 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> // 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 CarbonPlayer result = CarbonChatProvider.carbonChat().userManager().user(serverPlayer.getUUID()).join();
final MessageRecipientFilter filter = new MessageRecipientFilter(serverPlayer, result.player().selectedChannel()); final MessageRecipientFilter filter = new MessageRecipientFilter(serverPlayer, result.selectedChannel());
for (final ServerPlayer player : this.server.getPlayerList().getPlayers()) { for (final ServerPlayer player : this.server.getPlayerList().getPlayers()) {
if (filter.shouldFilterMessageTo(player)) { if (filter.shouldFilterMessageTo(player)) {
@@ -19,6 +19,7 @@
*/ */
package net.draycia.carbon.fabric.users; package net.draycia.carbon.fabric.users;
import com.google.inject.Provider;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Locale; 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.CarbonPlayerCommon;
import net.draycia.carbon.common.users.WrappedCarbonPlayer; import net.draycia.carbon.common.users.WrappedCarbonPlayer;
import net.draycia.carbon.fabric.CarbonChatFabric; import net.draycia.carbon.fabric.CarbonChatFabric;
import net.draycia.carbon.fabric.MinecraftServerHolder;
import net.kyori.adventure.audience.Audience; import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.audience.ForwardingAudience; import net.kyori.adventure.audience.ForwardingAudience;
import net.kyori.adventure.identity.Identity; import net.kyori.adventure.identity.Identity;
@@ -46,10 +48,12 @@ import org.checkerframework.framework.qual.DefaultQualifier;
public class CarbonPlayerFabric extends WrappedCarbonPlayer implements ForwardingAudience.Single { public class CarbonPlayerFabric extends WrappedCarbonPlayer implements ForwardingAudience.Single {
private final CarbonPlayerCommon carbonPlayerCommon; 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.carbonPlayerCommon = carbonPlayerCommon;
this.serverHolder = serverHolder;
this.carbonChatFabric = carbonChatFabric; this.carbonChatFabric = carbonChatFabric;
} }
@@ -58,9 +62,9 @@ public class CarbonPlayerFabric extends WrappedCarbonPlayer implements Forwardin
return this.player().orElseThrow(); return this.player().orElseThrow();
} }
private Optional<ServerPlayer> player() { public Optional<ServerPlayer> player() {
return Optional.ofNullable( return Optional.ofNullable(
this.carbonChatFabric.minecraftServer().getPlayerList() this.serverHolder.requireServer().getPlayerList()
.getPlayer(this.carbonPlayerCommon.uuid()) .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 player = this.player().orElse(null);
final @Nullable ServerPlayer otherPlayer = this.carbonChatFabric.minecraftServer() final @Nullable ServerPlayer otherPlayer = this.serverHolder.requireServer()
.getPlayerList().getPlayer(other.uuid()); .getPlayerList().getPlayer(other.uuid());
if (player == null || otherPlayer == null) { if (player == null || otherPlayer == null) {
@@ -130,7 +134,7 @@ public class CarbonPlayerFabric extends WrappedCarbonPlayer implements Forwardin
} }
final Optional<ServerPlayer> player = this.player(); final Optional<ServerPlayer> player = this.player();
final @Nullable ServerPlayer otherPlayer = this.carbonChatFabric.minecraftServer() final @Nullable ServerPlayer otherPlayer = this.serverHolder.requireServer()
.getPlayerList().getPlayer(other.uuid()); .getPlayerList().getPlayer(other.uuid());
if (player.isEmpty() || otherPlayer == null) { if (player.isEmpty() || otherPlayer == null) {
@@ -184,7 +188,7 @@ public class CarbonPlayerFabric extends WrappedCarbonPlayer implements Forwardin
@Override @Override
public String primaryGroup() { public String primaryGroup() {
if (!this.carbonChatFabric.luckPermsLoaded()) { if (!this.carbonChatFabric.get().luckPermsLoaded()) {
return "default"; return "default";
} }
@@ -193,7 +197,7 @@ public class CarbonPlayerFabric extends WrappedCarbonPlayer implements Forwardin
@Override @Override
public List<String> groups() { public List<String> groups() {
if (!this.carbonChatFabric.luckPermsLoaded()) { if (!this.carbonChatFabric.get().luckPermsLoaded()) {
return List.of("default"); 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": "*", "environment": "*",
"entrypoints": { "entrypoints": {
"main": [ "main": [
"net.draycia.carbon.fabric.CarbonChatFabric" "net.draycia.carbon.fabric.CarbonFabricBootstrap"
] ]
}, },
"mixins": [ "mixins": [
+14 -10
View File
@@ -12,18 +12,18 @@ plugins:
versions: versions:
indra: 3.0.1 indra: 3.0.1
licenser: 0.6.1 licenser: 0.6.1
shadow: 7.1.2 shadow: 8.1.0
adventure: 4.12.0 adventure: 4.13.0
cloud: 1.8.0 cloud: 1.8.3
cloudSponge: 1.8.0-SNAPSHOT cloudSponge: 1.8.0-SNAPSHOT
configurate: 4.1.2 configurate: 4.1.2
typesafeConfig: 1.4.1 typesafeConfig: 1.4.1
checkerQual: 3.28.0 checkerQual: 3.32.0
stylecheck: 0.1 stylecheck: 0.1
gson: 2.8.0 gson: 2.10
guava: 30.1-jre guava: 30.1-jre
bstats: 3.0.0 bstats: 3.0.0
paperApi: 1.19.3-R0.1-SNAPSHOT paperApi: 1.19.4-R0.1-SNAPSHOT
paperLib: 1.0.8-SNAPSHOT paperLib: 1.0.8-SNAPSHOT
kyoriEventApi: 5.0.0-SNAPSHOT kyoriEventApi: 5.0.0-SNAPSHOT
kyoriRegistry: 1.0.0-SNAPSHOT kyoriRegistry: 1.0.0-SNAPSHOT
@@ -32,9 +32,9 @@ versions:
guice: 5.1.0 guice: 5.1.0
velocityApi: 3.1.1 velocityApi: 3.1.1
geantyref: 1.3.11 geantyref: 1.3.11
fabricMinecraft: 1.19.3 fabricMinecraft: 1.19.4
fabricLoader: 0.14.12 fabricLoader: 0.14.17
adventurePlatformFabric: 5.6.1 adventurePlatformFabric: 5.8.0
luckPermsApi: 5.3 luckPermsApi: 5.3
essentialsx: 2.19.3 essentialsx: 2.19.3
discordsrv: 1.26.0 discordsrv: 1.26.0
@@ -185,6 +185,10 @@ dependencies:
group: com.google.inject group: com.google.inject
name: guice name: guice
version: { ref: guice } version: { ref: guice }
assistedInject:
group: com.google.inject.extensions
name: guice-assistedinject
version: { ref: guice }
jdbiCore: jdbiCore:
group: org.jdbi group: org.jdbi
@@ -297,7 +301,7 @@ dependencies:
name: indra-licenser-cadix name: indra-licenser-cadix
version: { ref: indra } version: { ref: indra }
shadow: shadow:
group: gradle.plugin.com.github.johnrengelman group: com.github.johnrengelman
name: shadow name: shadow
version: { ref: shadow } version: { ref: shadow }
licenser: licenser:
Binary file not shown.
+1 -1
View File
@@ -1,6 +1,6 @@
distributionBase=GRADLE_USER_HOME distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists 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 networkTimeout=10000
zipStoreBase=GRADLE_USER_HOME zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists zipStorePath=wrapper/dists
+1 -1
View File
@@ -34,7 +34,7 @@ tasks {
relocateDependency("io.leangen.geantyref") relocateDependency("io.leangen.geantyref")
} }
runServer { 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.Inject;
import com.google.inject.Injector; import com.google.inject.Injector;
import com.google.inject.Provider;
import com.google.inject.Singleton;
import github.scarsz.discordsrv.DiscordSRV; import github.scarsz.discordsrv.DiscordSRV;
import java.nio.file.Path; import java.nio.file.Path;
import java.util.Set; import java.util.Set;
import java.util.UUID; import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.CompletableFuture;
import net.draycia.carbon.api.CarbonChat;
import net.draycia.carbon.api.CarbonServer; 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.events.CarbonEventHandler;
import net.draycia.carbon.api.users.UserManager; import net.draycia.carbon.common.CarbonChatInternal;
import net.draycia.carbon.common.ForCarbon; import net.draycia.carbon.common.DataDirectory;
import net.draycia.carbon.common.PeriodicTasks;
import net.draycia.carbon.common.channels.CarbonChannelRegistry; 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.messages.CarbonMessages;
import net.draycia.carbon.common.messaging.MessagingManager; import net.draycia.carbon.common.messaging.MessagingManager;
import net.draycia.carbon.common.users.CarbonPlayerCommon; import net.draycia.carbon.common.users.ProfileCache;
import net.draycia.carbon.common.util.CloudUtils; import net.draycia.carbon.common.users.ProfileResolver;
import net.draycia.carbon.common.util.ListenerUtils;
import net.draycia.carbon.common.util.PlayerUtils;
import net.draycia.carbon.paper.hooks.DSRVChatHook; import net.draycia.carbon.paper.hooks.DSRVChatHook;
import net.draycia.carbon.paper.listeners.DiscordMessageListener; import net.draycia.carbon.paper.listeners.DiscordMessageListener;
import net.draycia.carbon.paper.listeners.PaperChatListener; import net.draycia.carbon.paper.listeners.PaperChatListener;
import net.draycia.carbon.paper.listeners.PaperPlayerJoinListener; 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.audience.Audience;
import net.kyori.adventure.text.Component; import net.kyori.adventure.text.Component;
import net.kyori.moonshine.message.IMessageRenderer; import net.kyori.moonshine.message.IMessageRenderer;
import ninja.egg82.messenger.services.PacketService;
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.bstats.bukkit.Metrics; import org.bstats.bukkit.Metrics;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.event.Listener; import org.bukkit.event.Listener;
import org.bukkit.plugin.java.JavaPlugin; 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.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.checkerframework.framework.qual.DefaultQualifier; import org.checkerframework.framework.qual.DefaultQualifier;
@DefaultQualifier(NonNull.class) @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( private static final Set<Class<? extends Listener>> LISTENER_CLASSES = Set.of(
PaperChatListener.class, PaperChatListener.class,
PaperPlayerJoinListener.class PaperPlayerJoinListener.class
); );
private static final int BSTATS_PLUGIN_ID = 8720; 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; private final JavaPlugin plugin;
CarbonChatPaper() {
}
@Inject @Inject
private void onLoad( private CarbonChatPaper(
final Injector injector, final Injector injector,
final JavaPlugin plugin, final JavaPlugin plugin,
final CarbonMessages carbonMessages, final CarbonMessages carbonMessages,
final ChannelRegistry channelRegistry, final CarbonEventHandler eventHandler,
final CarbonChannelRegistry channelRegistry,
final Provider<MessagingManager> messagingManager,
final CarbonServer carbonServer, final CarbonServer carbonServer,
final UserManager<CarbonPlayerCommon> userManager, final PaperUserManager userManager,
@ForCarbon final Path dataDirectory @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"); super(
this.injector = injector; injector, LogManager.getLogger("CarbonChat"), dataDirectory,
periodicTasks,
profileCache,
profileResolver,
userManager,
commandExecutor,
carbonServer,
carbonMessages,
eventHandler,
channelRegistry,
renderer,
messagingManager
);
this.plugin = plugin; this.plugin = plugin;
this.carbonMessages = carbonMessages;
this.channelRegistry = channelRegistry;
this.carbonServer = carbonServer;
this.userManager = userManager;
this.dataDirectory = dataDirectory;
this.packetService();
} }
void onEnable() { void onEnable() {
final Metrics metrics = new Metrics(this.plugin, BSTATS_PLUGIN_ID); final Metrics metrics = new Metrics(this.plugin, BSTATS_PLUGIN_ID);
this.init();
this.packetService();
for (final Class<? extends Listener> listenerClass : LISTENER_CLASSES) { for (final Class<? extends Listener> listenerClass : LISTENER_CLASSES) {
this.plugin.getServer().getPluginManager().registerEvents( this.plugin.getServer().getPluginManager().registerEvents(
this.injector.getInstance(listenerClass), this.injector().getInstance(listenerClass),
this.plugin 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(); this.discoverDiscordHooks();
} }
private void discoverDiscordHooks() { private void discoverDiscordHooks() {
if (Bukkit.getPluginManager().isPluginEnabled("EssentialsDiscord")) { 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); Bukkit.getPluginManager().registerEvents(discordMessageListener, this.plugin);
discordMessageListener.init(); discordMessageListener.init();
} }
if (Bukkit.getPluginManager().isPluginEnabled("DiscordSRV")) { 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()); DiscordSRV.getPlugin().getPluginHooks().add(new DSRVChatHook());
} }
} }
void onDisable() { void onDisable() {
PlayerUtils.saveLoggedInPlayers(this.carbonServer, this.userManager).forEach(CompletableFuture::join); this.shutdown();
}
@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);
} }
public static boolean papiLoaded() { public static boolean papiLoaded() {
@@ -22,25 +22,30 @@ package net.draycia.carbon.paper;
import cloud.commandframework.CommandManager; import cloud.commandframework.CommandManager;
import cloud.commandframework.brigadier.CloudBrigadierManager; import cloud.commandframework.brigadier.CloudBrigadierManager;
import cloud.commandframework.bukkit.parsers.PlayerArgument; import cloud.commandframework.bukkit.parsers.PlayerArgument;
import cloud.commandframework.execution.AsynchronousCommandExecutionCoordinator;
import cloud.commandframework.paper.PaperCommandManager; import cloud.commandframework.paper.PaperCommandManager;
import com.google.inject.AbstractModule; import com.google.inject.AbstractModule;
import com.google.inject.Injector; import com.google.inject.Injector;
import com.google.inject.Provides; import com.google.inject.Provides;
import com.google.inject.Singleton; import com.google.inject.Singleton;
import com.google.inject.TypeLiteral;
import java.nio.file.Path; import java.nio.file.Path;
import net.draycia.carbon.api.CarbonChat; import net.draycia.carbon.api.CarbonChat;
import net.draycia.carbon.api.CarbonServer; import net.draycia.carbon.api.CarbonServer;
import net.draycia.carbon.api.users.UserManager;
import net.draycia.carbon.api.util.SourcedAudience; import net.draycia.carbon.api.util.SourcedAudience;
import net.draycia.carbon.common.CarbonCommonModule; 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.Commander;
import net.draycia.carbon.common.command.argument.PlayerSuggestions; 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.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.common.util.CloudUtils;
import net.draycia.carbon.paper.command.PaperCommander; import net.draycia.carbon.paper.command.PaperCommander;
import net.draycia.carbon.paper.command.PaperPlayerCommander; import net.draycia.carbon.paper.command.PaperPlayerCommander;
import net.draycia.carbon.paper.messages.PaperMessageRenderer; import net.draycia.carbon.paper.messages.PaperMessageRenderer;
import net.draycia.carbon.paper.users.PaperProfileResolver;
import net.kyori.adventure.audience.Audience; import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.text.Component; import net.kyori.adventure.text.Component;
import net.kyori.moonshine.message.IMessageRenderer; 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 Logger logger = LogManager.getLogger("CarbonChat");
private final CarbonPaperBootstrap bootstrap; private final CarbonPaperBootstrap bootstrap;
private final CarbonChat carbonChat;
CarbonChatPaperModule( CarbonChatPaperModule(final CarbonPaperBootstrap bootstrap) {
final CarbonPaperBootstrap bootstrap,
final CarbonChat carbonChat
) {
this.bootstrap = bootstrap; this.bootstrap = bootstrap;
this.carbonChat = carbonChat;
} }
@Provides @Provides
@Singleton @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; final PaperCommandManager<Commander> commandManager;
try { try {
commandManager = new PaperCommandManager<>( commandManager = new PaperCommandManager<>(
this.bootstrap, this.bootstrap,
AsynchronousCommandExecutionCoordinator.<Commander>builder().build(), executionCoordinatorHolder.executionCoordinator(),
commandSender -> { commandSender -> {
if (commandSender instanceof Player player) { if (commandSender instanceof Player player) {
return new PaperPlayerCommander(server, player); return new PaperPlayerCommander(userManager, player);
} }
return PaperCommander.from(commandSender); return PaperCommander.from(commandSender);
}, },
@@ -116,21 +116,20 @@ public final class CarbonChatPaperModule extends AbstractModule {
return injector.getInstance(PaperMessageRenderer.class); return injector.getInstance(PaperMessageRenderer.class);
} }
@Provides
public CarbonChat carbonChat() {
return this.carbonChat;
}
@Override @Override
public void configure() { public void configure() {
this.install(new CarbonCommonModule()); this.install(new CarbonCommonModule());
this.bind(CarbonChat.class).to(CarbonChatPaper.class);
this.bind(JavaPlugin.class).toInstance(this.bootstrap); this.bind(JavaPlugin.class).toInstance(this.bootstrap);
this.bind(Server.class).toInstance(this.bootstrap.getServer()); this.bind(Server.class).toInstance(this.bootstrap.getServer());
this.bind(Logger.class).toInstance(this.logger); 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(CarbonServer.class).to(CarbonServerPaper.class);
this.bind(PlayerSuggestions.class).toInstance(new PlayerArgument.PlayerParser<Commander>()::suggestions); 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; package net.draycia.carbon.paper;
import com.google.inject.Guice; import com.google.inject.Guice;
import com.google.inject.Injector;
import io.papermc.lib.PaperLib; import io.papermc.lib.PaperLib;
import java.util.logging.Level; import java.util.logging.Level;
import net.draycia.carbon.api.CarbonChatProvider; import net.draycia.carbon.api.CarbonChatProvider;
@@ -45,10 +44,9 @@ public final class CarbonPaperBootstrap extends JavaPlugin {
return; return;
} }
this.carbonChat = new CarbonChatPaper(); this.carbonChat = Guice.createInjector(new CarbonChatPaperModule(this))
final Injector injector = Guice.createInjector(new CarbonChatPaperModule(this, this.carbonChat)); .getInstance(CarbonChatPaper.class);
CarbonChatProvider.register(this.carbonChat); CarbonChatProvider.register(this.carbonChat);
injector.injectMembers(this.carbonChat);
} }
// null = success // null = success
@@ -21,23 +21,16 @@ package net.draycia.carbon.paper;
import com.google.inject.Inject; import com.google.inject.Inject;
import com.google.inject.Singleton; import com.google.inject.Singleton;
import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.UUID; import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import net.draycia.carbon.api.CarbonServer; import net.draycia.carbon.api.CarbonServer;
import net.draycia.carbon.api.users.CarbonPlayer; 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.api.users.UserManager;
import net.draycia.carbon.common.users.CarbonPlayerCommon;
import net.draycia.carbon.paper.users.CarbonPlayerPaper; import net.draycia.carbon.paper.users.CarbonPlayerPaper;
import net.kyori.adventure.audience.Audience; import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.audience.ForwardingAudience; import net.kyori.adventure.audience.ForwardingAudience;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.Server; import org.bukkit.Server;
import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.checkerframework.framework.qual.DefaultQualifier; import org.checkerframework.framework.qual.DefaultQualifier;
@Singleton @Singleton
@@ -45,12 +38,12 @@ import org.checkerframework.framework.qual.DefaultQualifier;
public final class CarbonServerPaper implements CarbonServer, ForwardingAudience.Single { public final class CarbonServerPaper implements CarbonServer, ForwardingAudience.Single {
private final Server server; private final Server server;
private final UserManager<CarbonPlayerPaper> userManager; private final PaperUserManager userManager;
@Inject @Inject
private CarbonServerPaper(final Server server, final UserManager<CarbonPlayerCommon> userManager) { private CarbonServerPaper(final Server server, final PaperUserManager userManager) {
this.server = server; this.server = server;
this.userManager = new PaperUserManager(userManager); this.userManager = userManager;
} }
@Override @Override
@@ -65,17 +58,10 @@ public final class CarbonServerPaper implements CarbonServer, ForwardingAudience
@Override @Override
public List<? extends CarbonPlayer> players() { public List<? extends CarbonPlayer> players() {
final var players = new ArrayList<CarbonPlayer>(); return this.server.getOnlinePlayers().stream()
.map(bukkit -> this.userManager.user(bukkit.getUniqueId()).getNow(null))
for (final var player : this.server.getOnlinePlayers()) { .filter(Objects::nonNull)
final ComponentPlayerResult<CarbonPlayerPaper> result = this.userManager.carbonPlayer(player.getUniqueId()).join(); .toList();
if (result.player() != null) {
players.add(result.player());
}
}
return players;
} }
@Override @Override
@@ -83,24 +69,4 @@ public final class CarbonServerPaper implements CarbonServer, ForwardingAudience
return this.userManager; 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; package net.draycia.carbon.paper;
import java.util.UUID; import com.google.inject.Inject;
import java.util.concurrent.CompletableFuture; import com.google.inject.Singleton;
import net.draycia.carbon.api.users.ComponentPlayerResult; import net.draycia.carbon.common.users.Backing;
import net.draycia.carbon.api.users.UserManager;
import net.draycia.carbon.common.users.CarbonPlayerCommon; 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.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.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.checkerframework.framework.qual.DefaultQualifier; import org.checkerframework.framework.qual.DefaultQualifier;
@DefaultQualifier(NonNull.class) @DefaultQualifier(NonNull.class)
public class PaperUserManager implements UserManager<CarbonPlayerPaper>, SaveOnChange { @Singleton
public final class PaperUserManager extends PlatformUserManager<CarbonPlayerPaper> {
protected final UserManager<CarbonPlayerCommon> proxiedUserManager; @Inject
private PaperUserManager(final @Backing UserManagerInternal<CarbonPlayerCommon> backingManager) {
public PaperUserManager(final UserManager<CarbonPlayerCommon> proxiedUserManager) { super(backingManager);
this.proxiedUserManager = proxiedUserManager;
} }
@Override @Override
public CompletableFuture<ComponentPlayerResult<CarbonPlayerPaper>> carbonPlayer(final UUID uuid) { protected CarbonPlayerPaper wrap(final CarbonPlayerCommon common) {
return this.proxiedUserManager.carbonPlayer(uuid).thenApply(result -> { return new CarbonPlayerPaper(common);
if (result.player() == null) {
return new ComponentPlayerResult<>(null, result.reason());
}
return new ComponentPlayerResult<>(new CarbonPlayerPaper(result.player()), result.reason());
});
} }
@Override @Override
public CompletableFuture<ComponentPlayerResult<CarbonPlayerPaper>> savePlayer(final CarbonPlayerPaper player) { protected void updateTransientLoadedStatus(final CarbonPlayerPaper wrapped) {
return this.proxiedUserManager.savePlayer(player.carbonPlayerCommon()).thenApply(result -> { wrapped.carbonPlayerCommon().markTransientLoaded(wrapped.bukkitPlayer() == null);
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;
} }
} }
@@ -19,8 +19,8 @@
*/ */
package net.draycia.carbon.paper.command; 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.CarbonPlayer;
import net.draycia.carbon.api.users.UserManager;
import net.draycia.carbon.common.command.PlayerCommander; import net.draycia.carbon.common.command.PlayerCommander;
import net.kyori.adventure.audience.Audience; import net.kyori.adventure.audience.Audience;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
@@ -32,7 +32,7 @@ import static java.util.Objects.requireNonNull;
@DefaultQualifier(NonNull.class) @DefaultQualifier(NonNull.class)
public record PaperPlayerCommander( public record PaperPlayerCommander(
CarbonServer server, UserManager<?> userManager,
Player player Player player
) implements PlayerCommander, PaperCommander { ) implements PlayerCommander, PaperCommander {
@@ -48,7 +48,7 @@ public record PaperPlayerCommander(
@Override @Override
public CarbonPlayer carbonPlayer() { 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 @Override
@@ -59,19 +59,17 @@ public class DiscordMessageListener implements Listener {
return; 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.selectedChannel();
var channel = result.player().selectedChannel();
if (channel == null) { if (channel == null) {
channel = this.carbonChat.channelRegistry().defaultValue(); channel = this.carbonChat.channelRegistry().defaultValue();
}
final var messageType = this.channelMessageTypes.get(channel.key());
event.setType(messageType);
} }
final var messageType = this.channelMessageTypes.get(channel.key());
event.setType(messageType);
} }
@EventHandler @EventHandler
@@ -66,10 +66,9 @@ public final class PaperChatListener implements Listener {
@EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST) @EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST)
public void onPaperChat(final @NonNull AsyncChatEvent event) { public void onPaperChat(final @NonNull AsyncChatEvent event) {
final var playerResult = this.carbonChat.server().userManager().carbonPlayer(event.getPlayer().getUniqueId()).join(); final @Nullable CarbonPlayer sender = this.carbonChat.userManager().user(event.getPlayer().getUniqueId()).join();
final @Nullable CarbonPlayer sender = playerResult.player();
if (sender == null || event.viewers().isEmpty()) { if (event.viewers().isEmpty()) {
return; return;
} }
@@ -126,10 +125,7 @@ public final class PaperChatListener implements Listener {
final Audience recipientViewer; final Audience recipientViewer;
if (recipientUUID.isPresent()) { if (recipientUUID.isPresent()) {
final var recipientResult = this.carbonChat.server().userManager().carbonPlayer(viewer.get(Identity.UUID).orElseThrow()).join(); recipientViewer = this.carbonChat.userManager().user(viewer.get(Identity.UUID).orElseThrow()).join();
final @Nullable CarbonPlayer recipient = recipientResult.player();
recipientViewer = requireNonNullElse(recipient, viewer);
} else { } else {
recipientViewer = viewer; recipientViewer = viewer;
} }
@@ -21,11 +21,9 @@ package net.draycia.carbon.paper.listeners;
import com.google.inject.Inject; import com.google.inject.Inject;
import java.util.Optional; import java.util.Optional;
import net.draycia.carbon.api.CarbonChat; import net.draycia.carbon.common.users.ProfileCache;
import net.draycia.carbon.api.users.UserManager; import net.draycia.carbon.paper.PaperUserManager;
import net.draycia.carbon.common.users.CarbonPlayerCommon; import org.apache.logging.log4j.Logger;
import net.draycia.carbon.common.util.PlayerUtils;
import net.draycia.carbon.paper.users.CarbonPlayerPaper;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler; import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority; import org.bukkit.event.EventPriority;
@@ -38,41 +36,45 @@ import org.checkerframework.framework.qual.DefaultQualifier;
@DefaultQualifier(NonNull.class) @DefaultQualifier(NonNull.class)
public class PaperPlayerJoinListener implements Listener { public class PaperPlayerJoinListener implements Listener {
private final CarbonChat carbonChat; private final Logger logger;
private final UserManager<CarbonPlayerCommon> userManager; private final ProfileCache profileCache;
private final PaperUserManager userManager;
@Inject @Inject
public PaperPlayerJoinListener( public PaperPlayerJoinListener(
final CarbonChat carbonChat, final Logger logger,
final UserManager<CarbonPlayerCommon> userManager final ProfileCache profileCache,
final PaperUserManager userManager
) { ) {
this.carbonChat = carbonChat; this.logger = logger;
this.profileCache = profileCache;
this.userManager = userManager; 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) @EventHandler(priority = EventPriority.HIGH)
public void onJoin(final PlayerJoinEvent event) { public void onJoin(final PlayerJoinEvent event) {
this.carbonChat.server().userManager().carbonPlayer(event.getPlayer().getUniqueId()).thenAccept(result -> { this.userManager.user(event.getPlayer().getUniqueId()).thenAccept(result -> {
if (result.player() == null) { Optional.ofNullable(result.displayName()).ifPresent(displayName -> {
return;
}
Optional.ofNullable(result.player().displayName()).ifPresent(displayName -> {
final Player player = event.getPlayer(); final Player player = event.getPlayer();
player.displayName(displayName); player.displayName(displayName);
player.playerListName(displayName); player.playerListName(displayName);
}); });
}).exceptionally(thr -> {
this.logger.warn("Exception handling player join", thr);
return null;
}); });
} }
@EventHandler(priority = EventPriority.HIGH) @EventHandler(priority = EventPriority.HIGH)
public void onQuit(final PlayerQuitEvent event) { public void onQuit(final PlayerQuitEvent event) {
this.carbonChat.server().userManager().carbonPlayer(event.getPlayer().getUniqueId()).thenAccept(result -> { this.userManager.loggedOut(event.getPlayer().getUniqueId()).exceptionally(thr -> {
if (result.player() == null) { this.logger.warn("Exception saving data for player " + event.getPlayer().getName() + " with uuid " + event.getPlayer().getUniqueId());
return; return null;
}
PlayerUtils.saveAndInvalidatePlayer(this.carbonChat.server(), this.userManager, (CarbonPlayerPaper) result.player());
}); });
} }
@@ -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();
}
}