This commit is contained in:
BuildTools committed 2024-01-01 02:24:43 +05:00
commit 2f03847ec2
172 files changed
+15400

No files matched your search

@@ -0,0 +1,50 @@
/*
* Copyright 2000-2012 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.jetbrains.annotations;
import java.lang.annotation.*;
/**
* An element annotated with NotNull claims {@code null} value is
* <em>forbidden</em> to return (for methods), pass to (parameters) and hold
* (local variables and fields). Apart from documentation purposes this
* annotation is intended to be used by static analysis tools to validate
* against probable runtime errors and element contract violations.
*
* @author max
*/
@Documented
@Retention(RetentionPolicy.CLASS)
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER, ElementType.LOCAL_VARIABLE, ElementType.TYPE_USE})
public @interface NotNull {
/**
* @return Custom exception message
*/
String value() default "";
/**
* @return Custom exception type that should be thrown when not-nullity contract
* is violated. The exception class should have a constructor with one
* String argument (message).
* <p>
* By default, {@link IllegalArgumentException} is thrown on null method
* arguments and {@link IllegalStateException} &mdash; on null return
* value.
*/
Class<? extends Exception> exception() default Exception.class;
}
@@ -0,0 +1,47 @@
/*
* Copyright 2000-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.jetbrains.annotations;
import java.lang.annotation.*;
/**
* An element annotated with {@link Nullable} claims {@code null} value is
* perfectly <em>valid</em> to return (for methods), pass to (parameters) or
* hold in (local variables and fields). Apart from documentation purposes this
* annotation is intended to be used by static analysis tools to validate
* against probable runtime errors or element contract violations. <br>
* By convention, this annotation applied only when the value should
* <em>always</em> be checked against {@code null} because the developer could
* do nothing to prevent null from happening. Otherwise, too eager
* {@link Nullable} usage could lead to too many false positives from static
* analysis tools. <br>
* For example, {@link java.util.Map#get(Object key)} should <em>not</em> be
* annotated {@link Nullable} because someone may have put not-null value in the
* map by this key and is expecting to find this value there ever since. <br>
* On the other hand, the {@link java.lang.ref.Reference#get()} should be
* annotated {@link Nullable} because it returns {@code null} if object got
* collected which can happen at any time completely unexpectedly.
*
* @author max
*/
@Documented
@Retention(RetentionPolicy.CLASS)
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER, ElementType.LOCAL_VARIABLE, ElementType.TYPE_USE})
public @interface Nullable {
String value() default "";
}
@@ -0,0 +1,73 @@
package su.nightexpress.nightcore;
import org.jetbrains.annotations.NotNull;
import su.nightexpress.nightcore.command.base.ReloadSubCommand;
import su.nightexpress.nightcore.config.PluginDetails;
import su.nightexpress.nightcore.core.CoreConfig;
import su.nightexpress.nightcore.core.CoreLang;
import su.nightexpress.nightcore.core.CoreManager;
import su.nightexpress.nightcore.core.CorePerms;
import su.nightexpress.nightcore.core.command.CheckPermCommand;
import su.nightexpress.nightcore.dialog.Dialog;
import su.nightexpress.nightcore.integration.VaultHook;
import su.nightexpress.nightcore.language.LangAssets;
import su.nightexpress.nightcore.menu.impl.EditorMenu;
import su.nightexpress.nightcore.util.Plugins;
import su.nightexpress.nightcore.util.blocktracker.PlayerBlockTracker;
import java.util.HashSet;
import java.util.Set;
public class NightCore extends NightPlugin {
private final Set<NightCorePlugin> childrens;
private final CoreManager coreManager;
public NightCore() {
this.childrens = new HashSet<>();
this.coreManager = new CoreManager(this);
}
@Override
public void enable() {
LangAssets.load();
if (Plugins.hasVault()) {
VaultHook.setup();
this.getBaseCommand().addChildren(new CheckPermCommand(this));
}
this.getBaseCommand().addChildren(new ReloadSubCommand(this, CorePerms.COMMAND_RELOAD));
this.coreManager.setup();
}
@Override
public void disable() {
this.coreManager.shutdown();
Dialog.shutdown();
if (Plugins.hasVault()) {
VaultHook.shutdown();
}
PlayerBlockTracker.shutdown();
}
@Override
@NotNull
protected PluginDetails getDefaultDetails() {
return PluginDetails.create("nightcore", new String[]{"nightcore", "ncore"})
.setConfigClass(CoreConfig.class)
.setLangClass(CoreLang.class)
.setPermissionsClass(CorePerms.class);
}
void addChildren(@NotNull NightCorePlugin child) {
this.childrens.add(child);
child.info("Powered by " + this.getName());
}
@NotNull
public Set<NightCorePlugin> getChildrens() {
return new HashSet<>(this.childrens);
}
}
@@ -0,0 +1,119 @@
package su.nightexpress.nightcore;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.PluginManager;
import org.bukkit.scheduler.BukkitScheduler;
import org.bukkit.scheduler.BukkitTask;
import org.jetbrains.annotations.NotNull;
import su.nightexpress.nightcore.command.api.NightPluginCommand;
import su.nightexpress.nightcore.config.FileConfig;
import su.nightexpress.nightcore.command.CommandManager;
import su.nightexpress.nightcore.config.PluginDetails;
import su.nightexpress.nightcore.language.LangManager;
import su.nightexpress.nightcore.util.wrapper.UniTask;
import java.util.function.Consumer;
public interface NightCorePlugin extends Plugin {
boolean isEngine();
void enable();
void disable();
void reload();
@NotNull NightPluginCommand getBaseCommand();
@Override
@NotNull FileConfig getConfig();
@NotNull FileConfig getLang();
@NotNull PluginDetails getDetails();
@NotNull
default String getNameLocalized() {
return this.getDetails().getName();
}
@NotNull
default String getPrefix() {
return this.getDetails().getPrefix();
}
@NotNull
default String[] getCommandAliases() {
return this.getDetails().getCommandAliases();
}
@NotNull
default String getLanguage() {
return this.getDetails().getLanguage();
}
default void info(@NotNull String msg) {
this.getLogger().info(msg);
}
default void warn(@NotNull String msg) {
this.getLogger().warning(msg);
}
default void error(@NotNull String msg) {
this.getLogger().severe(msg);
}
default void debug(@NotNull String msg) {
this.info("[DEBUG] " + msg);
}
@NotNull LangManager getLangManager();
@NotNull CommandManager getCommandManager();
@NotNull
default BukkitScheduler getScheduler() {
return this.getServer().getScheduler();
}
@NotNull
default PluginManager getPluginManager() {
return this.getServer().getPluginManager();
}
default void runTask(@NotNull Consumer<BukkitTask> consumer) {
this.getScheduler().runTask(this, consumer);
}
default void runTaskAsync(@NotNull Consumer<BukkitTask> consumer) {
this.getScheduler().runTaskAsynchronously(this, consumer);
}
default void runTaskLater(@NotNull Consumer<BukkitTask> consumer, long delay) {
this.getScheduler().runTaskLater(this, consumer, delay);
}
default void runTaskLaterAsync(@NotNull Consumer<BukkitTask> consumer, long delay) {
this.getScheduler().runTaskLaterAsynchronously(this, consumer, delay);
}
default void runTaskTimer(@NotNull Consumer<BukkitTask> consumer, long delay, long interval) {
this.getScheduler().runTaskTimer(this, consumer, delay, interval);
}
default void runTaskTimerAsync(@NotNull Consumer<BukkitTask> consumer, long delay, long interval) {
this.getScheduler().runTaskTimerAsynchronously(this, consumer, delay, interval);
}
@NotNull
default UniTask createTask(@NotNull Runnable runnable) {
return new UniTask(this, runnable);
}
@NotNull
default UniTask createAsyncTask(@NotNull Runnable runnable) {
return this.createTask(runnable).setAsync();
}
}
@@ -0,0 +1,31 @@
package su.nightexpress.nightcore;
import org.jetbrains.annotations.NotNull;
import su.nightexpress.nightcore.database.AbstractUserDataHandler;
import su.nightexpress.nightcore.database.AbstractUserManager;
import su.nightexpress.nightcore.database.DataUser;
public abstract class NightDataPlugin<U extends DataUser> extends NightPlugin /*implements UserDataHolder*/ {
//protected AbstractUserDataHandler<NexDataPlugin<U>, U> dataHandler;
//protected AbstractUserManager<NexDataPlugin<U>, U> userManager;
@Override
protected void loadManagers() {
super.loadManagers();
this.getUserManager().loadOnlineUsers();
}
@Override
protected void unloadManagers() {
super.unloadManagers();
this.getUserManager().shutdown();
this.getData().shutdown();
}
@NotNull
public abstract AbstractUserDataHandler<? extends NightDataPlugin<U>, U> getData();
@NotNull
public abstract AbstractUserManager<? extends NightDataPlugin<U>, U> getUserManager();
}
@@ -0,0 +1,180 @@
package su.nightexpress.nightcore;
import org.bukkit.event.HandlerList;
import org.bukkit.plugin.java.JavaPlugin;
import org.jetbrains.annotations.NotNull;
import su.nightexpress.nightcore.command.CommandManager;
import su.nightexpress.nightcore.command.api.NightPluginCommand;
import su.nightexpress.nightcore.config.FileConfig;
import su.nightexpress.nightcore.config.PluginDetails;
import su.nightexpress.nightcore.language.LangManager;
import su.nightexpress.nightcore.menu.api.Menu;
import su.nightexpress.nightcore.menu.impl.AbstractMenu;
import su.nightexpress.nightcore.util.Lists;
import su.nightexpress.nightcore.util.Plugins;
import su.nightexpress.nightcore.util.Reflex;
import su.nightexpress.nightcore.util.Version;
import su.nightexpress.nightcore.util.wrapper.UniPermission;
import java.util.function.Predicate;
public abstract class NightPlugin extends JavaPlugin implements NightCorePlugin {
protected LangManager langManager;
protected CommandManager commandManager;
protected FileConfig config;
protected PluginDetails details;
private boolean isEngine;
public final boolean isEngine() {
return this.isEngine;
}
@Override
public void onEnable() {
long loadTook = System.currentTimeMillis();
this.isEngine = this instanceof NightCore;
if (!this.isEngine()) {
Plugins.CORE.addChildren(this);
}
Version version = Version.getCurrent();
if (version == Version.UNKNOWN) {
this.warn("=".repeat(35));
this.warn("WARNING: You're running an unsupported server version!");
this.warn("Expect bugs and broken features.");
this.warn("=".repeat(35));
}
else if (version.isDeprecated()) {
this.warn("=".repeat(35));
this.warn("WARNING: You're running an outdated/deprecated server version (" + Version.getCurrent().getLocalized() + ")!");
this.warn("Support for this version will be dropped soon.");
this.warn("Please, upgrade your server to at least " + Lists.next(Version.getCurrent(), Predicate.not(Version::isDeprecated)).getLocalized() + ".");
this.warn("=".repeat(35));
}
this.loadManagers();
this.info("Plugin loaded in " + (System.currentTimeMillis() - loadTook) + " ms!");
}
@Override
public void onDisable() {
this.unloadManagers();
}
public final void reload() {
if (this.isEngine()) {
this.setupConfig();
this.setupLanguage();
return;
}
this.unloadManagers();
this.loadManagers();
}
/*@Override
public final void reloadConfig() {
this.getConfig().reload();
this.loadConfig();
}
public final void reloadLang() {
this.getLang().reload();
this.loadLang();
}*/
@Override
@NotNull
public final FileConfig getConfig() {
return this.config;
}
@NotNull
public final FileConfig getLang() {
return this.getLangManager().getConfig();
}
@NotNull
@Override
public PluginDetails getDetails() {
return this.details == null ? this.getDefaultDetails() : this.details;
}
@NotNull
protected abstract PluginDetails getDefaultDetails();
protected void setupConfig() {
this.config = FileConfig.loadOrExtract(this, "config.yml");
this.details = PluginDetails.read(this);
if (this.getDetails().getConfigClass() != null) {
this.getConfig().initializeOptions(this.getDetails().getConfigClass());
}
}
protected void setupLanguage() {
this.langManager = new LangManager(this);
this.langManager.setup();
if (this.getDetails().getLangClass() != null) {
this.getLangManager().loadEntries(this.getDetails().getLangClass());
}
}
protected void setupPermissions() {
Class<?> clazz = this.getDetails().getPermissionsClass();
if (clazz == null) return;
Reflex.getFields(clazz, UniPermission.class).forEach(permission -> {
if (this.getPluginManager().getPermission(permission.getName()) == null) {
this.getPluginManager().addPermission(permission);
}
});
}
protected void setupCommands() {
this.commandManager = new CommandManager(this);
this.commandManager.setup();
}
protected void loadManagers() {
this.setupConfig(); // Load configuration.
this.setupLanguage(); // Load language.
this.setupPermissions(); // Register plugin permissions.
this.setupCommands(); // Register plugin commands.
this.enable(); // Load the plugin.
this.getConfig().saveChanges();
this.getLang().saveChanges();
}
protected void unloadManagers() {
this.getScheduler().cancelTasks(this); // Stop all plugin tasks.
this.disable();
HandlerList.unregisterAll(this); // Unregister all plugin listeners.
AbstractMenu.PLAYER_MENUS.values().forEach(Menu::close); // Close all GUIs.
this.getCommandManager().shutdown();
this.getLangManager().shutdown();
}
@NotNull
public final NightPluginCommand getBaseCommand() {
return this.getCommandManager().getMainCommand();
}
@NotNull
public final LangManager getLangManager() {
return this.langManager;
}
@NotNull
public final CommandManager getCommandManager() {
return this.commandManager;
}
}
@@ -0,0 +1,74 @@
package su.nightexpress.nightcore.command;
import org.bukkit.Bukkit;
import org.bukkit.World;
import org.jetbrains.annotations.NotNull;
import su.nightexpress.nightcore.util.Colorizer;
import su.nightexpress.nightcore.util.NumberUtil;
import java.util.function.Function;
public class CommandFlag<T> {
public static final char PREFIX = '-';
private final String name;
private final Function<String, T> parser;
public CommandFlag(@NotNull String name, @NotNull Function<String, T> parser) {
this.name = name;
this.parser = parser;
}
@NotNull
public static CommandFlag<World> worldFlag(@NotNull String name) {
return new CommandFlag<>(name, Bukkit::getWorld);
}
@NotNull
public static CommandFlag<String> stringFlag(@NotNull String name) {
return new CommandFlag<>(name, Function.identity());
}
@NotNull
public static CommandFlag<String> textFlag(@NotNull String name) {
return new CommandFlag<>(name, Colorizer::apply);
}
@NotNull
public static CommandFlag<Integer> intFlag(@NotNull String name) {
return new CommandFlag<>(name, str -> NumberUtil.getAnyInteger(str, 0));
}
@NotNull
public static CommandFlag<Double> doubleFlag(@NotNull String name) {
return new CommandFlag<>(name, str -> NumberUtil.getAnyDouble(str, 0D));
}
@NotNull
public static CommandFlag<Boolean> booleanFlag(@NotNull String name) {
return new CommandFlag<>(name, str -> true);
}
@NotNull
public String getName() {
return name;
}
@NotNull
public String getNamePrefixed() {
return PREFIX + this.getName();
}
@NotNull
public Function<String, T> getParser() {
return parser;
}
@Override
public String toString() {
return "CommandFlag{" +
"name='" + name + '\'' +
'}';
}
}
@@ -0,0 +1,89 @@
package su.nightexpress.nightcore.command;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import su.nightexpress.nightcore.NightCorePlugin;
import su.nightexpress.nightcore.command.api.NightPluginCommand;
import su.nightexpress.nightcore.manager.SimpleManager;
import su.nightexpress.nightcore.command.base.HelpSubCommand;
import su.nightexpress.nightcore.command.impl.BaseCommand;
import su.nightexpress.nightcore.util.CommandUtil;
import su.nightexpress.nightcore.util.Lists;
import java.util.HashSet;
import java.util.Set;
public class CommandManager extends SimpleManager<NightCorePlugin> {
private final Set<NightPluginCommand> commands;
private BaseCommand mainCommand;
public CommandManager(@NotNull NightCorePlugin plugin) {
super(plugin);
this.commands = new HashSet<>();
}
@Override
public void onLoad() {
String[] aliases = this.plugin.getCommandAliases();
if (aliases == null || aliases.length == 0) {
this.plugin.error("Could not register plugin commands!");
return;
}
// Create main plugin command and attach help sub-command as a default executor.
this.mainCommand = new BaseCommand(this.plugin);
this.mainCommand.addDefaultCommand(new HelpSubCommand(this.plugin));
// Register main command as a bukkit command.
this.registerCommand(this.mainCommand);
}
@Override
public void onShutdown() {
for (NightPluginCommand command : new HashSet<>(this.getCommands())) {
this.unregisterCommand(command);
command.getChildrens().clear();
}
this.getCommands().clear();
}
@NotNull
public Set<NightPluginCommand> getCommands() {
return this.commands;
}
@NotNull
public BaseCommand getMainCommand() {
return this.mainCommand;
}
@Nullable
public NightPluginCommand getCommand(@NotNull String alias) {
return this.getCommands().stream()
.filter(command -> Lists.contains(command.getAliases(), alias))
.findFirst().orElse(null);
}
public void registerCommand(@NotNull NightPluginCommand command) {
if (this.commands.add(command)) {
CommandUtil.register(this.plugin, command);
}
}
public boolean unregisterCommand(@NotNull String alias) {
NightPluginCommand command = this.getCommand(alias);
if (command != null) {
return this.unregisterCommand(command);
}
return false;
}
public boolean unregisterCommand(@NotNull NightPluginCommand command) {
if (this.commands.remove(command)) {
return CommandUtil.unregister(command.getAliases()[0]);
}
return false;
}
}
@@ -0,0 +1,79 @@
package su.nightexpress.nightcore.command;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import su.nightexpress.nightcore.util.NumberUtil;
import java.util.HashMap;
import java.util.Map;
public class CommandResult {
private final String label;
private final String[] args;
private final Map<CommandFlag<?>, String> flags;
public CommandResult(@NotNull String label, String[] args, @NotNull Map<CommandFlag<?>, StringBuilder> flags) {
this.label = label;
this.flags = new HashMap<>();
this.args = args;
flags.forEach((flag, content) -> this.flags.put(flag, content.toString()));
}
public int length() {
return this.args.length;
}
@NotNull
public String getArg(int index) {
return this.getArgs()[index];
}
@NotNull
public String getArg(int index, @NotNull String def) {
if (index >= this.length()) return def;
return this.getArgs()[index];
}
public int getInt(int index, int def) {
return NumberUtil.getAnyInteger(this.getArg(index, ""), def);
}
public double getDouble(int index, double def) {
return NumberUtil.getAnyDouble(this.getArg(index, ""), def);
}
public boolean hasFlag(@NotNull CommandFlag<?> flag) {
return this.getFlags().containsKey(flag);
}
@Nullable
public <T> T getFlag(@NotNull CommandFlag<T> flag) {
String value = this.getFlags().get(flag);
if (value == null) return null;
return flag.getParser().apply(value);
}
@NotNull
public <T> T getFlag(@NotNull CommandFlag<T> flag, @NotNull T def) {
T value = this.getFlag(flag);
return value == null ? def : value;
}
@NotNull
public String getLabel() {
return label;
}
public String[] getArgs() {
return args;
}
@NotNull
public Map<CommandFlag<?>, String> getFlags() {
return flags;
}
}
@@ -0,0 +1,99 @@
package su.nightexpress.nightcore.command.api;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.permissions.Permission;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import su.nightexpress.nightcore.command.CommandFlag;
import su.nightexpress.nightcore.language.entry.LangString;
import su.nightexpress.nightcore.language.legacy.LegacyLangString;
import su.nightexpress.nightcore.util.placeholder.Placeholder;
import java.util.Collection;
import java.util.List;
public interface NightCommand extends Placeholder {
@NotNull List<String> getTab(@NotNull Player player, int arg, @NotNull String[] args);
void execute(@NotNull CommandSender sender, @NotNull String label, @NotNull String[] args);
void addChildren(@NotNull NightCommand children);
void removeChildren(@NotNull String alias);
default boolean hasPermission(@NotNull CommandSender sender) {
return this.getPermission() == null || sender.hasPermission(this.getPermission());
}
@NotNull
default String getLabelWithParents() {
StringBuilder builder = new StringBuilder();
NightCommand parent = this.getParent();
while (parent != null) {
builder.insert(0, parent.getAliases()[0] + " ");
parent = parent.getParent();
}
builder.append(this.getAliases()[0]);
return builder.toString();
}
@Nullable NightCommand getParent();
void setParent(@Nullable NightCommand parent);
@Nullable NightCommand getChildren(@NotNull String alias);
@NotNull Collection<NightCommand> getChildrens();
@NotNull String[] getAliases();
@Nullable String getPermission();
default void setPermission(@Nullable Permission permission) {
this.setPermission(permission == null ? null : permission.getName());
}
void setPermission(@Nullable String permission);
@Nullable CommandFlag<?> getFlag(@NotNull String name);
@NotNull Collection<CommandFlag<?>> getFlags();
default void addFlag(@NotNull CommandFlag<?>... flags) {
for (CommandFlag<?> flag : flags) this.addFlag(flag);
}
void addFlag(@NotNull CommandFlag<?> flag);
@NotNull String getUsage();
@Deprecated
default void setUsage(@NotNull LegacyLangString string) {
this.setUsage(string.getString());
}
default void setUsage(@NotNull LangString string) {
this.setUsage(string.getString());
}
void setUsage(@NotNull String usage);
@NotNull String getDescription();
@Deprecated
default void setDescription(@NotNull LegacyLangString string) {
this.setDescription(string.getString());
}
default void setDescription(@NotNull LangString string) {
this.setDescription(string.getString());
}
void setDescription(@NotNull String description);
boolean isPlayerOnly();
void setPlayerOnly(boolean playerOnly);
}
@@ -0,0 +1,19 @@
package su.nightexpress.nightcore.command.api;
import org.bukkit.command.Command;
import org.bukkit.command.TabExecutor;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public interface NightPluginCommand extends NightCommand, TabExecutor {
@Nullable NightCommand getDefaultCommand();
void addDefaultCommand(@NotNull NightCommand command);
Command getBackend();
void setBackend(@NotNull Command backend);
//@NotNull NightCommand findChildren(@NotNull String[] args);
}
@@ -0,0 +1,39 @@
package su.nightexpress.nightcore.command.base;
import org.bukkit.command.CommandSender;
import org.jetbrains.annotations.NotNull;
import su.nightexpress.nightcore.NightCorePlugin;
import su.nightexpress.nightcore.command.impl.AbstractCommand;
import su.nightexpress.nightcore.command.CommandResult;
import su.nightexpress.nightcore.command.api.NightCommand;
import su.nightexpress.nightcore.core.CoreLang;
import su.nightexpress.nightcore.util.Placeholders;
public class HelpSubCommand extends AbstractCommand<NightCorePlugin> {
public HelpSubCommand(@NotNull NightCorePlugin plugin) {
super(plugin, new String[]{"help"});
this.setDescription(CoreLang.COMMAND_HELP_DESC);
}
@Override
protected void onExecute(@NotNull CommandSender sender, @NotNull CommandResult result) {
NightCommand parent = this.getParent();
if (parent == null) return;
if (!parent.hasPermission(sender)) {
this.errorPermission(sender);
return;
}
CoreLang.COMMAND_HELP_LIST.getMessage()
.replace(Placeholders.GENERIC_NAME, this.plugin.getNameLocalized())
.replace(Placeholders.GENERIC_ENTRY, list -> {
parent.getChildrens().forEach(children -> {
if (!children.hasPermission(sender)) return;
list.add(children.replacePlaceholders().apply(CoreLang.COMMAND_HELP_ENTRY.getString()));
});
}).send(sender);
}
}
@@ -0,0 +1,27 @@
package su.nightexpress.nightcore.command.base;
import org.bukkit.command.CommandSender;
import org.bukkit.permissions.Permission;
import org.jetbrains.annotations.NotNull;
import su.nightexpress.nightcore.NightCorePlugin;
import su.nightexpress.nightcore.command.CommandResult;
import su.nightexpress.nightcore.command.impl.AbstractCommand;
import su.nightexpress.nightcore.core.CoreLang;
public class ReloadSubCommand extends AbstractCommand<NightCorePlugin> {
public ReloadSubCommand(@NotNull NightCorePlugin plugin, @NotNull Permission permission) {
this(plugin, permission.getName());
}
public ReloadSubCommand(@NotNull NightCorePlugin plugin, @NotNull String permission) {
super(plugin, new String[]{"reload"}, permission);
this.setDescription(CoreLang.COMMAND_RELOAD_DESC);
}
@Override
protected void onExecute(@NotNull CommandSender sender, @NotNull CommandResult result) {
this.plugin.reload();
CoreLang.COMMAND_RELOAD_DONE.getMessage().send(sender);
}
}
@@ -0,0 +1,234 @@
package su.nightexpress.nightcore.command.impl;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.permissions.Permission;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import su.nightexpress.nightcore.NightCorePlugin;
import su.nightexpress.nightcore.command.CommandFlag;
import su.nightexpress.nightcore.command.CommandResult;
import su.nightexpress.nightcore.command.api.NightCommand;
import su.nightexpress.nightcore.core.CoreLang;
import su.nightexpress.nightcore.core.CorePerms;
import su.nightexpress.nightcore.util.Placeholders;
import su.nightexpress.nightcore.util.placeholder.PlaceholderMap;
import java.util.*;
import java.util.stream.Stream;
public abstract class AbstractCommand<P extends NightCorePlugin> implements NightCommand {
protected final P plugin;
private final String[] aliases;
private final Map<String, NightCommand> childrens;
private final Map<String, CommandFlag<?>> commandFlags;
private final PlaceholderMap placeholderMap;
private NightCommand parent;
private String permission;
private String usage;
private String description;
private boolean playerOnly;
public AbstractCommand(@NotNull P plugin, @NotNull String[] aliases) {
this(plugin, aliases, (String) null);
}
public AbstractCommand(@NotNull P plugin, @NotNull String[] aliases, @Nullable Permission permission) {
this(plugin, aliases, permission == null ? null : permission.getName());
}
public AbstractCommand(@NotNull P plugin, @NotNull String[] aliases, @Nullable String permission) {
this.plugin = plugin;
this.aliases = Stream.of(aliases).map(String::toLowerCase).toArray(String[]::new);
this.permission = permission;
this.childrens = new TreeMap<>();
this.commandFlags = new HashMap<>();
this.placeholderMap = new PlaceholderMap()
.add(Placeholders.COMMAND_DESCRIPTION, this::getDescription)
.add(Placeholders.COMMAND_USAGE, this::getUsage)
.add(Placeholders.COMMAND_LABEL, this::getLabelWithParents);
}
@Override
@NotNull
public PlaceholderMap getPlaceholders() {
return this.placeholderMap;
}
protected abstract void onExecute(@NotNull CommandSender sender, @NotNull CommandResult result);
@NotNull
public List<String> getTab(@NotNull Player player, int arg, @NotNull String[] args) {
if (player.hasPermission(CorePerms.COMMAND_FLAGS)) {
return this.getFlags().stream().map(CommandFlag::getNamePrefixed).toList();
}
return Collections.emptyList();
}
@Override
public final void execute(@NotNull CommandSender sender, @NotNull String label, @NotNull String[] args) {
if (this.isPlayerOnly() && !(sender instanceof Player)) {
this.errorSender(sender);
return;
}
if (!this.hasPermission(sender)) {
this.errorPermission(sender);
return;
}
List<String> cleanArgs = new ArrayList<>();
Map<CommandFlag<?>, StringBuilder> flagContent = new HashMap<>();
CommandFlag<?> lastFlag = null;
for (String arg : args) {
CommandFlag<?> found = arg.charAt(0) == CommandFlag.PREFIX ? this.getFlag(arg.substring(1)) : null;
if (found != null) {
flagContent.put(found, new StringBuilder());
lastFlag = found;
}
else if (lastFlag != null) {
StringBuilder builder = flagContent.get(lastFlag);
if (!builder.isEmpty()) builder.append(" ");
builder.append(arg);
}
else {
cleanArgs.add(arg);
}
}
if (!sender.hasPermission(CorePerms.COMMAND_FLAGS)) {
flagContent.clear();
}
CommandResult result = new CommandResult(label, cleanArgs.toArray(new String[0]), flagContent);
this.onExecute(sender, result);
}
public final void addChildren(@NotNull NightCommand children) {
if (children.getParent() != null) return;
Stream.of(children.getAliases()).forEach(alias -> {
this.childrens.put(alias, children);
});
children.setParent(this);
}
@Override
public final void removeChildren(@NotNull String alias) {
this.childrens.keySet().removeIf(key -> key.equalsIgnoreCase(alias));
}
@Override
@Nullable
public NightCommand getParent() {
return parent;
}
@Override
public void setParent(@Nullable NightCommand parent) {
this.parent = parent;
}
@Override
@Nullable
public final NightCommand getChildren(@NotNull String alias) {
return this.childrens.get(alias);
}
@Override
@NotNull
public Collection<NightCommand> getChildrens() {
return new HashSet<>(this.childrens.values());
}
@Override
@NotNull
public final String[] getAliases() {
return this.aliases;
}
@Override
@Nullable
public final String getPermission() {
return this.permission;
}
@Override
public void setPermission(@Nullable String permission) {
this.permission = permission;
}
@Override
@Nullable
public CommandFlag<?> getFlag(@NotNull String name) {
return this.commandFlags.get(name.toLowerCase());
}
@Override
public void addFlag(@NotNull CommandFlag<?> flag) {
this.commandFlags.put(flag.getName(), flag);
}
@Override
@NotNull
public Collection<CommandFlag<?>> getFlags() {
return this.commandFlags.values();
}
@Override
@NotNull
public String getUsage() {
return this.usage == null ? "" : this.usage;
}
@Override
public void setUsage(@NotNull String usage) {
this.usage = usage;
}
@Override
@NotNull
public String getDescription() {
return this.description == null ? "" : this.description;
}
@Override
public void setDescription(@NotNull String description) {
this.description = description;
}
@Override
public boolean isPlayerOnly() {
return this.playerOnly;
}
@Override
public void setPlayerOnly(boolean playerOnly) {
this.playerOnly = playerOnly;
}
protected final void errorUsage(@NotNull CommandSender sender) {
CoreLang.ERROR_COMMAND_USAGE.getMessage().replace(this.replacePlaceholders()).send(sender);
}
protected final void errorPermission(@NotNull CommandSender sender) {
CoreLang.ERROR_NO_PERMISSION.getMessage().send(sender);
}
protected final void errorPlayer(@NotNull CommandSender sender) {
CoreLang.ERROR_INVALID_PLAYER.getMessage().send(sender);
}
protected final void errorSender(@NotNull CommandSender sender) {
CoreLang.ERROR_COMMAND_PLAYER_ONLY.getMessage().send(sender);
}
protected final void errorNumber(@NotNull CommandSender sender, @NotNull String from) {
CoreLang.ERROR_INVALID_NUMBER.getMessage().replace(Placeholders.GENERIC_VALUE, from).send(sender);
}
}
@@ -0,0 +1,18 @@
package su.nightexpress.nightcore.command.impl;
import org.bukkit.command.CommandSender;
import org.jetbrains.annotations.NotNull;
import su.nightexpress.nightcore.NightCorePlugin;
import su.nightexpress.nightcore.command.CommandResult;
public class BaseCommand extends PluginCommand<NightCorePlugin> {
public BaseCommand(@NotNull NightCorePlugin plugin) {
super(plugin, plugin.getCommandAliases());
}
@Override
protected void onExecute(@NotNull CommandSender sender, @NotNull CommandResult result) {
}
}
@@ -0,0 +1,116 @@
package su.nightexpress.nightcore.command.impl;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.permissions.Permission;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import su.nightexpress.nightcore.NightCorePlugin;
import su.nightexpress.nightcore.command.api.NightCommand;
import su.nightexpress.nightcore.command.api.NightPluginCommand;
import su.nightexpress.nightcore.util.Lists;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public abstract class PluginCommand<P extends NightCorePlugin> extends AbstractCommand<P> implements NightPluginCommand {
private Command backend;
private NightCommand defaultCommand;
public PluginCommand(@NotNull P plugin, @NotNull String[] aliases) {
this(plugin, aliases, (String) null);
}
public PluginCommand(@NotNull P plugin, @NotNull String[] aliases, @Nullable Permission permission) {
super(plugin, aliases, permission);
}
public PluginCommand(@NotNull P plugin, @NotNull String[] aliases, @Nullable String permission) {
super(plugin, aliases, permission);
}
@Override
public void addDefaultCommand(@NotNull NightCommand command) {
this.addChildren(command);
this.defaultCommand = command;
}
@Override
@Nullable
public NightCommand getDefaultCommand() {
return defaultCommand;
}
@Override
public Command getBackend() {
return backend;
}
@Override
public void setBackend(@NotNull Command backend) {
this.backend = backend;
}
//@Override
@NotNull
private NightCommand findChildren(@NotNull String[] args) {
NightCommand command = this;//.defaultCommand;
int childCount = 0;
while (args.length > childCount) {
NightCommand child = command.getChildren(args[childCount++]);
if (child == null) break;
command = child;
}
return command;
}
/*private int countChildren(@NotNull String[] args) {
AbstractCommand<P> command = this;
int childCount = 0;
while (args.length > childCount) {
AbstractCommand<P> child = command.getChildren(args[childCount]);
if (child == null) break;
command = child;
childCount++;
}
return childCount;
}*/
@Override
public boolean onCommand(@NotNull CommandSender sender, @NotNull Command cmd, @NotNull String label, String[] args) {
NightCommand command = this.findChildren(args);
if (command instanceof NightPluginCommand pluginCommand) {
if (pluginCommand.getDefaultCommand() != null) {
command = pluginCommand.getDefaultCommand();
}
}
command.execute(sender, label, args);
return true;
}
@Override
public List<String> onTabComplete(@NotNull CommandSender sender, @NotNull Command cmd,
@NotNull String label, String[] args) {
if (!(sender instanceof Player player) || args.length == 0) return Collections.emptyList();
NightCommand command = this.findChildren(args);
if (!command.hasPermission(sender)) return Collections.emptyList();
List<String> list = new ArrayList<>();
if (!command.getChildrens().isEmpty()) {
command.getChildrens().stream().filter(child -> child.hasPermission(sender))
.forEach(child -> list.addAll(Arrays.asList(child.getAliases())));
}
else {
list.addAll(command.getTab(player, command.equals(this) ? (args.length) : (args.length - 1), args));
}
return Lists.getSequentialMatches(list, args[args.length - 1]);
}
}
@@ -0,0 +1,52 @@
package su.nightexpress.nightcore.command.impl;
import org.bukkit.command.*;
import org.bukkit.plugin.Plugin;
import org.jetbrains.annotations.NotNull;
import su.nightexpress.nightcore.command.api.NightPluginCommand;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class WrappedCommand extends Command implements PluginIdentifiableCommand {
protected final Plugin plugin;
protected final CommandExecutor executor;
protected final TabCompleter tabCompleter;
public WrappedCommand(@NotNull Plugin plugin, @NotNull NightPluginCommand command) {
this(plugin, command, command, command.getAliases(), command.getDescription(), command.getUsage());
this.setPermission(command.getPermission());
}
public WrappedCommand(@NotNull Plugin plugin,
@NotNull CommandExecutor executor,
@NotNull TabCompleter tabCompleter,
@NotNull String[] aliases,
@NotNull String description,
@NotNull String usage) {
super(aliases[0], description, usage, Arrays.asList(aliases));
this.plugin = plugin;
this.executor = executor;
this.tabCompleter = tabCompleter;
}
@Override
@NotNull
public Plugin getPlugin() {
return this.plugin;
}
@Override
public boolean execute(@NotNull CommandSender sender, @NotNull String label, @NotNull String[] args) {
return this.executor.onCommand(sender, this, label, args);
}
@Override
@NotNull
public List<String> tabComplete(@NotNull CommandSender sender, @NotNull String alias, @NotNull String[] args) {
List<String> list = this.tabCompleter.onTabComplete(sender, this, alias, args);
return list == null ? Collections.emptyList() : list;
}
}
@@ -0,0 +1,301 @@
package su.nightexpress.nightcore.config;
import org.bukkit.inventory.ItemStack;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import su.nightexpress.nightcore.util.TriFunction;
import su.nightexpress.nightcore.util.wrapper.UniParticle;
import su.nightexpress.nightcore.util.wrapper.UniSound;
import java.util.*;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collectors;
public class ConfigValue<T> {
private final String path;
private final T defaultValue;
private final String[] description;
private final Reader<T> reader;
private final Writer<T> writer;
private T value;
public ConfigValue(@NotNull String path,
@NotNull Reader<T> reader,
@NotNull Writer<T> writer,
@NotNull T defaultValue,
@Nullable String... description) {
this.path = path;
this.description = description == null ? new String[0] : description;
this.reader = reader;
this.writer = writer;
this.defaultValue = defaultValue;
}
@NotNull
public static <T> ConfigValue<T> create(@NotNull String path,
@NotNull Reader<T> reader,
@NotNull Writer<T> writer,
@NotNull T defaultValue,
@Nullable String... description) {
return new ConfigValue<>(path, reader, writer, defaultValue, description);
}
@NotNull
public static <T> ConfigValue<T> create(@NotNull String path,
@NotNull Reader<T> reader,
@NotNull Writer<T> writer,
@NotNull Supplier<T> defaultValue,
@Nullable String... description) {
return create(path, reader, writer, defaultValue.get(), description);
}
@NotNull
public static <T> ConfigValue<T> create(@NotNull String path, @NotNull Reader<T> reader, @NotNull T defaultValue, @Nullable String... description) {
return create(path, reader, FileConfig::set, defaultValue, description);
}
@NotNull
public static <T> ConfigValue<T> create(@NotNull String path, @NotNull Reader<T> reader, @NotNull Supplier<T> defaultValue, @Nullable String... description) {
return create(path, reader, FileConfig::set, defaultValue, description);
}
@NotNull
public static ConfigValue<Boolean> create(@NotNull String path, boolean defaultValue, @Nullable String... description) {
return create(path, FileConfig::getBoolean, defaultValue, description);
}
@NotNull
public static ConfigValue<Integer> create(@NotNull String path, int defaultValue, @Nullable String... description) {
return create(path, FileConfig::getInt, defaultValue, description);
}
@NotNull
public static ConfigValue<int[]> create(@NotNull String path, int[] defaultValue, @Nullable String... description) {
return create(path, FileConfig::getIntArray, FileConfig::setIntArray, defaultValue, description);
}
@NotNull
public static ConfigValue<Double> create(@NotNull String path, double defaultValue, @Nullable String... description) {
return create(path, FileConfig::getDouble, defaultValue, description);
}
@NotNull
public static ConfigValue<Long> create(@NotNull String path, long defaultValue, @Nullable String... description) {
return create(path, FileConfig::getLong, defaultValue, description);
}
@NotNull
public static ConfigValue<String> create(@NotNull String path, @NotNull String defaultValue, @Nullable String... description) {
return create(path, FileConfig::getString, defaultValue, description);
}
@NotNull
public static ConfigValue<String[]> create(@NotNull String path, @NotNull String[] defaultValue, @Nullable String... description) {
return create(path, FileConfig::getStringArray, FileConfig::setStringArray, defaultValue, description);
}
@NotNull
public static ConfigValue<List<String>> create(@NotNull String path, @NotNull List<String> defaultValue, @Nullable String... description) {
return create(path, (cfg, path1, def) -> cfg.getStringList(path1), defaultValue, description);
}
@NotNull
public static ConfigValue<Set<String>> create(@NotNull String path, @NotNull Set<String> defaultValue, @Nullable String... description) {
return create(path, (cfg, path1, def) -> cfg.getStringSet(path1), defaultValue, description);
}
@NotNull
public static ConfigValue<ItemStack> create(@NotNull String path, @NotNull ItemStack defaultValue, @Nullable String... description) {
return create(path, FileConfig::getItem, FileConfig::setItem, defaultValue, description);
}
@NotNull
public static ConfigValue<UniSound> create(@NotNull String path, @NotNull UniSound defaultValue, @Nullable String... description) {
Reader<UniSound> reader = (cfg, path1, def) -> UniSound.read(cfg, path1);
Writer<UniSound> writer = (cfg, path1, obj) -> obj.write(cfg, path1);
return create(path, reader, writer, defaultValue, description);
}
@NotNull
public static ConfigValue<UniParticle> create(@NotNull String path, @NotNull UniParticle defaultValue, @Nullable String... description) {
Reader<UniParticle> reader = (cfg, path1, def) -> UniParticle.read(cfg, path1);
Writer<UniParticle> writer = (cfg, path1, obj) -> obj.write(cfg, path1);
return create(path, reader, writer, defaultValue, description);
}
@NotNull
public static <E extends Enum<E>> ConfigValue<E> create(@NotNull String path, @NotNull Class<E> clazz, @NotNull E defaultValue, @Nullable String... description) {
Reader<E> reader = (cfg, path1, def) -> cfg.getEnum(path1, clazz, def);
Writer<E> writer = (cfg, path1, obj) -> cfg.set(path1, obj.name());
return create(path, reader, writer, defaultValue, description);
}
@NotNull
public static <V> ConfigValue<Set<V>> forSet(@NotNull String path,
@NotNull Function<String, V> reader,
@NotNull Writer<Set<V>> writer,
@NotNull Supplier<Set<V>> defaultValue,
@Nullable String... description) {
return forSet(path, reader, writer, defaultValue.get(), description);
}
@NotNull
public static <V> ConfigValue<Set<V>> forSet(@NotNull String path,
@NotNull Function<String, V> valFun,
@NotNull Writer<Set<V>> writer,
@NotNull Set<V> defaultValue,
@Nullable String... description) {
Reader<Set<V>> reader = (cfg, path1, def) -> cfg.getStringSet(path1).stream().map(valFun).filter(Objects::nonNull).collect(Collectors.toCollection(HashSet::new));
return create(path, reader, writer, defaultValue, description);
}
@NotNull
public static <K, V> ConfigValue<Map<K, V>> forMap(@NotNull String path,
@NotNull Function<String, K> keyFun,
@NotNull TriFunction<FileConfig, String, String, V> valFun,
@NotNull Writer<Map<K, V>> writer,
@NotNull Supplier<Map<K, V>> defaultValue,
@Nullable String... description) {
return forMap(path, keyFun, valFun, writer, defaultValue.get(), description);
}
@NotNull
public static <K, V> ConfigValue<Map<K, V>> forMap(@NotNull String path,
@NotNull Function<String, K> keyFun,
@NotNull TriFunction<FileConfig, String, String, V> valFun,
@NotNull Writer<Map<K, V>> writer,
@NotNull Map<K, V> defaultValue,
@Nullable String... description) {
return forMap(path, keyFun, valFun, HashMap::new, writer, defaultValue, description);
}
@NotNull
public static <K, V> ConfigValue<TreeMap<K, V>> forTreeMap(@NotNull String path,
@NotNull Function<String, K> keyFun,
@NotNull TriFunction<FileConfig, String, String, V> valFun,
@NotNull Writer<TreeMap<K, V>> writer,
@NotNull Supplier<TreeMap<K, V>> defaultValue, @Nullable String... description) {
return forTreeMap(path, keyFun, valFun, writer, defaultValue.get(), description);
}
@NotNull
public static <K, V> ConfigValue<TreeMap<K, V>> forTreeMap(@NotNull String path,
@NotNull Function<String, K> keyFun,
@NotNull TriFunction<FileConfig, String, String, V> valFun,
@NotNull Writer<TreeMap<K, V>> writer,
@NotNull TreeMap<K, V> defaultValue, @Nullable String... description) {
return forMap(path, keyFun, valFun, TreeMap::new, writer, defaultValue, description);
}
@NotNull
public static <K, V, M extends Map<K, V>> ConfigValue<M> forMap(@NotNull String path,
@NotNull Function<String, K> keyFun,
@NotNull TriFunction<FileConfig, String, String, V> valFun,
@NotNull Supplier<M> mapSupplier,
@NotNull Writer<M> writer,
@NotNull M defaultValue, @Nullable String... description) {
Reader<M> reader = (cfg, path1, def) -> {
M map = mapSupplier.get();
for (String id : cfg.getSection(path1)) {
K key = keyFun.apply(id);
V val = valFun.apply(cfg, path1, id);
if (key == null || val == null) continue;
map.put(key, val);
}
return map;
};
return create(path, reader, writer, defaultValue, description);
}
@NotNull
public static <V> ConfigValue<Map<String, V>> forMap(@NotNull String path,
@NotNull TriFunction<FileConfig, String, String, V> function,
@NotNull Writer<Map<String, V>> writer,
@NotNull Supplier<Map<String, V>> defaultValue,
@Nullable String... description) {
return forMap(path, String::toLowerCase, function, writer, defaultValue.get(), description);
}
@NotNull
public static <V> ConfigValue<Map<String, V>> forMap(@NotNull String path,
@NotNull TriFunction<FileConfig, String, String, V> function,
@NotNull Writer<Map<String, V>> writer,
@NotNull Map<String, V> defaultValue,
@Nullable String... description) {
return forMap(path, String::toLowerCase, function, writer, defaultValue, description);
}
@NotNull
public T read(@NotNull FileConfig cfg) {
if (!cfg.contains(this.getPath())) {
this.write(cfg);
}
if (this.getDescription().length > 0 && !this.getDescription()[0].isEmpty()) {
cfg.setComments(this.getPath(), this.getDescription());
}
return (this.value = this.reader.read(cfg, this.getPath(), this.getDefaultValue()));
}
public void write(@NotNull FileConfig cfg) {
this.getWriter().write(cfg, this.getPath(), this.get());
}
public boolean remove(@NotNull FileConfig cfg) {
return cfg.remove(this.getPath());
}
@NotNull
public T get() {
return this.value == null ? this.getDefaultValue() : this.value;
}
public void set(@NotNull T value) {
this.value = value;
}
@NotNull
public String getPath() {
return path;
}
@NotNull
public String[] getDescription() {
return description;
}
@NotNull
public T getDefaultValue() {
return defaultValue;
}
@NotNull
public Reader<T> getReader() {
return reader;
}
@NotNull
public Writer<T> getWriter() {
return writer;
}
public interface Reader<T> {
@NotNull T read(@NotNull FileConfig cfg, @NotNull String path, @NotNull T def);
}
public interface Writer<T> {
void write(@NotNull FileConfig cfg, @NotNull String path, @NotNull T obj);
}
}
@@ -0,0 +1,441 @@
package su.nightexpress.nightcore.config;
import org.bukkit.*;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.InvalidConfigurationException;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.inventory.ItemFlag;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.Damageable;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.inventory.meta.LeatherArmorMeta;
import org.bukkit.inventory.meta.PotionMeta;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import su.nightexpress.nightcore.util.Version;
import su.nightexpress.nightcore.NightCorePlugin;
import su.nightexpress.nightcore.util.*;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.stream.IntStream;
public class FileConfig extends YamlConfiguration {
private final File file;
private boolean isChanged = false;
public FileConfig(@NotNull String path, @NotNull String file) {
this(new File(path, file));
}
public FileConfig(@NotNull File file) {
this.options().width(512);
FileUtil.create(file);
this.file = file;
this.reload();
}
@NotNull
public static FileConfig loadOrExtract(@NotNull NightCorePlugin plugin, @NotNull String path, @NotNull String file) {
if (!path.endsWith("/")) {
path += "/";
}
return loadOrExtract(plugin, path + file);
}
@NotNull
public static FileConfig loadOrExtract(@NotNull NightCorePlugin plugin, @NotNull String filePath) {
if (!filePath.startsWith("/")) {
filePath = "/" + filePath;
}
File file = new File(plugin.getDataFolder() + filePath);
if (FileUtil.create(file)) {
try {
InputStream input = plugin.getClass().getResourceAsStream(filePath);
if (input != null) FileUtil.copy(input, file);
}
catch (Exception ex) {
ex.printStackTrace();
}
}
return new FileConfig(file);
}
@NotNull
public static List<FileConfig> loadAll(@NotNull String path) {
return loadAll(path, false);
}
@NotNull
public static List<FileConfig> loadAll(@NotNull String path, boolean deep) {
return FileUtil.getFiles(path, deep).stream().filter(file -> file.getName().endsWith(".yml")).map(FileConfig::new).toList();
}
public void initializeOptions(@NotNull Class<?> clazz) {
initializeOptions(clazz, this);
}
public static void initializeOptions(@NotNull Class<?> clazz, @NotNull FileConfig cfg) {
for (ConfigValue<?> value : Reflex.getFields(clazz, ConfigValue.class)) {
value.read(cfg);
}
cfg.saveChanges();
}
@NotNull
public File getFile() {
return this.file;
}
public void save() {
try {
this.save(this.file);
}
catch (IOException exception) {
exception.printStackTrace();
}
}
public boolean saveChanges() {
if (!this.isChanged) return false;
this.save();
this.isChanged = false;
return true;
}
public boolean reload() {
try {
this.load(this.file);
this.isChanged = false;
return true;
}
catch (IOException | InvalidConfigurationException exception) {
exception.printStackTrace();
}
return false;
}
public boolean addMissing(@NotNull String path, @Nullable Object val) {
if (this.contains(path)) return false;
this.set(path, val);
return true;
}
@Override
public void set(@NotNull String path, @Nullable Object value) {
if (value instanceof String str) {
value = Colorizer.plain(str);
}
else if (value instanceof Collection<?> collection) {
List<Object> list = new ArrayList<>(collection);
list.replaceAll(obj -> obj instanceof String str ? Colorizer.plain(str) : obj);
value = list;
}
else if (value instanceof Location location) {
value = LocationUtil.serialize(location);
}
else if (value instanceof Enum<?> en) {
value = en.name();
}
super.set(path, value);
this.isChanged = true;
}
public void setComments(@NotNull String path, @Nullable String... comments) {
this.setComments(path, Arrays.asList(comments));
}
public void setInlineComments(@NotNull String path, @Nullable String... comments) {
this.setInlineComments(path, Arrays.asList(comments));
}
@Override
public void setComments(@NotNull String path, @Nullable List<String> comments) {
if (this.getComments(path).equals(comments)) return;
super.setComments(path, comments);
this.isChanged = true;
}
@Override
public void setInlineComments(@NotNull String path, @Nullable List<String> comments) {
super.setInlineComments(path, comments);
}
public boolean remove(@NotNull String path) {
if (!this.contains(path)) return false;
this.set(path, null);
return true;
}
@NotNull
public Set<String> getSection(@NotNull String path) {
ConfigurationSection section = this.getConfigurationSection(path);
return section == null ? Collections.emptySet() : section.getKeys(false);
}
@Override
@Nullable
public String getString(@NotNull String path) {
String str = super.getString(path);
return str == null || str.isEmpty() ? null : str;
}
@Override
@NotNull
public String getString(@NotNull String path, @Nullable String def) {
String str = super.getString(path, def);
return str == null ? "" : str;
}
@NotNull
public Set<String> getStringSet(@NotNull String path) {
return new HashSet<>(this.getStringList(path));
}
@Override
@Nullable
public Location getLocation(@NotNull String path) {
String raw = this.getString(path);
return raw == null ? null : LocationUtil.deserialize(raw);
}
public int[] getIntArray(@NotNull String path) {
return getIntArray(path, new int[0]);
}
public int[] getIntArray(@NotNull String path, int[] def) {
String str = this.getString(path);
return str == null ? def : NumberUtil.getIntArray(str);
}
public void setIntArray(@NotNull String path, int[] arr) {
if (arr == null) {
this.set(path, null);
return;
}
this.set(path, String.join(",", IntStream.of(arr).boxed().map(String::valueOf).toList()));
}
@NotNull
public String @NotNull [] getStringArray(@NotNull String path, @NotNull String[] def) {
String str = this.getString(path);
return str == null ? def : str.split(",");
}
public void setStringArray(@NotNull String path, String[] arr) {
if (arr == null) {
this.set(path, null);
return;
}
this.set(path, String.join(",", arr));
}
@Nullable
public <T extends Enum<T>> T getEnum(@NotNull String path, @NotNull Class<T> clazz) {
return StringUtil.getEnum(this.getString(path), clazz).orElse(null);
}
@NotNull
public <T extends Enum<T>> T getEnum(@NotNull String path, @NotNull Class<T> clazz, @NotNull T def) {
return StringUtil.getEnum(this.getString(path), clazz).orElse(def);
}
@NotNull
public <T extends Enum<T>> List<T> getEnumList(@NotNull String path, @NotNull Class<T> clazz) {
return this.getStringSet(path).stream().map(str -> StringUtil.getEnum(str, clazz).orElse(null))
.filter(Objects::nonNull).toList();
}
/*@NotNull
public Set<FireworkEffect> getFireworkEffects(@NotNull String path) {
Set<FireworkEffect> effects = new HashSet<>();
for (String sId : this.getSection(path)) {
String path2 = path + "." + sId + ".";
FireworkEffect.Type type = this.getEnum(path2 + "Type", FireworkEffect.Type.class);
if (type == null) continue;
boolean flicker = this.getBoolean(path2 + "Flicker");
boolean trail = this.getBoolean(path2 + "Trail");
Set<Color> colors = new HashSet<>();
for (String colorRaw : this.getStringList(path2 + "Colors")) {
colors.add(StringUtil.parseColor(colorRaw));
}
Set<Color> fadeColors = new HashSet<>();
for (String colorRaw : this.getStringList(path2 + "Fade_Colors")) {
fadeColors.add(StringUtil.parseColor(colorRaw));
}
FireworkEffect.Builder builder = FireworkEffect.builder()
.with(type).flicker(flicker).trail(trail).withColor(colors).withFade(fadeColors);
effects.add(builder.build());
}
return effects;
}*/
@NotNull
public ItemStack getItem(@NotNull String path, @Nullable ItemStack def) {
ItemStack item = this.getItem(path);
return item.getType().isAir() && def != null ? def : item;
}
@NotNull
public ItemStack getItem(@NotNull String path) {
if (!path.isEmpty() && !path.endsWith(".")) path = path + ".";
Material material = Material.getMaterial(this.getString(path + "Material", "").toUpperCase());
if (material == null || material == Material.AIR) return new ItemStack(Material.AIR);
ItemStack item = new ItemStack(material);
item.setAmount(this.getInt(path + "Amount", 1));
String headSkin = this.getString(path + "SkinURL", "");
if (!headSkin.isEmpty()) {
ItemUtil.setHeadSkin(item, headSkin);
}
else {
String headTexture = this.getString(path + "Head_Texture", "");
if (!headTexture.isEmpty()) {
ItemUtil.setSkullTexture(item, headTexture);
}
}
ItemMeta meta = item.getItemMeta();
if (meta == null) return item;
int durability = this.getInt(path + "Durability");
if (durability > 0 && meta instanceof Damageable damageable) {
damageable.setDamage(durability);
}
String name = this.getString(path + "Name");
meta.setDisplayName(name != null ? Colorizer.apply(name) : null);
meta.setLore(Colorizer.apply(this.getStringList(path + "Lore")));
for (String sKey : this.getSection(path + "Enchants")) {
Enchantment enchantment;
NamespacedKey key = NamespacedKey.minecraft(sKey.toLowerCase());
if (Version.isAtLeast(Version.V1_19_R3)) {
enchantment = Registry.ENCHANTMENT.get(key);
}
else {
enchantment = Enchantment.getByKey(key);
}
if (enchantment == null) continue;
int eLvl = this.getInt(path + "Enchants." + sKey);
if (eLvl <= 0) continue;
meta.addEnchant(enchantment, eLvl, true);
}
int model = this.getInt(path + "Custom_Model_Data");
meta.setCustomModelData(model != 0 ? model : null);
List<String> flags = this.getStringList(path + "Item_Flags");
if (flags.contains(Placeholders.WILDCARD)) {
meta.addItemFlags(ItemFlag.values());
}
else {
flags.stream().map(str -> StringUtil.getEnum(str, ItemFlag.class).orElse(null)).filter(Objects::nonNull).forEach(meta::addItemFlags);
}
String colorRaw = this.getString(path + "Color");
if (colorRaw != null && !colorRaw.isEmpty()) {
Color color = StringUtil.getColor(colorRaw);
if (meta instanceof LeatherArmorMeta armorMeta) {
armorMeta.setColor(color);
}
else if (meta instanceof PotionMeta potionMeta) {
potionMeta.setColor(color);
}
}
meta.setUnbreakable(this.getBoolean(path + "Unbreakable"));
item.setItemMeta(meta);
return item;
}
public void setItem(@NotNull String path, @Nullable ItemStack item) {
if (item == null) {
this.set(path, null);
return;
}
if (!path.endsWith(".")) path = path + ".";
this.set(path.substring(0, path.length() - 1), null);
Material material = item.getType();
this.set(path + "Material", material.name());
this.set(path + "Amount", item.getAmount() <= 1 ? null : item.getAmount());
this.set(path + "SkinURL", ItemUtil.getHeadSkin(item));
if (!this.contains(path + "SkinURL")) {
this.set(path + "Head_Texture", ItemUtil.getSkullTexture(item));
}
ItemMeta meta = item.getItemMeta();
if (meta == null) return;
if (meta instanceof Damageable damageable) {
this.set(path + "Durability", damageable.getDamage() <= 0 ? null : damageable.getDamage());
}
this.set(path + "Name", meta.getDisplayName().isEmpty() ? null : meta.getDisplayName());
this.set(path + "Lore", meta.getLore());
for (Map.Entry<Enchantment, Integer> entry : meta.getEnchants().entrySet()) {
this.set(path + "Enchants." + entry.getKey().getKey().getKey(), entry.getValue());
}
this.set(path + "Custom_Model_Data", meta.hasCustomModelData() ? meta.getCustomModelData() : null);
Color color = null;
String colorRaw = null;
if (meta instanceof PotionMeta potionMeta) {
color = potionMeta.getColor();
}
else if (meta instanceof LeatherArmorMeta armorMeta) {
color = armorMeta.getColor();
}
if (color != null) {
colorRaw = color.getRed() + "," + color.getGreen() + "," + color.getBlue();
}
this.set(path + "Color", colorRaw);
List<String> itemFlags = new ArrayList<>(meta.getItemFlags().stream().map(ItemFlag::name).toList());
this.set(path + "Item_Flags", itemFlags.isEmpty() ? null : itemFlags);
this.set(path + "Unbreakable", meta.isUnbreakable() ? true : null);
}
@Nullable
public ItemStack getItemEncoded(@NotNull String path) {
String compressed = this.getString(path);
if (compressed == null) return null;
return ItemUtil.decompress(compressed);
}
public void setItemEncoded(@NotNull String path, @Nullable ItemStack item) {
this.set(path, item == null ? null : ItemUtil.compress(item));
}
@NotNull
public ItemStack[] getItemsEncoded(@NotNull String path) {
return ItemUtil.decompress(this.getStringList(path));
}
public void setItemsEncoded(@NotNull String path, @NotNull List<ItemStack> item) {
this.set(path, ItemUtil.compress(item));
}
}
@@ -0,0 +1,122 @@
package su.nightexpress.nightcore.config;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import su.nightexpress.nightcore.NightCorePlugin;
import su.nightexpress.nightcore.language.LangManager;
import su.nightexpress.nightcore.util.text.tag.Tags;
import java.util.Locale;
public class PluginDetails {
private final String name;
private final String prefix;
private final String[] commandAliases;
private final String language;
private Class<?> configClass;
private Class<?> langClass;
private Class<?> permissionsClass;
public PluginDetails(
@NotNull String name,
@NotNull String prefix,
@NotNull String[] commandAliases,
@NotNull String language
) {
this.name = name;
this.prefix = prefix;
this.commandAliases = commandAliases;
this.language = language.toLowerCase();
}
@NotNull
public static PluginDetails create(@NotNull String name, @NotNull String[] commandAliases) {
String prefix = Tags.YELLOW.enclose(name) + Tags.DARK_GRAY.enclose(" » ") + Tags.GRAY.getFullName();
String language = Locale.getDefault().getLanguage();
return new PluginDetails(name, prefix, commandAliases, language);
}
@NotNull
public static PluginDetails read(@NotNull NightCorePlugin plugin) {
FileConfig config = plugin.getConfig();
PluginDetails defaults = plugin.getDetails();
String pluginName = ConfigValue.create("Plugin.Name", defaults.getName(),
"Localized plugin name. It's used in messages and with internal placeholders.")
.read(config);
String pluginPrefix = ConfigValue.create("Plugin.Prefix", defaults.getPrefix(),
"Plugin prefix. Used in messages."
).read(config);
String[] commandAliases = ConfigValue.create("Plugin.Command_Aliases", defaults.getCommandAliases(),
"Command names that will be registered as main plugin commands.",
"Do not leave this empty. Split multiple names with a comma.")
.read(config);
String languageCode = ConfigValue.create("Plugin.Language", defaults.getLanguage(),
"Sets the plugin language.",
"Basically it tells the plugin to use certain messages config from the '" + LangManager.DIR_LANG + "' sub-folder.",
"If specified language is not available, default one (English) will be used instead.",
"[Default is System Locale]")
.read(config);
return new PluginDetails(pluginName, pluginPrefix, commandAliases, languageCode)
.setConfigClass(defaults.getConfigClass())
.setLangClass(defaults.getLangClass())
.setPermissionsClass(defaults.getPermissionsClass());
}
@NotNull
public String getName() {
return name;
}
@NotNull
public String getPrefix() {
return prefix;
}
@NotNull
public String[] getCommandAliases() {
return commandAliases;
}
@NotNull
public String getLanguage() {
return language;
}
@Nullable
public Class<?> getConfigClass() {
return configClass;
}
public PluginDetails setConfigClass(@Nullable Class<?> configClass) {
this.configClass = configClass;
return this;
}
@Nullable
public Class<?> getLangClass() {
return langClass;
}
public PluginDetails setLangClass(@Nullable Class<?> langClass) {
this.langClass = langClass;
return this;
}
@Nullable
public Class<?> getPermissionsClass() {
return permissionsClass;
}
public PluginDetails setPermissionsClass(@Nullable Class<?> permissionsClass) {
this.permissionsClass = permissionsClass;
return this;
}
}
@@ -0,0 +1,71 @@
package su.nightexpress.nightcore.core;
import su.nightexpress.nightcore.config.ConfigValue;
import su.nightexpress.nightcore.util.text.NightMessage;
import su.nightexpress.nightcore.util.text.tag.impl.ColorTag;
import java.awt.*;
import java.util.HashMap;
import java.util.Map;
public class CoreConfig {
public static final ConfigValue<Boolean> MODERN_TEXT_PRECOMPILE_LANG = ConfigValue.create("ModernTextFormation.Precompile_Language",
true,
"When enabled, parses (deserializes) language messages to Spigot TextComponent(s) on plugin load.",
"When disabled, parses (deserializes) language texts to Spigot TextComponent(s) in runtime when sending it to player.",
"Enabling this setting is good for performance, however messages with placeholders will be recompiled in runtime anyway.",
"(Side Note) Unlike NexEngine, it does not uses regex anymore, which makes deserialization significantly faster and accurate.",
"[Default is true]");
public static final ConfigValue<Map<String, Color>> MODERN_TEXT_DEFAULT_COLORS = ConfigValue.forMap("ModernTextFormation.Default_Colors",
(cfg, path, id) -> {
try {
Color color = Color.decode(cfg.getString(path + "." + id, "#ffffff"));
NightMessage.registerTag(new ColorTag(id, color));
return color;
}
catch (Exception exception) {
exception.printStackTrace();
return Color.WHITE;
}
},
(cfg, path, map) -> map.forEach((id, value) -> cfg.set(path + "." + id, "#" + Integer.toHexString(value.getRGB()).substring(2))),
() -> {
Map<String, Color> map = new HashMap<>();
map.put("aqua", Color.CYAN);
return map;
},
"Here you can define custom colors to use it in all nightcore plugins like <aqua>Text</aqua>.",
"You can also override default ones."
);
public static final ConfigValue<Long> MENU_CLICK_COOLDOWN = ConfigValue.create("Menu.Click_Cooldown",
150L,
"Sets cooldown (in milliseconds) for player clicks in GUIs.",
"[Default is 150ms]");
public static final ConfigValue<Boolean> USER_DEBUG_ENABLED = ConfigValue.create("UserData.Debug",
false,
"Enables debug messages for user data management.",
"[Default is false]");
public static final ConfigValue<Integer> USER_CACHE_LIFETIME = ConfigValue.create("UserData.Cache.LifeTime",
300,
"Sets how long (in seconds) user data will be cached for offline users",
"until removed and needs to be loaded from the database again.",
"[Default is 300 (5 minutes)]");
public static final ConfigValue<Boolean> USER_CACHE_NAME_AND_UUID = ConfigValue.create("UserData.Cache.Names_And_UUIDs",
true,
"Sets whether or not plugin will cache player names and UUIDs.",
"This will improve database performance when checking if user exists, but will increase memory usage.",
"[Default is true]");
public static final ConfigValue<Boolean> RESPECT_PLAYER_DISPLAYNAME = ConfigValue.create("Engine.Respect_Player_DisplayName",
false,
"Sets whether or not 'Player#getDisplayName' can be used to find & get players in addition to regular 'Player#getName'.",
"This is useful if you want to use custom player nicknames in commands.",
"(Works only for nightcore based plugins.)",
"[Default is false]");
}
@@ -0,0 +1,99 @@
package su.nightexpress.nightcore.core;
import net.md_5.bungee.api.chat.ClickEvent;
import org.jetbrains.annotations.NotNull;
import su.nightexpress.nightcore.dialog.Dialog;
import su.nightexpress.nightcore.language.entry.LangItem;
import su.nightexpress.nightcore.language.entry.LangString;
import su.nightexpress.nightcore.language.entry.LangText;
import su.nightexpress.nightcore.util.Placeholders;
import static su.nightexpress.nightcore.util.Placeholders.*;
import static su.nightexpress.nightcore.language.tag.MessageTags.*;
import static su.nightexpress.nightcore.util.text.tag.Tags.*;
public class CoreLang {
public static final LangText COMMAND_HELP_LIST = LangText.of("Command.Help.List",
TAG_NO_PREFIX,
" " + YELLOW.enclose(BOLD.enclose(GENERIC_NAME)) + GRAY.enclose(" - ") + YELLOW.enclose(BOLD.enclose("Commands:")),
"",
GRAY.enclose(" " + RED.enclose(BOLD.enclose("<>")) + " - Required, " + GREEN.enclose(BOLD.enclose("[]")) + " - Optional."),
"",
GENERIC_ENTRY,
" "
);
public static final LangString COMMAND_HELP_ENTRY = LangString.of("Command.Help.Entry",
" " + YELLOW.enclose( "/" + COMMAND_LABEL) + " " + ORANGE.enclose(Placeholders.COMMAND_USAGE) + GRAY.enclose(" - " + COMMAND_DESCRIPTION)
);
public static final LangString COMMAND_HELP_DESC = LangString.of("Command.Help.Desc", "Show help page.");
public static final LangString COMMAND_CHECKPERM_DESC = LangString.of("Command.CheckPerm.Desc", "Print player permission info.");
public static final LangString COMMAND_CHECKPERM_USAGE = LangString.of("Command.CheckPerm.Usage", "<player>");
public static final LangString COMMAND_RELOAD_DESC = LangString.of("Command.Reload.Desc", "Reload the plugin.");
public static final LangText COMMAND_RELOAD_DONE = LangText.of("Command.Reload.Done", "Plugin " + GREEN.enclose("reloaded") + "!");
public static final LangString TIME_DAY = LangString.of("Time.Day", GENERIC_AMOUNT + "d.");
public static final LangString TIME_HOUR = LangString.of("Time.Hour", GENERIC_AMOUNT + "h.");
public static final LangString TIME_MINUTE = LangString.of("Time.Min", GENERIC_AMOUNT + "min.");
public static final LangString TIME_SECOND = LangString.of("Time.Sec", GENERIC_AMOUNT + "sec.");
public static final LangString TIME_DELIMITER = LangString.of("Time.Delimiter", " ");
public static final LangString OTHER_YES = LangString.of("Other.Yes", GREEN.enclose("Yes"));
public static final LangString OTHER_NO = LangString.of("Other.No", RED.enclose("No"));
public static final LangString OTHER_ENABLED = LangString.of("Other.Enabled", GREEN.enclose("Enabled"));
public static final LangString OTHER_DISABLED = LangString.of("Other.Disabled", RED.enclose("Disabled"));
public static final LangString OTHER_ANY = LangString.of("Other.Any", "Any");
public static final LangString OTHER_NONE = LangString.of("Other.None", "None");
public static final LangString OTHER_NEVER = LangString.of("Other.Never", "Never");
public static final LangString OTHER_ONE_TIMED = LangString.of("Other.OneTimed", "One-Timed");
public static final LangString OTHER_UNLIMITED = LangString.of("Other.Unlimited", "Unlimited");
public static final LangString OTHER_INFINITY = LangString.of("Other.Infinity", "∞");
public static final LangText ERROR_INVALID_PLAYER = LangText.of("Error.Invalid_Player", RED.enclose("Player not found."));
public static final LangText ERROR_INVALID_WORLD = LangText.of("Error.Invalid_World", RED.enclose("Invalid world."));
public static final LangText ERROR_INVALID_NUMBER = LangText.of("Error.Invalid_Number", RED.enclose(GENERIC_VALUE + " is not a valid number."));
public static final LangText ERROR_NO_PERMISSION = LangText.of("Error.NoPermission", RED.enclose("You don't have permissions to do that!"));
public static final LangText ERROR_COMMAND_NOT_YOURSELF = LangText.of("Error.Command.NotYourself", RED.enclose("This command can not be used on yourself."));
public static final LangText ERROR_COMMAND_PLAYER_ONLY = LangText.of("Error.Command.PlayerOnly", RED.enclose("This command is for players only."));
public static final LangText ERROR_COMMAND_USAGE = LangText.of("Error.Command.Usage",
TAG_NO_PREFIX,
RED.enclose("Error: ") + GRAY.enclose("Wrong arguments!"),
RED.enclose("Usage: ") + YELLOW.enclose("/" + Placeholders.COMMAND_LABEL) + " " + ORANGE.enclose(Placeholders.COMMAND_USAGE),
" "
);
public static final LangText EDITOR_ACTION_EXIT = LangText.of("Editor.Action.Exit",
TAG_NO_PREFIX,
GRAY.enclose("Click " +
CLICK.enclose(
ClickEvent.Action.RUN_COMMAND,
HOVER.enclose(GREEN.enclose("[Here]"), GRAY.enclose("Click to cancel")),
"/" + Dialog.EXIT
)
+ " to leave input mode."),
" ");
public static final LangString EDITOR_INPUT_HEADER_MAIN = LangString.of("Editor.Input.Header.Main", GREEN.enclose(BOLD.enclose("Input Mode")));
public static final LangString EDITOR_INPUT_HEADER_ERROR = LangString.of("Editor.Input.Header.Error", RED.enclose(BOLD.enclose("ERROR")));
public static final LangString EDITOR_INPUT_ERROR_NOT_INTEGER = LangString.of("Editor.Input.Error.NotInteger", GRAY.enclose("Expecting " + RED.enclose("whole") + " number!"));
public static final LangString EDITOR_INPUT_ERROR_GENERIC = LangString.of("Editor.Input.Error.Generic", GRAY.enclose("Invalid value!"));
public static final LangItem EDITOR_ITEM_CLOSE = LangItem.of("Editor.Generic.Close", RED.enclose("(✕) Exit"));
public static final LangItem EDITOR_ITEM_RETURN = LangItem.of("Editor.Generic.Return", GRAY.enclose("(↓) ") + WHITE.enclose("Return"));
public static final LangItem EDITOR_ITEM_NEXT_PAGE = LangItem.of("Editor.Generic.NextPage", WHITE.enclose("Next Page") + GRAY.enclose(" (→)"));
public static final LangItem EDITOR_ITEM_PREVIOUS_PAGE = LangItem.of("Editor.Generic.PreviousPage", GRAY.enclose("(←) ") + WHITE.enclose("Previous Page"));
@NotNull
public static String getYesOrNo(boolean value) {
return (value ? OTHER_YES : OTHER_NO).getString();
}
@NotNull
public static String getEnabledOrDisabled(boolean value) {
return (value ? OTHER_ENABLED : OTHER_DISABLED).getString();
}
}
@@ -0,0 +1,37 @@
package su.nightexpress.nightcore.core;
import org.jetbrains.annotations.NotNull;
import su.nightexpress.nightcore.NightCore;
import su.nightexpress.nightcore.core.listener.CoreListener;
import su.nightexpress.nightcore.dialog.DialogListener;
import su.nightexpress.nightcore.manager.AbstractManager;
import su.nightexpress.nightcore.menu.MenuListener;
import su.nightexpress.nightcore.menu.impl.AbstractMenu;
public class CoreManager extends AbstractManager<NightCore> {
public CoreManager(@NotNull NightCore plugin) {
super(plugin);
}
@Override
protected void onLoad() {
this.addListener(new CoreListener(this.plugin));
this.addListener(new DialogListener(this.plugin));
this.addListener(new MenuListener(this.plugin));
this.addTask(this.plugin.createTask(() -> {
AbstractMenu.PLAYER_MENUS.values().forEach(menu -> {
if (menu.getOptions().isReadyToRefresh()) {
menu.flush();
menu.getOptions().setLastAutoRefresh(System.currentTimeMillis());
}
});
}).setSecondsInterval(1));
}
@Override
protected void onShutdown() {
}
}
@@ -0,0 +1,11 @@
package su.nightexpress.nightcore.core;
import su.nightexpress.nightcore.util.wrapper.UniPermission;
public class CorePerms {
public static final UniPermission COMMAND_RELOAD = new UniPermission("nightcore.command.reload");
public static final UniPermission COMMAND_CHECK_PERM = new UniPermission("nightcore.command.checkperm");
public static final UniPermission COMMAND_FLAGS = new UniPermission("nightcore.command.flags");
}
@@ -0,0 +1,58 @@
package su.nightexpress.nightcore.core.command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
import su.nightexpress.nightcore.NightCore;
import su.nightexpress.nightcore.command.CommandResult;
import su.nightexpress.nightcore.command.impl.AbstractCommand;
import su.nightexpress.nightcore.core.CoreLang;
import su.nightexpress.nightcore.core.CorePerms;
import su.nightexpress.nightcore.integration.VaultHook;
import su.nightexpress.nightcore.util.Colorizer;
import su.nightexpress.nightcore.util.Players;
import su.nightexpress.nightcore.util.text.NightMessage;
import java.util.List;
import static su.nightexpress.nightcore.util.text.tag.Tags.*;
public class CheckPermCommand extends AbstractCommand<NightCore> {
public CheckPermCommand(@NotNull NightCore plugin) {
super(plugin, new String[]{"checkperm"}, CorePerms.COMMAND_CHECK_PERM);
this.setDescription(CoreLang.COMMAND_CHECKPERM_DESC);
this.setUsage(CoreLang.COMMAND_CHECKPERM_USAGE);
}
@Override
@NotNull
public List<String> getTab(@NotNull Player player, int arg, @NotNull String[] args) {
if (arg == 1) {
return Players.playerNames(player);
}
return super.getTab(player, arg, args);
}
@Override
protected void onExecute(@NotNull CommandSender sender, @NotNull CommandResult result) {
if (result.length() < 2) {
this.errorUsage(sender);
return;
}
Player player = Players.getPlayer(result.getArg(1));
if (player == null) {
this.errorPlayer(sender);
return;
}
String builder =
BOLD.enclose(LIGHT_YELLOW.enclose("Permissions report for ") + LIGHT_ORANGE.enclose(player.getName() + ":")) +
LIGHT_ORANGE.enclose("▪ " + LIGHT_YELLOW.enclose("Primary Group: ") + Colorizer.plain(VaultHook.getPermissionGroup(player))) +
LIGHT_ORANGE.enclose("▪ " + LIGHT_YELLOW.enclose("All Groups: ") + Colorizer.plain(String.join(", ", VaultHook.getPermissionGroups(player)))) +
LIGHT_ORANGE.enclose("▪ " + LIGHT_YELLOW.enclose("Prefix: ") + VaultHook.getPrefix(player)) +
LIGHT_ORANGE.enclose("▪ " + LIGHT_YELLOW.enclose("Suffix: ") + VaultHook.getSuffix(player));
NightMessage.create(builder).send(sender);
}
}
@@ -0,0 +1,24 @@
package su.nightexpress.nightcore.core.listener;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.server.ServiceRegisterEvent;
import org.jetbrains.annotations.NotNull;
import su.nightexpress.nightcore.NightCore;
import su.nightexpress.nightcore.integration.VaultHook;
import su.nightexpress.nightcore.manager.AbstractListener;
import su.nightexpress.nightcore.util.Plugins;
public class CoreListener extends AbstractListener<NightCore> {
public CoreListener(@NotNull NightCore plugin) {
super(plugin);
}
@EventHandler(priority = EventPriority.NORMAL)
public void onServiceRegisterEvent(ServiceRegisterEvent event) {
if (!Plugins.hasVault()) return;
VaultHook.onServiceRegisterEvent(event);
}
}
@@ -0,0 +1,43 @@
package su.nightexpress.nightcore.database;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.jetbrains.annotations.NotNull;
import su.nightexpress.nightcore.NightCorePlugin;
import java.sql.Connection;
import java.sql.SQLException;
public abstract class AbstractConnector {
protected final NightCorePlugin plugin;
//protected final String url;
protected final HikariConfig config;
protected final HikariDataSource dataSource;
public AbstractConnector(@NotNull NightCorePlugin plugin, @NotNull DatabaseConfig config) {
this.plugin = plugin;
//this.url = getURL(config);
this.config = new HikariConfig();
this.config.setJdbcUrl(this.getURL(config));
this.setupConfig(config);
this.config.addDataSourceProperty("cachePrepStmts", "true");
this.config.addDataSourceProperty("prepStmtCacheSize", "250");
this.config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");
this.dataSource = new HikariDataSource(this.config);
}
protected abstract String getURL(@NotNull DatabaseConfig config);
protected abstract void setupConfig(@NotNull DatabaseConfig config);
public void close() {
this.dataSource.close();
}
@NotNull
public final Connection getConnection() throws SQLException {
return this.dataSource.getConnection();
}
}
@@ -0,0 +1,197 @@
package su.nightexpress.nightcore.database;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.bukkit.inventory.ItemStack;
import org.jetbrains.annotations.NotNull;
import su.nightexpress.nightcore.NightCorePlugin;
import su.nightexpress.nightcore.database.connection.MySQLConnector;
import su.nightexpress.nightcore.database.connection.SQLiteConnector;
import su.nightexpress.nightcore.database.serialize.ItemStackSerializer;
import su.nightexpress.nightcore.database.sql.SQLColumn;
import su.nightexpress.nightcore.database.sql.SQLCondition;
import su.nightexpress.nightcore.database.sql.SQLQueries;
import su.nightexpress.nightcore.database.sql.SQLValue;
import su.nightexpress.nightcore.database.sql.executor.*;
import su.nightexpress.nightcore.manager.SimpleManager;
import su.nightexpress.nightcore.util.wrapper.UniTask;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.function.Function;
public abstract class AbstractDataHandler<P extends NightCorePlugin> extends SimpleManager<P> {
protected final DatabaseConfig config;
protected final AbstractConnector connector;
protected final Gson gson;
private UniTask syncTask;
private UniTask saveTask;
public AbstractDataHandler(@NotNull P plugin) {
this(plugin, DatabaseConfig.read(plugin));
}
public AbstractDataHandler(@NotNull P plugin, @NotNull DatabaseConfig config) {
super(plugin);
this.config = config;
if (this.getDatabaseType() == DatabaseType.MYSQL) {
this.connector = new MySQLConnector(plugin, config);
}
else {
this.connector = new SQLiteConnector(plugin, config);
}
this.gson = this.registerAdapters(new GsonBuilder().setPrettyPrinting()).create();
}
@Override
protected void onLoad() {
if (this.getConfig().getSaveInterval() > 0) {
this.saveTask = this.plugin.createAsyncTask(this::onSave)
.setSecondsInterval(this.getConfig().getSaveInterval() * 60)
.start();
}
if (this.getConfig().getSyncInterval() > 0 && this.getDatabaseType() != DatabaseType.SQLITE) {
this.syncTask = this.plugin.createAsyncTask(this::onSynchronize)
.setSecondsInterval(this.getConfig().getSyncInterval())
.start();
this.plugin.info("Enabled data synchronization with " + config.getSyncInterval() + " seconds interval.");
}
if (this.getConfig().isPurgeEnabled() && this.getConfig().getPurgePeriod() > 0) {
this.onPurge();
}
}
@Override
protected void onShutdown() {
if (this.syncTask != null) this.syncTask.stop();
if (this.saveTask != null) this.saveTask.stop();
//this.onSynchronize();
this.onSave();
this.getConnector().close();
}
public abstract void onSynchronize();
public abstract void onSave();
public abstract void onPurge();
@NotNull
public DatabaseConfig getConfig() {
return this.config;
}
@NotNull
public DatabaseType getDatabaseType() {
return this.getConfig().getStorageType();
}
@NotNull
public String getTablePrefix() {
return this.getConfig().getTablePrefix();
}
@NotNull
public AbstractConnector getConnector() {
return this.connector;
}
@NotNull
protected GsonBuilder registerAdapters(@NotNull GsonBuilder builder) {
return builder.registerTypeAdapter(ItemStack.class, new ItemStackSerializer());
}
@NotNull
protected final Connection getConnection() throws SQLException {
return this.getConnector().getConnection();
}
public void createTable(@NotNull String table, @NotNull List<SQLColumn> columns) {
CreateTableExecutor.builder(table, this.getDatabaseType()).columns(columns).execute(this.getConnector());
}
public void renameTable(@NotNull String from, @NotNull String to) {
RenameTableExecutor.builder(from, this.getDatabaseType()).renameTo(to).execute(this.getConnector());
}
public void addColumn(@NotNull String table, @NotNull SQLValue... columns) {
AlterTableExecutor.builder(table, this.getDatabaseType()).addColumn(columns).execute(this.getConnector());
}
public void renameColumn(@NotNull String table, @NotNull SQLValue... columns) {
AlterTableExecutor.builder(table, this.getDatabaseType()).renameColumn(columns).execute(this.getConnector());
}
public void dropColumn(@NotNull String table, @NotNull SQLColumn... columns) {
AlterTableExecutor.builder(table, this.getDatabaseType()).dropColumn(columns).execute(this.getConnector());
}
public boolean hasColumn(@NotNull String table, @NotNull SQLColumn column) {
return SQLQueries.hasColumn(this.getConnector(), table, column);
}
public void insert(@NotNull String table, @NotNull List<SQLValue> values) {
InsertQueryExecutor.builder(table).values(values).execute(this.getConnector());
}
public void update(@NotNull String table, @NotNull List<SQLValue> values, @NotNull SQLCondition... conditions) {
UpdateQueryExecutor.builder(table).values(values).where(conditions).execute(this.getConnector());
}
public void delete(@NotNull String table, @NotNull SQLCondition... conditions) {
DeleteQueryExecutor.builder(table).where(conditions).execute(this.getConnector());
}
public boolean contains(@NotNull String table, @NotNull SQLCondition... conditions) {
return this.load(table, (resultSet -> true), Collections.emptyList(), Arrays.asList(conditions)).isPresent();
}
public boolean contains(@NotNull String table, @NotNull List<SQLColumn> columns, @NotNull SQLCondition... conditions) {
return this.load(table, (resultSet -> true), columns, Arrays.asList(conditions)).isPresent();
}
@NotNull
public <T> Optional<T> load(@NotNull String table, @NotNull Function<ResultSet, T> function,
@NotNull List<SQLColumn> columns,
@NotNull List<SQLCondition> conditions) {
List<T> list = this.load(table, function, columns, conditions, 1);
return list.isEmpty() ? Optional.empty() : Optional.of(list.get(0));
}
@NotNull
public <T> List<T> load(@NotNull String table, @NotNull Function<ResultSet, T> dataFunction) {
return this.load(table, dataFunction, -1);
}
@NotNull
public <T> List<T> load(@NotNull String table, @NotNull Function<ResultSet, T> dataFunction, int amount) {
return this.load(table, dataFunction, Collections.emptyList(), amount);
}
@NotNull
public <T> List<T> load(@NotNull String table,
@NotNull Function<ResultSet, T> dataFunction,
@NotNull List<SQLColumn> columns,
int amount) {
return this.load(table, dataFunction, columns, Collections.emptyList(), amount);
}
@NotNull
public <T> List<T> load(@NotNull String table,
@NotNull Function<ResultSet, T> dataFunction,
@NotNull List<SQLColumn> columns,
@NotNull List<SQLCondition> conditions,
int amount) {
return SelectQueryExecutor.builder(table, dataFunction).columns(columns).where(conditions).execute(this.getConnector());
}
}
@@ -0,0 +1,98 @@
package su.nightexpress.nightcore.database;
import org.bukkit.OfflinePlayer;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import su.nightexpress.nightcore.NightCorePlugin;
import java.util.UUID;
public abstract class AbstractUser<P extends NightCorePlugin> implements DataUser {
protected final P plugin;
protected final UUID uuid;
protected String name;
protected long dateCreated;
protected long lastOnline;
protected long cachedUntil;
public AbstractUser(@NotNull P plugin, @NotNull UUID uuid, @NotNull String name, long dateCreated, long lastOnline) {
this.plugin = plugin;
this.uuid = uuid;
this.name = name;
this.setDateCreated(dateCreated);
this.setLastOnline(lastOnline);
this.setCachedUntil(-1);
}
public void onLoad() {
}
public void onUnload() {
}
public boolean isCacheExpired() {
return this.getCachedUntil() > 0 && System.currentTimeMillis() > this.getCachedUntil();
}
public long getCachedUntil() {
return cachedUntil;
}
public void setCachedUntil(long cachedUntil) {
this.cachedUntil = cachedUntil;
}
@NotNull
public final UUID getId() {
return this.uuid;
}
@NotNull
public final String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public final long getDateCreated() {
return dateCreated;
}
public final void setDateCreated(long dateCreated) {
this.dateCreated = dateCreated;
}
public final long getLastOnline() {
return this.lastOnline;
}
public final void setLastOnline(long lastOnline) {
this.lastOnline = lastOnline;
}
public final boolean isOnline() {
return this.getPlayer() != null;
}
@NotNull
public final OfflinePlayer getOfflinePlayer() {
return this.plugin.getServer().getOfflinePlayer(this.getId());
}
@Nullable
public final Player getPlayer() {
return this.plugin.getServer().getPlayer(this.getId());
}
@Override
public String toString() {
return "AbstractUser [uuid=" + this.uuid + ", name=" + this.name + ", lastOnline=" + this.lastOnline + "]";
}
}
@@ -0,0 +1,191 @@
package su.nightexpress.nightcore.database;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import su.nightexpress.nightcore.NightDataPlugin;
import su.nightexpress.nightcore.database.sql.SQLColumn;
import su.nightexpress.nightcore.database.sql.SQLCondition;
import su.nightexpress.nightcore.database.sql.SQLQueries;
import su.nightexpress.nightcore.database.sql.SQLValue;
import su.nightexpress.nightcore.database.sql.column.ColumnType;
import su.nightexpress.nightcore.core.CoreConfig;
import su.nightexpress.nightcore.util.TimeUtil;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.LocalDateTime;
import java.util.*;
import java.util.function.Function;
public abstract class AbstractUserDataHandler<P extends NightDataPlugin<U>, U extends DataUser> extends AbstractDataHandler<P> {
protected static final SQLColumn COLUMN_USER_ID = SQLColumn.of("uuid", ColumnType.STRING);
protected static final SQLColumn COLUMN_USER_NAME = SQLColumn.of("name", ColumnType.STRING);
protected static final SQLColumn COLUMN_USER_DATE_CREATED = SQLColumn.of("dateCreated", ColumnType.LONG);
protected static final SQLColumn COLUMN_USER_LAST_ONLINE = SQLColumn.of("last_online", ColumnType.LONG);
protected final String tableUsers;
protected final Set<UUID> existIDs;
protected final Set<String> existNames;
protected AbstractUserDataHandler(@NotNull P plugin) {
this(plugin, DatabaseConfig.read(plugin));
}
protected AbstractUserDataHandler(@NotNull P plugin, @NotNull DatabaseConfig config) {
super(plugin, config);
this.tableUsers = this.getTablePrefix() + "_users";
this.existIDs = new HashSet<>();
this.existNames = new HashSet<>();
}
@Override
protected void onLoad() {
super.onLoad();
this.createUserTable();
this.cacheNamesAndIds();
}
@Override
protected void onShutdown() {
super.onShutdown();
}
@Override
public void onSave() {
for (U user : this.plugin.getUserManager().getLoaded()) {
this.saveUser(user);
}
}
@Override
public void onPurge() {
if (!SQLQueries.hasTable(this.getConnector(), this.tableUsers)) return;
LocalDateTime deadline = LocalDateTime.now().minusDays(this.getConfig().getPurgePeriod());
long deadlineMs = TimeUtil.toEpochMillis(deadline);
this.delete(this.tableUsers, SQLCondition.smaller(COLUMN_USER_LAST_ONLINE.toValue(deadlineMs)));
}
protected void createUserTable() {
List<SQLColumn> columns = new ArrayList<>();
columns.add(COLUMN_USER_ID);
columns.add(COLUMN_USER_NAME);
columns.add(COLUMN_USER_DATE_CREATED);
columns.add(COLUMN_USER_LAST_ONLINE);
columns.addAll(this.getExtraColumns());
this.createTable(this.tableUsers, columns);
}
public void cacheNamesAndIds() {
if (!CoreConfig.USER_CACHE_NAME_AND_UUID.get()) return;
Function<ResultSet, Void> function = resultSet -> {
try {
this.existIDs.add(UUID.fromString(resultSet.getString(COLUMN_USER_ID.getName())));
this.existNames.add(resultSet.getString(COLUMN_USER_NAME.getName()).toLowerCase());
}
catch (SQLException exception) {
exception.printStackTrace();
}
return null;
};
this.load(this.tableUsers, function, Arrays.asList(COLUMN_USER_ID, COLUMN_USER_NAME), Collections.emptyList(), -1);
}
@NotNull
protected abstract List<SQLColumn> getExtraColumns();
@NotNull
protected List<SQLColumn> getReadColumns() {
return Collections.emptyList();
}
@NotNull
protected abstract List<SQLValue> getSaveColumns(@NotNull U user);
@NotNull
protected abstract Function<ResultSet, U> getUserFunction();
@NotNull
public List<U> getUsers() {
return this.load(this.tableUsers, this.getUserFunction(), Collections.emptyList(), Collections.emptyList(), -1);
}
@Nullable
public U getUser(@NotNull Player player) {
return this.getUser(player.getUniqueId());
}
@Nullable
public final U getUser(@NotNull String name) {
return this.load(this.tableUsers, this.getUserFunction(), this.getReadColumns(),
Collections.singletonList(SQLCondition.equal(COLUMN_USER_NAME.asLowerCase().toValue(name.toLowerCase())))
).orElse(null);
}
@Nullable
public final U getUser(@NotNull UUID uuid) {
return this.load(this.tableUsers, this.getUserFunction(), this.getReadColumns(),
Collections.singletonList(SQLCondition.equal(COLUMN_USER_ID.toValue(uuid)))
).orElse(null);
}
public boolean isUserExists(@NotNull String name) {
if (CoreConfig.USER_CACHE_NAME_AND_UUID.get()) {
return this.existNames.contains(name.toLowerCase());
}
return this.contains(this.tableUsers, Collections.singletonList(COLUMN_USER_NAME), SQLCondition.equal(COLUMN_USER_NAME.asLowerCase().toValue(name.toLowerCase())));
}
public boolean isUserExists(@NotNull UUID uuid) {
if (CoreConfig.USER_CACHE_NAME_AND_UUID.get()) {
return this.existIDs.contains(uuid);
}
return this.contains(this.tableUsers, Collections.singletonList(COLUMN_USER_ID), SQLCondition.equal(COLUMN_USER_ID.toValue(uuid)));
}
public void saveUser(@NotNull U user) {
List<SQLValue> values = new ArrayList<>();
values.add(COLUMN_USER_NAME.toValue(user.getName()));
values.add(COLUMN_USER_DATE_CREATED.toValue(user.getDateCreated()));
values.add(COLUMN_USER_LAST_ONLINE.toValue(user.getLastOnline()));
values.addAll(this.getSaveColumns(user));
this.update(this.tableUsers, values, SQLCondition.equal(COLUMN_USER_ID.toValue(user.getId())));
}
public void addUser(@NotNull U user) {
List<SQLValue> values = new ArrayList<>();
values.add(COLUMN_USER_ID.toValue(user.getId()));
values.add(COLUMN_USER_NAME.toValue(user.getName()));
values.add(COLUMN_USER_DATE_CREATED.toValue(user.getDateCreated()));
values.add(COLUMN_USER_LAST_ONLINE.toValue(user.getLastOnline()));
values.addAll(this.getSaveColumns(user));
this.insert(this.tableUsers, values);
this.existIDs.add(user.getId());
this.existNames.add(user.getName());
}
public void deleteUser(@NotNull UUID uuid) {
this.delete(this.tableUsers, SQLCondition.equal(COLUMN_USER_ID.toValue(uuid)));
this.existIDs.clear();
this.existNames.clear();
this.cacheNamesAndIds();
}
public void deleteUser(@NotNull DataUser user) {
this.delete(this.tableUsers, SQLCondition.equal(COLUMN_USER_ID.toValue(user.getId())));
this.existIDs.remove(user.getId());
this.existNames.remove(user.getName());
}
}
@@ -0,0 +1,259 @@
package su.nightexpress.nightcore.database;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import su.nightexpress.nightcore.NightDataPlugin;
import su.nightexpress.nightcore.manager.AbstractManager;
import su.nightexpress.nightcore.core.CoreConfig;
import su.nightexpress.nightcore.database.listener.UserListener;
import su.nightexpress.nightcore.util.Players;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Consumer;
public abstract class AbstractUserManager<P extends NightDataPlugin<U>, U extends DataUser> extends AbstractManager<P> {
private final Map<UUID, U> loadedById;
private final Map<String, U> loadedByName;
public AbstractUserManager(@NotNull P plugin) {
super(plugin);
this.loadedById = new ConcurrentHashMap<>();
this.loadedByName = new ConcurrentHashMap<>();
}
@Override
protected void onLoad() {
this.addListener(new UserListener<>(this.plugin));
}
@Override
protected void onShutdown() {
this.getLoaded().forEach(this::save);
this.getLoadedByIdMap().clear();
this.getLoadedByNameMap().clear();
}
@NotNull
public abstract U createUserData(@NotNull UUID uuid, @NotNull String name);
public void loadOnlineUsers() {
this.plugin.getServer().getOnlinePlayers().stream().map(Player::getUniqueId).forEach(id -> {
U user = this.getUserData(id);
if (user != null) this.cachePermanent(user);
});
}
@NotNull
public final U getUserData(@NotNull Player player) {
UUID uuid = player.getUniqueId();
U user = this.getLoaded(uuid);
if (user != null) return user;
if (Players.isReal(player)) {
user = this.getUserData(uuid);
if (user != null) {
if (CoreConfig.USER_DEBUG_ENABLED.get()) {
new Throwable().printStackTrace();
this.plugin.warn("Main thread user data load for '" + uuid + "' aka '" + player.getName() + "'.");
}
return user;
}
}
return this.createUserData(uuid, player.getName());
}
@Nullable
public final U getUserData(@NotNull String name) {
Player player = Players.getPlayer(name);
if (player != null) return this.getUserData(player);
U user = this.getLoaded(name);
if (user != null) return user;
user = this.plugin.getData().getUser(name);
if (user != null) {
user.onLoad();
//this.plugin.debug("Loaded by name from DB: " + user.getName());
this.cacheTemporary(user);
}
return user;
}
@Nullable
public final U getUserData(@NotNull UUID uuid) {
U user = this.getLoaded(uuid);
if (user != null) return user;
user = this.plugin.getData().getUser(uuid);
if (user != null) {
user.onLoad();
//this.plugin.debug("Loaded by UUID from DB: " + user.getName());
this.cacheTemporary(user);
}
return user;
}
public final CompletableFuture<U> getUserDataAsync(@NotNull String name) {
return CompletableFuture.supplyAsync(() -> this.getUserData(name));
}
public final CompletableFuture<U> getUserDataAsync(@NotNull UUID uuid) {
return CompletableFuture.supplyAsync(() -> this.getUserData(uuid));
}
public void getUserDataAndPerform(@NotNull String name, Consumer<U> consumer) {
U user = this.getLoaded(name);
if (user != null) {
consumer.accept(user);
}
else this.getUserDataAsync(name).thenAccept(user2 -> this.plugin.runTask(task -> consumer.accept(user2)));
}
public void getUserDataAndPerform(@NotNull UUID uuid, Consumer<U> consumer) {
U user = this.getLoaded(uuid);
if (user != null) {
consumer.accept(user);
}
else this.getUserDataAsync(uuid).thenAccept(user2 -> this.plugin.runTask(task -> consumer.accept(user2)));
}
public void getUserDataAndPerformAsync(@NotNull String name, Consumer<U> consumer) {
U user = this.getLoaded(name);
if (user != null) {
consumer.accept(user);
}
else this.getUserDataAsync(name).thenAccept(consumer);
}
public void getUserDataAndPerformAsync(@NotNull UUID uuid, Consumer<U> consumer) {
U user = this.getLoaded(uuid);
if (user != null) {
consumer.accept(user);
}
else this.getUserDataAsync(uuid).thenAccept(consumer);
}
public final void unload(@NotNull Player player) {
this.unload(player.getUniqueId());
}
public final void unload(@NotNull UUID uuid) {
U user = this.getLoadedByIdMap().get(uuid);
if (user == null) return;
this.unload(user);
}
public void unload(@NotNull U user) {
Player player = user.getPlayer();
if (player != null) {
user.setName(player.getName());
user.setLastOnline(System.currentTimeMillis());
}
this.saveAsync(user);
this.cacheTemporary(user);
}
public void save(@NotNull U user) {
this.plugin.getData().saveUser(user);
}
public void saveAsync(@NotNull U user) {
this.plugin.runTaskAsync(task -> this.save(user));
}
@NotNull
public Set<U> getAllUsers() {
Map<UUID, U> users = new HashMap<>();
this.getLoaded().forEach(user -> users.put(user.getId(), user));
this.plugin.getData().getUsers().forEach(user -> {
users.putIfAbsent(user.getId(), user);
});
return new HashSet<>(users.values());
}
@NotNull
public Map<UUID, U> getLoadedByIdMap() {
this.removeExpired(this.loadedById.values());
return this.loadedById;
}
@NotNull
public Map<String, U> getLoadedByNameMap() {
this.removeExpired(this.loadedByName.values());
return loadedByName;
}
private void removeExpired(@NotNull Collection<U> collection) {
collection.removeIf(user -> {
if (user.isCacheExpired()) {
user.onUnload();
//this.plugin.debug("Cache expired: " + user.getName());
return true;
}
return false;
});
}
@NotNull
public Set<U> getLoaded() {
return new HashSet<>(this.getLoadedByIdMap().values());
}
@Nullable
public U getLoaded(@NotNull UUID uuid) {
return this.getLoadedByIdMap().get(uuid);
}
@Nullable
public U getLoaded(@NotNull String name) {
return this.getLoadedByNameMap().get(name.toLowerCase());
}
public boolean isLoaded(@NotNull Player player) {
return this.isLoaded(player.getUniqueId());
}
public boolean isLoaded(@NotNull UUID id) {
return this.getLoadedByIdMap().containsKey(id);
}
public boolean isLoaded(@NotNull String name) {
return this.getLoadedByNameMap().containsKey(name.toLowerCase());
}
public boolean isCreated(@NotNull String name) {
return this.plugin.getData().isUserExists(name);
}
public boolean isCreated(@NotNull UUID uuid) {
return this.plugin.getData().isUserExists(uuid);
}
public void cacheTemporary(@NotNull U user) {
user.setCachedUntil(System.currentTimeMillis() + CoreConfig.USER_CACHE_LIFETIME.get() * 1000L);
this.cache(user);
//this.plugin.debug("Temp user cache: " + user.getName());
}
public void cachePermanent(@NotNull U user) {
user.setCachedUntil(-1);
this.cache(user);
//this.plugin.debug("Permanent user cache: " + user.getName());
}
private void cache(@NotNull U user) {
this.getLoadedByIdMap().putIfAbsent(user.getId(), user);
this.getLoadedByNameMap().putIfAbsent(user.getName().toLowerCase(), user);
}
}
@@ -0,0 +1,41 @@
package su.nightexpress.nightcore.database;
import org.bukkit.OfflinePlayer;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.UUID;
public interface DataUser {
void onLoad();
void onUnload();
boolean isCacheExpired();
long getCachedUntil();
void setCachedUntil(long cachedUntil);
@NotNull UUID getId();
@NotNull String getName();
void setName(String name);
long getDateCreated();
void setDateCreated(long dateCreated);
long getLastOnline();
void setLastOnline(long lastOnline);
boolean isOnline();
@NotNull OfflinePlayer getOfflinePlayer();
@Nullable Player getPlayer();
}
@@ -0,0 +1,190 @@
package su.nightexpress.nightcore.database;
import org.jetbrains.annotations.NotNull;
import su.nightexpress.nightcore.NightCorePlugin;
import su.nightexpress.nightcore.config.ConfigValue;
import su.nightexpress.nightcore.config.FileConfig;
import su.nightexpress.nightcore.util.StringUtil;
import java.util.stream.Stream;
public class DatabaseConfig {
private final int saveInterval;
private final int syncInterval;
private final DatabaseType databaseType;
private final String tablePrefix;
private final boolean purgeEnabled;
private final int purgePeriod;
private final String username;
private final String password;
private final String host;
private final String database;
private final String urlOptions;
private final String filename;
public DatabaseConfig(
int saveInterval,
int syncInterval,
@NotNull DatabaseType databaseType,
@NotNull String tablePrefix,
boolean purgeEnabled,
int purgePeriod,
@NotNull String username,
@NotNull String password,
@NotNull String host,
@NotNull String database,
@NotNull String urlOptions,
@NotNull String filename
) {
this.saveInterval = saveInterval;
this.syncInterval = syncInterval;
this.databaseType = databaseType;
this.tablePrefix = tablePrefix;
this.purgeEnabled = purgeEnabled;
this.purgePeriod = purgePeriod;
this.username = username;
this.password = password;
this.host = host;
this.database = database;
this.urlOptions = urlOptions;
this.filename = filename;
}
@NotNull
public static DatabaseConfig read(@NotNull NightCorePlugin plugin) {
FileConfig cfg = plugin.getConfig();
String path = "Database.";
DatabaseType databaseType = ConfigValue.create(path + "Type", DatabaseType.class, DatabaseType.SQLITE,
"Sets database type.",
"Available values: " + String.join(",", Stream.of(DatabaseType.values()).map(Enum::name).toList()))
.read(cfg);
int saveInterval = ConfigValue.create(path + "Auto_Save_Interval", 20,
"Sets how often (in minutes) plugin data of online players will be saved to the database.",
"Set to '-1' to disable.")
.read(cfg);
int syncInterval = ConfigValue.create(path + "Sync_Interval", -1,
"Sets how often (in seconds) plugin data will be fetched and loaded from the remote database.",
"Useless for " + DatabaseType.SQLITE.name() + ".",
"Set to '-1' to disable.")
.read(cfg);
String tablePrefix = ConfigValue.create(path + "Table_Prefix", StringUtil.lowerCaseUnderscore(plugin.getName()),
"Custom prefix for plugin tables in database.")
.read(cfg);
String mysqlUser = ConfigValue.create(path + "MySQL.Username", "root",
"Database user name.")
.read(cfg);
String mysqlPassword = ConfigValue.create(path + "MySQL.Password", "root",
"Database password.")
.read(cfg);
String mysqlHost = ConfigValue.create(path + "MySQL.Host", "localhost:3306",
"Database address. Like http://127.0.0.1:3306/")
.read(cfg);
String mysqlBase = ConfigValue.create(path + "MySQL.Database", "minecraft",
"Name of the MySQL database where plugin will create tables.")
.read(cfg);
String urlOptions = ConfigValue.create(path + "MySQL.Options",
"?allowPublicKeyRetrieval=true&useSSL=false",
"Connection options. Do not touch unless you know what you're doing."
).read(cfg);
String sqliteFilename = ConfigValue.create(path + "SQLite.FileName", "data.db",
"File name for the SQLite database file.",
"Actually it's a path to the file, so you can use directories here.")
.read(cfg);
path = "Database.Purge.";
boolean purgeEnabled = ConfigValue.create(path + "Enabled", false,
"Enables the purge feature.",
"Purge will remove all records from the plugin tables that are 'old' enough.")
.read(cfg);
int purgePeriod = ConfigValue.create(path + "For_Period", 60,
"Sets maximal 'age' for the database records before they will be purged.",
"This option may have different behavior depends on the plugin.",
"By default it's days of inactivity for the plugin users.")
.read(cfg);
return new DatabaseConfig(
saveInterval, syncInterval,
databaseType, tablePrefix,
purgeEnabled, purgePeriod,
mysqlUser, mysqlPassword, mysqlHost, mysqlBase, urlOptions,
sqliteFilename
);
}
@NotNull
public DatabaseType getStorageType() {
return databaseType;
}
@NotNull
public String getTablePrefix() {
return tablePrefix;
}
public int getSaveInterval() {
return saveInterval;
}
public int getSyncInterval() {
return syncInterval;
}
public boolean isPurgeEnabled() {
return purgeEnabled;
}
public int getPurgePeriod() {
return purgePeriod;
}
@NotNull
public String getUsername() {
return username;
}
@NotNull
public String getPassword() {
return password;
}
@NotNull
public String getHost() {
return host;
}
@NotNull
public String getDatabase() {
return database;
}
@NotNull
public String getUrlOptions() {
return urlOptions;
}
@NotNull
public String getFilename() {
return filename;
}
}
@@ -0,0 +1,7 @@
package su.nightexpress.nightcore.database;
public enum DatabaseType {
MYSQL,
SQLITE,
}
@@ -0,0 +1,28 @@
package su.nightexpress.nightcore.database.connection;
import org.jetbrains.annotations.NotNull;
import su.nightexpress.nightcore.NightCorePlugin;
import su.nightexpress.nightcore.database.AbstractConnector;
import su.nightexpress.nightcore.database.DatabaseConfig;
public class MySQLConnector extends AbstractConnector {
public MySQLConnector(@NotNull NightCorePlugin plugin, @NotNull DatabaseConfig config) {
super(plugin, config);
}
@Override
protected String getURL(@NotNull DatabaseConfig config) {
String host = config.getHost();
String database = config.getDatabase();
String options = config.getUrlOptions();
return "jdbc:mysql://" + host + "/" + database + options;
}
@Override
protected void setupConfig(@NotNull DatabaseConfig config) {
this.config.setUsername(config.getUsername());
this.config.setPassword(config.getPassword());
}
}
@@ -0,0 +1,24 @@
package su.nightexpress.nightcore.database.connection;
import org.jetbrains.annotations.NotNull;
import su.nightexpress.nightcore.NightCorePlugin;
import su.nightexpress.nightcore.database.AbstractConnector;
import su.nightexpress.nightcore.database.DatabaseConfig;
public class SQLiteConnector extends AbstractConnector {
public SQLiteConnector(@NotNull NightCorePlugin plugin, @NotNull DatabaseConfig config) {
super(plugin, config);
}
@Override
protected String getURL(@NotNull DatabaseConfig config) {
String filePath = plugin.getDataFolder().getAbsolutePath() + "/" + config.getFilename();
return "jdbc:sqlite:" + filePath;
}
@Override
protected void setupConfig(@NotNull DatabaseConfig config) {
this.config.setMaximumPoolSize(1);
}
}
@@ -0,0 +1,49 @@
package su.nightexpress.nightcore.database.listener;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.player.AsyncPlayerPreLoginEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.jetbrains.annotations.NotNull;
import su.nightexpress.nightcore.NightDataPlugin;
import su.nightexpress.nightcore.core.CoreConfig;
import su.nightexpress.nightcore.database.DataUser;
import su.nightexpress.nightcore.manager.AbstractListener;
import su.nightexpress.nightcore.database.AbstractUserManager;
import java.util.UUID;
public class UserListener<P extends NightDataPlugin<U>, U extends DataUser> extends AbstractListener<P> {
private final AbstractUserManager<? extends NightDataPlugin<U>, U> userManager;
public UserListener(@NotNull P plugin) {
super(plugin);
this.userManager = plugin.getUserManager();
}
@EventHandler(priority = EventPriority.MONITOR)
public void onUserLogin(AsyncPlayerPreLoginEvent event) {
if (event.getLoginResult() != AsyncPlayerPreLoginEvent.Result.ALLOWED) return;
UUID uuid = event.getUniqueId();
U user;
if (!this.userManager.isCreated(uuid)) {
user = this.userManager.createUserData(uuid, event.getName());
plugin.getData().addUser(user);
if (CoreConfig.USER_DEBUG_ENABLED.get()) {
plugin.info("Created new data for: '" + uuid + "'");
}
}
else user = this.userManager.getUserData(uuid);
if (user != null) {
this.userManager.cachePermanent(user);
}
}
@EventHandler(priority = EventPriority.MONITOR)
public void onUserQuit(PlayerQuitEvent event) {
this.plugin.getUserManager().unload(event.getPlayer());
}
}
@@ -0,0 +1,24 @@
package su.nightexpress.nightcore.database.serialize;
import com.google.gson.*;
import org.bukkit.inventory.ItemStack;
import su.nightexpress.nightcore.util.ItemUtil;
import java.lang.reflect.Type;
public class ItemStackSerializer implements JsonSerializer<ItemStack>, JsonDeserializer<ItemStack> {
@Override
public JsonElement serialize(ItemStack item, Type type, JsonSerializationContext context) {
JsonObject object = new JsonObject();
object.addProperty("data64", ItemUtil.compress(item));
return object;
}
@Override
public ItemStack deserialize(JsonElement json, Type type, JsonDeserializationContext context) throws JsonParseException {
JsonObject object = json.getAsJsonObject();
return ItemUtil.decompress(object.get("data64").getAsString());
}
}
@@ -0,0 +1,68 @@
package su.nightexpress.nightcore.database.sql;
import org.jetbrains.annotations.NotNull;
import su.nightexpress.nightcore.database.DatabaseType;
import su.nightexpress.nightcore.database.sql.column.ColumnType;
public class SQLColumn {
private final String name;
private final String nameEscaped;
private final ColumnType type;
private final int length;
public SQLColumn(@NotNull String name, @NotNull ColumnType type, int length) {
this(name, "`" + name + "`", type, length);
}
public SQLColumn(@NotNull String name, @NotNull String nameEscaped, @NotNull ColumnType type, int length) {
this.name = name;
this.nameEscaped = nameEscaped;
this.type = type;
this.length = length;
}
@NotNull
public static SQLColumn of(@NotNull String name, @NotNull ColumnType type) {
return SQLColumn.of(name, type, -1);
}
@NotNull
public static SQLColumn of(@NotNull String name, @NotNull ColumnType type, int length) {
return new SQLColumn(name, type, length);
}
@NotNull
public SQLColumn asLowerCase() {
return new SQLColumn("LOWER(" + this.getName() + ")", this.getName(), this.getType(), this.getLength());
}
@NotNull
public String getName() {
return name;
}
@NotNull
public String getNameEscaped() {
return this.nameEscaped;
}
@NotNull
public ColumnType getType() {
return type;
}
public int getLength() {
return length;
}
@NotNull
public String formatType(@NotNull DatabaseType databaseType) {
return this.getType().getFormer().build(databaseType, this.getLength());
}
@NotNull
public SQLValue toValue(@NotNull Object value) {
return SQLValue.of(this, String.valueOf(value));
}
}
@@ -0,0 +1,72 @@
package su.nightexpress.nightcore.database.sql;
import org.jetbrains.annotations.NotNull;
public class SQLCondition {
private final SQLValue value;
private final Type type;
public SQLCondition(@NotNull SQLValue value, @NotNull Type type) {
this.value = value;
this.type = type;
}
@NotNull
public static SQLCondition of(@NotNull SQLValue value, @NotNull Type type) {
return new SQLCondition(value, type);
}
@NotNull
public static SQLCondition equal(@NotNull SQLValue value) {
return of(value, Type.EQUAL);
}
@NotNull
public static SQLCondition not(@NotNull SQLValue value) {
return of(value, Type.NOT_EQUAL);
}
@NotNull
public static SQLCondition smaller(@NotNull SQLValue value) {
return of(value, Type.SMALLER);
}
@NotNull
public static SQLCondition greater(@NotNull SQLValue value) {
return of(value, Type.GREATER);
}
@NotNull
public Type getType() {
return type;
}
@NotNull
public SQLValue getValue() {
return value;
}
@NotNull
public SQLColumn getColumn() {
return this.getValue().getColumn();
}
public enum Type {
GREATER(">"),
SMALLER("<"),
EQUAL("="),
NOT_EQUAL("!=");
private final String operator;
Type(@NotNull String operator) {
this.operator = operator;
}
@NotNull
public String getOperator() {
return operator;
}
}
}
@@ -0,0 +1,21 @@
package su.nightexpress.nightcore.database.sql;
import org.jetbrains.annotations.NotNull;
import su.nightexpress.nightcore.database.AbstractConnector;
public abstract class SQLExecutor<T> {
protected final String table;
protected SQLExecutor(@NotNull String table) {
this.table = table;
}
@NotNull
public String getTable() {
return "`" + this.table + "`";
}
@NotNull
public abstract T execute(@NotNull AbstractConnector connector);
}
@@ -0,0 +1,115 @@
package su.nightexpress.nightcore.database.sql;
import org.jetbrains.annotations.NotNull;
import su.nightexpress.nightcore.database.AbstractConnector;
import java.sql.*;
import java.util.*;
import java.util.function.Function;
public class SQLQueries {
public static boolean hasTable(@NotNull AbstractConnector connector, @NotNull String table) {
try (Connection connection = connector.getConnection()) {
boolean has;
DatabaseMetaData metaData = connection.getMetaData();
ResultSet tables = metaData.getTables(null, null, table, null);
has = tables.next();
tables.close();
return has;
}
catch (SQLException exception) {
exception.printStackTrace();
return false;
}
}
public static boolean hasColumn(@NotNull AbstractConnector connector,
@NotNull String table,
@NotNull SQLColumn column) {
String sql = "SELECT * FROM " + table;
String columnName = column.getName();
try (Connection connection = connector.getConnection();
Statement statement = connection.createStatement()) {
ResultSet resultSet = statement.executeQuery(sql);
ResultSetMetaData metaData = resultSet.getMetaData();
int columns = metaData.getColumnCount();
for (int index = 1; index <= columns; index++) {
if (columnName.equals(metaData.getColumnName(index))) {
return true;
}
}
return false;
}
catch (SQLException exception) {
exception.printStackTrace();
return false;
}
}
public static void executeStatement(@NotNull AbstractConnector connector,
@NotNull String sql) {
executeStatement(connector, sql, Collections.emptySet());
}
public static void executeStatement(@NotNull AbstractConnector connector,
@NotNull String sql,
@NotNull Collection<String> values1) {
executeStatement(connector, sql, values1, Collections.emptySet());
}
public static void executeStatement(@NotNull AbstractConnector connector,
@NotNull String sql,
@NotNull Collection<String> values1,
@NotNull Collection<String> values2) {
try (Connection connection = connector.getConnection();
PreparedStatement statement = connection.prepareStatement(sql)) {
int count = 1;
for (String columnName : values1) {
statement.setString(count++, columnName);
}
for (String columnValue : values2) {
statement.setString(count++, columnValue);
}
statement.executeUpdate();
}
catch (SQLException exception) {
exception.printStackTrace();
}
}
@NotNull
public static <T> List<@NotNull T> executeQuery(@NotNull AbstractConnector connector,
@NotNull String sql,
@NotNull Collection<String> values,
@NotNull Function<ResultSet, T> dataFunction,
int amount) {
List<T> list = new ArrayList<>();
try (Connection connection = connector.getConnection();
PreparedStatement statement = connection.prepareStatement(sql)) {
int count = 1;
for (String wValue : values) {
statement.setString(count++, wValue);
}
ResultSet resultSet = statement.executeQuery();
while (resultSet.next() && (amount < 0 || list.size() < amount)) {
list.add(dataFunction.apply(resultSet));
}
resultSet.close();
}
catch (SQLException exception) {
exception.printStackTrace();
}
list.removeIf(Objects::isNull);
return list;
}
}
@@ -0,0 +1,29 @@
package su.nightexpress.nightcore.database.sql;
import org.jetbrains.annotations.NotNull;
public class SQLValue {
private final SQLColumn column;
private final String value;
public SQLValue(@NotNull SQLColumn column, @NotNull String value) {
this.column = column;
this.value = value;
}
@NotNull
public static SQLValue of(@NotNull SQLColumn column, @NotNull String value) {
return new SQLValue(column, value);
}
@NotNull
public SQLColumn getColumn() {
return column;
}
@NotNull
public String getValue() {
return value;
}
}
@@ -0,0 +1,35 @@
package su.nightexpress.nightcore.database.sql.column;
import org.jetbrains.annotations.NotNull;
import su.nightexpress.nightcore.database.DatabaseType;
public interface ColumnFormer {
ColumnFormer STRING = (storageType, length) -> {
if (length < 1 || storageType == DatabaseType.SQLITE) {
return storageType == DatabaseType.SQLITE ? "TEXT NOT NULL" : "MEDIUMTEXT NOT NULL";
}
return "varchar(" + length + ") CHARACTER SET utf8 NOT NULL";
};
ColumnFormer INTEGER = (storageType, length) -> {
if (length < 1 || storageType == DatabaseType.SQLITE) {
return "INTEGER NOT NULL";
}
return "int(" + length + ") NOT NULL";
};
ColumnFormer DOUBLE = (storageType, length) -> {
return storageType == DatabaseType.SQLITE ? "REAL NOT NULL" : "double NOT NULL";
};
ColumnFormer LONG = (storageType, length) -> {
return length < 1 || storageType == DatabaseType.SQLITE ? "BIGINT NOT NULL" : "bigint(" + length + ") NOT NULL";
};
ColumnFormer BOOLEAN = (storageType, length) -> {
return storageType == DatabaseType.SQLITE ? "INTEGER NOT NULL" : "tinyint(1) NOT NULL";
};
@NotNull String build(@NotNull DatabaseType databaseType, int length);
}
@@ -0,0 +1,23 @@
package su.nightexpress.nightcore.database.sql.column;
import org.jetbrains.annotations.NotNull;
public class ColumnType {
public static final ColumnType INTEGER = new ColumnType(ColumnFormer.INTEGER);
public static final ColumnType DOUBLE = new ColumnType(ColumnFormer.DOUBLE);
public static final ColumnType LONG = new ColumnType(ColumnFormer.LONG);
public static final ColumnType BOOLEAN = new ColumnType(ColumnFormer.BOOLEAN);
public static final ColumnType STRING = new ColumnType(ColumnFormer.STRING);
private final ColumnFormer former;
public ColumnType(@NotNull ColumnFormer former) {
this.former = former;
}
@NotNull
public ColumnFormer getFormer() {
return former;
}
}
@@ -0,0 +1,112 @@
package su.nightexpress.nightcore.database.sql.executor;
import org.jetbrains.annotations.NotNull;
import su.nightexpress.nightcore.database.DatabaseType;
import su.nightexpress.nightcore.database.AbstractConnector;
import su.nightexpress.nightcore.database.connection.SQLiteConnector;
import su.nightexpress.nightcore.database.sql.SQLColumn;
import su.nightexpress.nightcore.database.sql.SQLExecutor;
import su.nightexpress.nightcore.database.sql.SQLQueries;
import su.nightexpress.nightcore.database.sql.SQLValue;
import su.nightexpress.nightcore.database.sql.column.ColumnType;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public final class AlterTableExecutor extends SQLExecutor<Void> {
private final DatabaseType databaseType;
private final List<SQLValue> columns;
private Type type;
private AlterTableExecutor(@NotNull String table, @NotNull DatabaseType databaseType) {
super(table);
this.databaseType = databaseType;
this.columns = new ArrayList<>();
}
private enum Type {
ADD_COLUMN, RENAME_COLUMN, DROP_COLUMN
}
@NotNull
public static AlterTableExecutor builder(@NotNull String table, @NotNull DatabaseType databaseType) {
return new AlterTableExecutor(table, databaseType);
}
@NotNull
public AlterTableExecutor addColumn(@NotNull SQLValue... columns) {
return this.addColumn(Arrays.asList(columns));
}
@NotNull
public AlterTableExecutor addColumn(@NotNull List<SQLValue> columns) {
return this.columns(columns, Type.ADD_COLUMN);
}
@NotNull
public AlterTableExecutor renameColumn(@NotNull SQLValue... columns) {
return this.addColumn(Arrays.asList(columns));
}
@NotNull
public AlterTableExecutor renameColumn(@NotNull List<SQLValue> columns) {
return this.columns(columns, Type.RENAME_COLUMN);
}
@NotNull
public AlterTableExecutor dropColumn(@NotNull SQLColumn... columns) {
return this.dropColumn(Arrays.asList(columns));
}
@NotNull
public AlterTableExecutor dropColumn(@NotNull List<SQLColumn> columns) {
return this.columns(columns.stream().map(column -> column.toValue("dummy")).toList(), Type.DROP_COLUMN);
}
private AlterTableExecutor columns(@NotNull List<SQLValue> values, @NotNull Type type) {
this.columns.clear();
this.columns.addAll(values);
this.type = type;
return this;
}
@Override
@NotNull
public Void execute(@NotNull AbstractConnector connector) {
if (this.columns.isEmpty()) return null;
if (this.type == Type.ADD_COLUMN) {
this.columns.forEach(value -> {
if (SQLQueries.hasColumn(connector, this.getTable(), value.getColumn())) return;
String sql = "ALTER TABLE " + this.getTable() + " ADD "
+ value.getColumn().getName() + " " + value.getColumn().formatType(this.databaseType);
if (connector instanceof SQLiteConnector || value.getColumn().getType() != ColumnType.STRING) {
sql = sql + " DEFAULT '" + value.getValue() + "'";
}
SQLQueries.executeStatement(connector, sql);
});
}
else if (this.type == Type.RENAME_COLUMN) {
this.columns.forEach(value -> {
if (!SQLQueries.hasColumn(connector, this.getTable(), value.getColumn())) return;
String sql = "ALTER TABLE " + this.getTable() + " RENAME COLUMN " + value.getColumn().getName() + " TO " + value.getValue();
SQLQueries.executeStatement(connector, sql);
});
}
else if (this.type == Type.DROP_COLUMN) {
this.columns.forEach(value -> {
if (!SQLQueries.hasColumn(connector, this.getTable(), value.getColumn())) return;
String sql = "ALTER TABLE " + this.getTable() + " DROP COLUMN " + value.getColumn().getName();
SQLQueries.executeStatement(connector, sql);
});
}
return null;
}
}
@@ -0,0 +1,66 @@
package su.nightexpress.nightcore.database.sql.executor;
import org.jetbrains.annotations.NotNull;
import su.nightexpress.nightcore.database.DatabaseType;
import su.nightexpress.nightcore.database.AbstractConnector;
import su.nightexpress.nightcore.database.sql.SQLColumn;
import su.nightexpress.nightcore.database.sql.SQLExecutor;
import su.nightexpress.nightcore.database.sql.SQLQueries;
import su.nightexpress.nightcore.database.sql.column.ColumnFormer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public final class CreateTableExecutor extends SQLExecutor<Void> {
private final DatabaseType databaseType;
private final List<SQLColumn> columns;
private CreateTableExecutor(@NotNull String table, @NotNull DatabaseType databaseType) {
super(table);
this.databaseType = databaseType;
this.columns = new ArrayList<>();
}
@NotNull
public static CreateTableExecutor builder(@NotNull String table, @NotNull DatabaseType databaseType) {
return new CreateTableExecutor(table, databaseType);
}
@NotNull
public CreateTableExecutor columns(@NotNull SQLColumn... columns) {
return this.columns(Arrays.asList(columns));
}
@NotNull
public CreateTableExecutor columns(@NotNull List<SQLColumn> columns) {
this.columns.clear();
this.columns.addAll(columns);
return this;
}
@Override
@NotNull
public Void execute(@NotNull AbstractConnector connector) {
if (this.columns.isEmpty()) return null;
String id = "`id` " + ColumnFormer.INTEGER.build(this.databaseType, 11);
if (this.databaseType == DatabaseType.SQLITE) {
id += " PRIMARY KEY AUTOINCREMENT";
}
else {
id += " PRIMARY KEY AUTO_INCREMENT";
}
String columns = id + "," + this.columns.stream()
.map(column -> column.getNameEscaped() + " " + column.formatType(this.databaseType))
.collect(Collectors.joining(", "));
String sql = "CREATE TABLE IF NOT EXISTS " + this.getTable() + "(" + columns + ");";
SQLQueries.executeStatement(connector, sql);
return null;
}
}
@@ -0,0 +1,56 @@
package su.nightexpress.nightcore.database.sql.executor;
import org.jetbrains.annotations.NotNull;
import su.nightexpress.nightcore.database.AbstractConnector;
import su.nightexpress.nightcore.database.sql.SQLCondition;
import su.nightexpress.nightcore.database.sql.SQLExecutor;
import su.nightexpress.nightcore.database.sql.SQLQueries;
import su.nightexpress.nightcore.database.sql.SQLValue;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public final class DeleteQueryExecutor extends SQLExecutor<Void> {
private final List<SQLCondition> wheres;
private DeleteQueryExecutor(@NotNull String table) {
super(table);
this.wheres = new ArrayList<>();
}
@NotNull
public static DeleteQueryExecutor builder(@NotNull String table) {
return new DeleteQueryExecutor(table);
}
@NotNull
public DeleteQueryExecutor where(@NotNull SQLCondition... wheres) {
return this.where(Arrays.asList(wheres));
}
@NotNull
public DeleteQueryExecutor where(@NotNull List<SQLCondition> wheres) {
this.wheres.clear();
this.wheres.addAll(wheres);
return this;
}
@Override
@NotNull
public Void execute(@NotNull AbstractConnector connector) {
if (this.wheres.isEmpty()) return null;
String whereCols = this.wheres.stream()
.map(where -> where.getValue().getColumn().getNameEscaped() + " " + where.getType().getOperator() + " ?")
.collect(Collectors.joining(" AND "));
String sql = "DELETE FROM " + this.getTable() + (whereCols.isEmpty() ? "" : " WHERE " + whereCols);
List<String> whereVals = this.wheres.stream().map(SQLCondition::getValue).map(SQLValue::getValue).toList();
SQLQueries.executeStatement(connector, sql, whereVals);
return null;
}
}
@@ -0,0 +1,54 @@
package su.nightexpress.nightcore.database.sql.executor;
import org.jetbrains.annotations.NotNull;
import su.nightexpress.nightcore.database.AbstractConnector;
import su.nightexpress.nightcore.database.sql.SQLColumn;
import su.nightexpress.nightcore.database.sql.SQLExecutor;
import su.nightexpress.nightcore.database.sql.SQLQueries;
import su.nightexpress.nightcore.database.sql.SQLValue;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public final class InsertQueryExecutor extends SQLExecutor<Void> {
private final List<SQLValue> values;
private InsertQueryExecutor(@NotNull String table) {
super(table);
this.values = new ArrayList<>();
}
@NotNull
public static InsertQueryExecutor builder(@NotNull String table) {
return new InsertQueryExecutor(table);
}
@NotNull
public InsertQueryExecutor values(@NotNull SQLValue... values) {
return this.values(Arrays.asList(values));
}
@NotNull
public InsertQueryExecutor values(@NotNull List<SQLValue> values) {
this.values.clear();
this.values.addAll(values);
return this;
}
@Override
@NotNull
public Void execute(@NotNull AbstractConnector connector) {
if (this.values.isEmpty()) return null;
String columns = this.values.stream().map(SQLValue::getColumn).map(SQLColumn::getNameEscaped).collect(Collectors.joining(","));
String values = this.values.stream().map(value -> "?").collect(Collectors.joining(","));
String sql = "INSERT INTO " + this.getTable() + "(" + columns + ") VALUES(" + values + ")";
List<String> values2 = this.values.stream().map(SQLValue::getValue).toList();
SQLQueries.executeStatement(connector, sql, values2);
return null;
}
}
@@ -0,0 +1,46 @@
package su.nightexpress.nightcore.database.sql.executor;
import org.jetbrains.annotations.NotNull;
import su.nightexpress.nightcore.database.DatabaseType;
import su.nightexpress.nightcore.database.AbstractConnector;
import su.nightexpress.nightcore.database.sql.SQLExecutor;
import su.nightexpress.nightcore.database.sql.SQLQueries;
public final class RenameTableExecutor extends SQLExecutor<Void> {
private final DatabaseType databaseType;
private String renameTo;
private RenameTableExecutor(@NotNull String table, @NotNull DatabaseType databaseType) {
super(table);
this.databaseType = databaseType;
}
@NotNull
public static RenameTableExecutor builder(@NotNull String table, @NotNull DatabaseType databaseType) {
return new RenameTableExecutor(table, databaseType);
}
@NotNull
public RenameTableExecutor renameTo(@NotNull String renameTo) {
this.renameTo = renameTo;
return this;
}
@Override
@NotNull
public Void execute(@NotNull AbstractConnector connector) {
if (this.renameTo == null || this.renameTo.isEmpty()) return null;
if (!SQLQueries.hasTable(connector, this.getTable())) return null;
StringBuilder sql = new StringBuilder();
if (this.databaseType == DatabaseType.MYSQL) {
sql.append("RENAME TABLE ").append(this.getTable()).append(" TO ").append(this.renameTo).append(";");
}
else {
sql.append("ALTER TABLE ").append(this.getTable()).append(" RENAME TO ").append(this.renameTo);
}
SQLQueries.executeStatement(connector, sql.toString());
return null;
}
}
@@ -0,0 +1,85 @@
package su.nightexpress.nightcore.database.sql.executor;
import org.jetbrains.annotations.NotNull;
import su.nightexpress.nightcore.database.AbstractConnector;
import su.nightexpress.nightcore.database.sql.*;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;
public final class SelectQueryExecutor<T> extends SQLExecutor<List<T>> {
private final List<SQLColumn> columns;
private final List<SQLCondition> wheres;
private final Function<ResultSet, T> dataFunction;
private int amount;
private SelectQueryExecutor(@NotNull String table, @NotNull Function<ResultSet, T> dataFunction) {
super(table);
this.columns = new ArrayList<>();
this.wheres = new ArrayList<>();
this.dataFunction = dataFunction;
this.amount = -1;
}
@NotNull
public static <T> SelectQueryExecutor<T> builder(@NotNull String table, @NotNull Function<ResultSet, T> dataFunction) {
return new SelectQueryExecutor<>(table, dataFunction);
}
/*@NotNull
public SelectQueryExecutor<T> all() {
return this.columns(new SQLColumn("*", ColumnType.STRING, -1));
}*/
@NotNull
public SelectQueryExecutor<T> columns(@NotNull SQLColumn... columns) {
return this.columns(Arrays.asList(columns));
}
@NotNull
public SelectQueryExecutor<T> columns(@NotNull List<SQLColumn> columns) {
//if (columns.isEmpty()) return this.all();
this.columns.clear();
this.columns.addAll(columns);
return this;
}
@NotNull
public SelectQueryExecutor<T> where(@NotNull SQLCondition... wheres) {
return this.where(Arrays.asList(wheres));
}
@NotNull
public SelectQueryExecutor<T> where(@NotNull List<SQLCondition> wheres) {
this.wheres.clear();
this.wheres.addAll(wheres);
return this;
}
@NotNull
public SelectQueryExecutor<T> amount(int amount) {
this.amount = amount;
return this;
}
@Override
@NotNull
public List<T> execute(@NotNull AbstractConnector connector) {
String columns = this.columns.stream().map(SQLColumn::getNameEscaped).collect(Collectors.joining(","));
if (columns.isEmpty()) columns = "*";
String wheres = this.wheres.stream().map(where -> where.getColumn().getNameEscaped() + " " + where.getType().getOperator() + " ?")
.collect(Collectors.joining(" AND "));
String sql = "SELECT " + columns + " FROM " + this.getTable() + (wheres.isEmpty() ? "" : " WHERE " + wheres);
List<String> values = this.wheres.stream().map(SQLCondition::getValue).map(SQLValue::getValue).toList();
return SQLQueries.executeQuery(connector, sql, values, this.dataFunction, this.amount);
}
}
@@ -0,0 +1,75 @@
package su.nightexpress.nightcore.database.sql.executor;
import org.jetbrains.annotations.NotNull;
import su.nightexpress.nightcore.database.AbstractConnector;
import su.nightexpress.nightcore.database.sql.SQLCondition;
import su.nightexpress.nightcore.database.sql.SQLExecutor;
import su.nightexpress.nightcore.database.sql.SQLQueries;
import su.nightexpress.nightcore.database.sql.SQLValue;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public final class UpdateQueryExecutor extends SQLExecutor<Void> {
private final List<SQLValue> values;
private final List<SQLCondition> wheres;
private UpdateQueryExecutor(@NotNull String table) {
super(table);
this.values = new ArrayList<>();
this.wheres = new ArrayList<>();
}
@NotNull
public static UpdateQueryExecutor builder(@NotNull String table) {
return new UpdateQueryExecutor(table);
}
@NotNull
public UpdateQueryExecutor values(@NotNull SQLValue... values) {
return this.values(Arrays.asList(values));
}
@NotNull
public UpdateQueryExecutor values(@NotNull List<SQLValue> values) {
this.values.clear();
this.values.addAll(values);
return this;
}
@NotNull
public UpdateQueryExecutor where(@NotNull SQLCondition... wheres) {
return this.where(Arrays.asList(wheres));
}
@NotNull
public UpdateQueryExecutor where(@NotNull List<SQLCondition> wheres) {
this.wheres.clear();
this.wheres.addAll(wheres);
return this;
}
@Override
@NotNull
public Void execute(@NotNull AbstractConnector connector) {
if (this.values.isEmpty()) return null;
String values = this.values.stream().map(value -> value.getColumn().getNameEscaped() + " = ?")
.collect(Collectors.joining(","));
String wheres = this.wheres.stream().map(where -> where.getColumn().getNameEscaped() + " " + where.getType().getOperator() + " ?")
.collect(Collectors.joining(" AND "));
String sql = "UPDATE " + this.getTable() + " SET " + values + (wheres.isEmpty() ? "" : " WHERE " + wheres);
List<String> values2 = this.values.stream().map(SQLValue::getValue).toList();
List<String> whers2 = this.wheres.stream().map(SQLCondition::getValue).map(SQLValue::getValue).toList();
SQLQueries.executeStatement(connector, sql, values2, whers2);
return null;
}
}
@@ -0,0 +1,193 @@
package su.nightexpress.nightcore.dialog;
import net.md_5.bungee.api.chat.ClickEvent;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import su.nightexpress.nightcore.core.CoreLang;
import su.nightexpress.nightcore.menu.api.Menu;
import su.nightexpress.nightcore.menu.impl.AbstractMenu;
import su.nightexpress.nightcore.util.Colorizer;
import su.nightexpress.nightcore.util.text.NightMessage;
import su.nightexpress.nightcore.util.text.WrappedMessage;
import su.nightexpress.nightcore.util.text.tag.Tags;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
public class Dialog {
private static final Map<UUID, Dialog> DIALOG_MAP = new ConcurrentHashMap<>();
public static final String EXIT = "#exit";
public static final String VALUES = "#values";
private final Player player;
private final DialogHandler handler;
private Menu lastMenu;
private List<String> suggestions;
public Dialog(@NotNull Player player, @NotNull DialogHandler handler) {
this.player = player;
this.handler = handler;
this.suggestions = new ArrayList<>();
}
@NotNull
public Player getPlayer() {
return player;
}
@NotNull
public DialogHandler getHandler() {
return handler;
}
@Nullable
public Menu getLastMenu() {
return lastMenu;
}
@NotNull
public Dialog setLastMenu(@Nullable Menu lastMenu) {
this.lastMenu = lastMenu;
return this;
}
@NotNull
public List<String> getSuggestions() {
return suggestions;
}
@NotNull
public Dialog setSuggestions(@NotNull Collection<String> suggestions, boolean autoRun) {
this.suggestions = suggestions.stream().sorted(String::compareTo).collect(Collectors.toCollection(ArrayList::new));
this.displaySuggestions(autoRun, 1);
return this;
}
public void displaySuggestions(boolean autoRun, int page) {
List<String> values = this.getSuggestions();
if (values.isEmpty()) return;
int perPage = 10;
int pages = (int) Math.ceil((double) values.size() / (double) perPage);
if (page < 1) page = 1;
else if (page > pages) page = pages;
int skip = (page - 1) * perPage;
boolean isLastPage = page == pages;
boolean isFirstPage = page == 1;
List<String> items = values.stream().skip(skip).limit(perPage).toList();
ClickEvent.Action action = autoRun ? ClickEvent.Action.RUN_COMMAND : ClickEvent.Action.SUGGEST_COMMAND;
NightMessage.Builder builder = NightMessage.builder();
builder.append("=".repeat(8) + "[ ", Tags.ORANGE);
builder.append("Value Helper", Tags.YELLOW);
builder.append("] " + "=".repeat(8), Tags.ORANGE);
builder.appendLineBreak();
items.forEach(element -> {
String value = element.charAt(0) == '/' ? element : '/' + element;
builder.append("> ", Tags.DARK_GRAY);
builder.append(element, Tags.GREEN)
.showText(Tags.GRAY.enclose( "Click me to select " + Tags.CYAN.enclose(element) + "."))
.clickEvent(action, value);
builder.appendLineBreak();
});
builder.append("=".repeat(9) + " ", Tags.ORANGE);
if (isFirstPage) {
builder.append("[<]", Tags.GRAY);
}
else {
builder.append("[<]", Tags.LIGHT_RED)
.showText(Tags.GRAY.enclose("Previous Page"))
.runCommand("/" + VALUES + " " + (page - 1) + " " + autoRun);
}
builder.append(" " + page, Tags.YELLOW);
builder.append("/", Tags.ORANGE);
builder.append(pages + " ", Tags.YELLOW);
if (isLastPage) {
builder.append("[>]", Tags.GRAY);
}
else {
builder.append("[>]", Tags.LIGHT_RED)
.showText(Tags.GRAY.enclose("Next Page"))
.runCommand("/" + VALUES + " " + (page + 1) + " " + autoRun);
}
builder.append(" " + "=".repeat(9), Tags.ORANGE);
builder.send(this.getPlayer());
}
@Deprecated
public void prompt(@NotNull String text) {
this.sendInfo(CoreLang.EDITOR_INPUT_HEADER_MAIN.getMessage().toLegacy(), Colorizer.apply(text));
}
public void prompt(@NotNull WrappedMessage text) {
this.info(CoreLang.EDITOR_INPUT_HEADER_MAIN.getMessage(), text);
}
@Deprecated
public void error(@NotNull String text) {
this.sendInfo(CoreLang.EDITOR_INPUT_HEADER_ERROR.getMessage().toLegacy(), Colorizer.apply(text));
}
public void error(@NotNull WrappedMessage text) {
this.info(CoreLang.EDITOR_INPUT_HEADER_ERROR.getMessage(), text);
}
public void info(@NotNull WrappedMessage title, @NotNull WrappedMessage text) {
this.sendInfo(title.toLegacy(), text.toLegacy());
}
@Deprecated
public void info(@NotNull String title, @NotNull String text) {
this.sendInfo(Colorizer.apply(title), Colorizer.apply(text));
}
private void sendInfo(@NotNull String title, @NotNull String text) {
this.getPlayer().sendTitle(title, text, 20, Short.MAX_VALUE, 20);
}
@NotNull
public static Dialog create(@NotNull Player player, @NotNull DialogHandler handler) {
Dialog dialog = new Dialog(player, handler)
.setLastMenu(AbstractMenu.getMenu(player));
DIALOG_MAP.put(player.getUniqueId(), dialog);
CoreLang.EDITOR_ACTION_EXIT.getMessage().send(player);
return dialog;
}
@Nullable
public static Dialog get(@NotNull Player player) {
return DIALOG_MAP.get(player.getUniqueId());
}
public static void stop(@NotNull Player player) {
Dialog dialog = DIALOG_MAP.remove(player.getUniqueId());
if (dialog == null) return;
Menu menu = dialog.getLastMenu();
if (menu != null) {
menu.open(player);
}
player.sendTitle("", "", 1, 1, 1);
}
public static void shutdown() {
DIALOG_MAP.clear();
}
public static boolean contains(@NotNull Player player) {
return get(player) != null;
}
}
@@ -0,0 +1,8 @@
package su.nightexpress.nightcore.dialog;
import org.jetbrains.annotations.NotNull;
public interface DialogHandler {
boolean onInput(@NotNull WrappedInput input);
}
@@ -0,0 +1,73 @@
package su.nightexpress.nightcore.dialog;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.player.AsyncPlayerChatEvent;
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.jetbrains.annotations.NotNull;
import su.nightexpress.nightcore.NightCore;
import su.nightexpress.nightcore.manager.AbstractListener;
import su.nightexpress.nightcore.util.Colorizer;
import su.nightexpress.nightcore.util.NumberUtil;
import java.util.HashSet;
public class DialogListener extends AbstractListener<NightCore> {
public DialogListener(@NotNull NightCore plugin) {
super(plugin);
}
@EventHandler(priority = EventPriority.MONITOR)
public void onQuit(PlayerQuitEvent event) {
Dialog.stop(event.getPlayer());
}
@EventHandler(priority = EventPriority.LOWEST)
public void onChatText(AsyncPlayerChatEvent event) {
Player player = event.getPlayer();
Dialog dialog = Dialog.get(player);
if (dialog == null) return;
event.getRecipients().clear();
event.setCancelled(true);
WrappedInput input = new WrappedInput(event);
this.plugin.runTask(task -> {
if (input.getTextRaw().equalsIgnoreCase(Dialog.EXIT) || dialog.getHandler().onInput(input)) {
Dialog.stop(player);
}
});
}
@EventHandler(priority = EventPriority.LOWEST)
public void onChatCommand(PlayerCommandPreprocessEvent event) {
Player player = event.getPlayer();
Dialog dialog = Dialog.get(player);
if (dialog == null) return;
event.setCancelled(true);
String raw = event.getMessage();
String text = Colorizer.apply(raw.substring(1));
if (text.startsWith(Dialog.VALUES)) {
String[] split = text.split(" ");
int page = split.length >= 2 ? NumberUtil.getInteger(split[1], 0) : 0;
boolean auto = split.length >= 3 && Boolean.parseBoolean(split[2]);
dialog.displaySuggestions(auto, page);
return;
}
AsyncPlayerChatEvent chatEvent = new AsyncPlayerChatEvent(true, player, text, new HashSet<>());
WrappedInput input = new WrappedInput(chatEvent);
this.plugin.runTask(task -> {
if (input.getTextRaw().equalsIgnoreCase(Dialog.EXIT) || dialog.getHandler().onInput(input)) {
Dialog.stop(player);
}
});
}
}
@@ -0,0 +1,92 @@
package su.nightexpress.nightcore.dialog;
import org.bukkit.event.player.AsyncPlayerChatEvent;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import su.nightexpress.nightcore.util.Colorizer;
import su.nightexpress.nightcore.util.NumberUtil;
import su.nightexpress.nightcore.util.StringUtil;
import su.nightexpress.nightcore.util.wrapper.UniDouble;
import su.nightexpress.nightcore.util.wrapper.UniInt;
public class WrappedInput {
private final String text;
private final String textRaw;
private final String textColored;
public WrappedInput(@NotNull AsyncPlayerChatEvent event) {
this(event.getMessage());
}
public WrappedInput(@NotNull String text) {
this.text = text;
this.textRaw = Colorizer.restrip(text); // TODO Modern formation, but keep colorizer to support legacy codes for other chat format plugins
this.textColored = Colorizer.apply(text);
}
public int asInt() {
return this.asInt(0);
}
public int asInt(int def) {
return NumberUtil.getInteger(this.getTextRaw(), def);
}
public int asAnyInt(int def) {
return NumberUtil.getAnyInteger(this.getTextRaw(), def);
}
public double asDouble() {
return this.asDouble(0D);
}
public double asDouble(double def) {
return NumberUtil.getDouble(this.getTextRaw(), def);
}
@NotNull
public UniDouble asUniDouble() {
return this.asUniDouble(0, 0);
}
@NotNull
public UniDouble asUniDouble(double min, double max) {
String[] split = this.getTextRaw().split(" ");
return UniDouble.of(NumberUtil.getDouble(split[0], min), NumberUtil.getDouble(split.length >= 2 ? split[1] : split[0], max));
}
@NotNull
public UniInt asUniInt() {
return this.asUniDouble().asInt();
}
public double asAnyDouble(double def) {
return NumberUtil.getAnyDouble(this.getTextRaw(), def);
}
@Nullable
public <E extends Enum<E>> E asEnum(@NotNull Class<E> clazz) {
return StringUtil.getEnum(this.getTextRaw(), clazz).orElse(null);
}
@NotNull
public <E extends Enum<E>> E asEnum(@NotNull Class<E> clazz, @NotNull E def) {
return StringUtil.getEnum(this.getTextRaw(), clazz).orElse(def);
}
@NotNull
public String getText() {
return text;
}
@NotNull
public String getTextRaw() {
return textRaw;
}
@NotNull
public String getTextColored() {
return textColored;
}
}
@@ -0,0 +1,162 @@
package su.nightexpress.nightcore.integration;
import net.milkbowl.vault.chat.Chat;
import net.milkbowl.vault.economy.Economy;
import net.milkbowl.vault.permission.Permission;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.entity.Player;
import org.bukkit.event.server.ServiceRegisterEvent;
import org.bukkit.plugin.RegisteredServiceProvider;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import su.nightexpress.nightcore.util.Plugins;
import java.util.Collections;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class VaultHook {
private static Economy economy;
private static Permission permission;
private static Chat chat;
public static void setup() {
setPermission();
setEconomy();
setChat();
}
public static void shutdown() {
economy = null;
permission = null;
chat = null;
}
@Nullable
private static <T> T getProvider(@NotNull Class<T> clazz) {
RegisteredServiceProvider<T> rsp = Bukkit.getServer().getServicesManager().getRegistration(clazz);
return rsp == null ? null : rsp.getProvider();
}
private static void setPermission() {
permission = getProvider(Permission.class);
if (permission != null) {
Plugins.CORE.info("Found permissions provider: " + permission.getName());
}
}
private static void setEconomy() {
economy = getProvider(Economy.class);
if (economy != null) {
Plugins.CORE.info("Found economy provider: " + economy.getName());
}
}
private static void setChat() {
chat = getProvider(Chat.class);
if (chat != null) {
Plugins.CORE.info("Found chat provider: " + chat.getName());
}
}
public static void onServiceRegisterEvent(@NotNull ServiceRegisterEvent event) {
Object provider = event.getProvider().getProvider();
if (economy == null && provider instanceof Economy) {
setEconomy();
}
else if (permission == null && provider instanceof Permission) {
setPermission();
}
else if (chat == null && provider instanceof Chat) {
setChat();
}
}
public static boolean hasPermissions() {
return getPermissions() != null;
}
@Nullable
public static Permission getPermissions() {
return permission;
}
public static boolean hasChat() {
return getChat() != null;
}
@Nullable
public static Chat getChat() {
return chat;
}
public static boolean hasEconomy() {
return getEconomy() != null;
}
@Nullable
public static Economy getEconomy() {
return economy;
}
@NotNull
public static String getEconomyName() {
return hasEconomy() ? economy.getName() : "null";
}
@NotNull
public static String getPermissionGroup(@NotNull Player player) {
if (!hasPermissions() || !permission.hasGroupSupport()) return "";
String group = permission.getPrimaryGroup(player);
return group == null ? "" : group.toLowerCase();
}
@NotNull
public static Set<String> getPermissionGroups(@NotNull Player player) {
if (!hasPermissions() || !permission.hasGroupSupport()) return Collections.emptySet();
String[] groups = permission.getPlayerGroups(player);
if (groups == null) groups = new String[] {getPermissionGroup(player)};
return Stream.of(groups).map(String::toLowerCase).collect(Collectors.toSet());
}
@NotNull
public static String getPrefix(@NotNull Player player) {
return hasChat() ? chat.getPlayerPrefix(player) : "";
}
@NotNull
public static String getSuffix(@NotNull Player player) {
return hasChat() ? chat.getPlayerSuffix(player) : "";
}
public static double getBalance(@NotNull Player player) {
return economy.getBalance(player);
}
public static double getBalance(@NotNull OfflinePlayer player) {
return economy.getBalance(player);
}
public static boolean addMoney(@NotNull Player player, double amount) {
return addMoney((OfflinePlayer) player, amount);
}
public static boolean addMoney(@NotNull OfflinePlayer player, double amount) {
return economy.depositPlayer(player, amount).transactionSuccess();
}
public static boolean takeMoney(@NotNull Player player, double amount) {
return takeMoney((OfflinePlayer) player, amount);
}
public static boolean takeMoney(@NotNull OfflinePlayer player, double amount) {
return economy.withdrawPlayer(player, Math.abs(amount)).transactionSuccess();
}
}
@@ -0,0 +1,120 @@
package su.nightexpress.nightcore.language;
import org.bukkit.Keyed;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.EntityType;
import org.bukkit.potion.PotionEffectType;
import org.jetbrains.annotations.NotNull;
import su.nightexpress.nightcore.NightCore;
import su.nightexpress.nightcore.config.FileConfig;
import su.nightexpress.nightcore.util.*;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.util.Optional;
public class LangAssets {
private static FileConfig config;
public static void load() {
NightCore core = Plugins.CORE;
String langCode = core.getLanguage();
String assetsCode = downloadAssets(core, langCode);
config = FileConfig.loadOrExtract(core, LangManager.DIR_LANG, getFileName(assetsCode));
}
@NotNull
private static String downloadAssets(@NotNull NightCore plugin, @NotNull String langCode) {
File file = new File(plugin.getDataFolder().getAbsolutePath() + LangManager.DIR_LANG, getFileName(langCode));
if (file.exists()) return langCode;
FileUtil.create(file);
String url = "https://github.com/nulli0n/NexEngine-spigot/raw/master/assets/" + langCode + ".yml";
try (BufferedInputStream in = new BufferedInputStream(new URL(url).openStream());
FileOutputStream fileOutputStream = new FileOutputStream(file)) {
plugin.info("Downloading '" + langCode + "' assets from github...");
byte[] dataBuffer = new byte[1024];
int bytesRead;
while ((bytesRead = in.read(dataBuffer, 0, 1024)) != -1) {
fileOutputStream.write(dataBuffer, 0, bytesRead);
}
return langCode;
}
catch (IOException exception) {
//exception.printStackTrace();
plugin.error("Could not download language assets for '" + langCode + "' (no such assets?).");
return LangManager.isDefault(langCode) ? langCode : downloadAssets(plugin, LangManager.DEFAULT_LANGUAGE);
}
}
@NotNull
private static String getFileName(@NotNull String langCode) {
return "assets_" + langCode + ".yml";
}
@NotNull
public static FileConfig getConfig() {
return config;
}
@NotNull
public static String get(@NotNull PotionEffectType type) {
return getAsset("PotionEffectType", type);
}
@NotNull
public static String get(@NotNull EntityType type) {
return getAsset("EntityType", type);
}
@NotNull
public static String get(@NotNull Material type) {
return getAsset("Material", type);
}
@NotNull
public static String get(@NotNull World world) {
return getOrCreate("World", world);
}
@NotNull
public static String get(@NotNull Enchantment enchantment) {
return getOrCreate("Enchantment", enchantment);
}
@NotNull
public static String getAsset(@NotNull String path, @NotNull Keyed keyed) {
return getAsset(path, keyed.getKey().getKey());
}
@NotNull
public static String getAsset(@NotNull String path, @NotNull String nameRaw) {
return getAsset(path + "." + nameRaw).orElse(nameRaw);
}
@NotNull
public static Optional<String> getAsset(@NotNull String path) {
return Optional.ofNullable(config.getString(path)).map(Colorizer::apply);
}
@NotNull
public static String getOrCreate(@NotNull String path, @NotNull Keyed keyed) {
return getOrCreate(path, keyed.getKey().getKey());
}
@NotNull
public static String getOrCreate(@NotNull String path, @NotNull String nameRaw) {
config.addMissing(path + "." + nameRaw, StringUtil.capitalizeUnderscored(nameRaw));
config.saveChanges();
return getAsset(path, nameRaw);
}
}
@@ -0,0 +1,94 @@
package su.nightexpress.nightcore.language;
import org.jetbrains.annotations.NotNull;
import su.nightexpress.nightcore.NightCorePlugin;
import su.nightexpress.nightcore.config.FileConfig;
import su.nightexpress.nightcore.manager.SimpleManager;
import su.nightexpress.nightcore.language.entry.LangEntry;
import su.nightexpress.nightcore.util.FileUtil;
import su.nightexpress.nightcore.util.Reflex;
import su.nightexpress.nightcore.util.StringUtil;
import java.io.File;
import java.io.InputStream;
public class LangManager extends SimpleManager<NightCorePlugin> {
public static final String DEFAULT_LANGUAGE = "en";
public static final String DIR_LANG = "/lang/";
private FileConfig config;
public LangManager(@NotNull NightCorePlugin plugin) {
super(plugin);
}
@Override
protected void onLoad() {
String langCode = this.plugin.getLanguage();
String realCode = this.extractConfig(langCode);
this.config = new FileConfig(this.plugin.getDataFolder() + DIR_LANG, this.getFileName(realCode));
}
@Override
protected void onShutdown() {
}
@NotNull
private String extractConfig(@NotNull String langCode) {
String fileName = this.getFileName(langCode);
File file = new File(plugin.getDataFolder() + DIR_LANG, fileName);
if (file.exists()) return langCode;
try {
InputStream input = plugin.getClass().getResourceAsStream(DIR_LANG + fileName);
if (input != null) {
FileUtil.create(file);
FileUtil.copy(input, file);
return langCode;
}
return isDefault(langCode) ? langCode : this.extractConfig(DEFAULT_LANGUAGE);
}
catch (Exception exception) {
exception.printStackTrace();
return isDefault(langCode) ? langCode : this.extractConfig(DEFAULT_LANGUAGE);
}
}
public void loadEntries(@NotNull Class<?> clazz) {
Reflex.getFields(clazz, LangEntry.class).forEach(entry -> {
entry.load(this.plugin);
});
}
/*public void loadEditor(@NotNull Class<?> clazz) {
Reflex.getFields(clazz, LangItem.class).forEach(entry -> {
entry.load(this.plugin);
});
}*/
public void loadEnum(@NotNull Class<? extends Enum<?>> clazz) {
for (Object eName : clazz.getEnumConstants()) {
String name = eName.toString();
String path = clazz.getSimpleName() + "." + name;
String val = StringUtil.capitalizeUnderscored(name);
this.getConfig().addMissing(path, val);
}
}
public static boolean isDefault(@NotNull String langCode) {
return langCode.equalsIgnoreCase(DEFAULT_LANGUAGE);
}
@NotNull
public String getFileName(@NotNull String langCode) {
return "messages_" + langCode + ".yml";
}
@NotNull
public FileConfig getConfig() {
return config;
}
}
@@ -0,0 +1,31 @@
package su.nightexpress.nightcore.language.entry;
import org.jetbrains.annotations.NotNull;
import su.nightexpress.nightcore.NightCorePlugin;
import su.nightexpress.nightcore.config.FileConfig;
public abstract class LangEntry<T> {
protected final String path;
protected final String defaultText;
public LangEntry(@NotNull String path, @NotNull String defaultText) {
this.path = path;
this.defaultText = defaultText;
}
public abstract boolean write(@NotNull FileConfig config);
@NotNull
public abstract T load(@NotNull NightCorePlugin plugin);
@NotNull
public String getPath() {
return path;
}
@NotNull
public String getDefaultText() {
return defaultText;
}
}
@@ -0,0 +1,227 @@
package su.nightexpress.nightcore.language.entry;
import org.bukkit.inventory.ItemStack;
import org.jetbrains.annotations.NotNull;
import su.nightexpress.nightcore.NightCorePlugin;
import su.nightexpress.nightcore.config.FileConfig;
import su.nightexpress.nightcore.util.ItemUtil;
import su.nightexpress.nightcore.util.Pair;
import su.nightexpress.nightcore.util.text.NightMessage;
import su.nightexpress.nightcore.util.text.WrappedMessage;
import su.nightexpress.nightcore.util.text.tag.Tags;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class LangItem extends LangEntry<Pair<String, List<String>>> {
private final List<String> defaultLore;
private String localizedName;
private List<String> localizedLore;
private WrappedMessage wrappedName;
private List<WrappedMessage> wrappedLore;
public LangItem(@NotNull String key, @NotNull String defaultName, @NotNull List<String> defaultLore) {
super(key, defaultName);
this.defaultLore = defaultLore;
}
@NotNull
public static LangItem of(@NotNull String key, @NotNull String name, @NotNull String... lore) {
return new LangItem(key, name, Arrays.asList(lore));
}
@Override
public boolean write(@NotNull FileConfig config) {
if (!config.contains(this.getPath())) {
config.set(this.getPath() + ".Name", this.getDefaultName());
config.set(this.getPath() + ".Lore", this.getDefaultLore());
return true;
}
return false;
}
@Override
@NotNull
public Pair<String, List<String>> load(@NotNull NightCorePlugin plugin) {
FileConfig config = plugin.getLang();
this.write(config);
this.setLocalizedName(config.getString(this.getPath() + ".Name", this.getDefaultName()));
this.setLocalizedLore(config.getStringList(this.getPath() + ".Lore"));
return Pair.of(this.getLocalizedName(), this.getLocalizedLore());
}
public void apply(@NotNull ItemStack item) {
ItemUtil.editMeta(item, meta -> {
meta.setDisplayName(this.getWrappedName().toLegacy());
meta.setLore(this.getWrappedLore().stream().map(WrappedMessage::toLegacy).toList());
});
}
@NotNull
public String getDefaultName() {
return this.getDefaultText();
}
@NotNull
public List<String> getDefaultLore() {
return defaultLore;
}
@NotNull
public String getLocalizedName() {
return localizedName;
}
public void setLocalizedName(@NotNull String localizedName) {
this.localizedName = localizedName;
this.wrappedName = NightMessage.create(localizedName);
}
@NotNull
public List<String> getLocalizedLore() {
return localizedLore;
}
public void setLocalizedLore(@NotNull List<String> localizedLore) {
this.localizedLore = localizedLore;
this.wrappedLore = new ArrayList<>();
localizedLore.forEach(line -> wrappedLore.add(NightMessage.create(line)));
}
@NotNull
public WrappedMessage getWrappedName() {
return wrappedName;
}
@NotNull
public List<WrappedMessage> getWrappedLore() {
return wrappedLore;
}
protected static final String LMB = "Left-Click";
protected static final String RMB = "Right-Click";
protected static final String DROP_KEY = "[Q] Drop Key";
protected static final String SWAP_KEY = "[F] Swap Key";
protected static final String SHIFT_LMB = "Shift-Left";
protected static final String SHIFT_RMB = "Shift-Right";
protected static final String DRAG_DROP = "Drag & Drop";
@NotNull
public static Builder builder(@NotNull String key) {
return new Builder(key);
}
public static final class Builder {
private final String key;
private String name;
private final List<String> lore;
public Builder(@NotNull String key) {
this.key = key;
this.name = "";
this.lore = new ArrayList<>();
}
@NotNull
public LangItem build() {
return new LangItem(this.key, this.name, this.lore);
}
@NotNull
public Builder name(@NotNull String name) {
this.name = Tags.YELLOW.enclose(Tags.BOLD.enclose(name));
return this;
}
@NotNull
public Builder text(@NotNull String... text) {
for (String str : text) {
this.addLore(Tags.GRAY.enclose(str));
}
return this;
}
@NotNull
public Builder textRaw(@NotNull String... text) {
return this.addLore(text);
}
@NotNull
public Builder currentHeader() {
return this.addLore(Tags.YELLOW.enclose(Tags.BOLD.enclose("Current:")));
}
@NotNull
public Builder current(@NotNull String type, @NotNull String value) {
return this.addLore(Tags.YELLOW.enclose("▪ " + Tags.GRAY.enclose(type) + ": " + value));
}
@NotNull
public Builder leftClick(@NotNull String action) {
return this.click(LMB, action);
}
@NotNull
public Builder rightClick(@NotNull String action) {
return this.click(RMB, action);
}
@NotNull
public Builder shiftLeft(@NotNull String action) {
return this.click(SHIFT_LMB, action);
}
@NotNull
public Builder shiftRight(@NotNull String action) {
return this.click(SHIFT_RMB, action);
}
@NotNull
public Builder dropKey(@NotNull String action) {
return this.click(DROP_KEY, action);
}
@NotNull
public Builder swapKey(@NotNull String action) {
return this.click(SWAP_KEY, action);
}
@NotNull
public Builder dragAndDrop(@NotNull String action) {
return this.click(DRAG_DROP, action);
}
@NotNull
public Builder click(@NotNull String click, @NotNull String action) {
return this.addLore(Tags.GRAY.enclose("(" + Tags.WHITE.enclose(click) + " to " + action + ")"));
}
@NotNull
public Builder emptyLine() {
return this.addLore("");
}
/*@NotNull
private Builder addLore(@NotNull String prefix, @NotNull String... text) {
for (String str : text) {
this.lore.add(prefix + str);
}
return this;
}*/
@NotNull
private Builder addLore(@NotNull String... text) {
Collections.addAll(this.lore, text);
return this;
}
}
}
@@ -0,0 +1,64 @@
package su.nightexpress.nightcore.language.entry;
import org.jetbrains.annotations.NotNull;
import su.nightexpress.nightcore.NightCorePlugin;
import su.nightexpress.nightcore.config.FileConfig;
import su.nightexpress.nightcore.util.text.NightMessage;
import su.nightexpress.nightcore.util.text.WrappedMessage;
public class LangString extends LangEntry<String> {
private String string;
private WrappedMessage message;
public LangString(@NotNull String path, @NotNull String defaultText) {
super(path, defaultText);
}
@NotNull
public static LangString of(@NotNull String path, @NotNull String defaultText) {
return new LangString(path, defaultText);
}
@Override
public boolean write(@NotNull FileConfig config) {
if (!config.contains(this.getPath())) {
String textDefault = this.getDefaultText();
config.set(this.getPath(), textDefault);
return true;
}
return false;
}
@Override
@NotNull
public String load(@NotNull NightCorePlugin plugin) {
FileConfig config = plugin.getLang();
this.write(config);
String text = config.getString(this.getPath(), this.getPath());
this.setString(text);
return this.getString();
}
@NotNull
public String getString() {
return string;
}
public void setString(@NotNull String string) {
this.string = string;
this.message = NightMessage.from(string);
}
@NotNull
public WrappedMessage getMessage() {
return this.message;
}
@NotNull
public String getLegacy() {
return this.getMessage().toLegacy();
}
}
@@ -0,0 +1,67 @@
package su.nightexpress.nightcore.language.entry;
import org.jetbrains.annotations.NotNull;
import su.nightexpress.nightcore.NightCorePlugin;
import su.nightexpress.nightcore.config.FileConfig;
import su.nightexpress.nightcore.language.message.LangMessage;
import su.nightexpress.nightcore.util.Placeholders;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class LangText extends LangEntry<LangMessage> {
private LangMessage message;
public LangText(@NotNull String path, @NotNull String... defaultText) {
super(path, String.join("\n", defaultText));
}
@NotNull
public static LangText of(@NotNull String path, @NotNull String defaultText) {
return new LangText(path, defaultText);
}
@NotNull
public static LangText of(@NotNull String path, @NotNull String... defaultText) {
return new LangText(path, defaultText);
}
@Override
public boolean write(@NotNull FileConfig config) {
if (!config.contains(this.getPath())) {
String textDefault = this.getDefaultText();
String[] textSplit = textDefault.split("\n");
config.set(this.getPath(), textSplit.length > 1 ? Arrays.asList(textSplit) : textDefault);
return true;
}
return false;
}
@Override
@NotNull
public LangMessage load(@NotNull NightCorePlugin plugin) {
FileConfig config = plugin.getLang();
this.write(config);
List<String> text = new ArrayList<>(config.getStringList(this.getPath()));
if (text.isEmpty()) {
text.add(config.getString(this.getPath(), this.getPath()));
}
this.setMessage(LangMessage.parse(plugin, String.join(Placeholders.TAG_LINE_BREAK, text)));
return this.getMessage();
}
@NotNull
public LangMessage getMessage() {
return message;
}
public void setMessage(@NotNull LangMessage message) {
this.message = message;
}
}
@@ -0,0 +1,179 @@
package su.nightexpress.nightcore.language.legacy;
import me.clip.placeholderapi.PlaceholderAPI;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
import su.nightexpress.nightcore.NightCorePlugin;
import su.nightexpress.nightcore.language.message.OutputType;
import su.nightexpress.nightcore.util.Colorizer;
import su.nightexpress.nightcore.util.Players;
import su.nightexpress.nightcore.util.message.NexParser;
import su.nightexpress.nightcore.util.regex.TimedMatcher;
import su.nightexpress.nightcore.util.wrapper.UniSound;
import java.util.ArrayList;
import java.util.List;
import java.util.function.BiConsumer;
import java.util.function.Predicate;
import java.util.function.UnaryOperator;
import java.util.regex.Pattern;
@Deprecated
public class LegacyLangMessage {
private static final Pattern OPTIONS_PATTERN = Pattern.compile("<\\!(.*?)\\!>");
private final NightCorePlugin plugin;
private final LegacyMessageOptions options;
private final List<String> defaultText;
private List<String> text;
public LegacyLangMessage(@NotNull NightCorePlugin plugin, @NotNull List<String> defaultText) {
this.plugin = plugin;
this.options = new LegacyMessageOptions();
this.defaultText = defaultText;
this.setText(defaultText);
this.setOptions();
}
private LegacyLangMessage(@NotNull LegacyLangMessage from) {
this.plugin = from.plugin;
this.options = from.options.copy();
this.defaultText = new ArrayList<>(from.defaultText);
this.text = new ArrayList<>(from.text);
}
private void setOptions() {
List<String> text = this.getText();
if (text.isEmpty()) return;
String msg = text.get(0);
TimedMatcher matcher = TimedMatcher.create(OPTIONS_PATTERN, msg);
if (!matcher.find()) return;
String optionTag = matcher.getMatcher().group(0);
String optionArgs = matcher.getMatcher().group(1).trim();
this.text.set(0, msg.replace(optionTag, ""));
this.text.removeIf(String::isEmpty);
this.options.read(optionArgs);
}
@NotNull
public List<String> getDefaultText() {
return this.defaultText;
}
@NotNull
public List<String> getText() {
return this.text;
}
@NotNull
public List<String> getText(@NotNull CommandSender sender) {
if (!this.options.hasPlaceholderAPI() || !(sender instanceof Player player)) return this.getText();
List<String> text = new ArrayList<>(this.getText());
text.replaceAll(line -> PlaceholderAPI.setPlaceholders(player, line));
return text;
}
private void setText(@NotNull List<String> text) {
this.text = Colorizer.apply(text);
this.text.removeIf(String::isEmpty);
}
@NotNull
public LegacyLangMessage replace(@NotNull String var, @NotNull Object replacer) {
return this.replace(str -> str.replace(var, String.valueOf(replacer)));
}
@NotNull
public LegacyLangMessage replace(@NotNull UnaryOperator<String> replacer) {
if (this.isEmpty()) return this;
LegacyLangMessage msgCopy = new LegacyLangMessage(this);
msgCopy.getText().replaceAll(replacer);
return msgCopy;
}
@NotNull
public LegacyLangMessage replace(@NotNull Predicate<String> predicate, @NotNull BiConsumer<String, List<String>> replacer) {
if (this.isEmpty()) return this;
LegacyLangMessage msgCopy = new LegacyLangMessage(this);
List<String> replaced = new ArrayList<>();
msgCopy.getText().forEach(line -> {
if (predicate.test(line)) {
replacer.accept(line, replaced);
return;
}
replaced.add(line);
});
msgCopy.setText(replaced);
return msgCopy;
}
public boolean isEmpty() {
return (this.options.getType() == OutputType.NONE || this.getText().isEmpty());
}
public void broadcast() {
if (this.isEmpty()) return;
Bukkit.getServer().getOnlinePlayers().forEach(this::send);
this.send(Bukkit.getServer().getConsoleSender());
}
public void send(@NotNull CommandSender sender) {
if (this.isEmpty()) return;
if (this.options.getSound() != null && sender instanceof Player player) {
UniSound.of(this.options.getSound()).play(player);
}
if (this.options.getType() == OutputType.CHAT) {
String prefix = this.options.hasPrefix() ? plugin.getPrefix() : "";
this.getText(sender).forEach(line -> {
Players.sendRichMessage(sender, prefix + line);
});
return;
}
if (sender instanceof Player player) {
if (this.options.getType() == OutputType.ACTION_BAR) {
Players.sendActionBar(player, String.join(" ", this.getText(player)));
}
else if (this.options.getType() == OutputType.TITLES) {
List<String> list = this.getText(player);
String title = list.size() > 0 ? NexParser.toPlainText(list.get(0)) : "";
String subtitle = list.size() > 1 ? NexParser.toPlainText(list.get(1)) : "";
player.sendTitle(title, subtitle, this.options.getTitleTimes()[0], this.options.getTitleTimes()[1], this.options.getTitleTimes()[2]);
}
}
}
/*@NotNull
public List<String> asList() {
return this.asList(this.getText());
}
@NotNull
public List<String> asList(@NotNull CommandSender sender) {
return this.asList(this.getText(sender));
}
@NotNull
private List<String> asList(@NotNull String localized) {
return this.isEmpty() ? Collections.emptyList() : Stream.of(localized.split("\\\\n"))
.filter(Predicate.not(String::isEmpty)).toList();
}
@NotNull
@Deprecated
public String normalizeLines() {
return String.join("\n", this.asList());
}*/
}
@@ -0,0 +1,53 @@
package su.nightexpress.nightcore.language.legacy;
import org.jetbrains.annotations.NotNull;
import su.nightexpress.nightcore.NightCorePlugin;
import su.nightexpress.nightcore.config.FileConfig;
import su.nightexpress.nightcore.language.entry.LangEntry;
import su.nightexpress.nightcore.util.Colorizer;
@Deprecated
public class LegacyLangString extends LangEntry<String> {
private String string;
public LegacyLangString(@NotNull String path, @NotNull String defaultText) {
super(path, defaultText);
}
@NotNull
public static LegacyLangString of(@NotNull String path, @NotNull String defaultText) {
return new LegacyLangString(path, defaultText);
}
@Override
public boolean write(@NotNull FileConfig config) {
if (!config.contains(this.getPath())) {
String textDefault = this.getDefaultText();
config.set(this.getPath(), textDefault);
return true;
}
return false;
}
@Override
@NotNull
public String load(@NotNull NightCorePlugin plugin) {
FileConfig config = plugin.getLang();
this.write(config);
String text = config.getString(this.getPath(), "<" + this.getPath() + ">");
this.setString(text);
return this.getString();
}
@NotNull
public String getString() {
return string;
}
public void setString(@NotNull String string) {
this.string = Colorizer.apply(string);
}
}
@@ -0,0 +1,68 @@
package su.nightexpress.nightcore.language.legacy;
import org.jetbrains.annotations.NotNull;
import su.nightexpress.nightcore.NightCorePlugin;
import su.nightexpress.nightcore.config.FileConfig;
import su.nightexpress.nightcore.language.entry.LangEntry;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
@Deprecated
public class LegacyLangText extends LangEntry<LegacyLangMessage> {
private LegacyLangMessage message;
public LegacyLangText(@NotNull String path, @NotNull String... defaultText) {
super(path, String.join("\n", defaultText));
}
@NotNull
public static LegacyLangText of(@NotNull String path, @NotNull String defaultText) {
return new LegacyLangText(path, defaultText);
}
@NotNull
public static LegacyLangText of(@NotNull String path, @NotNull String... defaultText) {
return new LegacyLangText(path, defaultText);
}
@Override
public boolean write(@NotNull FileConfig config) {
if (!config.contains(this.getPath())) {
String textDefault = this.getDefaultText();
String[] textSplit = textDefault.split("\n");
config.set(this.getPath(), textSplit.length > 1 ? Arrays.asList(textSplit) : textDefault);
return true;
}
return false;
}
@Override
@NotNull
public LegacyLangMessage load(@NotNull NightCorePlugin plugin) {
FileConfig config = plugin.getLang();
this.write(config);
List<String> text = new ArrayList<>(config.getStringList(this.getPath()));
if (text.isEmpty()) {
text.add(config.getString(this.getPath(), "<" + this.getPath() + ">"));
}
//String text = !list.isEmpty() ? String.join("\\n", list) : config.getString(this.getPath(), "<" + this.getPath() + ">");
this.setMessage(new LegacyLangMessage(plugin, text));
return this.getMessage();
}
@NotNull
public LegacyLangMessage getMessage() {
return message;
}
public void setMessage(@NotNull LegacyLangMessage message) {
this.message = message;
}
}
@@ -0,0 +1,26 @@
package su.nightexpress.nightcore.language.legacy;
import org.jetbrains.annotations.NotNull;
import java.util.regex.Pattern;
@Deprecated
public enum LegacyMessageOption {
PREFIX("prefix"),
SOUND("sound"),
TYPE("type"),
PAPI("papi"),
;
private final Pattern pattern;
LegacyMessageOption(@NotNull String name) {
this.pattern = Pattern.compile(name + ":(?:'|\")(.*?)(?:'|\")(?=>|\\s|$)");
}
@NotNull
public Pattern getPattern() {
return pattern;
}
}
@@ -0,0 +1,86 @@
package su.nightexpress.nightcore.language.legacy;
import org.bukkit.Sound;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import su.nightexpress.nightcore.language.message.OutputType;
import su.nightexpress.nightcore.util.NumberUtil;
import su.nightexpress.nightcore.util.Plugins;
import su.nightexpress.nightcore.util.StringUtil;
import su.nightexpress.nightcore.util.regex.TimedMatcher;
@Deprecated
public class LegacyMessageOptions {
private OutputType type;
private boolean hasPrefix;
private boolean papi;
private Sound sound;
private int[] titleTimes;
public LegacyMessageOptions() {
this.type = OutputType.CHAT;
this.hasPrefix = true;
}
@NotNull
public LegacyMessageOptions copy() {
LegacyMessageOptions copy = new LegacyMessageOptions();
copy.type = this.type;
copy.hasPrefix = this.hasPrefix;
copy.papi = this.papi;
copy.sound = this.sound;
copy.titleTimes = this.titleTimes;
return copy;
}
public void read(@NotNull String matchOptions) {
for (LegacyMessageOption option : LegacyMessageOption.values()) {
TimedMatcher matcherParam = TimedMatcher.create(option.getPattern(), matchOptions);
if (!matcherParam.find()) continue;
String optionValue = matcherParam.getMatcher().group(1).stripLeading();
switch (option) {
case TYPE -> {
String[] split = optionValue.split(":");
this.type = StringUtil.getEnum(split[0], OutputType.class).orElse(OutputType.CHAT);
if (this.type == OutputType.TITLES) {
this.titleTimes = new int[3];
if (split.length >= 4) {
this.titleTimes[0] = NumberUtil.getInteger(split[1]);
this.titleTimes[1] = NumberUtil.getAnyInteger(split[2], -1);
this.titleTimes[2] = NumberUtil.getInteger(split[3]);
}
if (this.titleTimes[1] < 0) this.titleTimes[1] = Short.MAX_VALUE;
}
}
case PREFIX -> this.hasPrefix = Boolean.parseBoolean(optionValue);
case PAPI -> this.papi = Boolean.parseBoolean(optionValue) && Plugins.hasPlaceholderAPI();
case SOUND -> this.sound = StringUtil.getEnum(optionValue, Sound.class).orElse(null);
}
}
}
@NotNull
public OutputType getType() {
return type;
}
public boolean hasPrefix() {
return this.hasPrefix;
}
public boolean hasPlaceholderAPI() {
return this.papi;
}
@Nullable
public Sound getSound() {
return sound;
}
public int[] getTitleTimes() {
return titleTimes;
}
}
@@ -0,0 +1,231 @@
package su.nightexpress.nightcore.language.message;
import me.clip.placeholderapi.PlaceholderAPI;
import net.md_5.bungee.api.chat.BaseComponent;
import net.md_5.bungee.api.chat.ComponentBuilder;
import net.md_5.bungee.api.chat.TextComponent;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
import su.nightexpress.nightcore.NightCorePlugin;
import su.nightexpress.nightcore.core.CoreConfig;
import su.nightexpress.nightcore.language.tag.MessageDecorator;
import su.nightexpress.nightcore.language.tag.MessageTags;
import su.nightexpress.nightcore.util.Placeholders;
import su.nightexpress.nightcore.util.Players;
import su.nightexpress.nightcore.util.text.NightMessage;
import su.nightexpress.nightcore.util.text.WrappedMessage;
import su.nightexpress.nightcore.util.text.tag.api.DynamicTag;
import su.nightexpress.nightcore.util.text.tag.api.Tag;
import su.nightexpress.nightcore.util.wrapper.UniSound;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.UnaryOperator;
public class LangMessage {
private final NightCorePlugin plugin;
private final String defaultText;
private final MessageOptions options;
private final WrappedMessage message;
public LangMessage(@NotNull NightCorePlugin plugin, @NotNull String defaultText, @NotNull MessageOptions options) {
this.plugin = plugin;
this.defaultText = defaultText;
this.options = options;
this.message = NightMessage.from(defaultText);
if (CoreConfig.MODERN_TEXT_PRECOMPILE_LANG.get()) {
this.message.compile();
}
}
private LangMessage(@NotNull LangMessage from) {
this.plugin = from.plugin;
this.defaultText = from.defaultText;
this.options = from.options.copy();
this.message = from.message.copy();
}
@NotNull
public static LangMessage parse(@NotNull NightCorePlugin plugin, @NotNull String string) {
MessageOptions options = new MessageOptions();
StringBuilder builder = new StringBuilder();
int length = string.length();
for (int index = 0; index < length; index++) {
char letter = string.charAt(index);
Tag:
if (letter == Tag.OPEN_BRACKET && index != (length - 1)) {
int indexEnd = string.indexOf(Tag.CLOSE_BRACKET, index);
if (indexEnd == -1) break Tag;
char next = string.charAt(index + 1);
if (next == Tag.CLOSE_BRACKET) break Tag;
String leading = string.substring(index + 1);
String brackets = string.substring(index + 1, indexEnd);
Tag tag = MessageTags.getTag(brackets);
if (tag == null) {
for (Tag registered : MessageTags.getTags()) {
String tagName = registered.getName();
if (leading.startsWith(tagName)) {
char latest = leading.charAt(tagName.length());
if (latest == Tag.CLOSE_BRACKET || registered instanceof DynamicTag) {
tag = registered;
break;
}
}
}
}
if (!(tag instanceof MessageDecorator decorator)) break Tag;
if (tag instanceof DynamicTag) {
int prefixSize = tag.getName().length() + 1; // 1 for semicolon
String content = DynamicTag.parseQuotedContent(leading.substring(prefixSize));
if (content == null) break Tag;
decorator.apply(options, content);
indexEnd = index + prefixSize + content.length() + 3; // 1 for close bracket, 2 for quotes
}
else {
decorator.apply(options, leading);
}
index = indexEnd;
continue;
}
builder.append(letter);
}
if (options.getOutputType() == OutputType.CHAT && options.hasPrefix()) {
builder.insert(0, plugin.getPrefix());
}
String text = builder.toString();
return new LangMessage(plugin, text, options);
}
@NotNull
public String getDefaultText() {
return this.defaultText;
}
@NotNull
public WrappedMessage getMessage() {
return this.message;
}
@NotNull
public WrappedMessage getMessage(@NotNull CommandSender sender) {
if (!this.options.usePlaceholderAPI() || !(sender instanceof Player player)) return this.getMessage();
return this.message.copy().replace(line -> PlaceholderAPI.setPlaceholders(player, line));
}
@NotNull
public LangMessage replace(@NotNull String var, @NotNull Object replacer) {
return this.replace(str -> str.replace(var, String.valueOf(replacer)));
}
@NotNull
public LangMessage replace(@NotNull String var, @NotNull Consumer<List<String>> replacer) {
List<String> list = new ArrayList<>();
replacer.accept(list);
return this.replace(var, list);
}
@NotNull
public LangMessage replace(@NotNull String var, @NotNull List<String> replacer) {
//String delimiter = CoreConfig.MODERN_TEXT_PRECOMPILE_LANG.get() ? "\n" : StandardTags.LINE_BREAK;
return this.replace(str -> str.replace(var, String.join(Placeholders.TAG_LINE_BREAK, replacer)));
}
@NotNull
public LangMessage replace(@NotNull UnaryOperator<String> replacer) {
if (this.isDisabled()) return this;
LangMessage copy = new LangMessage(this);
copy.getMessage().replace(replacer);
return copy;
}
/*@NotNull
public LangMessage replace(@NotNull Predicate<String> predicate, @NotNull BiConsumer<String, List<String>> replacer) {
if (this.isEmpty()) return this;
LangMessage msgCopy = new LangMessage(this);
List<String> replaced = new ArrayList<>();
List<String> text
msgCopy.getText().forEach(line -> {
if (predicate.test(line)) {
replacer.accept(line, replaced);
return;
}
replaced.add(line);
});
msgCopy.setText(replaced);
return msgCopy;
}*/
public boolean isDisabled() {
return this.options.getOutputType() == OutputType.NONE;
}
public void broadcast() {
if (this.isDisabled()) return;
this.plugin.getServer().getOnlinePlayers().forEach(this::send);
this.send(this.plugin.getServer().getConsoleSender());
}
public void send(@NotNull CommandSender sender) {
if (this.isDisabled()) return;
if (this.options.getSound() != null && sender instanceof Player player) {
UniSound.of(this.options.getSound()).play(player);
}
if (this.options.getOutputType() == OutputType.CHAT) {
this.getMessage(sender).send(sender);
return;
}
if (sender instanceof Player player) {
if (this.options.getOutputType() == OutputType.ACTION_BAR) {
Players.sendActionBar(player, this.getMessage(player));
//player.spigot().sendMessage(ChatMessageType.ACTION_BAR, this.getMessage(player).parseIfAbsent());
}
else if (this.options.getOutputType() == OutputType.TITLES) {
ComponentBuilder titleBuilder = new ComponentBuilder();
ComponentBuilder subBuilder = new ComponentBuilder();
ComponentBuilder current = titleBuilder;
for (BaseComponent component : this.getMessage(player).parseIfAbsent()) {
if (component instanceof TextComponent textComponent && textComponent.getText().equals("\n")) {
current = subBuilder;
continue;
}
current.append(component);
}
String title = TextComponent.toLegacyText(titleBuilder.create());
String subtitle = TextComponent.toLegacyText(subBuilder.create());
player.sendTitle(title, subtitle, this.options.getTitleTimes()[0], this.options.getTitleTimes()[1], this.options.getTitleTimes()[2]);
}
}
}
}
@@ -0,0 +1,72 @@
package su.nightexpress.nightcore.language.message;
import org.bukkit.Sound;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public class MessageOptions {
private OutputType outputType;
private boolean hasPrefix;
private boolean usePlaceholderAPI;
private Sound sound;
private int[] titleTimes;
public MessageOptions() {
this.setOutputType(OutputType.CHAT);
this.setHasPrefix(true);
}
@NotNull
public MessageOptions copy() {
MessageOptions copy = new MessageOptions();
copy.outputType = this.outputType;
copy.hasPrefix = this.hasPrefix;
copy.usePlaceholderAPI = this.usePlaceholderAPI;
copy.sound = this.sound;
copy.titleTimes = this.titleTimes;
return copy;
}
@NotNull
public OutputType getOutputType() {
return outputType;
}
public void setOutputType(OutputType outputType) {
this.outputType = outputType;
}
public boolean hasPrefix() {
return hasPrefix;
}
public void setHasPrefix(boolean hasPrefix) {
this.hasPrefix = hasPrefix;
}
public boolean usePlaceholderAPI() {
return this.usePlaceholderAPI;
}
public void setUsePlaceholderAPI(boolean usePlaceholderAPI) {
this.usePlaceholderAPI = usePlaceholderAPI;
}
@Nullable
public Sound getSound() {
return sound;
}
public void setSound(Sound sound) {
this.sound = sound;
}
public int[] getTitleTimes() {
return titleTimes;
}
public void setTitleTimes(int[] titleTimes) {
this.titleTimes = titleTimes;
}
}
@@ -0,0 +1,5 @@
package su.nightexpress.nightcore.language.message;
public enum OutputType {
CHAT, ACTION_BAR, TITLES, NONE,
}
@@ -0,0 +1,9 @@
package su.nightexpress.nightcore.language.tag;
import org.jetbrains.annotations.NotNull;
import su.nightexpress.nightcore.language.message.MessageOptions;
public interface MessageDecorator {
void apply(@NotNull MessageOptions options, @NotNull String value);
}
@@ -0,0 +1,48 @@
package su.nightexpress.nightcore.language.tag;
import org.jetbrains.annotations.NotNull;
import su.nightexpress.nightcore.language.tag.impl.NoPrefixTag;
import su.nightexpress.nightcore.language.tag.impl.PlaceholderTag;
import su.nightexpress.nightcore.language.tag.impl.SoundTag;
import su.nightexpress.nightcore.language.tag.impl.OutputTag;
import su.nightexpress.nightcore.util.text.tag.api.Tag;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
public class MessageTags {
private static final Map<String, Tag> TAG_MAP = new HashMap<>();
public static final NoPrefixTag NO_PREFIX = new NoPrefixTag();
public static final OutputTag OUTPUT = new OutputTag();
public static final SoundTag SOUND = new SoundTag();
public static final PlaceholderTag PLACEHOLDER = new PlaceholderTag();
static {
registerTags(NO_PREFIX, OUTPUT, SOUND, PLACEHOLDER);
}
public static void registerTags(@NotNull Tag... tags) {
for (Tag tag : tags) {
registerTag(tag);
}
}
public static void registerTag(@NotNull Tag tag, @NotNull String... aliases) {
TAG_MAP.put(tag.getName(), tag);
for (String alias : aliases) {
TAG_MAP.put(alias, tag);
}
}
@NotNull
public static Collection<Tag> getTags() {
return TAG_MAP.values();
}
public static Tag getTag(@NotNull String name) {
return TAG_MAP.get(name.toLowerCase());
}
}
@@ -0,0 +1,23 @@
package su.nightexpress.nightcore.language.tag.impl;
import org.jetbrains.annotations.NotNull;
import su.nightexpress.nightcore.language.message.MessageOptions;
import su.nightexpress.nightcore.language.tag.MessageDecorator;
import su.nightexpress.nightcore.util.text.tag.api.Tag;
public class NoPrefixTag extends Tag implements MessageDecorator {
public NoPrefixTag() {
super("noprefix");
}
@Override
public int getWeight() {
return 0;
}
@Override
public void apply(@NotNull MessageOptions options, @NotNull String value) {
options.setHasPrefix(false);
}
}
@@ -0,0 +1,53 @@
package su.nightexpress.nightcore.language.tag.impl;
import org.jetbrains.annotations.NotNull;
import su.nightexpress.nightcore.language.message.MessageOptions;
import su.nightexpress.nightcore.language.message.OutputType;
import su.nightexpress.nightcore.language.tag.MessageDecorator;
import su.nightexpress.nightcore.util.NumberUtil;
import su.nightexpress.nightcore.util.StringUtil;
import su.nightexpress.nightcore.util.text.tag.api.DynamicTag;
public class OutputTag extends DynamicTag implements MessageDecorator {
public OutputTag() {
super("output");
}
@Override
public int getWeight() {
return 0;
}
@NotNull
public String enclose(@NotNull OutputType type) {
String prefix = type.name().toLowerCase();
return this.leading(null, prefix);
}
@NotNull
public String enclose(int fade, int stay) {
String prefix = OutputType.TITLES.name().toLowerCase();
return this.leading(null, prefix + ":" + fade + ":" + stay + ":" + fade);
}
@Override
public void apply(@NotNull MessageOptions options, @NotNull String content) {
String[] split = content.split(":");
OutputType outputType = StringUtil.getEnum(split[0], OutputType.class).orElse(OutputType.CHAT);
options.setOutputType(outputType);
if (outputType == OutputType.TITLES) {
int[] titleTimes = new int[3];
if (split.length >= 4) {
titleTimes[0] = NumberUtil.getInteger(split[1]);
titleTimes[1] = NumberUtil.getAnyInteger(split[2], -1);
titleTimes[2] = NumberUtil.getInteger(split[3]);
}
if (titleTimes[1] < 0) titleTimes[1] = Short.MAX_VALUE;
options.setTitleTimes(titleTimes);
}
}
}
@@ -0,0 +1,23 @@
package su.nightexpress.nightcore.language.tag.impl;
import org.jetbrains.annotations.NotNull;
import su.nightexpress.nightcore.language.message.MessageOptions;
import su.nightexpress.nightcore.language.tag.MessageDecorator;
import su.nightexpress.nightcore.util.text.tag.api.Tag;
public class PlaceholderTag extends Tag implements MessageDecorator {
public PlaceholderTag() {
super("papi");
}
@Override
public int getWeight() {
return 0;
}
@Override
public void apply(@NotNull MessageOptions options, @NotNull String value) {
options.setUsePlaceholderAPI(true);
}
}
@@ -0,0 +1,31 @@
package su.nightexpress.nightcore.language.tag.impl;
import org.bukkit.Sound;
import org.jetbrains.annotations.NotNull;
import su.nightexpress.nightcore.language.message.MessageOptions;
import su.nightexpress.nightcore.language.tag.MessageDecorator;
import su.nightexpress.nightcore.util.StringUtil;
import su.nightexpress.nightcore.util.text.tag.api.DynamicTag;
public class SoundTag extends DynamicTag implements MessageDecorator {
public SoundTag() {
super("sound");
}
@Override
public int getWeight() {
return 0;
}
@NotNull
public String enclose(@NotNull Sound sound) {
return this.leading(null, sound.name().toLowerCase());
}
@Override
public void apply(@NotNull MessageOptions options, @NotNull String value) {
Sound sound = StringUtil.getEnum(value, Sound.class).orElse(null);
options.setSound(sound);
}
}
@@ -0,0 +1,71 @@
package su.nightexpress.nightcore.manager;
import org.jetbrains.annotations.NotNull;
import su.nightexpress.nightcore.NightCorePlugin;
import su.nightexpress.nightcore.config.FileConfig;
import su.nightexpress.nightcore.util.StringUtil;
import java.io.File;
public abstract class AbstractFileData<P extends NightCorePlugin> {
protected final P plugin;
protected final File file;
private final String id;
public AbstractFileData(@NotNull P plugin, @NotNull String filePath) {
this(plugin, new File(filePath));
}
public AbstractFileData(@NotNull P plugin, @NotNull File file) {
this(plugin, file, file.getName().replace(".yml", ""));
}
public AbstractFileData(@NotNull P plugin, @NotNull String filePath, @NotNull String id) {
this(plugin, new File(filePath), id);
}
public AbstractFileData(@NotNull P plugin, @NotNull File file, @NotNull String id) {
this.plugin = plugin;
this.file = file;
this.id = StringUtil.lowerCaseUnderscore(id);
}
public final boolean load() {
FileConfig config = this.getConfig();
if (!this.onLoad(config)) return false;
config.saveChanges();
return true;
}
public final void save() {
FileConfig config = this.getConfig();
this.onSave(config);
config.saveChanges();
}
protected abstract boolean onLoad(@NotNull FileConfig cfg);
protected abstract void onSave(@NotNull FileConfig cfg);
@NotNull
public final File getFile() {
return this.file;
}
/*@NotNull
public P plugin() {
return this.plugin;
}*/
@NotNull
public final String getId() {
return this.id;
}
@NotNull
public final FileConfig getConfig() {
return new FileConfig(this.getFile());
}
}
@@ -0,0 +1,19 @@
package su.nightexpress.nightcore.manager;
import org.jetbrains.annotations.NotNull;
import su.nightexpress.nightcore.NightCorePlugin;
public abstract class AbstractListener<P extends NightCorePlugin> implements SimpeListener {
@NotNull
public final P plugin;
public AbstractListener(@NotNull P plugin) {
this.plugin = plugin;
}
@Override
public void registerListeners() {
this.plugin.getPluginManager().registerEvents(this, this.plugin);
}
}
@@ -0,0 +1,42 @@
package su.nightexpress.nightcore.manager;
import org.jetbrains.annotations.NotNull;
import su.nightexpress.nightcore.NightCorePlugin;
import su.nightexpress.nightcore.util.wrapper.UniTask;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public abstract class AbstractManager<P extends NightCorePlugin> extends SimpleManager<P> {
protected final Set<SimpeListener> listeners;
protected final List<UniTask> tasks;
public AbstractManager(@NotNull P plugin) {
super(plugin);
this.listeners = new HashSet<>();
this.tasks = new ArrayList<>();
}
@Override
public void shutdown() {
this.tasks.forEach(UniTask::stop);
this.tasks.clear();
this.listeners.forEach(SimpeListener::unregisterListeners);
this.listeners.clear();
super.shutdown();
}
protected void addListener(@NotNull SimpeListener listener) {
if (this.listeners.add(listener)) {
listener.registerListeners();
}
}
protected void addTask(@NotNull UniTask task) {
this.tasks.add(task);
task.start();
}
}
@@ -0,0 +1,13 @@
package su.nightexpress.nightcore.manager;
import org.bukkit.event.HandlerList;
import org.bukkit.event.Listener;
public interface SimpeListener extends Listener {
void registerListeners();
default void unregisterListeners() {
HandlerList.unregisterAll(this);
}
}
@@ -0,0 +1,35 @@
package su.nightexpress.nightcore.manager;
import org.jetbrains.annotations.NotNull;
import su.nightexpress.nightcore.NightCorePlugin;
public abstract class SimpleManager<P extends NightCorePlugin> {
protected final P plugin;
public SimpleManager(@NotNull P plugin) {
this.plugin = plugin;
}
@NotNull
public P plugin() {
return this.plugin;
}
public void setup() {
this.onLoad();
}
public void shutdown() {
this.onShutdown();
}
public void reload() {
this.shutdown();
this.setup();
}
protected abstract void onLoad();
protected abstract void onShutdown();
}
@@ -0,0 +1,83 @@
package su.nightexpress.nightcore.menu;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.inventory.InventoryCloseEvent;
import org.bukkit.event.inventory.InventoryDragEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.jetbrains.annotations.NotNull;
import su.nightexpress.nightcore.NightCore;
import su.nightexpress.nightcore.core.CoreConfig;
import su.nightexpress.nightcore.menu.api.Menu;
import su.nightexpress.nightcore.manager.AbstractListener;
import su.nightexpress.nightcore.menu.click.ClickResult;
import su.nightexpress.nightcore.menu.impl.AbstractMenu;
public class MenuListener extends AbstractListener<NightCore> {
public MenuListener(@NotNull NightCore core) {
super(core);
}
@EventHandler(priority = EventPriority.MONITOR)
public void onQuit(PlayerQuitEvent event) {
AbstractMenu.PLAYER_MENUS.remove(event.getPlayer().getUniqueId());
}
@EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true)
public void onMenuItemClick(InventoryClickEvent event) {
Player player = (Player) event.getWhoClicked();
Menu menu = AbstractMenu.getMenu(player);
if (menu == null) return;
MenuViewer viewer = menu.getViewer(player);
if (viewer == null) return;
if (!viewer.canClickAgain(CoreConfig.MENU_CLICK_COOLDOWN.get())) {
event.setCancelled(true);
return;
}
Inventory inventory = event.getInventory();
ItemStack item = event.getCurrentItem();
int slot = event.getRawSlot();
boolean isMenu = slot < inventory.getSize();
boolean isEmptyItem = item == null || item.getType().isAir();
ClickResult result = new ClickResult(slot, item, isMenu);
menu.onClick(viewer, result, event);
viewer.setLastClickTime(System.currentTimeMillis());
}
@EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true)
public void onMenuItemDrag(InventoryDragEvent event) {
Player player = (Player) event.getWhoClicked();
Menu menu = AbstractMenu.getMenu(player);
if (menu == null) return;
MenuViewer viewer = menu.getViewer(player);
if (viewer == null) return;
menu.onDrag(viewer, event);
}
@EventHandler(priority = EventPriority.NORMAL)
public void onMenuClose(InventoryCloseEvent event) {
Player player = (Player) event.getPlayer();
Menu menu = AbstractMenu.getMenu(player);
if (menu == null) return;
MenuViewer viewer = menu.getViewer(player);
if (viewer == null) return;
menu.onClose(viewer, event);
}
}
@@ -0,0 +1,97 @@
package su.nightexpress.nightcore.menu;
import org.bukkit.Bukkit;
import org.bukkit.event.inventory.InventoryType;
import org.bukkit.inventory.Inventory;
import org.jetbrains.annotations.NotNull;
import su.nightexpress.nightcore.util.Colorizer;
import java.util.function.UnaryOperator;
public class MenuOptions {
private String title;
private int size;
private InventoryType type;
private int autoRefresh;
private long lastAutoRefresh;
public MenuOptions(@NotNull String title, int size, @NotNull InventoryType type) {
this(title, size, type, 0);
}
public MenuOptions(@NotNull String title, int size, @NotNull InventoryType type, int autoRefresh) {
this.setTitle(title);
this.setSize(size);
this.setType(type);
this.setAutoRefresh(autoRefresh);
}
public MenuOptions(@NotNull MenuOptions options) {
this(options.getTitle(), options.getSize(), options.getType(), options.getAutoRefresh());
this.lastAutoRefresh = 0L;
}
@NotNull
public Inventory createInventory() {
String title = this.getTitle();
if (this.getType() == InventoryType.CHEST) {
return Bukkit.getServer().createInventory(null, this.getSize(), title);
}
else {
return Bukkit.getServer().createInventory(null, this.getType(), title);
}
}
@NotNull
public String getTitle() {
return title;
}
public void setTitle(@NotNull String title) {
this.title = Colorizer.apply(title);
}
public void editTitle(@NotNull UnaryOperator<String> function) {
this.setTitle(function.apply(this.getTitle()));
}
public int getSize() {
return size;
}
public void setSize(int size) {
if (size <= 0 || size % 9 != 0 || size > 54) size = 27;
this.size = size;
}
@NotNull
public InventoryType getType() {
return type;
}
public void setType(@NotNull InventoryType type) {
this.type = type;
}
public int getAutoRefresh() {
return autoRefresh;
}
public void setAutoRefresh(int autoRefresh) {
this.autoRefresh = Math.max(0, autoRefresh);
}
public long getLastAutoRefresh() {
return lastAutoRefresh;
}
public void setLastAutoRefresh(long lastAutoRefresh) {
this.lastAutoRefresh = lastAutoRefresh;
}
public boolean isReadyToRefresh() {
return this.getAutoRefresh() > 0 && System.currentTimeMillis() - this.getLastAutoRefresh() >= this.getAutoRefresh();
}
}
@@ -0,0 +1,85 @@
package su.nightexpress.nightcore.menu;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryView;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import su.nightexpress.nightcore.util.Version;
public class MenuViewer {
private final Player player;
private Inventory inventory;
private InventoryView view;
private int page;
private int pages;
private long lastClickTime;
public MenuViewer(@NotNull Player player) {
this.player = player;
this.setPage(1);
this.setPages(1);
}
public void openInventory(@NotNull Inventory inventory) {
this.inventory = inventory;
this.view = this.getPlayer().openInventory(inventory);
}
public void flushInventory(@NotNull MenuOptions options) {
this.inventory.clear();
if (Version.isAtLeast(Version.V1_19_R3)) {
this.view.setTitle(options.getTitle());
}
}
public boolean hasInventory() {
return this.getInventory() != null && this.getView() != null;
}
public boolean canClickAgain(long cooldown) {
return this.getLastClickTime() == 0 || (System.currentTimeMillis() - this.getLastClickTime()) > cooldown;
}
@NotNull
public Player getPlayer() {
return player;
}
@Nullable
public Inventory getInventory() {
return inventory;
}
@Nullable
public InventoryView getView() {
return view;
}
public int getPage() {
return page;
}
public void setPage(int page) {
this.page = Math.max(1, page);
}
public int getPages() {
return pages;
}
public void setPages(int pages) {
this.pages = Math.max(1, pages);
}
public long getLastClickTime() {
return lastClickTime;
}
public void setLastClickTime(long lastClickTime) {
this.lastClickTime = lastClickTime;
}
}
@@ -0,0 +1,57 @@
package su.nightexpress.nightcore.menu.api;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.jetbrains.annotations.NotNull;
import su.nightexpress.nightcore.menu.MenuViewer;
import su.nightexpress.nightcore.menu.click.ClickAction;
import su.nightexpress.nightcore.menu.item.ItemOptions;
import su.nightexpress.nightcore.menu.item.MenuItem;
import java.util.ArrayList;
import java.util.List;
public interface AutoFilled<I> extends Menu {
int[] getAutoFillSlots();
@NotNull List<I> getAutoFills(@NotNull Player player);
@NotNull ItemStack getAutoFillStack(@NotNull Player player, @NotNull I object);
@NotNull ClickAction getAutoFillClick(@NotNull I object);
default void autoFill(@NotNull MenuViewer viewer) {
this.getAutoFillItems(viewer).forEach(this::addItem);
}
@NotNull
default List<MenuItem> getAutoFillItems(@NotNull MenuViewer viewer) {
Player player = viewer.getPlayer();
List<MenuItem> items = new ArrayList<>();
List<I> origin = this.getAutoFills(player);
int[] slots = this.getAutoFillSlots();
int limit = slots.length;
int pages = (int) Math.ceil((double) origin.size() / (double) limit);
viewer.setPages(pages);
viewer.setPage(Math.min(viewer.getPage(), viewer.getPages()));
int skip = (viewer.getPage() - 1) * limit;
List<I> list = origin.stream().skip(skip).limit(limit).toList();
int count = 0;
for (I object : list) {
ItemStack item = this.getAutoFillStack(player, object);
ItemOptions options = ItemOptions.personalWeak(player);
MenuItem menuItem = new MenuItem(item).setPriority(100).setOptions(options).setSlots(slots[count++])
.addClick(this.getAutoFillClick(object));
//MenuItem menuItem = new MenuItem(item, 100, options, slots[count++]);
//menuItem.addClick(this.getAutoFillClick(object));
items.add(menuItem);
}
return items;
}
}
@@ -0,0 +1,66 @@
package su.nightexpress.nightcore.menu.api;
import org.bukkit.entity.Player;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.inventory.InventoryCloseEvent;
import org.bukkit.event.inventory.InventoryDragEvent;
import org.bukkit.inventory.ItemStack;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import su.nightexpress.nightcore.menu.MenuOptions;
import su.nightexpress.nightcore.menu.MenuViewer;
import su.nightexpress.nightcore.menu.click.ClickResult;
import su.nightexpress.nightcore.menu.item.MenuItem;
import java.util.*;
public interface Menu {
void clear();
void flush();
void close();
void runNextTick(@NotNull Runnable runnable);
void onClick(@NotNull MenuViewer viewer, @NotNull ClickResult result, @NotNull InventoryClickEvent event);
void onDrag(@NotNull MenuViewer viewer, @NotNull InventoryDragEvent event);
void onClose(@NotNull MenuViewer viewer, @NotNull InventoryCloseEvent event);
boolean open(@NotNull MenuViewer viewer);
boolean open(@NotNull Player player);
boolean canOpen(@NotNull Player player);
boolean isPersistent();
@NotNull Collection<MenuViewer> getViewers();
@Nullable MenuViewer getViewer(@NotNull Player player);
@NotNull List<MenuItem> getItems(@NotNull MenuViewer viewer);
@Nullable MenuItem getItem(int slot);
@Nullable MenuItem getItem(@NotNull MenuViewer viewer, int slot);
@NotNull MenuItem addItem(@NotNull ItemStack item, int... slots);
@NotNull MenuItem addWeakItem(@NotNull Player player, @NotNull ItemStack item, int... slots);
@NotNull MenuItem addItem(@NotNull MenuItem menuItem);
@NotNull UUID getId();
//@NotNull Map<UUID, MenuViewer> getViewersMap();
@NotNull Set<MenuItem> getItems();
@NotNull MenuOptions getOptions();
}
@@ -0,0 +1,10 @@
package su.nightexpress.nightcore.menu.click;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.jetbrains.annotations.NotNull;
import su.nightexpress.nightcore.menu.MenuViewer;
public interface ClickAction {
void onClick(@NotNull MenuViewer viewer, @NotNull InventoryClickEvent event);
}
@@ -0,0 +1,38 @@
package su.nightexpress.nightcore.menu.click;
import org.bukkit.inventory.ItemStack;
import org.jetbrains.annotations.Nullable;
public class ClickResult {
private final int slot;
private final ItemStack itemStack;
private final boolean isMenu;
public ClickResult(int slot, @Nullable ItemStack itemStack, boolean isMenu) {
this.slot = slot;
this.itemStack = itemStack;
this.isMenu = isMenu;
}
public int getSlot() {
return slot;
}
@Nullable
public ItemStack getItemStack() {
return itemStack;
}
public boolean isEmptySlot() {
return this.itemStack == null || this.itemStack.getType().isAir();
}
public boolean isMenu() {
return isMenu;
}
public boolean isInventory() {
return !this.isMenu();
}
}
@@ -0,0 +1,45 @@
package su.nightexpress.nightcore.menu.click;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.jetbrains.annotations.NotNull;
public enum ClickType {
LEFT, RIGHT, SHIFT_LEFT, SHIFT_RIGHT,
DROP_KEY, SWAP_KEY,
NUMBER_1,
NUMBER_2,
NUMBER_3,
NUMBER_4,
NUMBER_5,
NUMBER_6,
NUMBER_7,
NUMBER_8,
NUMBER_9,
;
@NotNull
public static ClickType from(@NotNull InventoryClickEvent event) {
if (event.getClick() == org.bukkit.event.inventory.ClickType.DROP) return DROP_KEY;
if (event.getClick() == org.bukkit.event.inventory.ClickType.SWAP_OFFHAND) return SWAP_KEY;
if (event.getHotbarButton() >= 0) {
return switch (event.getHotbarButton()) {
case 0 -> NUMBER_1;
case 1 -> NUMBER_2;
case 2 -> NUMBER_3;
case 3 -> NUMBER_4;
case 4 -> NUMBER_5;
case 5 -> NUMBER_6;
case 6 -> NUMBER_7;
case 7 -> NUMBER_8;
case 8 -> NUMBER_9;
default -> throw new IllegalStateException("Unexpected value: " + event.getHotbarButton());
};
}
if (event.isShiftClick()) {
return event.isLeftClick() ? SHIFT_LEFT : SHIFT_RIGHT;
}
return event.isLeftClick() ? LEFT : RIGHT;
}
}
@@ -0,0 +1,266 @@
package su.nightexpress.nightcore.menu.impl;
import org.bukkit.entity.Player;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.inventory.InventoryCloseEvent;
import org.bukkit.event.inventory.InventoryDragEvent;
import org.bukkit.event.inventory.InventoryType;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import su.nightexpress.nightcore.NightCorePlugin;
import su.nightexpress.nightcore.dialog.Dialog;
import su.nightexpress.nightcore.menu.api.Menu;
import su.nightexpress.nightcore.menu.link.Linked;
import su.nightexpress.nightcore.menu.MenuOptions;
import su.nightexpress.nightcore.menu.MenuViewer;
import su.nightexpress.nightcore.menu.click.ClickResult;
import su.nightexpress.nightcore.menu.item.ItemOptions;
import su.nightexpress.nightcore.menu.item.MenuItem;
import su.nightexpress.nightcore.util.Lists;
import java.util.*;
public abstract class AbstractMenu<P extends NightCorePlugin> implements Menu {
public static final Map<UUID, Menu> PLAYER_MENUS = new HashMap<>();
protected final P plugin;
protected final UUID id;
protected final MenuOptions options;
protected final Map<UUID, MenuViewer> viewers;
protected final Set<MenuItem> items;
public AbstractMenu(@NotNull P plugin) {
this(plugin, "NC Inventory", InventoryType.CHEST);
}
public AbstractMenu(@NotNull P plugin, @NotNull String title, @NotNull InventoryType type) {
this(plugin, new MenuOptions(title, 27, type));
}
public AbstractMenu(@NotNull P plugin, @NotNull String title, int size) {
this(plugin, new MenuOptions(title, size, InventoryType.CHEST));
}
public AbstractMenu(@NotNull P plugin, @NotNull MenuOptions options) {
this.plugin = plugin;
this.id = UUID.randomUUID();
this.options = new MenuOptions(options);
this.viewers = new HashMap<>();
this.items = new HashSet<>();
}
@Nullable
public static Menu getMenu(@NotNull Player player) {
return PLAYER_MENUS.get(player.getUniqueId());
}
@Override
public void clear() {
this.close();
this.getItems().clear();
this.getViewers().clear();
}
@Override
public void close() {
new HashSet<>(this.getViewers()).forEach(viewer -> viewer.getPlayer().closeInventory());
}
/*@NotNull
public P plugin() {
return this.plugin;
}*/
@Override
public void runNextTick(@NotNull Runnable runnable) {
this.plugin.runTask(task -> runnable.run());
}
@Override
public void flush() {
this.getViewers().forEach(viewer -> this.open(viewer.getPlayer()));
}
@Override
public boolean canOpen(@NotNull Player player) {
return !player.isSleeping();
}
@Override
public boolean open(@NotNull MenuViewer viewer) {
return this.open(viewer.getPlayer());
}
@Override
public boolean open(@NotNull Player player) {
if (!this.canOpen(player)) return false;
MenuOptions options = new MenuOptions(this.getOptions());
MenuViewer viewer = this.getViewerOrCreate(player);
this.getItems().removeIf(menuItem -> menuItem.getOptions().canBeDestroyed(viewer));
this.onPrepare(viewer, options);
if (!viewer.hasInventory()) {
viewer.openInventory(options.createInventory());
}
else {
viewer.flushInventory(options);
}
Inventory inventory = viewer.getInventory();
if (inventory == null) {
this.plugin.debug("Could not create " + this.getClass().getSimpleName() + " inventory for '" + player.getName() + "'.");
return false;
}
this.getItems(viewer).forEach(menuItem -> {
ItemStack item = menuItem.getItemStack();
menuItem.getOptions().modifyDisplay(viewer, item);
for (int slot : menuItem.getSlots()) {
if (slot < 0 || slot >= inventory.getSize()) continue;
inventory.setItem(slot, item);
}
});
this.onReady(viewer, inventory);
PLAYER_MENUS.put(player.getUniqueId(), this);
return true;
}
protected abstract void onPrepare(@NotNull MenuViewer viewer, @NotNull MenuOptions options);
protected abstract void onReady(@NotNull MenuViewer viewer, @NotNull Inventory inventory);
@Override
public void onClick(@NotNull MenuViewer viewer, @NotNull ClickResult result, @NotNull InventoryClickEvent event) {
event.setCancelled(true);
if (result.isInventory()) return;
MenuItem menuItem = this.getItem(viewer, result.getSlot());
if (menuItem == null) return;
menuItem.getHandler().getClickActions().forEach(action -> action.onClick(viewer, event));
}
@Override
public void onDrag(@NotNull MenuViewer viewer, @NotNull InventoryDragEvent event) {
event.setCancelled(true);
}
@Override
public void onClose(@NotNull MenuViewer viewer, @NotNull InventoryCloseEvent event) {
Player player = viewer.getPlayer();
this.getViewersMap().remove(player.getUniqueId());
this.getItems().removeIf(menuItem -> menuItem.getOptions().canBeDestroyed(viewer));
PLAYER_MENUS.remove(player.getUniqueId());
// Do not clear link if entered Editor, so it can reopen menu without data loss when done.
if (this instanceof Linked<?> linked && !Dialog.contains(player)) {
linked.getLink().clear(viewer);
}
if (this.getViewers().isEmpty() && !this.isPersistent()) {
this.clear();
}
}
@Override
public boolean isPersistent() {
return true;
}
@Override
@NotNull
public Collection<MenuViewer> getViewers() {
return this.getViewersMap().values();
}
@Override
@Nullable
public MenuViewer getViewer(@NotNull Player player) {
return this.getViewersMap().get(player.getUniqueId());
}
@NotNull
private MenuViewer getViewerOrCreate(@NotNull Player player) {
return this.getViewersMap().computeIfAbsent(player.getUniqueId(), k -> new MenuViewer(player));
}
@Override
@NotNull
public List<MenuItem> getItems(@NotNull MenuViewer viewer) {
return this.getItems().stream()
.filter(menuItem -> menuItem.canSee(viewer))
.sorted(Comparator.comparingInt(MenuItem::getPriority)).toList();
}
@Override
@Nullable
public MenuItem getItem(int slot) {
return this.getItems().stream()
.filter(item -> Lists.contains(item.getSlots(), slot))
.max(Comparator.comparingInt(MenuItem::getPriority)).orElse(null);
}
@Override
@Nullable
public MenuItem getItem(@NotNull MenuViewer viewer, int slot) {
return this.getItems(viewer).stream()
.filter(menuItem -> Lists.contains(menuItem.getSlots(), slot))
.max(Comparator.comparingInt(MenuItem::getPriority)).orElse(null);
}
@Override
@NotNull
public MenuItem addItem(@NotNull ItemStack item, int... slots) {
return this.addItem(new MenuItem(item, slots));
}
@Override
@NotNull
public MenuItem addWeakItem(@NotNull Player player, @NotNull ItemStack item, int... slots) {
MenuItem menuItem = new MenuItem(item, slots);
menuItem.setOptions(ItemOptions.personalWeak(player));
return this.addItem(menuItem);
}
@Override
@NotNull
public MenuItem addItem(@NotNull MenuItem menuItem) {
this.getItems().add(menuItem);
return menuItem;
}
@Override
@NotNull
public UUID getId() {
return id;
}
@NotNull
private Map<UUID, MenuViewer> getViewersMap() {
return viewers;
}
@Override
@NotNull
public Set<MenuItem> getItems() {
return items;
}
@Override
@NotNull
public MenuOptions getOptions() {
return options;
}
}
@@ -0,0 +1,178 @@
package su.nightexpress.nightcore.menu.impl;
import org.bukkit.event.inventory.InventoryType;
import org.bukkit.inventory.ItemStack;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import su.nightexpress.nightcore.NightCorePlugin;
import su.nightexpress.nightcore.config.ConfigValue;
import su.nightexpress.nightcore.config.FileConfig;
import su.nightexpress.nightcore.menu.api.AutoFilled;
import su.nightexpress.nightcore.menu.MenuOptions;
import su.nightexpress.nightcore.menu.click.ClickAction;
import su.nightexpress.nightcore.menu.click.ClickType;
import su.nightexpress.nightcore.menu.item.ItemHandler;
import su.nightexpress.nightcore.menu.item.MenuItem;
import su.nightexpress.nightcore.util.*;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
public abstract class ConfigMenu<P extends NightCorePlugin> extends AbstractMenu<P> {
protected final FileConfig cfg;
protected final Map<String, ItemHandler> handlerMap;
protected String itemSection = "Content";
public ConfigMenu(@NotNull P plugin, @NotNull FileConfig cfg) {
super(plugin);
this.cfg = cfg;
this.handlerMap = new HashMap<>();
this.addHandler(ItemHandler.forClose(this));
if (this instanceof AutoFilled<?>) {
this.addHandler(ItemHandler.forNextPage(this));
this.addHandler(ItemHandler.forPreviousPage(this));
}
}
@NotNull
protected abstract MenuOptions createDefaultOptions();
@NotNull
protected abstract List<MenuItem> createDefaultItems();
public void load() {
this.loadConfig();
}
protected abstract void loadAdditional();
public void loadConfig() {
MenuOptions defaultOptions = this.createDefaultOptions();
String title = ConfigValue.create("Settings.Title", defaultOptions.getTitle(),
"Sets GUI title."
).read(cfg);
int size = ConfigValue.create("Settings.Size", defaultOptions.getSize(),
"Sets GUI size. Must be multiply of 9.",
"Useful for '" + InventoryType.CHEST.name() + "' Inventory Type only."
).read(cfg);
InventoryType type = ConfigValue.create("Settings.Inventory_Type", InventoryType.class, defaultOptions.getType(),
"Sets GUI type.",
"https://hub.spigotmc.org/javadocs/bukkit/org/bukkit/event/inventory/InventoryType.html"
).read(cfg);
int autoRefresh = ConfigValue.create("Settings.Auto_Refresh", defaultOptions.getAutoRefresh(),
"Sets GUI auto-refresh interval (in seconds). Set this to 0 to disable."
).read(cfg);
this.getOptions().setTitle(title);
this.getOptions().setSize(size);
this.getOptions().setType(type);
this.getOptions().setAutoRefresh(autoRefresh);
this.loadAdditional();
if (!this.cfg.contains(this.itemSection)) {
AtomicInteger count = new AtomicInteger();
this.createDefaultItems().forEach(menuItem -> {
String name = StringUtil.lowerCaseUnderscore(ItemUtil.getItemName(menuItem.getItemStack()));
this.writeItem(menuItem, this.itemSection + "." + name + "_" + count.incrementAndGet());
});
}
this.cfg.getSection(this.itemSection).forEach(sId -> {
MenuItem menuItem = this.readItem(this.itemSection + "." + sId);
this.addItem(menuItem);
});
List<String> comments = new ArrayList<>();
comments.add("=".repeat(20) + " GUI CONTENT " + "=".repeat(20));
comments.add("You can freely edit items in this section as you wish (add, remove, modify items).");
comments.add("The following values are available as button Types:");
comments.addAll(handlerMap.keySet().stream().map(String::toUpperCase).sorted(String::compareTo).toList());
comments.add("=".repeat(20) + " ITEM OPTIONS " + "=".repeat(20));
comments.add("> Item: Item to display. Please check: " + Placeholders.WIKI_ITEMS_URL);
comments.add("> Priority: Button priority. Better values will override other item(s) in the same slot(s).");
comments.add("> Slots: Button slots. From [0] to [Size - 1]. Split them with a comma.");
comments.add("> Click_Commands: Execute custom commands on click. " + Plugins.PLACEHOLDER_API + " available here.");
comments.add(" Available click types: " + String.join(", ", Lists.getEnums(ClickType.class)));
comments.add(" Click_Commands:");
comments.add(" LEFT:");
comments.add(" - say Hello");
comments.add(" - give " + Placeholders.PLAYER_NAME + " diamond 1");
comments.add("=".repeat(50));
this.cfg.setComments(this.itemSection, comments);
this.cfg.saveChanges();
}
@Override
public void clear() {
super.clear();
this.handlerMap.clear();
}
public void addHandler(@NotNull ItemHandler handler) {
this.handlerMap.put(handler.getName(), handler);
}
public void addHandler(@NotNull String name, @NotNull ClickAction action) {
this.addHandler(new ItemHandler(name, action));
}
@Nullable
public ItemHandler getHandler(@NotNull String name) {
return this.handlerMap.get(name.toLowerCase());
}
public boolean removeHandler(@NotNull String name) {
return this.handlerMap.remove(name.toLowerCase()) != null;
}
@NotNull
protected MenuItem readItem(@NotNull String path) {
String handlerName = cfg.getString(path + ".Type", Placeholders.DEFAULT);
ItemStack item = cfg.getItem(path + ".Item");
int[] slots = cfg.getIntArray(path + ".Slots");
int priority = cfg.getInt(path + ".Priority");
MenuItem menuItem = new MenuItem(item).setPriority(priority).setSlots(slots);
ItemHandler handler = this.getHandler(handlerName);
if (handler != null) {
menuItem.setHandler(handler);
}
if (cfg.contains(path + ".Click_Actions")) {
Map<ClickType, List<String>> commandMap = new HashMap<>();
for (String sType : cfg.getSection(path + ".Click_Actions")) {
ClickType clickType = StringUtil.getEnum(sType, ClickType.class).orElse(null);
if (clickType == null) continue;
List<String> commands = cfg.getStringList(path + ".Click_Actions." + sType);
commandMap.put(clickType, commands);
}
commandMap.values().removeIf(List::isEmpty);
ClickAction clickCommands = (viewer, event) -> {
List<String> commands = commandMap.getOrDefault(ClickType.from(event), Collections.emptyList());
commands.forEach(command -> Players.dispatchCommand(viewer.getPlayer(), command));
};
menuItem.addClick(clickCommands);
}
return menuItem;
}
protected void writeItem(@NotNull MenuItem menuItem, @NotNull String path) {
this.cfg.set(path + ".Priority", menuItem.getPriority());
this.cfg.setItem(path + ".Item", menuItem.getItemStack());
this.cfg.setIntArray(path + ".Slots", menuItem.getSlots());
this.cfg.set(path + ".Type", menuItem.getHandler().getName());
}
}
@@ -0,0 +1,131 @@
package su.nightexpress.nightcore.menu.impl;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemFlag;
import org.bukkit.inventory.ItemStack;
import org.jetbrains.annotations.NotNull;
import su.nightexpress.nightcore.NightCorePlugin;
import su.nightexpress.nightcore.core.CoreLang;
import su.nightexpress.nightcore.dialog.Dialog;
import su.nightexpress.nightcore.dialog.DialogHandler;
import su.nightexpress.nightcore.language.entry.LangItem;
import su.nightexpress.nightcore.language.entry.LangString;
import su.nightexpress.nightcore.language.legacy.LegacyLangString;
import su.nightexpress.nightcore.menu.MenuViewer;
import su.nightexpress.nightcore.menu.item.ItemHandler;
import su.nightexpress.nightcore.menu.item.MenuItem;
import su.nightexpress.nightcore.menu.link.Linked;
import su.nightexpress.nightcore.menu.link.ViewLink;
import su.nightexpress.nightcore.util.ItemUtil;
import su.nightexpress.nightcore.util.text.WrappedMessage;
public abstract class EditorMenu<P extends NightCorePlugin, T> extends AbstractMenu<P> implements Linked<T> {
protected final ViewLink<T> link;
public EditorMenu(@NotNull P plugin, @NotNull String title, int size) {
super(plugin, title, size);
this.link = new ViewLink<>();
}
@NotNull
@Override
public ViewLink<T> getLink() {
return link;
}
@NotNull
protected MenuItem addNextPage(int... slots) {
ItemStack item = new ItemStack(Material.PLAYER_HEAD);
ItemUtil.setSkullTexture(item, "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvNjgyYWQxYjljYjRkZDIxMjU5YzBkNzVhYTMxNWZmMzg5YzNjZWY3NTJiZTM5NDkzMzgxNjRiYWM4NGE5NmUifX19");
return this.addItem(item, CoreLang.EDITOR_ITEM_NEXT_PAGE, slots).setHandler(ItemHandler.forNextPage(this));
}
@NotNull
protected MenuItem addPreviousPage(int... slots) {
ItemStack item = new ItemStack(Material.PLAYER_HEAD);
ItemUtil.setSkullTexture(item, "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvMzdhZWU5YTc1YmYwZGY3ODk3MTgzMDE1Y2NhMGIyYTdkNzU1YzYzMzg4ZmYwMTc1MmQ1ZjQ0MTlmYzY0NSJ9fX0=");
return this.addItem(item, CoreLang.EDITOR_ITEM_PREVIOUS_PAGE, slots).setHandler(ItemHandler.forPreviousPage(this));
}
@NotNull
protected MenuItem addReturn(int... slots) {
ItemStack item = new ItemStack(Material.PLAYER_HEAD);
ItemUtil.setSkullTexture(item, "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvYTM4NTJiZjYxNmYzMWVkNjdjMzdkZTRiMGJhYTJjNWY4ZDhmY2E4MmU3MmRiY2FmY2JhNjY5NTZhODFjNCJ9fX0=");
return this.addItem(item, CoreLang.EDITOR_ITEM_RETURN, slots);
}
@NotNull
protected MenuItem addCreation(@NotNull LangItem locale, int... slots) {
ItemStack item = new ItemStack(Material.PLAYER_HEAD);
ItemUtil.setSkullTexture(item, "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvNWZmMzE0MzFkNjQ1ODdmZjZlZjk4YzA2NzU4MTA2ODFmOGMxM2JmOTZmNTFkOWNiMDdlZDc4NTJiMmZmZDEifX19");
return this.addItem(item, locale, slots);
}
@NotNull
protected MenuItem addExit(int... slots) {
ItemStack item = new ItemStack(Material.PLAYER_HEAD);
ItemUtil.setSkullTexture(item, "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvYmViNTg4YjIxYTZmOThhZDFmZjRlMDg1YzU1MmRjYjA1MGVmYzljYWI0MjdmNDYwNDhmMThmYzgwMzQ3NWY3In19fQ==");
return this.addItem(item, CoreLang.EDITOR_ITEM_CLOSE, slots).setHandler(ItemHandler.forClose(this));
}
@NotNull
public MenuItem addItem(@NotNull Material material, @NotNull LangItem locale, int... slots) {
return this.addItem(new ItemStack(material), locale, slots);
}
@NotNull
public MenuItem addItem(@NotNull ItemStack item, @NotNull LangItem locale, int... slots) {
ItemUtil.editMeta(item, meta -> {
meta.setDisplayName(locale.getLocalizedName());
meta.setLore(locale.getLocalizedLore());
meta.addItemFlags(ItemFlag.values());
});
MenuItem menuItem = new MenuItem(item).setPriority(100).setSlots(slots);
this.addItem(menuItem);
return menuItem;
}
@Deprecated
public void handleInput(@NotNull MenuViewer viewer, @NotNull LegacyLangString prompt, @NotNull DialogHandler handler) {
this.handleInput(viewer.getPlayer(), prompt, handler);
}
@Deprecated
public void handleInput(@NotNull Player player, @NotNull LegacyLangString prompt, @NotNull DialogHandler handler) {
this.handleInput(player, prompt.getString(), handler);
}
public void handleInput(@NotNull MenuViewer viewer, @NotNull LangString prompt, @NotNull DialogHandler handler) {
this.handleInput(viewer.getPlayer(), prompt, handler);
}
public void handleInput(@NotNull Player player, @NotNull LangString prompt, @NotNull DialogHandler handler) {
this.handleInput(player, prompt.getString(), handler);
}
@NotNull
public Dialog handleInput(@NotNull Player player, @NotNull WrappedMessage prompt, @NotNull DialogHandler handler) {
this.runNextTick(player::closeInventory);
Dialog dialog = Dialog.create(player, handler);
dialog.prompt(prompt);
return dialog;
}
@NotNull
public Dialog handleInput(@NotNull Player player, @NotNull String prompt, @NotNull DialogHandler handler) {
this.runNextTick(player::closeInventory);
Dialog dialog = Dialog.create(player, handler);
dialog.prompt(prompt);
return dialog;
}
@NotNull
public T getObject(@NotNull MenuViewer viewer) {
return this.getLink().get(viewer);
}
}
@@ -0,0 +1,95 @@
package su.nightexpress.nightcore.menu.item;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import su.nightexpress.nightcore.menu.api.Menu;
import su.nightexpress.nightcore.menu.MenuViewer;
import su.nightexpress.nightcore.menu.click.ClickAction;
import su.nightexpress.nightcore.util.Placeholders;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Predicate;
public class ItemHandler {
public static final String RETURN = "return";
public static final String CLOSE = "close";
public static final String NEXT_PAGE = "page_next";
public static final String PREVIOUS_PAGE = "page_previous";
private final String name;
private final List<ClickAction> clickActions;
private final Predicate<MenuViewer> visibilityPolicy;
public ItemHandler() {
this(Placeholders.DEFAULT, null, null);
}
public ItemHandler(@NotNull String name) {
this(name, null, null);
}
public ItemHandler(@NotNull String name, @Nullable ClickAction clickAction) {
this(name, clickAction, null);
}
public ItemHandler(@NotNull String name, @Nullable ClickAction clickAction, @Nullable Predicate<MenuViewer> visibilityPolicy) {
this.name = name.toLowerCase();
this.clickActions = new ArrayList<>();
this.visibilityPolicy = visibilityPolicy;
if (clickAction != null) {
this.getClickActions().add(clickAction);
}
}
@NotNull
public static ItemHandler forNextPage(@NotNull Menu menu) {
return new ItemHandler(NEXT_PAGE,
(viewer, event) -> {
if (viewer.getPage() < viewer.getPages()) {
viewer.setPage(viewer.getPage() + 1);
menu.open(viewer.getPlayer());
}
},
viewer -> viewer.getPage() < viewer.getPages());
}
@NotNull
public static ItemHandler forPreviousPage(@NotNull Menu menu) {
return new ItemHandler(PREVIOUS_PAGE,
(viewer, event) -> {
if (viewer.getPage() > 1) {
viewer.setPage(viewer.getPage() - 1);
menu.open(viewer.getPlayer());
}
},
viewer -> viewer.getPage() > 1);
}
@NotNull
public static ItemHandler forClose(@NotNull Menu menu) {
return new ItemHandler(CLOSE, (viewer, event) -> menu.runNextTick(() -> viewer.getPlayer().closeInventory()));
}
@NotNull
public static ItemHandler forReturn(@NotNull Menu menu, @NotNull ClickAction action) {
return new ItemHandler(RETURN, action);
}
@NotNull
public String getName() {
return name;
}
@NotNull
public List<ClickAction> getClickActions() {
return clickActions;
}
@Nullable
public Predicate<MenuViewer> getVisibilityPolicy() {
return visibilityPolicy;
}
}
@@ -0,0 +1,115 @@
package su.nightexpress.nightcore.menu.item;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import su.nightexpress.nightcore.menu.MenuViewer;
import java.util.function.BiConsumer;
import java.util.function.Predicate;
public class ItemOptions {
private Predicate<MenuViewer> visibilityPolicy;
private Predicate<MenuViewer> weakPolicy;
private BiConsumer<MenuViewer, ItemStack> displayModifier;
public ItemOptions() {
this(null, null, null);
}
public ItemOptions(@Nullable Predicate<MenuViewer> visibilityPolicy,
@Nullable Predicate<MenuViewer> weakPolicy,
@Nullable BiConsumer<MenuViewer, ItemStack> displayModifier) {
this.setVisibilityPolicy(visibilityPolicy);
this.setWeakPolicy(weakPolicy);
this.setDisplayModifier(displayModifier);
}
@NotNull
public static ItemOptions personalWeak(@NotNull Player player) {
Predicate<MenuViewer> visibility = (viewer -> viewer.getPlayer().getUniqueId().equals(player.getUniqueId()));
Predicate<MenuViewer> weak = (viewer -> viewer.getPlayer().getUniqueId().equals(player.getUniqueId()));
return new ItemOptions(visibility, weak, null);
}
@NotNull
public static ItemOptions personalPermanent(@NotNull Player player) {
Predicate<MenuViewer> visibility = (viewer -> viewer.getPlayer().getUniqueId().equals(player.getUniqueId()));
return new ItemOptions(visibility, null, null);
}
public boolean canSee(@NotNull MenuViewer viewer) {
Predicate<MenuViewer> policy = this.getVisibilityPolicy();
return policy == null || policy.test(viewer);
}
public boolean canBeDestroyed(@NotNull MenuViewer viewer) {
Predicate<MenuViewer> policy = this.getWeakPolicy();
return policy != null && policy.test(viewer);
}
public void modifyDisplay(@NotNull MenuViewer viewer, @NotNull ItemStack item) {
BiConsumer<MenuViewer, ItemStack> displayModifier = this.getDisplayModifier();
if (displayModifier != null) {
displayModifier.accept(viewer, item);
}
}
@Nullable
public Predicate<MenuViewer> getVisibilityPolicy() {
return visibilityPolicy;
}
@NotNull
public ItemOptions setVisibilityPolicy(@Nullable Predicate<MenuViewer> visibilityPolicy) {
this.visibilityPolicy = visibilityPolicy;
return this;
}
@NotNull
public ItemOptions addVisibilityPolicy(@NotNull Predicate<MenuViewer> visibilityPolicy) {
if (this.visibilityPolicy == null) {
this.setVisibilityPolicy(visibilityPolicy);
}
else {
this.visibilityPolicy = this.visibilityPolicy.and(visibilityPolicy);
}
return this;
}
@Nullable
public Predicate<MenuViewer> getWeakPolicy() {
return weakPolicy;
}
@NotNull
public ItemOptions setWeakPolicy(@Nullable Predicate<MenuViewer> weakPolicy) {
this.weakPolicy = weakPolicy;
return this;
}
@Nullable
public BiConsumer<MenuViewer, ItemStack> getDisplayModifier() {
return displayModifier;
}
@NotNull
public ItemOptions setDisplayModifier(@Nullable BiConsumer<MenuViewer, ItemStack> displayModifier) {
this.displayModifier = displayModifier;
return this;
}
@NotNull
public ItemOptions addDisplayModifier(@NotNull BiConsumer<MenuViewer, ItemStack> displayModifier) {
if (this.displayModifier == null) {
this.setDisplayModifier(displayModifier);
}
else {
this.displayModifier = this.displayModifier.andThen(displayModifier);
}
return this;
}
}
@@ -0,0 +1,113 @@
package su.nightexpress.nightcore.menu.item;
import org.bukkit.inventory.ItemStack;
import org.jetbrains.annotations.NotNull;
import su.nightexpress.nightcore.menu.MenuViewer;
import su.nightexpress.nightcore.menu.click.ClickAction;
public class MenuItem {
protected ItemStack itemStack;
protected int priority;
protected int[] slots;
protected ItemOptions options;
protected ItemHandler handler;
public MenuItem(@NotNull ItemStack itemStack) {
this(itemStack, new int[0]);
}
public MenuItem(@NotNull ItemStack itemStack, int... slots) {
this(itemStack, 0, slots);
}
public MenuItem(@NotNull ItemStack itemStack, int priority, int[] slots) {
this(itemStack, priority, slots, new ItemOptions(), new ItemHandler());
}
public MenuItem(@NotNull ItemStack itemStack, int priority, int[] slots, @NotNull ItemOptions options, @NotNull ItemHandler handler) {
this.setItemStack(itemStack);
this.setPriority(priority);
this.setSlots(slots);
this.setOptions(options);
this.setHandler(handler);
}
@NotNull
public MenuItem copy() {
return new MenuItem(this.getItemStack(), this.getPriority(), this.getSlots(), this.getOptions(), this.getHandler());
}
@NotNull
public MenuItem resetOptions() {
this.setOptions(new ItemOptions());
return this;
}
public boolean canSee(@NotNull MenuViewer viewer) {
if (!this.getOptions().canSee(viewer)) return false;
var policy = this.getHandler().getVisibilityPolicy();
return policy == null || policy.test(viewer);
}
@NotNull
public ItemStack getItemStack() {
return new ItemStack(this.itemStack);
}
@NotNull
public MenuItem setItemStack(@NotNull ItemStack itemStack) {
this.itemStack = new ItemStack(itemStack);
return this;
}
public int getPriority() {
return priority;
}
@NotNull
public MenuItem setPriority(int priority) {
this.priority = priority;
return this;
}
public int[] getSlots() {
return slots;
}
@NotNull
public MenuItem setSlots(int... slots) {
this.slots = slots;
return this;
}
@NotNull
public ItemOptions getOptions() {
return options;
}
@NotNull
public MenuItem setOptions(@NotNull ItemOptions options) {
this.options = options;
return this;
}
@NotNull
public ItemHandler getHandler() {
return handler;
}
@NotNull
public MenuItem setHandler(@NotNull ItemHandler handler) {
this.handler = handler;
return this;
}
@NotNull
public MenuItem addClick(@NotNull ClickAction click) {
this.getHandler().getClickActions().add(click);
return this;
}
}
@@ -0,0 +1,21 @@
package su.nightexpress.nightcore.menu.link;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
import su.nightexpress.nightcore.menu.api.Menu;
public interface Linked<T> extends Menu {
@NotNull ViewLink<T> getLink();
default boolean open(@NotNull Player player, @NotNull T obj) {
this.getLink().set(player, obj);
if (!this.open(player)) {
this.getLink().clear(player);
return false;
}
return true;
}
}
@@ -0,0 +1,41 @@
package su.nightexpress.nightcore.menu.link;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
import su.nightexpress.nightcore.menu.MenuViewer;
import java.util.Map;
import java.util.WeakHashMap;
public class ViewLink<T> {
private final Map<Player, T> map;
public ViewLink() {
this.map = new WeakHashMap<>();
}
public void set(@NotNull MenuViewer viewer, @NotNull T object) {
this.set(viewer.getPlayer(), object);
}
public void set(@NotNull Player viewer, @NotNull T object) {
this.map.put(viewer, object);
}
public T get(@NotNull MenuViewer viewer) {
return this.get(viewer.getPlayer());
}
public T get(@NotNull Player viewer) {
return this.map.get(viewer);
}
public void clear(@NotNull MenuViewer viewer) {
this.clear(viewer.getPlayer());
}
public void clear(@NotNull Player viewer) {
this.map.remove(viewer);
}
}
@@ -0,0 +1,34 @@
package su.nightexpress.nightcore.util;
//@BenchmarkMode({Mode.AverageTime})
//@OutputTimeUnit(TimeUnit.MILLISECONDS)
//@Fork(value = 1, jvmArgs = {"-Xms2G", "-Xmx2G"})
public class BenchmarkLoop {
/*private static final int N = 10_000_000;
public static void main(String[] args) throws RunnerException {
Options opt = new OptionsBuilder()
.include(BenchmarkLoop.class.getSimpleName())
.forks(1)
.build();
new Runner(opt).run();
}
@Benchmark
public static void first(Blackhole blackhole) {
for (int i = 0; i < N; i++) {
}
}
@Benchmark
public static void second(Blackhole blackhole) {
for (int i = 0; i < N; i++) {
}
}*/
}
@@ -0,0 +1,154 @@
package su.nightexpress.nightcore.util;
import net.md_5.bungee.api.ChatColor;
import org.jetbrains.annotations.NotNull;
import su.nightexpress.nightcore.util.regex.TimedMatcher;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
public class Colorizer {
public static final Pattern PATTERN_HEX = Pattern.compile("#([A-Fa-f0-9]{6})");
public static final Pattern PATTERN_GRADIENT = Pattern.compile("<gradient:" + PATTERN_HEX.pattern() + ">(.*?)</gradient:" + PATTERN_HEX.pattern() + ">");
@NotNull
public static String apply(@NotNull String str) {
return hex(gradient(legacy(str)));
}
@NotNull
public static List<String> apply(@NotNull List<String> list) {
list.replaceAll(Colorizer::apply);
return list;
}
@NotNull
public static Set<String> apply(@NotNull Set<String> set) {
return set.stream().map(Colorizer::apply).collect(Collectors.toSet());
}
@NotNull
public static String legacyHex(@NotNull String str) {
return hex(legacy(str));
}
@NotNull
public static String legacy(@NotNull String str) {
return ChatColor.translateAlternateColorCodes('&', str);
}
@NotNull
public static String hex(@NotNull String str) {
TimedMatcher timedMatcher = TimedMatcher.create(PATTERN_HEX, str);
//Matcher matcher = PATTERN_HEX.matcher(str);
StringBuilder buffer = new StringBuilder(str.length() + 4 * 8);
while (timedMatcher.find()) {
Matcher matcher = timedMatcher.getMatcher();
String group = matcher.group(1);
matcher.appendReplacement(buffer,
ChatColor.COLOR_CHAR + "x" + ChatColor.COLOR_CHAR + group.charAt(0) +
ChatColor.COLOR_CHAR + group.charAt(1) + ChatColor.COLOR_CHAR + group.charAt(2) +
ChatColor.COLOR_CHAR + group.charAt(3) + ChatColor.COLOR_CHAR + group.charAt(4) +
ChatColor.COLOR_CHAR + group.charAt(5));
}
return timedMatcher.getMatcher().appendTail(buffer).toString();
}
private static ChatColor[] createGradient(@NotNull java.awt.Color start, @NotNull java.awt.Color end, int length) {
ChatColor[] colors = new ChatColor[length];
for (int index = 0; index < length; index++) {
double percent = (double) index / (double) length;
int red = (int) (start.getRed() + percent * (end.getRed() - start.getRed()));
int green = (int) (start.getGreen() + percent * (end.getGreen() - start.getGreen()));
int blue = (int) (start.getBlue() + percent * (end.getBlue() - start.getBlue()));
java.awt.Color color = new java.awt.Color(red, green, blue);
colors[index] = ChatColor.of(color);
}
return colors;
}
@NotNull
public static String gradient(@NotNull String string) {
TimedMatcher timedMatcher = TimedMatcher.create(PATTERN_GRADIENT, string);
//Matcher matcher = PATTERN_GRADIENT.matcher(string);
while (timedMatcher.find()) {
Matcher matcher = timedMatcher.getMatcher();
String start = matcher.group(1);
String end = matcher.group(3);
String content = matcher.group(2);
java.awt.Color colorStart = new java.awt.Color(Integer.parseInt(start, 16));
java.awt.Color colorEnd = new java.awt.Color(Integer.parseInt(end, 16));
ChatColor[] colors = createGradient(colorStart, colorEnd, strip(content).length());
StringBuilder gradiented = new StringBuilder();
StringBuilder specialColors = new StringBuilder();
char[] characters = content.toCharArray();
int outIndex = 0;
for (int index = 0; index < characters.length; index++) {
if (characters[index] == ChatColor.COLOR_CHAR) {
if (index + 1 < characters.length) {
if (characters[index + 1] == 'r') {
specialColors.setLength(0);
}
else {
specialColors.append(characters[index]);
specialColors.append(characters[index + 1]);
}
index++;
}
else gradiented.append(colors[outIndex++]).append(specialColors).append(characters[index]);
}
else gradiented.append(colors[outIndex++]).append(specialColors).append(characters[index]);
}
string = string.replace(matcher.group(0), gradiented.toString());
}
return string;
}
@NotNull
public static String plain(@NotNull String str) {
return plainLegacy(plainHex(str));
}
@NotNull
public static String plainLegacy(@NotNull String str) {
return str.replace(ChatColor.COLOR_CHAR, '&');
}
@NotNull
public static String plainHex(@NotNull String str) {
StringBuilder buffer = new StringBuilder(str);
int index;
while ((index = buffer.toString().indexOf(ChatColor.COLOR_CHAR + "x")) >= 0) {
int count = 0;
buffer.replace(index, index + 2, "#");
for (int point = index + 1; count < 6; point += 1) {
buffer.deleteCharAt(point);
count++;
}
}
return buffer.toString();
}
@NotNull
public static String strip(@NotNull String str) {
String stripped = ChatColor.stripColor(str);
return stripped == null ? "" : stripped;
}
@NotNull
public static String restrip(@NotNull String str) {
return strip(apply(str));
}
}
Loaded 100 of 172 files, more files were not shown because too many files have changed in this diff. Show more