feat: 初版提交

This commit is contained in:
2024-01-20 04:57:37 +08:00
commit 29c6b1bf2f
30 changed files with 2249 additions and 0 deletions

43
.gitignore vendored Normal file
View File

@@ -0,0 +1,43 @@
.gradle
.idea
build/
!gradle/wrapper/gradle-wrapper.jar
!**/src/main/**/build/
!**/src/test/**/build/
### IntelliJ IDEA ###
.idea/modules.xml
.idea/jarRepositories.xml
.idea/compiler.xml
.idea/libraries/
*.iws
*.iml
*.ipr
out/
!**/src/main/**/out/
!**/src/test/**/out/
### Eclipse ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
bin/
!**/src/main/**/bin/
!**/src/test/**/bin/
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
### VS Code ###
.vscode/
### Mac OS ###
.DS_Store

43
build.gradle.kts Normal file
View File

@@ -0,0 +1,43 @@
@file:Suppress("VulnerableLibrariesLocal")
plugins {
id("java")
}
group = "cn.hamster3.mc.plugin"
version = "3.1.0"
repositories {
maven("https://maven.airgame.net/maven-public/")
}
dependencies {
compileOnly("org.jetbrains:annotations:24.1.0")
compileOnly("org.projectlombok:lombok:1.18.30")
annotationProcessor("org.projectlombok:lombok:1.18.30")
compileOnly("org.spigotmc:spigot-api:1.18.2-R0.1-SNAPSHOT")
compileOnly("cn.hamster3.mc.plugin:core-bukkit:1.2.0")
compileOnly("cn.hamster3.mc.plugin:ball-bukkit:1.5.0")
compileOnly("net.milkbowl.vault:VaultAPI:1.7")
compileOnly("me.clip:placeholderapi:+")
}
tasks {
processResources {
filesMatching("plugin.yml") {
expand(project.properties)
}
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
}
withType<JavaCompile> {
options.encoding = "UTF-8"
}
withType<Jar> {
archiveBaseName = "HamsterCurrency"
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
}
jar {
destinationDirectory = rootProject.layout.buildDirectory
}
}

BIN
gradle/wrapper/gradle-wrapper.jar vendored Normal file

Binary file not shown.

View File

@@ -0,0 +1,6 @@
#Sat Jan 13 22:44:56 CST 2024
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.4-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

234
gradlew vendored Normal file
View File

