Rename bukkit module to paper

This commit is contained in:
Draycia committed 2022-06-08 15:19:46 -07:00
1 parent a7a9dddf89
commit 5661cc293f
24 files changed
+156 -143

No files matched your search

+128
View File
@@ -0,0 +1,128 @@
plugins {
id("carbon.shadow-platform")
id("net.minecrell.plugin-yml.bukkit")
id("xyz.jpenilla.run-paper")
}
dependencies {
implementation(projects.carbonchatCommon)
// Server
compileOnly(libs.paperApi)
implementation(libs.paperLib)
// Commands
implementation(libs.cloudPaper)
// Misc
implementation(libs.bstatsBukkit)
// Plugins
compileOnly("me.clip:placeholderapi:2.10.9") // TODO: move this to libs.versions.yml
compileOnly(libs.essentialsXDiscord)
compileOnly(libs.discordsrv)
}
carbonShadowPlatform {
relocateGuice.set(true)
}
tasks {
shadowJar {
relocateDependency("io.papermc.lib")
relocateDependency("io.leangen.geantyref")
}
runServer {
minecraftVersion("1.18.2")
}
}
// Generates plugin.yml automatically
bukkit {
name = rootProject.name
version = project.version as String
main = "net.draycia.carbon.paper.CarbonChatPaper"
apiVersion = "1.18"
author = "Draycia"
depend = listOf("LuckPerms")
softDepend = listOf("PlaceholderAPI", "EssentialsDiscord", "DiscordSRV")
website = GITHUB_REPO_URL
permissions {
register("carbon.clearchat") {
description = "Clears the chat for all players except those with carbon.chearchat.exempt."
childrenMap = mapOf("carbon.clearchat.clear" to true)
}
register("carbon.clearchat.clear") {
description = "Clears the chat for all players except those with carbon.chearchat.exempt."
}
register("carbon.clearchat.exempt") {
description = "Exempts the player from having their chat cleared when /clearchat is executed."
}
register("carbon.debug") {
description = "Allows the sender to quickly check what carbon think's the player's primary and non-primary groups are."
}
register("carbon.help") {
description = "Shows Carbon's help menu, detailing each part of Carbon's commands."
}
register("carbon.hideidentity") {
description = "Prevents messages from the player from being blocked clientside."
}
register("carbon.ignore") {
description = "Ignores the player, hiding messages they send in chat and in whispers."
}
register("carbon.ignore.exempt") {
description = "Prevents the player from being ignored."
}
register("carbon.ignore.unignore") {
description = "Removes the player from the sender's ignore list."
}
register("carbon.itemlink") {
description = "Shows the player's held or equipped item in chat."
}
register("carbon.mute") {
description = "Mutes the player, preventing them from sending messages or whispers."
}
register("carbon.mute.exempt") {
description = "Prevents the player from being muted."
}
register("carbon.mute.info") {
description = "Shows if the player is muted or now."
}
register("carbon.mute.notify") {
description = "Notifies the player when someone else has been mute."
}
register("carbon.mute.unmute") {
description = "Unmutes the player, allowing them to use chat and send whispers."
}
register("carbon.nickname") {
description = "The nickname command, by default shows your nickname."
}
register("carbon.nickname.others") {
description = "Checks/sets other player's nicknames."
}
register("carbon.nickname.see") {
description = "Checks your/other player's nicknames."
}
register("carbon.nickname.self") {
description = "Checks/sets your nickname."
}
register("carbon.nickname.set") {
description = "Sets your/other player's nicknames."
}
register("carbon.reload") {
description = "Reloads Carbon's config, channel settings, and translations."
}
register("carbon.whisper") {
description = "Sends private messages to other players."
}
register("carbon.whisper.continue") {
description = "Sends a message to the last player you whispered."
}
register("carbon.whisper.reply") {
description = "Sends a message to the last player who messaged you."
}
register("carbon.whisper.vanished") {
description = "Allows the player to send messages to vanished players."
}
}
}
@@ -0,0 +1,214 @@
/*
* CarbonChat
*
* Copyright (c) 2021 Josua Parks (Vicarious)
* Contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package net.draycia.carbon.paper;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Singleton;
import com.google.inject.TypeLiteral;
import github.scarsz.discordsrv.DiscordSRV;
import io.papermc.lib.PaperLib;
import java.nio.file.Path;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.logging.Level;
import net.draycia.carbon.api.CarbonChat;
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.users.UserManager;
import net.draycia.carbon.api.util.RenderedMessage;
import net.draycia.carbon.common.channels.CarbonChannelRegistry;
import net.draycia.carbon.common.listeners.RadiusListener;
import net.draycia.carbon.common.messages.CarbonMessages;
import net.draycia.carbon.common.messaging.MessagingManager;
import net.draycia.carbon.common.users.CarbonPlayerCommon;
import net.draycia.carbon.common.util.CloudUtils;
import net.draycia.carbon.common.util.ListenerUtils;
import net.draycia.carbon.common.util.PlayerUtils;
import net.draycia.carbon.paper.listeners.DiscordMessageListener;
import net.draycia.carbon.paper.listeners.PaperChatListener;
import net.draycia.carbon.paper.listeners.PaperPlayerJoinListener;
import net.draycia.carbon.paper.util.PaperMessageRenderer;
import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.text.Component;
import net.kyori.moonshine.message.IMessageRenderer;
import ninja.egg82.messenger.services.PacketService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.bstats.bukkit.Metrics;
import org.bukkit.Bukkit;
import org.bukkit.event.Listener;
import org.bukkit.plugin.java.JavaPlugin;
import org.checkerframework.checker.nullness.qual.MonotonicNonNull;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.checkerframework.framework.qual.DefaultQualifier;
@Singleton
@DefaultQualifier(NonNull.class)
public final class CarbonChatPaper extends JavaPlugin implements CarbonChat {
private static final Set<Class<? extends Listener>> LISTENER_CLASSES = Set.of(
PaperChatListener.class,
PaperPlayerJoinListener.class
);
private static final int BSTATS_PLUGIN_ID = 8720;
private final CarbonEventHandler eventHandler = new CarbonEventHandler();
private @MonotonicNonNull Injector injector;
private @MonotonicNonNull UserManager<CarbonPlayerCommon> userManager;
private @MonotonicNonNull Logger logger;
private @MonotonicNonNull CarbonServerPaper carbonServerPaper;
private @MonotonicNonNull CarbonMessages carbonMessages;
private @MonotonicNonNull ChannelRegistry channelRegistry;
private final UUID serverId = UUID.randomUUID();
private @MonotonicNonNull MessagingManager messagingManager = null;
@Override
public void onLoad() {
if (!PaperLib.isPaper()) {
this.getLogger().log(Level.SEVERE, "*");
this.getLogger().log(Level.SEVERE, "* CarbonChat makes extensive use of APIs added by Paper.");
this.getLogger().log(Level.SEVERE, "* For this reason, CarbonChat is not compatible with Spigot or CraftBukkit servers.");
this.getLogger().log(Level.SEVERE, "* Upgrade your server to Paper in order to use CarbonChat.");
this.getLogger().log(Level.SEVERE, "*");
PaperLib.suggestPaper(this, Level.SEVERE);
this.getServer().getPluginManager().disablePlugin(this);
return;
}
CarbonChatProvider.register(this);
this.injector = Guice.createInjector(new CarbonChatPaperModule(this, this.dataDirectory()));
this.logger = LogManager.getLogger("CarbonChat");
this.carbonMessages = this.injector.getInstance(CarbonMessages.class);
this.channelRegistry = this.injector.getInstance(ChannelRegistry.class);
this.carbonServerPaper = this.injector.getInstance(CarbonServerPaper.class);
this.userManager = this.injector.getInstance(com.google.inject.Key.get(new TypeLiteral<UserManager<CarbonPlayerCommon>>() {}));
this.packetService();
}
@Override
public void onEnable() {
final Metrics metrics = new Metrics(this, BSTATS_PLUGIN_ID);
for (final Class<? extends Listener> listenerClass : LISTENER_CLASSES) {
this.getServer().getPluginManager().registerEvents(
this.injector.getInstance(listenerClass),
this
);
}
// Listeners
ListenerUtils.registerCommonListeners(this.injector);
this.injector.getInstance(RadiusListener.class);
// Commands
// This is a bit awkward looking
CloudUtils.loadCommands(this.injector);
final var commandSettings = CloudUtils.loadCommandSettings(this.injector);
CloudUtils.registerCommands(commandSettings);
// Player data saving
final long saveDelay = 5 * 60 * 20;
Bukkit.getScheduler().runTaskTimerAsynchronously(this,
() -> PlayerUtils.saveLoggedInPlayers(this.carbonServerPaper, this.userManager), saveDelay, saveDelay);
// Load channels
((CarbonChannelRegistry) this.channelRegistry()).loadConfigChannels(this.carbonMessages);
this.discoverDiscordHooks();
}
private void discoverDiscordHooks() {
if (Bukkit.getPluginManager().isPluginEnabled("EssentialsDiscord")) {
final DiscordMessageListener discordMessageListener = this.injector.getInstance(DiscordMessageListener.class);
Bukkit.getPluginManager().registerEvents(discordMessageListener, this);
discordMessageListener.init();
}
if (Bukkit.getPluginManager().isPluginEnabled("DiscordSRV")) {
this.logger.info("DiscordSRV found! Enabling hook.");
DiscordSRV.getPlugin().getPluginHooks().add(new CarbonChatHook());
}
}
@Override
public void onDisable() {
PlayerUtils.saveLoggedInPlayers(this.carbonServerPaper, this.userManager).forEach(CompletableFuture::join);
}
@Override
public UUID serverId() {
return this.serverId;
}
@Override
public @Nullable PacketService packetService() {
if (this.messagingManager == null) {
this.messagingManager = this.injector.getInstance(MessagingManager.class);
}
return this.messagingManager.packetService();
}
@Override
public Logger logger() {
return this.logger;
}
@Override
public Path dataDirectory() {
return this.getDataFolder().toPath();
}
@Override
public CarbonServerPaper server() {
return this.carbonServerPaper;
}
@Override
public ChannelRegistry channelRegistry() {
return this.channelRegistry;
}
public CarbonMessages carbonMessages() {
return this.carbonMessages;
}
@Override
public @NonNull CarbonEventHandler eventHandler() {
return this.eventHandler;
}
@Override
public IMessageRenderer<Audience, String, RenderedMessage, Component> messageRenderer() {
return this.injector.getInstance(PaperMessageRenderer.class);
}
public boolean papiLoaded() {
return Bukkit.getPluginManager().isPluginEnabled("PlaceholderAPI");
}
}
@@ -0,0 +1,129 @@
/*
* CarbonChat
*
* Copyright (c) 2021 Josua Parks (Vicarious)
* Contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package net.draycia.carbon.paper;
import cloud.commandframework.CommandManager;
import cloud.commandframework.brigadier.CloudBrigadierManager;
import cloud.commandframework.bukkit.parsers.PlayerArgument;
import cloud.commandframework.execution.AsynchronousCommandExecutionCoordinator;
import cloud.commandframework.paper.PaperCommandManager;
import com.google.inject.AbstractModule;
import com.google.inject.Injector;
import com.google.inject.Provides;
import com.google.inject.Singleton;
import java.nio.file.Path;
import net.draycia.carbon.api.CarbonChat;
import net.draycia.carbon.api.CarbonServer;
import net.draycia.carbon.api.util.RenderedMessage;
import net.draycia.carbon.api.util.SourcedAudience;
import net.draycia.carbon.common.CarbonCommonModule;
import net.draycia.carbon.common.ForCarbon;
import net.draycia.carbon.common.command.Commander;
import net.draycia.carbon.common.command.argument.PlayerSuggestions;
import net.draycia.carbon.common.util.CloudUtils;
import net.draycia.carbon.paper.command.PaperCommander;
import net.draycia.carbon.paper.command.PaperPlayerCommander;
import net.draycia.carbon.paper.util.PaperMessageRenderer;
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.bukkit.entity.Player;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.checkerframework.framework.qual.DefaultQualifier;
@DefaultQualifier(NonNull.class)
public final class CarbonChatPaperModule extends AbstractModule {
private final Logger logger = LogManager.getLogger("CarbonChat");
private final CarbonChatPaper carbonChat;
private final Path dataDirectory;
CarbonChatPaperModule(
final CarbonChatPaper carbonChat,
final Path dataDirectory
) {
this.carbonChat = carbonChat;
this.dataDirectory = dataDirectory;
}
@Provides
@Singleton
public CommandManager<Commander> commandManager() {
final PaperCommandManager<Commander> commandManager;
try {
commandManager = new PaperCommandManager<>(
this.carbonChat,
AsynchronousCommandExecutionCoordinator.<Commander>newBuilder().build(),
commandSender -> {
if (commandSender instanceof Player player) {
return new PaperPlayerCommander(this.carbonChat, player);
}
return PaperCommander.from(commandSender);
},
commander -> ((PaperCommander) commander).commandSender()
);
} catch (final Exception ex) {
throw new RuntimeException("Failed to initialize command manager.", ex);
}
CloudUtils.decorateCommandManager(commandManager, this.carbonChat.carbonMessages());
commandManager.registerAsynchronousCompletions();
commandManager.registerBrigadier();
final @Nullable CloudBrigadierManager<Commander, ?> brigadierManager =
commandManager.brigadierManager();
if (brigadierManager != null) {
brigadierManager.setNativeNumberSuggestions(false);
}
return commandManager;
}
@Provides
@Singleton
public IMessageRenderer<Audience, String, RenderedMessage, Component> messageRenderer(final Injector injector) {
return injector.getInstance(PaperMessageRenderer.class);
}
@Provides
@Singleton
public IMessageRenderer<SourcedAudience, String, RenderedMessage, Component> sourcedRenderer(final Injector injector) {
return injector.getInstance(PaperMessageRenderer.class);
}
@Override
public void configure() {
this.install(new CarbonCommonModule());
this.bind(CarbonChat.class).toInstance(this.carbonChat);
this.bind(CarbonChatPaper.class).toInstance(this.carbonChat);
this.bind(Logger.class).toInstance(this.logger);
this.bind(Path.class).annotatedWith(ForCarbon.class).toInstance(this.dataDirectory);
this.bind(CarbonServer.class).to(CarbonServerPaper.class);
this.bind(PlayerSuggestions.class).toInstance(new PlayerArgument.PlayerParser<Commander>()::suggestions);
}
}
@@ -0,0 +1,105 @@
/*
* CarbonChat
*
* Copyright (c) 2021 Josua Parks (Vicarious)
* Contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package net.draycia.carbon.paper;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import net.draycia.carbon.api.CarbonServer;
import net.draycia.carbon.api.users.CarbonPlayer;
import net.draycia.carbon.api.users.ComponentPlayerResult;
import net.draycia.carbon.api.users.UserManager;
import net.draycia.carbon.common.users.CarbonPlayerCommon;
import net.draycia.carbon.paper.users.CarbonPlayerPaper;
import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.audience.ForwardingAudience;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.checkerframework.framework.qual.DefaultQualifier;
@Singleton
@DefaultQualifier(NonNull.class)
public final class CarbonServerPaper implements CarbonServer, ForwardingAudience.Single {
private final CarbonChatPaper carbonChatPaper;
private final UserManager<CarbonPlayerPaper> userManager;
@Inject
private CarbonServerPaper(final CarbonChatPaper carbonChatPaper, final UserManager<CarbonPlayerCommon> userManager) {
this.carbonChatPaper = carbonChatPaper;
this.userManager = new PaperUserManager(userManager);
}
@Override
public Audience audience() {
return this.carbonChatPaper.getServer();
}
@Override
public Audience console() {
return this.carbonChatPaper.getServer().getConsoleSender();
}
@Override
public List<? extends CarbonPlayer> players() {
final var players = new ArrayList<CarbonPlayer>();
for (final var player : this.carbonChatPaper.getServer().getOnlinePlayers()) {
final ComponentPlayerResult<CarbonPlayerPaper> result = this.userManager.carbonPlayer(player.getUniqueId()).join();
if (result.player() != null) {
players.add(result.player());
}
}
return players;
}
@Override
public UserManager<CarbonPlayerPaper> userManager() {
return this.userManager;
}
@Override
public CompletableFuture<@Nullable UUID> resolveUUID(final String username) {
// TODO: user cache?
return CompletableFuture.supplyAsync(() -> {
final OfflinePlayer offlinePlayer = Bukkit.getOfflinePlayer(username);
if (!offlinePlayer.hasPlayedBefore()) {
return null;
}
return offlinePlayer.getUniqueId();
});
}
@Override
public CompletableFuture<@Nullable String> resolveName(final UUID uuid) {
// TODO: user cache?
return CompletableFuture.supplyAsync(() -> Bukkit.getOfflinePlayer(uuid).getName());
}
}
@@ -0,0 +1,158 @@
/*
* CarbonChat
*
* Copyright (c) 2021 Josua Parks (Vicarious)
* Contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package net.draycia.carbon.paper;
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.CarbonPlayerCommon;
import net.draycia.carbon.common.users.SaveOnChange;
import net.draycia.carbon.paper.users.CarbonPlayerPaper;
import net.kyori.adventure.key.Key;
import net.kyori.adventure.text.Component;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.checkerframework.framework.qual.DefaultQualifier;
@DefaultQualifier(NonNull.class)
public class PaperUserManager implements UserManager<CarbonPlayerPaper>, SaveOnChange {
protected final UserManager<CarbonPlayerCommon> proxiedUserManager;
public PaperUserManager(final UserManager<CarbonPlayerCommon> proxiedUserManager) {
this.proxiedUserManager = proxiedUserManager;
}
@Override
public CompletableFuture<ComponentPlayerResult<CarbonPlayerPaper>> carbonPlayer(final UUID uuid) {
return this.proxiedUserManager.carbonPlayer(uuid).thenApply(result -> {
if (result.player() == null) {
return new ComponentPlayerResult<>(null, result.reason());
}
return new ComponentPlayerResult<>(new CarbonPlayerPaper(result.player()), result.reason());
});
}
@Override
public CompletableFuture<ComponentPlayerResult<CarbonPlayerPaper>> savePlayer(final CarbonPlayerPaper player) {
return this.proxiedUserManager.savePlayer(player.carbonPlayerCommon()).thenApply(result -> {
if (result.player() == null) {
return new ComponentPlayerResult<>(null, result.reason());
}
return new ComponentPlayerResult<>(new CarbonPlayerPaper(result.player()), result.reason());
});
}
@Override
public CompletableFuture<ComponentPlayerResult<CarbonPlayerPaper>> saveAndInvalidatePlayer(final CarbonPlayerPaper player) {
return this.proxiedUserManager.saveAndInvalidatePlayer(player.carbonPlayerCommon()).thenApply(result -> {
if (result.player() == null) {
return new ComponentPlayerResult<>(null, result.reason());
}
return new ComponentPlayerResult<>(new CarbonPlayerPaper(result.player()), result.reason());
});
}
@Override
public int saveDisplayName(final UUID id, final @Nullable Component component) {
if (this.proxiedUserManager instanceof SaveOnChange saveOnChange) {
return saveOnChange.saveDisplayName(id, component);
}
return -1;
}
@Override
public int saveMuted(final UUID id, final boolean muted) {
if (this.proxiedUserManager instanceof SaveOnChange saveOnChange) {
return saveOnChange.saveMuted(id, muted);
}
return -1;
}
@Override
public int saveDeafened(final UUID id, final boolean deafened) {
if (this.proxiedUserManager instanceof SaveOnChange saveOnChange) {
return saveOnChange.saveDeafened(id, deafened);
}
return -1;
}
@Override
public int saveSpying(final UUID id, final boolean spying) {
if (this.proxiedUserManager instanceof SaveOnChange saveOnChange) {
return saveOnChange.saveSpying(id, spying);
}
return -1;
}
@Override
public int saveSelectedChannel(final UUID id, final @Nullable Key selectedChannel) {
if (this.proxiedUserManager instanceof SaveOnChange saveOnChange) {
return saveOnChange.saveSelectedChannel(id, selectedChannel);
}
return -1;
}
@Override
public int saveLastWhisperTarget(final UUID id, final @Nullable UUID lastWhisperTarget) {
if (this.proxiedUserManager instanceof SaveOnChange saveOnChange) {
return saveOnChange.saveLastWhisperTarget(id, lastWhisperTarget);
}
return -1;
}
@Override
public int saveWhisperReplyTarget(final UUID id, final @Nullable UUID whisperReplyTarget) {
if (this.proxiedUserManager instanceof SaveOnChange saveOnChange) {
return saveOnChange.saveWhisperReplyTarget(id, whisperReplyTarget);
}
return -1;
}
@Override
public int addIgnore(final UUID id, final UUID ignoredPlayer) {
if (this.proxiedUserManager instanceof SaveOnChange saveOnChange) {
return saveOnChange.addIgnore(id, ignoredPlayer);
}
return -1;
}
@Override
public int removeIgnore(final UUID id, final UUID ignoredPlayer) {
if (this.proxiedUserManager instanceof SaveOnChange saveOnChange) {
return saveOnChange.removeIgnore(id, ignoredPlayer);
}
return -1;
}
}
@@ -0,0 +1,47 @@
/*
* CarbonChat
*
* Copyright (c) 2021 Josua Parks (Vicarious)
* Contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package net.draycia.carbon.paper.command;
import net.draycia.carbon.common.command.Commander;
import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.audience.ForwardingAudience;
import org.bukkit.command.CommandSender;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.framework.qual.DefaultQualifier;
@DefaultQualifier(NonNull.class)
public interface PaperCommander extends Commander, ForwardingAudience.Single {
static PaperCommander from(final CommandSender sender) {
return new PaperCommanderImpl(sender);
}
CommandSender commandSender();
record PaperCommanderImpl(CommandSender commandSender) implements PaperCommander {
@Override
public Audience audience() {
return this.commandSender;
}
}
}
@@ -0,0 +1,52 @@
/*
* CarbonChat
*
* Copyright (c) 2021 Josua Parks (Vicarious)
* Contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package net.draycia.carbon.paper.command;
import net.draycia.carbon.api.CarbonChat;
import net.draycia.carbon.api.users.CarbonPlayer;
import net.draycia.carbon.common.command.PlayerCommander;
import net.kyori.adventure.audience.Audience;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.checkerframework.checker.nullness.qual.NonNull;
import static java.util.Objects.requireNonNull;
public record PaperPlayerCommander(
@NonNull CarbonChat carbon,
@NonNull Player player
) implements PlayerCommander, PaperCommander {
@Override
public @NonNull CommandSender commandSender() {
return this.player;
}
@Override
public @NonNull Audience audience() {
return this.player;
}
@Override
public @NonNull CarbonPlayer carbonPlayer() {
return requireNonNull(this.carbon.server().userManager().carbonPlayer(this.player.getUniqueId()).join().player(), "No CarbonPlayer for logged in Player!");
}
}
@@ -0,0 +1,90 @@
/*
* CarbonChat
*
* Copyright (c) 2021 Josua Parks (Vicarious)
* Contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package net.draycia.carbon.paper.listeners;
import com.google.inject.Inject;
import java.util.HashMap;
import java.util.Map;
import net.draycia.carbon.api.CarbonChat;
import net.draycia.carbon.paper.CarbonChatPaper;
import net.essentialsx.api.v2.events.discord.DiscordMessageEvent;
import net.essentialsx.api.v2.events.discord.DiscordRelayEvent;
import net.essentialsx.api.v2.services.discord.DiscordService;
import net.essentialsx.api.v2.services.discord.MessageType;
import net.kyori.adventure.key.Key;
import org.apache.logging.log4j.Logger;
import org.bukkit.Bukkit;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.checkerframework.checker.nullness.qual.Nullable;
public class DiscordMessageListener implements Listener {
private final CarbonChat carbonChat;
private final Map<Key, MessageType> channelMessageTypes = new HashMap<>();
@Inject
public DiscordMessageListener(
final CarbonChat carbonChat,
final Logger logger
) {
this.carbonChat = carbonChat;
logger.info("EssentialsXDiscord found! Enabling hook.");
}
// Minecraft -> Discord
@EventHandler
public void onDiscordMessage(final DiscordMessageEvent event) {
if (!event.getType().equals(MessageType.DefaultTypes.CHAT)) {
return;
}
final var result = this.carbonChat.server().userManager().carbonPlayer(event.getUUID()).join();
if (result.player() != null) {
var channel = result.player().selectedChannel();
if (channel == null) {
channel = this.carbonChat.channelRegistry().defaultValue();
}
final var messageType = this.channelMessageTypes.get(channel.key());
event.setType(messageType);
}
}
@EventHandler
public void onDiscordMessage(final DiscordRelayEvent event) {
}
public void init() {
final @Nullable DiscordService discord = Bukkit.getServicesManager().load(DiscordService.class);
if (discord != null) {
this.carbonChat.channelRegistry().forEach(channel -> {
final MessageType channelMessageType = new MessageType(channel.key().value());
discord.registerMessageType((CarbonChatPaper) this.carbonChat, channelMessageType);
this.channelMessageTypes.put(channel.key(), channelMessageType);
});
}
}
}
@@ -0,0 +1,180 @@
/*
* CarbonChat
*
* Copyright (c) 2021 Josua Parks (Vicarious)
* Contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package net.draycia.carbon.paper.listeners;
import com.google.inject.Inject;
import io.papermc.paper.event.player.AsyncChatEvent;
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.util.KeyedRenderer;
import net.draycia.carbon.api.util.RenderedMessage;
import net.draycia.carbon.paper.CarbonChatPaper;
import net.draycia.carbon.paper.users.CarbonPlayerPaper;
import net.kyori.adventure.audience.MessageType;
import net.kyori.adventure.identity.Identity;
import net.kyori.adventure.text.TextReplacementConfig;
import net.kyori.adventure.text.event.ClickEvent;
import net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
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.kyori.adventure.key.Key.key;
import static net.kyori.adventure.text.Component.empty;
import static net.kyori.adventure.text.Component.text;
@DefaultQualifier(NonNull.class)
public final class PaperChatListener implements Listener {
private final CarbonChatPaper carbonChat;
private final ChannelRegistry registry;
private static final Pattern DEFAULT_URL_PATTERN = Pattern.compile("(?:(https?)://)?([-\\w_.]+\\.\\w{2,})(/\\S*)?");
@Inject
public PaperChatListener(final CarbonChat carbonChat, final ChannelRegistry registry) {
this.carbonChat = (CarbonChatPaper) carbonChat;
this.registry = registry;
}
@EventHandler(ignoreCancelled = true)
public void onPlayerChat(final @NonNull AsyncChatEvent event) {
if (event.viewers().isEmpty()) {
return;
}
final var playerResult = this.carbonChat.server().userManager().carbonPlayer(event.getPlayer().getUniqueId()).join();
final @Nullable CarbonPlayer sender = playerResult.player();
if (sender == null) {
return;
}
var channel = requireNonNullElse(sender.selectedChannel(), this.registry.defaultValue());
final var messageContents = PlainTextComponentSerializer.plainText().serialize(event.originalMessage());
var eventMessage = event.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());
}
for (final var chatChannel : this.registry) {
if (chatChannel.quickPrefix() == null) {
continue;
}
if (messageContents.startsWith(chatChannel.quickPrefix()) && chatChannel.speechPermitted(sender).permitted()) {
channel = chatChannel;
eventMessage = eventMessage.replaceText(TextReplacementConfig.builder()
.once()
.matchLiteral(channel.quickPrefix())
.replacement(text())
.build());
break;
}
}
final var recipients = new ArrayList<>(channel.recipients(sender));
final var renderers = new ArrayList<KeyedRenderer>();
renderers.add(keyedRenderer(key("carbon", "default"), channel));
final var chatEvent = new CarbonChatEvent(sender, eventMessage, recipients, renderers, channel);
final var result = this.carbonChat.eventHandler().emit(chatEvent);
if (!result.wasSuccessful()) {
final var message = chatEvent.result().reason();
if (!message.equals(empty())) {
sender.sendMessage(message);
}
return;
}
try {
event.viewers().clear();
event.setCancelled(true);
} catch (final UnsupportedOperationException exception) {
exception.printStackTrace();
}
if (sender.hasPermission("carbon.hideidentity")) {
for (final var recipient : chatEvent.recipients()) {
var renderedMessage = new RenderedMessage(chatEvent.message(), MessageType.CHAT);
for (final var renderer : chatEvent.renderers()) {
try {
if (recipient instanceof Player player) {
final ComponentPlayerResult<CarbonPlayerPaper> targetPlayer = this.carbonChat.server().userManager().carbonPlayer(player.getUniqueId()).join();
renderedMessage = renderer.render(sender, targetPlayer.player(), renderedMessage.component(), chatEvent.message());
} else {
renderedMessage = renderer.render(sender, recipient, renderedMessage.component(), chatEvent.message());
}
} catch (final Exception e) {
e.printStackTrace();
}
}
recipient.sendMessage(Identity.nil(), renderedMessage.component(), renderedMessage.messageType());
}
} else {
try {
event.viewers().addAll(chatEvent.recipients());
} catch (final UnsupportedOperationException exception) {
exception.printStackTrace();
}
event.renderer((source, sourceDisplayName, message, viewer) -> {
var renderedMessage = new RenderedMessage(chatEvent.message(), MessageType.CHAT);
for (final var renderer : chatEvent.renderers()) {
try {
if (viewer instanceof Player player) {
final ComponentPlayerResult<CarbonPlayerPaper> targetPlayer = this.carbonChat.server().userManager().carbonPlayer(player.getUniqueId()).join();
renderedMessage = renderer.render(sender, targetPlayer.player(), renderedMessage.component(), message);
} else {
renderedMessage = renderer.render(sender, viewer, renderedMessage.component(), message);
}
} catch (final Exception e) {
e.printStackTrace();
}
}
return renderedMessage.component();
});
}
}
}
@@ -0,0 +1,61 @@
/*
* CarbonChat
*
* Copyright (c) 2021 Josua Parks (Vicarious)
* Contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package net.draycia.carbon.paper.listeners;
import com.google.inject.Inject;
import net.draycia.carbon.api.CarbonChat;
import net.draycia.carbon.api.users.UserManager;
import net.draycia.carbon.common.users.CarbonPlayerCommon;
import net.draycia.carbon.common.util.PlayerUtils;
import net.draycia.carbon.paper.users.CarbonPlayerPaper;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerQuitEvent;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.framework.qual.DefaultQualifier;
@DefaultQualifier(NonNull.class)
public class PaperPlayerJoinListener implements Listener {
private final CarbonChat carbonChat;
private final UserManager<CarbonPlayerCommon> userManager;
@Inject
public PaperPlayerJoinListener(
final CarbonChat carbonChat,
final UserManager<CarbonPlayerCommon> userManager
) {
this.carbonChat = carbonChat;
this.userManager = userManager;
}
@EventHandler(priority = EventPriority.MONITOR)
public void onQuit(final PlayerQuitEvent event) {
this.carbonChat.server().userManager().carbonPlayer(event.getPlayer().getUniqueId()).thenAccept(result -> {
if (result.player() == null) {
return;
}
PlayerUtils.saveAndInvalidatePlayer(this.carbonChat.server(), this.userManager, (CarbonPlayerPaper) result.player());
});
}
}
@@ -0,0 +1,198 @@
/*
* CarbonChat
*
* Copyright (c) 2021 Josua Parks (Vicarious)
* Contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package net.draycia.carbon.paper.users;
import io.papermc.paper.event.player.AsyncChatEvent;
import java.util.Collection;
import java.util.Locale;
import java.util.Optional;
import java.util.Set;
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.text.Component;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.player.AsyncPlayerChatEvent;
import org.bukkit.inventory.EntityEquipment;
import org.bukkit.inventory.EquipmentSlot;
import org.bukkit.inventory.ItemStack;
import org.bukkit.metadata.MetadataValue;
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;
@DefaultQualifier(NonNull.class)
public final class CarbonPlayerPaper extends WrappedCarbonPlayer implements ForwardingAudience.Single {
private final CarbonPlayerCommon carbonPlayerCommon;
public CarbonPlayerPaper(final CarbonPlayerCommon carbonPlayerCommon) {
this.carbonPlayerCommon = carbonPlayerCommon;
}
private Optional<Player> player() {
return Optional.ofNullable(Bukkit.getPlayer(this.carbonPlayerCommon.uuid()));
}
@Override
public CarbonPlayerCommon carbonPlayerCommon() {
return this.carbonPlayerCommon;
}
@Override
public @NotNull Audience audience() {
return this.player().map(player -> (Audience) player).orElse(Audience.empty());
}
@Override
public double distanceSquaredFrom(final CarbonPlayer other) {
if (this.player().isEmpty()) {
return -1;
}
final @Nullable Player player = this.player().orElse(null);
final @Nullable Player otherPlayer = Bukkit.getPlayer(other.uuid());
if (player == null || otherPlayer == null) {
return -1;
}
return player.getLocation().distanceSquared(otherPlayer.getLocation());
}
@Override
public boolean sameWorldAs(final CarbonPlayer other) {
if (this.player().isEmpty()) {
return false;
}
final Optional<Player> player = this.player();
final @Nullable Player otherPlayer = Bukkit.getPlayer(other.uuid());
if (player.isEmpty() || otherPlayer == null) {
return false;
}
return player.get().getWorld().equals(otherPlayer.getWorld());
}
@Override
public void displayName(final @Nullable Component displayName) {
this.carbonPlayerCommon.displayName(displayName);
this.player().ifPresent(player -> {
// Update player's name in chat
player.displayName(displayName);
// Update player's name in the tab player list
player.playerListName(displayName);
});
}
@Override
public @Nullable Component createItemHoverComponent(final InventorySlot slot) {
final Optional<Player> player = this.player(); // This is temporary (it's not)
if (player.isEmpty()) {
return null;
}
final EquipmentSlot equipmentSlot;
if (slot.equals(InventorySlot.MAIN_HAND)) {
equipmentSlot = EquipmentSlot.HAND;
} else if (slot.equals(InventorySlot.OFF_HAND)) {
equipmentSlot = EquipmentSlot.OFF_HAND;
} else if (slot.equals(InventorySlot.HELMET)) {
equipmentSlot = EquipmentSlot.HEAD;
} else if (slot.equals(InventorySlot.CHEST)) {
equipmentSlot = EquipmentSlot.CHEST;
} else if (slot.equals(InventorySlot.LEGS)) {
equipmentSlot = EquipmentSlot.LEGS;
} else if (slot.equals(InventorySlot.BOOTS)) {
equipmentSlot = EquipmentSlot.FEET;
} else {
return null;
}
final @Nullable EntityEquipment equipment = player.get().getEquipment();
if (equipment == null) {
return null;
}
final @Nullable ItemStack itemStack = equipment.getItem(equipmentSlot);
if (itemStack == null || itemStack.getType().isAir()) {
return null;
}
return itemStack.displayName();
}
@Override
public @Nullable Locale locale() {
return this.player().map(Player::locale).orElse(null);
}
@Override
public void sendMessageAsPlayer(final String message) {
// TODO: ensure method is not executed from main thread
// bukkit doesn't like that
this.player().ifPresent(player -> player.chat(message));
}
@Override
public boolean speechPermitted(final String message) {
// ...........
return new AsyncPlayerChatEvent(!Bukkit.isPrimaryThread(), this.player().get(), message, Set.of()).callEvent()
&& new AsyncChatEvent(!Bukkit.isPrimaryThread(), this.player().get(), Set.of(),
(player, name, msg, receiver) -> msg, Component.text(message), Component.text(message)).callEvent();
}
@Override
public boolean online() {
return this.player().isPresent();
}
@Override
public boolean vanished() {
return this.hasVanishMeta();
}
// Supported by PremiumVanish, SuperVanish, VanishNoPacket
private boolean hasVanishMeta() {
return this.player().stream()
.map(player -> player.getMetadata("vanished"))
.flatMap(Collection::stream)
.filter(value -> value.value() instanceof Boolean)
.anyMatch(MetadataValue::asBoolean);
}
public @Nullable Player bukkitPlayer() {
return Bukkit.getPlayer(this.uuid());
}
}
@@ -0,0 +1,67 @@
/*
* CarbonChat
*
* Copyright (c) 2021 Josua Parks (Vicarious)
* Contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package net.draycia.carbon.paper.util;
import github.scarsz.discordsrv.Debug;
import github.scarsz.discordsrv.DiscordSRV;
import github.scarsz.discordsrv.dependencies.kyori.adventure.text.minimessage.MiniMessage;
import github.scarsz.discordsrv.hooks.chat.ChatHook;
import github.scarsz.discordsrv.util.PluginUtil;
import net.draycia.carbon.api.CarbonChatProvider;
import net.draycia.carbon.api.channels.ChatChannel;
import net.draycia.carbon.api.events.CarbonChatEvent;
import net.draycia.carbon.api.users.CarbonPlayer;
import net.draycia.carbon.bukkit.users.CarbonPlayerBukkit;
import net.draycia.carbon.common.util.ChannelUtils;
import net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
import org.checkerframework.checker.nullness.qual.Nullable;
public class CarbonChatHook implements ChatHook {
public CarbonChatHook() {
CarbonChatProvider.carbonChat().eventHandler().subscribe(CarbonChatEvent.class, event -> {
final ChatChannel chatChannel = event.chatChannel();
final CarbonPlayer carbonPlayer = event.sender();
DiscordSRV.debug(Debug.MINECRAFT_TO_DISCORD, "Received a CarbonChatEvent (player: " + carbonPlayer.username() + ")");
final @Nullable Player player = ((CarbonPlayerBukkit) carbonPlayer).bukkitPlayer();
final String message = PlainTextComponentSerializer.plainText().serialize(event.message());
if (player != null) {
DiscordSRV.getPlugin().processChatMessage(player, message, chatChannel.commandName(), event.result().cancelled());
}
});
}
@Override
public void broadcastMessageToChannel(final String channel, final github.scarsz.discordsrv.dependencies.kyori.adventure.text.Component message) {
final String mmFormattedMessage = MiniMessage.miniMessage().serialize(message);
ChannelUtils.broadcastMessageToChannel(mmFormattedMessage, ChannelUtils.locateChannel(channel));
}
@Override
public Plugin getPlugin() {
return PluginUtil.getPlugin("CarbonChat");
}
}
@@ -0,0 +1,116 @@
/*
* CarbonChat
*
* Copyright (c) 2021 Josua Parks (Vicarious)
* Contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package net.draycia.carbon.paper.util;
import com.google.inject.Inject;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.Map;
import net.draycia.carbon.api.CarbonChatProvider;
import net.draycia.carbon.api.users.CarbonPlayer;
import net.draycia.carbon.api.util.RenderedMessage;
import net.draycia.carbon.api.util.SourcedAudience;
import net.draycia.carbon.common.config.ConfigFactory;
import net.draycia.carbon.common.util.ChatType;
import net.draycia.carbon.paper.CarbonChatPaper;
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.TagResolver;
import net.kyori.moonshine.message.IMessageRenderer;
import org.bukkit.Bukkit;
import org.checkerframework.checker.nullness.qual.MonotonicNonNull;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.checkerframework.framework.qual.DefaultQualifier;
@DefaultQualifier(NonNull.class)
public class PaperMessageRenderer<T extends Audience> implements IMessageRenderer<T, String, RenderedMessage, Component> {
private @MonotonicNonNull PlaceholderAPIMiniMessageParser parser = null;
private final MiniMessage miniMessage;
private final ConfigFactory configFactory;
@Inject
public PaperMessageRenderer(final ConfigFactory configFactory) {
this.miniMessage = MiniMessage.miniMessage();
this.configFactory = configFactory;
if (((CarbonChatPaper) CarbonChatProvider.carbonChat()).papiLoaded()) {
this.parser = PlaceholderAPIMiniMessageParser.create(MiniMessage.miniMessage());
}
}
@Override
public RenderedMessage render(
final T receiver,
final String intermediateMessage,
final Map<String, ? extends Component> resolvedPlaceholders,
final Method method,
final Type owner
) {
final TagResolver.Builder tagResolver = TagResolver.builder();
for (final var entry : resolvedPlaceholders.entrySet()) {
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;
for (final var entry : this.configFactory.primaryConfig().customPlaceholders().entrySet()) {
placeholderResolvedMessage = placeholderResolvedMessage.replace("<" + entry.getKey() + ">",
entry.getValue());
}
final Component message;
if (receiver instanceof SourcedAudience sourced && this.parser != null) {
if (sourced.sender() instanceof CarbonPlayer sender && sender.online()) {
if (sourced.recipient() instanceof CarbonPlayer recipient && recipient.online()) {
message = this.parser.parseRelational(Bukkit.getPlayer(sender.uuid()),
Bukkit.getPlayer(recipient.uuid()), placeholderResolvedMessage, tagResolver.build());
} else {
message = this.parser.parse(Bukkit.getPlayer(sender.uuid()), placeholderResolvedMessage, tagResolver.build());
}
} else {
message = this.miniMessage.deserialize(placeholderResolvedMessage, tagResolver.build());
}
} else {
message = this.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 RenderedMessage(message, messageType);
}
}
@@ -0,0 +1,117 @@
/*
* CarbonChat
*
* Copyright (c) 2021 Josua Parks (Vicarious)
* Contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package net.draycia.carbon.paper.util;
import java.util.function.UnaryOperator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import me.clip.placeholderapi.PlaceholderAPI;
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.TagResolver;
import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer;
import org.bukkit.OfflinePlayer;
import org.bukkit.entity.Player;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.framework.qual.DefaultQualifier;
@DefaultQualifier(NonNull.class)
public final class PlaceholderAPIMiniMessageParser {
private final MiniMessage miniMessage;
private PlaceholderAPIMiniMessageParser(final MiniMessage miniMessage) {
this.miniMessage = miniMessage;
}
public static PlaceholderAPIMiniMessageParser create(final MiniMessage backingInstance) {
return new PlaceholderAPIMiniMessageParser(backingInstance);
}
private static boolean containsLegacyColorCodes(final String string) {
final char[] charArray = string.toCharArray();
for (final char c : charArray) {
if (c == LegacyComponentSerializer.SECTION_CHAR) {
return true;
}
}
return false;
}
public Component parse(final OfflinePlayer player, final String input, final TagResolver tagResolver) {
return this.parse(
PlaceholderAPI.getPlaceholderPattern(),
match -> PlaceholderAPI.setPlaceholders(player, match),
input,
tagResolver
);
}
public Component parse(final OfflinePlayer player, final String input) {
return this.parse(player, input, TagResolver.empty());
}
public Component parseRelational(final Player one, final Player two, final String input, final TagResolver tagResolver) {
return this.parse(
PlaceholderAPI.getPlaceholderPattern(),
match -> PlaceholderAPI.setPlaceholders(one, PlaceholderAPI.setRelationalPlaceholders(one, two, match)),
input,
tagResolver
);
}
public Component parseRelational(final Player one, final Player two, final String input) {
return this.parseRelational(one, two, input, TagResolver.empty());
}
private Component parse(
final Pattern pattern,
final UnaryOperator<String> placeholderResolver,
final String input,
final TagResolver originalTags
) {
final Matcher matcher = pattern.matcher(input);
final TagResolver.Builder tagResolver = TagResolver.builder().resolvers(originalTags);
final StringBuilder builder = new StringBuilder();
int id = 0;
while (matcher.find()) {
final String match = matcher.group();
final String replaced = placeholderResolver.apply(match);
if (match.equals(replaced) || !containsLegacyColorCodes(replaced)) {
matcher.appendReplacement(builder, Matcher.quoteReplacement(replaced));
} else {
final String key = "papi_generated_template_" + id;
id++;
tagResolver.tag(key, Tag.inserting(LegacyComponentSerializer.legacySection().deserialize(replaced)));
matcher.appendReplacement(builder, Matcher.quoteReplacement("<" + key + ">"));
}
}
matcher.appendTail(builder);
return this.miniMessage.deserialize(builder.toString(), tagResolver.build());
}
}