mirror of
https://github.com/plexusorg/Plex.git
synced 2025-07-05 09:06:41 +00:00
Revert API
This commit is contained in:
49
src/main/java/dev/plex/util/AshconInfo.java
Normal file
49
src/main/java/dev/plex/util/AshconInfo.java
Normal file
@ -0,0 +1,49 @@
|
||||
package dev.plex.util;
|
||||
|
||||
import com.google.gson.annotations.SerializedName;
|
||||
import java.time.LocalDateTime;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.Setter;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
public class AshconInfo
|
||||
{
|
||||
private String uuid;
|
||||
private String username;
|
||||
|
||||
@SerializedName("username_history")
|
||||
private UsernameHistory[] usernameHistories;
|
||||
|
||||
private Textures textures;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@NoArgsConstructor
|
||||
public static class UsernameHistory
|
||||
{
|
||||
private String username;
|
||||
@SerializedName("changed_at")
|
||||
private LocalDateTime localDateTime;
|
||||
}
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@NoArgsConstructor
|
||||
public static class Textures
|
||||
{
|
||||
private boolean custom;
|
||||
private boolean slim;
|
||||
private SkinData raw;
|
||||
}
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@NoArgsConstructor
|
||||
public static class SkinData
|
||||
{
|
||||
private String value;
|
||||
private String signature;
|
||||
}
|
||||
}
|
60
src/main/java/dev/plex/util/MojangUtils.java
Normal file
60
src/main/java/dev/plex/util/MojangUtils.java
Normal file
@ -0,0 +1,60 @@
|
||||
package dev.plex.util;
|
||||
|
||||
import com.google.gson.GsonBuilder;
|
||||
import com.google.gson.JsonDeserializer;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneId;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.Arrays;
|
||||
import org.apache.http.HttpResponse;
|
||||
import org.apache.http.client.methods.HttpGet;
|
||||
import org.apache.http.impl.client.CloseableHttpClient;
|
||||
import org.apache.http.impl.client.HttpClients;
|
||||
import org.apache.http.util.EntityUtils;
|
||||
import org.json.JSONObject;
|
||||
|
||||
public class MojangUtils
|
||||
{
|
||||
|
||||
public static AshconInfo getInfo(String nameOrUuid)
|
||||
{
|
||||
CloseableHttpClient client = HttpClients.createDefault();
|
||||
HttpGet get = new HttpGet("https://api.ashcon.app/mojang/v2/user/" + nameOrUuid);
|
||||
try
|
||||
{
|
||||
HttpResponse response = client.execute(get);
|
||||
if (response == null || response.getEntity() == null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
String json = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
|
||||
JSONObject object = new JSONObject(json);
|
||||
if (!object.isNull("code") && object.getInt("code") == 404)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
client.close();
|
||||
AshconInfo ashconInfo = new GsonBuilder().registerTypeAdapter(LocalDateTime.class, (JsonDeserializer<LocalDateTime>)(json1, typeOfT, context) ->
|
||||
LocalDateTime.ofInstant(Instant.from(DateTimeFormatter.ISO_INSTANT.parse(json1.getAsJsonPrimitive().getAsString())), ZoneId.systemDefault())).create().fromJson(json, AshconInfo.class);
|
||||
|
||||
Arrays.sort(ashconInfo.getUsernameHistories(), (o1, o2) ->
|
||||
{
|
||||
if (o1.getLocalDateTime() == null || o2.getLocalDateTime() == null)
|
||||
{
|
||||
return 1;
|
||||
}
|
||||
return o1.getLocalDateTime().compareTo(o2.getLocalDateTime());
|
||||
});
|
||||
|
||||
return ashconInfo;
|
||||
}
|
||||
catch (IOException e)
|
||||
{
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
54
src/main/java/dev/plex/util/PlexLog.java
Normal file
54
src/main/java/dev/plex/util/PlexLog.java
Normal file
@ -0,0 +1,54 @@
|
||||
package dev.plex.util;
|
||||
|
||||
import dev.plex.Plex;
|
||||
import net.kyori.adventure.text.Component;
|
||||
import net.kyori.adventure.text.format.NamedTextColor;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.ChatColor;
|
||||
|
||||
public class PlexLog
|
||||
{
|
||||
public static void log(String message, Object... strings)
|
||||
{
|
||||
for (int i = 0; i < strings.length; i++)
|
||||
{
|
||||
if (message.contains("{" + i + "}"))
|
||||
{
|
||||
message = message.replace("{" + i + "}", strings[i].toString());
|
||||
}
|
||||
}
|
||||
Bukkit.getConsoleSender().sendMessage(String.format(ChatColor.YELLOW + "[Plex] " + ChatColor.GRAY + "%s", message));
|
||||
}
|
||||
|
||||
public static void log(Component component)
|
||||
{
|
||||
Bukkit.getConsoleSender().sendMessage(Component.text("[Plex] ").color(NamedTextColor.YELLOW).append(component).colorIfAbsent(NamedTextColor.GRAY));
|
||||
}
|
||||
|
||||
public static void error(String message, Object... strings)
|
||||
{
|
||||
for (int i = 0; i < strings.length; i++)
|
||||
{
|
||||
if (message.contains("{" + i + "}"))
|
||||
{
|
||||
message = message.replace("{" + i + "}", strings[i].toString());
|
||||
}
|
||||
}
|
||||
Bukkit.getConsoleSender().sendMessage(String.format(ChatColor.RED + "[Plex Error] " + ChatColor.GOLD + "%s", message));
|
||||
}
|
||||
|
||||
public static void debug(String message, Object... strings)
|
||||
{
|
||||
for (int i = 0; i < strings.length; i++)
|
||||
{
|
||||
if (message.contains("{" + i + "}"))
|
||||
{
|
||||
message = message.replace("{" + i + "}", strings[i].toString());
|
||||
}
|
||||
}
|
||||
if (Plex.get().config.getBoolean("debug"))
|
||||
{
|
||||
Bukkit.getConsoleSender().sendMessage(String.format(ChatColor.DARK_PURPLE + "[Plex Debug] " + ChatColor.GOLD + "%s", message));
|
||||
}
|
||||
}
|
||||
}
|
488
src/main/java/dev/plex/util/PlexUtils.java
Normal file
488
src/main/java/dev/plex/util/PlexUtils.java
Normal file
@ -0,0 +1,488 @@
|
||||
package dev.plex.util;
|
||||
|
||||
import com.google.common.collect.ImmutableSet;
|
||||
import com.google.common.reflect.ClassPath;
|
||||
import dev.plex.Plex;
|
||||
import dev.plex.PlexBase;
|
||||
import dev.plex.config.Config;
|
||||
import dev.plex.storage.StorageType;
|
||||
import net.kyori.adventure.text.Component;
|
||||
import net.kyori.adventure.text.minimessage.Context;
|
||||
import net.kyori.adventure.text.minimessage.MiniMessage;
|
||||
import net.kyori.adventure.text.minimessage.ParsingException;
|
||||
import net.kyori.adventure.text.minimessage.tag.Tag;
|
||||
import net.kyori.adventure.text.minimessage.tag.resolver.ArgumentQueue;
|
||||
import net.kyori.adventure.text.minimessage.tag.resolver.TagResolver;
|
||||
import net.kyori.adventure.text.minimessage.tag.standard.*;
|
||||
import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer;
|
||||
import net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer;
|
||||
import org.apache.commons.lang.math.NumberUtils;
|
||||
import org.bukkit.*;
|
||||
import org.bukkit.command.Command;
|
||||
import org.bukkit.command.PluginCommandYamlParser;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.plugin.Plugin;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import org.json.simple.JSONObject;
|
||||
import org.json.simple.parser.JSONParser;
|
||||
import org.json.simple.parser.ParseException;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.URL;
|
||||
import java.sql.Connection;
|
||||
import java.sql.SQLException;
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.Month;
|
||||
import java.time.ZoneId;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.ThreadLocalRandom;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class PlexUtils extends PlexBase
|
||||
{
|
||||
private static final Random RANDOM;
|
||||
private static final List<String> regxList = new ArrayList<>()
|
||||
{{
|
||||
add("y");
|
||||
add("mo");
|
||||
add("w");
|
||||
add("d");
|
||||
add("h");
|
||||
add("m");
|
||||
add("s");
|
||||
}};
|
||||
public static Map<String, ChatColor> CHAT_COLOR_NAMES;
|
||||
public static List<ChatColor> CHAT_COLOR_POOL;
|
||||
public static List<String> DEVELOPERS =
|
||||
Arrays.asList("78408086-1991-4c33-a571-d8fa325465b2", // Telesphoreo
|
||||
"f5cd54c4-3a24-4213-9a56-c06c49594dff", // Taahh
|
||||
"ca83b658-c03b-4106-9edc-72f70a80656d", // ayunami2000
|
||||
"2e06e049-24c8-42e4-8bcf-d35372af31e6" //Fleek
|
||||
);
|
||||
|
||||
static
|
||||
{
|
||||
RANDOM = new Random();
|
||||
CHAT_COLOR_NAMES = new HashMap<>();
|
||||
CHAT_COLOR_POOL = Arrays.asList(ChatColor.DARK_RED, ChatColor.RED, ChatColor.GOLD, ChatColor.YELLOW, ChatColor.GREEN, ChatColor.DARK_GREEN, ChatColor.AQUA, ChatColor.DARK_AQUA, ChatColor.BLUE, ChatColor.DARK_BLUE, ChatColor.DARK_PURPLE, ChatColor.LIGHT_PURPLE);
|
||||
for (final ChatColor chatColor : CHAT_COLOR_POOL)
|
||||
{
|
||||
CHAT_COLOR_NAMES.put(chatColor.name().toLowerCase().replace("_", ""), chatColor);
|
||||
}
|
||||
}
|
||||
|
||||
public static void disabledEffect(Player player, Location location)
|
||||
{
|
||||
Particle.CLOUD.builder().location(location).receivers(player).extra(0).offset(0.5, 0.5, 0.5).count(5).spawn();
|
||||
Particle.FLAME.builder().location(location).receivers(player).extra(0).offset(0.5, 0.5, 0.5).count(3).spawn();
|
||||
Particle.SOUL_FIRE_FLAME.builder().location(location).receivers(player).offset(0.5, 0.5, 0.5).extra(0).count(2).spawn();
|
||||
player.playSound(location, org.bukkit.Sound.BLOCK_FIRE_EXTINGUISH, 0.5f, 0.5f);
|
||||
}
|
||||
|
||||
public static void disabledEffectMultiple(Player[] players, Location location)
|
||||
{
|
||||
Particle.CLOUD.builder().location(location).receivers(players).extra(0).offset(0.5, 0.5, 0.5).count(5).spawn();
|
||||
Particle.FLAME.builder().location(location).receivers(players).extra(0).offset(0.5, 0.5, 0.5).count(3).spawn();
|
||||
Particle.SOUL_FIRE_FLAME.builder().location(location).receivers(players).offset(0.5, 0.5, 0.5).extra(0).count(2).spawn();
|
||||
// note that the sound is played to everyone who is close enough to hear it
|
||||
players[0].getWorld().playSound(location, org.bukkit.Sound.BLOCK_FIRE_EXTINGUISH, 0.5f, 0.5f);
|
||||
}
|
||||
|
||||
public static ChatColor randomChatColor()
|
||||
{
|
||||
return CHAT_COLOR_POOL.get(RANDOM.nextInt(CHAT_COLOR_POOL.size()));
|
||||
}
|
||||
|
||||
public static void testConnections()
|
||||
{
|
||||
if (Plex.get().getSqlConnection().getDataSource() != null)
|
||||
{
|
||||
try (Connection con = Plex.get().getSqlConnection().getCon())
|
||||
{
|
||||
if (Plex.get().getStorageType() == StorageType.MARIADB)
|
||||
{
|
||||
PlexLog.log("Successfully enabled MySQL!");
|
||||
}
|
||||
else if (Plex.get().getStorageType() == StorageType.SQLITE)
|
||||
{
|
||||
PlexLog.log("Successfully enabled SQLite!");
|
||||
}
|
||||
}
|
||||
catch (SQLException e)
|
||||
{
|
||||
if (Plex.get().getMongoConnection().getDatastore() != null)
|
||||
{
|
||||
PlexLog.log("Successfully enabled MongoDB!");
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (Plex.get().getMongoConnection().getDatastore() != null)
|
||||
{
|
||||
PlexLog.log("Successfully enabled MongoDB!");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static boolean isPluginCMD(String cmd, String pluginName)
|
||||
{
|
||||
Plugin plugin = Bukkit.getServer().getPluginManager().getPlugin(pluginName);
|
||||
if (plugin == null)
|
||||
{
|
||||
PlexLog.error(pluginName + " can not be found on the server! Make sure it is spelt correctly!");
|
||||
return false;
|
||||
}
|
||||
List<Command> cmds = PluginCommandYamlParser.parse(plugin);
|
||||
for (Command pluginCmd : cmds)
|
||||
{
|
||||
List<String> cmdAliases = pluginCmd.getAliases().size() > 0 ? pluginCmd.getAliases().stream().map(String::toLowerCase).collect(Collectors.toList()) : null;
|
||||
if (pluginCmd.getName().equalsIgnoreCase(cmd) || (cmdAliases != null && cmdAliases.contains(cmd.toLowerCase())))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public static String colorize(final String string)
|
||||
{
|
||||
return ChatColor.translateAlternateColorCodes('&', string);
|
||||
}
|
||||
|
||||
private static final MiniMessage safeMessage = MiniMessage.builder().tags(TagResolver.builder().resolvers(
|
||||
StandardTags.color(),
|
||||
StandardTags.decorations(),
|
||||
StandardTags.gradient(),
|
||||
StandardTags.rainbow(),
|
||||
StandardTags.reset()
|
||||
).build()).build();
|
||||
|
||||
private static final MiniMessage eggMessage = MiniMessage.builder().tags(new TagResolver()
|
||||
{
|
||||
@Override
|
||||
public @Nullable Tag resolve(@NotNull String name, @NotNull ArgumentQueue arguments, @NotNull Context ctx) throws ParsingException
|
||||
{
|
||||
return StandardTags.rainbow().resolve("rainbow", arguments, ctx);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean has(@NotNull String name)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
).build();
|
||||
|
||||
public static Component mmDeserialize(String input)
|
||||
{
|
||||
/*Calendar calendar = Calendar.getInstance();
|
||||
MiniMessage mm = (calendar.get(Calendar.MONTH) == Calendar.APRIL && calendar.get(Calendar.DAY_OF_MONTH) == 1 && (!plugin.config.contains("april_fools") || plugin.config.getBoolean("april_fools"))) ? eggMessage : safeMessage;
|
||||
return mm.deserialize(PlainTextComponentSerializer.plainText().serialize(LegacyComponentSerializer.legacySection().deserialize(input)));*/
|
||||
boolean aprilFools = plugin.config.getBoolean("april_fools");
|
||||
LocalDateTime date = LocalDateTime.now();
|
||||
if (aprilFools && date.getMonth() == Month.APRIL && date.getDayOfMonth() == 1)
|
||||
{
|
||||
Component component = PlainTextComponentSerializer.plainText().deserialize(input);
|
||||
return MiniMessage.miniMessage().deserialize("<rainbow>" + PlainTextComponentSerializer.plainText().serialize(component));
|
||||
}
|
||||
return MiniMessage.miniMessage().deserialize(input);
|
||||
}
|
||||
|
||||
public static Component mmCustomDeserialize(String input, TagResolver... resolvers)
|
||||
{
|
||||
return MiniMessage.builder().tags(TagResolver.builder().resolvers(resolvers).build()).build().deserialize(input);
|
||||
}
|
||||
|
||||
public static Component messageComponent(String entry, Object... objects)
|
||||
{
|
||||
return MiniMessage.miniMessage().deserialize(messageString(entry, objects));
|
||||
}
|
||||
|
||||
public static String messageString(String entry, Object... objects)
|
||||
{
|
||||
String f = plugin.messages.getString(entry);
|
||||
if (f == null)
|
||||
{
|
||||
throw new NullPointerException();
|
||||
}
|
||||
for (int i = 0; i < objects.length; i++)
|
||||
{
|
||||
f = f.replace("{" + i + "}", String.valueOf(objects[i]));
|
||||
}
|
||||
return f;
|
||||
}
|
||||
|
||||
private static long a(String parse)
|
||||
{
|
||||
StringBuilder sb = new StringBuilder();
|
||||
|
||||
regxList.forEach(obj ->
|
||||
{
|
||||
if (parse.endsWith(obj))
|
||||
{
|
||||
sb.append(parse.split(obj)[0]);
|
||||
}
|
||||
});
|
||||
|
||||
return Long.parseLong(sb.toString());
|
||||
}
|
||||
|
||||
private static TimeUnit verify(String arg)
|
||||
{
|
||||
TimeUnit unit = null;
|
||||
for (String c : regxList)
|
||||
{
|
||||
if (arg.endsWith(c))
|
||||
{
|
||||
switch (c)
|
||||
{
|
||||
case "y" -> unit = TimeUnit.YEAR;
|
||||
case "mo" -> unit = TimeUnit.MONTH;
|
||||
case "w" -> unit = TimeUnit.WEEK;
|
||||
case "d" -> unit = TimeUnit.DAY;
|
||||
case "h" -> unit = TimeUnit.HOUR;
|
||||
case "m" -> unit = TimeUnit.MINUTE;
|
||||
case "s" -> unit = TimeUnit.SECOND;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
return (unit != null) ? unit : TimeUnit.DAY;
|
||||
}
|
||||
|
||||
public static LocalDateTime parseDateOffset(String... time)
|
||||
{
|
||||
Instant instant = Instant.now();
|
||||
for (String arg : time)
|
||||
{
|
||||
instant = instant.plusSeconds(verify(arg).get() * a(arg));
|
||||
}
|
||||
return LocalDateTime.ofInstant(instant, ZoneId.systemDefault().getRules().getOffset(instant));
|
||||
}
|
||||
|
||||
public static ChatColor getChatColorFromConfig(Config config, ChatColor def, String path)
|
||||
{
|
||||
ChatColor color;
|
||||
if (config.getString(path) == null)
|
||||
{
|
||||
color = def;
|
||||
}
|
||||
else if (ChatColor.getByChar(config.getString(path)) == null)
|
||||
{
|
||||
color = def;
|
||||
}
|
||||
else
|
||||
{
|
||||
color = ChatColor.getByChar(config.getString(path));
|
||||
}
|
||||
return color;
|
||||
}
|
||||
|
||||
public static void setBlocks(Location c1, Location c2, Material material)
|
||||
{
|
||||
if (!c1.getWorld().getName().equals(c1.getWorld().getName()))
|
||||
{
|
||||
return;
|
||||
}
|
||||
int sy = Math.min(c1.getBlockY(), c2.getBlockY()), ey = Math.max(c1.getBlockY(), c2.getBlockY()), sx = Math.min(c1.getBlockX(), c2.getBlockX()), ex = Math.max(c1.getBlockX(), c2.getBlockX()), sz = Math.min(c1.getBlockZ(), c2.getBlockZ()), ez = Math.max(c1.getBlockZ(), c2.getBlockZ());
|
||||
World world = c1.getWorld();
|
||||
for (int y = sy; y <= ey; y++)
|
||||
{
|
||||
for (int x = sx; x <= ex; x++)
|
||||
{
|
||||
for (int z = sz; z <= ez; z++)
|
||||
{
|
||||
world.getBlockAt(x, y, z).setType(material);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static <T> void commitGlobalGameRules(World world)
|
||||
{
|
||||
for (String s : Plex.get().config.getStringList("global_gamerules"))
|
||||
{
|
||||
readGameRules(world, s);
|
||||
}
|
||||
}
|
||||
|
||||
public static <T> void commitSpecificGameRules(World world)
|
||||
{
|
||||
for (String s : Plex.get().config.getStringList("worlds." + world.getName().toLowerCase(Locale.ROOT) + ".gameRules"))
|
||||
{
|
||||
readGameRules(world, s);
|
||||
}
|
||||
}
|
||||
|
||||
private static <T> void readGameRules(World world, String s)
|
||||
{
|
||||
String gameRule = s.split(";")[0];
|
||||
T value = (T)s.split(";")[1];
|
||||
GameRule<T> rule = (GameRule<T>)GameRule.getByName(gameRule);
|
||||
if (rule != null && check(value).getClass().equals(rule.getType()))
|
||||
{
|
||||
world.setGameRule(rule, value);
|
||||
PlexLog.debug("Setting game rule " + gameRule + " for world " + world.getName() + " with value " + value);
|
||||
}
|
||||
else
|
||||
{
|
||||
PlexLog.error(String.format("Failed to set game rule %s for world %s with value %s!", gameRule, world.getName().toLowerCase(Locale.ROOT), value));
|
||||
}
|
||||
}
|
||||
|
||||
public static <T> Object check(T value)
|
||||
{
|
||||
if (value.toString().equalsIgnoreCase("true") || value.toString().equalsIgnoreCase("false"))
|
||||
{
|
||||
return Boolean.parseBoolean(value.toString());
|
||||
}
|
||||
|
||||
if (NumberUtils.isNumber(value.toString()))
|
||||
{
|
||||
return Integer.parseInt(value.toString());
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
public static List<String> getPlayerNameList()
|
||||
{
|
||||
return Bukkit.getOnlinePlayers().stream().map(Player::getName).collect(Collectors.toList());
|
||||
}
|
||||
|
||||
public static void broadcast(String s)
|
||||
{
|
||||
Bukkit.broadcast(LegacyComponentSerializer.legacyAmpersand().deserialize(s));
|
||||
}
|
||||
|
||||
public static void broadcast(Component component)
|
||||
{
|
||||
Bukkit.broadcast(component);
|
||||
}
|
||||
|
||||
public static Object simpleGET(String url)
|
||||
{
|
||||
try
|
||||
{
|
||||
URL u = new URL(url);
|
||||
HttpURLConnection connection = (HttpURLConnection)u.openConnection();
|
||||
connection.setRequestMethod("GET");
|
||||
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
|
||||
String line;
|
||||
StringBuilder content = new StringBuilder();
|
||||
while ((line = in.readLine()) != null)
|
||||
{
|
||||
content.append(line);
|
||||
}
|
||||
in.close();
|
||||
connection.disconnect();
|
||||
return new JSONParser().parse(content.toString());
|
||||
}
|
||||
catch (IOException | ParseException ex)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static UUID getFromName(String name)
|
||||
{
|
||||
JSONObject profile;
|
||||
profile = (JSONObject)simpleGET("https://api.ashcon.app/mojang/v2/user/" + name);
|
||||
if (profile == null)
|
||||
{
|
||||
PlexLog.error("Profile from Ashcon API returned null!");
|
||||
return null;
|
||||
}
|
||||
String uuidString = (String)profile.get("uuid");
|
||||
return UUID.fromString(uuidString);
|
||||
}
|
||||
|
||||
@SuppressWarnings("UnstableApiUsage")
|
||||
public static Set<Class<?>> getClassesFrom(String packageName)
|
||||
{
|
||||
Set<Class<?>> classes = new HashSet<>();
|
||||
try
|
||||
{
|
||||
ClassPath path = ClassPath.from(Plex.class.getClassLoader());
|
||||
ImmutableSet<ClassPath.ClassInfo> infoSet = path.getTopLevelClasses(packageName);
|
||||
infoSet.forEach(info ->
|
||||
{
|
||||
try
|
||||
{
|
||||
Class<?> clazz = Class.forName(info.getName());
|
||||
classes.add(clazz);
|
||||
}
|
||||
catch (ClassNotFoundException ex)
|
||||
{
|
||||
PlexLog.error("Unable to find class " + info.getName() + " in " + packageName);
|
||||
}
|
||||
});
|
||||
}
|
||||
catch (IOException ex)
|
||||
{
|
||||
PlexLog.error("Something went wrong while fetching classes from " + packageName);
|
||||
throw new RuntimeException(ex);
|
||||
}
|
||||
return Collections.unmodifiableSet(classes);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public static <T> Set<Class<? extends T>> getClassesBySubType(String packageName, Class<T> subType)
|
||||
{
|
||||
Set<Class<?>> loadedClasses = getClassesFrom(packageName);
|
||||
Set<Class<? extends T>> classes = new HashSet<>();
|
||||
loadedClasses.forEach(clazz ->
|
||||
{
|
||||
if (clazz.getSuperclass() == subType || Arrays.asList(clazz.getInterfaces()).contains(subType))
|
||||
{
|
||||
classes.add((Class<? extends T>)clazz);
|
||||
}
|
||||
});
|
||||
return Collections.unmodifiableSet(classes);
|
||||
}
|
||||
|
||||
public static boolean randomBoolean()
|
||||
{
|
||||
return ThreadLocalRandom.current().nextBoolean();
|
||||
}
|
||||
|
||||
public static int randomNum()
|
||||
{
|
||||
return ThreadLocalRandom.current().nextInt();
|
||||
}
|
||||
|
||||
public static int randomNum(int limit)
|
||||
{
|
||||
return ThreadLocalRandom.current().nextInt(limit);
|
||||
}
|
||||
|
||||
public static int randomNum(int start, int limit)
|
||||
{
|
||||
return ThreadLocalRandom.current().nextInt(start, limit);
|
||||
}
|
||||
|
||||
public static long getDateNow()
|
||||
{
|
||||
return new Date().getTime();
|
||||
}
|
||||
|
||||
public static Date getDateFromLong(long epoch)
|
||||
{
|
||||
return new Date(epoch);
|
||||
}
|
||||
|
||||
public static long hoursToSeconds(long hours)
|
||||
{
|
||||
return hours * 3600;
|
||||
}
|
||||
|
||||
public static long minutesToSeconds(long minutes)
|
||||
{
|
||||
return minutes * 60;
|
||||
}
|
||||
}
|
24
src/main/java/dev/plex/util/TimeUnit.java
Normal file
24
src/main/java/dev/plex/util/TimeUnit.java
Normal file
@ -0,0 +1,24 @@
|
||||
package dev.plex.util;
|
||||
|
||||
public enum TimeUnit
|
||||
{
|
||||
SECOND(1L),
|
||||
MINUTE(SECOND.get() * 60L),
|
||||
HOUR(MINUTE.get() * 60L),
|
||||
DAY(HOUR.get() * 24L),
|
||||
WEEK(DAY.get() * 7L),
|
||||
MONTH(DAY.get() * 30L),
|
||||
YEAR(MONTH.get() * 12L);
|
||||
|
||||
private final long time;
|
||||
|
||||
TimeUnit(long time)
|
||||
{
|
||||
this.time = time;
|
||||
}
|
||||
|
||||
public long get()
|
||||
{
|
||||
return time;
|
||||
}
|
||||
}
|
182
src/main/java/dev/plex/util/UpdateChecker.java
Normal file
182
src/main/java/dev/plex/util/UpdateChecker.java
Normal file
@ -0,0 +1,182 @@
|
||||
package dev.plex.util;
|
||||
|
||||
import com.google.common.base.Charsets;
|
||||
import com.google.gson.Gson;
|
||||
import com.google.gson.JsonObject;
|
||||
import com.google.gson.JsonSyntaxException;
|
||||
import dev.plex.Plex;
|
||||
import dev.plex.PlexBase;
|
||||
import net.kyori.adventure.text.Component;
|
||||
import net.kyori.adventure.text.format.NamedTextColor;
|
||||
import net.kyori.adventure.text.minimessage.MiniMessage;
|
||||
import org.apache.commons.io.FileUtils;
|
||||
import org.apache.http.HttpResponse;
|
||||
import org.apache.http.client.methods.HttpGet;
|
||||
import org.apache.http.impl.client.CloseableHttpClient;
|
||||
import org.apache.http.impl.client.HttpClients;
|
||||
import org.apache.http.util.EntityUtils;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.json.JSONObject;
|
||||
|
||||
import javax.annotation.Nonnull;
|
||||
import java.io.BufferedReader;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.URL;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
public class UpdateChecker extends PlexBase
|
||||
{
|
||||
/*
|
||||
* -4 = Never checked for updates
|
||||
* -3 = Likely rate limited
|
||||
* -2 = Unknown commit
|
||||
* -1 = Error occurred
|
||||
* 0 = Up to date
|
||||
* > 0 = Number of commits behind
|
||||
*/
|
||||
private final String DOWNLOAD_PAGE = "https://ci.plex.us.org/job/Plex/";
|
||||
private String branch = plugin.config.getString("update_branch");
|
||||
private int distance = -4;
|
||||
|
||||
// Adapted from Paper
|
||||
private int fetchDistanceFromGitHub(@Nonnull String repo, @Nonnull String branch, @Nonnull String hash)
|
||||
{
|
||||
try
|
||||
{
|
||||
HttpURLConnection connection = (HttpURLConnection)new URL("https://api.github.com/repos/" + repo + "/compare/" + branch + "..." + hash).openConnection();
|
||||
connection.connect();
|
||||
if (connection.getResponseCode() == HttpURLConnection.HTTP_NOT_FOUND)
|
||||
{
|
||||
return -2; // Unknown commit
|
||||
}
|
||||
if (connection.getResponseCode() == HttpURLConnection.HTTP_FORBIDDEN)
|
||||
{
|
||||
return -3; // Rate limited likely
|
||||
}
|
||||
try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), Charsets.UTF_8)))
|
||||
{
|
||||
JsonObject obj = new Gson().fromJson(reader, JsonObject.class);
|
||||
String status = obj.get("status").getAsString();
|
||||
return switch (status)
|
||||
{
|
||||
case "identical" -> 0;
|
||||
case "behind" -> obj.get("behind_by").getAsInt();
|
||||
default -> -1;
|
||||
};
|
||||
}
|
||||
catch (JsonSyntaxException | NumberFormatException e)
|
||||
{
|
||||
e.printStackTrace();
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
catch (IOException e)
|
||||
{
|
||||
e.printStackTrace();
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
// If verbose is 0, it will display nothing
|
||||
// If verbose is 1, it will only display a message if there is an update available
|
||||
// If verbose is 2, it will display all messages
|
||||
public boolean getUpdateStatusMessage(CommandSender sender, boolean cached, int verbosity)
|
||||
{
|
||||
if (branch == null)
|
||||
{
|
||||
PlexLog.error("You did not specify a branch to use for update checking. Defaulting to master.");
|
||||
branch = "master";
|
||||
}
|
||||
// If it's -4, it hasn't checked for updates yet
|
||||
if (distance == -4)
|
||||
{
|
||||
distance = fetchDistanceFromGitHub("plexusorg/Plex", branch, Plex.build.head);
|
||||
PlexLog.debug("Never checked for updates, checking now...");
|
||||
}
|
||||
else
|
||||
{
|
||||
// If the request isn't asked to be cached, fetch it
|
||||
if (!cached)
|
||||
{
|
||||
distance = fetchDistanceFromGitHub("plexusorg/Plex", branch, Plex.build.head);
|
||||
PlexLog.debug("We have checked for updates before, but this request was not asked to be cached.");
|
||||
}
|
||||
else
|
||||
{
|
||||
PlexLog.debug("We have checked for updates before, using cache.");
|
||||
}
|
||||
}
|
||||
|
||||
switch (distance)
|
||||
{
|
||||
case -1 -> {
|
||||
if (verbosity == 2)
|
||||
{
|
||||
sender.sendMessage(Component.text("There was an error checking for updates.").color(NamedTextColor.RED));
|
||||
}
|
||||
return false;
|
||||
}
|
||||
case 0 -> {
|
||||
if (verbosity == 2)
|
||||
{
|
||||
sender.sendMessage(Component.text("Plex is up to date!").color(NamedTextColor.GREEN));
|
||||
}
|
||||
return false;
|
||||
}
|
||||
case -2 -> {
|
||||
if (verbosity == 2)
|
||||
{
|
||||
sender.sendMessage(Component.text("Unknown version, unable to check for updates.").color(NamedTextColor.RED));
|
||||
}
|
||||
return false;
|
||||
}
|
||||
default -> {
|
||||
if (verbosity >= 1)
|
||||
{
|
||||
sender.sendMessage(Component.text("Plex is not up to date!", NamedTextColor.RED));
|
||||
sender.sendMessage(Component.text("Download a new version at: " + DOWNLOAD_PAGE).color(NamedTextColor.RED));
|
||||
sender.sendMessage(Component.text("Or run: /plex update").color(NamedTextColor.RED));
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void updateJar(CommandSender sender)
|
||||
{
|
||||
CloseableHttpClient client = HttpClients.createDefault();
|
||||
HttpGet get = new HttpGet(DOWNLOAD_PAGE + "job/" + branch + "/lastSuccessfulBuild/api/json");
|
||||
try
|
||||
{
|
||||
HttpResponse response = client.execute(get);
|
||||
JSONObject object = new JSONObject(EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8));
|
||||
JSONObject artifact = object.getJSONArray("artifacts").getJSONObject(0);
|
||||
String name = artifact.getString("fileName");
|
||||
sender.sendMessage(PlexUtils.mmDeserialize("<green>Downloading latest Plex jar file: " + name));
|
||||
CompletableFuture.runAsync(() ->
|
||||
{
|
||||
try
|
||||
{
|
||||
FileUtils.copyURLToFile(
|
||||
new URL(DOWNLOAD_PAGE + "job/" + branch + "/lastSuccessfulBuild/artifact/build/libs/" + name),
|
||||
new File(Bukkit.getUpdateFolderFile(), name)
|
||||
);
|
||||
sender.sendMessage(PlexUtils.mmDeserialize("<green>Saved new jar. Please restart your server."));
|
||||
}
|
||||
catch (IOException e)
|
||||
{
|
||||
e.printStackTrace();
|
||||
}
|
||||
});
|
||||
}
|
||||
catch (IOException e)
|
||||
{
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,20 @@
|
||||
package dev.plex.util.adapter;
|
||||
|
||||
import com.google.gson.JsonDeserializationContext;
|
||||
import com.google.gson.JsonDeserializer;
|
||||
import com.google.gson.JsonElement;
|
||||
import com.google.gson.JsonParseException;
|
||||
import java.lang.reflect.Type;
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneId;
|
||||
|
||||
public class LocalDateTimeDeserializer implements JsonDeserializer<LocalDateTime>
|
||||
{
|
||||
@Override
|
||||
public LocalDateTime deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException
|
||||
{
|
||||
Instant instant = Instant.ofEpochMilli(json.getAsJsonPrimitive().getAsLong());
|
||||
return LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
|
||||
}
|
||||
}
|
@ -0,0 +1,19 @@
|
||||
package dev.plex.util.adapter;
|
||||
|
||||
import com.google.gson.JsonElement;
|
||||
import com.google.gson.JsonPrimitive;
|
||||
import com.google.gson.JsonSerializationContext;
|
||||
import com.google.gson.JsonSerializer;
|
||||
import java.lang.reflect.Type;
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneId;
|
||||
|
||||
public class LocalDateTimeSerializer implements JsonSerializer<LocalDateTime>
|
||||
{
|
||||
@Override
|
||||
public JsonElement serialize(LocalDateTime src, Type typeOfSrc, JsonSerializationContext context)
|
||||
{
|
||||
return new JsonPrimitive(src.toInstant(ZoneId.systemDefault().getRules().getOffset(Instant.now())).toEpochMilli());
|
||||
}
|
||||
}
|
62
src/main/java/dev/plex/util/item/ItemBuilder.java
Normal file
62
src/main/java/dev/plex/util/item/ItemBuilder.java
Normal file
@ -0,0 +1,62 @@
|
||||
package dev.plex.util.item;
|
||||
|
||||
import net.kyori.adventure.text.Component;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.attribute.Attribute;
|
||||
import org.bukkit.attribute.AttributeModifier;
|
||||
import org.bukkit.enchantments.Enchantment;
|
||||
import org.bukkit.inventory.ItemFlag;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
import org.bukkit.inventory.meta.ItemMeta;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
public class ItemBuilder
|
||||
{
|
||||
|
||||
private final ItemStack itemStack;
|
||||
private final ItemMeta meta;
|
||||
|
||||
public ItemBuilder(Material material)
|
||||
{
|
||||
this.itemStack = new ItemStack(material);
|
||||
this.meta = itemStack.getItemMeta();
|
||||
}
|
||||
|
||||
public ItemBuilder lore(Component... lore)
|
||||
{
|
||||
this.meta.lore(Arrays.asList(lore));
|
||||
return this;
|
||||
}
|
||||
|
||||
public ItemBuilder displayName(Component displayName)
|
||||
{
|
||||
this.meta.displayName(displayName);
|
||||
return this;
|
||||
}
|
||||
|
||||
public ItemBuilder addEnchantment(Enchantment enchantment, int level)
|
||||
{
|
||||
this.meta.addEnchant(enchantment, level, true);
|
||||
return this;
|
||||
}
|
||||
|
||||
public ItemBuilder addItemFlag(ItemFlag... flags)
|
||||
{
|
||||
this.meta.addItemFlags(flags);
|
||||
return this;
|
||||
}
|
||||
|
||||
public ItemBuilder addAttributeModifier(Attribute attribute, AttributeModifier modifier)
|
||||
{
|
||||
this.meta.addAttributeModifier(attribute, modifier);
|
||||
return this;
|
||||
}
|
||||
|
||||
public ItemStack build()
|
||||
{
|
||||
this.itemStack.setItemMeta(this.meta);
|
||||
return this.itemStack;
|
||||
}
|
||||
|
||||
}
|
21
src/main/java/dev/plex/util/menu/AbstractMenu.java
Normal file
21
src/main/java/dev/plex/util/menu/AbstractMenu.java
Normal file
@ -0,0 +1,21 @@
|
||||
package dev.plex.util.menu;
|
||||
|
||||
import dev.plex.Plex;
|
||||
import org.bukkit.event.Listener;
|
||||
|
||||
public abstract class AbstractMenu implements Listener
|
||||
{
|
||||
private String name;
|
||||
|
||||
public AbstractMenu(String name)
|
||||
{
|
||||
this.name = name;
|
||||
|
||||
Plex.get().getServer().getPluginManager().registerEvents(this, Plex.get());
|
||||
}
|
||||
|
||||
public String getName()
|
||||
{
|
||||
return name;
|
||||
}
|
||||
}
|
20
src/main/java/dev/plex/util/menu/IMenu.java
Normal file
20
src/main/java/dev/plex/util/menu/IMenu.java
Normal file
@ -0,0 +1,20 @@
|
||||
package dev.plex.util.menu;
|
||||
|
||||
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.inventory.InventoryClickEvent;
|
||||
import org.bukkit.inventory.Inventory;
|
||||
|
||||
public interface IMenu
|
||||
{
|
||||
|
||||
Inventory getInventory();
|
||||
|
||||
|
||||
void openInv(Player player);
|
||||
|
||||
@EventHandler
|
||||
void onClick(InventoryClickEvent event);
|
||||
|
||||
}
|
Reference in New Issue
Block a user