@@ -0,0 +1,234 @@
#!/bin/sh
#
# Copyright © 2015-2021 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
APP_NAME="Gradle"
APP_BASE_NAME=${0##*/}
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Collect all arguments for the java command;
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
# shell script including quotes and variable substitutions, so put them in
# double quotes to make sure that they get re-expanded; and
# * put everything else in single quotes, so that it's not re-expanded.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \
"$@"
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"

89
gradlew.bat vendored Normal file
View File

@@ -0,0 +1,89 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto execute
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

2
settings.gradle.kts Normal file
View File

@@ -0,0 +1,2 @@
rootProject.name = "hamster-currency"

View File

@@ -0,0 +1,117 @@
package cn.hamster3.mc.plugin.currency;
import cn.hamster3.mc.plugin.ball.common.api.BallAPI;
import cn.hamster3.mc.plugin.currency.command.currency.ParentCurrencyCommand;
import cn.hamster3.mc.plugin.currency.core.ConfigManager;
import cn.hamster3.mc.plugin.currency.core.CurrencyDataManager;
import cn.hamster3.mc.plugin.currency.core.CurrencyMessage;
import cn.hamster3.mc.plugin.currency.data.CurrencyType;
import cn.hamster3.mc.plugin.currency.hook.PlaceholderHook;
import cn.hamster3.mc.plugin.currency.hook.VaultEconomyHook;
import cn.hamster3.mc.plugin.currency.listener.BallListener;
import cn.hamster3.mc.plugin.currency.listener.CurrencyListener;
import lombok.Getter;
import net.milkbowl.vault.economy.Economy;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.plugin.ServicePriority;
import org.bukkit.plugin.java.JavaPlugin;
import org.jetbrains.annotations.NotNull;
import java.sql.SQLException;
import java.util.logging.Logger;
public class CurrencyPlugin extends JavaPlugin {
public static final String BALL_CHANNEL = "HamsterCurrency";
@Getter
private static CurrencyPlugin instance;
@SuppressWarnings("unused")
public static void sync(@NotNull Runnable runnable) {
Bukkit.getScheduler().runTask(instance, runnable);
}
public static void async(@NotNull Runnable runnable) {
Bukkit.getScheduler().runTaskAsynchronously(instance, runnable);
}
@Override
public void onLoad() {
instance = this;
Logger logger = getLogger();
long start = System.currentTimeMillis();
logger.info("仓鼠经济正在初始化");
ConfigManager.init();
logger.info("已读取配置文件");
CurrencyMessage.init(this);
logger.info("已初始化语言文本");
try {
CurrencyDataManager.init();
logger.info("已初始化 CurrencyDataManager");
} catch (SQLException e) {
e.printStackTrace();
}
if (Bukkit.getPluginManager().getPlugin("Vault") != null) {
logger.info("检测到 Vault 已安装");
CurrencyType vaultType = CurrencyDataManager.getVaultCurrencyType();
if (vaultType == null) {
logger.info("未设置任何经济类型挂载至 Vault");
} else {
Bukkit.getServicesManager().register(Economy.class, new VaultEconomyHook(vaultType), this, ServicePriority.Normal);
logger.info(String.format("已挂载货币类型 %s(%s) 至 Vault 系统", vaultType.getId(), vaultType.getName()));
if (ConfigManager.isEnableVaultCommands()) {
logger.info("本插件暂不支持 vault 指令");
}
}
} else {
logger.warning("未找到 Vault 插件! 取消注册 Vault 经济系统");
}
if (Bukkit.getPluginManager().getPlugin("PlaceholderAPI") != null) {
logger.info("检测到 PlaceholderAPI 已安装");
if (PlaceholderHook.INSTANCE.register()) {
logger.info("已挂载 PlaceholderAPI 变量");
}
} else {
logger.warning("未检测到 PlaceholderAPI");
}
long time = System.currentTimeMillis() - start;
logger.info("仓鼠经济初始化完成,总计耗时 " + time + " ms");
}
@Override
public void onEnable() {
Logger logger = getLogger();
long start = System.currentTimeMillis();
logger.info("仓鼠经济正在启动");
BallAPI.getInstance().getEventBus().register(BallListener.INSTANCE);
logger.info("已注册 BallListener");
Bukkit.getPluginManager().registerEvents(CurrencyListener.INSTANCE, this);
logger.info("已注册 CurrencyListener");
ParentCurrencyCommand.INSTANCE.register();
long time = System.currentTimeMillis() - start;
logger.info("仓鼠经济启动完成,总计耗时 " + time + " ms");
async(() -> {
for (Player player : Bukkit.getOnlinePlayers()) {
try {
CurrencyDataManager.loadPlayerData(player.getUniqueId());
} catch (SQLException e) {
e.printStackTrace();
}
}
});
}
@Override
public void onDisable() {
Logger logger = getLogger();
long start = System.currentTimeMillis();
logger.info("仓鼠经济正在关闭");
Bukkit.getServicesManager().unregister(this);
logger.info("已注销所有插件服务");
long time = System.currentTimeMillis() - start;
logger.info("仓鼠经济已关闭,总计耗时 " + time + " ms");
}
}

View File

@@ -0,0 +1,84 @@
package cn.hamster3.mc.plugin.currency.api;
import cn.hamster3.mc.plugin.core.bukkit.hook.PointAPI;
import cn.hamster3.mc.plugin.currency.CurrencyPlugin;
import cn.hamster3.mc.plugin.currency.core.CurrencyDataManager;
import cn.hamster3.mc.plugin.currency.data.CurrencyType;
import org.bukkit.Bukkit;
import org.jetbrains.annotations.NotNull;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
/**
* 当 currencyID 为 PlayerPoints 且服务器安装了点券插件时,会自动更改为 PlayerPoints 接口
*/
@SuppressWarnings({"unused", "CallToPrintStackTrace"})
public final class CurrencyAPI {
private CurrencyAPI() {
}
public static double getPlayerCurrency(@NotNull UUID uuid, @NotNull String currencyID) {
if (currencyID.equals("PlayerPoints") && Bukkit.getPluginManager().isPluginEnabled("PlayerPoints")) {
return PointAPI.getPoint(uuid);
}
return CurrencyDataManager.getPlayerCurrency(uuid, currencyID);
}
public static void setPlayerCurrency(UUID uuid, @NotNull String currencyID, double amount) {
if (currencyID.equals("PlayerPoints") && Bukkit.getPluginManager().isPluginEnabled("PlayerPoints")) {
PointAPI.setPoint(uuid, (int) amount);
return;
}
CurrencyPlugin.async(() -> {
try {
CurrencyDataManager.setPlayerCurrency(uuid, currencyID, amount, true);
} catch (SQLException e) {
e.printStackTrace();
}
});
}
public static void addPlayerCurrency(UUID uuid, String currencyID, double amount) {
if (currencyID.equals("PlayerPoints") && Bukkit.getPluginManager().isPluginEnabled("PlayerPoints")) {
PointAPI.givePoint(uuid, (int) amount);
return;
}
CurrencyPlugin.async(() -> {
try {
double currency = CurrencyDataManager.getPlayerCurrency(uuid, currencyID);
currency += amount;
CurrencyDataManager.setPlayerCurrency(uuid, currencyID, currency, true);
} catch (SQLException e) {
e.printStackTrace();
}
});
}
public static void takePlayerCurrency(UUID uuid, String currencyID, double amount) {
if (currencyID.equals("PlayerPoints") && Bukkit.getPluginManager().isPluginEnabled("PlayerPoints")) {
PointAPI.takePoint(uuid, (int) amount);
return;
}
CurrencyPlugin.async(() -> {
try {
double currency = CurrencyDataManager.getPlayerCurrency(uuid, currencyID);
currency -= amount;
CurrencyDataManager.setPlayerCurrency(uuid, currencyID, currency, true);
} catch (SQLException e) {
e.printStackTrace();
}
});
}
public static boolean hasPlayerCurrency(UUID uuid, String currencyID, double amount) {
return getPlayerCurrency(uuid, currencyID) >= amount;
}
public List<CurrencyType> getAllCurrencyType() {
return new ArrayList<>(CurrencyDataManager.getCurrencyTypes());
}
}

View File

@@ -0,0 +1,109 @@
package cn.hamster3.mc.plugin.currency.command.currency;
import cn.hamster3.mc.plugin.core.bukkit.command.ChildCommand;
import cn.hamster3.mc.plugin.currency.CurrencyPlugin;
import cn.hamster3.mc.plugin.currency.core.CurrencyDataManager;
import cn.hamster3.mc.plugin.currency.core.CurrencyMessage;
import cn.hamster3.mc.plugin.currency.data.CurrencyType;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.sql.SQLException;
import java.util.Collections;
import java.util.List;
public class CurrencyCreateCommand extends ChildCommand {
public static final CurrencyCreateCommand INSTANCE = new CurrencyCreateCommand();
private CurrencyCreateCommand() {
}
@Override
public @NotNull String getName() {
return "create";
}
@Override
public @NotNull String getUsage() {
return "create <货币ID> <货币名称> <vault挂接(t|f)> <支持转账(t|f)>";
}
@Override
public boolean hasPermission(@NotNull CommandSender sender) {
return sender.hasPermission("hamster.currency.admin");
}
@Override
public @NotNull String getDescription() {
return "创建货币类型";
}
@Override
public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) {
if (args.length < 4) {
ParentCurrencyCommand.INSTANCE.sendHelp(sender);
return true;
}
if (CurrencyDataManager.getCurrencyType(args[0]) != null) {
CurrencyMessage.CURRENCY_TYPE_EXISTED.show(sender);
return true;
}
String id = args[0];
if (!id.matches("[a-zA-Z0-9-_]{0,36}")) {
CurrencyMessage.CURRENCY_TYPE_ID_ERROR.show(sender);
return true;
}
String name = args[1];
if (name.length() > 36) {
CurrencyMessage.CURRENCY_TYPE_NAME_TOO_LONG.show(sender);
return true;
}
boolean vault;
switch (args[2]) {
case "t": {
vault = true;
break;
}
case "f": {
vault = false;
break;
}
default: {
CurrencyMessage.CURRENCY_TYPE_VAULT_INPUT_ERROR.show(sender);
return true;
}
}
boolean transferable;
switch (args[3]) {
case "t": {
transferable = true;
break;
}
case "f": {
transferable = false;
break;
}
default: {
CurrencyMessage.CURRENCY_TYPE_TRANSFERABLE_INPUT_ERROR.show(sender);
return true;
}
}
CurrencyPlugin.async(() -> {
try {
CurrencyDataManager.setCurrencyType(new CurrencyType(id, name, vault, transferable), true);
CurrencyMessage.CURRENCY_CREATE_SUCCESS.show(sender);
} catch (SQLException e) {
e.printStackTrace();
}
});
return true;
}
@Nullable
@Override
public List<String> onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) {
return Collections.emptyList();
}
}

View File

@@ -0,0 +1,77 @@
package cn.hamster3.mc.plugin.currency.command.currency;
import cn.hamster3.mc.plugin.core.bukkit.command.ChildCommand;
import cn.hamster3.mc.plugin.currency.CurrencyPlugin;
import cn.hamster3.mc.plugin.currency.core.CurrencyDataManager;
import cn.hamster3.mc.plugin.currency.core.CurrencyMessage;
import cn.hamster3.mc.plugin.currency.data.CurrencyType;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.sql.SQLException;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
public class CurrencyDeleteCommand extends ChildCommand {
public static final CurrencyDeleteCommand INSTANCE = new CurrencyDeleteCommand();
private CurrencyDeleteCommand() {
}
@Override
public @NotNull String getName() {
return "delete";
}
@Override
public @NotNull String getUsage() {
return "delete <货币ID>";
}
@Override
public boolean hasPermission(@NotNull CommandSender sender) {
return sender.hasPermission("hamster.currency.admin");
}
@Override
public @NotNull String getDescription() {
return "删除货币类型";
}
@Override
public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) {
if (args.length < 1) {
ParentCurrencyCommand.INSTANCE.sendHelp(sender);
return true;
}
CurrencyType type = CurrencyDataManager.getCurrencyType(args[0]);
if (type == null) {
CurrencyMessage.CURRENCY_TYPE_NOT_EXIST.show(sender);
return true;
}
CurrencyPlugin.async(() -> {
try {
CurrencyDataManager.deleteCurrencyType(type.getId(), true);
CurrencyMessage.CURRENCY_DELETE_SUCCESS.show(sender);
} catch (SQLException e) {
e.printStackTrace();
}
});
return true;
}
@Nullable
@Override
public List<String> onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) {
if (args.length == 1) {
return CurrencyDataManager.getCurrencyTypes().stream()
.map(CurrencyType::getName)
.filter(o -> o.startsWith(args[0]))
.collect(Collectors.toList());
}
return Collections.emptyList();
}
}

