Merge pull request #236 from 4drian3d/feat/miniplaceholders

Reimplement Velocity Module and added MiniPlaceholders support
This commit is contained in:
Josua Parks authored and GitHub committed 2023-04-14 18:03:07 -07:00
commit 8c764217f2
27 files changed
+450 -527

No files matched your search

+17 -1
View File
@@ -22,7 +22,7 @@ hangarPublish.publications.register("plugin") {
platformVersions.add("1.19.4")
dependencies {
url("LuckPerms", "https://luckperms.net/")
url("EssentialsDiscord", "https://essentialsx.net/") {
hangar("EssentialsX", "Essentials") {
required.set(false)
}
url("DiscordSRV", "https://www.spigotmc.org/resources/discordsrv.18494/") {
@@ -31,6 +31,22 @@ hangarPublish.publications.register("plugin") {
url("PlaceholderAPI", "https://www.spigotmc.org/resources/placeholderapi.6245/") {
required.set(false)
}
hangar("MiniPlaceholders", "MiniPlaceholders") {
required.set(false)
}
}
}
platforms.register(Platforms.VELOCITY) {
jar.set(project(":carbonchat-velocity").the<CarbonPlatformExtension>().jarTask.flatMap { it.archiveFile })
platformVersions.add("3.2")
dependencies {
url("LuckPerms", "https://luckperms.net/")
hangar("MiniPlaceholders", "MiniPlaceholders") {
required.set(false)
}
hangar("4drian3d", "UnSignedVelocity") {
required.set(false)
}
}
}
}
@@ -189,6 +189,10 @@ public abstract class CarbonChatInternal<C extends CarbonPlayer> implements Carb
return this.messagingManager.get().packetService();
}
public boolean isProxy() {
return false;
}
public Injector injector() {
return this.injector;
}
@@ -47,6 +47,7 @@ public class ConfigChannelMessageSource implements IMessageSource<SourcedAudienc
The "console" format is what's shown to console.
The "discord" format is what's shown to supported discord integrations.
If PlaceholderAPI is installed, PAPI placeholders (with %) are supported.
If MiniPlaceholders is installed, its placeholders (with <>) are supported.
The keys are group names, the values are chat formats (MiniMessage).
For example:
basic {
@@ -32,6 +32,7 @@ import java.util.function.Consumer;
import net.draycia.carbon.api.CarbonChat;
import net.draycia.carbon.api.CarbonChatProvider;
import net.draycia.carbon.api.events.CarbonShutdownEvent;
import net.draycia.carbon.common.CarbonChatInternal;
import net.draycia.carbon.common.config.ConfigFactory;
import net.draycia.carbon.common.config.MessagingSettings;
import net.draycia.carbon.common.listeners.PingHandler;
@@ -83,7 +84,9 @@ public class MessagingManager {
final PingHandler pingHandler
) {
if (!configFactory.primaryConfig().messagingSettings().enabled()) {
logger.info("Messaging services disabled in config. Cross-server will not work without this!");
if (!((CarbonChatInternal<?>) carbonChat).isProxy()) {
logger.info("Messaging services disabled in config. Cross-server will not work without this!");
}
this.messagingService = EMPTY_MESSAGING_SERVICE;
this.packetService = null;
this.carbonChat = carbonChat;
@@ -19,6 +19,11 @@
*/
package net.draycia.carbon.common.util;
import com.google.common.base.Suppliers;
import java.util.function.Supplier;
import java.util.regex.Pattern;
import net.kyori.adventure.text.TextReplacementConfig;
import net.kyori.adventure.text.event.ClickEvent;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.checkerframework.framework.qual.DefaultQualifier;
@@ -26,6 +31,14 @@ import org.checkerframework.framework.qual.DefaultQualifier;
@DefaultQualifier(NonNull.class)
public final class Strings {
private static final Pattern DEFAULT_URL_PATTERN = Pattern.compile("(?:(https?)://)?([-\\w_.]+\\.\\w{2,})(/\\S*)?");
public static final Supplier<TextReplacementConfig> URL_REPLACEMENT_CONFIG = Suppliers.memoize(
() -> TextReplacementConfig.builder()
.match(DEFAULT_URL_PATTERN)
.replacement(builder -> builder.clickEvent(ClickEvent.clickEvent(ClickEvent.Action.OPEN_URL, builder.content())))
.build()
);
private Strings() {
}
@@ -28,6 +28,7 @@ import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.minimessage.MiniMessage;
import net.kyori.adventure.text.minimessage.tag.Tag;
import net.kyori.adventure.text.minimessage.tag.resolver.Placeholder;
import net.kyori.adventure.text.minimessage.tag.resolver.TagResolver;
import net.kyori.moonshine.message.IMessageRenderer;
import org.checkerframework.checker.nullness.qual.NonNull;
@@ -57,16 +58,11 @@ public class FabricMessageRenderer<T extends Audience> implements IMessageRender
tagResolver.tag(entry.getKey(), Tag.inserting(entry.getValue()));
}
// https://github.com/KyoriPowered/adventure-text-minimessage/issues/131
// TLDR: 25/10/21, tags in templates aren't parsed. we want them parsed.
String placeholderResolvedMessage = intermediateMessage;
this.configFactory.primaryConfig().customPlaceholders().forEach(
(key, value) -> tagResolver.resolver(Placeholder.parsed(key, value))
);
for (final var entry : this.configFactory.primaryConfig().customPlaceholders().entrySet()) {
placeholderResolvedMessage = placeholderResolvedMessage.replace("<" + entry.getKey() + ">",
entry.getValue());
}
return MiniMessage.miniMessage().deserialize(placeholderResolvedMessage, tagResolver.build());
return MiniMessage.miniMessage().deserialize(intermediateMessage, tagResolver.build());
}
}
@@ -23,7 +23,6 @@ import java.util.ArrayList;
import java.util.Optional;
import java.util.UUID;
import java.util.function.Consumer;
import java.util.regex.Pattern;
import net.draycia.carbon.api.channels.ChannelRegistry;
import net.draycia.carbon.api.events.CarbonChatEvent;
import net.draycia.carbon.api.users.CarbonPlayer;
@@ -33,13 +32,13 @@ import net.draycia.carbon.fabric.callback.ChatCallback;
import net.kyori.adventure.identity.Identity;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.TextReplacementConfig;
import net.kyori.adventure.text.event.ClickEvent;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.checkerframework.framework.qual.DefaultQualifier;
import static java.util.Objects.requireNonNullElse;
import static net.draycia.carbon.api.util.KeyedRenderer.keyedRenderer;
import static net.draycia.carbon.common.util.Strings.URL_REPLACEMENT_CONFIG;
import static net.kyori.adventure.key.Key.key;
import static net.kyori.adventure.text.Component.empty;
import static net.kyori.adventure.text.Component.text;
@@ -50,8 +49,6 @@ public class FabricChatListener implements Consumer<ChatCallback.Chat> {
private final CarbonChatFabric carbonChatFabric;
private final ChannelRegistry channelRegistry;
private static final Pattern DEFAULT_URL_PATTERN = Pattern.compile("(?:(https?)://)?([-\\w_.]+\\.\\w{2,})(/\\S*)?");
public FabricChatListener(final CarbonChatFabric carbonChatFabric, final ChannelRegistry channelRegistry) {
this.carbonChatFabric = carbonChatFabric;
this.channelRegistry = channelRegistry;
@@ -66,10 +63,7 @@ public class FabricChatListener implements Consumer<ChatCallback.Chat> {
Component eventMessage = text(chat.message());
if (sender.hasPermission("carbon.chatlinks")) {
eventMessage = eventMessage.replaceText(TextReplacementConfig.builder()
.match(DEFAULT_URL_PATTERN)
.replacement(builder -> builder.clickEvent(ClickEvent.clickEvent(ClickEvent.Action.OPEN_URL, builder.content())))
.build());
eventMessage = eventMessage.replaceText(URL_REPLACEMENT_CONFIG.get());
}
for (final var chatChannel : this.channelRegistry) {
+13 -1
View File
@@ -7,6 +7,7 @@ plugins:
net.kyori.blossom: 1.3.0
org.spongepowered.gradle.plugin: 2.1.1
xyz.jpenilla.run-paper: 2.0.1
xyz.jpenilla.run-velocity: 2.0.1
io.papermc.hangar-publish-plugin: 0.0.5
versions:
@@ -30,7 +31,7 @@ versions:
kyoriMoonshine: 2.0.4
log4j: 2.17.2
guice: 5.1.0
velocityApi: 3.1.1
velocityApi: 3.2.0-SNAPSHOT
geantyref: 1.3.11
fabricMinecraft: 1.19.4
fabricLoader: 0.14.17
@@ -38,6 +39,8 @@ versions:
luckPermsApi: 5.3
essentialsx: 2.19.3
discordsrv: 1.26.0
placeholderapi: 2.10.9
miniplaceholders: 2.0.0
jdbi: 3.34.0
hikari: 5.0.1
mysql: 8.0.31
@@ -328,4 +331,13 @@ dependencies:
name: discordsrv
version: { ref: discordsrv }
placeholderapi:
group: me.clip
name: placeholderapi
version: { ref: placeholderapi }
miniplaceholders:
group: io.github.miniplaceholders
name: miniplaceholders-api
version: { ref: miniplaceholders }
bundles:
+3 -1
View File
@@ -20,7 +20,8 @@ dependencies {
implementation(libs.bstatsBukkit)
// Plugins
compileOnly("me.clip:placeholderapi:2.10.9") // TODO: move this to libs.versions.yml
compileOnly(libs.placeholderapi)
compileOnly(libs.miniplaceholders)
compileOnly(libs.essentialsXDiscord)
compileOnly(libs.discordsrv)
}
@@ -54,6 +55,7 @@ paper {
dependencies += PaperPluginDescription.Dependency("PlaceholderAPI", false)
dependencies += PaperPluginDescription.Dependency("EssentialsDiscord", false)
dependencies += PaperPluginDescription.Dependency("DiscordSRV", false)
dependencies += PaperPluginDescription.Dependency("MiniPlaceholders", false)
website = GITHUB_REPO_URL
}
@@ -137,4 +137,8 @@ public final class CarbonChatPaper extends CarbonChatInternal<CarbonPlayerPaper>
return Bukkit.getPluginManager().isPluginEnabled("PlaceholderAPI");
}
public static boolean miniPlaceholdersLoaded() {
return Bukkit.getPluginManager().isPluginEnabled("MiniPlaceholders");
}
}
@@ -23,7 +23,6 @@ import com.google.inject.Inject;
import io.papermc.paper.event.player.AsyncChatEvent;
import java.util.ArrayList;
import java.util.Map;
import java.util.regex.Pattern;
import net.draycia.carbon.api.CarbonChat;
import net.draycia.carbon.api.channels.ChannelRegistry;
import net.draycia.carbon.api.events.CarbonChatEvent;
@@ -37,7 +36,6 @@ import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.identity.Identity;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.TextReplacementConfig;
import net.kyori.adventure.text.event.ClickEvent;
import net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer;
import net.kyori.event.EventSubscriber;
import ninja.egg82.messenger.services.PacketService;
@@ -50,6 +48,7 @@ import org.checkerframework.framework.qual.DefaultQualifier;
import static java.util.Objects.requireNonNullElse;
import static net.draycia.carbon.api.util.KeyedRenderer.keyedRenderer;
import static net.draycia.carbon.common.util.Strings.URL_REPLACEMENT_CONFIG;
import static net.kyori.adventure.key.Key.key;
import static net.kyori.adventure.text.Component.text;
@@ -60,8 +59,6 @@ public final class PaperChatListener implements Listener {
private final ChannelRegistry registry;
private final CarbonMessages carbonMessages;
private static final Pattern DEFAULT_URL_PATTERN = Pattern.compile("(?:(https?)://)?([-\\w_.]+\\.\\w{2,})(/\\S*)?");
@Inject
public PaperChatListener(final CarbonChat carbonChat, final ChannelRegistry registry, final CarbonMessages carbonMessages) {
this.carbonChat = (CarbonChatPaper) carbonChat;
@@ -82,10 +79,7 @@ public final class PaperChatListener implements Listener {
Component eventMessage = ConfigChatChannel.parseMessageTags(sender, messageContents);
if (sender.hasPermission("carbon.chatlinks")) {
eventMessage = eventMessage.replaceText(TextReplacementConfig.builder()
.match(DEFAULT_URL_PATTERN)
.replacement(builder -> builder.clickEvent(ClickEvent.clickEvent(ClickEvent.Action.OPEN_URL, builder.content())))
.build());
eventMessage = eventMessage.replaceText(URL_REPLACEMENT_CONFIG.get());
}
for (final var chatChannel : this.registry) {
@@ -21,6 +21,7 @@ package net.draycia.carbon.paper.messages;
import com.google.common.base.Suppliers;
import com.google.inject.Inject;
import io.github.miniplaceholders.api.MiniPlaceholders;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.Map;
@@ -33,6 +34,7 @@ import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.minimessage.MiniMessage;
import net.kyori.adventure.text.minimessage.tag.Tag;
import net.kyori.adventure.text.minimessage.tag.resolver.Placeholder;
import net.kyori.adventure.text.minimessage.tag.resolver.TagResolver;
import net.kyori.moonshine.message.IMessageRenderer;
import org.bukkit.Bukkit;
@@ -50,6 +52,8 @@ public class PaperMessageRenderer<T extends Audience> implements IMessageRendere
return null;
});
private final Supplier<Boolean> miniPlaceholdersAvailable = Suppliers.memoize(CarbonChatPaper::miniPlaceholdersLoaded);
private final MiniMessage miniMessage;
private final ConfigFactory configFactory;
@@ -73,33 +77,44 @@ public class PaperMessageRenderer<T extends Audience> implements IMessageRendere
tagResolver.tag(entry.getKey(), Tag.inserting(entry.getValue()));
}
// https://github.com/KyoriPowered/adventure-text-minimessage/issues/131
// TLDR: 25/10/21, tags in templates aren't parsed. we want them parsed.
String placeholderResolvedMessage = intermediateMessage;
this.configFactory.primaryConfig().customPlaceholders().forEach(
(key, value) -> tagResolver.resolver(Placeholder.parsed(key, value))
);
for (final var entry : this.configFactory.primaryConfig().customPlaceholders().entrySet()) {
placeholderResolvedMessage = placeholderResolvedMessage.replace("<" + entry.getKey() + ">",
entry.getValue());
if (this.miniPlaceholdersAvailable.get()) {
tagResolver.resolver(MiniPlaceholders.getGlobalPlaceholders());
}
final Component message;
if (!(receiver instanceof SourcedAudience sourced)) {
return this.miniMessage.deserialize(intermediateMessage, tagResolver.build());
}
if (receiver instanceof SourcedAudience sourced && this.parser.get() != null) {
if (sourced.sender() instanceof CarbonPlayer sender && sender.online()) {
if (sourced.recipient() instanceof CarbonPlayer recipient && recipient.online()) {
message = this.parser.get().parseRelational(Bukkit.getPlayer(sender.uuid()),
Bukkit.getPlayer(recipient.uuid()), placeholderResolvedMessage, tagResolver.build());
} else {
message = this.parser.get().parse(Bukkit.getPlayer(sender.uuid()), placeholderResolvedMessage, tagResolver.build());
}
} else {
message = this.miniMessage.deserialize(placeholderResolvedMessage, tagResolver.build());
if (!(sourced.sender() instanceof CarbonPlayer sender) || sender.online()) {
return this.miniMessage.deserialize(intermediateMessage, tagResolver.build());
}
if (!(sourced.recipient() instanceof CarbonPlayer recipient && recipient.online())) {
if (this.miniPlaceholdersAvailable.get()) {
tagResolver.resolver(MiniPlaceholders.getAudiencePlaceholders(Bukkit.getPlayer(sender.uuid())));
}
} else {
message = this.miniMessage.deserialize(placeholderResolvedMessage, tagResolver.build());
if (this.parser.get() != null) {
return this.parser.get().parse(Bukkit.getPlayer(sender.uuid()), intermediateMessage, tagResolver.build());
}
return this.miniMessage.deserialize(intermediateMessage, tagResolver.build());
}
return message;
if (this.miniPlaceholdersAvailable.get()) {
tagResolver.resolver(MiniPlaceholders.getRelationalPlaceholders(
Bukkit.getPlayer(sender.uuid()),
Bukkit.getPlayer(recipient.uuid())
));
}
if (this.parser.get() != null) {
return this.parser.get().parseRelational(Bukkit.getPlayer(sender.uuid()),
Bukkit.getPlayer(recipient.uuid()), intermediateMessage, tagResolver.build());
}
return this.miniMessage.deserialize(intermediateMessage, tagResolver.build());
}
}
+1 -1
View File
@@ -85,7 +85,7 @@ sequenceOf(
"paper",
// "sponge", // TODO API 10
"fabric",
// "velocity"
"velocity"
).forEach {
include("carbonchat-$it")
project(":carbonchat-$it").projectDir = file(it)
@@ -23,7 +23,6 @@ import com.google.inject.Inject;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.Map;
import net.draycia.carbon.api.util.Component;
import net.draycia.carbon.common.config.ConfigFactory;
import net.draycia.carbon.common.util.ChatType;
import net.kyori.adventure.audience.Audience;
@@ -31,6 +30,7 @@ import net.kyori.adventure.audience.MessageType;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.minimessage.MiniMessage;
import net.kyori.adventure.text.minimessage.tag.Tag;
import net.kyori.adventure.text.minimessage.tag.resolver.Placeholder;
import net.kyori.adventure.text.minimessage.tag.resolver.TagResolver;
import net.kyori.moonshine.message.IMessageRenderer;
import org.checkerframework.checker.nullness.qual.NonNull;
@@ -61,26 +61,11 @@ public class SpongeMessageRenderer<T extends Audience> implements IMessageRender
tagResolver.tag(entry.getKey(), Tag.inserting(entry.getValue()));
}
// https://github.com/KyoriPowered/adventure-text-minimessage/issues/131
// TLDR: 25/10/21, tags in templates aren't parsed. we want them parsed.
String placeholderResolvedMessage = intermediateMessage;
this.configFactory.primaryConfig().customPlaceholders().forEach(
(key, value) -> tagResolver.resolver(Placeholder.unparsed(key, value))
);
for (final var entry : this.configFactory.primaryConfig().customPlaceholders().entrySet()) {
placeholderResolvedMessage = placeholderResolvedMessage.replace("<" + entry.getKey() + ">",
entry.getValue());
}
final Component message = MiniMessage.miniMessage().deserialize(placeholderResolvedMessage, tagResolver.build());
final MessageType messageType;
final @Nullable ChatType chatType = method.getAnnotation(ChatType.class);
if (chatType != null) {
messageType = chatType.value();
} else {
messageType = MessageType.SYSTEM;
}
return new Component(message, messageType);
return MiniMessage.miniMessage().deserialize(intermediateMessage, tagResolver.build());;
}
}
+6 -32
View File
@@ -1,16 +1,9 @@
import java.util.*
import java.util.Locale
plugins {
id("carbon.shadow-platform")
id("net.kyori.blossom")
}
val velocityRun: Configuration by configurations.creating {
attributes {
attribute(Usage.USAGE_ATTRIBUTE, objects.named(Usage::class, Usage.JAVA_RUNTIME))
attribute(Category.CATEGORY_ATTRIBUTE, objects.named(Category::class, Category.LIBRARY))
attribute(LibraryElements.LIBRARY_ELEMENTS_ATTRIBUTE, objects.named(LibraryElements::class, LibraryElements.JAR))
}
id("xyz.jpenilla.run-velocity")
}
dependencies {
@@ -20,8 +13,7 @@ dependencies {
annotationProcessor(libs.velocityApi)
implementation(libs.cloudVelocity)
velocityRun("com.velocitypowered", "velocity-proxy", libs.versions.velocityApi.get())
compileOnly(libs.miniplaceholders)
}
tasks {
@@ -35,32 +27,14 @@ tasks {
exclude(dependency("javax.inject:javax.inject"))
}
}
register<JavaExec>("runProxy") {
group = "carbon"
standardInput = System.`in`
classpath(velocityRun.asFileTree)
workingDir = layout.projectDirectory.dir("run").asFile
val pluginJar = shadowJar.flatMap { it.archiveFile }
inputs.file(pluginJar)
doFirst {
if (!workingDir.exists()) {
workingDir.mkdirs()
}
val plugins = workingDir.resolve("plugins")
if (!plugins.exists()) {
plugins.mkdirs()
}
pluginJar.get().asFile.copyTo(plugins.resolve("carbon.jar"), overwrite = true)
}
runVelocity {
velocityVersion(libs.versions.velocityApi.get())
}
}
blossom {
mapOf(
"ID" to rootProject.name.toLowerCase(Locale.ROOT),
"ID" to rootProject.name.lowercase(Locale.ROOT),
"NAME" to rootProject.name,
"VERSION" to version,
"DESCRIPTION" to description,
@@ -1,7 +1,7 @@
/*
* CarbonChat
*
* Copyright (c) 2021 Josua Parks (Vicarious)
* Copyright (c) 2023 Josua Parks (Vicarious)
* Contributors
*
* This program is free software: you can redistribute it and/or modify
@@ -21,158 +21,99 @@ 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.plugin.Dependency;
import com.velocitypowered.api.plugin.Plugin;
import com.google.inject.Provider;
import com.google.inject.Singleton;
import com.velocitypowered.api.plugin.PluginContainer;
import com.velocitypowered.api.plugin.annotation.DataDirectory;
import com.velocitypowered.api.proxy.ProxyServer;
import java.nio.file.Path;
import java.util.Set;
import java.util.UUID;
import net.draycia.carbon.api.CarbonChat;
import java.util.concurrent.ScheduledExecutorService;
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.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.command.commands.ExecutionCoordinatorHolder;
import net.draycia.carbon.common.messages.CarbonMessages;
import net.draycia.carbon.common.messaging.MessagingManager;
import net.draycia.carbon.common.util.CloudUtils;
import net.draycia.carbon.common.util.ListenerUtils;
import net.draycia.carbon.common.users.ProfileCache;
import net.draycia.carbon.common.users.ProfileResolver;
import net.draycia.carbon.velocity.listeners.VelocityChatListener;
import net.draycia.carbon.velocity.listeners.VelocityPlayerJoinListener;
import net.draycia.carbon.velocity.users.CarbonPlayerVelocity;
import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.text.Component;
import net.kyori.moonshine.message.IMessageRenderer;
import ninja.egg82.messenger.services.PacketService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.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;
@Plugin(
id = "$[ID]",
name = "$[NAME]",
version = "$[VERSION]",
description = "$[DESCRIPTION]",
url = "$[URL]",
authors = {"Draycia"},
dependencies = {@Dependency(id = "luckperms")}
)
@DefaultQualifier(NonNull.class)
public class CarbonChatVelocity implements CarbonChat {
@Singleton
public class CarbonChatVelocity extends CarbonChatInternal<CarbonPlayerVelocity> {
private static final Set<Class<?>> LISTENER_CLASSES = Set.of(
VelocityChatListener.class,
VelocityPlayerJoinListener.class
);
private final Path dataDirectory;
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
public CarbonChatVelocity(
@DataDirectory final Path dataDirectory,
final ProxyServer proxyServer,
final Injector injector,
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);
this.dataDirectory = dataDirectory;
super(
injector, LogManager.getLogger(pluginContainer.getDescription().getId()),
dataDirectory,
periodicTasks,
profileCache,
profileResolver,
userManager,
commandExecutor,
carbonServer,
carbonMessages,
eventHandler,
channelRegistry,
renderer,
messagingManager
);
this.proxyServer = proxyServer;
this.logger = LogManager.getLogger(pluginContainer.getDescription().getId());
final CarbonChatVelocityModule carbonVelocityModule;
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);
CarbonChatProvider.register(this);
}
@Subscribe
public void onProxyInitialization(final ProxyInitializeEvent event) {
public void onInitialization(final CarbonVelocityBootstrap carbonVelocityBootstrap) {
this.init();
this.packetService();
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
ListenerUtils.registerCommonListeners(this.injector);
// Load channels
((CarbonChannelRegistry) this.channelRegistry()).loadConfigChannels(this.carbonMessages);
// Commands
CloudUtils.loadCommands(this.injector);
final var commandSettings = CloudUtils.loadCommandSettings(this.injector);
CloudUtils.registerCommands(commandSettings);
public void onShutdown() {
this.shutdown();
}
@Override
public UUID serverId() {
return this.serverId;
}
@Override
public @Nullable PacketService packetService() {
if (this.messagingManager == null) {
this.messagingManager = this.injector.getInstance(MessagingManager.class);
}
return this.messagingManager.packetService();
}
@Override
public Logger logger() {
return this.logger;
}
@Override
public Path dataDirectory() {
return this.dataDirectory;
}
@Override
public 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;
public boolean isProxy() {
return true;
}
}
@@ -1,7 +1,7 @@
/*
* CarbonChat
*
* Copyright (c) 2021 Josua Parks (Vicarious)
* Copyright (c) 2023 Josua Parks (Vicarious)
* Contributors
*
* 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.Provides;
import com.google.inject.Singleton;
import com.google.inject.TypeLiteral;
import com.velocitypowered.api.plugin.PluginContainer;
import com.velocitypowered.api.proxy.Player;
import com.velocitypowered.api.proxy.ProxyServer;
import java.nio.file.Path;
import net.draycia.carbon.api.CarbonChat;
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.common.CarbonCommonModule;
import net.draycia.carbon.common.ForCarbon;
import net.draycia.carbon.common.DataDirectory;
import net.draycia.carbon.common.command.Commander;
import net.draycia.carbon.common.command.argument.PlayerSuggestions;
import net.draycia.carbon.common.users.ProfileResolver;
import net.draycia.carbon.common.users.UserManagerInternal;
import net.draycia.carbon.velocity.command.VelocityCommander;
import net.draycia.carbon.velocity.command.VelocityPlayerCommander;
import net.draycia.carbon.velocity.users.VelocityProfileResolver;
import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.text.Component;
import net.kyori.moonshine.message.IMessageRenderer;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.framework.qual.DefaultQualifier;
@@ -51,36 +56,31 @@ import org.checkerframework.framework.qual.DefaultQualifier;
@DefaultQualifier(NonNull.class)
public final class CarbonChatVelocityModule extends AbstractModule {
private final Logger logger;
private final Path dataDirectory;
private final Logger logger = LogManager.getLogger("carbonchat");
private final PluginContainer pluginContainer;
private final ProxyServer proxyServer;
private final CarbonChatVelocity carbonChatVelocity;
private final Path dataDirectory;
CarbonChatVelocityModule(
final Logger logger,
final Path dataDirectory,
final PluginContainer pluginContainer,
final ProxyServer proxyServer,
final CarbonChatVelocity carbonChatVelocity
final Path dataDirectory
) {
this.logger = logger;
this.dataDirectory = dataDirectory;
this.pluginContainer = pluginContainer;
this.proxyServer = proxyServer;
this.carbonChatVelocity = carbonChatVelocity;
this.dataDirectory = dataDirectory;
}
@Provides
@Singleton
public CommandManager<Commander> createCommandManager() {
public CommandManager<Commander> createCommandManager(final UserManager<?> userManager) {
final VelocityCommandManager<Commander> commandManager = new VelocityCommandManager<>(
this.pluginContainer,
this.proxyServer,
AsynchronousCommandExecutionCoordinator.<Commander>builder().build(),
commandSender -> {
if (commandSender instanceof Player player) {
return new VelocityPlayerCommander(this.carbonChatVelocity, player);
return new VelocityPlayerCommander(userManager, player);
}
return VelocityCommander.from(commandSender);
@@ -110,11 +110,14 @@ public final class CarbonChatVelocityModule extends AbstractModule {
public void configure() {
this.install(new CarbonCommonModule());
this.bind(CarbonChat.class).toInstance(this.carbonChatVelocity);
this.bind(Logger.class).toInstance(this.logger);
this.bind(Path.class).annotatedWith(ForCarbon.class).toInstance(this.dataDirectory);
this.bind(CarbonChat.class).to(CarbonChatVelocity.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(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
*
* Copyright (c) 2021 Josua Parks (Vicarious)
* Copyright (c) 2023 Josua Parks (Vicarious)
* Contributors
*
* This program is free software: you can redistribute it and/or modify
@@ -19,31 +19,17 @@
*/
package net.draycia.carbon.velocity;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.inject.Inject;
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.List;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.Objects;
import net.draycia.carbon.api.CarbonServer;
import net.draycia.carbon.api.users.ComponentPlayerResult;
import net.draycia.carbon.api.users.CarbonPlayer;
import net.draycia.carbon.api.users.UserManager;
import net.draycia.carbon.common.users.CarbonPlayerCommon;
import net.draycia.carbon.common.util.FastUuidSansHyphens;
import net.draycia.carbon.velocity.users.CarbonPlayerVelocity;
import net.draycia.carbon.common.users.UserManagerInternal;
import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.audience.ForwardingAudience;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.checkerframework.framework.qual.DefaultQualifier;
import org.jetbrains.annotations.NotNull;
@@ -51,20 +37,17 @@ import org.jetbrains.annotations.NotNull;
public final class CarbonServerVelocity implements CarbonServer, ForwardingAudience.Single {
private final ProxyServer server;
private final UserManager<CarbonPlayerVelocity> userManager;
private final HttpClient client = HttpClient.newHttpClient();
private final Gson gson = new Gson();
private final UserManager<?> userManager;
@Inject
private CarbonServerVelocity(final ProxyServer server, final UserManager<CarbonPlayerCommon> userManager) {
private CarbonServerVelocity(final ProxyServer server, final UserManagerInternal<?> userManager) {
this.server = server;
this.userManager = new VelocityUserManager(userManager, server);
this.userManager = userManager;
}
@Override
public @NotNull Audience audience() {
return Audience.audience(this.console(), Audience.audience(this.players()));
return this.server;
}
@Override
@@ -73,83 +56,16 @@ public final class CarbonServerVelocity implements CarbonServer, ForwardingAudie
}
@Override
public List<CarbonPlayerVelocity> players() {
final var players = new ArrayList<CarbonPlayerVelocity>();
for (final var player : this.server.getAllPlayers()) {
final ComponentPlayerResult<CarbonPlayerVelocity> carbonPlayer = this.userManager.carbonPlayer(player.getUniqueId()).join();
if (carbonPlayer.player() != null) {
players.add(carbonPlayer.player());
}
}
return players;
public List<? extends CarbonPlayer> players() {
return this.server.getAllPlayers().stream()
.map(player -> this.userManager.user(player.getUniqueId()).getNow(null))
.filter(Objects::nonNull)
.toList();
}
@Override
public UserManager<CarbonPlayerVelocity> userManager() {
public UserManager<? extends CarbonPlayer> 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 final class CarbonVelocityBootstrap {
private final CarbonChatVelocity carbonVelocity;
@Inject
public CarbonVelocityBootstrap(
final Injector injector,
final ProxyServer proxyServer,
final PluginContainer pluginContainer,
@DataDirectory final Path dataDirectory
) {
this.carbonVelocity = injector.createChildInjector(new CarbonChatVelocityModule(
pluginContainer, proxyServer, dataDirectory)).getInstance(CarbonChatVelocity.class);
}
@Subscribe
public void onProxyInitialize(final ProxyInitializeEvent event) {
this.carbonVelocity.onInitialization(this);
}
@Subscribe
public void onProxyShutdown(final ProxyShutdownEvent event) {
this.carbonVelocity.onShutdown();
}
}
@@ -1,7 +1,7 @@
/*
* CarbonChat
*
* Copyright (c) 2021 Josua Parks (Vicarious)
* Copyright (c) 2023 Josua Parks (Vicarious)
* Contributors
*
* This program is free software: you can redistribute it and/or modify
@@ -20,30 +20,34 @@
package net.draycia.carbon.velocity;
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.Type;
import java.util.Map;
import net.draycia.carbon.api.util.Component;
import net.draycia.carbon.api.util.SourcedAudience;
import net.draycia.carbon.common.config.ConfigFactory;
import net.draycia.carbon.velocity.users.CarbonPlayerVelocity;
import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.audience.MessageType;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.minimessage.MiniMessage;
import net.kyori.adventure.text.minimessage.tag.Tag;
import net.kyori.adventure.text.minimessage.tag.resolver.Placeholder;
import net.kyori.adventure.text.minimessage.tag.resolver.TagResolver;
import net.kyori.moonshine.message.IMessageRenderer;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.checkerframework.framework.qual.DefaultQualifier;
@DefaultQualifier(NonNull.class)
public class VelocityMessageRenderer<T extends Audience> implements IMessageRenderer<T, String, Component, Component> {
private final ConfigFactory configFactory;
private final PluginManager pluginManager;
@Inject
public VelocityMessageRenderer(final ConfigFactory configFactory) {
public VelocityMessageRenderer(final ConfigFactory configFactory, final PluginManager pluginManager) {
this.configFactory = configFactory;
this.pluginManager = pluginManager;
}
@Override
@@ -60,26 +64,28 @@ public class VelocityMessageRenderer<T extends Audience> implements IMessageRend
tagResolver.tag(entry.getKey(), Tag.inserting(entry.getValue()));
}
// https://github.com/KyoriPowered/adventure-text-minimessage/issues/131
// TLDR: 25/10/21, tags in templates aren't parsed. we want them parsed.
String placeholderResolvedMessage = intermediateMessage;
this.configFactory.primaryConfig().customPlaceholders().forEach(
(key, value) -> tagResolver.resolver(Placeholder.parsed(key, value))
);
for (final var entry : this.configFactory.primaryConfig().customPlaceholders().entrySet()) {
placeholderResolvedMessage = placeholderResolvedMessage.replace("<" + entry.getKey() + ">",
entry.getValue());
if (this.pluginManager.isLoaded("miniplaceholders")) {
tagResolver.resolver(MiniPlaceholders.getGlobalPlaceholders());
if (receiver instanceof SourcedAudience sourced) {
if (sourced.sender() instanceof CarbonPlayerVelocity sender && sender.online()) {
if (sourced.recipient() instanceof CarbonPlayerVelocity recipient && recipient.online()) {
tagResolver.resolver(MiniPlaceholders.getRelationalPlaceholders(
sender.player().orElseThrow(),
recipient.player().orElseThrow()
));
} else {
tagResolver.resolver(MiniPlaceholders.getAudiencePlaceholders(sender.player().orElseThrow()));
}
}
}
}
final Component message = MiniMessage.miniMessage().deserialize(placeholderResolvedMessage, tagResolver.build());
final MessageType messageType;
final @Nullable ChatType chatType = method.getAnnotation(ChatType.class);
if (chatType != null) {
messageType = chatType.value();
} else {
messageType = MessageType.SYSTEM;
}
return new Component(message, messageType);
return MiniMessage.miniMessage().deserialize(intermediateMessage, tagResolver.build());
}
}
@@ -1,7 +1,7 @@
/*
* CarbonChat
*
* Copyright (c) 2021 Josua Parks (Vicarious)
* Copyright (c) 2023 Josua Parks (Vicarious)
* Contributors
*
* This program is free software: you can redistribute it and/or modify
@@ -19,143 +19,40 @@
*/
package net.draycia.carbon.velocity;
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.api.users.ComponentPlayerResult;
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.SaveOnChange;
import net.draycia.carbon.common.users.PlatformUserManager;
import net.draycia.carbon.common.users.UserManagerInternal;
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.Nullable;
import org.checkerframework.framework.qual.DefaultQualifier;
@DefaultQualifier(NonNull.class)
public class VelocityUserManager implements UserManager<CarbonPlayerVelocity>, SaveOnChange {
@Singleton
public class VelocityUserManager extends PlatformUserManager<CarbonPlayerVelocity> {
protected final UserManager<CarbonPlayerCommon> proxiedUserManager;
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.proxyServer = proxyServer;
}
@Override
public CompletableFuture<ComponentPlayerResult<CarbonPlayerVelocity>> carbonPlayer(final UUID uuid) {
return this.proxiedUserManager.carbonPlayer(uuid).thenApply(result -> {
if (result.player() == null) {
return new ComponentPlayerResult<>(null, result.reason());
}
return new ComponentPlayerResult<>(new CarbonPlayerVelocity(this.proxyServer, result.player()), result.reason());
});
protected CarbonPlayerVelocity wrap(final CarbonPlayerCommon common) {
return new CarbonPlayerVelocity(this.proxyServer, common);
}
@Override
public CompletableFuture<ComponentPlayerResult<CarbonPlayerVelocity>> savePlayer(final CarbonPlayerVelocity player) {
return this.proxiedUserManager.savePlayer(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 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;
protected void updateTransientLoadedStatus(final CarbonPlayerVelocity wrapped) {
wrapped.carbonPlayerCommon().markTransientLoaded(wrapped.player().isEmpty());
}
}
@@ -1,7 +1,7 @@
/*
* CarbonChat
*
* Copyright (c) 2021 Josua Parks (Vicarious)
* Copyright (c) 2023 Josua Parks (Vicarious)
* Contributors
*
* 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;
}
@Override
public boolean hasPermission(final String permission) {
return this.commandSource.hasPermission(permission);
}
}
}
@@ -1,7 +1,7 @@
/*
* CarbonChat
*
* Copyright (c) 2021 Josua Parks (Vicarious)
* Copyright (c) 2023 Josua Parks (Vicarious)
* Contributors
*
* 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.proxy.Player;
import net.draycia.carbon.api.CarbonChat;
import net.draycia.carbon.api.users.CarbonPlayer;
import net.draycia.carbon.api.users.UserManager;
import net.draycia.carbon.common.command.PlayerCommander;
import net.kyori.adventure.audience.Audience;
import org.checkerframework.checker.nullness.qual.NonNull;
@@ -33,7 +33,7 @@ import static java.util.Objects.requireNonNull;
@DefaultQualifier(NonNull.class)
public record VelocityPlayerCommander(
CarbonChat carbon,
UserManager<?> userManager,
Player player
) implements PlayerCommander, VelocityCommander {
@@ -49,7 +49,12 @@ public record VelocityPlayerCommander(
@Override
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
*
* Copyright (c) 2021 Josua Parks (Vicarious)
* Copyright (c) 2023 Josua Parks (Vicarious)
* Contributors
*
* This program is free software: you can redistribute it and/or modify
@@ -23,25 +23,21 @@ import com.google.inject.Inject;
import com.velocitypowered.api.event.Subscribe;
import com.velocitypowered.api.event.player.PlayerChatEvent;
import java.util.ArrayList;
import java.util.regex.Pattern;
import net.draycia.carbon.api.CarbonChat;
import net.draycia.carbon.api.channels.ChannelRegistry;
import net.draycia.carbon.api.events.CarbonChatEvent;
import net.draycia.carbon.api.users.CarbonPlayer;
import net.draycia.carbon.api.users.ComponentPlayerResult;
import net.draycia.carbon.api.users.UserManager;
import net.draycia.carbon.api.util.KeyedRenderer;
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.TextReplacementConfig;
import net.kyori.adventure.text.event.ClickEvent;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.checkerframework.framework.qual.DefaultQualifier;
import static java.util.Objects.requireNonNullElse;
import static net.draycia.carbon.api.util.KeyedRenderer.keyedRenderer;
import static net.draycia.carbon.common.util.Strings.URL_REPLACEMENT_CONFIG;
import static net.kyori.adventure.key.Key.key;
import static net.kyori.adventure.text.Component.empty;
import static net.kyori.adventure.text.Component.text;
@@ -51,13 +47,13 @@ public final class VelocityChatListener {
private final CarbonChatVelocity carbonChat;
private final ChannelRegistry registry;
private static final Pattern DEFAULT_URL_PATTERN = Pattern.compile("(?:(https?)://)?([-\\w_.]+\\.\\w{2,})(/\\S*)?");
private final UserManager<?> userManager;
@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.registry = registry;
this.userManager = userManager;
}
@Subscribe
@@ -68,23 +64,13 @@ public final class VelocityChatListener {
event.setResult(PlayerChatEvent.ChatResult.denied());
final ComponentPlayerResult<? extends CarbonPlayer> playerResult = this.carbonChat.server().userManager().carbonPlayer(event.getPlayer().getUniqueId()).join();
final @Nullable CarbonPlayer sender = playerResult.player();
if (sender == null) {
return;
}
final CarbonPlayer sender = this.userManager.user(event.getPlayer().getUniqueId()).join();
var channel = requireNonNullElse(sender.selectedChannel(), this.registry.defaultValue());
final var originalMessage = event.getResult().getMessage().orElse(event.getMessage());
Component eventMessage = text(originalMessage);
if (sender.hasPermission("carbon.chatlinks")) {
eventMessage = eventMessage.replaceText(TextReplacementConfig.builder()
.match(DEFAULT_URL_PATTERN)
.replacement(builder -> builder.clickEvent(ClickEvent.clickEvent(ClickEvent.Action.OPEN_URL, builder.content())))
.build());
eventMessage = eventMessage.replaceText(URL_REPLACEMENT_CONFIG.get());
}
for (final var chatChannel : this.registry) {
@@ -108,7 +94,7 @@ public final class VelocityChatListener {
final var renderers = new ArrayList<KeyedRenderer>();
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);
if (!result.wasSuccessful()) {
@@ -128,13 +114,7 @@ public final class VelocityChatListener {
renderedMessage = renderer.render(sender, recipient, renderedMessage, chatEvent.message());
}
final Identity identity = sender.hasPermission("carbon.hideidentity") ? Identity.nil() : sender.identity();
if (!(recipient instanceof CarbonPlayer)) {
recipient.sendMessage(identity, renderedMessage);
} else {
recipient.sendMessage(identity, renderedMessage);
}
recipient.sendMessage(renderedMessage);
}
event.setResult(PlayerChatEvent.ChatResult.denied());
@@ -1,7 +1,7 @@
/*
* CarbonChat
*
* Copyright (c) 2021 Josua Parks (Vicarious)
* Copyright (c) 2023 Josua Parks (Vicarious)
* Contributors
*
* 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.velocitypowered.api.event.Subscribe;
import com.velocitypowered.api.event.connection.DisconnectEvent;
import net.draycia.carbon.api.CarbonChat;
import net.draycia.carbon.api.users.UserManager;
import net.draycia.carbon.common.users.CarbonPlayerCommon;
import net.draycia.carbon.common.util.PlayerUtils;
import net.draycia.carbon.velocity.users.CarbonPlayerVelocity;
import com.velocitypowered.api.event.connection.LoginEvent;
import net.draycia.carbon.velocity.VelocityUserManager;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.framework.qual.DefaultQualifier;
import org.slf4j.Logger;
@DefaultQualifier(NonNull.class)
public class VelocityPlayerJoinListener {
private final CarbonChat carbonChat;
private final UserManager<CarbonPlayerCommon> userManager;
private final VelocityUserManager userManager;
private final Logger logger;
@Inject
public VelocityPlayerJoinListener(
final CarbonChat carbonChat,
final UserManager<CarbonPlayerCommon> userManager
final VelocityUserManager userManager,
final Logger logger
) {
this.carbonChat = carbonChat;
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
public void onPlayerLeave(final DisconnectEvent event) {
this.carbonChat.server().userManager().carbonPlayer(event.getPlayer().getUniqueId()).thenAccept(result -> {
if (result.player() == null) {
return;
}
PlayerUtils.saveAndInvalidatePlayer(this.carbonChat.server(), this.userManager, (CarbonPlayerVelocity) result.player());
this.userManager.loggedOut(event.getPlayer().getUniqueId()).exceptionally(ex -> {
this.logger.warn("Exception saving data for player " + event.getPlayer().getUsername() + " with uuid " + event.getPlayer().getUniqueId());
return null;
});
}
@@ -1,7 +1,7 @@
/*
* CarbonChat
*
* Copyright (c) 2021 Josua Parks (Vicarious)
* Copyright (c) 2023 Josua Parks (Vicarious)
* Contributors
*
* 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.ProxyServer;
import java.util.List;
import java.util.Locale;
import java.util.Optional;
import net.draycia.carbon.api.channels.ChatChannel;
import net.draycia.carbon.api.users.CarbonPlayer;
import net.draycia.carbon.api.util.InventorySlot;
import net.draycia.carbon.common.users.CarbonPlayerCommon;
import net.draycia.carbon.common.users.WrappedCarbonPlayer;
import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.audience.ForwardingAudience;
import net.kyori.adventure.key.Key;
import net.kyori.adventure.text.Component;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
@@ -53,10 +56,26 @@ public final class CarbonPlayerVelocity extends WrappedCarbonPlayer implements F
@Override
public boolean vanished() {
//TODO: VelocityVanish compatibility
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());
}
@@ -84,11 +103,8 @@ public final class CarbonPlayerVelocity extends WrappedCarbonPlayer implements F
return false;
}
if (player.get().getCurrentServer().isEmpty() || otherPlayer.get().getCurrentServer().isEmpty()) {
return false;
}
return player.get().getCurrentServer().get().equals(otherPlayer.get().getCurrentServer().get());
final var playerServer = player.get().getCurrentServer();
return playerServer.isPresent() && playerServer.equals(otherPlayer.get().getCurrentServer());
}
@Override
@@ -98,7 +114,8 @@ public final class CarbonPlayerVelocity extends WrappedCarbonPlayer implements F
@Override
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();
}
}