fix: Reimplement Velocity Module

feat: Added MiniPlaceholders support in Velocity module
This commit is contained in:
Adrian committed 2023-04-13 17:11:00 -05:00
1 parent 03af4448af
commit 5d028db601
14 files changed
+320 -400

No files matched your search

+1 -1
View File
@@ -85,7 +85,7 @@ sequenceOf(
"paper", "paper",
// "sponge", // TODO API 10 // "sponge", // TODO API 10
"fabric", "fabric",
// "velocity" "velocity"
).forEach { ).forEach {
include("carbonchat-$it") include("carbonchat-$it")
project(":carbonchat-$it").projectDir = file(it) project(":carbonchat-$it").projectDir = file(it)
+2
View File
@@ -22,6 +22,8 @@ dependencies {
implementation(libs.cloudVelocity) implementation(libs.cloudVelocity)
velocityRun("com.velocitypowered", "velocity-proxy", libs.versions.velocityApi.get()) velocityRun("com.velocitypowered", "velocity-proxy", libs.versions.velocityApi.get())
compileOnly(libs.miniplaceholders)
} }
tasks { tasks {
@@ -1,7 +1,7 @@
/* /*
* CarbonChat * CarbonChat
* *
* Copyright (c) 2021 Josua Parks (Vicarious) * Copyright (c) 2023 Josua Parks (Vicarious)
* Contributors * Contributors
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
@@ -21,158 +21,94 @@ package net.draycia.carbon.velocity;
import com.google.inject.Inject; import com.google.inject.Inject;
import com.google.inject.Injector; import com.google.inject.Injector;
import com.velocitypowered.api.event.Subscribe; import com.google.inject.Provider;
import com.velocitypowered.api.event.proxy.ProxyInitializeEvent; import com.google.inject.Singleton;
import com.velocitypowered.api.plugin.Dependency;
import com.velocitypowered.api.plugin.Plugin;
import com.velocitypowered.api.plugin.PluginContainer; import com.velocitypowered.api.plugin.PluginContainer;
import com.velocitypowered.api.plugin.annotation.DataDirectory; import com.velocitypowered.api.plugin.annotation.DataDirectory;
import com.velocitypowered.api.proxy.ProxyServer; import com.velocitypowered.api.proxy.ProxyServer;
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 net.draycia.carbon.api.CarbonChat;
import net.draycia.carbon.api.CarbonChatProvider; import net.draycia.carbon.api.CarbonChatProvider;
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.util.Component; import net.draycia.carbon.common.CarbonChatInternal;
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.util.CloudUtils; import net.draycia.carbon.common.users.ProfileCache;
import net.draycia.carbon.common.util.ListenerUtils; import net.draycia.carbon.common.users.ProfileResolver;
import net.draycia.carbon.velocity.listeners.VelocityChatListener; import net.draycia.carbon.velocity.listeners.VelocityChatListener;
import net.draycia.carbon.velocity.listeners.VelocityPlayerJoinListener; import net.draycia.carbon.velocity.listeners.VelocityPlayerJoinListener;
import net.draycia.carbon.velocity.users.CarbonPlayerVelocity;
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.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;
@Plugin(
id = "$[ID]",
name = "$[NAME]",
version = "$[VERSION]",
description = "$[DESCRIPTION]",
url = "$[URL]",
authors = {"Draycia"},
dependencies = {@Dependency(id = "luckperms")}
)
@DefaultQualifier(NonNull.class) @DefaultQualifier(NonNull.class)
public class CarbonChatVelocity implements CarbonChat { @Singleton
public class CarbonChatVelocity extends CarbonChatInternal<CarbonPlayerVelocity> {
private static final Set<Class<?>> LISTENER_CLASSES = Set.of( private static final Set<Class<?>> LISTENER_CLASSES = Set.of(
VelocityChatListener.class, VelocityChatListener.class,
VelocityPlayerJoinListener.class VelocityPlayerJoinListener.class
); );
private final Path dataDirectory;
private final ProxyServer proxyServer; private final ProxyServer proxyServer;
private final Logger logger;
private final Injector injector;
private final CarbonMessages carbonMessages;
private final ChannelRegistry channelRegistry;
private final CarbonServerVelocity carbonServer;
private final CarbonEventHandler eventHandler = new CarbonEventHandler();
private final UUID serverId = UUID.randomUUID();
private @MonotonicNonNull MessagingManager messagingManager = null;
@Inject @Inject
public CarbonChatVelocity( public CarbonChatVelocity(
@DataDirectory final Path dataDirectory,
final ProxyServer proxyServer, final ProxyServer proxyServer,
final Injector injector,
final PluginContainer pluginContainer, final PluginContainer pluginContainer,
final Injector injector @DataDirectory final Path dataDirectory,
@PeriodicTasks final ScheduledExecutorService periodicTasks,
final ProfileCache profileCache,
final ProfileResolver profileResolver,
final ExecutionCoordinatorHolder commandExecutor,
final IMessageRenderer<Audience, String, Component, Component> renderer,
final VelocityUserManager userManager,
final CarbonServerVelocity carbonServer,
final CarbonMessages carbonMessages,
final CarbonEventHandler eventHandler,
final CarbonChannelRegistry channelRegistry,
final Provider<MessagingManager> messagingManager
) { ) {
CarbonChatProvider.register(this); super(
injector, LogManager.getLogger(pluginContainer.getDescription().getId()),
this.dataDirectory = dataDirectory; dataDirectory,
periodicTasks,
profileCache,
profileResolver,
userManager,
commandExecutor,
carbonServer,
carbonMessages,
eventHandler,
channelRegistry,
renderer,
messagingManager
);
this.proxyServer = proxyServer; this.proxyServer = proxyServer;
this.logger = LogManager.getLogger(pluginContainer.getDescription().getId());
final CarbonChatVelocityModule carbonVelocityModule; CarbonChatProvider.register(this);
carbonVelocityModule = new CarbonChatVelocityModule(
this.logger, this.dataDirectory, pluginContainer, this.proxyServer, this);
this.injector = injector.createChildInjector(carbonVelocityModule);
this.carbonMessages = this.injector.getInstance(CarbonMessages.class);
this.channelRegistry = this.injector.getInstance(ChannelRegistry.class);
this.carbonServer = this.injector.getInstance(CarbonServerVelocity.class);
} }
@Subscribe public void onInitialization(final CarbonVelocityBootstrap carbonVelocityBootstrap) {
public void onProxyInitialization(final ProxyInitializeEvent event) { this.init();
this.packetService();
for (final Class<?> clazz : LISTENER_CLASSES) { for (final Class<?> clazz : LISTENER_CLASSES) {
this.proxyServer.getEventManager().register(this, this.injector.getInstance(clazz)); this.proxyServer.getEventManager().register(carbonVelocityBootstrap, this.injector().getInstance(clazz));
}
} }
// Listeners public void onShutdown() {
ListenerUtils.registerCommonListeners(this.injector); this.shutdown();
// Load channels
((CarbonChannelRegistry) this.channelRegistry()).loadConfigChannels(this.carbonMessages);
// Commands
CloudUtils.loadCommands(this.injector);
final var commandSettings = CloudUtils.loadCommandSettings(this.injector);
CloudUtils.registerCommands(commandSettings);
}
@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 CarbonServerVelocity server() {
return this.carbonServer;
}
@Override
public ChannelRegistry channelRegistry() {
return this.channelRegistry;
}
@Override
public <T extends Audience> IMessageRenderer<T, String, Component, Component> messageRenderer() {
return this.injector.getInstance(VelocityMessageRenderer.class);
}
public CarbonMessages carbonMessages() {
return this.carbonMessages;
}
@Override
public final @NonNull CarbonEventHandler eventHandler() {
return this.eventHandler;
} }
} }
@@ -1,7 +1,7 @@
/* /*
* CarbonChat * CarbonChat
* *
* Copyright (c) 2021 Josua Parks (Vicarious) * Copyright (c) 2023 Josua Parks (Vicarious)
* Contributors * Contributors
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
@@ -27,23 +27,28 @@ 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 com.velocitypowered.api.plugin.PluginContainer; import com.velocitypowered.api.plugin.PluginContainer;
import com.velocitypowered.api.proxy.Player; import com.velocitypowered.api.proxy.Player;
import com.velocitypowered.api.proxy.ProxyServer; import com.velocitypowered.api.proxy.ProxyServer;
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.util.Component; 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.users.ProfileResolver;
import net.draycia.carbon.common.users.UserManagerInternal;
import net.draycia.carbon.velocity.command.VelocityCommander; import net.draycia.carbon.velocity.command.VelocityCommander;
import net.draycia.carbon.velocity.command.VelocityPlayerCommander; import net.draycia.carbon.velocity.command.VelocityPlayerCommander;
import net.draycia.carbon.velocity.users.VelocityProfileResolver;
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 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;
@@ -51,36 +56,31 @@ import org.checkerframework.framework.qual.DefaultQualifier;
@DefaultQualifier(NonNull.class) @DefaultQualifier(NonNull.class)
public final class CarbonChatVelocityModule extends AbstractModule { public final class CarbonChatVelocityModule extends AbstractModule {
private final Logger logger; private final Logger logger = LogManager.getLogger("carbonchat");
private final Path dataDirectory;
private final PluginContainer pluginContainer; private final PluginContainer pluginContainer;
private final ProxyServer proxyServer; private final ProxyServer proxyServer;
private final CarbonChatVelocity carbonChatVelocity; private final Path dataDirectory;
CarbonChatVelocityModule( CarbonChatVelocityModule(
final Logger logger,
final Path dataDirectory,
final PluginContainer pluginContainer, final PluginContainer pluginContainer,
final ProxyServer proxyServer, final ProxyServer proxyServer,
final CarbonChatVelocity carbonChatVelocity final Path dataDirectory
) { ) {
this.logger = logger;
this.dataDirectory = dataDirectory;
this.pluginContainer = pluginContainer; this.pluginContainer = pluginContainer;
this.proxyServer = proxyServer; this.proxyServer = proxyServer;
this.carbonChatVelocity = carbonChatVelocity; this.dataDirectory = dataDirectory;
} }
@Provides @Provides
@Singleton @Singleton
public CommandManager<Commander> createCommandManager() { public CommandManager<Commander> createCommandManager(final UserManager<?> userManager) {
final VelocityCommandManager<Commander> commandManager = new VelocityCommandManager<>( final VelocityCommandManager<Commander> commandManager = new VelocityCommandManager<>(
this.pluginContainer, this.pluginContainer,
this.proxyServer, this.proxyServer,
AsynchronousCommandExecutionCoordinator.<Commander>builder().build(), AsynchronousCommandExecutionCoordinator.<Commander>builder().build(),
commandSender -> { commandSender -> {
if (commandSender instanceof Player player) { if (commandSender instanceof Player player) {
return new VelocityPlayerCommander(this.carbonChatVelocity, player); return new VelocityPlayerCommander(userManager, player);
} }
return VelocityCommander.from(commandSender); return VelocityCommander.from(commandSender);
@@ -110,11 +110,14 @@ public final class CarbonChatVelocityModule extends AbstractModule {
public void configure() { public void configure() {
this.install(new CarbonCommonModule()); this.install(new CarbonCommonModule());
this.bind(CarbonChat.class).toInstance(this.carbonChatVelocity); this.bind(CarbonChat.class).to(CarbonChatVelocity.class);
this.bind(Logger.class).toInstance(this.logger);
this.bind(Path.class).annotatedWith(ForCarbon.class).toInstance(this.dataDirectory);
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(PlayerSuggestions.class).toInstance(new PlayerArgument.PlayerParser<Commander>()::suggestions);
this.bind(ProfileResolver.class).to(VelocityProfileResolver.class);
this.bind(Path.class).annotatedWith(DataDirectory.class).toInstance(this.dataDirectory);
this.bind(Logger.class).toInstance(this.logger);
this.bind(new TypeLiteral<UserManager<?>>() {}).to(VelocityUserManager.class);
this.bind(new TypeLiteral<UserManagerInternal<?>>() {}).to(VelocityUserManager.class);
} }
} }
@@ -1,7 +1,7 @@
/* /*
* CarbonChat * CarbonChat
* *
* Copyright (c) 2021 Josua Parks (Vicarious) * Copyright (c) 2023 Josua Parks (Vicarious)
* Contributors * Contributors
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
@@ -19,31 +19,18 @@
*/ */
package net.draycia.carbon.velocity; package net.draycia.carbon.velocity;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.inject.Inject; import com.google.inject.Inject;
import com.velocitypowered.api.proxy.ProxyServer; import com.velocitypowered.api.proxy.ProxyServer;
import com.velocitypowered.api.util.UuidUtils;
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.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.UUID;
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.api.users.UserManager;
import net.draycia.carbon.common.users.CarbonPlayerCommon; import net.draycia.carbon.common.users.UserManagerInternal;
import net.draycia.carbon.common.util.FastUuidSansHyphens;
import net.draycia.carbon.velocity.users.CarbonPlayerVelocity; import net.draycia.carbon.velocity.users.CarbonPlayerVelocity;
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.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;
@@ -51,15 +38,12 @@ import org.jetbrains.annotations.NotNull;
public final class CarbonServerVelocity implements CarbonServer, ForwardingAudience.Single { public final class CarbonServerVelocity implements CarbonServer, ForwardingAudience.Single {
private final ProxyServer server; private final ProxyServer server;
private final UserManager<CarbonPlayerVelocity> userManager; private final UserManager<?> userManager;
private final HttpClient client = HttpClient.newHttpClient();
private final Gson gson = new Gson();
@Inject @Inject
private CarbonServerVelocity(final ProxyServer server, final UserManager<CarbonPlayerCommon> userManager) { private CarbonServerVelocity(final ProxyServer server, final UserManagerInternal<?> userManager) {
this.server = server; this.server = server;
this.userManager = new VelocityUserManager(userManager, server); this.userManager = userManager;
} }
@Override @Override
@@ -77,79 +61,17 @@ public final class CarbonServerVelocity implements CarbonServer, ForwardingAudie
final var players = new ArrayList<CarbonPlayerVelocity>(); final var players = new ArrayList<CarbonPlayerVelocity>();
for (final var player : this.server.getAllPlayers()) { for (final var player : this.server.getAllPlayers()) {
final ComponentPlayerResult<CarbonPlayerVelocity> carbonPlayer = this.userManager.carbonPlayer(player.getUniqueId()).join(); final CarbonPlayerVelocity carbonPlayer = (CarbonPlayerVelocity) this.userManager.user(player.getUniqueId()).join();
if (carbonPlayer.player() != null) { carbonPlayer.player().ifPresent(p -> players.add(carbonPlayer));
players.add(carbonPlayer.player());
}
} }
return players; return players;
} }
@Override @Override
public UserManager<CarbonPlayerVelocity> userManager() { public UserManager<? extends CarbonPlayer> userManager() {
return this.userManager; return this.userManager;
} }
@Override
public CompletableFuture<@Nullable UUID> resolveUUID(final String username) {
return CompletableFuture.supplyAsync(() -> {
final var serverPlayer = this.server.getPlayer(username);
if (serverPlayer.isPresent()) {
return serverPlayer.get().getUniqueId();
}
try {
final @Nullable JsonObject json = this.queryMojang(new URI("https://api.mojang.com/users/profiles/minecraft/" + username));
return FastUuidSansHyphens.parseUuid(json.get("id").getAsString());
} catch (final URISyntaxException exception) {
exception.printStackTrace();
}
return null;
});
}
@Override
public CompletableFuture<@Nullable String> resolveName(final UUID uuid) {
return CompletableFuture.supplyAsync(() -> {
final var serverPlayer = this.server.getPlayer(uuid);
if (serverPlayer.isPresent()) {
return serverPlayer.get().getUsername();
}
try {
final @Nullable JsonObject json = this.queryMojang(new URI("https://sessionserver.mojang.com/session/minecraft/profile/" + UuidUtils.toUndashed(uuid)));
return json.get("name").getAsString();
} catch (final URISyntaxException exception) {
exception.printStackTrace();
}
return null;
});
}
private @Nullable JsonObject queryMojang(final URI uri) {
final HttpRequest request = HttpRequest
.newBuilder(uri)
.GET()
.build();
try {
final HttpResponse<String> response =
this.client.send(request, HttpResponse.BodyHandlers.ofString());
final String mojangResponse = response.body();
return this.gson.fromJson(mojangResponse, JsonObject.class);
} catch (IOException | InterruptedException e) {
e.printStackTrace();
return null;
}
}
} }
@@ -0,0 +1,71 @@
/*
* 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.velocity;
import com.google.inject.Inject;
import com.google.inject.Injector;
import com.velocitypowered.api.event.Subscribe;
import com.velocitypowered.api.event.proxy.ProxyInitializeEvent;
import com.velocitypowered.api.event.proxy.ProxyShutdownEvent;
import com.velocitypowered.api.plugin.Dependency;
import com.velocitypowered.api.plugin.Plugin;
import com.velocitypowered.api.plugin.PluginContainer;
import com.velocitypowered.api.plugin.annotation.DataDirectory;
import com.velocitypowered.api.proxy.ProxyServer;
import java.nio.file.Path;
@Plugin(
id = "$[ID]",
name = "$[NAME]",
version = "$[VERSION]",
description = "$[DESCRIPTION]",
url = "$[URL]",
authors = {"Draycia"},
dependencies = {
@Dependency(id = "luckperms"),
@Dependency(id = "miniplaceholders", optional = true)
}
)
public class CarbonVelocityBootstrap {
@Inject
private Injector injector;
@Inject
private ProxyServer proxyServer;
@Inject
private PluginContainer pluginContainer;
@Inject
@DataDirectory
private Path dataDirectory;
private CarbonChatVelocity carbonVelocity;
@Subscribe
void onProxyInitialize(final ProxyInitializeEvent event) {
this.carbonVelocity = this.injector.createChildInjector(new CarbonChatVelocityModule(
this.pluginContainer, this.proxyServer, this.dataDirectory)).getInstance(CarbonChatVelocity.class);
this.carbonVelocity.onInitialization(this);
}
@Subscribe
void onProxyShutdown(final ProxyShutdownEvent event) {
this.carbonVelocity.onShutdown();
}
}
@@ -1,7 +1,7 @@
/* /*
* CarbonChat * CarbonChat
* *
* Copyright (c) 2021 Josua Parks (Vicarious) * Copyright (c) 2023 Josua Parks (Vicarious)
* Contributors * Contributors
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
@@ -20,30 +20,33 @@
package net.draycia.carbon.velocity; package net.draycia.carbon.velocity;
import com.google.inject.Inject; import com.google.inject.Inject;
import com.velocitypowered.api.plugin.PluginManager;
import io.github.miniplaceholders.api.MiniPlaceholders;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.lang.reflect.Type; import java.lang.reflect.Type;
import java.util.Map; import java.util.Map;
import net.draycia.carbon.api.util.Component; import net.draycia.carbon.api.users.CarbonPlayer;
import net.draycia.carbon.api.util.SourcedAudience;
import net.draycia.carbon.common.config.ConfigFactory; import net.draycia.carbon.common.config.ConfigFactory;
import net.kyori.adventure.audience.Audience; import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.audience.MessageType;
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;
import net.kyori.adventure.text.minimessage.tag.resolver.TagResolver; import net.kyori.adventure.text.minimessage.tag.resolver.TagResolver;
import net.kyori.moonshine.message.IMessageRenderer; import net.kyori.moonshine.message.IMessageRenderer;
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 VelocityMessageRenderer<T extends Audience> implements IMessageRenderer<T, String, Component, Component> { public class VelocityMessageRenderer<T extends Audience> implements IMessageRenderer<T, String, Component, Component> {
private final ConfigFactory configFactory; private final ConfigFactory configFactory;
private final PluginManager pluginManager;
@Inject @Inject
public VelocityMessageRenderer(final ConfigFactory configFactory) { public VelocityMessageRenderer(final ConfigFactory configFactory, final PluginManager pluginManager) {
this.configFactory = configFactory; this.configFactory = configFactory;
this.pluginManager = pluginManager;
} }
@Override @Override
@@ -69,17 +72,21 @@ public class VelocityMessageRenderer<T extends Audience> implements IMessageRend
entry.getValue()); entry.getValue());
} }
final Component message = MiniMessage.miniMessage().deserialize(placeholderResolvedMessage, tagResolver.build()); if (this.pluginManager.isLoaded("miniplaceholders")) {
final MessageType messageType; tagResolver.resolver(MiniPlaceholders.getGlobalPlaceholders());
final @Nullable ChatType chatType = method.getAnnotation(ChatType.class);
if (chatType != null) { if (receiver instanceof SourcedAudience sourced) {
messageType = chatType.value(); if (sourced.sender() instanceof CarbonPlayer sender) {
if (sourced.recipient() instanceof CarbonPlayer recipient) {
tagResolver.resolver(MiniPlaceholders.getRelationalPlaceholders(sender, recipient));
} else { } else {
messageType = MessageType.SYSTEM; tagResolver.resolver(MiniPlaceholders.getAudiencePlaceholders(sender));
}
}
}
} }
return new Component(message, messageType); return MiniMessage.miniMessage().deserialize(placeholderResolvedMessage, tagResolver.build());
} }
} }
@@ -1,7 +1,7 @@
/* /*
* CarbonChat * CarbonChat
* *
* Copyright (c) 2021 Josua Parks (Vicarious) * Copyright (c) 2023 Josua Parks (Vicarious)
* Contributors * Contributors
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
@@ -19,143 +19,40 @@
*/ */
package net.draycia.carbon.velocity; package net.draycia.carbon.velocity;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.velocitypowered.api.proxy.ProxyServer; import com.velocitypowered.api.proxy.ProxyServer;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
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.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.velocity.users.CarbonPlayerVelocity; import net.draycia.carbon.velocity.users.CarbonPlayerVelocity;
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 VelocityUserManager implements UserManager<CarbonPlayerVelocity>, SaveOnChange { @Singleton
public class VelocityUserManager extends PlatformUserManager<CarbonPlayerVelocity> {
protected final UserManager<CarbonPlayerCommon> proxiedUserManager; protected final UserManager<CarbonPlayerCommon> proxiedUserManager;
private final ProxyServer proxyServer; private final ProxyServer proxyServer;
public VelocityUserManager(final UserManager<CarbonPlayerCommon> proxiedUserManager, final ProxyServer proxyServer) { @Inject
public VelocityUserManager(@Backing final UserManagerInternal<CarbonPlayerCommon> proxiedUserManager, final ProxyServer proxyServer) {
super(proxiedUserManager);
this.proxiedUserManager = proxiedUserManager; this.proxiedUserManager = proxiedUserManager;
this.proxyServer = proxyServer; this.proxyServer = proxyServer;
} }
@Override @Override
public CompletableFuture<ComponentPlayerResult<CarbonPlayerVelocity>> carbonPlayer(final UUID uuid) { protected CarbonPlayerVelocity wrap(final CarbonPlayerCommon common) {
return this.proxiedUserManager.carbonPlayer(uuid).thenApply(result -> { return new CarbonPlayerVelocity(this.proxyServer, common);
if (result.player() == null) {
return new ComponentPlayerResult<>(null, result.reason());
}
return new ComponentPlayerResult<>(new CarbonPlayerVelocity(this.proxyServer, result.player()), result.reason());
});
} }
@Override @Override
public CompletableFuture<ComponentPlayerResult<CarbonPlayerVelocity>> savePlayer(final CarbonPlayerVelocity player) { protected void updateTransientLoadedStatus(final CarbonPlayerVelocity 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 CarbonPlayerVelocity(this.proxyServer, result.player()), result.reason());
});
}
@Override
public CompletableFuture<ComponentPlayerResult<CarbonPlayerVelocity>> saveAndInvalidatePlayer(final CarbonPlayerVelocity player) {
return this.proxiedUserManager.saveAndInvalidatePlayer(player.carbonPlayerCommon()).thenApply(result -> {
if (result.player() == null) {
return new ComponentPlayerResult<>(null, result.reason());
}
return new ComponentPlayerResult<>(new CarbonPlayerVelocity(this.proxyServer, 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;
} }
} }
@@ -1,7 +1,7 @@
/* /*
* CarbonChat * CarbonChat
* *
* Copyright (c) 2021 Josua Parks (Vicarious) * Copyright (c) 2023 Josua Parks (Vicarious)
* Contributors * Contributors
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
@@ -43,6 +43,10 @@ public interface VelocityCommander extends Commander, ForwardingAudience.Single
return this.commandSource; return this.commandSource;
} }
@Override
public boolean hasPermission(final String permission) {
return this.commandSource.hasPermission(permission);
}
} }
} }
@@ -1,7 +1,7 @@
/* /*
* CarbonChat * CarbonChat
* *
* Copyright (c) 2021 Josua Parks (Vicarious) * Copyright (c) 2023 Josua Parks (Vicarious)
* Contributors * Contributors
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
@@ -21,8 +21,8 @@ package net.draycia.carbon.velocity.command;
import com.velocitypowered.api.command.CommandSource; import com.velocitypowered.api.command.CommandSource;
import com.velocitypowered.api.proxy.Player; import com.velocitypowered.api.proxy.Player;
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.PlayerCommander; import net.draycia.carbon.common.command.PlayerCommander;
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;
@@ -33,7 +33,7 @@ import static java.util.Objects.requireNonNull;
@DefaultQualifier(NonNull.class) @DefaultQualifier(NonNull.class)
public record VelocityPlayerCommander( public record VelocityPlayerCommander(
CarbonChat carbon, UserManager<?> userManager,
Player player Player player
) implements PlayerCommander, VelocityCommander { ) implements PlayerCommander, VelocityCommander {
@@ -49,7 +49,12 @@ public record VelocityPlayerCommander(
@Override @Override
public CarbonPlayer carbonPlayer() { public CarbonPlayer carbonPlayer() {
return requireNonNull(this.carbon.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
public boolean hasPermission(final String permission) {
return this.player.hasPermission(permission);
} }
} }
@@ -1,7 +1,7 @@
/* /*
* CarbonChat * CarbonChat
* *
* Copyright (c) 2021 Josua Parks (Vicarious) * Copyright (c) 2023 Josua Parks (Vicarious)
* Contributors * Contributors
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
@@ -28,16 +28,13 @@ import net.draycia.carbon.api.CarbonChat;
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.users.UserManager;
import net.draycia.carbon.api.util.KeyedRenderer; import net.draycia.carbon.api.util.KeyedRenderer;
import net.draycia.carbon.velocity.CarbonChatVelocity; import net.draycia.carbon.velocity.CarbonChatVelocity;
import net.kyori.adventure.audience.MessageType;
import net.kyori.adventure.identity.Identity;
import net.kyori.adventure.text.Component; import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.TextReplacementConfig; import net.kyori.adventure.text.TextReplacementConfig;
import net.kyori.adventure.text.event.ClickEvent; import net.kyori.adventure.text.event.ClickEvent;
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.requireNonNullElse; import static java.util.Objects.requireNonNullElse;
@@ -51,13 +48,15 @@ public final class VelocityChatListener {
private final CarbonChatVelocity carbonChat; private final CarbonChatVelocity carbonChat;
private final ChannelRegistry registry; private final ChannelRegistry registry;
private final UserManager<?> userManager;
private static final Pattern DEFAULT_URL_PATTERN = Pattern.compile("(?:(https?)://)?([-\\w_.]+\\.\\w{2,})(/\\S*)?"); private static final Pattern DEFAULT_URL_PATTERN = Pattern.compile("(?:(https?)://)?([-\\w_.]+\\.\\w{2,})(/\\S*)?");
@Inject @Inject
private VelocityChatListener(final CarbonChat carbonChat, final ChannelRegistry registry) { private VelocityChatListener(final CarbonChat carbonChat, final ChannelRegistry registry, final UserManager<?> userManager) {
this.carbonChat = (CarbonChatVelocity) carbonChat; this.carbonChat = (CarbonChatVelocity) carbonChat;
this.registry = registry; this.registry = registry;
this.userManager = userManager;
} }
@Subscribe @Subscribe
@@ -68,15 +67,8 @@ public final class VelocityChatListener {
event.setResult(PlayerChatEvent.ChatResult.denied()); event.setResult(PlayerChatEvent.ChatResult.denied());
final ComponentPlayerResult<? extends CarbonPlayer> playerResult = this.carbonChat.server().userManager().carbonPlayer(event.getPlayer().getUniqueId()).join(); final CarbonPlayer sender = this.userManager.user(event.getPlayer().getUniqueId()).join();
final @Nullable CarbonPlayer sender = playerResult.player();
if (sender == null) {
return;
}
var channel = requireNonNullElse(sender.selectedChannel(), this.registry.defaultValue()); var channel = requireNonNullElse(sender.selectedChannel(), this.registry.defaultValue());
final var originalMessage = event.getResult().getMessage().orElse(event.getMessage()); final var originalMessage = event.getResult().getMessage().orElse(event.getMessage());
Component eventMessage = text(originalMessage); Component eventMessage = text(originalMessage);
@@ -108,7 +100,7 @@ public final class VelocityChatListener {
final var renderers = new ArrayList<KeyedRenderer>(); final var renderers = new ArrayList<KeyedRenderer>();
renderers.add(keyedRenderer(key("carbon", "default"), channel)); renderers.add(keyedRenderer(key("carbon", "default"), channel));
final var chatEvent = new CarbonChatEvent(sender, eventMessage, recipients, renderers, channel, false); final var chatEvent = new CarbonChatEvent(sender, eventMessage, recipients, renderers, channel, null);
final var result = this.carbonChat.eventHandler().emit(chatEvent); final var result = this.carbonChat.eventHandler().emit(chatEvent);
if (!result.wasSuccessful()) { if (!result.wasSuccessful()) {
@@ -128,13 +120,7 @@ public final class VelocityChatListener {
renderedMessage = renderer.render(sender, recipient, renderedMessage, chatEvent.message()); renderedMessage = renderer.render(sender, recipient, renderedMessage, chatEvent.message());
} }
final Identity identity = sender.hasPermission("carbon.hideidentity") ? Identity.nil() : sender.identity(); recipient.sendMessage(renderedMessage);
if (!(recipient instanceof CarbonPlayer)) {
recipient.sendMessage(identity, renderedMessage);
} else {
recipient.sendMessage(identity, renderedMessage);
}
} }
event.setResult(PlayerChatEvent.ChatResult.denied()); event.setResult(PlayerChatEvent.ChatResult.denied());
@@ -1,7 +1,7 @@
/* /*
* CarbonChat * CarbonChat
* *
* Copyright (c) 2021 Josua Parks (Vicarious) * Copyright (c) 2023 Josua Parks (Vicarious)
* Contributors * Contributors
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
@@ -22,37 +22,40 @@ package net.draycia.carbon.velocity.listeners;
import com.google.inject.Inject; import com.google.inject.Inject;
import com.velocitypowered.api.event.Subscribe; import com.velocitypowered.api.event.Subscribe;
import com.velocitypowered.api.event.connection.DisconnectEvent; import com.velocitypowered.api.event.connection.DisconnectEvent;
import net.draycia.carbon.api.CarbonChat; import com.velocitypowered.api.event.connection.LoginEvent;
import net.draycia.carbon.api.users.UserManager; import net.draycia.carbon.velocity.VelocityUserManager;
import net.draycia.carbon.common.users.CarbonPlayerCommon;
import net.draycia.carbon.common.util.PlayerUtils;
import net.draycia.carbon.velocity.users.CarbonPlayerVelocity;
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.slf4j.Logger;
@DefaultQualifier(NonNull.class) @DefaultQualifier(NonNull.class)
public class VelocityPlayerJoinListener { public class VelocityPlayerJoinListener {
private final CarbonChat carbonChat; private final VelocityUserManager userManager;
private final UserManager<CarbonPlayerCommon> userManager; private final Logger logger;
@Inject @Inject
public VelocityPlayerJoinListener( public VelocityPlayerJoinListener(
final CarbonChat carbonChat, final VelocityUserManager userManager,
final UserManager<CarbonPlayerCommon> userManager final Logger logger
) { ) {
this.carbonChat = carbonChat;
this.userManager = userManager; this.userManager = userManager;
this.logger = logger;
}
@Subscribe
public void onPlayerJoin(final LoginEvent event) {
this.userManager.user(event.getPlayer().getUniqueId()).exceptionally(thr -> {
this.logger.warn("Exception handling player join", thr);
return null;
});
} }
@Subscribe @Subscribe
public void onPlayerLeave(final DisconnectEvent event) { public void onPlayerLeave(final DisconnectEvent event) {
this.carbonChat.server().userManager().carbonPlayer(event.getPlayer().getUniqueId()).thenAccept(result -> { this.userManager.loggedOut(event.getPlayer().getUniqueId()).exceptionally(ex -> {
if (result.player() == null) { this.logger.warn("Exception saving data for player " + event.getPlayer().getUsername() + " with uuid " + event.getPlayer().getUniqueId());
return; return null;
}
PlayerUtils.saveAndInvalidatePlayer(this.carbonChat.server(), this.userManager, (CarbonPlayerVelocity) result.player());
}); });
} }
@@ -1,7 +1,7 @@
/* /*
* CarbonChat * CarbonChat
* *
* Copyright (c) 2021 Josua Parks (Vicarious) * Copyright (c) 2023 Josua Parks (Vicarious)
* Contributors * Contributors
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
@@ -21,14 +21,17 @@ package net.draycia.carbon.velocity.users;
import com.velocitypowered.api.proxy.Player; import com.velocitypowered.api.proxy.Player;
import com.velocitypowered.api.proxy.ProxyServer; import com.velocitypowered.api.proxy.ProxyServer;
import java.util.List;
import java.util.Locale; import java.util.Locale;
import java.util.Optional; import java.util.Optional;
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;
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.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.key.Key;
import net.kyori.adventure.text.Component; 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;
@@ -53,10 +56,26 @@ public final class CarbonPlayerVelocity extends WrappedCarbonPlayer implements F
@Override @Override
public boolean vanished() { public boolean vanished() {
//TODO: VelocityVanish compatibility
return false; return false;
} }
private Optional<Player> player() { @Override
public List<Key> leftChannels() {
return this.carbonPlayerCommon.leftChannels();
}
@Override
public void joinChannel(final ChatChannel channel) {
this.carbonPlayerCommon.joinChannel(channel);
}
@Override
public void leaveChannel(final ChatChannel channel) {
this.carbonPlayerCommon.leaveChannel(channel);
}
public Optional<Player> player() {
return this.server.getPlayer(this.uuid()); return this.server.getPlayer(this.uuid());
} }
@@ -84,11 +103,8 @@ public final class CarbonPlayerVelocity extends WrappedCarbonPlayer implements F
return false; return false;
} }
if (player.get().getCurrentServer().isEmpty() || otherPlayer.get().getCurrentServer().isEmpty()) { final var playerServer = player.get().getCurrentServer();
return false; return playerServer.isPresent() && playerServer.equals(otherPlayer.get().getCurrentServer());
}
return player.get().getCurrentServer().get().equals(otherPlayer.get().getCurrentServer().get());
} }
@Override @Override
@@ -98,7 +114,8 @@ public final class CarbonPlayerVelocity extends WrappedCarbonPlayer implements F
@Override @Override
public boolean online() { public boolean online() {
return this.player().isPresent(); final var player = this.player();
return player.isPresent() && player.get().isActive();
} }
} }
@@ -0,0 +1,67 @@
/*
* 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.velocity.users;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.velocitypowered.api.proxy.ProxyServer;
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.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.checkerframework.framework.qual.DefaultQualifier;
@Singleton
@DefaultQualifier(NonNull.class)
public class VelocityProfileResolver implements ProfileResolver {
private final ProxyServer proxyServer;
private final MojangProfileResolver mojang;
@Inject
public VelocityProfileResolver(final ProxyServer proxyServer, final MojangProfileResolver mojang) {
this.proxyServer = proxyServer;
this.mojang = mojang;
}
@Override
public CompletableFuture<@Nullable UUID> resolveUUID(final String username, final boolean cacheOnly) {
final var serverPlayer = this.proxyServer.getPlayer(username);
return serverPlayer.map(player -> CompletableFuture.completedFuture(player.getUniqueId()))
.orElseGet(() -> this.mojang.resolveUUID(username));
}
@Override
public CompletableFuture<@Nullable String> resolveName(final UUID uuid, final boolean cacheOnly) {
final var serverPlayer = this.proxyServer.getPlayer(uuid);
return serverPlayer.map(player -> CompletableFuture.completedFuture(player.getUsername()))
.orElseGet(() -> this.mojang.resolveName(uuid));
}
@Override
public void shutdown() {
this.mojang.shutdown();
}
}