View File

@@ -0,0 +1,84 @@
package cn.hamster3.mc.plugin.currency.command.currency;
import cn.hamster3.mc.plugin.ball.common.api.BallAPI;
import cn.hamster3.mc.plugin.ball.common.entity.BallPlayerInfo;
import cn.hamster3.mc.plugin.core.bukkit.command.ChildCommand;
import cn.hamster3.mc.plugin.currency.api.CurrencyAPI;
import cn.hamster3.mc.plugin.currency.core.CurrencyDataManager;
import cn.hamster3.mc.plugin.currency.core.CurrencyMessage;
import cn.hamster3.mc.plugin.currency.data.CurrencyType;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
public class CurrencyGiveCommand extends ChildCommand {
public static final CurrencyGiveCommand INSTANCE = new CurrencyGiveCommand();
private CurrencyGiveCommand() {
}
@Override
public @NotNull String getName() {
return "give";
}
@Override
public @NotNull String getUsage() {
return "give <玩家> <货币ID> <数额>";
}
@Override
public boolean hasPermission(@NotNull CommandSender sender) {
return sender.hasPermission("hamster.currency.admin");
}
@Override
public @NotNull String getDescription() {
return "给予玩家货币";
}
@Override
public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) {
if (args.length < 3) {
ParentCurrencyCommand.INSTANCE.sendHelp(sender);
return true;
}
BallPlayerInfo playerInfo = BallAPI.getInstance().getPlayerInfo(args[0]);
if (playerInfo == null) {
CurrencyMessage.PLAYER_NOT_FOUND.show(sender);
return true;
}
CurrencyType type = CurrencyDataManager.getCurrencyType(args[1]);
if (type == null) {
CurrencyMessage.CURRENCY_TYPE_NOT_EXIST.show(sender);
return true;
}
double amount = Double.parseDouble(args[2]);
CurrencyAPI.addPlayerCurrency(playerInfo.getUuid(), type.getId(), amount);
CurrencyMessage.CURRENCY_GIVE_SUCCESS.show(sender);
return true;
}
@Nullable
@Override
public List<String> onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) {
switch (args.length) {
case 1: {
return null;
}
case 2: {
return CurrencyDataManager.getCurrencyTypes().stream()
.map(CurrencyType::getId)
.filter(o -> o.startsWith(args[1]))
.collect(Collectors.toList());
}
default:
return Collections.emptyList();
}
}
}

View File

@@ -0,0 +1,131 @@
package cn.hamster3.mc.plugin.currency.command.currency;
import cn.hamster3.mc.plugin.ball.common.api.BallAPI;
import cn.hamster3.mc.plugin.ball.common.entity.BallPlayerInfo;
import cn.hamster3.mc.plugin.core.bukkit.command.ChildCommand;
import cn.hamster3.mc.plugin.core.bukkit.constant.CoreMessage;
import cn.hamster3.mc.plugin.core.common.data.DisplayMessage;
import cn.hamster3.mc.plugin.currency.CurrencyPlugin;
import cn.hamster3.mc.plugin.currency.api.CurrencyAPI;
import cn.hamster3.mc.plugin.currency.core.CurrencyDataManager;
import cn.hamster3.mc.plugin.currency.core.CurrencyMessage;
import cn.hamster3.mc.plugin.currency.data.CurrencyType;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.sql.SQLException;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
public class CurrencyPayCommand extends ChildCommand {
public static final CurrencyPayCommand INSTANCE = new CurrencyPayCommand();
private CurrencyPayCommand() {
}
@Override
public @NotNull String getName() {
return "pay";
}
@Override
public @NotNull String getUsage() {
return "pay <玩家> <货币ID> <数额>";
}
@Override
public boolean hasPermission(@NotNull CommandSender sender) {
return true;
}
@Override
public @NotNull String getDescription() {
return "向其他玩家转账";
}
@Override
public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) {
if (!(sender instanceof Player)) {
CoreMessage.COMMAND_MUST_USED_BY_PLAYER.show(sender);
return true;
}
Player player = (Player) sender;
if (args.length < 3) {
ParentCurrencyCommand.INSTANCE.sendHelp(sender);
return true;
}
BallPlayerInfo playerInfo = BallAPI.getInstance().getPlayerInfo(args[0]);
if (playerInfo == null) {
CurrencyMessage.PLAYER_NOT_FOUND.show(sender);
return true;
}
CurrencyType type = CurrencyDataManager.getCurrencyType(args[1]);
if (type == null) {
CurrencyMessage.CURRENCY_TYPE_NOT_EXIST.show(sender);
return true;
}
double amount;
try {
amount = Double.parseDouble(args[2]);
} catch (NumberFormatException e) {
CurrencyMessage.CURRENCY_AMOUNT_NUMBER_INPUT_ERROR.show(sender);
return true;
}
if (amount <= 0) {
CurrencyMessage.CURRENCY_AMOUNT_NUMBER_INPUT_ERROR.show(sender);
return true;
}
if (!type.isTransferable()) {
CurrencyMessage.PAY_CURRENCY_NOT_TRANSFERABLE.show(sender);
return true;
}
double currency = CurrencyAPI.getPlayerCurrency(player.getUniqueId(), type.getId());
if (currency < amount) {
CurrencyMessage.PAT_BALANCE_NOT_ENOUGH.show(sender, "%balance%", String.valueOf(currency));
return true;
}
CurrencyPlugin.async(() -> {
try {
CurrencyDataManager.setPlayerCurrency(player.getUniqueId(), type.getId(), currency - amount, true);
double targetCurrency = CurrencyDataManager.getPlayerCurrency(playerInfo.getUuid(), type.getId());
CurrencyDataManager.setPlayerCurrency(playerInfo.getUuid(), type.getId(), targetCurrency + amount, true);
CurrencyMessage.PAY_SUCCESS.show(sender,
"%type_id%", type.getId(),
"%type_name%", type.getName(),
"%to_player_name%", player.getName(),
"%amount%", String.valueOf(amount));
DisplayMessage message = CurrencyMessage.PAY_RECEIVED.getMessage().copy()
.replace("%type_id%", type.getId())
.replace("%type_name%", type.getName())
.replace("%from_player_name%", player.getName())
.replace("%amount%", String.valueOf(amount));
BallAPI.getInstance().sendMessageToPlayer(playerInfo.getUuid(), message, true);
} catch (SQLException e) {
e.printStackTrace();
}
});
return true;
}
@Nullable
@Override
public List<String> onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) {
switch (args.length) {
case 1: {
return null;
}
case 2: {
return CurrencyDataManager.getCurrencyTypes().stream()
.map(CurrencyType::getId)
.filter(o -> o.startsWith(args[1]))
.collect(Collectors.toList());
}
default:
return Collections.emptyList();
}
}
}

View File

