1
mirror of https://github.com/CarmJos/EasyPlugin.git synced 2026-06-05 00:58:17 +08:00

Compare commits

..

18 Commits

Author SHA1 Message Date
carm b5382a1cb3 chore(gui): 修改 GUIItemConfiguration 的读取与初始化方式 2022-07-01 20:01:50 +08:00
carm 77c035c2cb fix(main): 移除 isInitialized() 方法 (与部分服务端冲突) 2022-07-01 18:39:44 +08:00
carm fbf118436e feat(command): 指令部分新增基础方法 2022-06-26 10:34:06 +08:00
carm 572c22d2fc chore(pom): 移除无用条目 2022-06-18 05:38:13 +08:00
carm e416363751 fix(gui): 修复 GUIItemConfiguration 序列化错误的问题 2022-06-18 05:31:41 +08:00
carm 123e5463ad feat(main): 添加完整的构造方法用于测试 2022-06-18 04:40:35 +08:00
carm 65bc24d1e9 feat(storage): 为 StorageType 添加 DataStorage 泛型限制 2022-06-18 04:09:33 +08:00
carm 778235e8d1 feat(updater): 添加Github更新检查模块,方便获取基于Github发布的插件版本更新。 2022-06-18 03:04:30 +08:00
carm 120362f221 feat(updater): 添加Github更新检查模块,方便获取基于Github发布的插件版本更新。 2022-06-18 02:32:41 +08:00
carm 4c10a9798f feat(storage): 添加存储接口模块,包含存储相关的统一接口。 2022-06-18 02:32:08 +08:00
carm 558723ea82 chore(item): 添加序列化方法 2022-06-18 00:21:03 +08:00
carm b6bd4beda0 chore(item): 添加序列化方法 2022-06-18 00:16:02 +08:00
carm 7a06b39b31 feat(command): 新增可快捷return的消息方法。 2022-06-12 23:41:45 +08:00
carm 29fe7c3f76 feat(command): 新增可快捷return的消息方法。 2022-06-12 23:39:14 +08:00
carm 01b27e25bb feat(command): 新增可快捷return的消息方法。 2022-06-12 23:28:34 +08:00
carm 7e35f49e54 feat(main): 添加同步、异步与异步回调唤起事件的方法 2022-06-07 07:40:15 +08:00
carm 4dbcdfb02c ci(deploy): 简化部署流程 2022-06-03 03:45:29 +08:00
carm 9448c21810 docs(repo): 修改Github依赖地址 2022-05-30 04:24:35 +08:00
45 changed files with 1799 additions and 1317 deletions
+1 -1
View File
@@ -4,6 +4,6 @@
## 如何实现?
若您也想通过 [Github Actions](https://docs.github.com/en/actions/learn-github-actions)
若您也想通过 [Github Actions](https://docs.github.com/en/actions/learn-github-actions)
自动部署项目的Javadoc到 [Github Pages](https://pages.github.com/)
可以参考我的文章 [《自动部署Javadoc到Github Pages》](https://pages.carm.cc/doc/javadoc-in-github.html) 。
+27
View File
@@ -0,0 +1,27 @@
# EasyPlugin Repository
采用github的repo分支进行依赖,随项目发布而自动更新。
其他依赖方式见主页介绍。
## 依赖方式
### Maven
```xml
<repositories>
<repository>
<id>EasyPlugin</id>
<name>GitHub Branch Repository</name>
<url>https://github.com/CarmJos/EasyPlugin/blob/repo/</url>
</repository>
</repositories>
```
### Gradle
```groovy
repositories {
maven { url 'https://github.com/CarmJos/EasyPlugin/blob/repo/' }
}
```
+1 -1
View File
@@ -14,6 +14,7 @@ assignees: ''
### **问题来源**
描述一下通过哪些操作才发现的问题,如:
1. 使用了 ...
2. 输入了 ...
3. 出现了报错 ...
@@ -32,7 +33,6 @@ assignees: ''
- Java版本: `JDK11` / `OPENJDK8` / `JRE8` / `...`
- 服务端版本: 请在后台输入 `version` 并复制相关输出。
### **其他补充**
如有其他补充,可以在这里描述。
+4
View File
@@ -8,13 +8,17 @@ assignees: ''
---
### **功能简述**
简单的描述一下你想要的功能
### **需求来源**
简单的描述一下为什么需要这个功能。
### **功能参考**(可选)
如果有相关功能的参考,如文本、截图,请提供给我们。
### **附加内容**
如果有什么小细节需要重点注意,请在这里告诉我们。
+18 -54
View File
@@ -1,7 +1,7 @@
# This workflow will build a Java project with Maven, and cache/restore any dependencies to improve the workflow execution time
# For more information see: https://help.github.com/actions/language-and-framework-guides/building-and-testing-java-with-maven
name: Project Deployment
name: Deploy & Publish
on:
# 支持手动触发构建
@@ -11,10 +11,8 @@ on:
types: [ published ]
jobs:
github-deploy:
packages-deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: "Set up JDK"
@@ -34,10 +32,8 @@ jobs:
MAVEN_TOKEN: ${{secrets.GITHUB_TOKEN}}
local-deploy:
github-deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: "Set up JDK"
@@ -55,45 +51,7 @@ jobs:
rm -rf deploy
mkdir -vp deploy
cp -vrf $HOME/local-deploy/* deploy/
- name: "Configure Git"
env:
DEPLOY_PRI: ${{secrets.DEPLOY_PRI}}
run: |
sudo timedatectl set-timezone "Asia/Shanghai"
mkdir -p ~/.ssh/
echo "$DEPLOY_PRI" > ~/.ssh/id_rsa
chmod 600 ~/.ssh/id_rsa
ssh-keyscan github.com >> ~/.ssh/known_hosts
git config --global user.name '${{ github.repository_owner }}'
git config --global user.email '${{ github.repository_owner }}@users.noreply.github.com'
- name: "Commit files"
run: |
cd deploy
git init
git remote add origin git@github.com:${{ github.repository_owner }}/${{ github.event.repository.name }}.git
git checkout -b repo
git add -A
git commit -m "Maven project deployment."
- name: "Push files"
run: |
cd deploy
git push origin HEAD:repo --force
javadoc-deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: "Set up JDK"
uses: actions/setup-java@v2
with:
java-version: '8'
distribution: 'adopt'
cache: maven
cp -vrf .documentation/repository/REPO-README.md deploy/README.md
- name: "Generate Javadoc"
run: mvn -B javadoc:aggregate --file pom.xml -DskipTests
@@ -105,14 +63,14 @@ jobs:
cp -vrf target/site/apidocs/* docs/
cp -vrf .documentation/javadoc/JAVADOC-README.md docs/README.md
- name: "Generate Sitemap"
- name: "Generate Javadoc sitemap"
id: sitemap
uses: cicirello/generate-sitemap@v1
with:
base-url-path: https://${{ github.repository_owner }}.github.io/${{ github.event.repository.name }}
path-to-root: docs
- name: Output stats
- name: "Output Javadoc stats"
run: |
echo "sitemap-path = ${{ steps.sitemap.outputs.sitemap-path }}"
echo "url-count = ${{ steps.sitemap.outputs.url-count }}"
@@ -131,7 +89,17 @@ jobs:
git config --global user.name '${{ github.repository_owner }}'
git config --global user.email '${{ github.repository_owner }}@users.noreply.github.com'
- name: "Commit documentation"
- name: "Commit&Push repository files"
run: |
cd deploy
git init
git remote add origin git@github.com:${{ github.repository_owner }}/${{ github.event.repository.name }}.git
git checkout -b repo
git add -A
git commit -m "Maven project deployment."
git push origin HEAD:repo --force
- name: "Commit&Push API documentation"
run: |
cd docs
git init
@@ -139,8 +107,4 @@ jobs:
git checkout -b gh-pages
git add -A
git commit -m "API Document generated."
- name: "Push Javadoc website"
run: |
cd docs
git push origin HEAD:gh-pages --force
git push origin HEAD:gh-pages --force
+2 -2
View File
@@ -1,7 +1,7 @@
# This workflow will build a Java project with Maven, and cache/restore any dependencies to improve the workflow execution time
# For more information see: https://help.github.com/actions/language-and-framework-guides/building-and-testing-java-with-maven
name: Project Build & Tests
name: Build & Tests
on:
# 支持手动触发构建
@@ -19,7 +19,7 @@ jobs:
uses: actions/setup-java@v2
with:
cache: maven
java-version: '11'
java-version: '8'
distribution: 'adopt'
server-id: github
server-username: MAVEN_USERNAME
+3 -3
View File
@@ -67,10 +67,10 @@
<repositories>
<repository>
<!--采用github依赖库,安全稳定,但需要配置 (推荐)-->
<!--采用github-repo依赖库(推荐)-->
<id>EasyPlugin</id>
<name>GitHub Packages</name>
<url>https://maven.pkg.github.com/CarmJos/EasyPlugin</url>
<url>https://raw.githubusercontent.com/CarmJos/EasyPlugin/repo/</url>
</repository>
<repository>
@@ -121,7 +121,7 @@
```groovy
repositories {
// 采用github依赖库,安全稳定,但需要配置 (推荐)
maven { url 'https://maven.pkg.github.com/CarmJos/EasyPlugin' }
maven { url 'https://raw.githubusercontent.com/CarmJos/EasyPlugin/repo/' }
// 采用我的私人依赖库,简单方便,但可能因为变故而无法使用
maven { url 'https://repo.carm.cc/repository/maven-public/' }
+37 -6
View File
@@ -5,16 +5,47 @@
<parent>
<artifactId>easyplugin-parent</artifactId>
<groupId>cc.carm.lib</groupId>
<version>1.4.4-SNAPSHOT</version>
<version>1.4.10</version>
<relativePath>../../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>easyplugin-command</artifactId>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<maven.compiler.source>${project.jdk.version}</maven.compiler.source>
<maven.compiler.target>${project.jdk.version}</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.encoding>UTF-8</maven.compiler.encoding>
</properties>
<artifactId>easyplugin-command</artifactId>
<packaging>jar</packaging>
<name>EasyPlugin-Command</name>
<description>轻松插件指令接口模块,方便快捷的编写子指令。</description>
<url>https://github.com/CarmJos/EasyPlugin</url>
<developers>
<developer>
<id>CarmJos</id>
<name>Carm Jos</name>
<email>carm@carm.cc</email>
<url>https://www.carm.cc</url>
</developer>
</developers>
<licenses>
<license>
<name>The MIT License</name>
<url>https://opensource.org/licenses/MIT</url>
</license>
</licenses>
<issueManagement>
<system>GitHub Issues</system>
<url>https://github.com/CarmJos/EasyPlugin/issues</url>
</issueManagement>
<ciManagement>
<system>GitHub Actions</system>
<url>https://github.com/CarmJos/EasyPlugin/actions/workflows/maven.yml</url>
</ciManagement>
</project>
@@ -1,4 +1,3 @@
package cc.carm.lib.easyplugin.command;
import org.bukkit.command.Command;
@@ -39,7 +38,9 @@ public abstract class CommandHandler implements TabExecutor, NamedExecutor {
public abstract void noArgs(CommandSender sender);
public abstract void unknownCommand(CommandSender sender, String[] args);
public void unknownCommand(CommandSender sender, String[] args) {
noArgs(sender);
}
public abstract void noPermission(CommandSender sender);
@@ -1,8 +1,14 @@
package cc.carm.lib.easyplugin.command;
import org.bukkit.command.CommandSender;
import org.bukkit.permissions.Permissible;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.function.Function;
public interface NamedExecutor {
@@ -14,4 +20,17 @@ public interface NamedExecutor {
return true;
}
default Void sendMessage(@NotNull CommandSender sender, @NotNull String... messages) {
return sendMessage(sender, (Function<String, String>) null, messages);
}
default Void sendMessage(@NotNull CommandSender sender,
@Nullable Function<String, String> parser,
@NotNull String... messages) {
if (messages == null || messages.length == 0) return null;
Function<String, String> finalParser = Optional.ofNullable(parser).orElse(Function.identity());
Arrays.stream(messages).map(finalParser).forEach(sender::sendMessage);
return null;
}
}
@@ -1,15 +1,18 @@
package cc.carm.lib.easyplugin.command;
import com.google.common.collect.ImmutableList;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.OfflinePlayer;
import org.bukkit.World;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.HumanEntity;
import org.bukkit.potion.PotionEffectType;
import org.bukkit.util.StringUtil;
import org.jetbrains.annotations.NotNull;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
@@ -17,14 +20,22 @@ import java.util.stream.Stream;
public class SimpleCompleter {
public static @NotNull List<String> objects(@NotNull String input, List<?> objects) {
public static @NotNull List<String> none() {
return ImmutableList.of();
}
public static @NotNull List<String> objects(@NotNull String input, Collection<?> objects) {
return objects(input, objects.size(), objects);
}
public static @NotNull List<String> objects(@NotNull String input, int limit, List<?> objects) {
public static @NotNull List<String> objects(@NotNull String input, int limit, Collection<?> objects) {
return objects(input, limit, objects.stream());
}
public static @NotNull List<String> objects(@NotNull String input, Stream<?> stream) {
return objects(input, 20, stream);
}
public static @NotNull List<String> objects(@NotNull String input, int limit, Stream<?> stream) {
return stream.filter(Objects::nonNull).map(Object::toString)
.filter(s -> StringUtil.startsWithIgnoreCase(s, input))
@@ -39,11 +50,11 @@ public class SimpleCompleter {
return text(input, limit, Arrays.asList(texts));
}
public static @NotNull List<String> text(@NotNull String input, List<String> texts) {
public static @NotNull List<String> text(@NotNull String input, Collection<String> texts) {
return text(input, texts.size(), texts);
}
public static @NotNull List<String> text(@NotNull String input, int limit, List<String> texts) {
public static @NotNull List<String> text(@NotNull String input, int limit, Collection<String> texts) {
return objects(input, limit, texts);
}
@@ -87,4 +98,13 @@ public class SimpleCompleter {
return objects(input, limit, Arrays.stream(PotionEffectType.values()).map(PotionEffectType::getName));
}
public static @NotNull List<String> enchantments(@NotNull String input) {
return effects(input, 10);
}
@SuppressWarnings("deprecation")
public static @NotNull List<String> enchantments(@NotNull String input, int limit) {
return objects(input, limit, Arrays.stream(Enchantment.values()).map(Enchantment::getName));
}
}
+1 -25
View File
@@ -5,7 +5,7 @@
<parent>
<artifactId>easyplugin-parent</artifactId>
<groupId>cc.carm.lib</groupId>
<version>1.4.4-SNAPSHOT</version>
<version>1.4.10</version>
<relativePath>../../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
@@ -59,28 +59,4 @@
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
@@ -21,191 +21,193 @@ import java.util.stream.IntStream;
public class GUI {
private static JavaPlugin plugin;
private static final HashMap<UUID, GUI> openedGUIs = new HashMap<>();
private static JavaPlugin plugin;
private static final HashMap<UUID, GUI> openedGUIs = new HashMap<>();
public static void initialize(JavaPlugin plugin) {
GUI.plugin = plugin;
}
public static void initialize(JavaPlugin plugin) {
GUI.plugin = plugin;
}
public static JavaPlugin getPlugin() {
return plugin;
}
public static JavaPlugin getPlugin() {
return plugin;
}
public static HashMap<UUID, GUI> getOpenedGUIs() {
return openedGUIs;
}
public static HashMap<UUID, GUI> getOpenedGUIs() {
return openedGUIs;
}
protected GUIType type;
protected String name;
public HashMap<Integer, GUIItem> items;
public Inventory inv;
protected GUIType type;
protected String name;
public HashMap<Integer, GUIItem> items;
public Inventory inv;
/**
* 当玩家点击目标GUI时是否取消
*/
boolean cancelOnTarget = true;
/**
* 当玩家点击目标GUI时是否取消
*/
boolean cancelOnTarget = true;
/**
* 当玩家点击自己背包时是否取消
*/
boolean cancelOnSelf = true;
/**
* 当玩家点击自己背包时是否取消
*/
boolean cancelOnSelf = true;
/**
* 当玩家点击界面外时是否取消
*/
boolean cancelOnOuter = true;
/**
* 当玩家点击界面外时是否取消
*/
boolean cancelOnOuter = true;
Map<String, Object> flags;
Map<String, Object> flags;
GUIListener listener;
GUIListener listener;
public GUI(GUIType type, String name) {
this.type = type;
this.name = ColorParser.parse(name);
this.items = new HashMap<>();
}
public GUI(GUIType type, String name) {
this.type = type;
this.name = ColorParser.parse(name);
this.items = new HashMap<>();
}
public HashMap<@NotNull Integer, @NotNull GUIItem> getItems() {
return new HashMap<>(items);
}
public HashMap<@NotNull Integer, @NotNull GUIItem> getItems() {
return new HashMap<>(items);
}
public final void setItem(int index, @Nullable GUIItem item) {
if (item == null) {
this.items.remove(index);
} else {
this.items.put(index, item);
}
}
public final void setItem(int index, @Nullable GUIItem item) {
if (item == null) {
this.items.remove(index);
} else {
this.items.put(index, item);
}
}
public void setItem(GUIItem item, int... index) {
for (int i : index) {
setItem(i, item);
}
}
public void setItem(GUIItem item, int... index) {
for (int i : index) {
setItem(i, item);
}
}
public GUIItem getItem(int index) {
return this.items.get(index);
}
public GUIItem getItem(int index) {
return this.items.get(index);
}
/**
* 更新玩家箱子的视图
*/
public void updateView() {
if (this.inv != null) {
List<HumanEntity> viewers = this.inv.getViewers();
IntStream.range(0, this.inv.getSize()).forEach(index -> inv.setItem(index, new ItemStack(Material.AIR)));
getItems().forEach((index, item) -> inv.setItem(index, item.getDisplay()));
viewers.forEach(p -> ((Player) p).updateInventory());
}
}
/**
* 更新玩家箱子的视图
*/
public void updateView() {
if (this.inv != null) {
List<HumanEntity> viewers = this.inv.getViewers();
IntStream.range(0, this.inv.getSize()).forEach(index -> inv.setItem(index, new ItemStack(Material.AIR)));
getItems().forEach((index, item) -> inv.setItem(index, item.getDisplay()));
viewers.forEach(p -> ((Player) p).updateInventory());
}
}
/**
* 设置是否取消点击GUI内物品的事件
* 如果不取消,玩家可以从GUI中拿取物品。
*
* @param b 是否取消
*/
public void setCancelOnTarget(boolean b) {
this.cancelOnTarget = b;
}
/**
* 设置是否取消点击GUI内物品的事件
* 如果不取消,玩家可以从GUI中拿取物品。
*
* @param b 是否取消
*/
public void setCancelOnTarget(boolean b) {
this.cancelOnTarget = b;
}
/**
* 设置是否取消点击自己背包内物品的事件
* 如果不取消,玩家可以从自己的背包中拿取物品。
*
* @param b 是否取消
*/
public void setCancelOnSelf(boolean b) {
this.cancelOnSelf = b;
}
/**
* 设置是否取消点击自己背包内物品的事件
* 如果不取消,玩家可以从自己的背包中拿取物品。
*
* @param b 是否取消
*/
public void setCancelOnSelf(boolean b) {
this.cancelOnSelf = b;
}
/**
* 设置是否取消点击GUI外的事件
* 如果不取消,玩家可以把物品从GUI或背包中丢出去
*
* @param b 是否取消
*/
public void setCancelOnOuter(boolean b) {
this.cancelOnOuter = b;
}
/**
* 设置是否取消点击GUI外的事件
* 如果不取消,玩家可以把物品从GUI或背包中丢出去
*
* @param b 是否取消
*/
public void setCancelOnOuter(boolean b) {
this.cancelOnOuter = b;
}
public void addFlag(String flag, Object obj) {
if (this.flags == null) this.flags = new HashMap<>();
this.flags.put(flag, obj);
}
public void addFlag(String flag, Object obj) {
if (this.flags == null) this.flags = new HashMap<>();
this.flags.put(flag, obj);
}
public Object getFlag(String flag) {
if (this.flags == null) return null;
else
return this.flags.get(flag);
}
public Object getFlag(String flag) {
if (this.flags == null) return null;
else
return this.flags.get(flag);
}
public void setFlag(String flag, Object obj) {
if (this.flags == null) this.flags = new HashMap<>();
this.flags.replace(flag, obj);
}
public void setFlag(String flag, Object obj) {
if (this.flags == null) this.flags = new HashMap<>();
this.flags.replace(flag, obj);
}
public void removeFlag(String flag) {
if (this.flags == null) this.flags = new HashMap<>();
this.flags.remove(flag);
}
public void removeFlag(String flag) {
if (this.flags == null) this.flags = new HashMap<>();
this.flags.remove(flag);
}
public void rawClickListener(InventoryClickEvent event) {
}
public void rawClickListener(InventoryClickEvent event) {
}
public void openGUI(Player player) {
if (this.type == GUIType.CANCEL) { throw new IllegalStateException("被取消或不存在的GUI"); }
public void openGUI(Player player) {
if (this.type == GUIType.CANCEL) {
throw new IllegalStateException("被取消或不存在的GUI");
}
Inventory inv = Bukkit.createInventory(null, this.type.getSize(), this.name);
IntStream.range(0, inv.getSize()).forEach(index -> inv.setItem(index, new ItemStack(Material.AIR)));
getItems().forEach((index, item) -> inv.setItem(index, item.getDisplay()));
Inventory inv = Bukkit.createInventory(null, this.type.getSize(), this.name);
IntStream.range(0, inv.getSize()).forEach(index -> inv.setItem(index, new ItemStack(Material.AIR)));
getItems().forEach((index, item) -> inv.setItem(index, item.getDisplay()));
GUI previous = getOpenedGUI(player);
if(previous != null){
previous.listener.close(player);
}
GUI previous = getOpenedGUI(player);
if (previous != null) {
previous.listener.close(player);
}
setOpenedGUI(player, this);
setOpenedGUI(player, this);
this.inv = inv;
player.openInventory(inv);
this.inv = inv;
player.openInventory(inv);
if (listener == null) {
Bukkit.getPluginManager().registerEvents(listener = new GUIListener(this), getPlugin());
}
}
if (listener == null) {
Bukkit.getPluginManager().registerEvents(listener = new GUIListener(this), getPlugin());
}
}
/**
* 拖动GUI内物品是执行的代码
*
* @param event InventoryDragEvent
*/
public void onDrag(InventoryDragEvent event) {
}
/**
* 拖动GUI内物品是执行的代码
*
* @param event InventoryDragEvent
*/
public void onDrag(InventoryDragEvent event) {
}
/**
* 关闭GUI时执行的代码
*/
public void onClose() {
}
/**
* 关闭GUI时执行的代码
*/
public void onClose() {
}
public static void setOpenedGUI(Player player, GUI gui) {
getOpenedGUIs().put(player.getUniqueId(), gui);
}
public static void setOpenedGUI(Player player, GUI gui) {
getOpenedGUIs().put(player.getUniqueId(), gui);
}
public static boolean hasOpenedGUI(Player player) {
return getOpenedGUIs().containsKey(player.getUniqueId());
}
public static boolean hasOpenedGUI(Player player) {
return getOpenedGUIs().containsKey(player.getUniqueId());
}
public static GUI getOpenedGUI(Player player) {
return getOpenedGUIs().get(player.getUniqueId());
}
public static GUI getOpenedGUI(Player player) {
return getOpenedGUIs().get(player.getUniqueId());
}
public static void removeOpenedGUI(Player player) {
getOpenedGUIs().remove(player.getUniqueId());
}
public static void removeOpenedGUI(Player player) {
getOpenedGUIs().remove(player.getUniqueId());
}
}
@@ -10,64 +10,64 @@ import java.util.Set;
public class GUIItem {
ItemStack display;
boolean actionActive = true;
ItemStack display;
boolean actionActive = true;
public Set<GUIClickAction> actions = new HashSet<>();
public Set<GUIClickAction> actionsIgnoreActive = new HashSet<>();
public Set<GUIClickAction> actions = new HashSet<>();
public Set<GUIClickAction> actionsIgnoreActive = new HashSet<>();
public GUIItem(ItemStack display) {
this.display = display;
}
public GUIItem(ItemStack display) {
this.display = display;
}
public final ItemStack getDisplay() {
return this.display;
}
public final ItemStack getDisplay() {
return this.display;
}
public final void setDisplay(ItemStack display) {
this.display = display;
}
public final void setDisplay(ItemStack display) {
this.display = display;
}
public final boolean isActionActive() {
return this.actionActive;
}
public final boolean isActionActive() {
return this.actionActive;
}
public final void setActionActive(boolean b) {
actionActive = b;
}
public final void setActionActive(boolean b) {
actionActive = b;
}
/**
* 玩家点击GUI后执行的代码
*
* @param type 点击的类型
*/
public void onClick(ClickType type) {
/**
* 玩家点击GUI后执行的代码
*
* @param type 点击的类型
*/
public void onClick(ClickType type) {
}
}
public void addClickAction(GUIClickAction action) {
actions.add(action);
}
public void addClickAction(GUIClickAction action) {
actions.add(action);
}
public void addActionIgnoreActive(GUIClickAction action) {
actionsIgnoreActive.add(action);
}
public void addActionIgnoreActive(GUIClickAction action) {
actionsIgnoreActive.add(action);
}
public void rawClickAction(InventoryClickEvent event) {
public void rawClickAction(InventoryClickEvent event) {
}
}
/**
* 玩家点击GUI后执行的代码
*
* @param player 点击GUI的玩家
*/
public void customAction(Player player) {
/**
* 玩家点击GUI后执行的代码
*
* @param player 点击GUI的玩家
*/
public void customAction(Player player) {
}
}
public abstract static class GUIClickAction {
public abstract void run(ClickType type, Player player);
}
public abstract static class GUIClickAction {
public abstract void run(ClickType type, Player player);
}
}
@@ -11,82 +11,82 @@ import org.bukkit.event.player.PlayerQuitEvent;
public class GUIListener implements Listener {
GUI currentGUI;
GUI currentGUI;
public GUIListener(GUI gui) {
this.currentGUI = gui;
}
public GUIListener(GUI gui) {
this.currentGUI = gui;
}
public GUI getCurrentGUI() {
return currentGUI;
}
public GUI getCurrentGUI() {
return currentGUI;
}
@EventHandler
public void onInventoryClickEvent(InventoryClickEvent event) {
if (!(event.getWhoClicked() instanceof Player)) return;
Player player = (Player) event.getWhoClicked();
if (!GUI.hasOpenedGUI(player)) return;
if (GUI.getOpenedGUI(player) != getCurrentGUI()) return;
@EventHandler
public void onInventoryClickEvent(InventoryClickEvent event) {
if (!(event.getWhoClicked() instanceof Player)) return;
Player player = (Player) event.getWhoClicked();
if (!GUI.hasOpenedGUI(player)) return;
if (GUI.getOpenedGUI(player) != getCurrentGUI()) return;
getCurrentGUI().rawClickListener(event);
getCurrentGUI().rawClickListener(event);
if (event.getSlot() == -999 && getCurrentGUI().cancelOnOuter) {
event.setCancelled(true);
return;
}
if (event.getSlot() == -999 && getCurrentGUI().cancelOnOuter) {
event.setCancelled(true);
return;
}
if (event.getClickedInventory() == null) return;
if (event.getClickedInventory() == null) return;
if (event.getClickedInventory().equals(getCurrentGUI().inv)) {
if (event.getClickedInventory().equals(getCurrentGUI().inv)) {
if (getCurrentGUI().cancelOnTarget) event.setCancelled(true);
if (getCurrentGUI().cancelOnTarget) event.setCancelled(true);
if (event.getSlot() != -999) {
GUIItem clickedItem = getCurrentGUI().getItem(event.getSlot());
if (clickedItem != null) {
if (clickedItem.isActionActive()) {
clickedItem.onClick(event.getClick());
clickedItem.rawClickAction(event);
clickedItem.actions.forEach(action -> action.run(event.getClick(), player));
}
clickedItem.actionsIgnoreActive.forEach(action -> action.run(event.getClick(), player));
}
}
if (event.getSlot() != -999) {
GUIItem clickedItem = getCurrentGUI().getItem(event.getSlot());
if (clickedItem != null) {
if (clickedItem.isActionActive()) {
clickedItem.onClick(event.getClick());
clickedItem.rawClickAction(event);
clickedItem.actions.forEach(action -> action.run(event.getClick(), player));
}
clickedItem.actionsIgnoreActive.forEach(action -> action.run(event.getClick(), player));
}
}
} else if (event.getClickedInventory().equals(player.getInventory()) && getCurrentGUI().cancelOnSelf) {
event.setCancelled(true);
}
} else if (event.getClickedInventory().equals(player.getInventory()) && getCurrentGUI().cancelOnSelf) {
event.setCancelled(true);
}
}
}
@EventHandler
public void onDrag(InventoryDragEvent e) {
if (!(e.getWhoClicked() instanceof Player)) return;
if (e.getInventory().equals(getCurrentGUI().inv)
|| e.getInventory().equals(e.getWhoClicked().getInventory())) {
getCurrentGUI().onDrag(e);
}
}
@EventHandler
public void onDrag(InventoryDragEvent e) {
if (!(e.getWhoClicked() instanceof Player)) return;
if (e.getInventory().equals(getCurrentGUI().inv)
|| e.getInventory().equals(e.getWhoClicked().getInventory())) {
getCurrentGUI().onDrag(e);
}
}
@EventHandler
public void onInventoryCloseEvent(InventoryCloseEvent event) {
if (!(event.getPlayer() instanceof Player)) return;
if (!event.getInventory().equals(getCurrentGUI().inv)) return;
@EventHandler
public void onInventoryCloseEvent(InventoryCloseEvent event) {
if (!(event.getPlayer() instanceof Player)) return;
if (!event.getInventory().equals(getCurrentGUI().inv)) return;
close((Player) event.getPlayer());
close((Player) event.getPlayer());
}
}
protected void close(Player p){
HandlerList.unregisterAll(this);
getCurrentGUI().listener = null;
GUI.removeOpenedGUI(p);
getCurrentGUI().onClose();
}
protected void close(Player p) {
HandlerList.unregisterAll(this);
getCurrentGUI().listener = null;
GUI.removeOpenedGUI(p);
getCurrentGUI().onClose();
}
@EventHandler
public void onPlayerLeave(PlayerQuitEvent event) {
GUI.removeOpenedGUI(event.getPlayer());
}
@EventHandler
public void onPlayerLeave(PlayerQuitEvent event) {
GUI.removeOpenedGUI(event.getPlayer());
}
}
@@ -6,44 +6,44 @@ import java.util.Arrays;
public enum GUIType {
ONE_BY_NINE(1, 9),
TWO_BY_NINE(2, 18),
THREE_BY_NINE(3, 27),
FOUR_BY_NINE(4, 36),
FIVE_BY_NINE(5, 45),
SIX_BY_NINE(6, 54),
CANCEL(0, 0);
ONE_BY_NINE(1, 9),
TWO_BY_NINE(2, 18),
THREE_BY_NINE(3, 27),
FOUR_BY_NINE(4, 36),
FIVE_BY_NINE(5, 45),
SIX_BY_NINE(6, 54),
CANCEL(0, 0);
int lines;
int size;
int lines;
int size;
GUIType(int lines, int size) {
this.lines = lines;
this.size = size;
}
GUIType(int lines, int size) {
this.lines = lines;
this.size = size;
}
public int getLines() {
return lines;
}
public int getLines() {
return lines;
}
public int getSize() {
return size;
}
public int getSize() {
return size;
}
@NotNull
public static GUIType getBySize(int size) {
return Arrays.stream(values()).filter(type -> type.getSize() == size).findFirst().orElse(CANCEL);
}
@NotNull
public static GUIType getBySize(int size) {
return Arrays.stream(values()).filter(type -> type.getSize() == size).findFirst().orElse(CANCEL);
}
@NotNull
public static GUIType getByLines(int lines) {
return Arrays.stream(values()).filter(type -> type.getLines() == lines).findFirst().orElse(CANCEL);
}
@NotNull
public static GUIType getByLines(int lines) {
return Arrays.stream(values()).filter(type -> type.getLines() == lines).findFirst().orElse(CANCEL);
}
@NotNull
public static GUIType getByName(String name) {
return Arrays.stream(values()).filter(type -> type.name().equalsIgnoreCase(name)).findFirst().orElse(CANCEL);
}
@NotNull
public static GUIType getByName(String name) {
return Arrays.stream(values()).filter(type -> type.name().equalsIgnoreCase(name)).findFirst().orElse(CANCEL);
}
}
@@ -3,51 +3,104 @@ package cc.carm.lib.easyplugin.gui.configuration;
import cc.carm.lib.easyplugin.gui.GUIItem;
import org.bukkit.entity.Player;
import org.bukkit.event.inventory.ClickType;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public class GUIActionConfiguration {
public static @NotNull GUIActionConfiguration of(@NotNull GUIActionType actionType,
@Nullable ClickType clickType,
@Nullable String actionContent) {
return new GUIActionConfiguration(actionType, clickType, actionContent);
}
@Nullable ClickType clickType;
final @NotNull GUIActionType actionType;
final @Nullable String actionContent;
public static @NotNull GUIActionConfiguration of(@NotNull GUIActionType actionType,
@Nullable String actionContent) {
return of(actionType, null, actionContent);
}
public GUIActionConfiguration(@Nullable ClickType clickType,
@NotNull GUIActionType actionType,
@Nullable String actionContent) {
this.clickType = clickType;
this.actionType = actionType;
this.actionContent = actionContent;
}
public static @NotNull GUIActionConfiguration of(@NotNull GUIActionType actionType,
@Nullable ClickType clickType) {
return of(actionType, clickType, null);
}
public @Nullable ClickType getClickType() {
return clickType;
}
public static @NotNull GUIActionConfiguration of(@NotNull GUIActionType actionType) {
return of(actionType, null, null);
}
public @NotNull GUIActionType getActionType() {
return actionType;
}
protected final @NotNull GUIActionType actionType;
public @Nullable String getActionContent() {
return actionContent;
}
protected final @Nullable ClickType clickType;
protected final @Nullable String actionContent;
public void checkAction(Player player, ClickType type) {
if (getClickType() == null || getClickType() == type) executeAction(player);
}
public GUIActionConfiguration(@NotNull GUIActionType actionType,
@Nullable ClickType clickType,
@Nullable String actionContent) {
this.clickType = clickType;
this.actionType = actionType;
this.actionContent = actionContent;
}
public void executeAction(Player targetPlayer) {
getActionType().getExecutor().accept(targetPlayer, getActionContent());
}
public @Nullable ClickType getClickType() {
return clickType;
}
public GUIItem.GUIClickAction toClickAction() {
return new GUIItem.GUIClickAction() {
@Override
public void run(ClickType type, Player player) {
checkAction(player, type);
}
};
}
public @NotNull GUIActionType getActionType() {
return actionType;
}
public @Nullable String getActionContent() {
return actionContent;
}
public void checkAction(Player player, ClickType type) {
if (getClickType() == null || getClickType() == type) executeAction(player);
}
public void executeAction(Player targetPlayer) {
getActionType().getExecutor().accept(targetPlayer, getActionContent());
}
public GUIItem.GUIClickAction toClickAction() {
return new GUIItem.GUIClickAction() {
@Override
public void run(ClickType type, Player player) {
checkAction(player, type);
}
};
}
@Nullable
@Contract("null->null")
public static GUIActionConfiguration deserialize(@Nullable String actionString) {
if (actionString == null) return null;
int prefixStart = actionString.indexOf("[");
int prefixEnd = actionString.indexOf("]");
if (prefixStart < 0 || prefixEnd < 0) return null;
String prefix = actionString.substring(prefixStart + 1, prefixEnd);
ClickType clickType = null;
GUIActionType actionType;
if (prefix.contains(":")) {
String[] args = prefix.split(":");
clickType = GUIConfiguration.readClickType(args[0]);
actionType = GUIActionType.readActionType(args[1]);
} else {
actionType = GUIActionType.readActionType(prefix);
}
if (actionType == null) return null;
String content = actionString.substring(prefixEnd + 1).trim();
return of(actionType, clickType, content);
}
public @NotNull String serialize() {
String prefix = "[" + getActionType().name() + (getClickType() == null ? "" : ":" + getClickType().name()) + "]";
String content = getActionContent() == null ? "" : " " + getActionContent();
return prefix + content;
}
}
@@ -13,76 +13,76 @@ import java.util.function.BiConsumer;
public enum GUIActionType {
/**
* 以玩家聊天的形式执行
* 若内容以 “/" 开头,则会以玩家身份执行命令。
*/
CHAT((player, string) -> {
if (string == null) return;
MessageUtils.setPlaceholders(player, Collections.singletonList(string)).forEach(player::chat);
}),
/**
* 以玩家聊天的形式执行
* 若内容以 “/" 开头,则会以玩家身份执行命令。
*/
CHAT((player, string) -> {
if (string == null) return;
MessageUtils.setPlaceholders(player, Collections.singletonList(string)).forEach(player::chat);
}),
/**
* 以后台的形式执行指令
* 指令内容不需要以“/”开头。
*/
CONSOLE((player, string) -> {
if (string == null) return;
MessageUtils.setPlaceholders(player, Collections.singletonList(string))
.forEach(message -> Bukkit.dispatchCommand(Bukkit.getConsoleSender(), message));
}),
/**
* 以后台的形式执行指令
* 指令内容不需要以“/”开头。
*/
CONSOLE((player, string) -> {
if (string == null) return;
MessageUtils.setPlaceholders(player, Collections.singletonList(string))
.forEach(message -> Bukkit.dispatchCommand(Bukkit.getConsoleSender(), message));
}),
/**
* 向玩家发送消息。
*/
MESSAGE(MessageUtils::send),
/**
* 向玩家发送消息。
*/
MESSAGE(MessageUtils::send),
/**
* 向玩家发送声音。
* 允许配置音量与音调
* <ul>
* <li>SOUND_NAME</li>
* <li>SOUND_NAME:VOLUME</li>
* <li>SOUND_NAME:VOLUME:PITCH</li>
* </ul>
*/
SOUND((player, string) -> {
if (string == null) return;
try {
String[] args = string.contains(":") ? string.split(":") : new String[]{string};
Sound sound = Arrays.stream(Sound.values())
.filter(s -> s.name().equals(args[0]))
.findFirst().orElse(null);
/**
* 向玩家发送声音。
* 允许配置音量与音调
* <ul>
* <li>SOUND_NAME</li>
* <li>SOUND_NAME:VOLUME</li>
* <li>SOUND_NAME:VOLUME:PITCH</li>
* </ul>
*/
SOUND((player, string) -> {
if (string == null) return;
try {
String[] args = string.contains(":") ? string.split(":") : new String[]{string};
Sound sound = Arrays.stream(Sound.values())
.filter(s -> s.name().equals(args[0]))
.findFirst().orElse(null);
if (sound == null) return;
float volume = args.length > 1 ? Float.parseFloat(args[1]) : 1F;
float pitch = args.length > 2 ? Float.parseFloat(args[2]) : 1F;
if (sound == null) return;
float volume = args.length > 1 ? Float.parseFloat(args[1]) : 1F;
float pitch = args.length > 2 ? Float.parseFloat(args[2]) : 1F;
player.playSound(player.getLocation(), sound, volume, pitch);
} catch (Exception ignored) {
}
}),
player.playSound(player.getLocation(), sound, volume, pitch);
} catch (Exception ignored) {
}
}),
/**
* 为玩家关闭GUI。
*/
CLOSE((player, string) -> player.closeInventory());
/**
* 为玩家关闭GUI。
*/
CLOSE((player, string) -> player.closeInventory());
BiConsumer<@NotNull Player, @Nullable String> executor;
BiConsumer<@NotNull Player, @Nullable String> executor;
GUIActionType(BiConsumer<@NotNull Player, @Nullable String> executor) {
this.executor = executor;
}
GUIActionType(BiConsumer<@NotNull Player, @Nullable String> executor) {
this.executor = executor;
}
public BiConsumer<@NotNull Player, @Nullable String> getExecutor() {
return executor;
}
public BiConsumer<@NotNull Player, @Nullable String> getExecutor() {
return executor;
}
public static GUIActionType readActionType(String string) {
return Arrays.stream(GUIActionType.values())
.filter(action -> action.name().equalsIgnoreCase(string))
.findFirst().orElse(null);
}
public static GUIActionType readActionType(String string) {
return Arrays.stream(GUIActionType.values())
.filter(action -> action.name().equalsIgnoreCase(string))
.findFirst().orElse(null);
}
}
@@ -13,60 +13,60 @@ import java.util.stream.Collectors;
public class GUIConfiguration {
String title;
int lines;
String title;
int lines;
List<GUIItemConfiguration> guiItems;
List<GUIItemConfiguration> guiItems;
public GUIConfiguration(String title, int lines, List<GUIItemConfiguration> guiItems) {
this.title = title;
this.lines = lines;
this.guiItems = guiItems;
}
public GUIConfiguration(String title, int lines, List<GUIItemConfiguration> guiItems) {
this.title = title;
this.lines = lines;
this.guiItems = guiItems;
}
public String getTitle() {
return ColorParser.parse(title);
}
public String getTitle() {
return ColorParser.parse(title);
}
public int getLines() {
return lines;
}
public int getLines() {
return lines;
}
public GUIType getGUIType() {
return Optional.of(GUIType.getByLines(lines))
.map(type -> type == GUIType.CANCEL ? GUIType.SIX_BY_NINE : type)
.get();
}
public GUIType getGUIType() {
return Optional.of(GUIType.getByLines(lines))
.map(type -> type == GUIType.CANCEL ? GUIType.SIX_BY_NINE : type)
.get();
}
public List<GUIItemConfiguration> getGuiItems() {
return guiItems;
}
public List<GUIItemConfiguration> getGuiItems() {
return guiItems;
}
public void setupItems(Player player, GUI gui) {
getGuiItems().forEach(itemConfiguration -> itemConfiguration.setupItems(player, gui));
}
public void setupItems(Player player, GUI gui) {
getGuiItems().forEach(itemConfiguration -> itemConfiguration.setupItems(player, gui));
}
public static GUIConfiguration readConfiguration(@Nullable ConfigurationSection section) {
if (section == null) return new GUIConfiguration("name", 6, new ArrayList<>());
public static GUIConfiguration readConfiguration(@Nullable ConfigurationSection section) {
if (section == null) return new GUIConfiguration("name", 6, new ArrayList<>());
String title = section.getString("title", "");
int lines = section.getInt("lines", 6);
ConfigurationSection itemsSection = section.getConfigurationSection("items");
if (itemsSection == null) return new GUIConfiguration(title, lines, new ArrayList<>());
String title = section.getString("title", "");
int lines = section.getInt("lines", 6);
ConfigurationSection itemsSection = section.getConfigurationSection("items");
if (itemsSection == null) return new GUIConfiguration(title, lines, new ArrayList<>());
return new GUIConfiguration(
title, lines, itemsSection.getKeys(false).stream()
.map(key -> GUIItemConfiguration.readFrom(itemsSection.getConfigurationSection(key)))
.filter(Objects::nonNull)
.collect(Collectors.toList())
);
}
return new GUIConfiguration(
title, lines, itemsSection.getKeys(false).stream()
.map(key -> GUIItemConfiguration.readFrom(itemsSection.getConfigurationSection(key)))
.filter(Objects::nonNull)
.collect(Collectors.toList())
);
}
public static ClickType readClickType(String type) {
return Arrays.stream(ClickType.values())
.filter(click -> click.name().equalsIgnoreCase(type))
.findFirst().orElse(null);
}
public static ClickType readClickType(String type) {
return Arrays.stream(ClickType.values())
.filter(click -> click.name().equalsIgnoreCase(type))
.findFirst().orElse(null);
}
}
@@ -7,86 +7,90 @@ import cc.carm.lib.easyplugin.utils.MessageUtils;
import org.bukkit.Material;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.entity.Player;
import org.bukkit.event.inventory.ClickType;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.*;
import java.util.stream.Collectors;
public class GUIItemConfiguration {
Material material;
int data;
String name;
@NotNull List<String> lore;
@NotNull Material type;
int amount;
int data;
@Nullable String name;
@NotNull List<String> lore;
@NotNull List<Integer> slots;
@NotNull List<GUIActionConfiguration> actions;
@NotNull List<Integer> slots;
@NotNull List<GUIActionConfiguration> actions;
public GUIItemConfiguration(Material material, int data,
String name, @NotNull List<String> lore,
@NotNull List<GUIActionConfiguration> actions,
@NotNull List<Integer> slots) {
this.material = material;
this.data = data;
this.name = name;
this.lore = lore;
this.slots = slots;
this.actions = actions;
}
public GUIItemConfiguration(@NotNull Material type, int amount, int data,
@Nullable String name, @NotNull List<String> lore,
@NotNull List<GUIActionConfiguration> actions,
@NotNull List<Integer> slots) {
this.type = type;
this.amount = amount;
this.data = data;
this.name = name;
this.lore = lore;
this.slots = slots;
this.actions = actions;
}
public void setupItems(Player player, GUI gui) {
ItemStackFactory icon = new ItemStackFactory(this.material);
icon.setDurability(this.data);
if (this.name != null) icon.setDisplayName(this.name);
icon.setLore(MessageUtils.setPlaceholders(player, this.lore));
public void setupItems(Player player, GUI gui) {
ItemStackFactory icon = new ItemStackFactory(this.type, this.amount, this.data);
if (this.name != null) icon.setDisplayName(this.name);
icon.setLore(MessageUtils.setPlaceholders(player, this.lore));
GUIItem item = new GUIItem(icon.toItemStack());
this.actions.stream().map(GUIActionConfiguration::toClickAction).forEach(item::addClickAction);
this.slots.forEach(slot -> gui.setItem(slot, item));
}
GUIItem item = new GUIItem(icon.toItemStack());
this.actions.stream().map(GUIActionConfiguration::toClickAction).forEach(item::addClickAction);
this.slots.forEach(slot -> gui.setItem(slot, item));
}
@Nullable
public static GUIItemConfiguration readFrom(@Nullable ConfigurationSection itemSection) {
if (itemSection == null) return null;
Material material = Optional.ofNullable(Material.matchMaterial(itemSection.getString("material", "STONE"))).orElse(Material.STONE);
int data = itemSection.getInt("data", 0);
String name = itemSection.getString("name");
List<String> lore = itemSection.getStringList("lore");
public @NotNull Map<String, Object> serialize() {
LinkedHashMap<String, Object> map = new LinkedHashMap<>();
List<Integer> slots = itemSection.getIntegerList("slots");
int slot = itemSection.getInt("slot", 0);
map.put("type", this.type.name());
if (this.name != null) map.put("name", this.name);
if (this.amount != 1) map.put("amount", this.amount);
if (this.data != 0) map.put("data", this.data);
if (!this.lore.isEmpty()) map.put("lore", this.lore);
if (this.slots.size() > 1) {
map.put("slots", this.slots);
} else if (slots.size() == 1) {
map.put("slot", this.slots.get(0));
}
if (!this.actions.isEmpty()) {
map.put("actions", this.actions.stream().map(GUIActionConfiguration::serialize).collect(Collectors.toList()));
}
return map;
}
List<String> actionsString = itemSection.getStringList("actions");
List<GUIActionConfiguration> actions = new ArrayList<>();
for (String actionString : actionsString) {
int prefixStart = actionString.indexOf("[");
int prefixEnd = actionString.indexOf("]");
if (prefixStart < 0 || prefixEnd < 0) continue;
@Nullable
public static GUIItemConfiguration readFrom(@Nullable ConfigurationSection itemSection) {
if (itemSection == null) return null;
String material = Optional.ofNullable(itemSection.getString("type")).orElse("STONE");
Material type = Optional.ofNullable(Material.matchMaterial(material)).orElse(Material.STONE);
int data = itemSection.getInt("data", 0);
int amount = itemSection.getInt("amount", 1);
String name = itemSection.getString("name");
List<String> lore = itemSection.getStringList("lore");
String prefix = actionString.substring(prefixStart + 1, prefixEnd);
ClickType clickType = null;
GUIActionType actionType;
if (prefix.contains(":")) {
String[] args = prefix.split(":");
clickType = GUIConfiguration.readClickType(args[0]);
actionType = GUIActionType.readActionType(args[1]);
} else {
actionType = GUIActionType.readActionType(prefix);
}
List<Integer> slots = itemSection.getIntegerList("slots");
int slot = itemSection.getInt("slot", 0);
if (actionType == null) continue;
actions.add(new GUIActionConfiguration(clickType, actionType, actionString.substring(prefixEnd + 1).trim()));
}
return new GUIItemConfiguration(
material, data, name, lore, actions,
slots.size() > 0 ? slots : Collections.singletonList(slot)
);
}
List<String> actionsString = itemSection.getStringList("actions");
List<GUIActionConfiguration> actions = new ArrayList<>();
for (String actionString : actionsString) {
GUIActionConfiguration action = GUIActionConfiguration.deserialize(actionString);
if (action == null) continue;
actions.add(action);
}
return new GUIItemConfiguration(
type, amount, data, name, lore, actions,
slots.size() > 0 ? slots : Collections.singletonList(slot)
);
}
}
@@ -10,87 +10,87 @@ import java.util.function.Function;
public class AutoPagedGUI extends CommonPagedGUI {
public static Function<Player, ItemStack> defaultPreviousPage = null;
public static Function<Player, ItemStack> defaultNextPage = null;
public static Function<Player, ItemStack> defaultPreviousPage = null;
public static Function<Player, ItemStack> defaultNextPage = null;
ItemStack previousPageUI;
ItemStack nextPageUI;
int previousPageSlot = -1;
int nextPageSlot = -1;
ItemStack previousPageUI;
ItemStack nextPageUI;
int previousPageSlot = -1;
int nextPageSlot = -1;
public AutoPagedGUI(GUIType type, String name, int[] range) {
super(type, name, range);
}
public AutoPagedGUI(GUIType type, String name, int[] range) {
super(type, name, range);
}
public AutoPagedGUI(GUIType type, String name, int a, int b) {
super(type, name, a, b);
}
public AutoPagedGUI(GUIType type, String name, int a, int b) {
super(type, name, a, b);
}
public void setPreviousPageUI(ItemStack lastPageUI) {
this.previousPageUI = lastPageUI;
}
public void setPreviousPageUI(ItemStack lastPageUI) {
this.previousPageUI = lastPageUI;
}
public void setNextPageUI(ItemStack nextPageUI) {
this.nextPageUI = nextPageUI;
}
public void setNextPageUI(ItemStack nextPageUI) {
this.nextPageUI = nextPageUI;
}
public void setPreviousPageSlot(int slot) {
this.previousPageSlot = slot;
}
public void setPreviousPageSlot(int slot) {
this.previousPageSlot = slot;
}
public void setNextPageSlot(int slot) {
this.nextPageSlot = slot;
}
public void setNextPageSlot(int slot) {
this.nextPageSlot = slot;
}
@Override
public void openGUI(Player user) {
if (previousPageSlot >= 0) {
if (hasPreviousPage()) {
setItem(previousPageSlot, new GUIItem(
previousPageUI == null ? getDefaultPreviousPage(user) : previousPageUI) {
@Override
public void onClick(ClickType type) {
if (type == ClickType.RIGHT) {
goFirstPage();
} else {
goPreviousPage();
}
openGUI(user);
}
});
} else {
setItem(previousPageSlot, null);
}
}
@Override
public void openGUI(Player user) {
if (previousPageSlot >= 0) {
if (hasPreviousPage()) {
setItem(previousPageSlot, new GUIItem(
previousPageUI == null ? getDefaultPreviousPage(user) : previousPageUI) {
@Override
public void onClick(ClickType type) {
if (type == ClickType.RIGHT) {
goFirstPage();
} else {
goPreviousPage();
}
openGUI(user);
}
});
} else {
setItem(previousPageSlot, null);
}
}
if (nextPageSlot >= 0) {
if (hasNextPage()) {
setItem(nextPageSlot, new GUIItem(
nextPageUI == null ? getDefaultNextPage(user) : nextPageUI) {
@Override
public void onClick(ClickType type) {
if (type == ClickType.RIGHT) {
goLastPage();
} else {
goNextPage();
}
openGUI(user);
}
});
} else {
setItem(nextPageSlot, null);
}
}
if (nextPageSlot >= 0) {
if (hasNextPage()) {
setItem(nextPageSlot, new GUIItem(
nextPageUI == null ? getDefaultNextPage(user) : nextPageUI) {
@Override
public void onClick(ClickType type) {
if (type == ClickType.RIGHT) {
goLastPage();
} else {
goNextPage();
}
openGUI(user);
}
});
} else {
setItem(nextPageSlot, null);
}
}
super.openGUI(user);
}
super.openGUI(user);
}
private static ItemStack getDefaultNextPage(Player player) {
return defaultNextPage != null ? defaultNextPage.apply(player) : null;
}
private static ItemStack getDefaultNextPage(Player player) {
return defaultNextPage != null ? defaultNextPage.apply(player) : null;
}
private static ItemStack getDefaultPreviousPage(Player player) {
return defaultPreviousPage != null ? defaultPreviousPage.apply(player) : null;
}
private static ItemStack getDefaultPreviousPage(Player player) {
return defaultPreviousPage != null ? defaultPreviousPage.apply(player) : null;
}
}
@@ -11,22 +11,22 @@ import java.util.List;
public class CommonPagedGUI extends PagedGUI {
private int[] range;
private int[] range;
private CommonPagedGUI(GUIType type, String name) {
super(type, name);
}
private CommonPagedGUI(GUIType type, String name) {
super(type, name);
}
public CommonPagedGUI(GUIType type, String Name, int a, int b) {
this(type, Name, toRange(type, a, b));
}
public CommonPagedGUI(GUIType type, String Name, int a, int b) {
this(type, Name, toRange(type, a, b));
}
public CommonPagedGUI(GUIType type, String Name, int[] range) {
super(type, Name);
Arrays.sort(range);
this.range = range;
public CommonPagedGUI(GUIType type, String Name, int[] range) {
super(type, Name);
Arrays.sort(range);
this.range = range;
}
}
@@ -41,122 +41,122 @@ public class CommonPagedGUI extends PagedGUI {
}
*/
private static int[] toRange(GUIType type, int a, int b) {
if (a > b) {
a = a ^ b;
b = a ^ b;
a = a ^ b;
}
private static int[] toRange(GUIType type, int a, int b) {
if (a > b) {
a = a ^ b;
b = a ^ b;
a = a ^ b;
}
int lineA = getLine(a);
int columnA = getColumn(a);
int lineB = getLine(b);
int columnB = getColumn(b);
int lineA = getLine(a);
int columnA = getColumn(a);
int lineB = getLine(b);
int columnB = getColumn(b);
if (lineB > type.getLines())
throw new IndexOutOfBoundsException("页面内容范围超过了GUI的大小");
if (lineB > type.getLines())
throw new IndexOutOfBoundsException("页面内容范围超过了GUI的大小");
int[] range = new int[(lineB - lineA + 1) * (columnB - columnA + 1)];
int[] range = new int[(lineB - lineA + 1) * (columnB - columnA + 1)];
for (int i = 0, l = 0; i < type.getSize(); i++) {
int li = getLine(i);
int ci = getColumn(i);
if (li >= lineA && li <= lineB && ci >= columnA && ci <= columnB) {
range[l] = i;
l++;
}
}
for (int i = 0, l = 0; i < type.getSize(); i++) {
int li = getLine(i);
int ci = getColumn(i);
if (li >= lineA && li <= lineB && ci >= columnA && ci <= columnB) {
range[l] = i;
l++;
}
}
return range;
}
return range;
}
private static int getLine(int i) {
return i / 9 + 1;
}
private static int getLine(int i) {
return i / 9 + 1;
}
private static int getColumn(int i) {
return i % 9 + 1;
}
private static int getColumn(int i) {
return i % 9 + 1;
}
@Override
public boolean hasPreviousPage() {
return page > 1;
}
@Override
public boolean hasPreviousPage() {
return page > 1;
}
@Override
public boolean hasNextPage() {
return page < getLastPageNumber();
}
@Override
public boolean hasNextPage() {
return page < getLastPageNumber();
}
/**
* 前往第一页
*/
public void goFirstPage() {
if (hasPreviousPage())
this.page = 1;
else
throw new IndexOutOfBoundsException();
}
/**
* 前往第一页
*/
public void goFirstPage() {
if (hasPreviousPage())
this.page = 1;
else
throw new IndexOutOfBoundsException();
}
/**
* 前往最后一页
*/
public void goLastPage() {
if (hasNextPage())
this.page = getLastPageNumber();
else
throw new IndexOutOfBoundsException();
}
/**
* 前往最后一页
*/
public void goLastPage() {
if (hasNextPage())
this.page = getLastPageNumber();
else
throw new IndexOutOfBoundsException();
}
/**
* 得到最后一页的页码
*
* @return 最后一页的页码
*/
public int getLastPageNumber() {
return (this.container.size() / range.length) + 1;
}
/**
* 得到最后一页的页码
*
* @return 最后一页的页码
*/
public int getLastPageNumber() {
return (this.container.size() / range.length) + 1;
}
/**
* 得到第一页的页码
*
* @return 第一页页码(默认为1)
*/
public int getFirstPageNumber() {
return 1;
}
/**
* 得到第一页的页码
*
* @return 第一页页码(默认为1)
*/
public int getFirstPageNumber() {
return 1;
}
@Override
public void openGUI(Player player) {
if (container.isEmpty()) {
super.openGUI(player);
return;
}
List<GUIItem> list = new ArrayList<>();
int start = (page - 1) * range.length;
for (int i = start; i < start + range.length; i++) {
if (i < container.size()) {
list.add(container.get(i));
} else {
break;
}
}
@Override
public void openGUI(Player player) {
if (container.isEmpty()) {
super.openGUI(player);
return;
}
List<GUIItem> list = new ArrayList<>();
int start = (page - 1) * range.length;
for (int i = start; i < start + range.length; i++) {
if (i < container.size()) {
list.add(container.get(i));
} else {
break;
}
}
int i = 0;
Arrays.stream(range).forEach(index -> setItem(index, null));
for (int index : range) {
if (i < list.size()) {
setItem(index, list.get(i));
i++;
} else {
break;
}
}
super.openGUI(player);
}
int i = 0;
Arrays.stream(range).forEach(index -> setItem(index, null));
for (int index : range) {
if (i < list.size()) {
setItem(index, list.get(i));
i++;
} else {
break;
}
}
super.openGUI(player);
}
}
@@ -10,70 +10,70 @@ import java.util.List;
public abstract class PagedGUI extends GUI {
List<GUIItem> container = new ArrayList<>();
public int page = 1;
List<GUIItem> container = new ArrayList<>();
public int page = 1;
public PagedGUI(GUIType type, String name) {
super(type, name);
}
public PagedGUI(GUIType type, String name) {
super(type, name);
}
public int addItem(GUIItem i) {
container.add(i);
return container.size() - 1;
}
public int addItem(GUIItem i) {
container.add(i);
return container.size() - 1;
}
/**
* 从GUI中移除一个物品
*
* @param item 物品
*/
public void removeItem(GUIItem item) {
container.remove(item);
}
/**
* 从GUI中移除一个物品
*
* @param item 物品
*/
public void removeItem(GUIItem item) {
container.remove(item);
}
/**
* 从GUI中移除一个物品
*
* @param slot 物品格子数
*/
public void removeItem(int slot) {
container.remove(slot);
}
/**
* 从GUI中移除一个物品
*
* @param slot 物品格子数
*/
public void removeItem(int slot) {
container.remove(slot);
}
public List<GUIItem> getItemsContainer() {
return new ArrayList<>(container);
}
public List<GUIItem> getItemsContainer() {
return new ArrayList<>(container);
}
/**
* 前往上一页
*/
public void goPreviousPage() {
if (hasPreviousPage())
page--;
else
throw new IndexOutOfBoundsException();
}
/**
* 前往上一页
*/
public void goPreviousPage() {
if (hasPreviousPage())
page--;
else
throw new IndexOutOfBoundsException();
}
/**
* 前往下一页
*/
public void goNextPage() {
if (hasNextPage())
page++;
else
throw new IndexOutOfBoundsException();
}
/**
* 前往下一页
*/
public void goNextPage() {
if (hasNextPage())
page++;
else
throw new IndexOutOfBoundsException();
}
/**
* @return 是否有上一页
*/
public abstract boolean hasPreviousPage();
/**
* @return 是否有上一页
*/
public abstract boolean hasPreviousPage();
/**
* @return 是否有下一页
*/
public abstract boolean hasNextPage();
/**
* @return 是否有下一页
*/
public abstract boolean hasNextPage();
}
+31 -32
View File
@@ -1,4 +1,3 @@
import cc.carm.lib.easyplugin.gui.configuration.GUIActionType;
import cc.carm.lib.easyplugin.gui.configuration.GUIConfiguration;
import org.bukkit.event.inventory.ClickType;
@@ -10,43 +9,43 @@ import java.util.List;
public class ActionReadTest {
@Test
public void test() {
@Test
public void test() {
List<String> actions = Arrays.asList(
"[CHAT] 123123",
"[SHIFT_LEFT:CHAT] /test qwq",
"[CONSOLE] say hello",
"[CLOSE]"
);
List<String> actions = Arrays.asList(
"[CHAT] 123123",
"[SHIFT_LEFT:CHAT] /test qwq",
"[CONSOLE] say hello",
"[CLOSE]"
);
for (String actionString : actions) {
int prefixStart = actionString.indexOf("[");
int prefixEnd = actionString.indexOf("]");
if (prefixStart < 0 || prefixEnd < 0) continue;
for (String actionString : actions) {
int prefixStart = actionString.indexOf("[");
int prefixEnd = actionString.indexOf("]");
if (prefixStart < 0 || prefixEnd < 0) continue;
String prefix = actionString.substring(prefixStart + 1, prefixEnd);
ClickType clickType = null;
GUIActionType actionType;
if (prefix.contains(":")) {
String[] args = prefix.split(":");
clickType = GUIConfiguration.readClickType(args[0]);
actionType = GUIActionType.readActionType(args[1]);
} else {
actionType = GUIActionType.readActionType(prefix);
}
String prefix = actionString.substring(prefixStart + 1, prefixEnd);
ClickType clickType = null;
GUIActionType actionType;
if (prefix.contains(":")) {
String[] args = prefix.split(":");
clickType = GUIConfiguration.readClickType(args[0]);
actionType = GUIActionType.readActionType(args[1]);
} else {
actionType = GUIActionType.readActionType(prefix);
}
if (actionType == null) {
System.out.println("# " + actionString);
System.out.println("- actionType is Null");
continue;
}
if (actionType == null) {
System.out.println("# " + actionString);
System.out.println("- actionType is Null");
continue;
}
System.out.println("# " + actionType.name() + " " + (clickType == null ? "" : clickType.name()));
System.out.println("- " + actionString.substring(prefixEnd + 1).trim());
}
System.out.println("# " + actionType.name() + " " + (clickType == null ? "" : clickType.name()));
System.out.println("- " + actionString.substring(prefixEnd + 1).trim());
}
}
}
}
+1 -23
View File
@@ -5,7 +5,7 @@
<parent>
<artifactId>easyplugin-parent</artifactId>
<groupId>cc.carm.lib</groupId>
<version>1.4.4-SNAPSHOT</version>
<version>1.4.10</version>
<relativePath>../../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
@@ -56,31 +56,9 @@
<dependency>
<groupId>me.clip</groupId>
<artifactId>placeholderapi</artifactId>
<version>2.10.9</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
@@ -7,31 +7,46 @@ import org.bukkit.Bukkit;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.PluginCommand;
import org.bukkit.command.TabCompleter;
import org.bukkit.event.Event;
import org.bukkit.event.Listener;
import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.plugin.java.JavaPluginLoader;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.File;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
public abstract class EasyPlugin extends JavaPlugin {
protected EasyPluginMessageProvider messageProvider;
protected @NotNull EasyPluginMessageProvider messageProvider;
public EasyPlugin() {
this(EasyPluginMessageProvider.ZH_CN);
}
public EasyPlugin(EasyPluginMessageProvider messageProvider) {
public EasyPlugin(@NotNull EasyPluginMessageProvider messageProvider) {
this.messageProvider = messageProvider;
}
private SchedulerUtils scheduler;
private boolean initialized = false;
protected EasyPlugin(JavaPluginLoader loader, PluginDescriptionFile descriptionFile, File dataFolder, File file) {
this(EasyPluginMessageProvider.ZH_CN, loader, descriptionFile, dataFolder, file);
}
protected EasyPlugin(@NotNull EasyPluginMessageProvider messageProvider,
JavaPluginLoader loader, PluginDescriptionFile descriptionFile, File dataFolder, File file) {
super(loader, descriptionFile, dataFolder, file);
this.messageProvider = messageProvider;
}
protected SchedulerUtils scheduler;
protected boolean initialized = false;
@Override
public final void onLoad() {
@@ -64,7 +79,7 @@ public abstract class EasyPlugin extends JavaPlugin {
@Override
public final void onDisable() {
if (!hasOverride("shutdown") || !isInitialized()) return;
if (!hasOverride("shutdown") || !this.initialized) return;
outputInfo();
log(messageProvider.disabling(this));
@@ -88,10 +103,6 @@ public abstract class EasyPlugin extends JavaPlugin {
Optional.ofNullable(JarResourceUtils.readResource(this.getResource("PLUGIN_INFO"))).ifPresent(this::log);
}
public boolean isInitialized() {
return initialized;
}
public boolean isDebugging() {
return false;
}
@@ -134,6 +145,22 @@ public abstract class EasyPlugin extends JavaPlugin {
if (isDebugging()) print("&8[DEBUG] &r", messages);
}
public @NotNull <T extends Event> CompletableFuture<T> callSync(T event) {
CompletableFuture<T> future = new CompletableFuture<>();
getScheduler().run(() -> {
Bukkit.getPluginManager().callEvent(event);
future.complete(event);
});
return future;
}
public @NotNull <T extends Event> CompletableFuture<T> callAsync(T event) {
return CompletableFuture.supplyAsync(() -> {
Bukkit.getPluginManager().callEvent(event);
return event;
});
}
@SuppressWarnings("BooleanMethodIsAlwaysInverted")
private boolean hasOverride(String methodName) {
Map<Method, Method> methodMap = new HashMap<>();
@@ -8,7 +8,7 @@ import java.util.stream.Collectors;
public class ColorParser {
public static final Pattern HEX_PATTERN = Pattern.compile("&\\(&?#([0-9a-fA-F]{6})\\)");
public static final Pattern HEX_PATTERN = Pattern.compile("&\\(&?#([\\da-fA-F]{6})\\)");
public static String parse(String text) {
return parseBaseColor(parseHexColor(text));
@@ -14,131 +14,131 @@ import java.util.List;
import java.util.stream.Collectors;
public class ItemStackFactory {
ItemStack item;
ItemStack item;
private ItemStackFactory() {
}
private ItemStackFactory() {
}
public ItemStackFactory(ItemStack is) {
this.item = is.clone();
}
public ItemStackFactory(ItemStack is) {
this.item = is.clone();
}
public ItemStackFactory(Material type) {
this(type, 1);
}
public ItemStackFactory(Material type) {
this(type, 1);
}
public ItemStackFactory(Material type, int amount) {
this(type, amount, (short) 0);
}
public ItemStackFactory(Material type, int amount) {
this(type, amount, (short) 0);
}
public ItemStackFactory(Material type, int amount, short data) {
this.item = new ItemStack(type, amount, data);
}
public ItemStackFactory(Material type, int amount, short data) {
this.item = new ItemStack(type, amount, data);
}
public ItemStackFactory(Material type, int amount, int data) {
this(type, amount, (short) data);
}
public ItemStackFactory(Material type, int amount, int data) {
this(type, amount, (short) data);
}
public ItemStack toItemStack() {
return this.item;
}
public ItemStack toItemStack() {
return this.item;
}
public ItemStackFactory setType(Material type) {
this.item.setType(type);
return this;
}
public ItemStackFactory setType(Material type) {
this.item.setType(type);
return this;
}
public ItemStackFactory setDurability(int i) {
ItemMeta im = this.item.getItemMeta();
if (im instanceof Damageable) {
((Damageable) im).setDamage(i);
this.item.setItemMeta(im);
}
return this;
}
public ItemStackFactory setDurability(int i) {
ItemMeta im = this.item.getItemMeta();
if (im instanceof Damageable) {
((Damageable) im).setDamage(i);
this.item.setItemMeta(im);
}
return this;
}
public ItemStackFactory setAmount(int a) {
this.item.setAmount(a);
return this;
}
public ItemStackFactory setAmount(int a) {
this.item.setAmount(a);
return this;
}
public ItemStackFactory setDisplayName(@NotNull String name) {
ItemMeta im = this.item.getItemMeta();
if (im != null) {
im.setDisplayName(ColorParser.parse(name));
this.item.setItemMeta(im);
}
return this;
}
public ItemStackFactory setDisplayName(@NotNull String name) {
ItemMeta im = this.item.getItemMeta();
if (im != null) {
im.setDisplayName(ColorParser.parse(name));
this.item.setItemMeta(im);
}
return this;
}
public ItemStackFactory setLore(@NotNull List<String> loreList) {
ItemMeta im = this.item.getItemMeta();
if (im != null) {
im.setLore(
loreList.stream()
.map(ColorParser::parse)
.collect(Collectors.toList())
);
this.item.setItemMeta(im);
}
return this;
}
public ItemStackFactory setLore(@NotNull List<String> loreList) {
ItemMeta im = this.item.getItemMeta();
if (im != null) {
im.setLore(
loreList.stream()
.map(ColorParser::parse)
.collect(Collectors.toList())
);
this.item.setItemMeta(im);
}
return this;
}
public ItemStackFactory addLore(@NotNull String s) {
ItemMeta im = this.item.getItemMeta();
if (im != null) {
List<String> lore = im.getLore() != null ? im.getLore() : new ArrayList<>();
lore.add(ColorParser.parse(s));
im.setLore(lore);
this.item.setItemMeta(im);
}
return this;
}
public ItemStackFactory addLore(@NotNull String s) {
ItemMeta im = this.item.getItemMeta();
if (im != null) {
List<String> lore = im.getLore() != null ? im.getLore() : new ArrayList<>();
lore.add(ColorParser.parse(s));
im.setLore(lore);
this.item.setItemMeta(im);
}
return this;
}
public ItemStackFactory addEnchant(@NotNull Enchantment enchant, int level, boolean ignoreLevelRestriction) {
ItemMeta im = this.item.getItemMeta();
if (im != null) {
im.addEnchant(enchant, level, ignoreLevelRestriction);
this.item.setItemMeta(im);
}
public ItemStackFactory addEnchant(@NotNull Enchantment enchant, int level, boolean ignoreLevelRestriction) {
ItemMeta im = this.item.getItemMeta();
if (im != null) {
im.addEnchant(enchant, level, ignoreLevelRestriction);
this.item.setItemMeta(im);
}
return this;
}
return this;
}
public ItemStackFactory removeEnchant(@NotNull Enchantment enchant) {
ItemMeta im = this.item.getItemMeta();
if (im != null) {
im.removeEnchant(enchant);
this.item.setItemMeta(im);
}
return this;
}
public ItemStackFactory removeEnchant(@NotNull Enchantment enchant) {
ItemMeta im = this.item.getItemMeta();
if (im != null) {
im.removeEnchant(enchant);
this.item.setItemMeta(im);
}
return this;
}
public ItemStackFactory addFlag(@NotNull ItemFlag flag) {
ItemMeta im = this.item.getItemMeta();
if (im != null) {
im.addItemFlags(flag);
this.item.setItemMeta(im);
}
public ItemStackFactory addFlag(@NotNull ItemFlag flag) {
ItemMeta im = this.item.getItemMeta();
if (im != null) {
im.addItemFlags(flag);
this.item.setItemMeta(im);
}
return this;
}
return this;
}
public ItemStackFactory removeFlag(@NotNull ItemFlag flag) {
ItemMeta im = this.item.getItemMeta();
if (im != null) {
im.removeItemFlags(flag);
this.item.setItemMeta(im);
}
return this;
}
public ItemStackFactory removeFlag(@NotNull ItemFlag flag) {
ItemMeta im = this.item.getItemMeta();
if (im != null) {
im.removeItemFlags(flag);
this.item.setItemMeta(im);
}
return this;
}
public ItemStackFactory setUnbreakable(boolean unbreakable) {
ItemMeta im = this.item.getItemMeta();
if (im != null) {
im.setUnbreakable(unbreakable);
this.item.setItemMeta(im);
}
return this;
}
public ItemStackFactory setUnbreakable(boolean unbreakable) {
ItemMeta im = this.item.getItemMeta();
if (im != null) {
im.setUnbreakable(unbreakable);
this.item.setItemMeta(im);
}
return this;
}
}
@@ -12,344 +12,344 @@ import java.util.concurrent.Callable;
@SuppressWarnings("DuplicatedCode")
public class SchedulerUtils {
private final JavaPlugin plugin;
private final JavaPlugin plugin;
public SchedulerUtils(JavaPlugin plugin) {
this.plugin = plugin;
}
public SchedulerUtils(JavaPlugin plugin) {
this.plugin = plugin;
}
private JavaPlugin getPlugin() {
return plugin;
}
private JavaPlugin getPlugin() {
return plugin;
}
/**
* 在服务端主线程中执行一个任务
*
* @param runnable 需要执行的任务
*/
public void run(Runnable runnable) {
Bukkit.getScheduler().runTask(getPlugin(), runnable);
}
/**
* 在服务端主线程中执行一个任务
*
* @param runnable 需要执行的任务
*/
public void run(Runnable runnable) {
Bukkit.getScheduler().runTask(getPlugin(), runnable);
}
/**
* 异步执行一个任务。
*
* @param runnable 需要执行的任务
*/
public void runAsync(Runnable runnable) {
Bukkit.getScheduler().runTaskAsynchronously(getPlugin(), runnable);
}
/**
* 在主线程延时执行一个任务。
*
* @param delay 延迟的ticks
* @param runnable 需要执行的任务
*/
public void runLater(long delay, Runnable runnable) {
Bukkit.getScheduler().runTaskLater(getPlugin(), runnable, delay);
}
/**
* 异步执行一个任务。
*
* @param runnable 需要执行的任务
*/
public void runAsync(Runnable runnable) {
Bukkit.getScheduler().runTaskAsynchronously(getPlugin(), runnable);
}
/**
* 异步延时执行一个任务。
*
* @param delay 延迟的ticks
* @param runnable 需要执行的任务
*/
public void runLaterAsync(long delay, Runnable runnable) {
Bukkit.getScheduler().runTaskLaterAsynchronously(getPlugin(), runnable, delay);
}
/**
* 在主线程延时执行一个任务。
*
* @param delay 延迟的ticks
* @param runnable 需要执行的任务
*/
public void runLater(long delay, Runnable runnable) {
Bukkit.getScheduler().runTaskLater(getPlugin(), runnable, delay);
}
/**
* 间隔一段时间按顺序执行列表中的任务
*
* @param interval 间隔时间
* @param tasks 任务列表
*/
public void runAtInterval(long interval, Runnable... tasks) {
runAtInterval(0L, interval, tasks);
}
/**
* 异步延时执行一个任务
*
* @param delay 延迟的ticks
* @param runnable 需要执行的任务
*/
public void runLaterAsync(long delay, Runnable runnable) {
Bukkit.getScheduler().runTaskLaterAsynchronously(getPlugin(), runnable, delay);
}
/**
* 间隔一段时间按顺序执行列表中的任务
*
* @param interval 间隔时间
* @param tasks 任务列表
*/
public void runAtInterval(long interval, Runnable... tasks) {
runAtInterval(0L, interval, tasks);
}
/**
* 间隔一段时间按顺序执行列表中的任务
*
* @param delay 延迟时间
* @param interval 间隔时间
* @param tasks 任务列表
*/
public void runAtInterval(long delay, long interval, Runnable... tasks) {
new BukkitRunnable() {
private int index;
/**
* 间隔一段时间按顺序执行列表中的任务
*
* @param delay 延迟时间
* @param interval 间隔时间
* @param tasks 任务列表
*/
public void runAtInterval(long delay, long interval, Runnable... tasks) {
new BukkitRunnable() {
private int index;
@Override
public void run() {
if (this.index >= tasks.length) {
this.cancel();
return;
}
@Override
public void run() {
if (this.index >= tasks.length) {
this.cancel();
return;
}
tasks[index].run();
index++;
}
}.runTaskTimer(getPlugin(), delay, interval);
}
tasks[index].run();
index++;
}
}.runTaskTimer(getPlugin(), delay, interval);
}
/**
* 间隔一段时间按顺序异步执行列表中的任务
*
* @param interval 间隔时间
* @param tasks 任务列表
*/
public void runAtIntervalAsync(long interval, Runnable... tasks) {
runAtIntervalAsync(0L, interval, tasks);
}
/**
* 间隔一段时间按顺序异步执行列表中的任务
*
* @param interval 间隔时间
* @param tasks 任务列表
*/
public void runAtIntervalAsync(long interval, Runnable... tasks) {
runAtIntervalAsync(0L, interval, tasks);
}
/**
* 间隔一段时间按顺序异步执行列表中的任务
*
* @param delay 延迟时间
* @param interval 间隔时间
* @param tasks 任务列表
*/
public void runAtIntervalAsync(long delay, long interval, Runnable... tasks) {
new BukkitRunnable() {
private int index;
/**
* 间隔一段时间按顺序异步执行列表中的任务
*
* @param delay 延迟时间
* @param interval 间隔时间
* @param tasks 任务列表
*/
public void runAtIntervalAsync(long delay, long interval, Runnable... tasks) {
new BukkitRunnable() {
private int index;
@Override
public void run() {
if (this.index >= tasks.length) {
this.cancel();
return;
}
@Override
public void run() {
if (this.index >= tasks.length) {
this.cancel();
return;
}
tasks[index].run();
index++;
}
}.runTaskTimerAsynchronously(getPlugin(), delay, interval);
}
tasks[index].run();
index++;
}
}.runTaskTimerAsynchronously(getPlugin(), delay, interval);
}
/**
* 重复执行一个任务。
*
* @param repetitions 重复次数
* @param interval 间隔时间
* @param task 任务
* @param onComplete 结束时执行的任务
*/
public void repeat(int repetitions, long interval, Runnable task, Runnable onComplete) {
new BukkitRunnable() {
private int index;
/**
* 重复执行一个任务。
*
* @param repetitions 重复次数
* @param interval 间隔时间
* @param task 任务
* @param onComplete 结束时执行的任务
*/
public void repeat(int repetitions, long interval, Runnable task, Runnable onComplete) {
new BukkitRunnable() {
private int index;
@Override
public void run() {
index++;
if (this.index >= repetitions) {
this.cancel();
if (onComplete == null) {
return;
}
@Override
public void run() {
index++;
if (this.index >= repetitions) {
this.cancel();
if (onComplete == null) {
return;
}
onComplete.run();
return;
}
onComplete.run();
return;
}
task.run();
}
}.runTaskTimer(getPlugin(), 0L, interval);
}
task.run();
}
}.runTaskTimer(getPlugin(), 0L, interval);
}
/**
* 重复执行一个任务。
*
* @param repetitions 重复次数
* @param interval 间隔时间
* @param task 任务
* @param onComplete 结束时执行的任务
*/
public void repeatAsync(int repetitions, long interval, Runnable task, Runnable onComplete) {
new BukkitRunnable() {
private int index;
/**
* 重复执行一个任务。
*
* @param repetitions 重复次数
* @param interval 间隔时间
* @param task 任务
* @param onComplete 结束时执行的任务
*/
public void repeatAsync(int repetitions, long interval, Runnable task, Runnable onComplete) {
new BukkitRunnable() {
private int index;
@Override
public void run() {
index++;
if (this.index >= repetitions) {
this.cancel();
if (onComplete == null) {
return;
}
@Override
public void run() {
index++;
if (this.index >= repetitions) {
this.cancel();
if (onComplete == null) {
return;
}
onComplete.run();
return;
}
onComplete.run();
return;
}
task.run();
}
}.runTaskTimerAsynchronously(getPlugin(), 0L, interval);
}
task.run();
}
}.runTaskTimerAsynchronously(getPlugin(), 0L, interval);
}
/**
* 在满足某个条件时,重复执行一个任务。
*
* @param interval 重复间隔时间
* @param predicate 条件
* @param task 任务
* @param onComplete 结束时执行的任务
*/
public void repeatWhile(long interval, Callable<Boolean> predicate, Runnable task, Runnable onComplete) {
new BukkitRunnable() {
@Override
public void run() {
try {
if (!predicate.call()) {
this.cancel();
if (onComplete == null) {
return;
}
/**
* 在满足某个条件时,重复执行一个任务。
*
* @param interval 重复间隔时间
* @param predicate 条件
* @param task 任务
* @param onComplete 结束时执行的任务
*/
public void repeatWhile(long interval, Callable<Boolean> predicate, Runnable task, Runnable onComplete) {
new BukkitRunnable() {
@Override
public void run() {
try {
if (!predicate.call()) {
this.cancel();
if (onComplete == null) {
return;
}
onComplete.run();
return;
}
onComplete.run();
return;
}
task.run();
} catch (Exception e) {
e.printStackTrace();
}
}
}.runTaskTimer(getPlugin(), 0L, interval);
}
task.run();
} catch (Exception e) {
e.printStackTrace();
}
}
}.runTaskTimer(getPlugin(), 0L, interval);
}
/**
* 在满足某个条件时,重复执行一个任务。
*
* @param interval 重复间隔时间
* @param predicate 条件
* @param task 任务
* @param onComplete 结束时执行的任务
*/
public void repeatWhileAsync(long interval, Callable<Boolean> predicate, Runnable task, Runnable onComplete) {
new BukkitRunnable() {
@Override
public void run() {
try {
if (!predicate.call()) {
this.cancel();
if (onComplete == null) {
return;
}
/**
* 在满足某个条件时,重复执行一个任务。
*
* @param interval 重复间隔时间
* @param predicate 条件
* @param task 任务
* @param onComplete 结束时执行的任务
*/
public void repeatWhileAsync(long interval, Callable<Boolean> predicate, Runnable task, Runnable onComplete) {
new BukkitRunnable() {
@Override
public void run() {
try {
if (!predicate.call()) {
this.cancel();
if (onComplete == null) {
return;
}
onComplete.run();
return;
}
onComplete.run();
return;
}
task.run();
} catch (Exception e) {
e.printStackTrace();
}
}
}.runTaskTimerAsynchronously(getPlugin(), 0L, interval);
}
task.run();
} catch (Exception e) {
e.printStackTrace();
}
}
}.runTaskTimerAsynchronously(getPlugin(), 0L, interval);
}
public interface Task {
void start(Runnable onComplete);
}
public interface Task {
void start(Runnable onComplete);
}
public class TaskBuilder {
private final Queue<Task> taskList;
public class TaskBuilder {
private final Queue<Task> taskList;
public TaskBuilder() {
this.taskList = new LinkedList<>();
}
public TaskBuilder() {
this.taskList = new LinkedList<>();
}
public TaskBuilder append(TaskBuilder builder) {
this.taskList.addAll(builder.taskList);
return this;
}
public TaskBuilder append(TaskBuilder builder) {
this.taskList.addAll(builder.taskList);
return this;
}
public TaskBuilder appendDelay(long delay) {
this.taskList.add(onComplete -> SchedulerUtils.this.runLater(delay, onComplete));
return this;
}
public TaskBuilder appendDelay(long delay) {
this.taskList.add(onComplete -> SchedulerUtils.this.runLater(delay, onComplete));
return this;
}
public TaskBuilder appendTask(Runnable task) {
this.taskList.add(onComplete ->
{
task.run();
onComplete.run();
});
public TaskBuilder appendTask(Runnable task) {
this.taskList.add(onComplete ->
{
task.run();
onComplete.run();
});
return this;
}
return this;
}
public TaskBuilder appendTask(Task task) {
this.taskList.add(task);
return this;
}
public TaskBuilder appendTask(Task task) {
this.taskList.add(task);
return this;
}
public TaskBuilder appendDelayedTask(long delay, Runnable task) {
this.taskList.add(onComplete -> SchedulerUtils.this.runLater(delay, () ->
{
task.run();
onComplete.run();
}));
public TaskBuilder appendDelayedTask(long delay, Runnable task) {
this.taskList.add(onComplete -> SchedulerUtils.this.runLater(delay, () ->
{
task.run();
onComplete.run();
}));
return this;
}
return this;
}
public TaskBuilder appendTasks(long delay, long interval, Runnable... tasks) {
this.taskList.add(onComplete ->
{
Runnable[] runnables = Arrays.copyOf(tasks, tasks.length + 1);
runnables[runnables.length - 1] = onComplete;
SchedulerUtils.this.runAtInterval(delay, interval, runnables);
});
public TaskBuilder appendTasks(long delay, long interval, Runnable... tasks) {
this.taskList.add(onComplete ->
{
Runnable[] runnables = Arrays.copyOf(tasks, tasks.length + 1);
runnables[runnables.length - 1] = onComplete;
SchedulerUtils.this.runAtInterval(delay, interval, runnables);
});
return this;
}
return this;
}
public TaskBuilder appendRepeatingTask(int repetitions, long interval, Runnable task) {
this.taskList.add(onComplete -> SchedulerUtils.this.repeat(repetitions, interval, task, onComplete));
return this;
}
public TaskBuilder appendRepeatingTask(int repetitions, long interval, Runnable task) {
this.taskList.add(onComplete -> SchedulerUtils.this.repeat(repetitions, interval, task, onComplete));
return this;
}
public TaskBuilder appendConditionalRepeatingTask(long interval, Callable<Boolean> predicate, Runnable task) {
this.taskList.add(onComplete -> SchedulerUtils.this.repeatWhile(interval, predicate, task, onComplete));
return this;
}
public TaskBuilder appendConditionalRepeatingTask(long interval, Callable<Boolean> predicate, Runnable task) {
this.taskList.add(onComplete -> SchedulerUtils.this.repeatWhile(interval, predicate, task, onComplete));
return this;
}
public TaskBuilder waitFor(Callable<Boolean> predicate) {
this.taskList.add(onComplete -> new BukkitRunnable() {
@Override
public void run() {
try {
if (!predicate.call()) {
return;
}
public TaskBuilder waitFor(Callable<Boolean> predicate) {
this.taskList.add(onComplete -> new BukkitRunnable() {
@Override
public void run() {
try {
if (!predicate.call()) {
return;
}
this.cancel();
onComplete.run();
} catch (Exception e) {
e.printStackTrace();
}
}
}.runTaskTimer(getPlugin(), 0L, 1L));
return this;
}
this.cancel();
onComplete.run();
} catch (Exception e) {
e.printStackTrace();
}
}
}.runTaskTimer(getPlugin(), 0L, 1L));
return this;
}
public void runTasks() {
this.startNext();
}
public void runTasks() {
this.startNext();
}
private void startNext() {
Task task = this.taskList.poll();
if (task == null) {
return;
}
private void startNext() {
Task task = this.taskList.poll();
if (task == null) {
return;
}
task.start(this::startNext);
}
}
task.start(this::startNext);
}
}
}
+27
View File
@@ -0,0 +1,27 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>easyplugin-parent</artifactId>
<groupId>cc.carm.lib</groupId>
<version>1.4.10</version>
<relativePath>../../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<properties>
<maven.compiler.source>${project.jdk.version}</maven.compiler.source>
<maven.compiler.target>${project.jdk.version}</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.encoding>UTF-8</maven.compiler.encoding>
</properties>
<artifactId>easyplugin-storage</artifactId>
<packaging>jar</packaging>
<name>EasyPlugin-Storage</name>
<description>轻松插件存储接口模块,包含存储相关的统一接口。</description>
<url>https://github.com/CarmJos/EasyPlugin</url>
</project>
@@ -0,0 +1,40 @@
package cc.carm.lib.easyplugin.storage;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public interface DataStorage<K, T> {
/**
* 在插件加载存储源时执行。
*
* @throws Exception 当出现任何错误时抛出
*/
void initialize() throws Exception;
/**
* 在插件被卸载时执行。
*/
void shutdown();
/**
* 用于加载数据的方法。<b>该方法应当异步运行!</b>
* <br>
* <br>若不存在对应数据,请返回 null 。
* <br>若加载出现任何错误,请抛出异常。
*
* @param key 数据主键
* @throws Exception 当出现任何错误时抛出
*/
@Nullable
T loadData(@NotNull K key) throws Exception;
/**
* 用于保存数据的方法。 <b>该方法应当被异步运行!</b>
*
* @param data 数据
* @throws Exception 当出现任何错误时抛出
*/
void saveData(@NotNull T data) throws Exception;
}
@@ -0,0 +1,19 @@
package cc.carm.lib.easyplugin.storage;
import org.jetbrains.annotations.NotNull;
import java.util.List;
public interface StorageType<K, T, S extends DataStorage<K, T>> {
int getID();
@NotNull List<String> getAlias();
@NotNull Class<? extends S> getStorageClass();
default @NotNull S createStorage() throws Exception {
return getStorageClass().newInstance();
}
}
@@ -0,0 +1,31 @@
package cc.carm.lib.easyplugin.storage.file;
import cc.carm.lib.easyplugin.storage.DataStorage;
import org.jetbrains.annotations.NotNull;
import java.io.File;
public abstract class FileBasedStorage<K, T> implements DataStorage<K, T> {
protected final String fileName;
protected File dataFile;
public FileBasedStorage(String fileName) {
this.fileName = fileName;
}
protected @NotNull File initializeFile(@NotNull File parentFolder) throws Exception {
this.dataFile = new File(parentFolder, fileName);
if (!dataFile.exists()) {
if (!dataFile.createNewFile()) throw new Exception("无法创建数据文件!");
} else if (dataFile.isDirectory()) {
throw new Exception("文件路径对应的不是一个文件!");
}
return dataFile;
}
public File getDataFile() {
return dataFile;
}
}
@@ -0,0 +1,46 @@
package cc.carm.lib.easyplugin.storage.file;
import cc.carm.lib.easyplugin.storage.DataStorage;
import org.jetbrains.annotations.NotNull;
import java.io.File;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public abstract class FolderBasedStorage<K, T> implements DataStorage<K, T> {
protected final @NotNull String folderPath;
protected File dataFolder;
public FolderBasedStorage(@NotNull String folderPath) {
this.folderPath = folderPath;
}
protected @NotNull File initializeFolder(@NotNull File parentFolder) throws Exception {
this.dataFolder = new File(parentFolder, folderPath);
if (!dataFolder.exists()) {
if (!dataFolder.mkdir()) {
throw new Exception("无法创建数据文件夹!");
}
} else if (!dataFolder.isDirectory()) {
throw new Exception("数据文件夹路径对应的不是一个文件夹!");
}
return dataFolder;
}
protected @NotNull List<File> listFiles() {
if (this.dataFolder == null) return Collections.emptyList();
if (!this.dataFolder.isDirectory()) return Collections.emptyList();
File[] files = this.dataFolder.listFiles();
if (files == null) return Collections.emptyList();
return Arrays.asList(files);
}
public File getDataFolder() {
return dataFolder;
}
}
@@ -0,0 +1,24 @@
package cc.carm.lib.easyplugin.storage.file;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.jetbrains.annotations.NotNull;
import java.io.File;
public abstract class YAMLBasedStorage<K, T> extends FileBasedStorage<K, T> {
protected FileConfiguration configuration;
public YAMLBasedStorage(String fileName) {
super(fileName);
}
protected @NotNull FileConfiguration initializeConfiguration(@NotNull File parentFolder) throws Exception {
return this.configuration = YamlConfiguration.loadConfiguration(initializeFile(parentFolder));
}
public FileConfiguration getConfiguration() {
return configuration;
}
}
@@ -0,0 +1,31 @@
package cc.carm.lib.easyplugin.storage.plugin;
import cc.carm.lib.easyplugin.storage.DataStorage;
import org.bukkit.Bukkit;
import org.bukkit.plugin.Plugin;
public abstract class PluginBasedStorage<K, T> implements DataStorage<K, T> {
protected Plugin dependPlugin;
public PluginBasedStorage(String dependPluginName) {
this(Bukkit.getPluginManager().getPlugin(dependPluginName));
}
public PluginBasedStorage(Plugin dependPlugin) {
this.dependPlugin = dependPlugin;
}
@Override
public void initialize() throws NullPointerException {
if (dependPlugin == null) {
throw new NullPointerException("该存储类型依赖的插件不存在,请检查配置文件");
}
}
public Plugin getDependPlugin() {
return dependPlugin;
}
}
+1 -1
View File
@@ -5,7 +5,7 @@
<parent>
<artifactId>easyplugin-parent</artifactId>
<groupId>cc.carm.lib</groupId>
<version>1.4.4-SNAPSHOT</version>
<version>1.4.10</version>
<relativePath>../../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
+1 -1
View File
@@ -5,7 +5,7 @@
<parent>
<artifactId>easyplugin-parent</artifactId>
<groupId>cc.carm.lib</groupId>
<version>1.4.4-SNAPSHOT</version>
<version>1.4.10</version>
<relativePath>../../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
+1 -1
View File
@@ -5,7 +5,7 @@
<parent>
<artifactId>easyplugin-parent</artifactId>
<groupId>cc.carm.lib</groupId>
<version>1.4.4-SNAPSHOT</version>
<version>1.4.10</version>
<relativePath>../../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
+34
View File
@@ -0,0 +1,34 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>easyplugin-parent</artifactId>
<groupId>cc.carm.lib</groupId>
<version>1.4.10</version>
<relativePath>../../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<properties>
<maven.compiler.source>${project.jdk.version}</maven.compiler.source>
<maven.compiler.target>${project.jdk.version}</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.encoding>UTF-8</maven.compiler.encoding>
</properties>
<artifactId>easyplugin-githubchecker</artifactId>
<packaging>jar</packaging>
<name>EasyPlugin-GithubChecker</name>
<dependencies>
<dependency>
<groupId>cc.carm.lib</groupId>
<artifactId>githubreleases4j</artifactId>
<scope>compile</scope>
</dependency>
</dependencies>
</project>
@@ -0,0 +1,84 @@
package cc.carm.lib.easyplugin.updatechecker;
import cc.carm.lib.githubreleases4j.GithubReleases4J;
import org.bukkit.plugin.Plugin;
import org.jetbrains.annotations.NotNull;
import java.util.List;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class GHUpdateChecker {
protected static final @NotNull Pattern GH_URL_PATTERN = Pattern.compile("^https?://github.com/([A-Za-z\\d-_]+)/([^/]*?)/?");
public static @NotNull GHUpdateChecker of(@NotNull Logger logger, @NotNull String owner, @NotNull String repo) {
return new GHUpdateChecker(logger, owner, repo);
}
public static @NotNull GHUpdateChecker of(@NotNull Plugin plugin) {
return new GHUpdateChecker(plugin.getLogger(), getGithubOwner(plugin), plugin.getName());
}
public static @NotNull Runnable runner(@NotNull Logger logger,
@NotNull String owner, @NotNull String repo,
@NotNull String currentVersion) {
return of(logger, owner, repo).runner(currentVersion);
}
public static @NotNull Runnable runner(@NotNull Plugin plugin) {
return of(plugin).runner(plugin.getDescription().getVersion());
}
protected final @NotNull Logger logger;
protected final @NotNull String owner;
protected final @NotNull String repo;
public GHUpdateChecker(@NotNull Logger logger, @NotNull String owner, @NotNull String repo) {
this.logger = logger;
this.owner = owner;
this.repo = repo;
}
public void checkUpdate(@NotNull String currentVersion) {
Integer behindVersions = GithubReleases4J.getVersionBehind(owner, repo, currentVersion);
String downloadURL = GithubReleases4J.getReleasesURL(owner, repo);
if (behindVersions == null) {
this.logger.severe("检查更新失败,请您定期查看插件是否更新,避免安全问题。");
this.logger.severe("下载地址 " + downloadURL);
} else if (behindVersions == 0) {
this.logger.info("检查完成,当前已是最新版本。");
} else if (behindVersions > 0) {
this.logger.info("发现新版本! 目前已落后 " + behindVersions + " 个版本。");
this.logger.info("最新版下载地址 " + downloadURL);
} else {
this.logger.severe("检查更新失败! 当前版本未知,请您使用原生版本以避免安全问题。");
this.logger.severe("最新版下载地址 " + downloadURL);
}
}
public Runnable runner(@NotNull String currentVersion) {
return () -> checkUpdate(currentVersion);
}
protected static String getGithubOwner(Plugin plugin) {
// 首先,尝试从插件提供的网址中获取OWNER
String websiteOwner = getGithubOwner(plugin.getDescription().getWebsite());
if (websiteOwner != null && !websiteOwner.isEmpty()) return websiteOwner;
// 如果插件提供的网址中没有,则尝试获取插件的首位作者名
List<String> authors = plugin.getDescription().getAuthors();
if (!authors.isEmpty()) return authors.get(0);
// 再没有的话只能返回插件的名称了
return plugin.getName();
}
protected static String getGithubOwner(String url) {
Matcher matcher = GH_URL_PATTERN.matcher(url);
return matcher.find() ? matcher.group(1) : null;
}
}
@@ -0,0 +1,16 @@
package cc.carm.lib.easyplugin.updatechecker;
import org.junit.Test;
public class RegexTest {
@Test
public void onTest() {
System.out.println(GHUpdateChecker.getGithubOwner("https://github.com/CarmJos/EasyPlugin"));
System.out.println(GHUpdateChecker.getGithubOwner("https://github.com/Ghost-chu/QuickShop-Hikari/pulls"));
System.out.println(GHUpdateChecker.getGithubOwner("https://github.com/QWQ123/QuickShop"));
}
}
+1 -2
View File
@@ -5,7 +5,7 @@
<parent>
<artifactId>easyplugin-parent</artifactId>
<groupId>cc.carm.lib</groupId>
<version>1.4.4-SNAPSHOT</version>
<version>1.4.10</version>
<relativePath>../../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
@@ -27,7 +27,6 @@
<dependency>
<groupId>me.clip</groupId>
<artifactId>placeholderapi</artifactId>
<version>2.10.9</version>
<scope>provided</scope>
</dependency>
+2 -2
View File
@@ -5,7 +5,7 @@
<parent>
<artifactId>easyplugin-parent</artifactId>
<groupId>cc.carm.lib</groupId>
<version>1.4.4-SNAPSHOT</version>
<version>1.4.10</version>
<relativePath>../../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
@@ -24,10 +24,10 @@
<dependencies>
<!--suppress VulnerableLibrariesLocal -->
<dependency>
<groupId>com.github.MilkBowl</groupId>
<artifactId>VaultAPI</artifactId>
<version>1.7</version>
<scope>provided</scope>
</dependency>
+56 -30
View File
@@ -15,7 +15,7 @@
<groupId>cc.carm.lib</groupId>
<artifactId>easyplugin-parent</artifactId>
<packaging>pom</packaging>
<version>1.4.4-SNAPSHOT</version>
<version>1.4.10</version>
<modules>
<module>base/main</module>
@@ -24,10 +24,12 @@
<module>extension/papi</module>
<module>extension/vault</module>
<module>extension/gh-checker</module>
<module>collection/all</module>
<module>collection/bom</module>
<module>collection/common</module>
<module>base/storage</module>
</modules>
@@ -122,6 +124,26 @@
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>me.clip</groupId>
<artifactId>placeholderapi</artifactId>
<version>2.10.9</version>
</dependency>
<dependency>
<groupId>com.github.MilkBowl</groupId>
<artifactId>VaultAPI</artifactId>
<version>1.7</version>
</dependency>
<dependency>
<groupId>cc.carm.lib</groupId>
<artifactId>githubreleases4j</artifactId>
<version>1.3.1</version>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
@@ -132,6 +154,39 @@
<useSystemClassLoader>false</useSystemClassLoader>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>${project.jdk.version}</source>
<target>${project.jdk.version}</target>
<encoding>UTF-8</encoding>
<compilerArgument>-parameters</compilerArgument>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>3.2.0</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<version>3.2.0</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>jar-no-fork</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
</plugin>
</plugins>
<pluginManagement>
<plugins>
@@ -156,35 +211,6 @@
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
<compilerArgument>-parameters</compilerArgument>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>3.2.0</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<version>3.2.0</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>jar-no-fork</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>