Rename bukkit plugin to CarbonChat

Old name was CarbonChat-Bukkit, made command namespace pretty weird.
This commit is contained in:
Draycia committed 2020-10-16 22:11:50 -07:00
1 parent 483144abb5
commit b0ae8a806b
20 files changed
+43 -43

No files matched your search

@@ -0,0 +1,425 @@
package net.draycia.carbon.bukkit;
import cloud.commandframework.CommandManager;
import cloud.commandframework.execution.CommandExecutionCoordinator;
import cloud.commandframework.paper.PaperCommandManager;
import net.draycia.carbon.bukkit.listeners.events.BukkitChatListener;
import net.draycia.carbon.bukkit.listeners.events.ItemLinkHandler;
import net.draycia.carbon.bukkit.messaging.BungeeMessageService;
import net.draycia.carbon.bukkit.users.BukkitConsoleUser;
import net.draycia.carbon.bukkit.users.BukkitPlayerUser;
import net.draycia.carbon.bukkit.util.CarbonPlaceholders;
import net.draycia.carbon.bukkit.util.FunctionalityConstants;
import net.draycia.carbon.bukkit.util.Metrics;
import net.draycia.carbon.api.CarbonChat;
import net.draycia.carbon.api.CarbonChatProvider;
import net.draycia.carbon.api.config.CarbonTranslations;
import net.draycia.carbon.api.adventure.MessageProcessor;
import net.draycia.carbon.api.channels.ChannelRegistry;
import net.draycia.carbon.api.commands.settings.CommandSettingsRegistry;
import net.draycia.carbon.api.config.CarbonSettings;
import net.draycia.carbon.api.config.ChannelSettings;
import net.draycia.carbon.api.config.MessagingType;
import net.draycia.carbon.api.config.ModerationSettings;
import net.draycia.carbon.api.config.StorageType;
import net.draycia.carbon.api.messaging.MessageService;
import net.draycia.carbon.api.users.CarbonUser;
import net.draycia.carbon.api.users.PlayerUser;
import net.draycia.carbon.api.adventure.FormatType;
import net.draycia.carbon.common.channels.ChannelManager;
import net.draycia.carbon.common.config.KeySerializer;
import net.draycia.carbon.common.config.SoundSerializer;
import net.draycia.carbon.common.messaging.EmptyMessageService;
import net.draycia.carbon.api.config.SQLCredentials;
import net.draycia.carbon.common.messaging.RedisMessageService;
import net.draycia.carbon.bukkit.listeners.contexts.DistanceContext;
import net.draycia.carbon.bukkit.listeners.contexts.EconomyContext;
import net.draycia.carbon.common.contexts.FilterContext;
import net.draycia.carbon.bukkit.listeners.contexts.PAPIContext;
import net.draycia.carbon.bukkit.listeners.contexts.TownyContext;
import net.draycia.carbon.bukkit.listeners.contexts.WorldGuardContext;
import net.draycia.carbon.bukkit.listeners.contexts.mcMMOContext;
import net.draycia.carbon.common.listeners.events.CapsHandler;
import net.draycia.carbon.common.listeners.events.CustomPlaceholderHandler;
import net.draycia.carbon.common.listeners.events.IgnoredPlayerHandler;
import net.draycia.carbon.common.listeners.events.LegacyFormatHandler;
import net.draycia.carbon.common.listeners.events.MuteHandler;
import net.draycia.carbon.common.listeners.events.PingHandler;
import net.draycia.carbon.bukkit.listeners.events.PlaceholderHandler;
import net.draycia.carbon.common.listeners.events.PlayerJoinListener;
import net.draycia.carbon.bukkit.listeners.events.RelationalPlaceholderHandler;
import net.draycia.carbon.common.listeners.events.ShadowMuteHandler;
import net.draycia.carbon.common.listeners.events.UrlLinkHandler;
import net.draycia.carbon.common.listeners.events.UserFormattingHandler;
import net.draycia.carbon.common.listeners.events.WhisperPingHandler;
import net.draycia.carbon.common.adventure.AdventureManager;
import net.draycia.carbon.common.commands.misc.CommandRegistrar;
import net.draycia.carbon.common.messaging.MessageManager;
import net.draycia.carbon.api.users.UserService;
import net.draycia.carbon.common.users.JSONUserService;
import net.draycia.carbon.common.users.MySQLUserService;
import net.kyori.adventure.key.Key;
import net.kyori.adventure.platform.bukkit.BukkitAudiences;
import net.kyori.adventure.sound.Sound;
import net.kyori.adventure.text.serializer.craftbukkit.BukkitComponentSerializer;
import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer;
import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer;
import net.milkbowl.vault.economy.Economy;
import org.bukkit.Bukkit;
import org.bukkit.command.ConsoleCommandSender;
import org.bukkit.entity.Player;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.spongepowered.configurate.CommentedConfigurationNode;
import org.spongepowered.configurate.hocon.HoconConfigurationLoader;
import org.spongepowered.configurate.objectmapping.ObjectMappingException;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.function.Function;
import java.util.function.Supplier;
public final class CarbonChatBukkit extends JavaPlugin implements CarbonChat {
private static final int BSTATS_PLUGIN_ID = 8720;
private ChannelManager channelManager;
private AdventureManager messageProcessor;
private CommandSettingsRegistry commandSettings;
private ModerationSettings moderationSettings;
private CarbonSettings carbonSettings;
private ChannelSettings channelSettings;
private UserService<BukkitPlayerUser> userService;
private MessageManager messageManager;
private CarbonTranslations translations;
private CommandManager<CarbonUser> commandManager;
private Logger logger;
public static final LegacyComponentSerializer LEGACY =
LegacyComponentSerializer.builder()
.extractUrls()
.hexColors()
.character('§')
.useUnusualXRepeatedCharacterHexFormat()
.build();
@Override
public void onLoad() {
CarbonChatProvider.register(this);
}
@Override
public void onEnable() {
this.logger = LoggerFactory.getLogger(this.getName());
// Setup metrics
final Metrics metrics = new Metrics(this, BSTATS_PLUGIN_ID);
this.reloadConfig();
// Setup Adventure
final BukkitAudiences audiences = BukkitAudiences.create(this);
this.messageProcessor = new AdventureManager(audiences, FormatType.MINIMESSAGE); // TODO: get format type from config
// Initialize managers
this.channelManager = new ChannelManager(this);
// Handle messaging service
final MessagingType messagingType = this.carbonSettings().messagingType();
final MessageService messageService;
if (messagingType == MessagingType.REDIS) {
messageService = new RedisMessageService(this, this.carbonSettings.redisCredentials());
} else if (messagingType == MessagingType.BUNGEECORD) {
messageService = new BungeeMessageService(this); // TODO: only support this if bukkit
} else {
messageService = new EmptyMessageService();
}
this.messageManager = new MessageManager(this, messageService);
// Handle storage service
final StorageType storageType = this.carbonSettings().storageType();
final Supplier<Iterable<BukkitPlayerUser>> supplier = () -> {
final List<BukkitPlayerUser> users = new ArrayList<>();
for (final Player player : Bukkit.getOnlinePlayers()) {
users.add(this.userService.wrap(player.getUniqueId()));
}
return users;
};
final Function<String, UUID> nameResolver = name -> Bukkit.getOfflinePlayer(name).getUniqueId();
if (storageType == StorageType.MYSQL) {
this.logger().info("Enabling MySQL storage!");
final SQLCredentials credentials = this.carbonSettings().sqlCredentials();
this.userService = new MySQLUserService<>(this, credentials, supplier, BukkitPlayerUser::new, nameResolver);
} else if (storageType == StorageType.JSON) {
this.logger().info("Enabling JSON storage!");
this.userService = new JSONUserService<>(BukkitPlayerUser.class, this, supplier, BukkitPlayerUser::new, nameResolver);
} else {
this.logger().error("Invalid storage type selected! Falling back to JSON.");
this.userService = new JSONUserService<>(BukkitPlayerUser.class, this, supplier, BukkitPlayerUser::new, nameResolver);
}
// Setup listeners
this.setupCommands();
this.setupListeners();
this.registerContexts();
// Setup PlaceholderAPI placeholders
new CarbonPlaceholders(this).register();
// Log missing functionality
if (this.carbonSettings().showTips() && !FunctionalityConstants.HAS_HOVER_EVENT_METHOD) {
this.logger().error("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();
new CustomPlaceholderHandler();
new IgnoredPlayerHandler();
new ItemLinkHandler();
new LegacyFormatHandler();
new MuteHandler();
new PingHandler();
new PlaceholderHandler();
new PlayerJoinListener();
new RelationalPlaceholderHandler();
new ShadowMuteHandler();
new UrlLinkHandler();
new UserFormattingHandler();
new WhisperPingHandler();
}
private void setupCommands() {
try {
this.commandManager = new PaperCommandManager<>(this,
CommandExecutionCoordinator
.simpleCoordinator(), sender -> {
if (sender instanceof Player) {
return this.userService().wrap(((Player) sender).getUniqueId());
} else {
return new BukkitConsoleUser((ConsoleCommandSender) sender);
}
}, user -> {
if (user instanceof PlayerUser) {
return Bukkit.getPlayer(((PlayerUser) user).uuid());
} else {
return Bukkit.getConsoleSender();
}
});
CommandRegistrar.registerCommands(this.commandManager);
} catch (final Exception e) {
e.printStackTrace();
}
}
@Override
public void reloadConfig() {
this.getDataFolder().mkdirs();
this.loadCarbonSettings();
this.loadLanguage();
this.loadModerationSettings();
this.loadChannelSettings();
this.loadCommandSettings();
}
private void loadCarbonSettings() {
try {
final HoconConfigurationLoader loader =
this.loadConfigFile("config.conf", false);
final CommentedConfigurationNode node = loader.load();
this.carbonSettings = CarbonSettings.loadFrom(node);
loader.save(node);
} catch (final ObjectMappingException | IOException exception) {
exception.printStackTrace();
}
}
private void loadLanguage() {
try {
final HoconConfigurationLoader loader =
this.loadConfigFile("language.conf", false);
final CommentedConfigurationNode node = loader.load();
this.translations = CarbonTranslations.loadFrom(node);
loader.save(node);
} catch (final ObjectMappingException | IOException exception) {
exception.printStackTrace();
}
}
private void loadModerationSettings() {
try {
final HoconConfigurationLoader loader =
this.loadConfigFile("moderation.conf", false);
final CommentedConfigurationNode node = loader.load();
this.moderationSettings = ModerationSettings.loadFrom(node);
loader.save(node);
} catch (final ObjectMappingException | IOException exception) {
exception.printStackTrace();
}
}
private void loadCommandSettings() {
try {
final HoconConfigurationLoader loader =
this.loadConfigFile("carbonCommands.conf", true);
final CommentedConfigurationNode node = loader.load();
this.commandSettings = CommandSettingsRegistry.loadFrom(node);
loader.save(node);
} catch (final ObjectMappingException | IOException exception) {
exception.printStackTrace();
}
}
private void loadChannelSettings() {
try {
final HoconConfigurationLoader loader =
this.loadConfigFile("channels.conf", false);
final CommentedConfigurationNode node = loader.load();
this.channelSettings = ChannelSettings.loadFrom(node);
loader.save(node);
} catch (final ObjectMappingException | IOException exception) {
exception.printStackTrace();
}
}
private HoconConfigurationLoader loadConfigFile(final String fileName, final boolean saveResource) {
final File configFile = new File(this.getDataFolder(), fileName);
if (!(configFile.exists()) && saveResource) {
this.saveResource(fileName, false);
}
return HoconConfigurationLoader.builder()
.defaultOptions(opts -> {
return opts.shouldCopyDefaults(true).serializers(builder -> {
builder.register(Key.class, KeySerializer.INSTANCE)
.register(Sound.class, SoundSerializer.INSTANCE);
});
})
.file(configFile)
.build();
}
private void registerContexts() {
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();
new FilterContext(this);
new PAPIContext();
}
public @NonNull MessageManager messageManager() {
return this.messageManager;
}
public @NonNull UserService<BukkitPlayerUser> userService() {
return this.userService;
}
@Override
public @NonNull ChannelRegistry channelRegistry() {
return this.channelManager.registry();
}
@Override
public @NonNull CarbonTranslations translations() {
return this.translations;
}
@Override
public @NonNull ModerationSettings moderationSettings() {
return this.moderationSettings;
}
@Override
public @NonNull CarbonSettings carbonSettings() {
return this.carbonSettings;
}
@Override
public @NonNull ChannelSettings channelSettings() {
return this.channelSettings;
}
@Override
public @NonNull CommandSettingsRegistry commandSettings() {
return this.commandSettings;
}
@Override
public @NonNull CommandManager<CarbonUser> commandManager() {
return this.commandManager;
}
@Override
public @NonNull MessageProcessor messageProcessor() {
return this.messageProcessor;
}
@Override
public @NonNull MessageService messageService() {
return this.messageManager().messageService();
}
@Override
public @NonNull Logger logger() {
return this.logger;
}
@Override
public @NonNull Path dataFolder() {
return this.getDataFolder().toPath();
}
@Override
public @NonNull GsonComponentSerializer gsonSerializer() {
return BukkitComponentSerializer.gson();
}
}
@@ -0,0 +1,54 @@
package net.draycia.carbon.bukkit.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.Bukkit;
import org.bukkit.Location;
import org.bukkit.entity.Player;
import org.checkerframework.checker.nullness.qual.NonNull;
public class DistanceContext {
private @NonNull 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;
}
final Player sender = Bukkit.getPlayer(event.sender().uuid());
final Player recipient = Bukkit.getPlayer(event.recipient().uuid());
if (sender == null || recipient == null) {
event.cancelled(true);
return;
}
final Location senderLocation = sender.getLocation();
final Location targetLocation = recipient.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);
}
}
});
}
}
@@ -0,0 +1,96 @@
package net.draycia.carbon.bukkit.listeners.contexts;
import net.draycia.carbon.bukkit.CarbonChatBukkit;
import net.draycia.carbon.api.channels.TextChannel;
import net.draycia.carbon.api.events.misc.CarbonEvents;
import net.draycia.carbon.api.events.PreChatFormatEvent;
import net.draycia.carbon.api.Context;
import net.kyori.adventure.identity.Identity;
import net.milkbowl.vault.economy.Economy;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.checkerframework.checker.nullness.qual.NonNull;
public class EconomyContext {
private @NonNull final CarbonChatBukkit carbonChat;
private @NonNull final Economy economy;
public EconomyContext(@NonNull final CarbonChatBukkit carbonChat) {
this.carbonChat = carbonChat;
this.economy = this.carbonChat.getServer().getServicesManager().getRegistration(Economy.class).getProvider();
CarbonEvents.register(PreChatFormatEvent.class, event -> {
if (!(event.channel() instanceof TextChannel)) {
return;
}
final TextChannel channel = (TextChannel) event.channel();
final Context context = 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 = Bukkit.getOfflinePlayer(event.user().uuid());
if (!this.economy.has(player, requiredBal)) {
event.cancelled(true);
event.user().sendMessage(Identity.nil(), this.carbonChat.messageProcessor()
.processMessage(event.channel().cannotUseMessage()));
}
});
CarbonEvents.register(PreChatFormatEvent.class, event -> {
if (!(event.channel() instanceof TextChannel)) {
return;
}
final TextChannel channel = (TextChannel) event.channel();
final Context context = 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 = Bukkit.getOfflinePlayer(event.user().uuid());
if (!this.economy.has(player, cost)) {
event.cancelled(true);
event.user().sendMessage(Identity.nil(), this.carbonChat.messageProcessor()
.processMessage(event.channel().cannotUseMessage()));
return;
}
this.economy.withdrawPlayer(player, cost);
});
}
}
@@ -0,0 +1,77 @@
package net.draycia.carbon.bukkit.listeners.contexts;
import me.clip.placeholderapi.PlaceholderAPI;
import net.draycia.carbon.api.events.MessageContextEvent;
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.Bukkit;
import org.bukkit.entity.Player;
import org.checkerframework.checker.nullness.qual.NonNull;
public class PAPIContext {
private @NonNull static final String KEY = "placeholder";
private @NonNull static final String SENDER = "-sender";
private @NonNull static final String RECEIVER = "-receiver";
public PAPIContext() {
CarbonEvents.register(ReceiverContextEvent.class, PostOrders.NORMAL, false, event -> {
final Context context = event.channel().context(KEY + RECEIVER);
if (context == null) {
return;
}
if (!context.isString()) {
return;
}
final String[] pieces = context.asString().split("=");
if (pieces.length != 2) {
return;
}
final Player receiver = Bukkit.getPlayer(event.recipient().uuid());
if (receiver == null) {
return;
}
final String output = PlaceholderAPI.setPlaceholders(receiver, pieces[0]);
event.cancelled(output.equals(pieces[1]));
});
CarbonEvents.register(MessageContextEvent.class, PostOrders.NORMAL, false, event -> {
final Context context = event.channel().context(KEY + SENDER);
if (context == null) {
return;
}
if (!context.isString()) {
return;
}
final String[] pieces = context.asString().split("=");
if (pieces.length != 2) {
return;
}
final Player receiver = Bukkit.getPlayer(event.user().uuid());
if (receiver == null) {
return;
}
final String output = PlaceholderAPI.setPlaceholders(receiver, pieces[0]);
event.cancelled(output.equals(pieces[1]));
});
}
}
@@ -0,0 +1,132 @@
package net.draycia.carbon.bukkit.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.api.CarbonChat;
import net.draycia.carbon.api.channels.ChatChannel;
import net.draycia.carbon.api.channels.TextChannel;
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.CarbonUser;
import net.draycia.carbon.api.Context;
import net.draycia.carbon.api.users.PlayerUser;
import net.kyori.event.PostOrders;
import org.bukkit.Bukkit;
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 {
private @NonNull static final String KEY = "towny-town";
private @NonNull 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 -> {
if (!(event.channel() instanceof TextChannel)) {
return;
}
final TextChannel channel = (TextChannel) event.channel();
final Context context = 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 CarbonUser user = this.carbonChat.userService().wrap(Bukkit.getPlayer(name).getUniqueId());
final ChatChannel channel = user.selectedChannel();
if (!(channel instanceof TextChannel)) {
return;
}
final TextChannel textChannel = (TextChannel) channel;
final Context context = textChannel.context(KEY);
if (context != null && context.isBoolean() && context.asBoolean()) {
user.clearSelectedChannel();
}
}
@EventHandler
public void onPlayerJoin(final PlayerJoinEvent event) {
final PlayerUser user = this.carbonChat.userService().wrap(event.getPlayer().getUniqueId());
final ChatChannel channel = user.selectedChannel();
if (!(channel instanceof TextChannel)) {
return;
}
final TextChannel textChannel = (TextChannel) channel;
final Context context = textChannel.context(KEY);
if (context != null && context.isBoolean() && context.asBoolean() && !this.isInTown(user)) {
user.clearSelectedChannel();
}
}
public boolean isInTown(@NonNull final PlayerUser user) {
try {
return TownyAPI.getInstance().getDataSource().getResident(Bukkit.getPlayer(user.uuid()).getName()).hasTown();
} catch (final NotRegisteredException exception) {
exception.printStackTrace();
}
return false;
}
public boolean isInSameTown(@NonNull final PlayerUser user1, @NonNull final PlayerUser user2) {
if (Bukkit.getPlayer(user1.uuid()) == null || Bukkit.getPlayer(user2.uuid()) == null) {
return false;
}
try {
final Resident resident = TownyAPI.getInstance().getDataSource().getResident(Bukkit.getPlayer(user1.uuid()).getName());
if (resident.hasTown()) {
return resident.getTown().hasResident(Bukkit.getPlayer(user2.uuid()).getName());
}
} catch (final NotRegisteredException exception) {
exception.printStackTrace();
}
return false;
}
}
@@ -0,0 +1,124 @@
package net.draycia.carbon.bukkit.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.Context;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.checkerframework.checker.nullness.qual.NonNull;
public final class WorldGuardContext {
private @NonNull static final String KEY = "worldguard-region";
public WorldGuardContext() {
CarbonEvents.register(ReceiverContextEvent.class, event -> {
final Player senderPlayer = Bukkit.getPlayer(event.sender().uuid());
final Player recipientPlayer = Bukkit.getPlayer(event.recipient().uuid());
if (senderPlayer == null || recipientPlayer == null) {
return;
}
event.cancelled(this.testContext(senderPlayer, recipientPlayer, event.context(KEY)));
});
CarbonEvents.register(MessageContextEvent.class, event -> {
final Context value = event.channel().context(KEY);
final Player player = Bukkit.getPlayer(event.user().uuid());
if (player == null) {
return;
}
if (value != null && (value.isString() || value.isList()) && !this.isInRegionOrRegions(value, player)) {
event.cancelled(true);
}
});
}
private boolean isInRegionOrRegions(@NonNull final Context context, @NonNull final Player player) {
if (context.isString()) {
return this.isInRegion(context.asString(), player);
}
if (context.isList()) {
for (final String region : context.<String>asList()) {
if (this.isInRegion(region, player)) {
return true;
}
}
}
return false;
}
public boolean testContext(@NonNull final Player sender, @NonNull final Player 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 Player user1, @NonNull final Player user2) {
final Location user1Location = BukkitAdapter.adapt(user1.getLocation());
final Location user2Location = BukkitAdapter.adapt(user2.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 Player player) {
final RegionContainer container = WorldGuard.getInstance().getPlatform().getRegionContainer();
final World world = BukkitAdapter.adapt(player.getWorld());
final ProtectedRegion protection = container.get(world).getRegion(region);
return this.isInRegion(protection, player);
}
public boolean isInRegion(@NonNull final ProtectedRegion region, @NonNull final Player player) {
final org.bukkit.Location location = player.getLocation();
return region.contains(location.getBlockX(), location.getBlockY(), location.getBlockZ());
}
}
@@ -0,0 +1,110 @@
package net.draycia.carbon.bukkit.listeners.contexts;
import com.gmail.nossr50.api.PartyAPI;
import com.gmail.nossr50.events.party.McMMOPartyChangeEvent;
import net.draycia.carbon.api.CarbonChat;
import net.draycia.carbon.api.channels.ChatChannel;
import net.draycia.carbon.api.channels.TextChannel;
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.Context;
import net.draycia.carbon.api.users.PlayerUser;
import net.kyori.event.PostOrders;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
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 {
private @NonNull final CarbonChat carbonChat;
private @NonNull 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 -> {
if (!(event.channel() instanceof TextChannel)) {
return;
}
final TextChannel channel = (TextChannel) event.channel();
final Context context = channel.context(KEY);
if (context != null && context.isBoolean() && context.asBoolean()) {
if (!this.isInParty(event.user())) {
//event.failureMessage(carbonChat.carbonSettings().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;
}
this.checkContext(event.getPlayer());
}
@EventHandler
public void onPlayerJoin(final PlayerJoinEvent event) {
this.checkContext(event.getPlayer());
}
private void checkContext(final Player player) {
final PlayerUser user = this.carbonChat.userService().wrap(player.getUniqueId());
final ChatChannel channel = user.selectedChannel();
if (!(channel instanceof TextChannel)) {
return;
}
final TextChannel textChannel = (TextChannel) channel;
final Context context = textChannel.context(KEY);
if (context != null && context.isBoolean() && context.asBoolean() && !this.isInParty(user)) {
user.clearSelectedChannel();
}
}
public boolean isInParty(@NonNull final PlayerUser user) {
return PartyAPI.inParty(Bukkit.getPlayer(user.uuid()));
}
public boolean isInSameParty(@NonNull final PlayerUser user1, @NonNull final PlayerUser user2) {
if (Bukkit.getPlayer(user1.uuid()) == null || Bukkit.getPlayer(user2.uuid()) == null) {
return false;
}
return PartyAPI.inSameParty(Bukkit.getPlayer(user1.uuid()), Bukkit.getPlayer(user2.uuid()));
}
}
@@ -0,0 +1,126 @@
package net.draycia.carbon.bukkit.listeners.events;
import net.draycia.carbon.api.channels.ChatChannel;
import net.draycia.carbon.api.channels.TextChannel;
import net.draycia.carbon.api.events.UserEvent;
import net.draycia.carbon.api.events.misc.CarbonEvents;
import net.draycia.carbon.bukkit.CarbonChatBukkit;
import net.draycia.carbon.api.users.PlayerUser;
import net.kyori.adventure.identity.Identity;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.serializer.plain.PlainComponentSerializer;
import org.bukkit.Bukkit;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.AsyncPlayerChatEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.checkerframework.checker.nullness.qual.NonNull;
import java.util.Map;
public class BukkitChatListener implements Listener {
private @NonNull final CarbonChatBukkit carbonChat;
public BukkitChatListener(@NonNull final CarbonChatBukkit carbonChat) {
this.carbonChat = carbonChat;
}
// Chat messages
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onPlayerchat(@NonNull final AsyncPlayerChatEvent event) {
// TODO: Move most of this to Common handling
// TODO: ChatMessageEvent that's called at the start of this
// TODO: Obtain a component (for console usage) from that event, or another
final PlayerUser user = this.carbonChat.userService().wrap(event.getPlayer().getUniqueId());
ChatChannel channel = user.selectedChannel();
if (channel == null) {
if (this.carbonChat.channelRegistry().defaultValue() == null) {
return;
}
channel = this.carbonChat.channelRegistry().defaultValue();
}
// if (channel.shouldCancelChatEvent()) {
// event.setCancelled(true);
// }
for (final ChatChannel entry : this.carbonChat.channelRegistry()) {
if (!(entry instanceof TextChannel)) {
continue;
}
final TextChannel textChannel = (TextChannel) entry;
if (textChannel.messagePrefix() == null || textChannel.messagePrefix().isEmpty()) {
continue;
}
if (event.getMessage().startsWith(textChannel.messagePrefix())) {
if (entry.canPlayerUse(user)) {
event.setMessage(event.getMessage().substring(textChannel.messagePrefix().length()));
channel = entry;
break;
}
}
}
final ChatChannel selectedChannel = channel;
if (!selectedChannel.canPlayerUse(user)) {
return;
}
event.getRecipients().clear();
if (event.isAsynchronous()) {
final Map<PlayerUser, Component> messages =
selectedChannel.parseMessage(user, event.getMessage(), false);
for (final Map.Entry<PlayerUser, Component> entry : messages.entrySet()) {
if (entry.getValue().equals(Component.empty())) {
continue;
}
entry.getKey().sendMessage(Identity.identity(event.getPlayer().getUniqueId()), entry.getValue());
if (user.equals(entry.getKey())) {
event.setFormat(PlainComponentSerializer.plain().serialize(entry.getValue())
.replaceAll("(?:[^%]|\\A)%(?:[^%]|\\z)", "%%"));
}
}
} else {
Bukkit.getScheduler().runTaskAsynchronously(this.carbonChat, () -> {
selectedChannel.sendComponentsAndLog(
selectedChannel.parseMessage(user, event.getMessage(), false));
// if (this.carbonChat.getConfig().getBoolean("show-tips")) {
// this.carbonChat.logger().info("Tip: Sync chat event! I cannot set the message format due to this. :(");
// this.carbonChat.logger().info("Tip: To 'solve' this, do a binary search and see which plugin is triggering");
// this.carbonChat.logger().info("Tip: sync chat events and causing this, and let that plugin author know.");
// }
});
}
}
@EventHandler
public void onPlayerJoin(final PlayerJoinEvent event) {
final PlayerUser user = this.carbonChat.userService().wrap(event.getPlayer().getUniqueId());
final UserEvent.Join joinEvent = new UserEvent.Join(user);
CarbonEvents.post(joinEvent);
}
@EventHandler
public void onPlayerLeave(final PlayerQuitEvent event) {
final PlayerUser user = this.carbonChat.userService().wrap(event.getPlayer().getUniqueId());
final UserEvent.Leave leaveEvent = new UserEvent.Leave(user);
CarbonEvents.post(leaveEvent);
}
}
@@ -0,0 +1,50 @@
package net.draycia.carbon.bukkit.listeners.events;
import net.draycia.carbon.bukkit.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.Bukkit;
import org.bukkit.entity.Player;
import java.util.regex.Pattern;
public class ItemLinkHandler {
public ItemLinkHandler() {
CarbonEvents.register(ChatComponentEvent.class, PostOrders.FIRST, false, event -> {
// Handle item linking placeholders
final Player player = Bukkit.getPlayer(event.sender().uuid());
if (player == null) {
return;
}
if (!player.hasPermission("carbonchat.itemlink")) {
return;
}
final Component itemComponent = CarbonUtils.createComponent(player);
if (itemComponent.equals(Component.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 -> itemComponent);
event.component(component);
break;
}
}
});
}
}
@@ -0,0 +1,17 @@
package net.draycia.carbon.bukkit.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;
import org.bukkit.Bukkit;
public class PlaceholderHandler {
public PlaceholderHandler() {
CarbonEvents.register(PreChatFormatEvent.class, PostOrders.FIRST, false, event -> {
event.format(PlaceholderAPI.setPlaceholders(Bukkit.getOfflinePlayer(event.user().uuid()), event.format()));
});
}
}
@@ -0,0 +1,29 @@
package net.draycia.carbon.bukkit.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.Bukkit;
import org.bukkit.entity.Player;
public class RelationalPlaceholderHandler {
public RelationalPlaceholderHandler() {
CarbonEvents.register(ChatFormatEvent.class, PostOrders.FIRST, false, event -> {
if (event.target() == null) {
return;
}
final Player sender = Bukkit.getPlayer(event.sender().uuid());
final Player target = Bukkit.getPlayer(event.target().uuid());
if (sender == null || target == null) {
return;
}
event.format(PlaceholderAPI.setRelationalPlaceholders(sender, target, event.format()));
});
}
}
@@ -0,0 +1,111 @@
package net.draycia.carbon.bukkit.messaging;
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.bukkit.CarbonChatBukkit;
import net.draycia.carbon.api.messaging.MessageService;
import net.draycia.carbon.api.users.PlayerUser;
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 {
private @NonNull final CarbonChatBukkit carbonChat;
private @NonNull final BungeeChannelApi api;
private @NonNull final Map<@NonNull String, @NonNull BiConsumer<@NonNull PlayerUser, @NonNull ByteArrayDataInput>> userLoadedListeners = new HashMap<>();
private @NonNull final Map<@NonNull String, @NonNull BiConsumer<@NonNull UUID, @NonNull ByteArrayDataInput>> userNotLoadedListeners = new HashMap<>();
private @NonNull final UUID serverUUID = UUID.randomUUID();
public BungeeMessageService(@NonNull final CarbonChatBukkit 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 PlayerUser user = this.carbonChat.userService().wrapIfLoaded(uuid);
if (user != null) {
for (final Map.Entry<String, BiConsumer<PlayerUser, 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 PlayerUser, @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());
}
}
@@ -0,0 +1,61 @@
package net.draycia.carbon.bukkit.users;
import net.draycia.carbon.api.CarbonChat;
import net.draycia.carbon.api.CarbonChatProvider;
import net.draycia.carbon.api.channels.ChatChannel;
import net.draycia.carbon.api.users.ConsoleUser;
import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.audience.ForwardingAudience;
import net.kyori.adventure.platform.bukkit.BukkitAudiences;
import org.bukkit.Bukkit;
import org.bukkit.command.ConsoleCommandSender;
import org.bukkit.plugin.Plugin;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import java.util.Collections;
public class BukkitConsoleUser implements ConsoleUser, ForwardingAudience {
private final @NonNull CarbonChat carbonChat;
private final @NonNull Iterable<Audience> audience;
public BukkitConsoleUser(final @NonNull ConsoleCommandSender sender) {
final Plugin plugin = Bukkit.getPluginManager().getPlugin("CarbonChat-Bukkit");
this.carbonChat = CarbonChatProvider.carbonChat();
this.audience = Collections.singletonList(BukkitAudiences.create(plugin).sender(sender));
}
@Override
public @NonNull Iterable<? extends Audience> audiences() {
return this.audience;
}
@Override
public boolean hasPermission(@NonNull final String permission) {
return true;
}
@Override
public @NonNull String name() {
return "Console";
}
@Override
public @Nullable ChatChannel selectedChannel() {
// TODO: stub
return null;
}
@Override
public void selectedChannel(@NonNull final ChatChannel channel, final boolean fromRemote) {
// TODO: stub
}
@Override
public void clearSelectedChannel() {
// TODO: stub
}
}
@@ -0,0 +1,456 @@
package net.draycia.carbon.bukkit.users;
import net.draycia.carbon.api.channels.ChatChannel;
import net.draycia.carbon.api.users.CarbonUser;
import net.draycia.carbon.api.users.PlayerUser;
import net.draycia.carbon.api.users.UserChannelSettings;
import net.draycia.carbon.common.channels.CarbonWhisperChannel;
import net.draycia.carbon.bukkit.util.FunctionalityConstants;
import io.github.leonardosnt.bungeechannelapi.BungeeChannelApi;
import net.draycia.carbon.bukkit.CarbonChatBukkit;
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.identity.Identity;
import net.kyori.adventure.text.Component;
import net.luckperms.api.LuckPerms;
import net.luckperms.api.LuckPermsProvider;
import net.luckperms.api.model.group.Group;
import net.luckperms.api.model.user.User;
import net.luckperms.api.query.QueryOptions;
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.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;
public class BukkitPlayerUser implements PlayerUser, ForwardingAudience.Single {
private @NonNull final transient CarbonChatBukkit carbonChat;
private @NonNull final Map<@NonNull String, @NonNull SimpleUserChannelSettings> channelSettings = new HashMap<>();
private @NonNull final List<@NonNull UUID> ignoredUsers = new ArrayList<>();
private @MonotonicNonNull UUID uuid;
private boolean muted = false;
private boolean shadowMuted = false;
private boolean spyingWhispers = false;
private @Nullable String nickname = null;
private @Nullable UUID replyTarget = null;
private @Nullable String selectedChannelKey = null;
private transient @Nullable ChatChannel selectedChannel = null;
public BukkitPlayerUser() {
this.carbonChat = (CarbonChatBukkit) Bukkit.getPluginManager().getPlugin("CarbonChat-Bukkit");
}
public BukkitPlayerUser(@NonNull final UUID uuid) {
this();
this.uuid = uuid;
}
@Override
public @NonNull Audience audience() {
return this.carbonChat.messageProcessor().audiences().player(this.uuid());
}
@Override
public boolean online() {
return Bukkit.getPlayer(this.uuid()) != null;
}
@Override
public @NonNull UUID uuid() {
return this.uuid;
}
@Override
public @Nullable String nickname() {
return this.nickname;
}
@Override
public boolean hasPermission(@NonNull final String permission) {
return LuckPermsProvider.get().getUserManager().getUser(this.uuid())
.getCachedData().getPermissionData().checkPermission(permission).asBoolean();
}
@Override
public void nickname(@Nullable String newNickname, final boolean fromRemote) {
this.nickname = newNickname;
final OfflinePlayer player = Bukkit.getOfflinePlayer(this.uuid());
if (player.isOnline()) {
if (newNickname != null) {
final Component component = this.carbonChat.messageProcessor().processMessage(this.nickname);
newNickname = CarbonChatBukkit.LEGACY.serialize(component);
}
final Player onlinePlayer = player.getPlayer();
onlinePlayer.setDisplayName(newNickname);
// if (this.carbonChat.getConfig().getBoolean("nicknames-set-tab-name")) {
// onlinePlayer.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
public @Nullable String displayName() {
final Player player = Bukkit.getPlayer(this.uuid());
if (player != null) {
return player.getDisplayName();
}
return this.name();
}
public void displayName(@Nullable final String displayName) {
final Player player = Bukkit.getPlayer(this.uuid());
if (player != null) {
player.setDisplayName(displayName);
}
}
public @NonNull String name() {
return Objects.requireNonNull(Bukkit.getOfflinePlayer(this.uuid()).getName());
}
@Override
public @Nullable ChatChannel selectedChannel() {
if (this.selectedChannel != null) {
return this.selectedChannel;
}
if (this.selectedChannelKey != null) {
if (this.selectedChannelKey.equals("whisper") && this.replyTarget != null) {
this.selectedChannel = new CarbonWhisperChannel(this,
this.carbonChat.userService().wrap(this.replyTarget));
return this.selectedChannel;
}
return this.carbonChat.channelRegistry().getOrDefault(this.selectedChannelKey);
}
return null;
}
@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(Identity.nil(), this.carbonChat.messageProcessor().processMessage(event.failureMessage(),
"channel", chatChannel.name()));
return;
}
this.selectedChannelKey = chatChannel.key();
this.selectedChannel = chatChannel;
if (!fromRemote) {
this.carbonChat.messageManager().sendMessage("selected-channel", this.uuid(), byteArray -> {
byteArray.writeUTF(chatChannel.key());
});
}
final OfflinePlayer player = Bukkit.getOfflinePlayer(this.uuid());
if (player.isOnline()) {
this.sendMessage(Identity.nil(), this.carbonChat.messageProcessor().processMessage(chatChannel.switchMessage(),
"color", "<" + chatChannel.channelColor(this).toString() + ">",
"channel", chatChannel.name()));
}
}
@Override
public void clearSelectedChannel() {
this.selectedChannel(this.carbonChat.channelRegistry().defaultValue());
}
@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);
});
}
}
@Override
public @NonNull Iterable<@NonNull UUID> ignoredUsers() {
return this.ignoredUsers;
}
private transient final LuckPerms luckPerms = LuckPermsProvider.get();
@Override
public boolean hasGroup(@NonNull final String groupName) {
return this.hasGroup(this.luckPerms.getGroupManager().getGroup(groupName));
}
@Override
public boolean hasGroup(@NonNull final Group group) {
return this.groups().contains(group);
}
@Override
public @NonNull Collection<@NonNull Group> groups() {
final User user = this.luckPerms.getUserManager().getUser(this.uuid());
return user.getInheritedGroups(QueryOptions.nonContextual());
}
@Override
public @Nullable Group primaryGroup() {
final User user = this.luckPerms.getUserManager().getUser(this.uuid());
return this.luckPerms.getGroupManager().getGroup(user.getPrimaryGroup());
}
@Override
public @NonNull Iterable<@NonNull CarbonUser> ignoredChatUsers() {
final List<CarbonUser> users = new ArrayList<>();
for (final UUID uuid : this.ignoredUsers) {
users.add(this.carbonChat.userService().wrap(uuid));
}
return users;
}
@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
public @Nullable 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
public @NonNull UserChannelSettings channelSettings(@NonNull final ChatChannel channel) {
return this.channelSettings.computeIfAbsent(channel.key(), name -> {
return new SimpleUserChannelSettings(this.uuid, channel.key());
});
}
public @NonNull 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 PlayerUser sender, @NonNull final String message) {
if (this.ignoringUser(sender) || sender.ignoringUser(this)) {
return;
}
final String toPlayerFormat = this.carbonChat.carbonSettings().whisperOptions().senderFormat();
final String fromPlayerFormat = this.carbonChat.carbonSettings().whisperOptions().receiverFormat();
final OfflinePlayer offlineSender = Bukkit.getOfflinePlayer(sender.uuid());
String senderName = offlineSender.getName();
final String senderOfflineName = senderName;
if (offlineSender.isOnline()) {
senderName = offlineSender.getPlayer().getDisplayName();
}
final OfflinePlayer offlineTarget = Bukkit.getOfflinePlayer(this.uuid());
String targetName = offlineTarget.getName();
final String targetOfflineName = targetName;
if (offlineTarget.isOnline()) {
targetName = offlineTarget.getPlayer().getDisplayName();
}
final Component toPlayerComponent = this.carbonChat.messageProcessor().processMessage(toPlayerFormat,
"message", message, "targetname", targetOfflineName, "sendername", senderOfflineName,
"target", targetName, "sender", senderName);
final Component fromPlayerComponent = this.carbonChat.messageProcessor().processMessage(fromPlayerFormat,
"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 (offlineTarget.isOnline()) {
if (offlineSender.isOnline()) {
sender.sendMessage(Identity.identity(sender.uuid()), toPlayerComponent);
if (sender.shadowMuted()) {
return;
}
this.sendMessage(Identity.identity(sender.uuid()), fromPlayerComponent);
sender.replyTarget(this);
this.replyTarget(sender);
}
} else if (offlineSender.isOnline()) {
final String targetNameFinal = targetName;
final String senderNameFinal = senderName;
if (!FunctionalityConstants.HAS_PROXY) {
final String playerOfflineFormat = this.carbonChat.translations().otherPlayerOffline();
final Component playerOfflineComponent = this.carbonChat.messageProcessor().processMessage(playerOfflineFormat,
"message", message,
"targetname", targetOfflineName, "sendername", senderOfflineName,
"target", targetNameFinal, "sender", senderNameFinal);
sender.sendMessage(Identity.nil(), playerOfflineComponent);
return;
}
BungeeChannelApi.of(this.carbonChat).getPlayerList("ALL").thenAccept(list -> {
final OfflinePlayer player = Bukkit.getOfflinePlayer(this.uuid());
if (!list.contains(player.getName())) {
final String playerOfflineFormat = this.carbonChat.translations().otherPlayerOffline();
final Component playerOfflineComponent = this.carbonChat.messageProcessor().processMessage(playerOfflineFormat,
"message", message,
"targetname", targetOfflineName, "sendername", senderOfflineName,
"target", targetNameFinal, "sender", senderNameFinal);
sender.sendMessage(Identity.nil(), playerOfflineComponent);
return;
}
sender.sendMessage(Identity.identity(sender.uuid()), toPlayerComponent);
this.carbonChat.messageManager().sendMessage("whisper-component", sender.uuid(), byteArray -> {
byteArray.writeLong(this.uuid().getMostSignificantBits());
byteArray.writeLong(this.uuid().getLeastSignificantBits());
byteArray.writeUTF(this.carbonChat.gsonSerializer().serialize(fromPlayerComponent));
});
});
}
for (final Player player : Bukkit.getOnlinePlayers()) {
final PlayerUser user = this.carbonChat.userService().wrap(player.getUniqueId());
if (!user.spyingWhispers()) {
continue;
}
if (user.uuid().equals(sender.uuid()) || user.uuid().equals(this.uuid())) {
continue;
}
user.sendMessage(Identity.identity(sender.uuid()), this.carbonChat.messageProcessor()
.processMessage(this.carbonChat.translations().spyWhispers(), "message", message,
"targetname", targetOfflineName, "sendername", senderOfflineName, "target", targetName,
"sender", senderName));
}
}
}
@@ -0,0 +1,92 @@
package net.draycia.carbon.bukkit.users;
import net.draycia.carbon.api.CarbonChat;
import net.draycia.carbon.api.CarbonChatProvider;
import net.draycia.carbon.api.users.CarbonUser;
import net.draycia.carbon.api.users.UserChannelSettings;
import net.kyori.adventure.text.format.TextColor;
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 {
private @NonNull final transient CarbonChat carbonChat = CarbonChatProvider.carbonChat();
private boolean spying;
private boolean ignored;
private @NonNull String color;
@MonotonicNonNull // @NonNull but not initialised in all constructors.
private UUID uuid;
@MonotonicNonNull // @NonNull but not initialised in all constructors.
private String channel;
public SimpleUserChannelSettings(@NonNull final UUID uuid, @NonNull final String channel) {
this.uuid = uuid;
this.channel = channel;
}
private @NonNull CarbonUser user() {
return 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.messageService().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.messageService().sendMessage("ignoring-channel", this.uuid, byteArray -> {
byteArray.writeUTF(this.channel);
byteArray.writeBoolean(ignored);
});
}
}
@Override
public @Nullable 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.messageService().sendMessage("channel-color", this.uuid, byteArray -> {
byteArray.writeUTF(color.asHexString());
});
}
}
}
@@ -0,0 +1,88 @@
package net.draycia.carbon.bukkit.util;
import net.draycia.carbon.api.channels.ChatChannel;
import me.clip.placeholderapi.expansion.PlaceholderExpansion;
import net.draycia.carbon.bukkit.CarbonChatBukkit;
import net.draycia.carbon.api.users.PlayerUser;
import org.bukkit.entity.Player;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
public class CarbonPlaceholders extends PlaceholderExpansion {
private @NonNull final CarbonChatBukkit carbonChat;
public CarbonPlaceholders(@NonNull final CarbonChatBukkit carbonChat) {
this.carbonChat = carbonChat;
}
@Override
public @NonNull String getIdentifier() {
return "carbonchat";
}
@Override
public @NonNull String getAuthor() {
return "Draycia (Vicarious#0001)";
}
@Override
public @NonNull String getVersion() {
return "1.0.0";
}
@Override
public boolean persist() {
return true;
}
@Override
public @Nullable 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.channelRegistry().get(value);
if (channel == null) {
return "false";
}
final PlayerUser user = this.carbonChat.userService().wrap(player.getUniqueId());
return String.valueOf(channel.canPlayerUse(user));
} else if (key.startsWith("can_see_")) {
final String value = key.replace("can_see_", "");
final ChatChannel channel = this.carbonChat.channelRegistry().get(value);
if (channel == null) {
return "false";
}
final PlayerUser user = this.carbonChat.userService().wrap(player.getUniqueId());
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.channelRegistry().get(value);
if (channel == null) {
return "false";
}
final PlayerUser user = this.carbonChat.userService().wrap(player.getUniqueId());
return String.valueOf(user.channelSettings(channel).ignored());
} else if (key.startsWith("selected_channel")) {
final ChatChannel channel = this.carbonChat.userService().wrap(player.getUniqueId()).selectedChannel();
return channel == null ? this.carbonChat.channelRegistry().defaultValue().name() : channel.name();
}
return null;
}
}
@@ -0,0 +1,91 @@
/*
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.bukkit.util;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.NamedTextColor;
import net.kyori.adventure.text.serializer.bungeecord.BungeeComponentSerializer;
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.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.checkerframework.checker.nullness.qual.NonNull;
import java.util.ArrayList;
import java.util.List;
public final class CarbonUtils {
private static @NonNull final String @NonNull [] colors;
private CarbonUtils() {
}
static {
final List<String> colorList = new ArrayList<>();
for (final NamedTextColor color : NamedTextColor.NAMES.values()) {
colorList.add(color.toString());
}
colors = colorList.toArray(new String[0]);
}
public @NonNull static Component createComponent(@NonNull final Player player) {
if (!FunctionalityConstants.HAS_HOVER_EVENT_METHOD) {
return net.kyori.adventure.text.Component.empty();
}
final ItemStack itemStack = player.getInventory().getItemInMainHand();
if (itemStack.getType().isAir()) {
return net.kyori.adventure.text.Component.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 BungeeComponentSerializer.get().deserialize(component.create());
}
}
@@ -0,0 +1,45 @@
package net.draycia.carbon.bukkit.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.bukkit.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 pluginData() {
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.requestJsonObject();
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 serverData() {
// 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.serverData();
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 requestJsonObject() {
final JsonObject chart = new JsonObject();
chart.addProperty("chartId", this.chartId);
try {
final JsonObject data = this.chartData();
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 chartData() 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 chartData() 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 chartData() 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 chartData() 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 chartData() 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 chartData() 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 chartData() 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 chartData() 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;
}
}
}