@@ -0,0 +1,116 @@
package cn.hamster3.mc.plugin.currency.command.currency;
import cn.hamster3.mc.plugin.core.bukkit.command.ChildCommand;
import cn.hamster3.mc.plugin.currency.CurrencyPlugin;
import cn.hamster3.mc.plugin.currency.core.CurrencyDataManager;
import cn.hamster3.mc.plugin.currency.core.CurrencyMessage;
import cn.hamster3.mc.plugin.currency.data.CurrencyType;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.sql.SQLException;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
public class CurrencyResetCommand extends ChildCommand {
public static final CurrencyResetCommand INSTANCE = new CurrencyResetCommand();
private CurrencyResetCommand() {
}
@Override
public @NotNull String getName() {
return "reset";
}
@Override
public @NotNull String getUsage() {
return "reset <货币ID> <货币名称> <vault挂接(t|f)> <支持转账(t|f)>";
}
@Override
public boolean hasPermission(@NotNull CommandSender sender) {
return sender.hasPermission("hamster.currency.admin");
}
@Override
public @NotNull String getDescription() {
return "修改货币类型";
}
@Override
public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) {
if (args.length < 4) {
ParentCurrencyCommand.INSTANCE.sendHelp(sender);
return true;
}
if (CurrencyDataManager.getCurrencyType(args[0]) == null) {
CurrencyMessage.CURRENCY_TYPE_NOT_EXIST.show(sender);
return true;
}
String id = args[0];
if (!id.matches("[a-zA-Z0-9-_]{0,36}")) {
CurrencyMessage.CURRENCY_TYPE_ID_ERROR.show(sender);
return true;
}
String name = args[1];
if (name.length() > 36) {
CurrencyMessage.CURRENCY_TYPE_NAME_TOO_LONG.show(sender);
return true;
}
boolean vault;
switch (args[2]) {
case "t": {
vault = true;
break;
}
case "f": {
vault = false;
break;
}
default: {
CurrencyMessage.CURRENCY_TYPE_VAULT_INPUT_ERROR.show(sender);
return true;
}
}
boolean transferable;
switch (args[3]) {
case "t": {
transferable = true;
break;
}
case "f": {
transferable = false;
break;
}
default: {
CurrencyMessage.CURRENCY_TYPE_TRANSFERABLE_INPUT_ERROR.show(sender);
return true;
}
}
CurrencyPlugin.async(() -> {
try {
CurrencyDataManager.setCurrencyType(new CurrencyType(id, name, vault, transferable), true);
CurrencyMessage.CURRENCY_RESET_SUCCESS.show(sender);
} catch (SQLException e) {
e.printStackTrace();
}
});
return true;
}
@Nullable
@Override
public List<String> onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) {
if (args.length == 1) {
return CurrencyDataManager.getCurrencyTypes().stream()
.map(CurrencyType::getName)
.filter(o -> o.startsWith(args[0]))
.collect(Collectors.toList());
}
return Collections.emptyList();
}
}

View File

@@ -0,0 +1,98 @@
package cn.hamster3.mc.plugin.currency.command.currency;
import cn.hamster3.mc.plugin.ball.common.api.BallAPI;
import cn.hamster3.mc.plugin.ball.common.entity.BallPlayerInfo;
import cn.hamster3.mc.plugin.core.bukkit.command.ChildCommand;
import cn.hamster3.mc.plugin.currency.core.CurrencyDataManager;
import cn.hamster3.mc.plugin.currency.core.CurrencyMessage;
import cn.hamster3.mc.plugin.currency.data.CurrencyType;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.List;
import java.util.stream.Collectors;
public class CurrencySeeCommand extends ChildCommand {
public static final CurrencySeeCommand INSTANCE = new CurrencySeeCommand();
private CurrencySeeCommand() {
}
@Override
public @NotNull String getName() {
return "see";
}
@Override
public @NotNull String getUsage() {
return "see <玩家> [货币ID]";
}
@Override
public boolean hasPermission(@NotNull CommandSender sender) {
return sender.hasPermission("hamster.currency.admin");
}
@Override
public @NotNull String getDescription() {
return "查看玩家的货币余额";
}
@Override
public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) {
if (args.length < 1) {
ParentCurrencyCommand.INSTANCE.sendHelp(sender);
return true;
}
BallPlayerInfo playerInfo = BallAPI.getInstance().getPlayerInfo(args[0]);
if (playerInfo == null) {
CurrencyMessage.PLAYER_NOT_FOUND.show(sender);
return true;
}
if (args.length >= 2) {
CurrencyType type = CurrencyDataManager.getCurrencyType(args[1]);
if (type == null) {
CurrencyMessage.CURRENCY_TYPE_NOT_EXIST.show(sender);
return true;
}
double amount = CurrencyDataManager.getPlayerCurrency(playerInfo.getUuid(), type.getId());
CurrencyMessage.CURRENCY_SEE_RESULT.show(sender,
"%type_id%", type.getId(),
"%type_name%", type.getName(),
"%amount%", String.valueOf(amount),
"%player_name%", playerInfo.getName()
);
return true;
}
for (CurrencyType type : CurrencyDataManager.getCurrencyTypes()) {
double amount = CurrencyDataManager.getPlayerCurrency(playerInfo.getUuid(), type.getId());
CurrencyMessage.CURRENCY_SEE_RESULT.show(sender,
"%type_id%", type.getId(),
"%type_name%", type.getName(),
"%amount%", String.valueOf(amount),
"%player_name%", playerInfo.getName()
);
}
return true;
}
@Nullable
@Override
public List<String> onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) {
switch (args.length) {
case 1: {
return null;
}
case 2: {
return CurrencyDataManager.getCurrencyTypes().stream()
.map(CurrencyType::getName)
.filter(o -> o.startsWith(args[1]))
.collect(Collectors.toList());
}
default:
return null;
}
}
}

View File

@@ -0,0 +1,84 @@
package cn.hamster3.mc.plugin.currency.command.currency;
import cn.hamster3.mc.plugin.ball.common.api.BallAPI;
import cn.hamster3.mc.plugin.ball.common.entity.BallPlayerInfo;
import cn.hamster3.mc.plugin.core.bukkit.command.ChildCommand;
import cn.hamster3.mc.plugin.currency.api.CurrencyAPI;
import cn.hamster3.mc.plugin.currency.core.CurrencyDataManager;
import cn.hamster3.mc.plugin.currency.core.CurrencyMessage;
import cn.hamster3.mc.plugin.currency.data.CurrencyType;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
public class CurrencySetCommand extends ChildCommand {
public static final CurrencySetCommand INSTANCE = new CurrencySetCommand();
private CurrencySetCommand() {
}
@Override
public @NotNull String getName() {
return "set";
}
@Override
public @NotNull String getUsage() {
return "set <玩家> <货币ID> <数额>";
}
@Override
public boolean hasPermission(@NotNull CommandSender sender) {
return sender.hasPermission("hamster.currency.admin");
}
@Override
public @NotNull String getDescription() {
return "设置玩家的货币余额";
}
@Override
public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) {
if (args.length < 3) {
ParentCurrencyCommand.INSTANCE.sendHelp(sender);
return true;
}
BallPlayerInfo playerInfo = BallAPI.getInstance().getPlayerInfo(args[0]);
if (playerInfo == null) {
CurrencyMessage.PLAYER_NOT_FOUND.show(sender);
return true;
}
CurrencyType type = CurrencyDataManager.getCurrencyType(args[1]);
if (type == null) {
CurrencyMessage.CURRENCY_TYPE_NOT_EXIST.show(sender);
return true;
}
double amount = Double.parseDouble(args[2]);
CurrencyAPI.setPlayerCurrency(playerInfo.getUuid(), type.getId(), amount);
CurrencyMessage.CURRENCY_SET_SUCCESS.show(sender);
return true;
}
@Nullable
@Override
public List<String> onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) {
switch (args.length) {
case 1: {
return null;
}
case 2: {
return CurrencyDataManager.getCurrencyTypes().stream()
.map(CurrencyType::getId)
.filter(o -> o.startsWith(args[1]))
.collect(Collectors.toList());
}
default:
return Collections.emptyList();
}
}
}

