add back spigot support, do a bunch of refactoring & fix lower versions not having adventure

This commit is contained in:
Pyrbu 2023-04-21 18:15:28 +01:00
parent c7ff0ed8e8
commit 983f240511
28 changed files with 91 additions and 218 deletions

@ -6,6 +6,9 @@ plugins {
repositories {
mavenCentral()
maven {
url "https://hub.spigotmc.org/nexus/content/repositories/snapshots/"
}
maven {
url "https://repo.papermc.io/repository/maven-public/"
}
@ -18,7 +21,7 @@ repositories {
}
dependencies {
compileOnly "io.papermc.paper:paper-api:1.19.4-R0.1-SNAPSHOT"
compileOnly "org.spigotmc:spigot-api:1.19.4-R0.1-SNAPSHOT"
compileOnly "me.clip:placeholderapi:2.11.1"
//noinspection GradlePackageUpdate
@ -31,6 +34,7 @@ dependencies {
implementation "com.google.code.gson:gson:2.10.1"
implementation "org.bstats:bstats-bukkit:3.0.2"
implementation "com.github.robertlit:SpigotResourcesAPI:2.0"
implementation "net.kyori:adventure-platform-bukkit:4.3.0"
}
group "lol.pyr"

@ -4,15 +4,15 @@ import com.google.common.collect.Iterables;
import io.github.znetworkw.znpcservers.commands.exception.CommandException;
import io.github.znetworkw.znpcservers.commands.exception.CommandExecuteException;
import io.github.znetworkw.znpcservers.commands.exception.CommandPermissionException;
import org.bukkit.Bukkit;
import io.github.znetworkw.znpcservers.reflection.Reflections;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandMap;
import org.bukkit.command.CommandSender;
import org.bukkit.command.defaults.BukkitCommand;
import java.lang.reflect.Method;
import java.util.*;
@SuppressWarnings("deprecation")
public class Command extends BukkitCommand {
private final Map<CommandInformation, CommandInvoker> subCommands;
@ -23,7 +23,7 @@ public class Command extends BukkitCommand {
}
private void load() {
Bukkit.getCommandMap().register(getName(), this);
((CommandMap) Reflections.COMMAND_MAP_FIELD.get()).register(getName(), this);
for (Method method : getClass().getMethods()) {
if (method.isAnnotationPresent(CommandInformation.class)) {
CommandInformation cmdInfo = method.getAnnotation(CommandInformation.class);

@ -7,19 +7,9 @@ import io.github.znetworkw.znpcservers.utility.GuavaCollectors;
public final class FunctionFactory {
public static ImmutableList<NPCFunction> WITHOUT_FUNCTION = ImmutableList.of(new NPCFunction.WithoutFunction("look"), new NPCFunction.WithoutFunctionSelfUpdate("holo"), new NPCFunction.WithoutFunctionSelfUpdate("mirror"));
public static ImmutableList<NPCFunction> WITH_FUNCTION = ImmutableList.of(new GlowFunction());
public static ImmutableList<NPCFunction> ALL = new ImmutableList.Builder<NPCFunction>()
.addAll(WITHOUT_FUNCTION)
.addAll(WITH_FUNCTION)
.build();
public static ImmutableMap<String, NPCFunction> BY_NAME;
static {
BY_NAME = ALL.stream().collect(GuavaCollectors.toImmutableMap(NPCFunction::getName, function -> function));
}
public static ImmutableList<NPCFunction> ALL = new ImmutableList.Builder<NPCFunction>().addAll(WITHOUT_FUNCTION).addAll(WITH_FUNCTION).build();
public static ImmutableMap<String, NPCFunction> BY_NAME = ALL.stream().collect(GuavaCollectors.toImmutableMap(NPCFunction::getName, function -> function));
public static NPCFunction findFunctionForName(String name) {
return BY_NAME.get(name);

@ -10,11 +10,8 @@ import org.bukkit.ChatColor;
public class NPCAction {
private final ActionType actionType;
private final ClickType clickType;
private final String action;
private int delay;
public NPCAction(ActionType actionType, ClickType clickType, String action, int delay) {
@ -65,7 +62,6 @@ public class NPCAction {
.toString();
}
@SuppressWarnings("deprecation")
enum ActionType {
CMD {
public void run(ZUser user, String actionValue) {

@ -9,31 +9,18 @@ import java.util.*;
@SuppressWarnings("unused")
public class NPCModel {
private int id;
private double hologramHeight;
private String skin;
private String signature = "";
private String pathName;
private String glowName;
private ConversationModel conversation;
private ZLocation location;
private NPCType npcType;
private List<String> hologramLines;
private List<NPCAction> clickActions;
private Map<ItemSlot, ItemStack> npcEquip;
private Map<String, Boolean> npcFunctions;
private Map<String, String[]> customizationMap;
public NPCModel(int id) {

@ -20,11 +20,8 @@ import java.util.concurrent.ConcurrentMap;
@SuppressWarnings("ALL")
public interface NPCPath {
void initialize(DataInputStream paramDataInputStream) throws IOException;
void write(DataOutputStream paramDataOutputStream) throws IOException;
void start();
PathInitializer getPath(NPC paramNPC);
interface PathInitializer {
@ -88,13 +85,9 @@ public interface NPCPath {
abstract class AbstractTypeWriter implements NPCPath {
private static final ConcurrentMap<String, AbstractTypeWriter> PATH_TYPES = new ConcurrentHashMap<>();
private static final int PATH_DELAY = 1;
private final TypeWriter typeWriter;
private final File file;
private final List<ZLocation> locationList;
public AbstractTypeWriter(TypeWriter typeWriter, File file) {

@ -5,12 +5,8 @@ import io.github.znetworkw.znpcservers.skin.SkinFetcherResult;
import io.github.znetworkw.znpcservers.utility.Utils;
public class NPCSkin {
private static final String[] EMPTY_ARRAY = new String[0];
private static final int LAYER_INDEX = SkinLayerValues.findLayerByVersion();
private final String texture;
private final String signature;
protected NPCSkin(String... values) {
@ -21,7 +17,7 @@ public class NPCSkin {
}
public static NPCSkin forValues(String... values) {
return new NPCSkin((values.length > 0) ? values : EMPTY_ARRAY);
return new NPCSkin((values.length > 0) ? values : new String[0]);
}
public static void forName(String skin, SkinFetcherResult skinFetcherResult) {

@ -18,20 +18,13 @@ public enum TypeProperty {
}
public static TypeProperty forType(Class<?> primitiveType) {
if (primitiveType == String.class)
return STRING;
if (primitiveType == boolean.class)
return BOOLEAN;
if (primitiveType == int.class)
return INT;
if (primitiveType == double.class)
return DOUBLE;
if (primitiveType == float.class)
return FLOAT;
if (primitiveType == short.class)
return SHORT;
if (primitiveType == long.class)
return LONG;
if (primitiveType == String.class) return STRING;
if (primitiveType == boolean.class) return BOOLEAN;
if (primitiveType == int.class) return INT;
if (primitiveType == double.class) return DOUBLE;
if (primitiveType == float.class) return FLOAT;
if (primitiveType == short.class) return SHORT;
if (primitiveType == long.class) return LONG;
return null;
}

@ -7,11 +7,8 @@ import java.util.List;
public class Conversation {
private final String name;
private final List<ConversationKey> texts;
private int radius = 5;
private int delay = 10;
public Conversation(String name) {

@ -10,13 +10,9 @@ import java.util.stream.StreamSupport;
public class ConversationKey {
private static final Splitter SPACE_SPLITTER = Splitter.on(" ");
private final List<String> lines;
private final List<NPCAction> actions;
private int delay = 1;
private String soundName;
public ConversationKey(String line) {

@ -16,15 +16,10 @@ import java.util.UUID;
public class ConversationProcessor {
private static final Map<UUID, String> RUNNING_CONVERSATIONS = new HashMap<>();
private final NPC npc;
private final ConversationModel conversationModel;
private final Player player;
private int conversationIndex = 0;
private long conversationIndexDelay = System.nanoTime();
public ConversationProcessor(NPC npc, ConversationModel conversationModel, Player player) {

@ -5,6 +5,7 @@ import org.bukkit.entity.Player;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
@SuppressWarnings("unused")
public class NPCInteractEvent extends Event {
private static final HandlerList handlerList = new HandlerList();
private final Player player;

@ -6,7 +6,6 @@ import net.md_5.bungee.api.ChatColor;
import java.util.concurrent.ThreadLocalRandom;
@SuppressWarnings("deprecation")
public class RGBLine implements LineReplacer {
public String make(String string) {
String rgbString = string;

@ -4,6 +4,7 @@ import com.mojang.authlib.GameProfile;
import io.github.znetworkw.znpcservers.reflection.types.*;
import io.github.znetworkw.znpcservers.utility.Utils;
import io.netty.channel.Channel;
import org.bukkit.Bukkit;
import org.bukkit.inventory.ItemStack;
import java.lang.reflect.Constructor;
@ -538,22 +539,26 @@ public final class Reflections {
public static final ReflectionLazyLoader<Object> ADD_PLAYER_FIELD = new FieldReflection(new ReflectionBuilder(ReflectionPackage.PACKET)
.withClassName("PacketPlayOutPlayerInfo$EnumPlayerInfoAction")
.withClassName("ClientboundPlayerInfoUpdatePacket$a")
.withFieldName((Utils.BUKKIT_VERSION > 16) ? "a" : "ADD_PLAYER")).asValueField();
.withFieldName((Utils.BUKKIT_VERSION > 16) ? "a" : "ADD_PLAYER")).staticValueLoader();
public static final ReflectionLazyLoader<Object> UPDATE_LISTED_FIELD = new FieldReflection(new ReflectionBuilder(ReflectionPackage.PACKET)
.withClassName("ClientboundPlayerInfoUpdatePacket$a")
.withFieldName("d")).asValueField();
.withFieldName("d")).staticValueLoader();
public static final ReflectionLazyLoader<Object> REMOVE_PLAYER_FIELD = new FieldReflection(new ReflectionBuilder(ReflectionPackage.PACKET)
.withClassName("PacketPlayOutPlayerInfo$EnumPlayerInfoAction")
.withClassName("ClientboundPlayerInfoUpdatePacket$a")
.withFieldName((Utils.BUKKIT_VERSION > 16) ? "e" : "REMOVE_PLAYER")).asValueField();
.withFieldName((Utils.BUKKIT_VERSION > 16) ? "e" : "REMOVE_PLAYER")).staticValueLoader();
public static final ReflectionLazyLoader<Object> DATA_WATCHER_REGISTER_FIELD = new FieldReflection(new ReflectionBuilder(ReflectionPackage.PACKET)
.withClassName(DATA_WATCHER_REGISTRY)
.withFieldName("a")).asValueField();
.withFieldName("a")).staticValueLoader();
public static final ReflectionLazyLoader<Object> ENUM_TAG_VISIBILITY_NEVER_FIELD = new FieldReflection(new ReflectionBuilder(ReflectionPackage.PACKET)
.withClassName(ENUM_TAG_VISIBILITY)
.withFieldName("b")).asValueField();
.withFieldName("b")).staticValueLoader();
public static final ReflectionLazyLoader<Object> COMMAND_MAP_FIELD = new FieldReflection(new ReflectionBuilder(ReflectionPackage.BUKKIT)
.withClassName("CraftServer")
.withFieldName("commandMap")).valueLoader(Bukkit.getServer());
}

@ -29,21 +29,27 @@ public class FieldReflection extends ReflectionLazyLoader<Field> {
return field;
}
public AsValueField asValueField() {
return new AsValueField(this, possibleClassNames);
public FieldValueReflection staticValueLoader() {
return new FieldValueReflection(this, possibleClassNames, null);
}
private static class AsValueField extends ReflectionLazyLoader<Object> {
public FieldValueReflection valueLoader(Object obj) {
return new FieldValueReflection(this, possibleClassNames, obj);
}
private static class FieldValueReflection extends ReflectionLazyLoader<Object> {
private final Object obj;
private final FieldReflection fieldReflection;
public AsValueField(FieldReflection fieldReflection, List<String> className) {
public FieldValueReflection(FieldReflection fieldReflection, List<String> className, Object obj) {
super(className);
this.obj = obj;
this.fieldReflection = fieldReflection;
}
protected Object load() throws IllegalAccessException, NoSuchFieldException {
Field field = this.fieldReflection.load();
return field.get(null);
Field field = this.fieldReflection.get();
return field.get(obj);
}
}
}

@ -16,7 +16,6 @@ import java.util.concurrent.Executors;
public class SkinFetcher {
private static final ExecutorService SKIN_EXECUTOR_SERVICE = Executors.newCachedThreadPool();
private final SkinFetcherBuilder builder;
public SkinFetcher(SkinFetcherBuilder builder) {
@ -31,32 +30,12 @@ public class SkinFetcher {
connection.setRequestMethod(this.builder.getAPIServer().getMethod());
if (this.builder.isUrlType()) {
connection.setDoOutput(true);
DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
try {
try (DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) {
outputStream.writeBytes("url=" + URLEncoder.encode(this.builder.getData(), StandardCharsets.UTF_8));
outputStream.close();
} catch (Throwable throwable) {
try {
outputStream.close();
} catch (Throwable throwable1) {
throwable.addSuppressed(throwable1);
}
throw throwable;
}
}
try {
Reader reader = new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8);
try {
completableFuture.complete(JsonParser.parseReader(reader).getAsJsonObject());
reader.close();
} catch (Throwable throwable) {
try {
reader.close();
} catch (Throwable throwable1) {
throwable.addSuppressed(throwable1);
}
throw throwable;
}
try (Reader reader = new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8)) {
completableFuture.complete(JsonParser.parseReader(reader).getAsJsonObject());
} finally {
connection.disconnect();
}

@ -35,9 +35,7 @@ public class EventService<T extends Event> {
}
public static <T extends Event> EventService<T> addService(ZUser user, Class<T> eventClass) {
if (EventService.hasService(user, eventClass)) {
throw new IllegalStateException(eventClass.getSimpleName() + " is already register for " + user.getUUID().toString());
}
if (EventService.hasService(user, eventClass)) throw new IllegalStateException(eventClass.getSimpleName() + " is already register for " + user.getUUID().toString());
EventService<T> service = new EventService<>(eventClass, new ArrayList<>());
user.getEventServices().add(service);
user.toPlayer().closeInventory();

@ -1,18 +1,17 @@
package io.github.znetworkw.znpcservers.user;
import com.mojang.authlib.GameProfile;
import io.github.znetworkw.znpcservers.reflection.Reflections;
import io.github.znetworkw.znpcservers.npc.NPC;
import io.github.znetworkw.znpcservers.npc.NPCAction;
import io.github.znetworkw.znpcservers.npc.event.ClickType;
import io.github.znetworkw.znpcservers.npc.event.NPCInteractEvent;
import io.github.znetworkw.znpcservers.reflection.Reflections;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageDecoder;
import lol.pyr.znpcsplus.ZNPCsPlus;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.NamedTextColor;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitRunnable;
@ -72,9 +71,9 @@ public class ZUser {
}
if (tries-- > 0) return;
cancel();
player.kick(Component.text("[ZNPCsPlus]", NamedTextColor.RED).appendNewline()
.append(Component.text("Couldn't inject interaction detector to channel", NamedTextColor.WHITE)).appendNewline()
.append(Component.text("Please report this at https://github.com/Pyrbu/ZNPCsPlus", NamedTextColor.WHITE)));
player.kickPlayer(ChatColor.RED + "[ZNPCsPlus]\n" +
ChatColor.WHITE + "Couldn't inject interaction detector to channel\n" +
ChatColor.WHITE + "Please report this at https://github.com/Pyrbu/ZNPCsPlus");
ZNPCsPlus.LOGGER.severe("Couldn't inject interaction detector to channel for player " + player.getName() + " (" + player.getUniqueId() + ")");
ex.printStackTrace();
}

@ -12,7 +12,6 @@ import org.bukkit.entity.Player;
import java.lang.reflect.Field;
import java.util.concurrent.ThreadLocalRandom;
@SuppressWarnings("deprecation")
public final class Utils {
public static final int BUKKIT_VERSION;
public static boolean PLACEHOLDER_SUPPORT = Bukkit.getPluginManager().isPluginEnabled("PlaceholderAPI");
@ -50,7 +49,7 @@ public final class Utils {
}
public static void sendTitle(Player player, String title, String subTitle) {
player.sendTitle(toColor(title), toColor(subTitle));
player.sendTitle(toColor(title), toColor(subTitle), 1, 3, 1);
}
public static void setValue(Object fieldInstance, String fieldName, Object value) throws NoSuchFieldException, IllegalAccessException {

@ -7,9 +7,7 @@ import org.bukkit.inventory.Inventory;
public class ZInventory {
private final Player player;
private ZInventoryPage page;
private Inventory inventory;
public ZInventory(Player player) {
@ -32,12 +30,9 @@ public class ZInventory {
this.page = page;
}
@SuppressWarnings("deprecation")
public Inventory build(ZInventoryPage page) {
if (page == null)
throw new IllegalStateException("page is null");
if (page.getRows() / 9 > 6)
throw new IllegalArgumentException(String.format("Unexpected rows size. Has %d, max %d", page.getRows(), 6));
if (page == null) throw new IllegalStateException("page is null");
if (page.getRows() / 9 > 6) throw new IllegalArgumentException(String.format("Unexpected rows size. Has %d, max %d", page.getRows(), 6));
setCurrentPage(page);
page.getInventoryItems().removeIf(zInventoryItem -> !zInventoryItem.isDefault());
page.update();

@ -4,11 +4,8 @@ import org.bukkit.inventory.ItemStack;
public class ZInventoryItem {
private final ItemStack itemStack;
private final int slot;
private final boolean isDefault;
private final ZInventoryCallback clickCallback;
public ZInventoryItem(ItemStack itemStack, int slot, boolean isDefault, ZInventoryCallback zInventoryCallback) {

@ -9,14 +9,10 @@ import org.bukkit.inventory.ItemStack;
import java.util.ArrayList;
import java.util.List;
@SuppressWarnings("deprecation")
public abstract class ZInventoryPage {
private final ZInventory zInventory;
private final String pageName;
private final int rows;
private final List<ZInventoryItem> inventoryItems;
public ZInventoryPage(ZInventory zInventory, String inventoryName, int rows) {

@ -9,7 +9,6 @@ import java.util.Arrays;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
@SuppressWarnings("deprecation")
public class ItemStackBuilder {
private final ItemStack itemStack;
@ -21,8 +20,7 @@ public class ItemStackBuilder {
}
public static ItemStackBuilder forMaterial(Material material) {
if (material == null || material == Material.AIR)
throw new IllegalStateException("can't create builder for a NULL material.");
if (material == null || material == Material.AIR) throw new IllegalStateException("can't create builder for a NULL material.");
return new ItemStackBuilder(new ItemStack(material, 1));
}
@ -32,8 +30,7 @@ public class ItemStackBuilder {
}
public ItemStackBuilder setLore(Iterable<String> lore) {
this.itemMeta.setLore(StreamSupport.stream(lore.spliterator(), false)
.map(Utils::toColor).collect(Collectors.toList()));
this.itemMeta.setLore(StreamSupport.stream(lore.spliterator(), false).map(Utils::toColor).collect(Collectors.toList()));
this.itemStack.setItemMeta(this.itemMeta);
return this;
}
@ -42,11 +39,6 @@ public class ItemStackBuilder {
return setLore(Arrays.asList(lore));
}
public ItemStackBuilder setAmount(int amount) {
this.itemStack.setAmount(amount);
return this;
}
public ItemStack build() {
this.itemStack.setItemMeta(this.itemMeta);
return this.itemStack;

@ -16,63 +16,19 @@ public class ItemStackSerializer implements JsonSerializer<ItemStack>, JsonDeser
private static final ItemStack DEFAULT = new ItemStack(Material.AIR);
public ItemStack deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
try {
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(Base64.getDecoder().decode(json.getAsString()));
try {
BukkitObjectInputStream bukkitObjectOutputStream = new BukkitObjectInputStream(byteArrayInputStream);
try {
ItemStack itemStack = (ItemStack) bukkitObjectOutputStream.readObject();
bukkitObjectOutputStream.close();
byteArrayInputStream.close();
return itemStack;
} catch (Throwable throwable) {
try {
bukkitObjectOutputStream.close();
} catch (Throwable throwable1) {
throwable.addSuppressed(throwable1);
}
throw throwable;
}
} catch (Throwable throwable) {
try {
byteArrayInputStream.close();
} catch (Throwable throwable1) {
throwable.addSuppressed(throwable1);
}
throw throwable;
}
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(Base64.getDecoder().decode(json.getAsString()));
try (BukkitObjectInputStream bukkitObjectOutputStream = new BukkitObjectInputStream(byteArrayInputStream)) {
return (ItemStack) bukkitObjectOutputStream.readObject();
} catch (IOException | ClassNotFoundException e) {
return DEFAULT;
}
}
public JsonElement serialize(ItemStack src, Type typeOfSrc, JsonSerializationContext context) {
try {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
try {
BukkitObjectOutputStream bukkitObjectOutputStream = new BukkitObjectOutputStream(byteArrayOutputStream);
try {
bukkitObjectOutputStream.writeObject(src);
JsonPrimitive jsonPrimitive = new JsonPrimitive(Base64.getEncoder().encodeToString(byteArrayOutputStream.toByteArray()));
bukkitObjectOutputStream.close();
byteArrayOutputStream.close();
return jsonPrimitive;
} catch (Throwable throwable) {
try {
bukkitObjectOutputStream.close();
} catch (Throwable throwable1) {
throwable.addSuppressed(throwable1);
}
throw throwable;
}
} catch (Throwable throwable) {
try {
byteArrayOutputStream.close();
} catch (Throwable throwable1) {
throwable.addSuppressed(throwable1);
}
throw throwable;
}
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
try (BukkitObjectOutputStream bukkitObjectOutputStream = new BukkitObjectOutputStream(byteArrayOutputStream)) {
bukkitObjectOutputStream.writeObject(src);
return new JsonPrimitive(Base64.getEncoder().encodeToString(byteArrayOutputStream.toByteArray()));
} catch (IOException e) {
throw new JsonParseException("Cannot serialize itemstack", e);
}

@ -1,5 +1,6 @@
package io.github.znetworkw.znpcservers.utility.location;
import com.google.common.base.Preconditions;
import com.google.gson.*;
import org.bukkit.Bukkit;
import org.bukkit.Location;
@ -9,19 +10,12 @@ import java.lang.reflect.Type;
public class ZLocation {
public static final ZLocationSerializer SERIALIZER = new ZLocationSerializer();
private final String worldName;
private final double x;
private final double y;
private final double z;
private final float yaw;
private final float pitch;
private Location bukkitLocation;
public ZLocation(String worldName, double x, double y, double z, float yaw, float pitch) {
@ -34,7 +28,7 @@ public class ZLocation {
}
public ZLocation(Location location) {
this(location.getWorld().getName(), location
this(Preconditions.checkNotNull(location.getWorld()).getName(), location
.getX(), location
.getY(), location
.getZ(), location

@ -17,10 +17,12 @@ import io.github.znetworkw.znpcservers.npc.task.NPCVisibilityTask;
import io.github.znetworkw.znpcservers.user.ZUser;
import io.github.znetworkw.znpcservers.utility.BungeeUtils;
import io.github.znetworkw.znpcservers.utility.SchedulerUtils;
import io.github.znetworkw.znpcservers.utility.Utils;
import io.github.znetworkw.znpcservers.utility.itemstack.ItemStackSerializer;
import io.github.znetworkw.znpcservers.utility.location.ZLocation;
import lol.pyr.znpcsplus.updater.UpdateChecker;
import lol.pyr.znpcsplus.updater.UpdateNotificationListener;
import net.kyori.adventure.platform.bukkit.BukkitAudiences;
import org.apache.commons.io.FileUtils;
import org.bstats.bukkit.Metrics;
import org.bukkit.Bukkit;
@ -47,6 +49,7 @@ public class ZNPCsPlus extends JavaPlugin {
private static final int PLUGIN_ID = 18244;
public static SchedulerUtils SCHEDULER;
public static BungeeUtils BUNGEE_UTILS;
public static BukkitAudiences ADVENTURE;
private boolean enabled = false;
@ -73,18 +76,21 @@ public class ZNPCsPlus extends JavaPlugin {
PATH_FOLDER = new File(PLUGIN_FOLDER, "paths");
}
@SuppressWarnings("deprecation")
private void log(Logger logger, String str) {
logger.info(Utils.versionNewer(12) ? str : ChatColor.stripColor(str).replace("\u2764 ", "<3"));
}
@Override
public void onEnable() {
Logger serverLogger = getServer().getLogger();
serverLogger.info(ChatColor.YELLOW + " ___ __ __ __");
serverLogger.info(ChatColor.YELLOW + " _/ |\\ | |__) | (__` " + ChatColor.GOLD + "__|__ " + ChatColor.YELLOW + getDescription().getName() + " " + ChatColor.GOLD + "v" + getDescription().getVersion());
serverLogger.info(ChatColor.YELLOW + " /__ | \\| | |__ .__) " + ChatColor.GOLD + " | " + ChatColor.GRAY + "Maintained with " + ChatColor.RED + "\u2764 " + ChatColor.GRAY + " by Pyr#6969");
serverLogger.info("");
log(serverLogger, ChatColor.YELLOW + " ___ __ __ __");
log(serverLogger, ChatColor.YELLOW + " _/ |\\ | |__) | (__` " + ChatColor.GOLD + "__|__ " + ChatColor.YELLOW + getDescription().getName() + " " + ChatColor.GOLD + "v" + getDescription().getVersion());
log(serverLogger, ChatColor.YELLOW + " /__ | \\| | |__ .__) " + ChatColor.GOLD + " | " + ChatColor.GRAY + "Maintained with " + ChatColor.RED + "\u2764 " + ChatColor.GRAY + " by Pyr#6969");
log(serverLogger, "");
if (Bukkit.getPluginManager().isPluginEnabled("ServersNPC")) {
serverLogger.info(ChatColor.DARK_RED + " * Detected old version of ZNPCs! Disabling the plugin.");
serverLogger.info("");
log(serverLogger, ChatColor.DARK_RED + " * Detected old version of ZNPCs! Disabling the plugin.");
log(serverLogger, "");
Bukkit.getPluginManager().disablePlugin(this);
return;
}
@ -92,21 +98,24 @@ public class ZNPCsPlus extends JavaPlugin {
File oldFolder = new File(PLUGIN_FOLDER.getParent(), "ServersNPC");
if (!PLUGIN_FOLDER.exists() && oldFolder.exists()) {
serverLogger.info(ChatColor.WHITE + " * Converting old ZNPCs files...");
log(serverLogger, ChatColor.WHITE + " * Converting old ZNPCs files...");
try {
FileUtils.moveDirectory(oldFolder, PLUGIN_FOLDER);
} catch (IOException e) {
serverLogger.info(ChatColor.RED + " * Failed to convert old ZNPCs files" + (e.getMessage() == null ? "" : " due to " + e.getMessage()));
log(serverLogger, ChatColor.RED + " * Failed to convert old ZNPCs files" + (e.getMessage() == null ? "" : " due to " + e.getMessage()));
}
}
log(serverLogger, ChatColor.WHITE + " * Initializing adventure...");
ADVENTURE = BukkitAudiences.create(this);
PLUGIN_FOLDER.mkdirs();
PATH_FOLDER.mkdirs();
serverLogger.info(ChatColor.WHITE + " * Loading paths...");
log(serverLogger, ChatColor.WHITE + " * Loading paths...");
loadAllPaths();
serverLogger.info(ChatColor.WHITE + " * Registering components...");
log(serverLogger, ChatColor.WHITE + " * Registering components...");
getServer().getMessenger().registerOutgoingPluginChannel(this, "BungeeCord");
new Metrics(this, PLUGIN_ID);
new DefaultCommand();
@ -114,7 +123,7 @@ public class ZNPCsPlus extends JavaPlugin {
BUNGEE_UTILS = new BungeeUtils(this);
Bukkit.getOnlinePlayers().forEach(ZUser::find);
serverLogger.info(ChatColor.WHITE + " * Starting tasks...");
log(serverLogger, ChatColor.WHITE + " * Starting tasks...");
new NPCPositionTask(this);
new NPCVisibilityTask(this);
new NPCSaveTask(this, ConfigurationConstants.SAVE_DELAY);
@ -123,8 +132,8 @@ public class ZNPCsPlus extends JavaPlugin {
if (ConfigurationConstants.CHECK_FOR_UPDATES) new UpdateNotificationListener(this, new UpdateChecker(this));
enabled = true;
serverLogger.info(ChatColor.WHITE + " * Loading complete! (" + (System.currentTimeMillis() - before) + "ms)");
serverLogger.info("");
log(serverLogger, ChatColor.WHITE + " * Loading complete! (" + (System.currentTimeMillis() - before) + "ms)");
log(serverLogger, "");
}
@Override
@ -132,6 +141,8 @@ public class ZNPCsPlus extends JavaPlugin {
if (!enabled) return;
Configuration.SAVE_CONFIGURATIONS.forEach(Configuration::save);
Bukkit.getOnlinePlayers().forEach(ZUser::unregister);
ADVENTURE.close();
ADVENTURE = null;
}
public void loadAllPaths() {

@ -7,7 +7,6 @@ import org.bukkit.scheduler.BukkitRunnable;
import java.util.concurrent.TimeUnit;
@SuppressWarnings("deprecation")
public class UpdateChecker extends BukkitRunnable {
private final static SpigotResourcesAPI api = new SpigotResourcesAPI(1, TimeUnit.MINUTES);
public final static int RESOURCE_ID = 109380;

@ -9,7 +9,6 @@ import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
@SuppressWarnings("deprecation")
public class UpdateNotificationListener implements Listener {
private final ZNPCsPlus plugin;
private final UpdateChecker updateChecker;
@ -26,7 +25,8 @@ public class UpdateNotificationListener implements Listener {
if (updateChecker.getStatus() != UpdateChecker.Status.UPDATE_NEEDED) return;
Bukkit.getScheduler().runTaskLater(plugin, () -> {
if (!event.getPlayer().isOnline()) return;
event.getPlayer().sendMessage(Component.text(plugin.getDescription().getName() + " v" + updateChecker.getLatestVersion() + " is available now!", NamedTextColor.GOLD).appendNewline()
ZNPCsPlus.ADVENTURE.player(event.getPlayer())
.sendMessage(Component.text(plugin.getDescription().getName() + " v" + updateChecker.getLatestVersion() + " is available now!", NamedTextColor.GOLD).appendNewline()
.append(Component.text("Click this message to open the Spigot page (CLICK)", NamedTextColor.YELLOW)).clickEvent(ClickEvent.openUrl(UpdateChecker.DOWNLOAD_LINK)));
}, 100L);
}