Merge pull request '1.3.3 稳定版' (#3) from dev into master

Reviewed-on: #3
This commit is contained in:
2024-03-24 13:36:54 +08:00
27 changed files with 222 additions and 387 deletions

View File

@@ -26,9 +26,9 @@ repositories {
dependencies { dependencies {
// 对于 Bukkit 插件 // 对于 Bukkit 插件
compileOnly("cn.hamster3.mc.plugin:core-bukkit:1.3.2") compileOnly("cn.hamster3.mc.plugin:core-bukkit:1.3.3")
// 对于 BungeeCord 插件 // 对于 BungeeCord 插件
compileOnly("cn.hamster3.mc.plugin:core-bungee:1.3.2") compileOnly("cn.hamster3.mc.plugin:core-bungee:1.3.3")
} }
``` ```
@@ -54,13 +54,13 @@ dependencies {
<dependency> <dependency>
<groupId>cn.hamster3.mc.plugin</groupId> <groupId>cn.hamster3.mc.plugin</groupId>
<artifactId>core-bukkit</artifactId> <artifactId>core-bukkit</artifactId>
<version>1.3.2</version> <version>1.3.3</version>
</dependency> </dependency>
<!--对于 BungeeCord 插件--> <!--对于 BungeeCord 插件-->
<dependency> <dependency>
<groupId>cn.hamster3.mc.plugin</groupId> <groupId>cn.hamster3.mc.plugin</groupId>
<artifactId>core-bungee</artifactId> <artifactId>core-bungee</artifactId>
<version>1.3.2</version> <version>1.3.3</version>
</dependency> </dependency>
</dependencies> </dependencies>
</project> </project>

View File

@@ -5,7 +5,8 @@ plugins {
} }
group = "cn.hamster3.mc.plugin" group = "cn.hamster3.mc.plugin"
version = "1.3.2" version = "1.3.3"
description = "叁只仓鼠的 Minecraft 插件开发通用工具包"
subprojects { subprojects {
apply { apply {
@@ -16,6 +17,7 @@ subprojects {
group = rootProject.group group = rootProject.group
version = rootProject.version version = rootProject.version
description = rootProject.description
repositories { repositories {
maven("https://maven.airgame.net/maven-public") maven("https://maven.airgame.net/maven-public")

View File

@@ -1,12 +1,7 @@
@file:Suppress("VulnerableLibrariesLocal") @file:Suppress("VulnerableLibrariesLocal")
import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar
evaluationDependsOn(":core-common") evaluationDependsOn(":core-common")
val shade = configurations.create("shade")
val shadeJava8 = configurations.create("shadeJava8")
dependencies { dependencies {
api(project(":core-common")) { isTransitive = false } api(project(":core-common")) { isTransitive = false }
compileOnly("org.spigotmc:spigot-api:1.18.2-R0.1-SNAPSHOT") compileOnly("org.spigotmc:spigot-api:1.18.2-R0.1-SNAPSHOT")
@@ -30,16 +25,15 @@ dependencies {
} }
// https://mvnrepository.com/artifact/org.quartz-scheduler/quartz // https://mvnrepository.com/artifact/org.quartz-scheduler/quartz
api("org.quartz-scheduler:quartz:2.3.2") { isTransitive = false } api("org.quartz-scheduler:quartz:2.3.2") { isTransitive = false }
// https://mvnrepository.com/artifact/com.sun.mail/jakarta.mail
api("com.sun.mail:jakarta.mail:2.0.1")
// https://www.spigotmc.org/resources/nbt-api.7939/ // https://www.spigotmc.org/resources/nbt-api.7939/
implementation("de.tr7zw:item-nbt-api:2.12.2") implementation("de.tr7zw:item-nbt-api:2.12.2")
// https://mvnrepository.com/artifact/com.zaxxer/HikariCP // https://mvnrepository.com/artifact/com.zaxxer/HikariCP
implementation("com.zaxxer:HikariCP:4.0.3") { exclude(group = "org.slf4j") } implementation("com.zaxxer:HikariCP:4.0.3") { exclude(group = "org.slf4j") }
// https://mvnrepository.com/artifact/org.jetbrains.kotlin/kotlin-stdlib
shade("org.jetbrains.kotlin:kotlin-stdlib:1.9.23") { exclude(group = "org.jetbrains") }
// https://mvnrepository.com/artifact/org.jetbrains.kotlin/kotlin-stdlib-jdk8 // https://mvnrepository.com/artifact/org.jetbrains.kotlin/kotlin-stdlib-jdk8
shadeJava8("org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.9.23") { exclude(group = "org.jetbrains") } implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.9.23") { exclude(group = "org.jetbrains") }
} }
tasks { tasks {
@@ -52,23 +46,8 @@ tasks {
archiveBaseName = "HamsterCore-Bukkit" archiveBaseName = "HamsterCore-Bukkit"
} }
shadowJar { shadowJar {
from(shade.map { if (it.isDirectory) it else zipTree(it) })
destinationDirectory = rootProject.layout.buildDirectory destinationDirectory = rootProject.layout.buildDirectory
relocate("de.tr7zw.changeme.nbtapi", "cn.hamster3.mc.plugin.core.lib.de.tr7zw.nbtapi") relocate("de.tr7zw.changeme.nbtapi", "cn.hamster3.mc.plugin.core.lib.de.tr7zw.nbtapi")
relocate("de.tr7zw.annotations", "cn.hamster3.mc.plugin.core.lib.de.tr7zw.nbtapi.annotations") relocate("de.tr7zw.annotations", "cn.hamster3.mc.plugin.core.lib.de.tr7zw.nbtapi.annotations")
} }
val shadowJava8 = register<ShadowJar>("shadowJava8") {
dependsOn(":core-common:build")
archiveClassifier = "Java8"
from(project.configurations.runtimeClasspath.get().map { if (it.isDirectory) it else zipTree(it) })
from(processResources.get().outputs)
from(jar.get().outputs)
from(shadeJava8.map { if (it.isDirectory) it else zipTree(it) })
destinationDirectory = rootProject.layout.buildDirectory
relocate("de.tr7zw.changeme.nbtapi", "cn.hamster3.mc.plugin.core.lib.de.tr7zw.nbtapi")
relocate("de.tr7zw.annotations", "cn.hamster3.mc.plugin.core.lib.de.tr7zw.nbtapi.annotations")
}
build {
dependsOn(shadowJava8)
}
} }

View File

@@ -13,6 +13,7 @@ import cn.hamster3.mc.plugin.core.bukkit.page.handler.PageHandler;
import cn.hamster3.mc.plugin.core.bukkit.page.listener.PageListener; import cn.hamster3.mc.plugin.core.bukkit.page.listener.PageListener;
import cn.hamster3.mc.plugin.core.bukkit.util.MinecraftVersion; import cn.hamster3.mc.plugin.core.bukkit.util.MinecraftVersion;
import cn.hamster3.mc.plugin.core.common.api.CoreAPI; import cn.hamster3.mc.plugin.core.common.api.CoreAPI;
import cn.hamster3.mc.plugin.core.common.config.ConfigSection;
import cn.hamster3.mc.plugin.core.common.config.YamlConfig; import cn.hamster3.mc.plugin.core.common.config.YamlConfig;
import cn.hamster3.mc.plugin.core.common.util.UpdateCheckUtils; import cn.hamster3.mc.plugin.core.common.util.UpdateCheckUtils;
import lombok.Getter; import lombok.Getter;
@@ -27,7 +28,6 @@ import org.bukkit.scheduler.BukkitTask;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import java.io.File; import java.io.File;
import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.InputStreamReader; import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
@@ -35,7 +35,6 @@ import java.nio.file.Files;
import java.nio.file.StandardCopyOption; import java.nio.file.StandardCopyOption;
import java.util.logging.Logger; import java.util.logging.Logger;
@SuppressWarnings("CallToPrintStackTrace")
public class HamsterCorePlugin extends JavaPlugin { public class HamsterCorePlugin extends JavaPlugin {
@Getter @Getter
private static HamsterCorePlugin instance; private static HamsterCorePlugin instance;
@@ -117,21 +116,7 @@ public class HamsterCorePlugin extends JavaPlugin {
sync(() -> { sync(() -> {
PointAPI.reloadPlayerPointAPIHook(); PointAPI.reloadPlayerPointAPIHook();
VaultAPI.reloadVaultHook(); VaultAPI.reloadVaultHook();
async(() -> { async(this::checkUpdate);
for (Plugin plugin : Bukkit.getPluginManager().getPlugins()) {
try (InputStream stream = plugin.getResource("update.yml")) {
if (stream == null) {
continue;
}
try (InputStreamReader reader = new InputStreamReader(stream, StandardCharsets.UTF_8)) {
YamlConfig config = YamlConfig.load(reader);
UpdateCheckUtils.showUpdate(plugin.getName(), config, Bukkit.getConsoleSender()::sendMessage);
}
} catch (IOException ignored) {
}
}
});
}); });
logger.info("仓鼠核心启动完成,总计耗时 " + time + " ms"); logger.info("仓鼠核心启动完成,总计耗时 " + time + " ms");
} }
@@ -160,4 +145,23 @@ public class HamsterCorePlugin extends JavaPlugin {
long time = System.currentTimeMillis() - start; long time = System.currentTimeMillis() - start;
logger.info("仓鼠核心已关闭,总计耗时 " + time + " ms"); logger.info("仓鼠核心已关闭,总计耗时 " + time + " ms");
} }
private void checkUpdate() {
for (Plugin plugin : Bukkit.getPluginManager().getPlugins()) {
try (InputStream stream = plugin.getResource("plugin.yml")) {
if (stream == null) {
continue;
}
try (InputStreamReader reader = new InputStreamReader(stream, StandardCharsets.UTF_8)) {
YamlConfig config = YamlConfig.load(reader);
ConfigSection section = config.getSection("UPDATE_CHECKER");
if (section == null) {
continue;
}
UpdateCheckUtils.checkUpdate(plugin.getName(), section);
}
} catch (Exception ignored) {
}
}
}
} }

View File

@@ -14,7 +14,6 @@ public class CoreCommand extends ParentCommand {
addChildCommand(GCCommand.INSTANCE); addChildCommand(GCCommand.INSTANCE);
addChildCommand(YamlCommand.INSTANCE); addChildCommand(YamlCommand.INSTANCE);
addChildCommand(InfoModeCommand.INSTANCE); addChildCommand(InfoModeCommand.INSTANCE);
addChildCommand(ReloadCommand.INSTANCE);
addChildCommand(MemoryCommand.INSTANCE); addChildCommand(MemoryCommand.INSTANCE);
addChildCommand(SystemCommand.INSTANCE); addChildCommand(SystemCommand.INSTANCE);
} }

View File

@@ -1,49 +0,0 @@
package cn.hamster3.mc.plugin.core.bukkit.command.core.sub;
import cn.hamster3.mc.plugin.core.bukkit.command.ChildCommand;
import cn.hamster3.mc.plugin.core.bukkit.page.PageManager;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.jetbrains.annotations.NotNull;
import java.util.Collections;
import java.util.List;
public class ReloadCommand extends ChildCommand {
public static final ReloadCommand INSTANCE = new ReloadCommand();
private ReloadCommand() {
}
@Override
public @NotNull String getName() {
return "reload";
}
@Override
public @NotNull String getUsage() {
return "reload";
}
@Override
public boolean hasPermission(@NotNull CommandSender sender) {
return true;
}
@Override
public @NotNull String getDescription() {
return "重载页面配置文件";
}
@Override
public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) {
PageManager.PAGE_CONFIG.clear();
sender.sendMessage("§a已重载页面配置文件");
return true;
}
@Override
public List<String> onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String alias, String[] args) {
return Collections.emptyList();
}
}

View File

@@ -7,7 +7,6 @@ import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.inventory.Inventory; import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryHolder; import org.bukkit.inventory.InventoryHolder;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.Plugin;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
@@ -18,8 +17,6 @@ import java.util.Map;
@SuppressWarnings("unused") @SuppressWarnings("unused")
public class PageConfig implements InventoryHolder { public class PageConfig implements InventoryHolder {
@NotNull
private final Plugin plugin;
@NotNull @NotNull
private final ConfigurationSection rawConfig; private final ConfigurationSection rawConfig;
@@ -38,8 +35,7 @@ public class PageConfig implements InventoryHolder {
@NotNull @NotNull
private final Inventory inventory; private final Inventory inventory;
public PageConfig(@NotNull Plugin plugin, @NotNull ConfigurationSection rawConfig) { public PageConfig(@NotNull ConfigurationSection rawConfig) {
this.plugin = plugin;
this.rawConfig = rawConfig; this.rawConfig = rawConfig;
title = rawConfig.getString("title", "").replace("&", "§"); title = rawConfig.getString("title", "").replace("&", "§");
@@ -163,11 +159,6 @@ public class PageConfig implements InventoryHolder {
throw new IllegalArgumentException("未找到名称为 " + groupName + " 的按钮编组"); throw new IllegalArgumentException("未找到名称为 " + groupName + " 的按钮编组");
} }
@NotNull
public Plugin getPlugin() {
return plugin;
}
@NotNull @NotNull
public ConfigurationSection getRawConfig() { public ConfigurationSection getRawConfig() {
return rawConfig; return rawConfig;

View File

@@ -1,61 +0,0 @@
package cn.hamster3.mc.plugin.core.bukkit.page;
import org.bukkit.Bukkit;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.plugin.Plugin;
import org.jetbrains.annotations.NotNull;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.HashMap;
public class PageManager {
public static final HashMap<String, PageConfig> PAGE_CONFIG = new HashMap<>();
@NotNull
public static PageConfig getPageConfig(@NotNull Class<?> clazz) {
PageConfig pageConfig = PAGE_CONFIG.get(clazz.getName());
if (pageConfig != null) {
return pageConfig;
}
if (!clazz.isAnnotationPresent(PluginPage.class)) {
throw new IllegalArgumentException(clazz.getName() + " 未被 @PluginPage 注解修饰");
}
PluginPage annotation = clazz.getAnnotation(PluginPage.class);
String pluginName = annotation.value();
Plugin plugin = Bukkit.getPluginManager().getPlugin(pluginName);
if (plugin == null) {
throw new IllegalArgumentException("未找到插件 " + pluginName + " ");
}
pageConfig = getPageConfig(plugin, clazz.getSimpleName());
PAGE_CONFIG.put(clazz.getName(), pageConfig);
return pageConfig;
}
@NotNull
public static PageConfig getPageConfig(@NotNull Plugin plugin, @NotNull String pageName) {
String pluginName = plugin.getName();
File pageFolder = new File(plugin.getDataFolder(), "pages");
if (pageFolder.mkdirs()) {
plugin.getLogger().info("创建页面配置文件夹");
}
String filename = pageName + ".yml";
File pageConfigFile = new File(pageFolder, filename);
if (pageConfigFile.exists()) {
YamlConfiguration config = YamlConfiguration.loadConfiguration(pageConfigFile);
return new PageConfig(plugin, config);
}
try (InputStream stream = plugin.getResource("pages/" + filename)) {
if (stream != null) {
Files.copy(stream, pageConfigFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
}
} catch (IOException e) {
throw new IllegalArgumentException("为插件 " + pluginName + " 加载页面配置文件 " + filename + " 时出错", e);
}
YamlConfiguration config = YamlConfiguration.loadConfiguration(pageConfigFile);
return new PageConfig(plugin, config);
}
}

View File

@@ -4,6 +4,7 @@ import cn.hamster3.mc.plugin.core.bukkit.page.ButtonGroup;
import cn.hamster3.mc.plugin.core.bukkit.page.PageConfig; import cn.hamster3.mc.plugin.core.bukkit.page.PageConfig;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.entity.HumanEntity; import org.bukkit.entity.HumanEntity;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import java.util.List; import java.util.List;
@@ -12,15 +13,11 @@ import java.util.List;
* 固定页面的 GUI * 固定页面的 GUI
*/ */
@SuppressWarnings("unused") @SuppressWarnings("unused")
public class FixedPageHandler extends PageHandler { public abstract class FixedPageHandler extends PageHandler {
public FixedPageHandler(@NotNull HumanEntity player) { public FixedPageHandler(@NotNull Player player) {
super(player); super(player);
} }
public FixedPageHandler(@NotNull PageConfig config, @NotNull HumanEntity player) {
super(config, player);
}
@Override @Override
public void initPage() { public void initPage() {
if (inventory == null) { if (inventory == null) {

View File

@@ -2,15 +2,17 @@ package cn.hamster3.mc.plugin.core.bukkit.page.handler;
import cn.hamster3.mc.plugin.core.bukkit.page.ButtonGroup; import cn.hamster3.mc.plugin.core.bukkit.page.ButtonGroup;
import cn.hamster3.mc.plugin.core.bukkit.page.PageConfig; import cn.hamster3.mc.plugin.core.bukkit.page.PageConfig;
import cn.hamster3.mc.plugin.core.bukkit.page.PageManager; import cn.hamster3.mc.plugin.core.bukkit.util.CoreBukkitUtils;
import lombok.Getter;
import me.clip.placeholderapi.PlaceholderAPI; import me.clip.placeholderapi.PlaceholderAPI;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.Sound; import org.bukkit.Sound;
import org.bukkit.entity.HumanEntity; import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.event.inventory.*; import org.bukkit.event.inventory.*;
import org.bukkit.inventory.Inventory; import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryHolder; import org.bukkit.inventory.InventoryHolder;
import org.bukkit.plugin.Plugin;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import java.util.HashMap; import java.util.HashMap;
@@ -20,21 +22,29 @@ import java.util.Map;
* GUI 处理类 * GUI 处理类
*/ */
@SuppressWarnings("unused") @SuppressWarnings("unused")
@Getter
public abstract class PageHandler implements InventoryHolder { public abstract class PageHandler implements InventoryHolder {
@NotNull
private final PageConfig pageConfig; private final PageConfig pageConfig;
private final HumanEntity player; @NotNull
private final Player player;
protected Inventory inventory; protected Inventory inventory;
public PageHandler(@NotNull HumanEntity player) { public PageHandler(@NotNull Player player) {
pageConfig = PageManager.getPageConfig(getClass()); pageConfig = loadPageConfig();
this.player = player; this.player = player;
} }
public PageHandler(@NotNull PageConfig pageConfig, @NotNull HumanEntity player) { @NotNull
this.pageConfig = pageConfig; public PageConfig loadPageConfig() {
this.player = player; String simpleName = getClass().getSimpleName();
YamlConfiguration config = CoreBukkitUtils.getPluginConfig(getPlugin(), "pages/" + simpleName + ".yml");
return new PageConfig(config);
} }
@NotNull
public abstract Plugin getPlugin();
public abstract void initPage(); public abstract void initPage();
public void onOpen(@NotNull InventoryOpenEvent event) { public void onOpen(@NotNull InventoryOpenEvent event) {
@@ -55,9 +65,6 @@ public abstract class PageHandler implements InventoryHolder {
} }
public void onPlayButtonSound(@NotNull ClickType clickType, @NotNull InventoryAction action, int index) { public void onPlayButtonSound(@NotNull ClickType clickType, @NotNull InventoryAction action, int index) {
if (!(player instanceof Player)) {
return;
}
PageConfig config = getPageConfig(); PageConfig config = getPageConfig();
String buttonName = getButtonGroup().getButtonName(index); String buttonName = getButtonGroup().getButtonName(index);
Sound sound = config.getButtonSound(buttonName); Sound sound = config.getButtonSound(buttonName);
@@ -73,7 +80,7 @@ public abstract class PageHandler implements InventoryHolder {
if (sound == null) { if (sound == null) {
return; return;
} }
((Player) player).playSound(player.getLocation(), sound, 1, 1); player.playSound(player.getLocation(), sound, 1, 1);
} }
public void onDrag(@NotNull InventoryDragEvent event) { public void onDrag(@NotNull InventoryDragEvent event) {
@@ -94,21 +101,11 @@ public abstract class PageHandler implements InventoryHolder {
if (init) { if (init) {
initPage(); initPage();
} }
Bukkit.getScheduler().runTask(pageConfig.getPlugin(), () -> player.openInventory(getInventory())); Bukkit.getScheduler().runTask(getPlugin(), () -> player.openInventory(getInventory()));
} }
public void close() { public void close() {
Bukkit.getScheduler().runTask(pageConfig.getPlugin(), player::closeInventory); Bukkit.getScheduler().runTask(getPlugin(), player::closeInventory);
}
@NotNull
public PageConfig getPageConfig() {
return pageConfig;
}
@NotNull
public HumanEntity getPlayer() {
return player;
} }
@NotNull @NotNull
@@ -118,9 +115,9 @@ public abstract class PageHandler implements InventoryHolder {
@NotNull @NotNull
public String getTitle() { public String getTitle() {
String title = pageConfig.getTitle(); String title = getPageConfig().getTitle();
if (player instanceof Player && Bukkit.getPluginManager().isPluginEnabled("PlaceholderAPI")) { if (Bukkit.getPluginManager().isPluginEnabled("PlaceholderAPI")) {
title = PlaceholderAPI.setPlaceholders((Player) player, title); title = PlaceholderAPI.setPlaceholders(player, title);
} }
for (Map.Entry<String, String> entry : getPageVariables().entrySet()) { for (Map.Entry<String, String> entry : getPageVariables().entrySet()) {
title = title.replace(entry.getKey(), entry.getValue()); title = title.replace(entry.getKey(), entry.getValue());

View File

@@ -46,24 +46,18 @@ public abstract class PageableHandler<E> extends FixedPageHandler {
@Getter @Getter
private int page; private int page;
public PageableHandler(@NotNull HumanEntity player) { public PageableHandler(@NotNull Player player) {
super(player); super(player);
this.page = 0; this.page = 0;
elementSlot = new HashMap<>(); elementSlot = new HashMap<>();
} }
public PageableHandler(@NotNull HumanEntity player, int page) { public PageableHandler(@NotNull Player player, int page) {
super(player); super(player);
this.page = page; this.page = page;
elementSlot = new HashMap<>(); elementSlot = new HashMap<>();
} }
public PageableHandler(@NotNull PageConfig config, @NotNull HumanEntity player, int page) {
super(config, player);
this.page = page;
elementSlot = new HashMap<>();
}
@NotNull @NotNull
public abstract List<E> getPageElements(); public abstract List<E> getPageElements();
@@ -95,10 +89,7 @@ public abstract class PageableHandler<E> extends FixedPageHandler {
@Override @Override
public void onPlayButtonSound(@NotNull ClickType clickType, @NotNull InventoryAction action, int index) { public void onPlayButtonSound(@NotNull ClickType clickType, @NotNull InventoryAction action, int index) {
HumanEntity player = getPlayer(); Player player = getPlayer();
if (!(player instanceof Player)) {
return;
}
PageConfig config = getPageConfig(); PageConfig config = getPageConfig();
String buttonName = getButtonGroup().getButtonName(index); String buttonName = getButtonGroup().getButtonName(index);
Sound sound = config.getButtonSound(buttonName); Sound sound = config.getButtonSound(buttonName);
@@ -120,7 +111,7 @@ public abstract class PageableHandler<E> extends FixedPageHandler {
if (sound == null) { if (sound == null) {
return; return;
} }
((Player) player).playSound(player.getLocation(), sound, 1, 1); player.playSound(player.getLocation(), sound, 1, 1);
} }
@Override @Override
@@ -177,14 +168,14 @@ public abstract class PageableHandler<E> extends FixedPageHandler {
for (Map.Entry<String, String> entry : variables.entrySet()) { for (Map.Entry<String, String> entry : variables.entrySet()) {
displayName = displayName.replace(entry.getKey(), entry.getValue()); displayName = displayName.replace(entry.getKey(), entry.getValue());
} }
if (player instanceof Player && Bukkit.getPluginManager().isPluginEnabled("PlaceholderAPI")) { if (Bukkit.getPluginManager().isPluginEnabled("PlaceholderAPI")) {
displayName = PlaceholderAPI.setPlaceholders((OfflinePlayer) player, displayName); displayName = PlaceholderAPI.setPlaceholders((OfflinePlayer) player, displayName);
} }
meta.setDisplayName(displayName); meta.setDisplayName(displayName);
} }
List<String> lore = meta.getLore(); List<String> lore = meta.getLore();
if (lore != null) { if (lore != null) {
if (player instanceof Player && Bukkit.getPluginManager().isPluginEnabled("PlaceholderAPI")) { if (Bukkit.getPluginManager().isPluginEnabled("PlaceholderAPI")) {
lore.replaceAll(s -> { lore.replaceAll(s -> {
for (Map.Entry<String, String> entry : variables.entrySet()) { for (Map.Entry<String, String> entry : variables.entrySet()) {
s = s.replace(entry.getKey(), entry.getValue()); s = s.replace(entry.getKey(), entry.getValue());

View File

@@ -9,15 +9,12 @@
redis-url: "redis://localhost:6379/0?clientName=HamsterCore&timeout=5s" redis-url: "redis://localhost:6379/0?clientName=HamsterCore&timeout=5s"
datasource: datasource:
# 数据库链接驱动地址 # 数据库链接驱动地址旧版服务端低于1.13请使用com.mysql.jdbc.Driver
# 除非你知道自己在做什么,否则不建议更改该项
# 旧版服务端低于1.13请使用com.mysql.jdbc.Driver
driver: "com.mysql.cj.jdbc.Driver" driver: "com.mysql.cj.jdbc.Driver"
# 数据库链接填写格式: # MySQL数据库链接填写格式:
# jdbc:mysql://{数据库地址}:{数据库端口}/{使用的库名}?参数 # jdbc:mysql://{数据库地址}:{数据库端口}/{使用的库名}?参数
# 除非你知道自己在做什么,否则不建议随意更改参数
url: "jdbc:mysql://localhost:3306/Test?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf8&autoReconnect=true&useSSL=false&allowPublicKeyRetrieval=true" url: "jdbc:mysql://localhost:3306/Test?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf8&autoReconnect=true&useSSL=false&allowPublicKeyRetrieval=true"
# 如果你不需要做多端跨服,那么请使用 sqlite 作本地数据库 # 如果你不需要做多端跨服,那么请使用 sqlite 作本地数据库
# driver: "org.sqlite.JDBC" # driver: "org.sqlite.JDBC"
# url: "jdbc:sqlite:./plugins/HamsterCore/database.db" # url: "jdbc:sqlite:./plugins/HamsterCore/database.db"
# 用户名 # 用户名

View File

@@ -4,8 +4,15 @@ version: ${version}
api-version: 1.13 api-version: 1.13
author: MiniDay author: MiniDay
description: ${description}
website: https://git.airgame.net/MiniDay/hamster-core website: https://git.airgame.net/MiniDay/hamster-core
description: 仓鼠核心:叁只仓鼠的 Minecraft 插件开发通用工具包
UPDATE_CHECKER:
VERSION: ${version}
CHECK_TYPE: GITEA_RELEASES
GIT_BASE_URL: https://git.airgame.net
GIT_REPO: MiniDay/hamster-core
DOWNLOAD_URL: https://jenkins.airgame.net/job/opensource/job/hamster-core/
load: STARTUP load: STARTUP

View File

@@ -1,6 +0,0 @@
version: ${version}
CHECK_TYPE: GITEA_RELEASES
GIT_BASE_URL: https://git.airgame.net
GIT_REPO: MiniDay/hamster-core
GIT_TOKEN: a44a69a4d1b8601bf6091403247759cd28764d5e
DOWNLOAD_URL: https://jenkins.airgame.net/job/opensource/job/hamster-core/

View File

@@ -1,12 +1,7 @@
@file:Suppress("VulnerableLibrariesLocal") @file:Suppress("VulnerableLibrariesLocal")
import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar
evaluationDependsOn(":core-common") evaluationDependsOn(":core-common")
val shade = configurations.create("shade")
val shadeJava8 = configurations.create("shadeJava8")
dependencies { dependencies {
api(project(":core-common")) { isTransitive = false } api(project(":core-common")) { isTransitive = false }
compileOnly("net.md-5:bungeecord-api:1.20-R0.1") compileOnly("net.md-5:bungeecord-api:1.20-R0.1")
@@ -26,13 +21,12 @@ dependencies {
} }
// https://mvnrepository.com/artifact/org.quartz-scheduler/quartz // https://mvnrepository.com/artifact/org.quartz-scheduler/quartz
api("org.quartz-scheduler:quartz:2.3.2") { isTransitive = false } api("org.quartz-scheduler:quartz:2.3.2") { isTransitive = false }
// https://mvnrepository.com/artifact/com.sun.mail/jakarta.mail
api("com.sun.mail:jakarta.mail:2.0.1")
implementation("com.zaxxer:HikariCP:4.0.3") { exclude(group = "org.slf4j") } implementation("com.zaxxer:HikariCP:4.0.3") { exclude(group = "org.slf4j") }
// https://mvnrepository.com/artifact/org.jetbrains.kotlin/kotlin-stdlib
shade("org.jetbrains.kotlin:kotlin-stdlib:1.9.23") { exclude(group = "org.jetbrains") }
// https://mvnrepository.com/artifact/org.jetbrains.kotlin/kotlin-stdlib-jdk8 // https://mvnrepository.com/artifact/org.jetbrains.kotlin/kotlin-stdlib-jdk8
shadeJava8("org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.9.23") { exclude(group = "org.jetbrains") } implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.9.23") { exclude(group = "org.jetbrains") }
} }
tasks { tasks {
@@ -45,23 +39,6 @@ tasks {
archiveBaseName = "HamsterCore-BungeeCord" archiveBaseName = "HamsterCore-BungeeCord"
} }
shadowJar { shadowJar {
from(shade.map { if (it.isDirectory) it else zipTree(it) })
destinationDirectory = rootProject.layout.buildDirectory destinationDirectory = rootProject.layout.buildDirectory
} }
shadowJar {
from(shade.map { if (it.isDirectory) it else zipTree(it) })
destinationDirectory = rootProject.layout.buildDirectory
}
val shadowJava8 = register<ShadowJar>("shadowJava8") {
dependsOn(":core-common:build")
archiveClassifier = "Java8"
from(project.configurations.runtimeClasspath.get().map { if (it.isDirectory) it else zipTree(it) })
from(processResources.get().outputs)
from(jar.get().outputs)
from(shadeJava8.map { if (it.isDirectory) it else zipTree(it) })
destinationDirectory = rootProject.layout.buildDirectory
}
build {
dependsOn(shadowJava8)
}
} }

View File

@@ -2,12 +2,12 @@ package cn.hamster3.mc.plugin.core.bungee;
import cn.hamster3.mc.plugin.core.bungee.api.CoreBungeeAPI; import cn.hamster3.mc.plugin.core.bungee.api.CoreBungeeAPI;
import cn.hamster3.mc.plugin.core.common.api.CoreAPI; import cn.hamster3.mc.plugin.core.common.api.CoreAPI;
import cn.hamster3.mc.plugin.core.common.config.ConfigSection;
import cn.hamster3.mc.plugin.core.common.config.YamlConfig; import cn.hamster3.mc.plugin.core.common.config.YamlConfig;
import cn.hamster3.mc.plugin.core.common.util.UpdateCheckUtils; import cn.hamster3.mc.plugin.core.common.util.UpdateCheckUtils;
import lombok.Getter; import lombok.Getter;
import net.kyori.adventure.platform.bungeecord.BungeeAudiences; import net.kyori.adventure.platform.bungeecord.BungeeAudiences;
import net.md_5.bungee.api.ProxyServer; import net.md_5.bungee.api.ProxyServer;
import net.md_5.bungee.api.chat.TextComponent;
import net.md_5.bungee.api.plugin.Plugin; import net.md_5.bungee.api.plugin.Plugin;
import java.io.File; import java.io.File;
@@ -62,26 +62,9 @@ public class HamsterCorePlugin extends Plugin {
logger.info("仓鼠核心正在启动"); logger.info("仓鼠核心正在启动");
audienceProvider = BungeeAudiences.create(this); audienceProvider = BungeeAudiences.create(this);
logger.info("已创建 AudienceProvider"); logger.info("已创建 AudienceProvider");
CoreAPI.getInstance().getExecutorService().submit(this::checkUpdate);
long time = System.currentTimeMillis() - start; long time = System.currentTimeMillis() - start;
logger.info("仓鼠核心启动完成,总计耗时 " + time + " ms"); logger.info("仓鼠核心启动完成,总计耗时 " + time + " ms");
CoreAPI.getInstance().getExecutorService().submit(() -> {
for (Plugin plugin : ProxyServer.getInstance().getPluginManager().getPlugins()) {
try (InputStream stream = plugin.getResourceAsStream("update.yml")) {
if (stream == null) {
continue;
}
try (InputStreamReader reader = new InputStreamReader(stream, StandardCharsets.UTF_8)) {
YamlConfig config = YamlConfig.load(reader);
UpdateCheckUtils.showUpdate(
plugin.getDescription().getName(), config,
(s) -> ProxyServer.getInstance().getConsole().sendMessage(TextComponent.fromLegacyText(s))
);
}
} catch (IOException ignored) {
}
}
});
} }
@Override @Override
@@ -99,4 +82,23 @@ public class HamsterCorePlugin extends Plugin {
long time = System.currentTimeMillis() - start; long time = System.currentTimeMillis() - start;
logger.info("仓鼠核心已关闭,总计耗时 " + time + " ms"); logger.info("仓鼠核心已关闭,总计耗时 " + time + " ms");
} }
private void checkUpdate() {
for (Plugin plugin : ProxyServer.getInstance().getPluginManager().getPlugins()) {
try (InputStream stream = plugin.getResourceAsStream("bungee.yml")) {
if (stream == null) {
continue;
}
try (InputStreamReader reader = new InputStreamReader(stream, StandardCharsets.UTF_8)) {
YamlConfig config = YamlConfig.load(reader);
ConfigSection section = config.getSection("UPDATE_CHECKER");
if (section == null) {
continue;
}
UpdateCheckUtils.checkUpdate(plugin.getDescription().getName(), section);
}
} catch (IOException ignored) {
}
}
}
} }

View File

@@ -3,4 +3,12 @@ main: cn.hamster3.mc.plugin.core.bungee.HamsterCorePlugin
version: ${version} version: ${version}
author: MiniDay author: MiniDay
description: 仓鼠核心:叁只仓鼠的 Minecraft 插件开发通用工具包 description: ${description}
website: https://git.airgame.net/MiniDay/hamster-core
UPDATE_CHECKER:
VERSION: ${version}
CHECK_TYPE: GITEA_RELEASES
GIT_BASE_URL: https://git.airgame.net
GIT_REPO: MiniDay/hamster-core
DOWNLOAD_URL: https://jenkins.airgame.net/job/opensource/job/hamster-core/

View File

@@ -10,11 +10,9 @@ redis-url: "redis://localhost:6379/0?clientName=HamsterCore&timeout=5s"
datasource: datasource:
# 数据库链接驱动地址 # 数据库链接驱动地址
# 除非你知道自己在做什么,否则不建议更改该项
driver: "com.mysql.cj.jdbc.Driver" driver: "com.mysql.cj.jdbc.Driver"
# 数据库链接填写格式: # MySQL数据库链接填写格式:
# jdbc:mysql://{数据库地址}:{数据库端口}/{使用的库名}?参数 # jdbc:mysql://{数据库地址}:{数据库端口}/{使用的库名}?参数
# 除非你知道自己在做什么,否则不建议随意更改参数
url: "jdbc:mysql://localhost:3306/Test?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf8&autoReconnect=true&useSSL=false&allowPublicKeyRetrieval=true" url: "jdbc:mysql://localhost:3306/Test?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf8&autoReconnect=true&useSSL=false&allowPublicKeyRetrieval=true"
# 用户名 # 用户名
username: "root" username: "root"

View File

@@ -1,6 +0,0 @@
version: ${version}
CHECK_TYPE: GITEA_RELEASES
GIT_BASE_URL: https://git.airgame.net
GIT_REPO: MiniDay/hamster-core
GIT_TOKEN: a44a69a4d1b8601bf6091403247759cd28764d5e
DOWNLOAD_URL: https://jenkins.airgame.net/job/opensource/job/hamster-core/

View File

@@ -12,6 +12,10 @@ dependencies {
exclude(group = "org.jetbrains") exclude(group = "org.jetbrains")
exclude(group = "com.google.code.gson") exclude(group = "com.google.code.gson")
} }
compileOnlyApi("net.kyori:adventure-text-serializer-legacy:4.13.1") {
exclude(group = "org.jetbrains")
exclude(group = "com.google.code.gson")
}
// https://mvnrepository.com/artifact/redis.clients/jedis // https://mvnrepository.com/artifact/redis.clients/jedis
compileOnlyApi("redis.clients:jedis:5.1.2") { compileOnlyApi("redis.clients:jedis:5.1.2") {
@@ -19,6 +23,8 @@ dependencies {
exclude(group = "org.slf4j") exclude(group = "org.slf4j")
} }
compileOnlyApi("org.quartz-scheduler:quartz:2.3.2") { isTransitive = false } compileOnlyApi("org.quartz-scheduler:quartz:2.3.2") { isTransitive = false }
// https://mvnrepository.com/artifact/com.sun.mail/jakarta.mail
compileOnlyApi("com.sun.mail:jakarta.mail:2.0.1")
// https://mvnrepository.com/artifact/com.zaxxer/HikariCP // https://mvnrepository.com/artifact/com.zaxxer/HikariCP
compileOnly("com.zaxxer:HikariCP:4.0.3") { isTransitive = false } compileOnly("com.zaxxer:HikariCP:4.0.3") { isTransitive = false }

View File

@@ -29,7 +29,7 @@ public abstract class CoreAPI {
@NotNull @NotNull
private final JedisPool jedisPool; private final JedisPool jedisPool;
/** /**
* HamsterCore 公用数据库连接池 * 公用数据库连接池
*/ */
@Getter @Getter
@NotNull @NotNull
@@ -63,7 +63,7 @@ public abstract class CoreAPI {
} }
/** /**
* 获取 HamsterCore 公用数据库连接池 * 获取公用数据库连接池
* *
* @return 公用数据库连接池 * @return 公用数据库连接池
*/ */
@@ -73,7 +73,7 @@ public abstract class CoreAPI {
} }
/** /**
* 获取 HamsterCore 公用数据库连接 * 获取公用数据库连接
* *
* @return 公用数据库连接 * @return 公用数据库连接
* @throws SQLException - * @throws SQLException -

View File

@@ -1,10 +1,13 @@
package cn.hamster3.mc.plugin.core.common.util; package cn.hamster3.mc.plugin.core.common.util;
import cn.hamster3.mc.plugin.core.common.api.CoreAPI;
import cn.hamster3.mc.plugin.core.common.config.ConfigSection; import cn.hamster3.mc.plugin.core.common.config.ConfigSection;
import com.google.gson.JsonArray; import com.google.gson.JsonArray;
import com.google.gson.JsonElement; import com.google.gson.JsonElement;
import com.google.gson.JsonObject; import com.google.gson.JsonObject;
import com.google.gson.JsonParser; import com.google.gson.JsonParser;
import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
@@ -14,6 +17,9 @@ import java.io.InputStreamReader;
import java.net.HttpURLConnection; import java.net.HttpURLConnection;
import java.net.URL; import java.net.URL;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public final class UpdateCheckUtils { public final class UpdateCheckUtils {
private static final JsonParser JSON_PARSER = new JsonParser(); private static final JsonParser JSON_PARSER = new JsonParser();
@@ -21,59 +27,66 @@ public final class UpdateCheckUtils {
private UpdateCheckUtils() { private UpdateCheckUtils() {
} }
public static void showUpdate(@NotNull String pluginName, @NotNull ConfigSection config, @NotNull UpdateReceiver sender) { public static void checkUpdate(@NotNull String pluginName, @NotNull ConfigSection updateConfig) throws IOException {
String version = config.getString("version"); checkUpdate(pluginName, updateConfig, CoreAPI.getInstance().getAudienceProvider().console());
if (version == null) { }
public static void checkUpdate(@NotNull String pluginName, @NotNull ConfigSection updateConfig, @NotNull Audience sender) throws IOException {
String version = updateConfig.getString("VERSION", "");
String checkType = updateConfig.getString("CHECK_TYPE", "");
String baseUrl = updateConfig.getString("GIT_BASE_URL");
String gitRepo = updateConfig.getString("GIT_REPO");
String downloadUrl = updateConfig.getString("DOWNLOAD_URL");
if (baseUrl == null || gitRepo == null) {
return; return;
} }
String checkType = config.getString("CHECK_TYPE", ""); String gitToken = updateConfig.getString("GIT_TOKEN");
try { String lastRelease = null;
switch (checkType) { switch (checkType) {
case "GITEA_RELEASES": { case "GITEA_RELEASES": {
String baseUrl = config.getString("GIT_BASE_URL"); lastRelease = getGiteaLastRelease(baseUrl, gitRepo, gitToken);
String gitRepo = config.getString("GIT_REPO");
String downloadUrl = config.getString("DOWNLOAD_URL");
if (baseUrl == null || gitRepo == null || downloadUrl == null) {
return;
}
String gitToken = config.getString("GIT_TOKEN");
String lastRelease = getGiteaLastRelease(baseUrl, gitRepo, gitToken);
if (lastRelease == null) {
break;
}
if (lastRelease.compareToIgnoreCase(version) <= 0) {
break;
}
sender.sendMessage(String.format("§a插件 §l%s§a 发布了新版本 %s", pluginName, lastRelease));
sender.sendMessage(String.format("§b下载链接: §n%s", downloadUrl));
break; break;
} }
case "GITLAB_RELEASES": { case "GITLAB_RELEASES": {
String baseUrl = config.getString("GIT_BASE_URL");
String gitRepo = config.getString("GIT_REPO");
String downloadUrl = config.getString("DOWNLOAD_URL");
if (baseUrl == null || gitRepo == null || downloadUrl == null) {
return;
}
String gitToken = config.getString("GIT_TOKEN");
int projectID = getGitlabProjectID(baseUrl, gitRepo, gitToken); int projectID = getGitlabProjectID(baseUrl, gitRepo, gitToken);
if (projectID < 0) { if (projectID < 0) {
break; break;
} }
String lastRelease = getGitlabLastRelease(baseUrl, projectID, gitToken); lastRelease = getGitlabLastRelease(baseUrl, projectID, gitToken);
break;
}
}
if (lastRelease == null) { if (lastRelease == null) {
break; return;
} }
if (lastRelease.compareToIgnoreCase(version) <= 0) { if (compareVersion(lastRelease, version) <= 0) {
break; return;
} }
sender.sendMessage(String.format("§a插件 §l%s§a 发布了新版本 %s", pluginName, lastRelease)); sender.sendMessage(LegacyComponentSerializer.legacySection().deserialize(
sender.sendMessage(String.format("§b下载链接: §n%s", downloadUrl)); String.format("§a插件 §l%s§a 发布了新版本 %s", pluginName, lastRelease)
break; ));
if (downloadUrl != null) {
sender.sendMessage(LegacyComponentSerializer.legacySection().deserialize("§b下载链接: §n" + downloadUrl));
} }
} }
} catch (Exception ignored) {
public static int compareVersion(@NotNull String version1, String version2) {
List<Integer> collect1 = Arrays.stream(version1.split("[+-]")[0].split("\\."))
.map(Integer::parseInt).collect(Collectors.toList());
List<Integer> collect2 = Arrays.stream(version2.split("[+-]")[0].split("\\."))
.map(Integer::parseInt).collect(Collectors.toList());
int max = Math.max(collect1.size(), collect2.size());
for (int i = 0; i < max; i++) {
int v1 = i < collect1.size() ? collect1.get(i) : 0;
int v2 = i < collect2.size() ? collect2.get(i) : 0;
if (v1 > v2) {
return 1;
} }
if (v1 < v2) {
return -1;
}
}
return 0;
} }
@Nullable @Nullable
@@ -103,12 +116,12 @@ public final class UpdateCheckUtils {
} }
public static int getGitlabProjectID(@NotNull String baseUrl, @NotNull String repo, @Nullable String token) throws IOException { public static int getGitlabProjectID(@NotNull String baseUrl, @NotNull String repo, @Nullable String token) throws IOException {
URL url = new URL("https://" + baseUrl + "/api/v4/projects?search=" + repo); URL url = new URL(baseUrl + "/api/v4/projects?search=" + repo);
HttpURLConnection connection = (HttpURLConnection) url.openConnection(); HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true); connection.setDoInput(true);
connection.setRequestMethod("GET"); connection.setRequestMethod("GET");
if (token != null) { if (token != null) {
connection.setRequestProperty("PRIVATE-TOKEN", "token " + token); connection.setRequestProperty("PRIVATE-TOKEN", token);
} }
connection.connect(); connection.connect();
try (InputStream stream = connection.getInputStream()) { try (InputStream stream = connection.getInputStream()) {
@@ -130,7 +143,7 @@ public final class UpdateCheckUtils {
connection.setDoInput(true); connection.setDoInput(true);
connection.setRequestMethod("GET"); connection.setRequestMethod("GET");
if (token != null) { if (token != null) {
connection.setRequestProperty("Authorization", "token " + token); connection.setRequestProperty("PRIVATE-TOKEN", token);
} }
connection.connect(); connection.connect();
try (InputStream stream = connection.getInputStream()) { try (InputStream stream = connection.getInputStream()) {
@@ -140,8 +153,4 @@ public final class UpdateCheckUtils {
} }
} }
} }
public interface UpdateReceiver {
void sendMessage(@NotNull String message);
}
} }

View File

@@ -15,6 +15,8 @@ dependencies {
} }
// https://mvnrepository.com/artifact/org.quartz-scheduler/quartz // https://mvnrepository.com/artifact/org.quartz-scheduler/quartz
api("org.quartz-scheduler:quartz:2.3.2") { isTransitive = false } api("org.quartz-scheduler:quartz:2.3.2") { isTransitive = false }
// https://mvnrepository.com/artifact/com.sun.mail/jakarta.mail
api("com.sun.mail:jakarta.mail:2.0.1")
// https://mvnrepository.com/artifact/com.zaxxer/HikariCP // https://mvnrepository.com/artifact/com.zaxxer/HikariCP
implementation("com.zaxxer:HikariCP:5.1.0") { isTransitive = false } implementation("com.zaxxer:HikariCP:5.1.0") { isTransitive = false }

View File

@@ -15,11 +15,9 @@ import com.velocitypowered.api.plugin.annotation.DataDirectory;
import com.velocitypowered.api.proxy.ProxyServer; import com.velocitypowered.api.proxy.ProxyServer;
import com.zaxxer.hikari.HikariDataSource; import com.zaxxer.hikari.HikariDataSource;
import lombok.Getter; import lombok.Getter;
import net.kyori.adventure.text.Component;
import org.slf4j.Logger; import org.slf4j.Logger;
import java.io.File; import java.io.File;
import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.InputStreamReader; import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
@@ -72,39 +70,16 @@ public class HamsterCorePlugin {
slf4jLogger.error("初始化 CoreAPI 出错", e); slf4jLogger.error("初始化 CoreAPI 出错", e);
} }
long time = System.currentTimeMillis() - start; long time = System.currentTimeMillis() - start;
slf4jLogger.info("HamsterCore 初始化完成,总计耗时 " + time + " ms"); slf4jLogger.info("仓鼠核心初始化完成,总计耗时 " + time + " ms");
} }
@Subscribe(order = PostOrder.FIRST) @Subscribe(order = PostOrder.FIRST)
public void onProxyInitialization(ProxyInitializeEvent event) { public void onProxyInitialization(ProxyInitializeEvent event) {
long start = System.currentTimeMillis(); long start = System.currentTimeMillis();
slf4jLogger.info("仓鼠核心正在启动"); slf4jLogger.info("仓鼠核心正在启动");
CoreAPI.getInstance().getExecutorService().submit(this::checkUpdate);
long time = System.currentTimeMillis() - start; long time = System.currentTimeMillis() - start;
slf4jLogger.info("仓鼠核心启动完成,总计耗时 " + time + " ms"); slf4jLogger.info("仓鼠核心启动完成,总计耗时 " + time + " ms");
CoreAPI.getInstance().getExecutorService().submit(() -> {
for (PluginContainer plugin : proxyServer.getPluginManager().getPlugins()) {
String pluginName = plugin.getDescription().getName().orElse(null);
if (pluginName == null) {
continue;
}
Object pluginObject = plugin.getInstance().orElse(null);
if (pluginObject == null) {
continue;
}
try (InputStream stream = pluginObject.getClass().getResourceAsStream("/update.yml")) {
if (stream == null) {
continue;
}
try (InputStreamReader reader = new InputStreamReader(stream, StandardCharsets.UTF_8)) {
YamlConfig config = YamlConfig.load(reader);
UpdateCheckUtils.showUpdate(pluginName, config, (s) -> proxyServer.sendMessage(Component.text(s)));
} catch (IOException ignored) {
}
} catch (IOException e) {
e.printStackTrace();
}
}
});
} }
@Subscribe(order = PostOrder.LAST) @Subscribe(order = PostOrder.LAST)
@@ -121,6 +96,29 @@ public class HamsterCorePlugin {
CoreAPI.getInstance().getScheduledService().shutdownNow(); CoreAPI.getInstance().getScheduledService().shutdownNow();
slf4jLogger.info("已关闭 ScheduledExecutorService 线程池"); slf4jLogger.info("已关闭 ScheduledExecutorService 线程池");
long time = System.currentTimeMillis() - start; long time = System.currentTimeMillis() - start;
slf4jLogger.info("HamsterCore 关闭完成,总计耗时 " + time + " ms"); slf4jLogger.info("仓鼠核心关闭完成,总计耗时 " + time + " ms");
}
private void checkUpdate() {
for (PluginContainer plugin : proxyServer.getPluginManager().getPlugins()) {
String pluginName = plugin.getDescription().getName().orElse(null);
if (pluginName == null) {
continue;
}
Object pluginObject = plugin.getInstance().orElse(null);
if (pluginObject == null) {
continue;
}
try (InputStream stream = pluginObject.getClass().getResourceAsStream("/update.yml")) {
if (stream == null) {
continue;
}
try (InputStreamReader reader = new InputStreamReader(stream, StandardCharsets.UTF_8)) {
YamlConfig config = YamlConfig.load(reader);
UpdateCheckUtils.checkUpdate(pluginName, config);
}
} catch (Exception ignored) {
}
}
} }
} }

View File

@@ -7,9 +7,9 @@ import cn.hamster3.mc.plugin.core.common.data.DisplayMessage;
import cn.hamster3.mc.plugin.core.common.impl.ComponentTypeAdapter; import cn.hamster3.mc.plugin.core.common.impl.ComponentTypeAdapter;
import cn.hamster3.mc.plugin.core.common.impl.MessageTypeAdapter; import cn.hamster3.mc.plugin.core.common.impl.MessageTypeAdapter;
import cn.hamster3.mc.plugin.core.velocity.HamsterCorePlugin; import cn.hamster3.mc.plugin.core.velocity.HamsterCorePlugin;
import cn.hamster3.mc.plugin.core.velocity.impl.AudienceProviderImpl;
import com.google.gson.Gson; import com.google.gson.Gson;
import com.google.gson.GsonBuilder; import com.google.gson.GsonBuilder;
import cn.hamster3.mc.plugin.core.velocity.impl.AudienceProviderImpl;
import net.kyori.adventure.platform.AudienceProvider; import net.kyori.adventure.platform.AudienceProvider;
import net.kyori.adventure.text.Component; import net.kyori.adventure.text.Component;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;

View File

@@ -10,16 +10,10 @@ redis-url: "redis://localhost:6379/0?clientName=HamsterCore&timeout=5s"
datasource: datasource:
# 数据库链接驱动地址 # 数据库链接驱动地址
# 除非你知道自己在做什么,否则不建议更改该项
# 旧版服务端低于1.13请使用com.mysql.jdbc.Driver
driver: "com.mysql.cj.jdbc.Driver" driver: "com.mysql.cj.jdbc.Driver"
# 数据库链接填写格式: # MySQL数据库链接填写格式:
# jdbc:mysql://{数据库地址}:{数据库端口}/{使用的库名}?参数 # jdbc:mysql://{数据库地址}:{数据库端口}/{使用的库名}?参数
# 除非你知道自己在做什么,否则不建议随意更改参数
url: "jdbc:mysql://localhost:3306/Test?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf8&autoReconnect=true&useSSL=false&allowPublicKeyRetrieval=true" url: "jdbc:mysql://localhost:3306/Test?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf8&autoReconnect=true&useSSL=false&allowPublicKeyRetrieval=true"
# 如果你不需要做多端跨服,那么请使用 sqlite 作本地数据库
# driver: "org.sqlite.JDBC"
# url: "jdbc:sqlite:./plugins/HamsterCore/database.db"
# 用户名 # 用户名
username: "root" username: "root"
# 密码 # 密码
@@ -28,8 +22,8 @@ datasource:
# 推荐值1~3 # 推荐值1~3
minimum-idle: 0 minimum-idle: 0
# 最大链接数 # 最大链接数
# 推荐值:不低于3 # 推荐值:不低于5
maximum-pool-size: 3 maximum-pool-size: 5
# 保持连接池可用的间隔 # 保持连接池可用的间隔
# 除非你的服务器数据库连接经常断开,否则不建议启用该选项 # 除非你的服务器数据库连接经常断开,否则不建议启用该选项
# 单位:毫秒 # 单位:毫秒

View File

@@ -1,6 +1,5 @@
version: ${version} VERSION: ${version}
CHECK_TYPE: GITEA_RELEASES CHECK_TYPE: GITEA_RELEASES
GIT_BASE_URL: https://git.airgame.net GIT_BASE_URL: https://git.airgame.net
GIT_REPO: MiniDay/hamster-core GIT_REPO: MiniDay/hamster-core
GIT_TOKEN: a44a69a4d1b8601bf6091403247759cd28764d5e
DOWNLOAD_URL: https://jenkins.airgame.net/job/opensource/job/hamster-core/ DOWNLOAD_URL: https://jenkins.airgame.net/job/opensource/job/hamster-core/