View File

@@ -0,0 +1,84 @@
package cn.hamster3.mc.plugin.currency.command.currency;
import cn.hamster3.mc.plugin.ball.common.api.BallAPI;
import cn.hamster3.mc.plugin.ball.common.entity.BallPlayerInfo;
import cn.hamster3.mc.plugin.core.bukkit.command.ChildCommand;
import cn.hamster3.mc.plugin.currency.api.CurrencyAPI;
import cn.hamster3.mc.plugin.currency.core.CurrencyDataManager;
import cn.hamster3.mc.plugin.currency.core.CurrencyMessage;
import cn.hamster3.mc.plugin.currency.data.CurrencyType;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
public class CurrencyTakeCommand extends ChildCommand {
public static final CurrencyTakeCommand INSTANCE = new CurrencyTakeCommand();
private CurrencyTakeCommand() {
}
@Override
public @NotNull String getName() {
return "take";
}
@Override
public @NotNull String getUsage() {
return "take <玩家> <货币ID> <数额>";
}
@Override
public boolean hasPermission(@NotNull CommandSender sender) {
return sender.hasPermission("hamster.currency.admin");
}
@Override
public @NotNull String getDescription() {
return "扣除玩家的货币余额";
}
@Override
public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) {
if (args.length < 3) {
ParentCurrencyCommand.INSTANCE.sendHelp(sender);
return true;
}
BallPlayerInfo playerInfo = BallAPI.getInstance().getPlayerInfo(args[0]);
if (playerInfo == null) {
CurrencyMessage.PLAYER_NOT_FOUND.show(sender);
return true;
}
CurrencyType type = CurrencyDataManager.getCurrencyType(args[1]);
if (type == null) {
CurrencyMessage.CURRENCY_TYPE_NOT_EXIST.show(sender);
return true;
}
double amount = Double.parseDouble(args[2]);
CurrencyAPI.takePlayerCurrency(playerInfo.getUuid(), type.getId(), amount);
CurrencyMessage.CURRENCY_TAKE_SUCCESS.show(sender);
return true;
}
@Nullable
@Override
public List<String> onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) {
switch (args.length) {
case 1: {
return null;
}
case 2: {
return CurrencyDataManager.getCurrencyTypes().stream()
.map(CurrencyType::getId)
.filter(o -> o.startsWith(args[1]))
.collect(Collectors.toList());
}
default:
return Collections.emptyList();
}
}
}

View File

@@ -0,0 +1,37 @@
package cn.hamster3.mc.plugin.currency.command.currency;
import cn.hamster3.mc.plugin.core.bukkit.command.ParentCommand;
import cn.hamster3.mc.plugin.currency.CurrencyPlugin;
import org.bukkit.command.CommandSender;
import org.bukkit.plugin.java.JavaPlugin;
import org.jetbrains.annotations.NotNull;
public class ParentCurrencyCommand extends ParentCommand {
public static final ParentCurrencyCommand INSTANCE = new ParentCurrencyCommand();
private ParentCurrencyCommand() {
addChildCommand(CurrencyCreateCommand.INSTANCE);
addChildCommand(CurrencyResetCommand.INSTANCE);
addChildCommand(CurrencyDeleteCommand.INSTANCE);
addChildCommand(CurrencyGiveCommand.INSTANCE);
addChildCommand(CurrencyTakeCommand.INSTANCE);
addChildCommand(CurrencySetCommand.INSTANCE);
addChildCommand(CurrencySeeCommand.INSTANCE);
addChildCommand(CurrencyPayCommand.INSTANCE);
}
@Override
public @NotNull String getName() {
return "hamster-currency";
}
@Override
public @NotNull JavaPlugin getPlugin() {
return CurrencyPlugin.getInstance();
}
@Override
public boolean hasPermission(@NotNull CommandSender sender) {
return true;
}
}

View File

@@ -0,0 +1,22 @@
package cn.hamster3.mc.plugin.currency.command.vault;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.command.TabExecutor;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.List;
public class BalanceCommand implements TabExecutor {
@Override
public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) {
return false;
}
@Nullable
@Override
public List<String> onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) {
return null;
}
}

View File

@@ -0,0 +1,27 @@
package cn.hamster3.mc.plugin.currency.core;
import cn.hamster3.mc.plugin.currency.CurrencyPlugin;
import lombok.Getter;
import org.bukkit.configuration.file.FileConfiguration;
public class ConfigManager {
@Getter
private static boolean enableVaultCommands;
@Getter
private static String currencyNamePlural;
@Getter
private static String currencyNameSingular;
public static void init() {
CurrencyPlugin plugin = CurrencyPlugin.getInstance();
plugin.saveDefaultConfig();
plugin.reloadConfig();
FileConfiguration pluginConfig = plugin.getConfig();
enableVaultCommands = pluginConfig.getBoolean("enable-vault-commands", true);
currencyNamePlural = pluginConfig.getString("vault-settings.currency-name-plural", "金币");
currencyNameSingular = pluginConfig.getString("vault-settings.currency-name-singular", "金币");
}
}

View File

