From 106f72c84efa927d63be3932272f304647f6df1a Mon Sep 17 00:00:00 2001 From: Flibio Date: Sun, 3 Apr 2016 09:53:07 -0600 Subject: [PATCH] EconomyLite 2.0 - Complete rewrite + Supports multiple currencies - Switched to H2 backend - Removed scoreboard - Removed businesses - Reworked commands + Added top balance command + Added commands to manage virtual accounts Closes #3 and #8 --- HEADER.txt | 22 + README.md | 28 +- build.gradle | 83 +++ gradle.properties | 4 + gradlew | 160 +++++ gradlew.bat | 90 +++ pom.xml | 92 --- settings.gradle | 1 + .../flibio/economylite/EconomyLite.java | 256 ++++++++ .../github/flibio/economylite/PluginInfo.java | 39 ++ .../economylite/api/CurrencyEconService.java | 75 +++ .../economylite/api/PlayerEconService.java | 114 ++++ .../economylite/api/VirtualEconService.java | 113 ++++ .../economylite/commands/PayCommand.java | 91 +++ .../commands/admin/AddCommand.java | 86 +++ .../commands/admin/EconCommand.java | 55 ++ .../commands/admin/RemoveCommand.java | 86 +++ .../commands/admin/SetCommand.java | 86 +++ .../commands/balance/BalTopCommand.java | 75 +++ .../commands/balance/BalanceCommand.java | 108 ++++ .../commands/currency/CurrencyCommand.java | 56 ++ .../currency/CurrencyCreateCommand.java | 90 +++ .../currency/CurrencyDeleteCommand.java | 102 +++ .../commands/currency/CurrencySetCommand.java | 88 +++ .../virtual/VirtualBalanceCommand.java | 88 +++ .../commands/virtual/VirtualSetCommand.java | 82 +++ .../economylite/impl/CurrencyService.java | 83 +++ .../economylite/impl/PlayerDataService.java | 36 ++ .../economylite/impl/PlayerServiceCommon.java | 98 +++ .../economylite/impl/VirtualDataService.java | 36 ++ .../impl/VirtualServiceCommon.java | 99 +++ .../impl/economy/LiteCurrency.java | 96 +++ .../impl/economy/LiteEconomyService.java | 108 ++++ .../economy/account/LiteUniqueAccount.java | 222 +++++++ .../economy/account/LiteVirtualAccount.java | 208 +++++++ .../event/LiteEconomyTransactionEvent.java | 51 ++ .../registry/CurrencyRegistryModule.java | 51 ++ .../result}/LiteTransactionResult.java | 32 +- .../economy/result/LiteTransferResult.java | 48 ++ .../flibio/economylite/modules/Module.java | 59 ++ .../modules/business/BusinessModule.java | 55 ++ .../modules/sql/PlayerSqlService.java | 37 ++ .../economylite/modules/sql/SqlModule.java | 83 +++ .../modules/sql/VirtualSqlService.java | 37 ++ src/main/resources/messages.properties | 58 ++ .../EconomyLite/API/EconomyLiteAPI.java | 61 -- .../Flibio/EconomyLite/API/LiteCurrency.java | 68 -- .../EconomyLite/API/LiteEconomyService.java | 76 --- .../EconomyLite/API/LiteTransferResult.java | 24 - .../EconomyLite/API/LiteUniqueAccount.java | 171 ----- .../EconomyLite/API/LiteVirtualAccount.java | 168 ----- .../EconomyLite/Commands/AddCommand.java | 92 --- .../EconomyLite/Commands/BalanceCommand.java | 104 ---- .../Commands/BusinessDeleteCommand.java | 129 ---- .../Commands/BusinessInviteAcceptCommand.java | 83 --- .../Commands/BusinessInviteCommand.java | 105 ---- .../Commands/BusinessLeaveCommand.java | 98 --- .../Commands/BusinessOwnersCommand.java | 76 --- .../Commands/BusinessRegisterCommand.java | 83 --- .../Commands/BusinessTransferCommand.java | 116 ---- .../EconomyLite/Commands/PayCommand.java | 207 ------- .../Commands/PayOverrideCommand.java | 201 ------ .../Commands/PlayerBalanceCommand.java | 70 --- .../EconomyLite/Commands/RemoveCommand.java | 94 --- .../EconomyLite/Commands/SetCommand.java | 90 --- src/me/Flibio/EconomyLite/EconomyLite.java | 333 ---------- .../Events/BalanceChangeEvent.java | 48 -- .../Events/LiteEconomyTransactionEvent.java | 27 - .../Listeners/BalanceChangeListener.java | 52 -- .../Listeners/PlayerJoinListener.java | 71 --- .../Registry/CurrencyRegistryModule.java | 23 - .../EconomyLite/Utils/BusinessManager.java | 582 ------------------ .../Flibio/EconomyLite/Utils/FileManager.java | 183 ------ .../EconomyLite/Utils/MySQLManager.java | 547 ---------------- .../EconomyLite/Utils/PlayerManager.java | 283 --------- .../EconomyLite/Utils/ScoreboardUtils.java | 47 -- .../Flibio/EconomyLite/Utils/TextUtils.java | 338 ---------- 77 files changed, 3558 insertions(+), 4759 deletions(-) create mode 100644 HEADER.txt create mode 100644 build.gradle create mode 100644 gradle.properties create mode 100644 gradlew create mode 100644 gradlew.bat delete mode 100644 pom.xml create mode 100644 settings.gradle create mode 100644 src/main/java/io/github/flibio/economylite/EconomyLite.java create mode 100644 src/main/java/io/github/flibio/economylite/PluginInfo.java create mode 100644 src/main/java/io/github/flibio/economylite/api/CurrencyEconService.java create mode 100644 src/main/java/io/github/flibio/economylite/api/PlayerEconService.java create mode 100644 src/main/java/io/github/flibio/economylite/api/VirtualEconService.java create mode 100644 src/main/java/io/github/flibio/economylite/commands/PayCommand.java create mode 100644 src/main/java/io/github/flibio/economylite/commands/admin/AddCommand.java create mode 100644 src/main/java/io/github/flibio/economylite/commands/admin/EconCommand.java create mode 100644 src/main/java/io/github/flibio/economylite/commands/admin/RemoveCommand.java create mode 100644 src/main/java/io/github/flibio/economylite/commands/admin/SetCommand.java create mode 100644 src/main/java/io/github/flibio/economylite/commands/balance/BalTopCommand.java create mode 100644 src/main/java/io/github/flibio/economylite/commands/balance/BalanceCommand.java create mode 100644 src/main/java/io/github/flibio/economylite/commands/currency/CurrencyCommand.java create mode 100644 src/main/java/io/github/flibio/economylite/commands/currency/CurrencyCreateCommand.java create mode 100644 src/main/java/io/github/flibio/economylite/commands/currency/CurrencyDeleteCommand.java create mode 100644 src/main/java/io/github/flibio/economylite/commands/currency/CurrencySetCommand.java create mode 100644 src/main/java/io/github/flibio/economylite/commands/virtual/VirtualBalanceCommand.java create mode 100644 src/main/java/io/github/flibio/economylite/commands/virtual/VirtualSetCommand.java create mode 100644 src/main/java/io/github/flibio/economylite/impl/CurrencyService.java create mode 100644 src/main/java/io/github/flibio/economylite/impl/PlayerDataService.java create mode 100644 src/main/java/io/github/flibio/economylite/impl/PlayerServiceCommon.java create mode 100644 src/main/java/io/github/flibio/economylite/impl/VirtualDataService.java create mode 100644 src/main/java/io/github/flibio/economylite/impl/VirtualServiceCommon.java create mode 100644 src/main/java/io/github/flibio/economylite/impl/economy/LiteCurrency.java create mode 100644 src/main/java/io/github/flibio/economylite/impl/economy/LiteEconomyService.java create mode 100644 src/main/java/io/github/flibio/economylite/impl/economy/account/LiteUniqueAccount.java create mode 100644 src/main/java/io/github/flibio/economylite/impl/economy/account/LiteVirtualAccount.java create mode 100644 src/main/java/io/github/flibio/economylite/impl/economy/event/LiteEconomyTransactionEvent.java create mode 100644 src/main/java/io/github/flibio/economylite/impl/economy/registry/CurrencyRegistryModule.java rename src/{me/Flibio/EconomyLite/API => main/java/io/github/flibio/economylite/impl/economy/result}/LiteTransactionResult.java (50%) create mode 100644 src/main/java/io/github/flibio/economylite/impl/economy/result/LiteTransferResult.java create mode 100644 src/main/java/io/github/flibio/economylite/modules/Module.java create mode 100644 src/main/java/io/github/flibio/economylite/modules/business/BusinessModule.java create mode 100644 src/main/java/io/github/flibio/economylite/modules/sql/PlayerSqlService.java create mode 100644 src/main/java/io/github/flibio/economylite/modules/sql/SqlModule.java create mode 100644 src/main/java/io/github/flibio/economylite/modules/sql/VirtualSqlService.java create mode 100644 src/main/resources/messages.properties delete mode 100644 src/me/Flibio/EconomyLite/API/EconomyLiteAPI.java delete mode 100644 src/me/Flibio/EconomyLite/API/LiteCurrency.java delete mode 100644 src/me/Flibio/EconomyLite/API/LiteEconomyService.java delete mode 100644 src/me/Flibio/EconomyLite/API/LiteTransferResult.java delete mode 100644 src/me/Flibio/EconomyLite/API/LiteUniqueAccount.java delete mode 100644 src/me/Flibio/EconomyLite/API/LiteVirtualAccount.java delete mode 100644 src/me/Flibio/EconomyLite/Commands/AddCommand.java delete mode 100644 src/me/Flibio/EconomyLite/Commands/BalanceCommand.java delete mode 100644 src/me/Flibio/EconomyLite/Commands/BusinessDeleteCommand.java delete mode 100644 src/me/Flibio/EconomyLite/Commands/BusinessInviteAcceptCommand.java delete mode 100644 src/me/Flibio/EconomyLite/Commands/BusinessInviteCommand.java delete mode 100644 src/me/Flibio/EconomyLite/Commands/BusinessLeaveCommand.java delete mode 100644 src/me/Flibio/EconomyLite/Commands/BusinessOwnersCommand.java delete mode 100644 src/me/Flibio/EconomyLite/Commands/BusinessRegisterCommand.java delete mode 100644 src/me/Flibio/EconomyLite/Commands/BusinessTransferCommand.java delete mode 100644 src/me/Flibio/EconomyLite/Commands/PayCommand.java delete mode 100644 src/me/Flibio/EconomyLite/Commands/PayOverrideCommand.java delete mode 100644 src/me/Flibio/EconomyLite/Commands/PlayerBalanceCommand.java delete mode 100644 src/me/Flibio/EconomyLite/Commands/RemoveCommand.java delete mode 100644 src/me/Flibio/EconomyLite/Commands/SetCommand.java delete mode 100644 src/me/Flibio/EconomyLite/EconomyLite.java delete mode 100644 src/me/Flibio/EconomyLite/Events/BalanceChangeEvent.java delete mode 100644 src/me/Flibio/EconomyLite/Events/LiteEconomyTransactionEvent.java delete mode 100644 src/me/Flibio/EconomyLite/Listeners/BalanceChangeListener.java delete mode 100644 src/me/Flibio/EconomyLite/Listeners/PlayerJoinListener.java delete mode 100644 src/me/Flibio/EconomyLite/Registry/CurrencyRegistryModule.java delete mode 100644 src/me/Flibio/EconomyLite/Utils/BusinessManager.java delete mode 100644 src/me/Flibio/EconomyLite/Utils/FileManager.java delete mode 100644 src/me/Flibio/EconomyLite/Utils/MySQLManager.java delete mode 100644 src/me/Flibio/EconomyLite/Utils/PlayerManager.java delete mode 100644 src/me/Flibio/EconomyLite/Utils/ScoreboardUtils.java delete mode 100644 src/me/Flibio/EconomyLite/Utils/TextUtils.java diff --git a/HEADER.txt b/HEADER.txt new file mode 100644 index 0000000..536d2c4 --- /dev/null +++ b/HEADER.txt @@ -0,0 +1,22 @@ +This file is part of ${name}, licensed under the MIT License (MIT). + +Copyright (c) ${inceptionYear} - ${currentYear} ${owner} +Copyright (c) Contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. \ No newline at end of file diff --git a/README.md b/README.md index 262dd03..fd93dcb 100644 --- a/README.md +++ b/README.md @@ -1,27 +1,31 @@ ![EconomyLite](http://i.imgur.com/MsuOo9w.png) +[![Downloads](https://img.shields.io/github/downloads/flibio/economylite/total.svg?style=flat-square)](https://github.com/Flibio/EconomyLite/releases) +[![Issues](https://img.shields.io/github/issues/flibio/economylite.svg?style=flat-square)](http://www.github.com/Flibio/EconomyLite/issues/) +[![Gitter](https://img.shields.io/badge/chat-on_gitter-3F51B5.svg?style=flat-square)](https://gitter.im/Flibio/EconomyLite) + EconomyLite is a lightweight, yet advanced economy plugin for your Sponge server. The plugin is built to be customizable, and you can enable and disable features at your will. ###Features - Drag & Drop Installation - - Just drop EconomyLite into your "mods" folder with Sponge and start your server + - Just drop EconomyLite into your "mods" folder with Sponge and start your server - Multi-Threaded - - EconomyLite is multi-threaded for the best possible performance + - EconomyLite is multi-threaded for the best possible performance - Multiple Storage Options - - Store your data however you like, MySQL or on a local file -- Modular - - Almost every aspect of EconomyLite can be changed to suit your needs -- Username Changes - - Any player can change their name, and EconomyLite can handle it -- Businesses - - EconomyLite has full support for creating businesses -- Administration - - Built-in commands used to interact with EconomyLite + - Store your data however you like, locally or on a MySQL database +- Customizable + - Much of EconomyLite can be changed to suit your needs +- Username Change Support + - Any player can change their name, and EconomyLite can handle it +- Virtual Management + - EconomyLite includes commands to manage virtual accounts +- Multiple Currencies + - EconomyLite has built-in support for multiple currencies ###Installation -Drag and drop EconomyLite into your "mods" folder along with Sponge and start your server. The configuration file can be found in `config/EconomyLite/config.conf`. +Drag and drop EconomyLite into your "mods" folder along with Sponge and start your server. The configuration files can be found in `config/EconomyLite`. --- diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..db02b8c --- /dev/null +++ b/build.gradle @@ -0,0 +1,83 @@ +plugins { + id 'java' + id 'eclipse' + id 'maven' + id 'com.github.hierynomus.license' version '0.12.1' + id 'net.ellune.blossom' version '1.0.1' + id 'com.github.johnrengelman.shadow' version '1.2.3' +} + +sourceCompatibility = '1.8' +targetCompatibility = '1.8' + +group 'io.github.flibio' +version '2.0.0' + +defaultTasks 'licenseFormat', 'clean', 'build' + +repositories { + mavenCentral() + jcenter() + maven { + name 'Sponge API repo' + url 'http://repo.spongepowered.org/maven' + } + maven { + name = 'minecrell' + url = 'http://repo.minecrell.net/releases' + } + maven { url "https://jitpack.io" } +} + +dependencies { + compile 'org.spongepowered:spongeapi:4.1.0-SNAPSHOT' + compile 'com.github.flibio:updatifier:v1.4.0:api' + compile 'net.minecrell.mcstats:statslite-sponge:0.2.2' + compile 'com.github.flibiostudio:utils:1.5.1' +} + +shadowJar { + dependencies { + include dependency('net.minecrell.mcstats:statslite-sponge') + include dependency('com.github.flibio:updatifier') + include dependency('com.github.flibiostudio:utils') + } + + relocate 'me.flibio.updatifier', 'io.github.flibio.economylite.updatifier' + relocate 'net.minecrell.mcstats', 'io.github.flibio.economylite.statslite' + relocate 'io.github.flibio.utils', 'io.github.flibio.economylite.utils' +} + +artifacts { + archives shadowJar +} + +license { + + // The project properties to use + ext.name = project.name + ext.owner = project.owner + ext.inceptionYear = project.inceptionYear + ext.currentYear = project.currentYear + + // The file that contains the license header + header file('HEADER.txt') + + // The source sets to apply the license to + sourceSets = project.sourceSets + + ignoreFailures false + strictCheck true + + mapping { + java = 'SLASHSTAR_STYLE' + } +} + +task wrapper(type: Wrapper) { + gradleVersion = '2.11' +} + +blossom { + replaceToken '@project.version@', project.version, 'src/main/java/io/github/flibio/economylite/PluginInfo.java' +} diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..b1c135e --- /dev/null +++ b/gradle.properties @@ -0,0 +1,4 @@ +name=EconomyLite +owner=Flibio +inceptionYear=2015 +currentYear=2016 diff --git a/gradlew b/gradlew new file mode 100644 index 0000000..9d82f78 --- /dev/null +++ b/gradlew @@ -0,0 +1,160 @@ +#!/usr/bin/env bash + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS="" + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn ( ) { + echo "$*" +} + +die ( ) { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; +esac + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +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" = "false" -a "$darwin" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin, switch paths to Windows format before running java +if $cygwin ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=$((i+1)) + done + case $i in + (0) set -- ;; + (1) set -- "$args0" ;; + (2) set -- "$args0" "$args1" ;; + (3) set -- "$args0" "$args1" "$args2" ;; + (4) set -- "$args0" "$args1" "$args2" "$args3" ;; + (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules +function splitJvmOpts() { + JVM_OPTS=("$@") +} +eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS +JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" + +exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..8a0b282 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,90 @@ +@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 + +@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= + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@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 init + +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 init + +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 + +:init +@rem Get command-line arguments, handling Windowz variants + +if not "%OS%" == "Windows_NT" goto win9xME_args +if "%@eval[2+2]" == "4" goto 4NT_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* +goto execute + +:4NT_args +@rem Get arguments from the 4NT Shell from JP Software +set CMD_LINE_ARGS=%$ + +: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 %CMD_LINE_ARGS% + +: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 diff --git a/pom.xml b/pom.xml deleted file mode 100644 index 890d8f5..0000000 --- a/pom.xml +++ /dev/null @@ -1,92 +0,0 @@ - - 4.0.0 - EconomyLite - EconomyLite - 1.2.2 - jar - EconomyLite - An economy plugin for Sponge - https://github.com/Flibio/EconomyLite - - - src - - - maven-compiler-plugin - 3.1 - - 1.8 - 1.8 - - - - org.apache.maven.plugins - maven-shade-plugin - 2.4.3 - - - package - - shade - - - - - net.minecrell.mcstats - me.Flibio.EconomyLite.mcstats - - - me.flibio.updatifier - me.Flibio.EconomyLite.updatifier - - - - - - - - - - - sponge-maven-repo - Sponge maven repo - http://repo.spongepowered.org/maven - - true - - - true - - - - minecrell - http://repo.minecrell.net/releases - - - jitpack.io - https://jitpack.io - - - - - - org.spongepowered - spongeapi - 4.0.3 - provided - - - com.github.Flibio - Updatifier - RELEASE - api - compile - - - net.minecrell.mcstats - statslite-sponge - 0.2.2 - compile - - - diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 0000000..e7516bf --- /dev/null +++ b/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'EconomyLite' diff --git a/src/main/java/io/github/flibio/economylite/EconomyLite.java b/src/main/java/io/github/flibio/economylite/EconomyLite.java new file mode 100644 index 0000000..d01fbd2 --- /dev/null +++ b/src/main/java/io/github/flibio/economylite/EconomyLite.java @@ -0,0 +1,256 @@ +/* + * This file is part of EconomyLite, licensed under the MIT License (MIT). + * + * Copyright (c) 2015 - 2016 Flibio + * Copyright (c) Contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package io.github.flibio.economylite; + +import me.flibio.updatifier.Updatifier; +import net.minecrell.mcstats.SpongeStatsLite; +import ninja.leaping.configurate.ConfigurationNode; + +import org.slf4j.Logger; +import org.spongepowered.api.Game; +import org.spongepowered.api.event.Listener; +import org.spongepowered.api.event.game.state.GameInitializationEvent; +import org.spongepowered.api.plugin.Plugin; +import org.spongepowered.api.service.economy.Currency; +import org.spongepowered.api.service.economy.EconomyService; +import org.spongepowered.api.text.serializer.TextSerializers; + +import com.google.common.collect.ImmutableList; +import com.google.inject.Inject; + +import io.github.flibio.economylite.api.CurrencyEconService; +import io.github.flibio.economylite.api.PlayerEconService; +import io.github.flibio.economylite.api.VirtualEconService; +import io.github.flibio.economylite.commands.PayCommand; +import io.github.flibio.economylite.commands.admin.AddCommand; +import io.github.flibio.economylite.commands.admin.EconCommand; +import io.github.flibio.economylite.commands.admin.RemoveCommand; +import io.github.flibio.economylite.commands.admin.SetCommand; +import io.github.flibio.economylite.commands.balance.BalTopCommand; +import io.github.flibio.economylite.commands.balance.BalanceCommand; +import io.github.flibio.economylite.commands.currency.CurrencyCommand; +import io.github.flibio.economylite.commands.currency.CurrencyCreateCommand; +import io.github.flibio.economylite.commands.currency.CurrencyDeleteCommand; +import io.github.flibio.economylite.commands.currency.CurrencySetCommand; +import io.github.flibio.economylite.commands.virtual.VirtualBalanceCommand; +import io.github.flibio.economylite.commands.virtual.VirtualSetCommand; +import io.github.flibio.economylite.impl.CurrencyService; +import io.github.flibio.economylite.impl.PlayerDataService; +import io.github.flibio.economylite.impl.VirtualDataService; +import io.github.flibio.economylite.impl.economy.LiteCurrency; +import io.github.flibio.economylite.impl.economy.LiteEconomyService; +import io.github.flibio.economylite.impl.economy.registry.CurrencyRegistryModule; +import io.github.flibio.economylite.modules.Module; +import io.github.flibio.economylite.modules.sql.SqlModule; +import io.github.flibio.utils.commands.CommandLoader; +import io.github.flibio.utils.file.ConfigManager; +import io.github.flibio.utils.message.MessageStorage; + +import java.util.List; +import java.util.Optional; + +@Updatifier(repoName = "EconomyLite", repoOwner = "Flibio", version = "v" + PluginInfo.VERSION) +@Plugin(id = PluginInfo.ID, name = PluginInfo.NAME, version = PluginInfo.VERSION, description = PluginInfo.DESCRIPTION) +public class EconomyLite { + + @Inject private Logger logger; + + @Inject private Game game; + + @Inject private SpongeStatsLite statsLite; + + private static ConfigManager configManager; + private static MessageStorage messageStorage; + private static EconomyLite instance; + + public static LiteEconomyService economyService; + private static VirtualEconService virtualEconService; + private static PlayerEconService playerEconService; + public static CurrencyEconService currencyEconService; + + @Listener + public void onServerInitialize(GameInitializationEvent event) { + logger.info("EconomyLite " + PluginInfo.VERSION + " is initializing!"); + instance = this; + // Start Statslite + this.statsLite.start(); + // File setup + configManager = ConfigManager.createInstance(this).get(); + initializeFiles(); + initializeCurrencies(); + // Load Message Storage + messageStorage = MessageStorage.createInstance(this); + initializeMessage(); + // Load modules + getModules().forEach(m -> { + m.initializeConfig(); + if (m.isEnabled()) { + if (m.initialize(logger, instance)) { + logger.info("Loaded the " + m.getName() + " module!"); + } else { + logger.error("Failed to load the " + m.getName() + " module!"); + } + } + }); + // If the services have not been set, set them to default. + if (playerEconService == null || virtualEconService == null) { + playerEconService = new PlayerDataService(); + virtualEconService = new VirtualDataService(); + } + // Load the economy service + economyService = new LiteEconomyService(); + // Register the Economy Service + game.getServiceManager().setProvider(this, EconomyService.class, economyService); + CommandLoader.registerCommands(this, TextSerializers.FORMATTING_CODE.serialize(messageStorage.getMessage("command.invalidsource")), + new CurrencyCommand(), + new CurrencySetCommand(), + new CurrencyDeleteCommand(), + new CurrencyCreateCommand(), + new BalanceCommand(), + new EconCommand(), + new SetCommand(), + new RemoveCommand(), + new AddCommand(), + new PayCommand(), + new BalTopCommand(), + new VirtualBalanceCommand(), + new VirtualSetCommand() + ); + // Register currency registry + game.getRegistry().registerModule(Currency.class, new CurrencyRegistryModule()); + } + + private void initializeFiles() { + configManager.setDefault("config.conf", "default-balance", Double.class, 0.0); + configManager.setDefault("config.conf", "virt-default-balance", Double.class, 0.0); + } + + public static boolean isEnabled(String path) { + if (configManager.getValue("config.conf", path, Boolean.class).isPresent()) { + return configManager.getValue("config.conf", path, Boolean.class).get(); + } else { + getInstance().getLogger().error("An error has occurred loading config value " + path + "! Defaulting to false."); + return false; + } + } + + private void initializeCurrencies() { + // Initialize the default currency into file + configManager.setDefault("currencies.conf", "current", String.class, "coin"); + configManager.setDefault("currencies.conf", "coin.singular", String.class, "Coin"); + configManager.setDefault("currencies.conf", "coin.plural", String.class, "Coins"); + configManager.setDefault("currencies.conf", "coin.symbol", String.class, "C"); + Currency defaultCurrency = new LiteCurrency("Coin", "Coins", "C", true, 2); + currencyEconService = new CurrencyService(defaultCurrency); + // Load all of the currencies + Optional fOpt = configManager.getFile("currencies.conf"); + if (fOpt.isPresent()) { + ConfigurationNode root = fOpt.get(); + for (Object raw : root.getChildrenMap().keySet()) { + if (raw instanceof String) { + String currencyId = (String) raw; + Optional sOpt = configManager.getValue("currencies.conf", currencyId + ".singular", String.class); + Optional pOpt = configManager.getValue("currencies.conf", currencyId + ".plural", String.class); + Optional syOpt = configManager.getValue("currencies.conf", currencyId + ".symbol", String.class); + if (sOpt.isPresent() && pOpt.isPresent() && syOpt.isPresent() && !currencyId.equals("coin")) { + Currency currency = new LiteCurrency(sOpt.get(), pOpt.get(), syOpt.get(), false, 2); + currencyEconService.addCurrency(currency); + } + } + } + } + // Attempt to load the current currency + Optional cOpt = configManager.getValue("currencies.conf", "current", String.class); + if (cOpt.isPresent()) { + String currentCur = cOpt.get(); + currencyEconService.getCurrencies().forEach(c -> { + if (("economylite:" + currentCur).equalsIgnoreCase(c.getId())) { + // This is the current currency + currencyEconService.setCurrentCurrency(c); + } + }); + } + // If the current currency string failed to load set it to default + if (currencyEconService.getCurrentCurrency().equals(defaultCurrency)) { + configManager.setValue("currencies.conf", "current", String.class, "coin"); + } + logger.info("Using currency: " + currencyEconService.getCurrentCurrency().getName()); + } + + private void initializeMessage() { + messageStorage.defaultMessages("messages"); + } + + public Logger getLogger() { + return logger; + } + + public Game getGame() { + return game; + } + + public static ConfigManager getConfigManager() { + return configManager; + } + + public static MessageStorage getMessageStorage() { + return messageStorage; + } + + public static PlayerEconService getPlayerService() { + return playerEconService; + } + + public static VirtualEconService getVirtualService() { + return virtualEconService; + } + + public static CurrencyEconService getCurrencyService() { + return currencyEconService; + } + + public static EconomyService getEconomyService() { + return economyService; + } + + public static EconomyLite getInstance() { + return instance; + } + + public static List getModules() { + return ImmutableList.of(new SqlModule()); + } + + // Setters + + public static void setPlayerService(PlayerEconService serv) { + playerEconService = serv; + } + + public static void setVirtualService(VirtualEconService serv) { + virtualEconService = serv; + } + +} diff --git a/src/main/java/io/github/flibio/economylite/PluginInfo.java b/src/main/java/io/github/flibio/economylite/PluginInfo.java new file mode 100644 index 0000000..946a6f4 --- /dev/null +++ b/src/main/java/io/github/flibio/economylite/PluginInfo.java @@ -0,0 +1,39 @@ +/* + * This file is part of EconomyLite, licensed under the MIT License (MIT). + * + * Copyright (c) 2015 - 2016 Flibio + * Copyright (c) Contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package io.github.flibio.economylite; + +/** + * General information about the {@link EconomyLite} plugin + */ +public class PluginInfo { + + private PluginInfo() { + } + + public static final String ID = "economylite"; + public static final String NAME = "EconomyLite"; + public static final String VERSION = "@project.version@"; + public static final String DESCRIPTION = "An economy plugin for Sponge."; +} diff --git a/src/main/java/io/github/flibio/economylite/api/CurrencyEconService.java b/src/main/java/io/github/flibio/economylite/api/CurrencyEconService.java new file mode 100644 index 0000000..074eda6 --- /dev/null +++ b/src/main/java/io/github/flibio/economylite/api/CurrencyEconService.java @@ -0,0 +1,75 @@ +/* + * This file is part of EconomyLite, licensed under the MIT License (MIT). + * + * Copyright (c) 2015 - 2016 Flibio + * Copyright (c) Contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package io.github.flibio.economylite.api; + +import org.spongepowered.api.service.economy.Currency; + +import java.util.Set; + +public interface CurrencyEconService { + + /** + * Gets all currencies. + * + * @return A set of all currencies. + */ + public Set getCurrencies(); + + /** + * Adds a currency to the currencies. + * + * @param currency The currency to add. + */ + public void addCurrency(Currency currency); + + /** + * Gets the default currency. + * + * @return The default currency. + */ + public Currency getDefaultCurrency(); + + /** + * Sets the currency in use by the server. + * + * @param currency The currency in use. + */ + public void setCurrentCurrency(Currency currency); + + /** + * Deletes a currency. + * + * @param currency The currency to delete. + */ + public void deleteCurrency(Currency currency); + + /** + * Gets the currency in use by the server. + * + * @return The currency in use. + */ + public Currency getCurrentCurrency(); + +} diff --git a/src/main/java/io/github/flibio/economylite/api/PlayerEconService.java b/src/main/java/io/github/flibio/economylite/api/PlayerEconService.java new file mode 100644 index 0000000..6a5edf3 --- /dev/null +++ b/src/main/java/io/github/flibio/economylite/api/PlayerEconService.java @@ -0,0 +1,114 @@ +/* + * This file is part of EconomyLite, licensed under the MIT License (MIT). + * + * Copyright (c) 2015 - 2016 Flibio + * Copyright (c) Contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package io.github.flibio.economylite.api; + +import org.spongepowered.api.service.economy.Currency; +import org.spongepowered.api.service.economy.account.UniqueAccount; + +import java.math.BigDecimal; +import java.util.List; +import java.util.UUID; + +/** + * Interfaces directly with the storage system. Performs no checks, simply does + * exactly what it is told. + */ +public interface PlayerEconService { + + /** + * Gets the balance of a player. + * + * @param uuid The UUID of the player to get the balance of. + * @param currency The currency to use. + * @return The balance of the player. + */ + public BigDecimal getBalance(UUID uuid, Currency currency); + + /** + * Sets the balance of a player. + * + * @param uuid The UUID of the player to set the balance of. + * @param balance The new balance of the uuid. + * @param currency The currency to use. + * @return If the player's balance was changed successfully. + */ + public boolean setBalance(UUID uuid, BigDecimal balance, Currency currency); + + /** + * Removes currency from a player's balance. + * + * @param uuid The UUID of the player to remove currency from. + * @param amount The amount of currency to remove. + * @param currency The currency to use. + * @return If the player's balance was changed successfully. + */ + default public boolean withdraw(UUID uuid, BigDecimal amount, Currency currency) { + return setBalance(uuid, getBalance(uuid, currency).subtract(amount), currency); + } + + /** + * Adds currency to a player's balance. + * + * @param uuid The UUID of the player to add currency to. + * @param amount The amount of currency to add. + * @param currency The currency to use. + * @return If the player's balance was changed successfully. + */ + default public boolean deposit(UUID uuid, BigDecimal amount, Currency currency) { + return setBalance(uuid, getBalance(uuid, currency).add(amount), currency); + } + + /** + * Checks if a player exists in the system with any currency. + * + * @param uuid The UUID of the player to check for. + * @return If the player exists or not. + */ + public boolean accountExists(UUID uuid); + + /** + * Checks if a player exists in the system for the specified currency. + * + * @param uuid The UUID of the player to check for. + * @param currency The currency to check against. + * @return If the player exists or not. + */ + public boolean accountExists(UUID uuid, Currency currency); + + /** + * Clears a currency from the database. + * + * @param currency The currency to clear. + */ + public void clearCurrency(Currency currency); + + /** + * Gets all unique accounts registered in the EconomyLite system. + * + * @return All unique accounts registered in the EconomyLite system. + */ + public List getAllAccounts(); + +} diff --git a/src/main/java/io/github/flibio/economylite/api/VirtualEconService.java b/src/main/java/io/github/flibio/economylite/api/VirtualEconService.java new file mode 100644 index 0000000..4541e1f --- /dev/null +++ b/src/main/java/io/github/flibio/economylite/api/VirtualEconService.java @@ -0,0 +1,113 @@ +/* + * This file is part of EconomyLite, licensed under the MIT License (MIT). + * + * Copyright (c) 2015 - 2016 Flibio + * Copyright (c) Contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package io.github.flibio.economylite.api; + +import org.spongepowered.api.service.economy.Currency; +import org.spongepowered.api.service.economy.account.VirtualAccount; + +import java.math.BigDecimal; +import java.util.List; + +/** + * Interfaces directly with the storage system. Performs no checks, simply does + * exactly what it is told. + */ +public interface VirtualEconService { + + /** + * Gets the balance of an account. + * + * @param id The name of the account to get the balance of. + * @param currency The currency to use. + * @return The balance of the account. + */ + public BigDecimal getBalance(String id, Currency currency); + + /** + * Sets the balance of an account. + * + * @param id The String of the player to set the balance of. + * @param balance The new balance of the id. + * @param currency The currency to use. + * @return If the player's balance was changed successfully. + */ + public boolean setBalance(String id, BigDecimal balance, Currency currency); + + /** + * Removes currency from an accounts's balance. + * + * @param id The name of the account to remove currency from. + * @param amount The amount of currency to remove. + * @param currency The currency to use. + * @return If the account's balance was changed successfully. + */ + default public boolean withdraw(String id, BigDecimal amount, Currency currency) { + return setBalance(id, getBalance(id, currency).subtract(amount), currency); + } + + /** + * Adds currency to an account's balance. + * + * @param id The name of the account to add currency to. + * @param amount The amount of currency to add. + * @param currency The currency to use. + * @return If the account's balance was changed successfully. + */ + default public boolean deposit(String id, BigDecimal amount, Currency currency) { + return setBalance(id, getBalance(id, currency).add(amount), currency); + } + + /** + * Checks if an account exists in the system. + * + * @param id The name of the account to check for. + * @return If the account exists or not. + */ + public boolean accountExists(String id); + + /** + * Checks if an account exists in the system for the specified currency. + * + * @param id The name of the account to check for. + * @param currency The currency to check against. + * @return If the account exists or not. + */ + public boolean accountExists(String id, Currency currency); + + /** + * Clears a currency from the database. + * + * @param currency The currency to clear. + */ + public void clearCurrency(Currency currency); + + /** + * Gets all virtual accounts registered in the EconomyLite system. + * + * @return All virtual accounts registered in the EconomyLite system. + */ + public List getAllAccounts(); + +} diff --git a/src/main/java/io/github/flibio/economylite/commands/PayCommand.java b/src/main/java/io/github/flibio/economylite/commands/PayCommand.java new file mode 100644 index 0000000..c8a4496 --- /dev/null +++ b/src/main/java/io/github/flibio/economylite/commands/PayCommand.java @@ -0,0 +1,91 @@ +/* + * This file is part of EconomyLite, licensed under the MIT License (MIT). + * + * Copyright (c) 2015 - 2016 Flibio + * Copyright (c) Contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package io.github.flibio.economylite.commands; + +import org.spongepowered.api.command.args.CommandContext; +import org.spongepowered.api.command.args.GenericArguments; +import org.spongepowered.api.command.spec.CommandSpec; +import org.spongepowered.api.command.spec.CommandSpec.Builder; +import org.spongepowered.api.entity.living.player.Player; +import org.spongepowered.api.entity.living.player.User; +import org.spongepowered.api.event.cause.Cause; +import org.spongepowered.api.event.cause.NamedCause; +import org.spongepowered.api.service.economy.EconomyService; +import org.spongepowered.api.service.economy.account.UniqueAccount; +import org.spongepowered.api.service.economy.transaction.ResultType; +import org.spongepowered.api.text.Text; + +import io.github.flibio.economylite.EconomyLite; +import io.github.flibio.utils.commands.AsyncCommand; +import io.github.flibio.utils.commands.BaseCommandExecutor; +import io.github.flibio.utils.commands.Command; +import io.github.flibio.utils.message.MessageStorage; + +import java.math.BigDecimal; +import java.util.Optional; + +@AsyncCommand +@Command(aliases = {"pay"}, permission = "economylite.pay") +public class PayCommand extends BaseCommandExecutor { + + private MessageStorage messageStorage = EconomyLite.getMessageStorage(); + private EconomyService ecoService = EconomyLite.getEconomyService(); + + @Override + public Builder getCommandSpecBuilder() { + return CommandSpec.builder() + .executor(this) + .arguments(GenericArguments.user(Text.of("player")), GenericArguments.doubleNum(Text.of("amount"))); + } + + @Override + public void run(Player src, CommandContext args) { + if (args.getOne("player").isPresent() && args.getOne("amount").isPresent()) { + BigDecimal amount = BigDecimal.valueOf(args.getOne("amount").get()); + User target = args.getOne("player").get(); + String targetName = target.getName(); + if (!target.getUniqueId().equals(src.getUniqueId())) { + Optional uOpt = ecoService.getOrCreateAccount(src.getUniqueId()); + Optional tOpt = ecoService.getOrCreateAccount(target.getUniqueId()); + if (uOpt.isPresent() && tOpt.isPresent()) { + if (uOpt.get() + .transfer(tOpt.get(), ecoService.getDefaultCurrency(), amount, Cause.of(NamedCause.owner(EconomyLite.getInstance()))) + .getResult().equals(ResultType.SUCCESS)) { + src.sendMessage(messageStorage.getMessage("command.pay.success", "target", targetName)); + } else { + src.sendMessage(messageStorage.getMessage("command.pay.failed", "target", targetName)); + } + } else { + src.sendMessage(messageStorage.getMessage("command.error")); + } + } else { + src.sendMessage(messageStorage.getMessage("command.pay.notyou")); + } + } else { + src.sendMessage(messageStorage.getMessage("command.error")); + } + } + +} diff --git a/src/main/java/io/github/flibio/economylite/commands/admin/AddCommand.java b/src/main/java/io/github/flibio/economylite/commands/admin/AddCommand.java new file mode 100644 index 0000000..46cb0dd --- /dev/null +++ b/src/main/java/io/github/flibio/economylite/commands/admin/AddCommand.java @@ -0,0 +1,86 @@ +/* + * This file is part of EconomyLite, licensed under the MIT License (MIT). + * + * Copyright (c) 2015 - 2016 Flibio + * Copyright (c) Contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package io.github.flibio.economylite.commands.admin; + +import org.spongepowered.api.command.CommandSource; +import org.spongepowered.api.command.args.CommandContext; +import org.spongepowered.api.command.args.GenericArguments; +import org.spongepowered.api.command.spec.CommandSpec; +import org.spongepowered.api.command.spec.CommandSpec.Builder; +import org.spongepowered.api.entity.living.player.User; +import org.spongepowered.api.event.cause.Cause; +import org.spongepowered.api.event.cause.NamedCause; +import org.spongepowered.api.service.economy.account.UniqueAccount; +import org.spongepowered.api.service.economy.transaction.ResultType; +import org.spongepowered.api.text.Text; + +import io.github.flibio.economylite.EconomyLite; +import io.github.flibio.utils.commands.AsyncCommand; +import io.github.flibio.utils.commands.BaseCommandExecutor; +import io.github.flibio.utils.commands.Command; +import io.github.flibio.utils.commands.ParentCommand; +import io.github.flibio.utils.message.MessageStorage; + +import java.math.BigDecimal; +import java.util.Optional; + +@AsyncCommand +@ParentCommand(parentCommand = EconCommand.class) +@Command(aliases = {"add"}, permission = "economylite.admin.econ.add") +public class AddCommand extends BaseCommandExecutor { + + private MessageStorage messageStorage = EconomyLite.getMessageStorage(); + + @Override + public Builder getCommandSpecBuilder() { + return CommandSpec.builder() + .executor(this) + .arguments(GenericArguments.user(Text.of("player")), GenericArguments.doubleNum(Text.of("amount"))); + } + + @Override + public void run(CommandSource src, CommandContext args) { + if (args.getOne("player").isPresent() && args.getOne("amount").isPresent()) { + User target = args.getOne("player").get(); + String targetName = target.getName(); + BigDecimal toAdd = BigDecimal.valueOf(args.getOne("amount").get()); + Optional uOpt = EconomyLite.getEconomyService().getOrCreateAccount(target.getUniqueId()); + if (uOpt.isPresent()) { + UniqueAccount targetAccount = uOpt.get(); + if (targetAccount.deposit(EconomyLite.getCurrencyService().getCurrentCurrency(), toAdd, + Cause.of(NamedCause.owner(EconomyLite.getInstance()))).getResult().equals(ResultType.SUCCESS)) { + src.sendMessage(messageStorage.getMessage("command.econ.addsuccess", "name", targetName)); + } else { + src.sendMessage(messageStorage.getMessage("command.econ.addfail", "name", targetName)); + } + } else { + src.sendMessage(messageStorage.getMessage("command.error")); + } + } else { + src.sendMessage(messageStorage.getMessage("command.error")); + } + } + +} diff --git a/src/main/java/io/github/flibio/economylite/commands/admin/EconCommand.java b/src/main/java/io/github/flibio/economylite/commands/admin/EconCommand.java new file mode 100644 index 0000000..a215a95 --- /dev/null +++ b/src/main/java/io/github/flibio/economylite/commands/admin/EconCommand.java @@ -0,0 +1,55 @@ +/* + * This file is part of EconomyLite, licensed under the MIT License (MIT). + * + * Copyright (c) 2015 - 2016 Flibio + * Copyright (c) Contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package io.github.flibio.economylite.commands.admin; + +import org.spongepowered.api.command.CommandSource; +import org.spongepowered.api.command.args.CommandContext; +import org.spongepowered.api.command.spec.CommandSpec; +import org.spongepowered.api.command.spec.CommandSpec.Builder; + +import io.github.flibio.economylite.EconomyLite; +import io.github.flibio.utils.commands.AsyncCommand; +import io.github.flibio.utils.commands.BaseCommandExecutor; +import io.github.flibio.utils.commands.Command; +import io.github.flibio.utils.message.MessageStorage; + +@AsyncCommand +@Command(aliases = {"economy", "econ", "eco"}, permission = "economylite.admin.econ") +public class EconCommand extends BaseCommandExecutor { + + private MessageStorage messageStorage = EconomyLite.getMessageStorage(); + + @Override + public Builder getCommandSpecBuilder() { + return CommandSpec.builder() + .executor(this); + } + + @Override + public void run(CommandSource src, CommandContext args) { + src.sendMessage(messageStorage.getMessage("command.usage", "command", "/econ", "subcommands", "add | set | remove ")); + } + +} diff --git a/src/main/java/io/github/flibio/economylite/commands/admin/RemoveCommand.java b/src/main/java/io/github/flibio/economylite/commands/admin/RemoveCommand.java new file mode 100644 index 0000000..92ed54c --- /dev/null +++ b/src/main/java/io/github/flibio/economylite/commands/admin/RemoveCommand.java @@ -0,0 +1,86 @@ +/* + * This file is part of EconomyLite, licensed under the MIT License (MIT). + * + * Copyright (c) 2015 - 2016 Flibio + * Copyright (c) Contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package io.github.flibio.economylite.commands.admin; + +import org.spongepowered.api.command.CommandSource; +import org.spongepowered.api.command.args.CommandContext; +import org.spongepowered.api.command.args.GenericArguments; +import org.spongepowered.api.command.spec.CommandSpec; +import org.spongepowered.api.command.spec.CommandSpec.Builder; +import org.spongepowered.api.entity.living.player.User; +import org.spongepowered.api.event.cause.Cause; +import org.spongepowered.api.event.cause.NamedCause; +import org.spongepowered.api.service.economy.account.UniqueAccount; +import org.spongepowered.api.service.economy.transaction.ResultType; +import org.spongepowered.api.text.Text; + +import io.github.flibio.economylite.EconomyLite; +import io.github.flibio.utils.commands.AsyncCommand; +import io.github.flibio.utils.commands.BaseCommandExecutor; +import io.github.flibio.utils.commands.Command; +import io.github.flibio.utils.commands.ParentCommand; +import io.github.flibio.utils.message.MessageStorage; + +import java.math.BigDecimal; +import java.util.Optional; + +@AsyncCommand +@ParentCommand(parentCommand = EconCommand.class) +@Command(aliases = {"remove"}, permission = "economylite.admin.econ.remove") +public class RemoveCommand extends BaseCommandExecutor { + + private MessageStorage messageStorage = EconomyLite.getMessageStorage(); + + @Override + public Builder getCommandSpecBuilder() { + return CommandSpec.builder() + .executor(this) + .arguments(GenericArguments.user(Text.of("player")), GenericArguments.doubleNum(Text.of("amount"))); + } + + @Override + public void run(CommandSource src, CommandContext args) { + if (args.getOne("player").isPresent() && args.getOne("amount").isPresent()) { + User target = args.getOne("player").get(); + String targetName = target.getName(); + BigDecimal toRemove = BigDecimal.valueOf(args.getOne("amount").get()); + Optional uOpt = EconomyLite.getEconomyService().getOrCreateAccount(target.getUniqueId()); + if (uOpt.isPresent()) { + UniqueAccount targetAccount = uOpt.get(); + if (targetAccount.withdraw(EconomyLite.getCurrencyService().getCurrentCurrency(), toRemove, + Cause.of(NamedCause.owner(EconomyLite.getInstance()))).getResult().equals(ResultType.SUCCESS)) { + src.sendMessage(messageStorage.getMessage("command.econ.removesuccess", "name", targetName)); + } else { + src.sendMessage(messageStorage.getMessage("command.econ.removefail", "name", targetName)); + } + } else { + src.sendMessage(messageStorage.getMessage("command.error")); + } + } else { + src.sendMessage(messageStorage.getMessage("command.error")); + } + } + +} diff --git a/src/main/java/io/github/flibio/economylite/commands/admin/SetCommand.java b/src/main/java/io/github/flibio/economylite/commands/admin/SetCommand.java new file mode 100644 index 0000000..3785e29 --- /dev/null +++ b/src/main/java/io/github/flibio/economylite/commands/admin/SetCommand.java @@ -0,0 +1,86 @@ +/* + * This file is part of EconomyLite, licensed under the MIT License (MIT). + * + * Copyright (c) 2015 - 2016 Flibio + * Copyright (c) Contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package io.github.flibio.economylite.commands.admin; + +import org.spongepowered.api.command.CommandSource; +import org.spongepowered.api.command.args.CommandContext; +import org.spongepowered.api.command.args.GenericArguments; +import org.spongepowered.api.command.spec.CommandSpec; +import org.spongepowered.api.command.spec.CommandSpec.Builder; +import org.spongepowered.api.entity.living.player.User; +import org.spongepowered.api.event.cause.Cause; +import org.spongepowered.api.event.cause.NamedCause; +import org.spongepowered.api.service.economy.account.UniqueAccount; +import org.spongepowered.api.service.economy.transaction.ResultType; +import org.spongepowered.api.text.Text; + +import io.github.flibio.economylite.EconomyLite; +import io.github.flibio.utils.commands.AsyncCommand; +import io.github.flibio.utils.commands.BaseCommandExecutor; +import io.github.flibio.utils.commands.Command; +import io.github.flibio.utils.commands.ParentCommand; +import io.github.flibio.utils.message.MessageStorage; + +import java.math.BigDecimal; +import java.util.Optional; + +@AsyncCommand +@ParentCommand(parentCommand = EconCommand.class) +@Command(aliases = {"set"}, permission = "economylite.admin.econ.set") +public class SetCommand extends BaseCommandExecutor { + + private MessageStorage messageStorage = EconomyLite.getMessageStorage(); + + @Override + public Builder getCommandSpecBuilder() { + return CommandSpec.builder() + .executor(this) + .arguments(GenericArguments.user(Text.of("player")), GenericArguments.doubleNum(Text.of("balance"))); + } + + @Override + public void run(CommandSource src, CommandContext args) { + if (args.getOne("player").isPresent() && args.getOne("balance").isPresent()) { + User target = args.getOne("player").get(); + String targetName = target.getName(); + BigDecimal newBal = BigDecimal.valueOf(args.getOne("balance").get()); + Optional uOpt = EconomyLite.getEconomyService().getOrCreateAccount(target.getUniqueId()); + if (uOpt.isPresent()) { + UniqueAccount targetAccount = uOpt.get(); + if (targetAccount.setBalance(EconomyLite.getCurrencyService().getCurrentCurrency(), newBal, + Cause.of(NamedCause.owner(EconomyLite.getInstance()))).getResult().equals(ResultType.SUCCESS)) { + src.sendMessage(messageStorage.getMessage("command.econ.setsuccess", "name", targetName)); + } else { + src.sendMessage(messageStorage.getMessage("command.econ.setfail", "name", targetName)); + } + } else { + src.sendMessage(messageStorage.getMessage("command.error")); + } + } else { + src.sendMessage(messageStorage.getMessage("command.error")); + } + } + +} diff --git a/src/main/java/io/github/flibio/economylite/commands/balance/BalTopCommand.java b/src/main/java/io/github/flibio/economylite/commands/balance/BalTopCommand.java new file mode 100644 index 0000000..74106b8 --- /dev/null +++ b/src/main/java/io/github/flibio/economylite/commands/balance/BalTopCommand.java @@ -0,0 +1,75 @@ +/* + * This file is part of EconomyLite, licensed under the MIT License (MIT). + * + * Copyright (c) 2015 - 2016 Flibio + * Copyright (c) Contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package io.github.flibio.economylite.commands.balance; + +import org.spongepowered.api.command.CommandSource; +import org.spongepowered.api.command.args.CommandContext; +import org.spongepowered.api.command.spec.CommandSpec; +import org.spongepowered.api.command.spec.CommandSpec.Builder; +import org.spongepowered.api.service.economy.Currency; +import org.spongepowered.api.service.economy.account.UniqueAccount; +import org.spongepowered.api.text.Text; + +import com.google.common.collect.ImmutableMap; + +import io.github.flibio.economylite.EconomyLite; +import io.github.flibio.utils.commands.AsyncCommand; +import io.github.flibio.utils.commands.BaseCommandExecutor; +import io.github.flibio.utils.commands.Command; + +import java.math.BigDecimal; +import java.util.Map; +import java.util.TreeMap; + +@AsyncCommand +@Command(aliases = {"baltop"}, permission = "economylite.baltop") +public class BalTopCommand extends BaseCommandExecutor { + + @Override + public Builder getCommandSpecBuilder() { + return CommandSpec.builder() + .executor(this); + } + + @Override + public void run(CommandSource src, CommandContext args) { + Currency currency = EconomyLite.getCurrencyService().getCurrentCurrency(); + src.sendMessage(EconomyLite.getMessageStorage().getMessage("command.baltop.head")); + Currency current = EconomyLite.getEconomyService().getDefaultCurrency(); + TreeMap bals = new TreeMap<>(); + for (UniqueAccount account : EconomyLite.getPlayerService().getAllAccounts()) { + bals.put(account.getDisplayName().toPlain(), account.getBalance(current)); + } + + bals.entrySet().stream().sorted(Map.Entry.comparingByValue().reversed()).limit(3).forEachOrdered(e -> { + Text label = current.getPluralDisplayName(); + if (e.getValue().equals(BigDecimal.ONE)) { + label = current.getDisplayName(); + } + src.sendMessage(EconomyLite.getMessageStorage().getMessage("command.baltop.data", + ImmutableMap.of("name", Text.of(e.getKey()), "balance", currency.format(e.getValue()), "label", label))); + }); + } +} diff --git a/src/main/java/io/github/flibio/economylite/commands/balance/BalanceCommand.java b/src/main/java/io/github/flibio/economylite/commands/balance/BalanceCommand.java new file mode 100644 index 0000000..73c31e4 --- /dev/null +++ b/src/main/java/io/github/flibio/economylite/commands/balance/BalanceCommand.java @@ -0,0 +1,108 @@ +/* + * This file is part of EconomyLite, licensed under the MIT License (MIT). + * + * Copyright (c) 2015 - 2016 Flibio + * Copyright (c) Contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package io.github.flibio.economylite.commands.balance; + +import org.spongepowered.api.command.CommandSource; +import org.spongepowered.api.command.args.CommandContext; +import org.spongepowered.api.command.args.GenericArguments; +import org.spongepowered.api.command.spec.CommandSpec; +import org.spongepowered.api.command.spec.CommandSpec.Builder; +import org.spongepowered.api.entity.living.player.Player; +import org.spongepowered.api.entity.living.player.User; +import org.spongepowered.api.service.economy.Currency; +import org.spongepowered.api.service.economy.account.UniqueAccount; +import org.spongepowered.api.text.Text; + +import com.google.common.collect.ImmutableMap; + +import io.github.flibio.economylite.EconomyLite; +import io.github.flibio.economylite.api.CurrencyEconService; +import io.github.flibio.utils.commands.AsyncCommand; +import io.github.flibio.utils.commands.BaseCommandExecutor; +import io.github.flibio.utils.commands.Command; +import io.github.flibio.utils.message.MessageStorage; + +import java.math.BigDecimal; +import java.util.Optional; + +@AsyncCommand +@Command(aliases = {"balance", "bal"}, permission = "economylite.balance") +public class BalanceCommand extends BaseCommandExecutor { + + private MessageStorage messageStorage = EconomyLite.getMessageStorage(); + private CurrencyEconService currencyService = EconomyLite.getCurrencyService(); + + @Override + public Builder getCommandSpecBuilder() { + return CommandSpec.builder() + .executor(this) + .arguments(GenericArguments.optional(GenericArguments.user(Text.of("player")))); + } + + @Override + public void run(CommandSource src, CommandContext args) { + Currency currency = currencyService.getCurrentCurrency(); + if (args.getOne("player").isPresent()) { + if (src.hasPermission("economylite.admin.balanceothers")) { + User target = args.getOne("player").get(); + String targetName = target.getName(); + Optional uOpt = EconomyLite.getEconomyService().getOrCreateAccount(target.getUniqueId()); + if (uOpt.isPresent()) { + BigDecimal bal = uOpt.get().getBalance(currency); + Text label = currency.getPluralDisplayName(); + if (bal.equals(BigDecimal.ONE)) { + label = currency.getDisplayName(); + } + src.sendMessage(messageStorage.getMessage("command.balanceother", + ImmutableMap.of("player", Text.of(targetName), "balance", currency.format(bal), "label", label))); + } else { + src.sendMessage(messageStorage.getMessage("command.error")); + } + } else { + src.sendMessage(messageStorage.getMessage("command.noperm")); + } + } else { + // Get the balance of the running player + if (src instanceof Player) { + Player player = (Player) src; + Optional uOpt = EconomyLite.getEconomyService().getOrCreateAccount(player.getUniqueId()); + if (uOpt.isPresent()) { + BigDecimal bal = uOpt.get().getBalance(currency); + Text label = currency.getPluralDisplayName(); + if (bal.equals(BigDecimal.ONE)) { + label = currency.getDisplayName(); + } + src.sendMessage(messageStorage.getMessage("command.balance", "balance", currency.format(bal), "label", label)); + } else { + src.sendMessage(messageStorage.getMessage("command.error")); + } + } else { + // If the there are no arguments the source must be a player + src.sendMessage(messageStorage.getMessage("command.invalidsource", "sourcetype", "player")); + } + } + } + +} diff --git a/src/main/java/io/github/flibio/economylite/commands/currency/CurrencyCommand.java b/src/main/java/io/github/flibio/economylite/commands/currency/CurrencyCommand.java new file mode 100644 index 0000000..a729988 --- /dev/null +++ b/src/main/java/io/github/flibio/economylite/commands/currency/CurrencyCommand.java @@ -0,0 +1,56 @@ +/* + * This file is part of EconomyLite, licensed under the MIT License (MIT). + * + * Copyright (c) 2015 - 2016 Flibio + * Copyright (c) Contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package io.github.flibio.economylite.commands.currency; + +import org.spongepowered.api.command.CommandSource; +import org.spongepowered.api.command.args.CommandContext; +import org.spongepowered.api.command.spec.CommandSpec; +import org.spongepowered.api.command.spec.CommandSpec.Builder; + +import io.github.flibio.economylite.EconomyLite; +import io.github.flibio.utils.commands.AsyncCommand; +import io.github.flibio.utils.commands.BaseCommandExecutor; +import io.github.flibio.utils.commands.Command; +import io.github.flibio.utils.message.MessageStorage; + +@AsyncCommand +@Command(aliases = {"currency", "cur"}, permission = "economylite.admin.currency") +public class CurrencyCommand extends BaseCommandExecutor { + + private MessageStorage messageStorage = EconomyLite.getMessageStorage(); + + @Override + public Builder getCommandSpecBuilder() { + return CommandSpec.builder() + .executor(this); + } + + @Override + public void run(CommandSource src, CommandContext args) { + src.sendMessage(messageStorage.getMessage("command.currency.current", "currency", EconomyLite.getEconomyService().getDefaultCurrency() + .getDisplayName())); + src.sendMessage(messageStorage.getMessage("command.usage", "command", "/currency", "subcommands", "set | create | delete")); + } +} diff --git a/src/main/java/io/github/flibio/economylite/commands/currency/CurrencyCreateCommand.java b/src/main/java/io/github/flibio/economylite/commands/currency/CurrencyCreateCommand.java new file mode 100644 index 0000000..71deed1 --- /dev/null +++ b/src/main/java/io/github/flibio/economylite/commands/currency/CurrencyCreateCommand.java @@ -0,0 +1,90 @@ +/* + * This file is part of EconomyLite, licensed under the MIT License (MIT). + * + * Copyright (c) 2015 - 2016 Flibio + * Copyright (c) Contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package io.github.flibio.economylite.commands.currency; + +import org.spongepowered.api.command.CommandSource; +import org.spongepowered.api.command.args.CommandContext; +import org.spongepowered.api.command.args.GenericArguments; +import org.spongepowered.api.command.spec.CommandSpec; +import org.spongepowered.api.command.spec.CommandSpec.Builder; +import org.spongepowered.api.service.economy.Currency; +import org.spongepowered.api.text.Text; + +import io.github.flibio.economylite.EconomyLite; +import io.github.flibio.economylite.api.CurrencyEconService; +import io.github.flibio.economylite.impl.economy.LiteCurrency; +import io.github.flibio.utils.commands.AsyncCommand; +import io.github.flibio.utils.commands.BaseCommandExecutor; +import io.github.flibio.utils.commands.Command; +import io.github.flibio.utils.commands.ParentCommand; +import io.github.flibio.utils.file.ConfigManager; +import io.github.flibio.utils.message.MessageStorage; + +@AsyncCommand +@ParentCommand(parentCommand = CurrencyCommand.class) +@Command(aliases = {"create"}, permission = "economylite.admin.currency.create") +public class CurrencyCreateCommand extends BaseCommandExecutor { + + private MessageStorage messageStorage = EconomyLite.getMessageStorage(); + private CurrencyEconService currencyService = EconomyLite.getCurrencyService(); + private ConfigManager configManager = EconomyLite.getConfigManager(); + + @Override + public Builder getCommandSpecBuilder() { + return CommandSpec + .builder() + .executor(this) + .arguments(GenericArguments.string(Text.of("singular")), GenericArguments.string(Text.of("plural")), + GenericArguments.string(Text.of("symbol"))); + } + + @Override + public void run(CommandSource src, CommandContext args) { + if (args.getOne("singular").isPresent() && args.getOne("plural").isPresent() && args.getOne("symbol").isPresent()) { + String singular = args.getOne("singular").get(); + String plural = args.getOne("plural").get(); + String symbol = args.getOne("symbol").get(); + boolean found = false; + for (Currency c : currencyService.getCurrencies()) { + if (c.getDisplayName().toPlain().equalsIgnoreCase(singular)) { + found = true; + } + } + if (found) { + src.sendMessage(messageStorage.getMessage("command.currency.exists")); + } else { + Currency currency = new LiteCurrency(singular, plural, symbol, false, 2); + currencyService.addCurrency(currency); + String configId = currency.getId().replaceAll("economylite:", ""); + configManager.setValue("currencies.conf", configId + ".singular", String.class, currency.getDisplayName().toPlain()); + configManager.setValue("currencies.conf", configId + ".plural", String.class, currency.getPluralDisplayName().toPlain()); + configManager.setValue("currencies.conf", configId + ".symbol", String.class, currency.getSymbol().toPlain()); + src.sendMessage(messageStorage.getMessage("command.currency.created", "currency", currency.getDisplayName().toPlain())); + } + } else { + src.sendMessage(messageStorage.getMessage("command.error")); + } + } +} diff --git a/src/main/java/io/github/flibio/economylite/commands/currency/CurrencyDeleteCommand.java b/src/main/java/io/github/flibio/economylite/commands/currency/CurrencyDeleteCommand.java new file mode 100644 index 0000000..e5fee51 --- /dev/null +++ b/src/main/java/io/github/flibio/economylite/commands/currency/CurrencyDeleteCommand.java @@ -0,0 +1,102 @@ +/* + * This file is part of EconomyLite, licensed under the MIT License (MIT). + * + * Copyright (c) 2015 - 2016 Flibio + * Copyright (c) Contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package io.github.flibio.economylite.commands.currency; + +import org.spongepowered.api.command.CommandSource; +import org.spongepowered.api.command.args.CommandContext; +import org.spongepowered.api.command.args.GenericArguments; +import org.spongepowered.api.command.spec.CommandSpec; +import org.spongepowered.api.command.spec.CommandSpec.Builder; +import org.spongepowered.api.service.economy.Currency; +import org.spongepowered.api.text.Text; +import org.spongepowered.api.text.action.TextActions; + +import io.github.flibio.economylite.EconomyLite; +import io.github.flibio.economylite.api.CurrencyEconService; +import io.github.flibio.utils.commands.AsyncCommand; +import io.github.flibio.utils.commands.BaseCommandExecutor; +import io.github.flibio.utils.commands.Command; +import io.github.flibio.utils.commands.ParentCommand; +import io.github.flibio.utils.message.MessageStorage; + +@AsyncCommand +@ParentCommand(parentCommand = CurrencyCommand.class) +@Command(aliases = {"delete"}, permission = "economylite.admin.currency.delete") +public class CurrencyDeleteCommand extends BaseCommandExecutor { + + private MessageStorage messageStorage = EconomyLite.getMessageStorage(); + private CurrencyEconService currencyService = EconomyLite.getCurrencyService(); + + @Override + public Builder getCommandSpecBuilder() { + return CommandSpec.builder() + .executor(this) + .arguments(GenericArguments.optional(GenericArguments.remainingJoinedStrings(Text.of("currency")))); + } + + @Override + public void run(CommandSource src, CommandContext args) { + if (args.getOne("currency").isPresent()) { + String currencyName = args.getOne("currency").get(); + boolean found = false; + for (Currency c : currencyService.getCurrencies()) { + if (c.getDisplayName().toPlain().equalsIgnoreCase(currencyName)) { + found = true; + if (currencyService.getDefaultCurrency().equals(c)) { + // You can not delete the default + src.sendMessage(messageStorage.getMessage("command.currency.deletedefault")); + } else { + if (currencyService.getCurrentCurrency().equals(c)) { + currencyService.setCurrentCurrency(currencyService.getDefaultCurrency()); + } + currencyService.deleteCurrency(c); + src.sendMessage(messageStorage.getMessage("command.currency.deleted", "currency", c.getDisplayName())); + } + } + } + if (!found) { + src.sendMessage(messageStorage.getMessage("command.currency.invalid")); + } + } else { + src.sendMessage(messageStorage.getMessage("command.currency.delete")); + currencyService.getCurrencies().forEach(currency -> { + if (!currency.equals(currencyService.getDefaultCurrency())) { + src.sendMessage(Text.of(currency.getDisplayName()).toBuilder().onClick(TextActions.executeCallback(c -> { + src.sendMessage(messageStorage.getMessage("command.currency.deleteconfirm", "currency", currency.getDisplayName()) + .toBuilder().onClick( + TextActions.executeCallback(c2 -> { + if (currencyService.getCurrentCurrency().equals(currency)) { + currencyService.setCurrentCurrency(currencyService.getDefaultCurrency()); + } + currencyService.deleteCurrency(currency); + src.sendMessage(messageStorage.getMessage("command.currency.deleted", "currency", + currency.getDisplayName())); + })).build()); + })).build()); + } + }); + } + } +} diff --git a/src/main/java/io/github/flibio/economylite/commands/currency/CurrencySetCommand.java b/src/main/java/io/github/flibio/economylite/commands/currency/CurrencySetCommand.java new file mode 100644 index 0000000..8339231 --- /dev/null +++ b/src/main/java/io/github/flibio/economylite/commands/currency/CurrencySetCommand.java @@ -0,0 +1,88 @@ +/* + * This file is part of EconomyLite, licensed under the MIT License (MIT). + * + * Copyright (c) 2015 - 2016 Flibio + * Copyright (c) Contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package io.github.flibio.economylite.commands.currency; + +import org.spongepowered.api.command.CommandSource; +import org.spongepowered.api.command.args.CommandContext; +import org.spongepowered.api.command.args.GenericArguments; +import org.spongepowered.api.command.spec.CommandSpec; +import org.spongepowered.api.command.spec.CommandSpec.Builder; +import org.spongepowered.api.service.economy.Currency; +import org.spongepowered.api.text.Text; +import org.spongepowered.api.text.action.TextActions; + +import io.github.flibio.economylite.EconomyLite; +import io.github.flibio.economylite.api.CurrencyEconService; +import io.github.flibio.utils.commands.AsyncCommand; +import io.github.flibio.utils.commands.BaseCommandExecutor; +import io.github.flibio.utils.commands.Command; +import io.github.flibio.utils.commands.ParentCommand; +import io.github.flibio.utils.message.MessageStorage; + +@AsyncCommand +@ParentCommand(parentCommand = CurrencyCommand.class) +@Command(aliases = {"set"}, permission = "economylite.admin.currency.set") +public class CurrencySetCommand extends BaseCommandExecutor { + + private MessageStorage messageStorage = EconomyLite.getMessageStorage(); + private CurrencyEconService currencyService = EconomyLite.getCurrencyService(); + + @Override + public Builder getCommandSpecBuilder() { + return CommandSpec.builder() + .executor(this) + .arguments(GenericArguments.optional(GenericArguments.remainingJoinedStrings(Text.of("currency")))); + } + + @Override + public void run(CommandSource src, CommandContext args) { + if (args.getOne("currency").isPresent()) { + String currencyName = args.getOne("currency").get(); + boolean found = false; + for (Currency c : currencyService.getCurrencies()) { + if (c.getDisplayName().toPlain().equalsIgnoreCase(currencyName)) { + currencyService.setCurrentCurrency(c); + found = true; + src.sendMessage(messageStorage.getMessage("command.currency.changed", "currency", c.getDisplayName())); + } + } + if (!found) { + src.sendMessage(messageStorage.getMessage("command.currency.invalid")); + } + } else { + src.sendMessage(messageStorage.getMessage("command.currency.current", "currency", currencyService.getCurrentCurrency().getDisplayName())); + src.sendMessage(messageStorage.getMessage("command.currency.selectnew")); + currencyService.getCurrencies().forEach(currency -> { + src.sendMessage(Text.of(currency.getDisplayName()).toBuilder().onClick(TextActions.executeCallback(c -> { + src.sendMessage(messageStorage.getMessage("command.currency.confirm", "currency", currency.getDisplayName()).toBuilder() + .onClick(TextActions.executeCallback(c2 -> { + currencyService.setCurrentCurrency(currency); + src.sendMessage(messageStorage.getMessage("command.currency.changed", "currency", currency.getDisplayName())); + })).build()); + })).build()); + }); + } + } +} diff --git a/src/main/java/io/github/flibio/economylite/commands/virtual/VirtualBalanceCommand.java b/src/main/java/io/github/flibio/economylite/commands/virtual/VirtualBalanceCommand.java new file mode 100644 index 0000000..b303fbd --- /dev/null +++ b/src/main/java/io/github/flibio/economylite/commands/virtual/VirtualBalanceCommand.java @@ -0,0 +1,88 @@ +/* + * This file is part of EconomyLite, licensed under the MIT License (MIT). + * + * Copyright (c) 2015 - 2016 Flibio + * Copyright (c) Contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package io.github.flibio.economylite.commands.virtual; + +import org.spongepowered.api.command.CommandSource; +import org.spongepowered.api.command.args.CommandContext; +import org.spongepowered.api.command.args.GenericArguments; +import org.spongepowered.api.command.spec.CommandSpec; +import org.spongepowered.api.command.spec.CommandSpec.Builder; +import org.spongepowered.api.service.economy.Currency; +import org.spongepowered.api.service.economy.account.Account; +import org.spongepowered.api.text.Text; + +import com.google.common.collect.ImmutableMap; + +import io.github.flibio.economylite.EconomyLite; +import io.github.flibio.economylite.api.CurrencyEconService; +import io.github.flibio.utils.commands.AsyncCommand; +import io.github.flibio.utils.commands.BaseCommandExecutor; +import io.github.flibio.utils.commands.Command; +import io.github.flibio.utils.message.MessageStorage; + +import java.math.BigDecimal; +import java.util.Optional; + +@AsyncCommand +@Command(aliases = {"vbalance", "vbal"}, permission = "economylite.admin.virtual.balance") +public class VirtualBalanceCommand extends BaseCommandExecutor { + + private MessageStorage messageStorage = EconomyLite.getMessageStorage(); + private CurrencyEconService currencyService = EconomyLite.getCurrencyService(); + + @Override + public Builder getCommandSpecBuilder() { + return CommandSpec.builder() + .executor(this) + .arguments(GenericArguments.remainingJoinedStrings(Text.of("account"))); + } + + @Override + public void run(CommandSource src, CommandContext args) { + Currency currency = currencyService.getCurrentCurrency(); + if (args.getOne("account").isPresent()) { + if (src.hasPermission("economylite.admin.virtualbalance")) { + String target = args.getOne("account").get(); + Optional aOpt = EconomyLite.getEconomyService().getOrCreateAccount(target); + if (aOpt.isPresent()) { + BigDecimal bal = aOpt.get().getBalance(currency); + Text label = currency.getPluralDisplayName(); + if (bal.equals(BigDecimal.ONE)) { + label = currency.getDisplayName(); + } + src.sendMessage(messageStorage.getMessage("command.balanceother", + ImmutableMap.of("player", aOpt.get().getDisplayName(), "balance", currency.format(bal), "label", label))); + } else { + src.sendMessage(messageStorage.getMessage("command.error")); + } + } else { + src.sendMessage(messageStorage.getMessage("command.noperm")); + } + } else { + src.sendMessage(messageStorage.getMessage("command.error")); + } + } + +} diff --git a/src/main/java/io/github/flibio/economylite/commands/virtual/VirtualSetCommand.java b/src/main/java/io/github/flibio/economylite/commands/virtual/VirtualSetCommand.java new file mode 100644 index 0000000..cb70915 --- /dev/null +++ b/src/main/java/io/github/flibio/economylite/commands/virtual/VirtualSetCommand.java @@ -0,0 +1,82 @@ +/* + * This file is part of EconomyLite, licensed under the MIT License (MIT). + * + * Copyright (c) 2015 - 2016 Flibio + * Copyright (c) Contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package io.github.flibio.economylite.commands.virtual; + +import org.spongepowered.api.command.CommandSource; +import org.spongepowered.api.command.args.CommandContext; +import org.spongepowered.api.command.args.GenericArguments; +import org.spongepowered.api.command.spec.CommandSpec; +import org.spongepowered.api.command.spec.CommandSpec.Builder; +import org.spongepowered.api.event.cause.Cause; +import org.spongepowered.api.event.cause.NamedCause; +import org.spongepowered.api.service.economy.account.Account; +import org.spongepowered.api.service.economy.transaction.ResultType; +import org.spongepowered.api.text.Text; + +import io.github.flibio.economylite.EconomyLite; +import io.github.flibio.utils.commands.AsyncCommand; +import io.github.flibio.utils.commands.BaseCommandExecutor; +import io.github.flibio.utils.commands.Command; +import io.github.flibio.utils.message.MessageStorage; + +import java.math.BigDecimal; +import java.util.Optional; + +@AsyncCommand +@Command(aliases = {"vset"}, permission = "economylite.admin.virtual.set") +public class VirtualSetCommand extends BaseCommandExecutor { + + private MessageStorage messageStorage = EconomyLite.getMessageStorage(); + + @Override + public Builder getCommandSpecBuilder() { + return CommandSpec.builder() + .executor(this) + .arguments(GenericArguments.string(Text.of("account")), GenericArguments.doubleNum(Text.of("balance"))); + } + + @Override + public void run(CommandSource src, CommandContext args) { + if (args.getOne("account").isPresent() && args.getOne("balance").isPresent()) { + String target = args.getOne("account").get(); + BigDecimal newBal = BigDecimal.valueOf(args.getOne("balance").get()); + Optional aOpt = EconomyLite.getEconomyService().getOrCreateAccount(target); + if (aOpt.isPresent()) { + Account targetAccount = aOpt.get(); + if (targetAccount.setBalance(EconomyLite.getCurrencyService().getCurrentCurrency(), newBal, + Cause.of(NamedCause.owner(EconomyLite.getInstance()))).getResult().equals(ResultType.SUCCESS)) { + src.sendMessage(messageStorage.getMessage("command.econ.setsuccess", "name", targetAccount.getDisplayName())); + } else { + src.sendMessage(messageStorage.getMessage("command.econ.setfail", "name", targetAccount.getDisplayName())); + } + } else { + src.sendMessage(messageStorage.getMessage("command.error")); + } + } else { + src.sendMessage(messageStorage.getMessage("command.error")); + } + } + +} diff --git a/src/main/java/io/github/flibio/economylite/impl/CurrencyService.java b/src/main/java/io/github/flibio/economylite/impl/CurrencyService.java new file mode 100644 index 0000000..89f2958 --- /dev/null +++ b/src/main/java/io/github/flibio/economylite/impl/CurrencyService.java @@ -0,0 +1,83 @@ +/* + * This file is part of EconomyLite, licensed under the MIT License (MIT). + * + * Copyright (c) 2015 - 2016 Flibio + * Copyright (c) Contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package io.github.flibio.economylite.impl; + +import org.spongepowered.api.service.economy.Currency; + +import io.github.flibio.economylite.EconomyLite; +import io.github.flibio.economylite.api.CurrencyEconService; + +import java.util.HashSet; +import java.util.Set; + +public class CurrencyService implements CurrencyEconService { + + private HashSet currencies = new HashSet(); + private Currency defaultCurrency; + private Currency currentCurrency; + + public CurrencyService(Currency defaultCurrency) { + this.defaultCurrency = defaultCurrency; + this.currentCurrency = defaultCurrency; + } + + @Override + public void addCurrency(Currency currency) { + currencies.add(currency); + } + + @Override + public Set getCurrencies() { + HashSet set = currencies; + set.add(defaultCurrency); + return set; + } + + @Override + public Currency getDefaultCurrency() { + return defaultCurrency; + } + + @Override + public void setCurrentCurrency(Currency currency) { + this.currentCurrency = currency; + EconomyLite.getConfigManager().setValue("currencies.conf", "current", String.class, currency.getId().replaceAll("economylite:", "")); + } + + @Override + public Currency getCurrentCurrency() { + return currentCurrency; + } + + @Override + public void deleteCurrency(Currency currency) { + if (currency != defaultCurrency) { + EconomyLite.getPlayerService().clearCurrency(currency); + EconomyLite.getVirtualService().clearCurrency(currency); + currencies.remove(currency); + EconomyLite.getConfigManager().deleteValue("currencies.conf", currency.getId().replaceAll("economylite:", "")); + } + } +} diff --git a/src/main/java/io/github/flibio/economylite/impl/PlayerDataService.java b/src/main/java/io/github/flibio/economylite/impl/PlayerDataService.java new file mode 100644 index 0000000..04d2bf3 --- /dev/null +++ b/src/main/java/io/github/flibio/economylite/impl/PlayerDataService.java @@ -0,0 +1,36 @@ +/* + * This file is part of EconomyLite, licensed under the MIT License (MIT). + * + * Copyright (c) 2015 - 2016 Flibio + * Copyright (c) Contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package io.github.flibio.economylite.impl; + +import io.github.flibio.economylite.EconomyLite; +import io.github.flibio.utils.sql.LocalSqlManager; + +public class PlayerDataService extends PlayerServiceCommon { + + public PlayerDataService() { + super(LocalSqlManager.createInstance(EconomyLite.getInstance(), "data").get()); + } + +} diff --git a/src/main/java/io/github/flibio/economylite/impl/PlayerServiceCommon.java b/src/main/java/io/github/flibio/economylite/impl/PlayerServiceCommon.java new file mode 100644 index 0000000..af996f9 --- /dev/null +++ b/src/main/java/io/github/flibio/economylite/impl/PlayerServiceCommon.java @@ -0,0 +1,98 @@ +/* + * This file is part of EconomyLite, licensed under the MIT License (MIT). + * + * Copyright (c) 2015 - 2016 Flibio + * Copyright (c) Contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package io.github.flibio.economylite.impl; + +import org.spongepowered.api.service.economy.Currency; +import org.spongepowered.api.service.economy.EconomyService; +import org.spongepowered.api.service.economy.account.UniqueAccount; + +import io.github.flibio.economylite.EconomyLite; +import io.github.flibio.economylite.api.PlayerEconService; +import io.github.flibio.utils.sql.SqlManager; + +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.UUID; + +public class PlayerServiceCommon implements PlayerEconService { + + private SqlManager manager; + + public PlayerServiceCommon(SqlManager manager) { + this.manager = manager; + if (isWorking()) + manager.executeUpdate("CREATE TABLE IF NOT EXISTS economyliteplayers(uuid VARCHAR(36), balance DECIMAL(11,2), currency VARCHAR(1024))"); + } + + public boolean isWorking() { + return manager.testConnection(); + } + + public BigDecimal getBalance(UUID uuid, Currency currency) { + Optional bOpt = + manager.queryType("balance", BigDecimal.class, "SELECT balance FROM economyliteplayers WHERE uuid = ? AND currency = ?", + uuid.toString(), currency.getId()); + return (bOpt.isPresent()) ? bOpt.get() : BigDecimal.ZERO; + } + + public boolean setBalance(UUID uuid, BigDecimal balance, Currency currency) { + if (accountExists(uuid, currency)) { + return manager.executeUpdate("UPDATE economyliteplayers SET balance = ? WHERE uuid = ? AND currency = ?", balance.toString(), + uuid.toString(), currency.getId()); + } else { + return manager.executeUpdate("INSERT INTO economyliteplayers (`uuid`, `balance`, `currency`) VALUES (?, ?, ?)", uuid.toString(), + balance.toString(), currency.getId()); + } + } + + public boolean accountExists(UUID uuid) { + return manager.queryExists("SELECT uuid FROM economyliteplayers WHERE uuid = ?", uuid.toString()); + } + + public boolean accountExists(UUID uuid, Currency currency) { + return manager.queryExists("SELECT uuid FROM economyliteplayers WHERE uuid = ? AND currency = ?", uuid.toString(), currency.getId()); + } + + public void clearCurrency(Currency currency) { + manager.executeUpdate("DELETE FROM economyliteplayers WHERE currency = ?", currency.getId()); + } + + public List getAllAccounts() { + ArrayList accounts = new ArrayList<>(); + List uuids = + manager.queryTypeList("uuid", String.class, "SELECT uuid FROM economyliteplayers WHERE currency = ?", EconomyLite.getEconomyService() + .getDefaultCurrency().getId()); + EconomyService ecoService = EconomyLite.getEconomyService(); + for (String uuid : uuids) { + Optional uOpt = ecoService.getOrCreateAccount(UUID.fromString(uuid)); + if (uOpt.isPresent()) { + accounts.add(uOpt.get()); + } + } + return accounts; + } +} diff --git a/src/main/java/io/github/flibio/economylite/impl/VirtualDataService.java b/src/main/java/io/github/flibio/economylite/impl/VirtualDataService.java new file mode 100644 index 0000000..365ac12 --- /dev/null +++ b/src/main/java/io/github/flibio/economylite/impl/VirtualDataService.java @@ -0,0 +1,36 @@ +/* + * This file is part of EconomyLite, licensed under the MIT License (MIT). + * + * Copyright (c) 2015 - 2016 Flibio + * Copyright (c) Contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package io.github.flibio.economylite.impl; + +import io.github.flibio.economylite.EconomyLite; +import io.github.flibio.utils.sql.LocalSqlManager; + +public class VirtualDataService extends VirtualServiceCommon { + + public VirtualDataService() { + super(LocalSqlManager.createInstance(EconomyLite.getInstance(), "data").get()); + } + +} diff --git a/src/main/java/io/github/flibio/economylite/impl/VirtualServiceCommon.java b/src/main/java/io/github/flibio/economylite/impl/VirtualServiceCommon.java new file mode 100644 index 0000000..9492eed --- /dev/null +++ b/src/main/java/io/github/flibio/economylite/impl/VirtualServiceCommon.java @@ -0,0 +1,99 @@ +/* + * This file is part of EconomyLite, licensed under the MIT License (MIT). + * + * Copyright (c) 2015 - 2016 Flibio + * Copyright (c) Contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package io.github.flibio.economylite.impl; + +import org.spongepowered.api.service.economy.Currency; +import org.spongepowered.api.service.economy.EconomyService; +import org.spongepowered.api.service.economy.account.Account; +import org.spongepowered.api.service.economy.account.VirtualAccount; + +import io.github.flibio.economylite.EconomyLite; +import io.github.flibio.economylite.api.VirtualEconService; +import io.github.flibio.utils.sql.SqlManager; + +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +public class VirtualServiceCommon implements VirtualEconService { + + private SqlManager manager; + + public VirtualServiceCommon(SqlManager manager) { + this.manager = manager; + if (isWorking()) + manager.executeUpdate("CREATE TABLE IF NOT EXISTS economylitevirts(id VARCHAR(36), balance DECIMAL(11,2), currency VARCHAR(1024))"); + } + + public boolean isWorking() { + return manager.testConnection(); + } + + public BigDecimal getBalance(String id, Currency currency) { + Optional bOpt = + manager.queryType("balance", BigDecimal.class, "SELECT balance FROM economylitevirts WHERE id = ? AND currency = ?", id, + currency.getId()); + return (bOpt.isPresent()) ? bOpt.get() : BigDecimal.ZERO; + } + + public boolean setBalance(String id, BigDecimal balance, Currency currency) { + if (accountExists(id, currency)) { + return manager.executeUpdate("UPDATE economylitevirts SET balance = ? WHERE id = ? AND currency = ?", balance.toString(), id, + currency.getId()); + } else { + return manager.executeUpdate("INSERT INTO economylitevirts (`id`, `balance`, `currency`) VALUES (?, ?, ?)", id, balance.toString(), + currency.getId()); + } + } + + public boolean accountExists(String id) { + return manager.queryExists("SELECT id FROM economylitevirts WHERE id = ?", id); + } + + public boolean accountExists(String id, Currency currency) { + return manager.queryExists("SELECT id FROM economylitevirts WHERE id = ? AND currency = ?", id, currency.getId()); + } + + public void clearCurrency(Currency currency) { + manager.executeUpdate("DELETE FROM economylitevirts WHERE currency = ?", currency.getId()); + } + + public List getAllAccounts() { + ArrayList accounts = new ArrayList<>(); + List ids = + manager.queryTypeList("id", String.class, "SELECT id FROM economylitevirts WHERE currency = ?", EconomyLite.getEconomyService() + .getDefaultCurrency().getId()); + EconomyService ecoService = EconomyLite.getEconomyService(); + for (String id : ids) { + Optional vOpt = ecoService.getOrCreateAccount(id); + if (vOpt.isPresent() && (vOpt.get() instanceof VirtualAccount)) { + accounts.add((VirtualAccount) vOpt.get()); + } + } + return accounts; + } + +} diff --git a/src/main/java/io/github/flibio/economylite/impl/economy/LiteCurrency.java b/src/main/java/io/github/flibio/economylite/impl/economy/LiteCurrency.java new file mode 100644 index 0000000..e171d80 --- /dev/null +++ b/src/main/java/io/github/flibio/economylite/impl/economy/LiteCurrency.java @@ -0,0 +1,96 @@ +/* + * This file is part of EconomyLite, licensed under the MIT License (MIT). + * + * Copyright (c) 2015 - 2016 Flibio + * Copyright (c) Contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package io.github.flibio.economylite.impl.economy; + +import org.spongepowered.api.service.economy.Currency; +import org.spongepowered.api.text.Text; + +import java.math.BigDecimal; +import java.math.RoundingMode; + +public class LiteCurrency implements Currency { + + private String singular; + private String plural; + private String symbol; + private boolean defaultCur; + private int digits; + + public LiteCurrency(String singular, String plural, String symbol, boolean defaultCur, int digits) { + this.singular = singular; + this.plural = plural; + this.symbol = symbol; + this.defaultCur = defaultCur; + this.digits = digits; + } + + @Override + public int getDefaultFractionDigits() { + return digits; + } + + @Override + public Text getDisplayName() { + return Text.of(singular); + } + + @Override + public Text getPluralDisplayName() { + return Text.of(plural); + } + + @Override + public Text getSymbol() { + return Text.of(symbol); + } + + @Override + public boolean isDefault() { + return defaultCur; + } + + @Override + public Text format(BigDecimal amount, int digits) { + return Text.of(amount.setScale(digits, RoundingMode.HALF_UP)); + } + + @Override + public String getId() { + return "economylite:" + singular.toLowerCase().replaceAll(" ", "_"); + } + + @Override + public String getName() { + return singular; + } + + @Override + public boolean equals(Object other) { + if (!(other instanceof Currency)) + return false; + return this.getId().equals(((Currency) other).getId()); + } + +} diff --git a/src/main/java/io/github/flibio/economylite/impl/economy/LiteEconomyService.java b/src/main/java/io/github/flibio/economylite/impl/economy/LiteEconomyService.java new file mode 100644 index 0000000..2ce2850 --- /dev/null +++ b/src/main/java/io/github/flibio/economylite/impl/economy/LiteEconomyService.java @@ -0,0 +1,108 @@ +/* + * This file is part of EconomyLite, licensed under the MIT License (MIT). + * + * Copyright (c) 2015 - 2016 Flibio + * Copyright (c) Contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package io.github.flibio.economylite.impl.economy; + +import org.spongepowered.api.service.context.ContextCalculator; +import org.spongepowered.api.service.economy.Currency; +import org.spongepowered.api.service.economy.EconomyService; +import org.spongepowered.api.service.economy.account.Account; +import org.spongepowered.api.service.economy.account.UniqueAccount; +import org.spongepowered.api.service.economy.account.VirtualAccount; + +import io.github.flibio.economylite.EconomyLite; +import io.github.flibio.economylite.api.CurrencyEconService; +import io.github.flibio.economylite.api.PlayerEconService; +import io.github.flibio.economylite.api.VirtualEconService; +import io.github.flibio.economylite.impl.economy.account.LiteUniqueAccount; +import io.github.flibio.economylite.impl.economy.account.LiteVirtualAccount; + +import java.util.Optional; +import java.util.Set; +import java.util.UUID; + +public class LiteEconomyService implements EconomyService { + + private PlayerEconService playerService = EconomyLite.getPlayerService(); + private VirtualEconService virtualService = EconomyLite.getVirtualService(); + private CurrencyEconService currencyService = EconomyLite.getCurrencyService(); + + @Override + public void registerContextCalculator(ContextCalculator arg0) { + return; + } + + @Override + public Optional getOrCreateAccount(UUID uuid) { + if (playerService.accountExists(uuid, getDefaultCurrency())) { + // Return the account + return Optional.of(new LiteUniqueAccount(uuid)); + } else { + // Make a new account + UniqueAccount account = new LiteUniqueAccount(uuid); + if (playerService.setBalance(uuid, account.getDefaultBalance(getDefaultCurrency()), getDefaultCurrency())) { + return Optional.of(account); + } else { + return Optional.empty(); + } + } + } + + @Override + public Optional getOrCreateAccount(String id) { + if (virtualService.accountExists(id, getDefaultCurrency())) { + // Return the account + return Optional.of(new LiteVirtualAccount(id)); + } else { + // Make a new account + VirtualAccount account = new LiteVirtualAccount(id); + if (virtualService.setBalance(id, account.getDefaultBalance(getDefaultCurrency()), getDefaultCurrency())) { + return Optional.of(account); + } else { + return Optional.empty(); + } + } + } + + @Override + public Set getCurrencies() { + return currencyService.getCurrencies(); + } + + @Override + public Currency getDefaultCurrency() { + return currencyService.getCurrentCurrency(); + } + + @Override + public boolean hasAccount(UUID uuid) { + return playerService.accountExists(uuid); + } + + @Override + public boolean hasAccount(String identifier) { + return virtualService.accountExists(identifier); + } + +} diff --git a/src/main/java/io/github/flibio/economylite/impl/economy/account/LiteUniqueAccount.java b/src/main/java/io/github/flibio/economylite/impl/economy/account/LiteUniqueAccount.java new file mode 100644 index 0000000..81cff86 --- /dev/null +++ b/src/main/java/io/github/flibio/economylite/impl/economy/account/LiteUniqueAccount.java @@ -0,0 +1,222 @@ +/* + * This file is part of EconomyLite, licensed under the MIT License (MIT). + * + * Copyright (c) 2015 - 2016 Flibio + * Copyright (c) Contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package io.github.flibio.economylite.impl.economy.account; + +import org.spongepowered.api.Sponge; +import org.spongepowered.api.event.cause.Cause; +import org.spongepowered.api.service.context.Context; +import org.spongepowered.api.service.economy.Currency; +import org.spongepowered.api.service.economy.account.Account; +import org.spongepowered.api.service.economy.account.UniqueAccount; +import org.spongepowered.api.service.economy.transaction.ResultType; +import org.spongepowered.api.service.economy.transaction.TransactionResult; +import org.spongepowered.api.service.economy.transaction.TransactionType; +import org.spongepowered.api.service.economy.transaction.TransactionTypes; +import org.spongepowered.api.service.economy.transaction.TransferResult; +import org.spongepowered.api.text.Text; + +import io.github.flibio.economylite.EconomyLite; +import io.github.flibio.economylite.api.CurrencyEconService; +import io.github.flibio.economylite.api.PlayerEconService; +import io.github.flibio.economylite.impl.economy.event.LiteEconomyTransactionEvent; +import io.github.flibio.economylite.impl.economy.result.LiteTransactionResult; +import io.github.flibio.economylite.impl.economy.result.LiteTransferResult; +import io.github.flibio.utils.player.NameUtils; + +import java.math.BigDecimal; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; + +public class LiteUniqueAccount implements UniqueAccount { + + private PlayerEconService playerService = EconomyLite.getPlayerService(); + private CurrencyEconService currencyService = EconomyLite.getCurrencyService(); + + private UUID uuid; + private String name; + + public LiteUniqueAccount(UUID uuid) { + this.uuid = uuid; + Optional nOpt = NameUtils.getName(uuid); + if (nOpt.isPresent()) { + this.name = nOpt.get(); + } else { + this.name = "error"; + } + } + + @Override + public Text getDisplayName() { + return Text.of(name); + } + + @Override + public BigDecimal getDefaultBalance(Currency currency) { + Optional bOpt = EconomyLite.getConfigManager().getValue("config.conf", "default-balance", Double.class); + if (bOpt.isPresent()) { + return BigDecimal.valueOf(bOpt.get()); + } else { + return BigDecimal.ZERO; + } + } + + @Override + public boolean hasBalance(Currency currency, Set contexts) { + return playerService.accountExists(uuid, currency); + } + + @Override + public BigDecimal getBalance(Currency currency, Set contexts) { + return playerService.getBalance(uuid, currency); + } + + @Override + public Map getBalances(Set contexts) { + HashMap balances = new HashMap(); + for (Currency currency : currencyService.getCurrencies()) { + if (playerService.accountExists(uuid, currency)) { + balances.put(currency, playerService.getBalance(uuid, currency)); + } + } + return balances; + } + + @Override + public TransactionResult setBalance(Currency currency, BigDecimal amount, Cause cause, Set contexts) { + // Check if the new balance is in bounds + if (amount.compareTo(BigDecimal.ZERO) == -1 || amount.compareTo(BigDecimal.valueOf(1000000)) == 1) { + return resultAndEvent(this, amount, currency, ResultType.ACCOUNT_NO_SPACE, TransactionTypes.DEPOSIT); + } + if (playerService.setBalance(uuid, amount, currency)) { + return resultAndEvent(this, amount, currency, ResultType.SUCCESS, TransactionTypes.DEPOSIT); + } else { + return resultAndEvent(this, amount, currency, ResultType.FAILED, TransactionTypes.DEPOSIT); + } + } + + @Override + public Map resetBalances(Cause cause, Set contexts) { + HashMap results = new HashMap<>(); + for (Currency currency : currencyService.getCurrencies()) { + if (playerService.accountExists(uuid, currency)) { + if (playerService.setBalance(uuid, getDefaultBalance(currency), currency)) { + results.put(currency, resultAndEvent(this, getBalance(currency), currency, ResultType.SUCCESS, TransactionTypes.WITHDRAW)); + } else { + results.put(currency, resultAndEvent(this, getBalance(currency), currency, ResultType.FAILED, TransactionTypes.WITHDRAW)); + } + } + } + return results; + } + + @Override + public TransactionResult resetBalance(Currency currency, Cause cause, Set contexts) { + if (playerService.setBalance(uuid, getDefaultBalance(currency), currency)) { + return resultAndEvent(this, BigDecimal.ZERO, currency, ResultType.SUCCESS, TransactionTypes.WITHDRAW); + } else { + return resultAndEvent(this, BigDecimal.ZERO, currency, ResultType.FAILED, TransactionTypes.WITHDRAW); + } + } + + @Override + public TransactionResult deposit(Currency currency, BigDecimal amount, Cause cause, Set contexts) { + BigDecimal newBal = getBalance(currency).add(amount); + // Check if the new balance is in bounds + if (newBal.compareTo(BigDecimal.ZERO) == -1 || newBal.compareTo(BigDecimal.valueOf(1000000)) == 1) { + return resultAndEvent(this, amount, currency, ResultType.ACCOUNT_NO_SPACE, TransactionTypes.DEPOSIT); + } + if (playerService.deposit(uuid, amount, currency)) { + return resultAndEvent(this, amount, currency, ResultType.SUCCESS, TransactionTypes.DEPOSIT); + } else { + return resultAndEvent(this, amount, currency, ResultType.FAILED, TransactionTypes.DEPOSIT); + } + } + + @Override + public TransactionResult withdraw(Currency currency, BigDecimal amount, Cause cause, Set contexts) { + BigDecimal newBal = getBalance(currency).subtract(amount); + // Check if the new balance is in bounds + if (newBal.compareTo(BigDecimal.ZERO) == -1 || newBal.compareTo(BigDecimal.valueOf(1000000)) == 1) { + return resultAndEvent(this, amount, currency, ResultType.ACCOUNT_NO_SPACE, TransactionTypes.WITHDRAW); + } + if (playerService.withdraw(uuid, amount, currency)) { + return resultAndEvent(this, amount, currency, ResultType.SUCCESS, TransactionTypes.WITHDRAW); + } else { + return resultAndEvent(this, amount, currency, ResultType.FAILED, TransactionTypes.WITHDRAW); + } + } + + @Override + public TransferResult transfer(Account to, Currency currency, BigDecimal amount, Cause cause, Set contexts) { + BigDecimal newBal = to.getBalance(currency).add(amount); + // Check if the new balance is in bounds + if (newBal.compareTo(BigDecimal.ZERO) == -1 || newBal.compareTo(BigDecimal.valueOf(1000000)) == 1) { + return resultAndEvent(this, amount, currency, ResultType.ACCOUNT_NO_SPACE, to); + } + // Check if the account has enough funds + if (amount.compareTo(getBalance(currency)) == 1) { + return resultAndEvent(this, amount, currency, ResultType.ACCOUNT_NO_FUNDS, to); + } + if (withdraw(currency, amount, cause).getResult().equals(ResultType.SUCCESS) + && to.deposit(currency, amount, cause).getResult().equals(ResultType.SUCCESS)) { + return resultAndEvent(this, amount, currency, ResultType.SUCCESS, to); + } else { + return resultAndEvent(this, amount, currency, ResultType.FAILED, to); + } + } + + @Override + public String getIdentifier() { + return uuid.toString(); + } + + @Override + public Set getActiveContexts() { + return new HashSet(); + } + + private TransactionResult resultAndEvent(Account account, BigDecimal amount, Currency currency, ResultType resultType, + TransactionType transactionType) { + TransactionResult result = new LiteTransactionResult(account, amount, currency, resultType, transactionType); + Sponge.getEventManager().post(new LiteEconomyTransactionEvent(result)); + return result; + } + + private TransferResult resultAndEvent(Account account, BigDecimal amount, Currency currency, ResultType resultType, Account toWho) { + TransferResult result = new LiteTransferResult(account, amount, currency, resultType, toWho); + Sponge.getEventManager().post(new LiteEconomyTransactionEvent(result)); + return result; + } + + @Override + public UUID getUniqueId() { + return uuid; + } + +} diff --git a/src/main/java/io/github/flibio/economylite/impl/economy/account/LiteVirtualAccount.java b/src/main/java/io/github/flibio/economylite/impl/economy/account/LiteVirtualAccount.java new file mode 100644 index 0000000..334b0ee --- /dev/null +++ b/src/main/java/io/github/flibio/economylite/impl/economy/account/LiteVirtualAccount.java @@ -0,0 +1,208 @@ +/* + * This file is part of EconomyLite, licensed under the MIT License (MIT). + * + * Copyright (c) 2015 - 2016 Flibio + * Copyright (c) Contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package io.github.flibio.economylite.impl.economy.account; + +import org.spongepowered.api.Sponge; +import org.spongepowered.api.event.cause.Cause; +import org.spongepowered.api.service.context.Context; +import org.spongepowered.api.service.economy.Currency; +import org.spongepowered.api.service.economy.account.Account; +import org.spongepowered.api.service.economy.account.VirtualAccount; +import org.spongepowered.api.service.economy.transaction.ResultType; +import org.spongepowered.api.service.economy.transaction.TransactionResult; +import org.spongepowered.api.service.economy.transaction.TransactionType; +import org.spongepowered.api.service.economy.transaction.TransactionTypes; +import org.spongepowered.api.service.economy.transaction.TransferResult; +import org.spongepowered.api.text.Text; + +import io.github.flibio.economylite.EconomyLite; +import io.github.flibio.economylite.api.CurrencyEconService; +import io.github.flibio.economylite.api.VirtualEconService; +import io.github.flibio.economylite.impl.economy.event.LiteEconomyTransactionEvent; +import io.github.flibio.economylite.impl.economy.result.LiteTransactionResult; +import io.github.flibio.economylite.impl.economy.result.LiteTransferResult; + +import java.math.BigDecimal; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Optional; +import java.util.Set; + +public class LiteVirtualAccount implements VirtualAccount { + + private VirtualEconService virtualService = EconomyLite.getVirtualService(); + private CurrencyEconService currencyService = EconomyLite.getCurrencyService(); + + private String name; + + public LiteVirtualAccount(String id) { + this.name = id; + } + + @Override + public Text getDisplayName() { + return Text.of(name); + } + + @Override + public BigDecimal getDefaultBalance(Currency currency) { + Optional bOpt = EconomyLite.getConfigManager().getValue("config.conf", "virt-default-balance", Double.class); + if (bOpt.isPresent()) { + return BigDecimal.valueOf(bOpt.get()); + } else { + return BigDecimal.ZERO; + } + } + + @Override + public boolean hasBalance(Currency currency, Set contexts) { + return virtualService.accountExists(name, currency); + } + + @Override + public BigDecimal getBalance(Currency currency, Set contexts) { + return virtualService.getBalance(name, currency); + } + + @Override + public Map getBalances(Set contexts) { + HashMap balances = new HashMap(); + for (Currency currency : currencyService.getCurrencies()) { + if (virtualService.accountExists(name, currency)) { + balances.put(currency, virtualService.getBalance(name, currency)); + } + } + return balances; + } + + @Override + public TransactionResult setBalance(Currency currency, BigDecimal amount, Cause cause, Set contexts) { + // Check if the new balance is in bounds + if (amount.compareTo(BigDecimal.ZERO) == -1 || amount.compareTo(BigDecimal.valueOf(1000000)) == 1) { + return resultAndEvent(this, amount, currency, ResultType.ACCOUNT_NO_SPACE, TransactionTypes.DEPOSIT); + } + if (virtualService.setBalance(name, amount, currency)) { + return resultAndEvent(this, amount, currency, ResultType.SUCCESS, TransactionTypes.DEPOSIT); + } else { + return resultAndEvent(this, amount, currency, ResultType.FAILED, TransactionTypes.DEPOSIT); + } + } + + @Override + public Map resetBalances(Cause cause, Set contexts) { + HashMap results = new HashMap<>(); + for (Currency currency : currencyService.getCurrencies()) { + if (virtualService.accountExists(name, currency)) { + if (virtualService.setBalance(name, getDefaultBalance(currency), currency)) { + results.put(currency, resultAndEvent(this, getBalance(currency), currency, ResultType.SUCCESS, TransactionTypes.WITHDRAW)); + } else { + results.put(currency, resultAndEvent(this, getBalance(currency), currency, ResultType.FAILED, TransactionTypes.WITHDRAW)); + } + } + } + return results; + } + + @Override + public TransactionResult resetBalance(Currency currency, Cause cause, Set contexts) { + if (virtualService.setBalance(name, getDefaultBalance(currency), currency)) { + return resultAndEvent(this, BigDecimal.ZERO, currency, ResultType.SUCCESS, TransactionTypes.WITHDRAW); + } else { + return resultAndEvent(this, BigDecimal.ZERO, currency, ResultType.FAILED, TransactionTypes.WITHDRAW); + } + } + + @Override + public TransactionResult deposit(Currency currency, BigDecimal amount, Cause cause, Set contexts) { + BigDecimal newBal = getBalance(currency).add(amount); + // Check if the new balance is in bounds + if (newBal.compareTo(BigDecimal.ZERO) == -1 || newBal.compareTo(BigDecimal.valueOf(1000000)) == 1) { + return resultAndEvent(this, amount, currency, ResultType.ACCOUNT_NO_SPACE, TransactionTypes.DEPOSIT); + } + if (virtualService.deposit(name, amount, currency)) { + return resultAndEvent(this, amount, currency, ResultType.SUCCESS, TransactionTypes.DEPOSIT); + } else { + return resultAndEvent(this, amount, currency, ResultType.FAILED, TransactionTypes.DEPOSIT); + } + } + + @Override + public TransactionResult withdraw(Currency currency, BigDecimal amount, Cause cause, Set contexts) { + BigDecimal newBal = getBalance(currency).subtract(amount); + // Check if the new balance is in bounds + if (newBal.compareTo(BigDecimal.ZERO) == -1 || newBal.compareTo(BigDecimal.valueOf(1000000)) == 1) { + return resultAndEvent(this, amount, currency, ResultType.ACCOUNT_NO_SPACE, TransactionTypes.WITHDRAW); + } + if (virtualService.withdraw(name, amount, currency)) { + return resultAndEvent(this, amount, currency, ResultType.SUCCESS, TransactionTypes.WITHDRAW); + } else { + return resultAndEvent(this, amount, currency, ResultType.FAILED, TransactionTypes.WITHDRAW); + } + } + + @Override + public TransferResult transfer(Account to, Currency currency, BigDecimal amount, Cause cause, Set contexts) { + BigDecimal newBal = to.getBalance(currency).add(amount); + // Check if the new balance is in bounds + if (newBal.compareTo(BigDecimal.ZERO) == -1 || newBal.compareTo(BigDecimal.valueOf(1000000)) == 1) { + return resultAndEvent(this, amount, currency, ResultType.ACCOUNT_NO_SPACE, to); + } + // Check if the account has enough funds + if (amount.compareTo(getBalance(currency)) == 1) { + return resultAndEvent(this, amount, currency, ResultType.ACCOUNT_NO_FUNDS, to); + } + if (withdraw(currency, amount, cause).getResult().equals(ResultType.SUCCESS) + && to.deposit(currency, amount, cause).getResult().equals(ResultType.SUCCESS)) { + return resultAndEvent(this, amount, currency, ResultType.SUCCESS, to); + } else { + return resultAndEvent(this, amount, currency, ResultType.FAILED, to); + } + } + + @Override + public String getIdentifier() { + return name; + } + + @Override + public Set getActiveContexts() { + return new HashSet(); + } + + private TransactionResult resultAndEvent(Account account, BigDecimal amount, Currency currency, ResultType resultType, + TransactionType transactionType) { + TransactionResult result = new LiteTransactionResult(account, amount, currency, resultType, transactionType); + Sponge.getEventManager().post(new LiteEconomyTransactionEvent(result)); + return result; + } + + private TransferResult resultAndEvent(Account account, BigDecimal amount, Currency currency, ResultType resultType, Account toWho) { + TransferResult result = new LiteTransferResult(account, amount, currency, resultType, toWho); + Sponge.getEventManager().post(new LiteEconomyTransactionEvent(result)); + return result; + } + +} diff --git a/src/main/java/io/github/flibio/economylite/impl/economy/event/LiteEconomyTransactionEvent.java b/src/main/java/io/github/flibio/economylite/impl/economy/event/LiteEconomyTransactionEvent.java new file mode 100644 index 0000000..0136911 --- /dev/null +++ b/src/main/java/io/github/flibio/economylite/impl/economy/event/LiteEconomyTransactionEvent.java @@ -0,0 +1,51 @@ +/* + * This file is part of EconomyLite, licensed under the MIT License (MIT). + * + * Copyright (c) 2015 - 2016 Flibio + * Copyright (c) Contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package io.github.flibio.economylite.impl.economy.event; + +import org.spongepowered.api.event.cause.Cause; +import org.spongepowered.api.event.economy.EconomyTransactionEvent; +import org.spongepowered.api.service.economy.transaction.TransactionResult; + +import io.github.flibio.economylite.EconomyLite; + +public class LiteEconomyTransactionEvent implements EconomyTransactionEvent { + + private TransactionResult result; + + public LiteEconomyTransactionEvent(TransactionResult result) { + this.result = result; + } + + @Override + public Cause getCause() { + return Cause.builder().owner(EconomyLite.getInstance()).build(); + } + + @Override + public TransactionResult getTransactionResult() { + return this.result; + } + +} diff --git a/src/main/java/io/github/flibio/economylite/impl/economy/registry/CurrencyRegistryModule.java b/src/main/java/io/github/flibio/economylite/impl/economy/registry/CurrencyRegistryModule.java new file mode 100644 index 0000000..35f16d7 --- /dev/null +++ b/src/main/java/io/github/flibio/economylite/impl/economy/registry/CurrencyRegistryModule.java @@ -0,0 +1,51 @@ +/* + * This file is part of EconomyLite, licensed under the MIT License (MIT). + * + * Copyright (c) 2015 - 2016 Flibio + * Copyright (c) Contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package io.github.flibio.economylite.impl.economy.registry; + +import org.spongepowered.api.registry.CatalogRegistryModule; +import org.spongepowered.api.service.economy.Currency; + +import io.github.flibio.economylite.EconomyLite; + +import java.util.Collection; +import java.util.Optional; + +public class CurrencyRegistryModule implements CatalogRegistryModule { + + @Override + public Optional getById(String id) { + for (Currency cur : EconomyLite.getCurrencyService().getCurrencies()) { + if (cur.getId().equals(id)) { + return Optional.of(cur); + } + } + return Optional.empty(); + } + + @Override + public Collection getAll() { + return EconomyLite.getCurrencyService().getCurrencies(); + } +} diff --git a/src/me/Flibio/EconomyLite/API/LiteTransactionResult.java b/src/main/java/io/github/flibio/economylite/impl/economy/result/LiteTransactionResult.java similarity index 50% rename from src/me/Flibio/EconomyLite/API/LiteTransactionResult.java rename to src/main/java/io/github/flibio/economylite/impl/economy/result/LiteTransactionResult.java index 28bea39..b30a5cb 100644 --- a/src/me/Flibio/EconomyLite/API/LiteTransactionResult.java +++ b/src/main/java/io/github/flibio/economylite/impl/economy/result/LiteTransactionResult.java @@ -1,6 +1,28 @@ -package me.Flibio.EconomyLite.API; - -import me.Flibio.EconomyLite.EconomyLite; +/* + * This file is part of EconomyLite, licensed under the MIT License (MIT). + * + * Copyright (c) 2015 - 2016 Flibio + * Copyright (c) Contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package io.github.flibio.economylite.impl.economy.result; import org.spongepowered.api.service.context.Context; import org.spongepowered.api.service.economy.Currency; @@ -22,11 +44,11 @@ public class LiteTransactionResult implements TransactionResult { private ResultType result; private TransactionType transactionType; - public LiteTransactionResult(Account account, BigDecimal amount, ResultType result, TransactionType transactionType) { + public LiteTransactionResult(Account account, BigDecimal amount, Currency currency, ResultType result, TransactionType transactionType) { this.account = account; this.amount = amount; this.contexts = new HashSet(); - this.currency = EconomyLite.getCurrency(); + this.currency = currency; this.result = result; this.transactionType = transactionType; } diff --git a/src/main/java/io/github/flibio/economylite/impl/economy/result/LiteTransferResult.java b/src/main/java/io/github/flibio/economylite/impl/economy/result/LiteTransferResult.java new file mode 100644 index 0000000..5c68637 --- /dev/null +++ b/src/main/java/io/github/flibio/economylite/impl/economy/result/LiteTransferResult.java @@ -0,0 +1,48 @@ +/* + * This file is part of EconomyLite, licensed under the MIT License (MIT). + * + * Copyright (c) 2015 - 2016 Flibio + * Copyright (c) Contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package io.github.flibio.economylite.impl.economy.result; + +import org.spongepowered.api.service.economy.Currency; +import org.spongepowered.api.service.economy.account.Account; +import org.spongepowered.api.service.economy.transaction.ResultType; +import org.spongepowered.api.service.economy.transaction.TransactionTypes; +import org.spongepowered.api.service.economy.transaction.TransferResult; + +import java.math.BigDecimal; + +public class LiteTransferResult extends LiteTransactionResult implements TransferResult { + + private Account toWho; + + public LiteTransferResult(Account account, BigDecimal amount, Currency currency, ResultType result, Account toWho) { + super(account, amount, currency, result, TransactionTypes.TRANSFER); + this.toWho = toWho; + } + + @Override + public Account getAccountTo() { + return this.toWho; + } +} diff --git a/src/main/java/io/github/flibio/economylite/modules/Module.java b/src/main/java/io/github/flibio/economylite/modules/Module.java new file mode 100644 index 0000000..d21a52a --- /dev/null +++ b/src/main/java/io/github/flibio/economylite/modules/Module.java @@ -0,0 +1,59 @@ +/* + * This file is part of EconomyLite, licensed under the MIT License (MIT). + * + * Copyright (c) 2015 - 2016 Flibio + * Copyright (c) Contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package io.github.flibio.economylite.modules; + +import org.slf4j.Logger; + +public interface Module { + + /** + * Initializes the module. + * + * @param logger An instance of the plugin's logger. + * @param plugin An instance of the main plugin class. + * @return If the initialization was successful or not. + */ + public boolean initialize(Logger logger, Object plugin); + + /** + * Sets all default config variables for the module. + */ + public void initializeConfig(); + + /** + * Gets the name of the module. + * + * @return The name of the module. + */ + public String getName(); + + /** + * Checks if a module is enabled. + * + * @return If the module is enabled or not. + */ + public boolean isEnabled(); + +} diff --git a/src/main/java/io/github/flibio/economylite/modules/business/BusinessModule.java b/src/main/java/io/github/flibio/economylite/modules/business/BusinessModule.java new file mode 100644 index 0000000..fe17a39 --- /dev/null +++ b/src/main/java/io/github/flibio/economylite/modules/business/BusinessModule.java @@ -0,0 +1,55 @@ +/* + * This file is part of EconomyLite, licensed under the MIT License (MIT). + * + * Copyright (c) 2015 - 2016 Flibio + * Copyright (c) Contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package io.github.flibio.economylite.modules.business; + +import org.slf4j.Logger; + +import io.github.flibio.economylite.modules.Module; + +public class BusinessModule implements Module { + + @Override + public boolean initialize(Logger logger, Object plugin) { + // TODO - Implementation has not yet been decided + return false; + } + + @Override + public void initializeConfig() { + // TODO - Implementation has not yet been decided + } + + @Override + public String getName() { + return "Business"; + } + + @Override + public boolean isEnabled() { + // TODO - Implementation has not yet been decided + return false; + } + +} diff --git a/src/main/java/io/github/flibio/economylite/modules/sql/PlayerSqlService.java b/src/main/java/io/github/flibio/economylite/modules/sql/PlayerSqlService.java new file mode 100644 index 0000000..bb1adf5 --- /dev/null +++ b/src/main/java/io/github/flibio/economylite/modules/sql/PlayerSqlService.java @@ -0,0 +1,37 @@ +/* + * This file is part of EconomyLite, licensed under the MIT License (MIT). + * + * Copyright (c) 2015 - 2016 Flibio + * Copyright (c) Contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package io.github.flibio.economylite.modules.sql; + +import io.github.flibio.economylite.EconomyLite; +import io.github.flibio.economylite.impl.PlayerServiceCommon; +import io.github.flibio.utils.sql.RemoteSqlManager; + +public class PlayerSqlService extends PlayerServiceCommon { + + public PlayerSqlService(String hostname, String port, String database, String username, String password) { + super(RemoteSqlManager.createInstance(EconomyLite.getInstance(), hostname, port, database, username, password).get()); + } + +} diff --git a/src/main/java/io/github/flibio/economylite/modules/sql/SqlModule.java b/src/main/java/io/github/flibio/economylite/modules/sql/SqlModule.java new file mode 100644 index 0000000..e970f92 --- /dev/null +++ b/src/main/java/io/github/flibio/economylite/modules/sql/SqlModule.java @@ -0,0 +1,83 @@ +/* + * This file is part of EconomyLite, licensed under the MIT License (MIT). + * + * Copyright (c) 2015 - 2016 Flibio + * Copyright (c) Contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package io.github.flibio.economylite.modules.sql; + +import org.slf4j.Logger; + +import io.github.flibio.economylite.EconomyLite; +import io.github.flibio.economylite.modules.Module; +import io.github.flibio.utils.file.ConfigManager; + +import java.util.Optional; + +public class SqlModule implements Module { + + private ConfigManager configManager = EconomyLite.getConfigManager(); + + @Override + public boolean initialize(Logger logger, Object plugin) { + String hostname = getDetail("hostname"); + String port = getDetail("port"); + String database = getDetail("database"); + String username = getDetail("username"); + String password = getDetail("password"); + PlayerSqlService pService = new PlayerSqlService(hostname, port, database, username, password); + VirtualSqlService vService = new VirtualSqlService(hostname, port, database, username, password); + if (pService.isWorking() && vService.isWorking()) { + EconomyLite.setPlayerService(pService); + EconomyLite.setVirtualService(vService); + } else { + return false; + } + return true; + } + + @Override + public void initializeConfig() { + configManager.setDefault("config.conf", "modules.mysql.enabled", Boolean.class, false); + configManager.setDefault("config.conf", "modules.mysql.hostname", String.class, "hostname"); + configManager.setDefault("config.conf", "modules.mysql.port", String.class, "3306"); + configManager.setDefault("config.conf", "modules.mysql.database", String.class, "database"); + configManager.setDefault("config.conf", "modules.mysql.username", String.class, "username"); + configManager.setDefault("config.conf", "modules.mysql.password", String.class, "password"); + } + + @Override + public String getName() { + return "SQL"; + } + + @Override + public boolean isEnabled() { + Optional eOpt = configManager.getValue("config.conf", "modules.mysql.enabled", Boolean.class); + return (eOpt.isPresent()) ? eOpt.get() : false; + } + + private String getDetail(String name) { + Optional vOpt = configManager.getValue("config.conf", "modules.mysql." + name, String.class); + return (vOpt.isPresent()) ? vOpt.get() : ""; + } + +} diff --git a/src/main/java/io/github/flibio/economylite/modules/sql/VirtualSqlService.java b/src/main/java/io/github/flibio/economylite/modules/sql/VirtualSqlService.java new file mode 100644 index 0000000..818d7ca --- /dev/null +++ b/src/main/java/io/github/flibio/economylite/modules/sql/VirtualSqlService.java @@ -0,0 +1,37 @@ +/* + * This file is part of EconomyLite, licensed under the MIT License (MIT). + * + * Copyright (c) 2015 - 2016 Flibio + * Copyright (c) Contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package io.github.flibio.economylite.modules.sql; + +import io.github.flibio.economylite.EconomyLite; +import io.github.flibio.economylite.impl.VirtualServiceCommon; +import io.github.flibio.utils.sql.RemoteSqlManager; + +public class VirtualSqlService extends VirtualServiceCommon { + + public VirtualSqlService(String hostname, String port, String database, String username, String password) { + super(RemoteSqlManager.createInstance(EconomyLite.getInstance(), hostname, port, database, username, password).get()); + } + +} diff --git a/src/main/resources/messages.properties b/src/main/resources/messages.properties new file mode 100644 index 0000000..a3ddabe --- /dev/null +++ b/src/main/resources/messages.properties @@ -0,0 +1,58 @@ +# +# This file is part of EconomyLite, licensed under the MIT License (MIT). +# +# Copyright (c) 2015 - 2016 Flibio +# Copyright (c) Contributors +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +# THE SOFTWARE. +# + +command.usage=&aUsage: &f{command} {subcommands} +command.noperm=&cYou do not have permission to run this command! +command.invalidsource=&cYou must be a {sourcetype} to use this command! +command.error=&cAn internal error has occurred! + +command.baltop.head=&6Top Three Balances: +command.baltop.data=&6{name}: &a{balance} &6{label} + +command.balance=&6Current Balance: &a{balance} &6{label} +command.balanceother=&6{player}'s Balance: &a{balance} &6{label} + +command.currency.changed=&6Changed the currency to &a{currency}! +command.currency.confirm=&6Click on this message to confirm the switch to &a{currency}! +command.currency.current=&6Current Currency: &a{currency}! +command.currency.invalid=&cThat currency could not be found! +command.currency.selectnew=&6Run &a/currency set &6to change the currency or click on a new currency! +command.currency.delete=&6Run &a/currency delete &6to delete a currency or click on a currency! +command.currency.deleteconfirm=&6Click on this message to confirm the deletion of &a{currency}! +command.currency.deleted=&6Deleted the currency &a{currency}! +command.currency.deletedefault=&cYou may not delete the default currency! +command.currency.created=&6Registered new currency: &a{currency}! +command.currency.exists=&cThat currency already exists! + +command.econ.addfail=&cFailed to add currency to the balance of {name}! +command.econ.addsuccess=&aSuccessfully added currency to the balance of &6{name}! +command.econ.removefail=&cFailed to remove currency from the balance of {name}! +command.econ.removesuccess=&aSuccessfully removed currency from the balance of &6{name}! +command.econ.setfail=&cFailed to set the balance of {name}! +command.econ.setsuccess=&aSuccessfully set the balance of &6{name}! + +command.pay.notyou=&cYou can not pay yourself! +command.pay.failed=&cThe payment to {target} failed! +command.pay.success=&aSuccessfully payed &6{target}! diff --git a/src/me/Flibio/EconomyLite/API/EconomyLiteAPI.java b/src/me/Flibio/EconomyLite/API/EconomyLiteAPI.java deleted file mode 100644 index b3d2c7e..0000000 --- a/src/me/Flibio/EconomyLite/API/EconomyLiteAPI.java +++ /dev/null @@ -1,61 +0,0 @@ -package me.Flibio.EconomyLite.API; - -import me.Flibio.EconomyLite.EconomyLite; -import me.Flibio.EconomyLite.Utils.BusinessManager; -import me.Flibio.EconomyLite.Utils.PlayerManager; - -public class EconomyLiteAPI { - - private BusinessManager businessAPI = new BusinessManager(); - - private PlayerManager playerAPI = new PlayerManager(); - - /** - * EconomyLite's API. - * - * Methods will query a MySQL Database if the EconomyLite user has opted to save data to a database. - * - * If possible, you should run these methods in a seperate thread. - */ - public EconomyLiteAPI() { - if(!EconomyLite.optionEnabled("businesses")) { - businessAPI = null; - } - } - - public BusinessManager getBusinessAPI() { - return businessAPI; - } - - public PlayerManager getPlayerAPI() { - return playerAPI; - } - - /** - * Gets the version of EconomyLite currently running - * @return - * String of the version in format X.Y.Z - */ - public String getVersion() { - return EconomyLite.access.version; - } - - /** - * Gets the singular label for currency - * @return - * String of the singular label - */ - public String getSingularCurrencyLabel() { - return EconomyLite.access.currencySingular; - } - - /** - * Gets the plural label for currency - * @return - * String of the plural label - */ - public String getPluralCurrencyLabel() { - return EconomyLite.access.currencyPlural; - } - -} diff --git a/src/me/Flibio/EconomyLite/API/LiteCurrency.java b/src/me/Flibio/EconomyLite/API/LiteCurrency.java deleted file mode 100644 index 36c13cd..0000000 --- a/src/me/Flibio/EconomyLite/API/LiteCurrency.java +++ /dev/null @@ -1,68 +0,0 @@ -package me.Flibio.EconomyLite.API; - -import me.Flibio.EconomyLite.EconomyLite; - -import org.spongepowered.api.service.economy.Currency; -import org.spongepowered.api.text.Text; - -import java.math.BigDecimal; -import java.math.RoundingMode; - -public class LiteCurrency implements Currency { - - public LiteCurrency() { - - } - - @Override - public int getDefaultFractionDigits() { - return 0; - } - - @Override - public Text getDisplayName() { - return Text.of(EconomyLite.access.currencySingular); - } - - @Override - public Text getPluralDisplayName() { - return Text.of(EconomyLite.access.currencyPlural); - } - - @Override - public Text getSymbol() { - return Text.of(EconomyLite.access.currencyPlural.substring(0, 1)); - } - - @Override - public boolean isDefault() { - return true; - } - - @Override - public Text format(BigDecimal amount, int arg1) { - int rounded = amount.setScale(0, RoundingMode.HALF_UP).intValue(); - if(rounded==1) { - return Text.of(rounded," ",EconomyLite.access.currencySingular); - } else { - return Text.of(rounded," ",EconomyLite.access.currencyPlural); - } - } - - @Override - public String getId() { - return "economylite:currency"; - } - - @Override - public String getName() { - return "EconomyLite Currency"; - } - - @Override - public boolean equals(Object other) { - if(!(other instanceof Currency)) - return false; - return this.getId().equals( ((Currency) other).getId() ); - } -} diff --git a/src/me/Flibio/EconomyLite/API/LiteEconomyService.java b/src/me/Flibio/EconomyLite/API/LiteEconomyService.java deleted file mode 100644 index 66a7033..0000000 --- a/src/me/Flibio/EconomyLite/API/LiteEconomyService.java +++ /dev/null @@ -1,76 +0,0 @@ -package me.Flibio.EconomyLite.API; - -import me.Flibio.EconomyLite.EconomyLite; -import me.Flibio.EconomyLite.Utils.BusinessManager; -import me.Flibio.EconomyLite.Utils.PlayerManager; - -import org.spongepowered.api.service.context.ContextCalculator; -import org.spongepowered.api.service.economy.Currency; -import org.spongepowered.api.service.economy.EconomyService; -import org.spongepowered.api.service.economy.account.Account; -import org.spongepowered.api.service.economy.account.UniqueAccount; - -import java.util.HashSet; -import java.util.Optional; -import java.util.Set; -import java.util.UUID; - -public class LiteEconomyService implements EconomyService { - - private PlayerManager playerManager = new PlayerManager(); - private BusinessManager businessManager = new BusinessManager(); - - @Override - public void registerContextCalculator(ContextCalculator arg0) { - return; - } - - @Override - public Optional getOrCreateAccount(UUID uuid) { - if(playerManager.playerExists(uuid.toString())) { - return Optional.of(new LiteUniqueAccount(uuid)); - } else { - if(playerManager.registerPlayer(uuid.toString(),EconomyLite.getOptionInteger("defaultCurrency"))) { - return Optional.of(new LiteUniqueAccount(uuid)); - } else { - return Optional.empty(); - } - } - } - - @Override - public Optional getOrCreateAccount(String id) { - if(businessManager.businessExists(id)) { - return Optional.of(new LiteVirtualAccount(id)); - } else { - if(businessManager.createBusiness(id)) { - return Optional.of(new LiteVirtualAccount(id)); - } else { - return Optional.empty(); - } - } - } - - @Override - public Set getCurrencies() { - HashSet set = new HashSet(); - set.add(new LiteCurrency()); - return set; - } - - @Override - public Currency getDefaultCurrency() { - return EconomyLite.getCurrency(); - } - - @Override - public boolean hasAccount(UUID uuid) { - return playerManager.playerExists(uuid.toString()); - } - - @Override - public boolean hasAccount(String id) { - return businessManager.businessExists(id); - } - -} diff --git a/src/me/Flibio/EconomyLite/API/LiteTransferResult.java b/src/me/Flibio/EconomyLite/API/LiteTransferResult.java deleted file mode 100644 index 8f5bdce..0000000 --- a/src/me/Flibio/EconomyLite/API/LiteTransferResult.java +++ /dev/null @@ -1,24 +0,0 @@ -package me.Flibio.EconomyLite.API; - -import org.spongepowered.api.service.economy.account.Account; -import org.spongepowered.api.service.economy.transaction.ResultType; -import org.spongepowered.api.service.economy.transaction.TransactionTypes; -import org.spongepowered.api.service.economy.transaction.TransferResult; - -import java.math.BigDecimal; - -public class LiteTransferResult extends LiteTransactionResult implements TransferResult { - - private Account toWho; - - public LiteTransferResult(Account account, BigDecimal amount, ResultType result, Account toWho) { - super(account, amount, result, TransactionTypes.TRANSFER); - this.toWho = toWho; - } - - @Override - public Account getAccountTo() { - return this.toWho; - } - -} diff --git a/src/me/Flibio/EconomyLite/API/LiteUniqueAccount.java b/src/me/Flibio/EconomyLite/API/LiteUniqueAccount.java deleted file mode 100644 index fce9cc9..0000000 --- a/src/me/Flibio/EconomyLite/API/LiteUniqueAccount.java +++ /dev/null @@ -1,171 +0,0 @@ -package me.Flibio.EconomyLite.API; - -import me.Flibio.EconomyLite.EconomyLite; -import me.Flibio.EconomyLite.Events.LiteEconomyTransactionEvent; -import me.Flibio.EconomyLite.Utils.PlayerManager; - -import org.spongepowered.api.Sponge; -import org.spongepowered.api.event.cause.Cause; -import org.spongepowered.api.service.context.Context; -import org.spongepowered.api.service.economy.Currency; -import org.spongepowered.api.service.economy.account.Account; -import org.spongepowered.api.service.economy.account.UniqueAccount; -import org.spongepowered.api.service.economy.transaction.ResultType; -import org.spongepowered.api.service.economy.transaction.TransactionResult; -import org.spongepowered.api.service.economy.transaction.TransactionTypes; -import org.spongepowered.api.service.economy.transaction.TransferResult; -import org.spongepowered.api.text.Text; - -import java.math.BigDecimal; -import java.math.RoundingMode; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; -import java.util.UUID; -//Change whole deal to go through the EconomyService, add event to VirtualAccount -public class LiteUniqueAccount implements UniqueAccount { - - private UUID uuid; - private PlayerManager playerManager; - private LiteCurrency liteCurrency; - - public LiteUniqueAccount(UUID uuid) { - this.uuid = uuid; - this.playerManager = new PlayerManager(); - this.liteCurrency = (LiteCurrency) EconomyLite.getCurrency(); - } - - @Override - public TransactionResult deposit(Currency currency, BigDecimal amount, - Cause cause, Set contexts) { - if(playerManager.addCurrency(uuid.toString(),amount.setScale(0, RoundingMode.HALF_UP).intValue())) { - TransactionResult result = new LiteTransactionResult(this,amount,ResultType.SUCCESS,TransactionTypes.TRANSFER); - Sponge.getGame().getEventManager().post(new LiteEconomyTransactionEvent(result)); - return result; - } else { - TransactionResult result = new LiteTransactionResult(this,amount,ResultType.FAILED,TransactionTypes.TRANSFER); - Sponge.getGame().getEventManager().post(new LiteEconomyTransactionEvent(result)); - return result; - } - } - - @Override - public BigDecimal getBalance(Currency currency, Set context) { - return BigDecimal.valueOf(playerManager.getBalance(uuid.toString())); - } - - @Override - public Map getBalances(Set arg0) { - int currentBal = playerManager.getBalance(uuid.toString()); - if(currentBal<0) { - return new HashMap(); - } else { - HashMap map = new HashMap(); - map.put(liteCurrency, BigDecimal.valueOf(currentBal)); - return map; - } - } - - @Override - public BigDecimal getDefaultBalance(Currency currency) { - return BigDecimal.valueOf(0); - } - - @Override - public Text getDisplayName() { - return Text.of((new PlayerManager()).getName(uuid.toString())); - } - - @Override - public boolean hasBalance(Currency currency, Set contexts) { - return playerManager.playerExists(uuid.toString()); - } - - @Override - public TransactionResult resetBalance(Currency currency, Cause cause, - Set contexts) { - return setBalance(currency,BigDecimal.ZERO,cause,contexts); - } - - @Override - public Map resetBalances(Cause cause, Set contexts) { - Map map = new HashMap<>(); - map.put(liteCurrency, resetBalance(liteCurrency,cause,contexts)); - return map; - } - - @Override - public TransactionResult setBalance(Currency currency, BigDecimal amount, - Cause cause, Set contexts) { - if(playerManager.setBalance(uuid.toString(),amount.setScale(0, RoundingMode.HALF_UP).intValue())) { - TransactionResult result = new LiteTransactionResult(this,amount,ResultType.SUCCESS,TransactionTypes.TRANSFER); - Sponge.getGame().getEventManager().post(new LiteEconomyTransactionEvent(result)); - return result; - } else { - TransactionResult result = new LiteTransactionResult(this,amount,ResultType.FAILED,TransactionTypes.TRANSFER); - Sponge.getGame().getEventManager().post(new LiteEconomyTransactionEvent(result)); - return result; - } - } - - @Override - public TransferResult transfer(Account account, Currency currency, - BigDecimal bigAmount, Cause cause, Set contexts) { - int toAccountBal = account.getBalance(liteCurrency).setScale(0, RoundingMode.HALF_UP).intValue(); - int amount = bigAmount.setScale(0, RoundingMode.HALF_UP).intValue(); - if(toAccountBal+amount>1000000) { - TransferResult result = new LiteTransferResult(this,BigDecimal.valueOf(amount),ResultType.ACCOUNT_NO_SPACE,account); - Sponge.getGame().getEventManager().post(new LiteEconomyTransactionEvent(result)); - return result; - } else { - if(getBalance(liteCurrency, new HashSet()).setScale(0, RoundingMode.HALF_UP).intValue()()).getResult().equals(ResultType.SUCCESS) - &&account.deposit(liteCurrency,BigDecimal.valueOf(amount),cause,new HashSet()).getResult(). - equals(ResultType.SUCCESS)) { - TransferResult result = new LiteTransferResult(this,BigDecimal.valueOf(amount),ResultType.SUCCESS,account); - Sponge.getGame().getEventManager().post(new LiteEconomyTransactionEvent(result)); - return result; - } else { - TransferResult result = new LiteTransferResult(this,BigDecimal.valueOf(amount),ResultType.FAILED,account); - Sponge.getGame().getEventManager().post(new LiteEconomyTransactionEvent(result)); - return result; - } - } - } - } - - @Override - public TransactionResult withdraw(Currency currency, BigDecimal amount, - Cause cause, Set contexts) { - if(playerManager.removeCurrency(uuid.toString(),amount.setScale(0, RoundingMode.HALF_UP).intValue())) { - TransactionResult result = new LiteTransactionResult(this,amount,ResultType.SUCCESS,TransactionTypes.WITHDRAW); - Sponge.getGame().getEventManager().post(new LiteEconomyTransactionEvent(result)); - return result; - } else { - TransactionResult result = new LiteTransactionResult(this,amount,ResultType.FAILED,TransactionTypes.WITHDRAW); - Sponge.getGame().getEventManager().post(new LiteEconomyTransactionEvent(result)); - return result; - } - } - - @Override - public Set getActiveContexts() { - return new HashSet(); - } - - @Override - public String getIdentifier() { - return this.uuid.toString(); - } - - @Override - public UUID getUniqueId() { - return this.uuid; - } - -} diff --git a/src/me/Flibio/EconomyLite/API/LiteVirtualAccount.java b/src/me/Flibio/EconomyLite/API/LiteVirtualAccount.java deleted file mode 100644 index a37ccaa..0000000 --- a/src/me/Flibio/EconomyLite/API/LiteVirtualAccount.java +++ /dev/null @@ -1,168 +0,0 @@ -package me.Flibio.EconomyLite.API; - -import me.Flibio.EconomyLite.EconomyLite; -import me.Flibio.EconomyLite.Events.LiteEconomyTransactionEvent; -import me.Flibio.EconomyLite.Utils.BusinessManager; - -import org.spongepowered.api.Sponge; -import org.spongepowered.api.event.cause.Cause; -import org.spongepowered.api.service.context.Context; -import org.spongepowered.api.service.economy.Currency; -import org.spongepowered.api.service.economy.account.Account; -import org.spongepowered.api.service.economy.account.VirtualAccount; -import org.spongepowered.api.service.economy.transaction.ResultType; -import org.spongepowered.api.service.economy.transaction.TransactionResult; -import org.spongepowered.api.service.economy.transaction.TransactionTypes; -import org.spongepowered.api.service.economy.transaction.TransferResult; -import org.spongepowered.api.text.Text; - -import java.math.BigDecimal; -import java.math.RoundingMode; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - -public class LiteVirtualAccount implements VirtualAccount { - - private String id; - private Text displayName; - private BusinessManager businessManager; - private LiteCurrency liteCurrency; - - //VirtualAccounts are treated as businesses, this will possibly change in the future - public LiteVirtualAccount(String id) { - this.id = id; - this.displayName = Text.of(id); - this.businessManager = new BusinessManager(); - this.liteCurrency = (LiteCurrency) EconomyLite.getCurrency(); - } - - @Override - public TransactionResult deposit(Currency currency, BigDecimal amount, - Cause cause, Set contexts) { - if(businessManager.addCurrency(id,amount.setScale(0, RoundingMode.HALF_UP).intValue())) { - TransactionResult result = new LiteTransactionResult(this,amount,ResultType.SUCCESS,TransactionTypes.TRANSFER); - Sponge.getGame().getEventManager().post(new LiteEconomyTransactionEvent(result)); - return result; - } else { - TransactionResult result = new LiteTransactionResult(this,amount,ResultType.FAILED,TransactionTypes.TRANSFER); - Sponge.getGame().getEventManager().post(new LiteEconomyTransactionEvent(result)); - return result; - } - } - - @Override - public BigDecimal getBalance(Currency currency, Set contexts) { - return BigDecimal.valueOf(businessManager.getBusinessBalance(id)); - } - - @Override - public Map getBalances(Set contexts) { - int currentBal = businessManager.getBusinessBalance(id); - if(currentBal<0) { - return new HashMap(); - } else { - HashMap map = new HashMap(); - map.put(liteCurrency, BigDecimal.valueOf(currentBal)); - return map; - } - } - - @Override - public BigDecimal getDefaultBalance(Currency currency) { - return BigDecimal.valueOf(0); - } - - @Override - public Text getDisplayName() { - return this.displayName; - } - - @Override - public boolean hasBalance(Currency currency, Set contexts) { - return businessManager.businessExists(id); - } - - @Override - public TransactionResult resetBalance(Currency currency, Cause cause, - Set contexts) { - return setBalance(currency,BigDecimal.ZERO,cause,contexts); - } - - @Override - public Map resetBalances(Cause cause, Set contexts) { - Map map = new HashMap<>(); - map.put(liteCurrency, resetBalance(liteCurrency,cause,contexts)); - return map; - } - - @Override - public TransactionResult setBalance(Currency currency, BigDecimal amount, - Cause cause, Set contexts) { - if(businessManager.setBusinessBalance(id,amount.setScale(0, RoundingMode.HALF_UP).intValue())) { - TransactionResult result = new LiteTransactionResult(this,amount,ResultType.SUCCESS,TransactionTypes.TRANSFER); - Sponge.getGame().getEventManager().post(new LiteEconomyTransactionEvent(result)); - return result; - } else { - TransactionResult result = new LiteTransactionResult(this,amount,ResultType.FAILED,TransactionTypes.TRANSFER); - Sponge.getGame().getEventManager().post(new LiteEconomyTransactionEvent(result)); - return result; - } - } - - @Override - public TransferResult transfer(Account account, Currency currency, - BigDecimal bigAmount, Cause cause, Set contexts) { - int toAccountBal = account.getBalance(liteCurrency).setScale(0, RoundingMode.HALF_UP).intValue(); - int amount = bigAmount.setScale(0, RoundingMode.HALF_UP).intValue(); - if(toAccountBal+amount>1000000) { - TransferResult result = new LiteTransferResult(this,BigDecimal.valueOf(amount),ResultType.ACCOUNT_NO_SPACE,account); - Sponge.getGame().getEventManager().post(new LiteEconomyTransactionEvent(result)); - return result; - } else { - if(getBalance(liteCurrency, new HashSet()).setScale(0, RoundingMode.HALF_UP).intValue()()).getResult().equals(ResultType.SUCCESS) - &&account.deposit(liteCurrency,BigDecimal.valueOf(amount),cause,new HashSet()).getResult(). - equals(ResultType.SUCCESS)) { - TransferResult result = new LiteTransferResult(this,BigDecimal.valueOf(amount),ResultType.SUCCESS,account); - Sponge.getGame().getEventManager().post(new LiteEconomyTransactionEvent(result)); - return result; - } else { - TransferResult result = new LiteTransferResult(this,BigDecimal.valueOf(amount),ResultType.FAILED,account); - Sponge.getGame().getEventManager().post(new LiteEconomyTransactionEvent(result)); - return result; - } - } - } - } - - @Override - public TransactionResult withdraw(Currency currency, BigDecimal amount, - Cause cause, Set contexts) { - if(businessManager.removeCurrency(id,amount.setScale(0, RoundingMode.HALF_UP).intValue())) { - TransactionResult result = new LiteTransactionResult(this,amount,ResultType.SUCCESS,TransactionTypes.WITHDRAW); - Sponge.getGame().getEventManager().post(new LiteEconomyTransactionEvent(result)); - return result; - } else { - TransactionResult result = new LiteTransactionResult(this,amount,ResultType.FAILED,TransactionTypes.WITHDRAW); - Sponge.getGame().getEventManager().post(new LiteEconomyTransactionEvent(result)); - return result; - } - } - - @Override - public Set getActiveContexts() { - return new HashSet(); - } - - @Override - public String getIdentifier() { - return this.id; - } - -} diff --git a/src/me/Flibio/EconomyLite/Commands/AddCommand.java b/src/me/Flibio/EconomyLite/Commands/AddCommand.java deleted file mode 100644 index fe964cb..0000000 --- a/src/me/Flibio/EconomyLite/Commands/AddCommand.java +++ /dev/null @@ -1,92 +0,0 @@ -package me.Flibio.EconomyLite.Commands; - -import me.Flibio.EconomyLite.EconomyLite; -import me.Flibio.EconomyLite.Utils.PlayerManager; -import me.Flibio.EconomyLite.Utils.TextUtils; - -import org.spongepowered.api.command.CommandException; -import org.spongepowered.api.command.CommandResult; -import org.spongepowered.api.command.CommandSource; -import org.spongepowered.api.command.args.CommandContext; -import org.spongepowered.api.command.spec.CommandExecutor; -import org.spongepowered.api.event.cause.Cause; -import org.spongepowered.api.event.cause.NamedCause; -import org.spongepowered.api.scheduler.Task.Builder; -import org.spongepowered.api.service.economy.Currency; -import org.spongepowered.api.service.economy.EconomyService; -import org.spongepowered.api.service.economy.account.UniqueAccount; -import org.spongepowered.api.service.economy.transaction.ResultType; -import org.spongepowered.api.text.format.TextColors; - -import java.math.BigDecimal; -import java.math.RoundingMode; -import java.util.Optional; -import java.util.UUID; - -public class AddCommand implements CommandExecutor { - - private TextUtils textUtils = new TextUtils(); - private EconomyService economyService = EconomyLite.getService(); - private Currency currency = EconomyLite.getService().getDefaultCurrency(); - private PlayerManager playerManager = new PlayerManager(); - private Builder taskBuilder = EconomyLite.access.game.getScheduler().createTaskBuilder(); - - @Override - public CommandResult execute(CommandSource source, CommandContext args) - throws CommandException { - //Run on a seperate thread - taskBuilder.execute(new Runnable(){ - public void run() { - //Retrieve arguments - Optional playerNameOptional = args.getOne("player"); - Optional amountOptional = args.getOne("amount"); - if(playerNameOptional.isPresent()&&amountOptional.isPresent()) { - //Set the variables - String playerName = playerNameOptional.get(); - int amount = amountOptional.get(); - source.sendMessage(textUtils.editingBalance(playerName)); - //Get the players UUID - String uuid = playerManager.getUUID(playerName); - if(!uuid.isEmpty()) { - Optional uOpt = economyService.getOrCreateAccount(UUID.fromString(uuid)); - if(!uOpt.isPresent()) { - //Account is not present - source.sendMessage(textUtils.basicText("An internal error has occured!", TextColors.RED)); - return; - } else { - UniqueAccount account = uOpt.get(); - //Set amount - int newAmount = amount + account.getBalance(currency).setScale(0, RoundingMode.HALF_UP).intValue(); - //Check if the amount is in-between of the parameters - if(newAmount<0||newAmount>1000000) { - //New balance is too big or small - source.sendMessage(textUtils.basicText("The new balance must be in-between 0 and 1,000,000 "+EconomyLite.access.currencyPlural+"!", TextColors.RED)); - return; - } - //Set the player's balance - if(account.setBalance(currency, BigDecimal.valueOf(newAmount), Cause.of(NamedCause.owner(EconomyLite.access))).getResult().equals(ResultType.SUCCESS)) { - //Successful - source.sendMessage(textUtils.successfulBalanceChangeText(playerName, newAmount)); - return; - } else { - //Send error message - source.sendMessage(textUtils.basicText("An internal error has occured!", TextColors.RED)); - return; - } - } - } else { - //UUID is empty - source.sendMessage(textUtils.basicText("An internal error has occured!", TextColors.RED)); - return; - } - } else { - //Send error message - source.sendMessage(textUtils.basicText("An internal error has occured!", TextColors.RED)); - return; - } - } - }).async().submit(EconomyLite.access); - return CommandResult.success(); - } - -} diff --git a/src/me/Flibio/EconomyLite/Commands/BalanceCommand.java b/src/me/Flibio/EconomyLite/Commands/BalanceCommand.java deleted file mode 100644 index ddfd6a0..0000000 --- a/src/me/Flibio/EconomyLite/Commands/BalanceCommand.java +++ /dev/null @@ -1,104 +0,0 @@ -package me.Flibio.EconomyLite.Commands; - -import me.Flibio.EconomyLite.EconomyLite; -import me.Flibio.EconomyLite.Utils.BusinessManager; -import me.Flibio.EconomyLite.Utils.TextUtils; - -import org.spongepowered.api.command.CommandException; -import org.spongepowered.api.command.CommandResult; -import org.spongepowered.api.command.CommandSource; -import org.spongepowered.api.command.args.CommandContext; -import org.spongepowered.api.command.spec.CommandExecutor; -import org.spongepowered.api.entity.living.player.Player; -import org.spongepowered.api.scheduler.Task.Builder; -import org.spongepowered.api.service.economy.Currency; -import org.spongepowered.api.service.economy.EconomyService; -import org.spongepowered.api.service.economy.account.UniqueAccount; -import org.spongepowered.api.text.format.TextColors; - -import java.math.RoundingMode; -import java.util.Optional; - -public class BalanceCommand implements CommandExecutor{ - - private TextUtils textUtils = new TextUtils(); - private EconomyService economyService = EconomyLite.getService(); - private Currency currency = EconomyLite.getService().getDefaultCurrency(); - private BusinessManager businessManager = new BusinessManager(); - private Builder taskBuilder = EconomyLite.access.game.getScheduler().createTaskBuilder(); - - @Override - public CommandResult execute(CommandSource source, CommandContext args) - throws CommandException { - //Run in a seperate thread - taskBuilder.execute(new Runnable() { - public void run() { - //Make sure the source is a player - if(!(source instanceof Player)) { - source.sendMessage(textUtils.basicText("You must be a player to use /balance!", TextColors.RED)); - return; - } - - Player player = (Player) source; - - Optional business = args.getOne("business"); - if(business.isPresent()&&EconomyLite.optionEnabled("businesses")) { - //Check if player has permission - if(!player.hasPermission("econ.business.balance")) { - source.sendMessage(textUtils.basicText("You do not have permission to use this command!", TextColors.RED)); - return; - } - //Player wants to view a business balance - String businessName = args.getOne("business").get(); - //Check if the business exists - if(businessManager.businessExists(businessName)) { - //Check if the player is an owner - if(businessManager.ownerExists(businessName, player.getUniqueId().toString())) { - //Attempt to send the player the businesses balance - int balance = businessManager.getBusinessBalance(businessName); - if(balance<0) { - //Send error message - player.sendMessage(textUtils.basicText("An internal error has occured!", TextColors.RED)); - return; - } else { - //Send business balance - player.sendMessage(textUtils.businessBalanceText(businessManager.getCorrectBusinessName(businessName), balance)); - return; - } - } else { - //Player not an owner - player.sendMessage(textUtils.basicText("You do not have permission to view the balance of that business!", TextColors.RED)); - return; - } - } else { - //Business not found - player.sendMessage(textUtils.basicText("Business could not be found!", TextColors.RED)); - return; - } - } else { - //Player wants to view their balance - Optional uOpt = economyService.getOrCreateAccount(player.getUniqueId()); - if(!uOpt.isPresent()) { - //Account is not present - source.sendMessage(textUtils.basicText("An internal error has occured!", TextColors.RED)); - return; - } else { - UniqueAccount account = uOpt.get(); - int balance = account.getBalance(currency).setScale(0, RoundingMode.HALF_UP).intValue(); - if(balance<0) { - //Send error message - player.sendMessage(textUtils.basicText("An internal error has occured!", TextColors.RED)); - return; - } else { - //Send player their balance - player.sendMessage(textUtils.playerBalanceText(balance)); - return; - } - } - } - } - }).submit(EconomyLite.access); - return CommandResult.success(); - } - -} diff --git a/src/me/Flibio/EconomyLite/Commands/BusinessDeleteCommand.java b/src/me/Flibio/EconomyLite/Commands/BusinessDeleteCommand.java deleted file mode 100644 index 195dbb9..0000000 --- a/src/me/Flibio/EconomyLite/Commands/BusinessDeleteCommand.java +++ /dev/null @@ -1,129 +0,0 @@ -package me.Flibio.EconomyLite.Commands; - -import me.Flibio.EconomyLite.EconomyLite; -import me.Flibio.EconomyLite.Utils.BusinessManager; -import me.Flibio.EconomyLite.Utils.TextUtils; - -import org.spongepowered.api.command.CommandException; -import org.spongepowered.api.command.CommandResult; -import org.spongepowered.api.command.CommandSource; -import org.spongepowered.api.command.args.CommandContext; -import org.spongepowered.api.command.spec.CommandExecutor; -import org.spongepowered.api.entity.living.player.Player; -import org.spongepowered.api.event.cause.Cause; -import org.spongepowered.api.event.cause.NamedCause; -import org.spongepowered.api.scheduler.Task.Builder; -import org.spongepowered.api.service.economy.Currency; -import org.spongepowered.api.service.economy.EconomyService; -import org.spongepowered.api.service.economy.account.UniqueAccount; -import org.spongepowered.api.text.format.TextColors; - -import java.math.BigDecimal; -import java.util.ArrayList; -import java.util.Optional; -import java.util.UUID; - -public class BusinessDeleteCommand implements CommandExecutor { - - private TextUtils textUtils = new TextUtils(); - private BusinessManager businessManager = new BusinessManager();private EconomyService economyService = EconomyLite.getService(); - private Currency currency = EconomyLite.getService().getDefaultCurrency(); - //private PlayerManager playerManager = new PlayerManager(); - private Builder taskBuilder = EconomyLite.access.game.getScheduler().createTaskBuilder(); - - @Override - public CommandResult execute(CommandSource source, CommandContext args) - throws CommandException { - //Run in a new thread - taskBuilder.execute(new Runnable() { - public void run() { - //Make sure the source is a player - if(!(source instanceof Player)) { - source.sendMessage(textUtils.basicText("You must be a player to delete a business!", TextColors.RED)); - return; - } - - Player player = (Player) source; - - //Retrieve arguments - Optional businessNameOptional = args.getOne("business"); - if(businessNameOptional.isPresent()) { - String businessName = businessNameOptional.get(); - //Check if the business already exists - if(businessManager.businessExists(businessName)) { - //Check if the player is an owner - if(businessManager.ownerExists(businessName, player.getUniqueId().toString())) { - String correctName = businessManager.getCorrectBusinessName(businessName); - //Check if the business needs confirmation - if(businessManager.confirmationNeeded(businessName)) { - //Tell user that the business needs confirmation - businessManager.setConfirmationNeeded(businessName, false); - //Expire in 1 minute - Thread expireThread = new Thread(new Runnable(){ - public void run() { - try{ - Thread.sleep(60000); - businessManager.setConfirmationNeeded(businessName, true); - } catch(InterruptedException e) { - businessManager.setConfirmationNeeded(businessName, true); - } - } - }); - expireThread.start(); - player.sendMessage(textUtils.aboutToDelete(correctName)); - player.sendMessage(textUtils.clickToContinue("/business delete "+businessName)); - return; - } else { - //Get balance - int balance = businessManager.getBusinessBalance(businessName); - if(balance<0) { - //Error occured - player.sendMessage(textUtils.basicText("An internal error has occured!", TextColors.RED)); - return; - } - int eachGet = (int) Math.floor(balance/businessManager.getBusinessOwners(businessName).size()); - ArrayList owners = businessManager.getBusinessOwners(businessName); - //Try to delete business - if(businessManager.deleteBusiness(businessName)) { - //Success - player.sendMessage(textUtils.deleteSuccess(correctName)); - //Distribute funds to all owners - for(String uuid : owners) { - Optional uOpt = economyService.getOrCreateAccount(UUID.fromString(uuid)); - if(!uOpt.isPresent()) { - //Account is not present - source.sendMessage(textUtils.basicText("An internal error has occured!", TextColors.RED)); - return; - } else { - UniqueAccount account = uOpt.get(); - account.deposit(currency, BigDecimal.valueOf(eachGet), Cause.of(NamedCause.owner(EconomyLite.access))); - } - } - return; - } else { - //Error occured - player.sendMessage(textUtils.basicText("An internal error has occured!", TextColors.RED)); - return; - } - } - } else { - //Player doesn't have permission - player.sendMessage(textUtils.basicText("You don't have permission to delete that business!", TextColors.RED)); - return; - } - } else { - //Business doesn't exist - player.sendMessage(textUtils.basicText("That business could not be found!", TextColors.RED)); - return; - } - } else { - //Send error message - player.sendMessage(textUtils.basicText("An internal error has occured!", TextColors.RED)); - return; - } - } - }).async().submit(EconomyLite.access); - return CommandResult.success(); - } - -} diff --git a/src/me/Flibio/EconomyLite/Commands/BusinessInviteAcceptCommand.java b/src/me/Flibio/EconomyLite/Commands/BusinessInviteAcceptCommand.java deleted file mode 100644 index eb78005..0000000 --- a/src/me/Flibio/EconomyLite/Commands/BusinessInviteAcceptCommand.java +++ /dev/null @@ -1,83 +0,0 @@ -package me.Flibio.EconomyLite.Commands; - -import me.Flibio.EconomyLite.EconomyLite; -import me.Flibio.EconomyLite.Utils.BusinessManager; -import me.Flibio.EconomyLite.Utils.TextUtils; - -import org.spongepowered.api.command.CommandException; -import org.spongepowered.api.command.CommandResult; -import org.spongepowered.api.command.CommandSource; -import org.spongepowered.api.command.args.CommandContext; -import org.spongepowered.api.command.spec.CommandExecutor; -import org.spongepowered.api.entity.living.player.Player; -import org.spongepowered.api.scheduler.Task.Builder; -import org.spongepowered.api.text.format.TextColors; - -import java.util.Optional; - -public class BusinessInviteAcceptCommand implements CommandExecutor { - - private TextUtils textUtils = new TextUtils(); - private BusinessManager businessManager = new BusinessManager(); - private Builder taskBuilder = EconomyLite.access.game.getScheduler().createTaskBuilder(); - - @Override - public CommandResult execute(CommandSource source, CommandContext args) - throws CommandException { - //Run in a new thread - taskBuilder.execute(new Runnable() { - public void run() { - //Make sure the source is a player - if(!(source instanceof Player)) { - source.sendMessage(textUtils.basicText("You must be a player to accept an invite!", TextColors.RED)); - return; - } - - Player player = (Player) source; - - String uuid = player.getUniqueId().toString(); - - //Retrieve arguments - Optional businessNameOptional = args.getOne("business"); - if(businessNameOptional.isPresent()) { - String businessName = businessNameOptional.get(); - //Check if the business exists - if(businessManager.businessExists(businessName)) { - //Check if the player is an owner - if(businessManager.ownerExists(businessName, uuid)) { - //Already an owner - player.sendMessage(textUtils.basicText("You are already an owner of that business!", TextColors.RED)); - return; - } else { - //Check if the player has an invite - if(businessManager.isInvited(businessName, uuid)) { - //Accept the invite - if(businessManager.setInvited(businessName, uuid, false)&&businessManager.addOwner(businessName, uuid)) { - //Tell the player they were accepted - player.sendMessage(textUtils.inviteAccept(businessManager.getCorrectBusinessName(businessName))); - return; - } else { - //Error - player.sendMessage(textUtils.basicText("An internal error has occured!", TextColors.RED)); - return; - } - } else { - player.sendMessage(textUtils.basicText("You are not invited to join that business!", TextColors.RED)); - return; - } - } - } else { - player.sendMessage(textUtils.basicText("Business was not found!", TextColors.RED)); - return; - } - } else { - //Send error message - player.sendMessage(textUtils.basicText("An internal error has occured!", TextColors.RED)); - return; - } - } - }).async().submit(EconomyLite.access); - return CommandResult.success(); - } - -} diff --git a/src/me/Flibio/EconomyLite/Commands/BusinessInviteCommand.java b/src/me/Flibio/EconomyLite/Commands/BusinessInviteCommand.java deleted file mode 100644 index 6c3ffc0..0000000 --- a/src/me/Flibio/EconomyLite/Commands/BusinessInviteCommand.java +++ /dev/null @@ -1,105 +0,0 @@ -package me.Flibio.EconomyLite.Commands; - -import me.Flibio.EconomyLite.EconomyLite; -import me.Flibio.EconomyLite.Utils.BusinessManager; -import me.Flibio.EconomyLite.Utils.PlayerManager; -import me.Flibio.EconomyLite.Utils.TextUtils; - -import org.spongepowered.api.command.CommandException; -import org.spongepowered.api.command.CommandResult; -import org.spongepowered.api.command.CommandSource; -import org.spongepowered.api.command.args.CommandContext; -import org.spongepowered.api.command.spec.CommandExecutor; -import org.spongepowered.api.entity.living.player.Player; -import org.spongepowered.api.scheduler.Task.Builder; -import org.spongepowered.api.text.format.TextColors; - -import java.util.Optional; - -public class BusinessInviteCommand implements CommandExecutor { - - private TextUtils textUtils = new TextUtils(); - private BusinessManager businessManager = new BusinessManager(); - private PlayerManager playerManager = new PlayerManager(); - private Builder taskBuilder = EconomyLite.access.game.getScheduler().createTaskBuilder(); - - @Override - public CommandResult execute(CommandSource source, CommandContext args) - throws CommandException { - //Run in a new thread - taskBuilder.execute(new Runnable() { - public void run() { - //Make sure the source is a player - if(!(source instanceof Player)) { - source.sendMessage(textUtils.basicText("You must be a player to invite someone to a business!", TextColors.RED)); - return; - } - - Player player = (Player) source; - - //Retrieve arguments - Optional playerNameOptional = args.getOne("player"); - Optional businessNameOptional = args.getOne("business"); - if(playerNameOptional.isPresent()&&businessNameOptional.isPresent()) { - String playerName = playerNameOptional.get(); - String businessName = businessNameOptional.get(); - String uuid = playerManager.getUUID(playerName); - //Check if the uuid is an error - if(uuid.isEmpty()) { - player.sendMessage(textUtils.basicText("An internal error has occured!", TextColors.RED)); - return; - } - //Check if the business exists - if(businessManager.businessExists(businessName)) { - //Check if the player is an owner - if(businessManager.ownerExists(businessName, player.getUniqueId().toString())) { - //Check if the target is already an owner - if(businessManager.ownerExists(businessName, uuid)) { - player.sendMessage(textUtils.basicText("That player is already an owner of that business!", TextColors.RED)); - return; - } else { - //Check if the player is already invited - if(businessManager.isInvited(businessName, uuid)) { - //Player is already invited - player.sendMessage(textUtils.basicText("That has already been invited to join that business!", TextColors.RED)); - return; - } else { - //Attempt to send the invite - if(businessManager.setInvited(businessName, uuid, true)) { - //Success! - Check if the player is online and send them the invite if they are - for(Player p : EconomyLite.access.game.getServer().getOnlinePlayers()) { - if(p.getUniqueId().toString().equals(uuid)) { - //Player was found - send invite message - p.sendMessage(textUtils.invited(businessManager.getCorrectBusinessName(businessName))); - p.sendMessage(textUtils.clickToContinue("/business inviteAccept "+businessName)); - } - } - //Tell the command sender invite was sent - player.sendMessage(textUtils.successfulInvite(businessManager.getCorrectBusinessName(businessName), playerName)); - return; - } else { - //Error - player.sendMessage(textUtils.basicText("An internal error has occured!", TextColors.RED)); - return; - } - } - } - } else { - player.sendMessage(textUtils.basicText("You don't have permission to add owners to this business!", TextColors.RED)); - return; - } - } else { - player.sendMessage(textUtils.basicText("Business was not found!", TextColors.RED)); - return; - } - } else { - //Send error message - player.sendMessage(textUtils.basicText("An internal error has occured!", TextColors.RED)); - return; - } - } - }).async().submit(EconomyLite.access); - return CommandResult.success(); - } - -} diff --git a/src/me/Flibio/EconomyLite/Commands/BusinessLeaveCommand.java b/src/me/Flibio/EconomyLite/Commands/BusinessLeaveCommand.java deleted file mode 100644 index 39acf52..0000000 --- a/src/me/Flibio/EconomyLite/Commands/BusinessLeaveCommand.java +++ /dev/null @@ -1,98 +0,0 @@ -package me.Flibio.EconomyLite.Commands; - -import me.Flibio.EconomyLite.EconomyLite; -import me.Flibio.EconomyLite.Utils.BusinessManager; -import me.Flibio.EconomyLite.Utils.TextUtils; - -import org.spongepowered.api.command.CommandException; -import org.spongepowered.api.command.CommandResult; -import org.spongepowered.api.command.CommandSource; -import org.spongepowered.api.command.args.CommandContext; -import org.spongepowered.api.command.spec.CommandExecutor; -import org.spongepowered.api.entity.living.player.Player; -import org.spongepowered.api.scheduler.Task.Builder; -import org.spongepowered.api.text.format.TextColors; - -import java.util.Optional; - -public class BusinessLeaveCommand implements CommandExecutor { - - private TextUtils textUtils = new TextUtils(); - private BusinessManager businessManager = new BusinessManager(); - private Builder taskBuilder = EconomyLite.access.game.getScheduler().createTaskBuilder(); - - @Override - public CommandResult execute(CommandSource source, CommandContext args) - throws CommandException { - //Run in a new thread - taskBuilder.execute(new Runnable() { - public void run() { - //Make sure the source is a player - if(!(source instanceof Player)) { - source.sendMessage(textUtils.basicText("You must be a player to leave a business!", TextColors.RED)); - return; - } - - Player player = (Player) source; - - //Retrieve arguments - Optional businessNameOptional = args.getOne("business"); - if(businessNameOptional.isPresent()) { - String businessName = businessNameOptional.get(); - //Check if the business already exists - if(businessManager.businessExists(businessName)) { - String correctName = businessManager.getCorrectBusinessName(businessName); - //Check if the player is an owner - if(businessManager.ownerExists(businessName, player.getUniqueId().toString())) { - //Check if the player is the only owner - if(businessManager.getBusinessOwners(businessName).size()==1) { - //Tell player that the business will be deleted - player.sendMessage(textUtils.leaveOnlyOwner(correctName)); - businessManager.setConfirmationNeeded(businessName, false); - //Expire in 1 minute - Thread expireThread = new Thread(new Runnable(){ - public void run() { - try{ - Thread.sleep(60000); - businessManager.setConfirmationNeeded(businessName, true); - } catch(InterruptedException e) { - businessManager.setConfirmationNeeded(businessName, true); - } - } - }); - expireThread.start(); - player.sendMessage(textUtils.clickToContinue("/business delete "+businessName)); - return; - } else { - //Leave the business - if(businessManager.removeOwner(businessName, player.getUniqueId().toString())) { - //Success - player.sendMessage(textUtils.leaveSuccess(businessName)); - return; - } else { - //Error - player.sendMessage(textUtils.basicText("An internal error has occured!", TextColors.RED)); - return; - } - } - } else { - //Player doesn't have permission - player.sendMessage(textUtils.basicText("You are not an owner of that business!", TextColors.RED)); - return; - } - } else { - //Business doesn't exist - player.sendMessage(textUtils.basicText("That business could not be found!", TextColors.RED)); - return; - } - } else { - //Send error message - player.sendMessage(textUtils.basicText("An internal error has occured!", TextColors.RED)); - return; - } - } - }).async().submit(EconomyLite.access); - return CommandResult.success(); - } - -} diff --git a/src/me/Flibio/EconomyLite/Commands/BusinessOwnersCommand.java b/src/me/Flibio/EconomyLite/Commands/BusinessOwnersCommand.java deleted file mode 100644 index 5b7a302..0000000 --- a/src/me/Flibio/EconomyLite/Commands/BusinessOwnersCommand.java +++ /dev/null @@ -1,76 +0,0 @@ -package me.Flibio.EconomyLite.Commands; - -import me.Flibio.EconomyLite.EconomyLite; -import me.Flibio.EconomyLite.Utils.BusinessManager; -import me.Flibio.EconomyLite.Utils.PlayerManager; -import me.Flibio.EconomyLite.Utils.TextUtils; - -import org.spongepowered.api.command.CommandException; -import org.spongepowered.api.command.CommandResult; -import org.spongepowered.api.command.CommandSource; -import org.spongepowered.api.command.args.CommandContext; -import org.spongepowered.api.command.spec.CommandExecutor; -import org.spongepowered.api.entity.living.player.Player; -import org.spongepowered.api.scheduler.Task.Builder; -import org.spongepowered.api.text.format.TextColors; - -import java.util.ArrayList; -import java.util.Optional; - -public class BusinessOwnersCommand implements CommandExecutor{ - - private TextUtils textUtils = new TextUtils(); - private BusinessManager businessManager = new BusinessManager(); - private PlayerManager playerManager = new PlayerManager(); - private Builder taskBuilder = EconomyLite.access.game.getScheduler().createTaskBuilder(); - - @Override - public CommandResult execute(CommandSource source, CommandContext args) - throws CommandException { - //Run in a seperate thread - taskBuilder.execute(new Runnable() { - public void run() { - //Make sure the source is a player - if(!(source instanceof Player)) { - source.sendMessage(textUtils.basicText("You must be a player to view the owners of a business!", TextColors.RED)); - return; - } - - Player player = (Player) source; - - Optional rawBusiness = args.getOne("business"); - if(rawBusiness.isPresent()) { - //Parameter is present - String businessName = rawBusiness.get().trim(); - String correctName = businessManager.getCorrectBusinessName(businessName); - - //Check if the business exists - if(!businessManager.businessExists(businessName)) { - player.sendMessage(textUtils.basicText("That business doesn't exist!", TextColors.RED)); - return; - } - //Check if the player is an owner - if(!businessManager.ownerExists(businessName, player.getUniqueId().toString())) { - player.sendMessage(textUtils.basicText("You don't have permission to view the owners of that business!", TextColors.RED)); - return; - } - //Send the message: - ArrayList owners = businessManager.getBusinessOwners(businessName); - player.sendMessage(textUtils.ownersTitle(correctName)); - for(String owner : owners) { - player.sendMessage(textUtils.owner(playerManager.getName(owner))); - } - } else { - //An error occured - player.sendMessage(textUtils.basicText("An internal error has occured!", TextColors.RED)); - return; - } - - } - }).async().submit(EconomyLite.access); - return CommandResult.success(); - } - - - -} diff --git a/src/me/Flibio/EconomyLite/Commands/BusinessRegisterCommand.java b/src/me/Flibio/EconomyLite/Commands/BusinessRegisterCommand.java deleted file mode 100644 index 43d46b7..0000000 --- a/src/me/Flibio/EconomyLite/Commands/BusinessRegisterCommand.java +++ /dev/null @@ -1,83 +0,0 @@ -package me.Flibio.EconomyLite.Commands; - -import me.Flibio.EconomyLite.EconomyLite; -import me.Flibio.EconomyLite.Utils.BusinessManager; -import me.Flibio.EconomyLite.Utils.TextUtils; - -import org.spongepowered.api.command.CommandException; -import org.spongepowered.api.command.CommandResult; -import org.spongepowered.api.command.CommandSource; -import org.spongepowered.api.command.args.CommandContext; -import org.spongepowered.api.command.spec.CommandExecutor; -import org.spongepowered.api.entity.living.player.Player; -import org.spongepowered.api.scheduler.Task.Builder; -import org.spongepowered.api.text.format.TextColors; - -import java.util.Optional; - -public class BusinessRegisterCommand implements CommandExecutor { - - private TextUtils textUtils = new TextUtils(); - private BusinessManager businessManager = new BusinessManager(); - private Builder taskBuilder = EconomyLite.access.game.getScheduler().createTaskBuilder(); - - @Override - public CommandResult execute(CommandSource source, CommandContext args) - throws CommandException { - //Run in a new thread - taskBuilder.execute(new Runnable() { - public void run() { - //Make sure the source is a player - if(!(source instanceof Player)) { - source.sendMessage(textUtils.basicText("You must be a player to create a business!", TextColors.RED)); - return; - } - - Player player = (Player) source; - - //Retrieve arguments - Optional businessNameOptional = args.getOne("business"); - if(businessNameOptional.isPresent()) { - String businessName = businessNameOptional.get(); - //Check if the business name is too long - if(businessName.length()>1000) { - //Name to long - player.sendMessage(textUtils.basicText("That business name is too long!", TextColors.RED)); - return; - } - //Check if the business already exists - if(!businessManager.businessExists(businessName)) { - //Try to create business - if(businessManager.createBusiness(businessName)) { - //Attempt to add player as an owner - if(businessManager.addOwner(businessName, player.getUniqueId().toString())) { - //Successful - player.sendMessage(textUtils.successfulBusinessRegister(businessManager.getCorrectBusinessName(businessName))); - return; - } else { - //Error occured - delete business - businessManager.deleteBusiness(businessName); - player.sendMessage(textUtils.basicText("An internal error has occured!", TextColors.RED)); - return; - } - } else { - //Error occured - player.sendMessage(textUtils.basicText("An internal error has occured!", TextColors.RED)); - return; - } - } else { - //Business exists - player.sendMessage(textUtils.basicText("A business with that name already exists!", TextColors.RED)); - return; - } - } else { - //Send error message - player.sendMessage(textUtils.basicText("An internal error has occured!", TextColors.RED)); - return; - } - } - }).async().submit(EconomyLite.access); - return CommandResult.success(); - } - -} diff --git a/src/me/Flibio/EconomyLite/Commands/BusinessTransferCommand.java b/src/me/Flibio/EconomyLite/Commands/BusinessTransferCommand.java deleted file mode 100644 index 0d7611f..0000000 --- a/src/me/Flibio/EconomyLite/Commands/BusinessTransferCommand.java +++ /dev/null @@ -1,116 +0,0 @@ -package me.Flibio.EconomyLite.Commands; - -import me.Flibio.EconomyLite.EconomyLite; -import me.Flibio.EconomyLite.Utils.BusinessManager; -import me.Flibio.EconomyLite.Utils.TextUtils; - -import org.spongepowered.api.command.CommandException; -import org.spongepowered.api.command.CommandResult; -import org.spongepowered.api.command.CommandSource; -import org.spongepowered.api.command.args.CommandContext; -import org.spongepowered.api.command.spec.CommandExecutor; -import org.spongepowered.api.entity.living.player.Player; -import org.spongepowered.api.event.cause.Cause; -import org.spongepowered.api.event.cause.NamedCause; -import org.spongepowered.api.scheduler.Task.Builder; -import org.spongepowered.api.service.economy.Currency; -import org.spongepowered.api.service.economy.EconomyService; -import org.spongepowered.api.service.economy.account.UniqueAccount; -import org.spongepowered.api.service.economy.transaction.ResultType; -import org.spongepowered.api.text.format.TextColors; - -import java.math.BigDecimal; -import java.math.RoundingMode; -import java.util.Optional; - -public class BusinessTransferCommand implements CommandExecutor{ - - private TextUtils textUtils = new TextUtils(); - private EconomyService economyService = EconomyLite.getService(); - private Currency currency = EconomyLite.getService().getDefaultCurrency(); - private BusinessManager businessManager = new BusinessManager(); - private Builder taskBuilder = EconomyLite.access.game.getScheduler().createTaskBuilder(); - - @Override - public CommandResult execute(CommandSource source, CommandContext args) - throws CommandException { - //Run in a seperate thread - taskBuilder.execute(new Runnable() { - public void run() { - //Make sure the source is a player - if(!(source instanceof Player)) { - source.sendMessage(textUtils.basicText("You must be a player to transfer funds to your account!", TextColors.RED)); - return; - } - - Player player = (Player) source; - - Optional rawAmount = args.getOne("amount"); - Optional rawBusiness = args.getOne("business"); - if(rawAmount.isPresent()&&rawBusiness.isPresent()) { - //Both parameters are present - int amount = rawAmount.get(); - String businessName = rawBusiness.get().trim(); - String correctName = businessManager.getCorrectBusinessName(businessName); - Optional uOpt = economyService.getOrCreateAccount(player.getUniqueId()); - if(!uOpt.isPresent()) { - //Account is not present - source.sendMessage(textUtils.basicText("An internal error has occured!", TextColors.RED)); - return; - } else { - UniqueAccount account = uOpt.get(); - //Check if the business exists - if(!businessManager.businessExists(businessName)) { - player.sendMessage(textUtils.basicText("That business doesn't exist!", TextColors.RED)); - return; - } - //Check if the player is an owner - if(!businessManager.ownerExists(businessName, player.getUniqueId().toString())) { - player.sendMessage(textUtils.basicText("You don't have permission to draw funds from that business!", TextColors.RED)); - return; - } - int businessBalance = businessManager.getBusinessBalance(businessName); - int playerBalance = account.getBalance(currency).setScale(0, RoundingMode.HALF_UP).intValue(); - //Check for an error - if(businessBalance<0||playerBalance<0) { - player.sendMessage(textUtils.basicText("An internal error has occured!", TextColors.RED)); - return; - } - //Check if the business has enough funds - if(amount>businessBalance) { - //Not enough funds - player.sendMessage(textUtils.basicText("That business doesn't have enough funds!", TextColors.RED)); - return; - } - int newBalance = businessBalance + playerBalance; - //Make sure the new balance is within the parameters - if(newBalance<0||newBalance>1000000) { - player.sendMessage(textUtils.basicText("Your balance must stay within 0 and 1,000,000 "+EconomyLite.access.currencyPlural+"!", TextColors.RED)); - return; - } - //Attempt to transfer the money - if(!businessManager.removeCurrency(businessName, amount)) { - player.sendMessage(textUtils.basicText("An internal error has occured!", TextColors.RED)); - return; - } - if(!account.setBalance(currency, BigDecimal.valueOf(playerBalance+amount), Cause.of(NamedCause.owner(EconomyLite.access))).getResult().equals(ResultType.SUCCESS)) { - player.sendMessage(textUtils.basicText("An internal error has occured!", TextColors.RED)); - return; - } - //Success! - player.sendMessage(textUtils.transferSuccess(correctName, amount)); - } - } else { - //An error occured - player.sendMessage(textUtils.basicText("An internal error has occured!", TextColors.RED)); - return; - } - - } - }).async().submit(EconomyLite.access); - return CommandResult.success(); - } - - - -} diff --git a/src/me/Flibio/EconomyLite/Commands/PayCommand.java b/src/me/Flibio/EconomyLite/Commands/PayCommand.java deleted file mode 100644 index 6beccc8..0000000 --- a/src/me/Flibio/EconomyLite/Commands/PayCommand.java +++ /dev/null @@ -1,207 +0,0 @@ -package me.Flibio.EconomyLite.Commands; - -import me.Flibio.EconomyLite.EconomyLite; -import me.Flibio.EconomyLite.Utils.BusinessManager; -import me.Flibio.EconomyLite.Utils.PlayerManager; -import me.Flibio.EconomyLite.Utils.TextUtils; - -import org.spongepowered.api.Sponge; -import org.spongepowered.api.command.CommandException; -import org.spongepowered.api.command.CommandResult; -import org.spongepowered.api.command.CommandSource; -import org.spongepowered.api.command.args.CommandContext; -import org.spongepowered.api.command.spec.CommandExecutor; -import org.spongepowered.api.entity.living.player.Player; -import org.spongepowered.api.event.cause.Cause; -import org.spongepowered.api.event.cause.NamedCause; -import org.spongepowered.api.scheduler.Task.Builder; -import org.spongepowered.api.service.economy.Currency; -import org.spongepowered.api.service.economy.EconomyService; -import org.spongepowered.api.service.economy.account.UniqueAccount; -import org.spongepowered.api.service.economy.transaction.ResultType; -import org.spongepowered.api.text.format.TextColors; - -import java.math.BigDecimal; -import java.math.RoundingMode; -import java.util.Optional; -import java.util.UUID; - -public class PayCommand implements CommandExecutor{ - - private TextUtils textUtils = new TextUtils(); - private EconomyService economyService = EconomyLite.getService(); - private Currency currency = EconomyLite.getService().getDefaultCurrency(); - private PlayerManager playerManager = new PlayerManager(); - private BusinessManager businessManager = new BusinessManager(); - private Builder taskBuilder = EconomyLite.access.game.getScheduler().createTaskBuilder(); - - @Override - public CommandResult execute(final CommandSource source, final CommandContext args) - throws CommandException { - //Run in a seperate thread - taskBuilder.execute(new Runnable() { - public void run() { - //Make sure the source is a player - if(!(source instanceof Player)) { - source.sendMessage(textUtils.basicText("You must be a player to use /pay!", TextColors.RED)); - return; - } - - Player player = (Player) source; - - String uuid = player.getUniqueId().toString(); - if(!playerManager.playerExists(uuid)) { - player.sendMessage(textUtils.basicText("An internal error has occurred!", TextColors.RED)); - return; - } - - Optional rawAmount = args.getOne("amount"); - Optional rawWho = args.getOne("who"); - if(rawWho.isPresent()&&rawAmount.isPresent()) { - //Both parameters are present - int amount = rawAmount.get(); - String who = rawWho.get(); - - if(who.equalsIgnoreCase(player.getName())) { - player.sendMessage(textUtils.basicText("Why would you pay yourself!?", TextColors.RED)); - return; - } - - if(who.trim().split(" ").length>1) { - //Who is a business - String businessName = who; - payBusiness(uuid,amount,player,businessName); - return; - } else { - //Get the UUID and check if it exists - String targetUuid = playerManager.getUUID(who); - //Check if the uuid is a registered player - if(economyService.getOrCreateAccount(UUID.fromString(targetUuid)).isPresent()) { - //It is a player, is it also a business? - if(businessManager.businessExists(who)) { - //Present them with an option - player.sendMessage(textUtils.payOption(who)); - player.sendMessage(textUtils.payOptionPlayer(who, amount)); - player.sendMessage(textUtils.payOptionBusiness(who, amount)); - return; - } else { - //It is a player - String playerName = who; - payPlayer(uuid,amount,player,playerName,targetUuid); - return; - } - } else { - //Not a registered player, search businesses - if(businessManager.businessExists(who)) { - //Who is a business - String businessName = who; - payBusiness(uuid,amount,player,businessName); - return; - } else { - //Nothing found - player.sendMessage(textUtils.basicText("No registered business/player could be found!", TextColors.RED)); - return; - } - } - } - } else { - //An error occurred - player.sendMessage(textUtils.basicText("An internal error has occurred!", TextColors.RED)); - return; - } - - } - }).async().submit(EconomyLite.access); - return CommandResult.success(); - } - - private void payBusiness(String uuid, int amount, Player player, String businessName) { - UniqueAccount account = economyService.getOrCreateAccount(UUID.fromString(uuid)).get(); - int balance = account.getBalance(currency).setScale(0, RoundingMode.HALF_UP).intValue(); - //Check for an error - if(balance>-1) { - //Check if the player has enough money - if(amount>balance) { - //Player doesn't have enough funds - player.sendMessage(textUtils.basicText("You don't have enough money to pay!", TextColors.RED)); - return; - } else { - //Check if the new balance is within parameters - int newBalance = businessManager.getBusinessBalance(businessName) + amount; - if(newBalance<0||newBalance>1000000) { - //Out of range - player.sendMessage(textUtils.basicText("The new balance must be in-between 0 and 1,000,000 "+EconomyLite.access.currencyPlural+"!", TextColors.RED)); - return; - } else { - //Process transaction - if(account.withdraw(currency,BigDecimal.valueOf(amount),Cause.of(NamedCause.owner(EconomyLite.access))).getResult().equals(ResultType.SUCCESS)&& - businessManager.setBusinessBalance(businessName, newBalance)) { - //Success - player.sendMessage(textUtils.paySuccess(businessName, amount)); - for(String owner : businessManager.getBusinessOwners(businessName)) { - Sponge.getServer().getOnlinePlayers().forEach(p -> { - if(p.getName().equalsIgnoreCase(owner)) { - p.sendMessage(textUtils.bPayed(player.getName(), amount, businessName)); - } - }); - } - return; - } else { - //Error - player.sendMessage(textUtils.basicText("An internal error has occurred!", TextColors.RED)); - return; - } - } - } - } else { - //Error - player.sendMessage(textUtils.basicText("An internal error has occurred!", TextColors.RED)); - return; - } - } - - private void payPlayer(String uuid, int amount, Player player, String playerName, String targetUUID) { - UniqueAccount account = economyService.getOrCreateAccount(UUID.fromString(uuid)).get(); - UniqueAccount targetAccount = economyService.getOrCreateAccount(UUID.fromString(targetUUID)).get(); - int balance = account.getBalance(currency).setScale(0, RoundingMode.HALF_UP).intValue(); - //Check for an error - if(balance>-1) { - //Check if the player has enough money - if(amount>balance) { - //Player doesn't have enough funds - player.sendMessage(textUtils.basicText("You don't have enough money to pay!", TextColors.RED)); - return; - } else { - //Check if the new balance is within parameters - int newBalance = targetAccount.getBalance(currency).setScale(0, RoundingMode.HALF_UP).intValue() + amount; - if(newBalance<0||newBalance>1000000) { - //Out of range - player.sendMessage(textUtils.basicText("The new balance must be in-between 0 and 1,000,000 "+EconomyLite.access.currencyPlural+"!", TextColors.RED)); - return; - } else { - //Process transaction - if(account.withdraw(currency,BigDecimal.valueOf(amount),Cause.of(NamedCause.owner(EconomyLite.access))).getResult().equals(ResultType.SUCCESS)&& - targetAccount.setBalance(currency,BigDecimal.valueOf(newBalance),Cause.of(NamedCause.owner(EconomyLite.access))).getResult().equals(ResultType.SUCCESS)) { - //Success - player.sendMessage(textUtils.paySuccess(playerName, amount)); - for(Player oPlayer : Sponge.getServer().getOnlinePlayers()) { - if(oPlayer.getUniqueId().toString().equals(targetUUID)) { - oPlayer.sendMessage(textUtils.payed(player.getName(),amount)); - } - } - return; - } else { - //Error - player.sendMessage(textUtils.basicText("An internal error has occurred!", TextColors.RED)); - return; - } - } - } - } else { - //Error - player.sendMessage(textUtils.basicText("An internal error has occurred!", TextColors.RED)); - return; - } - } - -} diff --git a/src/me/Flibio/EconomyLite/Commands/PayOverrideCommand.java b/src/me/Flibio/EconomyLite/Commands/PayOverrideCommand.java deleted file mode 100644 index f17dd77..0000000 --- a/src/me/Flibio/EconomyLite/Commands/PayOverrideCommand.java +++ /dev/null @@ -1,201 +0,0 @@ -package me.Flibio.EconomyLite.Commands; - -import me.Flibio.EconomyLite.EconomyLite; -import me.Flibio.EconomyLite.Utils.BusinessManager; -import me.Flibio.EconomyLite.Utils.PlayerManager; -import me.Flibio.EconomyLite.Utils.TextUtils; - -import org.spongepowered.api.Sponge; -import org.spongepowered.api.command.CommandException; -import org.spongepowered.api.command.CommandResult; -import org.spongepowered.api.command.CommandSource; -import org.spongepowered.api.command.args.CommandContext; -import org.spongepowered.api.command.spec.CommandExecutor; -import org.spongepowered.api.entity.living.player.Player; -import org.spongepowered.api.event.cause.Cause; -import org.spongepowered.api.event.cause.NamedCause; -import org.spongepowered.api.scheduler.Task.Builder; -import org.spongepowered.api.service.economy.Currency; -import org.spongepowered.api.service.economy.EconomyService; -import org.spongepowered.api.service.economy.account.UniqueAccount; -import org.spongepowered.api.service.economy.transaction.ResultType; -import org.spongepowered.api.text.format.TextColors; - -import java.math.BigDecimal; -import java.math.RoundingMode; -import java.util.Optional; -import java.util.UUID; - -public class PayOverrideCommand implements CommandExecutor{ - - private TextUtils textUtils = new TextUtils(); - private EconomyService economyService = EconomyLite.getService(); - private Currency currency = EconomyLite.getService().getDefaultCurrency(); - private PlayerManager playerManager = new PlayerManager(); - private BusinessManager businessManager = new BusinessManager(); - private Builder taskBuilder = EconomyLite.access.game.getScheduler().createTaskBuilder(); - - @Override - public CommandResult execute(CommandSource source, CommandContext args) - throws CommandException { - //Run in a seperate thread - taskBuilder.execute(new Runnable() { - public void run() { - //Make sure the source is a player - if(!(source instanceof Player)) { - source.sendMessage(textUtils.basicText("You must be a player to use /pay!", TextColors.RED)); - return; - } - - Player player = (Player) source; - - String uuid = player.getUniqueId().toString(); - if(!playerManager.playerExists(uuid)) { - player.sendMessage(textUtils.basicText("An internal error has occurred!", TextColors.RED)); - return; - } - - Optional rawWhoType = args.getOne("whoType"); - Optional rawAmount = args.getOne("amount"); - Optional rawWho = args.getOne("who"); - if(rawWhoType.isPresent()&&rawWho.isPresent()&&rawAmount.isPresent()) { - //Both parameters are present - String whoType = rawWhoType.get(); - int amount = rawAmount.get(); - String who = rawWho.get(); - - if(whoType.equalsIgnoreCase("player")) { - //Who is a player - if(who.equalsIgnoreCase(player.getName())) { - player.sendMessage(textUtils.basicText("Why would you pay yourself!?", TextColors.RED)); - return; - } - String playerName = who; - String playerUUID = playerManager.getUUID(playerName); - if(playerManager.playerExists(playerUUID)) { - //Pay player - payPlayer(uuid, amount, player, playerName, playerUUID); - return; - } else { - //Player not found - player.sendMessage(textUtils.basicText("That player could not be found!", TextColors.RED)); - return; - } - } else if(whoType.equalsIgnoreCase("business")) { - //Who is a business - String businessName = who; - if(businessManager.businessExists(businessName)) { - //Pay business - payBusiness(uuid, amount, player, businessName); - return; - } else { - //Business not found - player.sendMessage(textUtils.basicText("That business could not be found!", TextColors.RED)); - return; - } - } else { - //An error occured - player.sendMessage(textUtils.basicText("An internal error has occured!", TextColors.RED)); - return; - } - } else { - //An error occured - player.sendMessage(textUtils.basicText("An internal error has occured!pp", TextColors.RED)); - return; - } - - } - }).async().submit(EconomyLite.access); - return CommandResult.success(); - } - - private void payBusiness(String uuid, int amount, Player player, String businessName) { - UniqueAccount account = economyService.getOrCreateAccount(UUID.fromString(uuid)).get(); - int balance = account.getBalance(currency).setScale(0, RoundingMode.HALF_UP).intValue(); - //Check for an error - if(balance>-1) { - //Check if the player has enough money - if(amount>balance) { - //Player doesn't have enough funds - player.sendMessage(textUtils.basicText("You don't have enough money to pay!", TextColors.RED)); - return; - } else { - //Check if the new balance is within parameters - int newBalance = businessManager.getBusinessBalance(businessName) + amount; - if(newBalance<0||newBalance>1000000) { - //Out of range - player.sendMessage(textUtils.basicText("The new balance must be in-between 0 and 1,000,000 "+EconomyLite.access.currencyPlural+"!", TextColors.RED)); - return; - } else { - //Process transaction - if(account.withdraw(currency,BigDecimal.valueOf(amount),Cause.of(NamedCause.owner(EconomyLite.access))).getResult().equals(ResultType.SUCCESS)&& - businessManager.setBusinessBalance(businessName, newBalance)) { - //Success - player.sendMessage(textUtils.paySuccess(businessName, amount)); - for(String owner : businessManager.getBusinessOwners(businessName)) { - Sponge.getServer().getOnlinePlayers().forEach(p -> { - if(p.getName().equalsIgnoreCase(owner)) { - p.sendMessage(textUtils.bPayed(player.getName(), amount, businessName)); - } - }); - } - return; - } else { - //Error - player.sendMessage(textUtils.basicText("An internal error has occurred!", TextColors.RED)); - return; - } - } - } - } else { - //Error - player.sendMessage(textUtils.basicText("An internal error has occurred!", TextColors.RED)); - return; - } - } - - private void payPlayer(String uuid, int amount, Player player, String playerName, String targetUUID) { - UniqueAccount account = economyService.getOrCreateAccount(UUID.fromString(uuid)).get(); - UniqueAccount targetAccount = economyService.getOrCreateAccount(UUID.fromString(targetUUID)).get(); - int balance = account.getBalance(currency).setScale(0, RoundingMode.HALF_UP).intValue(); - //Check for an error - if(balance>-1) { - //Check if the player has enough money - if(amount>balance) { - //Player doesn't have enough funds - player.sendMessage(textUtils.basicText("You don't have enough money to pay!", TextColors.RED)); - return; - } else { - //Check if the new balance is within parameters - int newBalance = targetAccount.getBalance(currency).setScale(0, RoundingMode.HALF_UP).intValue() + amount; - if(newBalance<0||newBalance>1000000) { - //Out of range - player.sendMessage(textUtils.basicText("The new balance must be in-between 0 and 1,000,000 "+EconomyLite.access.currencyPlural+"!", TextColors.RED)); - return; - } else { - //Process transaction - if(account.withdraw(currency,BigDecimal.valueOf(amount),Cause.of(NamedCause.owner(EconomyLite.access))).getResult().equals(ResultType.SUCCESS)&& - targetAccount.setBalance(currency,BigDecimal.valueOf(newBalance),Cause.of(NamedCause.owner(EconomyLite.access))).getResult().equals(ResultType.SUCCESS)) { - //Success - player.sendMessage(textUtils.paySuccess(playerName, amount)); - for(Player oPlayer : Sponge.getServer().getOnlinePlayers()) { - if(oPlayer.getUniqueId().toString().equals(targetUUID)) { - oPlayer.sendMessage(textUtils.payed(player.getName(),amount)); - } - } - return; - } else { - //Error - player.sendMessage(textUtils.basicText("An internal error has occurred!", TextColors.RED)); - return; - } - } - } - } else { - //Error - player.sendMessage(textUtils.basicText("An internal error has occurred!", TextColors.RED)); - return; - } - } - -} diff --git a/src/me/Flibio/EconomyLite/Commands/PlayerBalanceCommand.java b/src/me/Flibio/EconomyLite/Commands/PlayerBalanceCommand.java deleted file mode 100644 index f239402..0000000 --- a/src/me/Flibio/EconomyLite/Commands/PlayerBalanceCommand.java +++ /dev/null @@ -1,70 +0,0 @@ -package me.Flibio.EconomyLite.Commands; - -import me.Flibio.EconomyLite.EconomyLite; -import me.Flibio.EconomyLite.Utils.PlayerManager; -import me.Flibio.EconomyLite.Utils.TextUtils; - -import org.spongepowered.api.command.CommandException; -import org.spongepowered.api.command.CommandResult; -import org.spongepowered.api.command.CommandSource; -import org.spongepowered.api.command.args.CommandContext; -import org.spongepowered.api.command.spec.CommandExecutor; -import org.spongepowered.api.scheduler.Task.Builder; -import org.spongepowered.api.service.economy.Currency; -import org.spongepowered.api.service.economy.EconomyService; -import org.spongepowered.api.service.economy.account.UniqueAccount; -import org.spongepowered.api.text.format.TextColors; - -import java.math.RoundingMode; -import java.util.Optional; -import java.util.UUID; - -public class PlayerBalanceCommand implements CommandExecutor { - - private TextUtils textUtils = new TextUtils(); - private EconomyService economyService = EconomyLite.getService(); - private Currency currency = EconomyLite.getService().getDefaultCurrency(); - private PlayerManager playerManager = new PlayerManager(); - private Builder taskBuilder = EconomyLite.access.game.getScheduler().createTaskBuilder(); - - @Override - public CommandResult execute(CommandSource source, CommandContext args) - throws CommandException { - //Run in a seperate thread - taskBuilder.execute(new Runnable() { - public void run() { - - Optional target = args.getOne("player"); - if(target.isPresent()) { - //Check if player has permission - if(!source.hasPermission("econ.playerbalance")) { - source.sendMessage(textUtils.basicText("You do not have permission to use this command!", TextColors.RED)); - return; - } - //Player wants to view another player's balance - String targetName = target.get(); - String uuid = playerManager.getUUID(targetName); - Optional oAct = economyService.getOrCreateAccount(UUID.fromString(uuid)); - if(oAct.isPresent()) { - int balance = oAct.get().getBalance(currency).setScale(0, RoundingMode.HALF_UP).intValue(); - if(balance<0) { - source.sendMessage(textUtils.basicText("An internal error has occurred!", TextColors.RED)); - return; - } else { - source.sendMessage(textUtils.playerBalanceText(balance, targetName)); - return; - } - } else { - source.sendMessage(textUtils.basicText("An internal error has occurred!", TextColors.RED)); - return; - } - } else { - source.sendMessage(textUtils.basicText("You need to specify a player to get the balance of!", TextColors.RED)); - return; - } - } - }).submit(EconomyLite.access); - return CommandResult.success(); - } - -} diff --git a/src/me/Flibio/EconomyLite/Commands/RemoveCommand.java b/src/me/Flibio/EconomyLite/Commands/RemoveCommand.java deleted file mode 100644 index cef5a90..0000000 --- a/src/me/Flibio/EconomyLite/Commands/RemoveCommand.java +++ /dev/null @@ -1,94 +0,0 @@ -package me.Flibio.EconomyLite.Commands; - -import me.Flibio.EconomyLite.EconomyLite; -import me.Flibio.EconomyLite.Utils.PlayerManager; -import me.Flibio.EconomyLite.Utils.TextUtils; - -import org.spongepowered.api.command.CommandException; -import org.spongepowered.api.command.CommandResult; -import org.spongepowered.api.command.CommandSource; -import org.spongepowered.api.command.args.CommandContext; -import org.spongepowered.api.command.spec.CommandExecutor; -import org.spongepowered.api.event.cause.Cause; -import org.spongepowered.api.event.cause.NamedCause; -import org.spongepowered.api.scheduler.Task.Builder; -import org.spongepowered.api.service.economy.Currency; -import org.spongepowered.api.service.economy.EconomyService; -import org.spongepowered.api.service.economy.account.UniqueAccount; -import org.spongepowered.api.service.economy.transaction.ResultType; -import org.spongepowered.api.text.format.TextColors; - -import java.math.BigDecimal; -import java.math.RoundingMode; -import java.util.Optional; -import java.util.UUID; - -public class RemoveCommand implements CommandExecutor { - - private TextUtils textUtils = new TextUtils(); - private EconomyService economyService = EconomyLite.getService(); - private Currency currency = EconomyLite.getService().getDefaultCurrency(); - private PlayerManager playerManager = new PlayerManager(); - private Builder taskBuilder = EconomyLite.access.game.getScheduler().createTaskBuilder(); - - @Override - public CommandResult execute(CommandSource source, CommandContext args) - throws CommandException { - //Run on a seperate thread - taskBuilder.execute(new Runnable() { - public void run() { - //Retrieve arguments - Optional playerNameOptional = args.getOne("player"); - Optional amountOptional = args.getOne("amount"); - if(playerNameOptional.isPresent()&&amountOptional.isPresent()) { - //Set the variables - String playerName = playerNameOptional.get(); - int amount = amountOptional.get(); - //Run the thread - source.sendMessage(textUtils.editingBalance(playerName)); - //Get the players UUID - String uuid = playerManager.getUUID(playerName); - if(!uuid.isEmpty()) { - Optional uOpt = economyService.getOrCreateAccount(UUID.fromString(uuid)); - if(!uOpt.isPresent()) { - //Account is not present - source.sendMessage(textUtils.basicText("An internal error has occured!", TextColors.RED)); - return; - } else { - UniqueAccount account = uOpt.get(); - //Set amount - int newAmount = account.getBalance(currency).setScale(0, RoundingMode.HALF_UP).intValue() - amount; - //Check if the amount is in-between of the parameters - if(newAmount<0||newAmount>1000000) { - //New balance is to big or small - source.sendMessage(textUtils.basicText("The new balance must be in-between 0 and 1,000,000 "+EconomyLite.access.currencyPlural+"!", TextColors.RED)); - return; - } - //Set the player's balance - if(account.setBalance(currency,BigDecimal.valueOf(newAmount),Cause.of(NamedCause.owner(EconomyLite.access))).getResult().equals(ResultType.SUCCESS)) { - //Successful - source.sendMessage(textUtils.successfulBalanceChangeText(playerName, newAmount)); - return; - } else { - //Send error message - source.sendMessage(textUtils.basicText("An internal error has occured!", TextColors.RED)); - return; - } - } - } else { - //UUID is empty - source.sendMessage(textUtils.basicText("An internal error has occured!", TextColors.RED)); - return; - } - - } else { - //Send error message - source.sendMessage(textUtils.basicText("An internal error has occured!", TextColors.RED)); - return; - } - } - }).async().submit(EconomyLite.access); - return CommandResult.success(); - } - -} diff --git a/src/me/Flibio/EconomyLite/Commands/SetCommand.java b/src/me/Flibio/EconomyLite/Commands/SetCommand.java deleted file mode 100644 index 44609ae..0000000 --- a/src/me/Flibio/EconomyLite/Commands/SetCommand.java +++ /dev/null @@ -1,90 +0,0 @@ -package me.Flibio.EconomyLite.Commands; - -import me.Flibio.EconomyLite.EconomyLite; -import me.Flibio.EconomyLite.Utils.PlayerManager; -import me.Flibio.EconomyLite.Utils.TextUtils; - -import org.spongepowered.api.command.CommandException; -import org.spongepowered.api.command.CommandResult; -import org.spongepowered.api.command.CommandSource; -import org.spongepowered.api.command.args.CommandContext; -import org.spongepowered.api.command.spec.CommandExecutor; -import org.spongepowered.api.event.cause.Cause; -import org.spongepowered.api.event.cause.NamedCause; -import org.spongepowered.api.scheduler.Task.Builder; -import org.spongepowered.api.service.economy.Currency; -import org.spongepowered.api.service.economy.EconomyService; -import org.spongepowered.api.service.economy.account.UniqueAccount; -import org.spongepowered.api.service.economy.transaction.ResultType; -import org.spongepowered.api.text.format.TextColors; - -import java.math.BigDecimal; -import java.util.Optional; -import java.util.UUID; - -public class SetCommand implements CommandExecutor { - - private TextUtils textUtils = new TextUtils(); - private EconomyService economyService = EconomyLite.getService(); - private Currency currency = EconomyLite.getService().getDefaultCurrency(); - private PlayerManager playerManager = new PlayerManager(); - private Builder taskBuilder = EconomyLite.access.game.getScheduler().createTaskBuilder(); - - @Override - public CommandResult execute(CommandSource source, CommandContext args) - throws CommandException { - //Run command process in a seperate thread - taskBuilder.execute(new Runnable() { - public void run() { - //Retrieve arguments - Optional playerNameOptional = args.getOne("player"); - Optional amountOptional = args.getOne("amount"); - if(playerNameOptional.isPresent()&&amountOptional.isPresent()) { - //Set the variables - String playerName = playerNameOptional.get(); - int amount = amountOptional.get(); - //Run the thread - source.sendMessage(textUtils.editingBalance(playerName)); - //Get the players UUID - String uuid = playerManager.getUUID(playerName); - if(!uuid.isEmpty()) { - Optional uOpt = economyService.getOrCreateAccount(UUID.fromString(uuid)); - if(!uOpt.isPresent()) { - //Account is not present - source.sendMessage(textUtils.basicText("An internal error has occured!", TextColors.RED)); - return; - } else { - UniqueAccount account = uOpt.get(); - //Check if the amount is in-between of the parameters - if(amount<0||amount>1000000) { - //New balance is to big or small - source.sendMessage(textUtils.basicText("The new balance must be in-between 0 and 1,000,000 "+EconomyLite.access.currencyPlural+"!", TextColors.RED)); - return; - } - //Set the player's balance - if(account.setBalance(currency,BigDecimal.valueOf(amount),Cause.of(NamedCause.owner(EconomyLite.access))).getResult().equals(ResultType.SUCCESS)) { - //Successful - source.sendMessage(textUtils.successfulBalanceChangeText(playerName, amount)); - return; - } else { - //Send error message - source.sendMessage(textUtils.basicText("An internal error has occured!", TextColors.RED)); - return; - } - } - } else { - //UUID is empty - source.sendMessage(textUtils.basicText("An internal error has occured!", TextColors.RED)); - return; - } - } else { - //Send error message - source.sendMessage(textUtils.basicText("An internal error has occured!", TextColors.RED)); - return; - } - } - }).async().submit(EconomyLite.access); - return CommandResult.success(); - } - -} diff --git a/src/me/Flibio/EconomyLite/EconomyLite.java b/src/me/Flibio/EconomyLite/EconomyLite.java deleted file mode 100644 index d9ff1d0..0000000 --- a/src/me/Flibio/EconomyLite/EconomyLite.java +++ /dev/null @@ -1,333 +0,0 @@ -package me.Flibio.EconomyLite; - -import me.Flibio.EconomyLite.API.EconomyLiteAPI; -import me.Flibio.EconomyLite.API.LiteCurrency; -import me.Flibio.EconomyLite.API.LiteEconomyService; -import me.Flibio.EconomyLite.Commands.AddCommand; -import me.Flibio.EconomyLite.Commands.BalanceCommand; -import me.Flibio.EconomyLite.Commands.BusinessDeleteCommand; -import me.Flibio.EconomyLite.Commands.BusinessInviteAcceptCommand; -import me.Flibio.EconomyLite.Commands.BusinessInviteCommand; -import me.Flibio.EconomyLite.Commands.BusinessLeaveCommand; -import me.Flibio.EconomyLite.Commands.BusinessOwnersCommand; -import me.Flibio.EconomyLite.Commands.BusinessRegisterCommand; -import me.Flibio.EconomyLite.Commands.BusinessTransferCommand; -import me.Flibio.EconomyLite.Commands.PayCommand; -import me.Flibio.EconomyLite.Commands.PayOverrideCommand; -import me.Flibio.EconomyLite.Commands.PlayerBalanceCommand; -import me.Flibio.EconomyLite.Commands.RemoveCommand; -import me.Flibio.EconomyLite.Commands.SetCommand; -import me.Flibio.EconomyLite.Listeners.BalanceChangeListener; -import me.Flibio.EconomyLite.Listeners.PlayerJoinListener; -import me.Flibio.EconomyLite.Registry.CurrencyRegistryModule; -import me.Flibio.EconomyLite.Utils.BusinessManager; -import me.Flibio.EconomyLite.Utils.FileManager; -import me.Flibio.EconomyLite.Utils.FileManager.FileType; -import me.Flibio.EconomyLite.Utils.MySQLManager; -import me.flibio.updatifier.Updatifier; -import net.minecrell.mcstats.SpongeStatsLite; -import ninja.leaping.configurate.ConfigurationNode; - -import org.slf4j.Logger; -import org.spongepowered.api.Game; -import org.spongepowered.api.command.args.GenericArguments; -import org.spongepowered.api.command.spec.CommandSpec; -import org.spongepowered.api.event.Listener; -import org.spongepowered.api.event.game.state.GameInitializationEvent; -import org.spongepowered.api.plugin.Plugin; -import org.spongepowered.api.service.economy.Currency; -import org.spongepowered.api.service.economy.EconomyService; -import org.spongepowered.api.service.sql.SqlService; -import org.spongepowered.api.text.Text; - -import com.google.inject.Inject; - -import java.util.HashMap; -import java.util.Optional; - -@Updatifier(repoName = "EconomyLite", repoOwner = "Flibio", version = "v1.2.2") -@Plugin(id = "me.flibio.economylite", name = "EconomyLite", version = "1.2.2", description = "Sponge economy plugin.") -public class EconomyLite { - - @Inject - public Logger logger; - - @Inject - public Game game; - - @Inject - private SpongeStatsLite statsLite; - private FileManager fileManager; - private BusinessManager businessManager; - private static EconomyService economyService; - private static Currency currency; - private static CurrencyRegistryModule currencyRegistryModule; - - public static EconomyLite access; - - public String currencySingular = ""; - public String currencyPlural = ""; - - public boolean sqlEnabled = false; - - private static MySQLManager mySQL = null; - - public String version = EconomyLite.class.getAnnotation(Plugin.class).version(); - - private static HashMap configOptions = new HashMap(); - - @Listener - public void onServerInitialize(GameInitializationEvent event) { - logger.info("EconomyLite v"+version+" by Flibio initializing!"); - this.statsLite.start(); - //Set the access - access = this; - - fileManager = new FileManager(); - businessManager = new BusinessManager(); - - //Create files and load config options - initializeFiles(); - loadConfigurationOptions(); - //Attempt to load MySQL if it is enabled - Optional sqlServiceOptional = game.getServiceManager().provide(SqlService.class); - if(optionEnabled("mysql.enabled")&&sqlServiceOptional.isPresent()) { - //Enable MySQL - sqlEnabled = true; - //Connect to the database - logger.info("Enabling MySQL..."); - mySQL = new MySQLManager(getOption("mysql.hostname"), getOption("mysql.port"), getOption("mysql.database"), - getOption("mysql.username"), getOption("mysql.password"), sqlServiceOptional.get()); - } - //Register events and commands - registerEvents(); - registerCommands(); - //Register EconomyLiteAPI - game.getServiceManager().setProvider(this, EconomyLiteAPI.class, new EconomyLiteAPI()); - economyService = new LiteEconomyService(); - game.getServiceManager().setProvider(this, EconomyService.class, economyService); - currencyRegistryModule = new CurrencyRegistryModule(); - game.getRegistry().registerModule(Currency.class, currencyRegistryModule); - logger.info("API registered successfully!"); - //Reset business confirmations - game.getScheduler().createTaskBuilder().execute(new Runnable() { - public void run() { - fileManager.loadFile(FileType.BUSINESS_DATA); - ConfigurationNode root = fileManager.getFile(FileType.BUSINESS_DATA); - for(ConfigurationNode raw : root.getChildrenMap().values()) { - businessManager.setConfirmationNeeded(raw.getKey().toString(), true); - } - } - }).async().submit(this); - } - - private void registerEvents() { - game.getEventManager().registerListeners(this, new PlayerJoinListener()); - game.getEventManager().registerListeners(this, new BalanceChangeListener()); - } - - private void registerCommands() { - CommandSpec balanceCommand = CommandSpec.builder() - .description(Text.of("View EconomyLite balance")) - .arguments(GenericArguments.optional(GenericArguments.remainingJoinedStrings(Text.of("business")))) - .executor(new BalanceCommand()) - .build(); - game.getCommandManager().register(this, balanceCommand, "balance", "bal"); - CommandSpec pBalanceCommand = CommandSpec.builder() - .description(Text.of("View EconomyLite balance of another player")) - .arguments(GenericArguments.string(Text.of("player"))) - .executor(new PlayerBalanceCommand()) - .build(); - game.getCommandManager().register(this, pBalanceCommand, "playerbalance", "pbal"); - //Add Child Command - CommandSpec addCommand = CommandSpec.builder() - .description(Text.of("Add currency to a player's balance")) - .arguments(GenericArguments.integer(Text.of("amount")), GenericArguments.string(Text.of("player"))) - .executor(new AddCommand()) - .build(); - //Remove Child Command - CommandSpec removeCommand = CommandSpec.builder() - .description(Text.of("Remove currency from a player's balance")) - .arguments(GenericArguments.integer(Text.of("amount")), GenericArguments.string(Text.of("player"))) - .executor(new RemoveCommand()) - .build(); - //Set Child Command - CommandSpec setCommand = CommandSpec.builder() - .description(Text.of("Set a player's balance")) - .arguments(GenericArguments.string(Text.of("player")), GenericArguments.integer(Text.of("amount"))) - .executor(new SetCommand()) - .build(); - //Main Econ Command - CommandSpec econCommand = CommandSpec.builder() - .description(Text.of("Edit player balances")) - .permission("econ.admin") - .child(addCommand, "add") - .child(removeCommand, "remove") - .child(setCommand, "set") - .build(); - game.getCommandManager().register(this, econCommand, "econ"); - //Business Commands - if(optionEnabled("businesses")) { - //Register Child - CommandSpec businessRegisterCommand = CommandSpec.builder() - .description(Text.of("Register a new business")) - .permission("econ.busines.register") - .arguments(GenericArguments.remainingJoinedStrings(Text.of("business"))) - .executor(new BusinessRegisterCommand()) - .build(); - //Delete Child - CommandSpec businessDeleteCommand = CommandSpec.builder() - .description(Text.of("Delete a business")) - .permission("econ.busines.delete") - .arguments(GenericArguments.remainingJoinedStrings(Text.of("business"))) - .executor(new BusinessDeleteCommand()) - .build(); - //Leave Child - CommandSpec businessLeaveCommand = CommandSpec.builder() - .description(Text.of("Leave a business as an owner")) - .permission("econ.busines.leave") - .arguments(GenericArguments.remainingJoinedStrings(Text.of("business"))) - .executor(new BusinessLeaveCommand()) - .build(); - //Invite Child - CommandSpec businessInviteCommand = CommandSpec.builder() - .description(Text.of("Invite an owner to a business")) - .permission("econ.busines.invite") - .arguments(GenericArguments.string(Text.of("player")),GenericArguments.remainingJoinedStrings(Text.of("business"))) - .executor(new BusinessInviteCommand()) - .build(); - //Invite Accept Child - CommandSpec businessInviteAcceptCommand = CommandSpec.builder() - .description(Text.of("Accept an invite to a business")) - .permission("econ.busines.invite") - .arguments(GenericArguments.remainingJoinedStrings(Text.of("business"))) - .executor(new BusinessInviteAcceptCommand()) - .build(); - //Transfer Child - CommandSpec businessTransferCommand = CommandSpec.builder() - .description(Text.of("Transfer some of the business funds to your account")) - .permission("econ.busines.transfer") - .arguments(GenericArguments.integer(Text.of("amount")),GenericArguments.remainingJoinedStrings(Text.of("business"))) - .executor(new BusinessTransferCommand()) - .build(); - //Owners Child - CommandSpec businessOwnersCommand = CommandSpec.builder() - .description(Text.of("View the owners of a business")) - .permission("econ.busines.owners") - .arguments(GenericArguments.remainingJoinedStrings(Text.of("business"))) - .executor(new BusinessOwnersCommand()) - .build(); - //Main Command - CommandSpec businessCommand = CommandSpec.builder() - .description(Text.of("Business management commands")) - .permission("econ.business") - .child(businessRegisterCommand, "register", "reg") - .child(businessDeleteCommand, "delete", "del") - .child(businessLeaveCommand, "leave") - .child(businessInviteCommand, "invite", "inv") - .child(businessInviteAcceptCommand, "inviteAccept") - .child(businessTransferCommand, "transfer") - .child(businessOwnersCommand, "owners") - .build(); - game.getCommandManager().register(this, businessCommand, "business"); - } - //Pay Commands - CommandSpec payCommand = CommandSpec.builder() - .description(Text.of("Pay another player or business")) - .permission("econ.pay") - .arguments(GenericArguments.integer(Text.of("amount")), GenericArguments.remainingJoinedStrings(Text.of("who"))) - .executor(new PayCommand()) - .build(); - game.getCommandManager().register(this, payCommand, "pay"); - CommandSpec payOverrideCommand = CommandSpec.builder() - .description(Text.of("Pay another player or business")) - .permission("econ.pay") - .arguments(GenericArguments.string(Text.of("whoType")), GenericArguments.integer(Text.of("amount")), GenericArguments.remainingJoinedStrings(Text.of("who"))) - .executor(new PayOverrideCommand()) - .build(); - game.getCommandManager().register(this, payOverrideCommand, "paySpecified"); - } - - //Generates all files and sets default configuration using FileManager class - private void initializeFiles() { - fileManager.generateFolder("config/EconomyLite"); - fileManager.generateFile("config/EconomyLite/config.conf"); - fileManager.generateFile("config/EconomyLite/data.conf"); - fileManager.generateFile("config/EconomyLite/businesses.conf"); - - fileManager.loadFile(FileType.CONFIGURATION); - - fileManager.testDefault("Currency-Singular", "Coin"); - fileManager.testDefault("Currency-Plural", "Coins"); - fileManager.testDefault("Scoreboard", "disabled"); - fileManager.testDefault("Businesses", "enabled"); - fileManager.testDefault("Default-Currency", 0); - fileManager.testDefault("MySQL.Enabled", "disabled"); - fileManager.testDefault("MySQL.Hostname", "hostname"); - fileManager.testDefault("MySQL.Port", 3306); - fileManager.testDefault("MySQL.Database", "database"); - fileManager.testDefault("MySQL.Username", "username"); - fileManager.testDefault("MySQL.Password", "password"); - } - - //Loads all of the config options from the configuration file - private void loadConfigurationOptions() { - fileManager.loadFile(FileType.CONFIGURATION); - configOptions.put("currencySingular", fileManager.getConfigValue("Currency-Singular")); - currencySingular = configOptions.get("currencySingular"); - configOptions.put("currencyPlural", fileManager.getConfigValue("Currency-Plural")); - currencyPlural = configOptions.get("currencyPlural"); - configOptions.put("scoreboard", fileManager.getConfigValue("Scoreboard")); - configOptions.put("businesses", fileManager.getConfigValue("Businesses")); - configOptions.put("defaultCurrency", fileManager.getConfigValue("Default-Currency")); - configOptions.put("mysql.enabled", fileManager.getConfigValue("MySQL.Enabled")); - configOptions.put("mysql.hostname", fileManager.getConfigValue("MySQL.Hostname")); - configOptions.put("mysql.port", fileManager.getConfigValue("MySQL.Port")); - configOptions.put("mysql.database", fileManager.getConfigValue("MySQL.Database")); - configOptions.put("mysql.username", fileManager.getConfigValue("MySQL.Username")); - configOptions.put("mysql.password", fileManager.getConfigValue("MySQL.Password")); - } - - public static boolean optionEnabled(String optionName) { - if(configOptions.get(optionName).equalsIgnoreCase("enabled")) { - return true; - } else { - return false; - } - } - - public static String getOption(String optionName) { - if(!configOptions.containsKey(optionName)) return ""; - return configOptions.get(optionName); - } - - public static int getOptionInteger(String optionName) { - if(!configOptions.containsKey(optionName)) return 0; - try { - return Integer.parseInt(configOptions.get(optionName)); - } catch(Exception e) { - return 0; - } - } - - public static Currency getCurrency() { - if(currency == null) { - currency = new LiteCurrency(); - } - return currency; - } - - public static EconomyService getService() { - if(economyService==null) { - economyService = new LiteEconomyService(); - return economyService; - } else { - return economyService; - } - } - - public static MySQLManager getMySQL() { - return mySQL; - } - -} diff --git a/src/me/Flibio/EconomyLite/Events/BalanceChangeEvent.java b/src/me/Flibio/EconomyLite/Events/BalanceChangeEvent.java deleted file mode 100644 index 1e5c81d..0000000 --- a/src/me/Flibio/EconomyLite/Events/BalanceChangeEvent.java +++ /dev/null @@ -1,48 +0,0 @@ -package me.Flibio.EconomyLite.Events; - -import me.Flibio.EconomyLite.EconomyLite; -import org.spongepowered.api.event.Cancellable; -import org.spongepowered.api.event.cause.Cause; -import org.spongepowered.api.event.cause.NamedCause; -import org.spongepowered.api.event.impl.AbstractEvent; - -import java.util.UUID; - -public class BalanceChangeEvent extends AbstractEvent implements Cancellable { - - private boolean cancelled = false; - private UUID playerUUID; - - /** - * Sponge event called when a player's balance changes - * @param playerUUID - * The UUID of the player whose balance changed - */ - public BalanceChangeEvent(String playerUUID){ - this.playerUUID = UUID.fromString(playerUUID); - } - - @Override - public boolean isCancelled() { - return this.cancelled; - } - - @Override - public void setCancelled(boolean cancelled) { - this.cancelled = cancelled; - } - - /** - * Gets the UUID of the player whose balance changed - * @return Player's UUID - */ - public UUID getPlayerUUID(){ - return playerUUID; - } - - @Override - public Cause getCause() { - return Cause.of(NamedCause.owner(EconomyLite.access)); - } - -} diff --git a/src/me/Flibio/EconomyLite/Events/LiteEconomyTransactionEvent.java b/src/me/Flibio/EconomyLite/Events/LiteEconomyTransactionEvent.java deleted file mode 100644 index 18cc9a2..0000000 --- a/src/me/Flibio/EconomyLite/Events/LiteEconomyTransactionEvent.java +++ /dev/null @@ -1,27 +0,0 @@ -package me.Flibio.EconomyLite.Events; - -import me.Flibio.EconomyLite.EconomyLite; -import org.spongepowered.api.event.cause.Cause; -import org.spongepowered.api.event.cause.NamedCause; -import org.spongepowered.api.event.economy.EconomyTransactionEvent; -import org.spongepowered.api.service.economy.transaction.TransactionResult; - -public class LiteEconomyTransactionEvent implements EconomyTransactionEvent { - - private TransactionResult result; - - public LiteEconomyTransactionEvent(TransactionResult result) { - this.result = result; - } - - @Override - public Cause getCause() { - return Cause.of(NamedCause.owner(EconomyLite.access)); - } - - @Override - public TransactionResult getTransactionResult() { - return this.result; - } - -} diff --git a/src/me/Flibio/EconomyLite/Listeners/BalanceChangeListener.java b/src/me/Flibio/EconomyLite/Listeners/BalanceChangeListener.java deleted file mode 100644 index 4d72444..0000000 --- a/src/me/Flibio/EconomyLite/Listeners/BalanceChangeListener.java +++ /dev/null @@ -1,52 +0,0 @@ -package me.Flibio.EconomyLite.Listeners; - -import me.Flibio.EconomyLite.EconomyLite; -import me.Flibio.EconomyLite.Events.BalanceChangeEvent; -import me.Flibio.EconomyLite.Utils.ScoreboardUtils; - -import org.spongepowered.api.entity.living.player.Player; -import org.spongepowered.api.event.Listener; -import org.spongepowered.api.service.economy.Currency; -import org.spongepowered.api.service.economy.EconomyService; -import org.spongepowered.api.service.economy.account.UniqueAccount; -import org.spongepowered.api.text.Text; -import org.spongepowered.api.text.format.TextColors; - -import java.math.RoundingMode; -import java.util.HashMap; -import java.util.Optional; -import java.util.UUID; - -public class BalanceChangeListener { - - private EconomyService economyService = EconomyLite.getService(); - private Currency currency = EconomyLite.getService().getDefaultCurrency(); - private ScoreboardUtils scoreboardUtils = new ScoreboardUtils(); - - @Listener - public void onPlayerBalanceChange(BalanceChangeEvent event) { - UUID uuid = event.getPlayerUUID(); - - //Check if the scoreboard is enabled - if(EconomyLite.optionEnabled("scoreboard")) { - //Get the player's balance - Text displayName = Text.builder("EconomyLite").color(TextColors.YELLOW).build(); - Text balanceLabel = Text.builder("Balance: ").color(TextColors.GREEN).build(); - - HashMap objectiveValues = new HashMap(); - Optional uOpt = economyService.getOrCreateAccount(uuid); - if(uOpt.isPresent()) { - UniqueAccount account = uOpt.get(); - objectiveValues.put(balanceLabel, account.getBalance(currency).setScale(0, RoundingMode.HALF_UP).intValue()); - - //Get the player - Optional player = EconomyLite.access.game.getServer().getPlayer(uuid); - //Check if the player exists - if(!player.isPresent()) return; - - player.get().setScoreboard(scoreboardUtils.createScoreboard("EconomyLite", displayName, objectiveValues)); - } - } - } - -} diff --git a/src/me/Flibio/EconomyLite/Listeners/PlayerJoinListener.java b/src/me/Flibio/EconomyLite/Listeners/PlayerJoinListener.java deleted file mode 100644 index dcb9058..0000000 --- a/src/me/Flibio/EconomyLite/Listeners/PlayerJoinListener.java +++ /dev/null @@ -1,71 +0,0 @@ -package me.Flibio.EconomyLite.Listeners; - -import me.Flibio.EconomyLite.EconomyLite; -import me.Flibio.EconomyLite.Utils.BusinessManager; -import me.Flibio.EconomyLite.Utils.ScoreboardUtils; -import me.Flibio.EconomyLite.Utils.TextUtils; - -import org.spongepowered.api.entity.living.player.Player; -import org.spongepowered.api.event.Listener; -import org.spongepowered.api.event.network.ClientConnectionEvent; -import org.spongepowered.api.scheduler.Task.Builder; -import org.spongepowered.api.service.economy.Currency; -import org.spongepowered.api.service.economy.EconomyService; -import org.spongepowered.api.service.economy.account.UniqueAccount; -import org.spongepowered.api.text.Text; -import org.spongepowered.api.text.format.TextColors; - -import java.math.RoundingMode; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Optional; - -public class PlayerJoinListener { - - private ScoreboardUtils scoreboardUtils = new ScoreboardUtils(); - private EconomyService economyService = EconomyLite.getService(); - private Currency currency = EconomyLite.getService().getDefaultCurrency(); - private Builder taskBuilder = EconomyLite.access.game.getScheduler().createTaskBuilder(); - - @Listener - public void onPlayerJoin(ClientConnectionEvent.Join event) { - Player player = (Player) event.getTargetEntity(); - - economyService.getOrCreateAccount(player.getUniqueId()); - - //Show scoreboard if it is enabled - if(EconomyLite.optionEnabled("scoreboard")) { - Text displayName = Text.builder("EconomyLite").color(TextColors.YELLOW).build(); - Text balanceLabel = Text.builder("Balance: ").color(TextColors.GREEN).build(); - - HashMap objectiveValues = new HashMap(); - Optional uOpt = economyService.getOrCreateAccount(player.getUniqueId()); - if(uOpt.isPresent()) { - UniqueAccount account = uOpt.get(); - objectiveValues.put(balanceLabel, account.getBalance(currency).setScale(0, RoundingMode.HALF_UP).intValue()); - - player.setScoreboard(scoreboardUtils.createScoreboard("EconomyLite", displayName, objectiveValues)); - } - } - - //Check if the player has any invites - taskBuilder.execute(new Runnable() { - public void run() { - BusinessManager manager = new BusinessManager(); - TextUtils textUtils = new TextUtils(); - - ArrayList businesses = manager.getAllBusinesses(); - for(String business : businesses) { - if(manager.businessExists(business)) { - if(manager.isInvited(business, player.getUniqueId().toString())) { - //Tell player that he/she is invited - player.sendMessage(textUtils.invited(manager.getCorrectBusinessName(business))); - player.sendMessage(textUtils.clickToContinue("/business inviteAccept "+business)); - } - } - } - } - }).async().submit(EconomyLite.access); - } - -} diff --git a/src/me/Flibio/EconomyLite/Registry/CurrencyRegistryModule.java b/src/me/Flibio/EconomyLite/Registry/CurrencyRegistryModule.java deleted file mode 100644 index c671ee5..0000000 --- a/src/me/Flibio/EconomyLite/Registry/CurrencyRegistryModule.java +++ /dev/null @@ -1,23 +0,0 @@ -package me.Flibio.EconomyLite.Registry; - -import me.Flibio.EconomyLite.EconomyLite; -import org.spongepowered.api.registry.CatalogRegistryModule; -import org.spongepowered.api.service.economy.Currency; - -import java.util.*; - -public class CurrencyRegistryModule implements CatalogRegistryModule { - - @Override - public Optional getById(String id) { - Currency currency = EconomyLite.getCurrency(); - if (currency.getId().equals(id)) - return Optional.of(currency); - return Optional.empty(); - } - - @Override - public Collection getAll() { - return Collections.singleton(EconomyLite.getCurrency()); - } -} diff --git a/src/me/Flibio/EconomyLite/Utils/BusinessManager.java b/src/me/Flibio/EconomyLite/Utils/BusinessManager.java deleted file mode 100644 index 68cceaf..0000000 --- a/src/me/Flibio/EconomyLite/Utils/BusinessManager.java +++ /dev/null @@ -1,582 +0,0 @@ -package me.Flibio.EconomyLite.Utils; - -import me.Flibio.EconomyLite.EconomyLite; -import me.Flibio.EconomyLite.Utils.FileManager.FileType; -import me.Flibio.EconomyLite.Utils.MySQLManager.ChangeAction; -import ninja.leaping.configurate.ConfigurationNode; - -import java.util.ArrayList; -import java.util.List; - -public class BusinessManager { - - private FileManager fileManager; - - /** - * EconomyLite's Business API. - * - * Methods will query a MySQL Database if the EconomyLite user has opted to save data to a database. - * - * If possible, you should run these methods in a seperate thread. - */ - public BusinessManager() { - fileManager = new FileManager(); - } - - /** - * Registers a new business with EconomyLite - * @param businessName - * Name of the business to register - * @return - * Boolean based on if the method was successful or not - */ - public boolean createBusiness(String businessName) { - if(EconomyLite.access.sqlEnabled) { - //MySQL - MySQLManager mySQL = EconomyLite.getMySQL(); - if(mySQL.businessExists(businessName)) return false; - return mySQL.newBusiness(businessName); - } else { - //Load and get the business file - fileManager.loadFile(FileType.BUSINESS_DATA); - ConfigurationNode root = fileManager.getFile(FileType.BUSINESS_DATA); - //Check if business exists - if(!businessExists(businessName)) { - //Set the balance and the owner of the business - root.getNode(businessName).getNode("balance").setValue(0); - root.getNode(businessName).getNode("owners").setValue(new ArrayList()); - root.getNode(businessName).getNode("invited").setValue(new ArrayList()); - root.getNode(businessName).getNode("confirmNeeded").setValue(true); - fileManager.saveFile(FileType.BUSINESS_DATA, root); - return true; - } else { - return false; - } - } - } - - /** - * Checks if the specified business exists - * @param businessName - * Business to check - * @return - * Boolean based on if the business was found or not - */ - public boolean businessExists(String businessName) { - if(EconomyLite.access.sqlEnabled) { - MySQLManager mySQL = EconomyLite.getMySQL(); - return mySQL.businessExists(businessName); - } else { - //Load and get the businesses file - fileManager.loadFile(FileType.BUSINESS_DATA); - ConfigurationNode root = fileManager.getFile(FileType.BUSINESS_DATA); - //Check if the business name is in the business file - for(Object raw : root.getChildrenMap().keySet()) { - if(raw instanceof String) { - String business = (String) raw; - - if(business.trim().equalsIgnoreCase(businessName.trim())) { - return true; - } - } - } - return false; - } - } - - /** - * Gets the balance of the specified business - * @param businessName - * Name of the business whose balance to get - * @return - * Integer of the balance of the business(-1 if an error occured) - */ - public int getBusinessBalance(String businessName) { - if(EconomyLite.access.sqlEnabled) { - MySQLManager mySQL = EconomyLite.getMySQL(); - if(!mySQL.businessExists(businessName)) return -1; - return mySQL.getBusinessBalance(businessName); - } else { - //Check if the business exists - if(businessExists(businessName)) { - ConfigurationNode business = getBusiness(businessName); - if(business==null) return -1; - //Read the balance - ConfigurationNode balance = business.getNode("balance"); - String rawBalance = balance.getString(); - int intBalance; - try { - intBalance = Integer.parseInt(rawBalance); - } catch(NumberFormatException e) { - return -1; - } - return intBalance; - } else { - return -1; - } - } - } - - /** - * Sets a business's to an amount - * @param businessName - * The name of the business whose balance will be set - * @param amount - * What to set the businesses balance to - * @return - * Boolean based on if the method was successful or not - */ - public boolean setBusinessBalance(String businessName, int amount) { - if(EconomyLite.access.sqlEnabled) { - MySQLManager mySQL = EconomyLite.getMySQL(); - if(!mySQL.businessExists(businessName)) return false; - return mySQL.setBusinessBalance(businessName, amount); - } else { - //Load and get the business file - fileManager.loadFile(FileType.BUSINESS_DATA); - ConfigurationNode root = fileManager.getFile(FileType.BUSINESS_DATA); - //Check if business exists - if(businessExists(businessName)) { - ConfigurationNode business = getBusiness(businessName); - if(business==null) return false; - if(amount<0||amount>1000000) return false; - //Change the balance - root.getNode(business.getKey()).getNode("balance").setValue(amount); - fileManager.saveFile(FileType.BUSINESS_DATA, root); - return true; - } else { - return false; - } - } - } - - /** - * Gets a list of all owners of a business - * @param businessName - * Name of the business to retrieve owners from - * @return - * List of all owners of the specified business - */ - public ArrayList getBusinessOwners(String businessName) { - if(EconomyLite.access.sqlEnabled) { - MySQLManager mySQL = EconomyLite.getMySQL(); - return mySQL.getOwners(businessName); - } else { - //Check if business exists - if(businessExists(businessName)) { - ConfigurationNode business = getBusiness(businessName); - if(business==null) return null; - ArrayList owners = getStringListValues(business.getNode("owners")); - return owners; - } else { - return null; - } - } - } - - /** - * Checks if the specified player is an owner of the specified business - * @param businessName - * Name of the business to check - * @param uuid - * UUID of the player to search for - * @return - * Boolean based on the the player is an owner or not - */ - public boolean ownerExists(String businessName, String uuid) { - if(EconomyLite.access.sqlEnabled) { - MySQLManager mySQL = EconomyLite.getMySQL(); - if(!mySQL.businessExists(businessName)) return false; - return mySQL.getOwners(businessName).contains(uuid); - } else { - //Check if business exists - if(businessExists(businessName)) { - ConfigurationNode business = getBusiness(businessName); - if(business==null) return false; - ArrayList owners = getStringListValues(business.getNode("owners")); - if(owners.contains(uuid)) { - return true; - } else { - return false; - } - } else { - return false; - } - } - } - - /** - * Adds an owner to a business - * @param businessName - * Business whom the owner will be added to - * @param uuid - * UUID of the player to add as an owner - * @return - * Boolean based on if the method was successful or not - */ - public boolean addOwner(String businessName, String uuid) { - if(EconomyLite.access.sqlEnabled) { - MySQLManager mySQL = EconomyLite.getMySQL(); - if(!mySQL.businessExists(businessName)) return false; - return mySQL.setOwner(ChangeAction.ADD, uuid, businessName); - } else { - //Load and get the business file - fileManager.loadFile(FileType.BUSINESS_DATA); - ConfigurationNode root = fileManager.getFile(FileType.BUSINESS_DATA); - //Check if business exists - if(businessExists(businessName)) { - ConfigurationNode business = getBusiness(businessName); - if(business==null) return false; - ArrayList owners = getStringListValues(business.getNode("owners")); - owners.add(uuid); - - root.getNode(business.getKey()).getNode("owners").setValue(owners); - fileManager.saveFile(FileType.BUSINESS_DATA, root); - return true; - } else { - return false; - } - } - } - - /** - * Removes an owner from a business - * @param businessName - * Business whom the owner will be removed from - * @param uuid - * UUID of the player to remove as an owner - * @return - * Boolean based on if the method was successful or not - */ - public boolean removeOwner(String businessName, String uuid) { - if(EconomyLite.access.sqlEnabled) { - MySQLManager mySQL = EconomyLite.getMySQL(); - if(!mySQL.businessExists(businessName)) return false; - return mySQL.setOwner(ChangeAction.REMOVE, uuid, businessName); - } else { - //Load and get the business file - fileManager.loadFile(FileType.BUSINESS_DATA); - ConfigurationNode root = fileManager.getFile(FileType.BUSINESS_DATA); - //Check if business exists - if(businessExists(businessName)) { - ConfigurationNode business = getBusiness(businessName); - if(business==null) return false; - ArrayList owners = getStringListValues(business.getNode("owners")); - owners.remove(uuid); - root.getNode(business.getKey()).getNode("owners").setValue(owners); - fileManager.saveFile(FileType.BUSINESS_DATA, root); - return true; - } else { - return false; - } - } - } - - /** - * Deletes a business from EconomyLite - * @param businessName - * The business to delete - * @return - * Boolean based on if the method was successful or not - */ - public boolean deleteBusiness(String businessName) { - if(EconomyLite.access.sqlEnabled) { - MySQLManager mySQL = EconomyLite.getMySQL(); - if(!mySQL.businessExists(businessName)) return false; - return mySQL.deleteBusiness(businessName); - } else { - //Load and get the business file - fileManager.loadFile(FileType.BUSINESS_DATA); - ConfigurationNode root = fileManager.getFile(FileType.BUSINESS_DATA); - //Check if business exists - if(businessExists(businessName)) { - ConfigurationNode business = getBusiness(businessName); - if(business==null) return false; - root.getNode(business.getKey()).setValue(null); - fileManager.saveFile(FileType.BUSINESS_DATA, root); - return true; - } else { - return false; - } - } - } - - /** - * Sets if a business needs confirmation or not - * @param businessName - * Business to change confirmation of - * @param needed - * What to set the confirmation needed to - * @return - * Boolean based on if the method was successful or not - */ - public boolean setConfirmationNeeded(String businessName, boolean needed) { - if(EconomyLite.access.sqlEnabled) { - MySQLManager mySQL = EconomyLite.getMySQL(); - if(!mySQL.businessExists(businessName)) return false; - return mySQL.setConfirm(businessName, needed); - } else { - //Load and get the business file - fileManager.loadFile(FileType.BUSINESS_DATA); - ConfigurationNode root = fileManager.getFile(FileType.BUSINESS_DATA); - //Check if business exists - if(businessExists(businessName)) { - ConfigurationNode business = getBusiness(businessName); - if(business==null) return false; - root.getNode(business.getKey()).getNode("confirmNeeded").setValue(needed); - fileManager.saveFile(FileType.BUSINESS_DATA, root); - return true; - } else { - return false; - } - } - } - - /** - * Checks if a business needs confirmation to delete it - * @param businessName - * The business to check - * @return - * Boolean based on if the business needs confirmation or not - */ - public boolean confirmationNeeded(String businessName) { - if(EconomyLite.access.sqlEnabled) { - MySQLManager mySQL = EconomyLite.getMySQL(); - if(!mySQL.businessExists(businessName)) return true; - return mySQL.needsConfirm(businessName); - } else { - ConfigurationNode business = getBusiness(businessName); - if(business==null) return true; - return business.getNode("confirmNeeded").getBoolean(); - } - } - - /** - * Sets if a player is invited or not to a business - * @param businessName - * Business whose invited list will be edited - * @param uuid - * UUID of the player to change the invited status of - * @param inviteStatus - * Boolean if the player is invited or not - * @return - * Boolean based on if the method was successful or not - */ - public boolean setInvited(String businessName, String uuid, boolean inviteStatus) { - if(EconomyLite.access.sqlEnabled) { - MySQLManager mySQL = EconomyLite.getMySQL(); - if(!mySQL.businessExists(businessName)) return false; - if(inviteStatus){ - return mySQL.setInvite(ChangeAction.ADD, uuid, businessName); - } else { - return mySQL.setInvite(ChangeAction.REMOVE, uuid, businessName); - } - } - //Load and get the business file - fileManager.loadFile(FileType.BUSINESS_DATA); - ConfigurationNode root = fileManager.getFile(FileType.BUSINESS_DATA); - //Check if business exists - if(businessExists(businessName)) { - ConfigurationNode business = getBusiness(businessName); - if(business==null) return false; - ArrayList invitedList = getStringListValues(business.getNode("invited")); - ArrayList invited = new ArrayList(); - for(String invitee : invitedList) { - invited.add(invitee); - } - if(inviteStatus) { - invited.add(uuid); - } else { - invited.remove(uuid); - } - root.getNode(business.getKey()).getNode("invited").setValue(invited); - fileManager.saveFile(FileType.BUSINESS_DATA, root); - return true; - } else { - return false; - } - } - - /** - * Checks if a player was invited to join a business - * @param businessName - * The business to check for invite - * @param uuid - * UUID of the player to check for - * @return - * Boolean based on if the player was invited or not - */ - public boolean isInvited(String businessName, String uuid) { - if(EconomyLite.access.sqlEnabled) { - MySQLManager mySQL = EconomyLite.getMySQL(); - if(!mySQL.businessExists(businessName)) return false; - return mySQL.getInvited(businessName).contains(uuid); - } else { - //Check if business exists - if(businessExists(businessName)) { - ConfigurationNode business = getBusiness(businessName); - if(business==null) return false; - ArrayList invited = getStringListValues(business.getNode("invited")); - if(invited.contains(uuid)) { - return true; - } else { - return false; - } - } else { - return false; - } - } - } - - /** - * Gets a business from the EconomyLite data file - * @param businessName - * Business which to search for - * @return - * ConfigurationNode of the business, null if not found or an error occured - */ - private ConfigurationNode getBusiness(String businessName) { - if(businessExists(businessName)) { - //Load and get the business file - fileManager.loadFile(FileType.BUSINESS_DATA); - ConfigurationNode root = fileManager.getFile(FileType.BUSINESS_DATA); - //Loop through the children and find the business - for(ConfigurationNode business : root.getChildrenMap().values()) { - Object raw = business.getKey(); - if(raw instanceof String) { - if(((String) raw).equalsIgnoreCase(businessName)) { - return business; - } - } - } - return null; - } else { - return null; - } - } - - /** - * Gets the correct capitilaztion of a business name - * @param businessName - * The business name to capitlize - * @return - * Correctly capitalized business name, empty string if the business is not found - */ - public String getCorrectBusinessName(String businessName) { - if(EconomyLite.access.sqlEnabled) { - MySQLManager mySQL = EconomyLite.getMySQL(); - if(!mySQL.businessExists(businessName)) return ""; - return mySQL.getCapitalizedBusinessName(businessName); - } else { - if(businessExists(businessName)) { - ConfigurationNode business = getBusiness(businessName); - if(business==null) return ""; - Object raw = business.getKey(); - if(raw instanceof String) { - return (String) raw; - } else { - return ""; - } - } else { - return ""; - } - } - } - - /** - * Gets a list of all the businesses for one owner - * @param owner - * The owner to check for - * @return - * An String ArrayList which contains all of the business names the owner is a part of - */ - public ArrayList getBusinesses(String owner) { - if(EconomyLite.access.sqlEnabled) { - MySQLManager mySQL = EconomyLite.getMySQL(); - return mySQL.getBusinesses(owner); - } else { - //Load and get the business file - fileManager.loadFile(FileType.BUSINESS_DATA); - ConfigurationNode root = fileManager.getFile(FileType.BUSINESS_DATA); - ArrayList businesses = new ArrayList(); - //Loop through the children and find the business - for(ConfigurationNode business : root.getChildrenMap().values()) { - Object raw = business.getKey(); - if(raw instanceof String) { - String businessName = (String) raw; - if(ownerExists(businessName,owner)) { - businesses.add(businessName); - } - } - } - return businesses; - } - } - - /** - * Adds the specified amount of currency to the specified business - * @param uuid - * Name of the business who will receive the currency - * @param amount - * Amount of currency the business will receive - * @return - * If the method failed or was successful - */ - public boolean addCurrency(String id, int amount) { - return setBusinessBalance(id, getBusinessBalance(id) + amount); - } - - /** - * Removes the specified amount of currency from the specified business - * @param uuid - * Name of the business whom the currency will be taken from - * @param amount - * Amount of currency the business will lose - * @return - * If the method failed or was successful - */ - public boolean removeCurrency(String id, int amount) { - return setBusinessBalance(id, getBusinessBalance(id) - amount); - } - - /** - * Gets a list of all the businesses - * @return - * An String ArrayList which contains all of the business names - */ - public ArrayList getAllBusinesses() { - if(EconomyLite.access.sqlEnabled) { - MySQLManager mySQL = EconomyLite.getMySQL(); - return mySQL.getAllBusinesses(); - } else { - //Load and get the business file - fileManager.loadFile(FileType.BUSINESS_DATA); - ConfigurationNode root = fileManager.getFile(FileType.BUSINESS_DATA); - ArrayList businesses = new ArrayList(); - //Loop through the children and find the business - for(ConfigurationNode business : root.getChildrenMap().values()) { - Object raw = business.getKey(); - if(raw instanceof String) { - String businessName = (String) raw; - businesses.add(businessName); - } - } - return businesses; - } - } - - private ArrayList getStringListValues(ConfigurationNode node) { - Object rawList = node.getValue(); - ArrayList toReturn = new ArrayList(); - - if(rawList instanceof List) { - List list = (List) rawList; - for(Object rawObject : list) { - if(rawObject instanceof String) { - toReturn.add((String) rawObject); - } - } - } - return toReturn; - } -} \ No newline at end of file diff --git a/src/me/Flibio/EconomyLite/Utils/FileManager.java b/src/me/Flibio/EconomyLite/Utils/FileManager.java deleted file mode 100644 index d02270c..0000000 --- a/src/me/Flibio/EconomyLite/Utils/FileManager.java +++ /dev/null @@ -1,183 +0,0 @@ -package me.Flibio.EconomyLite.Utils; - -import java.io.File; -import java.io.IOException; - -import me.Flibio.EconomyLite.EconomyLite; -import ninja.leaping.configurate.ConfigurationNode; -import ninja.leaping.configurate.hocon.HoconConfigurationLoader; -import ninja.leaping.configurate.loader.ConfigurationLoader; - -import org.slf4j.Logger; - -import com.typesafe.config.ConfigException; - - -public class FileManager { - - //Declare FileType enumerator - public enum FileType { - CONFIGURATION, - DATA, - BUSINESS_DATA - } - - private Logger logger; - private ConfigurationNode configRoot; - private ConfigurationNode businessRoot; - private ConfigurationNode dataRoot; - - public FileManager() { - this.logger = EconomyLite.access.logger; - } - - public void testDefault(String path, Object value) { - if(configRoot!=null) { - //Check if the configuration file doesn't contain the path - if(configRoot.getNode((Object[]) path.split("\\.")).getValue()==null) { - //Set the path to the default value - configRoot.getNode((Object[]) path.split("\\.")).setValue(value); - saveFile(FileType.CONFIGURATION,configRoot); - } - } - } - - public String getConfigValue(String path) { - if(configRoot!=null) { - //Check if the configuration file contains the path - if(configRoot.getNode((Object[]) path.split("\\.")).getValue()!=null){ - //Get the value and return it - return configRoot.getNode((Object[]) path.split("\\.")).getString(); - } else { - return ""; - } - } else { - return ""; - } - } - - public void generateFolder(String path) { - File folder = new File(path); - try{ - if(!folder.exists()){ - logger.info(path+" not found, generating..."); - if(folder.mkdir()){ - logger.info("Successfully generated "+path); - } else { - logger.warn("Error generating "+path); - } - - } - } catch(Exception e){ - logger.warn("Error generating "+path+": "); - logger.warn(e.getMessage()); - } - } - - public void generateFile(String path) { - File file = new File(path); - try{ - if(!file.exists()){ - logger.info(path+" not found, generating..."); - try { - file.createNewFile(); - logger.info("Successfully generated "+path); - } catch (IOException e) { - logger.error("Error generating "+path); - logger.error(e.getMessage()); - } - } - } catch(Exception e){ - logger.warn("Error generating "+path+": "); - logger.warn(e.getMessage()); - } - } - - public void loadFile(FileType file) { - String fileName = ""; - switch(file) { - case CONFIGURATION: - fileName = "config.conf"; - break; - - case DATA: - fileName = "data.conf"; - break; - - case BUSINESS_DATA: - fileName = "businesses.conf"; - break; - } - - ConfigurationLoader manager = HoconConfigurationLoader.builder().setFile(new File("config/EconomyLite/"+fileName)).build(); - ConfigurationNode root; - try { - root = manager.load(); - } catch (IOException e) { - logger.error("Error loading "+fileName+"!"); - logger.error(e.getMessage()); - return; - } catch (ConfigException e) { - logger.error("Error loading "+fileName+"!"); - logger.error("Did you edit something wrong? For a blank value use double quotes."); - logger.error(e.getMessage()); - return; - } - - switch(file) { - case CONFIGURATION: - configRoot = root; - break; - - case DATA: - dataRoot = root; - break; - - case BUSINESS_DATA: - businessRoot = root; - break; - } - } - - public ConfigurationNode getFile(FileType file) { - switch(file) { - case CONFIGURATION: - return configRoot; - - case DATA: - return dataRoot; - - case BUSINESS_DATA: - return businessRoot; - - default: - return null; - } - } - - public void saveFile(FileType file, ConfigurationNode root) { - String fileName = ""; - switch(file) { - case CONFIGURATION: - fileName = "config.conf"; - break; - - case DATA: - fileName = "data.conf"; - break; - - case BUSINESS_DATA: - fileName = "businesses.conf"; - break; - } - ConfigurationLoader manager = HoconConfigurationLoader.builder().setFile(new File("config/EconomyLite/"+fileName)).build(); - - try { - manager.save(root); - } catch (IOException e) { - logger.error("Error saving "+fileName+"!"); - logger.error(e.getMessage()); - } - } - -} diff --git a/src/me/Flibio/EconomyLite/Utils/MySQLManager.java b/src/me/Flibio/EconomyLite/Utils/MySQLManager.java deleted file mode 100644 index 7fa4a9e..0000000 --- a/src/me/Flibio/EconomyLite/Utils/MySQLManager.java +++ /dev/null @@ -1,547 +0,0 @@ -package me.Flibio.EconomyLite.Utils; - -import me.Flibio.EconomyLite.EconomyLite; - -import org.slf4j.Logger; -import org.spongepowered.api.service.sql.SqlService; - -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; -import java.util.ArrayList; - -import javax.sql.DataSource; - -public class MySQLManager { - - public enum ChangeAction { - REMOVE,ADD - } - - private String hostname; - private String port; - private String database; - private String username; - private String password; - - private Connection con; - private Statement statement; - private SqlService sqlService; - - private Logger logger = EconomyLite.access.logger; - - public MySQLManager(String hostname, String port, String database, - String username, String password, SqlService sql) { - //Set the connection variables - this.hostname = hostname; - this.port = port; - this.database = database; - this.username = username; - this.password = password; - - //Set the sql service variable - sqlService = sql; - - //Open a connection - con = openConnection(); - createStatement(); - if(statement!=null){ - try { - PreparedStatement ps = con.prepareStatement("CREATE TABLE IF NOT EXISTS EconomyLite(uuid VARCHAR(100), currency INT(100))"); - ps.executeUpdate(); - PreparedStatement ps2 = con.prepareStatement("CREATE TABLE IF NOT EXISTS EconomyLiteBusinesses(name VARCHAR(1000),balance INT(100),needConfirm VARCHAR(5))"); - ps2.executeUpdate(); - PreparedStatement ps3 = con.prepareStatement("CREATE TABLE IF NOT EXISTS EconomyLiteBusinessOwners(uuid VARCHAR(100), business VARCHAR(1000))"); - ps3.executeUpdate(); - PreparedStatement ps4 = con.prepareStatement("CREATE TABLE IF NOT EXISTS EconomyLiteBusinessInvited(uuid VARCHAR(100), business VARCHAR(1000))"); - ps4.executeUpdate(); - } catch (SQLException e) { - logger.error("Error creating EconomyLite databases..."); - logger.error(e.getMessage()); - } - } - closeConnection(); - } - //Generic-- - private Connection openConnection() { - try { - DataSource source = sqlService.getDataSource("jdbc:mysql://"+hostname+":"+port+"/"+database+"?user="+username+"&password="+password); - return source.getConnection(); - } catch (SQLException e) { - logger.error("Error opening MySQL connection..."); - logger.error("Invalid credentials, hostname, database?"); - logger.error(e.getMessage()); - return null; - } - } - - private void createStatement() { - if(con == null) return; - try { - statement = con.createStatement(); - } catch (SQLException e) { - logger.error("Error creating MySQL statement..."); - logger.error(e.getMessage()); - } - } - - private void closeConnection(){ - try { - con.close(); - } catch (SQLException e) { - logger.error("Error closing MySQL connection..."); - logger.error(e.getMessage()); - } - } - - private void reconnect() { - closeConnection(); - con = openConnection(); - createStatement(); - } - //Players-- - public boolean playerExists(String uuid) { - reconnect(); - ResultSet res; - try { - PreparedStatement ps = con.prepareStatement("SELECT uuid FROM EconomyLite WHERE uuid = ?"); - ps.setString(1, uuid); - res = ps.executeQuery(); - if(!(res.next())) { - closeConnection(); - return false; - } else { - closeConnection(); - return true; - } - } catch (SQLException e) { - logger.error("Error checking if player exists..."); - logger.error(e.getMessage()); - closeConnection(); - return false; - } - } - - public int getBalance(String uuid) { - //Make sure the player exists - if(!playerExists(uuid)) { - return -1; - } - reconnect(); - ResultSet res; - try { - PreparedStatement ps = con.prepareStatement("SELECT currency FROM EconomyLite WHERE uuid = ?"); - ps.setString(1, uuid); - res = ps.executeQuery(); - res.next(); - closeConnection(); - return res.getInt("currency"); - } catch (SQLException e) { - logger.error("Error getting currency of player..."); - logger.error(e.getMessage()); - closeConnection(); - return -1; - } - } - - public boolean newPlayer(String uuid) { - //Make sure the player doesn't exist - if(playerExists(uuid)) { - return false; - } - reconnect(); - try { - PreparedStatement ps = con.prepareStatement("INSERT INTO EconomyLite (`uuid`, `currency`) VALUES (?, '0');"); - ps.setString(1, uuid); - ps.executeUpdate(); - closeConnection(); - return true; - } catch (SQLException e) { - logger.error("Error registering new player..."); - logger.error(e.getMessage()); - closeConnection(); - return false; - } - } - - public boolean setBalance(String uuid, int balance) { - //Make sure the player exists - if(!playerExists(uuid)) { - return false; - } - reconnect(); - try { - PreparedStatement ps = con.prepareStatement("UPDATE EconomyLite SET currency = ? WHERE uuid = ?"); - ps.setString(1, Integer.toString(balance)); - ps.setString(2, uuid); - ps.executeUpdate(); - closeConnection(); - return true; - } catch (SQLException e) { - logger.error("Error setting currency of player..."); - logger.error(e.getMessage()); - closeConnection(); - return false; - } - } - //Businesses-- - public boolean businessExists(String name) { - reconnect(); - ResultSet res; - try { - PreparedStatement ps = con.prepareStatement("SELECT name FROM EconomyLiteBusinesses WHERE name = ?"); - ps.setString(1, name); - res = ps.executeQuery(); - if(!(res.next())) { - closeConnection(); - return false; - } else { - closeConnection(); - return true; - } - } catch (SQLException e) { - logger.error("Error checking if business exists..."); - logger.error(e.getMessage()); - closeConnection(); - return false; - } - } - - public int getBusinessBalance(String name) { - //Make sure the business exists - if(!businessExists(name)) { - return -1; - } - reconnect(); - ResultSet res; - try { - PreparedStatement ps = con.prepareStatement("SELECT balance FROM EconomyLiteBusinesses WHERE name = ?"); - ps.setString(1, name); - res = ps.executeQuery(); - res.next(); - closeConnection(); - return res.getInt("balance"); - } catch (SQLException e) { - logger.error("Error getting balance of business..."); - logger.error(e.getMessage()); - closeConnection(); - return -1; - } - } - - public boolean newBusiness(String name) { - //Make sure the business doesn't exist - if(businessExists(name)) { - return false; - } - reconnect(); - try { - PreparedStatement ps = con.prepareStatement("INSERT INTO EconomyLiteBusinesses (`name`, `balance`, `needConfirm`) VALUES (?, '0', 'true');"); - ps.setString(1, name); - ps.executeUpdate(); - closeConnection(); - return true; - } catch (SQLException e) { - logger.error("Error registering new business..."); - logger.error(e.getMessage()); - closeConnection(); - return false; - } - } - - public boolean setBusinessBalance(String name, int balance) { - //Make sure the business exists - if(!businessExists(name)) { - return false; - } - reconnect(); - try { - PreparedStatement ps = con.prepareStatement("UPDATE EconomyLiteBusinesses SET balance = ? WHERE name = ?"); - ps.setString(1, Integer.toString(balance)); - ps.setString(2, name); - ps.executeUpdate(); - closeConnection(); - return true; - } catch (SQLException e) { - logger.error("Error setting balance of business..."); - logger.error(e.getMessage()); - closeConnection(); - return false; - } - } - - public boolean deleteBusiness(String name) { - //Make sure the business exists - if(!businessExists(name)) { - return false; - } - reconnect(); - try { - PreparedStatement ps = con.prepareStatement("DELETE FROM EconomyLiteBusinesses WHERE name = ?"); - ps.setString(1, name); - ps.executeUpdate(); - PreparedStatement ps2 = con.prepareStatement("DELETE FROM EconomyLiteBusinessOwners WHERE business = ?"); - ps2.setString(1, name); - ps2.executeUpdate(); - PreparedStatement ps3 = con.prepareStatement("DELETE FROM EconomyLiteBusinessInvited WHERE business = ?"); - ps3.setString(1, name); - ps3.executeUpdate(); - closeConnection(); - return true; - } catch (SQLException e) { - logger.error("Error deleting business..."); - logger.error(e.getMessage()); - closeConnection(); - return false; - } - } - - public String getCapitalizedBusinessName(String name) { - //Make sure the business exists - if(!businessExists(name)) { - return ""; - } - reconnect(); - ResultSet res; - try { - PreparedStatement ps = con.prepareStatement("SELECT name FROM EconomyLiteBusinesses WHERE name = ?"); - ps.setString(1, name); - res = ps.executeQuery(); - res.next(); - closeConnection(); - return res.getString("name"); - } catch (SQLException e) { - logger.error("Error getting name of business..."); - logger.error(e.getMessage()); - closeConnection(); - return ""; - } - } - - public boolean needsConfirm(String business) { - if(!businessExists(business)) { - return true; - } - reconnect(); - ResultSet res; - try { - PreparedStatement ps = con.prepareStatement("SELECT needConfirm FROM EconomyLiteBusinesses WHERE name = ?"); - ps.setString(1, business); - res = ps.executeQuery(); - res.next(); - closeConnection(); - return res.getBoolean("needConfirm"); - } catch (SQLException e) { - logger.error("Error getting need confirm of business..."); - logger.error(e.getMessage()); - closeConnection(); - return true; - } - } - - public boolean setConfirm(String business, boolean needConfirm) { - //Make sure the business exists - if(!businessExists(business)) { - return false; - } - reconnect(); - try { - PreparedStatement ps = con.prepareStatement("UPDATE EconomyLiteBusinesses SET needConfirm = ? WHERE name = ?"); - ps.setString(1, Boolean.toString(needConfirm)); - ps.setString(2, business); - ps.executeUpdate(); - closeConnection(); - return true; - } catch (SQLException e) { - logger.error("Error setting need confirm of business..."); - logger.error(e.getMessage()); - closeConnection(); - return false; - } - } - - public ArrayList getAllBusinesses() { - ArrayList businesses = new ArrayList(); - reconnect(); - ResultSet res; - try { - PreparedStatement ps = con.prepareStatement("SELECT name FROM EconomyLiteBusinesses"); - res = ps.executeQuery(); - while(res.next()) { - businesses.add(res.getString("name")); - } - closeConnection(); - return businesses; - } catch (SQLException e) { - logger.error("Error getting businesses..."); - logger.error(e.getMessage()); - closeConnection(); - return businesses; - } - } - - public ArrayList getBusinesses(String owner) { - ArrayList businesses = new ArrayList(); - reconnect(); - ResultSet res; - try { - PreparedStatement ps = con.prepareStatement("SELECT name FROM EconomyLiteBusinesses"); - res = ps.executeQuery(); - while(res.next()) { - String name = res.getString("name"); - if(getOwners(name).contains(owner)) { - businesses.add(name); - } - } - closeConnection(); - return businesses; - } catch (SQLException e) { - logger.error("Error getting businesses..."); - logger.error(e.getMessage()); - closeConnection(); - return businesses; - } - } - - public ArrayList getOwners(String business) { - ArrayList owners = new ArrayList(); - if(!businessExists(business)) { - return owners; - } - reconnect(); - ResultSet res; - try { - PreparedStatement ps = con.prepareStatement("SELECT uuid FROM EconomyLiteBusinessOwners WHERE business = ?"); - ps.setString(1, business); - res = ps.executeQuery(); - while(res.next()) { - owners.add(res.getString("uuid")); - } - closeConnection(); - return owners; - } catch (SQLException e) { - logger.error("Error getting owners..."); - logger.error(e.getMessage()); - closeConnection(); - return owners; - } - } - - public ArrayList getInvited(String business) { - ArrayList invited = new ArrayList(); - if(!businessExists(business)) { - return invited; - } - reconnect(); - ResultSet res; - try { - PreparedStatement ps = con.prepareStatement("SELECT uuid FROM EconomyLiteBusinessInvited WHERE business = ?"); - ps.setString(1, business); - res = ps.executeQuery(); - while(res.next()) { - invited.add(res.getString("uuid")); - } - closeConnection(); - return invited; - } catch (SQLException e) { - logger.error("Error getting invited..."); - logger.error(e.getMessage()); - closeConnection(); - return invited; - } - } - - public boolean setOwner(ChangeAction action, String owner, String business) { - if(!businessExists(business)) { - return false; - } - if(action.equals(ChangeAction.REMOVE)) { - //Delete the user - reconnect(); - try { - PreparedStatement ps = con.prepareStatement("DELETE FROM EconomyLiteBusinessOwners WHERE business = ? AND uuid = ?"); - ps.setString(1, business); - ps.setString(2, owner); - ps.executeUpdate(); - closeConnection(); - return true; - } catch (SQLException e) { - logger.error("Error setting owner..."); - logger.error(e.getMessage()); - closeConnection(); - return false; - } - } else if(action.equals(ChangeAction.ADD)) { - //Add the user - if(getOwners(business).contains(owner)) { - //Owner exists - return false; - } else { - reconnect(); - try { - PreparedStatement ps = con.prepareStatement("INSERT INTO EconomyLiteBusinessOwners (`uuid`, `business`) VALUES (?, ?);"); - ps.setString(1, owner); - ps.setString(2, business); - ps.executeUpdate(); - closeConnection(); - return true; - } catch (SQLException e) { - logger.error("Error setting owner..."); - logger.error(e.getMessage()); - closeConnection(); - return false; - } - } - } else { - return false; - } - } - - public boolean setInvite(ChangeAction action, String owner, String business) { - if(!businessExists(business)) { - return false; - } - if(action.equals(ChangeAction.REMOVE)) { - //Delete the user - reconnect(); - try { - PreparedStatement ps = con.prepareStatement("DELETE FROM EconomyLiteBusinessInvited WHERE business = ? AND uuid = ?"); - ps.setString(1, business); - ps.setString(2, owner); - ps.executeUpdate(); - closeConnection(); - return true; - } catch (SQLException e) { - logger.error("Error setting invited..."); - logger.error(e.getMessage()); - closeConnection(); - return false; - } - } else if(action.equals(ChangeAction.ADD)) { - //Add the user - if(getInvited(business).contains(owner)) { - //Owner exists - return false; - } else { - reconnect(); - try { - PreparedStatement ps = con.prepareStatement("INSERT INTO EconomyLiteBusinessInvited (`uuid`, `business`) VALUES (?, ?);"); - ps.setString(1, owner); - ps.setString(2, business); - ps.executeUpdate(); - closeConnection(); - return true; - } catch (SQLException e) { - logger.error("Error setting invited..."); - logger.error(e.getMessage()); - closeConnection(); - return false; - } - } - } else { - return false; - } - } -} \ No newline at end of file diff --git a/src/me/Flibio/EconomyLite/Utils/PlayerManager.java b/src/me/Flibio/EconomyLite/Utils/PlayerManager.java deleted file mode 100644 index 985e147..0000000 --- a/src/me/Flibio/EconomyLite/Utils/PlayerManager.java +++ /dev/null @@ -1,283 +0,0 @@ -package me.Flibio.EconomyLite.Utils; - -import me.Flibio.EconomyLite.EconomyLite; -import me.Flibio.EconomyLite.Events.BalanceChangeEvent; -import me.Flibio.EconomyLite.Utils.FileManager.FileType; -import ninja.leaping.configurate.ConfigurationNode; - -import org.slf4j.Logger; -import org.spongepowered.api.Game; -import org.spongepowered.api.profile.GameProfile; -import org.spongepowered.api.profile.GameProfileManager; - -import java.util.UUID; -import java.util.concurrent.ExecutionException; - -public class PlayerManager { - - private Logger logger; - private FileManager fileManager; - private Game game; - - /** - * EconomyLite's Player API. - * - * Methods will query a MySQL Database if the EconomyLite user has opted to save data to a database. - * - * If possible, you should run these methods in a seperate thread. - */ - public PlayerManager() { - this.game = EconomyLite.access.game; - this.logger = EconomyLite.access.logger; - - fileManager = new FileManager(); - } - - /** - * Looks up a player's UUID - * @param name - * Name of the player whom to lookup - * @return - * String of the UUID found(blank string if an error occured) - */ - public String getUUID(String name) { - GameProfileManager manager = game.getServer().getGameProfileManager(); - GameProfile profile; - try { - profile = manager.get(name).get(); - } catch (InterruptedException | ExecutionException e) { - logger.error("Error getting player's UUID"); - return ""; - } - return profile.getUniqueId().toString(); - } - - /** - * Looks up a player's name - * @param uuid - * UUID of the player whom to lookup - * @return - * Name of the corresponding player - */ - public String getName(String uuid) { - GameProfileManager manager = game.getServer().getGameProfileManager(); - GameProfile profile; - try { - profile = manager.get(UUID.fromString(uuid)).get(); - } catch (InterruptedException | ExecutionException e) { - logger.error("Error getting player's name"); - return ""; - } - return profile.getName().toString(); - } - - /** - * Sets the balance of the given player to the given amount - * @param uuid - * UUID of the player whose balance will be changed - * @param balance - * What the player's balance will be set to - * @return - * If the method failed or was successful - */ - public boolean setBalance(String uuid, int balance) { - //Check if the balance is withing parameters - if(balance<0||balance>1000000) return false; - if(EconomyLite.access.sqlEnabled) { - //Use MySQL - MySQLManager mySQL = EconomyLite.getMySQL(); - if(mySQL.playerExists(uuid)) { - //Change balance - if(!mySQL.setBalance(uuid, balance)) return false; - game.getEventManager().post(new BalanceChangeEvent(uuid)); - return true; - } else { - //Register player - if(!mySQL.newPlayer(uuid)) return false; - if(!mySQL.setBalance(uuid, balance)) return false; - game.getEventManager().post(new BalanceChangeEvent(uuid)); - return true; - } - } else { - //Use local file - fileManager.loadFile(FileType.DATA); - ConfigurationNode root = fileManager.getFile(FileType.DATA); - - //Check if the player exists - if(playerExists(uuid)) { - //Player exists - change balance - root.getNode(uuid).getNode("balance").setValue(balance); - fileManager.saveFile(FileType.DATA, root); - //Post a balance change event with the player's uuid - game.getEventManager().post(new BalanceChangeEvent(uuid)); - return true; - } else { - //Player doesn't exists - register player - if(registerPlayer(uuid,balance)) { - //Success! - game.getEventManager().post(new BalanceChangeEvent(uuid)); - return true; - } else { - //Failed - return false; - } - } - } - - } - - /** - * Registers a player with EconomyLite - * @param uuid - * UUID of the player to register - * @return - * Boolean based on if the command was successful or not - */ - public boolean registerPlayer(String uuid) { - if(EconomyLite.access.sqlEnabled) { - //MySQL - MySQLManager mySQL = EconomyLite.getMySQL(); - if(mySQL.playerExists(uuid)) return false; - return mySQL.newPlayer(uuid); - } else { - //Use local file - fileManager.loadFile(FileType.DATA); - ConfigurationNode root = fileManager.getFile(FileType.DATA); - - //Check if the player exists - if(playerExists(uuid)) { - //Player already exists - return false; - } else { - //Register the player - root.getNode(uuid).getNode("balance").setValue(0); - fileManager.saveFile(FileType.DATA, root); - return true; - } - } - } - - /** - * Registers a new player with a preset balance - * @param uuid - * UUID of the player to register - * @param balance - * The balance that the player will be set to - * @return - * If the method was successful or not - */ - public boolean registerPlayer(String uuid, int balance) { - if(EconomyLite.access.sqlEnabled) { - //MySQL - MySQLManager mySQL = EconomyLite.getMySQL(); - if(mySQL.playerExists(uuid)) return false; - if(!mySQL.newPlayer(uuid)) return false; - return mySQL.setBalance(uuid, balance); - } else { - //Use local file - fileManager.loadFile(FileType.DATA); - ConfigurationNode root = fileManager.getFile(FileType.DATA); - - //Check if the player exists - if(playerExists(uuid)) { - //Player already exists - return false; - } else { - //Register the player - root.getNode(uuid).getNode("balance").setValue(balance); - fileManager.saveFile(FileType.DATA, root); - return true; - } - } - } - - /** - * Checks if the given player has data stored in the system - * @param uuid - * UUID of the player to check - * @return - * If the player was found or not - */ - public boolean playerExists(String uuid) { - if(EconomyLite.optionEnabled("mysql.enabled")) { - //Use MySQL - MySQLManager mySQL = EconomyLite.getMySQL(); - return mySQL.playerExists(uuid); - } else { - //Use local file - fileManager.loadFile(FileType.DATA); - ConfigurationNode root = fileManager.getFile(FileType.DATA); - - //Check if the uuid is found in the file - if(root.getChildrenMap().containsKey(uuid)) { - return true; - } else { - return false; - } - - } - - } - - /** - * Checks the balance of the given player - * @param uuid - * UUID of the player whose balance will be checked - * @return - * The balance of the player (-1 will be returned if there was an error) - */ - public int getBalance(String uuid) { - if(EconomyLite.optionEnabled("mysql.enabled")) { - //Use MySQL - MySQLManager mySQL = EconomyLite.getMySQL(); - if(!mySQL.playerExists(uuid)) return -1; - return mySQL.getBalance(uuid); - } else { - //Use local file - fileManager.loadFile(FileType.DATA); - ConfigurationNode root = fileManager.getFile(FileType.DATA); - - //Check if the player exists - if(playerExists(uuid)) { - //Retrieve their balance - String raw = root.getNode(uuid).getNode("balance").getString(); - int balance = -1; - try { - balance = Integer.parseInt(raw); - } catch(NumberFormatException e) { - logger.error("Error getting player balance!"); - logger.error(e.getMessage()); - } - return balance; - } else { - return -1; - } - } - } - - /** - * Adds the specified amount of currency to the specified player - * @param uuid - * UUID of the player who will receive the currency - * @param amount - * Amount of currency the player will receive - * @return - * If the method failed or was successful - */ - public boolean addCurrency(String uuid, int amount) { - return setBalance(uuid, getBalance(uuid) + amount); - } - - /** - * Removes the specified amount of currency from the specified player - * @param uuid - * UUID of the player whom the currency will be taken from - * @param amount - * Amount of currency the player will lose - * @return - * If the method failed or was successful - */ - public boolean removeCurrency(String uuid, int amount) { - return setBalance(uuid, getBalance(uuid) - amount); - } -} \ No newline at end of file diff --git a/src/me/Flibio/EconomyLite/Utils/ScoreboardUtils.java b/src/me/Flibio/EconomyLite/Utils/ScoreboardUtils.java deleted file mode 100644 index 307f473..0000000 --- a/src/me/Flibio/EconomyLite/Utils/ScoreboardUtils.java +++ /dev/null @@ -1,47 +0,0 @@ -package me.Flibio.EconomyLite.Utils; - -import me.Flibio.EconomyLite.EconomyLite; - -import org.spongepowered.api.Game; -import org.spongepowered.api.scoreboard.Scoreboard; -import org.spongepowered.api.scoreboard.critieria.Criteria; -import org.spongepowered.api.scoreboard.displayslot.DisplaySlots; -import org.spongepowered.api.scoreboard.objective.Objective; -import org.spongepowered.api.text.Text; - -import java.util.HashMap; - -public class ScoreboardUtils { - - private Game game; - - /** - * Creates a new instance of the ScoreboardUtils class - * - */ - public ScoreboardUtils() { - this.game = EconomyLite.access.game; - } - - /** - * Creates a scoreboard based on the parameters that you give it - * - * @param objectiveName - * Name of the scoreboard - * @param displayName - * Display name of the scoreboard - * @param objectiveValues - * HashMap containing all of the values that will be placed in the objective - * @return Completed scoreboard - */ - public Scoreboard createScoreboard(String objectiveName, Text displayName, HashMap objectiveValues) { - Scoreboard board = game.getRegistry().createBuilder(Scoreboard.Builder.class).build(); - Objective obj = game.getRegistry().createBuilder(Objective.Builder.class).name(objectiveName).criterion(Criteria.DUMMY).displayName(displayName).build(); - for(Text name : objectiveValues.keySet()) { - int value = objectiveValues.get(name); - obj.getOrCreateScore(name).setScore(value); - } - board.updateDisplaySlot(obj,DisplaySlots.SIDEBAR); - return board; - } -} diff --git a/src/me/Flibio/EconomyLite/Utils/TextUtils.java b/src/me/Flibio/EconomyLite/Utils/TextUtils.java deleted file mode 100644 index 3da902a..0000000 --- a/src/me/Flibio/EconomyLite/Utils/TextUtils.java +++ /dev/null @@ -1,338 +0,0 @@ -package me.Flibio.EconomyLite.Utils; - -import me.Flibio.EconomyLite.EconomyLite; - -import org.spongepowered.api.text.Text; -import org.spongepowered.api.text.action.TextActions; -import org.spongepowered.api.text.format.TextColor; -import org.spongepowered.api.text.format.TextColors; - -import java.net.MalformedURLException; -import java.net.URL; - -public class TextUtils { - - public TextUtils() { - - } - - public Text basicText(String text, TextColor color) { - return Text.builder(text).color(color).build(); - } - - public Text basicText(String text) { - return Text.builder(text).build(); - } - - public Text playerBalanceText(int balance) { - Text balanceText = Text.builder("EconomyLite » ").color(TextColors.GOLD).build(); - String label = EconomyLite.access.currencyPlural; - if(balance==1) label = EconomyLite.access.currencySingular; - - balanceText = balanceText.toBuilder().append(basicText("Your balance: ",TextColors.YELLOW)).build(); - balanceText = balanceText.toBuilder().append(basicText(balance+" ",TextColors.GREEN)).build(); - balanceText = balanceText.toBuilder().append(basicText(label+"!",TextColors.DARK_GREEN)).build(); - - return balanceText; - } - - public Text playerBalanceText(int balance, String who) { - Text balanceText = Text.builder("EconomyLite » ").color(TextColors.GOLD).build(); - String label = EconomyLite.access.currencyPlural; - if(balance==1) label = EconomyLite.access.currencySingular; - - balanceText = balanceText.toBuilder().append(basicText(who+"'s balance: ",TextColors.YELLOW)).build(); - balanceText = balanceText.toBuilder().append(basicText(balance+" ",TextColors.GREEN)).build(); - balanceText = balanceText.toBuilder().append(basicText(label+"!",TextColors.DARK_GREEN)).build(); - - return balanceText; - } - - public Text businessBalanceText(String businessName, int balance) { - Text balanceText = Text.builder("EconomyLite » ").color(TextColors.GOLD).build(); - String label = EconomyLite.access.currencyPlural; - if(balance==1) label = EconomyLite.access.currencySingular; - - balanceText = balanceText.toBuilder().append(basicText(businessName+" balance: ",TextColors.YELLOW)).build(); - balanceText = balanceText.toBuilder().append(basicText(balance+" ",TextColors.GREEN)).build(); - balanceText = balanceText.toBuilder().append(basicText(label+"!",TextColors.DARK_GREEN)).build(); - - return balanceText; - } - - public Text successfulBalanceChangeText(String playerName, int balance) { - Text balanceText = Text.builder("EconomyLite » ").color(TextColors.GOLD).build(); - String label = EconomyLite.access.currencyPlural; - if(balance==1) label = EconomyLite.access.currencySingular; - - balanceText = balanceText.toBuilder().append(basicText("Successfully set ",TextColors.YELLOW)).build(); - balanceText = balanceText.toBuilder().append(basicText(playerName+"'s",TextColors.GREEN)).build(); - balanceText = balanceText.toBuilder().append(basicText(" balance to ",TextColors.YELLOW)).build(); - balanceText = balanceText.toBuilder().append(basicText(balance+" ",TextColors.GREEN)).build(); - balanceText = balanceText.toBuilder().append(basicText(label+"!",TextColors.DARK_GREEN)).build(); - - return balanceText; - } - - public Text successfulBusinessRegister(String businessName) { - Text balanceText = Text.builder("EconomyLite » ").color(TextColors.GOLD).build(); - - balanceText = balanceText.toBuilder().append(basicText("Successfully registered ",TextColors.YELLOW)).build(); - balanceText = balanceText.toBuilder().append(basicText(businessName,TextColors.GREEN)).build(); - balanceText = balanceText.toBuilder().append(basicText(" as a business!",TextColors.YELLOW)).build(); - - return balanceText; - } - - public Text updateAvailable(String version, String url) { - Text text = Text.builder("EconomyLite").color(TextColors.GREEN).build(); - text = text.toBuilder().append(basicText(" v"+version,TextColors.LIGHT_PURPLE)).build(); - text = text.toBuilder().append(basicText(" is now available to download! ",TextColors.YELLOW)).build(); - try { - text = text.toBuilder().append(Text.builder(url).color(TextColors.GRAY).onClick(TextActions.openUrl(new URL(url))).build()).build(); - } catch (MalformedURLException e) {} - - return text; - } - - public Text editingBalance(String player) { - Text text = Text.builder("EconomyLite » ").color(TextColors.GOLD).build(); - - text = text.toBuilder().append(basicText("Changing ",TextColors.YELLOW)).build(); - text = text.toBuilder().append(basicText(player+"'s ",TextColors.GREEN)).build(); - text = text.toBuilder().append(basicText(EconomyLite.access.currencySingular,TextColors.DARK_GREEN)).build(); - text = text.toBuilder().append(basicText(" balance!",TextColors.YELLOW)).build(); - - return text; - } - - public Text payOptionPlayer(String playerName, int amount) { - Text text = Text.builder("[").color(TextColors.GRAY).build(); - - text = text.toBuilder().append(basicText("Pay ", TextColors.YELLOW)).build(); - text = text.toBuilder().append(basicText("PLAYER ", TextColors.LIGHT_PURPLE)).build(); - text = text.toBuilder().append(basicText(playerName, TextColors.YELLOW)).build(); - text = text.toBuilder().append(basicText("]", TextColors.GRAY)).build(); - - Text hover = basicText("Pay the player ",TextColors.YELLOW); - hover = hover.toBuilder().append(basicText(playerName, TextColors.GREEN)).build(); - - text = text.toBuilder().onHover(TextActions.showText(hover)).build(); - text = text.toBuilder().onClick(TextActions.runCommand("/paySpecified player "+amount+" "+playerName)).build(); - - return text; - } - - public Text payOptionBusiness(String businessName, int amount) { - Text text = Text.builder("[").color(TextColors.GRAY).build(); - - text = text.toBuilder().append(basicText("Pay ", TextColors.YELLOW)).build(); - text = text.toBuilder().append(basicText("BUSINESS ", TextColors.LIGHT_PURPLE)).build(); - text = text.toBuilder().append(basicText(businessName, TextColors.YELLOW)).build(); - text = text.toBuilder().append(basicText("]", TextColors.GRAY)).build(); - - Text hover = basicText("Pay the business ",TextColors.YELLOW); - hover = hover.toBuilder().append(basicText(businessName, TextColors.GREEN)).build(); - - text = text.toBuilder().onHover(TextActions.showText(hover)).build(); - text = text.toBuilder().onClick(TextActions.runCommand("/paySpecified business "+amount+" "+businessName)).build(); - - return text; - } - - public Text payOption(String who) { - Text balanceText = Text.builder("EconomyLite » ").color(TextColors.GOLD).build(); - - balanceText = balanceText.toBuilder().append(basicText(who,TextColors.GREEN)).build(); - balanceText = balanceText.toBuilder().append(basicText(" is both a ",TextColors.YELLOW)).build(); - balanceText = balanceText.toBuilder().append(basicText("player",TextColors.LIGHT_PURPLE)).build(); - balanceText = balanceText.toBuilder().append(basicText(" and a ",TextColors.YELLOW)).build(); - balanceText = balanceText.toBuilder().append(basicText("business!",TextColors.LIGHT_PURPLE)).build(); - balanceText = balanceText.toBuilder().append(basicText(" Please select which one you would like to pay: ",TextColors.YELLOW)).build(); - - return balanceText; - } - - public Text paySuccess(String who, int amount) { - Text text = Text.builder("EconomyLite » ").color(TextColors.GOLD).build(); - String label = EconomyLite.access.currencyPlural; - if(amount==1) label = EconomyLite.access.currencySingular; - - text = text.toBuilder().append(basicText("Successfully payed ",TextColors.YELLOW)).build(); - text = text.toBuilder().append(basicText(amount+" ",TextColors.GREEN)).build(); - text = text.toBuilder().append(basicText(label,TextColors.DARK_GREEN)).build(); - text = text.toBuilder().append(basicText(" to ",TextColors.YELLOW)).build(); - text = text.toBuilder().append(basicText(who+"!",TextColors.GREEN)).build(); - - return text; - } - - public Text payed(String from, int amount) { - Text text = Text.builder("EconomyLite » ").color(TextColors.GOLD).build(); - String label = EconomyLite.access.currencyPlural; - if(amount==1) label = EconomyLite.access.currencySingular; - - text = text.toBuilder().append(basicText("You have received ",TextColors.YELLOW)).build(); - text = text.toBuilder().append(basicText(amount+" ",TextColors.GREEN)).build(); - text = text.toBuilder().append(basicText(label,TextColors.DARK_GREEN)).build(); - text = text.toBuilder().append(basicText(" from ",TextColors.YELLOW)).build(); - text = text.toBuilder().append(basicText(from+"!",TextColors.GREEN)).build(); - - return text; - } - - public Text bPayed(String from, int amount, String business) { - Text text = Text.builder("EconomyLite » ").color(TextColors.GOLD).build(); - String label = EconomyLite.access.currencyPlural; - if(amount==1) label = EconomyLite.access.currencySingular; - - text = text.toBuilder().append(basicText(business+" has received ",TextColors.YELLOW)).build(); - text = text.toBuilder().append(basicText(amount+" ",TextColors.GREEN)).build(); - text = text.toBuilder().append(basicText(label,TextColors.DARK_GREEN)).build(); - text = text.toBuilder().append(basicText(" from ",TextColors.YELLOW)).build(); - text = text.toBuilder().append(basicText(from+"!",TextColors.GREEN)).build(); - - return text; - } - - public Text leaveSuccess(String business) { - Text text = Text.builder("EconomyLite » ").color(TextColors.GOLD).build(); - - text = text.toBuilder().append(basicText("Successfully left ",TextColors.YELLOW)).build(); - text = text.toBuilder().append(basicText(business+"!",TextColors.GREEN)).build(); - - return text; - } - - public Text leaveOnlyOwner(String business) { - Text text = Text.builder("EconomyLite » ").color(TextColors.GOLD).build(); - - text = text.toBuilder().append(basicText("Since you are the only owner of ",TextColors.YELLOW)).build(); - text = text.toBuilder().append(basicText(business,TextColors.GREEN)).build(); - text = text.toBuilder().append(basicText(", it will be ",TextColors.YELLOW)).build(); - text = text.toBuilder().append(basicText("deleted!",TextColors.RED)).build(); - - return text; - } - - public Text clickToContinue(String command) { - Text text = basicText("[",TextColors.GRAY); - text = text.toBuilder().append(basicText("CLICK TO CONTINUE",TextColors.GREEN)).build(); - text = text.toBuilder().append(basicText("]",TextColors.GRAY)).build(); - - Text hover = basicText("Click me",TextColors.GREEN); - hover = hover.toBuilder().append(basicText(" to continue!", TextColors.YELLOW)).build(); - - text = text.toBuilder().onHover(TextActions.showText(hover)).build(); - text = text.toBuilder().onClick(TextActions.runCommand(command)).build(); - - return text; - } - - public Text deleteSuccess(String what) { - Text text = Text.builder("EconomyLite » ").color(TextColors.GOLD).build(); - text = text.toBuilder().append(basicText("Sucessfully ",TextColors.YELLOW)).build(); - text = text.toBuilder().append(basicText("deleted ",TextColors.RED)).build(); - text = text.toBuilder().append(basicText(what+"!",TextColors.GREEN)).build(); - - return text; - } - - public Text invited(String what) { - Text text = Text.builder("EconomyLite » ").color(TextColors.GOLD).build(); - text = text.toBuilder().append(basicText("You have been invited to join ",TextColors.YELLOW)).build(); - text = text.toBuilder().append(basicText(what+"!",TextColors.GREEN)).build(); - text = text.toBuilder().append(basicText(" Click continue to accept!",TextColors.YELLOW)).build(); - - return text; - } - - public Text inviteAccept(String what) { - Text text = Text.builder("EconomyLite » ").color(TextColors.GOLD).build(); - text = text.toBuilder().append(basicText("You are now an owner of ",TextColors.YELLOW)).build(); - text = text.toBuilder().append(basicText(what+"!",TextColors.GREEN)).build(); - - return text; - } - - public Text successfulInvite(String what, String who) { - Text text = Text.builder("EconomyLite » ").color(TextColors.GOLD).build(); - text = text.toBuilder().append(basicText("Successfully invited ",TextColors.YELLOW)).build(); - text = text.toBuilder().append(basicText(who,TextColors.GREEN)).build(); - text = text.toBuilder().append(basicText(" to join ",TextColors.YELLOW)).build(); - text = text.toBuilder().append(basicText(what+"!",TextColors.GREEN)).build(); - - return text; - } - - public Text aboutToDelete(String what) { - Text text = Text.builder("EconomyLite » ").color(TextColors.GOLD).build(); - text = text.toBuilder().append(basicText(what,TextColors.GREEN)).build(); - text = text.toBuilder().append(basicText(" is about to be ",TextColors.YELLOW)).build(); - text = text.toBuilder().append(basicText("deleted. ",TextColors.RED)).build(); - text = text.toBuilder().append(basicText("Are you sure you wish to continue?",TextColors.YELLOW)).build(); - - return text; - } - - public Text transferSuccess(String businessName, int amount) { - Text text = Text.builder("EconomyLite » ").color(TextColors.GOLD).build(); - String label = EconomyLite.access.currencyPlural; - if(amount==1) label = EconomyLite.access.currencySingular; - - text = text.toBuilder().append(basicText("Successfully transfered ",TextColors.YELLOW)).build(); - text = text.toBuilder().append(basicText(amount+" ",TextColors.GREEN)).build(); - text = text.toBuilder().append(basicText(label,TextColors.DARK_GREEN)).build(); - text = text.toBuilder().append(basicText(" from ",TextColors.YELLOW)).build(); - text = text.toBuilder().append(basicText(businessName,TextColors.GREEN)).build(); - text = text.toBuilder().append(basicText(" into your account!",TextColors.YELLOW)).build(); - - return text; - } - - public Text ownersTitle(String businessName) { - Text text = Text.builder("EconomyLite » ").color(TextColors.GOLD).build(); - - text = text.toBuilder().append(basicText("Owners of ",TextColors.YELLOW)).build(); - text = text.toBuilder().append(basicText(businessName+":",TextColors.GREEN)).build(); - - return text; - } - - public Text owner(String owner) { - Text text = Text.builder(" + ").color(TextColors.YELLOW).build(); - - text = text.toBuilder().append(basicText(owner,TextColors.GREEN)).build(); - - return text; - } - - public Text change(String change) { - Text text = Text.builder(" + ").color(TextColors.YELLOW).build(); - - text = text.toBuilder().append(basicText(change,TextColors.GREEN)).build(); - - return text; - } - - public String getDownloadUrl(String jsonRelease) { - return jsonRelease.split("browser_download_url")[1].split("}",2)[0].replaceAll("\"", "").replaceFirst(":", "").trim(); - } - - public Integer versionCompare(String str1, String str2) { - String[] vals1 = str1.split("\\."); - String[] vals2 = str2.split("\\."); - int i = 0; - - while (i < vals1.length && i < vals2.length && vals1[i].equals(vals2[i])) { - i++; - } - - if (i < vals1.length && i < vals2.length) { - int diff = Integer.valueOf(vals1[i]).compareTo(Integer.valueOf(vals2[i])); - return Integer.signum(diff); - } else { - return Integer.signum(vals1.length - vals2.length); - } - } -}