9 Commits
Author SHA1 Message Date
XiaoMoMi 9d88ead4e3 remap libs 2024-02-20 04:59:14 +08:00
XiaoMoMi 810b8f0593 version number 2024-02-18 03:23:44 +08:00
XiaoMoMi 930cdf8c00 Fix concurrent modification 2024-02-18 03:16:33 +08:00
XiaoMoMi a26e6dc784 optimize imports 2024-02-10 18:44:22 +08:00
XiaoMoMi e450b1429d channel mode 2024-02-04 18:43:55 +08:00
XiaoMoMi 7811cea007 Update gradle.properties 2024-02-03 03:51:39 +08:00
XiaoMoMi 22a440ae23 geyser 2024-02-03 03:43:30 +08:00
XiaoMoMi c279c9a74d Update build.gradle.kts 2024-02-03 03:27:35 +08:00
XiaoMoMi a6b11d1fe7 2.3.2 2024-02-03 03:25:34 +08:00
67 changed files with 2474 additions and 463 deletions

No files matched your search

+1 -1
View File
@@ -1,7 +1,7 @@
dependencies {
implementation(project(":common"))
compileOnly("dev.folia:folia-api:1.20.1-R0.1-SNAPSHOT")
compileOnly("me.clip:placeholderapi:2.11.5")
implementation(project(":common"))
implementation("net.kyori:adventure-api:4.15.0")
}
@@ -18,6 +18,7 @@
package net.momirealms.customnameplates.api.manager;
import net.momirealms.customnameplates.api.mechanic.bubble.Bubble;
import net.momirealms.customnameplates.api.mechanic.bubble.provider.AbstractChatProvider;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.Nullable;
@@ -26,6 +27,21 @@ import java.util.List;
public interface BubbleManager {
/**
* Set a custom chat provider
*
* @param provider provider
* @return success or not
*/
boolean setCustomChatProvider(AbstractChatProvider provider);
/**
* Remove a custom chat provider
*
* @return success or not
*/
boolean removeCustomChatProvider();
/**
* Register a bubble into map
*
@@ -118,10 +134,20 @@ public interface BubbleManager {
*/
String getDefaultBubble();
void onChat(Player player, String text, String channel);
/**
* Get all the bubbles' keys
*
* @return keys
*/
Collection<String> getBubbleKeys();
/**
* Trigger chat
*
* @param player player
* @param text text
*/
void onChat(Player player, String text);
}
@@ -0,0 +1,25 @@
/*
* Copyright (C) <2022> <XiaoMoMi>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package net.momirealms.customnameplates.api.mechanic.bubble;
public enum ChannelMode {
ALL,
JOINED,
CAN_JOIN
}
@@ -0,0 +1,39 @@
/*
* Copyright (C) <2022> <XiaoMoMi>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package net.momirealms.customnameplates.api.mechanic.bubble.provider;
import net.momirealms.customnameplates.api.manager.BubbleManager;
import org.bukkit.entity.Player;
import org.bukkit.event.Listener;
public abstract class AbstractChatProvider implements Listener {
protected BubbleManager chatBubblesManager;
public AbstractChatProvider(BubbleManager chatBubblesManager) {
this.chatBubblesManager = chatBubblesManager;
}
public abstract void register();
public abstract void unregister();
public abstract boolean hasJoinedChannel(Player player, String channelID);
public abstract boolean canJoinChannel(Player player, String channelID);
}
@@ -44,9 +44,11 @@ public class ViewerText {
for (String placeholder : placeholders) {
processedText = processedText.replace(placeholder, "%s");
if (placeholder.startsWith("%viewer_")) {
this.placeholders[i] = new ClaimedText(null, "%" + placeholder.substring("%viewer_".length()));
this.placeholders[i] = new ClaimedText(null, "%" + placeholder.substring("%viewer_".length()), false);
} else if (placeholder.startsWith("%rel_")) {
this.placeholders[i] = new ClaimedText(owner, placeholder, true);
} else {
this.placeholders[i] = new ClaimedText(owner, placeholder);
this.placeholders[i] = new ClaimedText(owner, placeholder, false);
}
i++;
}
@@ -109,11 +111,13 @@ public class ViewerText {
private final String placeholder;
private final Player owner;
private String latestValue;
private final boolean relational;
public ClaimedText(Player owner, String placeholder) {
public ClaimedText(Player owner, String placeholder, boolean relational) {
this.placeholder = placeholder;
this.owner = owner;
this.latestValue = null;
this.relational = relational;
this.update();
}
@@ -125,7 +129,13 @@ public class ViewerText {
public String getValue(Player viewer) {
return Objects.requireNonNullElseGet(
latestValue,
() -> PlaceholderAPI.setPlaceholders(owner == null ? viewer : owner, placeholder)
() -> {
if (relational) {
return PlaceholderAPI.setRelationalPlaceholders(viewer, owner, placeholder);
} else {
return PlaceholderAPI.setPlaceholders(owner == null ? viewer : owner, placeholder);
}
}
);
}
}
@@ -20,7 +20,7 @@ package net.momirealms.customnameplates.api.mechanic.tag.unlimited;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import java.util.Vector;
import java.util.Collection;
public interface EntityTagEntity {
@@ -30,7 +30,7 @@ public interface EntityTagEntity {
void removeTag(StaticTextEntity tag);
Vector<StaticTextEntity> getStaticTags();
Collection<StaticTextEntity> getStaticTags();
void forceAddNearbyPlayer(Player player);
@@ -19,7 +19,7 @@ package net.momirealms.customnameplates.api.mechanic.tag.unlimited;
import net.momirealms.customnameplates.api.mechanic.tag.NameplatePlayer;
import java.util.Vector;
import java.util.Collection;
public interface EntityTagPlayer extends NameplatePlayer {
@@ -35,9 +35,9 @@ public interface EntityTagPlayer extends NameplatePlayer {
void removeTag(StaticTextEntity tag);
Vector<DynamicTextEntity> getDynamicTags();
Collection<DynamicTextEntity> getDynamicTags();
Vector<StaticTextEntity> getStaticTags();
Collection<StaticTextEntity> getStaticTags();
void setHatOffset(double hatOffset);
+2 -1
View File
@@ -7,7 +7,7 @@ plugins {
allprojects {
version = "2.3.1.0"
version = "2.3.3.0"
apply<JavaPlugin>()
apply(plugin = "java")
@@ -43,6 +43,7 @@ allprojects {
maven("https://repo.kryptonmc.org/releases")
maven("https://repo.oraxen.com/releases/")
maven("https://nexus.codecrafter47.de/content/repositories/public/")
maven("https://repo.opencollab.dev/main/")
}
}
+16 -7
View File
@@ -12,7 +12,10 @@ dependencies {
compileOnly("me.clip:placeholderapi:2.11.5")
// config
compileOnly("dev.dejvokep:boosted-yaml:1.3.1")
compileOnly("dev.dejvokep:boosted-yaml:1.3.2")
// bStats
compileOnly("org.bstats:bstats-bukkit:3.0.2")
// team
compileOnly("me.neznamy:tab-api:4.0.2")
@@ -33,11 +36,13 @@ dependencies {
compileOnly("io.th0rgal:oraxen:1.165.0")
compileOnly("com.github.FrancoBM12:API-MagicCosmetics:2.2.5")
compileOnly("commons-io:commons-io:2.15.1")
compileOnly("org.geysermc.geyser:api:2.2.0-SNAPSHOT")
// chat channels
compileOnly(files("libs/VentureChat-3.7.1.jar"))
compileOnly(files("libs/TrChat-2.0.11.jar"))
compileOnly(files("libs/carbonchat-paper-3.0.0-beta.26.jar"))
compileOnly("net.william278:huskchat:2.7.1")
// api module
implementation(project(":api"))
@@ -46,11 +51,6 @@ dependencies {
// adventure
implementation("net.kyori:adventure-api:4.15.0")
implementation("net.kyori:adventure-platform-bukkit:4.3.2")
implementation("net.kyori:adventure-text-minimessage:4.15.0")
implementation("net.kyori:adventure-text-serializer-legacy:4.15.0")
// bStats
implementation("org.bstats:bstats-bukkit:3.0.2")
// local lib
implementation(files("libs/BiomeAPI.jar"))
@@ -61,5 +61,14 @@ tasks {
relocate ("net.kyori", "net.momirealms.customnameplates.libraries")
relocate ("org.bstats", "net.momirealms.customnameplates.libraries.bstats")
relocate ("net.momirealms.biomeapi", "net.momirealms.customnameplates.libraries.biomeapi")
relocate ("org.apache.commons.pool2", "net.momirealms.customnameplates.libraries.commonspool2")
relocate ("com.mysql", "net.momirealms.customnameplates.libraries.mysql")
relocate ("org.mariadb", "net.momirealms.customnameplates.libraries.mariadb")
relocate ("com.zaxxer.hikari", "net.momirealms.customnameplates.libraries.hikari")
relocate ("redis.clients.jedis", "net.momirealms.customnameplates.libraries.jedis")
relocate ("com.mongodb", "net.momirealms.customnameplates.libraries.mongodb")
relocate ("org.bson", "net.momirealms.customnameplates.libraries.bson")
relocate ("dev.jorel.commandapi", "net.momirealms.customnameplates.libraries.commandapi")
relocate ("dev.dejvokep.boostedyaml", "net.momirealms.customnameplates.libraries.boostedyaml")
}
}
Binary file not shown.
@@ -22,7 +22,10 @@ import net.momirealms.customnameplates.api.event.CustomNameplatesReloadEvent;
import net.momirealms.customnameplates.api.util.LogUtils;
import net.momirealms.customnameplates.paper.adventure.AdventureManagerImpl;
import net.momirealms.customnameplates.paper.command.CommandManager;
import net.momirealms.customnameplates.paper.helper.LibraryLoader;
import net.momirealms.customnameplates.paper.libraries.classpath.ReflectionClassPathAppender;
import net.momirealms.customnameplates.paper.libraries.dependencies.Dependency;
import net.momirealms.customnameplates.paper.libraries.dependencies.DependencyManager;
import net.momirealms.customnameplates.paper.libraries.dependencies.DependencyManagerImpl;
import net.momirealms.customnameplates.paper.mechanic.actionbar.ActionBarManagerImpl;
import net.momirealms.customnameplates.paper.mechanic.background.BackGroundManagerImpl;
import net.momirealms.customnameplates.paper.mechanic.bossbar.BossBarManagerImpl;
@@ -50,16 +53,41 @@ import org.bukkit.event.HandlerList;
import org.bukkit.event.Listener;
import java.io.File;
import java.util.TimeZone;
import java.util.ArrayList;
import java.util.List;
public class CustomNameplatesPluginImpl extends CustomNameplatesPlugin implements Listener {
private CoolDownManager coolDownManager;
private PacketManager packetManager;
private DependencyManager dependencyManager;
@Override
public void onLoad() {
this.loadLibraries();
this.dependencyManager = new DependencyManagerImpl(this, new ReflectionClassPathAppender(this.getClassLoader()));
this.dependencyManager.loadDependencies(new ArrayList<>(
List.of(
Dependency.GSON,
Dependency.SLF4J_API,
Dependency.SLF4J_SIMPLE,
Dependency.COMMAND_API,
Dependency.BOOSTED_YAML,
Dependency.ADVENTURE_TEXT_MINIMESSAGE,
Dependency.ADVENTURE_LEGACY_SERIALIZER,
Dependency.MYSQL_DRIVER,
Dependency.MARIADB_DRIVER,
Dependency.MONGODB_DRIVER_SYNC,
Dependency.MONGODB_DRIVER_CORE,
Dependency.MONGODB_DRIVER_BSON,
Dependency.JEDIS,
Dependency.COMMONS_POOL_2,
Dependency.H2_DRIVER,
Dependency.SQLITE_DRIVER,
Dependency.BSTATS_BASE,
Dependency.HIKARI,
Dependency.BSTATS_BUKKIT
)
));
ReflectionUtils.load();
}
@@ -155,27 +183,6 @@ public class CustomNameplatesPluginImpl extends CustomNameplatesPlugin implement
}
}
private void loadLibraries() {
String mavenRepo = TimeZone.getDefault().getID().startsWith("Asia") ?
"https://maven.aliyun.com/repository/public/" : "https://repo.maven.apache.org/maven2/";
LibraryLoader.loadDependencies(
"org.apache.commons:commons-pool2:2.12.0", mavenRepo,
"redis.clients:jedis:5.1.0", mavenRepo,
"dev.dejvokep:boosted-yaml:1.3.1", mavenRepo,
"com.zaxxer:HikariCP:5.0.1", mavenRepo,
"org.mariadb.jdbc:mariadb-java-client:3.3.0", mavenRepo,
"com.mysql:mysql-connector-j:8.2.0", mavenRepo,
"commons-io:commons-io:2.15.1", mavenRepo,
"com.google.code.gson:gson:2.10.1", mavenRepo,
"com.h2database:h2:2.2.224", mavenRepo,
"org.mongodb:mongodb-driver-sync:4.11.1", mavenRepo,
"org.mongodb:mongodb-driver-core:4.11.1", mavenRepo,
"org.mongodb:bson:4.11.1", mavenRepo,
"org.xerial:sqlite-jdbc:3.43.2.2", mavenRepo,
"dev.jorel:commandapi-bukkit-shade:9.3.0", mavenRepo
);
}
public CoolDownManager getCoolDownManager() {
return coolDownManager;
}
@@ -183,4 +190,8 @@ public class CustomNameplatesPluginImpl extends CustomNameplatesPlugin implement
public PacketManager getPacketManager() {
return packetManager;
}
public DependencyManager getDependencyManager() {
return dependencyManager;
}
}
@@ -116,7 +116,7 @@ public class CommandManager {
for (String availableBubble : bubbles) {
stringJoiner.add(availableBubble);
}
AdventureManagerImpl.getInstance().sendMessageWithPrefix(player, CNLocale.MSG_AVAILABLE_BUBBLE.replace("{Bubble}", stringJoiner.toString()));
AdventureManagerImpl.getInstance().sendMessageWithPrefix(player, CNLocale.MSG_AVAILABLE_BUBBLE.replace("{Bubble}", stringJoiner.toString()).replace("{Bubbles}", stringJoiner.toString()));
} else {
AdventureManagerImpl.getInstance().sendMessageWithPrefix(player, CNLocale.MSG_HAVE_NO_BUBBLE);
}
@@ -340,7 +340,7 @@ public class CommandManager {
for (String availableNameplate : nameplates) {
stringJoiner.add(availableNameplate);
}
AdventureManagerImpl.getInstance().sendMessageWithPrefix(player, CNLocale.MSG_AVAILABLE_NAMEPLATE.replace("{Nameplates}", stringJoiner.toString()));
AdventureManagerImpl.getInstance().sendMessageWithPrefix(player, CNLocale.MSG_AVAILABLE_NAMEPLATE.replace("{Nameplates}", stringJoiner.toString()).replace("{Nameplate}", stringJoiner.toString()));
} else {
AdventureManagerImpl.getInstance().sendMessageWithPrefix(player, CNLocale.MSG_HAVE_NO_NAMEPLATE);
}
@@ -1,182 +0,0 @@
/*
* This file is part of helper, licensed under the MIT License.
*
* Copyright (c) lucko (Luck) <luck@lucko.me>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.momirealms.customnameplates.paper.helper;
import com.google.common.base.Supplier;
import com.google.common.base.Suppliers;
import net.momirealms.customnameplates.api.CustomNameplatesPlugin;
import net.momirealms.customnameplates.api.util.LogUtils;
import net.momirealms.customnameplates.paper.CustomNameplatesPluginImpl;
import java.io.File;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.Files;
import java.util.Objects;
import java.util.StringJoiner;
/**
* Resolves {@link MavenLibrary} annotations for a class, and loads the dependency
* into the classloader.
*/
public final class LibraryLoader {
@SuppressWarnings("Guava")
private static final Supplier<URLClassLoaderAccess> URL_INJECTOR = Suppliers.memoize(() -> URLClassLoaderAccess.create((URLClassLoader) CustomNameplatesPluginImpl.getInstance().getClass().getClassLoader()));
/**
* Resolves all {@link MavenLibrary} annotations on the given object.
*
* @param object the object to load libraries for.
*/
public static void loadAll(Object object) {
loadAll(object.getClass());
}
/**
* Resolves all {@link MavenLibrary} annotations on the given class.
*
* @param clazz the class to load libraries for.
*/
public static void loadAll(Class<?> clazz) {
MavenLibrary[] libs = clazz.getDeclaredAnnotationsByType(MavenLibrary.class);
for (MavenLibrary lib : libs) {
load(lib.groupId(), lib.artifactId(), lib.version(), lib.repo().url());
}
}
public static void load(String groupId, String artifactId, String version, String repoUrl) {
load(new Dependency(groupId, artifactId, version, repoUrl));
}
public static void loadDependencies(String... libs) {
if (libs == null || libs.length % 2 != 0)
return;
for (int i = 0; i < libs.length; i+=2) {
String[] split = libs[i].split(":");
load(new Dependency(
split[0],
split[1],
split[2],
libs[i+1]
));
}
}
public static void load(Dependency d) {
// LogUtils.info(String.format("Loading dependency %s:%s:%s", d.groupId, d.artifactId, d.version));
String name = d.artifactId() + "-" + d.version();
File saveLocation = new File(getLibFolder(d), name + ".jar");
if (!saveLocation.exists()) {
try {
LogUtils.info("Dependency '" + name + "' is not already in the libraries folder. Attempting to download...");
URL url = d.getUrl();
try (InputStream is = url.openStream()) {
Files.copy(is, saveLocation.toPath());
LogUtils.info("Dependency '" + name + "' successfully downloaded.");
}
} catch (Exception e) {
e.printStackTrace();
}
}
if (!saveLocation.exists())
throw new RuntimeException("Unable to download dependency: " + d);
try {
URL_INJECTOR.get().addURL(saveLocation.toURI().toURL());
} catch (Exception e) {
throw new RuntimeException("Unable to load dependency: " + saveLocation, e);
}
}
@SuppressWarnings("all")
private static File getLibFolder(Dependency dependency) {
File pluginDataFolder = CustomNameplatesPlugin.getInstance().getDataFolder();
File serverDir = pluginDataFolder.getParentFile().getParentFile();
File helperDir = new File(serverDir, "libraries");
String[] split = dependency.groupId().split("\\.");
File jarDir;
StringJoiner stringJoiner = new StringJoiner(File.separator);
for (String str : split) {
stringJoiner.add(str);
}
jarDir = new File(helperDir, stringJoiner + File.separator + dependency.artifactId + File.separator + dependency.version);
jarDir.mkdirs();
return jarDir;
}
public record Dependency(String groupId, String artifactId, String version, String repoUrl) {
public Dependency(String groupId, String artifactId, String version, String repoUrl) {
this.groupId = Objects.requireNonNull(groupId, "groupId");
this.artifactId = Objects.requireNonNull(artifactId, "artifactId");
this.version = Objects.requireNonNull(version, "version");
this.repoUrl = Objects.requireNonNull(repoUrl, "repoUrl");
}
public URL getUrl() throws MalformedURLException {
String repo = this.repoUrl;
if (!repo.endsWith("/")) {
repo += "/";
}
repo += "%s/%s/%s/%s-%s.jar";
String url = String.format(repo, this.groupId.replace(".", "/"), this.artifactId, this.version, this.artifactId, this.version);
return new URL(url);
}
@Override
public boolean equals(Object o) {
if (o == this) return true;
if (!(o instanceof Dependency other)) return false;
return this.groupId().equals(other.groupId()) &&
this.artifactId().equals(other.artifactId()) &&
this.version().equals(other.version()) &&
this.repoUrl().equals(other.repoUrl());
}
@Override
public int hashCode() {
final int PRIME = 59;
int result = 1;
result = result * PRIME + this.groupId().hashCode();
result = result * PRIME + this.artifactId().hashCode();
result = result * PRIME + this.version().hashCode();
result = result * PRIME + this.repoUrl().hashCode();
return result;
}
@Override
public String toString() {
return "LibraryLoader.Dependency(" +
"groupId=" + this.groupId() + ", " +
"artifactId=" + this.artifactId() + ", " +
"version=" + this.version() + ", " +
"repoUrl=" + this.repoUrl() + ")";
}
}
}
@@ -1,5 +1,5 @@
/*
* This file is part of helper, licensed under the MIT License.
* This file is part of LuckPerms, licensed under the MIT License.
*
* Copyright (c) lucko (Luck) <luck@lucko.me>
* Copyright (c) contributors
@@ -23,21 +23,19 @@
* SOFTWARE.
*/
package net.momirealms.customnameplates.paper.helper;
package net.momirealms.customnameplates.paper.libraries.classpath;
import org.jetbrains.annotations.NotNull;
import java.lang.annotation.*;
import java.nio.file.Path;
/**
* Annotation to indicate the required libraries for a class.
* Interface which allows access to add URLs to the plugin classpath at runtime.
*/
@Documented
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface MavenLibraries {
public interface ClassPathAppender extends AutoCloseable {
@NotNull
MavenLibrary[] value() default {};
void addJarToClasspath(Path file);
@Override
default void close() {
}
}
@@ -0,0 +1,62 @@
/*
* This file is part of LuckPerms, licensed under the MIT License.
*
* Copyright (c) lucko (Luck) <luck@lucko.me>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.momirealms.customnameplates.paper.libraries.classpath;
import net.momirealms.customnameplates.paper.libraries.loader.JarInJarClassLoader;
import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.file.Path;
public class JarInJarClassPathAppender implements ClassPathAppender {
private final JarInJarClassLoader classLoader;
public JarInJarClassPathAppender(ClassLoader classLoader) {
if (!(classLoader instanceof JarInJarClassLoader)) {
throw new IllegalArgumentException("Loader is not a JarInJarClassLoader: " + classLoader.getClass().getName());
}
this.classLoader = (JarInJarClassLoader) classLoader;
}
@Override
public void addJarToClasspath(Path file) {
try {
this.classLoader.addJarToClasspath(file.toUri().toURL());
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
}
@Override
public void close() {
this.classLoader.deleteJarResource();
try {
this.classLoader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
@@ -0,0 +1,52 @@
/*
* This file is part of LuckPerms, licensed under the MIT License.
*
* Copyright (c) lucko (Luck) <luck@lucko.me>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.momirealms.customnameplates.paper.libraries.classpath;
import java.net.MalformedURLException;
import java.net.URLClassLoader;
import java.nio.file.Path;
public class ReflectionClassPathAppender implements ClassPathAppender {
private final URLClassLoaderAccess classLoaderAccess;
public ReflectionClassPathAppender(ClassLoader classLoader) throws IllegalStateException {
if (classLoader instanceof URLClassLoader) {
this.classLoaderAccess = URLClassLoaderAccess.create((URLClassLoader) classLoader);
} else {
throw new IllegalStateException("ClassLoader is not instance of URLClassLoader");
}
}
@Override
public void addJarToClasspath(Path file) {
try {
this.classLoaderAccess.addURL(file.toUri().toURL());
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
}
}
@@ -1,5 +1,5 @@
/*
* This file is part of helper, licensed under the MIT License.
* This file is part of LuckPerms, licensed under the MIT License.
*
* Copyright (c) lucko (Luck) <luck@lucko.me>
* Copyright (c) contributors
@@ -23,11 +23,12 @@
* SOFTWARE.
*/
package net.momirealms.customnameplates.paper.helper;
package net.momirealms.customnameplates.paper.libraries.classpath;
import org.jetbrains.annotations.NotNull;
import org.checkerframework.checker.nullness.qual.NonNull;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Collection;
@@ -43,8 +44,10 @@ public abstract class URLClassLoaderAccess {
* @param classLoader the class loader
* @return the access object
*/
static URLClassLoaderAccess create(URLClassLoader classLoader) {
if (Unsafe.isSupported()) {
public static URLClassLoaderAccess create(URLClassLoader classLoader) {
if (Reflection.isSupported()) {
return new Reflection(classLoader);
} else if (Unsafe.isSupported()) {
return new Unsafe(classLoader);
} else {
return Noop.INSTANCE;
@@ -63,7 +66,48 @@ public abstract class URLClassLoaderAccess {
*
* @param url the URL to add
*/
public abstract void addURL(@NotNull URL url);
public abstract void addURL(@NonNull URL url);
private static void throwError(Throwable cause) throws UnsupportedOperationException {
throw new UnsupportedOperationException("LuckPerms is unable to inject into the plugin URLClassLoader.\n" +
"You may be able to fix this problem by adding the following command-line argument " +
"directly after the 'java' command in your start script: \n'--add-opens java.base/java.lang=ALL-UNNAMED'", cause);
}
/**
* Accesses using reflection, not supported on Java 9+.
*/
private static class Reflection extends URLClassLoaderAccess {
private static final Method ADD_URL_METHOD;
static {
Method addUrlMethod;
try {
addUrlMethod = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
addUrlMethod.setAccessible(true);
} catch (Exception e) {
addUrlMethod = null;
}
ADD_URL_METHOD = addUrlMethod;
}
private static boolean isSupported() {
return ADD_URL_METHOD != null;
}
Reflection(URLClassLoader classLoader) {
super(classLoader);
}
@Override
public void addURL(@NonNull URL url) {
try {
ADD_URL_METHOD.invoke(super.classLoader, url);
} catch (ReflectiveOperationException e) {
URLClassLoaderAccess.throwError(e);
}
}
}
/**
* Accesses using sun.misc.Unsafe, supported on Java 9+.
@@ -106,6 +150,7 @@ public abstract class URLClassLoaderAccess {
unopenedURLs = null;
pathURLs = null;
}
this.unopenedURLs = unopenedURLs;
this.pathURLs = pathURLs;
}
@@ -117,9 +162,15 @@ public abstract class URLClassLoaderAccess {
}
@Override
public void addURL(@NotNull URL url) {
this.unopenedURLs.add(url);
this.pathURLs.add(url);
public void addURL(@NonNull URL url) {
if (this.unopenedURLs == null || this.pathURLs == null) {
URLClassLoaderAccess.throwError(new NullPointerException("unopenedURLs or pathURLs"));
}
synchronized (this.unopenedURLs) {
this.unopenedURLs.add(url);
this.pathURLs.add(url);
}
}
}
@@ -131,8 +182,8 @@ public abstract class URLClassLoaderAccess {
}
@Override
public void addURL(@NotNull URL url) {
throw new UnsupportedOperationException();
public void addURL(@NonNull URL url) {
URLClassLoaderAccess.throwError(null);
}
}
@@ -0,0 +1,360 @@
/*
* This file is part of LuckPerms, licensed under the MIT License.
*
* Copyright (c) lucko (Luck) <luck@lucko.me>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.momirealms.customnameplates.paper.libraries.dependencies;
import com.google.common.collect.ImmutableList;
import net.momirealms.customnameplates.paper.libraries.dependencies.relocation.Relocation;
import org.jetbrains.annotations.Nullable;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.Locale;
/**
* The dependencies used by LuckPerms.
*/
public enum Dependency {
ASM(
"org.ow2.asm",
"asm",
"9.1",
null,
"asm"
),
ASM_COMMONS(
"org.ow2.asm",
"asm-commons",
"9.1",
null,
"asm-commons"
),
JAR_RELOCATOR(
"me.lucko",
"jar-relocator",
"1.7",
null,
"jar-relocator"
),
KYORI_OPTION(
"net{}kyori",
"option",
"1.0.0",
null,
"kyori-option",
Relocation.of("option", "net{}kyori{}option")
),
ADVENTURE_API(
"net{}kyori",
"adventure-api",
"4.15.0",
null,
"adventure-api",
Relocation.of("adventure", "net{}kyori{}adventure")
),
ADVENTURE_KEY(
"net{}kyori",
"adventure-key",
"4.15.0",
null,
"adventure-key",
Relocation.of("adventure", "net{}kyori{}adventure")
),
ADVENTURE_NBT(
"net{}kyori",
"adventure-nbt",
"4.15.0",
null,
"adventure-nbt",
Relocation.of("adventure", "net{}kyori{}adventure")
),
ADVENTURE_LEGACY_SERIALIZER(
"net{}kyori",
"adventure-text-serializer-legacy",
"4.15.0",
null,
"adventure-text-serializer-legacy",
Relocation.of("adventure", "net{}kyori{}adventure")
),
ADVENTURE_TEXT_LOGGER(
"net{}kyori",
"adventure-text-logger-slf4j",
"4.15.0",
null,
"adventure-text-logger-slf4j",
Relocation.of("adventure", "net{}kyori{}adventure")
),
ADVENTURE_GSON(
"net{}kyori",
"adventure-text-serializer-gson",
"4.15.0",
null,
"adventure-text-serializer-gson",
Relocation.of("adventure", "net{}kyori{}adventure")
),
ADVENTURE_GSON_LEGACY(
"net{}kyori",
"adventure-text-serializer-gson-legacy-impl",
"4.15.0",
null,
"adventure-text-serializer-gson-legacy-impl",
Relocation.of("adventure", "net{}kyori{}adventure")
),
ADVENTURE_PLATFORM(
"net{}kyori",
"adventure-platform-api",
"4.3.2",
null,
"adventure-platform-api",
Relocation.of("adventure", "net{}kyori{}adventure")
),
ADVENTURE_PLATFORM_BUKKIT(
"net{}kyori",
"adventure-platform-bukkit",
"4.3.2",
null,
"adventure-platform-bukkit",
Relocation.of("adventure", "net{}kyori{}adventure")
),
ADVENTURE_PLATFORM_FACET(
"net{}kyori",
"adventure-platform-facet",
"4.3.2",
null,
"adventure-platform-facet",
Relocation.of("adventure", "net{}kyori{}adventure")
),
ADVENTURE_TEXT_MINIMESSAGE(
"net{}kyori",
"adventure-text-minimessage",
"4.15.0",
null,
"adventure-text-minimessage",
Relocation.of("adventure", "net{}kyori{}adventure")
),
COMMAND_API(
"dev{}jorel",
"commandapi-bukkit-shade",
"9.3.0",
null,
"commandapi-bukkit",
Relocation.of("commandapi", "dev{}jorel{}commandapi")
),
MARIADB_DRIVER(
"org{}mariadb{}jdbc",
"mariadb-java-client",
"3.3.2",
null,
"mariadb-java-client",
Relocation.of("mariadb", "org{}mariadb")
),
BOOSTED_YAML(
"dev{}dejvokep",
"boosted-yaml",
"1.3.2",
null,
"boosted-yaml",
Relocation.of("boostedyaml", "dev{}dejvokep{}boostedyaml")
),
MYSQL_DRIVER(
"com{}mysql",
"mysql-connector-j",
"8.3.0",
null,
"mysql-connector-j",
Relocation.of("mysql", "com{}mysql")
),
H2_DRIVER(
"com.h2database",
"h2",
"2.2.224",
null,
"h2database"
),
SQLITE_DRIVER(
"org.xerial",
"sqlite-jdbc",
"3.45.1.0",
null,
"sqlite-jdbc"
),
HIKARI(
"com{}zaxxer",
"HikariCP",
"5.0.1",
null,
"HikariCP",
Relocation.of("hikari", "com{}zaxxer{}hikari")
),
SLF4J_SIMPLE(
"org.slf4j",
"slf4j-simple",
"2.0.12",
null,
"slf4j-simple"
),
SLF4J_API(
"org.slf4j",
"slf4j-api",
"2.0.12",
null,
"slf4j-api"
),
MONGODB_DRIVER_CORE(
"org{}mongodb",
"mongodb-driver-core",
"4.11.1",
null,
"mongodb-driver-core",
Relocation.of("mongodb", "com{}mongodb"),
Relocation.of("bson", "org{}bson")
),
MONGODB_DRIVER_SYNC(
"org{}mongodb",
"mongodb-driver-sync",
"4.11.1",
null,
"mongodb-driver-sync",
Relocation.of("mongodb", "com{}mongodb"),
Relocation.of("bson", "org{}bson")
),
MONGODB_DRIVER_BSON(
"org{}mongodb",
"bson",
"4.11.1",
null,
"mongodb-bson",
Relocation.of("mongodb", "com{}mongodb"),
Relocation.of("bson", "org{}bson")
),
JEDIS(
"redis{}clients",
"jedis",
"5.1.0",
null,
"jedis",
Relocation.of("jedis", "redis{}clients{}jedis"),
Relocation.of("commonspool2", "org{}apache{}commons{}pool2")
),
BSTATS_BASE(
"org{}bstats",
"bstats-base",
"3.0.2",
null,
"bstats-base",
Relocation.of("bstats", "org{}bstats")
),
BSTATS_BUKKIT(
"org{}bstats",
"bstats-bukkit",
"3.0.2",
null,
"bstats-bukkit",
Relocation.of("bstats", "org{}bstats")
),
COMMONS_POOL_2(
"org{}apache{}commons",
"commons-pool2",
"2.11.0",
null,
"commons-pool2",
Relocation.of("commonspool2", "org{}apache{}commons{}pool2")
),
GSON(
"com.google.code.gson",
"gson",
"2.10.1",
null,
"gson"
),;
private final String mavenRepoPath;
private final String version;
private final List<Relocation> relocations;
private final String repo;
private final String artifact;
private static final String MAVEN_FORMAT = "%s/%s/%s/%s-%s.jar";
Dependency(String groupId, String artifactId, String version, String repo, String artifact) {
this(groupId, artifactId, version, repo, artifact, new Relocation[0]);
}
Dependency(String groupId, String artifactId, String version, String repo, String artifact, Relocation... relocations) {
this.mavenRepoPath = String.format(MAVEN_FORMAT,
rewriteEscaping(groupId).replace(".", "/"),
rewriteEscaping(artifactId),
version,
rewriteEscaping(artifactId),
version
);
this.version = version;
this.relocations = ImmutableList.copyOf(relocations);
this.repo = repo;
this.artifact = artifact;
}
private static String rewriteEscaping(String s) {
return s.replace("{}", ".");
}
public String getFileName(String classifier) {
String name = artifact.toLowerCase(Locale.ROOT).replace('_', '-');
String extra = classifier == null || classifier.isEmpty()
? ""
: "-" + classifier;
return name + "-" + this.version + extra + ".jar";
}
String getMavenRepoPath() {
return this.mavenRepoPath;
}
public List<Relocation> getRelocations() {
return this.relocations;
}
/**
* Creates a {@link MessageDigest} suitable for computing the checksums
* of dependencies.
*
* @return the digest
*/
public static MessageDigest createDigest() {
try {
return MessageDigest.getInstance("SHA-256");
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}
@Nullable
public String getRepo() {
return repo;
}
}
@@ -0,0 +1,48 @@
/*
* This file is part of LuckPerms, licensed under the MIT License.
*
* Copyright (c) lucko (Luck) <luck@lucko.me>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.momirealms.customnameplates.paper.libraries.dependencies;
/**
* Exception thrown if a dependency cannot be downloaded.
*/
public class DependencyDownloadException extends Exception {
public DependencyDownloadException() {
}
public DependencyDownloadException(String message) {
super(message);
}
public DependencyDownloadException(String message, Throwable cause) {
super(message, cause);
}
public DependencyDownloadException(Throwable cause) {
super(cause);
}
}
@@ -1,5 +1,5 @@
/*
* This file is part of helper, licensed under the MIT License.
* This file is part of LuckPerms, licensed under the MIT License.
*
* Copyright (c) lucko (Luck) <luck@lucko.me>
* Copyright (c) contributors
@@ -23,51 +23,31 @@
* SOFTWARE.
*/
package net.momirealms.customnameplates.paper.helper;
package net.momirealms.customnameplates.paper.libraries.dependencies;
import org.jetbrains.annotations.NotNull;
import java.lang.annotation.*;
import java.util.Collection;
import java.util.Set;
/**
* Annotation to indicate a required library for a class.
* Loads and manages runtime dependencies for the plugin.
*/
@Documented
@Repeatable(MavenLibraries.class)
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface MavenLibrary {
public interface DependencyManager extends AutoCloseable {
/**
* The group id of the library
* Loads dependencies.
*
* @return the group id of the library
* @param dependencies the dependencies to load
*/
@NotNull
String groupId();
void loadDependencies(Collection<Dependency> dependencies);
/**
* The artifact id of the library
* Obtains an isolated classloader containing the given dependencies.
*
* @return the artifact id of the library
* @param dependencies the dependencies
* @return the classloader
*/
@NotNull
String artifactId();
/**
* The version of the library
*
* @return the version of the library
*/
@NotNull
String version();
/**
* The repo where the library can be obtained from
*
* @return the repo where the library can be obtained from
*/
@NotNull
Repository repo() default @Repository(url = "https://repo1.maven.org/maven2");
ClassLoader obtainClassLoaderWith(Set<Dependency> dependencies);
@Override
void close();
}
@@ -0,0 +1,231 @@
/*
* This file is part of LuckPerms, licensed under the MIT License.
*
* Copyright (c) lucko (Luck) <luck@lucko.me>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.momirealms.customnameplates.paper.libraries.dependencies;
import com.google.common.collect.ImmutableSet;
import net.momirealms.customnameplates.paper.CustomNameplatesPluginImpl;
import net.momirealms.customnameplates.paper.libraries.classpath.ClassPathAppender;
import net.momirealms.customnameplates.paper.libraries.dependencies.classloader.IsolatedClassLoader;
import net.momirealms.customnameplates.paper.libraries.dependencies.relocation.Relocation;
import net.momirealms.customnameplates.paper.libraries.dependencies.relocation.RelocationHandler;
import org.checkerframework.checker.nullness.qual.MonotonicNonNull;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.*;
import java.util.concurrent.CountDownLatch;
/**
* Loads and manages runtime dependencies for the plugin.
*/
public class DependencyManagerImpl implements DependencyManager {
/** A registry containing plugin specific behaviour for dependencies. */
private final DependencyRegistry registry;
/** The path where library jars are cached. */
private final Path cacheDirectory;
/** The classpath appender to preload dependencies into */
private final ClassPathAppender classPathAppender;
/** A map of dependencies which have already been loaded. */
private final EnumMap<Dependency, Path> loaded = new EnumMap<>(Dependency.class);
/** A map of isolated classloaders which have been created. */
private final Map<ImmutableSet<Dependency>, IsolatedClassLoader> loaders = new HashMap<>();
/** Cached relocation handler instance. */
private @MonotonicNonNull RelocationHandler relocationHandler = null;
public DependencyManagerImpl(CustomNameplatesPluginImpl plugin, ClassPathAppender classPathAppender) {
this.registry = new DependencyRegistry();
this.cacheDirectory = setupCacheDirectory(plugin);
this.classPathAppender = classPathAppender;
}
private synchronized RelocationHandler getRelocationHandler() {
if (this.relocationHandler == null) {
this.relocationHandler = new RelocationHandler(this);
}
return this.relocationHandler;
}
@Override
public ClassLoader obtainClassLoaderWith(Set<Dependency> dependencies) {
ImmutableSet<Dependency> set = ImmutableSet.copyOf(dependencies);
for (Dependency dependency : dependencies) {
if (!this.loaded.containsKey(dependency)) {
throw new IllegalStateException("Dependency " + dependency + " is not loaded.");
}
}
synchronized (this.loaders) {
IsolatedClassLoader classLoader = this.loaders.get(set);
if (classLoader != null) {
return classLoader;
}
URL[] urls = set.stream()
.map(this.loaded::get)
.map(file -> {
try {
return file.toUri().toURL();
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
})
.toArray(URL[]::new);
classLoader = new IsolatedClassLoader(urls);
this.loaders.put(set, classLoader);
return classLoader;
}
}
@Override
public void loadDependencies(Collection<Dependency> dependencies) {
CountDownLatch latch = new CountDownLatch(dependencies.size());
for (Dependency dependency : dependencies) {
if (this.loaded.containsKey(dependency)) {
latch.countDown();
continue;
}
try {
loadDependency(dependency);
} catch (Throwable e) {
new RuntimeException("Unable to load dependency " + dependency.name(), e).printStackTrace();
} finally {
latch.countDown();
}
}
try {
latch.await();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
private void loadDependency(Dependency dependency) throws Exception {
if (this.loaded.containsKey(dependency)) {
return;
}
Path file = remapDependency(dependency, downloadDependency(dependency));
this.loaded.put(dependency, file);
if (this.classPathAppender != null && this.registry.shouldAutoLoad(dependency)) {
this.classPathAppender.addJarToClasspath(file);
}
}
private Path downloadDependency(Dependency dependency) throws DependencyDownloadException {
Path file = this.cacheDirectory.resolve(dependency.getFileName(null));
// if the file already exists, don't attempt to re-download it.
if (Files.exists(file)) {
return file;
}
DependencyDownloadException lastError = null;
String forceRepo = dependency.getRepo();
if (forceRepo == null) {
// attempt to download the dependency from each repo in order.
for (DependencyRepository repo : DependencyRepository.values()) {
if (repo.getId().equals("maven") && TimeZone.getDefault().getID().startsWith("Asia")) {
continue;
}
try {
repo.download(dependency, file);
return file;
} catch (DependencyDownloadException e) {
lastError = e;
}
}
} else {
DependencyRepository repository = DependencyRepository.getByID(forceRepo);
if (repository != null) {
try {
repository.download(dependency, file);
return file;
} catch (DependencyDownloadException e) {
lastError = e;
}
}
}
throw Objects.requireNonNull(lastError);
}
private Path remapDependency(Dependency dependency, Path normalFile) throws Exception {
List<Relocation> rules = new ArrayList<>(dependency.getRelocations());
if (rules.isEmpty()) {
return normalFile;
}
Path remappedFile = this.cacheDirectory.resolve(dependency.getFileName(DependencyRegistry.isGsonRelocated() ? "remapped-legacy" : "remapped"));
// if the remapped source exists already, just use that.
if (Files.exists(remappedFile)) {
return remappedFile;
}
getRelocationHandler().remap(normalFile, remappedFile, rules);
return remappedFile;
}
private static Path setupCacheDirectory(CustomNameplatesPluginImpl plugin) {
File folder = new File(plugin.getDataFolder(), "libs");
folder.mkdirs();
return folder.toPath();
}
@Override
public void close() {
IOException firstEx = null;
for (IsolatedClassLoader loader : this.loaders.values()) {
try {
loader.close();
} catch (IOException ex) {
if (firstEx == null) {
firstEx = ex;
} else {
firstEx.addSuppressed(ex);
}
}
}
if (firstEx != null) {
firstEx.printStackTrace();
}
}
}
@@ -0,0 +1,62 @@
/*
* This file is part of LuckPerms, licensed under the MIT License.
*
* Copyright (c) lucko (Luck) <luck@lucko.me>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.momirealms.customnameplates.paper.libraries.dependencies;
import com.google.gson.JsonElement;
/**
* Applies LuckPerms specific behaviour for {@link Dependency}s.
*/
public class DependencyRegistry {
public boolean shouldAutoLoad(Dependency dependency) {
return switch (dependency) {
// all used within 'isolated' classloaders, and are therefore not
// relocated.
case ASM, ASM_COMMONS, JAR_RELOCATOR, H2_DRIVER, SQLITE_DRIVER -> false;
default -> true;
};
}
@SuppressWarnings("ConstantConditions")
public static boolean isGsonRelocated() {
return JsonElement.class.getName().startsWith("net.momirealms");
}
private static boolean classExists(String className) {
try {
Class.forName(className);
return true;
} catch (ClassNotFoundException e) {
return false;
}
}
private static boolean slf4jPresent() {
return classExists("org.slf4j.Logger") && classExists("org.slf4j.LoggerFactory");
}
}
@@ -0,0 +1,141 @@
/*
* This file is part of LuckPerms, licensed under the MIT License.
*
* Copyright (c) lucko (Luck) <luck@lucko.me>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.momirealms.customnameplates.paper.libraries.dependencies;
import com.google.common.io.ByteStreams;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.concurrent.TimeUnit;
/**
* Represents a repository which contains {@link Dependency}s.
*/
public enum DependencyRepository {
MAVEN_CENTRAL("maven", "https://repo1.maven.org/maven2/") {
@Override
protected URLConnection openConnection(Dependency dependency) throws IOException {
URLConnection connection = super.openConnection(dependency);
connection.setConnectTimeout((int) TimeUnit.SECONDS.toMillis(5));
connection.setReadTimeout((int) TimeUnit.SECONDS.toMillis(5));
return connection;
}
},
/**
* Maven Central
*/
MAVEN_CENTRAL_MIRROR("aliyun", "https://maven.aliyun.com/repository/public/"),
/**
* Code MC
*/
CODE_MC("codemc", "https://repo.codemc.io/repository/maven-public/");
private final String url;
private final String id;
DependencyRepository(String id, String url) {
this.url = url;
this.id = id;
}
public static DependencyRepository getByID(String id) {
for (DependencyRepository repository : values()) {
if (id.equals(repository.id)) {
return repository;
}
}
return null;
}
/**
* Opens a connection to the given {@code dependency}.
*
* @param dependency the dependency to download
* @return the connection
* @throws IOException if unable to open a connection
*/
protected URLConnection openConnection(Dependency dependency) throws IOException {
URL dependencyUrl = new URL(this.url + dependency.getMavenRepoPath());
return dependencyUrl.openConnection();
}
/**
* Downloads the raw bytes of the {@code dependency}.
*
* @param dependency the dependency to download
* @return the downloaded bytes
* @throws DependencyDownloadException if unable to download
*/
public byte[] downloadRaw(Dependency dependency) throws DependencyDownloadException {
try {
URLConnection connection = openConnection(dependency);
try (InputStream in = connection.getInputStream()) {
byte[] bytes = ByteStreams.toByteArray(in);
if (bytes.length == 0) {
throw new DependencyDownloadException("Empty stream");
}
return bytes;
}
} catch (Exception e) {
throw new DependencyDownloadException(e);
}
}
/**
* @param dependency the dependency to download
* @return the downloaded bytes
* @throws DependencyDownloadException if unable to download
*/
public byte[] download(Dependency dependency) throws DependencyDownloadException {
return downloadRaw(dependency);
}
/**
* Downloads the the {@code dependency} to the {@code file}, ensuring the
* downloaded bytes match the checksum.
*
* @param dependency the dependency to download
* @param file the file to write to
* @throws DependencyDownloadException if unable to download
*/
public void download(Dependency dependency, Path file) throws DependencyDownloadException {
try {
Files.write(file, download(dependency));
} catch (IOException e) {
throw new DependencyDownloadException(e);
}
}
public String getId() {
return id;
}
}
@@ -0,0 +1,54 @@
/*
* This file is part of LuckPerms, licensed under the MIT License.
*
* Copyright (c) lucko (Luck) <luck@lucko.me>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.momirealms.customnameplates.paper.libraries.dependencies.classloader;
import java.net.URL;
import java.net.URLClassLoader;
/**
* A classloader "isolated" from the rest of the Minecraft server.
*
* <p>Used to load specific LuckPerms dependencies without causing conflicts
* with other plugins, or libraries provided by the server implementation.</p>
*/
public class IsolatedClassLoader extends URLClassLoader {
static {
ClassLoader.registerAsParallelCapable();
}
public IsolatedClassLoader(URL[] urls) {
/*
* ClassLoader#getSystemClassLoader returns the AppClassLoader
*
* Calling #getParent on this returns the ExtClassLoader (Java 8) or
* the PlatformClassLoader (Java 9). Since we want this classloader to
* be isolated from the Minecraft server (the app), we set the parent
* to be the platform class loader.
*/
super(urls, ClassLoader.getSystemClassLoader().getParent());
}
}
@@ -0,0 +1,66 @@
/*
* This file is part of LuckPerms, licensed under the MIT License.
*
* Copyright (c) lucko (Luck) <luck@lucko.me>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.momirealms.customnameplates.paper.libraries.dependencies.relocation;
import java.util.Objects;
public final class Relocation {
private static final String RELOCATION_PREFIX = "net.momirealms.customnameplates.libraries.";
public static Relocation of(String id, String pattern) {
return new Relocation(pattern.replace("{}", "."), RELOCATION_PREFIX + id);
}
private final String pattern;
private final String relocatedPattern;
private Relocation(String pattern, String relocatedPattern) {
this.pattern = pattern;
this.relocatedPattern = relocatedPattern;
}
public String getPattern() {
return this.pattern;
}
public String getRelocatedPattern() {
return this.relocatedPattern;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Relocation that = (Relocation) o;
return Objects.equals(this.pattern, that.pattern) &&
Objects.equals(this.relocatedPattern, that.relocatedPattern);
}
@Override
public int hashCode() {
return Objects.hash(this.pattern, this.relocatedPattern);
}
}
@@ -0,0 +1,91 @@
/*
* This file is part of LuckPerms, licensed under the MIT License.
*
* Copyright (c) lucko (Luck) <luck@lucko.me>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.momirealms.customnameplates.paper.libraries.dependencies.relocation;
import net.momirealms.customnameplates.paper.libraries.dependencies.Dependency;
import net.momirealms.customnameplates.paper.libraries.dependencies.DependencyManager;
import net.momirealms.customnameplates.paper.libraries.dependencies.classloader.IsolatedClassLoader;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.nio.file.Path;
import java.util.*;
/**
* Handles class runtime relocation of packages in downloaded dependencies
*/
public class RelocationHandler {
public static final Set<Dependency> DEPENDENCIES = EnumSet.of(Dependency.ASM, Dependency.ASM_COMMONS, Dependency.JAR_RELOCATOR);
private static final String JAR_RELOCATOR_CLASS = "me.lucko.jarrelocator.JarRelocator";
private static final String JAR_RELOCATOR_RUN_METHOD = "run";
private final Constructor<?> jarRelocatorConstructor;
private final Method jarRelocatorRunMethod;
public RelocationHandler(DependencyManager dependencyManager) {
ClassLoader classLoader = null;
try {
// download the required dependencies for remapping
dependencyManager.loadDependencies(DEPENDENCIES);
// get a classloader containing the required dependencies as sources
classLoader = dependencyManager.obtainClassLoaderWith(DEPENDENCIES);
// load the relocator class
Class<?> jarRelocatorClass = classLoader.loadClass(JAR_RELOCATOR_CLASS);
// prepare the the reflected constructor & method instances
this.jarRelocatorConstructor = jarRelocatorClass.getDeclaredConstructor(File.class, File.class, Map.class);
this.jarRelocatorConstructor.setAccessible(true);
this.jarRelocatorRunMethod = jarRelocatorClass.getDeclaredMethod(JAR_RELOCATOR_RUN_METHOD);
this.jarRelocatorRunMethod.setAccessible(true);
} catch (Exception e) {
try {
if (classLoader instanceof IsolatedClassLoader) {
((IsolatedClassLoader) classLoader).close();
}
} catch (IOException ex) {
e.addSuppressed(ex);
}
throw new RuntimeException(e);
}
}
public void remap(Path input, Path output, List<Relocation> relocations) throws Exception {
Map<String, String> mappings = new HashMap<>();
for (Relocation relocation : relocations) {
mappings.put(relocation.getPattern(), relocation.getRelocatedPattern());
}
// create and invoke a new relocator
Object relocator = this.jarRelocatorConstructor.newInstance(input.toFile(), output.toFile(), mappings);
this.jarRelocatorRunMethod.invoke(relocator);
}
}
@@ -0,0 +1,37 @@
/*
* This file is part of LuckPerms, licensed under the MIT License.
*
* Copyright (c) lucko (Luck) <luck@lucko.me>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.momirealms.customnameplates.paper.libraries.dependencies.relocation;
public final class RelocationHelper {
// screw maven shade
public static final String OKIO_STRING = String.valueOf(new char[]{'o', 'k', 'i', 'o'});
public static final String OKHTTP3_STRING = String.valueOf(new char[]{'o', 'k', 'h', 't', 't', 'p', '3'});
private RelocationHelper() {
}
}
@@ -0,0 +1,155 @@
/*
* This file is part of LuckPerms, licensed under the MIT License.
*
* Copyright (c) lucko (Luck) <luck@lucko.me>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.momirealms.customnameplates.paper.libraries.loader;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Constructor;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
/**
* Classloader that can load a jar from within another jar file.
*
* <p>The "loader" jar contains the loading code & public API classes,
* and is class-loaded by the platform.</p>
*
* <p>The inner "plugin" jar contains the plugin itself, and is class-loaded
* by the loading code & this classloader.</p>
*/
public class JarInJarClassLoader extends URLClassLoader {
static {
ClassLoader.registerAsParallelCapable();
}
/**
* Creates a new jar-in-jar class loader.
*
* @param loaderClassLoader the loader plugin's classloader (setup and created by the platform)
* @param jarResourcePath the path to the jar-in-jar resource within the loader jar
* @throws LoadingException if something unexpectedly bad happens
*/
public JarInJarClassLoader(ClassLoader loaderClassLoader, String jarResourcePath) throws LoadingException {
super(new URL[]{extractJar(loaderClassLoader, jarResourcePath)}, loaderClassLoader);
}
public void addJarToClasspath(URL url) {
addURL(url);
}
public void deleteJarResource() {
URL[] urls = getURLs();
if (urls.length == 0) {
return;
}
try {
Path path = Paths.get(urls[0].toURI());
Files.deleteIfExists(path);
} catch (Exception e) {
// ignore
}
}
/**
* Creates a new plugin instance.
*
* @param bootstrapClass the name of the bootstrap plugin class
* @param loaderPluginType the type of the loader plugin, the only parameter of the bootstrap
* plugin constructor
* @param loaderPlugin the loader plugin instance
* @param <T> the type of the loader plugin
* @return the instantiated bootstrap plugin
*/
public <T> LoaderBootstrap instantiatePlugin(String bootstrapClass, Class<T> loaderPluginType, T loaderPlugin) throws LoadingException {
Class<? extends LoaderBootstrap> plugin;
try {
plugin = loadClass(bootstrapClass).asSubclass(LoaderBootstrap.class);
} catch (ReflectiveOperationException e) {
throw new LoadingException("Unable to load bootstrap class", e);
}
Constructor<? extends LoaderBootstrap> constructor;
try {
constructor = plugin.getConstructor(loaderPluginType);
} catch (ReflectiveOperationException e) {
throw new LoadingException("Unable to get bootstrap constructor", e);
}
try {
return constructor.newInstance(loaderPlugin);
} catch (ReflectiveOperationException e) {
throw new LoadingException("Unable to create bootstrap plugin instance", e);
}
}
/**
* Extracts the "jar-in-jar" from the loader plugin into a temporary file,
* then returns a URL that can be used by the {@link JarInJarClassLoader}.
*
* @param loaderClassLoader the classloader for the "host" loader plugin
* @param jarResourcePath the inner jar resource path
* @return a URL to the extracted file
*/
private static URL extractJar(ClassLoader loaderClassLoader, String jarResourcePath) throws LoadingException {
// get the jar-in-jar resource
URL jarInJar = loaderClassLoader.getResource(jarResourcePath);
if (jarInJar == null) {
throw new LoadingException("Could not locate jar-in-jar");
}
// create a temporary file
// on posix systems by default this is only read/writable by the process owner
Path path;
try {
path = Files.createTempFile("luckperms-jarinjar", ".jar.tmp");
} catch (IOException e) {
throw new LoadingException("Unable to create a temporary file", e);
}
// mark that the file should be deleted on exit
path.toFile().deleteOnExit();
// copy the jar-in-jar to the temporary file path
try (InputStream in = jarInJar.openStream()) {
Files.copy(in, path, StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
throw new LoadingException("Unable to copy jar-in-jar to temporary path", e);
}
try {
return path.toUri().toURL();
} catch (MalformedURLException e) {
throw new LoadingException("Unable to get URL from path", e);
}
}
}
@@ -1,5 +1,5 @@
/*
* This file is part of helper, licensed under the MIT License.
* This file is part of LuckPerms, licensed under the MIT License.
*
* Copyright (c) lucko (Luck) <luck@lucko.me>
* Copyright (c) contributors
@@ -23,23 +23,17 @@
* SOFTWARE.
*/
package net.momirealms.customnameplates.paper.helper;
import java.lang.annotation.*;
package net.momirealms.customnameplates.paper.libraries.loader;
/**
* Represents a maven repository.
* Minimal bootstrap plugin, called by the loader plugin.
*/
@Documented
@Target(ElementType.LOCAL_VARIABLE)
@Retention(RetentionPolicy.RUNTIME)
public @interface Repository {
public interface LoaderBootstrap {
/**
* Gets the base url of the repository.
*
* @return the base url of the repository
*/
String url();
void onLoad();
default void onEnable() {}
default void onDisable() {}
}
@@ -0,0 +1,41 @@
/*
* This file is part of LuckPerms, licensed under the MIT License.
*
* Copyright (c) lucko (Luck) <luck@lucko.me>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.momirealms.customnameplates.paper.libraries.loader;
/**
* Runtime exception used if there is a problem during loading
*/
public class LoadingException extends RuntimeException {
public LoadingException(String message) {
super(message);
}
public LoadingException(String message, Throwable cause) {
super(message, cause);
}
}
@@ -62,7 +62,7 @@ public class ActionBarReceiver {
}
case UPDATE -> {
if (controller.isShown()) {
controller.initialize();
controller.initialize(condition);
AdventureManagerImpl.getInstance().sendActionbar(player, controller.getLatestContent());
} else {
AdventureManagerImpl.getInstance().sendActionbar(player, "");
@@ -98,7 +98,7 @@ public class BossBarReceiver {
if (this.bossBars[j].left().isShown())
this.bossBars[j].right().hide();
controller.initialize();
controller.initialize(condition);
pair.right().setMiniMessageText(pair.left().getLatestContent());
pair.right().show();
@@ -19,11 +19,14 @@ package net.momirealms.customnameplates.paper.mechanic.bubble;
import me.clip.placeholderapi.PlaceholderAPI;
import net.kyori.adventure.text.minimessage.MiniMessage;
import net.momirealms.customnameplates.api.CustomNameplatesPlugin;
import net.momirealms.customnameplates.api.data.OnlineUser;
import net.momirealms.customnameplates.api.event.BubblesSpawnEvent;
import net.momirealms.customnameplates.api.event.NameplateDataLoadEvent;
import net.momirealms.customnameplates.api.manager.BubbleManager;
import net.momirealms.customnameplates.api.mechanic.bubble.Bubble;
import net.momirealms.customnameplates.api.mechanic.bubble.ChannelMode;
import net.momirealms.customnameplates.api.mechanic.bubble.provider.AbstractChatProvider;
import net.momirealms.customnameplates.api.mechanic.character.CharacterArranger;
import net.momirealms.customnameplates.api.mechanic.character.ConfiguredChar;
import net.momirealms.customnameplates.api.mechanic.tag.unlimited.EntityTagPlayer;
@@ -36,10 +39,7 @@ import net.momirealms.customnameplates.paper.adventure.AdventureManagerImpl;
import net.momirealms.customnameplates.paper.mechanic.bubble.image.ImageParser;
import net.momirealms.customnameplates.paper.mechanic.bubble.image.ItemsAdderImageImpl;
import net.momirealms.customnameplates.paper.mechanic.bubble.image.OraxenImageImpl;
import net.momirealms.customnameplates.paper.mechanic.bubble.listener.AbstractChatListener;
import net.momirealms.customnameplates.paper.mechanic.bubble.listener.AsyncChatListener;
import net.momirealms.customnameplates.paper.mechanic.bubble.listener.TrChatListener;
import net.momirealms.customnameplates.paper.mechanic.bubble.listener.VentureChatListener;
import net.momirealms.customnameplates.paper.mechanic.bubble.provider.*;
import net.momirealms.customnameplates.paper.setting.CNConfig;
import org.bukkit.Bukkit;
import org.bukkit.GameMode;
@@ -48,6 +48,7 @@ import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.HandlerList;
import org.bukkit.event.Listener;
import org.bukkit.plugin.PluginManager;
import org.bukkit.potion.PotionEffectType;
import org.jetbrains.annotations.Nullable;
@@ -56,9 +57,10 @@ import java.io.File;
import java.util.*;
import java.util.concurrent.TimeUnit;
public class BubbleManagerImpl implements BubbleManager {
public class BubbleManagerImpl implements BubbleManager, Listener {
private AbstractChatListener chatListener;
private AbstractChatProvider chatProvider;
private AbstractChatProvider customProvider;
private ImageParser imageParser;
private final HashMap<String, Bubble> bubbleMap;
private final CustomNameplatesPluginImpl plugin;
@@ -75,6 +77,7 @@ public class BubbleManagerImpl implements BubbleManager {
private int lengthPerLine;
private int subStringIndex;
private String[] blacklistChannels;
private ChannelMode channelMode;
public BubbleManagerImpl(CustomNameplatesPluginImpl plugin) {
this.plugin = plugin;
@@ -90,14 +93,16 @@ public class BubbleManagerImpl implements BubbleManager {
if (!CNConfig.bubbleModule) return;
this.loadConfig();
this.loadBubbles();
this.registerListener();
this.registerChatProvider();
this.registerImageParser();
Bukkit.getPluginManager().registerEvents(this, plugin);
}
public void unload() {
this.imageParser = null;
this.bubbleMap.clear();
if (chatListener != null) HandlerList.unregisterAll(chatListener);
if (chatProvider != null) chatProvider.unregister();
HandlerList.unregisterAll(this);
}
private void loadConfig() {
@@ -115,6 +120,7 @@ public class BubbleManagerImpl implements BubbleManager {
lengthPerLine = config.getInt("characters-per-line", 30);
startFormat = config.getString("default-format.start", "<gradient:#F5F5F5:#E1FFFF:#F5F5F5><u>");
endFormat = config.getString("default-format.end", "<!u></gradient>");
channelMode = ChannelMode.valueOf(config.getString("channel-mode","all").toUpperCase(Locale.ENGLISH));
}
private void registerImageParser() {
@@ -126,16 +132,47 @@ public class BubbleManagerImpl implements BubbleManager {
}
}
private void registerListener() {
PluginManager pluginManager = Bukkit.getPluginManager();
if (CNConfig.trChatChannel) {
this.chatListener = new TrChatListener(this);
private void registerChatProvider() {
if (this.customProvider != null) {
this.chatProvider = customProvider;
} else if (CNConfig.trChatChannel) {
this.chatProvider = new TrChatProvider(this);
} else if (CNConfig.ventureChatChannel) {
this.chatListener = new VentureChatListener(this);
this.chatProvider = new VentureChatProvider(this);
} else if (CNConfig.huskChatChannel) {
this.chatProvider = new HuskChatProvider(this);
} else if (CNConfig.carbonChatChannel) {
this.chatProvider = new CarbonChatProvider(this);
} else {
this.chatListener = new AsyncChatListener(this);
try {
Class.forName("io.papermc.paper.event.player.AsyncChatEvent");
this.chatProvider = new PaperAsyncChatProvider(this);
} catch (ClassNotFoundException e) {
this.chatProvider = new AsyncChatProvider(this);
}
}
pluginManager.registerEvents(chatListener, plugin);
this.chatProvider.register();
}
@Override
public boolean setCustomChatProvider(AbstractChatProvider provider) {
if (this.customProvider != null)
return false;
this.customProvider = provider;
if (chatProvider != null) chatProvider.unregister();
this.registerChatProvider();
return true;
}
@Override
public boolean removeCustomChatProvider() {
if (this.customProvider != null) {
this.customProvider.unregister();
this.customProvider = null;
this.registerChatProvider();
return true;
}
return false;
}
private void loadBubbles() {
@@ -208,12 +245,24 @@ public class BubbleManagerImpl implements BubbleManager {
return this.bubbleMap.remove(key) != null;
}
@Override
public void onChat(Player player, String text) {
onChat(player, text, null);
}
@Override
public void onChat(Player player, String text, String channel) {
if ( player.getGameMode() == GameMode.SPECTATOR
|| player.hasPotionEffect(PotionEffectType.INVISIBILITY)
|| !player.hasPermission("bubbles.use")
) return;
if (Bukkit.isPrimaryThread()) {
String finalText = text;
CustomNameplatesPlugin.get().getScheduler().runTaskAsync(() -> onChat(player, finalText));
return;
}
var optionalUser = plugin.getStorageManager().getOnlineUser(player.getUniqueId());
if (optionalUser.isEmpty()) {
return;
@@ -258,14 +307,14 @@ public class BubbleManagerImpl implements BubbleManager {
int finalIndex = i;
String finalBubble = bubble;
plugin.getScheduler().runTaskAsyncLater(
() -> sendBubble(player, split[finalIndex], bubbleConfig, finalBubble),
() -> sendBubble(player, split[finalIndex], bubbleConfig, finalBubble, channel),
(long) i * 250 + 100,
TimeUnit.MILLISECONDS
);
}
}
private void sendBubble(Player player, String text, Bubble bubbleConfig, String key) {
private void sendBubble(Player player, String text, Bubble bubbleConfig, String key, @Nullable String channel) {
if (key.equals("none")) {
text = startFormat + PlaceholderAPI.setPlaceholders(player, prefix) + text + PlaceholderAPI.setPlaceholders(player, suffix) + endFormat;
} else {
@@ -279,7 +328,20 @@ public class BubbleManagerImpl implements BubbleManager {
StaticTextEntity entity = tagPlayer.addTag(StaticTextTagSetting.builder()
.leaveRule((p, e) -> true)
.comeRule((p, e) -> true)
.comeRule((p, e) -> {
switch (channelMode) {
case ALL -> {
return true;
}
case JOINED -> {
return channel == null || chatProvider.hasJoinedChannel(p, channel);
}
case CAN_JOIN -> {
return channel == null || chatProvider.canJoinChannel(p, channel);
}
}
return false;
})
.verticalOffset(yOffset)
.defaultText(text)
.plugin("bubble")
@@ -1,46 +0,0 @@
/*
* Copyright (C) <2022> <XiaoMoMi>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package net.momirealms.customnameplates.paper.mechanic.bubble.listener;
import mineverse.Aust1n46.chat.api.MineverseChatPlayer;
import mineverse.Aust1n46.chat.api.events.VentureChatEvent;
import net.momirealms.customnameplates.api.CustomNameplatesPlugin;
import net.momirealms.customnameplates.paper.mechanic.bubble.BubbleManagerImpl;
import org.bukkit.event.EventHandler;
public class VentureChatListener extends AbstractChatListener {
public VentureChatListener(BubbleManagerImpl chatBubblesManager) {
super(chatBubblesManager);
}
@EventHandler
public void onVentureChat(VentureChatEvent event) {
String channelName = event.getChannel().getName();
for (String channel : chatBubblesManager.getBlacklistChannels()) {
if (channelName.equals(channel)) return;
}
final MineverseChatPlayer chatPlayer = event.getMineverseChatPlayer();
if (chatPlayer == null) {
return;
}
CustomNameplatesPlugin.get().getScheduler().runTaskAsync(() -> {
chatBubblesManager.onChat(chatPlayer.getPlayer(), event.getChat());
});
}
}
@@ -15,22 +15,46 @@
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package net.momirealms.customnameplates.paper.mechanic.bubble.listener;
package net.momirealms.customnameplates.paper.mechanic.bubble.provider;
import net.momirealms.customnameplates.api.CustomNameplatesPlugin;
import net.momirealms.customnameplates.paper.mechanic.bubble.BubbleManagerImpl;
import net.momirealms.customnameplates.api.manager.BubbleManager;
import net.momirealms.customnameplates.api.mechanic.bubble.provider.AbstractChatProvider;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.HandlerList;
import org.bukkit.event.player.AsyncPlayerChatEvent;
public class AsyncChatListener extends AbstractChatListener {
public class AsyncChatProvider extends AbstractChatProvider {
public AsyncChatListener(BubbleManagerImpl chatBubblesManager) {
public AsyncChatProvider(BubbleManager chatBubblesManager) {
super(chatBubblesManager);
}
@EventHandler
@Override
public void register() {
Bukkit.getPluginManager().registerEvents(this, CustomNameplatesPlugin.get());
}
@Override
public void unregister() {
HandlerList.unregisterAll(this);
}
@Override
public boolean hasJoinedChannel(Player player, String channelID) {
return true;
}
@Override
public boolean canJoinChannel(Player player, String channelID) {
return true;
}
// This event is not async sometimes
@EventHandler (ignoreCancelled = true)
public void onChat(AsyncPlayerChatEvent event) {
if (event.isCancelled()) return;
CustomNameplatesPlugin.get().getScheduler().runTaskAsync(() -> chatBubblesManager.onChat(event.getPlayer(), event.getMessage()));
}
}
@@ -0,0 +1,147 @@
/*
* Copyright (C) <2022> <XiaoMoMi>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package net.momirealms.customnameplates.paper.mechanic.bubble.provider;
import net.draycia.carbon.api.CarbonChat;
import net.draycia.carbon.api.channels.ChannelRegistry;
import net.draycia.carbon.api.channels.ChatChannel;
import net.draycia.carbon.api.event.CarbonEventSubscription;
import net.draycia.carbon.api.event.events.CarbonChatEvent;
import net.draycia.carbon.api.users.CarbonPlayer;
import net.momirealms.customnameplates.api.CustomNameplatesPlugin;
import net.momirealms.customnameplates.api.manager.BubbleManager;
import net.momirealms.customnameplates.api.mechanic.bubble.provider.AbstractChatProvider;
import net.momirealms.customnameplates.api.util.LogUtils;
import net.momirealms.customnameplates.paper.util.ReflectionUtils;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class CarbonChatProvider extends AbstractChatProvider {
private final CarbonChat api;
private CarbonEventSubscription<CarbonChatEvent> subscription;
private Method originalMessageMethod;
private Method channelKeyMethod;
private Method getChannelByKeyMethod;
public CarbonChatProvider(BubbleManager chatBubblesManager) {
super(chatBubblesManager);
this.api = net.draycia.carbon.api.CarbonChatProvider.carbonChat();
try {
this.originalMessageMethod = CarbonChatEvent.class.getMethod("originalMessage");
this.channelKeyMethod = ChatChannel.class.getMethod("key");
this.getChannelByKeyMethod = ChannelRegistry.class.getMethod("channel", ReflectionUtils.getKeyClass());
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void register() {
subscription = api.eventHandler().subscribe(CarbonChatEvent.class, event -> {
if (event.cancelled())
return;
ChatChannel chatChannel = event.chatChannel();
Object key = getChannelKey(chatChannel);
if (key == null) return;
String channel = ReflectionUtils.getKeyAsString(key);
for (String black : chatBubblesManager.getBlacklistChannels()) {
if (channel.equals(black)) return;
}
Player player = Bukkit.getPlayer(event.sender().uuid());
if (player == null || !player.isOnline())
return;
Object component = getComponentFromEvent(event);
String message = ReflectionUtils.getMiniMessageTextFromNonShadedComponent(component);
CustomNameplatesPlugin.get().getScheduler().runTaskAsync(() -> chatBubblesManager.onChat(player, message, channel));
});
}
@Override
public void unregister() {
if (subscription != null) {
subscription.dispose();
}
}
@Override
public boolean hasJoinedChannel(Player player, String channelID) {
CarbonPlayer cPlayer = null;
for (CarbonPlayer carbonPlayer : api.server().players()) {
if (carbonPlayer.uuid().equals(player.getUniqueId())) {
cPlayer = carbonPlayer;
break;
}
}
if (cPlayer == null) {
return false;
}
ChatChannel selectedChannel = cPlayer.selectedChannel();
if (selectedChannel == null) {
return false;
}
Object key = getChannelKey(selectedChannel);
String str = ReflectionUtils.getKeyAsString(key);
return str.equals(channelID);
}
@Override
public boolean canJoinChannel(Player player, String channelID) {
ChannelRegistry registry = api.channelRegistry();
Object key = ReflectionUtils.getKerFromString(channelID);
if (key == null) {
return false;
}
ChatChannel channel = null;
try {
channel = (ChatChannel) getChannelByKeyMethod.invoke(registry, key);
} catch (IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
if (channel == null) {
LogUtils.warn("Channel " + channelID + " doesn't exist.");
return false;
}
String perm = channel.permission();
if (perm == null) {
return true;
}
return player.hasPermission(perm);
}
private Object getChannelKey(ChatChannel channel) {
try {
return this.channelKeyMethod.invoke(channel);
} catch (InvocationTargetException | IllegalAccessException e) {
e.printStackTrace();
}
return null;
}
private Object getComponentFromEvent(CarbonChatEvent event) {
try {
return this.originalMessageMethod.invoke(event);
} catch (InvocationTargetException | IllegalAccessException e) {
e.printStackTrace();
}
return ReflectionUtils.getEmptyComponent();
}
}
@@ -0,0 +1,85 @@
/*
* Copyright (C) <2022> <XiaoMoMi>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package net.momirealms.customnameplates.paper.mechanic.bubble.provider;
import net.momirealms.customnameplates.api.CustomNameplatesPlugin;
import net.momirealms.customnameplates.api.manager.BubbleManager;
import net.momirealms.customnameplates.api.mechanic.bubble.provider.AbstractChatProvider;
import net.momirealms.customnameplates.api.util.LogUtils;
import net.william278.huskchat.bukkit.BukkitHuskChat;
import net.william278.huskchat.bukkit.event.ChatMessageEvent;
import net.william278.huskchat.channel.Channel;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.HandlerList;
public class HuskChatProvider extends AbstractChatProvider {
public HuskChatProvider(BubbleManager chatBubblesManager) {
super(chatBubblesManager);
}
@Override
public void register() {
Bukkit.getPluginManager().registerEvents(this, CustomNameplatesPlugin.get());
}
@Override
public void unregister() {
HandlerList.unregisterAll(this);
}
@Override
public boolean hasJoinedChannel(Player player, String channelID) {
String channel = BukkitHuskChat.getInstance().getPlayerCache().getPlayerChannel(player.getUniqueId());
if (channel == null) {
LogUtils.warn("Channel " + channelID + " doesn't exist.");
return false;
}
return channel.equals(channelID);
}
@Override
public boolean canJoinChannel(Player player, String channelID) {
Channel channel = BukkitHuskChat.getInstance().getSettings().getChannels().get(channelID);
if (channel == null) {
LogUtils.warn("Channel " + channelID + " doesn't exist.");
return false;
}
String receivePerm = channel.getReceivePermission();
if (receivePerm == null) {
return true;
}
return player.hasPermission(receivePerm);
}
@EventHandler (ignoreCancelled = true)
public void onHuskChat(ChatMessageEvent event) {
String channel = event.getChannelId();
for (String black : chatBubblesManager.getBlacklistChannels()) {
if (channel.equals(black)) return;
}
Player player = Bukkit.getPlayer(event.getSender().getUuid());
if (player == null || !player.isOnline())
return;
CustomNameplatesPlugin.get().getScheduler().runTaskAsync(() -> {
chatBubblesManager.onChat(player, event.getMessage(), channel);
});
}
}
@@ -0,0 +1,81 @@
/*
* Copyright (C) <2022> <XiaoMoMi>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package net.momirealms.customnameplates.paper.mechanic.bubble.provider;
import io.papermc.paper.event.player.AsyncChatEvent;
import net.momirealms.customnameplates.api.CustomNameplatesPlugin;
import net.momirealms.customnameplates.api.manager.BubbleManager;
import net.momirealms.customnameplates.api.mechanic.bubble.provider.AbstractChatProvider;
import net.momirealms.customnameplates.paper.util.ReflectionUtils;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.HandlerList;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class PaperAsyncChatProvider extends AbstractChatProvider {
private Method messageMethod;
public PaperAsyncChatProvider(BubbleManager chatBubblesManager) {
super(chatBubblesManager);
try {
this.messageMethod = AsyncChatEvent.class.getMethod("message");
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void register() {
Bukkit.getPluginManager().registerEvents(this, CustomNameplatesPlugin.get());
}
@Override
public void unregister() {
HandlerList.unregisterAll(this);
}
@Override
public boolean hasJoinedChannel(Player player, String channelID) {
return true;
}
@Override
public boolean canJoinChannel(Player player, String channelID) {
return true;
}
@EventHandler (ignoreCancelled = true)
public void onChat(AsyncChatEvent event) {
Object component = getComponentFromEvent(event);
String message = ReflectionUtils.getMiniMessageTextFromNonShadedComponent(component);
CustomNameplatesPlugin.get().getScheduler().runTaskAsync(() -> chatBubblesManager.onChat(event.getPlayer(), message));
}
private Object getComponentFromEvent(AsyncChatEvent event) {
try {
return this.messageMethod.invoke(event);
} catch (InvocationTargetException | IllegalAccessException e) {
e.printStackTrace();
}
return ReflectionUtils.getEmptyComponent();
}
}
@@ -15,7 +15,7 @@
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package net.momirealms.customnameplates.paper.mechanic.bubble.listener;
package net.momirealms.customnameplates.paper.mechanic.bubble.provider;
import me.arasple.mc.trchat.TrChat;
import me.arasple.mc.trchat.api.event.TrChatEvent;
@@ -23,20 +23,54 @@ import me.arasple.mc.trchat.module.display.channel.Channel;
import me.arasple.mc.trchat.module.internal.filter.FilteredObject;
import me.arasple.mc.trchat.taboolib.platform.BukkitAdapter;
import net.momirealms.customnameplates.api.CustomNameplatesPlugin;
import net.momirealms.customnameplates.paper.mechanic.bubble.BubbleManagerImpl;
import net.momirealms.customnameplates.api.manager.BubbleManager;
import net.momirealms.customnameplates.api.mechanic.bubble.provider.AbstractChatProvider;
import net.momirealms.customnameplates.api.util.LogUtils;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.HandlerList;
import java.util.Arrays;
public class TrChatListener extends AbstractChatListener {
public class TrChatProvider extends AbstractChatProvider {
private final BukkitAdapter adapter;
public TrChatListener(BubbleManagerImpl chatBubblesManager) {
public TrChatProvider(BubbleManager chatBubblesManager) {
super(chatBubblesManager);
this.adapter = new BukkitAdapter();
}
@Override
public void register() {
Bukkit.getPluginManager().registerEvents(this, CustomNameplatesPlugin.get());
}
@Override
public void unregister() {
HandlerList.unregisterAll(this);
}
@Override
public boolean hasJoinedChannel(Player player, String channelID) {
if (TrChat.INSTANCE.api().getChannelManager().getChannel(channelID) instanceof Channel channel) {
return channel.getListeners().contains(player.getName());
} else {
LogUtils.warn("Channel " + channelID + " doesn't exist.");
return false;
}
}
@Override
public boolean canJoinChannel(Player player, String channelID) {
if (TrChat.INSTANCE.api().getChannelManager().getChannel(channelID) instanceof Channel channel) {
String perm = channel.getSettings().getJoinPermission();
return player.hasPermission(perm);
} else {
LogUtils.warn("Channel " + channelID + " doesn't exist.");
return false;
}
}
@EventHandler (ignoreCancelled = true)
public void onTrChat(TrChatEvent event) {
if (!event.getForward()) return;
@@ -47,7 +81,7 @@ public class TrChatListener extends AbstractChatListener {
}
FilteredObject object = TrChat.INSTANCE.api().getFilterManager().filter(event.getMessage(), adapter.adaptPlayer(event.getPlayer()), true);
CustomNameplatesPlugin.get().getScheduler().runTaskAsync(() -> {
chatBubblesManager.onChat(event.getSession().getPlayer(), object.getFiltered());
chatBubblesManager.onChat(event.getSession().getPlayer(), object.getFiltered(), channelName);
});
}
}
@@ -0,0 +1,82 @@
/*
* Copyright (C) <2022> <XiaoMoMi>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package net.momirealms.customnameplates.paper.mechanic.bubble.provider;
import mineverse.Aust1n46.chat.api.MineverseChatAPI;
import mineverse.Aust1n46.chat.api.MineverseChatPlayer;
import mineverse.Aust1n46.chat.api.events.VentureChatEvent;
import mineverse.Aust1n46.chat.channel.ChatChannel;
import net.momirealms.customnameplates.api.CustomNameplatesPlugin;
import net.momirealms.customnameplates.api.manager.BubbleManager;
import net.momirealms.customnameplates.api.mechanic.bubble.provider.AbstractChatProvider;
import net.momirealms.customnameplates.api.util.LogUtils;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.HandlerList;
public class VentureChatProvider extends AbstractChatProvider {
public VentureChatProvider(BubbleManager chatBubblesManager) {
super(chatBubblesManager);
}
@Override
public void register() {
Bukkit.getPluginManager().registerEvents(this, CustomNameplatesPlugin.get());
}
@Override
public void unregister() {
HandlerList.unregisterAll(this);
}
@Override
public boolean hasJoinedChannel(Player player, String channelID) {
MineverseChatPlayer mcp = MineverseChatAPI.getOnlineMineverseChatPlayer(player);
return mcp.getCurrentChannel().getName().equals(channelID);
}
@Override
public boolean canJoinChannel(Player player, String channelID) {
ChatChannel channel = ChatChannel.getChannel(channelID);
if (channel == null) {
LogUtils.warn("Channel " + channelID + " doesn't exist.");
return false;
}
if (channel.hasPermission()) {
return player.hasPermission(channel.getPermission());
}
return true;
}
@EventHandler (ignoreCancelled = true)
public void onVentureChat(VentureChatEvent event) {
String channelName = event.getChannel().getName();
for (String channel : chatBubblesManager.getBlacklistChannels()) {
if (channelName.equals(channel)) return;
}
final MineverseChatPlayer chatPlayer = event.getMineverseChatPlayer();
if (chatPlayer == null) {
return;
}
CustomNameplatesPlugin.get().getScheduler().runTaskAsync(() -> {
chatBubblesManager.onChat(chatPlayer.getPlayer(), event.getChat(), channelName);
});
}
}
@@ -21,6 +21,7 @@ import me.clip.placeholderapi.PlaceholderAPI;
import net.momirealms.customnameplates.api.manager.RequirementManager;
import net.momirealms.customnameplates.api.requirement.Condition;
import net.momirealms.customnameplates.api.requirement.Requirement;
import net.momirealms.customnameplates.api.util.LogUtils;
import org.bukkit.entity.Player;
public class DisplayController {
@@ -35,6 +36,7 @@ public class DisplayController {
private int timeLeft;
private int index;
private final TimeLimitText[] texts;
private boolean metAnyCondition;
public DisplayController(
Player player,
@@ -44,10 +46,10 @@ public class DisplayController {
) {
this.owner = player;
this.checkFrequency = checkFrequency;
this.checkTimer = 0;
this.refreshTimer = 0;
this.requirements = requirements;
this.texts = texts;
this.checkTimer = checkFrequency - 1;
}
public NextStage stateCheck(Condition condition) {
@@ -78,21 +80,33 @@ public class DisplayController {
}
public boolean updateText(Condition condition) {
timeLeft--;
if (timeLeft > 0)
timeLeft--;
// Definitely goto "if" on init
if (timeLeft == 0) {
int triedTimes = 0;
do {
index++;
if (index >= texts.length) {
index = 0;
}
if (triedTimes == texts.length) {
timeLeft = Math.max(checkFrequency, 1);
metAnyCondition = false;
LogUtils.warn("No text is available for player " + owner.getName() + ". Please check your conditions.");
return updateText("");
}
triedTimes++;
} while (!RequirementManager.isRequirementMet(condition, texts[index].getRequirements()));
metAnyCondition = true;
timeLeft = texts[index].getDuration();
refreshTimer = 0;
return updateText(texts[index].getText());
}
if (texts[index].getRefreshFrequency() <= 0) {
if (!metAnyCondition || texts[index].getRefreshFrequency() <= 0) {
return false;
}
@@ -114,12 +128,13 @@ public class DisplayController {
return true;
}
public void initialize() {
index = 0;
public void initialize(Condition condition) {
index = texts.length - 1;
checkTimer = 0;
refreshTimer = 0;
timeLeft = texts[0].getDuration();
latestValue = PlaceholderAPI.setPlaceholders(owner, texts[0].getText());
timeLeft = 1;
// The text would definitely be refreshed
updateText(condition);
}
public String getLatestContent() {
@@ -238,7 +238,7 @@ public class VersionManagerImpl implements VersionManager, Listener {
final Player player = event.getPlayer();
if (player.isOp()) {
if (!PlaceholderAPI.isRegistered("player")) {
AdventureManagerImpl.getInstance().sendMessageWithPrefix(player, "You haven't installed Player Expansion yet. Click <b><gold><click:run_command:/papi ecloud download Player>HERE</click></gold><b> to download.");
AdventureManagerImpl.getInstance().sendMessageWithPrefix(player, "You haven't installed Player Expansion yet. Click <b><gold><u><click:run_command:/papi ecloud download Player>HERE</click></u></gold></b> to download. Otherwise you might encounter console spam on first installation.");
}
}
}
@@ -55,7 +55,6 @@ import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.event.player.PlayerToggleSneakEvent;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.File;
import java.util.*;
@@ -43,6 +43,7 @@ public class MagicCosmeticsListener implements Listener {
if (cosmetic instanceof Hat hat) {
if (unlimitedTagManager.getUnlimitedObject(player.getUniqueId()) instanceof UnlimitedPlayer unlimitedPlayer) {
unlimitedPlayer.setHatOffset(hat.isHideCosmetic() ? 0 : hat.getOffSetY());
unlimitedPlayer.teleport();
}
}
}
@@ -59,6 +60,7 @@ public class MagicCosmeticsListener implements Listener {
final Cosmetic cosmetic = playerData.getHat();
if (cosmetic instanceof Hat hat) {
unlimitedPlayer.setHatOffset(hat.isHideCosmetic() ? 0 : hat.getOffSetY());
unlimitedPlayer.teleport();
}
}
}
@@ -72,6 +74,7 @@ public class MagicCosmeticsListener implements Listener {
if (cosmetic instanceof Hat hat) {
if (unlimitedTagManager.getUnlimitedObject(player.getUniqueId()) instanceof UnlimitedPlayer unlimitedPlayer) {
unlimitedPlayer.setHatOffset(hat.isHideCosmetic() ? 0 : hat.getOffSetY());
unlimitedPlayer.teleport();
}
}
}
@@ -82,6 +85,7 @@ public class MagicCosmeticsListener implements Listener {
if (event.getCosmeticType() == CosmeticType.HAT) {
if (unlimitedTagManager.getUnlimitedObject(player.getUniqueId()) instanceof UnlimitedPlayer unlimitedPlayer) {
unlimitedPlayer.setHatOffset(0);
unlimitedPlayer.teleport();
}
}
}
@@ -92,6 +96,7 @@ public class MagicCosmeticsListener implements Listener {
if (cosmetic instanceof Hat hat) {
if (unlimitedTagManager.getUnlimitedObject(event.getPlayerData().getUniqueId()) instanceof UnlimitedPlayer unlimitedPlayer) {
unlimitedPlayer.setHatOffset(hat.isHideCosmetic() ? 0 : hat.getOffSetY());
unlimitedPlayer.teleport();
}
}
}
@@ -26,6 +26,8 @@ import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.entity.Pose;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Vector;
public class UnlimitedEntity implements EntityTagEntity {
@@ -33,21 +35,25 @@ public class UnlimitedEntity implements EntityTagEntity {
protected final UnlimitedTagManagerImpl manager;
protected final Entity entity;
protected final Vector<Player> nearbyPlayers;
protected Player[] nearbyPlayerArray;
protected final Vector<StaticTextEntity> staticTags;
protected StaticTextEntity[] staticTagArray;
public UnlimitedEntity(UnlimitedTagManagerImpl manager, Entity entity) {
this.manager = manager;
this.entity = entity;
this.nearbyPlayers = new Vector<>();
this.staticTags = new Vector<>();
staticTagVectorToArray();
playerVectorToArray();
}
public Entity getEntity() {
return entity;
}
public Vector<Player> getNearbyPlayers() {
return nearbyPlayers;
public Player[] getNearbyPlayers() {
return nearbyPlayerArray;
}
public void addNearbyPlayerNaturally(Player player) {
@@ -55,7 +61,8 @@ public class UnlimitedEntity implements EntityTagEntity {
return;
}
nearbyPlayers.add(player);
for (StaticTextEntity tag : staticTags) {
playerVectorToArray();
for (StaticTextEntity tag : staticTagArray) {
if (tag.getComeRule().isPassed(player, entity)) {
tag.addPlayerToViewers(player);
}
@@ -67,7 +74,8 @@ public class UnlimitedEntity implements EntityTagEntity {
return;
}
nearbyPlayers.remove(player);
for (StaticTextEntity tag : staticTags) {
playerVectorToArray();
for (StaticTextEntity tag : staticTagArray) {
if (tag.getLeaveRule().isPassed(player, entity)) {
tag.removePlayerFromViewers(player);
}
@@ -91,8 +99,11 @@ public class UnlimitedEntity implements EntityTagEntity {
return;
}
staticTags.add(tag);
staticTagVectorToArray();
for (Player all : nearbyPlayers) {
tag.addPlayerToViewers(all);
if (tag.getComeRule().isPassed(all, entity)) {
tag.addPlayerToViewers(all);
}
}
}
@@ -107,12 +118,13 @@ public class UnlimitedEntity implements EntityTagEntity {
public void removeTag(StaticTextEntity tag) {
if (staticTags.remove(tag)) {
tag.destroy();
staticTagVectorToArray();
}
}
@Override
public Vector<StaticTextEntity> getStaticTags() {
return staticTags;
public Collection<StaticTextEntity> getStaticTags() {
return new ArrayList<>(staticTags);
}
@Override
@@ -121,7 +133,8 @@ public class UnlimitedEntity implements EntityTagEntity {
return;
}
nearbyPlayers.add(player);
for (StaticTextEntity tag : staticTags) {
playerVectorToArray();
for (StaticTextEntity tag : staticTagArray) {
tag.addPlayerToViewers(player);
}
}
@@ -132,32 +145,32 @@ public class UnlimitedEntity implements EntityTagEntity {
return;
}
nearbyPlayers.remove(player);
for (StaticTextEntity tag : staticTags) {
playerVectorToArray();
for (StaticTextEntity tag : staticTagArray) {
tag.removePlayerFromViewers(player);
}
}
public void move(Player receiver, short x, short y, short z, boolean onGround) {
for (StaticTextEntity tag : staticTags) {
for (StaticTextEntity tag : staticTagArray) {
tag.move(receiver, x, y, z, onGround);
}
}
public void teleport(Player receiver, double x, double y, double z, boolean onGround) {
for (StaticTextEntity tag : staticTags) {
for (StaticTextEntity tag : staticTagArray) {
tag.teleport(receiver, x, y, z, onGround);
}
}
public void teleport() {
for (StaticTextEntity tag : staticTags) {
for (StaticTextEntity tag : staticTagArray) {
tag.teleport();
}
}
public void handlePose(Pose previous, Pose pose) {
for (StaticTextEntity tag : staticTags) {
for (StaticTextEntity tag : staticTagArray) {
tag.handlePose(previous, pose);
}
}
@@ -165,16 +178,26 @@ public class UnlimitedEntity implements EntityTagEntity {
@Override
public void destroy() {
manager.removeUnlimitedEntityFromMap(entity.getUniqueId());
for (StaticTextEntity tag : staticTags) {
for (StaticTextEntity tag : staticTagArray) {
tag.destroy();
}
nearbyPlayers.clear();
staticTags.clear();
staticTagArray = null;
nearbyPlayerArray = null;
}
public void respawn() {
for (StaticTextEntity tag : staticTags) {
for (StaticTextEntity tag : staticTagArray) {
tag.respawn(entity.getPose());
}
}
protected void staticTagVectorToArray() {
staticTagArray = staticTags.toArray(new StaticTextEntity[0]);
}
protected void playerVectorToArray() {
nearbyPlayerArray = nearbyPlayers.toArray(new Player[0]);
}
}
@@ -26,12 +26,15 @@ import net.momirealms.customnameplates.paper.setting.CNConfig;
import org.bukkit.entity.Player;
import org.bukkit.entity.Pose;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Vector;
public class UnlimitedPlayer extends UnlimitedEntity implements EntityTagPlayer {
private final Player owner;
private final Vector<DynamicTextEntity> dynamicTags;
private DynamicTextEntity[] dynamicTagArray;
private double hatOffset;
private boolean isPreviewing;
@@ -39,6 +42,7 @@ public class UnlimitedPlayer extends UnlimitedEntity implements EntityTagPlayer
super(manager, player);
this.owner = player;
this.dynamicTags = new Vector<>();
this.dynamicTagVectorToArray();
}
@Override
@@ -47,7 +51,8 @@ public class UnlimitedPlayer extends UnlimitedEntity implements EntityTagPlayer
return;
}
dynamicTags.add(tag);
for (Player all : nearbyPlayers) {
dynamicTagVectorToArray();
for (Player all : getNearbyPlayers()) {
if (tag.canShow() && tag.canSee(all)) {
tag.addPlayerToViewers(all);
}
@@ -60,8 +65,11 @@ public class UnlimitedPlayer extends UnlimitedEntity implements EntityTagPlayer
return;
}
staticTags.add(tag);
for (Player all : nearbyPlayers) {
tag.addPlayerToViewers(all);
dynamicTagVectorToArray();
for (Player all : getNearbyPlayers()) {
if (tag.getComeRule().isPassed(all, owner)) {
tag.addPlayerToViewers(all);
}
}
}
@@ -83,19 +91,13 @@ public class UnlimitedPlayer extends UnlimitedEntity implements EntityTagPlayer
public void removeTag(DynamicTextEntity tag) {
if (dynamicTags.remove(tag)) {
tag.destroy();
dynamicTagVectorToArray();
}
}
@Override
public void removeTag(StaticTextEntity tag) {
if (staticTags.remove(tag)) {
tag.destroy();
}
}
@Override
public Vector<DynamicTextEntity> getDynamicTags() {
return dynamicTags;
public Collection<DynamicTextEntity> getDynamicTags() {
return new ArrayList<>(dynamicTags);
}
@Override
@@ -128,7 +130,7 @@ public class UnlimitedPlayer extends UnlimitedEntity implements EntityTagPlayer
@Override
public void updateText() {
for (DynamicTextEntity tag : dynamicTags) {
for (DynamicTextEntity tag : dynamicTagArray) {
tag.updateText();
}
}
@@ -144,13 +146,14 @@ public class UnlimitedPlayer extends UnlimitedEntity implements EntityTagPlayer
return;
}
nearbyPlayers.add(player);
playerVectorToArray();
setNameInvisibleFor(player);
for (StaticTextEntity tag : staticTags) {
for (StaticTextEntity tag : staticTagArray) {
if (tag.getComeRule().isPassed(player, entity)) {
tag.addPlayerToViewers(player);
}
}
for (DynamicTextEntity tag : dynamicTags) {
for (DynamicTextEntity tag : dynamicTagArray) {
if (tag.canShow() && tag.canSee(player)) {
tag.addPlayerToViewers(player);
}
@@ -162,14 +165,15 @@ public class UnlimitedPlayer extends UnlimitedEntity implements EntityTagPlayer
if (!nearbyPlayers.contains(player)) {
return;
}
super.nearbyPlayers.remove(player);
nearbyPlayers.remove(player);
playerVectorToArray();
setNameVisibleFor(player);
for (StaticTextEntity tag : staticTags) {
for (StaticTextEntity tag : staticTagArray) {
if (tag.getLeaveRule().isPassed(player, entity)) {
tag.removePlayerFromViewers(player);
}
}
for (DynamicTextEntity tag : dynamicTags) {
for (DynamicTextEntity tag : dynamicTagArray) {
tag.removePlayerFromViewers(player);
}
}
@@ -177,22 +181,23 @@ public class UnlimitedPlayer extends UnlimitedEntity implements EntityTagPlayer
@Override
public void destroy() {
manager.removeUnlimitedEntityFromMap(entity.getUniqueId());
for (Player viewer : nearbyPlayers) {
for (Player viewer : getNearbyPlayers()) {
setNameVisibleFor(viewer);
}
for (DynamicTextEntity tag : dynamicTags) {
for (DynamicTextEntity tag : dynamicTagArray) {
tag.destroy();
}
for (StaticTextEntity tag : staticTags) {
for (StaticTextEntity tag : staticTagArray) {
tag.destroy();
}
nearbyPlayers.clear();
dynamicTags.clear();
staticTags.clear();
staticTagArray = null;
}
public void sneak(boolean sneaking, boolean flying) {
for (DynamicTextEntity tag : dynamicTags) {
for (DynamicTextEntity tag : dynamicTagArray) {
tag.setSneak(sneaking, !flying);
}
}
@@ -200,7 +205,7 @@ public class UnlimitedPlayer extends UnlimitedEntity implements EntityTagPlayer
@Override
public void respawn() {
super.respawn();
for (DynamicTextEntity tag : dynamicTags) {
for (DynamicTextEntity tag : dynamicTagArray) {
tag.respawn(owner.getPose());
}
}
@@ -208,7 +213,7 @@ public class UnlimitedPlayer extends UnlimitedEntity implements EntityTagPlayer
@Override
public void move(Player receiver, short x, short y, short z, boolean onGround) {
super.move(receiver, x, y, z, onGround);
for (DynamicTextEntity tag : dynamicTags) {
for (DynamicTextEntity tag : dynamicTagArray) {
tag.move(receiver, x, y, z, onGround);
}
}
@@ -216,7 +221,7 @@ public class UnlimitedPlayer extends UnlimitedEntity implements EntityTagPlayer
@Override
public void teleport(Player receiver, double x, double y, double z, boolean onGround) {
super.teleport(receiver, x, y, z, onGround);
for (DynamicTextEntity tag : dynamicTags) {
for (DynamicTextEntity tag : dynamicTagArray) {
tag.teleport(receiver, x, y, z, onGround);
}
}
@@ -224,7 +229,7 @@ public class UnlimitedPlayer extends UnlimitedEntity implements EntityTagPlayer
@Override
public void teleport() {
super.teleport();
for (DynamicTextEntity tag : dynamicTags) {
for (DynamicTextEntity tag : dynamicTagArray) {
tag.teleport();
}
}
@@ -232,7 +237,7 @@ public class UnlimitedPlayer extends UnlimitedEntity implements EntityTagPlayer
@Override
public void handlePose(Pose previous, Pose pose) {
super.handlePose(previous, pose);
for (DynamicTextEntity tag : dynamicTags) {
for (DynamicTextEntity tag : dynamicTagArray) {
tag.handlePose(previous, pose);
}
}
@@ -264,8 +269,12 @@ public class UnlimitedPlayer extends UnlimitedEntity implements EntityTagPlayer
}
public void timer() {
for (DynamicTextEntity tag : dynamicTags) {
for (DynamicTextEntity tag : dynamicTagArray) {
tag.timer();
}
}
private void dynamicTagVectorToArray() {
dynamicTagArray = dynamicTags.toArray(new DynamicTextEntity[0]);
}
}
@@ -17,7 +17,6 @@
package net.momirealms.customnameplates.paper.mechanic.placeholder;
import me.clip.placeholderapi.PlaceholderAPI;
import net.momirealms.customnameplates.api.CustomNameplatesPlugin;
import net.momirealms.customnameplates.api.manager.PlaceholderManager;
import net.momirealms.customnameplates.api.mechanic.character.ConfiguredChar;
@@ -29,6 +29,7 @@ import net.momirealms.customnameplates.paper.CustomNameplatesPluginImpl;
import net.momirealms.customnameplates.paper.mechanic.requirement.papi.PapiCondition;
import net.momirealms.customnameplates.paper.util.ClassUtils;
import net.momirealms.customnameplates.paper.util.ConfigUtils;
import net.momirealms.customnameplates.paper.util.GeyserUtils;
import org.bukkit.World;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.potion.PotionEffect;
@@ -121,6 +122,7 @@ public class RequirementManagerImpl implements RequirementManager {
this.registerPapiRequirement();
this.registerInListRequirement();
this.registerGameModeRequirement();
this.registerGeyserRequirement();
}
/**
@@ -289,6 +291,19 @@ public class RequirementManagerImpl implements RequirementManager {
});
}
private void registerGeyserRequirement() {
registerRequirement("geyser", (args) -> {
boolean arg = (boolean) args;
return condition -> {
if (arg) {
return GeyserUtils.isBedrockPlayer(condition.getOfflinePlayer().getUniqueId());
} else {
return !GeyserUtils.isBedrockPlayer(condition.getOfflinePlayer().getUniqueId());
}
};
});
}
private void registerBiomeRequirement() {
registerRequirement("biome", (args) -> {
HashSet<String> biomes = new HashSet<>(ConfigUtils.stringListArgs(args));
@@ -48,7 +48,7 @@ public class SchedulerImpl implements Scheduler {
}
/**
* Reloads the scheduler configuration based on CustomFishingPlugin settings.
* Reloads the scheduler configuration based on settings.
*/
public void reload() {
try {
@@ -38,7 +38,7 @@ import java.util.Objects;
public class CNConfig {
public static String configVersion = "25";
public static String configVersion = "26";
public static int cacheSize;
public static int corePoolSize;
public static long keepAliveTime;
@@ -83,6 +83,8 @@ public class CNConfig {
public static boolean unknownTeam;
public static boolean createRealTeam;
public static boolean enableShader;
public static boolean huskChatChannel;
public static boolean carbonChatChannel;
public static void load() {
try {
@@ -130,6 +132,8 @@ public class CNConfig {
copyPackOraxen = integrationSection.getBoolean("resource-pack.Oraxen", false);
trChatChannel = integrationSection.getBoolean("chat.TrChat", false);
ventureChatChannel = integrationSection.getBoolean("chat.VentureChat", false);
huskChatChannel = integrationSection.getBoolean("chat.HuskChat", false);
carbonChatChannel = integrationSection.getBoolean("chat.CarbonChat", false);
tabTeam = integrationSection.getBoolean("team.TAB", false);
cmiTeam = integrationSection.getBoolean("team.CMI", false);
velocitab = integrationSection.getBoolean("team.Velocitab", false);
@@ -152,7 +152,6 @@ public class RedisManager extends AbstractStorage {
try (Jedis jedis = jedisPool.getResource()) {
byte[] key = getRedisKey("cn_data", uuid);
byte[] data = jedis.get(key);
jedis.del(key);
if (data != null) {
future.complete(Optional.of(plugin.getStorageManager().fromBytes(data)));
plugin.debug("Redis data retrieved for " + uuid + "; normal data");
@@ -55,7 +55,6 @@ public abstract class AbstractHikariDatabase extends AbstractSQLDatabase impleme
} else if (getStorageType() == StorageType.MySQL) {
try {
Class.forName("com.mysql.jdbc.Driver");
LogUtils.warn("It seems that you are not using MySQL 8.0+. It's recommended to update.");
} catch (ClassNotFoundException e2) {
LogUtils.warn("No MySQL driver is found");
}
@@ -76,7 +75,7 @@ public abstract class AbstractHikariDatabase extends AbstractSQLDatabase impleme
return;
}
super.tablePrefix = section.getString("table-prefix", "customfishing");
super.tablePrefix = section.getString("table-prefix", "nameplates");
HikariConfig hikariConfig = new HikariConfig();
hikariConfig.setUsername(section.getString("user", "root"));
hikariConfig.setPassword(section.getString("password", "pa55w0rd"));
@@ -19,19 +19,23 @@ package net.momirealms.customnameplates.paper.storage.method.database.sql;
import net.momirealms.customnameplates.api.CustomNameplatesPlugin;
import net.momirealms.customnameplates.api.data.StorageType;
import net.momirealms.customnameplates.paper.CustomNameplatesPluginImpl;
import net.momirealms.customnameplates.paper.libraries.dependencies.Dependency;
import org.bukkit.configuration.file.YamlConfiguration;
import org.h2.jdbcx.JdbcConnectionPool;
import java.io.File;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.EnumSet;
/**
* An implementation of AbstractSQLDatabase that uses the H2 embedded database for player data storage.
*/
public class H2Impl extends AbstractSQLDatabase {
private JdbcConnectionPool connectionPool;
private Object connectionPool;
private Method disposeMethod;
private Method getConnectionMethod;
public H2Impl(CustomNameplatesPlugin plugin) {
super(plugin);
@@ -44,10 +48,20 @@ public class H2Impl extends AbstractSQLDatabase {
public void initialize() {
YamlConfiguration config = plugin.getConfig("database.yml");
File databaseFile = new File(plugin.getDataFolder(), config.getString("H2.file", "data.db"));
super.tablePrefix = config.getString("H2.table-prefix", "customnameplates");
super.tablePrefix = config.getString("H2.table-prefix", "nameplates");
final String url = String.format("jdbc:h2:%s", databaseFile.getAbsolutePath());
this.connectionPool = JdbcConnectionPool.create(url, "sa", "");
ClassLoader classLoader = ((CustomNameplatesPluginImpl) plugin).getDependencyManager().obtainClassLoaderWith(EnumSet.of(Dependency.H2_DRIVER));
try {
Class<?> connectionClass = classLoader.loadClass("org.h2.jdbcx.JdbcConnectionPool");
Method createPoolMethod = connectionClass.getMethod("create", String.class, String.class, String.class);
this.connectionPool = createPoolMethod.invoke(null, url, "sa", "");
this.disposeMethod = connectionClass.getMethod("dispose");
this.getConnectionMethod = connectionClass.getMethod("getConnection");
} catch (ReflectiveOperationException e) {
throw new RuntimeException(e);
}
super.createTableIfNotExist();
}
@@ -57,7 +71,11 @@ public class H2Impl extends AbstractSQLDatabase {
@Override
public void disable() {
if (connectionPool != null) {
connectionPool.dispose();
try {
disposeMethod.invoke(connectionPool);
} catch (ReflectiveOperationException e) {
e.printStackTrace();
}
}
}
@@ -67,7 +85,11 @@ public class H2Impl extends AbstractSQLDatabase {
}
@Override
public Connection getConnection() throws SQLException {
return connectionPool.getConnection();
public Connection getConnection() {
try {
return (Connection) getConnectionMethod.invoke(connectionPool);
} catch (ReflectiveOperationException e) {
throw new RuntimeException(e);
}
}
}
@@ -51,7 +51,7 @@ public class SQLiteImpl extends AbstractSQLDatabase {
public void initialize() {
YamlConfiguration config = plugin.getConfig("database.yml");
this.databaseFile = new File(plugin.getDataFolder(), config.getString("SQLite.file", "data") + ".db");
super.tablePrefix = config.getString("SQLite.table-prefix", "customfishing");
super.tablePrefix = config.getString("SQLite.table-prefix", "nameplates");
super.createTableIfNotExist();
}
@@ -15,16 +15,15 @@
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package net.momirealms.customnameplates.paper.mechanic.bubble.listener;
package net.momirealms.customnameplates.paper.util;
import net.momirealms.customnameplates.paper.mechanic.bubble.BubbleManagerImpl;
import org.bukkit.event.Listener;
import org.geysermc.api.Geyser;
public abstract class AbstractChatListener implements Listener {
import java.util.UUID;
protected BubbleManagerImpl chatBubblesManager;
public class GeyserUtils {
public AbstractChatListener(BubbleManagerImpl chatBubblesManager) {
this.chatBubblesManager = chatBubblesManager;
public static boolean isBedrockPlayer(UUID uuid) {
return Geyser.api().isBedrockPlayer(uuid);
}
}
@@ -38,10 +38,37 @@ public class Migration {
updateBubble();
updateNameplate();
updateCustomPlaceholders();
updateLanguages();
deleteFiles();
return true;
}
private static void updateLanguages() {
File messageFolder = new File(CustomNameplatesPlugin.get().getDataFolder(), "messages");
if (messageFolder.exists()) {
File[] files = messageFolder.listFiles();
if (files == null)
return;
for (File file : files) {
YamlConfiguration config = YamlConfiguration.loadConfiguration(file);
ConfigurationSection messageSection = config.getConfigurationSection("messages");
if (messageSection != null) {
for (String key : messageSection.getKeys(false)) {
String original = messageSection.getString(key);
if (original != null && original.contains("{Bubbles}")) {
messageSection.set(key, original.replace("{Bubbles}", "{Bubble}"));
}
}
}
try {
config.save(file);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
private static void deleteFiles() {
try {
FileUtils.delete(new File(CustomNameplatesPlugin.get().getDataFolder(), "database.yml"));
@@ -34,6 +34,11 @@ public class ReflectionUtils {
private static Constructor<?> updateConstructor;
private static Method iChatComponentMethod;
private static Object emptyComponent;
private static Method serializeComponentMethod;
private static Method keyAsStringMethod;
private static Method keyFromStringMethod;
private static Object miniMessageInstance;
private static Class<?> keyClass;
public static void load() {
try {
@@ -54,6 +59,18 @@ public class ReflectionUtils {
LogUtils.severe("Error occurred when loading reflections", exception);
exception.printStackTrace();
}
try {
Class<?> componentClass = Class.forName("net;kyori;adventure;text;Component".replace(";", "."));
Class<?> miniMessageClass = Class.forName("net;kyori;adventure;text;minimessage;MiniMessage".replace(";", "."));
Method miniMessageInstanceGetMethod = miniMessageClass.getMethod("miniMessage");
miniMessageInstance = miniMessageInstanceGetMethod.invoke(null);
serializeComponentMethod = miniMessageClass.getMethod("serialize", componentClass);
keyClass = Class.forName("net;kyori;adventure;key;Key".replace(";", "."));
keyAsStringMethod = keyClass.getMethod("asString");
keyFromStringMethod = keyClass.getMethod("key", String.class);
} catch (ClassNotFoundException | NoSuchMethodException | InvocationTargetException |
IllegalAccessException ignored) {
}
}
public static Object getRemoveBossBarPacket() {
@@ -75,4 +92,35 @@ public class ReflectionUtils {
public static Object getEmptyComponent() {
return emptyComponent;
}
public static Class<?> getKeyClass() {
return keyClass;
}
public static String getKeyAsString(Object key) {
try {
return (String) keyAsStringMethod.invoke(key);
} catch (InvocationTargetException | IllegalAccessException e) {
e.printStackTrace();
}
return "";
}
public static Object getKerFromString(String key) {
try {
return keyFromStringMethod.invoke(key);
} catch (InvocationTargetException | IllegalAccessException e) {
e.printStackTrace();
}
return null;
}
public static String getMiniMessageTextFromNonShadedComponent(Object component) {
try {
return (String) serializeComponentMethod.invoke(miniMessageInstance, component);
} catch (InvocationTargetException | IllegalAccessException e) {
e.printStackTrace();
}
return "";
}
}
+6 -3
View File
@@ -1,5 +1,5 @@
# Do not change
config-version: '25'
config-version: '26'
# Debug mode
debug: false
@@ -38,6 +38,8 @@ integrations:
chat:
TrChat: false
VentureChat: false
HuskChat: false
CarbonChat: false
resource-pack:
# disable resource pack generation on server start
@@ -89,7 +91,8 @@ other-settings:
create-real-teams: false
# It's recommended to use MiniMessage format. If you insist on using legacy color code "&", enable the support below.
legacy-color-code-support: false
# Disabling this option would make color formatting faster
legacy-color-code-support: true
# Thread pool settings
thread-pool-settings:
@@ -101,7 +104,7 @@ other-settings:
# If a thread is idle for more than this attribute value, it will exit due to timeout
keepAliveTime: 30
# delay x ticks before actionbar/bossbar is sent to players
# delay x ticks before actionbar/bossbar sent to players
send-delay: 0
# Set the size for the cache system. This is useful and would bring huge performance improvement if you keep it to a reasonable value
@@ -3,6 +3,11 @@ blacklist-channels:
- Private
- Staff
# ALL: all the players can see the bubble
# JOINED: players in the same channel can see each other's bubble
# CAN_JOIN: players that have permission to certain channels would see the bubble in that channel
channel-mode: ALL
# Default bubble to display if player's bubble is "none"
default-bubble: 'chat'
@@ -15,7 +15,7 @@ messages:
force-unequip-nameplates: '<white>你已强制卸下玩家 {Player} 的铭牌!</white>'
not-exist-nameplates: '<white>那个铭牌不存在!</white>'
not-available-nameplates: '<white>你还未拥有这个铭牌!</white>'
available-nameplates: '<white>可用铭牌: {Nameplates}</white>'
available-nameplates: '<white>可用铭牌: {Nameplate}</white>'
have-no-nameplates: '<white>你还没有拥有任何铭牌.</white>'
force-preview: '<white>正在强制玩家 {Player} 预览铭牌</white>'
@@ -15,7 +15,7 @@ messages:
force-unequip-nameplates: '<white>Successfully removed {Player}''s nameplate!</white>'
not-exist-nameplates: '<white>This nameplate does not exist!</white>'
not-available-nameplates: '<white>This nameplate is currently not available!</white>'
available-nameplates: '<white>Available nameplates: {Nameplates}.</white>'
available-nameplates: '<white>Available nameplates: {Nameplate}.</white>'
have-no-nameplates: '<white>You don''t have any nameplate yet'
force-preview: '<white>Forced {Player} to preview the nameplate</white>'
+1 -1
View File
@@ -15,7 +15,7 @@ messages:
force-unequip-nameplates: '<white>La plaque de nom de {Player} a été retirée avec succès !</white>'
not-exist-nameplates: '<white>Cette plaque de nom n'existe pas !</white>'
not-available-nameplates: '<white>Cette plaque de nom n'est actuellement pas disponible !</white>'
available-nameplates: '<white>Plaques de nom disponibles : {Nameplates}.</white>'
available-nameplates: '<white>Plaques de nom disponibles : {Nameplate}.</white>'
have-no-nameplates: '<white>Vous n'avez pas encore de plaque de nom</white>'
force-preview: '<white>Forced {Player} to preview the nameplate</white>'
@@ -15,7 +15,7 @@ messages:
force-unequip-nameplates: '<white>Успешно снят Нэймплейт у {Player}!</white>'
not-exist-nameplates: '<white>Такой Нэйплейт не существует!</white>'
not-available-nameplates: '<white>Этот Нэймплейт сейчас недоступен!</white>'
available-nameplates: '<white>Доступные Нэймплейты: {Nameplates}.</white>'
available-nameplates: '<white>Доступные Нэймплейты: {Nameplate}.</white>'
have-no-nameplates: '<white>У вас еще нет никаких Нэймплейтов.'
force-preview: '<white>Forced {Player} to preview the nameplate</white>'
@@ -15,7 +15,7 @@ messages:
force-unequip-nameplates: '<white>Eliminado con éxito {Player}''s nameplate!</white>'
not-exist-nameplates: '<white>Este nameplate no existe!</white>'
not-available-nameplates: '<white>Este nameplate no esta actualmente disponible!</white>'
available-nameplates: '<white>Nameplates Disponibles: {Nameplates}.</white>'
available-nameplates: '<white>Nameplates Disponibles: {Nameplate}.</white>'
have-no-nameplates: '<white>No tienes ningun nameplate aun'
force-preview: '<white>Forced {Player} to preview the nameplate</white>'
@@ -16,7 +16,7 @@ messages:
force-unequip-nameplates: '<white>{Player} oyuncusunun isim etiketi başarıyla kaldırıldı!</white>'
not-exist-nameplates: '<white>Bu isim etiketi mevcut değil!</white>'
not-available-nameplates: '<white>Bu isim etiketi şu anda kullanılabilir değil!</white>'
available-nameplates: '<white>Mevcut isim etiketleri: {Nameplates}.</white>'
available-nameplates: '<white>Mevcut isim etiketleri: {Nameplate}.</white>'
have-no-nameplates: '<white>Henüz hiç isim etiketiniz yok</white>'
force-preview: '<white>Forced {Player} to preview the nameplate</white>'
+1 -1
View File
@@ -5,7 +5,7 @@ api-version: 1.17
authors: [ XiaoMoMi ]
folia-supported: true
depend: [ ProtocolLib ,PlaceholderAPI ]
softdepend: [ MagicCosmetics, TAB, CMI, TrChat, ItemsAdder, Oraxen ]
softdepend: [ MagicCosmetics, TAB, CMI, TrChat, ItemsAdder, Oraxen, CarbonChat, HuskChat ]
permissions:
nameplates.command.*:
description: Gives access to all nameplate user commands
+9
View File
@@ -11,5 +11,14 @@ tasks {
relocate ("net.kyori", "net.momirealms.customnameplates.libraries")
relocate ("org.bstats", "net.momirealms.customnameplates.libraries.bstats")
relocate ("net.momirealms.biomeapi", "net.momirealms.customnameplates.libraries.biomeapi")
relocate ("org.apache.commons.pool2", "net.momirealms.customnameplates.libraries.commonspool2")
relocate ("com.mysql", "net.momirealms.customnameplates.libraries.mysql")
relocate ("org.mariadb", "net.momirealms.customnameplates.libraries.mariadb")
relocate ("com.zaxxer.hikari", "net.momirealms.customnameplates.libraries.hikari")
relocate ("redis.clients.jedis", "net.momirealms.customnameplates.libraries.jedis")
relocate ("com.mongodb", "net.momirealms.customnameplates.libraries.mongodb")
relocate ("org.bson", "net.momirealms.customnameplates.libraries.bson")
relocate ("dev.jorel.commandapi", "net.momirealms.customnameplates.libraries.commandapi")
relocate ("dev.dejvokep.boostedyaml", "net.momirealms.customnameplates.libraries.boostedyaml")
}
}