@@ -0,0 +1,164 @@
package cn.hamster3.mc.plugin.currency.core;
import cn.hamster3.mc.plugin.ball.common.api.BallAPI;
import cn.hamster3.mc.plugin.core.common.api.CoreAPI;
import cn.hamster3.mc.plugin.currency.CurrencyPlugin;
import cn.hamster3.mc.plugin.currency.data.CurrencyType;
import com.google.gson.JsonObject;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.sql.*;
import java.util.Collection;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
public final class CurrencyDataManager {
private static final ConcurrentMap<String, CurrencyType> CURRENCY_TYPES = new ConcurrentHashMap<>();
private static final ConcurrentMap<UUID, ConcurrentMap<String, Double>> PLAYER_DATA = new ConcurrentHashMap<>();
private CurrencyDataManager() {
}
public static void init() throws SQLException {
try (Connection connection = CoreAPI.getInstance().getConnection()) {
try (Statement statement = connection.createStatement()) {
statement.execute("CREATE TABLE IF NOT EXISTS hamster_currency_type(" +
"`id` VARCHAR(36) PRIMARY KEY," +
"`name` VARCHAR(36) NOT NULL," +
"`vault` BOOLEAN NOT NULL," +
"`transferable` BOOLEAN NOT NULL" +
") CHARSET utf8mb4;");
statement.execute("CREATE TABLE IF NOT EXISTS hamster_currency_data(" +
"`uuid` CHAR(36) NOT NULL," +
"`currency` VARCHAR(36) NOT NULL," +
"`amount` DOUBLE NOT NULL," +
"UNIQUE KEY `unique_player_currency` (`uuid`, `currency`)" +
") CHARSET utf8mb4;");
try (ResultSet set = statement.executeQuery("SELECT * FROM hamster_currency_type;")) {
while (set.next()) {
CurrencyType type = new CurrencyType(
set.getString("id"),
set.getString("name"),
set.getBoolean("vault"),
set.getBoolean("transferable")
);
CURRENCY_TYPES.put(type.getId(), type);
}
}
try (ResultSet set = statement.executeQuery("SELECT * FROM hamster_currency_data ORDER BY `uuid`;")) {
if (set.next()) {
setPlayerCurrency(
UUID.fromString(set.getString("uuid")),
set.getString("currency"),
set.getDouble("amount"),
false
);
}
}
}
}
}
public static void loadPlayerData(@NotNull UUID uuid) throws SQLException {
try (Connection connection = CoreAPI.getInstance().getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(
"SELECT currency, amount FROM hamster_currency_data WHERE `uuid`=?;"
)) {
statement.setString(1, uuid.toString());
try (ResultSet set = statement.executeQuery()) {
Map<String, Double> currency = getPlayerCurrency(uuid);
while (set.next()) {
currency.put(set.getString("currency"), set.getDouble("amount"));
}
}
}
}
}
@NotNull
public static Map<String, Double> getPlayerCurrency(@NotNull UUID uuid) {
return PLAYER_DATA.computeIfAbsent(uuid, o -> new ConcurrentHashMap<>());
}
public static double getPlayerCurrency(@NotNull UUID uuid, @NotNull String typeID) {
return getPlayerCurrency(uuid).getOrDefault(typeID, 0d);
}
public static void setPlayerCurrency(@NotNull UUID uuid, @NotNull String typeID, double amount, boolean broadcast) throws SQLException {
Map<String, Double> currency = getPlayerCurrency(uuid);
currency.put(typeID, amount);
if (broadcast) {
try (Connection connection = CoreAPI.getInstance().getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(
"REPLACE INTO hamster_currency_data VALUES(?, ?, ?);"
)) {
statement.setString(1, uuid.toString());
statement.setString(2, typeID);
statement.setDouble(3, amount);
statement.executeUpdate();
}
}
JsonObject object = new JsonObject();
object.addProperty("uuid", uuid.toString());
object.addProperty("typeID", typeID);
object.addProperty("amount", amount);
BallAPI.getInstance().sendBallMessage(CurrencyPlugin.BALL_CHANNEL, "setPlayerCurrency", object);
}
}
@NotNull
public static Collection<CurrencyType> getCurrencyTypes() {
return CURRENCY_TYPES.values();
}
@Nullable
public static CurrencyType getCurrencyType(@NotNull String id) {
return CURRENCY_TYPES.get(id);
}
@Nullable
public static CurrencyType getVaultCurrencyType() {
for (CurrencyType type : CURRENCY_TYPES.values()) {
if (type.isVault()) {
return type;
}
}
return null;
}
public static void setCurrencyType(@NotNull CurrencyType type, boolean broadcast) throws SQLException {
CURRENCY_TYPES.put(type.getId(), type);
if (broadcast) {
try (Connection connection = CoreAPI.getInstance().getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(
"REPLACE INTO hamster_currency_type VALUES(?, ?, ?, ?);"
)) {
statement.setString(1, type.getId());
statement.setString(2, type.getName());
statement.setBoolean(3, type.isVault());
statement.setBoolean(4, type.isTransferable());
statement.executeUpdate();
}
BallAPI.getInstance().sendBallMessage(CurrencyPlugin.BALL_CHANNEL, "setCurrencyType", type);
}
}
}
public static void deleteCurrencyType(@NotNull String typeID, boolean broadcast) throws SQLException {
CURRENCY_TYPES.remove(typeID);
if (broadcast) {
try (Connection connection = CoreAPI.getInstance().getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(
"DELETE FROM hamster_currency_type WHERE `id`=?;"
)) {
statement.setString(1, typeID);
statement.executeUpdate();
}
BallAPI.getInstance().sendBallMessage(CurrencyPlugin.BALL_CHANNEL, "setCurrencyType", typeID);
}
}
}
}

View File

@@ -0,0 +1,103 @@
package cn.hamster3.mc.plugin.currency.core;
import cn.hamster3.mc.plugin.core.bukkit.api.CoreBukkitAPI;
import cn.hamster3.mc.plugin.core.bukkit.util.CoreBukkitUtils;
import cn.hamster3.mc.plugin.core.common.data.DisplayMessage;
import cn.hamster3.mc.plugin.core.lib.net.kyori.adventure.audience.Audience;
import cn.hamster3.mc.plugin.core.lib.net.kyori.adventure.text.TextReplacementConfig;
import lombok.Getter;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.plugin.Plugin;
import org.jetbrains.annotations.NotNull;
import java.io.File;
import java.io.IOException;
@Getter
public enum CurrencyMessage {
PLAYER_NOT_FOUND("§c未找到该玩家"),
CURRENCY_TYPE_NOT_EXIST("§c未找到该货币类型"),
CURRENCY_TYPE_EXISTED("§c该货币 ID 已存在"),
CURRENCY_TYPE_ID_ERROR("§c货币 ID 只能由英文字母和下划线组成,且不能超过 36 个字符"),
CURRENCY_TYPE_NAME_TOO_LONG("§c货币名称的长度不能超过 36 个字符"),
CURRENCY_TYPE_VAULT_INPUT_ERROR("§c货币的 vault 类型只能是 't' 或者 'f'"),
CURRENCY_TYPE_TRANSFERABLE_INPUT_ERROR("§c货币的 允许转账 类型只能是 't' 或者 'f'"),
CURRENCY_AMOUNT_NUMBER_INPUT_ERROR("§c货币金额只能是一个大于 0 的数字"),
CURRENCY_CREATE_SUCCESS("货币创建成功"),
CURRENCY_DELETE_SUCCESS("货币删除成功"),
CURRENCY_GIVE_SUCCESS("货币给予成功"),
CURRENCY_SET_SUCCESS("货币设置成功"),
CURRENCY_TAKE_SUCCESS("货币扣除成功"),
CURRENCY_RESET_SUCCESS("货币重设成功"),
CURRENCY_SEE_RESULT("玩家 %player_name% 的 %type_id% 余额为: %amount% (%type_name%)"),
PAY_CURRENCY_NOT_TRANSFERABLE("§c这个货币类型不支持转账"),
PAT_BALANCE_NOT_ENOUGH("§c你的余额不够 (剩余 %amount%"),
PAY_SUCCESS("已向玩家 %to_player_name% 转账 %amount% %type_name%."),
PAY_RECEIVED("收到玩家 %from_player_name% 转账 %amount% %type_name%."),
;
@NotNull
private DisplayMessage message;
CurrencyMessage(@NotNull String message) {
this.message = new DisplayMessage().setMessage(message);
}
@SuppressWarnings("CallToPrintStackTrace")
public static void init(@NotNull Plugin plugin) {
File dataFolder = plugin.getDataFolder();
if (dataFolder.mkdirs()) {
plugin.getLogger().info("已生成插件存档文件夹 " + dataFolder.getName());
}
File file = new File(dataFolder, "messages.yml");
YamlConfiguration config = new YamlConfiguration();
if (file.exists()) {
try {
config.load(file);
} catch (Exception e) {
plugin.getLogger().warning("加载消息配置文件时出现了一个异常:");
e.printStackTrace();
}
}
for (CurrencyMessage value : values()) {
ConfigurationSection section = config.getConfigurationSection(value.name());
if (section == null) {
plugin.getLogger().info("生成消息设置: " + value.name());
config.set(value.name(), CoreBukkitUtils.saveDisplayMessage(value.message));
continue;
}
try {
value.message = CoreBukkitUtils.loadDisplayMessage(section);
} catch (Exception e) {
plugin.getLogger().warning("加载消息设置 " + value.name() + " 时遇到了一个异常: ");
e.printStackTrace();
}
}
try {
config.save(file);
} catch (IOException e) {
plugin.getLogger().warning("保存消息配置文件时出现了一个异常:");
e.printStackTrace();
}
}
public void show(@NotNull CommandSender sender) {
message.show(CoreBukkitAPI.getInstance().getAudienceProvider().sender(sender));
}
public void show(@NotNull CommandSender sender, @NotNull String... replacement) {
if (replacement.length % 2 != 0) {
throw new IllegalArgumentException();
}
TextReplacementConfig[] configs = new TextReplacementConfig[replacement.length / 2];
for (int i = 0; i < configs.length; i++) {
String key = replacement[i * 2];
String value = replacement[i * 2 + 1];
configs[i] = TextReplacementConfig.builder().matchLiteral(key).replacement(value).build();
}
Audience audience = CoreBukkitAPI.getInstance().getAudienceProvider().sender(sender);
message.show(audience, configs);
}
}

