mirror of
https://github.com/darksaid98/Carbon.git
synced 2026-12-02 22:16:22 +00:00
Begin API abstraction!
This commit is contained in:
1 parent
59511c037f
commit
7299ff64a5
86 files changed
+399
-436
No files matched your search
@@ -0,0 +1,257 @@
|
||||
package net.draycia.carbon;
|
||||
|
||||
import net.draycia.carbon.listeners.contexts.DistanceContext;
|
||||
import net.draycia.carbon.listeners.contexts.EconomyContext;
|
||||
import net.draycia.carbon.listeners.contexts.FilterContext;
|
||||
import net.draycia.carbon.listeners.contexts.TownyContext;
|
||||
import net.draycia.carbon.listeners.contexts.WorldGuardContext;
|
||||
import net.draycia.carbon.listeners.contexts.mcMMOContext;
|
||||
import net.draycia.carbon.listeners.events.BukkitChatListener;
|
||||
import net.draycia.carbon.listeners.events.CapsHandler;
|
||||
import net.draycia.carbon.listeners.events.CustomPlaceholderHandler;
|
||||
import net.draycia.carbon.listeners.events.IgnoredPlayerHandler;
|
||||
import net.draycia.carbon.listeners.events.ItemLinkHandler;
|
||||
import net.draycia.carbon.listeners.events.LegacyFormatHandler;
|
||||
import net.draycia.carbon.listeners.events.MuteHandler;
|
||||
import net.draycia.carbon.listeners.events.OfflineNameHandler;
|
||||
import net.draycia.carbon.listeners.events.PingHandler;
|
||||
import net.draycia.carbon.listeners.events.PlaceholderHandler;
|
||||
import net.draycia.carbon.listeners.events.PlayerJoinListener;
|
||||
import net.draycia.carbon.listeners.events.RelationalPlaceholderHandler;
|
||||
import net.draycia.carbon.listeners.events.ShadowMuteHandler;
|
||||
import net.draycia.carbon.listeners.events.UrlLinkHandler;
|
||||
import net.draycia.carbon.listeners.events.UserFormattingHandler;
|
||||
import net.draycia.carbon.listeners.events.WhisperPingHandler;
|
||||
import net.draycia.carbon.managers.AdventureManager;
|
||||
import net.draycia.carbon.managers.ChannelManager;
|
||||
import net.draycia.carbon.managers.CommandManager;
|
||||
import net.draycia.carbon.messaging.MessageManager;
|
||||
import net.draycia.carbon.api.users.UserService;
|
||||
import net.draycia.carbon.storage.impl.JSONUserService;
|
||||
import net.draycia.carbon.storage.impl.MySQLUserService;
|
||||
import net.draycia.carbon.util.CarbonPlaceholders;
|
||||
import net.draycia.carbon.util.FunctionalityConstants;
|
||||
import net.draycia.carbon.util.Metrics;
|
||||
import dev.jorel.commandapi.CommandAPI;
|
||||
import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer;
|
||||
import net.milkbowl.vault.economy.Economy;
|
||||
import net.milkbowl.vault.permission.Permission;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.configuration.file.YamlConfiguration;
|
||||
import org.bukkit.plugin.PluginManager;
|
||||
import org.bukkit.plugin.java.JavaPlugin;
|
||||
import org.checkerframework.checker.nullness.qual.NonNull;
|
||||
|
||||
import java.io.File;
|
||||
|
||||
public final class CarbonChat extends JavaPlugin {
|
||||
|
||||
private static final int BSTATS_PLUGIN_ID = 8720;
|
||||
|
||||
private Permission permission;
|
||||
|
||||
private CommandManager commandManager;
|
||||
private ChannelManager channelManager;
|
||||
private AdventureManager adventureManager;
|
||||
|
||||
private UserService userService;
|
||||
private MessageManager messageManager;
|
||||
|
||||
private YamlConfiguration modConfig;
|
||||
private YamlConfiguration languageConfig;
|
||||
private YamlConfiguration commandsConfig;
|
||||
|
||||
private FilterContext filterContext;
|
||||
|
||||
public static final LegacyComponentSerializer LEGACY =
|
||||
LegacyComponentSerializer.builder()
|
||||
.extractUrls()
|
||||
.hexColors()
|
||||
.character('§')
|
||||
.useUnusualXRepeatedCharacterHexFormat()
|
||||
.build();
|
||||
|
||||
@Override
|
||||
public void onLoad() {
|
||||
CommandAPI.onLoad(false);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onEnable() {
|
||||
CommandAPI.onEnable(this);
|
||||
final Metrics metrics = new Metrics(this, BSTATS_PLUGIN_ID);
|
||||
|
||||
// Ensure config is present to be modified by the user
|
||||
if (!(new File(this.getDataFolder(), "config.yml").exists())) {
|
||||
this.saveDefaultConfig();
|
||||
}
|
||||
|
||||
if (!(new File(this.getDataFolder(), "moderation.yml").exists())) {
|
||||
this.saveResource("moderation.yml", false);
|
||||
}
|
||||
|
||||
if (!(new File(this.getDataFolder(), "language.yml").exists())) {
|
||||
this.saveResource("language.yml", false);
|
||||
}
|
||||
|
||||
if (!(new File(this.getDataFolder(), "commands.yml").exists())) {
|
||||
this.saveResource("commands.yml", false);
|
||||
}
|
||||
|
||||
this.loadModConfig();
|
||||
this.loadLanguage();
|
||||
|
||||
// Setup Adventure
|
||||
this.adventureManager = new AdventureManager(this);
|
||||
|
||||
// Setup vault and permissions
|
||||
this.permission = this.getServer().getServicesManager().getRegistration(Permission.class).getProvider();
|
||||
|
||||
// Initialize managers
|
||||
this.channelManager = new ChannelManager(this);
|
||||
this.messageManager = new MessageManager(this);
|
||||
this.commandManager = new CommandManager(this);
|
||||
|
||||
final String storageType = this.getConfig().getString("storage.type");
|
||||
|
||||
if (storageType.equalsIgnoreCase("mysql")) {
|
||||
this.getLogger().info("Enabling MySQL storage!");
|
||||
this.userService = new MySQLUserService(this);
|
||||
} else if (storageType.equalsIgnoreCase("json")) {
|
||||
this.getLogger().info("Enabling JSON storage!");
|
||||
this.userService = new JSONUserService(this);
|
||||
} else {
|
||||
this.getLogger().warning("Invalid storage type selected! Falling back to JSON.");
|
||||
this.userService = new JSONUserService(this);
|
||||
}
|
||||
|
||||
// Setup listeners
|
||||
this.setupListeners();
|
||||
this.registerContexts();
|
||||
|
||||
new CarbonPlaceholders(this).register();
|
||||
|
||||
if (!FunctionalityConstants.HAS_HOVER_EVENT_METHOD) {
|
||||
this.getLogger().warning("Item linking disabled! Please use Paper 1.16.2 #172 or newer.");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDisable() {
|
||||
this.userService.onDisable();
|
||||
}
|
||||
|
||||
private void setupListeners() {
|
||||
final PluginManager pluginManager = this.getServer().getPluginManager();
|
||||
|
||||
// Register chat listeners
|
||||
pluginManager.registerEvents(new BukkitChatListener(this), this);
|
||||
new CapsHandler(this);
|
||||
new CustomPlaceholderHandler(this);
|
||||
new IgnoredPlayerHandler();
|
||||
new ItemLinkHandler();
|
||||
new LegacyFormatHandler();
|
||||
new MuteHandler();
|
||||
new OfflineNameHandler();
|
||||
new PingHandler(this);
|
||||
new PlaceholderHandler();
|
||||
pluginManager.registerEvents(new PlayerJoinListener(this), this);
|
||||
new RelationalPlaceholderHandler();
|
||||
new ShadowMuteHandler(this);
|
||||
new UrlLinkHandler();
|
||||
new UserFormattingHandler();
|
||||
new WhisperPingHandler(this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void reloadConfig() {
|
||||
super.reloadConfig();
|
||||
|
||||
this.loadModConfig();
|
||||
this.loadLanguage();
|
||||
this.loadCommandsConfig();
|
||||
}
|
||||
|
||||
public void reloadFilters() {
|
||||
this.filterContext.reloadFilters();
|
||||
}
|
||||
|
||||
private void loadModConfig() {
|
||||
this.modConfig = YamlConfiguration.loadConfiguration(new File(this.getDataFolder(), "moderation.yml"));
|
||||
}
|
||||
|
||||
private void loadLanguage() {
|
||||
this.languageConfig = YamlConfiguration.loadConfiguration(new File(this.getDataFolder(), "language.yml"));
|
||||
}
|
||||
|
||||
private void loadCommandsConfig() {
|
||||
this.commandsConfig = YamlConfiguration.loadConfiguration(new File(this.getDataFolder(), "commands.yml"));
|
||||
}
|
||||
|
||||
private void registerContexts() {
|
||||
this.filterContext = new FilterContext(this);
|
||||
|
||||
if (Bukkit.getPluginManager().isPluginEnabled("Towny")) {
|
||||
this.getServer().getPluginManager().registerEvents(new TownyContext(this), this);
|
||||
}
|
||||
|
||||
if (Bukkit.getPluginManager().isPluginEnabled("mcMMO")) {
|
||||
this.getServer().getPluginManager().registerEvents(new mcMMOContext(this), this);
|
||||
}
|
||||
|
||||
if (Bukkit.getPluginManager().isPluginEnabled("WorldGuard")) {
|
||||
new WorldGuardContext();
|
||||
}
|
||||
|
||||
if (Bukkit.getServicesManager().isProvidedFor(Economy.class)) {
|
||||
new EconomyContext(this);
|
||||
}
|
||||
|
||||
new DistanceContext();
|
||||
}
|
||||
|
||||
@NonNull
|
||||
public YamlConfiguration moderationConfig() {
|
||||
return this.modConfig;
|
||||
}
|
||||
|
||||
@NonNull
|
||||
public YamlConfiguration commandsConfig() {
|
||||
return this.commandsConfig;
|
||||
}
|
||||
|
||||
@NonNull
|
||||
public YamlConfiguration language() {
|
||||
return this.languageConfig;
|
||||
}
|
||||
|
||||
@NonNull
|
||||
public Permission permission() {
|
||||
return this.permission;
|
||||
}
|
||||
|
||||
@NonNull
|
||||
public CommandManager commandManager() {
|
||||
return this.commandManager;
|
||||
}
|
||||
|
||||
@NonNull
|
||||
public ChannelManager channelManager() {
|
||||
return this.channelManager;
|
||||
}
|
||||
|
||||
@NonNull
|
||||
public MessageManager messageManager() {
|
||||
return this.messageManager;
|
||||
}
|
||||
|
||||
@NonNull
|
||||
public UserService userService() {
|
||||
return this.userService;
|
||||
}
|
||||
|
||||
@NonNull
|
||||
public AdventureManager adventureManager() {
|
||||
return this.adventureManager;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package net.draycia.carbon.channels;
|
||||
|
||||
import net.draycia.carbon.api.channels.ChatChannel;
|
||||
import net.draycia.carbon.commands.AliasedChannelCommand;
|
||||
import dev.jorel.commandapi.CommandAPI;
|
||||
import net.draycia.carbon.CarbonChat;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.checkerframework.checker.nullness.qual.NonNull;
|
||||
import org.checkerframework.checker.nullness.qual.Nullable;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public class ChannelRegistry implements Registry<ChatChannel> {
|
||||
|
||||
@NonNull
|
||||
private final Map<@NonNull String, @NonNull ChatChannel> registry = new HashMap<>();
|
||||
|
||||
@NonNull
|
||||
private final List<@NonNull AliasedChannelCommand> channelCommands = new ArrayList<>();
|
||||
|
||||
@NonNull
|
||||
private final CarbonChat carbonChat;
|
||||
|
||||
public ChannelRegistry(@NonNull final CarbonChat carbonChat) {
|
||||
this.carbonChat = carbonChat;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean register(@NonNull final String key, @NonNull final ChatChannel value) {
|
||||
final boolean registerSuccessful = this.registry.putIfAbsent(key, value) == null;
|
||||
|
||||
if (registerSuccessful) {
|
||||
final AliasedChannelCommand command = new AliasedChannelCommand(this.carbonChat, value);
|
||||
|
||||
this.channelCommands.add(command);
|
||||
|
||||
if (value instanceof Listener) {
|
||||
Bukkit.getPluginManager().registerEvents((Listener) value, this.carbonChat);
|
||||
}
|
||||
}
|
||||
|
||||
return registerSuccessful;
|
||||
}
|
||||
|
||||
@Override
|
||||
@NonNull
|
||||
public Collection<@NonNull ChatChannel> values() {
|
||||
return this.registry.values();
|
||||
}
|
||||
|
||||
@Override
|
||||
@Nullable
|
||||
public ChatChannel channel(@NonNull final String key) {
|
||||
return this.registry.get(key);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void clearAll() {
|
||||
this.registry.clear();
|
||||
|
||||
for (final AliasedChannelCommand command : this.channelCommands) {
|
||||
this.carbonChat.getLogger().info("Unregistering command for channel: " + command.chatChannel().name());
|
||||
CommandAPI.unregister(command.commandName());
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+638
@@ -0,0 +1,638 @@
|
||||
package net.draycia.carbon.channels.impls;
|
||||
|
||||
import net.draycia.carbon.util.CarbonUtils;
|
||||
import net.draycia.carbon.CarbonChat;
|
||||
import net.draycia.carbon.api.channels.ChatChannel;
|
||||
import net.draycia.carbon.api.events.misc.CarbonEvents;
|
||||
import net.draycia.carbon.api.events.ChatComponentEvent;
|
||||
import net.draycia.carbon.api.events.ChatFormatEvent;
|
||||
import net.draycia.carbon.api.events.MessageContextEvent;
|
||||
import net.draycia.carbon.api.events.PreChatFormatEvent;
|
||||
import net.draycia.carbon.api.events.ReceiverContextEvent;
|
||||
import net.draycia.carbon.api.users.ChatUser;
|
||||
import net.draycia.carbon.api.Context;
|
||||
import net.kyori.adventure.text.Component;
|
||||
import net.kyori.adventure.text.TextComponent;
|
||||
import net.kyori.adventure.text.format.NamedTextColor;
|
||||
import net.kyori.adventure.text.format.TextColor;
|
||||
import net.kyori.adventure.text.minimessage.MiniMessage;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.configuration.ConfigurationSection;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.checkerframework.checker.nullness.qual.NonNull;
|
||||
import org.checkerframework.checker.nullness.qual.Nullable;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
public class CarbonChatChannel extends ChatChannel {
|
||||
|
||||
@NonNull
|
||||
private static final Pattern MESSAGE_PATTERN = Pattern.compile("<message>");
|
||||
|
||||
@NonNull
|
||||
private final String key;
|
||||
|
||||
@NonNull
|
||||
private final CarbonChat carbonChat;
|
||||
|
||||
@Nullable
|
||||
private final ConfigurationSection config;
|
||||
|
||||
public CarbonChatChannel(@NonNull final String key, @NonNull final CarbonChat carbonChat, @Nullable final ConfigurationSection config) {
|
||||
this.key = key;
|
||||
this.carbonChat = carbonChat;
|
||||
this.config = config;
|
||||
}
|
||||
|
||||
@NonNull
|
||||
public CarbonChat carbonChat() {
|
||||
return this.carbonChat;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean testContext(@NonNull final ChatUser sender, @NonNull final ChatUser target) {
|
||||
final ReceiverContextEvent event = new ReceiverContextEvent(this, sender, target);
|
||||
|
||||
CarbonEvents.post(event);
|
||||
|
||||
return !event.cancelled();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean canPlayerUse(@NonNull final ChatUser user) {
|
||||
return user.player().hasPermission("carbonchat.channels." + this.name() + ".use");
|
||||
}
|
||||
|
||||
@Override
|
||||
@NonNull
|
||||
public List<@NonNull ChatUser> audiences() {
|
||||
final List<ChatUser> audience = new ArrayList<>();
|
||||
|
||||
for (final Player player : Bukkit.getOnlinePlayers()) {
|
||||
final ChatUser playerUser = this.carbonChat.userService().wrap(player);
|
||||
|
||||
if (this.canPlayerSee(playerUser, true)) {
|
||||
audience.add(playerUser);
|
||||
}
|
||||
}
|
||||
|
||||
return audience;
|
||||
}
|
||||
|
||||
private void updateUserNickname(@NonNull final ChatUser user) {
|
||||
if (user.online()) {
|
||||
String nickname = user.nickname();
|
||||
|
||||
if (nickname != null) {
|
||||
final Component component = this.carbonChat.adventureManager().processMessage(nickname);
|
||||
nickname = CarbonChat.LEGACY.serialize(component);
|
||||
|
||||
user.player().setDisplayName(nickname);
|
||||
|
||||
if (this.carbonChat.getConfig().getBoolean("nicknames-set-tab-name")) {
|
||||
user.player().setPlayerListName(nickname);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
@NonNull
|
||||
public Component sendMessage(@NonNull final ChatUser user, @NonNull final Collection<@NonNull ChatUser> recipients, @NonNull final String message, final boolean fromRemote) {
|
||||
this.updateUserNickname(user);
|
||||
|
||||
final MessageContextEvent event = new MessageContextEvent(this, user);
|
||||
|
||||
CarbonEvents.post(event);
|
||||
|
||||
if (event.cancelled()) {
|
||||
return TextComponent.empty();
|
||||
}
|
||||
|
||||
// Get player's formatting
|
||||
final String messageFormat = this.format(user);
|
||||
|
||||
// Call custom chat event
|
||||
final PreChatFormatEvent preFormatEvent = new PreChatFormatEvent(user, this, messageFormat, message);
|
||||
|
||||
CarbonEvents.post(preFormatEvent);
|
||||
|
||||
// Return if cancelled or message is emptied
|
||||
|
||||
if (preFormatEvent.cancelled() || preFormatEvent.message().trim().isEmpty()) {
|
||||
return TextComponent.empty();
|
||||
}
|
||||
|
||||
final String displayName;
|
||||
|
||||
if (user.nickname() != null) {
|
||||
displayName = user.nickname();
|
||||
} else {
|
||||
if (user.online()) {
|
||||
displayName = user.player().getDisplayName();
|
||||
} else {
|
||||
displayName = user.offlinePlayer().getName();
|
||||
}
|
||||
}
|
||||
|
||||
// Iterate through players who should receive messages in this channel
|
||||
for (final ChatUser target : recipients) {
|
||||
// Call second format event. Used for relational stuff (placeholders etc)
|
||||
final ChatFormatEvent formatEvent = new ChatFormatEvent(user, target, this, preFormatEvent.format(), preFormatEvent.message());
|
||||
|
||||
CarbonEvents.post(formatEvent);
|
||||
|
||||
// Again, return if cancelled or message is emptied
|
||||
if (formatEvent.cancelled() || formatEvent.message().trim().isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
final TextColor targetColor = this.channelColor(target);
|
||||
|
||||
TextComponent formatComponent = (TextComponent) this.carbonChat.adventureManager().processMessage(formatEvent.format(),
|
||||
"br", "\n",
|
||||
"displayname", displayName,
|
||||
"color", "<" + targetColor.asHexString() + ">",
|
||||
"phase", Long.toString(System.currentTimeMillis() % 25),
|
||||
"server", this.carbonChat.getConfig().getString("server-name", "Server"),
|
||||
"message", formatEvent.message());
|
||||
|
||||
if (this.isUserSpying(user, target)) {
|
||||
final String prefix = this.processPlaceholders(user, this.carbonChat.getConfig().getString("spy-prefix"));
|
||||
|
||||
formatComponent = (TextComponent) MiniMessage.get().parse(prefix, "color",
|
||||
targetColor.asHexString()).append(formatComponent);
|
||||
}
|
||||
|
||||
final ChatComponentEvent newEvent = new ChatComponentEvent(user, target, this, formatComponent,
|
||||
formatEvent.message());
|
||||
|
||||
CarbonEvents.post(newEvent);
|
||||
|
||||
target.sendMessage(newEvent.component());
|
||||
}
|
||||
|
||||
final ChatFormatEvent consoleFormatEvent = new ChatFormatEvent(user, null, this, preFormatEvent.format(),
|
||||
preFormatEvent.message());
|
||||
|
||||
CarbonEvents.post(consoleFormatEvent);
|
||||
|
||||
final TextColor targetColor = this.channelColor(user);
|
||||
|
||||
final TextComponent consoleFormat = (TextComponent) this.carbonChat.adventureManager().processMessage(consoleFormatEvent.format(),
|
||||
"br", "\n",
|
||||
"displayname", displayName,
|
||||
"color", "<" + targetColor.asHexString() + ">",
|
||||
"phase", Long.toString(System.currentTimeMillis() % 25),
|
||||
"server", this.carbonChat.getConfig().getString("server-name", "Server"),
|
||||
"message", consoleFormatEvent.message());
|
||||
|
||||
final ChatComponentEvent consoleEvent = new ChatComponentEvent(user, null, this, consoleFormat,
|
||||
consoleFormatEvent.message());
|
||||
|
||||
CarbonEvents.post(consoleEvent);
|
||||
|
||||
// Route message to bungee / discord (if message originates from this server)
|
||||
// Use instanceof and not isOnline, if this message originates from another then the instanceof will
|
||||
// fail, but isOnline may succeed if the player is online on both servers (somehow).
|
||||
if (user.online() && !fromRemote && (this.bungee() || this.crossServer())) {
|
||||
this.sendMessageToBungee(user.player(), consoleEvent.component());
|
||||
}
|
||||
|
||||
return consoleEvent.component();
|
||||
}
|
||||
|
||||
@Override
|
||||
@NonNull
|
||||
public Component sendMessage(@NonNull final ChatUser user, @NonNull final String message, final boolean fromRemote) {
|
||||
return this.sendMessage(user, this.audiences(), message, fromRemote);
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public String format(@NonNull final ChatUser user) {
|
||||
for (final String group : this.groupOverrides()) {
|
||||
if (this.userHasGroup(user, group)) {
|
||||
final String format = this.format(group);
|
||||
|
||||
if (format != null) {
|
||||
return format;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (this.primaryGroupOnly()) {
|
||||
return this.primaryGroupFormat(user);
|
||||
} else {
|
||||
return this.firstFoundUserFormat(user);
|
||||
}
|
||||
}
|
||||
|
||||
private boolean userHasGroup(@NonNull final ChatUser user, @NonNull final String group) {
|
||||
if (user.online()) {
|
||||
if (this.carbonChat.permission().playerInGroup(user.player(), group)) {
|
||||
return true;
|
||||
}
|
||||
} else {
|
||||
if (this.carbonChat.permission().playerInGroup(null, user.offlinePlayer(), group)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
if (user.online() && this.permissionGroupMatching()) {
|
||||
return user.player().hasPermission("carbonchat.group." + group);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
private String firstFoundUserFormat(@NonNull final ChatUser user) {
|
||||
final String[] playerGroups;
|
||||
|
||||
if (user.online()) {
|
||||
playerGroups = this.carbonChat.permission().getPlayerGroups(user.player());
|
||||
} else {
|
||||
playerGroups = this.carbonChat.permission().getPlayerGroups(null, user.offlinePlayer());
|
||||
}
|
||||
|
||||
for (final String group : playerGroups) {
|
||||
final String groupFormat = this.format(group);
|
||||
|
||||
if (groupFormat != null) {
|
||||
return groupFormat;
|
||||
}
|
||||
}
|
||||
|
||||
return this.defaultFormat();
|
||||
}
|
||||
|
||||
@Nullable
|
||||
private String primaryGroupFormat(@NonNull final ChatUser user) {
|
||||
final String primaryGroup;
|
||||
|
||||
if (user.online()) {
|
||||
primaryGroup = this.carbonChat.permission().getPrimaryGroup(user.player());
|
||||
} else {
|
||||
primaryGroup = this.carbonChat.permission().getPrimaryGroup(null, user.offlinePlayer());
|
||||
}
|
||||
|
||||
final String primaryGroupFormat = this.format(primaryGroup);
|
||||
|
||||
if (primaryGroupFormat != null) {
|
||||
return primaryGroupFormat;
|
||||
}
|
||||
|
||||
return this.defaultFormat();
|
||||
}
|
||||
|
||||
@Nullable
|
||||
private String defaultFormat() {
|
||||
return this.format(this.defaultFormatName());
|
||||
}
|
||||
|
||||
@Override
|
||||
@Nullable
|
||||
public String format(@NonNull final String group) {
|
||||
return this.getString("formats." + group);
|
||||
}
|
||||
|
||||
private boolean isUserSpying(@NonNull final ChatUser sender, @NonNull final ChatUser target) {
|
||||
if (!this.canPlayerSee(sender, target, false)) {
|
||||
return target.channelSettings(this).spying();
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void sendComponent(@NonNull final ChatUser player, @NonNull final Component component) {
|
||||
for (final ChatUser user : this.audiences()) {
|
||||
if (!user.ignoringUser(player)) {
|
||||
user.sendMessage(component);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void sendMessageToBungee(@NonNull final Player player, @NonNull final Component component) {
|
||||
this.carbonChat.messageManager().sendMessage("channel-component", player.getUniqueId(), byteArray -> {
|
||||
byteArray.writeUTF(this.key());
|
||||
byteArray.writeUTF(this.carbonChat.adventureManager().audiences().gsonSerializer().serialize(component));
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean canPlayerSee(@NonNull final ChatUser target, final boolean checkSpying) {
|
||||
final Player targetPlayer = target.player();
|
||||
|
||||
if (checkSpying && targetPlayer.hasPermission("carbonchat.spy." + this.name())) {
|
||||
if (target.channelSettings(this).spying()) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
if (!targetPlayer.hasPermission("carbonchat.channels." + this.name() + ".see")) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (this.ignorable()) {
|
||||
return !target.channelSettings(this).ignored();
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public boolean canPlayerSee(@NonNull final ChatUser sender, @NonNull final ChatUser target, final boolean checkSpying) {
|
||||
final Player targetPlayer = target.player();
|
||||
|
||||
if (!this.canPlayerSee(target, checkSpying)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (this.ignorable()) {
|
||||
return !target.ignoringUser(sender) || targetPlayer.hasPermission("carbonchat.ignore.exempt");
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
@Nullable
|
||||
public TextColor channelColor(@NonNull final ChatUser user) {
|
||||
final TextColor userColor = user.channelSettings(this).color();
|
||||
|
||||
if (userColor != null) {
|
||||
return userColor;
|
||||
}
|
||||
|
||||
final String input = this.getString("color");
|
||||
|
||||
final TextColor color = CarbonUtils.parseColor(user, input);
|
||||
|
||||
if (color == null && this.carbonChat.getConfig().getBoolean("show-tips")) {
|
||||
this.carbonChat.getLogger().warning("Tip: Channel color found (" + input + ") is invalid!");
|
||||
this.carbonChat.getLogger().warning("Falling back to #FFFFFF");
|
||||
|
||||
return NamedTextColor.WHITE;
|
||||
}
|
||||
|
||||
return color;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
private String defaultFormatName() {
|
||||
return this.getString("default-group");
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isDefault() {
|
||||
if (this.config != null && this.config.contains("default")) {
|
||||
return this.config.getBoolean("default");
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean ignorable() {
|
||||
return this.getBoolean("ignorable");
|
||||
}
|
||||
|
||||
@Override
|
||||
@Deprecated
|
||||
public boolean bungee() {
|
||||
return this.getBoolean("should-bungee");
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean crossServer() {
|
||||
return this.getBoolean("is-cross-server");
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean honorsRecipientList() {
|
||||
return this.getBoolean("honors-recipient-list");
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean permissionGroupMatching() {
|
||||
return this.getBoolean("permission-group-matching");
|
||||
}
|
||||
|
||||
@Override
|
||||
@NonNull
|
||||
public List<@NonNull String> groupOverrides() {
|
||||
return this.getStringList("group-overrides");
|
||||
}
|
||||
|
||||
@Override
|
||||
@NonNull
|
||||
public String name() {
|
||||
final String name = this.getString("name");
|
||||
return name == null ? this.key : name;
|
||||
}
|
||||
|
||||
@Override
|
||||
@Nullable
|
||||
public String messagePrefix() {
|
||||
if (this.config != null && this.config.contains("message-prefix")) {
|
||||
return this.config.getString("message-prefix");
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
@Nullable
|
||||
public String switchMessage() {
|
||||
return this.getString("switch-message");
|
||||
}
|
||||
|
||||
@Override
|
||||
@Nullable
|
||||
public String switchOtherMessage() {
|
||||
return this.getString("switch-other-message");
|
||||
}
|
||||
|
||||
@Override
|
||||
@Nullable
|
||||
public String switchFailureMessage() {
|
||||
return this.getString("switch-failure-message");
|
||||
}
|
||||
|
||||
@Override
|
||||
@Nullable
|
||||
public String cannotIgnoreMessage() {
|
||||
return this.getString("cannot-ignore-message");
|
||||
}
|
||||
|
||||
@Override
|
||||
@Nullable
|
||||
public String toggleOffMessage() {
|
||||
return this.getString("toggle-off-message");
|
||||
}
|
||||
|
||||
@Override
|
||||
@Nullable
|
||||
public String toggleOnMessage() {
|
||||
return this.getString("toggle-on-message");
|
||||
}
|
||||
|
||||
@Override
|
||||
@Nullable
|
||||
public String toggleOtherOnMessage() {
|
||||
return this.getString("toggle-other-on");
|
||||
}
|
||||
|
||||
@Override
|
||||
@Nullable
|
||||
public String toggleOtherOffMessage() {
|
||||
return this.getString("toggle-other-off");
|
||||
}
|
||||
|
||||
@Override
|
||||
@Nullable
|
||||
public String cannotUseMessage() {
|
||||
return this.getString("cannot-use-channel");
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean primaryGroupOnly() {
|
||||
return this.getBoolean("primary-group-only");
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean shouldCancelChatEvent() {
|
||||
return this.getBoolean("cancel-message-event");
|
||||
}
|
||||
|
||||
@Override
|
||||
@NonNull
|
||||
public List<@NonNull Pattern> itemLinkPatterns() {
|
||||
final ArrayList<Pattern> itemPatterns = new ArrayList<>();
|
||||
|
||||
for (final String entry : this.carbonChat.getConfig().getStringList("item-link-placeholders")) {
|
||||
itemPatterns.add(Pattern.compile(Pattern.quote(entry)));
|
||||
}
|
||||
|
||||
return itemPatterns;
|
||||
}
|
||||
|
||||
@Override
|
||||
@Nullable
|
||||
public Context context(@NonNull final String key) {
|
||||
final ConfigurationSection section = this.config == null ? null : this.config.getConfigurationSection("contexts");
|
||||
|
||||
if (section == null) {
|
||||
final ConfigurationSection defaultSection = this.carbonChat.getConfig().getConfigurationSection("default");
|
||||
|
||||
if (defaultSection == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
final ConfigurationSection defaultContexts = defaultSection.getConfigurationSection("contexts");
|
||||
|
||||
if (defaultContexts == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
final Object value = defaultContexts.get(key);
|
||||
|
||||
if (value != null) {
|
||||
return new Context(key, value);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
final Object value = section.get(key);
|
||||
|
||||
if (value == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return new Context(key, value);
|
||||
}
|
||||
|
||||
@Nullable
|
||||
@SuppressWarnings("checkstyle:MethodName")
|
||||
private String getString(@NonNull final String key) {
|
||||
if (this.config != null && this.config.contains(key)) {
|
||||
return this.config.getString(key);
|
||||
}
|
||||
|
||||
final ConfigurationSection defaultSection = this.carbonChat.getConfig().getConfigurationSection("default");
|
||||
|
||||
if (defaultSection != null && defaultSection.contains(key)) {
|
||||
return defaultSection.getString(key);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
@NonNull
|
||||
@SuppressWarnings("checkstyle:MethodName")
|
||||
private List<@NonNull String> getStringList(@NonNull final String key) {
|
||||
if (this.config != null && this.config.contains(key)) {
|
||||
return this.config.getStringList(key);
|
||||
}
|
||||
|
||||
final ConfigurationSection defaultSection = this.carbonChat.getConfig().getConfigurationSection("default");
|
||||
|
||||
if (defaultSection != null && defaultSection.contains(key)) {
|
||||
return defaultSection.getStringList(key);
|
||||
}
|
||||
|
||||
return Collections.emptyList();
|
||||
}
|
||||
|
||||
@SuppressWarnings("checkstyle:MethodName")
|
||||
private boolean getBoolean(@NonNull final String key) {
|
||||
if (this.config != null && this.config.contains(key)) {
|
||||
return this.config.getBoolean(key);
|
||||
}
|
||||
|
||||
final ConfigurationSection defaultSection = this.carbonChat.getConfig().getConfigurationSection("default");
|
||||
|
||||
if (defaultSection != null && defaultSection.contains(key)) {
|
||||
return defaultSection.getBoolean(key);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
@SuppressWarnings("checkstyle:MethodName")
|
||||
private double getDouble(@NonNull final String key) {
|
||||
if (this.config != null && this.config.contains(key)) {
|
||||
return this.config.getDouble(key);
|
||||
}
|
||||
|
||||
final ConfigurationSection defaultSection = this.carbonChat.getConfig().getConfigurationSection("default");
|
||||
|
||||
if (defaultSection != null && defaultSection.contains(key)) {
|
||||
return defaultSection.getDouble(key);
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
@NonNull
|
||||
public String key() {
|
||||
return this.key;
|
||||
}
|
||||
|
||||
@Override
|
||||
@Nullable
|
||||
public String aliases() {
|
||||
final String aliases = this.getString("aliases");
|
||||
|
||||
if (aliases == null) {
|
||||
return this.key();
|
||||
}
|
||||
|
||||
return aliases;
|
||||
}
|
||||
}
|
||||
+84
@@ -0,0 +1,84 @@
|
||||
package net.draycia.carbon.commands;
|
||||
|
||||
import dev.jorel.commandapi.CommandAPICommand;
|
||||
import dev.jorel.commandapi.CommandPermission;
|
||||
import dev.jorel.commandapi.arguments.Argument;
|
||||
import dev.jorel.commandapi.arguments.GreedyStringArgument;
|
||||
import net.draycia.carbon.CarbonChat;
|
||||
import net.draycia.carbon.api.channels.ChatChannel;
|
||||
import net.draycia.carbon.api.users.ChatUser;
|
||||
import net.kyori.adventure.text.Component;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.checkerframework.checker.nullness.qual.NonNull;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
|
||||
public class AliasedChannelCommand {
|
||||
|
||||
@NonNull
|
||||
private final CarbonChat carbonChat;
|
||||
|
||||
@NonNull
|
||||
private final ChatChannel chatChannel;
|
||||
|
||||
@NonNull
|
||||
private final String commandName;
|
||||
|
||||
public AliasedChannelCommand(@NonNull final CarbonChat carbonChat, @NonNull final ChatChannel chatChannel) {
|
||||
this.carbonChat = carbonChat;
|
||||
this.chatChannel = chatChannel;
|
||||
|
||||
this.commandName = chatChannel.key();
|
||||
|
||||
final LinkedHashMap<String, Argument> setChannelArguments = new LinkedHashMap<>();
|
||||
|
||||
new CommandAPICommand(this.commandName)
|
||||
.withArguments(setChannelArguments)
|
||||
.withPermission(CommandPermission.fromString("carbonchat.channel"))
|
||||
.executesPlayer(this::channel)
|
||||
.register();
|
||||
|
||||
final LinkedHashMap<String, Argument> sendMessageArguments = new LinkedHashMap<>();
|
||||
sendMessageArguments.put("message", new GreedyStringArgument());
|
||||
|
||||
new CommandAPICommand(this.commandName)
|
||||
.withArguments(sendMessageArguments)
|
||||
.withPermission(CommandPermission.fromString("carbonchat.channel.message"))
|
||||
.executesPlayer(this::sendMessage)
|
||||
.register();
|
||||
}
|
||||
|
||||
private void channel(@NonNull final Player player, @NonNull final Object @NonNull [] args) {
|
||||
final ChatUser user = this.carbonChat.userService().wrap(player);
|
||||
|
||||
if (user.channelSettings(this.chatChannel()).ignored()) {
|
||||
user.sendMessage(this.carbonChat.adventureManager().processMessageWithPapi(player, this.chatChannel().cannotUseMessage(),
|
||||
"br", "\n",
|
||||
"color", "<" + this.chatChannel().channelColor(user).toString() + ">",
|
||||
"channel", this.chatChannel().name()));
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
user.selectedChannel(this.chatChannel());
|
||||
}
|
||||
|
||||
private void sendMessage(@NonNull final Player player, @NonNull final Object @NonNull [] args) {
|
||||
final ChatUser user = this.carbonChat.userService().wrap(player);
|
||||
final String message = (String) args[0];
|
||||
|
||||
final Component component = this.chatChannel().sendMessage(user, message, false);
|
||||
|
||||
this.carbonChat.adventureManager().audiences().console().sendMessage(component);
|
||||
}
|
||||
|
||||
@NonNull
|
||||
public ChatChannel chatChannel() {
|
||||
return this.chatChannel;
|
||||
}
|
||||
|
||||
@NonNull
|
||||
public String commandName() {
|
||||
return this.commandName;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
package net.draycia.carbon.commands;
|
||||
|
||||
import net.draycia.carbon.api.commands.CommandSettings;
|
||||
import net.draycia.carbon.util.CarbonUtils;
|
||||
import net.draycia.carbon.util.CommandUtils;
|
||||
import dev.jorel.commandapi.CommandAPICommand;
|
||||
import dev.jorel.commandapi.CommandPermission;
|
||||
import dev.jorel.commandapi.arguments.Argument;
|
||||
import dev.jorel.commandapi.arguments.GreedyStringArgument;
|
||||
import net.draycia.carbon.CarbonChat;
|
||||
import net.draycia.carbon.api.channels.ChatChannel;
|
||||
import net.draycia.carbon.api.users.ChatUser;
|
||||
import net.kyori.adventure.text.Component;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.checkerframework.checker.nullness.qual.NonNull;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
|
||||
public class ChannelCommand {
|
||||
|
||||
@NonNull
|
||||
private final CarbonChat carbonChat;
|
||||
|
||||
public ChannelCommand(@NonNull final CarbonChat carbonChat, @NonNull final CommandSettings commandSettings) {
|
||||
this.carbonChat = carbonChat;
|
||||
|
||||
if (!commandSettings.enabled()) {
|
||||
return;
|
||||
}
|
||||
|
||||
CommandUtils.handleDuplicateCommands(commandSettings);
|
||||
|
||||
final LinkedHashMap<String, Argument> setChannelArguments = new LinkedHashMap<>();
|
||||
setChannelArguments.put("channel", CarbonUtils.channelArgument());
|
||||
|
||||
new CommandAPICommand(commandSettings.name())
|
||||
.withArguments(setChannelArguments)
|
||||
.withAliases(commandSettings.aliases())
|
||||
.withPermission(CommandPermission.fromString("carbonchat.channel"))
|
||||
.executesPlayer(this::channel)
|
||||
.register();
|
||||
|
||||
final LinkedHashMap<String, Argument> sendMessageArguments = new LinkedHashMap<>();
|
||||
sendMessageArguments.put("channel", CarbonUtils.channelArgument());
|
||||
sendMessageArguments.put("message", new GreedyStringArgument());
|
||||
|
||||
new CommandAPICommand(commandSettings.name())
|
||||
.withArguments(sendMessageArguments)
|
||||
.withAliases(commandSettings.aliases())
|
||||
.withPermission(CommandPermission.fromString("carbonchat.channel.message"))
|
||||
.executesPlayer(this::sendMessage)
|
||||
.register();
|
||||
}
|
||||
|
||||
private void channel(@NonNull final Player player, @NonNull final Object @NonNull [] args) {
|
||||
final ChatUser user = this.carbonChat.userService().wrap(player);
|
||||
final ChatChannel channel = (ChatChannel) args[0];
|
||||
|
||||
if (user.channelSettings(channel).ignored()) {
|
||||
user.sendMessage(this.carbonChat.adventureManager().processMessageWithPapi(player, channel.cannotUseMessage(),
|
||||
"br", "\n",
|
||||
"color", "<" + channel.channelColor(user).toString() + ">",
|
||||
"channel", channel.name()));
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
user.selectedChannel(channel);
|
||||
}
|
||||
|
||||
private void sendMessage(@NonNull final Player player, @NonNull final Object @NonNull [] args) {
|
||||
final ChatUser user = this.carbonChat.userService().wrap(player);
|
||||
final ChatChannel channel = (ChatChannel) args[0];
|
||||
final String message = (String) args[1];
|
||||
|
||||
final Component component = channel.sendMessage(user, message, false);
|
||||
|
||||
this.carbonChat.adventureManager().audiences().console().sendMessage(component);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
package net.draycia.carbon.commands;
|
||||
|
||||
import net.draycia.carbon.util.CarbonUtils;
|
||||
import net.draycia.carbon.util.CommandUtils;
|
||||
import dev.jorel.commandapi.CommandAPICommand;
|
||||
import dev.jorel.commandapi.CommandPermission;
|
||||
import dev.jorel.commandapi.arguments.Argument;
|
||||
import net.draycia.carbon.CarbonChat;
|
||||
import net.draycia.carbon.api.channels.ChatChannel;
|
||||
import net.draycia.carbon.api.users.ChatUser;
|
||||
import net.draycia.carbon.api.commands.CommandSettings;
|
||||
import net.kyori.adventure.audience.Audience;
|
||||
import net.kyori.adventure.text.Component;
|
||||
import net.kyori.adventure.text.TextComponent;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.checkerframework.checker.nullness.qual.NonNull;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Iterator;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
public class ChannelListCommand {
|
||||
|
||||
@NonNull
|
||||
private final CarbonChat carbonChat;
|
||||
|
||||
public ChannelListCommand(@NonNull final CarbonChat carbonChat, @NonNull final CommandSettings commandSettings) {
|
||||
this.carbonChat = carbonChat;
|
||||
|
||||
if (!commandSettings.enabled()) {
|
||||
return;
|
||||
}
|
||||
|
||||
CommandUtils.handleDuplicateCommands(commandSettings);
|
||||
|
||||
final LinkedHashMap<String, Argument> channelArguments = new LinkedHashMap<>();
|
||||
|
||||
new CommandAPICommand(commandSettings.name())
|
||||
.withArguments(channelArguments)
|
||||
.withAliases(commandSettings.aliases())
|
||||
.withPermission(CommandPermission.fromString("carbonchat.channellist"))
|
||||
.executesPlayer(this::executeSelf)
|
||||
.register();
|
||||
|
||||
final LinkedHashMap<String, Argument> argumentsOther = new LinkedHashMap<>();
|
||||
argumentsOther.put("player", CarbonUtils.onlineChatUserArgument());
|
||||
|
||||
new CommandAPICommand(commandSettings.name())
|
||||
.withArguments(argumentsOther)
|
||||
.withAliases(commandSettings.aliases())
|
||||
.withPermission(CommandPermission.fromString("carbonchat.channellist.other"))
|
||||
.executes(this::executeOther)
|
||||
.register();
|
||||
}
|
||||
|
||||
public void executeSelf(@NonNull final Player player, @NonNull final Object @NonNull [] args) {
|
||||
final Iterator<ChatChannel> allChannels = this.carbonChat.channelManager().registry().values().iterator();
|
||||
final ChatUser user = this.carbonChat.userService().wrap(player);
|
||||
|
||||
this.listAndSend(player, user, allChannels);
|
||||
}
|
||||
|
||||
public void executeOther(@NonNull final CommandSender sender, @NonNull final Object @NonNull [] args) {
|
||||
final Audience cmdSender = this.carbonChat.adventureManager().audiences().audience(sender);
|
||||
final ChatUser user = (ChatUser) args[0];
|
||||
|
||||
if (!user.online()) {
|
||||
final String mustBeOnline = this.carbonChat.language().getString("user-must-be-online");
|
||||
cmdSender.sendMessage(this.carbonChat.adventureManager().processMessage(mustBeOnline, "br", "\n", "player", user.offlinePlayer().getName()));
|
||||
return;
|
||||
}
|
||||
|
||||
final Iterator<ChatChannel> allChannels = this.carbonChat.channelManager().registry().values().iterator();
|
||||
this.listAndSend(sender, user, allChannels);
|
||||
}
|
||||
|
||||
private void listAndSend(@NonNull final CommandSender sender, @NonNull final ChatUser user,
|
||||
@NonNull final Iterator<ChatChannel> allChannels) {
|
||||
ChatChannel channel;
|
||||
final List<ChatChannel> canSee = new ArrayList<>();
|
||||
final List<ChatChannel> cannotSee = new ArrayList<>();
|
||||
|
||||
while (allChannels.hasNext()) {
|
||||
channel = allChannels.next();
|
||||
|
||||
if (channel.canPlayerSee(user, true)) {
|
||||
canSee.add(channel);
|
||||
} else {
|
||||
cannotSee.add(channel);
|
||||
}
|
||||
}
|
||||
|
||||
final Iterator<ChatChannel> visibleChannels = canSee.iterator();
|
||||
final TextComponent.Builder availableList = TextComponent.builder("");
|
||||
|
||||
this.makeList(visibleChannels, availableList);
|
||||
|
||||
final String availableFormat = this.carbonChat.language().getString("available-channels-list");
|
||||
Component availableComponent = this.carbonChat.adventureManager().processMessage(availableFormat, "br", "\n");
|
||||
availableComponent = availableComponent.replaceFirstText(Pattern.compile(Pattern.quote("<list>")), ac -> availableList);
|
||||
|
||||
final Audience audience = this.carbonChat.adventureManager().audiences().audience(sender);
|
||||
|
||||
audience.sendMessage(availableComponent);
|
||||
|
||||
if (sender.hasPermission("carbonchat.channellist.bypass") && !cannotSee.isEmpty()) {
|
||||
final Iterator<ChatChannel> invisibleChannels = cannotSee.iterator();
|
||||
final TextComponent.Builder unavailableList = TextComponent.builder("");
|
||||
|
||||
this.makeList(invisibleChannels, unavailableList);
|
||||
|
||||
final String unavailableFormat = this.carbonChat.language().getString("unavailable-channels-list");
|
||||
Component unavailableComponent = this.carbonChat.adventureManager().processMessage(unavailableFormat, "br", "\n");
|
||||
unavailableComponent = unavailableComponent.replaceFirstText(Pattern.compile(Pattern.quote("<list>")), uac -> unavailableList);
|
||||
|
||||
audience.sendMessage(unavailableComponent);
|
||||
}
|
||||
}
|
||||
|
||||
private void makeList(@NonNull final Iterator<@NonNull ChatChannel> iterator, final TextComponent.@NonNull Builder list) {
|
||||
final String listSeparator = this.carbonChat.language().getString("channel-list-separator", ", ");
|
||||
// TODO: Larry, why did you double assign the listSeparatorComponent?
|
||||
final Component listSeparatorComponent = TextComponent.of(listSeparator);
|
||||
|
||||
while (iterator.hasNext()) {
|
||||
list.append(TextComponent.of(iterator.next().name()));
|
||||
|
||||
if (iterator.hasNext()) {
|
||||
list.append(listSeparatorComponent);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package net.draycia.carbon.commands;
|
||||
|
||||
import net.draycia.carbon.api.commands.CommandSettings;
|
||||
import net.draycia.carbon.util.CommandUtils;
|
||||
import dev.jorel.commandapi.CommandAPICommand;
|
||||
import dev.jorel.commandapi.CommandPermission;
|
||||
import net.draycia.carbon.CarbonChat;
|
||||
import net.kyori.adventure.text.Component;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.checkerframework.checker.nullness.qual.NonNull;
|
||||
|
||||
public class ChatReloadCommand {
|
||||
|
||||
@NonNull
|
||||
private final CarbonChat carbonChat;
|
||||
|
||||
public ChatReloadCommand(@NonNull final CarbonChat carbonChat, @NonNull final CommandSettings commandSettings) {
|
||||
this.carbonChat = carbonChat;
|
||||
|
||||
if (!commandSettings.enabled()) {
|
||||
return;
|
||||
}
|
||||
|
||||
CommandUtils.handleDuplicateCommands(commandSettings);
|
||||
|
||||
new CommandAPICommand(commandSettings.name())
|
||||
.withAliases(commandSettings.aliases())
|
||||
.withPermission(CommandPermission.fromString("carbonchat.reload"))
|
||||
.executes(this::execute)
|
||||
.register();
|
||||
}
|
||||
|
||||
private void execute(@NonNull final CommandSender sender, @NonNull final Object @NonNull [] args) {
|
||||
this.carbonChat.reloadConfig();
|
||||
this.carbonChat.reloadFilters();
|
||||
|
||||
final Component message = this.carbonChat.adventureManager()
|
||||
.processMessage(this.carbonChat.language().getString("reloaded"), "br", "\n");
|
||||
|
||||
this.carbonChat.adventureManager().audiences().audience(sender).sendMessage(message);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package net.draycia.carbon.commands;
|
||||
|
||||
import net.draycia.carbon.api.users.ChatUser;
|
||||
import net.draycia.carbon.api.commands.CommandSettings;
|
||||
import net.draycia.carbon.util.CommandUtils;
|
||||
import dev.jorel.commandapi.CommandAPICommand;
|
||||
import dev.jorel.commandapi.CommandPermission;
|
||||
import net.draycia.carbon.CarbonChat;
|
||||
import net.kyori.adventure.text.Component;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.checkerframework.checker.nullness.qual.NonNull;
|
||||
|
||||
public class ClearChatCommand {
|
||||
|
||||
@NonNull
|
||||
private final CarbonChat carbonChat;
|
||||
|
||||
public ClearChatCommand(@NonNull final CarbonChat carbonChat, @NonNull final CommandSettings commandSettings) {
|
||||
this.carbonChat = carbonChat;
|
||||
|
||||
if (!commandSettings.enabled()) {
|
||||
return;
|
||||
}
|
||||
|
||||
CommandUtils.handleDuplicateCommands(commandSettings);
|
||||
|
||||
new CommandAPICommand(commandSettings.name())
|
||||
.withAliases(commandSettings.aliases())
|
||||
.withPermission(CommandPermission.fromString("carbonchat.clearchat.clear"))
|
||||
.executes(this::execute)
|
||||
.register();
|
||||
}
|
||||
|
||||
private void execute(@NonNull final CommandSender sender, @NonNull final Object @NonNull [] args) {
|
||||
final String format = this.carbonChat.moderationConfig().getString("clear-chat.message", "");
|
||||
final Component component = this.carbonChat.adventureManager().processMessage(format, "br", "\n");
|
||||
|
||||
for (final Player player : Bukkit.getOnlinePlayers()) {
|
||||
final ChatUser audience = this.carbonChat.userService().wrap(player);
|
||||
|
||||
if (player.hasPermission("carbonchat.clearchat.exempt")) {
|
||||
final String message = this.carbonChat.language().getString("clear-exempt");
|
||||
audience.sendMessage(this.carbonChat.adventureManager().processMessage(message, "player", sender.getName()));
|
||||
} else {
|
||||
for (int i = 0; i < this.carbonChat.moderationConfig().getInt("clear-chat.message-count", 100); i++) {
|
||||
audience.sendMessage(component);
|
||||
}
|
||||
}
|
||||
|
||||
if (player.hasPermission("carbonchat.clearchat.notify")) {
|
||||
final String message = this.carbonChat.language().getString("clear-notify");
|
||||
audience.sendMessage(this.carbonChat.adventureManager().processMessage(message, "player", sender.getName()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package net.draycia.carbon.commands;
|
||||
|
||||
import net.draycia.carbon.api.commands.CommandSettings;
|
||||
import net.draycia.carbon.util.CarbonUtils;
|
||||
import net.draycia.carbon.util.CommandUtils;
|
||||
import dev.jorel.commandapi.CommandAPICommand;
|
||||
import dev.jorel.commandapi.CommandPermission;
|
||||
import dev.jorel.commandapi.arguments.Argument;
|
||||
import net.draycia.carbon.CarbonChat;
|
||||
import net.draycia.carbon.api.users.ChatUser;
|
||||
import net.kyori.adventure.text.Component;
|
||||
import net.milkbowl.vault.permission.Permission;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.checkerframework.checker.nullness.qual.NonNull;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
|
||||
public class IgnoreCommand {
|
||||
|
||||
@NonNull
|
||||
private final CarbonChat carbonChat;
|
||||
|
||||
public IgnoreCommand(@NonNull final CarbonChat carbonChat, @NonNull final CommandSettings commandSettings) {
|
||||
this.carbonChat = carbonChat;
|
||||
|
||||
if (!commandSettings.enabled()) {
|
||||
return;
|
||||
}
|
||||
|
||||
CommandUtils.handleDuplicateCommands(commandSettings);
|
||||
|
||||
final LinkedHashMap<String, Argument> channelArguments = new LinkedHashMap<>();
|
||||
channelArguments.put("player", CarbonUtils.chatUserArgument());
|
||||
|
||||
new CommandAPICommand(commandSettings.name())
|
||||
.withArguments(channelArguments)
|
||||
.withAliases(commandSettings.aliases())
|
||||
.withPermission(CommandPermission.fromString("carbonchat.ignore"))
|
||||
.executesPlayer(this::execute)
|
||||
.register();
|
||||
}
|
||||
|
||||
private void execute(@NonNull final Player player, @NonNull final Object @NonNull [] args) {
|
||||
final ChatUser targetUser = (ChatUser) args[0];
|
||||
final ChatUser user = this.carbonChat.userService().wrap(player);
|
||||
|
||||
if (user.ignoringUser(targetUser)) {
|
||||
user.ignoringUser(targetUser, false);
|
||||
user.sendMessage(this.carbonChat.adventureManager().processMessageWithPapi(player,
|
||||
this.carbonChat.language().getString("not-ignoring-user"),
|
||||
"br", "\n", "player", targetUser.offlinePlayer().getName()));
|
||||
} else {
|
||||
Bukkit.getScheduler().runTaskAsynchronously(this.carbonChat, () -> {
|
||||
final Permission permission = this.carbonChat.permission();
|
||||
final String format;
|
||||
|
||||
if (permission.playerHas(null, targetUser.offlinePlayer(), "carbonchat.ignore.exempt")) {
|
||||
format = this.carbonChat.language().getString("ignore-exempt");
|
||||
} else {
|
||||
user.ignoringUser(targetUser, true);
|
||||
format = this.carbonChat.language().getString("ignoring-user");
|
||||
}
|
||||
|
||||
final Component message = this.carbonChat.adventureManager().processMessageWithPapi(player, format,
|
||||
"br", "\n", "sender", player.getDisplayName(), "player",
|
||||
targetUser.offlinePlayer().getName());
|
||||
|
||||
user.sendMessage(message);
|
||||
});
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package net.draycia.carbon.commands;
|
||||
|
||||
import dev.jorel.commandapi.CommandAPICommand;
|
||||
import dev.jorel.commandapi.CommandPermission;
|
||||
import dev.jorel.commandapi.arguments.Argument;
|
||||
import dev.jorel.commandapi.arguments.GreedyStringArgument;
|
||||
import me.clip.placeholderapi.PlaceholderAPI;
|
||||
import net.draycia.carbon.CarbonChat;
|
||||
import net.draycia.carbon.api.users.ChatUser;
|
||||
import net.draycia.carbon.api.commands.CommandSettings;
|
||||
import net.draycia.carbon.util.CommandUtils;
|
||||
import net.kyori.adventure.text.Component;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.checkerframework.checker.nullness.qual.NonNull;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
|
||||
public class MeCommand {
|
||||
|
||||
@NonNull
|
||||
private final CarbonChat carbonChat;
|
||||
|
||||
public MeCommand(@NonNull final CarbonChat carbonChat, @NonNull final CommandSettings commandSettings) {
|
||||
this.carbonChat = carbonChat;
|
||||
|
||||
if (!commandSettings.enabled()) {
|
||||
return;
|
||||
}
|
||||
|
||||
CommandUtils.handleDuplicateCommands(commandSettings);
|
||||
|
||||
final LinkedHashMap<String, Argument> channelArguments = new LinkedHashMap<>();
|
||||
channelArguments.put("message", new GreedyStringArgument());
|
||||
|
||||
new CommandAPICommand(commandSettings.name())
|
||||
.withArguments(channelArguments)
|
||||
.withAliases(commandSettings.aliases())
|
||||
.withPermission(CommandPermission.fromString("carbonchat.me"))
|
||||
.executesPlayer(this::execute)
|
||||
.register();
|
||||
}
|
||||
|
||||
private void execute(@NonNull final Player player, @NonNull final Object @NonNull [] args) {
|
||||
final String message = ((String) args[0]).replace("</pre>", "");
|
||||
String format = PlaceholderAPI.setPlaceholders(player, this.carbonChat.language().getString("me"));
|
||||
|
||||
if (!player.hasPermission("carbonchat.me.formatting")) {
|
||||
format = format.replace("<message>", "<pre><message></pre>");
|
||||
}
|
||||
|
||||
final Component component = this.carbonChat.adventureManager().processMessage(format, "br", "\n",
|
||||
"displayname", player.getDisplayName(), "message", message);
|
||||
|
||||
final ChatUser user = this.carbonChat.userService().wrap(player);
|
||||
|
||||
if (user.shadowMuted()) {
|
||||
user.sendMessage(component);
|
||||
} else {
|
||||
for (final Player onlinePlayer : Bukkit.getOnlinePlayers()) {
|
||||
if (this.carbonChat.userService().wrap(onlinePlayer).ignoringUser(user)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
this.carbonChat.adventureManager().audiences().player(onlinePlayer).sendMessage(component);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package net.draycia.carbon.commands;
|
||||
|
||||
import net.draycia.carbon.api.commands.CommandSettings;
|
||||
import net.draycia.carbon.util.CarbonUtils;
|
||||
import net.draycia.carbon.util.CommandUtils;
|
||||
import dev.jorel.commandapi.CommandAPICommand;
|
||||
import dev.jorel.commandapi.CommandPermission;
|
||||
import dev.jorel.commandapi.arguments.Argument;
|
||||
import dev.jorel.commandapi.arguments.GreedyStringArgument;
|
||||
import net.draycia.carbon.CarbonChat;
|
||||
import net.draycia.carbon.api.users.ChatUser;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.checkerframework.checker.nullness.qual.NonNull;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
|
||||
public class MessageCommand {
|
||||
|
||||
@NonNull
|
||||
private final CarbonChat carbonChat;
|
||||
|
||||
public MessageCommand(@NonNull final CarbonChat carbonChat, @NonNull final CommandSettings commandSettings) {
|
||||
this.carbonChat = carbonChat;
|
||||
|
||||
if (!commandSettings.enabled()) {
|
||||
return;
|
||||
}
|
||||
|
||||
CommandUtils.handleDuplicateCommands(commandSettings);
|
||||
|
||||
final LinkedHashMap<String, Argument> arguments = new LinkedHashMap<>();
|
||||
arguments.put("player", CarbonUtils.chatUserArgument());
|
||||
arguments.put("message", new GreedyStringArgument());
|
||||
|
||||
new CommandAPICommand(commandSettings.name())
|
||||
.withArguments(arguments)
|
||||
.withAliases(commandSettings.aliases())
|
||||
.withPermission(CommandPermission.fromString("carbonchat.message"))
|
||||
.executesPlayer(this::execute)
|
||||
.register();
|
||||
}
|
||||
|
||||
private void execute(@NonNull final Player player, @NonNull final Object @NonNull [] args) {
|
||||
final ChatUser targetUser = (ChatUser) args[0];
|
||||
final String message = (String) args[1];
|
||||
|
||||
final ChatUser sender = this.carbonChat.userService().wrap(player);
|
||||
|
||||
targetUser.sendMessage(sender, message);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
package net.draycia.carbon.commands;
|
||||
|
||||
import net.draycia.carbon.api.users.ChatUser;
|
||||
import net.draycia.carbon.api.commands.CommandSettings;
|
||||
import net.draycia.carbon.util.CarbonUtils;
|
||||
import net.draycia.carbon.util.CommandUtils;
|
||||
import dev.jorel.commandapi.CommandAPICommand;
|
||||
import dev.jorel.commandapi.CommandPermission;
|
||||
import dev.jorel.commandapi.arguments.Argument;
|
||||
import net.draycia.carbon.CarbonChat;
|
||||
import net.kyori.adventure.audience.Audience;
|
||||
import net.kyori.adventure.text.Component;
|
||||
import net.milkbowl.vault.permission.Permission;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.checkerframework.checker.nullness.qual.NonNull;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
|
||||
public class MuteCommand {
|
||||
|
||||
@NonNull
|
||||
private final CarbonChat carbonChat;
|
||||
|
||||
public MuteCommand(@NonNull final CarbonChat carbonChat, @NonNull final CommandSettings commandSettings) {
|
||||
this.carbonChat = carbonChat;
|
||||
|
||||
if (!commandSettings.enabled()) {
|
||||
return;
|
||||
}
|
||||
|
||||
CommandUtils.handleDuplicateCommands(commandSettings);
|
||||
|
||||
final LinkedHashMap<String, Argument> arguments = new LinkedHashMap<>();
|
||||
arguments.put("player", CarbonUtils.chatUserArgument());
|
||||
|
||||
new CommandAPICommand(commandSettings.name())
|
||||
.withArguments(arguments)
|
||||
.withAliases(commandSettings.aliases())
|
||||
.withPermission(CommandPermission.fromString("carbonchat.mute"))
|
||||
.executes(this::execute)
|
||||
.register();
|
||||
}
|
||||
|
||||
private void execute(@NonNull final CommandSender sender, @NonNull final Object @NonNull [] args) {
|
||||
final ChatUser user = (ChatUser) args[0];
|
||||
final Audience audience = this.carbonChat.adventureManager().audiences().audience(sender);
|
||||
|
||||
if (user.shadowMuted()) {
|
||||
user.muted(false);
|
||||
final String format = this.carbonChat.language().getString("no-longer-muted");
|
||||
|
||||
final Component message = this.carbonChat.adventureManager().processMessage(format, "br", "\n",
|
||||
"player", user.offlinePlayer().getName());
|
||||
|
||||
audience.sendMessage(message);
|
||||
} else {
|
||||
Bukkit.getScheduler().runTaskAsynchronously(this.carbonChat, () -> {
|
||||
final Permission permission = this.carbonChat.permission();
|
||||
final String format;
|
||||
|
||||
if (permission.playerHas(null, user.offlinePlayer(), "carbonchat.mute.exempt")) {
|
||||
format = this.carbonChat.language().getString("mute-exempt");
|
||||
} else {
|
||||
user.muted(true);
|
||||
format = this.carbonChat.language().getString("is-now-muted");
|
||||
}
|
||||
|
||||
final Component message = this.carbonChat.adventureManager().processMessage(format, "br", "\n",
|
||||
"player", user.offlinePlayer().getName());
|
||||
|
||||
audience.sendMessage(message);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
package net.draycia.carbon.commands;
|
||||
|
||||
import net.draycia.carbon.api.commands.CommandSettings;
|
||||
import net.draycia.carbon.util.CarbonUtils;
|
||||
import net.draycia.carbon.util.CommandUtils;
|
||||
import dev.jorel.commandapi.CommandAPICommand;
|
||||
import dev.jorel.commandapi.CommandPermission;
|
||||
import dev.jorel.commandapi.arguments.Argument;
|
||||
import dev.jorel.commandapi.arguments.StringArgument;
|
||||
import net.draycia.carbon.CarbonChat;
|
||||
import net.draycia.carbon.api.users.ChatUser;
|
||||
import net.kyori.adventure.audience.Audience;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.checkerframework.checker.nullness.qual.NonNull;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
|
||||
public class NicknameCommand {
|
||||
|
||||
@NonNull
|
||||
private final CarbonChat carbonChat;
|
||||
|
||||
public NicknameCommand(@NonNull final CarbonChat carbonChat, @NonNull final CommandSettings commandSettings) {
|
||||
this.carbonChat = carbonChat;
|
||||
|
||||
if (!commandSettings.enabled()) {
|
||||
return;
|
||||
}
|
||||
|
||||
CommandUtils.handleDuplicateCommands(commandSettings);
|
||||
|
||||
final LinkedHashMap<String, Argument> selfArguments = new LinkedHashMap<>();
|
||||
selfArguments.put("nickname", new StringArgument());
|
||||
|
||||
new CommandAPICommand(commandSettings.name())
|
||||
.withArguments(selfArguments)
|
||||
.withAliases(commandSettings.aliases())
|
||||
.withPermission(CommandPermission.fromString("carbonchat.nickname"))
|
||||
.executesPlayer(this::executeSelf)
|
||||
.register();
|
||||
|
||||
final LinkedHashMap<String, Argument> otherArguments = new LinkedHashMap<>();
|
||||
otherArguments.put("player", CarbonUtils.chatUserArgument());
|
||||
otherArguments.put("nickname", new StringArgument());
|
||||
|
||||
new CommandAPICommand(commandSettings.name())
|
||||
.withArguments(otherArguments)
|
||||
.withAliases(commandSettings.aliases())
|
||||
.withPermission(CommandPermission.fromString("carbonchat.nickname.others"))
|
||||
.executes(this::executeOther)
|
||||
.register();
|
||||
}
|
||||
|
||||
private void executeSelf(@NonNull final Player player, @NonNull final Object @NonNull [] args) {
|
||||
String nickname = (String) args[0];
|
||||
final ChatUser sender = this.carbonChat.userService().wrap(player);
|
||||
|
||||
if (nickname.equalsIgnoreCase("off") || nickname.equalsIgnoreCase(player.getName())) {
|
||||
nickname = null;
|
||||
}
|
||||
|
||||
sender.nickname(nickname);
|
||||
|
||||
final String message;
|
||||
|
||||
if (nickname == null) {
|
||||
message = this.carbonChat.language().getString("nickname-reset");
|
||||
} else {
|
||||
message = this.carbonChat.language().getString("nickname-set");
|
||||
}
|
||||
|
||||
sender.sendMessage(this.carbonChat.adventureManager().processMessage(
|
||||
message, "nickname", nickname == null ? "" : nickname,
|
||||
"user", sender.offlinePlayer().getName()));
|
||||
}
|
||||
|
||||
private void executeOther(@NonNull final CommandSender sender, @NonNull final Object @NonNull [] args) {
|
||||
final Audience user = this.carbonChat.adventureManager().audiences().audience(sender);
|
||||
final ChatUser target = (ChatUser) args[0];
|
||||
String nickname = (String) args[1];
|
||||
|
||||
if (nickname.equalsIgnoreCase("off") ||
|
||||
nickname.equalsIgnoreCase(target.offlinePlayer().getName())) {
|
||||
nickname = null;
|
||||
}
|
||||
|
||||
target.nickname(nickname);
|
||||
|
||||
final String message;
|
||||
|
||||
if (nickname == null) {
|
||||
message = this.carbonChat.language().getString("other-nickname-reset");
|
||||
} else {
|
||||
message = this.carbonChat.language().getString("other-nickname-set");
|
||||
}
|
||||
|
||||
user.sendMessage(this.carbonChat.adventureManager().processMessage(
|
||||
message, "nickname", nickname == null ? "" : nickname,
|
||||
"user", target.offlinePlayer().getName()));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package net.draycia.carbon.commands;
|
||||
|
||||
import dev.jorel.commandapi.CommandAPICommand;
|
||||
import dev.jorel.commandapi.CommandPermission;
|
||||
import dev.jorel.commandapi.arguments.Argument;
|
||||
import dev.jorel.commandapi.arguments.GreedyStringArgument;
|
||||
import net.draycia.carbon.CarbonChat;
|
||||
import net.draycia.carbon.api.users.ChatUser;
|
||||
import net.draycia.carbon.api.commands.CommandSettings;
|
||||
import net.draycia.carbon.util.CommandUtils;
|
||||
import net.kyori.adventure.text.Component;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.checkerframework.checker.nullness.qual.NonNull;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
|
||||
public class ReplyCommand {
|
||||
|
||||
@NonNull
|
||||
private final CarbonChat carbonChat;
|
||||
|
||||
public ReplyCommand(@NonNull final CarbonChat carbonChat, @NonNull final CommandSettings commandSettings) {
|
||||
this.carbonChat = carbonChat;
|
||||
|
||||
if (!commandSettings.enabled()) {
|
||||
return;
|
||||
}
|
||||
|
||||
CommandUtils.handleDuplicateCommands(commandSettings);
|
||||
|
||||
final LinkedHashMap<String, Argument> arguments = new LinkedHashMap<>();
|
||||
arguments.put("message", new GreedyStringArgument());
|
||||
|
||||
new CommandAPICommand(commandSettings.name())
|
||||
.withArguments(arguments)
|
||||
.withAliases(commandSettings.aliases())
|
||||
.withPermission(CommandPermission.fromString("carbonchat.reply"))
|
||||
.executesPlayer(this::execute)
|
||||
.register();
|
||||
}
|
||||
|
||||
private void execute(@NonNull final Player player, @NonNull final Object @NonNull [] args) {
|
||||
final String input = (String) args[0];
|
||||
|
||||
final ChatUser user = this.carbonChat.userService().wrap(player);
|
||||
|
||||
if (input.isEmpty()) {
|
||||
final String message = this.carbonChat.language().getString("reply-message-blank");
|
||||
final Component component = this.carbonChat.adventureManager().processMessage(message, "br", "\n");
|
||||
|
||||
user.sendMessage(component);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (user.replyTarget() == null) {
|
||||
final String message = this.carbonChat.language().getString("no-reply-target");
|
||||
final Component component = this.carbonChat.adventureManager().processMessage(message, "br", "\n");
|
||||
|
||||
user.sendMessage(component);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
final ChatUser targetUser = this.carbonChat.userService().wrap(user.replyTarget());
|
||||
|
||||
targetUser.sendMessage(user, input);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package net.draycia.carbon.commands;
|
||||
|
||||
import dev.jorel.commandapi.CommandAPICommand;
|
||||
import dev.jorel.commandapi.CommandPermission;
|
||||
import dev.jorel.commandapi.arguments.Argument;
|
||||
import dev.jorel.commandapi.arguments.LiteralArgument;
|
||||
import net.draycia.carbon.CarbonChat;
|
||||
import net.draycia.carbon.api.channels.ChatChannel;
|
||||
import net.draycia.carbon.api.users.ChatUser;
|
||||
import net.draycia.carbon.api.commands.CommandSettings;
|
||||
import net.draycia.carbon.api.users.UserChannelSettings;
|
||||
import net.draycia.carbon.util.CarbonUtils;
|
||||
import net.draycia.carbon.util.CommandUtils;
|
||||
import net.kyori.adventure.text.format.TextColor;
|
||||
import org.checkerframework.checker.nullness.qual.NonNull;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
|
||||
public class SetColorCommand {
|
||||
|
||||
@NonNull
|
||||
private final CarbonChat carbonChat;
|
||||
|
||||
public SetColorCommand(@NonNull final CarbonChat carbonChat, @NonNull final CommandSettings commandSettings) {
|
||||
this.carbonChat = carbonChat;
|
||||
|
||||
if (!commandSettings.enabled()) {
|
||||
return;
|
||||
}
|
||||
|
||||
CommandUtils.handleDuplicateCommands(commandSettings);
|
||||
|
||||
for (final ChatChannel channel : this.carbonChat.channelManager().registry().values()) {
|
||||
final LinkedHashMap<String, Argument> arguments = new LinkedHashMap<>();
|
||||
arguments.put("channel", new LiteralArgument(channel.key()));
|
||||
arguments.put("color", CarbonUtils.textColorArgument());
|
||||
|
||||
new CommandAPICommand(commandSettings.name())
|
||||
.withArguments(arguments)
|
||||
.withAliases(commandSettings.aliases())
|
||||
.withPermission(CommandPermission.fromString("carbonchat.setcolor"))
|
||||
.executesPlayer((player, args) -> {
|
||||
final TextColor color = (TextColor) args[0];
|
||||
final ChatUser user = this.carbonChat.userService().wrap(player);
|
||||
|
||||
if (!player.hasPermission("carbonchat.setcolor." + channel.key())) {
|
||||
user.sendMessage(carbonChat.adventureManager().processMessageWithPapi(player,
|
||||
this.carbonChat.language().getString("cannot-set-color"),
|
||||
"br", "\n", "input", color.asHexString(),
|
||||
"channel", channel.name()));
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
final UserChannelSettings settings = user.channelSettings(channel);
|
||||
|
||||
settings.color(color);
|
||||
|
||||
user.sendMessage(carbonChat.adventureManager().processMessageWithPapi(player,
|
||||
this.carbonChat.language().getString("channel-color-set"),
|
||||
"br", "\n", "color", "<color:" + color.asHexString() + ">", "channel",
|
||||
channel.name(), "hex", color.asHexString()));
|
||||
})
|
||||
.register();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
package net.draycia.carbon.commands;
|
||||
|
||||
import net.draycia.carbon.api.users.ChatUser;
|
||||
import net.draycia.carbon.api.commands.CommandSettings;
|
||||
import net.draycia.carbon.util.CarbonUtils;
|
||||
import net.draycia.carbon.util.CommandUtils;
|
||||
import dev.jorel.commandapi.CommandAPICommand;
|
||||
import dev.jorel.commandapi.CommandPermission;
|
||||
import dev.jorel.commandapi.arguments.Argument;
|
||||
import net.draycia.carbon.CarbonChat;
|
||||
import net.kyori.adventure.audience.Audience;
|
||||
import net.kyori.adventure.text.Component;
|
||||
import net.milkbowl.vault.permission.Permission;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.checkerframework.checker.nullness.qual.NonNull;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
|
||||
public class ShadowMuteCommand {
|
||||
|
||||
@NonNull
|
||||
private final CarbonChat carbonChat;
|
||||
|
||||
public ShadowMuteCommand(@NonNull final CarbonChat carbonChat, @NonNull final CommandSettings commandSettings) {
|
||||
this.carbonChat = carbonChat;
|
||||
|
||||
if (!commandSettings.enabled()) {
|
||||
return;
|
||||
}
|
||||
|
||||
CommandUtils.handleDuplicateCommands(commandSettings);
|
||||
|
||||
final LinkedHashMap<String, Argument> arguments = new LinkedHashMap<>();
|
||||
arguments.put("player", CarbonUtils.chatUserArgument());
|
||||
|
||||
new CommandAPICommand(commandSettings.name())
|
||||
.withArguments(arguments)
|
||||
.withAliases(commandSettings.aliases())
|
||||
.withPermission(CommandPermission.fromString("carbonchat.shadowmute"))
|
||||
.executes(this::execute)
|
||||
.register();
|
||||
}
|
||||
|
||||
private void execute(@NonNull final CommandSender sender, @NonNull final Object @NonNull [] args) {
|
||||
final ChatUser user = (ChatUser) args[0];
|
||||
final Audience audience = this.carbonChat.adventureManager().audiences().audience(sender);
|
||||
|
||||
if (user.shadowMuted()) {
|
||||
user.shadowMuted(false);
|
||||
final String format = this.carbonChat.language().getString("no-longer-shadow-muted");
|
||||
|
||||
final Component message = this.carbonChat.adventureManager().processMessage(format, "br", "\n",
|
||||
"player", user.offlinePlayer().getName());
|
||||
|
||||
audience.sendMessage(message);
|
||||
} else {
|
||||
Bukkit.getScheduler().runTaskAsynchronously(this.carbonChat, () -> {
|
||||
final Permission permission = this.carbonChat.permission();
|
||||
final String format;
|
||||
|
||||
if (permission.playerHas(null, user.offlinePlayer(), "carbonchat.shadowmute.exempt")) {
|
||||
format = this.carbonChat.language().getString("shadow-mute-exempt");
|
||||
} else {
|
||||
user.shadowMuted(true);
|
||||
format = this.carbonChat.language().getString("is-now-shadow-muted");
|
||||
}
|
||||
|
||||
final Component message = this.carbonChat.adventureManager().processMessage(format, "br", "\n",
|
||||
"player", user.offlinePlayer().getName());
|
||||
|
||||
audience.sendMessage(message);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
package net.draycia.carbon.commands;
|
||||
|
||||
import net.draycia.carbon.api.channels.ChatChannel;
|
||||
import net.draycia.carbon.api.users.ChatUser;
|
||||
import net.draycia.carbon.api.commands.CommandSettings;
|
||||
import net.draycia.carbon.api.users.UserChannelSettings;
|
||||
import net.draycia.carbon.util.CarbonUtils;
|
||||
import net.draycia.carbon.util.CommandUtils;
|
||||
import dev.jorel.commandapi.CommandAPICommand;
|
||||
import dev.jorel.commandapi.CommandPermission;
|
||||
import dev.jorel.commandapi.arguments.Argument;
|
||||
import dev.jorel.commandapi.arguments.BooleanArgument;
|
||||
import dev.jorel.commandapi.arguments.LiteralArgument;
|
||||
import net.draycia.carbon.CarbonChat;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.checkerframework.checker.nullness.qual.NonNull;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
|
||||
public class SpyChannelCommand {
|
||||
|
||||
@NonNull
|
||||
private final CarbonChat carbonChat;
|
||||
|
||||
public SpyChannelCommand(@NonNull final CarbonChat carbonChat, @NonNull final CommandSettings commandSettings) {
|
||||
this.carbonChat = carbonChat;
|
||||
|
||||
if (!commandSettings.enabled()) {
|
||||
return;
|
||||
}
|
||||
|
||||
CommandUtils.handleDuplicateCommands(commandSettings);
|
||||
|
||||
final LinkedHashMap<String, Argument> channelArguments = new LinkedHashMap<>();
|
||||
channelArguments.put("channel", CarbonUtils.channelArgument());
|
||||
|
||||
new CommandAPICommand(commandSettings.name())
|
||||
.withArguments(channelArguments)
|
||||
.withAliases(commandSettings.aliases())
|
||||
.withPermission(CommandPermission.fromString("carbonchat.spy"))
|
||||
.executesPlayer(this::execute)
|
||||
.register();
|
||||
|
||||
final LinkedHashMap<String, Argument> whisperArguments = new LinkedHashMap<>();
|
||||
whisperArguments.put("channel", new LiteralArgument("whispers"));
|
||||
|
||||
new CommandAPICommand(commandSettings.name())
|
||||
.withArguments(whisperArguments)
|
||||
.withAliases(commandSettings.aliases())
|
||||
.withPermission(CommandPermission.fromString("carbonchat.spy"))
|
||||
.executesPlayer(this::executeWhispers)
|
||||
.register();
|
||||
|
||||
final LinkedHashMap<String, Argument> everythingArguments = new LinkedHashMap<>();
|
||||
everythingArguments.put("channel", new LiteralArgument("*"));
|
||||
everythingArguments.put("should-spy", new BooleanArgument());
|
||||
|
||||
new CommandAPICommand(commandSettings.name())
|
||||
.withArguments(everythingArguments)
|
||||
.withAliases(commandSettings.aliases())
|
||||
.withPermission(CommandPermission.fromString("carbonchat.spy"))
|
||||
.executesPlayer(this::executeEverything) // lul
|
||||
.register();
|
||||
}
|
||||
|
||||
private void execute(@NonNull final Player player, @NonNull final Object @NonNull [] args) {
|
||||
final ChatChannel chatChannel = (ChatChannel) args[0];
|
||||
final ChatUser user = this.carbonChat.userService().wrap(player);
|
||||
|
||||
final String message;
|
||||
|
||||
final UserChannelSettings settings = user.channelSettings(chatChannel);
|
||||
|
||||
if (settings.spying()) {
|
||||
settings.spying(false);
|
||||
message = this.carbonChat.language().getString("spy-toggled-off");
|
||||
} else {
|
||||
settings.spying(true);
|
||||
message = this.carbonChat.language().getString("spy-toggled-on");
|
||||
}
|
||||
|
||||
user.sendMessage(this.carbonChat.adventureManager().processMessageWithPapi(player, message, "br", "\n",
|
||||
"color", "<color:" + chatChannel.channelColor(user).toString() + ">", "channel", chatChannel.name()));
|
||||
}
|
||||
|
||||
private void executeWhispers(@NonNull final Player player, @NonNull final Object @NonNull [] args) {
|
||||
final ChatUser user = this.carbonChat.userService().wrap(player);
|
||||
|
||||
final String message;
|
||||
|
||||
if (user.spyingwhispers()) {
|
||||
user.spyingWhispers(false);
|
||||
message = this.carbonChat.language().getString("spy-whispers-off");
|
||||
} else {
|
||||
user.spyingWhispers(true);
|
||||
message = this.carbonChat.language().getString("spy-whispers-on");
|
||||
}
|
||||
|
||||
user.sendMessage(this.carbonChat.adventureManager().processMessageWithPapi(player, message, "br", "\n"));
|
||||
}
|
||||
|
||||
private void executeEverything(@NonNull final Player player, @NonNull final Object @NonNull [] args) {
|
||||
final Boolean shouldSpy = (Boolean) args[0];
|
||||
|
||||
final ChatUser user = this.carbonChat.userService().wrap(player);
|
||||
|
||||
final String message;
|
||||
|
||||
if (shouldSpy) {
|
||||
user.spyingWhispers(true);
|
||||
|
||||
for (final ChatChannel channel : this.carbonChat.channelManager().registry().values()) {
|
||||
user.channelSettings(channel).spying(true);
|
||||
}
|
||||
|
||||
message = this.carbonChat.language().getString("spy-everything-off");
|
||||
} else {
|
||||
user.spyingWhispers(false);
|
||||
|
||||
for (final ChatChannel channel : this.carbonChat.channelManager().registry().values()) {
|
||||
user.channelSettings(channel).spying(false);
|
||||
}
|
||||
|
||||
message = this.carbonChat.language().getString("spy-everything-on");
|
||||
}
|
||||
|
||||
user.sendMessage(this.carbonChat.adventureManager().processMessageWithPapi(player, message, "br", "\n"));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
package net.draycia.carbon.commands;
|
||||
|
||||
import net.draycia.carbon.util.CarbonUtils;
|
||||
import net.draycia.carbon.util.CommandUtils;
|
||||
import dev.jorel.commandapi.CommandAPICommand;
|
||||
import dev.jorel.commandapi.CommandPermission;
|
||||
import dev.jorel.commandapi.arguments.Argument;
|
||||
import dev.jorel.commandapi.arguments.GreedyStringArgument;
|
||||
import net.draycia.carbon.CarbonChat;
|
||||
import net.draycia.carbon.api.channels.ChatChannel;
|
||||
import net.draycia.carbon.api.users.ChatUser;
|
||||
import net.draycia.carbon.api.commands.CommandSettings;
|
||||
import net.kyori.adventure.text.Component;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.checkerframework.checker.nullness.qual.NonNull;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
|
||||
public class SudoChannelCommand {
|
||||
|
||||
@NonNull
|
||||
private final CarbonChat carbonChat;
|
||||
|
||||
public SudoChannelCommand(@NonNull final CarbonChat carbonChat, @NonNull final CommandSettings commandSettings) {
|
||||
this.carbonChat = carbonChat;
|
||||
|
||||
if (!commandSettings.enabled()) {
|
||||
return;
|
||||
}
|
||||
|
||||
CommandUtils.handleDuplicateCommands(commandSettings);
|
||||
|
||||
final LinkedHashMap<String, Argument> setOtherChannelArguments = new LinkedHashMap<>();
|
||||
setOtherChannelArguments.put("player", CarbonUtils.onlineChatUserArgument());
|
||||
setOtherChannelArguments.put("channel", CarbonUtils.channelArgument());
|
||||
|
||||
new CommandAPICommand(commandSettings.name())
|
||||
.withArguments(setOtherChannelArguments)
|
||||
.withAliases(commandSettings.aliases())
|
||||
.withPermission(CommandPermission.fromString("carbonchat.channel.others"))
|
||||
.executes((sender, args) -> {
|
||||
this.otherChannel(sender, (ChatUser) args[0], (ChatChannel) args[1]);
|
||||
})
|
||||
.register();
|
||||
|
||||
final LinkedHashMap<String, Argument> sendMessageOtherArguments = new LinkedHashMap<>();
|
||||
sendMessageOtherArguments.put("player", CarbonUtils.onlineChatUserArgument());
|
||||
sendMessageOtherArguments.put("channel", CarbonUtils.channelArgument());
|
||||
sendMessageOtherArguments.put("message", new GreedyStringArgument());
|
||||
|
||||
new CommandAPICommand(commandSettings.name())
|
||||
.withArguments(sendMessageOtherArguments)
|
||||
.withAliases(commandSettings.aliases())
|
||||
.withPermission(CommandPermission.fromString("carbonchat.channel.others.message"))
|
||||
.executes((sender, args) -> {
|
||||
this.sendMessageOther(sender, (ChatUser) args[0], (ChatChannel) args[1], (String) args[2]);
|
||||
})
|
||||
.register();
|
||||
}
|
||||
|
||||
private void otherChannel(@NonNull final CommandSender sender, @NonNull final ChatUser user, @NonNull final ChatChannel channel) {
|
||||
user.selectedChannel(channel);
|
||||
|
||||
final String message = channel.switchMessage();
|
||||
final String otherMessage = channel.switchOtherMessage();
|
||||
|
||||
user.sendMessage(this.carbonChat.adventureManager().processMessage(message, "br", "\n",
|
||||
"color", "<color:" + channel.channelColor(user).toString() + ">", "channel", channel.name()));
|
||||
|
||||
this.carbonChat.adventureManager().audiences().audience(sender).sendMessage(
|
||||
this.carbonChat.adventureManager().processMessage(otherMessage, "br", "\n",
|
||||
"color", "<color:" + channel.channelColor(user).toString() + ">", "channel", channel.name(),
|
||||
"player", user.offlinePlayer().getName()));
|
||||
}
|
||||
|
||||
private void sendMessageOther(@NonNull final CommandSender sender, @NonNull final ChatUser user,
|
||||
@NonNull final ChatChannel channel, @NonNull final String message) {
|
||||
final Component component = channel.sendMessage(user, message, false);
|
||||
|
||||
this.carbonChat.adventureManager().audiences().console().sendMessage(component);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
package net.draycia.carbon.commands;
|
||||
|
||||
import net.draycia.carbon.api.channels.ChatChannel;
|
||||
import net.draycia.carbon.api.users.ChatUser;
|
||||
import net.draycia.carbon.api.commands.CommandSettings;
|
||||
import net.draycia.carbon.api.users.UserChannelSettings;
|
||||
import net.draycia.carbon.util.CarbonUtils;
|
||||
import net.draycia.carbon.util.CommandUtils;
|
||||
import dev.jorel.commandapi.CommandAPICommand;
|
||||
import dev.jorel.commandapi.CommandPermission;
|
||||
import dev.jorel.commandapi.arguments.Argument;
|
||||
import net.draycia.carbon.CarbonChat;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.checkerframework.checker.nullness.qual.NonNull;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
|
||||
public class ToggleCommand {
|
||||
|
||||
@NonNull
|
||||
private final CarbonChat carbonChat;
|
||||
|
||||
public ToggleCommand(@NonNull final CarbonChat carbonChat, @NonNull final CommandSettings commandSettings) {
|
||||
this.carbonChat = carbonChat;
|
||||
|
||||
if (!commandSettings.enabled()) {
|
||||
return;
|
||||
}
|
||||
|
||||
CommandUtils.handleDuplicateCommands(commandSettings);
|
||||
|
||||
final LinkedHashMap<String, Argument> channelArguments = new LinkedHashMap<>();
|
||||
channelArguments.put("channel", CarbonUtils.channelArgument());
|
||||
|
||||
new CommandAPICommand(commandSettings.name())
|
||||
.withArguments(channelArguments)
|
||||
.withAliases(commandSettings.aliases())
|
||||
.withPermission(CommandPermission.fromString("carbonchat.toggle"))
|
||||
.executesPlayer(this::executeSelf)
|
||||
.register();
|
||||
|
||||
final LinkedHashMap<String, Argument> argumentsOther = new LinkedHashMap<>();
|
||||
argumentsOther.put("players", CarbonUtils.chatUserArgument());
|
||||
argumentsOther.put("channel", CarbonUtils.channelArgument());
|
||||
|
||||
new CommandAPICommand(commandSettings.name())
|
||||
.withArguments(argumentsOther)
|
||||
.withAliases(commandSettings.aliases())
|
||||
.withPermission(CommandPermission.fromString("carbonchat.toggle"))
|
||||
.executes(this::executeOther)
|
||||
.register();
|
||||
}
|
||||
|
||||
private void executeSelf(@NonNull final Player player, @NonNull final Object @NonNull [] args) {
|
||||
final ChatUser user = this.carbonChat.userService().wrap(player);
|
||||
final ChatChannel channel = (ChatChannel) args[0];
|
||||
|
||||
final String message;
|
||||
|
||||
final UserChannelSettings settings = user.channelSettings(channel);
|
||||
|
||||
if (!channel.ignorable()) {
|
||||
message = channel.cannotIgnoreMessage();
|
||||
} else if (settings.ignored()) {
|
||||
settings.ignoring(false);
|
||||
message = channel.toggleOffMessage();
|
||||
} else {
|
||||
settings.ignoring(true);
|
||||
message = channel.toggleOnMessage();
|
||||
}
|
||||
|
||||
user.sendMessage(this.carbonChat.adventureManager().processMessageWithPapi(player, message, "br", "\n",
|
||||
"color", "<color:" + channel.channelColor(user).toString() + ">", "channel", channel.name()));
|
||||
}
|
||||
|
||||
private void executeOther(@NonNull final CommandSender sender, @NonNull final Object @NonNull [] args) {
|
||||
final ChatUser user = (ChatUser) args[0];
|
||||
final ChatChannel channel = (ChatChannel) args[1];
|
||||
|
||||
final String message;
|
||||
final String otherMessage;
|
||||
|
||||
final UserChannelSettings settings = user.channelSettings(channel);
|
||||
|
||||
if (settings.ignored()) {
|
||||
settings.ignoring(false);
|
||||
message = channel.toggleOffMessage();
|
||||
otherMessage = channel.toggleOtherOffMessage();
|
||||
} else {
|
||||
settings.ignoring(true);
|
||||
message = channel.toggleOnMessage();
|
||||
otherMessage = channel.toggleOtherOnMessage();
|
||||
}
|
||||
|
||||
user.sendMessage(this.carbonChat.adventureManager().processMessage(message, "br", "\n",
|
||||
"color", "<color:" + channel.channelColor(user).toString() + ">", "channel", channel.name()));
|
||||
|
||||
this.carbonChat.adventureManager().audiences().audience(sender).sendMessage(
|
||||
this.carbonChat.adventureManager().processMessage(otherMessage,
|
||||
"br", "\n", "color", "<color:" + channel.channelColor(user).toString() + ">",
|
||||
"channel", channel.name(), "player", user.offlinePlayer().getName()));
|
||||
}
|
||||
}
|
||||
+50
@@ -0,0 +1,50 @@
|
||||
package net.draycia.carbon.listeners.contexts;
|
||||
|
||||
import net.draycia.carbon.api.events.misc.CarbonEvents;
|
||||
import net.draycia.carbon.api.events.ReceiverContextEvent;
|
||||
import net.draycia.carbon.api.Context;
|
||||
import net.kyori.event.PostOrders;
|
||||
import org.bukkit.Location;
|
||||
import org.checkerframework.checker.nullness.qual.NonNull;
|
||||
|
||||
public class DistanceContext {
|
||||
|
||||
@NonNull
|
||||
private static final String KEY = "distance";
|
||||
|
||||
public DistanceContext() {
|
||||
CarbonEvents.register(ReceiverContextEvent.class, PostOrders.NORMAL, false, event -> {
|
||||
final Context context = event.channel().context(KEY);
|
||||
|
||||
if (context == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (context.isBoolean() && !context.asBoolean()) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!event.sender().online() || !event.recipient().online()) {
|
||||
event.cancelled(true);
|
||||
return;
|
||||
}
|
||||
|
||||
final Location senderLocation = event.sender().player().getLocation();
|
||||
final Location targetLocation = event.recipient().player().getLocation();
|
||||
|
||||
if (!senderLocation.getWorld().equals(targetLocation.getWorld())) {
|
||||
event.cancelled(true);
|
||||
return;
|
||||
}
|
||||
|
||||
if (context.isNumber()) {
|
||||
final double value = context.asNumber().doubleValue();
|
||||
|
||||
if (value > 0) {
|
||||
event.cancelled(senderLocation.distance(targetLocation) > value);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
+85
@@ -0,0 +1,85 @@
|
||||
package net.draycia.carbon.listeners.contexts;
|
||||
|
||||
import net.draycia.carbon.CarbonChat;
|
||||
import net.draycia.carbon.api.events.misc.CarbonEvents;
|
||||
import net.draycia.carbon.api.events.PreChatFormatEvent;
|
||||
import net.draycia.carbon.api.Context;
|
||||
import net.milkbowl.vault.economy.Economy;
|
||||
import org.bukkit.OfflinePlayer;
|
||||
import org.checkerframework.checker.nullness.qual.NonNull;
|
||||
|
||||
public class EconomyContext {
|
||||
@NonNull
|
||||
private final CarbonChat carbonChat;
|
||||
|
||||
@NonNull
|
||||
private final Economy economy;
|
||||
|
||||
public EconomyContext(@NonNull final CarbonChat carbonChat) {
|
||||
this.carbonChat = carbonChat;
|
||||
this.economy = this.carbonChat.getServer().getServicesManager().getRegistration(Economy.class).getProvider();
|
||||
|
||||
CarbonEvents.register(PreChatFormatEvent.class, event -> {
|
||||
final Context context = event.channel().context("vault-balance");
|
||||
|
||||
if (context == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
final Double requiredBal;
|
||||
|
||||
if (context.isNumber()) {
|
||||
requiredBal = context.asNumber().doubleValue();;
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
|
||||
if (requiredBal.equals(0.0)) {
|
||||
return;
|
||||
}
|
||||
|
||||
final OfflinePlayer player = event.user().offlinePlayer();
|
||||
|
||||
if (!this.economy.has(player, requiredBal)) {
|
||||
event.cancelled(true);
|
||||
|
||||
event.user().sendMessage(this.carbonChat.adventureManager()
|
||||
.processMessage(event.channel().cannotUseMessage()));
|
||||
}
|
||||
});
|
||||
|
||||
CarbonEvents.register(PreChatFormatEvent.class, event -> {
|
||||
final Context context = event.channel().context("vault-cost");
|
||||
|
||||
if (context == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
final Double cost;
|
||||
|
||||
if (context.isNumber()) {
|
||||
cost = context.asNumber().doubleValue();
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
|
||||
if (cost.equals(0.0)) {
|
||||
return;
|
||||
}
|
||||
|
||||
final OfflinePlayer player = event.user().offlinePlayer();
|
||||
|
||||
if (!this.economy.has(player, cost)) {
|
||||
event.cancelled(true);
|
||||
|
||||
event.user().sendMessage(this.carbonChat.adventureManager()
|
||||
.processMessage(event.channel().cannotUseMessage()));
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
this.economy.withdrawPlayer(player, cost);
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
+117
@@ -0,0 +1,117 @@
|
||||
package net.draycia.carbon.listeners.contexts;
|
||||
|
||||
import net.draycia.carbon.api.channels.ChatChannel;
|
||||
import net.draycia.carbon.CarbonChat;
|
||||
import net.draycia.carbon.api.events.misc.CarbonEvents;
|
||||
import net.draycia.carbon.api.events.PreChatFormatEvent;
|
||||
import net.draycia.carbon.api.Context;
|
||||
import net.kyori.event.PostOrders;
|
||||
import org.bukkit.configuration.ConfigurationSection;
|
||||
import org.bukkit.configuration.file.FileConfiguration;
|
||||
import org.checkerframework.checker.nullness.qual.NonNull;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
public class FilterContext {
|
||||
|
||||
@NonNull
|
||||
private final CarbonChat carbonChat;
|
||||
|
||||
@NonNull
|
||||
private final Map<String, List<@NonNull Pattern>> patternReplacements = new HashMap<>();
|
||||
|
||||
@NonNull
|
||||
private final List<@NonNull Pattern> blockedWords = new ArrayList<>();
|
||||
|
||||
public FilterContext(@NonNull final CarbonChat carbonChat) {
|
||||
this.carbonChat = carbonChat;
|
||||
this.reloadFilters();
|
||||
|
||||
CarbonEvents.register(PreChatFormatEvent.class, PostOrders.FIRST, false, event -> {
|
||||
if (!carbonChat.moderationConfig().getBoolean("filters.enabled")) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (event.user().online()) {
|
||||
if (event.user().player().hasPermission("carbonchat.filter.exempt")) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (!this.channelUsesFilter(event.channel())) {
|
||||
return;
|
||||
}
|
||||
|
||||
String message = event.message();
|
||||
|
||||
for (final Map.Entry<String, List<Pattern>> entry : this.patternReplacements.entrySet()) {
|
||||
for (final Pattern pattern : entry.getValue()) {
|
||||
final Matcher matcher = pattern.matcher(message);
|
||||
|
||||
if (entry.getKey().equals("_")) {
|
||||
message = matcher.replaceAll("");
|
||||
} else {
|
||||
message = matcher.replaceAll(entry.getKey());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
event.message(message);
|
||||
|
||||
for (final Pattern blockedWord : this.blockedWords) {
|
||||
if (blockedWord.matcher(event.message()).find()) {
|
||||
event.cancelled(true);
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public void reloadFilters() {
|
||||
this.patternReplacements.clear();
|
||||
this.blockedWords.clear();
|
||||
|
||||
final FileConfiguration config = this.carbonChat.moderationConfig();
|
||||
final ConfigurationSection filters = config.getConfigurationSection("filters.filters");
|
||||
|
||||
if (filters != null) {
|
||||
for (final String replacement : filters.getKeys(false)) {
|
||||
final List<Pattern> patterns = new ArrayList<>();
|
||||
|
||||
for (final String word : filters.getStringList(replacement)) {
|
||||
if (this.carbonChat.moderationConfig().getBoolean("filters.case-sensitive")) {
|
||||
patterns.add(Pattern.compile(word));
|
||||
} else {
|
||||
patterns.add(Pattern.compile(word, Pattern.CASE_INSENSITIVE));
|
||||
}
|
||||
}
|
||||
|
||||
this.patternReplacements.put(replacement, patterns);
|
||||
}
|
||||
}
|
||||
|
||||
for (final String replacement : config.getStringList("filters.blocked-words")) {
|
||||
if (this.carbonChat.moderationConfig().getBoolean("filters.case-sensitive")) {
|
||||
this.blockedWords.add(Pattern.compile(replacement));
|
||||
} else {
|
||||
this.blockedWords.add(Pattern.compile(replacement, Pattern.CASE_INSENSITIVE));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private boolean channelUsesFilter(@NonNull final ChatChannel chatChannel) {
|
||||
final Context context = chatChannel.context("filter");
|
||||
|
||||
if (context == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return context.isBoolean() && context.asBoolean();
|
||||
}
|
||||
|
||||
}
|
||||
+124
@@ -0,0 +1,124 @@
|
||||
package net.draycia.carbon.listeners.contexts;
|
||||
|
||||
import com.palmergames.bukkit.towny.TownyAPI;
|
||||
import com.palmergames.bukkit.towny.event.TownRemoveResidentEvent;
|
||||
import com.palmergames.bukkit.towny.exceptions.NotRegisteredException;
|
||||
import com.palmergames.bukkit.towny.object.Resident;
|
||||
import net.draycia.carbon.CarbonChat;
|
||||
import net.draycia.carbon.api.channels.ChatChannel;
|
||||
import net.draycia.carbon.api.events.misc.CarbonEvents;
|
||||
import net.draycia.carbon.api.events.ChannelSwitchEvent;
|
||||
import net.draycia.carbon.api.events.MessageContextEvent;
|
||||
import net.draycia.carbon.api.events.ReceiverContextEvent;
|
||||
import net.draycia.carbon.api.users.ChatUser;
|
||||
import net.draycia.carbon.api.Context;
|
||||
import net.kyori.event.PostOrders;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.bukkit.event.player.PlayerJoinEvent;
|
||||
import org.checkerframework.checker.nullness.qual.NonNull;
|
||||
|
||||
public final class TownyContext implements Listener {
|
||||
|
||||
@NonNull
|
||||
private static final String KEY = "towny-town";
|
||||
|
||||
@NonNull
|
||||
private final CarbonChat carbonChat;
|
||||
|
||||
public TownyContext(@NonNull final CarbonChat carbonChat) {
|
||||
this.carbonChat = carbonChat;
|
||||
|
||||
CarbonEvents.register(ReceiverContextEvent.class, event -> {
|
||||
final Context context = event.channel().context(KEY);
|
||||
|
||||
if (context != null && context.isBoolean() && context.asBoolean()) {
|
||||
event.cancelled(!this.isInSameTown(event.sender(), event.recipient()));
|
||||
}
|
||||
});
|
||||
|
||||
CarbonEvents.register(ChannelSwitchEvent.class, event -> {
|
||||
final Context context = event.channel().context(KEY);
|
||||
|
||||
if (context != null && context.isBoolean() && context.asBoolean()) {
|
||||
if (!this.isInTown(event.user())) {
|
||||
event.failureMessage(carbonChat.getConfig().getString("contexts.Towny.cancellation-message"));
|
||||
event.cancelled(true);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
CarbonEvents.register(MessageContextEvent.class, PostOrders.NORMAL, false, event -> {
|
||||
// TODO: event.setFailureMessage
|
||||
final Context context = event.channel().context(KEY);
|
||||
|
||||
if (context != null && context.isBoolean() && context.asBoolean()) {
|
||||
if (!this.isInTown(event.user())) {
|
||||
event.cancelled(!this.isInTown(event.user()));
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void onResidentRemove(final TownRemoveResidentEvent event) {
|
||||
final String name = event.getResident().getName();
|
||||
final ChatUser user = this.carbonChat.userService().wrap(name);
|
||||
final ChatChannel channel = user.selectedChannel();
|
||||
|
||||
if (channel == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
final Context context = channel.context(KEY);
|
||||
|
||||
if (context != null && context.isBoolean() && context.asBoolean()) {
|
||||
user.clearSelectedChannel();
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void onPlayerJoin(final PlayerJoinEvent event) {
|
||||
final ChatUser user = this.carbonChat.userService().wrap(event.getPlayer());
|
||||
final ChatChannel channel = user.selectedChannel();
|
||||
|
||||
if (channel == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
final Context context = channel.context(KEY);
|
||||
|
||||
if (context != null && context.isBoolean() && context.asBoolean() && !this.isInTown(user)) {
|
||||
user.clearSelectedChannel();
|
||||
}
|
||||
}
|
||||
|
||||
public boolean isInTown(@NonNull final ChatUser user) {
|
||||
try {
|
||||
return TownyAPI.getInstance().getDataSource().getResident(user.player().getName()).hasTown();
|
||||
} catch (final NotRegisteredException exception) {
|
||||
exception.printStackTrace();
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public boolean isInSameTown(@NonNull final ChatUser user1, @NonNull final ChatUser user2) {
|
||||
if (!user1.online() || !user2.online()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
final Resident resident = TownyAPI.getInstance().getDataSource().getResident(user1.player().getName());
|
||||
|
||||
if (resident.hasTown()) {
|
||||
return resident.getTown().hasResident(user2.player().getName());
|
||||
}
|
||||
} catch (final NotRegisteredException exception) {
|
||||
exception.printStackTrace();
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
}
|
||||
+116
@@ -0,0 +1,116 @@
|
||||
package net.draycia.carbon.listeners.contexts;
|
||||
|
||||
import com.sk89q.worldedit.bukkit.BukkitAdapter;
|
||||
import com.sk89q.worldedit.util.Location;
|
||||
import com.sk89q.worldedit.world.World;
|
||||
import com.sk89q.worldguard.WorldGuard;
|
||||
import com.sk89q.worldguard.protection.ApplicableRegionSet;
|
||||
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
|
||||
import com.sk89q.worldguard.protection.regions.RegionContainer;
|
||||
import com.sk89q.worldguard.protection.regions.RegionQuery;
|
||||
import net.draycia.carbon.api.events.misc.CarbonEvents;
|
||||
import net.draycia.carbon.api.events.MessageContextEvent;
|
||||
import net.draycia.carbon.api.events.ReceiverContextEvent;
|
||||
import net.draycia.carbon.api.users.ChatUser;
|
||||
import net.draycia.carbon.api.Context;
|
||||
import org.checkerframework.checker.nullness.qual.NonNull;
|
||||
|
||||
public final class WorldGuardContext {
|
||||
|
||||
@NonNull
|
||||
private static final String KEY = "worldguard-region";
|
||||
|
||||
public WorldGuardContext() {
|
||||
CarbonEvents.register(ReceiverContextEvent.class, event -> {
|
||||
event.cancelled(this.testContext(event.sender(), event.recipient(), event.context(KEY)));
|
||||
});
|
||||
|
||||
CarbonEvents.register(MessageContextEvent.class, event -> {
|
||||
final Context value = event.channel().context(KEY);
|
||||
|
||||
if (value != null && (value.isString() || value.isList()) && !this.isInRegionOrRegions(value, event.user())) {
|
||||
event.cancelled(true);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private boolean isInRegionOrRegions(@NonNull final Context context, @NonNull final ChatUser user) {
|
||||
if (context.isString()) {
|
||||
return this.isInRegion(context.asString(), user);
|
||||
}
|
||||
|
||||
if (context.isList()) {
|
||||
for (final String region : context.<String>asList()) {
|
||||
if (this.isInRegion(region, user)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public boolean testContext(@NonNull final ChatUser sender, @NonNull final ChatUser target, @NonNull final Context context) {
|
||||
boolean user1InRegion = false;
|
||||
boolean user2InRegion = false;
|
||||
|
||||
if (context.isBoolean() && context.asBoolean()) {
|
||||
return this.isInSameRegion(sender, target);
|
||||
} else if (context.isString()) {
|
||||
user1InRegion = this.isInRegion(context.asString(), sender);
|
||||
user2InRegion = this.isInRegion(context.asString(), target);
|
||||
} else if (context.isList()) {
|
||||
for (final String item : context.<String>asList()) {
|
||||
if (!user1InRegion) {
|
||||
user1InRegion = this.isInRegion(item, sender);
|
||||
}
|
||||
|
||||
if (!user2InRegion) {
|
||||
user2InRegion = this.isInRegion(item, target);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
return true;
|
||||
}
|
||||
|
||||
return user1InRegion && user2InRegion;
|
||||
}
|
||||
|
||||
public boolean isInSameRegion(@NonNull final ChatUser user1, @NonNull final ChatUser user2) {
|
||||
if (!user1.online() || !user2.online()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
final Location user1Location = BukkitAdapter.adapt(user1.player().getLocation());
|
||||
final Location user2Location = BukkitAdapter.adapt(user2.player().getLocation());
|
||||
|
||||
final RegionContainer container = WorldGuard.getInstance().getPlatform().getRegionContainer();
|
||||
final RegionQuery regionQuery = container.createQuery();
|
||||
|
||||
final ApplicableRegionSet user1Regions = regionQuery.getApplicableRegions(user1Location);
|
||||
final ApplicableRegionSet user2Regions = regionQuery.getApplicableRegions(user2Location);
|
||||
|
||||
for (final ProtectedRegion region : user1Regions) {
|
||||
if (user2Regions.getRegions().contains(region)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public boolean isInRegion(@NonNull final String region, @NonNull final ChatUser user) {
|
||||
final RegionContainer container = WorldGuard.getInstance().getPlatform().getRegionContainer();
|
||||
final World world = BukkitAdapter.adapt(user.player().getWorld());
|
||||
final ProtectedRegion protection = container.get(world).getRegion(region);
|
||||
|
||||
return this.isInRegion(protection, user);
|
||||
}
|
||||
|
||||
public boolean isInRegion(@NonNull final ProtectedRegion region, @NonNull final ChatUser user) {
|
||||
final org.bukkit.Location location = user.player().getLocation();
|
||||
|
||||
return region.contains(location.getBlockX(), location.getBlockY(), location.getBlockZ());
|
||||
}
|
||||
|
||||
}
|
||||
+110
@@ -0,0 +1,110 @@
|
||||
package net.draycia.carbon.listeners.contexts;
|
||||
|
||||
import com.gmail.nossr50.api.PartyAPI;
|
||||
import com.gmail.nossr50.events.party.McMMOPartyChangeEvent;
|
||||
import net.draycia.carbon.CarbonChat;
|
||||
import net.draycia.carbon.api.channels.ChatChannel;
|
||||
import net.draycia.carbon.api.events.misc.CarbonEvents;
|
||||
import net.draycia.carbon.api.events.ChannelSwitchEvent;
|
||||
import net.draycia.carbon.api.events.MessageContextEvent;
|
||||
import net.draycia.carbon.api.events.ReceiverContextEvent;
|
||||
import net.draycia.carbon.api.users.ChatUser;
|
||||
import net.draycia.carbon.api.Context;
|
||||
import net.kyori.event.PostOrders;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.bukkit.event.player.PlayerJoinEvent;
|
||||
import org.checkerframework.checker.nullness.qual.NonNull;
|
||||
|
||||
public final class mcMMOContext implements Listener {
|
||||
|
||||
@NonNull
|
||||
private final CarbonChat carbonChat;
|
||||
|
||||
@NonNull
|
||||
private static final String KEY = "mcmmo-party";
|
||||
|
||||
public mcMMOContext(@NonNull final CarbonChat carbonChat) {
|
||||
this.carbonChat = carbonChat;
|
||||
|
||||
CarbonEvents.register(ReceiverContextEvent.class, PostOrders.NORMAL, false, event -> {
|
||||
final Context context = event.channel().context(KEY);
|
||||
|
||||
if (context != null && context.isBoolean() && context.asBoolean()) {
|
||||
// TODO: failureMessage
|
||||
event.cancelled(!this.isInSameParty(event.sender(), event.recipient()));
|
||||
}
|
||||
});
|
||||
|
||||
CarbonEvents.register(ChannelSwitchEvent.class, PostOrders.NORMAL, false, event -> {
|
||||
final Context context = event.channel().context(KEY);
|
||||
|
||||
if (context != null && context.isBoolean() && context.asBoolean()) {
|
||||
if (!this.isInParty(event.user())) {
|
||||
event.failureMessage(carbonChat.getConfig().getString("contexts.mcMMO.cancellation-message"));
|
||||
event.cancelled(true);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
CarbonEvents.register(MessageContextEvent.class, PostOrders.NORMAL, false, event -> {
|
||||
final Context context = event.channel().context(KEY);
|
||||
|
||||
if (context != null && context.isBoolean() && context.asBoolean()) {
|
||||
event.cancelled(!this.isInParty(event.user()));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private static final McMMOPartyChangeEvent.EventReason LEFT = McMMOPartyChangeEvent.EventReason.LEFT_PARTY;
|
||||
private static final McMMOPartyChangeEvent.EventReason KICKED = McMMOPartyChangeEvent.EventReason.KICKED_FROM_PARTY;
|
||||
|
||||
@EventHandler(ignoreCancelled = true)
|
||||
public void onPartyLeave(final McMMOPartyChangeEvent event) {
|
||||
if (event.getReason() != LEFT && event.getReason() != KICKED) {
|
||||
return;
|
||||
}
|
||||
|
||||
final ChatUser user = this.carbonChat.userService().wrap(event.getPlayer());
|
||||
final ChatChannel channel = user.selectedChannel();
|
||||
|
||||
if (channel == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
final Context context = channel.context(KEY);
|
||||
|
||||
if (context != null && context.isBoolean() && context.asBoolean() && !this.isInParty(user)) {
|
||||
user.clearSelectedChannel();
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void onPlayerJoin(final PlayerJoinEvent event) {
|
||||
final ChatUser user = this.carbonChat.userService().wrap(event.getPlayer());
|
||||
final ChatChannel channel = user.selectedChannel();
|
||||
|
||||
if (channel == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
final Context context = channel.context(KEY);
|
||||
|
||||
if (context != null && context.isBoolean() && context.asBoolean() && !this.isInParty(user)) {
|
||||
user.clearSelectedChannel();
|
||||
}
|
||||
}
|
||||
|
||||
public boolean isInParty(@NonNull final ChatUser user) {
|
||||
return PartyAPI.inParty(user.player());
|
||||
}
|
||||
|
||||
public boolean isInSameParty(@NonNull final ChatUser user1, @NonNull final ChatUser user2) {
|
||||
if (!user1.online() || !user2.online()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return PartyAPI.inSameParty(user1.player(), user2.player());
|
||||
}
|
||||
|
||||
}
|
||||
+103
@@ -0,0 +1,103 @@
|
||||
package net.draycia.carbon.listeners.events;
|
||||
|
||||
import net.draycia.carbon.api.channels.ChatChannel;
|
||||
import net.draycia.carbon.api.users.ChatUser;
|
||||
import net.draycia.carbon.CarbonChat;
|
||||
import net.kyori.adventure.text.Component;
|
||||
import net.kyori.adventure.text.TextComponent;
|
||||
import net.kyori.adventure.text.serializer.plain.PlainComponentSerializer;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.EventPriority;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.bukkit.event.player.AsyncPlayerChatEvent;
|
||||
import org.checkerframework.checker.nullness.qual.NonNull;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.HashSet;
|
||||
|
||||
public class BukkitChatListener implements Listener {
|
||||
|
||||
@NonNull
|
||||
private final CarbonChat carbonChat;
|
||||
|
||||
public BukkitChatListener(@NonNull final CarbonChat carbonChat) {
|
||||
this.carbonChat = carbonChat;
|
||||
}
|
||||
|
||||
// Chat messages
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void onPlayerchat(@NonNull final AsyncPlayerChatEvent event) {
|
||||
final ChatUser user = this.carbonChat.userService().wrap(event.getPlayer());
|
||||
ChatChannel channel = user.selectedChannel();
|
||||
|
||||
if (channel == null) {
|
||||
if (this.carbonChat.channelManager().defaultChannel() == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
channel = this.carbonChat.channelManager().defaultChannel();
|
||||
}
|
||||
|
||||
if (channel.shouldCancelChatEvent()) {
|
||||
event.setCancelled(true);
|
||||
}
|
||||
|
||||
for (final ChatChannel entry : this.carbonChat.channelManager().registry().values()) {
|
||||
if (entry.messagePrefix() == null || entry.messagePrefix().isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (event.getMessage().startsWith(entry.messagePrefix())) {
|
||||
if (entry.canPlayerUse(user)) {
|
||||
event.setMessage(event.getMessage().substring(entry.messagePrefix().length()));
|
||||
channel = entry;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
final ChatChannel selectedChannel = channel;
|
||||
|
||||
if (!selectedChannel.canPlayerUse(user)) {
|
||||
return;
|
||||
}
|
||||
|
||||
final Collection<ChatUser> recipients;
|
||||
|
||||
if (selectedChannel.honorsRecipientList()) {
|
||||
recipients = new HashSet<>();
|
||||
|
||||
for (final Player recipient : event.getRecipients()) {
|
||||
recipients.add(this.carbonChat.userService().wrap(recipient));
|
||||
}
|
||||
} else {
|
||||
recipients = selectedChannel.audiences();
|
||||
}
|
||||
|
||||
event.getRecipients().clear();
|
||||
|
||||
if (event.isAsynchronous()) {
|
||||
final Component component = selectedChannel.sendMessage(user, recipients, event.getMessage(), false);
|
||||
|
||||
if (!component.equals(TextComponent.empty())) {
|
||||
event.setFormat(PlainComponentSerializer.plain().serialize(component)
|
||||
.replaceAll("(?:[^%]|\\A)%(?:[^%]|\\z)", "%%"));
|
||||
}
|
||||
} else {
|
||||
Bukkit.getScheduler().runTaskAsynchronously(this.carbonChat, () -> {
|
||||
final Component component = selectedChannel.sendMessage(user, recipients, event.getMessage(), false);
|
||||
|
||||
this.carbonChat.adventureManager().audiences().console().sendMessage(component);
|
||||
|
||||
if (this.carbonChat.getConfig().getBoolean("show-tips")) {
|
||||
this.carbonChat.getLogger().info("Tip: Sync chat event! I cannot set the message format due to this. :(");
|
||||
this.carbonChat.getLogger().info("Tip: To 'solve' this, do a binary search and see which plugin is triggering");
|
||||
this.carbonChat.getLogger().info("Tip: sync chat events and causing this, and let that plugin author know.");
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package net.draycia.carbon.listeners.events;
|
||||
|
||||
import net.draycia.carbon.CarbonChat;
|
||||
import net.draycia.carbon.api.events.misc.CarbonEvents;
|
||||
import net.draycia.carbon.api.events.PreChatFormatEvent;
|
||||
import net.kyori.event.PostOrders;
|
||||
import org.checkerframework.checker.nullness.qual.NonNull;
|
||||
|
||||
public class CapsHandler {
|
||||
|
||||
public CapsHandler(@NonNull final CarbonChat carbonChat) {
|
||||
CarbonEvents.register(PreChatFormatEvent.class, PostOrders.FIRST, false, event -> {
|
||||
if (!carbonChat.moderationConfig().getBoolean("caps-protection.enabled")) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!(event.message().length() >= carbonChat.moderationConfig().getInt("caps-protection.minimum-length"))) {
|
||||
return;
|
||||
}
|
||||
|
||||
int amountOfCaps = 0;
|
||||
|
||||
for (final char letter : event.message().toCharArray()) {
|
||||
if (Character.isUpperCase(letter)) {
|
||||
amountOfCaps++;
|
||||
}
|
||||
}
|
||||
|
||||
final double capsPercentage = (amountOfCaps * 100.0) / event.message().length();
|
||||
|
||||
if (!(capsPercentage >= carbonChat.moderationConfig().getDouble("caps-protection.percent-caps"))) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (carbonChat.moderationConfig().getBoolean("block-message")) {
|
||||
event.cancelled(true);
|
||||
} else {
|
||||
event.message(event.message().toLowerCase());
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
package net.draycia.carbon.listeners.events;
|
||||
|
||||
import net.draycia.carbon.CarbonChat;
|
||||
import net.draycia.carbon.api.events.misc.CarbonEvents;
|
||||
import net.draycia.carbon.api.events.PreChatFormatEvent;
|
||||
import net.kyori.event.PostOrders;
|
||||
import org.bukkit.configuration.ConfigurationSection;
|
||||
import org.checkerframework.checker.nullness.qual.NonNull;
|
||||
|
||||
public class CustomPlaceholderHandler {
|
||||
|
||||
public CustomPlaceholderHandler(@NonNull final CarbonChat carbonChat) {
|
||||
CarbonEvents.register(PreChatFormatEvent.class, PostOrders.FIRST, false, event -> {
|
||||
final ConfigurationSection placeholders = carbonChat.getConfig().getConfigurationSection("placeholders");
|
||||
|
||||
for (final String key : placeholders.getKeys(false)) {
|
||||
final String value = placeholders.getString(key);
|
||||
|
||||
event.format(event.format().replace("<" + key + ">", value));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
package net.draycia.carbon.listeners.events;
|
||||
|
||||
import net.draycia.carbon.api.events.misc.CarbonEvents;
|
||||
import net.draycia.carbon.api.events.ChatFormatEvent;
|
||||
import net.kyori.event.PostOrders;
|
||||
|
||||
public class IgnoredPlayerHandler {
|
||||
|
||||
public IgnoredPlayerHandler() {
|
||||
CarbonEvents.register(ChatFormatEvent.class, PostOrders.FIRST, false, event -> {
|
||||
if (event.target() == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (event.target().ignoringUser(event.sender())) {
|
||||
event.cancelled(true);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
package net.draycia.carbon.listeners.events;
|
||||
|
||||
import net.draycia.carbon.util.CarbonUtils;
|
||||
import net.draycia.carbon.api.events.misc.CarbonEvents;
|
||||
import net.draycia.carbon.api.events.ChatComponentEvent;
|
||||
import net.kyori.adventure.text.Component;
|
||||
import net.kyori.adventure.text.TextComponent;
|
||||
import net.kyori.event.PostOrders;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
public class ItemLinkHandler {
|
||||
|
||||
public ItemLinkHandler() {
|
||||
CarbonEvents.register(ChatComponentEvent.class, PostOrders.FIRST, false, event -> {
|
||||
if (!event.sender().online()) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Handle item linking placeholders
|
||||
final Player player = event.sender().player();
|
||||
|
||||
if (!player.hasPermission("carbonchat.itemlink")) {
|
||||
return;
|
||||
}
|
||||
|
||||
final Component itemComponent = CarbonUtils.createComponent(player);
|
||||
|
||||
if (itemComponent.equals(TextComponent.empty())) {
|
||||
return;
|
||||
}
|
||||
|
||||
for (final Pattern pattern : event.channel().itemLinkPatterns()) {
|
||||
final String patternContent = pattern.toString().replace("\\Q", "").replace("\\E", "");
|
||||
|
||||
if (event.originalMessage().contains(patternContent)) {
|
||||
final TextComponent component = (TextComponent) event.component().replaceFirstText(pattern, input -> {
|
||||
return TextComponent.builder().append(itemComponent);
|
||||
});
|
||||
|
||||
event.component(component);
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
package net.draycia.carbon.listeners.events;
|
||||
|
||||
import net.kyori.adventure.text.format.TextColor;
|
||||
import net.kyori.adventure.text.format.TextDecoration;
|
||||
import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer;
|
||||
import net.kyori.adventure.text.serializer.legacy.LegacyFormat;
|
||||
import net.draycia.carbon.api.events.misc.CarbonEvents;
|
||||
import net.draycia.carbon.api.events.PreChatFormatEvent;
|
||||
import net.kyori.event.PostOrders;
|
||||
import org.checkerframework.checker.nullness.qual.NonNull;
|
||||
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
public class LegacyFormatHandler {
|
||||
|
||||
private final @NonNull Pattern pattern =
|
||||
Pattern.compile("[§&]x[§&]([0-9a-f])[§&]([0-9a-f])[§&]([0-9a-f])[§&]([0-9a-f])[§&]([0-9a-f])[§&]([0-9a-f])");
|
||||
|
||||
public LegacyFormatHandler() {
|
||||
CarbonEvents.register(PreChatFormatEvent.class, PostOrders.FIRST, false, event -> {
|
||||
// Legacy RGB
|
||||
event.format(this.pattern.matcher(event.format()).replaceAll("<#$1$2$3$4$5$6>"));
|
||||
|
||||
// Legacy Colors
|
||||
for (final char c : "0123456789abcdef".toCharArray()) {
|
||||
final LegacyFormat format = LegacyComponentSerializer.parseChar(c);
|
||||
final TextColor color = format.color();
|
||||
|
||||
event.format(event.format().replaceAll("[§&]" + c, "<" + color.asHexString() + ">"));
|
||||
}
|
||||
|
||||
// Legacy Formatting
|
||||
for (final char c : "klmno".toCharArray()) {
|
||||
final LegacyFormat format = LegacyComponentSerializer.parseChar(c);
|
||||
final TextDecoration decoration = format.decoration();
|
||||
|
||||
event.format(event.format().replaceAll("[§&]" + c, "<" + decoration.name() + ">"));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package net.draycia.carbon.listeners.events;
|
||||
|
||||
import net.draycia.carbon.api.events.misc.CarbonEvents;
|
||||
import net.draycia.carbon.api.events.PrivateMessageEvent;
|
||||
import net.draycia.carbon.api.events.PreChatFormatEvent;
|
||||
|
||||
public class MuteHandler {
|
||||
|
||||
public MuteHandler() {
|
||||
CarbonEvents.register(PrivateMessageEvent.class, event -> {
|
||||
if (event.sender().muted()) {
|
||||
event.cancelled(true);
|
||||
}
|
||||
});
|
||||
|
||||
CarbonEvents.register(PreChatFormatEvent.class, event -> {
|
||||
if (event.user().muted()) {
|
||||
event.cancelled(true);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
package net.draycia.carbon.listeners.events;
|
||||
|
||||
import net.draycia.carbon.api.events.misc.CarbonEvents;
|
||||
import net.draycia.carbon.api.events.PreChatFormatEvent;
|
||||
import net.kyori.event.PostOrders;
|
||||
|
||||
public class OfflineNameHandler {
|
||||
|
||||
public OfflineNameHandler() {
|
||||
CarbonEvents.register(PreChatFormatEvent.class, PostOrders.LATE, false, event -> {
|
||||
// If the player isn't online (cross server message), use their normal name
|
||||
if (!event.user().online()) {
|
||||
event.format(event.format().replace("%player_displayname%", "%player_name%"));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package net.draycia.carbon.listeners.events;
|
||||
|
||||
import net.draycia.carbon.CarbonChat;
|
||||
import net.draycia.carbon.api.events.misc.CarbonEvents;
|
||||
import net.draycia.carbon.api.events.ChatComponentEvent;
|
||||
import net.kyori.adventure.key.Key;
|
||||
import net.kyori.adventure.sound.Sound;
|
||||
import net.kyori.event.PostOrders;
|
||||
import org.checkerframework.checker.nullness.qual.NonNull;
|
||||
|
||||
public class PingHandler {
|
||||
|
||||
public PingHandler(@NonNull final CarbonChat carbonChat) {
|
||||
CarbonEvents.register(ChatComponentEvent.class, PostOrders.LAST, false, event -> {
|
||||
if (!carbonChat.getConfig().getBoolean("pings.enabled")) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (event.target() == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
final String targetName = event.target().offlinePlayer().getName();
|
||||
final String prefix = carbonChat.getConfig().getString("pings.prefix", "");
|
||||
final boolean caseSensitive = carbonChat.getConfig().getBoolean("pings.case-sensitive", false);
|
||||
|
||||
if (targetName == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (caseSensitive) {
|
||||
if (!event.originalMessage().contains(prefix + targetName)) {
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
if (!event.originalMessage().toLowerCase().contains((prefix + targetName).toLowerCase())) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
final Key key = Key.of(carbonChat.getConfig().getString("pings.sound"));
|
||||
final Sound.Source source = Sound.Source.valueOf(carbonChat.getConfig().getString("pings.source"));
|
||||
final float volume = (float) carbonChat.getConfig().getDouble("pings.volume");
|
||||
final float pitch = (float) carbonChat.getConfig().getDouble("pings.pitch");
|
||||
|
||||
event.target().playSound(Sound.of(key, source, volume, pitch));
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
package net.draycia.carbon.listeners.events;
|
||||
|
||||
import me.clip.placeholderapi.PlaceholderAPI;
|
||||
import net.draycia.carbon.api.events.misc.CarbonEvents;
|
||||
import net.draycia.carbon.api.events.PreChatFormatEvent;
|
||||
import net.kyori.event.PostOrders;
|
||||
|
||||
public class PlaceholderHandler {
|
||||
|
||||
public PlaceholderHandler() {
|
||||
CarbonEvents.register(PreChatFormatEvent.class, PostOrders.FIRST, false, event -> {
|
||||
event.format(PlaceholderAPI.setPlaceholders(event.user().offlinePlayer(), event.format()));
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
package net.draycia.carbon.listeners.events;
|
||||
|
||||
import net.draycia.carbon.api.channels.ChatChannel;
|
||||
import net.draycia.carbon.api.users.ChatUser;
|
||||
import net.draycia.carbon.CarbonChat;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.bukkit.event.player.PlayerJoinEvent;
|
||||
import org.bukkit.event.player.PlayerQuitEvent;
|
||||
import org.checkerframework.checker.nullness.qual.NonNull;
|
||||
|
||||
public class PlayerJoinListener implements Listener {
|
||||
|
||||
@NonNull
|
||||
private final CarbonChat carbonChat;
|
||||
|
||||
public PlayerJoinListener(@NonNull final CarbonChat carbonChat) {
|
||||
this.carbonChat = carbonChat;
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void onPlayerJoin(final PlayerJoinEvent event) {
|
||||
final ChatUser user = this.carbonChat.userService().wrap(event.getPlayer());
|
||||
|
||||
this.carbonChat.userService().validate(user);
|
||||
|
||||
if (user.nickname() != null) {
|
||||
user.nickname(user.nickname());
|
||||
}
|
||||
|
||||
final String channel = this.carbonChat.getConfig().getString("channel-on-join");
|
||||
|
||||
if (channel == null || channel.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (channel.equals("DEFAULT")) {
|
||||
user.selectedChannel(this.carbonChat.channelManager().defaultChannel());
|
||||
return;
|
||||
}
|
||||
|
||||
final ChatChannel chatChannel = this.carbonChat.channelManager().registry().channel(channel);
|
||||
|
||||
if (chatChannel != null) {
|
||||
user.selectedChannel(chatChannel);
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void onPlayerQuit(final PlayerQuitEvent event) {
|
||||
final ChatUser user = this.carbonChat.userService().wrapIfLoaded(event.getPlayer());
|
||||
|
||||
if (user != null) {
|
||||
this.carbonChat.userService().invalidate(user);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
package net.draycia.carbon.listeners.events;
|
||||
|
||||
import me.clip.placeholderapi.PlaceholderAPI;
|
||||
import net.draycia.carbon.api.events.misc.CarbonEvents;
|
||||
import net.draycia.carbon.api.events.ChatFormatEvent;
|
||||
import net.kyori.event.PostOrders;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
public class RelationalPlaceholderHandler {
|
||||
|
||||
public RelationalPlaceholderHandler() {
|
||||
CarbonEvents.register(ChatFormatEvent.class, PostOrders.FIRST, false, event -> {
|
||||
if (event.target() == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!event.sender().online() || !event.target().online()) {
|
||||
return;
|
||||
}
|
||||
|
||||
final Player sender = event.sender().player();
|
||||
final Player target = event.target().player();
|
||||
|
||||
event.format(PlaceholderAPI.setRelationalPlaceholders(sender, target, event.format()));
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
package net.draycia.carbon.listeners.events;
|
||||
|
||||
import net.draycia.carbon.CarbonChat;
|
||||
import net.draycia.carbon.api.events.misc.CarbonEvents;
|
||||
import net.draycia.carbon.api.events.ChatComponentEvent;
|
||||
import net.draycia.carbon.api.events.ChatFormatEvent;
|
||||
import net.kyori.event.PostOrders;
|
||||
import org.checkerframework.checker.nullness.qual.NonNull;
|
||||
|
||||
public class ShadowMuteHandler {
|
||||
|
||||
public ShadowMuteHandler(@NonNull final CarbonChat carbonChat) {
|
||||
CarbonEvents.register(ChatComponentEvent.class, PostOrders.FIRST, false, event -> {
|
||||
if (event.sender().shadowMuted() && event.sender().equals(event.target())) {
|
||||
event.cancelled(true);
|
||||
}
|
||||
});
|
||||
|
||||
CarbonEvents.register(ChatFormatEvent.class, PostOrders.FIRST, false, event -> {
|
||||
if (event.target() != null) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!event.sender().shadowMuted()) {
|
||||
return;
|
||||
}
|
||||
|
||||
final String prefix = carbonChat.moderationConfig().getString("shadow-mute-prefix", "[SM] ");
|
||||
|
||||
event.format(prefix + event.format());
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
package net.draycia.carbon.listeners.events;
|
||||
|
||||
import net.draycia.carbon.api.events.misc.CarbonEvents;
|
||||
import net.draycia.carbon.api.events.ChatComponentEvent;
|
||||
import net.kyori.adventure.text.TextComponent;
|
||||
import net.kyori.adventure.text.event.ClickEvent;
|
||||
import net.kyori.event.PostOrders;
|
||||
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
public class UrlLinkHandler {
|
||||
|
||||
private static final Pattern URL_PATTERN = Pattern.compile("(?:(https?)://)?([-\\w_.]+\\.\\w{2,})(/\\S*)?");
|
||||
|
||||
public UrlLinkHandler() {
|
||||
CarbonEvents.register(ChatComponentEvent.class, PostOrders.NORMAL, true, event -> {
|
||||
final TextComponent newComponent = (TextComponent) event.component()
|
||||
.replaceText(URL_PATTERN, url -> url.clickEvent(ClickEvent.openUrl(url.content())));
|
||||
|
||||
event.component(newComponent);
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
package net.draycia.carbon.listeners.events;
|
||||
|
||||
import net.draycia.carbon.CarbonChat;
|
||||
import net.draycia.carbon.api.events.misc.CarbonEvents;
|
||||
import net.draycia.carbon.api.events.PreChatFormatEvent;
|
||||
import net.kyori.adventure.text.minimessage.MiniMessage;
|
||||
import net.kyori.event.PostOrders;
|
||||
|
||||
public class UserFormattingHandler {
|
||||
|
||||
public UserFormattingHandler() {
|
||||
CarbonEvents.register(PreChatFormatEvent.class, PostOrders.FIRST, false, event -> {
|
||||
if (!event.user().online()) {
|
||||
this.suppressFormatting(event);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!event.user().player().hasPermission("carbonchat.formatting") &&
|
||||
!event.user().player().hasPermission("carbonchat.channels." + event.channel().key() + ".formatting")) {
|
||||
this.suppressFormatting(event);
|
||||
} else {
|
||||
// Swap the &-style codes for minimessage-compatible strings
|
||||
event.message(MiniMessage.get().serialize(CarbonChat.LEGACY.deserialize(event.message())));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void suppressFormatting(final PreChatFormatEvent event) {
|
||||
event.format(event.format().replace("<message>", "<pre><message></pre>"));
|
||||
}
|
||||
|
||||
}
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
package net.draycia.carbon.listeners.events;
|
||||
|
||||
import net.draycia.carbon.CarbonChat;
|
||||
import net.draycia.carbon.api.events.misc.CarbonEvents;
|
||||
import net.draycia.carbon.api.events.PrivateMessageEvent;
|
||||
import net.kyori.adventure.key.Key;
|
||||
import net.kyori.adventure.sound.Sound;
|
||||
import net.kyori.event.PostOrders;
|
||||
import org.checkerframework.checker.nullness.qual.NonNull;
|
||||
|
||||
public class WhisperPingHandler {
|
||||
|
||||
public WhisperPingHandler(@NonNull final CarbonChat carbonChat) {
|
||||
|
||||
CarbonEvents.register(PrivateMessageEvent.class, PostOrders.LAST, false, event -> {
|
||||
if (event.sender().uuid().equals(event.target().uuid())) {
|
||||
return;
|
||||
}
|
||||
|
||||
final String senderName = event.sender().offlinePlayer().getName();
|
||||
|
||||
if (senderName == null || !event.message().contains(senderName)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!carbonChat.getConfig().getBoolean("whisper.pings.enabled")) {
|
||||
return;
|
||||
}
|
||||
|
||||
final Key key = Key.of(carbonChat.getConfig().getString("whisper.pings.sound"));
|
||||
final Sound.Source source = Sound.Source.valueOf(carbonChat.getConfig().getString("whisper.pings.source"));
|
||||
final float volume = (float) carbonChat.getConfig().getDouble("whisper.pings.volume");
|
||||
final float pitch = (float) carbonChat.getConfig().getDouble("whisper.pings.pitch");
|
||||
|
||||
event.sender().playSound(Sound.of(key, source, volume, pitch));
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
package net.draycia.carbon.managers;
|
||||
|
||||
import de.themoep.minedown.adventure.MineDown;
|
||||
import me.clip.placeholderapi.PlaceholderAPI;
|
||||
import net.draycia.carbon.CarbonChat;
|
||||
import net.kyori.adventure.platform.bukkit.BukkitAudiences;
|
||||
import net.kyori.adventure.text.Component;
|
||||
import net.kyori.adventure.text.TextComponent;
|
||||
import net.kyori.adventure.text.minimessage.MiniMessage;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.checkerframework.checker.nullness.qual.NonNull;
|
||||
import org.checkerframework.checker.nullness.qual.Nullable;
|
||||
|
||||
public class AdventureManager {
|
||||
|
||||
@NonNull
|
||||
private final CarbonChat carbonChat;
|
||||
|
||||
@NonNull
|
||||
private final BukkitAudiences audiences;
|
||||
|
||||
public AdventureManager(@NonNull final CarbonChat carbonChat) {
|
||||
this.carbonChat = carbonChat;
|
||||
this.audiences = BukkitAudiences.create(carbonChat);
|
||||
}
|
||||
|
||||
@NonNull
|
||||
public Component processMessageWithPapi(@NonNull final Player player, @Nullable final String input,
|
||||
@NonNull final String @NonNull ... placeholders) {
|
||||
if (input == null || input.trim().isEmpty()) {
|
||||
return TextComponent.empty();
|
||||
}
|
||||
|
||||
return this.processMessage(PlaceholderAPI.setPlaceholders(player, input), placeholders);
|
||||
}
|
||||
|
||||
@NonNull
|
||||
public Component processMessage(@Nullable final String input, @NonNull final String @NonNull ... placeholders) {
|
||||
if (input == null || input.trim().isEmpty()) {
|
||||
return TextComponent.empty();
|
||||
}
|
||||
|
||||
switch (this.carbonChat.language().getString("formatting.type", "minimessage").toLowerCase()) {
|
||||
case "minedown":
|
||||
return MineDown.parse(input, placeholders);
|
||||
case "mojang":
|
||||
case "mojangson":
|
||||
case "json":
|
||||
return this.processMojang(input, placeholders);
|
||||
case "minimessage-markdown":
|
||||
return MiniMessage.markdown().parse(input, placeholders);
|
||||
case "minimessage":
|
||||
default:
|
||||
return MiniMessage.get().parse(input, placeholders);
|
||||
}
|
||||
}
|
||||
|
||||
@NonNull
|
||||
private Component processMojang(@NonNull String input, @NonNull final String @NonNull ... placeholders) {
|
||||
for (int i = 0; i < placeholders.length; i += 2) {
|
||||
final String placeholder = placeholders[i];
|
||||
final String replacement = placeholders[i + 1];
|
||||
|
||||
input = input.replace("<" + placeholder + ">", replacement);
|
||||
}
|
||||
|
||||
return this.audiences().gsonSerializer().deserialize(input);
|
||||
}
|
||||
|
||||
@NonNull
|
||||
public BukkitAudiences audiences() {
|
||||
return this.audiences;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
package net.draycia.carbon.managers;
|
||||
|
||||
import net.draycia.carbon.channels.impls.CarbonChatChannel;
|
||||
import net.draycia.carbon.CarbonChat;
|
||||
import net.draycia.carbon.channels.ChannelRegistry;
|
||||
import net.draycia.carbon.api.channels.ChatChannel;
|
||||
import net.draycia.carbon.api.events.misc.CarbonEvents;
|
||||
import net.draycia.carbon.api.events.ChannelRegisterEvent;
|
||||
import org.bukkit.configuration.ConfigurationSection;
|
||||
import org.checkerframework.checker.nullness.qual.MonotonicNonNull;
|
||||
import org.checkerframework.checker.nullness.qual.NonNull;
|
||||
import org.checkerframework.checker.nullness.qual.Nullable;
|
||||
|
||||
import java.util.Collections;
|
||||
|
||||
public class ChannelManager {
|
||||
|
||||
@NonNull
|
||||
private final CarbonChat carbonChat;
|
||||
|
||||
@NonNull
|
||||
private final ChannelRegistry registry;
|
||||
|
||||
@Nullable
|
||||
@MonotonicNonNull
|
||||
private String defaultChannelKey = null;
|
||||
|
||||
public ChannelManager(@NonNull final CarbonChat carbonChat) {
|
||||
this.carbonChat = carbonChat;
|
||||
this.registry = new ChannelRegistry(carbonChat);
|
||||
|
||||
this.reload();
|
||||
}
|
||||
|
||||
public @Nullable ChatChannel loadChannel(@NonNull final String key, @NonNull final ConfigurationSection section) {
|
||||
final ChatChannel channel = new CarbonChatChannel(key, this.carbonChat, section);
|
||||
|
||||
final String name = section.getString("name");
|
||||
|
||||
if (name != null && name.length() > 16) {
|
||||
this.carbonChat.getLogger().warning("Channel name [" + name + "] too long! Max length: 16.");
|
||||
this.carbonChat.getLogger().warning("Skipping channel, please check your settings!");
|
||||
return null;
|
||||
}
|
||||
|
||||
return channel;
|
||||
}
|
||||
|
||||
public boolean registerChannel(@NonNull final ChatChannel channel) {
|
||||
final boolean success = this.registry().register(channel.key(), channel);
|
||||
|
||||
if (success) {
|
||||
if (channel.isDefault() && this.defaultChannelKey == null) {
|
||||
this.carbonChat.getLogger().info("Default channel registered: " + channel.name());
|
||||
this.defaultChannelKey = channel.key();
|
||||
}
|
||||
|
||||
CarbonEvents.post(new ChannelRegisterEvent(Collections.singletonList(channel), this.registry()));
|
||||
}
|
||||
|
||||
return success;
|
||||
}
|
||||
|
||||
public @NonNull Registry<ChatChannel> registry() {
|
||||
return this.registry;
|
||||
}
|
||||
|
||||
public @Nullable ChatChannel defaultChannel() {
|
||||
if (this.defaultChannelKey != null) {
|
||||
return this.registry.channel(this.defaultChannelKey);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public @Nullable ChatChannel channelOrDefault(@Nullable final String key) {
|
||||
if (key == null) {
|
||||
return this.defaultChannel();
|
||||
}
|
||||
|
||||
final ChatChannel channel = this.registry.channel(key);
|
||||
|
||||
if (channel == null) {
|
||||
return this.defaultChannel();
|
||||
}
|
||||
|
||||
return channel;
|
||||
}
|
||||
|
||||
private void reload() {
|
||||
this.registry.clearAll();
|
||||
|
||||
for (final String key : this.carbonChat.getConfig().getConfigurationSection("channels").getKeys(false)) {
|
||||
final ConfigurationSection section =
|
||||
this.carbonChat.getConfig().getConfigurationSection("channels").getConfigurationSection(key);
|
||||
|
||||
final ChatChannel channel = this.loadChannel(key, section);
|
||||
|
||||
if (channel != null) {
|
||||
if (this.registerChannel(channel)) {
|
||||
String prefix = channel.messagePrefix();
|
||||
|
||||
if (prefix != null && !prefix.trim().isEmpty()) {
|
||||
prefix = "(" + prefix + ") ";
|
||||
} else {
|
||||
prefix = "";
|
||||
}
|
||||
|
||||
this.carbonChat.getLogger().info("Registering channel: " + prefix + channel.name());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package net.draycia.carbon.managers;
|
||||
|
||||
import net.draycia.carbon.commands.ChannelCommand;
|
||||
import net.draycia.carbon.commands.ChannelListCommand;
|
||||
import net.draycia.carbon.commands.ChatReloadCommand;
|
||||
import net.draycia.carbon.commands.ClearChatCommand;
|
||||
import net.draycia.carbon.commands.IgnoreCommand;
|
||||
import net.draycia.carbon.commands.MeCommand;
|
||||
import net.draycia.carbon.commands.MessageCommand;
|
||||
import net.draycia.carbon.commands.MuteCommand;
|
||||
import net.draycia.carbon.commands.NicknameCommand;
|
||||
import net.draycia.carbon.commands.ReplyCommand;
|
||||
import net.draycia.carbon.commands.SetColorCommand;
|
||||
import net.draycia.carbon.commands.SpyChannelCommand;
|
||||
import net.draycia.carbon.commands.SudoChannelCommand;
|
||||
import net.draycia.carbon.commands.ToggleCommand;
|
||||
import net.draycia.carbon.api.commands.CommandSettings;
|
||||
import net.draycia.carbon.CarbonChat;
|
||||
import net.draycia.carbon.commands.ShadowMuteCommand;
|
||||
import org.bukkit.configuration.ConfigurationSection;
|
||||
import org.checkerframework.checker.nullness.qual.NonNull;
|
||||
|
||||
public class CommandManager {
|
||||
|
||||
@NonNull
|
||||
private final CarbonChat carbonChat;
|
||||
|
||||
public CommandManager(@NonNull final CarbonChat carbonChat) {
|
||||
this.carbonChat = carbonChat;
|
||||
|
||||
this.reloadCommands();
|
||||
}
|
||||
|
||||
private void reloadCommands() {
|
||||
new ChannelCommand(this.carbonChat, this.commandSettings("channel"));
|
||||
new ChannelListCommand(this.carbonChat, this.commandSettings("channellist"));
|
||||
new ChatReloadCommand(this.carbonChat, this.commandSettings("chatreload"));
|
||||
new ClearChatCommand(this.carbonChat, this.commandSettings("clearchat"));
|
||||
new IgnoreCommand(this.carbonChat, this.commandSettings("ignore"));
|
||||
new MeCommand(this.carbonChat, this.commandSettings("me"));
|
||||
new MessageCommand(this.carbonChat, this.commandSettings("message"));
|
||||
new MuteCommand(this.carbonChat, this.commandSettings("mute"));
|
||||
new NicknameCommand(this.carbonChat, this.commandSettings("nickname"));
|
||||
new ReplyCommand(this.carbonChat, this.commandSettings("reply"));
|
||||
new SetColorCommand(this.carbonChat, this.commandSettings("setcolor"));
|
||||
new ShadowMuteCommand(this.carbonChat, this.commandSettings("shadowmute"));
|
||||
new SpyChannelCommand(this.carbonChat, this.commandSettings("spy"));
|
||||
new SudoChannelCommand(this.carbonChat, this.commandSettings("sudochannel"));
|
||||
new ToggleCommand(this.carbonChat, this.commandSettings("toggle"));
|
||||
}
|
||||
|
||||
@NonNull
|
||||
private CommandSettings commandSettings(@NonNull final String command) {
|
||||
final ConfigurationSection section = this.carbonChat.commandsConfig().getConfigurationSection(command);
|
||||
|
||||
return new CommandSettings(section.getBoolean("enabled"), section.getString("name"),
|
||||
section.getStringList("aliases"));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
package net.draycia.carbon.messaging;
|
||||
|
||||
import net.draycia.carbon.api.messaging.MessageService;
|
||||
import net.draycia.carbon.messaging.impl.BungeeMessageService;
|
||||
import com.google.common.io.ByteArrayDataOutput;
|
||||
import net.draycia.carbon.CarbonChat;
|
||||
import net.draycia.carbon.api.channels.ChatChannel;
|
||||
import net.draycia.carbon.messaging.impl.EmptyMessageService;
|
||||
import net.draycia.carbon.messaging.impl.RedisMessageService;
|
||||
import net.draycia.carbon.api.users.ChatUser;
|
||||
import net.kyori.adventure.text.Component;
|
||||
import net.kyori.adventure.text.format.TextColor;
|
||||
import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer;
|
||||
import org.checkerframework.checker.nullness.qual.NonNull;
|
||||
|
||||
import java.util.UUID;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
public class MessageManager {
|
||||
|
||||
@NonNull
|
||||
private final CarbonChat carbonChat;
|
||||
|
||||
@NonNull
|
||||
private final MessageService messageService;
|
||||
|
||||
@NonNull
|
||||
private final GsonComponentSerializer gsonSerializer;
|
||||
|
||||
public MessageManager(@NonNull final CarbonChat carbonChat) {
|
||||
this.carbonChat = carbonChat;
|
||||
this.gsonSerializer = this.carbonChat.adventureManager().audiences().gsonSerializer();
|
||||
|
||||
String messageSystem = this.carbonChat.getConfig().getString("message-system", "none");
|
||||
|
||||
if (messageSystem == null) {
|
||||
messageSystem = "none";
|
||||
}
|
||||
|
||||
switch (messageSystem.toLowerCase()) {
|
||||
case "bungee":
|
||||
this.carbonChat.getLogger().info("Using Bungee Plugin Messaging for message forwarding!");
|
||||
this.messageService = new BungeeMessageService(this.carbonChat);
|
||||
break;
|
||||
case "redis":
|
||||
this.carbonChat.getLogger().info("Using Redis for message forwarding!");
|
||||
this.messageService = new RedisMessageService(this.carbonChat);
|
||||
break;
|
||||
case "none":
|
||||
this.messageService = new EmptyMessageService();
|
||||
break;
|
||||
default:
|
||||
this.carbonChat.getLogger().info("Invalid message service selected! Disabling syncing until next restart!");
|
||||
this.messageService = new EmptyMessageService();
|
||||
break;
|
||||
}
|
||||
|
||||
this.registerDefaultListeners();
|
||||
}
|
||||
|
||||
private void registerDefaultListeners() {
|
||||
this.messageService().registerUserMessageListener("nickname", (user, byteArray) -> {
|
||||
final String nickname = byteArray.readUTF();
|
||||
|
||||
user.nickname(nickname, true);
|
||||
|
||||
if (user.online()) {
|
||||
final String message = this.carbonChat.language().getString("nickname-set");
|
||||
|
||||
user.sendMessage(this.carbonChat.adventureManager().processMessageWithPapi(user.player(),
|
||||
message, "nickname", nickname));
|
||||
}
|
||||
});
|
||||
|
||||
this.messageService().registerUserMessageListener("nickname-reset", (user, byteArray) -> {
|
||||
user.nickname(null, true);
|
||||
|
||||
if (user.online()) {
|
||||
final String message = this.carbonChat.language().getString("nickname-reset");
|
||||
|
||||
user.sendMessage(this.carbonChat.adventureManager().processMessageWithPapi(user.player(), message));
|
||||
}
|
||||
});
|
||||
|
||||
this.messageService().registerUserMessageListener("selected-channel", (user, byteArray) -> {
|
||||
user.selectedChannel(this.carbonChat.channelManager().registry().channel(byteArray.readUTF()), true);
|
||||
});
|
||||
|
||||
this.messageService().registerUserMessageListener("spying-whispers", (user, byteArray) -> {
|
||||
user.spyingWhispers(byteArray.readBoolean(), true);
|
||||
});
|
||||
|
||||
this.messageService().registerUserMessageListener("muted", (user, byteArray) -> {
|
||||
user.muted(byteArray.readBoolean(), true);
|
||||
});
|
||||
|
||||
this.messageService().registerUserMessageListener("shadow-muted", (user, byteArray) -> {
|
||||
user.shadowMuted(byteArray.readBoolean(), true);
|
||||
});
|
||||
|
||||
this.messageService().registerUserMessageListener("reply-target", (user, byteArray) -> {
|
||||
user.replyTarget(new UUID(byteArray.readLong(), byteArray.readLong()), true);
|
||||
});
|
||||
|
||||
this.messageService().registerUserMessageListener("ignoring-user", (user, byteArray) -> {
|
||||
user.ignoringUser(new UUID(byteArray.readLong(), byteArray.readLong()), byteArray.readBoolean(), true);
|
||||
});
|
||||
|
||||
this.messageService().registerUserMessageListener("ignoring-channel", (user, byteArray) -> {
|
||||
user.channelSettings(this.carbonChat.channelManager().registry().channel(byteArray.readUTF()))
|
||||
.ignoring(byteArray.readBoolean(), true);
|
||||
});
|
||||
|
||||
this.messageService().registerUserMessageListener("spying-channel", (user, byteArray) -> {
|
||||
user.channelSettings(this.carbonChat.channelManager().registry().channel(byteArray.readUTF()))
|
||||
.spying(byteArray.readBoolean(), true);
|
||||
});
|
||||
|
||||
this.messageService().registerUserMessageListener("channel-color", (user, byteArray) -> {
|
||||
user.channelSettings(this.carbonChat.channelManager().registry().channel(byteArray.readUTF()))
|
||||
.color(TextColor.fromHexString(byteArray.readUTF()), true);
|
||||
});
|
||||
|
||||
this.messageService().registerUserMessageListener("channel-color-reset", (user, byteArray) -> {
|
||||
user.channelSettings(this.carbonChat.channelManager().registry().channel(byteArray.readUTF()))
|
||||
.color(null, true);
|
||||
});
|
||||
|
||||
this.messageService().registerUUIDMessageListener("channel-component", (uuid, byteArray) -> {
|
||||
final ChatChannel channel = this.carbonChat.channelManager().registry().channel(byteArray.readUTF());
|
||||
final ChatUser user = this.carbonChat.userService().wrap(uuid);
|
||||
|
||||
if (channel != null) {
|
||||
final Component component = this.gsonSerializer.deserialize(byteArray.readUTF());
|
||||
|
||||
channel.sendComponent(user, component);
|
||||
|
||||
this.carbonChat.adventureManager().audiences().console().sendMessage(component);
|
||||
}
|
||||
});
|
||||
|
||||
this.messageService().registerUUIDMessageListener("whisper-component", (uuid, byteArray) -> {
|
||||
final UUID recipient = new UUID(byteArray.readLong(), byteArray.readLong());
|
||||
|
||||
final ChatUser target = this.carbonChat.userService().wrap(recipient);
|
||||
final String message = byteArray.readUTF();
|
||||
|
||||
if (!target.ignoringUser(uuid)) {
|
||||
target.replyTarget(uuid);
|
||||
target.sendMessage(this.gsonSerializer.deserialize(message));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@NonNull
|
||||
public MessageService messageService() {
|
||||
return this.messageService;
|
||||
}
|
||||
|
||||
public void sendMessage(@NonNull final String key, @NonNull final UUID uuid,
|
||||
@NonNull final Consumer<@NonNull ByteArrayDataOutput> consumer) {
|
||||
this.messageService().sendMessage(key, uuid, consumer);
|
||||
}
|
||||
|
||||
}
|
||||
+116
@@ -0,0 +1,116 @@
|
||||
package net.draycia.carbon.messaging.impl;
|
||||
|
||||
import com.google.common.io.ByteArrayDataInput;
|
||||
import com.google.common.io.ByteArrayDataOutput;
|
||||
import com.google.common.io.ByteStreams;
|
||||
import io.github.leonardosnt.bungeechannelapi.BungeeChannelApi;
|
||||
import net.draycia.carbon.CarbonChat;
|
||||
import net.draycia.carbon.api.messaging.MessageService;
|
||||
import net.draycia.carbon.api.users.ChatUser;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.checkerframework.checker.nullness.qual.NonNull;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.function.BiConsumer;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
public class BungeeMessageService implements MessageService {
|
||||
|
||||
@NonNull
|
||||
private final CarbonChat carbonChat;
|
||||
|
||||
@NonNull
|
||||
private final BungeeChannelApi api;
|
||||
|
||||
@NonNull
|
||||
private final Map<@NonNull String, @NonNull BiConsumer<@NonNull ChatUser, @NonNull ByteArrayDataInput>> userLoadedListeners = new HashMap<>();
|
||||
|
||||
@NonNull
|
||||
private final Map<@NonNull String, @NonNull BiConsumer<@NonNull UUID, @NonNull ByteArrayDataInput>> userNotLoadedListeners = new HashMap<>();
|
||||
|
||||
@NonNull
|
||||
private final UUID serverUUID = UUID.randomUUID();
|
||||
|
||||
public BungeeMessageService(@NonNull final CarbonChat carbonChat) {
|
||||
this.carbonChat = carbonChat;
|
||||
|
||||
this.carbonChat.getServer().getMessenger().registerOutgoingPluginChannel(carbonChat, "BungeeCord");
|
||||
|
||||
this.api = BungeeChannelApi.of(carbonChat);
|
||||
|
||||
this.api.registerForwardListener((String channel, Player player, byte[] bytes) -> {
|
||||
try {
|
||||
final ByteArrayDataInput input = ByteStreams.newDataInput(bytes);
|
||||
|
||||
// Separated out for ease of debugging.
|
||||
final long mostServer = input.readLong();
|
||||
final long leastServer = input.readLong();
|
||||
|
||||
final UUID messageUUID = new UUID(mostServer, leastServer);
|
||||
|
||||
if (messageUUID.equals(this.serverUUID)) {
|
||||
return;
|
||||
}
|
||||
|
||||
final long mostUser = input.readLong();
|
||||
final long leastUser = input.readLong();
|
||||
|
||||
final UUID userUUID = new UUID(mostUser, leastUser);
|
||||
|
||||
this.receiveMessage(userUUID, channel, input);
|
||||
} catch (final IllegalStateException ignored) {
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void receiveMessage(@NonNull final UUID uuid, @NonNull final String key, @NonNull final ByteArrayDataInput value) {
|
||||
final ChatUser user = this.carbonChat.userService().wrapIfLoaded(uuid);
|
||||
|
||||
if (user != null) {
|
||||
for (final Map.Entry<String, BiConsumer<ChatUser, ByteArrayDataInput>> listener : this.userLoadedListeners.entrySet()) {
|
||||
if (key.equals(listener.getKey())) {
|
||||
listener.getValue().accept(user, value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (final Map.Entry<String, BiConsumer<UUID, ByteArrayDataInput>> listener : this.userNotLoadedListeners.entrySet()) {
|
||||
if (key.equals(listener.getKey())) {
|
||||
listener.getValue().accept(uuid, value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void registerUserMessageListener(@NonNull final String key, @NonNull final BiConsumer<@NonNull ChatUser, @NonNull ByteArrayDataInput> listener) {
|
||||
this.userLoadedListeners.put(key, listener);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void registerUUIDMessageListener(@NonNull final String key, @NonNull final BiConsumer<@NonNull UUID, @NonNull ByteArrayDataInput> listener) {
|
||||
this.userNotLoadedListeners.put(key, listener);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void unregisterMessageListener(@NonNull final String key) {
|
||||
this.userLoadedListeners.remove(key);
|
||||
this.userNotLoadedListeners.remove(key);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void sendMessage(@NonNull final String key, @NonNull final UUID uuid, @NonNull final Consumer<ByteArrayDataOutput> consumer) {
|
||||
final ByteArrayDataOutput msg = ByteStreams.newDataOutput();
|
||||
|
||||
msg.writeLong(this.serverUUID.getMostSignificantBits());
|
||||
msg.writeLong(this.serverUUID.getLeastSignificantBits());
|
||||
msg.writeLong(uuid.getMostSignificantBits());
|
||||
msg.writeLong(uuid.getLeastSignificantBits());
|
||||
|
||||
consumer.accept(msg);
|
||||
|
||||
this.api.forward("ALL", key, msg.toByteArray());
|
||||
}
|
||||
|
||||
}
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
package net.draycia.carbon.messaging.impl;
|
||||
|
||||
import com.google.common.io.ByteArrayDataInput;
|
||||
import com.google.common.io.ByteArrayDataOutput;
|
||||
import net.draycia.carbon.api.messaging.MessageService;
|
||||
import net.draycia.carbon.api.users.ChatUser;
|
||||
import org.checkerframework.checker.nullness.qual.NonNull;
|
||||
|
||||
import java.util.UUID;
|
||||
import java.util.function.BiConsumer;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
public class EmptyMessageService implements MessageService {
|
||||
|
||||
@Override
|
||||
public void registerUserMessageListener(@NonNull final String key, @NonNull final BiConsumer<@NonNull ChatUser, @NonNull ByteArrayDataInput> listener) {
|
||||
// do nothing
|
||||
}
|
||||
|
||||
@Override
|
||||
public void registerUUIDMessageListener(@NonNull final String key, @NonNull final BiConsumer<@NonNull UUID, @NonNull ByteArrayDataInput> listener) {
|
||||
// do nothing
|
||||
}
|
||||
|
||||
@Override
|
||||
public void unregisterMessageListener(@NonNull final String key) {
|
||||
// do nothing
|
||||
}
|
||||
|
||||
@Override
|
||||
public void sendMessage(@NonNull final String key, @NonNull final UUID uuid, @NonNull final Consumer<@NonNull ByteArrayDataOutput> consumer) {
|
||||
// do nothing
|
||||
}
|
||||
|
||||
}
|
||||
+133
@@ -0,0 +1,133 @@
|
||||
package net.draycia.carbon.messaging.impl;
|
||||
|
||||
import com.google.common.io.ByteArrayDataInput;
|
||||
import com.google.common.io.ByteArrayDataOutput;
|
||||
import com.google.common.io.ByteStreams;
|
||||
import io.lettuce.core.RedisClient;
|
||||
import io.lettuce.core.RedisURI;
|
||||
import io.lettuce.core.pubsub.StatefulRedisPubSubConnection;
|
||||
import io.lettuce.core.pubsub.api.sync.RedisPubSubCommands;
|
||||
import net.draycia.carbon.CarbonChat;
|
||||
import net.draycia.carbon.api.messaging.MessageService;
|
||||
import net.draycia.carbon.api.users.ChatUser;
|
||||
import net.draycia.carbon.util.RedisListener;
|
||||
import org.checkerframework.checker.nullness.qual.NonNull;
|
||||
|
||||
import java.util.Base64;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.function.BiConsumer;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
public class RedisMessageService implements MessageService {
|
||||
|
||||
@NonNull
|
||||
private final Map<@NonNull String, @NonNull BiConsumer<@NonNull ChatUser, @NonNull ByteArrayDataInput>> userLoadedListeners = new HashMap<>();
|
||||
|
||||
@NonNull
|
||||
private final Map<@NonNull String, @NonNull BiConsumer<@NonNull UUID, @NonNull ByteArrayDataInput>> userNotLoadedListeners = new HashMap<>();
|
||||
|
||||
@NonNull
|
||||
private final RedisPubSubCommands<@NonNull String, @NonNull String> subscribeSync;
|
||||
|
||||
@NonNull
|
||||
private final RedisPubSubCommands<@NonNull String, @NonNull String> publishSync;
|
||||
|
||||
@NonNull
|
||||
private final UUID serverUUID = UUID.randomUUID();
|
||||
|
||||
@NonNull
|
||||
private final CarbonChat carbonChat;
|
||||
|
||||
public RedisMessageService(@NonNull final CarbonChat carbonChat) {
|
||||
this.carbonChat = carbonChat;
|
||||
|
||||
final String host = this.carbonChat.getConfig().getString("redis.host");
|
||||
final String password = this.carbonChat.getConfig().getString("redis.password");
|
||||
final int port = this.carbonChat.getConfig().getInt("redis.port");
|
||||
final int database = this.carbonChat.getConfig().getInt("redis.database");
|
||||
|
||||
final RedisURI.Builder builder = RedisURI.Builder.redis(host, port)
|
||||
.withDatabase(database);
|
||||
|
||||
if (password != null) {
|
||||
builder.withPassword(password.toCharArray());
|
||||
}
|
||||
|
||||
final RedisClient client = RedisClient.create(builder.build());
|
||||
|
||||
final StatefulRedisPubSubConnection<String, String> subscribeConnection = client.connectPubSub();
|
||||
this.subscribeSync = subscribeConnection.sync();
|
||||
|
||||
final StatefulRedisPubSubConnection<String, String> publishConnection = client.connectPubSub();
|
||||
this.publishSync = publishConnection.sync();
|
||||
|
||||
subscribeConnection.addListener((RedisListener) (channel, message) -> {
|
||||
final ByteArrayDataInput input = ByteStreams.newDataInput(Base64.getDecoder().decode(message));
|
||||
|
||||
final UUID messageUUID = new UUID(input.readLong(), input.readLong());
|
||||
|
||||
if (messageUUID.equals(this.serverUUID)) {
|
||||
return;
|
||||
}
|
||||
|
||||
final UUID uuid = new UUID(input.readLong(), input.readLong());
|
||||
|
||||
this.receiveMessage(uuid, channel, input);
|
||||
});
|
||||
}
|
||||
|
||||
private void receiveMessage(@NonNull final UUID uuid, @NonNull final String key, @NonNull final ByteArrayDataInput value) {
|
||||
final ChatUser user = this.carbonChat.userService().wrapIfLoaded(uuid);
|
||||
|
||||
if (user != null) {
|
||||
for (final Map.Entry<String, BiConsumer<ChatUser, ByteArrayDataInput>> listener : this.userLoadedListeners.entrySet()) {
|
||||
if (key.equals(listener.getKey())) {
|
||||
listener.getValue().accept(user, value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (final Map.Entry<String, BiConsumer<UUID, ByteArrayDataInput>> listener : this.userNotLoadedListeners.entrySet()) {
|
||||
if (key.equals(listener.getKey())) {
|
||||
listener.getValue().accept(uuid, value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void registerUserMessageListener(@NonNull final String key, @NonNull final BiConsumer<@NonNull ChatUser, @NonNull ByteArrayDataInput> listener) {
|
||||
this.userLoadedListeners.put(key, listener);
|
||||
this.subscribeSync.subscribe(key);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void registerUUIDMessageListener(@NonNull final String key, @NonNull final BiConsumer<@NonNull UUID, @NonNull ByteArrayDataInput> listener) {
|
||||
this.userNotLoadedListeners.put(key, listener);
|
||||
this.subscribeSync.subscribe(key);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void unregisterMessageListener(@NonNull final String key) {
|
||||
this.userLoadedListeners.remove(key);
|
||||
this.userNotLoadedListeners.remove(key);
|
||||
|
||||
this.subscribeSync.unsubscribe(key);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void sendMessage(@NonNull final String key, @NonNull final UUID uuid, @NonNull final Consumer<@NonNull ByteArrayDataOutput> consumer) {
|
||||
final ByteArrayDataOutput msg = ByteStreams.newDataOutput();
|
||||
|
||||
msg.writeLong(this.serverUUID.getMostSignificantBits());
|
||||
msg.writeLong(this.serverUUID.getLeastSignificantBits());
|
||||
msg.writeLong(uuid.getMostSignificantBits());
|
||||
msg.writeLong(uuid.getLeastSignificantBits());
|
||||
|
||||
consumer.accept(msg);
|
||||
|
||||
this.publishSync.publish(key, Base64.getEncoder().encodeToString(msg.toByteArray()));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,401 @@
|
||||
package net.draycia.carbon.storage.impl;
|
||||
|
||||
import net.draycia.carbon.api.channels.ChatChannel;
|
||||
import net.draycia.carbon.api.users.ChatUser;
|
||||
import net.draycia.carbon.api.users.UserChannelSettings;
|
||||
import net.draycia.carbon.util.FunctionalityConstants;
|
||||
import io.github.leonardosnt.bungeechannelapi.BungeeChannelApi;
|
||||
import net.draycia.carbon.CarbonChat;
|
||||
import net.draycia.carbon.api.events.misc.CarbonEvents;
|
||||
import net.draycia.carbon.api.events.ChannelSwitchEvent;
|
||||
import net.draycia.carbon.api.events.PrivateMessageEvent;
|
||||
import net.kyori.adventure.audience.Audience;
|
||||
import net.kyori.adventure.audience.ForwardingAudience;
|
||||
import net.kyori.adventure.key.Key;
|
||||
import net.kyori.adventure.sound.Sound;
|
||||
import net.kyori.adventure.text.Component;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.OfflinePlayer;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.checkerframework.checker.nullness.qual.MonotonicNonNull;
|
||||
import org.checkerframework.checker.nullness.qual.NonNull;
|
||||
import org.checkerframework.checker.nullness.qual.Nullable;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
public class CarbonChatUser implements ChatUser, ForwardingAudience {
|
||||
|
||||
@NonNull
|
||||
private final transient CarbonChat carbonChat;
|
||||
@NonNull
|
||||
private final Map<@NonNull String, @NonNull SimpleUserChannelSettings> channelSettings = new HashMap<>();
|
||||
@NonNull
|
||||
private final List<@NonNull UUID> ignoredUsers = new ArrayList<>();
|
||||
@MonotonicNonNull // @NonNull but not initialised in all constructors.
|
||||
private UUID uuid;
|
||||
@Nullable
|
||||
private String selectedChannel = null;
|
||||
private boolean muted = false;
|
||||
private boolean shadowMuted = false;
|
||||
private boolean spyingWhispers = false;
|
||||
|
||||
@Nullable
|
||||
private String nickname = null;
|
||||
|
||||
@Nullable
|
||||
private transient UUID replyTarget = null;
|
||||
|
||||
public CarbonChatUser() {
|
||||
this.carbonChat = (CarbonChat) Bukkit.getPluginManager().getPlugin("CarbonChat");
|
||||
}
|
||||
|
||||
public CarbonChatUser(@NonNull final UUID uuid) {
|
||||
this();
|
||||
this.uuid = uuid;
|
||||
}
|
||||
|
||||
@Override
|
||||
@NonNull
|
||||
public Iterable<@NonNull ? extends Audience> audiences() {
|
||||
return Collections.singleton(this.carbonChat.adventureManager().audiences().player(this.uuid));
|
||||
}
|
||||
|
||||
@Override
|
||||
@Nullable
|
||||
public Player player() {
|
||||
return Bukkit.getPlayer(this.uuid);
|
||||
}
|
||||
|
||||
@Override
|
||||
@NonNull
|
||||
public OfflinePlayer offlinePlayer() {
|
||||
return Bukkit.getOfflinePlayer(this.uuid);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean online() {
|
||||
return this.offlinePlayer().isOnline();
|
||||
}
|
||||
|
||||
@Override
|
||||
@NonNull
|
||||
public UUID uuid() {
|
||||
return this.uuid;
|
||||
}
|
||||
|
||||
@Override
|
||||
@Nullable
|
||||
public String nickname() {
|
||||
return this.nickname;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void nickname(@Nullable String newNickname, final boolean fromRemote) {
|
||||
this.nickname = newNickname;
|
||||
|
||||
if (this.online()) {
|
||||
if (newNickname != null) {
|
||||
final Component component = this.carbonChat.adventureManager().processMessage(this.nickname);
|
||||
newNickname = CarbonChat.LEGACY.serialize(component);
|
||||
}
|
||||
|
||||
this.player().setDisplayName(newNickname);
|
||||
|
||||
if (this.carbonChat.getConfig().getBoolean("nicknames-set-tab-name")) {
|
||||
this.player().setPlayerListName(newNickname);
|
||||
}
|
||||
}
|
||||
|
||||
if (!fromRemote) {
|
||||
if (this.nickname == null) {
|
||||
this.carbonChat.messageManager().sendMessage("nickname-reset", this.uuid(), byteArray -> {
|
||||
});
|
||||
} else {
|
||||
this.carbonChat.messageManager().sendMessage("nickname", this.uuid(), byteArray -> {
|
||||
byteArray.writeUTF(this.nickname);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
@Nullable
|
||||
public ChatChannel selectedChannel() {
|
||||
if (this.selectedChannel == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return this.carbonChat.channelManager().channelOrDefault(this.selectedChannel);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void selectedChannel(@NonNull final ChatChannel chatChannel, final boolean fromRemote) {
|
||||
final String failureMessage = chatChannel.switchFailureMessage();
|
||||
|
||||
final ChannelSwitchEvent event = new ChannelSwitchEvent(chatChannel, this, failureMessage);
|
||||
|
||||
CarbonEvents.post(event);
|
||||
|
||||
if (event.cancelled()) {
|
||||
this.sendMessage(this.carbonChat.adventureManager().processMessage(event.failureMessage(),
|
||||
"channel", chatChannel.name()));
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
this.selectedChannel = chatChannel.key();
|
||||
|
||||
if (!fromRemote) {
|
||||
this.carbonChat.messageManager().sendMessage("selected-channel", this.uuid(), byteArray -> {
|
||||
byteArray.writeUTF(chatChannel.key());
|
||||
});
|
||||
}
|
||||
|
||||
if (this.online()) {
|
||||
this.sendMessage(this.carbonChat.adventureManager().processMessageWithPapi(this.player(), chatChannel.switchMessage(),
|
||||
"br", "\n",
|
||||
"color", "<" + chatChannel.channelColor(this).toString() + ">",
|
||||
"channel", chatChannel.name()));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void clearSelectedChannel() {
|
||||
this.selectedChannel(this.carbonChat.channelManager().defaultChannel());
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean ignoringUser(@NonNull final UUID uuid) {
|
||||
return this.ignoredUsers.contains(uuid);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void ignoringUser(@NonNull final UUID uuid, final boolean ignoring, final boolean fromRemote) {
|
||||
if (ignoring) {
|
||||
this.ignoredUsers.add(uuid);
|
||||
} else {
|
||||
this.ignoredUsers.remove(uuid);
|
||||
}
|
||||
|
||||
if (!fromRemote) {
|
||||
this.carbonChat.messageManager().sendMessage("ignoring-user", this.uuid(), byteArray -> {
|
||||
byteArray.writeLong(uuid.getMostSignificantBits());
|
||||
byteArray.writeLong(uuid.getLeastSignificantBits());
|
||||
byteArray.writeBoolean(ignoring);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@NonNull
|
||||
public List<@NonNull UUID> ignoredUsers() {
|
||||
return this.ignoredUsers;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void muted(final boolean muted, final boolean fromRemote) {
|
||||
this.muted = muted;
|
||||
|
||||
if (!fromRemote) {
|
||||
this.carbonChat.messageManager().sendMessage("muted", this.uuid(), byteArray -> {
|
||||
byteArray.writeBoolean(muted);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean muted() {
|
||||
return this.muted;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void shadowMuted(final boolean shadowMuted, final boolean fromRemote) {
|
||||
this.shadowMuted = shadowMuted;
|
||||
|
||||
if (!fromRemote) {
|
||||
this.carbonChat.messageManager().sendMessage("shadow-muted", this.uuid(), byteArray -> {
|
||||
byteArray.writeBoolean(shadowMuted);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean shadowMuted() {
|
||||
return this.shadowMuted;
|
||||
}
|
||||
|
||||
@Override
|
||||
@Nullable
|
||||
public UUID replyTarget() {
|
||||
return this.replyTarget;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void replyTarget(@Nullable final UUID target, final boolean fromRemote) {
|
||||
this.replyTarget = target;
|
||||
|
||||
if (!fromRemote) {
|
||||
this.carbonChat.messageManager().sendMessage("reply-target", this.uuid(), byteArray -> {
|
||||
byteArray.writeLong(target.getMostSignificantBits());
|
||||
byteArray.writeLong(target.getLeastSignificantBits());
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
@NonNull
|
||||
public UserChannelSettings channelSettings(@NonNull final ChatChannel channel) {
|
||||
return this.channelSettings.computeIfAbsent(channel.key(), name -> {
|
||||
return new SimpleUserChannelSettings(this.uuid, channel.key());
|
||||
});
|
||||
}
|
||||
|
||||
@NonNull
|
||||
public Map<@NonNull String, @NonNull ? extends UserChannelSettings> channelSettings() {
|
||||
return this.channelSettings;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void spyingWhispers(final boolean spyingWhispers, final boolean fromRemote) {
|
||||
this.spyingWhispers = spyingWhispers;
|
||||
|
||||
if (!fromRemote) {
|
||||
this.carbonChat.messageManager().sendMessage("spying-whispers", this.uuid(), byteArray -> {
|
||||
byteArray.writeBoolean(spyingWhispers);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean spyingwhispers() {
|
||||
return this.spyingWhispers;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void sendMessage(@NonNull final ChatUser sender, @NonNull final String message) {
|
||||
if (this.ignoringUser(sender) || sender.ignoringUser(this)) {
|
||||
return;
|
||||
}
|
||||
|
||||
final String toPlayerFormat = this.carbonChat.language().getString("message-to-other");
|
||||
final String fromPlayerFormat = this.carbonChat.language().getString("message-from-other");
|
||||
|
||||
String senderName = sender.offlinePlayer().getName();
|
||||
final String senderOfflineName = senderName;
|
||||
|
||||
String targetName = this.offlinePlayer().getName();
|
||||
final String targetOfflineName = targetName;
|
||||
|
||||
if (sender.online()) {
|
||||
senderName = sender.player().getDisplayName();
|
||||
}
|
||||
|
||||
if (this.online()) {
|
||||
targetName = this.player().getDisplayName();
|
||||
}
|
||||
|
||||
final Component toPlayerComponent = this.carbonChat.adventureManager().processMessage(toPlayerFormat, "br", "\n",
|
||||
"message", message,
|
||||
"targetname", targetOfflineName, "sendername", senderOfflineName,
|
||||
"target", targetName, "sender", senderName);
|
||||
|
||||
final Component fromPlayerComponent = this.carbonChat.adventureManager().processMessage(fromPlayerFormat, "br", "\n",
|
||||
"message", message,
|
||||
"targetname", targetOfflineName, "sendername", senderOfflineName,
|
||||
"target", targetName, "sender", senderName);
|
||||
|
||||
final PrivateMessageEvent event = new PrivateMessageEvent(sender, this, toPlayerComponent, fromPlayerComponent, message);
|
||||
|
||||
CarbonEvents.post(event);
|
||||
|
||||
if (event.cancelled()) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.online()) {
|
||||
if (sender.online()) {
|
||||
sender.sendMessage(toPlayerComponent);
|
||||
|
||||
if (sender.shadowMuted()) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.sendMessage(fromPlayerComponent);
|
||||
|
||||
sender.replyTarget(this);
|
||||
this.replyTarget(sender);
|
||||
|
||||
if (this.carbonChat.getConfig().getBoolean("pings.on-whisper")) {
|
||||
final Key key = Key.of(this.carbonChat.getConfig().getString("pings.sound"));
|
||||
final Sound.Source source = Sound.Source.valueOf(this.carbonChat.getConfig().getString("pings.source"));
|
||||
final float volume = (float) this.carbonChat.getConfig().getDouble("pings.volume");
|
||||
final float pitch = (float) this.carbonChat.getConfig().getDouble("pings.pitch");
|
||||
|
||||
this.playSound(Sound.of(key, source, volume, pitch));
|
||||
}
|
||||
}
|
||||
} else if (sender.online()) {
|
||||
final String targetNameFinal = targetName;
|
||||
final String senderNameFinal = senderName;
|
||||
|
||||
if (!FunctionalityConstants.HAS_PROXY) {
|
||||
final String playerOfflineFormat = this.carbonChat.language().getString("other-player-offline");
|
||||
|
||||
final Component playerOfflineComponent = this.carbonChat.adventureManager().processMessage(playerOfflineFormat,
|
||||
"br", "\n",
|
||||
"message", message,
|
||||
"targetname", targetOfflineName, "sendername", senderOfflineName,
|
||||
"target", targetNameFinal, "sender", senderNameFinal);
|
||||
|
||||
sender.sendMessage(playerOfflineComponent);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
BungeeChannelApi.of(this.carbonChat).getPlayerList("ALL").thenAccept(list -> {
|
||||
if (!list.contains(this.offlinePlayer().getName())) {
|
||||
final String playerOfflineFormat = this.carbonChat.language().getString("other-player-offline");
|
||||
|
||||
final Component playerOfflineComponent = this.carbonChat.adventureManager().processMessage(playerOfflineFormat,
|
||||
"br", "\n",
|
||||
"message", message,
|
||||
"targetname", targetOfflineName, "sendername", senderOfflineName,
|
||||
"target", targetNameFinal, "sender", senderNameFinal);
|
||||
|
||||
sender.sendMessage(playerOfflineComponent);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
sender.sendMessage(toPlayerComponent);
|
||||
|
||||
this.carbonChat.messageManager().sendMessage("whisper-component", sender.uuid(), byteArray -> {
|
||||
byteArray.writeLong(this.uuid().getMostSignificantBits());
|
||||
byteArray.writeLong(this.uuid().getLeastSignificantBits());
|
||||
byteArray.writeUTF(this.carbonChat.adventureManager().audiences().gsonSerializer().serialize(fromPlayerComponent));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
for (final Player player : Bukkit.getOnlinePlayers()) {
|
||||
final ChatUser user = this.carbonChat.userService().wrap(player);
|
||||
|
||||
if (!user.spyingwhispers()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (user.uuid().equals(sender.uuid()) || user.uuid().equals(this.uuid())) {
|
||||
continue;
|
||||
}
|
||||
|
||||
user.sendMessage(this.carbonChat.adventureManager().processMessage(this.carbonChat.language().getString("spy-whispers"),
|
||||
"br", "\n", "message", message,
|
||||
"targetname", targetOfflineName, "sendername", senderOfflineName,
|
||||
"target", targetName, "sender", senderName));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
package net.draycia.carbon.storage.impl;
|
||||
|
||||
import com.google.common.cache.CacheBuilder;
|
||||
import com.google.common.cache.CacheLoader;
|
||||
import com.google.common.cache.LoadingCache;
|
||||
import com.google.common.cache.RemovalNotification;
|
||||
import com.google.gson.Gson;
|
||||
import com.google.gson.GsonBuilder;
|
||||
import com.google.gson.reflect.TypeToken;
|
||||
import com.google.gson.stream.JsonReader;
|
||||
import com.google.gson.stream.JsonWriter;
|
||||
import net.draycia.carbon.CarbonChat;
|
||||
import net.draycia.carbon.api.users.ChatUser;
|
||||
import net.draycia.carbon.api.users.UserService;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.OfflinePlayer;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.checkerframework.checker.nullness.qual.NonNull;
|
||||
import org.checkerframework.checker.nullness.qual.Nullable;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileReader;
|
||||
import java.io.FileWriter;
|
||||
import java.io.IOException;
|
||||
import java.lang.reflect.Type;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
|
||||
public class JSONUserService implements UserService {
|
||||
|
||||
@NonNull
|
||||
private final CarbonChat carbonChat;
|
||||
@NonNull
|
||||
private final Gson gson = new GsonBuilder().setPrettyPrinting().create();
|
||||
@NonNull
|
||||
private final Type userType = new TypeToken<CarbonChatUser>() {}.getType();
|
||||
@NonNull
|
||||
private final LoadingCache<@NonNull UUID, @NonNull CarbonChatUser> userCache = CacheBuilder.newBuilder()
|
||||
.removalListener(this::saveUser)
|
||||
.build(CacheLoader.from(this::loadUser));
|
||||
|
||||
public JSONUserService(@NonNull final CarbonChat carbonChat) {
|
||||
this.carbonChat = carbonChat;
|
||||
|
||||
Bukkit.getScheduler().scheduleSyncRepeatingTask(carbonChat, this.userCache::cleanUp, 0L, 20 * 60 * 10);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDisable() {
|
||||
this.userCache.invalidateAll();
|
||||
this.userCache.cleanUp();
|
||||
}
|
||||
|
||||
@Override
|
||||
@Nullable
|
||||
public ChatUser wrap(@NonNull final String name) {
|
||||
final Player player = Bukkit.getPlayer(name);
|
||||
|
||||
if (player != null) {
|
||||
return this.wrap(player);
|
||||
}
|
||||
|
||||
return this.wrap(Bukkit.getOfflinePlayer(name));
|
||||
}
|
||||
|
||||
@Override
|
||||
@Nullable
|
||||
public ChatUser wrap(@NonNull final OfflinePlayer player) {
|
||||
return this.wrap(player.getUniqueId());
|
||||
}
|
||||
|
||||
@Override
|
||||
@Nullable
|
||||
public ChatUser wrap(@NonNull final UUID uuid) {
|
||||
try {
|
||||
return this.userCache.get(uuid);
|
||||
} catch (final ExecutionException exception) {
|
||||
exception.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
@Nullable
|
||||
public ChatUser wrapIfLoaded(@NonNull final UUID uuid) {
|
||||
return this.userCache.getIfPresent(uuid);
|
||||
}
|
||||
|
||||
@Override
|
||||
@Nullable
|
||||
public ChatUser refreshUser(@NonNull final UUID uuid) {
|
||||
this.userCache.invalidate(uuid);
|
||||
|
||||
return this.wrap(uuid);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void invalidate(@NonNull final ChatUser user) {
|
||||
this.userCache.invalidate(user.uuid());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void validate(@NonNull final ChatUser user) {
|
||||
this.userCache.put(user.uuid(), (CarbonChatUser) user);
|
||||
}
|
||||
|
||||
@NonNull
|
||||
private CarbonChatUser loadUser(@NonNull final UUID uuid) {
|
||||
final File userFile = new File(this.carbonChat.getDataFolder(), "users/" + uuid.toString() + ".json");
|
||||
this.ensureFileExists(userFile);
|
||||
|
||||
try (final JsonReader reader = this.gson.newJsonReader(new FileReader(userFile))) {
|
||||
final CarbonChatUser user = this.gson.fromJson(reader, this.userType);
|
||||
|
||||
if (user != null) {
|
||||
return user;
|
||||
}
|
||||
} catch (final IOException exception) {
|
||||
exception.printStackTrace();
|
||||
}
|
||||
|
||||
return new CarbonChatUser(uuid);
|
||||
}
|
||||
|
||||
private void saveUser(@NonNull final RemovalNotification<@NonNull UUID, @NonNull CarbonChatUser> notification) {
|
||||
final File userFile = new File(this.carbonChat.getDataFolder(), "users/" + notification.getKey().toString() + ".json");
|
||||
this.ensureFileExists(userFile);
|
||||
|
||||
try (final JsonWriter writer = this.gson.newJsonWriter(new FileWriter(userFile))) {
|
||||
this.gson.toJson(notification.getValue(), this.userType, writer);
|
||||
} catch (final IOException exception) {
|
||||
exception.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
private void ensureFileExists(@NonNull final File file) {
|
||||
if (!file.getParentFile().exists()) {
|
||||
file.getParentFile().mkdirs();
|
||||
}
|
||||
|
||||
if (!file.exists()) {
|
||||
try {
|
||||
file.createNewFile();
|
||||
} catch (final IOException exception) {
|
||||
exception.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+249
@@ -0,0 +1,249 @@
|
||||
package net.draycia.carbon.storage.impl;
|
||||
|
||||
import net.draycia.carbon.api.channels.ChatChannel;
|
||||
import net.draycia.carbon.api.users.UserChannelSettings;
|
||||
import co.aikar.idb.BukkitDB;
|
||||
import co.aikar.idb.DB;
|
||||
import co.aikar.idb.Database;
|
||||
import co.aikar.idb.DbRow;
|
||||
import co.aikar.idb.DbStatement;
|
||||
import co.aikar.idb.HikariPooledDatabase;
|
||||
import com.google.common.cache.CacheBuilder;
|
||||
import com.google.common.cache.CacheLoader;
|
||||
import com.google.common.cache.LoadingCache;
|
||||
import com.google.common.cache.RemovalNotification;
|
||||
import net.draycia.carbon.CarbonChat;
|
||||
import net.draycia.carbon.api.users.ChatUser;
|
||||
import net.draycia.carbon.api.users.UserService;
|
||||
import net.kyori.adventure.text.format.TextColor;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.OfflinePlayer;
|
||||
import org.bukkit.configuration.ConfigurationSection;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.checkerframework.checker.nullness.qual.NonNull;
|
||||
import org.checkerframework.checker.nullness.qual.Nullable;
|
||||
|
||||
import java.sql.SQLException;
|
||||
import java.sql.SQLSyntaxErrorException;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
|
||||
public class MySQLUserService implements UserService {
|
||||
|
||||
@NonNull
|
||||
private final CarbonChat carbonChat;
|
||||
@NonNull
|
||||
private final Database database;
|
||||
@NonNull
|
||||
private final LoadingCache<@NonNull UUID, @NonNull CarbonChatUser> userCache = CacheBuilder.newBuilder()
|
||||
.removalListener(this::saveUser)
|
||||
.build(CacheLoader.from(this::loadUser));
|
||||
|
||||
public MySQLUserService(@NonNull final CarbonChat carbonChat) {
|
||||
this.carbonChat = carbonChat;
|
||||
|
||||
final ConfigurationSection section = this.carbonChat.getConfig().getConfigurationSection("storage");
|
||||
|
||||
if (section == null) {
|
||||
throw new IllegalStateException("Missing Database Credentials!");
|
||||
}
|
||||
|
||||
final String username = section.getString("username", "username");
|
||||
final String password = section.getString("password", "password");
|
||||
final String dbname = section.getString("database", "0");
|
||||
final String hostandport = section.getString("hostname", "hostname") + ":" + section.getString("port", "0");
|
||||
|
||||
this.database = new HikariPooledDatabase(BukkitDB.getRecommendedOptions(carbonChat, username, password, dbname, hostandport));
|
||||
|
||||
DB.setGlobalDatabase(this.database);
|
||||
|
||||
try {
|
||||
this.database.executeUpdate("CREATE TABLE IF NOT EXISTS sc_users (uuid CHAR(36) PRIMARY KEY," +
|
||||
"channel VARCHAR(16), muted BOOLEAN, shadowmuted BOOLEAN, spyingwhispers BOOLEAN," +
|
||||
"nickname VARCHAR(512))");
|
||||
|
||||
// Ignore the exception, it's just saying the column already exists
|
||||
try {
|
||||
this.database.executeUpdate("ALTER TABLE sc_users ADD COLUMN spyingwhispers BOOLEAN DEFAULT false");
|
||||
this.database.executeUpdate("ALTER TABLE sc_users ADD COLUMN nickname VARCHAR(512) DEFAULT false");
|
||||
} catch (final SQLSyntaxErrorException ignored) {
|
||||
}
|
||||
|
||||
this.database.executeUpdate("CREATE TABLE IF NOT EXISTS sc_channel_settings (uuid CHAR(36), channel CHAR(16), spying BOOLEAN, ignored BOOLEAN, color TINYTEXT, PRIMARY KEY (uuid, channel))");
|
||||
|
||||
this.database.executeUpdate("CREATE TABLE IF NOT EXISTS sc_ignored_users (uuid CHAR(36), user CHAR(36), PRIMARY KEY (uuid, user))");
|
||||
} catch (final SQLException exception) {
|
||||
exception.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDisable() {
|
||||
this.userCache.invalidateAll();
|
||||
this.userCache.cleanUp();
|
||||
this.database.close();
|
||||
}
|
||||
|
||||
@Override
|
||||
@Nullable
|
||||
public ChatUser wrap(@NonNull final String name) {
|
||||
final Player player = Bukkit.getPlayer(name);
|
||||
|
||||
if (player != null) {
|
||||
return this.wrap(player);
|
||||
}
|
||||
|
||||
return this.wrap(Bukkit.getOfflinePlayer(name));
|
||||
}
|
||||
|
||||
@Override
|
||||
@Nullable
|
||||
public ChatUser wrap(@NonNull final OfflinePlayer player) {
|
||||
return this.wrap(player.getUniqueId());
|
||||
}
|
||||
|
||||
@Override
|
||||
@Nullable
|
||||
public ChatUser wrap(@NonNull final UUID uuid) {
|
||||
try {
|
||||
return this.userCache.get(uuid);
|
||||
} catch (final ExecutionException exception) {
|
||||
exception.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
@Nullable
|
||||
public ChatUser wrapIfLoaded(@NonNull final UUID uuid) {
|
||||
return this.userCache.getIfPresent(uuid);
|
||||
}
|
||||
|
||||
@Override
|
||||
@Nullable
|
||||
public ChatUser refreshUser(@NonNull final UUID uuid) {
|
||||
this.userCache.invalidate(uuid);
|
||||
|
||||
return this.wrap(uuid);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void invalidate(@NonNull final ChatUser user) {
|
||||
this.userCache.invalidate(user.uuid());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void validate(@NonNull final ChatUser user) {
|
||||
this.userCache.put(user.uuid(), (CarbonChatUser) user);
|
||||
}
|
||||
|
||||
@NonNull
|
||||
private CarbonChatUser loadUser(@NonNull final UUID uuid) {
|
||||
final CarbonChatUser user = new CarbonChatUser(uuid);
|
||||
|
||||
try (final DbStatement statement = this.database.query("SELECT * from sc_users WHERE uuid = ?;")) {
|
||||
statement.execute(uuid.toString());
|
||||
|
||||
final DbRow users = statement.getNextRow();
|
||||
|
||||
if (users == null) {
|
||||
return user;
|
||||
}
|
||||
|
||||
final List<DbRow> channelSettings = this.database.getResults("SELECT * from sc_channel_settings WHERE uuid = ?;", uuid.toString());
|
||||
final List<DbRow> ignoredUsers = this.database.getResults("SELECT * from sc_ignored_users WHERE uuid = ?;", uuid.toString());
|
||||
|
||||
final ChatChannel channel = this.carbonChat.channelManager().channelOrDefault(users.getString("channel"));
|
||||
|
||||
if (channel != null) {
|
||||
user.selectedChannel(channel, true);
|
||||
}
|
||||
|
||||
final String nickname = users.getString("nickname");
|
||||
|
||||
if (nickname != null) {
|
||||
user.nickname(nickname, true);
|
||||
}
|
||||
|
||||
user.muted(users.<Boolean>get("muted"), true);
|
||||
user.shadowMuted(users.<Boolean>get("shadowmuted"), true);
|
||||
user.spyingWhispers(users.<Boolean>get("spyingwhispers"), true);
|
||||
|
||||
for (final DbRow channelSetting : channelSettings) {
|
||||
final ChatChannel chatChannel = this.carbonChat.channelManager().registry().channel(channelSetting.getString("channel"));
|
||||
|
||||
if (chatChannel != null) {
|
||||
final UserChannelSettings settings = user.channelSettings(chatChannel);
|
||||
|
||||
settings.spying(channelSetting.<Boolean>get("spying"), true);
|
||||
settings.ignoring(channelSetting.<Boolean>get("ignored"), true);
|
||||
|
||||
final String color = channelSetting.getString("color");
|
||||
|
||||
if (color != null) {
|
||||
settings.color(TextColor.fromHexString(color), true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (final DbRow ignoredUser : ignoredUsers) {
|
||||
user.ignoringUser(UUID.fromString(ignoredUser.getString("user")), true, true);
|
||||
}
|
||||
} catch (final SQLException exception) {
|
||||
exception.printStackTrace();
|
||||
}
|
||||
|
||||
return user;
|
||||
}
|
||||
|
||||
private void saveUser(@NonNull final RemovalNotification<@NonNull UUID, @NonNull CarbonChatUser> notification) {
|
||||
final CarbonChatUser user = notification.getValue();
|
||||
|
||||
this.database.createTransaction(stm -> {
|
||||
// Save user general data
|
||||
String selectedName = null;
|
||||
|
||||
if (user.selectedChannel() != null) {
|
||||
selectedName = user.selectedChannel().key();
|
||||
}
|
||||
|
||||
this.carbonChat.getLogger().info("Saving user data!");
|
||||
stm.executeUpdateQuery("INSERT INTO sc_users (uuid, channel, muted, shadowmuted, spyingwhispers, nickname) VALUES (?, ?, ?, ?, ?, ?) " +
|
||||
"ON DUPLICATE KEY UPDATE channel = ?, muted = ?, shadowmuted = ?, spyingwhispers = ?, nickname =?",
|
||||
user.uuid().toString(), selectedName, user.muted(), user.shadowMuted(), user.spyingwhispers(), user.nickname(),
|
||||
selectedName, user.muted(), user.shadowMuted(), user.spyingwhispers(), user.nickname());
|
||||
|
||||
this.carbonChat.getLogger().info("Saving user channel settings!");
|
||||
// Save user channel settings
|
||||
for (final Map.Entry<String, ? extends UserChannelSettings> entry : user.channelSettings().entrySet()) {
|
||||
final UserChannelSettings value = entry.getValue();
|
||||
|
||||
String colorString = null;
|
||||
|
||||
if (value.color() != null) {
|
||||
colorString = value.color().asHexString();
|
||||
}
|
||||
|
||||
stm.executeUpdateQuery("INSERT INTO sc_channel_settings (uuid, channel, spying, ignored, color) VALUES (?, ?, ?, ?, ?) " +
|
||||
"ON DUPLICATE KEY UPDATE spying = ?, ignored = ?, color = ?",
|
||||
user.uuid().toString(), entry.getKey(), value.spying(), value.ignored(), colorString,
|
||||
value.spying(), value.ignored(), colorString);
|
||||
}
|
||||
|
||||
this.carbonChat.getLogger().info("Saving user ignores!");
|
||||
// Save user ignore list (remove old entries then add new ones)
|
||||
// TODO: keep DB up to date with settings as settings are mutated
|
||||
stm.executeUpdateQuery("DELETE FROM sc_ignored_users WHERE uuid = ?", user.uuid().toString());
|
||||
|
||||
for (final UUID entry : user.ignoredUsers()) {
|
||||
stm.executeUpdateQuery("INSERT INTO sc_ignored_users (uuid, user) VALUES (?, ?)",
|
||||
user.uuid().toString(), entry.toString());
|
||||
}
|
||||
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
+101
@@ -0,0 +1,101 @@
|
||||
package net.draycia.carbon.storage.impl;
|
||||
|
||||
import net.draycia.carbon.api.users.UserChannelSettings;
|
||||
import net.draycia.carbon.CarbonChat;
|
||||
import net.kyori.adventure.text.format.TextColor;
|
||||
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 java.util.UUID;
|
||||
|
||||
public class SimpleUserChannelSettings implements UserChannelSettings {
|
||||
|
||||
@NonNull
|
||||
private final transient CarbonChat carbonChat;
|
||||
private boolean spying;
|
||||
private boolean ignored;
|
||||
@Nullable
|
||||
private String color;
|
||||
@MonotonicNonNull // @NonNull but not initialised in all constructors.
|
||||
private UUID uuid;
|
||||
@MonotonicNonNull // @NonNull but not initialised in all constructors.
|
||||
private String channel;
|
||||
|
||||
private SimpleUserChannelSettings() {
|
||||
this.carbonChat = (CarbonChat) Bukkit.getPluginManager().getPlugin("CarbonChat");
|
||||
}
|
||||
|
||||
public SimpleUserChannelSettings(@NonNull final UUID uuid, @NonNull final String channel) {
|
||||
this.uuid = uuid;
|
||||
this.channel = channel;
|
||||
|
||||
this.carbonChat = (CarbonChat) Bukkit.getPluginManager().getPlugin("CarbonChat");
|
||||
}
|
||||
|
||||
@NonNull
|
||||
private CarbonChatUser user() {
|
||||
return (CarbonChatUser) this.carbonChat.userService().wrap(this.uuid);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean spying() {
|
||||
return this.spying;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void spying(final boolean spying, final boolean fromRemote) {
|
||||
this.spying = spying;
|
||||
|
||||
if (!fromRemote) {
|
||||
this.carbonChat.messageManager().sendMessage("spying-channel", this.uuid, byteArray -> {
|
||||
byteArray.writeUTF(this.channel);
|
||||
byteArray.writeBoolean(spying);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean ignored() {
|
||||
return this.ignored;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void ignoring(final boolean ignored, final boolean fromRemote) {
|
||||
this.ignored = ignored;
|
||||
|
||||
if (!fromRemote) {
|
||||
this.carbonChat.messageManager().sendMessage("ignoring-channel", this.uuid, byteArray -> {
|
||||
byteArray.writeUTF(this.channel);
|
||||
byteArray.writeBoolean(ignored);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
@Nullable
|
||||
public TextColor color() {
|
||||
if (this.color == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return TextColor.fromHexString(this.color);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void color(@Nullable final TextColor color, final boolean fromRemote) {
|
||||
if (color == null) {
|
||||
this.color = null;
|
||||
} else {
|
||||
this.color = color.asHexString();
|
||||
}
|
||||
|
||||
if (!fromRemote) {
|
||||
this.carbonChat.messageManager().sendMessage("channel-color", this.uuid, byteArray -> {
|
||||
byteArray.writeUTF(color.asHexString());
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
package net.draycia.carbon.util;
|
||||
|
||||
import net.draycia.carbon.api.channels.ChatChannel;
|
||||
import net.draycia.carbon.api.users.ChatUser;
|
||||
import me.clip.placeholderapi.expansion.PlaceholderExpansion;
|
||||
import net.draycia.carbon.CarbonChat;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.checkerframework.checker.nullness.qual.NonNull;
|
||||
import org.checkerframework.checker.nullness.qual.Nullable;
|
||||
|
||||
public class CarbonPlaceholders extends PlaceholderExpansion {
|
||||
|
||||
@NonNull
|
||||
private final CarbonChat carbonChat;
|
||||
|
||||
public CarbonPlaceholders(@NonNull final CarbonChat carbonChat) {
|
||||
this.carbonChat = carbonChat;
|
||||
}
|
||||
|
||||
@Override
|
||||
@NonNull
|
||||
public String getIdentifier() {
|
||||
return "carbonchat";
|
||||
}
|
||||
|
||||
@Override
|
||||
@NonNull
|
||||
public String getAuthor() {
|
||||
return "Draycia (Vicarious#0001)";
|
||||
}
|
||||
|
||||
@Override
|
||||
@NonNull
|
||||
public String getVersion() {
|
||||
return "1.0.0";
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean persist() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
@Nullable
|
||||
public String onPlaceholderRequest(@NonNull final Player player, @NonNull final String identifier) {
|
||||
final String key = identifier.toLowerCase();
|
||||
|
||||
if (key.startsWith("can_use_")) {
|
||||
final String value = key.replace("can_use_", "");
|
||||
|
||||
final ChatChannel channel = this.carbonChat.channelManager().registry().channel(value);
|
||||
|
||||
if (channel == null) {
|
||||
return "false";
|
||||
}
|
||||
|
||||
final ChatUser user = this.carbonChat.userService().wrap(player);
|
||||
|
||||
return String.valueOf(channel.canPlayerUse(user));
|
||||
} else if (key.startsWith("can_see_")) {
|
||||
final String value = key.replace("can_see_", "");
|
||||
|
||||
final ChatChannel channel = this.carbonChat.channelManager().registry().channel(value);
|
||||
|
||||
if (channel == null) {
|
||||
return "false";
|
||||
}
|
||||
|
||||
final ChatUser user = this.carbonChat.userService().wrap(player);
|
||||
|
||||
return String.valueOf(channel.canPlayerSee(user, true));
|
||||
} else if (key.startsWith("ignoring_channel_")) {
|
||||
final String value = key.replace("ignoring_channel_", "");
|
||||
|
||||
final ChatChannel channel = this.carbonChat.channelManager().registry().channel(value);
|
||||
|
||||
if (channel == null) {
|
||||
return "false";
|
||||
}
|
||||
|
||||
final ChatUser user = this.carbonChat.userService().wrap(player);
|
||||
|
||||
return String.valueOf(user.channelSettings(channel).ignored());
|
||||
} else if (key.startsWith("selected_channel")) {
|
||||
final ChatChannel channel = this.carbonChat.userService().wrap(player).selectedChannel();
|
||||
|
||||
return channel == null ? this.carbonChat.channelManager().defaultChannel().name() : channel.name();
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,215 @@
|
||||
/*
|
||||
Simple channel based chat plugin for Spigot
|
||||
Copyright (C) 2020 Alexander Söderberg
|
||||
Copyright (C) 2020 Josua Parks (Draycia)
|
||||
|
||||
Modifications made to work with Kyori/Adventure
|
||||
|
||||
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.util;
|
||||
|
||||
import dev.jorel.commandapi.arguments.Argument;
|
||||
import dev.jorel.commandapi.arguments.CustomArgument;
|
||||
import me.clip.placeholderapi.PlaceholderAPI;
|
||||
import net.draycia.carbon.CarbonChat;
|
||||
import net.draycia.carbon.api.channels.ChatChannel;
|
||||
import net.draycia.carbon.api.users.ChatUser;
|
||||
import net.kyori.adventure.text.Component;
|
||||
import net.kyori.adventure.text.format.NamedTextColor;
|
||||
import net.kyori.adventure.text.format.TextColor;
|
||||
import net.kyori.adventure.text.serializer.bungeecord.BungeeCordComponentSerializer;
|
||||
import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer;
|
||||
import net.md_5.bungee.api.ChatColor;
|
||||
import net.md_5.bungee.api.chat.ComponentBuilder;
|
||||
import net.md_5.bungee.api.chat.HoverEvent;
|
||||
import net.md_5.bungee.api.chat.TextComponent;
|
||||
import net.md_5.bungee.api.chat.TranslatableComponent;
|
||||
import net.md_5.bungee.api.chat.hover.content.Content;
|
||||
import org.apache.commons.lang.NotImplementedException;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
import org.checkerframework.checker.nullness.qual.NonNull;
|
||||
import org.checkerframework.checker.nullness.qual.Nullable;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public final class CarbonUtils {
|
||||
|
||||
private static final @NonNull String @NonNull [] colors;
|
||||
|
||||
private CarbonUtils() {
|
||||
|
||||
}
|
||||
|
||||
static {
|
||||
final List<String> colorList = new ArrayList<>();
|
||||
|
||||
for (final NamedTextColor color : NamedTextColor.values()) {
|
||||
colorList.add(color.toString());
|
||||
}
|
||||
|
||||
colors = colorList.toArray(new String[0]);
|
||||
}
|
||||
|
||||
@NonNull
|
||||
public static Component createComponent(@NonNull final Player player) {
|
||||
if (!FunctionalityConstants.HAS_HOVER_EVENT_METHOD) {
|
||||
return net.kyori.adventure.text.TextComponent.empty();
|
||||
}
|
||||
|
||||
final ItemStack itemStack = player.getInventory().getItemInMainHand();
|
||||
|
||||
if (itemStack.getType().isAir()) {
|
||||
return net.kyori.adventure.text.TextComponent.empty();
|
||||
}
|
||||
|
||||
final Content content = Bukkit.getItemFactory().hoverContentOf(itemStack);
|
||||
final HoverEvent event = new HoverEvent(HoverEvent.Action.SHOW_ITEM, content);
|
||||
|
||||
final ComponentBuilder component = new ComponentBuilder();
|
||||
component.event(event); // Let this be inherited by all coming components.
|
||||
component.color(ChatColor.WHITE).append("[");
|
||||
|
||||
if (itemStack.getItemMeta().hasDisplayName()) {
|
||||
component.append(TextComponent.fromLegacyText(itemStack.getItemMeta().getDisplayName()));
|
||||
} else {
|
||||
// As of 1.13, Material is 1:1 with MC's names
|
||||
final String prefix = itemStack.getType().isBlock() ? "block" : "item";
|
||||
final String name = prefix + ".minecraft." + itemStack.getType().name().toLowerCase();
|
||||
|
||||
component.append(new TranslatableComponent(name));
|
||||
}
|
||||
|
||||
component.color(ChatColor.WHITE).append("]");
|
||||
|
||||
return BungeeCordComponentSerializer.get().deserialize(component.create());
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public static TextColor parseColor(@Nullable final String input) {
|
||||
return parseColor(null, input);
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public static TextColor parseColor(@Nullable final ChatUser user, @Nullable String input) {
|
||||
if (input == null) {
|
||||
input = "white";
|
||||
}
|
||||
|
||||
if (user != null && user.online()) {
|
||||
input = PlaceholderAPI.setPlaceholders(user.player(), input);
|
||||
}
|
||||
|
||||
for (final NamedTextColor namedColor : NamedTextColor.values()) {
|
||||
if (namedColor.toString().equalsIgnoreCase(input)) {
|
||||
return namedColor;
|
||||
}
|
||||
}
|
||||
|
||||
if (input.contains("&") || input.contains("§")) {
|
||||
input = input.replace("&", "§");
|
||||
|
||||
return LegacyComponentSerializer.legacySection().deserialize(input).color();
|
||||
}
|
||||
|
||||
return TextColor.fromCSSHexString(input);
|
||||
}
|
||||
|
||||
@NonNull
|
||||
public static Argument onlineChatUserArgument() {
|
||||
return new CustomArgument<>(input -> {
|
||||
final CarbonChat carbonChat = (CarbonChat) Bukkit.getPluginManager().getPlugin("CarbonChat");
|
||||
|
||||
final Player player = Bukkit.getPlayer(input);
|
||||
|
||||
if (player == null) {
|
||||
throw new CustomArgument.CustomArgumentException("Invalid player for input (" + input + ")");
|
||||
}
|
||||
|
||||
return carbonChat.userService().wrap(player);
|
||||
// }).overrideSuggestions((sender, args) -> {
|
||||
// ArrayList<String> players = new ArrayList<>();
|
||||
//
|
||||
// for (Player player : Bukkit.getOnlinePlayers()) {
|
||||
// players.add(player.getName());
|
||||
// }
|
||||
//
|
||||
// return players.toArray(new String[0]);
|
||||
});
|
||||
}
|
||||
|
||||
@NonNull
|
||||
public static Argument chatUserArgument() {
|
||||
return new CustomArgument<>(input -> {
|
||||
final CarbonChat carbonChat = (CarbonChat) Bukkit.getPluginManager().getPlugin("CarbonChat");
|
||||
|
||||
return carbonChat.userService().wrap(input);
|
||||
// }).overrideSuggestions((sender, args) -> {
|
||||
// ArrayList<String> players = new ArrayList<>();
|
||||
//
|
||||
// for (Player player : Bukkit.getOnlinePlayers()) {
|
||||
// players.add(player.getName());
|
||||
// }
|
||||
//
|
||||
// return players.toArray(new String[0]);
|
||||
});
|
||||
}
|
||||
|
||||
@NonNull
|
||||
public static Argument textColorArgument() {
|
||||
return new CustomArgument<>(input -> {
|
||||
final TextColor color = parseColor(input);
|
||||
|
||||
if (color == null) {
|
||||
throw new CustomArgument.CustomArgumentException("Invalid color for input (" + input + ")");
|
||||
}
|
||||
|
||||
return color;
|
||||
}).overrideSuggestions(colors);
|
||||
}
|
||||
|
||||
@NonNull
|
||||
public static Argument channelArgument() {
|
||||
return new CustomArgument<>(input -> {
|
||||
final CarbonChat carbonChat = (CarbonChat) Bukkit.getPluginManager().getPlugin("CarbonChat");
|
||||
|
||||
final ChatChannel channel = carbonChat.channelManager().registry().channel(input);
|
||||
|
||||
if (channel == null) {
|
||||
throw new CustomArgument.CustomArgumentException("Invalid channel for input (" + input + ")");
|
||||
}
|
||||
|
||||
return channel;
|
||||
// }).overrideSuggestions((sender, args) -> {
|
||||
// CarbonChat carbonChat = (CarbonChat) Bukkit.getPluginManager().getPlugin("CarbonChat");
|
||||
//
|
||||
// ArrayList<String> channels = new ArrayList<>();
|
||||
//
|
||||
// for (ChatChannel channel : this.carbonChat.getChannelManager().getRegistry().values()) {
|
||||
// channels.add(channel.getKey());
|
||||
// }
|
||||
//
|
||||
// return channels.toArray(new String[0]);
|
||||
});
|
||||
}
|
||||
|
||||
@NonNull
|
||||
public static Argument usableChannelArgument() {
|
||||
throw new NotImplementedException("Not implemented yet.");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package net.draycia.carbon.util;
|
||||
|
||||
import dev.jorel.commandapi.CommandAPI;
|
||||
import net.draycia.carbon.api.commands.CommandSettings;
|
||||
import org.checkerframework.checker.nullness.qual.NonNull;
|
||||
|
||||
public final class CommandUtils {
|
||||
|
||||
private CommandUtils() {
|
||||
|
||||
}
|
||||
|
||||
public static void handleDuplicateCommands(@NonNull final CommandSettings settings) {
|
||||
CommandAPI.unregister(settings.name());
|
||||
|
||||
for (final String command : settings.aliases()) {
|
||||
CommandAPI.unregister(command);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package net.draycia.carbon.util;
|
||||
|
||||
import org.bukkit.inventory.ItemFactory;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
import org.checkerframework.checker.nullness.qual.NonNull;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
|
||||
@SuppressWarnings("ResultOfMethodCallIgnored") // This is a common pattern in this class.
|
||||
public final class FunctionalityConstants {
|
||||
|
||||
public static final boolean HAS_HOVER_EVENT_METHOD = noThrow(() -> ItemFactory.class.getMethod("hoverContentOf", ItemStack.class));
|
||||
public static final boolean HAS_PROXY;
|
||||
|
||||
static {
|
||||
boolean hasProxy = false;
|
||||
|
||||
try {
|
||||
final Class<?> spigotConfig = Class.forName("org.spigotmc.SpigotConfig");
|
||||
final Field bungee = spigotConfig.getField("bungee");
|
||||
hasProxy = bungee.getBoolean(null);
|
||||
} catch (final ClassNotFoundException | NoSuchFieldException | IllegalAccessException ignored) {
|
||||
}
|
||||
|
||||
HAS_PROXY = hasProxy;
|
||||
}
|
||||
|
||||
private FunctionalityConstants() {
|
||||
|
||||
}
|
||||
|
||||
private static boolean noThrow(@NonNull final ThrowingRunnable runnable) {
|
||||
try {
|
||||
runnable.run();
|
||||
return true;
|
||||
} catch (final Exception ex) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@FunctionalInterface
|
||||
private interface ThrowingRunnable {
|
||||
void run() throws Exception;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,735 @@
|
||||
package net.draycia.carbon.util;
|
||||
|
||||
import com.google.gson.JsonArray;
|
||||
import com.google.gson.JsonObject;
|
||||
import com.google.gson.JsonParser;
|
||||
import com.google.gson.JsonPrimitive;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.configuration.file.YamlConfiguration;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.plugin.Plugin;
|
||||
import org.bukkit.plugin.RegisteredServiceProvider;
|
||||
import org.bukkit.plugin.ServicePriority;
|
||||
|
||||
import javax.net.ssl.HttpsURLConnection;
|
||||
import java.io.BufferedReader;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.DataOutputStream;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.lang.reflect.Method;
|
||||
import java.net.URL;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Timer;
|
||||
import java.util.TimerTask;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.Callable;
|
||||
import java.util.logging.Level;
|
||||
import java.util.zip.GZIPOutputStream;
|
||||
|
||||
/**
|
||||
* bStats collects some data for plugin authors.
|
||||
* <p>
|
||||
* Check out https://bStats.org/ to learn more about bStats!
|
||||
*/
|
||||
@SuppressWarnings({"WeakerAccess", "unused"})
|
||||
public class Metrics {
|
||||
|
||||
static {
|
||||
// You can use the property to disable the check in your test environment
|
||||
if (System.getProperty("bstats.relocatecheck") == null || !System.getProperty("bstats.relocatecheck").equals("false")) {
|
||||
// Maven's Relocate is clever and changes strings, too. So we have to use this little "trick" ... :D
|
||||
final String defaultPackage = new String(
|
||||
new byte[]{'o', 'r', 'g', '.', 'b', 's', 't', 'a', 't', 's', '.', 'b', 'u', 'k', 'k', 'i', 't'});
|
||||
final String examplePackage = new String(new byte[]{'y', 'o', 'u', 'r', '.', 'p', 'a', 'c', 'k', 'a', 'g', 'e'});
|
||||
// We want to make sure nobody just copy & pastes the example and use the wrong package names
|
||||
if (Metrics.class.getPackage().getName().equals(defaultPackage) || Metrics.class.getPackage().getName().equals(examplePackage)) {
|
||||
throw new IllegalStateException("bStats Metrics class has not been relocated correctly!");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The version of this bStats class
|
||||
public static final int B_STATS_VERSION = 1;
|
||||
|
||||
// The url to which the data is sent
|
||||
private static final String URL = "https://bStats.org/submitData/bukkit";
|
||||
|
||||
// Is bStats enabled on this server?
|
||||
private boolean enabled;
|
||||
|
||||
// Should failed requests be logged?
|
||||
private static boolean logFailedRequests;
|
||||
|
||||
// Should the sent data be logged?
|
||||
private static boolean logSentData;
|
||||
|
||||
// Should the response text be logged?
|
||||
private static boolean logResponseStatusText;
|
||||
|
||||
// The uuid of the server
|
||||
private static String serverUUID;
|
||||
|
||||
// The plugin
|
||||
private final Plugin plugin;
|
||||
|
||||
// The plugin id
|
||||
private final int pluginId;
|
||||
|
||||
// A list with all custom charts
|
||||
private final List<CustomChart> charts = new ArrayList<>();
|
||||
|
||||
/**
|
||||
* Class constructor.
|
||||
*
|
||||
* @param plugin The plugin which stats should be submitted.
|
||||
* @param pluginId The id of the plugin.
|
||||
* It can be found at <a href="https://bstats.org/what-is-my-plugin-id">What is my plugin id?</a>
|
||||
*/
|
||||
public Metrics(final Plugin plugin, final int pluginId) {
|
||||
if (plugin == null) {
|
||||
throw new IllegalArgumentException("Plugin cannot be null!");
|
||||
}
|
||||
this.plugin = plugin;
|
||||
this.pluginId = pluginId;
|
||||
|
||||
// Get the config file
|
||||
final File bStatsFolder = new File(plugin.getDataFolder().getParentFile(), "bStats");
|
||||
final File configFile = new File(bStatsFolder, "config.yml");
|
||||
final YamlConfiguration config = YamlConfiguration.loadConfiguration(configFile);
|
||||
|
||||
// Check if the config file exists
|
||||
if (!config.isSet("serverUuid")) {
|
||||
|
||||
// Add default values
|
||||
config.addDefault("enabled", true);
|
||||
// Every server gets it's unique random id.
|
||||
config.addDefault("serverUuid", UUID.randomUUID().toString());
|
||||
// Should failed request be logged?
|
||||
config.addDefault("logFailedRequests", false);
|
||||
// Should the sent data be logged?
|
||||
config.addDefault("logSentData", false);
|
||||
// Should the response text be logged?
|
||||
config.addDefault("logResponseStatusText", false);
|
||||
|
||||
// Inform the server owners about bStats
|
||||
config.options().header(
|
||||
"bStats collects some data for plugin authors like how many servers are using their plugins.\n" +
|
||||
"To honor their work, you should not disable it.\n" +
|
||||
"This has nearly no effect on the server performance!\n" +
|
||||
"Check out https://bStats.org/ to learn more :)"
|
||||
).copyDefaults(true);
|
||||
try {
|
||||
config.save(configFile);
|
||||
} catch (final IOException ignored) {
|
||||
}
|
||||
}
|
||||
|
||||
// Load the data
|
||||
this.enabled = config.getBoolean("enabled", true);
|
||||
serverUUID = config.getString("serverUuid");
|
||||
logFailedRequests = config.getBoolean("logFailedRequests", false);
|
||||
logSentData = config.getBoolean("logSentData", false);
|
||||
logResponseStatusText = config.getBoolean("logResponseStatusText", false);
|
||||
|
||||
if (this.enabled) {
|
||||
boolean found = false;
|
||||
// Search for all other bStats Metrics classes to see if we are the first one
|
||||
for (final Class<?> service : Bukkit.getServicesManager().getKnownServices()) {
|
||||
try {
|
||||
service.getField("B_STATS_VERSION"); // Our identifier :)
|
||||
found = true; // We aren't the first
|
||||
break;
|
||||
} catch (final NoSuchFieldException ignored) {
|
||||
}
|
||||
}
|
||||
// Register our service
|
||||
Bukkit.getServicesManager().register(Metrics.class, this, plugin, ServicePriority.Normal);
|
||||
if (!found) {
|
||||
// We are the first!
|
||||
this.startSubmitting();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if bStats is enabled.
|
||||
*
|
||||
* @return Whether bStats is enabled or not.
|
||||
*/
|
||||
public boolean isEnabled() {
|
||||
return this.enabled;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a custom chart.
|
||||
*
|
||||
* @param chart The chart to add.
|
||||
*/
|
||||
public void addCustomChart(final CustomChart chart) {
|
||||
if (chart == null) {
|
||||
throw new IllegalArgumentException("Chart cannot be null!");
|
||||
}
|
||||
this.charts.add(chart);
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts the Scheduler which submits our data every 30 minutes.
|
||||
*/
|
||||
private void startSubmitting() {
|
||||
final Timer timer = new Timer(true); // We use a timer cause the Bukkit scheduler is affected by server lags
|
||||
timer.scheduleAtFixedRate(new TimerTask() {
|
||||
@Override
|
||||
public void run() {
|
||||
if (!Metrics.this.plugin.isEnabled()) { // Plugin was disabled
|
||||
timer.cancel();
|
||||
return;
|
||||
}
|
||||
// Nevertheless we want our code to run in the Bukkit main thread, so we have to use the Bukkit scheduler
|
||||
// Don't be afraid! The connection to the bStats server is still async, only the stats collection is sync ;)
|
||||
Bukkit.getScheduler().runTask(Metrics.this.plugin, () -> Metrics.this.submitData());
|
||||
}
|
||||
}, 1000 * 60 * 5, 1000 * 60 * 30);
|
||||
// Submit the data every 30 minutes, first time after 5 minutes to give other plugins enough time to start
|
||||
// WARNING: Changing the frequency has no effect but your plugin WILL be blocked/deleted!
|
||||
// WARNING: Just don't do it!
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the plugin specific data.
|
||||
* This method is called using Reflection.
|
||||
*
|
||||
* @return The plugin specific data.
|
||||
*/
|
||||
public JsonObject getPluginData() {
|
||||
final JsonObject data = new JsonObject();
|
||||
|
||||
final String pluginName = this.plugin.getDescription().getName();
|
||||
final String pluginVersion = this.plugin.getDescription().getVersion();
|
||||
|
||||
data.addProperty("pluginName", pluginName); // Append the name of the plugin
|
||||
data.addProperty("id", this.pluginId); // Append the id of the plugin
|
||||
data.addProperty("pluginVersion", pluginVersion); // Append the version of the plugin
|
||||
final JsonArray customCharts = new JsonArray();
|
||||
for (final CustomChart customChart : this.charts) {
|
||||
// Add the data of the custom charts
|
||||
final JsonObject chart = customChart.getRequestJsonObject();
|
||||
if (chart == null) { // If the chart is null, we skip it
|
||||
continue;
|
||||
}
|
||||
customCharts.add(chart);
|
||||
}
|
||||
data.add("customCharts", customCharts);
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the server specific data.
|
||||
*
|
||||
* @return The server specific data.
|
||||
*/
|
||||
private JsonObject getServerData() {
|
||||
// Minecraft specific data
|
||||
int playerAmount;
|
||||
try {
|
||||
// Around MC 1.8 the return type was changed to a collection from an array,
|
||||
// This fixes java.lang.NoSuchMethodError: org.bukkit.Bukkit.getOnlinePlayers()Ljava/util/Collection;
|
||||
final Method onlinePlayersMethod = Class.forName("org.bukkit.Server").getMethod("getOnlinePlayers");
|
||||
playerAmount = onlinePlayersMethod.getReturnType().equals(Collection.class)
|
||||
? ((Collection<?>) onlinePlayersMethod.invoke(Bukkit.getServer())).size()
|
||||
: ((Player[]) onlinePlayersMethod.invoke(Bukkit.getServer())).length;
|
||||
} catch (final Exception e) {
|
||||
playerAmount = Bukkit.getOnlinePlayers().size(); // Just use the new method if the Reflection failed
|
||||
}
|
||||
final int onlineMode = Bukkit.getOnlineMode() ? 1 : 0;
|
||||
final String bukkitVersion = Bukkit.getVersion();
|
||||
final String bukkitName = Bukkit.getName();
|
||||
|
||||
// OS/Java specific data
|
||||
final String javaVersion = System.getProperty("java.version");
|
||||
final String osName = System.getProperty("os.name");
|
||||
final String osArch = System.getProperty("os.arch");
|
||||
final String osVersion = System.getProperty("os.version");
|
||||
final int coreCount = Runtime.getRuntime().availableProcessors();
|
||||
|
||||
final JsonObject data = new JsonObject();
|
||||
|
||||
data.addProperty("serverUUID", serverUUID);
|
||||
|
||||
data.addProperty("playerAmount", playerAmount);
|
||||
data.addProperty("onlineMode", onlineMode);
|
||||
data.addProperty("bukkitVersion", bukkitVersion);
|
||||
data.addProperty("bukkitName", bukkitName);
|
||||
|
||||
data.addProperty("javaVersion", javaVersion);
|
||||
data.addProperty("osName", osName);
|
||||
data.addProperty("osArch", osArch);
|
||||
data.addProperty("osVersion", osVersion);
|
||||
data.addProperty("coreCount", coreCount);
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Collects the data and sends it afterwards.
|
||||
*/
|
||||
private void submitData() {
|
||||
final JsonObject data = this.getServerData();
|
||||
|
||||
final JsonArray pluginData = new JsonArray();
|
||||
// Search for all other bStats Metrics classes to get their plugin data
|
||||
for (final Class<?> service : Bukkit.getServicesManager().getKnownServices()) {
|
||||
try {
|
||||
service.getField("B_STATS_VERSION"); // Our identifier :)
|
||||
|
||||
for (final RegisteredServiceProvider<?> provider : Bukkit.getServicesManager().getRegistrations(service)) {
|
||||
try {
|
||||
final Object plugin = provider.getService().getMethod("getPluginData").invoke(provider.getProvider());
|
||||
if (plugin instanceof JsonObject) {
|
||||
pluginData.add((JsonObject) plugin);
|
||||
} else { // old bstats version compatibility
|
||||
try {
|
||||
final Class<?> jsonObjectJsonSimple = Class.forName("org.json.simple.JSONObject");
|
||||
if (plugin.getClass().isAssignableFrom(jsonObjectJsonSimple)) {
|
||||
final Method jsonStringGetter = jsonObjectJsonSimple.getDeclaredMethod("toJSONString");
|
||||
jsonStringGetter.setAccessible(true);
|
||||
final String jsonString = (String) jsonStringGetter.invoke(plugin);
|
||||
final JsonObject object = new JsonParser().parse(jsonString).getAsJsonObject();
|
||||
pluginData.add(object);
|
||||
}
|
||||
} catch (final ClassNotFoundException e) {
|
||||
// minecraft version 1.14+
|
||||
if (logFailedRequests) {
|
||||
this.plugin.getLogger().log(Level.SEVERE, "Encountered unexpected exception", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (final NullPointerException | NoSuchMethodException | IllegalAccessException | InvocationTargetException ignored) {
|
||||
}
|
||||
}
|
||||
} catch (final NoSuchFieldException ignored) {
|
||||
}
|
||||
}
|
||||
|
||||
data.add("plugins", pluginData);
|
||||
|
||||
// Create a new thread for the connection to the bStats server
|
||||
new Thread(() -> {
|
||||
try {
|
||||
// Send the data
|
||||
sendData(this.plugin, data);
|
||||
} catch (final Exception e) {
|
||||
// Something went wrong! :(
|
||||
if (logFailedRequests) {
|
||||
this.plugin.getLogger().log(Level.WARNING, "Could not submit plugin stats of " + this.plugin.getName(), e);
|
||||
}
|
||||
}
|
||||
}).start();
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends the data to the bStats server.
|
||||
*
|
||||
* @param plugin Any plugin. It's just used to get a logger instance.
|
||||
* @param data The data to send.
|
||||
* @throws Exception If the request failed.
|
||||
*/
|
||||
private static void sendData(final Plugin plugin, final JsonObject data) throws Exception {
|
||||
if (data == null) {
|
||||
throw new IllegalArgumentException("Data cannot be null!");
|
||||
}
|
||||
if (Bukkit.isPrimaryThread()) {
|
||||
throw new IllegalAccessException("This method must not be called from the main thread!");
|
||||
}
|
||||
if (logSentData) {
|
||||
plugin.getLogger().info("Sending data to bStats: " + data);
|
||||
}
|
||||
final HttpsURLConnection connection = (HttpsURLConnection) new URL(URL).openConnection();
|
||||
|
||||
// Compress the data to save bandwidth
|
||||
final byte[] compressedData = compress(data.toString());
|
||||
|
||||
// Add headers
|
||||
connection.setRequestMethod("POST");
|
||||
connection.addRequestProperty("Accept", "application/json");
|
||||
connection.addRequestProperty("Connection", "close");
|
||||
connection.addRequestProperty("Content-Encoding", "gzip"); // We gzip our request
|
||||
connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length));
|
||||
connection.setRequestProperty("Content-Type", "application/json"); // We send our data in JSON format
|
||||
connection.setRequestProperty("User-Agent", "MC-Server/" + B_STATS_VERSION);
|
||||
|
||||
// Send data
|
||||
connection.setDoOutput(true);
|
||||
try (final DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) {
|
||||
outputStream.write(compressedData);
|
||||
}
|
||||
|
||||
final StringBuilder builder = new StringBuilder();
|
||||
try (final BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
|
||||
String line;
|
||||
while ((line = bufferedReader.readLine()) != null) {
|
||||
builder.append(line);
|
||||
}
|
||||
}
|
||||
|
||||
if (logResponseStatusText) {
|
||||
plugin.getLogger().info("Sent data to bStats and received response: " + builder);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gzips the given String.
|
||||
*
|
||||
* @param str The string to gzip.
|
||||
* @return The gzipped String.
|
||||
* @throws IOException If the compression failed.
|
||||
*/
|
||||
private static byte[] compress(final String str) throws IOException {
|
||||
if (str == null) {
|
||||
return null;
|
||||
}
|
||||
final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
|
||||
try (final GZIPOutputStream gzip = new GZIPOutputStream(outputStream)) {
|
||||
gzip.write(str.getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
return outputStream.toByteArray();
|
||||
}
|
||||
|
||||
/**
|
||||
* Represents a custom chart.
|
||||
*/
|
||||
public static abstract class CustomChart {
|
||||
|
||||
// The id of the chart
|
||||
final String chartId;
|
||||
|
||||
/**
|
||||
* Class constructor.
|
||||
*
|
||||
* @param chartId The id of the chart.
|
||||
*/
|
||||
CustomChart(final String chartId) {
|
||||
if (chartId == null || chartId.isEmpty()) {
|
||||
throw new IllegalArgumentException("ChartId cannot be null or empty!");
|
||||
}
|
||||
this.chartId = chartId;
|
||||
}
|
||||
|
||||
private JsonObject getRequestJsonObject() {
|
||||
final JsonObject chart = new JsonObject();
|
||||
chart.addProperty("chartId", this.chartId);
|
||||
try {
|
||||
final JsonObject data = this.getChartData();
|
||||
if (data == null) {
|
||||
// If the data is null we don't send the chart.
|
||||
return null;
|
||||
}
|
||||
chart.add("data", data);
|
||||
} catch (final Throwable t) {
|
||||
if (logFailedRequests) {
|
||||
Bukkit.getLogger().log(Level.WARNING, "Failed to get data for custom chart with id " + this.chartId, t);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
return chart;
|
||||
}
|
||||
|
||||
protected abstract JsonObject getChartData() throws Exception;
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Represents a custom simple pie.
|
||||
*/
|
||||
public static class SimplePie extends CustomChart {
|
||||
|
||||
private final Callable<String> callable;
|
||||
|
||||
/**
|
||||
* Class constructor.
|
||||
*
|
||||
* @param chartId The id of the chart.
|
||||
* @param callable The callable which is used to request the chart data.
|
||||
*/
|
||||
public SimplePie(final String chartId, final Callable<String> callable) {
|
||||
super(chartId);
|
||||
this.callable = callable;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected JsonObject getChartData() throws Exception {
|
||||
final JsonObject data = new JsonObject();
|
||||
final String value = this.callable.call();
|
||||
if (value == null || value.isEmpty()) {
|
||||
// Null = skip the chart
|
||||
return null;
|
||||
}
|
||||
data.addProperty("value", value);
|
||||
return data;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Represents a custom advanced pie.
|
||||
*/
|
||||
public static class AdvancedPie extends CustomChart {
|
||||
|
||||
private final Callable<Map<String, Integer>> callable;
|
||||
|
||||
/**
|
||||
* Class constructor.
|
||||
*
|
||||
* @param chartId The id of the chart.
|
||||
* @param callable The callable which is used to request the chart data.
|
||||
*/
|
||||
public AdvancedPie(final String chartId, final Callable<Map<String, Integer>> callable) {
|
||||
super(chartId);
|
||||
this.callable = callable;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected JsonObject getChartData() throws Exception {
|
||||
final JsonObject data = new JsonObject();
|
||||
final JsonObject values = new JsonObject();
|
||||
final Map<String, Integer> map = this.callable.call();
|
||||
if (map == null || map.isEmpty()) {
|
||||
// Null = skip the chart
|
||||
return null;
|
||||
}
|
||||
boolean allSkipped = true;
|
||||
for (final Map.Entry<String, Integer> entry : map.entrySet()) {
|
||||
if (entry.getValue() == 0) {
|
||||
continue; // Skip this invalid
|
||||
}
|
||||
allSkipped = false;
|
||||
values.addProperty(entry.getKey(), entry.getValue());
|
||||
}
|
||||
if (allSkipped) {
|
||||
// Null = skip the chart
|
||||
return null;
|
||||
}
|
||||
data.add("values", values);
|
||||
return data;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Represents a custom drilldown pie.
|
||||
*/
|
||||
public static class DrilldownPie extends CustomChart {
|
||||
|
||||
private final Callable<Map<String, Map<String, Integer>>> callable;
|
||||
|
||||
/**
|
||||
* Class constructor.
|
||||
*
|
||||
* @param chartId The id of the chart.
|
||||
* @param callable The callable which is used to request the chart data.
|
||||
*/
|
||||
public DrilldownPie(final String chartId, final Callable<Map<String, Map<String, Integer>>> callable) {
|
||||
super(chartId);
|
||||
this.callable = callable;
|
||||
}
|
||||
|
||||
@Override
|
||||
public JsonObject getChartData() throws Exception {
|
||||
final JsonObject data = new JsonObject();
|
||||
final JsonObject values = new JsonObject();
|
||||
final Map<String, Map<String, Integer>> map = this.callable.call();
|
||||
if (map == null || map.isEmpty()) {
|
||||
// Null = skip the chart
|
||||
return null;
|
||||
}
|
||||
boolean reallyAllSkipped = true;
|
||||
for (final Map.Entry<String, Map<String, Integer>> entryValues : map.entrySet()) {
|
||||
final JsonObject value = new JsonObject();
|
||||
boolean allSkipped = true;
|
||||
for (final Map.Entry<String, Integer> valueEntry : map.get(entryValues.getKey()).entrySet()) {
|
||||
value.addProperty(valueEntry.getKey(), valueEntry.getValue());
|
||||
allSkipped = false;
|
||||
}
|
||||
if (!allSkipped) {
|
||||
reallyAllSkipped = false;
|
||||
values.add(entryValues.getKey(), value);
|
||||
}
|
||||
}
|
||||
if (reallyAllSkipped) {
|
||||
// Null = skip the chart
|
||||
return null;
|
||||
}
|
||||
data.add("values", values);
|
||||
return data;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Represents a custom single line chart.
|
||||
*/
|
||||
public static class SingleLineChart extends CustomChart {
|
||||
|
||||
private final Callable<Integer> callable;
|
||||
|
||||
/**
|
||||
* Class constructor.
|
||||
*
|
||||
* @param chartId The id of the chart.
|
||||
* @param callable The callable which is used to request the chart data.
|
||||
*/
|
||||
public SingleLineChart(final String chartId, final Callable<Integer> callable) {
|
||||
super(chartId);
|
||||
this.callable = callable;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected JsonObject getChartData() throws Exception {
|
||||
final JsonObject data = new JsonObject();
|
||||
final int value = this.callable.call();
|
||||
if (value == 0) {
|
||||
// Null = skip the chart
|
||||
return null;
|
||||
}
|
||||
data.addProperty("value", value);
|
||||
return data;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Represents a custom multi line chart.
|
||||
*/
|
||||
public static class MultiLineChart extends CustomChart {
|
||||
|
||||
private final Callable<Map<String, Integer>> callable;
|
||||
|
||||
/**
|
||||
* Class constructor.
|
||||
*
|
||||
* @param chartId The id of the chart.
|
||||
* @param callable The callable which is used to request the chart data.
|
||||
*/
|
||||
public MultiLineChart(final String chartId, final Callable<Map<String, Integer>> callable) {
|
||||
super(chartId);
|
||||
this.callable = callable;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected JsonObject getChartData() throws Exception {
|
||||
final JsonObject data = new JsonObject();
|
||||
final JsonObject values = new JsonObject();
|
||||
final Map<String, Integer> map = this.callable.call();
|
||||
if (map == null || map.isEmpty()) {
|
||||
// Null = skip the chart
|
||||
return null;
|
||||
}
|
||||
boolean allSkipped = true;
|
||||
for (final Map.Entry<String, Integer> entry : map.entrySet()) {
|
||||
if (entry.getValue() == 0) {
|
||||
continue; // Skip this invalid
|
||||
}
|
||||
allSkipped = false;
|
||||
values.addProperty(entry.getKey(), entry.getValue());
|
||||
}
|
||||
if (allSkipped) {
|
||||
// Null = skip the chart
|
||||
return null;
|
||||
}
|
||||
data.add("values", values);
|
||||
return data;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Represents a custom simple bar chart.
|
||||
*/
|
||||
public static class SimpleBarChart extends CustomChart {
|
||||
|
||||
private final Callable<Map<String, Integer>> callable;
|
||||
|
||||
/**
|
||||
* Class constructor.
|
||||
*
|
||||
* @param chartId The id of the chart.
|
||||
* @param callable The callable which is used to request the chart data.
|
||||
*/
|
||||
public SimpleBarChart(final String chartId, final Callable<Map<String, Integer>> callable) {
|
||||
super(chartId);
|
||||
this.callable = callable;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected JsonObject getChartData() throws Exception {
|
||||
final JsonObject data = new JsonObject();
|
||||
final JsonObject values = new JsonObject();
|
||||
final Map<String, Integer> map = this.callable.call();
|
||||
if (map == null || map.isEmpty()) {
|
||||
// Null = skip the chart
|
||||
return null;
|
||||
}
|
||||
for (final Map.Entry<String, Integer> entry : map.entrySet()) {
|
||||
final JsonArray categoryValues = new JsonArray();
|
||||
categoryValues.add(new JsonPrimitive(entry.getValue()));
|
||||
values.add(entry.getKey(), categoryValues);
|
||||
}
|
||||
data.add("values", values);
|
||||
return data;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Represents a custom advanced bar chart.
|
||||
*/
|
||||
public static class AdvancedBarChart extends CustomChart {
|
||||
|
||||
private final Callable<Map<String, int[]>> callable;
|
||||
|
||||
/**
|
||||
* Class constructor.
|
||||
*
|
||||
* @param chartId The id of the chart.
|
||||
* @param callable The callable which is used to request the chart data.
|
||||
*/
|
||||
public AdvancedBarChart(final String chartId, final Callable<Map<String, int[]>> callable) {
|
||||
super(chartId);
|
||||
this.callable = callable;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected JsonObject getChartData() throws Exception {
|
||||
final JsonObject data = new JsonObject();
|
||||
final JsonObject values = new JsonObject();
|
||||
final Map<String, int[]> map = this.callable.call();
|
||||
if (map == null || map.isEmpty()) {
|
||||
// Null = skip the chart
|
||||
return null;
|
||||
}
|
||||
boolean allSkipped = true;
|
||||
for (final Map.Entry<String, int[]> entry : map.entrySet()) {
|
||||
if (entry.getValue().length == 0) {
|
||||
continue; // Skip this invalid
|
||||
}
|
||||
allSkipped = false;
|
||||
final JsonArray categoryValues = new JsonArray();
|
||||
for (final int categoryValue : entry.getValue()) {
|
||||
categoryValues.add(new JsonPrimitive(categoryValue));
|
||||
}
|
||||
values.add(entry.getKey(), categoryValues);
|
||||
}
|
||||
if (allSkipped) {
|
||||
// Null = skip the chart
|
||||
return null;
|
||||
}
|
||||
data.add("values", values);
|
||||
return data;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package net.draycia.carbon.util;
|
||||
|
||||
import io.lettuce.core.pubsub.RedisPubSubListener;
|
||||
import org.checkerframework.checker.nullness.qual.NonNull;
|
||||
|
||||
@FunctionalInterface
|
||||
public interface RedisListener extends RedisPubSubListener<String, String> {
|
||||
|
||||
@Override
|
||||
void message(@NonNull String channel, @NonNull String message);
|
||||
|
||||
@Override
|
||||
default void message(@NonNull final String pattern, @NonNull final String channel, @NonNull final String message) {
|
||||
}
|
||||
|
||||
@Override
|
||||
default void subscribed(@NonNull final String channel, final long count) {
|
||||
}
|
||||
|
||||
@Override
|
||||
default void psubscribed(@NonNull final String pattern, final long count) {
|
||||
}
|
||||
|
||||
@Override
|
||||
default void unsubscribed(@NonNull final String channel, final long count) {
|
||||
}
|
||||
|
||||
@Override
|
||||
default void punsubscribed(@NonNull final String pattern, final long count) {
|
||||
}
|
||||
|
||||
}
|
||||
Reference in new issue
Block a user