cross-server whispers & cross-server player name tab completion in commands

This commit is contained in:
Jason Penilla authored and Jason committed 2023-08-08 09:23:57 -07:00
1 parent 18f94a31c9
commit b46f6c6016
27 files changed
+1895 -231

No files matched your search

+2
View File
@@ -35,4 +35,6 @@
checks="MissingJavadocPackage"/> checks="MissingJavadocPackage"/>
<suppress files="src[\\/]main[\\/]java[\\/]net[\\/]draycia[\\/]carbon[\\/](paper|sponge|common|velocity|fabric)[\\/].*" <suppress files="src[\\/]main[\\/]java[\\/]net[\\/]draycia[\\/]carbon[\\/](paper|sponge|common|velocity|fabric)[\\/].*"
checks="MissingJavadocType"/> checks="MissingJavadocType"/>
<suppress files="src[\\/]main[\\/]java[\\/]com[\\/]google[\\/]inject[\\/]assistedinject[\\/].*"
checks="[a-zA-Z0-9]*"/>
</suppressions> </suppressions>
+1
View File
@@ -82,3 +82,4 @@ gradle-app.setting
.DS_Store .DS_Store
**/run/ **/run/
**/run2/
@@ -23,6 +23,7 @@ license {
exclude("net/draycia/carbon/common/command/argument/OptionValueParser.java") exclude("net/draycia/carbon/common/command/argument/OptionValueParser.java")
exclude("net/draycia/carbon/common/messages/PrefixedDelegateIterator.java") exclude("net/draycia/carbon/common/messages/PrefixedDelegateIterator.java")
exclude("net/draycia/carbon/common/messages/StandardPlaceholderResolverStrategyButDifferent.java") exclude("net/draycia/carbon/common/messages/StandardPlaceholderResolverStrategyButDifferent.java")
exclude("com/google/inject/assistedinject")
} }
tasks { tasks {
File diff suppressed because it is too large. Load diff
@@ -37,6 +37,7 @@ import net.draycia.carbon.common.command.commands.ExecutionCoordinatorHolder;
import net.draycia.carbon.common.listeners.Listener; import net.draycia.carbon.common.listeners.Listener;
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.messaging.packets.PacketFactory;
import net.draycia.carbon.common.users.ProfileCache; import net.draycia.carbon.common.users.ProfileCache;
import net.draycia.carbon.common.users.ProfileResolver; import net.draycia.carbon.common.users.ProfileResolver;
import net.draycia.carbon.common.users.UserManagerInternal; import net.draycia.carbon.common.users.UserManagerInternal;
@@ -138,6 +139,11 @@ public abstract class CarbonChatInternal<C extends CarbonPlayer> implements Carb
} }
protected void shutdown() { protected void shutdown() {
this.messagingManager.get().withPacketService(packetService -> {
packetService.queuePacket(this.injector.getInstance(PacketFactory.class).clearLocalPlayersPacket());
packetService.flushQueue(); // todo remove
});
// this.messagingManager.get().onShutdown(); // todo fix this taking so long
ConcurrentUtil.shutdownExecutor(this.periodicTasks, TimeUnit.MILLISECONDS, 500); ConcurrentUtil.shutdownExecutor(this.periodicTasks, TimeUnit.MILLISECONDS, 500);
this.profileCache.save(); this.profileCache.save();
this.profileResolver.shutdown(); this.profileResolver.shutdown();
@@ -21,11 +21,16 @@ package net.draycia.carbon.common;
import com.google.inject.AbstractModule; import com.google.inject.AbstractModule;
import com.google.inject.Injector; import com.google.inject.Injector;
import com.google.inject.Module;
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 com.google.inject.assistedinject.FactoryModuleBuilder; import com.google.inject.assistedinject.FactoryModuleBuilder;
import com.google.inject.assistedinject.FactoryProvider3;
import com.google.inject.multibindings.Multibinder; import com.google.inject.multibindings.Multibinder;
import io.leangen.geantyref.TypeToken; import io.leangen.geantyref.TypeToken;
import java.lang.invoke.MethodHandles;
import java.util.Objects; import java.util.Objects;
import java.util.UUID; import java.util.UUID;
import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledExecutorService;
@@ -33,6 +38,7 @@ import net.draycia.carbon.api.channels.ChannelRegistry;
import net.draycia.carbon.api.event.CarbonEventHandler; import net.draycia.carbon.api.event.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.ArgumentFactory;
import net.draycia.carbon.common.command.argument.PlayerSuggestions;
import net.draycia.carbon.common.command.commands.ExecutionCoordinatorHolder; 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.event.CarbonEventHandlerImpl; import net.draycia.carbon.common.event.CarbonEventHandlerImpl;
@@ -58,11 +64,13 @@ import net.draycia.carbon.common.messages.placeholders.UUIDPlaceholderResolver;
import net.draycia.carbon.common.messaging.packets.PacketFactory; import net.draycia.carbon.common.messaging.packets.PacketFactory;
import net.draycia.carbon.common.users.Backing; 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.NetworkUsers;
import net.draycia.carbon.common.users.UserManagerInternal; 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.draycia.carbon.common.util.ConcurrentUtil;
import net.draycia.carbon.common.util.Exceptions;
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;
@@ -130,9 +138,10 @@ public final class CarbonCommonModule extends AbstractModule {
@Override @Override
protected void configure() { protected void configure() {
this.install(new FactoryModuleBuilder().build(ArgumentFactory.class)); this.install(new FactoryModuleBuilder().build(ArgumentFactory.class));
this.install(new FactoryModuleBuilder().build(PacketFactory.class)); this.install(factoryModule(PacketFactory.class));
this.bind(ChannelRegistry.class).to(CarbonChannelRegistry.class); this.bind(ChannelRegistry.class).to(CarbonChannelRegistry.class);
this.bind(CarbonEventHandler.class).to(CarbonEventHandlerImpl.class); this.bind(CarbonEventHandler.class).to(CarbonEventHandlerImpl.class);
this.bind(PlayerSuggestions.class).to(NetworkUsers.class);
final Multibinder<Listener> listeners = Multibinder.newSetBinder(this.binder(), Listener.class); final Multibinder<Listener> listeners = Multibinder.newSetBinder(this.binder(), Listener.class);
listeners.addBinding().to(DeafenHandler.class); listeners.addBinding().to(DeafenHandler.class);
@@ -145,4 +154,23 @@ public final class CarbonCommonModule extends AbstractModule {
listeners.addBinding().to(RadiusListener.class); listeners.addBinding().to(RadiusListener.class);
} }
// Helper to create a FactoryProvider3 module
private static <T> Module factoryModule(final Class<T> factoryInterface) {
return new AbstractModule() {
@Override
protected void configure() {
try {
final Provider<T> factoryProvider = new FactoryProvider3<>(
com.google.inject.Key.get(TypeLiteral.get(factoryInterface)),
null,
MethodHandles.privateLookupIn(factoryInterface, MethodHandles.lookup())
);
this.binder().bind(factoryInterface).toProvider(factoryProvider);
} catch (final Exception e) {
throw Exceptions.rethrow(e);
}
}
};
}
} }
@@ -26,24 +26,16 @@ import cloud.commandframework.minecraft.extras.RichDescription;
import com.google.inject.Inject; 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.event.events.CarbonPrivateChatEvent;
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.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.config.ConfigFactory; import net.draycia.carbon.common.config.ConfigFactory;
import net.draycia.carbon.common.event.events.CarbonPrivateChatEventImpl;
import net.draycia.carbon.common.messages.CarbonMessages; import net.draycia.carbon.common.messages.CarbonMessages;
import net.draycia.carbon.common.util.CloudUtils;
import net.kyori.adventure.key.Key; import net.kyori.adventure.key.Key;
import net.kyori.adventure.sound.Sound;
import net.kyori.adventure.text.Component;
import org.checkerframework.checker.nullness.qual.MonotonicNonNull; 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)
@@ -53,18 +45,21 @@ public class ContinueCommand extends CarbonCommand {
final CommandManager<Commander> commandManager; final CommandManager<Commander> commandManager;
final CarbonMessages carbonMessages; final CarbonMessages carbonMessages;
final ConfigFactory configFactory; final ConfigFactory configFactory;
private final WhisperCommand.WhisperHandler whisper;
@Inject @Inject
public ContinueCommand( public ContinueCommand(
final CarbonChat carbonChat, final CarbonChat carbonChat,
final CommandManager<Commander> commandManager, final CommandManager<Commander> commandManager,
final CarbonMessages carbonMessages, final CarbonMessages carbonMessages,
final ConfigFactory configFactory final ConfigFactory configFactory,
final WhisperCommand.WhisperHandler whisper
) { ) {
this.carbonChat = carbonChat; this.carbonChat = carbonChat;
this.commandManager = commandManager; this.commandManager = commandManager;
this.carbonMessages = carbonMessages; this.carbonMessages = carbonMessages;
this.configFactory = configFactory; this.configFactory = configFactory;
this.whisper = whisper;
} }
@Override @Override
@@ -104,51 +99,7 @@ public class ContinueCommand extends CarbonCommand {
final @MonotonicNonNull CarbonPlayer recipient = this.carbonChat final @MonotonicNonNull CarbonPlayer recipient = this.carbonChat
.userManager().user(whisperTarget).join(); .userManager().user(whisperTarget).join();
if (sender.equals(recipient)) { this.whisper.whisper(sender, recipient, message);
this.carbonMessages.whisperSelfError(sender, CarbonPlayer.renderName(sender));
return;
}
if (!recipient.online() || !sender.awareOf(recipient) && !sender.hasPermission("carbon.whisper.vanished")) {
final var rawNameInput = CloudUtils.rawInputByMatchingName(handler.getRawInput(), recipient);
final var exception = new CarbonPlayerArgument.CarbonPlayerParseException(rawNameInput, handler);
this.carbonMessages.errorCommandArgumentParsing(sender, CloudUtils.message(exception));
return;
}
if (sender.ignoring(recipient)) {
this.carbonMessages.whisperIgnoringTarget(sender, CarbonPlayer.renderName(recipient));
return;
}
if (recipient.ignoring(sender)) {
this.carbonMessages.whisperTargetIgnoring(sender, CarbonPlayer.renderName(recipient));
return;
}
final Component senderName = CarbonPlayer.renderName(sender);
final Component recipientName = CarbonPlayer.renderName(recipient);
final CarbonPrivateChatEvent privateChatEvent = new CarbonPrivateChatEventImpl(sender, recipient, Component.text(message));
this.carbonChat.eventHandler().emit(privateChatEvent);
if (privateChatEvent.cancelled()) {
this.carbonMessages.whisperError(sender, CarbonPlayer.renderName(sender), CarbonPlayer.renderName(recipient));
return;
}
this.carbonMessages.whisperSender(new SourcedAudience(sender, sender), senderName, recipientName, privateChatEvent.message());
this.carbonMessages.whisperRecipient(new SourcedAudience(sender, recipient), senderName, recipientName, privateChatEvent.message());
this.carbonMessages.whisperConsoleLog(this.carbonChat.server().console(), senderName, recipientName, privateChatEvent.message());
final @Nullable Sound messageSound = this.configFactory.primaryConfig().messageSound();
if (messageSound != null) {
recipient.playSound(messageSound);
}
sender.lastWhisperTarget(recipient.uuid());
sender.whisperReplyTarget(recipient.uuid());
recipient.whisperReplyTarget(sender.uuid());
}) })
.build(); .build();
@@ -26,21 +26,14 @@ import cloud.commandframework.minecraft.extras.RichDescription;
import com.google.inject.Inject; 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.event.events.CarbonPrivateChatEvent;
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.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.config.ConfigFactory; import net.draycia.carbon.common.config.ConfigFactory;
import net.draycia.carbon.common.event.events.CarbonPrivateChatEventImpl;
import net.draycia.carbon.common.messages.CarbonMessages; import net.draycia.carbon.common.messages.CarbonMessages;
import net.draycia.carbon.common.util.CloudUtils;
import net.kyori.adventure.key.Key; import net.kyori.adventure.key.Key;
import net.kyori.adventure.sound.Sound;
import net.kyori.adventure.text.Component;
import org.checkerframework.checker.nullness.qual.MonotonicNonNull; 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.checker.nullness.qual.Nullable;
@@ -53,18 +46,21 @@ public class ReplyCommand extends CarbonCommand {
final CommandManager<Commander> commandManager; final CommandManager<Commander> commandManager;
final CarbonMessages carbonMessages; final CarbonMessages carbonMessages;
final ConfigFactory configFactory; final ConfigFactory configFactory;
private final WhisperCommand.WhisperHandler whisper;
@Inject @Inject
public ReplyCommand( public ReplyCommand(
final CarbonChat carbonChat, final CarbonChat carbonChat,
final CommandManager<Commander> commandManager, final CommandManager<Commander> commandManager,
final CarbonMessages carbonMessages, final CarbonMessages carbonMessages,
final ConfigFactory configFactory final ConfigFactory configFactory,
final WhisperCommand.WhisperHandler whisper
) { ) {
this.carbonChat = carbonChat; this.carbonChat = carbonChat;
this.commandManager = commandManager; this.commandManager = commandManager;
this.carbonMessages = carbonMessages; this.carbonMessages = carbonMessages;
this.configFactory = configFactory; this.configFactory = configFactory;
this.whisper = whisper;
} }
@Override @Override
@@ -103,51 +99,7 @@ public class ReplyCommand extends CarbonCommand {
final @MonotonicNonNull CarbonPlayer recipient = this.carbonChat.userManager().user(replyTarget).join(); final @MonotonicNonNull CarbonPlayer recipient = this.carbonChat.userManager().user(replyTarget).join();
if (sender.equals(recipient)) { this.whisper.whisper(sender, recipient, message);
this.carbonMessages.whisperSelfError(sender, CarbonPlayer.renderName(sender));
return;
}
if (!recipient.online() || !sender.awareOf(recipient) && !sender.hasPermission("carbon.whisper.vanished")) {
final var rawNameInput = CloudUtils.rawInputByMatchingName(handler.getRawInput(), recipient);
final var exception = new CarbonPlayerArgument.CarbonPlayerParseException(rawNameInput, handler);
this.carbonMessages.errorCommandArgumentParsing(sender, CloudUtils.message(exception));
return;
}
if (sender.ignoring(recipient)) {
this.carbonMessages.whisperIgnoringTarget(sender, CarbonPlayer.renderName(recipient));
return;
}
if (recipient.ignoring(sender)) {
this.carbonMessages.whisperTargetIgnoring(sender, CarbonPlayer.renderName(recipient));
return;
}
final Component senderName = CarbonPlayer.renderName(sender);
final Component recipientName = CarbonPlayer.renderName(recipient);
final CarbonPrivateChatEvent privateChatEvent = new CarbonPrivateChatEventImpl(sender, recipient, Component.text(message));
this.carbonChat.eventHandler().emit(privateChatEvent);
if (privateChatEvent.cancelled()) {
this.carbonMessages.whisperError(sender, CarbonPlayer.renderName(sender), CarbonPlayer.renderName(recipient));
return;
}
this.carbonMessages.whisperSender(new SourcedAudience(sender, sender), senderName, recipientName, privateChatEvent.message());
this.carbonMessages.whisperRecipient(new SourcedAudience(sender, recipient), senderName, recipientName, privateChatEvent.message());
this.carbonMessages.whisperConsoleLog(this.carbonChat.server().console(), senderName, recipientName, privateChatEvent.message());
final @Nullable Sound messageSound = this.configFactory.primaryConfig().messageSound();
if (messageSound != null) {
recipient.playSound(messageSound);
}
sender.lastWhisperTarget(recipient.uuid());
sender.whisperReplyTarget(recipient.uuid());
recipient.whisperReplyTarget(sender.uuid());
}) })
.build(); .build();
@@ -24,23 +24,29 @@ import cloud.commandframework.arguments.standard.StringArgument;
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 net.draycia.carbon.api.CarbonChat; import com.google.inject.Provider;
import net.draycia.carbon.api.CarbonServer;
import net.draycia.carbon.api.event.CarbonEventHandler;
import net.draycia.carbon.api.event.events.CarbonPrivateChatEvent; import net.draycia.carbon.api.event.events.CarbonPrivateChatEvent;
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.util.SourcedAudience; import net.draycia.carbon.api.util.SourcedAudience;
import net.draycia.carbon.common.command.ArgumentFactory; 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.config.ConfigFactory; import net.draycia.carbon.common.config.ConfigFactory;
import net.draycia.carbon.common.event.events.CarbonPrivateChatEventImpl; import net.draycia.carbon.common.event.events.CarbonPrivateChatEventImpl;
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.messaging.MessagingManager;
import net.draycia.carbon.common.messaging.packets.PacketFactory;
import net.draycia.carbon.common.messaging.packets.WhisperPacket;
import net.draycia.carbon.common.users.NetworkUsers;
import net.kyori.adventure.key.Key; import net.kyori.adventure.key.Key;
import net.kyori.adventure.sound.Sound; import net.kyori.adventure.sound.Sound;
import net.kyori.adventure.text.Component; 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;
@@ -48,25 +54,22 @@ import org.checkerframework.framework.qual.DefaultQualifier;
@DefaultQualifier(NonNull.class) @DefaultQualifier(NonNull.class)
public class WhisperCommand extends CarbonCommand { public class WhisperCommand extends CarbonCommand {
final CarbonChat carbonChat; private final CommandManager<Commander> commandManager;
final CommandManager<Commander> commandManager; private final CarbonMessages carbonMessages;
final CarbonMessages carbonMessages;
private final ArgumentFactory argumentFactory; private final ArgumentFactory argumentFactory;
final ConfigFactory configFactory; private final WhisperHandler whisper;
@Inject @Inject
public WhisperCommand( public WhisperCommand(
final CarbonChat carbonChat,
final CommandManager<Commander> commandManager, final CommandManager<Commander> commandManager,
final CarbonMessages carbonMessages, final CarbonMessages carbonMessages,
final ArgumentFactory argumentFactory, final ArgumentFactory argumentFactory,
final ConfigFactory configFactory final WhisperHandler whisper
) { ) {
this.carbonChat = carbonChat;
this.commandManager = commandManager; this.commandManager = commandManager;
this.carbonMessages = carbonMessages; this.carbonMessages = carbonMessages;
this.argumentFactory = argumentFactory; this.argumentFactory = argumentFactory;
this.configFactory = configFactory; this.whisper = whisper;
} }
@Override @Override
@@ -89,67 +92,147 @@ public class WhisperCommand extends CarbonCommand {
.permission("carbon.whisper.message") .permission("carbon.whisper.message")
.senderType(PlayerCommander.class) .senderType(PlayerCommander.class)
.meta(MinecraftExtrasMetaKeys.DESCRIPTION, this.carbonMessages.commandWhisperDescription()) .meta(MinecraftExtrasMetaKeys.DESCRIPTION, this.carbonMessages.commandWhisperDescription())
.handler(handler -> { .handler(ctx -> {
final CarbonPlayer sender = ((PlayerCommander) handler.getSender()).carbonPlayer(); final CarbonPlayer sender = ((PlayerCommander) ctx.getSender()).carbonPlayer();
if (sender.muted()) { if (sender.muted()) {
this.carbonMessages.muteCannotSpeak(sender); this.carbonMessages.muteCannotSpeak(sender);
return; return;
} }
final String message = handler.get("message"); final String message = ctx.get("message");
final CarbonPlayer recipient = handler.get("player"); final CarbonPlayer recipient = ctx.get("player");
if (sender.equals(recipient)) { this.whisper.whisper(sender, recipient, message);
this.carbonMessages.whisperSelfError(sender, CarbonPlayer.renderName(sender));
return;
}
if (!recipient.online() || !sender.awareOf(recipient) && !sender.hasPermission("carbon.whisper.vanished")) {
final var rawNameInput = CloudUtils.rawInputByMatchingName(handler.getRawInput(), recipient);
final var exception = new CarbonPlayerArgument.CarbonPlayerParseException(rawNameInput, handler);
this.carbonMessages.errorCommandArgumentParsing(sender, CloudUtils.message(exception));
return;
}
if (sender.ignoring(recipient)) {
this.carbonMessages.whisperIgnoringTarget(sender, CarbonPlayer.renderName(recipient));
return;
}
if (recipient.ignoring(sender)) {
this.carbonMessages.whisperTargetIgnoring(sender, CarbonPlayer.renderName(recipient));
return;
}
final Component senderName = CarbonPlayer.renderName(sender);
final Component recipientName = CarbonPlayer.renderName(recipient);
final CarbonPrivateChatEvent privateChatEvent = new CarbonPrivateChatEventImpl(sender, recipient, Component.text(message));
this.carbonChat.eventHandler().emit(privateChatEvent);
if (privateChatEvent.cancelled()) {
this.carbonMessages.whisperError(sender, CarbonPlayer.renderName(sender), CarbonPlayer.renderName(recipient));
return;
}
this.carbonMessages.whisperSender(new SourcedAudience(sender, sender), senderName, recipientName, privateChatEvent.message());
this.carbonMessages.whisperRecipient(new SourcedAudience(sender, recipient), senderName, recipientName, privateChatEvent.message());
this.carbonMessages.whisperConsoleLog(this.carbonChat.server().console(), senderName, recipientName, privateChatEvent.message());
final @Nullable Sound messageSound = this.configFactory.primaryConfig().messageSound();
if (messageSound != null) {
recipient.playSound(messageSound);
}
sender.lastWhisperTarget(recipient.uuid());
sender.whisperReplyTarget(recipient.uuid());
recipient.whisperReplyTarget(sender.uuid());
}) })
.build(); .build();
this.commandManager.command(command); this.commandManager.command(command);
} }
public static final class WhisperHandler {
private final Logger logger;
private final CarbonMessages carbonMessages;
private final ConfigFactory configFactory;
private final Provider<MessagingManager> messaging;
private final PacketFactory packetFactory;
private final UserManager<? extends CarbonPlayer> userManager;
private final CarbonServer server;
private final CarbonEventHandler events;
private final NetworkUsers network;
@Inject
private WhisperHandler(
final Logger logger,
final CarbonMessages carbonMessages,
final ConfigFactory configFactory,
final Provider<MessagingManager> messaging,
final PacketFactory packetFactory,
final UserManager<?> userManager,
final CarbonServer server,
final CarbonEventHandler events,
final NetworkUsers network
) {
this.logger = logger;
this.carbonMessages = carbonMessages;
this.configFactory = configFactory;
this.messaging = messaging;
this.packetFactory = packetFactory;
this.userManager = userManager;
this.server = server;
this.events = events;
this.network = network;
}
public void whisper(
final CarbonPlayer sender,
final CarbonPlayer recipient,
final String message
) {
if (sender.equals(recipient)) {
this.carbonMessages.whisperSelfError(sender, CarbonPlayer.renderName(sender));
return;
}
if (!this.network.online(recipient) || !sender.awareOf(recipient) && !sender.hasPermission("carbon.whisper.vanished")) {
//final var rawNameInput = CloudUtils.rawInputByMatchingName(ctx.getRawInput(), recipient);
//final var exception = new CarbonPlayerArgument.CarbonPlayerParseException(/*rawNameInput*/ recipient.username(), null);
// todo
this.carbonMessages.errorCommandArgumentParsing(sender, Component.text("No such player " + recipient.username()));
return;
}
final boolean localRecipient = recipient.online();
if (sender.ignoring(recipient)) {
this.carbonMessages.whisperIgnoringTarget(sender, CarbonPlayer.renderName(recipient));
return;
}
if (recipient.ignoring(sender)) {
this.carbonMessages.whisperTargetIgnoring(sender, CarbonPlayer.renderName(recipient));
return;
}
final Component senderName = CarbonPlayer.renderName(sender);
final Component recipientName = CarbonPlayer.renderName(recipient);
final CarbonPrivateChatEvent privateChatEvent = new CarbonPrivateChatEventImpl(sender, recipient, Component.text(message));
this.events.emit(privateChatEvent);
if (privateChatEvent.cancelled()) {
this.carbonMessages.whisperError(sender, CarbonPlayer.renderName(sender), CarbonPlayer.renderName(recipient));
return;
}
this.carbonMessages.whisperSender(new SourcedAudience(sender, sender), senderName, recipientName, privateChatEvent.message());
if (localRecipient) {
this.carbonMessages.whisperRecipient(new SourcedAudience(sender, recipient), senderName, recipientName, privateChatEvent.message());
}
this.carbonMessages.whisperConsoleLog(this.server.console(), senderName, recipientName, privateChatEvent.message());
final @Nullable Sound messageSound = this.configFactory.primaryConfig().messageSound();
if (localRecipient && messageSound != null) {
recipient.playSound(messageSound);
}
sender.lastWhisperTarget(recipient.uuid());
sender.whisperReplyTarget(recipient.uuid());
if (localRecipient) {
recipient.whisperReplyTarget(sender.uuid());
} else {
this.messaging.get().withPacketService(packetService -> {
packetService.queuePacket(this.packetFactory.whisperPacket(sender.uuid(), recipient.uuid(), privateChatEvent.message()));
});
}
}
public void handlePacket(final WhisperPacket packet) {
final @Nullable CarbonPlayer recipient = this.server.players().stream()
.filter(p -> p.uuid().equals(packet.to()))
.findFirst()
.orElse(null);
if (recipient == null) {
return;
}
this.userManager.user(packet.from()).thenAccept(sender -> {
final Component senderName = CarbonPlayer.renderName(sender);
final Component recipientName = CarbonPlayer.renderName(recipient);
recipient.whisperReplyTarget(sender.uuid());
this.carbonMessages.whisperRecipient(new SourcedAudience(sender, recipient), senderName, recipientName, packet.message());
this.carbonMessages.whisperConsoleLog(this.server.console(), senderName, recipientName, packet.message());
final @Nullable Sound messageSound = this.configFactory.primaryConfig().messageSound();
if (messageSound != null) {
recipient.playSound(messageSound);
}
}).exceptionally(ex -> {
this.logger.warn("Failed to handle whisper packet {}", packet, ex);
return null;
});
}
}
} }
@@ -22,13 +22,21 @@ package net.draycia.carbon.common.messaging;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import net.draycia.carbon.api.CarbonChat; import net.draycia.carbon.api.CarbonChat;
import net.draycia.carbon.api.CarbonServer;
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.event.CarbonEventHandler;
import net.draycia.carbon.api.event.events.CarbonChatEvent; import net.draycia.carbon.api.event.events.CarbonChatEvent;
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.command.commands.WhisperCommand;
import net.draycia.carbon.common.event.events.CarbonChatEventImpl; import net.draycia.carbon.common.event.events.CarbonChatEventImpl;
import net.draycia.carbon.common.messaging.packets.ChatMessagePacket; import net.draycia.carbon.common.messaging.packets.ChatMessagePacket;
import net.draycia.carbon.common.messaging.packets.LocalPlayerChangePacket;
import net.draycia.carbon.common.messaging.packets.LocalPlayersPacket;
import net.draycia.carbon.common.messaging.packets.SaveCompletedPacket; import net.draycia.carbon.common.messaging.packets.SaveCompletedPacket;
import net.draycia.carbon.common.messaging.packets.WhisperPacket;
import net.draycia.carbon.common.users.NetworkUsers;
import net.draycia.carbon.common.users.UserManagerInternal; import net.draycia.carbon.common.users.UserManagerInternal;
import net.kyori.adventure.audience.Audience; import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.text.Component; import net.kyori.adventure.text.Component;
@@ -42,17 +50,27 @@ import org.jetbrains.annotations.NotNull;
@DefaultQualifier(NonNull.class) @DefaultQualifier(NonNull.class)
public final class CarbonChatPacketHandler extends AbstractMessagingHandler { public final class CarbonChatPacketHandler extends AbstractMessagingHandler {
private final CarbonChat carbonChat; private final CarbonEventHandler events;
private final CarbonServer server;
private final ChannelRegistry channels;
private final UserManagerInternal<?> userManager; private final UserManagerInternal<?> userManager;
private final NetworkUsers networkUsers;
private final WhisperCommand.WhisperHandler whisper;
CarbonChatPacketHandler( CarbonChatPacketHandler(
final CarbonChat carbonChat, final CarbonChat carbonChat,
final MessagingManager messagingManager, final MessagingManager messagingManager,
final UserManagerInternal<?> userManager final UserManagerInternal<?> userManager,
final NetworkUsers networkUsers,
final WhisperCommand.WhisperHandler whisper
) { ) {
super(messagingManager.requirePacketService()); super(messagingManager.requirePacketService());
this.carbonChat = carbonChat; this.events = carbonChat.eventHandler();
this.server = carbonChat.server();
this.channels = carbonChat.channelRegistry();
this.userManager = userManager; this.userManager = userManager;
this.networkUsers = networkUsers;
this.whisper = whisper;
} }
@Override @Override
@@ -60,19 +78,26 @@ public final class CarbonChatPacketHandler extends AbstractMessagingHandler {
if (packet instanceof SaveCompletedPacket statePacket) { if (packet instanceof SaveCompletedPacket statePacket) {
this.userManager.saveCompleteMessageReceived(statePacket.playerId()); this.userManager.saveCompleteMessageReceived(statePacket.playerId());
return true; return true;
} } else if (packet instanceof ChatMessagePacket messagePacket) {
if (packet instanceof ChatMessagePacket messagePacket) {
return this.handleMessagePacket(messagePacket); return this.handleMessagePacket(messagePacket);
} else if (packet instanceof LocalPlayersPacket playersPacket) {
this.networkUsers.handlePacket(playersPacket);
return true;
} else if (packet instanceof LocalPlayerChangePacket playerChangePacket) {
this.networkUsers.handlePacket(playerChangePacket);
return true;
} else if (packet instanceof WhisperPacket whisperPacket) {
this.whisper.handlePacket(whisperPacket);
return true;
} }
return false; return false;
} }
private boolean handleMessagePacket(final ChatMessagePacket messagePacket) { private boolean handleMessagePacket(final ChatMessagePacket messagePacket) {
final CarbonPlayer sender = this.carbonChat.userManager().user(messagePacket.userId()).join(); final CarbonPlayer sender = this.userManager.user(messagePacket.userId()).join();
final @Nullable ChatChannel channel = this.carbonChat.channelRegistry().channel(messagePacket.channelKey()); final @Nullable ChatChannel channel = this.channels.channel(messagePacket.channelKey());
if (channel == null) { if (channel == null) {
return false; return false;
@@ -82,7 +107,7 @@ public final class CarbonChatPacketHandler extends AbstractMessagingHandler {
final List<Audience> recipients = channel.recipients(sender); final List<Audience> recipients = channel.recipients(sender);
final CarbonChatEvent chatEvent = new CarbonChatEventImpl(sender, messagePacket.message(), recipients, renderers, channel, null, false); final CarbonChatEvent chatEvent = new CarbonChatEventImpl(sender, messagePacket.message(), recipients, renderers, channel, null, false);
this.carbonChat.eventHandler().emit(chatEvent); this.events.emit(chatEvent);
for (final Audience recipient : recipients) { for (final Audience recipient : recipients) {
if (recipient instanceof CarbonPlayer carbonRecipient if (recipient instanceof CarbonPlayer carbonRecipient
@@ -99,7 +124,7 @@ public final class CarbonChatPacketHandler extends AbstractMessagingHandler {
recipient.sendMessage(renderedMessage); recipient.sendMessage(renderedMessage);
} }
this.carbonChat.server().console().sendMessage(Component.text("[Cross-Server] ").append(chatEvent.message())); this.server.console().sendMessage(Component.text("[Cross-Server] ").append(chatEvent.message()));
return true; return true;
} }
@@ -23,6 +23,9 @@ import com.google.inject.Inject;
import com.google.inject.Singleton; import com.google.inject.Singleton;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects; import java.util.Objects;
import java.util.UUID; import java.util.UUID;
import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledExecutorService;
@@ -30,13 +33,19 @@ import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException; import java.util.concurrent.TimeoutException;
import java.util.function.Consumer; import java.util.function.Consumer;
import net.draycia.carbon.api.CarbonChat; import net.draycia.carbon.api.CarbonChat;
import net.draycia.carbon.api.event.events.CarbonShutdownEvent; import net.draycia.carbon.api.CarbonServer;
import net.draycia.carbon.api.users.CarbonPlayer;
import net.draycia.carbon.common.CarbonChatInternal; import net.draycia.carbon.common.CarbonChatInternal;
import net.draycia.carbon.common.command.commands.WhisperCommand;
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.listeners.PingHandler;
import net.draycia.carbon.common.messaging.packets.ChatMessagePacket; import net.draycia.carbon.common.messaging.packets.ChatMessagePacket;
import net.draycia.carbon.common.messaging.packets.LocalPlayerChangePacket;
import net.draycia.carbon.common.messaging.packets.LocalPlayersPacket;
import net.draycia.carbon.common.messaging.packets.PacketFactory;
import net.draycia.carbon.common.messaging.packets.SaveCompletedPacket; import net.draycia.carbon.common.messaging.packets.SaveCompletedPacket;
import net.draycia.carbon.common.messaging.packets.WhisperPacket;
import net.draycia.carbon.common.users.NetworkUsers;
import net.draycia.carbon.common.users.UserManagerInternal; import net.draycia.carbon.common.users.UserManagerInternal;
import net.draycia.carbon.common.util.ConcurrentUtil; import net.draycia.carbon.common.util.ConcurrentUtil;
import net.draycia.carbon.common.util.ExceptionLoggingScheduledThreadPoolExecutor; import net.draycia.carbon.common.util.ExceptionLoggingScheduledThreadPoolExecutor;
@@ -70,7 +79,7 @@ public class MessagingManager {
private static final byte protocolVersion = 0; private static final byte protocolVersion = 0;
private final CarbonChat carbonChat; private final CarbonChat carbonChat;
private final @MonotonicNonNull ScheduledExecutorService executorService; private final @MonotonicNonNull ScheduledExecutorService scheduledExecutor;
private final @MonotonicNonNull PacketService packetService; private final @MonotonicNonNull PacketService packetService;
private @MonotonicNonNull MessagingService messagingService; private @MonotonicNonNull MessagingService messagingService;
@@ -78,9 +87,12 @@ public class MessagingManager {
public MessagingManager( public MessagingManager(
final ConfigFactory configFactory, final ConfigFactory configFactory,
final CarbonChat carbonChat, final CarbonChat carbonChat,
final CarbonServer server,
final Logger logger, final Logger logger,
final UserManagerInternal<?> userManager, final UserManagerInternal<?> userManager,
final PingHandler pingHandler final NetworkUsers networkUsers,
final WhisperCommand.WhisperHandler whisper,
final PacketFactory packetFactory
) { ) {
if (!configFactory.primaryConfig().messagingSettings().enabled()) { if (!configFactory.primaryConfig().messagingSettings().enabled()) {
if (!((CarbonChatInternal<?>) carbonChat).isProxy()) { if (!((CarbonChatInternal<?>) carbonChat).isProxy()) {
@@ -89,7 +101,7 @@ public class MessagingManager {
this.messagingService = EMPTY_MESSAGING_SERVICE; this.messagingService = EMPTY_MESSAGING_SERVICE;
this.packetService = null; this.packetService = null;
this.carbonChat = carbonChat; this.carbonChat = carbonChat;
this.executorService = null; this.scheduledExecutor = null;
return; return;
} }
@@ -102,15 +114,24 @@ public class MessagingManager {
//PacketManager.register(HeartbeatPacket.class, HeartbeatPacket::new); //PacketManager.register(HeartbeatPacket.class, HeartbeatPacket::new);
PacketManager.register(ChatMessagePacket.class, ChatMessagePacket::new); PacketManager.register(ChatMessagePacket.class, ChatMessagePacket::new);
PacketManager.register(SaveCompletedPacket.class, SaveCompletedPacket::new); PacketManager.register(SaveCompletedPacket.class, SaveCompletedPacket::new);
PacketManager.register(LocalPlayersPacket.class, LocalPlayersPacket::new);
PacketManager.register(LocalPlayerChangePacket.class, LocalPlayerChangePacket::new);
PacketManager.register(WhisperPacket.class, WhisperPacket::new);
this.packetService = new PacketService(4, false, protocolVersion); this.packetService = new PacketService(4, false, protocolVersion) {
this.executorService = new ExceptionLoggingScheduledThreadPoolExecutor(10, // todo super is broken - calls remove on COWIterator
@Override
public boolean removeMessenger(final @NonNull String serviceName) {
return true;
}
};
this.scheduledExecutor = new ExceptionLoggingScheduledThreadPoolExecutor(4,
ConcurrentUtil.carbonThreadFactory(carbonChat.logger(), "MessagingManager"), carbonChat.logger()); 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);
handlerImpl.addHandler(new CarbonServerHandler(carbonChat.serverId(), this.packetService, handlerImpl)); handlerImpl.addHandler(new CarbonServerHandler(server, carbonChat.serverId(), this.packetService, handlerImpl, packetFactory));
handlerImpl.addHandler(new CarbonChatPacketHandler(carbonChat, this, userManager)); handlerImpl.addHandler(new CarbonChatPacketHandler(carbonChat, this, userManager, networkUsers, whisper));
try { try {
this.initMessagingService(this.packetService, handlerImpl, new File("/"), this.initMessagingService(this.packetService, handlerImpl, new File("/"),
@@ -126,22 +147,18 @@ public class MessagingManager {
this.packetService.flushQueue(); this.packetService.flushQueue();
// Broadcast keepalive packets // Broadcast keepalive packets
this.executorService.scheduleAtFixedRate(() -> { this.scheduledExecutor.scheduleAtFixedRate(() -> {
this.packetService.queuePacket(new KeepAlivePacket(carbonChat.serverId())); this.packetService.queuePacket(new KeepAlivePacket(carbonChat.serverId()));
this.packetService.flushQueue(); this.packetService.flushQueue();
}, 5, 5, TimeUnit.SECONDS); }, 5, 5, TimeUnit.SECONDS);
this.executorService.scheduleAtFixedRate(() -> { this.scheduledExecutor.scheduleAtFixedRate(() -> {
try { try {
this.packetService.flushQueue(); this.packetService.flushQueue();
} catch (final IndexOutOfBoundsException ignored) { } catch (final IndexOutOfBoundsException ignored) {
} }
}, 0, 1, TimeUnit.SECONDS); }, 0, 250, TimeUnit.MILLISECONDS);
carbonChat.eventHandler().subscribe(CarbonShutdownEvent.class, 0, false, event -> {
this.onShutdown();
});
} }
public @Nullable PacketService packetService() { public @Nullable PacketService packetService() {
@@ -158,14 +175,14 @@ public class MessagingManager {
} }
} }
private void onShutdown() { public void onShutdown() {
if (this.executorService != null) {
ConcurrentUtil.shutdownExecutor(this.executorService, TimeUnit.SECONDS, 10);
}
if (this.packetService != null) { if (this.packetService != null) {
this.packetService.flushQueue(); this.packetService.flushQueue();
this.packetService.shutdown(); this.packetService.shutdown();
} }
if (this.scheduledExecutor != null) {
ConcurrentUtil.shutdownExecutor(this.scheduledExecutor, TimeUnit.MILLISECONDS, 500);
}
this.messagingService.close(); this.messagingService.close();
} }
@@ -231,12 +248,30 @@ public class MessagingManager {
private static final class CarbonServerHandler extends AbstractServerMessagingHandler { private static final class CarbonServerHandler extends AbstractServerMessagingHandler {
private final CarbonServer server;
private final PacketFactory packetFactory;
private CarbonServerHandler( private CarbonServerHandler(
final @NotNull UUID serverId, final @NonNull CarbonServer server,
final @NotNull PacketService packetService, final @NonNull UUID serverId,
final @NotNull MessagingHandler messagingHandler final @NonNull PacketService packetService,
final @NonNull MessagingHandler messagingHandler,
final @NonNull PacketFactory packetFactory
) { ) {
super(serverId, packetService, messagingHandler); super(serverId, packetService, messagingHandler);
this.server = server;
this.packetFactory = packetFactory;
}
@Override
protected void handleInitialization(final @NonNull InitializationPacket packet) {
super.handleInitialization(packet);
final List<? extends CarbonPlayer> players = this.server.players();
final Map<UUID, String> map = new HashMap<>();
for (final CarbonPlayer player : players) {
map.put(player.uuid(), player.username());
}
this.packetService.queuePacket(this.packetFactory.localPlayersPacket(map));
} }
} }
@@ -23,6 +23,8 @@ import io.netty.buffer.ByteBuf;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.UUID; import java.util.UUID;
import java.util.function.BiConsumer;
import java.util.function.Function;
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.adventure.text.serializer.gson.GsonComponentSerializer; import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer;
@@ -56,21 +58,30 @@ public abstract class CarbonPacket extends AbstractPacket {
return Key.key(value); return Key.key(value);
} }
protected final void writeStringMap(final Map<String, String> map, final ByteBuf buffer) { protected final <K, V> void writeMap(
final Map<K, V> map,
final BiConsumer<K, ByteBuf> keyWriter,
final BiConsumer<V, ByteBuf> valueWriter,
final ByteBuf buffer
) {
this.writeVarInt(map.size(), buffer); this.writeVarInt(map.size(), buffer);
for (final Map.Entry<String, String> entry : map.entrySet()) { for (final Map.Entry<K, V> entry : map.entrySet()) {
this.writeString(entry.getKey(), buffer); keyWriter.accept(entry.getKey(), buffer);
this.writeString(entry.getValue(), buffer); valueWriter.accept(entry.getValue(), buffer);
} }
} }
protected final Map<String, String> readStringMap(final ByteBuf buffer) { protected final <K, V> Map<K, V> readMap(
final ByteBuf buffer,
final Function<ByteBuf, K> keyReader,
final Function<ByteBuf, V> valueReader
) {
final int size = this.readVarInt(buffer); final int size = this.readVarInt(buffer);
final Map<String, String> map = new HashMap<>(); final Map<K, V> map = new HashMap<>();
for (int i = 0; i < size; i++) { for (int i = 0; i < size; i++) {
map.put(this.readString(buffer), this.readString(buffer)); map.put(keyReader.apply(buffer), valueReader.apply(buffer));
} }
return map; return map;
@@ -0,0 +1,95 @@
/*
* 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.messaging.packets;
import com.google.inject.assistedinject.Assisted;
import com.google.inject.assistedinject.AssistedInject;
import io.netty.buffer.ByteBuf;
import java.util.UUID;
import net.draycia.carbon.api.CarbonChat;
import org.checkerframework.checker.nullness.qual.MonotonicNonNull;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.checkerframework.framework.qual.DefaultQualifier;
@DefaultQualifier(NonNull.class)
public final class LocalPlayerChangePacket extends CarbonPacket {
private @MonotonicNonNull UUID playerId;
private @MonotonicNonNull String playerName;
private @MonotonicNonNull ChangeType changeType;
@AssistedInject
public LocalPlayerChangePacket(
final CarbonChat carbonChat,
final @Assisted UUID playerId,
final @Assisted @Nullable String playerName,
final @Assisted ChangeType changeType
) {
super(carbonChat.serverId());
if (changeType == ChangeType.ADD && playerName == null) {
throw new IllegalArgumentException("playerName cannot be null for ChangeType.ADD");
}
this.playerId = playerId;
this.playerName = playerName;
this.changeType = changeType;
}
public LocalPlayerChangePacket(final UUID sender, final ByteBuf data) {
super(sender);
this.read(data);
}
public UUID playerId() {
return this.playerId;
}
public String playerName() {
return this.playerName;
}
public ChangeType changeType() {
return this.changeType;
}
@Override
public void read(final ByteBuf buffer) {
this.playerId = this.readUUID(buffer);
final String type = this.readString(buffer);
this.changeType = ChangeType.valueOf(type);
if (this.changeType == ChangeType.ADD) {
this.playerName = this.readString(buffer);
}
}
@Override
public void write(final ByteBuf buffer) {
this.writeUUID(this.playerId, buffer);
this.writeString(this.changeType.name(), buffer);
if (this.changeType == ChangeType.ADD) {
this.writeString(this.playerName, buffer);
}
}
public enum ChangeType {
ADD, REMOVE
}
}
@@ -0,0 +1,65 @@
/*
* 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.messaging.packets;
import com.google.inject.assistedinject.Assisted;
import com.google.inject.assistedinject.AssistedInject;
import io.netty.buffer.ByteBuf;
import java.util.Map;
import java.util.UUID;
import net.draycia.carbon.api.CarbonChat;
import org.checkerframework.checker.nullness.qual.MonotonicNonNull;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.framework.qual.DefaultQualifier;
@DefaultQualifier(NonNull.class)
public final class LocalPlayersPacket extends CarbonPacket {
private @MonotonicNonNull Map<UUID, String> players;
@AssistedInject
public LocalPlayersPacket(
final CarbonChat carbonChat,
final @Assisted Map<UUID, String> players
) {
super(carbonChat.serverId());
this.players = players;
}
public LocalPlayersPacket(final UUID sender, final ByteBuf data) {
super(sender);
this.read(data);
}
public Map<UUID, String> players() {
return this.players;
}
@Override
public void read(final ByteBuf buffer) {
this.players = this.readMap(buffer, this::readUUID, this::readString);
}
@Override
public void write(final ByteBuf buffer) {
this.writeMap(this.players, this::writeUUID, this::writeString, buffer);
}
}
@@ -19,8 +19,12 @@
*/ */
package net.draycia.carbon.common.messaging.packets; package net.draycia.carbon.common.messaging.packets;
import com.google.inject.assistedinject.Assisted;
import java.util.Map;
import java.util.UUID; import java.util.UUID;
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)
@@ -28,4 +32,22 @@ public interface PacketFactory {
SaveCompletedPacket saveCompletedPacket(UUID playerId); SaveCompletedPacket saveCompletedPacket(UUID playerId);
LocalPlayersPacket localPlayersPacket(Map<UUID, String> players);
default LocalPlayersPacket clearLocalPlayersPacket() {
return this.localPlayersPacket(Map.of());
}
LocalPlayerChangePacket localPlayerChangePacket(UUID player, @Nullable String name, LocalPlayerChangePacket.ChangeType type);
default LocalPlayerChangePacket addLocalPlayerPacket(final UUID id, final String name) {
return this.localPlayerChangePacket(id, name, LocalPlayerChangePacket.ChangeType.ADD);
}
default LocalPlayerChangePacket removeLocalPlayerPacket(final UUID id) {
return this.localPlayerChangePacket(id, null, LocalPlayerChangePacket.ChangeType.REMOVE);
}
WhisperPacket whisperPacket(@Assisted("from") UUID from, @Assisted("to") UUID to, Component msg);
} }
@@ -0,0 +1,93 @@
/*
* 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.messaging.packets;
import com.google.inject.assistedinject.Assisted;
import com.google.inject.assistedinject.AssistedInject;
import io.netty.buffer.ByteBuf;
import java.util.UUID;
import net.draycia.carbon.api.CarbonChat;
import net.kyori.adventure.text.Component;
import org.checkerframework.checker.nullness.qual.MonotonicNonNull;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.framework.qual.DefaultQualifier;
@DefaultQualifier(NonNull.class)
public final class WhisperPacket extends CarbonPacket {
private @MonotonicNonNull UUID from;
private @MonotonicNonNull UUID to;
private @MonotonicNonNull Component message;
@AssistedInject
public WhisperPacket(
final CarbonChat carbonChat,
final @Assisted("from") UUID from,
final @Assisted("to") UUID to,
final @Assisted Component message
) {
super(carbonChat.serverId());
this.from = from;
this.to = to;
this.message = message;
}
public WhisperPacket(final UUID sender, final ByteBuf data) {
super(sender);
this.read(data);
}
public UUID from() {
return this.from;
}
public UUID to() {
return this.to;
}
public Component message() {
return this.message;
}
@Override
public void read(final ByteBuf buffer) {
this.from = this.readUUID(buffer);
this.to = this.readUUID(buffer);
this.message = this.readComponent(buffer);
}
@Override
public void write(final ByteBuf buffer) {
this.writeUUID(this.from, buffer);
this.writeUUID(this.to, buffer);
this.writeComponent(this.message, buffer);
}
@Override
public String toString() {
return "WhisperPacket{" +
"from=" + this.from +
", to=" + this.to +
", message=" + this.message +
", sender=" + this.sender +
'}';
}
}
@@ -144,6 +144,9 @@ public abstract class CachingUserManager implements UserManagerInternal<CarbonPl
@Override @Override
public CompletableFuture<Void> loggedOut(final UUID uuid) { public CompletableFuture<Void> loggedOut(final UUID uuid) {
this.messagingManager.get().withPacketService(packetService -> {
packetService.queuePacket(this.packetFactory.removeLocalPlayerPacket(uuid));
});
this.cacheLock.lock(); this.cacheLock.lock();
try { try {
final @Nullable CompletableFuture<CarbonPlayerCommon> remove = this.cache.remove(uuid); final @Nullable CompletableFuture<CarbonPlayerCommon> remove = this.cache.remove(uuid);
@@ -0,0 +1,133 @@
/*
* 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 cloud.commandframework.context.CommandContext;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.stream.Stream;
import net.draycia.carbon.api.CarbonServer;
import net.draycia.carbon.api.users.CarbonPlayer;
import net.draycia.carbon.api.users.UserManager;
import net.draycia.carbon.common.command.Commander;
import net.draycia.carbon.common.command.PlayerCommander;
import net.draycia.carbon.common.command.argument.PlayerSuggestions;
import net.draycia.carbon.common.messaging.packets.LocalPlayerChangePacket;
import net.draycia.carbon.common.messaging.packets.LocalPlayersPacket;
import net.draycia.carbon.common.util.Exceptions;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.framework.qual.DefaultQualifier;
/**
* Eventually consistent store of who is on each server in the network (besides self).
*
* <p>Currently used for username suggestions and whispers.</p>
*/
@DefaultQualifier(NonNull.class)
@Singleton
public final class NetworkUsers implements PlayerSuggestions {
private final CarbonServer server;
private final Map<UUID, Map<UUID, String>> map = new ConcurrentHashMap<>();
private final UserManager<? extends CarbonPlayer> userManager;
@Inject
private NetworkUsers(
final CarbonServer server,
final UserManager<?> userManager
) {
this.server = server;
this.userManager = userManager;
}
public void handlePacket(final LocalPlayerChangePacket packet) {
final Map<UUID, String> serverMap = this.map.computeIfAbsent(packet.getSender(), $ -> new ConcurrentHashMap<>());
switch (packet.changeType()) {
case ADD -> serverMap.put(packet.playerId(), packet.playerName());
case REMOVE -> serverMap.remove(packet.playerId());
}
this.map.values().removeIf(Map::isEmpty);
}
public void handlePacket(final LocalPlayersPacket packet) {
if (packet.players().isEmpty()) {
this.map.remove(packet.getSender());
} else {
final Map<UUID, String> serverMap = this.map.computeIfAbsent(packet.getSender(), $ -> new ConcurrentHashMap<>());
serverMap.clear();
serverMap.putAll(packet.players());
}
}
// PlayerSuggestions impl
@Override
public List<String> apply(final CommandContext<Commander> ctx, final String input) {
final Commander commander = ctx.getSender();
final List<? extends CarbonPlayer> local = this.server.players();
if (!(commander instanceof PlayerCommander player)) {
return Stream.concat(local.stream().map(CarbonPlayer::username), this.map.values().stream().flatMap(m -> m.values().stream()))
.distinct()
.toList();
}
final CarbonPlayer carbonPlayer = player.carbonPlayer();
final List<? extends CompletableFuture<? extends CarbonPlayer>> remotePlayerFutures =
this.map.values().stream()
.flatMap(m -> m.keySet().stream())
.map(this.userManager::user)
.toList(); // collect to ensure we request all futures before waiting
final CompletableFuture<Void> combinedFuture = CompletableFuture.allOf(remotePlayerFutures.toArray(CompletableFuture[]::new));
try {
combinedFuture.get(50, TimeUnit.MILLISECONDS);
} catch (final TimeoutException ignore) {
} catch (final Exception e) {
throw Exceptions.rethrow(e);
}
final Stream<? extends CarbonPlayer> remote = remotePlayerFutures.stream()
.map(future -> future.getNow(null))
.filter(Objects::nonNull);
return Stream.concat(local.stream(), remote)
.filter(carbonPlayer::awareOf)
.map(CarbonPlayer::username)
.distinct()
.toList();
}
public boolean online(final CarbonPlayer player) {
if (player.online()) {
return true;
}
return this.map.values().stream().anyMatch(server -> server.containsKey(player.uuid()));
}
}
@@ -25,6 +25,7 @@ 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;
// todo use data from NetworkPlayers?
@DefaultQualifier(NonNull.class) @DefaultQualifier(NonNull.class)
public interface ProfileResolver { public interface ProfileResolver {
+1 -1
View File
@@ -87,6 +87,6 @@ tasks {
} }
modrinth { modrinth {
gameVersions.set(listOf(libs.versions.fabricMinecraft.get())) gameVersions.set(listOf(libs.versions.minecraft.get()))
loaders.addAll("fabric") loaders.addAll("fabric")
} }
@@ -36,7 +36,6 @@ import net.draycia.carbon.common.CarbonCommonModule;
import net.draycia.carbon.common.DataDirectory; import net.draycia.carbon.common.DataDirectory;
import net.draycia.carbon.common.PlatformScheduler; import net.draycia.carbon.common.PlatformScheduler;
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.commands.ExecutionCoordinatorHolder; 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.ProfileResolver;
@@ -108,13 +107,6 @@ 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());
@@ -20,8 +20,11 @@
package net.draycia.carbon.fabric.listeners; package net.draycia.carbon.fabric.listeners;
import com.google.inject.Inject; import com.google.inject.Inject;
import com.google.inject.Provider;
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.messaging.MessagingManager;
import net.draycia.carbon.common.messaging.packets.PacketFactory;
import net.draycia.carbon.common.users.ProfileCache; import net.draycia.carbon.common.users.ProfileCache;
import net.draycia.carbon.common.users.UserManagerInternal; import net.draycia.carbon.common.users.UserManagerInternal;
import net.fabricmc.fabric.api.networking.v1.PacketSender; import net.fabricmc.fabric.api.networking.v1.PacketSender;
@@ -43,23 +46,32 @@ public class FabricJoinQuitListener implements ServerPlayConnectionEvents.Join,
private final Logger logger; private final Logger logger;
private final ConfigFactory configFactory; private final ConfigFactory configFactory;
private final UserManagerInternal<?> userManager; private final UserManagerInternal<?> userManager;
private final Provider<MessagingManager> messaging;
private final PacketFactory packetFactory;
@Inject @Inject
public FabricJoinQuitListener( public FabricJoinQuitListener(
final Logger logger, final Logger logger,
final ConfigFactory configFactory, final ConfigFactory configFactory,
final ProfileCache profileCache, final ProfileCache profileCache,
final UserManagerInternal<?> userManager final UserManagerInternal<?> userManager,
final Provider<MessagingManager> messaging,
final PacketFactory packetFactory
) { ) {
this.logger = logger; this.logger = logger;
this.configFactory = configFactory; this.configFactory = configFactory;
this.profileCache = profileCache; this.profileCache = profileCache;
this.userManager = userManager; this.userManager = userManager;
this.messaging = messaging;
this.packetFactory = packetFactory;
} }
@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()); this.profileCache.cache(handler.getPlayer().getUUID(), handler.getPlayer().getGameProfile().getName());
this.messaging.get().withPacketService(packetService -> {
packetService.queuePacket(this.packetFactory.addLocalPlayerPacket(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();
+2 -2
View File
@@ -34,7 +34,7 @@ versions:
guice: 5.1.0 guice: 5.1.0
velocityApi: 3.2.0-SNAPSHOT velocityApi: 3.2.0-SNAPSHOT
geantyref: 1.3.11 geantyref: 1.3.11
fabricMinecraft: 1.20.1 minecraft: 1.20.1
fabricLoader: 0.14.21 fabricLoader: 0.14.21
adventurePlatformFabric: 5.9.0 adventurePlatformFabric: 5.9.0
luckPermsApi: 5.3 luckPermsApi: 5.3
@@ -306,7 +306,7 @@ dependencies:
fabricMinecraft: fabricMinecraft:
group: com.mojang group: com.mojang
name: minecraft name: minecraft
version: { ref: fabricMinecraft } version: { ref: minecraft }
fabricLoader: fabricLoader:
group: net.fabricmc group: net.fabricmc
name: fabric-loader name: fabric-loader
+8 -1
View File
@@ -1,3 +1,5 @@
import xyz.jpenilla.runpaper.task.RunServer
plugins { plugins {
id("carbon.shadow-platform") id("carbon.shadow-platform")
id("net.minecrell.plugin-yml.bukkit") id("net.minecrell.plugin-yml.bukkit")
@@ -37,7 +39,12 @@ tasks {
relocateCloud() relocateCloud()
} }
runServer { runServer {
minecraftVersion("1.20.1") version.set(libs.versions.minecraft)
}
register<RunServer>("runServer2") {
version.set(libs.versions.minecraft)
pluginJars.from(shadowJar.flatMap { it.archiveFile })
runDirectory.set(layout.projectDirectory.dir("run2"))
} }
writeDependencies { writeDependencies {
} }
@@ -21,7 +21,6 @@ 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.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;
@@ -38,7 +37,6 @@ import net.draycia.carbon.common.CarbonCommonModule;
import net.draycia.carbon.common.DataDirectory; import net.draycia.carbon.common.DataDirectory;
import net.draycia.carbon.common.PlatformScheduler; import net.draycia.carbon.common.PlatformScheduler;
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.commands.ExecutionCoordinatorHolder; 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.ProfileResolver;
@@ -132,7 +130,6 @@ public final class CarbonChatPaperModule extends AbstractModule {
this.bind(Logger.class).toInstance(this.logger); this.bind(Logger.class).toInstance(this.logger);
this.bind(Path.class).annotatedWith(DataDirectory.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(ProfileResolver.class).to(PaperProfileResolver.class); this.bind(ProfileResolver.class).to(PaperProfileResolver.class);
this.bind(PlatformScheduler.class).to(PaperScheduler.class); this.bind(PlatformScheduler.class).to(PaperScheduler.class);
this.bind(new TypeLiteral<UserManager<?>>() {}).to(PaperUserManager.class); this.bind(new TypeLiteral<UserManager<?>>() {}).to(PaperUserManager.class);
@@ -20,8 +20,11 @@
package net.draycia.carbon.paper.listeners; package net.draycia.carbon.paper.listeners;
import com.google.inject.Inject; import com.google.inject.Inject;
import com.google.inject.Provider;
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.messaging.MessagingManager;
import net.draycia.carbon.common.messaging.packets.PacketFactory;
import net.draycia.carbon.common.users.ProfileCache; import net.draycia.carbon.common.users.ProfileCache;
import net.draycia.carbon.paper.PaperUserManager; import net.draycia.carbon.paper.PaperUserManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
@@ -29,6 +32,7 @@ import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority; import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener; import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerLoginEvent;
import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.event.player.PlayerQuitEvent;
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;
@@ -44,23 +48,36 @@ public class PaperPlayerJoinListener implements Listener {
private final Logger logger; private final Logger logger;
private final ProfileCache profileCache; private final ProfileCache profileCache;
private final PaperUserManager userManager; private final PaperUserManager userManager;
private final Provider<MessagingManager> messaging;
private final PacketFactory packetFactory;
@Inject @Inject
public PaperPlayerJoinListener( public PaperPlayerJoinListener(
final ConfigFactory configFactory, final ConfigFactory configFactory,
final Logger logger, final Logger logger,
final ProfileCache profileCache, final ProfileCache profileCache,
final PaperUserManager userManager final PaperUserManager userManager,
final Provider<MessagingManager> messaging,
final PacketFactory packetFactory
) { ) {
this.configFactory = configFactory; this.configFactory = configFactory;
this.logger = logger; this.logger = logger;
this.profileCache = profileCache; this.profileCache = profileCache;
this.userManager = userManager; this.userManager = userManager;
this.messaging = messaging;
this.packetFactory = packetFactory;
}
@EventHandler
public void onLogin(final PlayerLoginEvent event) {
this.profileCache.cache(event.getPlayer().getUniqueId(), event.getPlayer().getName());
} }
@EventHandler(priority = EventPriority.LOWEST) @EventHandler(priority = EventPriority.LOWEST)
public void cacheProfile(final PlayerJoinEvent event) { public void onJoinEarly(final PlayerJoinEvent event) {
this.profileCache.cache(event.getPlayer().getUniqueId(), event.getPlayer().getName()); this.messaging.get().withPacketService(packetService -> {
packetService.queuePacket(this.packetFactory.addLocalPlayerPacket(event.getPlayer().getUniqueId(), event.getPlayer().getName()));
});
} }
@EventHandler(priority = EventPriority.HIGH) @EventHandler(priority = EventPriority.HIGH)
@@ -21,7 +21,6 @@ package net.draycia.carbon.velocity;
import cloud.commandframework.CommandManager; import cloud.commandframework.CommandManager;
import cloud.commandframework.velocity.VelocityCommandManager; import cloud.commandframework.velocity.VelocityCommandManager;
import cloud.commandframework.velocity.arguments.PlayerArgument;
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;
@@ -39,7 +38,6 @@ import net.draycia.carbon.common.CarbonCommonModule;
import net.draycia.carbon.common.DataDirectory; import net.draycia.carbon.common.DataDirectory;
import net.draycia.carbon.common.PlatformScheduler; import net.draycia.carbon.common.PlatformScheduler;
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.commands.ExecutionCoordinatorHolder; 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.ProfileResolver;
@@ -122,7 +120,6 @@ public final class CarbonChatVelocityModule extends AbstractModule {
this.bind(CarbonChat.class).to(CarbonChatVelocity.class); this.bind(CarbonChat.class).to(CarbonChatVelocity.class);
this.bind(CarbonServer.class).to(CarbonServerVelocity.class); this.bind(CarbonServer.class).to(CarbonServerVelocity.class);
this.bind(PlayerSuggestions.class).toInstance(new PlayerArgument.PlayerParser<Commander>()::suggestions);
this.bind(ProfileResolver.class).to(VelocityProfileResolver.class); this.bind(ProfileResolver.class).to(VelocityProfileResolver.class);
this.bind(Path.class).annotatedWith(DataDirectory.class).toInstance(this.dataDirectory); this.bind(Path.class).annotatedWith(DataDirectory.class).toInstance(this.dataDirectory);
this.bind(Logger.class).toInstance(this.logger); this.bind(Logger.class).toInstance(this.logger);