View File

@@ -0,0 +1,25 @@
package cn.hamster3.mc.plugin.currency.data;
import lombok.AllArgsConstructor;
import lombok.Getter;
@Getter
@AllArgsConstructor
public class CurrencyType {
/**
* 货币 ID
*/
private String id;
/**
* 显示名称
*/
private String name;
/**
* 是否挂接到 vault
*/
private boolean vault;
/**
* 是否允许转账
*/
private boolean transferable;
}

View File

@@ -0,0 +1,31 @@
package cn.hamster3.mc.plugin.currency.data;
import lombok.Data;
import org.jetbrains.annotations.NotNull;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
@Data
public class PlayerData {
@NotNull
private UUID uuid;
@NotNull
private String playerName;
@NotNull
private Map<String , Double> currency;
public PlayerData(@NotNull UUID uuid, @NotNull String playerName) {
this.uuid = uuid;
this.playerName = playerName;
currency = new ConcurrentHashMap<>();
}
public PlayerData(@NotNull UUID uuid, @NotNull String playerName, @NotNull Map<String, Double> currency) {
this.uuid = uuid;
this.playerName = playerName;
this.currency = currency;
}
}

View File

@@ -0,0 +1,42 @@
package cn.hamster3.mc.plugin.currency.hook;
import cn.hamster3.mc.plugin.currency.core.CurrencyDataManager;
import me.clip.placeholderapi.expansion.PlaceholderExpansion;
import org.bukkit.OfflinePlayer;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
public final class PlaceholderHook extends PlaceholderExpansion {
public static final PlaceholderHook INSTANCE = new PlaceholderHook();
private PlaceholderHook() {
}
@Override
@NotNull
public String getIdentifier() {
return "currency";
}
@Override
@NotNull
public String getAuthor() {
return "MiniDay";
}
@Override
@NotNull
public String getVersion() {
return "1.0.0";
}
@Override
public String onRequest(OfflinePlayer player, @NotNull String params) {
return String.format("%.2f", CurrencyDataManager.getPlayerCurrency(player.getUniqueId(), params));
}
@Override
public String onPlaceholderRequest(Player player, @NotNull String params) {
return onRequest(player, params);
}
}

View File

@@ -0,0 +1,259 @@
package cn.hamster3.mc.plugin.currency.hook;
import cn.hamster3.mc.plugin.ball.common.api.BallAPI;
import cn.hamster3.mc.plugin.currency.CurrencyPlugin;
import cn.hamster3.mc.plugin.currency.core.ConfigManager;
import cn.hamster3.mc.plugin.currency.core.CurrencyDataManager;
import cn.hamster3.mc.plugin.currency.data.CurrencyType;
import net.milkbowl.vault.economy.AbstractEconomy;
import net.milkbowl.vault.economy.EconomyResponse;
import org.bukkit.OfflinePlayer;
import org.jetbrains.annotations.NotNull;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
public class VaultEconomyHook extends AbstractEconomy {
private static final EconomyResponse NOT_IMPLEMENTED_RESPONSE =
new EconomyResponse(
0,
0,
EconomyResponse.ResponseType.NOT_IMPLEMENTED,
"HamsterCurrency 未实现该功能~"
);
@NotNull
private final CurrencyType currencyType;
public VaultEconomyHook(@NotNull CurrencyType currencyType) {
this.currencyType = currencyType;
}
@Override
public boolean isEnabled() {
return true;
}
@Override
public String getName() {
return "HamsterCurrency";
}
@Override
public int fractionalDigits() {
return 2;
}
@Override
public String format(double amount) {
return String.format("%.2f", amount);
}
@Override
public String currencyNamePlural() {
return ConfigManager.getCurrencyNamePlural();
}
@Override
public String currencyNameSingular() {
return ConfigManager.getCurrencyNameSingular();
}
@Override
public double getBalance(String playerName) {
UUID uuid = BallAPI.getInstance().getPlayerInfo(playerName).getUuid();
return CurrencyDataManager.getPlayerCurrency(uuid, currencyType.getId());
}
@Override
public double getBalance(OfflinePlayer player) {
return CurrencyDataManager.getPlayerCurrency(player.getUniqueId(), currencyType.getId());
}
@Override
public double getBalance(String playerName, String world) {
return getBalance(playerName);
}
@Override
public double getBalance(OfflinePlayer player, String world) {
return getBalance(player);
}
@Override
public boolean has(String playerName, double amount) {
return getBalance(playerName) >= amount;
}
@Override
public boolean has(OfflinePlayer player, double amount) {
return getBalance(player) >= amount;
}
@Override
public boolean has(String playerName, String worldName, double amount) {
return getBalance(playerName) >= amount;
}
@Override
public boolean has(OfflinePlayer player, String worldName, double amount) {
return getBalance(player) >= amount;
}
@Override
public EconomyResponse withdrawPlayer(String playerName, double amount) {
UUID uuid = BallAPI.getInstance().getPlayerInfo(playerName).getUuid();
double balance = CurrencyDataManager.getPlayerCurrency(uuid, currencyType.getId());
if (balance < amount) {
return new EconomyResponse(amount, balance, EconomyResponse.ResponseType.FAILURE, "余额不足");
}
double result = balance - amount;
CurrencyPlugin.async(() -> {
try {
CurrencyDataManager.setPlayerCurrency(uuid, currencyType.getId(), result, true);
} catch (SQLException e) {
e.printStackTrace();
}
});
return new EconomyResponse(amount, result, EconomyResponse.ResponseType.SUCCESS, "扣款成功");
}
@Override
public EconomyResponse withdrawPlayer(OfflinePlayer player, double amount) {
UUID uuid = player.getUniqueId();
double balance = CurrencyDataManager.getPlayerCurrency(uuid, currencyType.getId());
if (balance < amount) {
return new EconomyResponse(amount, balance, EconomyResponse.ResponseType.FAILURE, "余额不足");
}
double result = balance - amount;
CurrencyPlugin.async(() -> {
try {
CurrencyDataManager.setPlayerCurrency(uuid, currencyType.getId(), result, true);
} catch (SQLException e) {
e.printStackTrace();
}
});
return new EconomyResponse(amount, result, EconomyResponse.ResponseType.SUCCESS, "扣款成功");
}
@Override
public EconomyResponse withdrawPlayer(String playerName, String worldName, double amount) {
return withdrawPlayer(playerName, amount);
}
@Override
public EconomyResponse withdrawPlayer(OfflinePlayer player, String worldName, double amount) {
return withdrawPlayer(player, amount);
}
@Override
public EconomyResponse depositPlayer(String playerName, double amount) {
UUID uuid = BallAPI.getInstance().getPlayerInfo(playerName).getUuid();
double balance = CurrencyDataManager.getPlayerCurrency(uuid, currencyType.getId());
double result = balance + amount;
CurrencyPlugin.async(() -> {
try {
CurrencyDataManager.setPlayerCurrency(uuid, currencyType.getId(), result, true);
} catch (SQLException e) {
e.printStackTrace();
}
});
return new EconomyResponse(amount, result, EconomyResponse.ResponseType.SUCCESS, "");
}
@Override
public EconomyResponse depositPlayer(OfflinePlayer player, double amount) {
UUID uuid = player.getUniqueId();
double balance = CurrencyDataManager.getPlayerCurrency(uuid, currencyType.getId());
double result = balance + amount;
CurrencyPlugin.async(() -> {
try {
CurrencyDataManager.setPlayerCurrency(uuid, currencyType.getId(), result, true);
} catch (SQLException e) {
e.printStackTrace();
}
});
return new EconomyResponse(amount, result, EconomyResponse.ResponseType.SUCCESS, "");
}
@Override
public EconomyResponse depositPlayer(String playerName, String worldName, double amount) {
return depositPlayer(playerName, amount);
}
@Override
public EconomyResponse depositPlayer(OfflinePlayer player, String worldName, double amount) {
return depositPlayer(player, amount);
}
@Override
public boolean hasBankSupport() {
return false;
}
@Override
public boolean hasAccount(String playerName) {
return true;
}
@Override
public boolean hasAccount(String playerName, String worldName) {
return true;
}
@Override
public EconomyResponse createBank(String name, String player) {
return NOT_IMPLEMENTED_RESPONSE;
}
@Override
public EconomyResponse deleteBank(String name) {
return NOT_IMPLEMENTED_RESPONSE;
}
@Override
public EconomyResponse bankBalance(String name) {
return NOT_IMPLEMENTED_RESPONSE;
}
@Override
public EconomyResponse bankHas(String name, double amount) {
return NOT_IMPLEMENTED_RESPONSE;
}
@Override
public EconomyResponse bankWithdraw(String name, double amount) {
return NOT_IMPLEMENTED_RESPONSE;
}
@Override
public EconomyResponse bankDeposit(String name, double amount) {
return NOT_IMPLEMENTED_RESPONSE;
}
@Override
public EconomyResponse isBankOwner(String name, String playerName) {
return NOT_IMPLEMENTED_RESPONSE;
}
@Override
public EconomyResponse isBankMember(String name, String playerName) {
return NOT_IMPLEMENTED_RESPONSE;
}
@Override
public List<String> getBanks() {
return new ArrayList<>();
}
@Override
public boolean createPlayerAccount(String playerName) {
return true;
}
@Override
public boolean createPlayerAccount(String playerName, String worldName) {
return true;
}
}

View File

@@ -0,0 +1,60 @@
package cn.hamster3.mc.plugin.currency.listener;
import cn.hamster3.mc.plugin.ball.common.data.BallMessage;
import cn.hamster3.mc.plugin.ball.common.event.message.MessageReceivedEvent;
import cn.hamster3.mc.plugin.core.common.api.CoreAPI;
import cn.hamster3.mc.plugin.currency.CurrencyPlugin;
import cn.hamster3.mc.plugin.currency.core.CurrencyDataManager;
import cn.hamster3.mc.plugin.currency.data.CurrencyType;
import com.google.common.eventbus.Subscribe;
import com.google.gson.JsonObject;
import java.sql.SQLException;
import java.util.UUID;
@SuppressWarnings("CallToPrintStackTrace")
public class BallListener {
public static final BallListener INSTANCE = new BallListener();
private BallListener() {
}
@Subscribe
public void onMessageReceived(MessageReceivedEvent event) {
if (!CurrencyPlugin.BALL_CHANNEL.equals(event.getChannel())) {
return;
}
BallMessage message = event.getMessage();
switch (message.getAction()) {
case "setPlayerCurrency": {
JsonObject object = message.getContentAsJsonObject();
UUID uuid = UUID.fromString(object.get("uuid").getAsString());
String typeID = object.get("typeID").getAsString();
double amount = object.get("amount").getAsDouble();
try {
CurrencyDataManager.setPlayerCurrency(uuid, typeID, amount, false);
} catch (SQLException e) {
e.printStackTrace();
}
break;
}
case "setCurrencyType": {
CurrencyType type = CoreAPI.getInstance().getGson().fromJson(message.getContent(), CurrencyType.class);
try {
CurrencyDataManager.setCurrencyType(type, false);
} catch (SQLException e) {
e.printStackTrace();
}
break;
}
case "removeCurrencyType": {
try {
CurrencyDataManager.deleteCurrencyType(message.getContentAsString(), false);
} catch (SQLException e) {
e.printStackTrace();
}
break;
}
}
}
}

View File

@@ -0,0 +1,32 @@
package cn.hamster3.mc.plugin.currency.listener;
import cn.hamster3.mc.plugin.currency.CurrencyPlugin;
import cn.hamster3.mc.plugin.currency.core.CurrencyDataManager;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerLoginEvent;
import java.sql.SQLException;
import java.util.UUID;
public class CurrencyListener implements Listener {
public static final CurrencyListener INSTANCE = new CurrencyListener();
private CurrencyListener() {
}
@EventHandler(ignoreCancelled = true)
public void onPlayerLogin(PlayerLoginEvent event) {
Player player = event.getPlayer();
UUID uuid = player.getUniqueId();
CurrencyPlugin.async(() -> {
try {
CurrencyDataManager.loadPlayerData(uuid);
} catch (SQLException e) {
e.printStackTrace();
}
});
}
}

View File

@@ -0,0 +1,6 @@
# 是否启用 vault 默认的指令
enable-vault-commands: true
vault-settings:
currency-name-plural: 金币
currency-name-singular: 金币

View File

@@ -0,0 +1,40 @@
name: HamsterCurrency
main: cn.hamster3.mc.plugin.currency.CurrencyPlugin
version: ${version}
api-version: 1.13
load: STARTUP
author: MiniDay
description: 叁只仓鼠的跨服多货币经济插件
website: https://github.com/MiniDay/hamster-currency
depend:
- HamsterCore
- HamsterBall
softdepend:
- PlaceholderAPI
- PlayerPoints
- Vault
commands:
hamster-currency:
aliases: [ hcurrency, currency ]
balance:
aliases: [ bal, seemoney ]
balanceTop:
aliases: [ baltop ]
payMoney:
aliases: [ pay ]
economy:
aliases: [ eco, money ]
permissions:
hamster.currency.admin:
default: op
hamster.currency.see:
default: true
hamster.currency.see.other:
default: op
hamster.currency.top:
default: op