├── .gitignore ├── .travis.yml ├── HEADER.txt ├── LICENSE ├── README.md ├── build.gradle ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle └── src └── main ├── java └── io │ └── github │ └── flibio │ └── economylite │ ├── CauseFactory.java │ ├── EconomyLite.java │ ├── PluginInfo.java │ ├── TextUtils.java │ ├── api │ ├── CurrencyEconService.java │ ├── PlayerEconService.java │ └── VirtualEconService.java │ ├── bstats │ └── Metrics.java │ ├── commands │ ├── MigrateCommand.java │ ├── PayCommand.java │ ├── RefreshCommand.java │ ├── admin │ │ ├── AddCommand.java │ │ ├── EconCommand.java │ │ ├── RemoveCommand.java │ │ ├── SetAllCommand.java │ │ └── SetCommand.java │ ├── balance │ │ ├── BalTopCommand.java │ │ └── BalanceCommand.java │ ├── currency │ │ ├── CurrencyCommand.java │ │ ├── CurrencyCreateCommand.java │ │ ├── CurrencyDeleteCommand.java │ │ └── CurrencySetCommand.java │ └── virtual │ │ ├── PayVirtualCommand.java │ │ ├── VirtualAddCommand.java │ │ ├── VirtualBalanceCommand.java │ │ ├── VirtualEconCommand.java │ │ ├── VirtualPayCommand.java │ │ ├── VirtualRemoveCommand.java │ │ └── VirtualSetCommand.java │ ├── impl │ ├── CurrencyService.java │ ├── PlayerDataService.java │ ├── PlayerServiceCommon.java │ ├── VirtualDataService.java │ ├── VirtualServiceCommon.java │ └── economy │ │ ├── LiteCurrency.java │ │ ├── LiteEconomyService.java │ │ ├── account │ │ ├── LiteUniqueAccount.java │ │ └── LiteVirtualAccount.java │ │ ├── event │ │ └── LiteEconomyTransactionEvent.java │ │ ├── registry │ │ └── CurrencyRegistryModule.java │ │ └── result │ │ ├── LiteTransactionResult.java │ │ └── LiteTransferResult.java │ └── modules │ ├── Module.java │ ├── business │ └── BusinessModule.java │ ├── loan │ ├── LoanListener.java │ ├── LoanManager.java │ ├── LoanModule.java │ ├── LoanTextUtils.java │ ├── command │ │ ├── LoanAcceptCommand.java │ │ ├── LoanBalanceCommand.java │ │ ├── LoanCommand.java │ │ ├── LoanDenyCommand.java │ │ ├── LoanPayCommand.java │ │ └── LoanTakeCommand.java │ └── event │ │ └── LoanBalanceChangeEvent.java │ └── sql │ ├── PlayerSqlService.java │ ├── SqlModule.java │ └── VirtualSqlService.java └── resources └── messages.properties /.gitignore: -------------------------------------------------------------------------------- 1 | # IntelliJ 2 | .idea/ 3 | *.iml 4 | out/ 5 | 6 | # Gradle 7 | .gradle/ 8 | build/ 9 | gradle-app.setting 10 | !gradle-wrapper.jar 11 | 12 | # Eclipse 13 | bin/ 14 | tmp/ 15 | local.properties 16 | .settings/ 17 | .project 18 | .factorypath 19 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: java 2 | jdk: 3 | - oraclejdk8 4 | notifications: 5 | email: false 6 | install: 7 | - 'chmod +x ./gradlew' 8 | script: gradle shadowJar 9 | -------------------------------------------------------------------------------- /HEADER.txt: -------------------------------------------------------------------------------- 1 | This file is part of ${name}, licensed under the MIT License (MIT). See the LICENSE file at the root of this project for more information. -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2015 - 2018 Flibio 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in 13 | all copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | THE SOFTWARE. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ![EconomyLite](http://i.imgur.com/MsuOo9w.png) 2 | 3 | [![Issues](https://img.shields.io/github/issues/flibio/economylite.svg?style=flat-square)](http://www.github.com/Flibio/EconomyLite/issues/) 4 | [![Gitter](https://img.shields.io/badge/chat-on_gitter-3F51B5.svg?style=flat-square)](https://gitter.im/Flibio/EconomyLite) 5 | 6 | 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. 7 | 8 | ### Features 9 | 10 | - Drag & Drop Installation 11 | - Just drop EconomyLite into your "mods" folder with Sponge and start your server 12 | - Multi-Threaded 13 | - EconomyLite is multi-threaded for the best possible performance 14 | - Multiple Storage Options 15 | - Store your data however you like, locally or on a MySQL database 16 | - Migration 17 | - EconomyLite allows you to easily migrate your data from another economy plugin 18 | - Customizable 19 | - Much of EconomyLite can be changed to suit your needs 20 | - Virtual Management 21 | - EconomyLite includes commands to manage virtual accounts 22 | - Loans 23 | - Players can take out loans if they are running short on money 24 | - Multiple Currencies 25 | - EconomyLite has built-in support for multiple currencies 26 | 27 | ### Installation 28 | 29 | Drag and drop EconomyLite into your "mods" folder along with Sponge and start your server. The configuration files can be found in `config/EconomyLite`. 30 | 31 | --- 32 | 33 | :inbox_tray: [**Download EconomyLite**][1] 34 | 35 | :speech_balloon: [**Issues & Suggestions**][3] 36 | 37 | :newspaper: [**Forum Post**][4] 38 | 39 | :books: [**Docs**][5] 40 | 41 | :heavy_dollar_sign: [**Support Me**][6] 42 | 43 | --- 44 | 45 | ![EconomyLite Statistics](http://i.flibio.net/economylite.php) 46 | 47 | [1]: https://ore.spongepowered.org/Flibio/EconomyLite/versions 48 | [3]: https://github.com/Flibio/EconomyLite/issues 49 | [4]: https://forums.spongepowered.org/t/economylite/16502 50 | [5]: http://flibiostudio.github.io/EconomyLiteDocs/index.html 51 | [6]: http://flibio.weebly.com/support-me.html 52 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'java' 3 | id 'eclipse' 4 | id 'maven' 5 | id 'com.github.hierynomus.license' version '0.12.1' 6 | id 'net.ellune.blossom' version '1.0.1' 7 | id 'com.github.johnrengelman.shadow' version '1.2.3' 8 | } 9 | 10 | sourceCompatibility = '1.8' 11 | targetCompatibility = '1.8' 12 | 13 | group 'io.github.flibio' 14 | 15 | defaultTasks 'licenseFormat', 'shadowJar' 16 | 17 | repositories { 18 | mavenCentral() 19 | jcenter() 20 | maven { 21 | name 'Sponge API repo' 22 | url 'http://repo.spongepowered.org/maven' 23 | } 24 | maven { url "https://jitpack.io" } 25 | } 26 | 27 | dependencies { 28 | compile "org.spongepowered:spongeapi:${project.apiVersion}" 29 | compile 'com.github.flibiostudio:utils:164f3b6' 30 | } 31 | 32 | shadowJar { 33 | def bVer = System.getenv("BUILD_NUMBER") ?: version 34 | def buildNumber = '' 35 | if (System.getenv("TRAVIS") != null) { 36 | buildNumber = '-BUILD' 37 | } 38 | archiveName = "EconomyLite-${project.apiVersion.minus("-SNAPSHOT")}-${bVer}${buildNumber}.jar" 39 | 40 | dependencies { 41 | include dependency('com.github.flibiostudio:utils') 42 | } 43 | 44 | relocate 'io.github.flibio.utils', 'io.github.flibio.economylite.utils' 45 | } 46 | 47 | artifacts { 48 | archives shadowJar 49 | } 50 | 51 | license { 52 | 53 | // The project properties to use 54 | ext.name = project.name 55 | 56 | // The file that contains the license header 57 | header file('HEADER.txt') 58 | 59 | // The source sets to apply the license to 60 | sourceSets = project.sourceSets 61 | 62 | // Exclude properties files 63 | exclude "**/*.properties" 64 | 65 | ignoreFailures false 66 | strictCheck true 67 | 68 | mapping { 69 | java = 'SLASHSTAR_STYLE' 70 | } 71 | } 72 | 73 | task wrapper(type: Wrapper) { 74 | gradleVersion = '2.11' 75 | } 76 | 77 | blossom { 78 | replaceToken '@project.version@', project.version, 'src/main/java/io/github/flibio/economylite/PluginInfo.java' 79 | } 80 | -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | name=EconomyLite 2 | owner=Flibio 3 | inceptionYear=2015 4 | currentYear=2018 5 | version=2.15.1 6 | apiVersion=7.1.0-SNAPSHOT -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Flibio/EconomyLite/d5dee7a38feaba74fcd61b1f374e6db7777811cd/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Wed Jul 20 14:48:55 MDT 2016 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | distributionUrl=https\://services.gradle.org/distributions/gradle-2.11-bin.zip 7 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Attempt to set APP_HOME 10 | # Resolve links: $0 may be a link 11 | PRG="$0" 12 | # Need this for relative symlinks. 13 | while [ -h "$PRG" ] ; do 14 | ls=`ls -ld "$PRG"` 15 | link=`expr "$ls" : '.*-> \(.*\)$'` 16 | if expr "$link" : '/.*' > /dev/null; then 17 | PRG="$link" 18 | else 19 | PRG=`dirname "$PRG"`"/$link" 20 | fi 21 | done 22 | SAVED="`pwd`" 23 | cd "`dirname \"$PRG\"`/" >/dev/null 24 | APP_HOME="`pwd -P`" 25 | cd "$SAVED" >/dev/null 26 | 27 | APP_NAME="Gradle" 28 | APP_BASE_NAME=`basename "$0"` 29 | 30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 31 | DEFAULT_JVM_OPTS="" 32 | 33 | # Use the maximum available, or set MAX_FD != -1 to use that value. 34 | MAX_FD="maximum" 35 | 36 | warn ( ) { 37 | echo "$*" 38 | } 39 | 40 | die ( ) { 41 | echo 42 | echo "$*" 43 | echo 44 | exit 1 45 | } 46 | 47 | # OS specific support (must be 'true' or 'false'). 48 | cygwin=false 49 | msys=false 50 | darwin=false 51 | nonstop=false 52 | case "`uname`" in 53 | CYGWIN* ) 54 | cygwin=true 55 | ;; 56 | Darwin* ) 57 | darwin=true 58 | ;; 59 | MINGW* ) 60 | msys=true 61 | ;; 62 | NONSTOP* ) 63 | nonstop=true 64 | ;; 65 | esac 66 | 67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 68 | 69 | # Determine the Java command to use to start the JVM. 70 | if [ -n "$JAVA_HOME" ] ; then 71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 72 | # IBM's JDK on AIX uses strange locations for the executables 73 | JAVACMD="$JAVA_HOME/jre/sh/java" 74 | else 75 | JAVACMD="$JAVA_HOME/bin/java" 76 | fi 77 | if [ ! -x "$JAVACMD" ] ; then 78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 79 | 80 | Please set the JAVA_HOME variable in your environment to match the 81 | location of your Java installation." 82 | fi 83 | else 84 | JAVACMD="java" 85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 86 | 87 | Please set the JAVA_HOME variable in your environment to match the 88 | location of your Java installation." 89 | fi 90 | 91 | # Increase the maximum file descriptors if we can. 92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 93 | MAX_FD_LIMIT=`ulimit -H -n` 94 | if [ $? -eq 0 ] ; then 95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 96 | MAX_FD="$MAX_FD_LIMIT" 97 | fi 98 | ulimit -n $MAX_FD 99 | if [ $? -ne 0 ] ; then 100 | warn "Could not set maximum file descriptor limit: $MAX_FD" 101 | fi 102 | else 103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 104 | fi 105 | fi 106 | 107 | # For Darwin, add options to specify how the application appears in the dock 108 | if $darwin; then 109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 110 | fi 111 | 112 | # For Cygwin, switch paths to Windows format before running java 113 | if $cygwin ; then 114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 116 | JAVACMD=`cygpath --unix "$JAVACMD"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules 158 | function splitJvmOpts() { 159 | JVM_OPTS=("$@") 160 | } 161 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS 162 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" 163 | 164 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" 165 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | set DIRNAME=%~dp0 12 | if "%DIRNAME%" == "" set DIRNAME=. 13 | set APP_BASE_NAME=%~n0 14 | set APP_HOME=%DIRNAME% 15 | 16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 17 | set DEFAULT_JVM_OPTS= 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windows variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | if "%@eval[2+2]" == "4" goto 4NT_args 53 | 54 | :win9xME_args 55 | @rem Slurp the command line arguments. 56 | set CMD_LINE_ARGS= 57 | set _SKIP=2 58 | 59 | :win9xME_args_slurp 60 | if "x%~1" == "x" goto execute 61 | 62 | set CMD_LINE_ARGS=%* 63 | goto execute 64 | 65 | :4NT_args 66 | @rem Get arguments from the 4NT Shell from JP Software 67 | set CMD_LINE_ARGS=%$ 68 | 69 | :execute 70 | @rem Setup the command line 71 | 72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 73 | 74 | @rem Execute Gradle 75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 76 | 77 | :end 78 | @rem End local scope for the variables with windows NT shell 79 | if "%ERRORLEVEL%"=="0" goto mainEnd 80 | 81 | :fail 82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 83 | rem the _cmd.exe /c_ return code! 84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 85 | exit /b 1 86 | 87 | :mainEnd 88 | if "%OS%"=="Windows_NT" endlocal 89 | 90 | :omega 91 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'EconomyLite' 2 | -------------------------------------------------------------------------------- /src/main/java/io/github/flibio/economylite/CauseFactory.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of EconomyLite, licensed under the MIT License (MIT). See the LICENSE file at the root of this project for more information. 3 | */ 4 | package io.github.flibio.economylite; 5 | 6 | import org.spongepowered.api.event.cause.EventContext; 7 | 8 | import org.spongepowered.api.event.cause.Cause; 9 | 10 | public class CauseFactory { 11 | 12 | public static Cause create(String reason) { 13 | return Cause.of(EventContext.empty(), reason, EconomyLite.getInstance().getPluginContainer()); 14 | } 15 | 16 | public static Cause stringCause(String reason) { 17 | return Cause.of(EventContext.empty(),("economylite:" + reason.toLowerCase().replaceAll(" ", "_"))); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/io/github/flibio/economylite/PluginInfo.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of EconomyLite, licensed under the MIT License (MIT). See the LICENSE file at the root of this project for more information. 3 | */ 4 | package io.github.flibio.economylite; 5 | 6 | /** 7 | * General information about the {@link EconomyLite} plugin 8 | */ 9 | public class PluginInfo { 10 | 11 | private PluginInfo() { 12 | } 13 | 14 | public static final String ID = "economylite"; 15 | public static final String NAME = "EconomyLite"; 16 | public static final String VERSION = "@project.version@"; 17 | public static final String DESCRIPTION = "An economy plugin for Sponge."; 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/io/github/flibio/economylite/TextUtils.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of EconomyLite, licensed under the MIT License (MIT). See the LICENSE file at the root of this project for more information. 3 | */ 4 | package io.github.flibio.economylite; 5 | 6 | import org.spongepowered.api.command.CommandSource; 7 | import org.spongepowered.api.text.Text; 8 | import org.spongepowered.api.text.action.TextActions; 9 | import org.spongepowered.api.text.format.TextColors; 10 | 11 | import java.util.function.Consumer; 12 | 13 | public class TextUtils { 14 | 15 | public static Text yesOrNo(Consumer yes, Consumer no) { 16 | Text accept = 17 | Text.of(TextColors.DARK_GRAY, "[", TextColors.GREEN, "YES", TextColors.DARK_GRAY, "]").toBuilder() 18 | .onHover(TextActions.showText(Text.of(TextColors.GREEN, "Yes!"))) 19 | .onClick(TextActions.executeCallback(yes)) 20 | .build(); 21 | Text deny = 22 | Text.of(TextColors.DARK_GRAY, "[", TextColors.RED, "NO", TextColors.DARK_GRAY, "]").toBuilder() 23 | .onHover(TextActions.showText(Text.of(TextColors.RED, "No!"))) 24 | .onClick(TextActions.executeCallback(no)) 25 | .build(); 26 | return accept.toBuilder().append(Text.of(" "), deny).build(); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/io/github/flibio/economylite/api/CurrencyEconService.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of EconomyLite, licensed under the MIT License (MIT). See the LICENSE file at the root of this project for more information. 3 | */ 4 | package io.github.flibio.economylite.api; 5 | 6 | import org.spongepowered.api.service.economy.Currency; 7 | 8 | import java.util.Set; 9 | 10 | public interface CurrencyEconService { 11 | 12 | /** 13 | * Gets all currencies. 14 | * 15 | * @return A set of all currencies. 16 | */ 17 | public Set getCurrencies(); 18 | 19 | /** 20 | * Adds a currency to the currencies. 21 | * 22 | * @param currency The currency to add. 23 | */ 24 | public void addCurrency(Currency currency); 25 | 26 | /** 27 | * Gets the default currency. 28 | * 29 | * @return The default currency. 30 | */ 31 | public Currency getDefaultCurrency(); 32 | 33 | /** 34 | * Sets the currency in use by the server. 35 | * 36 | * @param currency The currency in use. 37 | */ 38 | public void setCurrentCurrency(Currency currency); 39 | 40 | /** 41 | * Deletes a currency. 42 | * 43 | * @param currency The currency to delete. 44 | */ 45 | public void deleteCurrency(Currency currency); 46 | 47 | /** 48 | * Gets the currency in use by the server. 49 | * 50 | * @return The currency in use. 51 | */ 52 | public Currency getCurrentCurrency(); 53 | 54 | } 55 | -------------------------------------------------------------------------------- /src/main/java/io/github/flibio/economylite/api/PlayerEconService.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of EconomyLite, licensed under the MIT License (MIT). See the LICENSE file at the root of this project for more information. 3 | */ 4 | package io.github.flibio.economylite.api; 5 | 6 | import org.spongepowered.api.event.cause.Cause; 7 | import org.spongepowered.api.service.economy.Currency; 8 | import org.spongepowered.api.service.economy.account.UniqueAccount; 9 | 10 | import java.math.BigDecimal; 11 | import java.util.List; 12 | import java.util.UUID; 13 | 14 | /** 15 | * Interfaces directly with the storage system. Performs no checks, simply does 16 | * exactly what it is told. 17 | */ 18 | public interface PlayerEconService { 19 | 20 | /** 21 | * Gets the balance of a player. 22 | * 23 | * @param uuid The UUID of the player to get the balance of. 24 | * @param currency The currency to use. 25 | * @param cause What is getting the balance. 26 | * @param cache Whether not to utilize the cache. 27 | * @return The balance of the player. 28 | */ 29 | public BigDecimal getBalance(UUID uuid, Currency currency, Cause cause, boolean cache); 30 | 31 | /** 32 | * Gets the balance of a player. Caching is used. 33 | * 34 | * @param uuid The UUID of the player to get the balance of. 35 | * @param currency The currency to use. 36 | * @param cause What is getting the balance. 37 | * @return The balance of the player. 38 | */ 39 | default public BigDecimal getBalance(UUID uuid, Currency currency, Cause cause) { 40 | return getBalance(uuid, currency, cause, true); 41 | } 42 | 43 | /** 44 | * Sets the balance of a player. 45 | * 46 | * @param uuid The UUID of the player to set the balance of. 47 | * @param balance The new balance of the uuid. 48 | * @param currency The currency to use. 49 | * @param cause What caused the balance change. 50 | * @return If the player's balance was changed successfully. 51 | */ 52 | public boolean setBalance(UUID uuid, BigDecimal balance, Currency currency, Cause cause); 53 | 54 | /** 55 | * Removes currency from a player's balance. 56 | * 57 | * @param uuid The UUID of the player to remove currency from. 58 | * @param amount The amount of currency to remove. 59 | * @param currency The currency to use. 60 | * @param cause What caused the balance change. 61 | * @return If the player's balance was changed successfully. 62 | */ 63 | default public boolean withdraw(UUID uuid, BigDecimal amount, Currency currency, Cause cause) { 64 | return setBalance(uuid, getBalance(uuid, currency, cause, false).subtract(amount), currency, cause); 65 | } 66 | 67 | /** 68 | * Adds currency to a player's balance. 69 | * 70 | * @param uuid The UUID of the player to add currency to. 71 | * @param amount The amount of currency to add. 72 | * @param currency The currency to use. 73 | * @param cause What caused the balance change. 74 | * @return If the player's balance was changed successfully. 75 | */ 76 | default public boolean deposit(UUID uuid, BigDecimal amount, Currency currency, Cause cause) { 77 | return setBalance(uuid, getBalance(uuid, currency, cause, false).add(amount), currency, cause); 78 | } 79 | 80 | /** 81 | * Checks if a player exists in the system for the specified currency. 82 | * 83 | * @param uuid The UUID of the player to check for. 84 | * @param currency The currency to check against. 85 | * @param cause What is checking if the account exists. 86 | * @return If the player exists or not. 87 | */ 88 | public boolean accountExists(UUID uuid, Currency currency, Cause cause); 89 | 90 | /** 91 | * Clears a currency from the database. 92 | * 93 | * @param currency The currency to clear. 94 | * @param cause What is clearing the balances. 95 | */ 96 | public void clearCurrency(Currency currency, Cause cause); 97 | 98 | /** 99 | * Gets the top unique accounts registered in the EconomyLite system. 100 | * 101 | * @param start The starting account to get. 102 | * @param end The ending account to get. 103 | * @param cause What is getting the accounts. 104 | * @return The top unique accounts registered in the EconomyLite system. 105 | */ 106 | public List getTopAccounts(int start, int end, Cause cause); 107 | 108 | /** 109 | * Sets the balance of all players. 110 | * 111 | * @param balance The new balance. 112 | * @param currency The currency to use. 113 | * @param cause What caused the balance change. 114 | * @return If the balances were changed successfully. 115 | */ 116 | public boolean setBalanceAll(BigDecimal balance, Currency currency, Cause cause); 117 | } 118 | -------------------------------------------------------------------------------- /src/main/java/io/github/flibio/economylite/api/VirtualEconService.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of EconomyLite, licensed under the MIT License (MIT). See the LICENSE file at the root of this project for more information. 3 | */ 4 | package io.github.flibio.economylite.api; 5 | 6 | import org.spongepowered.api.event.cause.Cause; 7 | import org.spongepowered.api.service.economy.Currency; 8 | import org.spongepowered.api.service.economy.account.VirtualAccount; 9 | 10 | import java.math.BigDecimal; 11 | import java.util.List; 12 | 13 | /** 14 | * Interfaces directly with the storage system. Performs no checks, simply does 15 | * exactly what it is told. 16 | */ 17 | public interface VirtualEconService { 18 | 19 | /** 20 | * Gets the balance of an account. 21 | * 22 | * @param id The name of the account to get the balance of. 23 | * @param currency The currency to use. 24 | * @param cause What is getting the balance. 25 | * @param cache Whether or not the cache will be used. 26 | * @return The balance of the account. 27 | */ 28 | public BigDecimal getBalance(String id, Currency currency, Cause cause, boolean cache); 29 | 30 | /** 31 | * Gets the balance of an account. Caching will be used. 32 | * 33 | * @param id The name of the account to get the balance of. 34 | * @param currency The currency to use. 35 | * @param cause What is getting the balance. 36 | * @return The balance of the account. 37 | */ 38 | default public BigDecimal getBalance(String id, Currency currency, Cause cause) { 39 | return getBalance(id, currency, cause, true); 40 | } 41 | 42 | /** 43 | * Sets the balance of an account. 44 | * 45 | * @param id The String of the player to set the balance of. 46 | * @param balance The new balance of the id. 47 | * @param currency The currency to use. 48 | * @param cause What caused the balance change. 49 | * @return If the player's balance was changed successfully. 50 | */ 51 | public boolean setBalance(String id, BigDecimal balance, Currency currency, Cause cause); 52 | 53 | /** 54 | * Removes currency from an accounts's balance. 55 | * 56 | * @param id The name of the account to remove currency from. 57 | * @param amount The amount of currency to remove. 58 | * @param currency The currency to use. 59 | * @param cause What caused the balance change. 60 | * @return If the account's balance was changed successfully. 61 | */ 62 | default public boolean withdraw(String id, BigDecimal amount, Currency currency, Cause cause) { 63 | return setBalance(id, getBalance(id, currency, cause, false).subtract(amount), currency, cause); 64 | } 65 | 66 | /** 67 | * Adds currency to an account's balance. 68 | * 69 | * @param id The name of the account to add currency to. 70 | * @param amount The amount of currency to add. 71 | * @param currency The currency to use. 72 | * @param cause What caused the balance change. 73 | * @return If the account's balance was changed successfully. 74 | */ 75 | default public boolean deposit(String id, BigDecimal amount, Currency currency, Cause cause) { 76 | return setBalance(id, getBalance(id, currency, cause, false).add(amount), currency, cause); 77 | } 78 | 79 | /** 80 | * Checks if an account exists in the system for the specified currency. 81 | * 82 | * @param id The name of the account to check for. 83 | * @param currency The currency to check against. 84 | * @param cause What is checking if the account exists. 85 | * @return If the account exists or not. 86 | */ 87 | public boolean accountExists(String id, Currency currency, Cause cause); 88 | 89 | /** 90 | * Clears a currency from the database. 91 | * 92 | * @param currency The currency to clear. 93 | * @param cause What is checking if the account exists. 94 | */ 95 | public void clearCurrency(Currency currency, Cause cause); 96 | 97 | /** 98 | * Gets the top virtual accounts registered in the EconomyLite system. 99 | * 100 | * @param start The starting account to get. 101 | * @param end The ending account to get. 102 | * @param cause What is checking if the account exists. 103 | * @return The top virtual accounts registered in the EconomyLite system. 104 | */ 105 | public List getTopAccounts(int start, int end, Cause cause); 106 | 107 | } 108 | -------------------------------------------------------------------------------- /src/main/java/io/github/flibio/economylite/commands/MigrateCommand.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of EconomyLite, licensed under the MIT License (MIT). See the LICENSE file at the root of this project for more information. 3 | */ 4 | package io.github.flibio.economylite.commands; 5 | 6 | import io.github.flibio.economylite.CauseFactory; 7 | import io.github.flibio.economylite.EconomyLite; 8 | import io.github.flibio.economylite.api.PlayerEconService; 9 | import io.github.flibio.economylite.api.VirtualEconService; 10 | import io.github.flibio.economylite.impl.PlayerDataService; 11 | import io.github.flibio.economylite.impl.PlayerServiceCommon; 12 | import io.github.flibio.utils.commands.AsyncCommand; 13 | import io.github.flibio.utils.commands.BaseCommandExecutor; 14 | import io.github.flibio.utils.commands.Command; 15 | import io.github.flibio.utils.message.MessageStorage; 16 | import ninja.leaping.configurate.ConfigurationNode; 17 | import ninja.leaping.configurate.hocon.HoconConfigurationLoader; 18 | import ninja.leaping.configurate.loader.ConfigurationLoader; 19 | import org.slf4j.Logger; 20 | import org.spongepowered.api.command.CommandSource; 21 | import org.spongepowered.api.command.args.CommandContext; 22 | import org.spongepowered.api.command.args.GenericArguments; 23 | import org.spongepowered.api.command.spec.CommandSpec; 24 | import org.spongepowered.api.command.spec.CommandSpec.Builder; 25 | import org.spongepowered.api.service.economy.Currency; 26 | import org.spongepowered.api.text.Text; 27 | 28 | import java.io.File; 29 | import java.io.FileNotFoundException; 30 | import java.math.BigDecimal; 31 | import java.util.HashMap; 32 | import java.util.Map; 33 | import java.util.UUID; 34 | 35 | @AsyncCommand 36 | @Command(aliases = {"migrate"}, permission = "economylite.admin.migrate") 37 | public class MigrateCommand extends BaseCommandExecutor { 38 | 39 | private MessageStorage messageStorage = EconomyLite.getMessageStorage(); 40 | private PlayerEconService playerService = EconomyLite.getPlayerService(); 41 | private VirtualEconService virtualService = EconomyLite.getVirtualService(); 42 | private Logger logger = EconomyLite.getInstance().getLogger(); 43 | 44 | @Override 45 | public Builder getCommandSpecBuilder() { 46 | return CommandSpec.builder() 47 | .executor(this) 48 | .arguments(GenericArguments.string(Text.of("mode")), GenericArguments.optional(GenericArguments.bool(Text.of("confirm")))); 49 | } 50 | 51 | @Override 52 | public void run(CommandSource src, CommandContext args) { 53 | if (args.getOne("mode").isPresent()) { 54 | // Check if migration is confirmed 55 | if (args.getOne("confirm").isPresent() && args.getOne("confirm").get()) { 56 | // Attempt to migrate 57 | String mode = args.getOne("mode").get(); 58 | if (mode.equalsIgnoreCase("totaleconomy")) { 59 | try { 60 | // Migrate from TotalEconomy 61 | String configDir = EconomyLite.getInstance().getMainDir(); 62 | if (!configDir.substring(configDir.length() - 1).equalsIgnoreCase("/")) { 63 | configDir += "/"; 64 | } 65 | // Check if the file exists 66 | File file = new File(configDir + "totaleconomy/accounts.conf"); 67 | if (!file.exists()) { 68 | logger.error("Could not find TotalEconomy file!"); 69 | throw new FileNotFoundException(); 70 | } 71 | // Attempt to load the file 72 | ConfigurationLoader manager = HoconConfigurationLoader.builder().setFile(file).build(); 73 | ConfigurationNode root = manager.load(); 74 | root.getChildrenMap().keySet().forEach(raw -> { 75 | if (raw instanceof String) { 76 | String uuid = (String) raw; 77 | root.getNode(uuid).getChildrenMap().keySet().forEach(n -> { 78 | if (n.toString().contains("balance")) { 79 | ConfigurationNode sub = root.getNode(uuid).getNode(n.toString()); 80 | if (!sub.isVirtual()) { 81 | playerService.setBalance(UUID.fromString(uuid), BigDecimal.valueOf(sub.getDouble()), 82 | EconomyLite.getEconomyService().getDefaultCurrency(), CauseFactory.create("Migration")); 83 | logger.debug(uuid.toString() + ":migrate: " + sub.getDouble()); 84 | } 85 | } 86 | }); 87 | } 88 | }); 89 | src.sendMessage(messageStorage.getMessage("command.migrate.completed")); 90 | } catch (Exception e) { 91 | logger.error(e.getMessage()); 92 | src.sendMessage(messageStorage.getMessage("command.migrate.fail")); 93 | } 94 | } else if (mode.equalsIgnoreCase("tomysql")) { 95 | try { 96 | // Migrate from H2 to MySQL 97 | if (EconomyLite.getPlayerService() instanceof PlayerDataService) { 98 | // MySQL is not setup 99 | src.sendMessage(messageStorage.getMessage("command.migrate.fail")); 100 | return; 101 | } 102 | // Get current MySQL service 103 | PlayerEconService s = EconomyLite.getPlayerService(); 104 | if (!(s instanceof PlayerServiceCommon)) { 105 | src.sendMessage(messageStorage.getMessage("command.migrate.fail")); 106 | return; 107 | } 108 | PlayerServiceCommon sqlService = (PlayerServiceCommon) s; 109 | // Load the data service 110 | PlayerDataService dataService = new PlayerDataService(); 111 | // Get Currency Data 112 | Map cIds = new HashMap<>(); 113 | EconomyLite.getCurrencyService().getCurrencies().forEach(c -> { 114 | cIds.put(c.getId(), c); 115 | }); 116 | // Insert new data 117 | dataService.getAccountsMigration().forEach(r -> { 118 | String[] d = r.split("%-%"); 119 | if (cIds.get(d[2]) != null) { 120 | sqlService.setRawData(d[0], d[1], cIds.get(d[2])); 121 | } 122 | }); 123 | src.sendMessage(messageStorage.getMessage("command.migrate.completed")); 124 | } catch (Exception e) { 125 | logger.error(e.getMessage()); 126 | src.sendMessage(messageStorage.getMessage("command.migrate.fail")); 127 | } 128 | } else { 129 | // Invalid mode 130 | src.sendMessage(messageStorage.getMessage("command.migrate.nomode")); 131 | } 132 | } else { 133 | src.sendMessage(messageStorage.getMessage("command.migrate.confirm")); 134 | } 135 | } else { 136 | src.sendMessage(messageStorage.getMessage("command.migrate.nomode")); 137 | } 138 | } 139 | } 140 | -------------------------------------------------------------------------------- /src/main/java/io/github/flibio/economylite/commands/PayCommand.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of EconomyLite, licensed under the MIT License (MIT). See the LICENSE file at the root of this project for more information. 3 | */ 4 | package io.github.flibio.economylite.commands; 5 | 6 | import io.github.flibio.economylite.TextUtils; 7 | 8 | import io.github.flibio.economylite.EconomyLite; 9 | import io.github.flibio.utils.commands.AsyncCommand; 10 | import io.github.flibio.utils.commands.BaseCommandExecutor; 11 | import io.github.flibio.utils.commands.Command; 12 | import io.github.flibio.utils.message.MessageStorage; 13 | import org.spongepowered.api.Sponge; 14 | import org.spongepowered.api.command.args.CommandContext; 15 | import org.spongepowered.api.command.args.GenericArguments; 16 | import org.spongepowered.api.command.spec.CommandSpec; 17 | import org.spongepowered.api.command.spec.CommandSpec.Builder; 18 | import org.spongepowered.api.entity.living.player.Player; 19 | import org.spongepowered.api.entity.living.player.User; 20 | import org.spongepowered.api.event.cause.Cause; 21 | import org.spongepowered.api.event.cause.EventContext; 22 | import org.spongepowered.api.service.economy.EconomyService; 23 | import org.spongepowered.api.service.economy.account.UniqueAccount; 24 | import org.spongepowered.api.service.economy.transaction.ResultType; 25 | import org.spongepowered.api.text.Text; 26 | 27 | import java.math.BigDecimal; 28 | import java.util.Locale; 29 | import java.util.Optional; 30 | 31 | @AsyncCommand 32 | @Command(aliases = {"pay"}, permission = "economylite.pay") 33 | public class PayCommand extends BaseCommandExecutor { 34 | 35 | private MessageStorage messageStorage = EconomyLite.getMessageStorage(); 36 | private EconomyService ecoService = EconomyLite.getEconomyService(); 37 | 38 | @Override 39 | public Builder getCommandSpecBuilder() { 40 | return CommandSpec.builder() 41 | .executor(this) 42 | .arguments(GenericArguments.user(Text.of("player")), GenericArguments.doubleNum(Text.of("amount"))); 43 | } 44 | 45 | @Override 46 | public void run(Player src, CommandContext args) { 47 | if (args.getOne("player").isPresent() && args.getOne("amount").isPresent()) { 48 | BigDecimal amount = BigDecimal.valueOf(args.getOne("amount").get()); 49 | if (amount.doubleValue() <= 0) { 50 | src.sendMessage(messageStorage.getMessage("command.pay.invalid")); 51 | } else { 52 | User target = args.getOne("player").get(); 53 | if (!EconomyLite.getConfigManager().getValue(Boolean.class, false, "confirm-offline-payments") || target.isOnline()) { 54 | // Complete the payment 55 | pay(target, amount, src); 56 | } else { 57 | src.sendMessage(messageStorage.getMessage("command.pay.confirm", "player", target.getName())); 58 | // Check if they want to still pay 59 | src.sendMessage(TextUtils.yesOrNo(c -> { 60 | pay(target, amount, src); 61 | }, c -> { 62 | src.sendMessage(messageStorage.getMessage("command.pay.confirmno", "player", target.getName())); 63 | })); 64 | } 65 | 66 | } 67 | } else { 68 | src.sendMessage(messageStorage.getMessage("command.error")); 69 | } 70 | } 71 | 72 | private void pay(User target, BigDecimal amount, Player src) { 73 | String targetName = target.getName(); 74 | if (!target.getUniqueId().equals(src.getUniqueId())) { 75 | Optional uOpt = ecoService.getOrCreateAccount(src.getUniqueId()); 76 | Optional tOpt = ecoService.getOrCreateAccount(target.getUniqueId()); 77 | if (uOpt.isPresent() && tOpt.isPresent()) { 78 | if (uOpt.get() 79 | .transfer(tOpt.get(), ecoService.getDefaultCurrency(), amount, Cause.of(EventContext.empty(), (EconomyLite.getInstance()))) 80 | .getResult().equals(ResultType.SUCCESS)) { 81 | Text label = ecoService.getDefaultCurrency().getPluralDisplayName(); 82 | if (amount.equals(BigDecimal.ONE)) { 83 | label = ecoService.getDefaultCurrency().getDisplayName(); 84 | } 85 | src.sendMessage(messageStorage.getMessage("command.pay.success", "target", targetName, "amountandlabel", 86 | String.format(Locale.ENGLISH, "%,.2f", amount) + " " + label.toPlain())); 87 | final Text curLabel = label; 88 | Sponge.getServer().getPlayer(target.getUniqueId()).ifPresent(p -> { 89 | p.sendMessage(messageStorage.getMessage("command.pay.target", "amountandlabel", 90 | String.format(Locale.ENGLISH, "%,.2f", amount) + " " + curLabel.toPlain(), "sender", 91 | uOpt.get().getDisplayName().toPlain())); 92 | }); 93 | } else { 94 | src.sendMessage(messageStorage.getMessage("command.pay.failed", "target", targetName)); 95 | } 96 | } else { 97 | src.sendMessage(messageStorage.getMessage("command.error")); 98 | } 99 | } else { 100 | src.sendMessage(messageStorage.getMessage("command.pay.notyou")); 101 | } 102 | } 103 | 104 | } 105 | -------------------------------------------------------------------------------- /src/main/java/io/github/flibio/economylite/commands/RefreshCommand.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of EconomyLite, licensed under the MIT License (MIT). See the LICENSE file at the root of this project for more information. 3 | */ 4 | package io.github.flibio.economylite.commands; 5 | 6 | import io.github.flibio.economylite.EconomyLite; 7 | import io.github.flibio.economylite.api.PlayerEconService; 8 | import io.github.flibio.economylite.api.VirtualEconService; 9 | import io.github.flibio.economylite.impl.PlayerServiceCommon; 10 | import io.github.flibio.economylite.impl.VirtualServiceCommon; 11 | import io.github.flibio.utils.commands.AsyncCommand; 12 | import io.github.flibio.utils.commands.BaseCommandExecutor; 13 | import io.github.flibio.utils.commands.Command; 14 | import io.github.flibio.utils.message.MessageStorage; 15 | import org.spongepowered.api.command.CommandSource; 16 | import org.spongepowered.api.command.args.CommandContext; 17 | import org.spongepowered.api.command.spec.CommandSpec; 18 | 19 | @AsyncCommand 20 | @Command(aliases = {"ecorefresh"}, permission = "economylite.admin.refresh") 21 | public class RefreshCommand extends BaseCommandExecutor { 22 | 23 | private MessageStorage messageStorage = EconomyLite.getMessageStorage(); 24 | 25 | @Override 26 | public CommandSpec.Builder getCommandSpecBuilder() { 27 | return CommandSpec.builder() 28 | .executor(this); 29 | } 30 | 31 | @Override 32 | public void run(CommandSource src, CommandContext args) { 33 | PlayerEconService ps = EconomyLite.getPlayerService(); 34 | if (!(ps instanceof PlayerServiceCommon)) { 35 | src.sendMessage(messageStorage.getMessage("command.refresh.fail")); 36 | return; 37 | } 38 | VirtualEconService vs = EconomyLite.getVirtualService(); 39 | if (!(vs instanceof VirtualServiceCommon)) { 40 | src.sendMessage(messageStorage.getMessage("command.refresh.fail")); 41 | return; 42 | } 43 | 44 | PlayerServiceCommon playerService = (PlayerServiceCommon) ps; 45 | VirtualServiceCommon virtualService = (VirtualServiceCommon) vs; 46 | 47 | playerService.resetCache(); 48 | virtualService.resetCache(); 49 | 50 | src.sendMessage(messageStorage.getMessage("command.refresh.success")); 51 | } 52 | 53 | } 54 | -------------------------------------------------------------------------------- /src/main/java/io/github/flibio/economylite/commands/admin/AddCommand.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of EconomyLite, licensed under the MIT License (MIT). See the LICENSE file at the root of this project for more information. 3 | */ 4 | package io.github.flibio.economylite.commands.admin; 5 | 6 | import io.github.flibio.economylite.EconomyLite; 7 | import io.github.flibio.utils.commands.AsyncCommand; 8 | import io.github.flibio.utils.commands.BaseCommandExecutor; 9 | import io.github.flibio.utils.commands.Command; 10 | import io.github.flibio.utils.commands.ParentCommand; 11 | import io.github.flibio.utils.message.MessageStorage; 12 | import org.spongepowered.api.command.CommandSource; 13 | import org.spongepowered.api.command.args.CommandContext; 14 | import org.spongepowered.api.command.args.GenericArguments; 15 | import org.spongepowered.api.command.spec.CommandSpec; 16 | import org.spongepowered.api.command.spec.CommandSpec.Builder; 17 | import org.spongepowered.api.entity.living.player.Player; 18 | import org.spongepowered.api.entity.living.player.User; 19 | import org.spongepowered.api.event.cause.Cause; 20 | import org.spongepowered.api.event.cause.EventContext; 21 | import org.spongepowered.api.service.economy.account.UniqueAccount; 22 | import org.spongepowered.api.service.economy.transaction.ResultType; 23 | import org.spongepowered.api.text.Text; 24 | 25 | import java.math.BigDecimal; 26 | import java.util.Optional; 27 | 28 | @AsyncCommand 29 | @ParentCommand(parentCommand = EconCommand.class) 30 | @Command(aliases = {"add"}, permission = "economylite.admin.econ.add") 31 | public class AddCommand extends BaseCommandExecutor { 32 | 33 | private MessageStorage messageStorage = EconomyLite.getMessageStorage(); 34 | 35 | @Override 36 | public Builder getCommandSpecBuilder() { 37 | return CommandSpec.builder() 38 | .executor(this) 39 | .arguments(GenericArguments.user(Text.of("player")), GenericArguments.doubleNum(Text.of("amount"))); 40 | } 41 | 42 | @Override 43 | public void run(CommandSource src, CommandContext args) { 44 | if (args.getOne("player").isPresent() && args.getOne("amount").isPresent()) { 45 | User target = args.getOne("player").get(); 46 | String targetName = target.getName(); 47 | BigDecimal toAdd = BigDecimal.valueOf(args.getOne("amount").get()); 48 | Optional uOpt = EconomyLite.getEconomyService().getOrCreateAccount(target.getUniqueId()); 49 | if (uOpt.isPresent()) { 50 | UniqueAccount targetAccount = uOpt.get(); 51 | if (targetAccount.deposit(EconomyLite.getCurrencyService().getCurrentCurrency(), toAdd, 52 | Cause.of(EventContext.empty(),(EconomyLite.getInstance()))).getResult().equals(ResultType.SUCCESS)) { 53 | src.sendMessage(messageStorage.getMessage("command.econ.addsuccess", "name", targetName)); 54 | attemptNotify(target); 55 | } else { 56 | src.sendMessage(messageStorage.getMessage("command.econ.addfail", "name", targetName)); 57 | } 58 | } else { 59 | src.sendMessage(messageStorage.getMessage("command.error")); 60 | } 61 | } else { 62 | src.sendMessage(messageStorage.getMessage("command.error")); 63 | } 64 | } 65 | 66 | private void attemptNotify(User target) { 67 | if (target instanceof Player) { 68 | ((Player) target).sendMessage(messageStorage.getMessage("command.econ.notify")); 69 | } 70 | } 71 | 72 | } 73 | -------------------------------------------------------------------------------- /src/main/java/io/github/flibio/economylite/commands/admin/EconCommand.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of EconomyLite, licensed under the MIT License (MIT). See the LICENSE file at the root of this project for more information. 3 | */ 4 | package io.github.flibio.economylite.commands.admin; 5 | 6 | import org.spongepowered.api.command.CommandSource; 7 | import org.spongepowered.api.command.args.CommandContext; 8 | import org.spongepowered.api.command.spec.CommandSpec; 9 | import org.spongepowered.api.command.spec.CommandSpec.Builder; 10 | 11 | import io.github.flibio.economylite.EconomyLite; 12 | import io.github.flibio.utils.commands.AsyncCommand; 13 | import io.github.flibio.utils.commands.BaseCommandExecutor; 14 | import io.github.flibio.utils.commands.Command; 15 | import io.github.flibio.utils.message.MessageStorage; 16 | 17 | @AsyncCommand 18 | @Command(aliases = {"economy", "econ", "eco"}, permission = "economylite.admin.econ") 19 | public class EconCommand extends BaseCommandExecutor { 20 | 21 | private MessageStorage messageStorage = EconomyLite.getMessageStorage(); 22 | 23 | @Override 24 | public Builder getCommandSpecBuilder() { 25 | return CommandSpec.builder() 26 | .executor(this); 27 | } 28 | 29 | @Override 30 | public void run(CommandSource src, CommandContext args) { 31 | src.sendMessage(messageStorage.getMessage("command.usage", "command", "/econ", "subcommands", "add | set | remove ")); 32 | src.sendMessage(messageStorage.getMessage("command.usage", "command", "/econ", "subcommands", "setall ")); 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/io/github/flibio/economylite/commands/admin/RemoveCommand.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of EconomyLite, licensed under the MIT License (MIT). See the LICENSE file at the root of this project for more information. 3 | */ 4 | package io.github.flibio.economylite.commands.admin; 5 | 6 | import org.spongepowered.api.entity.living.player.Player; 7 | 8 | import org.spongepowered.api.command.CommandSource; 9 | import org.spongepowered.api.command.args.CommandContext; 10 | import org.spongepowered.api.command.args.GenericArguments; 11 | import org.spongepowered.api.command.spec.CommandSpec; 12 | import org.spongepowered.api.command.spec.CommandSpec.Builder; 13 | import org.spongepowered.api.entity.living.player.User; 14 | import org.spongepowered.api.event.cause.Cause; 15 | import org.spongepowered.api.event.cause.EventContext; 16 | import org.spongepowered.api.service.economy.account.UniqueAccount; 17 | import org.spongepowered.api.service.economy.transaction.ResultType; 18 | import org.spongepowered.api.text.Text; 19 | import io.github.flibio.economylite.EconomyLite; 20 | import io.github.flibio.utils.commands.AsyncCommand; 21 | import io.github.flibio.utils.commands.BaseCommandExecutor; 22 | import io.github.flibio.utils.commands.Command; 23 | import io.github.flibio.utils.commands.ParentCommand; 24 | import io.github.flibio.utils.message.MessageStorage; 25 | 26 | import java.math.BigDecimal; 27 | import java.util.Optional; 28 | 29 | @AsyncCommand 30 | @ParentCommand(parentCommand = EconCommand.class) 31 | @Command(aliases = {"remove"}, permission = "economylite.admin.econ.remove") 32 | public class RemoveCommand extends BaseCommandExecutor { 33 | 34 | private MessageStorage messageStorage = EconomyLite.getMessageStorage(); 35 | 36 | @Override 37 | public Builder getCommandSpecBuilder() { 38 | return CommandSpec.builder() 39 | .executor(this) 40 | .arguments(GenericArguments.user(Text.of("player")), GenericArguments.doubleNum(Text.of("amount"))); 41 | } 42 | 43 | @Override 44 | public void run(CommandSource src, CommandContext args) { 45 | if (args.getOne("player").isPresent() && args.getOne("amount").isPresent()) { 46 | User target = args.getOne("player").get(); 47 | String targetName = target.getName(); 48 | BigDecimal toRemove = BigDecimal.valueOf(args.getOne("amount").get()); 49 | Optional uOpt = EconomyLite.getEconomyService().getOrCreateAccount(target.getUniqueId()); 50 | if (uOpt.isPresent()) { 51 | UniqueAccount targetAccount = uOpt.get(); 52 | if (targetAccount.withdraw(EconomyLite.getCurrencyService().getCurrentCurrency(), toRemove, 53 | Cause.of(EventContext.empty(),(EconomyLite.getInstance()))).getResult().equals(ResultType.SUCCESS)) { 54 | src.sendMessage(messageStorage.getMessage("command.econ.removesuccess", "name", targetName)); 55 | attemptNotify(target); 56 | } else { 57 | src.sendMessage(messageStorage.getMessage("command.econ.removefail", "name", targetName)); 58 | } 59 | } else { 60 | src.sendMessage(messageStorage.getMessage("command.error")); 61 | } 62 | } else { 63 | src.sendMessage(messageStorage.getMessage("command.error")); 64 | } 65 | } 66 | 67 | private void attemptNotify(User target) { 68 | if (target instanceof Player) { 69 | ((Player) target).sendMessage(messageStorage.getMessage("command.econ.notify")); 70 | } 71 | } 72 | 73 | } 74 | -------------------------------------------------------------------------------- /src/main/java/io/github/flibio/economylite/commands/admin/SetAllCommand.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of EconomyLite, licensed under the MIT License (MIT). See the LICENSE file at the root of this project for more information. 3 | */ 4 | package io.github.flibio.economylite.commands.admin; 5 | 6 | import io.github.flibio.economylite.EconomyLite; 7 | import io.github.flibio.utils.commands.AsyncCommand; 8 | import io.github.flibio.utils.commands.BaseCommandExecutor; 9 | import io.github.flibio.utils.commands.Command; 10 | import io.github.flibio.utils.commands.ParentCommand; 11 | import io.github.flibio.utils.message.MessageStorage; 12 | import org.spongepowered.api.command.CommandSource; 13 | import org.spongepowered.api.command.args.CommandContext; 14 | import org.spongepowered.api.command.args.GenericArguments; 15 | import org.spongepowered.api.command.spec.CommandSpec; 16 | import org.spongepowered.api.command.spec.CommandSpec.Builder; 17 | import org.spongepowered.api.event.cause.Cause; 18 | import org.spongepowered.api.event.cause.EventContext; 19 | import org.spongepowered.api.text.Text; 20 | 21 | import java.math.BigDecimal; 22 | 23 | @AsyncCommand 24 | @ParentCommand(parentCommand = EconCommand.class) 25 | @Command(aliases = {"setall"}, permission = "economylite.admin.econ.setall") 26 | public class SetAllCommand extends BaseCommandExecutor { 27 | 28 | private MessageStorage messageStorage = EconomyLite.getMessageStorage(); 29 | 30 | @Override 31 | public Builder getCommandSpecBuilder() { 32 | return CommandSpec.builder() 33 | .executor(this) 34 | .arguments(GenericArguments.doubleNum(Text.of("balance"))); 35 | } 36 | 37 | @Override 38 | public void run(CommandSource src, CommandContext args) { 39 | if (args.getOne("balance").isPresent()) { 40 | String targetName = "all players"; 41 | BigDecimal newBal = BigDecimal.valueOf(args.getOne("balance").get()); 42 | if (EconomyLite.getPlayerService().setBalanceAll(newBal, EconomyLite.getCurrencyService().getCurrentCurrency(), 43 | Cause.of(EventContext.empty(),(EconomyLite.getInstance())))) { 44 | src.sendMessage(messageStorage.getMessage("command.econ.setsuccess", "name", targetName)); 45 | } else { 46 | src.sendMessage(messageStorage.getMessage("command.econ.setfail", "name", targetName)); 47 | } 48 | } else { 49 | src.sendMessage(messageStorage.getMessage("command.error")); 50 | } 51 | } 52 | 53 | } 54 | -------------------------------------------------------------------------------- /src/main/java/io/github/flibio/economylite/commands/admin/SetCommand.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of EconomyLite, licensed under the MIT License (MIT). See the LICENSE file at the root of this project for more information. 3 | */ 4 | package io.github.flibio.economylite.commands.admin; 5 | 6 | import org.spongepowered.api.entity.living.player.Player; 7 | 8 | import org.spongepowered.api.command.CommandSource; 9 | import org.spongepowered.api.command.args.CommandContext; 10 | import org.spongepowered.api.command.args.GenericArguments; 11 | import org.spongepowered.api.command.spec.CommandSpec; 12 | import org.spongepowered.api.command.spec.CommandSpec.Builder; 13 | import org.spongepowered.api.entity.living.player.User; 14 | import org.spongepowered.api.event.cause.Cause; 15 | import org.spongepowered.api.event.cause.EventContext; 16 | import org.spongepowered.api.service.economy.account.UniqueAccount; 17 | import org.spongepowered.api.service.economy.transaction.ResultType; 18 | import org.spongepowered.api.text.Text; 19 | import io.github.flibio.economylite.EconomyLite; 20 | import io.github.flibio.utils.commands.AsyncCommand; 21 | import io.github.flibio.utils.commands.BaseCommandExecutor; 22 | import io.github.flibio.utils.commands.Command; 23 | import io.github.flibio.utils.commands.ParentCommand; 24 | import io.github.flibio.utils.message.MessageStorage; 25 | 26 | import java.math.BigDecimal; 27 | import java.util.Optional; 28 | 29 | @AsyncCommand 30 | @ParentCommand(parentCommand = EconCommand.class) 31 | @Command(aliases = {"set"}, permission = "economylite.admin.econ.set") 32 | public class SetCommand extends BaseCommandExecutor { 33 | 34 | private MessageStorage messageStorage = EconomyLite.getMessageStorage(); 35 | 36 | @Override 37 | public Builder getCommandSpecBuilder() { 38 | return CommandSpec.builder() 39 | .executor(this) 40 | .arguments(GenericArguments.user(Text.of("player")), GenericArguments.doubleNum(Text.of("balance"))); 41 | } 42 | 43 | @Override 44 | public void run(CommandSource src, CommandContext args) { 45 | if (args.getOne("player").isPresent() && args.getOne("balance").isPresent()) { 46 | User target = args.getOne("player").get(); 47 | String targetName = target.getName(); 48 | BigDecimal newBal = BigDecimal.valueOf(args.getOne("balance").get()); 49 | Optional uOpt = EconomyLite.getEconomyService().getOrCreateAccount(target.getUniqueId()); 50 | if (uOpt.isPresent()) { 51 | UniqueAccount targetAccount = uOpt.get(); 52 | if (targetAccount.setBalance(EconomyLite.getCurrencyService().getCurrentCurrency(), newBal, 53 | Cause.of(EventContext.empty(),(EconomyLite.getInstance()))).getResult().equals(ResultType.SUCCESS)) { 54 | src.sendMessage(messageStorage.getMessage("command.econ.setsuccess", "name", targetName)); 55 | attemptNotify(target); 56 | } else { 57 | src.sendMessage(messageStorage.getMessage("command.econ.setfail", "name", targetName)); 58 | } 59 | } else { 60 | src.sendMessage(messageStorage.getMessage("command.error")); 61 | } 62 | } else { 63 | src.sendMessage(messageStorage.getMessage("command.error")); 64 | } 65 | } 66 | 67 | private void attemptNotify(User target) { 68 | if (target instanceof Player) { 69 | ((Player) target).sendMessage(messageStorage.getMessage("command.econ.notify")); 70 | } 71 | } 72 | 73 | } 74 | -------------------------------------------------------------------------------- /src/main/java/io/github/flibio/economylite/commands/balance/BalTopCommand.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of EconomyLite, licensed under the MIT License (MIT). See the LICENSE file at the root of this project for more information. 3 | */ 4 | package io.github.flibio.economylite.commands.balance; 5 | 6 | import io.github.flibio.economylite.CauseFactory; 7 | import com.google.common.collect.ImmutableMap; 8 | import io.github.flibio.economylite.EconomyLite; 9 | import io.github.flibio.utils.commands.AsyncCommand; 10 | import io.github.flibio.utils.commands.BaseCommandExecutor; 11 | import io.github.flibio.utils.commands.Command; 12 | import io.github.flibio.utils.message.MessageStorage; 13 | import org.spongepowered.api.command.CommandSource; 14 | import org.spongepowered.api.command.args.CommandContext; 15 | import org.spongepowered.api.command.args.GenericArguments; 16 | import org.spongepowered.api.command.spec.CommandSpec; 17 | import org.spongepowered.api.command.spec.CommandSpec.Builder; 18 | import org.spongepowered.api.service.economy.Currency; 19 | import org.spongepowered.api.service.economy.account.UniqueAccount; 20 | import org.spongepowered.api.text.Text; 21 | import org.spongepowered.api.text.action.TextActions; 22 | import org.spongepowered.api.text.format.TextColors; 23 | 24 | import java.math.BigDecimal; 25 | import java.util.Locale; 26 | import java.util.Map; 27 | import java.util.Optional; 28 | import java.util.TreeMap; 29 | 30 | @AsyncCommand 31 | @Command(aliases = {"baltop"}, permission = "economylite.baltop") 32 | public class BalTopCommand extends BaseCommandExecutor { 33 | 34 | MessageStorage messages = EconomyLite.getMessageStorage(); 35 | 36 | private int count; 37 | 38 | @Override 39 | public Builder getCommandSpecBuilder() { 40 | return CommandSpec.builder() 41 | .executor(this) 42 | .arguments(GenericArguments.optional(GenericArguments.integer(Text.of("page")))); 43 | } 44 | 45 | @Override 46 | public void run(CommandSource src, CommandContext args) { 47 | Currency current = EconomyLite.getCurrencyService().getCurrentCurrency(); 48 | TreeMap bals = new TreeMap<>(); 49 | Optional pOpt = args.getOne("page"); 50 | int pageNumber = 1; 51 | if (pOpt.isPresent()) { 52 | pageNumber = pOpt.get(); 53 | } 54 | if (pageNumber < 1) { 55 | src.sendMessage(messages.getMessage("command.baltop.invalidpage")); 56 | return; 57 | } 58 | int start, end; 59 | if (pageNumber == 1) { 60 | start = 1; 61 | end = 5; 62 | } else { 63 | start = ((pageNumber - 1) * 5) + 1; 64 | end = pageNumber * 10; 65 | } 66 | for (UniqueAccount account : EconomyLite.getPlayerService().getTopAccounts(start, end + 1, CauseFactory.create("Baltop command."))) { 67 | bals.put(account.getDisplayName().toPlain(), account.getBalance(current)); 68 | } 69 | boolean nextPage = true; 70 | if (bals.size() < 1) { 71 | src.sendMessage(messages.getMessage("command.baltop.nodata")); 72 | return; 73 | } 74 | if (bals.size() < 6) { 75 | nextPage = false; 76 | } 77 | src.sendMessage(messages.getMessage("command.baltop.head", "page", String.valueOf(pageNumber))); 78 | count = start; 79 | bals.entrySet().stream().sorted(Map.Entry.comparingByValue().reversed()).limit(5).forEachOrdered(e -> { 80 | Text label = current.getPluralDisplayName(); 81 | if (e.getValue().equals(BigDecimal.ONE)) { 82 | label = current.getDisplayName(); 83 | } 84 | src.sendMessage(messages.getMessage( 85 | "command.baltop.data", "position", Integer.toString(count), "name", e.getKey(), "balance", 86 | String.format(Locale.ENGLISH, "%,.2f", e.getValue()), "label", label.toPlain())); 87 | count++; 88 | }); 89 | Text toSend = Text.of(); 90 | if (pageNumber > 1) { 91 | toSend = toSend.toBuilder().append( 92 | messages.getMessage("command.baltop.navigation", "button", "<-").toBuilder() 93 | .onClick(TextActions.runCommand("/baltop " + (pageNumber - 1))) 94 | .onHover(TextActions.showText(Text.of(TextColors.GREEN, "BACK"))).build()).build(); 95 | toSend = toSend.toBuilder().append(Text.of(" ")).build(); 96 | } 97 | toSend = toSend.toBuilder().append(messages.getMessage("command.baltop.navigation", "button", String.valueOf(pageNumber))).build(); 98 | if (nextPage) { 99 | toSend = toSend.toBuilder().append(Text.of(" ")).build(); 100 | toSend = toSend.toBuilder().append( 101 | messages.getMessage("command.baltop.navigation", "button", "->").toBuilder() 102 | .onClick(TextActions.runCommand("/baltop " + (pageNumber + 1))) 103 | .onHover(TextActions.showText(Text.of(TextColors.GREEN, "NEXT"))).build()).build(); 104 | } 105 | if (!toSend.toPlain().isEmpty()) { 106 | src.sendMessage(toSend); 107 | } 108 | count = 0; 109 | } 110 | } 111 | -------------------------------------------------------------------------------- /src/main/java/io/github/flibio/economylite/commands/balance/BalanceCommand.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of EconomyLite, licensed under the MIT License (MIT). See the LICENSE file at the root of this project for more information. 3 | */ 4 | package io.github.flibio.economylite.commands.balance; 5 | 6 | import io.github.flibio.economylite.EconomyLite; 7 | import io.github.flibio.economylite.api.CurrencyEconService; 8 | import io.github.flibio.utils.commands.AsyncCommand; 9 | import io.github.flibio.utils.commands.BaseCommandExecutor; 10 | import io.github.flibio.utils.commands.Command; 11 | import io.github.flibio.utils.message.MessageStorage; 12 | import org.spongepowered.api.command.CommandSource; 13 | import org.spongepowered.api.command.args.CommandContext; 14 | import org.spongepowered.api.command.args.GenericArguments; 15 | import org.spongepowered.api.command.spec.CommandSpec; 16 | import org.spongepowered.api.command.spec.CommandSpec.Builder; 17 | import org.spongepowered.api.entity.living.player.Player; 18 | import org.spongepowered.api.entity.living.player.User; 19 | import org.spongepowered.api.service.economy.Currency; 20 | import org.spongepowered.api.service.economy.account.UniqueAccount; 21 | import org.spongepowered.api.text.Text; 22 | import org.spongepowered.api.text.serializer.TextSerializers; 23 | 24 | import java.math.BigDecimal; 25 | import java.util.Locale; 26 | import java.util.Optional; 27 | 28 | @AsyncCommand 29 | @Command(aliases = {"balance", "money", "bal"}, permission = "economylite.balance") 30 | public class BalanceCommand extends BaseCommandExecutor { 31 | 32 | private MessageStorage messageStorage = EconomyLite.getMessageStorage(); 33 | private CurrencyEconService currencyService = EconomyLite.getCurrencyService(); 34 | 35 | @Override 36 | public Builder getCommandSpecBuilder() { 37 | return CommandSpec.builder() 38 | .executor(this) 39 | .arguments(GenericArguments.optional(GenericArguments.user(Text.of("player")))); 40 | } 41 | 42 | @Override 43 | public void run(CommandSource src, CommandContext args) { 44 | Currency currency = currencyService.getCurrentCurrency(); 45 | if (args.getOne("player").isPresent()) { 46 | if (src.hasPermission("economylite.admin.balanceothers")) { 47 | User target = args.getOne("player").get(); 48 | String targetName = target.getName(); 49 | Optional uOpt = EconomyLite.getEconomyService().getOrCreateAccount(target.getUniqueId()); 50 | if (uOpt.isPresent()) { 51 | BigDecimal bal = uOpt.get().getBalance(currency); 52 | Text label = currency.getPluralDisplayName(); 53 | if (bal.equals(BigDecimal.ONE)) { 54 | label = currency.getDisplayName(); 55 | } 56 | src.sendMessage(messageStorage 57 | .getMessage("command.balanceother", "player", targetName, "balance", String.format(Locale.ENGLISH, "%,.2f", bal), "label", 58 | TextSerializers.FORMATTING_CODE.serialize(label))); 59 | } else { 60 | src.sendMessage(messageStorage.getMessage("command.error")); 61 | } 62 | } else { 63 | src.sendMessage(messageStorage.getMessage("command.noperm")); 64 | } 65 | } else { 66 | // Get the balance of the running player 67 | if (src instanceof Player) { 68 | Player player = (Player) src; 69 | Optional uOpt = EconomyLite.getEconomyService().getOrCreateAccount(player.getUniqueId()); 70 | if (uOpt.isPresent()) { 71 | BigDecimal bal = uOpt.get().getBalance(currency); 72 | Text label = currency.getPluralDisplayName(); 73 | if (bal.equals(BigDecimal.ONE)) { 74 | label = currency.getDisplayName(); 75 | } 76 | src.sendMessage(messageStorage.getMessage("command.balance", "balance", String.format(Locale.ENGLISH, "%,.2f", bal), 77 | "label", TextSerializers.FORMATTING_CODE.serialize(label))); 78 | } else { 79 | src.sendMessage(messageStorage.getMessage("command.error")); 80 | } 81 | } else { 82 | // If the there are no arguments the source must be a player 83 | src.sendMessage(messageStorage.getMessage("command.invalidsource", "sourcetype", "player")); 84 | } 85 | } 86 | } 87 | 88 | } 89 | -------------------------------------------------------------------------------- /src/main/java/io/github/flibio/economylite/commands/currency/CurrencyCommand.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of EconomyLite, licensed under the MIT License (MIT). See the LICENSE file at the root of this project for more information. 3 | */ 4 | package io.github.flibio.economylite.commands.currency; 5 | 6 | import org.spongepowered.api.command.CommandSource; 7 | import org.spongepowered.api.command.args.CommandContext; 8 | import org.spongepowered.api.command.spec.CommandSpec; 9 | import org.spongepowered.api.command.spec.CommandSpec.Builder; 10 | 11 | import io.github.flibio.economylite.EconomyLite; 12 | import io.github.flibio.utils.commands.AsyncCommand; 13 | import io.github.flibio.utils.commands.BaseCommandExecutor; 14 | import io.github.flibio.utils.commands.Command; 15 | import io.github.flibio.utils.message.MessageStorage; 16 | 17 | @AsyncCommand 18 | @Command(aliases = {"currency", "cur"}, permission = "economylite.admin.currency") 19 | public class CurrencyCommand extends BaseCommandExecutor { 20 | 21 | private MessageStorage messageStorage = EconomyLite.getMessageStorage(); 22 | 23 | @Override 24 | public Builder getCommandSpecBuilder() { 25 | return CommandSpec.builder() 26 | .executor(this); 27 | } 28 | 29 | @Override 30 | public void run(CommandSource src, CommandContext args) { 31 | src.sendMessage(messageStorage.getMessage("command.currency.current", "currency", EconomyLite.getEconomyService().getDefaultCurrency() 32 | .getDisplayName().toPlain())); 33 | src.sendMessage(messageStorage.getMessage("command.usage", "command", "/currency", "subcommands", "set | create | delete")); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/io/github/flibio/economylite/commands/currency/CurrencyCreateCommand.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of EconomyLite, licensed under the MIT License (MIT). See the LICENSE file at the root of this project for more information. 3 | */ 4 | package io.github.flibio.economylite.commands.currency; 5 | 6 | import io.github.flibio.economylite.EconomyLite; 7 | import io.github.flibio.economylite.api.CurrencyEconService; 8 | import io.github.flibio.economylite.impl.economy.LiteCurrency; 9 | import io.github.flibio.utils.commands.AsyncCommand; 10 | import io.github.flibio.utils.commands.BaseCommandExecutor; 11 | import io.github.flibio.utils.commands.Command; 12 | import io.github.flibio.utils.commands.ParentCommand; 13 | import io.github.flibio.utils.config.ConfigManager; 14 | import io.github.flibio.utils.file.FileManager; 15 | import io.github.flibio.utils.message.MessageStorage; 16 | import org.spongepowered.api.command.CommandSource; 17 | import org.spongepowered.api.command.args.CommandContext; 18 | import org.spongepowered.api.command.args.GenericArguments; 19 | import org.spongepowered.api.command.spec.CommandSpec; 20 | import org.spongepowered.api.command.spec.CommandSpec.Builder; 21 | import org.spongepowered.api.service.economy.Currency; 22 | import org.spongepowered.api.text.Text; 23 | 24 | @AsyncCommand 25 | @ParentCommand(parentCommand = CurrencyCommand.class) 26 | @Command(aliases = {"create"}, permission = "economylite.admin.currency.create") 27 | public class CurrencyCreateCommand extends BaseCommandExecutor { 28 | 29 | private MessageStorage messageStorage = EconomyLite.getMessageStorage(); 30 | private CurrencyEconService currencyService = EconomyLite.getCurrencyService(); 31 | private ConfigManager manager = EconomyLite.getCurrencyManager(); 32 | 33 | @Override 34 | public Builder getCommandSpecBuilder() { 35 | return CommandSpec 36 | .builder() 37 | .executor(this) 38 | .arguments(GenericArguments.string(Text.of("singular")), GenericArguments.string(Text.of("plural")), 39 | GenericArguments.string(Text.of("symbol"))); 40 | } 41 | 42 | @Override 43 | public void run(CommandSource src, CommandContext args) { 44 | if (args.getOne("singular").isPresent() && args.getOne("plural").isPresent() && args.getOne("symbol").isPresent()) { 45 | String singular = args.getOne("singular").get(); 46 | String plural = args.getOne("plural").get(); 47 | String symbol = args.getOne("symbol").get(); 48 | boolean found = false; 49 | for (Currency c : currencyService.getCurrencies()) { 50 | if (c.getDisplayName().toPlain().equalsIgnoreCase(singular)) { 51 | found = true; 52 | } 53 | } 54 | if (found) { 55 | src.sendMessage(messageStorage.getMessage("command.currency.exists")); 56 | } else { 57 | Currency currency = new LiteCurrency(singular, plural, symbol, false, 2); 58 | currencyService.addCurrency(currency); 59 | String configId = currency.getId().replaceAll("economylite:", ""); 60 | manager.forceValue(currency.getDisplayName().toPlain(), configId, ".singular"); 61 | manager.forceValue(currency.getPluralDisplayName().toPlain(), configId, ".plural"); 62 | manager.forceValue(currency.getSymbol().toPlain(), configId, ".symbol"); 63 | manager.save(); 64 | src.sendMessage(messageStorage.getMessage("command.currency.created", "currency", currency.getDisplayName().toPlain())); 65 | } 66 | } else { 67 | src.sendMessage(messageStorage.getMessage("command.error")); 68 | } 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /src/main/java/io/github/flibio/economylite/commands/currency/CurrencyDeleteCommand.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of EconomyLite, licensed under the MIT License (MIT). See the LICENSE file at the root of this project for more information. 3 | */ 4 | package io.github.flibio.economylite.commands.currency; 5 | 6 | import org.spongepowered.api.command.CommandSource; 7 | import org.spongepowered.api.command.args.CommandContext; 8 | import org.spongepowered.api.command.args.GenericArguments; 9 | import org.spongepowered.api.command.spec.CommandSpec; 10 | import org.spongepowered.api.command.spec.CommandSpec.Builder; 11 | import org.spongepowered.api.service.economy.Currency; 12 | import org.spongepowered.api.text.Text; 13 | import org.spongepowered.api.text.action.TextActions; 14 | 15 | import io.github.flibio.economylite.EconomyLite; 16 | import io.github.flibio.economylite.api.CurrencyEconService; 17 | import io.github.flibio.utils.commands.AsyncCommand; 18 | import io.github.flibio.utils.commands.BaseCommandExecutor; 19 | import io.github.flibio.utils.commands.Command; 20 | import io.github.flibio.utils.commands.ParentCommand; 21 | import io.github.flibio.utils.message.MessageStorage; 22 | 23 | @AsyncCommand 24 | @ParentCommand(parentCommand = CurrencyCommand.class) 25 | @Command(aliases = {"delete"}, permission = "economylite.admin.currency.delete") 26 | public class CurrencyDeleteCommand extends BaseCommandExecutor { 27 | 28 | private MessageStorage messageStorage = EconomyLite.getMessageStorage(); 29 | private CurrencyEconService currencyService = EconomyLite.getCurrencyService(); 30 | 31 | @Override 32 | public Builder getCommandSpecBuilder() { 33 | return CommandSpec.builder() 34 | .executor(this) 35 | .arguments(GenericArguments.optional(GenericArguments.remainingJoinedStrings(Text.of("currency")))); 36 | } 37 | 38 | @Override 39 | public void run(CommandSource src, CommandContext args) { 40 | if (args.getOne("currency").isPresent()) { 41 | String currencyName = args.getOne("currency").get(); 42 | boolean found = false; 43 | for (Currency c : currencyService.getCurrencies()) { 44 | if (c.getDisplayName().toPlain().equalsIgnoreCase(currencyName)) { 45 | found = true; 46 | if (currencyService.getDefaultCurrency().equals(c)) { 47 | // You can not delete the default 48 | src.sendMessage(messageStorage.getMessage("command.currency.deletedefault")); 49 | } else { 50 | if (currencyService.getCurrentCurrency().equals(c)) { 51 | currencyService.setCurrentCurrency(currencyService.getDefaultCurrency()); 52 | } 53 | currencyService.deleteCurrency(c); 54 | src.sendMessage(messageStorage.getMessage("command.currency.deleted", "currency", c.getDisplayName().toPlain())); 55 | } 56 | } 57 | } 58 | if (!found) { 59 | src.sendMessage(messageStorage.getMessage("command.currency.invalid")); 60 | } 61 | } else { 62 | src.sendMessage(messageStorage.getMessage("command.currency.delete")); 63 | currencyService.getCurrencies().forEach(currency -> { 64 | if (!currency.equals(currencyService.getDefaultCurrency())) { 65 | src.sendMessage(Text.of(currency.getDisplayName()).toBuilder().onClick(TextActions.executeCallback(c -> { 66 | src.sendMessage(messageStorage.getMessage("command.currency.deleteconfirm", "currency", currency.getDisplayName().toPlain()) 67 | .toBuilder().onClick( 68 | TextActions.executeCallback(c2 -> { 69 | if (currencyService.getCurrentCurrency().equals(currency)) { 70 | currencyService.setCurrentCurrency(currencyService.getDefaultCurrency()); 71 | } 72 | currencyService.deleteCurrency(currency); 73 | src.sendMessage(messageStorage.getMessage("command.currency.deleted", "currency", 74 | currency.getDisplayName().toPlain())); 75 | })).build()); 76 | })).build()); 77 | } 78 | }); 79 | } 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /src/main/java/io/github/flibio/economylite/commands/currency/CurrencySetCommand.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of EconomyLite, licensed under the MIT License (MIT). See the LICENSE file at the root of this project for more information. 3 | */ 4 | package io.github.flibio.economylite.commands.currency; 5 | 6 | import org.spongepowered.api.command.CommandSource; 7 | import org.spongepowered.api.command.args.CommandContext; 8 | import org.spongepowered.api.command.args.GenericArguments; 9 | import org.spongepowered.api.command.spec.CommandSpec; 10 | import org.spongepowered.api.command.spec.CommandSpec.Builder; 11 | import org.spongepowered.api.service.economy.Currency; 12 | import org.spongepowered.api.text.Text; 13 | import org.spongepowered.api.text.action.TextActions; 14 | 15 | import io.github.flibio.economylite.EconomyLite; 16 | import io.github.flibio.economylite.api.CurrencyEconService; 17 | import io.github.flibio.utils.commands.AsyncCommand; 18 | import io.github.flibio.utils.commands.BaseCommandExecutor; 19 | import io.github.flibio.utils.commands.Command; 20 | import io.github.flibio.utils.commands.ParentCommand; 21 | import io.github.flibio.utils.message.MessageStorage; 22 | 23 | @AsyncCommand 24 | @ParentCommand(parentCommand = CurrencyCommand.class) 25 | @Command(aliases = {"set"}, permission = "economylite.admin.currency.set") 26 | public class CurrencySetCommand extends BaseCommandExecutor { 27 | 28 | private MessageStorage messageStorage = EconomyLite.getMessageStorage(); 29 | private CurrencyEconService currencyService = EconomyLite.getCurrencyService(); 30 | 31 | @Override 32 | public Builder getCommandSpecBuilder() { 33 | return CommandSpec.builder() 34 | .executor(this) 35 | .arguments(GenericArguments.optional(GenericArguments.remainingJoinedStrings(Text.of("currency")))); 36 | } 37 | 38 | @Override 39 | public void run(CommandSource src, CommandContext args) { 40 | if (args.getOne("currency").isPresent()) { 41 | String currencyName = args.getOne("currency").get(); 42 | boolean found = false; 43 | for (Currency c : currencyService.getCurrencies()) { 44 | if (c.getDisplayName().toPlain().equalsIgnoreCase(currencyName)) { 45 | currencyService.setCurrentCurrency(c); 46 | found = true; 47 | src.sendMessage(messageStorage.getMessage("command.currency.changed", "currency", c.getDisplayName().toPlain())); 48 | } 49 | } 50 | if (!found) { 51 | src.sendMessage(messageStorage.getMessage("command.currency.invalid")); 52 | } 53 | } else { 54 | src.sendMessage(messageStorage.getMessage("command.currency.current", "currency", currencyService.getCurrentCurrency().getDisplayName() 55 | .toPlain())); 56 | src.sendMessage(messageStorage.getMessage("command.currency.selectnew")); 57 | currencyService.getCurrencies().forEach(currency -> { 58 | src.sendMessage(Text.of(currency.getDisplayName()).toBuilder().onClick(TextActions.executeCallback(c -> { 59 | src.sendMessage(messageStorage.getMessage("command.currency.confirm", "currency", currency.getDisplayName().toPlain()).toBuilder() 60 | .onClick(TextActions.executeCallback(c2 -> { 61 | currencyService.setCurrentCurrency(currency); 62 | src.sendMessage( 63 | messageStorage.getMessage("command.currency.changed", "currency", currency.getDisplayName().toPlain())); 64 | })).build()); 65 | })).build()); 66 | }); 67 | } 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /src/main/java/io/github/flibio/economylite/commands/virtual/PayVirtualCommand.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of EconomyLite, licensed under the MIT License (MIT). See the LICENSE file at the root of this project for more information. 3 | */ 4 | package io.github.flibio.economylite.commands.virtual; 5 | 6 | import io.github.flibio.economylite.EconomyLite; 7 | import io.github.flibio.utils.commands.AsyncCommand; 8 | import io.github.flibio.utils.commands.BaseCommandExecutor; 9 | import io.github.flibio.utils.commands.Command; 10 | import io.github.flibio.utils.message.MessageStorage; 11 | import org.spongepowered.api.command.args.CommandContext; 12 | import org.spongepowered.api.command.args.GenericArguments; 13 | import org.spongepowered.api.command.spec.CommandSpec; 14 | import org.spongepowered.api.command.spec.CommandSpec.Builder; 15 | import org.spongepowered.api.entity.living.player.Player; 16 | import org.spongepowered.api.event.cause.Cause; 17 | import org.spongepowered.api.event.cause.EventContext; 18 | import org.spongepowered.api.service.economy.EconomyService; 19 | import org.spongepowered.api.service.economy.account.Account; 20 | import org.spongepowered.api.service.economy.account.UniqueAccount; 21 | import org.spongepowered.api.service.economy.transaction.ResultType; 22 | import org.spongepowered.api.text.Text; 23 | 24 | import java.math.BigDecimal; 25 | import java.util.Optional; 26 | 27 | @AsyncCommand 28 | @Command(aliases = {"payvirtual", "payv"}, permission = "economylite.virtual.pay") 29 | public class PayVirtualCommand extends BaseCommandExecutor { 30 | 31 | private MessageStorage messageStorage = EconomyLite.getMessageStorage(); 32 | private EconomyService ecoService = EconomyLite.getEconomyService(); 33 | 34 | @Override 35 | public Builder getCommandSpecBuilder() { 36 | return CommandSpec 37 | .builder() 38 | .executor(this) 39 | .arguments(GenericArguments.string(Text.of("target")), GenericArguments.doubleNum(Text.of("amount"))); 40 | } 41 | 42 | @Override 43 | public void run(Player src, CommandContext args) { 44 | if (args.getOne("target").isPresent() && args.getOne("amount").isPresent()) { 45 | String target = args.getOne("target").get(); 46 | BigDecimal amount = BigDecimal.valueOf(args.getOne("amount").get()); 47 | Optional aOpt = EconomyLite.getEconomyService().getOrCreateAccount(target); 48 | Optional uOpt = EconomyLite.getEconomyService().getOrCreateAccount(src.getUniqueId()); 49 | // Check for negative payments 50 | if (amount.doubleValue() <= 0) { 51 | src.sendMessage(messageStorage.getMessage("command.pay.invalid")); 52 | } else { 53 | if (aOpt.isPresent() && uOpt.isPresent()) { 54 | Account receiver = aOpt.get(); 55 | UniqueAccount payer = uOpt.get(); 56 | if (payer.transfer(receiver, ecoService.getDefaultCurrency(), amount, Cause.of(EventContext.empty(), (EconomyLite.getInstance()))) 57 | .getResult().equals(ResultType.SUCCESS)) { 58 | src.sendMessage(messageStorage.getMessage("command.pay.success", "target", receiver.getDisplayName().toPlain())); 59 | } else { 60 | src.sendMessage(messageStorage.getMessage("command.pay.failed", "target", receiver.getDisplayName().toPlain())); 61 | } 62 | } 63 | } 64 | } else { 65 | src.sendMessage(messageStorage.getMessage("command.error")); 66 | } 67 | } 68 | 69 | } 70 | -------------------------------------------------------------------------------- /src/main/java/io/github/flibio/economylite/commands/virtual/VirtualAddCommand.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of EconomyLite, licensed under the MIT License (MIT). See the LICENSE file at the root of this project for more information. 3 | */ 4 | package io.github.flibio.economylite.commands.virtual; 5 | 6 | import io.github.flibio.economylite.EconomyLite; 7 | import io.github.flibio.utils.commands.AsyncCommand; 8 | import io.github.flibio.utils.commands.BaseCommandExecutor; 9 | import io.github.flibio.utils.commands.Command; 10 | import io.github.flibio.utils.commands.ParentCommand; 11 | import io.github.flibio.utils.message.MessageStorage; 12 | import org.spongepowered.api.command.CommandSource; 13 | import org.spongepowered.api.command.args.CommandContext; 14 | import org.spongepowered.api.command.args.GenericArguments; 15 | import org.spongepowered.api.command.spec.CommandSpec; 16 | import org.spongepowered.api.command.spec.CommandSpec.Builder; 17 | import org.spongepowered.api.event.cause.Cause; 18 | import org.spongepowered.api.event.cause.EventContext; 19 | import org.spongepowered.api.service.economy.account.Account; 20 | import org.spongepowered.api.service.economy.transaction.ResultType; 21 | import org.spongepowered.api.text.Text; 22 | 23 | import java.math.BigDecimal; 24 | import java.util.Optional; 25 | 26 | @AsyncCommand 27 | @ParentCommand(parentCommand = VirtualEconCommand.class) 28 | @Command(aliases = {"add"}, permission = "economylite.admin.virtual.add") 29 | public class VirtualAddCommand extends BaseCommandExecutor { 30 | 31 | private MessageStorage messageStorage = EconomyLite.getMessageStorage(); 32 | 33 | @Override 34 | public Builder getCommandSpecBuilder() { 35 | return CommandSpec.builder() 36 | .executor(this) 37 | .arguments(GenericArguments.string(Text.of("account")), GenericArguments.doubleNum(Text.of("amount"))); 38 | } 39 | 40 | @Override 41 | public void run(CommandSource src, CommandContext args) { 42 | if (args.getOne("account").isPresent() && args.getOne("amount").isPresent()) { 43 | String target = args.getOne("account").get(); 44 | BigDecimal toAdd = BigDecimal.valueOf(args.getOne("amount").get()); 45 | Optional aOpt = EconomyLite.getEconomyService().getOrCreateAccount(target); 46 | if (aOpt.isPresent()) { 47 | Account targetAccount = aOpt.get(); 48 | if (targetAccount.deposit(EconomyLite.getCurrencyService().getCurrentCurrency(), toAdd, 49 | Cause.of(EventContext.empty(),(EconomyLite.getInstance()))).getResult().equals(ResultType.SUCCESS)) { 50 | src.sendMessage(messageStorage.getMessage("command.econ.addsuccess", "name", target)); 51 | } else { 52 | src.sendMessage(messageStorage.getMessage("command.econ.addfail", "name", target)); 53 | } 54 | } else { 55 | src.sendMessage(messageStorage.getMessage("command.error")); 56 | } 57 | } else { 58 | src.sendMessage(messageStorage.getMessage("command.error")); 59 | } 60 | } 61 | 62 | } 63 | -------------------------------------------------------------------------------- /src/main/java/io/github/flibio/economylite/commands/virtual/VirtualBalanceCommand.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of EconomyLite, licensed under the MIT License (MIT). See the LICENSE file at the root of this project for more information. 3 | */ 4 | package io.github.flibio.economylite.commands.virtual; 5 | 6 | import org.spongepowered.api.command.CommandSource; 7 | import org.spongepowered.api.command.args.CommandContext; 8 | import org.spongepowered.api.command.args.GenericArguments; 9 | import org.spongepowered.api.command.spec.CommandSpec; 10 | import org.spongepowered.api.command.spec.CommandSpec.Builder; 11 | import org.spongepowered.api.service.economy.Currency; 12 | import org.spongepowered.api.service.economy.account.Account; 13 | import org.spongepowered.api.text.Text; 14 | import com.google.common.collect.ImmutableMap; 15 | import io.github.flibio.economylite.EconomyLite; 16 | import io.github.flibio.economylite.api.CurrencyEconService; 17 | import io.github.flibio.utils.commands.AsyncCommand; 18 | import io.github.flibio.utils.commands.BaseCommandExecutor; 19 | import io.github.flibio.utils.commands.Command; 20 | import io.github.flibio.utils.message.MessageStorage; 21 | 22 | import java.math.BigDecimal; 23 | import java.util.Locale; 24 | import java.util.Optional; 25 | 26 | @AsyncCommand 27 | @Command(aliases = {"vbalance", "vbal"}, permission = "economylite.admin.virtual.balance") 28 | public class VirtualBalanceCommand extends BaseCommandExecutor { 29 | 30 | private MessageStorage messageStorage = EconomyLite.getMessageStorage(); 31 | private CurrencyEconService currencyService = EconomyLite.getCurrencyService(); 32 | 33 | @Override 34 | public Builder getCommandSpecBuilder() { 35 | return CommandSpec.builder() 36 | .executor(this) 37 | .arguments(GenericArguments.remainingJoinedStrings(Text.of("account"))); 38 | } 39 | 40 | @Override 41 | public void run(CommandSource src, CommandContext args) { 42 | Currency currency = currencyService.getCurrentCurrency(); 43 | if (args.getOne("account").isPresent()) { 44 | if (src.hasPermission("economylite.admin.virtualbalance")) { 45 | String target = args.getOne("account").get(); 46 | Optional aOpt = EconomyLite.getEconomyService().getOrCreateAccount(target); 47 | if (aOpt.isPresent()) { 48 | BigDecimal bal = aOpt.get().getBalance(currency); 49 | Text label = currency.getPluralDisplayName(); 50 | if (bal.equals(BigDecimal.ONE)) { 51 | label = currency.getDisplayName(); 52 | } 53 | src.sendMessage(messageStorage.getMessage("command.balanceother", "player", aOpt.get().getDisplayName().toPlain(), "balance", 54 | String.format(Locale.ENGLISH, "%,.2f", bal), "label", label.toPlain())); 55 | } else { 56 | src.sendMessage(messageStorage.getMessage("command.error")); 57 | } 58 | } else { 59 | src.sendMessage(messageStorage.getMessage("command.noperm")); 60 | } 61 | } else { 62 | src.sendMessage(messageStorage.getMessage("command.error")); 63 | } 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /src/main/java/io/github/flibio/economylite/commands/virtual/VirtualEconCommand.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of EconomyLite, licensed under the MIT License (MIT). See the LICENSE file at the root of this project for more information. 3 | */ 4 | package io.github.flibio.economylite.commands.virtual; 5 | 6 | import io.github.flibio.economylite.EconomyLite; 7 | import io.github.flibio.utils.commands.AsyncCommand; 8 | import io.github.flibio.utils.commands.BaseCommandExecutor; 9 | import io.github.flibio.utils.commands.Command; 10 | import io.github.flibio.utils.message.MessageStorage; 11 | import org.spongepowered.api.command.CommandSource; 12 | import org.spongepowered.api.command.args.CommandContext; 13 | import org.spongepowered.api.command.spec.CommandSpec; 14 | import org.spongepowered.api.command.spec.CommandSpec.Builder; 15 | 16 | @AsyncCommand 17 | @Command(aliases = {"veconomy", "vecon", "veco"}, permission = "economylite.admin.virtual") 18 | public class VirtualEconCommand extends BaseCommandExecutor { 19 | 20 | private MessageStorage messageStorage = EconomyLite.getMessageStorage(); 21 | 22 | @Override 23 | public Builder getCommandSpecBuilder() { 24 | return CommandSpec.builder() 25 | .executor(this); 26 | } 27 | 28 | @Override 29 | public void run(CommandSource src, CommandContext args) { 30 | src.sendMessage(messageStorage.getMessage("command.usage", "command", "/vecon", "subcommands", "add | set | remove ")); 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/io/github/flibio/economylite/commands/virtual/VirtualPayCommand.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of EconomyLite, licensed under the MIT License (MIT). See the LICENSE file at the root of this project for more information. 3 | */ 4 | package io.github.flibio.economylite.commands.virtual; 5 | 6 | import io.github.flibio.economylite.EconomyLite; 7 | import io.github.flibio.utils.commands.AsyncCommand; 8 | import io.github.flibio.utils.commands.BaseCommandExecutor; 9 | import io.github.flibio.utils.commands.Command; 10 | import io.github.flibio.utils.message.MessageStorage; 11 | import org.spongepowered.api.command.CommandSource; 12 | import org.spongepowered.api.command.args.CommandContext; 13 | import org.spongepowered.api.command.args.GenericArguments; 14 | import org.spongepowered.api.command.spec.CommandSpec; 15 | import org.spongepowered.api.command.spec.CommandSpec.Builder; 16 | import org.spongepowered.api.entity.living.player.Player; 17 | import org.spongepowered.api.entity.living.player.User; 18 | import org.spongepowered.api.event.cause.Cause; 19 | import org.spongepowered.api.event.cause.EventContext; 20 | import org.spongepowered.api.service.economy.EconomyService; 21 | import org.spongepowered.api.service.economy.account.Account; 22 | import org.spongepowered.api.service.economy.account.UniqueAccount; 23 | import org.spongepowered.api.service.economy.transaction.ResultType; 24 | import org.spongepowered.api.text.Text; 25 | 26 | import java.math.BigDecimal; 27 | import java.util.Locale; 28 | import java.util.Optional; 29 | 30 | @AsyncCommand 31 | @Command(aliases = {"vpay"}, permission = "economylite.admin.virtual.pay") 32 | public class VirtualPayCommand extends BaseCommandExecutor { 33 | 34 | private MessageStorage messageStorage = EconomyLite.getMessageStorage(); 35 | private EconomyService ecoService = EconomyLite.getEconomyService(); 36 | 37 | @Override 38 | public Builder getCommandSpecBuilder() { 39 | return CommandSpec 40 | .builder() 41 | .executor(this) 42 | .arguments(GenericArguments.string(Text.of("account")), GenericArguments.user(Text.of("target")), 43 | GenericArguments.doubleNum(Text.of("amount"))); 44 | } 45 | 46 | @Override 47 | public void run(CommandSource src, CommandContext args) { 48 | if (args.getOne("account").isPresent() && args.getOne("target").isPresent() && args.getOne("amount").isPresent()) { 49 | String account = args.getOne("account").get(); 50 | User target = args.getOne("target").get(); 51 | BigDecimal amount = BigDecimal.valueOf(args.getOne("amount").get()); 52 | Optional aOpt = EconomyLite.getEconomyService().getOrCreateAccount(account); 53 | Optional uOpt = EconomyLite.getEconomyService().getOrCreateAccount(target.getUniqueId()); 54 | // Check for negative payments 55 | if (amount.compareTo(BigDecimal.ONE) == -1) { 56 | src.sendMessage(messageStorage.getMessage("command.pay.invalid")); 57 | } else { 58 | if (aOpt.isPresent() && uOpt.isPresent()) { 59 | Account payer = aOpt.get(); 60 | UniqueAccount receiver = uOpt.get(); 61 | if (payer.transfer(receiver, ecoService.getDefaultCurrency(), amount, Cause.of(EventContext.empty(), EconomyLite.getInstance 62 | ())) 63 | .getResult().equals(ResultType.SUCCESS)) { 64 | src.sendMessage(messageStorage.getMessage("command.pay.success", "target", target.getName())); 65 | if (target instanceof Player) { 66 | Text label = ecoService.getDefaultCurrency().getPluralDisplayName(); 67 | if (amount.equals(BigDecimal.ONE)) { 68 | label = ecoService.getDefaultCurrency().getDisplayName(); 69 | } 70 | ((Player) target).sendMessage(messageStorage.getMessage("command.pay.target", "amountandlabel", 71 | String.format(Locale.ENGLISH, "%,.2f", amount) + " " + label.toPlain(), "sender", 72 | payer.getDisplayName().toPlain())); 73 | } 74 | } else { 75 | src.sendMessage(messageStorage.getMessage("command.pay.failed", "target", target.getName())); 76 | } 77 | } 78 | } 79 | } else { 80 | src.sendMessage(messageStorage.getMessage("command.error")); 81 | } 82 | } 83 | 84 | } 85 | -------------------------------------------------------------------------------- /src/main/java/io/github/flibio/economylite/commands/virtual/VirtualRemoveCommand.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of EconomyLite, licensed under the MIT License (MIT). See the LICENSE file at the root of this project for more information. 3 | */ 4 | package io.github.flibio.economylite.commands.virtual; 5 | 6 | import io.github.flibio.economylite.EconomyLite; 7 | import io.github.flibio.utils.commands.AsyncCommand; 8 | import io.github.flibio.utils.commands.BaseCommandExecutor; 9 | import io.github.flibio.utils.commands.Command; 10 | import io.github.flibio.utils.commands.ParentCommand; 11 | import io.github.flibio.utils.message.MessageStorage; 12 | import org.spongepowered.api.command.CommandSource; 13 | import org.spongepowered.api.command.args.CommandContext; 14 | import org.spongepowered.api.command.args.GenericArguments; 15 | import org.spongepowered.api.command.spec.CommandSpec; 16 | import org.spongepowered.api.command.spec.CommandSpec.Builder; 17 | import org.spongepowered.api.event.cause.Cause; 18 | import org.spongepowered.api.event.cause.EventContext; 19 | import org.spongepowered.api.service.economy.account.Account; 20 | import org.spongepowered.api.service.economy.transaction.ResultType; 21 | import org.spongepowered.api.text.Text; 22 | 23 | import java.math.BigDecimal; 24 | import java.util.Optional; 25 | 26 | @AsyncCommand 27 | @ParentCommand(parentCommand = VirtualEconCommand.class) 28 | @Command(aliases = {"remove"}, permission = "economylite.admin.virtual.remove") 29 | public class VirtualRemoveCommand extends BaseCommandExecutor { 30 | 31 | private MessageStorage messageStorage = EconomyLite.getMessageStorage(); 32 | 33 | @Override 34 | public Builder getCommandSpecBuilder() { 35 | return CommandSpec.builder() 36 | .executor(this) 37 | .arguments(GenericArguments.string(Text.of("account")), GenericArguments.doubleNum(Text.of("amount"))); 38 | } 39 | 40 | @Override 41 | public void run(CommandSource src, CommandContext args) { 42 | if (args.getOne("account").isPresent() && args.getOne("amount").isPresent()) { 43 | String target = args.getOne("account").get(); 44 | BigDecimal toRemove = BigDecimal.valueOf(args.getOne("amount").get()); 45 | Optional aOpt = EconomyLite.getEconomyService().getOrCreateAccount(target); 46 | if (aOpt.isPresent()) { 47 | Account targetAccount = aOpt.get(); 48 | if (targetAccount.withdraw(EconomyLite.getCurrencyService().getCurrentCurrency(), toRemove, 49 | Cause.of(EventContext.empty(),(EconomyLite.getInstance()))).getResult().equals(ResultType.SUCCESS)) { 50 | src.sendMessage(messageStorage.getMessage("command.econ.removesuccess", "name", target)); 51 | } else { 52 | src.sendMessage(messageStorage.getMessage("command.econ.removefail", "name", target)); 53 | } 54 | } else { 55 | src.sendMessage(messageStorage.getMessage("command.error")); 56 | } 57 | } else { 58 | src.sendMessage(messageStorage.getMessage("command.error")); 59 | } 60 | } 61 | 62 | } 63 | -------------------------------------------------------------------------------- /src/main/java/io/github/flibio/economylite/commands/virtual/VirtualSetCommand.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of EconomyLite, licensed under the MIT License (MIT). See the LICENSE file at the root of this project for more information. 3 | */ 4 | package io.github.flibio.economylite.commands.virtual; 5 | 6 | import io.github.flibio.utils.commands.ParentCommand; 7 | 8 | import org.spongepowered.api.command.CommandSource; 9 | import org.spongepowered.api.command.args.CommandContext; 10 | import org.spongepowered.api.command.args.GenericArguments; 11 | import org.spongepowered.api.command.spec.CommandSpec; 12 | import org.spongepowered.api.command.spec.CommandSpec.Builder; 13 | import org.spongepowered.api.event.cause.Cause; 14 | import org.spongepowered.api.event.cause.EventContext; 15 | import org.spongepowered.api.service.economy.account.Account; 16 | import org.spongepowered.api.service.economy.transaction.ResultType; 17 | import org.spongepowered.api.text.Text; 18 | import io.github.flibio.economylite.EconomyLite; 19 | import io.github.flibio.utils.commands.AsyncCommand; 20 | import io.github.flibio.utils.commands.BaseCommandExecutor; 21 | import io.github.flibio.utils.commands.Command; 22 | import io.github.flibio.utils.message.MessageStorage; 23 | 24 | import java.math.BigDecimal; 25 | import java.util.Optional; 26 | 27 | @AsyncCommand 28 | @ParentCommand(parentCommand = VirtualEconCommand.class) 29 | @Command(aliases = {"set"}, permission = "economylite.admin.virtual.set") 30 | public class VirtualSetCommand extends BaseCommandExecutor { 31 | 32 | private MessageStorage messageStorage = EconomyLite.getMessageStorage(); 33 | 34 | @Override 35 | public Builder getCommandSpecBuilder() { 36 | return CommandSpec.builder() 37 | .executor(this) 38 | .arguments(GenericArguments.string(Text.of("account")), GenericArguments.doubleNum(Text.of("amount"))); 39 | } 40 | 41 | @Override 42 | public void run(CommandSource src, CommandContext args) { 43 | if (args.getOne("account").isPresent() && args.getOne("amount").isPresent()) { 44 | String target = args.getOne("account").get(); 45 | BigDecimal newBal = BigDecimal.valueOf(args.getOne("amount").get()); 46 | Optional aOpt = EconomyLite.getEconomyService().getOrCreateAccount(target); 47 | if (aOpt.isPresent()) { 48 | Account targetAccount = aOpt.get(); 49 | if (targetAccount.setBalance(EconomyLite.getCurrencyService().getCurrentCurrency(), newBal, 50 | Cause.of(EventContext.empty(), (EconomyLite.getInstance()))).getResult().equals(ResultType.SUCCESS)) { 51 | src.sendMessage(messageStorage.getMessage("command.econ.setsuccess", "name", targetAccount.getDisplayName().toPlain())); 52 | } else { 53 | src.sendMessage(messageStorage.getMessage("command.econ.setfail", "name", targetAccount.getDisplayName().toPlain())); 54 | } 55 | } else { 56 | src.sendMessage(messageStorage.getMessage("command.error")); 57 | } 58 | } else { 59 | src.sendMessage(messageStorage.getMessage("command.error")); 60 | } 61 | } 62 | 63 | } 64 | -------------------------------------------------------------------------------- /src/main/java/io/github/flibio/economylite/impl/CurrencyService.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of EconomyLite, licensed under the MIT License (MIT). See the LICENSE file at the root of this project for more information. 3 | */ 4 | package io.github.flibio.economylite.impl; 5 | 6 | import io.github.flibio.economylite.CauseFactory; 7 | import io.github.flibio.economylite.EconomyLite; 8 | import io.github.flibio.economylite.api.CurrencyEconService; 9 | import org.spongepowered.api.service.economy.Currency; 10 | 11 | import java.util.HashSet; 12 | import java.util.Set; 13 | 14 | public class CurrencyService implements CurrencyEconService { 15 | 16 | private HashSet currencies = new HashSet(); 17 | private Currency defaultCurrency; 18 | private Currency currentCurrency; 19 | 20 | public CurrencyService(Currency defaultCurrency) { 21 | this.defaultCurrency = defaultCurrency; 22 | this.currentCurrency = defaultCurrency; 23 | } 24 | 25 | @Override 26 | public void addCurrency(Currency currency) { 27 | currencies.add(currency); 28 | } 29 | 30 | @Override 31 | public Set getCurrencies() { 32 | HashSet set = currencies; 33 | set.add(defaultCurrency); 34 | return set; 35 | } 36 | 37 | @Override 38 | public Currency getDefaultCurrency() { 39 | return defaultCurrency; 40 | } 41 | 42 | @Override 43 | public void setCurrentCurrency(Currency currency) { 44 | this.currentCurrency = currency; 45 | EconomyLite.getCurrencyManager().forceValue(currency.getId().replaceAll("economylite:", ""), "current"); 46 | EconomyLite.getCurrencyManager().save(); 47 | } 48 | 49 | @Override 50 | public Currency getCurrentCurrency() { 51 | return currentCurrency; 52 | } 53 | 54 | @Override 55 | public void deleteCurrency(Currency currency) { 56 | if (currency != defaultCurrency) { 57 | EconomyLite.getPlayerService().clearCurrency(currency, CauseFactory.create("Currency deletion")); 58 | EconomyLite.getVirtualService().clearCurrency(currency, CauseFactory.create("Currency deletion")); 59 | currencies.remove(currency); 60 | EconomyLite.getCurrencyManager().forceValue(null, currency.getId().replaceAll("economylite:", "")); 61 | EconomyLite.getCurrencyManager().save(); 62 | } 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /src/main/java/io/github/flibio/economylite/impl/PlayerDataService.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of EconomyLite, licensed under the MIT License (MIT). See the LICENSE file at the root of this project for more information. 3 | */ 4 | package io.github.flibio.economylite.impl; 5 | 6 | import io.github.flibio.economylite.EconomyLite; 7 | import io.github.flibio.utils.sql.LocalSqlManager; 8 | 9 | import java.io.File; 10 | 11 | public class PlayerDataService extends PlayerServiceCommon { 12 | 13 | public PlayerDataService() { 14 | super(LocalSqlManager.createInstance(EconomyLite.getInstance(), "data", correctPath(EconomyLite.getInstance().getConfigDir().toString())) 15 | .get(), true); 16 | } 17 | 18 | private static String correctPath(String path) { 19 | if (new File(path).isAbsolute()) { 20 | return path; 21 | } else { 22 | return "./" + path; 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/io/github/flibio/economylite/impl/PlayerServiceCommon.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of EconomyLite, licensed under the MIT License (MIT). See the LICENSE file at the root of this project for more information. 3 | */ 4 | package io.github.flibio.economylite.impl; 5 | 6 | import io.github.flibio.economylite.CauseFactory; 7 | 8 | import io.github.flibio.economylite.EconomyLite; 9 | import io.github.flibio.economylite.api.PlayerEconService; 10 | import io.github.flibio.utils.sql.CacheManager; 11 | import io.github.flibio.utils.sql.SqlManager; 12 | import org.slf4j.Logger; 13 | import org.spongepowered.api.event.cause.Cause; 14 | import org.spongepowered.api.service.economy.Currency; 15 | import org.spongepowered.api.service.economy.EconomyService; 16 | import org.spongepowered.api.service.economy.account.UniqueAccount; 17 | import org.spongepowered.api.service.economy.account.VirtualAccount; 18 | 19 | import java.math.BigDecimal; 20 | import java.sql.Connection; 21 | import java.sql.PreparedStatement; 22 | import java.sql.ResultSet; 23 | import java.util.ArrayList; 24 | import java.util.List; 25 | import java.util.Optional; 26 | import java.util.UUID; 27 | 28 | import javax.sql.DataSource; 29 | 30 | public class PlayerServiceCommon implements PlayerEconService { 31 | 32 | private SqlManager manager; 33 | private boolean log; 34 | private Logger logger = EconomyLite.getInstance().getLogger(); 35 | 36 | private CacheManager balCache; 37 | private CacheManager exCache; 38 | private CacheManager> topCache; 39 | 40 | public PlayerServiceCommon(SqlManager manager, boolean h2) { 41 | this.manager = manager; 42 | this.log = EconomyLite.getConfigManager().getValue(Boolean.class, false, "debug-logging"); 43 | if (manager.initialTestConnection()) { 44 | manager.executeUpdate("CREATE TABLE IF NOT EXISTS economyliteplayers(uuid VARCHAR(36), balance DECIMAL(11,2), currency VARCHAR(1024))"); 45 | } 46 | repair(h2); 47 | // Create caches 48 | balCache = CacheManager.create(logger, 64, 360); 49 | exCache = CacheManager.create(logger, 128, 360); 50 | topCache = CacheManager.create(logger, 16, 30); 51 | } 52 | 53 | private void repair(boolean h2) { 54 | if (h2) { 55 | if (needRepair("SELECT * FROM INFORMATION_SCHEMA.CONSTRAINTS WHERE TABLE_NAME = 'ECONOMYLITEPLAYERS'")) { 56 | logger.info("Repairing the database..."); 57 | } else { 58 | logger.debug("Database repairs not necessary!"); 59 | return; 60 | } 61 | logger.info("Renaming database..."); 62 | manager.executeUpdate("ALTER TABLE economyliteplayers RENAME TO economyliteplayersold"); 63 | logger.info("Recreating database..."); 64 | manager.executeUpdate("CREATE TABLE economyliteplayers AS SELECT * FROM economyliteplayersold"); 65 | logger.info("Dropping database..."); 66 | manager.executeUpdate("DROP TABLE economyliteplayersold"); 67 | logger.info("Repairs complete!"); 68 | return; 69 | } else { 70 | if (needRepair("show index from economyliteplayers where Column_name='uuid'")) { 71 | logger.info("Repairing the database..."); 72 | } else { 73 | logger.debug("Database repairs not necessary!"); 74 | return; 75 | } 76 | logger.info("Renaming database..."); 77 | manager.executeUpdate("RENAME TABLE economyliteplayers TO economyliteplayersold"); 78 | logger.info("Recreating database..."); 79 | manager.executeUpdate("CREATE TABLE economyliteplayers AS SELECT * FROM economyliteplayersold"); 80 | logger.info("Dropping database..."); 81 | manager.executeUpdate("DROP TABLE economyliteplayersold"); 82 | logger.info("Repairs complete!"); 83 | return; 84 | } 85 | } 86 | 87 | /** 88 | * Returns true if database needs to be repaired. 89 | */ 90 | private boolean needRepair(String sql) { 91 | DataSource source = manager.getDataSource(); 92 | try { 93 | Connection con = source.getConnection(); 94 | try { 95 | PreparedStatement ps = con.prepareStatement(sql); 96 | ps.closeOnCompletion(); 97 | ResultSet rs = ps.executeQuery(); 98 | rs.next(); 99 | rs.getString(1); 100 | } finally { 101 | con.close(); 102 | } 103 | } catch (Exception e) { 104 | return false; 105 | } 106 | 107 | return true; 108 | } 109 | 110 | public void resetCache() { 111 | balCache.clear(); 112 | exCache.clear(); 113 | topCache.clear(); 114 | } 115 | 116 | public boolean isWorking() { 117 | return manager.testConnection(); 118 | } 119 | 120 | public BigDecimal getBalance(UUID uuid, Currency currency, Cause cause, boolean cache) { 121 | BigDecimal result = balCache.getIfPresent(formId(uuid, currency)); 122 | if (cache && result != null) { 123 | debug("playercommon: {C} Balance of '" + uuid.toString() + "' - " + cause.toString() + " = " + result.toPlainString()); 124 | return result; 125 | } 126 | Optional bOpt = 127 | manager.queryType("balance", BigDecimal.class, "SELECT balance FROM economyliteplayers WHERE uuid = ? AND currency = ?", 128 | uuid.toString(), currency.getId()); 129 | result = (bOpt.isPresent()) ? bOpt.get() : BigDecimal.ZERO; 130 | balCache.update(formId(uuid, currency), result); 131 | exCache.update(formId(uuid, currency), true); 132 | debug("playercommon: Balance of '" + uuid.toString() + "' - " + cause.toString() + " = " + result.toPlainString()); 133 | return result; 134 | } 135 | 136 | public boolean setBalance(UUID uuid, BigDecimal balance, Currency currency, Cause cause) { 137 | boolean result; 138 | if (accountExists(uuid, currency, cause)) { 139 | result = manager.executeUpdate("UPDATE economyliteplayers SET balance = ? WHERE uuid = ? AND currency = ?", balance.toString(), 140 | uuid.toString(), currency.getId()); 141 | debug("playercommon: +Account Exists+ Setting balance of '" + uuid.toString() + "' to '" + balance.toPlainString() + "' with '" 142 | + currency.getId() + "' - " + cause.toString() + " = " + result); 143 | } else { 144 | result = manager.executeUpdate("INSERT INTO economyliteplayers (`uuid`, `balance`, `currency`) VALUES (?, ?, ?)", 145 | uuid.toString(), balance.toString(), currency.getId()); 146 | debug("playercommon: +Account Does Not Exist+ Setting balance of '" + uuid.toString() + "' to '" + balance.toPlainString() 147 | + "' with '" + currency.getId() + "' - " + cause.toString() + " = " + result); 148 | } 149 | if (result) { 150 | balCache.update(formId(uuid, currency), balance); 151 | exCache.update(formId(uuid, currency), true); 152 | } 153 | return result; 154 | } 155 | 156 | public boolean accountExists(UUID uuid, Currency currency, Cause cause) { 157 | Boolean result = exCache.getIfPresent(formId(uuid, currency)); 158 | if (result != null) { 159 | debug("playercommon: {C} Checking if '" + uuid.toString() + "' exists with '" + currency.getId() + "' - " + cause.toString() + " = " 160 | + result); 161 | return result; 162 | } 163 | result = manager.queryExists("SELECT uuid FROM economyliteplayers WHERE uuid = ? AND currency = ?", uuid.toString(), currency.getId()); 164 | debug("playercommon: Checking if '" + uuid.toString() + "' exists with '" + currency.getId() + "' - " + cause.toString() + " = " + result); 165 | exCache.update(formId(uuid, currency), result); 166 | return result; 167 | } 168 | 169 | public void clearCurrency(Currency currency, Cause cause) { 170 | boolean result = manager.executeUpdate("DELETE FROM economyliteplayers WHERE currency = ?", currency.getId()); 171 | debug("playercommon: Clearing currency '" + currency.getId() + "' - " + cause.toString() + " = " + result); 172 | balCache.clear(); 173 | exCache.clear(); 174 | topCache.clear(); 175 | } 176 | 177 | public List getTopAccounts(int start, int end, Cause cause) { 178 | debug("playercommon: Getting top accounts - " + cause.toString()); 179 | String mid = start + "-" + end + ":" + EconomyLite.getEconomyService().getDefaultCurrency().getId(); 180 | List accounts = topCache.getIfPresent(mid); 181 | if (accounts != null) { 182 | return accounts; 183 | } 184 | int offset = start - 1; 185 | int limit = end - offset; 186 | accounts = new ArrayList<>(); 187 | List uuids = 188 | manager.queryTypeList("uuid", String.class, 189 | "SELECT uuid FROM economyliteplayers WHERE currency = ? ORDER BY balance DESC LIMIT ?, ?", 190 | EconomyLite.getEconomyService().getDefaultCurrency().getId(), offset, limit); 191 | EconomyService ecoService = EconomyLite.getEconomyService(); 192 | for (String uuid : uuids) { 193 | Optional uOpt = ecoService.getOrCreateAccount(UUID.fromString(uuid)); 194 | if (uOpt.isPresent()) { 195 | accounts.add(uOpt.get()); 196 | } 197 | } 198 | topCache.update(mid, accounts); 199 | return accounts; 200 | } 201 | 202 | public boolean setBalanceAll(BigDecimal balance, Currency currency, Cause cause) { 203 | boolean result = manager.executeUpdate("UPDATE economyliteplayers SET balance = ? WHERE currency = ?", balance.toString(), currency.getId()); 204 | debug("playercommon: +Account Exists+ Setting balance of ALL to '" + balance.toPlainString() + "' with '" 205 | + currency.getId() + "' - " + cause.toString() + " = " + result); 206 | topCache.clear(); 207 | balCache.clear(); 208 | return result; 209 | } 210 | 211 | public List getAccountsMigration() { 212 | List accounts = new ArrayList<>(); 213 | try { 214 | Connection con = manager.getDataSource().getConnection(); 215 | try { 216 | PreparedStatement ps = con.prepareStatement("SELECT * FROM economyliteplayers"); 217 | ps.closeOnCompletion(); 218 | 219 | ResultSet rs = ps.executeQuery(); 220 | try { 221 | while (rs.next()) { 222 | accounts.add(rs.getString("uuid") + "%-%" + rs.getDouble("balance") + "%-%" + rs.getString("currency")); 223 | } 224 | rs.close(); 225 | return accounts; 226 | } catch (Exception e) { 227 | logger.error(e.getMessage()); 228 | return accounts; 229 | } 230 | 231 | } finally { 232 | con.close(); 233 | } 234 | } catch (Exception e) { 235 | e.printStackTrace(); 236 | } 237 | return accounts; 238 | } 239 | 240 | public void setRawData(String uuid, String bal, Currency currency) { 241 | if (accountExists(UUID.fromString(uuid), currency, CauseFactory.stringCause("Migration"))) { 242 | manager.executeUpdate("UPDATE economyliteplayers SET balance = ? WHERE uuid = ? AND currency = ?", bal, uuid, currency.getId()); 243 | } else { 244 | manager.executeUpdate("INSERT INTO economyliteplayers (`uuid`, `balance`, `currency`) VALUES (?, ?, ?)", uuid, bal, currency.getId()); 245 | } 246 | } 247 | 248 | private void debug(String message) { 249 | if (log) { 250 | logger.debug(message); 251 | } 252 | } 253 | 254 | private String formId(UUID id, Currency currency) { 255 | return id.toString() + ":" + currency.getId(); 256 | } 257 | } 258 | -------------------------------------------------------------------------------- /src/main/java/io/github/flibio/economylite/impl/VirtualDataService.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of EconomyLite, licensed under the MIT License (MIT). See the LICENSE file at the root of this project for more information. 3 | */ 4 | package io.github.flibio.economylite.impl; 5 | 6 | import java.io.File; 7 | 8 | import io.github.flibio.economylite.EconomyLite; 9 | import io.github.flibio.utils.sql.LocalSqlManager; 10 | 11 | public class VirtualDataService extends VirtualServiceCommon { 12 | 13 | public VirtualDataService() { 14 | super(LocalSqlManager.createInstance(EconomyLite.getInstance(), "data", correctPath(EconomyLite.getInstance().getConfigDir().toString())) 15 | .get(), true); 16 | } 17 | 18 | private static String correctPath(String path) { 19 | if (new File(path).isAbsolute()) { 20 | return path; 21 | } else { 22 | return "./" + path; 23 | } 24 | } 25 | 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/io/github/flibio/economylite/impl/VirtualServiceCommon.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of EconomyLite, licensed under the MIT License (MIT). See the LICENSE file at the root of this project for more information. 3 | */ 4 | package io.github.flibio.economylite.impl; 5 | 6 | import com.google.common.cache.Cache; 7 | import com.google.common.cache.CacheBuilder; 8 | import io.github.flibio.economylite.EconomyLite; 9 | import io.github.flibio.economylite.api.VirtualEconService; 10 | import io.github.flibio.utils.sql.CacheManager; 11 | import io.github.flibio.utils.sql.SqlManager; 12 | import org.slf4j.Logger; 13 | import org.spongepowered.api.event.cause.Cause; 14 | import org.spongepowered.api.service.economy.Currency; 15 | import org.spongepowered.api.service.economy.EconomyService; 16 | import org.spongepowered.api.service.economy.account.Account; 17 | import org.spongepowered.api.service.economy.account.VirtualAccount; 18 | 19 | import java.math.BigDecimal; 20 | import java.sql.Connection; 21 | import java.sql.PreparedStatement; 22 | import java.sql.ResultSet; 23 | import java.util.ArrayList; 24 | import java.util.List; 25 | import java.util.Optional; 26 | import java.util.concurrent.TimeUnit; 27 | 28 | import javax.sql.DataSource; 29 | 30 | public class VirtualServiceCommon implements VirtualEconService { 31 | 32 | private SqlManager manager; 33 | private boolean log; 34 | private Logger logger = EconomyLite.getInstance().getLogger(); 35 | 36 | private CacheManager balCache; 37 | private CacheManager exCache; 38 | private CacheManager> topCache; 39 | 40 | public VirtualServiceCommon(SqlManager manager, boolean h2) { 41 | this.manager = manager; 42 | this.log = EconomyLite.getConfigManager().getValue(Boolean.class, false, "debug-logging"); 43 | if (manager.initialTestConnection()) { 44 | manager.executeUpdate("CREATE TABLE IF NOT EXISTS economylitevirts(id VARCHAR(36), balance DECIMAL(11,2), currency VARCHAR(1024))"); 45 | if (h2) { 46 | manager.executeUpdate("ALTER TABLE `economylitevirts` ALTER COLUMN `id` VARCHAR(1024)"); 47 | } else { 48 | manager.executeUpdate("ALTER TABLE `economylitevirts` CHANGE `id` `id` VARCHAR(1024)"); 49 | } 50 | } 51 | repair(h2); 52 | // Create caches 53 | balCache = CacheManager.create(logger, 64, 360); 54 | exCache = CacheManager.create(logger, 128, 360); 55 | topCache = CacheManager.create(logger, 16, 30); 56 | } 57 | 58 | private void repair(boolean h2) { 59 | if (h2) { 60 | if (needRepair("SELECT * FROM INFORMATION_SCHEMA.CONSTRAINTS WHERE TABLE_NAME = 'ECONOMYLITEVIRTS'")) { 61 | logger.info("Repairing the database..."); 62 | } else { 63 | logger.debug("Database repairs not necessary!"); 64 | return; 65 | } 66 | logger.info("Renaming database..."); 67 | manager.executeUpdate("ALTER TABLE economylitevirts RENAME TO economylitevirtsold"); 68 | logger.info("Recreating database..."); 69 | manager.executeUpdate("CREATE TABLE economylitevirts AS SELECT * FROM economylitevirtsold"); 70 | logger.info("Dropping database..."); 71 | manager.executeUpdate("DROP TABLE economylitevirtsold"); 72 | logger.info("Repairs complete!"); 73 | return; 74 | } else { 75 | if (needRepair("show index from economylitevirts where Column_name='id'")) { 76 | logger.info("Repairing the database..."); 77 | } else { 78 | logger.debug("Database repairs not necessary!"); 79 | return; 80 | } 81 | logger.info("Renaming database..."); 82 | manager.executeUpdate("RENAME TABLE economylitevirts TO economylitevirtsold"); 83 | logger.info("Recreating database..."); 84 | manager.executeUpdate("CREATE TABLE economylitevirts AS SELECT * FROM economylitevirtsold"); 85 | logger.info("Dropping database..."); 86 | manager.executeUpdate("DROP TABLE economylitevirtssold"); 87 | logger.info("Repairs complete!"); 88 | return; 89 | } 90 | } 91 | 92 | /** 93 | * Returns true if database needs to be repaired. 94 | */ 95 | private boolean needRepair(String sql) { 96 | DataSource source = manager.getDataSource(); 97 | try { 98 | Connection con = source.getConnection(); 99 | try { 100 | PreparedStatement ps = con.prepareStatement(sql); 101 | ps.closeOnCompletion(); 102 | ResultSet rs = ps.executeQuery(); 103 | rs.next(); 104 | rs.getString(1); 105 | } finally { 106 | con.close(); 107 | } 108 | } catch (Exception e) { 109 | return false; 110 | } 111 | 112 | return true; 113 | } 114 | 115 | public void resetCache() { 116 | balCache.clear(); 117 | exCache.clear(); 118 | topCache.clear(); 119 | } 120 | 121 | public boolean isWorking() { 122 | return manager.testConnection(); 123 | } 124 | 125 | public BigDecimal getBalance(String id, Currency currency, Cause cause, boolean cache) { 126 | BigDecimal result = balCache.getIfPresent(formId(id, currency)); 127 | if (cache && result != null) { 128 | debug("virtcommon: {C} Balance of '" + id + "' - " + cause.toString() + " = " + result.toPlainString()); 129 | return result; 130 | } 131 | Optional bOpt = 132 | manager.queryType("balance", BigDecimal.class, "SELECT balance FROM economylitevirts WHERE id = ? AND currency = ?", id, 133 | currency.getId()); 134 | result = (bOpt.isPresent()) ? bOpt.get() : BigDecimal.ZERO; 135 | balCache.update(formId(id, currency), result); 136 | exCache.update(formId(id, currency), true); 137 | debug("virtcommon: Balance of '" + id + "' - " + cause.toString() + " = " + result.toPlainString()); 138 | return result; 139 | } 140 | 141 | public boolean setBalance(String id, BigDecimal balance, Currency currency, Cause cause) { 142 | boolean result; 143 | if (accountExists(id, currency, cause)) { 144 | result = manager.executeUpdate("UPDATE economylitevirts SET balance = ? WHERE id = ? AND currency = ?", balance.toString(), id, 145 | currency.getId()); 146 | debug("virtcommon: +Account Exists+ Setting balance of '" + id + "' to '" + balance.toPlainString() + "' with '" 147 | + currency.getId() + "' - " + cause.toString() + " = " + result); 148 | } else { 149 | result = manager.executeUpdate("INSERT INTO economylitevirts (`id`, `balance`, `currency`) VALUES (?, ?, ?)", id, balance.toString(), 150 | currency.getId()); 151 | debug("virtcommon: +Account Does Not Exist+ Setting balance of '" + id + "' to '" + balance.toPlainString() 152 | + "' with '" + currency.getId() + "' - " + cause.toString() + " = " + result); 153 | } 154 | if (result) { 155 | balCache.update(formId(id, currency), balance); 156 | exCache.update(formId(id, currency), true); 157 | } 158 | return result; 159 | } 160 | 161 | public boolean accountExists(String id, Currency currency, Cause cause) { 162 | Boolean result = exCache.getIfPresent(formId(id, currency)); 163 | if (result != null) { 164 | debug("virtcommon: {C} Checking if '" + id + "' exists with '" + currency.getId() + "' - " + cause.toString() + " = " + result); 165 | return result; 166 | } 167 | result = manager.queryExists("SELECT id FROM economylitevirts WHERE id = ? AND currency = ?", id, currency.getId()); 168 | debug("virtcommon: Checking if '" + id + "' exists with '" + currency.getId() + "' - " + cause.toString() + " = " + result); 169 | exCache.update(formId(id, currency), result); 170 | return result; 171 | } 172 | 173 | public void clearCurrency(Currency currency, Cause cause) { 174 | boolean result = manager.executeUpdate("DELETE FROM economylitevirts WHERE currency = ?", currency.getId()); 175 | debug("virtcommon: Clearing currency '" + currency.getId() + "' - " + cause.toString() + " = " + result); 176 | balCache.clear(); 177 | exCache.clear(); 178 | topCache.clear(); 179 | } 180 | 181 | public List getTopAccounts(int start, int end, Cause cause) { 182 | debug("virtcommon: Getting top accounts - " + cause.toString()); 183 | String mid = start + "-" + end + ":" + EconomyLite.getEconomyService().getDefaultCurrency().getId(); 184 | List accounts = topCache.getIfPresent(mid); 185 | if (accounts != null) { 186 | return accounts; 187 | } 188 | int offset = start - 1; 189 | int limit = end - offset; 190 | accounts = new ArrayList<>(); 191 | List ids = 192 | manager.queryTypeList("id", String.class, "SELECT id FROM economylitevirts WHERE currency = ? ORDER BY balance DESC LIMIT ?, ?", 193 | EconomyLite.getEconomyService().getDefaultCurrency().getId(), offset, limit); 194 | EconomyService ecoService = EconomyLite.getEconomyService(); 195 | for (String id : ids) { 196 | Optional vOpt = ecoService.getOrCreateAccount(id); 197 | if (vOpt.isPresent() && (vOpt.get() instanceof VirtualAccount)) { 198 | accounts.add((VirtualAccount) vOpt.get()); 199 | } 200 | } 201 | topCache.update(mid, accounts); 202 | return accounts; 203 | } 204 | 205 | private void debug(String message) { 206 | if (log) { 207 | logger.debug(message); 208 | } 209 | } 210 | 211 | private String formId(String id, Currency currency) { 212 | return id + ":" + currency.getId(); 213 | } 214 | } 215 | -------------------------------------------------------------------------------- /src/main/java/io/github/flibio/economylite/impl/economy/LiteCurrency.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of EconomyLite, licensed under the MIT License (MIT). See the LICENSE file at the root of this project for more information. 3 | */ 4 | package io.github.flibio.economylite.impl.economy; 5 | 6 | import org.spongepowered.api.service.economy.Currency; 7 | import org.spongepowered.api.text.Text; 8 | 9 | import java.math.BigDecimal; 10 | import java.math.RoundingMode; 11 | import java.util.Locale; 12 | 13 | public class LiteCurrency implements Currency { 14 | 15 | private String singular; 16 | private String plural; 17 | private String symbol; 18 | private boolean defaultCur; 19 | private int digits; 20 | 21 | public LiteCurrency(String singular, String plural, String symbol, boolean defaultCur, int digits) { 22 | this.singular = singular; 23 | this.plural = plural; 24 | this.symbol = symbol; 25 | this.defaultCur = defaultCur; 26 | this.digits = digits; 27 | } 28 | 29 | @Override 30 | public int getDefaultFractionDigits() { 31 | return digits; 32 | } 33 | 34 | @Override 35 | public Text getDisplayName() { 36 | return Text.of(singular); 37 | } 38 | 39 | @Override 40 | public Text getPluralDisplayName() { 41 | return Text.of(plural); 42 | } 43 | 44 | @Override 45 | public Text getSymbol() { 46 | return Text.of(symbol); 47 | } 48 | 49 | @Override 50 | public boolean isDefault() { 51 | return defaultCur; 52 | } 53 | 54 | @Override 55 | public Text format(BigDecimal amount, int digits) { 56 | Text label = getPluralDisplayName(); 57 | if (amount.equals(BigDecimal.ONE)) { 58 | label = getDisplayName(); 59 | } 60 | return Text.of(String.format(Locale.ENGLISH, "%,.2f", amount.setScale(digits, RoundingMode.HALF_UP)) + " ", label); 61 | } 62 | 63 | @Override 64 | public String getId() { 65 | return "economylite:" + singular.toLowerCase().replaceAll(" ", "_"); 66 | } 67 | 68 | @Override 69 | public String getName() { 70 | return singular; 71 | } 72 | 73 | @Override 74 | public boolean equals(Object other) { 75 | if (!(other instanceof Currency)) 76 | return false; 77 | return this.getId().equals(((Currency) other).getId()); 78 | } 79 | 80 | } 81 | -------------------------------------------------------------------------------- /src/main/java/io/github/flibio/economylite/impl/economy/LiteEconomyService.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of EconomyLite, licensed under the MIT License (MIT). See the LICENSE file at the root of this project for more information. 3 | */ 4 | package io.github.flibio.economylite.impl.economy; 5 | 6 | import io.github.flibio.economylite.CauseFactory; 7 | import io.github.flibio.economylite.EconomyLite; 8 | import io.github.flibio.economylite.api.CurrencyEconService; 9 | import io.github.flibio.economylite.api.PlayerEconService; 10 | import io.github.flibio.economylite.api.VirtualEconService; 11 | import io.github.flibio.economylite.impl.economy.account.LiteUniqueAccount; 12 | import io.github.flibio.economylite.impl.economy.account.LiteVirtualAccount; 13 | import org.spongepowered.api.service.context.ContextCalculator; 14 | import org.spongepowered.api.service.economy.Currency; 15 | import org.spongepowered.api.service.economy.EconomyService; 16 | import org.spongepowered.api.service.economy.account.Account; 17 | import org.spongepowered.api.service.economy.account.UniqueAccount; 18 | import org.spongepowered.api.service.economy.account.VirtualAccount; 19 | 20 | import java.util.Optional; 21 | import java.util.Set; 22 | import java.util.UUID; 23 | 24 | public class LiteEconomyService implements EconomyService { 25 | 26 | private PlayerEconService playerService = EconomyLite.getPlayerService(); 27 | private VirtualEconService virtualService = EconomyLite.getVirtualService(); 28 | private CurrencyEconService currencyService = EconomyLite.getCurrencyService(); 29 | 30 | @Override 31 | public void registerContextCalculator(ContextCalculator arg0) { 32 | return; 33 | } 34 | 35 | @Override 36 | public Optional getOrCreateAccount(UUID uuid) { 37 | if (playerService.accountExists(uuid, getDefaultCurrency(), CauseFactory.create("New account check"))) { 38 | // Return the account 39 | return Optional.of(new LiteUniqueAccount(uuid)); 40 | } else { 41 | // Make a new account 42 | UniqueAccount account = new LiteUniqueAccount(uuid); 43 | if (playerService.setBalance(uuid, account.getDefaultBalance(getDefaultCurrency()), getDefaultCurrency(), 44 | CauseFactory.create("Creating account"))) { 45 | return Optional.of(account); 46 | } else { 47 | return Optional.empty(); 48 | } 49 | } 50 | } 51 | 52 | @Override 53 | public Optional getOrCreateAccount(String id) { 54 | if (virtualService.accountExists(id, getDefaultCurrency(), CauseFactory.create("New account check"))) { 55 | // Return the account 56 | return Optional.of(new LiteVirtualAccount(id)); 57 | } else { 58 | // Make a new account 59 | VirtualAccount account = new LiteVirtualAccount(id); 60 | if (virtualService.setBalance(id, account.getDefaultBalance(getDefaultCurrency()), getDefaultCurrency(), 61 | CauseFactory.create("Creating account"))) { 62 | return Optional.of(account); 63 | } else { 64 | return Optional.empty(); 65 | } 66 | } 67 | } 68 | 69 | @Override 70 | public Set getCurrencies() { 71 | return currencyService.getCurrencies(); 72 | } 73 | 74 | @Override 75 | public Currency getDefaultCurrency() { 76 | return currencyService.getCurrentCurrency(); 77 | } 78 | 79 | @Override 80 | public boolean hasAccount(UUID uuid) { 81 | return playerService.accountExists(uuid, getDefaultCurrency(), CauseFactory.create("Checking account existance")); 82 | } 83 | 84 | @Override 85 | public boolean hasAccount(String identifier) { 86 | return virtualService.accountExists(identifier, getDefaultCurrency(), CauseFactory.create("Checking account existance")); 87 | } 88 | 89 | } 90 | -------------------------------------------------------------------------------- /src/main/java/io/github/flibio/economylite/impl/economy/account/LiteUniqueAccount.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of EconomyLite, licensed under the MIT License (MIT). See the LICENSE file at the root of this project for more information. 3 | */ 4 | package io.github.flibio.economylite.impl.economy.account; 5 | 6 | import io.github.flibio.economylite.CauseFactory; 7 | import io.github.flibio.economylite.EconomyLite; 8 | import io.github.flibio.economylite.api.CurrencyEconService; 9 | import io.github.flibio.economylite.api.PlayerEconService; 10 | import io.github.flibio.economylite.impl.economy.event.LiteEconomyTransactionEvent; 11 | import io.github.flibio.economylite.impl.economy.result.LiteTransactionResult; 12 | import io.github.flibio.economylite.impl.economy.result.LiteTransferResult; 13 | import io.github.flibio.utils.player.NameUtils; 14 | import org.spongepowered.api.Sponge; 15 | import org.spongepowered.api.event.cause.Cause; 16 | import org.spongepowered.api.service.context.Context; 17 | import org.spongepowered.api.service.economy.Currency; 18 | import org.spongepowered.api.service.economy.account.Account; 19 | import org.spongepowered.api.service.economy.account.UniqueAccount; 20 | import org.spongepowered.api.service.economy.transaction.ResultType; 21 | import org.spongepowered.api.service.economy.transaction.TransactionResult; 22 | import org.spongepowered.api.service.economy.transaction.TransactionType; 23 | import org.spongepowered.api.service.economy.transaction.TransactionTypes; 24 | import org.spongepowered.api.service.economy.transaction.TransferResult; 25 | import org.spongepowered.api.text.Text; 26 | 27 | import java.math.BigDecimal; 28 | import java.util.HashMap; 29 | import java.util.HashSet; 30 | import java.util.Map; 31 | import java.util.Optional; 32 | import java.util.Set; 33 | import java.util.UUID; 34 | 35 | public class LiteUniqueAccount implements UniqueAccount { 36 | 37 | private PlayerEconService playerService = EconomyLite.getPlayerService(); 38 | private CurrencyEconService currencyService = EconomyLite.getCurrencyService(); 39 | 40 | private UUID uuid; 41 | private String name; 42 | 43 | public LiteUniqueAccount(UUID uuid) { 44 | this.uuid = uuid; 45 | try { 46 | Optional nOpt = NameUtils.getName(uuid); 47 | if (nOpt.isPresent()) { 48 | this.name = nOpt.get(); 49 | } else { 50 | this.name = uuid.toString(); 51 | } 52 | } catch (Exception e) { 53 | this.name = uuid.toString(); 54 | } 55 | } 56 | 57 | @Override 58 | public Text getDisplayName() { 59 | return Text.of(name); 60 | } 61 | 62 | @Override 63 | public BigDecimal getDefaultBalance(Currency currency) { 64 | Optional bOpt = EconomyLite.getConfigManager().getValue(Double.class, "default-balance", "player"); 65 | if (bOpt.isPresent()) { 66 | return BigDecimal.valueOf(bOpt.get()); 67 | } else { 68 | return BigDecimal.ZERO; 69 | } 70 | } 71 | 72 | @Override 73 | public boolean hasBalance(Currency currency, Set contexts) { 74 | return playerService.accountExists(uuid, currency, CauseFactory.create("Has Balance")); 75 | } 76 | 77 | @Override 78 | public BigDecimal getBalance(Currency currency, Set contexts) { 79 | if (!hasBalance(currency, contexts)) { 80 | playerService.setBalance(uuid, getDefaultBalance(currency), currency, CauseFactory.create("New Account")); 81 | } 82 | return playerService.getBalance(uuid, currency, CauseFactory.create("Get Balance")); 83 | } 84 | 85 | @Override 86 | public Map getBalances(Set contexts) { 87 | HashMap balances = new HashMap(); 88 | for (Currency currency : currencyService.getCurrencies()) { 89 | if (playerService.accountExists(uuid, currency, CauseFactory.create("Get Balances"))) { 90 | balances.put(currency, playerService.getBalance(uuid, currency, CauseFactory.create("Get Balances Put"))); 91 | } 92 | } 93 | return balances; 94 | } 95 | 96 | @Override 97 | public TransactionResult setBalance(Currency currency, BigDecimal amount, Cause cause, Set contexts) { 98 | // Check if the new balance is in bounds 99 | if (amount.compareTo(BigDecimal.ZERO) == -1 || amount.compareTo(BigDecimal.valueOf(999999999)) == 1) { 100 | return resultAndEvent(this, amount, currency, ResultType.ACCOUNT_NO_SPACE, TransactionTypes.DEPOSIT, cause); 101 | } 102 | if (playerService.setBalance(uuid, amount, currency, cause)) { 103 | return resultAndEvent(this, amount, currency, ResultType.SUCCESS, TransactionTypes.DEPOSIT, cause); 104 | } else { 105 | return resultAndEvent(this, amount, currency, ResultType.FAILED, TransactionTypes.DEPOSIT, cause); 106 | } 107 | } 108 | 109 | @Override 110 | public Map resetBalances(Cause cause, Set contexts) { 111 | HashMap results = new HashMap<>(); 112 | for (Currency currency : currencyService.getCurrencies()) { 113 | if (playerService.accountExists(uuid, currency, cause)) { 114 | if (playerService.setBalance(uuid, getDefaultBalance(currency), currency, cause)) { 115 | results.put(currency, resultAndEvent(this, getBalance(currency), currency, ResultType.SUCCESS, TransactionTypes.WITHDRAW, cause)); 116 | } else { 117 | results.put(currency, resultAndEvent(this, getBalance(currency), currency, ResultType.FAILED, TransactionTypes.WITHDRAW, cause)); 118 | } 119 | } 120 | } 121 | return results; 122 | } 123 | 124 | @Override 125 | public TransactionResult resetBalance(Currency currency, Cause cause, Set contexts) { 126 | if (playerService.setBalance(uuid, getDefaultBalance(currency), currency, cause)) { 127 | return resultAndEvent(this, BigDecimal.ZERO, currency, ResultType.SUCCESS, TransactionTypes.WITHDRAW, cause); 128 | } else { 129 | return resultAndEvent(this, BigDecimal.ZERO, currency, ResultType.FAILED, TransactionTypes.WITHDRAW, cause); 130 | } 131 | } 132 | 133 | @Override 134 | public TransactionResult deposit(Currency currency, BigDecimal amount, Cause cause, Set contexts) { 135 | BigDecimal newBal = getBalance(currency).add(amount); 136 | // Check if the new balance is in bounds 137 | if (newBal.compareTo(BigDecimal.ZERO) == -1 || newBal.compareTo(BigDecimal.valueOf(999999999)) == 1) { 138 | return resultAndEvent(this, amount, currency, ResultType.ACCOUNT_NO_SPACE, TransactionTypes.DEPOSIT, cause); 139 | } 140 | if (playerService.deposit(uuid, amount, currency, cause)) { 141 | return resultAndEvent(this, amount, currency, ResultType.SUCCESS, TransactionTypes.DEPOSIT, cause); 142 | } else { 143 | return resultAndEvent(this, amount, currency, ResultType.FAILED, TransactionTypes.DEPOSIT, cause); 144 | } 145 | } 146 | 147 | @Override 148 | public TransactionResult withdraw(Currency currency, BigDecimal amount, Cause cause, Set contexts) { 149 | BigDecimal newBal = getBalance(currency).subtract(amount); 150 | // Check if the new balance is in bounds 151 | if (newBal.compareTo(BigDecimal.ZERO) == -1) { 152 | return resultAndEvent(this, amount, currency, ResultType.ACCOUNT_NO_FUNDS, TransactionTypes.WITHDRAW, cause); 153 | } 154 | if (newBal.compareTo(BigDecimal.valueOf(999999999)) == 1) { 155 | return resultAndEvent(this, amount, currency, ResultType.ACCOUNT_NO_SPACE, TransactionTypes.WITHDRAW, cause); 156 | } 157 | if (playerService.withdraw(uuid, amount, currency, cause)) { 158 | return resultAndEvent(this, amount, currency, ResultType.SUCCESS, TransactionTypes.WITHDRAW, cause); 159 | } else { 160 | return resultAndEvent(this, amount, currency, ResultType.FAILED, TransactionTypes.WITHDRAW, cause); 161 | } 162 | } 163 | 164 | @Override 165 | public TransferResult transfer(Account to, Currency currency, BigDecimal amount, Cause cause, Set contexts) { 166 | BigDecimal newBal = to.getBalance(currency).add(amount); 167 | // Check if the new balance is in bounds 168 | if (newBal.compareTo(BigDecimal.ZERO) == -1 || newBal.compareTo(BigDecimal.valueOf(999999999)) == 1) { 169 | return resultAndEvent(this, amount, currency, ResultType.ACCOUNT_NO_SPACE, to, cause); 170 | } 171 | // Check if the account has enough funds 172 | if (amount.compareTo(getBalance(currency)) == 1) { 173 | return resultAndEvent(this, amount, currency, ResultType.ACCOUNT_NO_FUNDS, to, cause); 174 | } 175 | if (withdraw(currency, amount, cause).getResult().equals(ResultType.SUCCESS) 176 | && to.deposit(currency, amount, cause).getResult().equals(ResultType.SUCCESS)) { 177 | return resultAndEvent(this, amount, currency, ResultType.SUCCESS, to, cause); 178 | } else { 179 | return resultAndEvent(this, amount, currency, ResultType.FAILED, to, cause); 180 | } 181 | } 182 | 183 | @Override 184 | public String getIdentifier() { 185 | return uuid.toString(); 186 | } 187 | 188 | @Override 189 | public Set getActiveContexts() { 190 | return new HashSet(); 191 | } 192 | 193 | private TransactionResult resultAndEvent(Account account, BigDecimal amount, Currency currency, ResultType resultType, 194 | TransactionType transactionType, Cause cause) { 195 | TransactionResult result = new LiteTransactionResult(account, amount, currency, resultType, transactionType); 196 | Sponge.getEventManager().post(new LiteEconomyTransactionEvent(result, UUID.fromString(account.getIdentifier()), cause)); 197 | return result; 198 | } 199 | 200 | private TransferResult resultAndEvent(Account account, BigDecimal amount, Currency currency, ResultType resultType, Account toWho, Cause cause) { 201 | TransferResult result = new LiteTransferResult(account, amount, currency, resultType, toWho); 202 | Sponge.getEventManager().post(new LiteEconomyTransactionEvent(result, UUID.fromString(account.getIdentifier()), cause)); 203 | return result; 204 | } 205 | 206 | @Override 207 | public UUID getUniqueId() { 208 | return uuid; 209 | } 210 | 211 | } 212 | -------------------------------------------------------------------------------- /src/main/java/io/github/flibio/economylite/impl/economy/account/LiteVirtualAccount.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of EconomyLite, licensed under the MIT License (MIT). See the LICENSE file at the root of this project for more information. 3 | */ 4 | package io.github.flibio.economylite.impl.economy.account; 5 | 6 | import io.github.flibio.economylite.CauseFactory; 7 | import io.github.flibio.economylite.EconomyLite; 8 | import io.github.flibio.economylite.api.CurrencyEconService; 9 | import io.github.flibio.economylite.api.VirtualEconService; 10 | import io.github.flibio.economylite.impl.economy.event.LiteEconomyTransactionEvent; 11 | import io.github.flibio.economylite.impl.economy.result.LiteTransactionResult; 12 | import io.github.flibio.economylite.impl.economy.result.LiteTransferResult; 13 | import org.spongepowered.api.Sponge; 14 | import org.spongepowered.api.event.cause.Cause; 15 | import org.spongepowered.api.service.context.Context; 16 | import org.spongepowered.api.service.economy.Currency; 17 | import org.spongepowered.api.service.economy.account.Account; 18 | import org.spongepowered.api.service.economy.account.VirtualAccount; 19 | import org.spongepowered.api.service.economy.transaction.ResultType; 20 | import org.spongepowered.api.service.economy.transaction.TransactionResult; 21 | import org.spongepowered.api.service.economy.transaction.TransactionType; 22 | import org.spongepowered.api.service.economy.transaction.TransactionTypes; 23 | import org.spongepowered.api.service.economy.transaction.TransferResult; 24 | import org.spongepowered.api.text.Text; 25 | 26 | import java.math.BigDecimal; 27 | import java.util.HashMap; 28 | import java.util.HashSet; 29 | import java.util.Map; 30 | import java.util.Optional; 31 | import java.util.Set; 32 | 33 | public class LiteVirtualAccount implements VirtualAccount { 34 | 35 | private VirtualEconService virtualService = EconomyLite.getVirtualService(); 36 | private CurrencyEconService currencyService = EconomyLite.getCurrencyService(); 37 | 38 | private String name; 39 | 40 | public LiteVirtualAccount(String id) { 41 | this.name = id; 42 | } 43 | 44 | @Override 45 | public Text getDisplayName() { 46 | return Text.of(name); 47 | } 48 | 49 | @Override 50 | public BigDecimal getDefaultBalance(Currency currency) { 51 | Optional bOpt = EconomyLite.getConfigManager().getValue(Double.class, "default-balance", "virtual"); 52 | if (bOpt.isPresent()) { 53 | return BigDecimal.valueOf(bOpt.get()); 54 | } else { 55 | return BigDecimal.ZERO; 56 | } 57 | } 58 | 59 | @Override 60 | public boolean hasBalance(Currency currency, Set contexts) { 61 | return virtualService.accountExists(name, currency, CauseFactory.create("Has Balance")); 62 | } 63 | 64 | @Override 65 | public BigDecimal getBalance(Currency currency, Set contexts) { 66 | if (!hasBalance(currency, contexts)) { 67 | virtualService.setBalance(name, getDefaultBalance(currency), currency, CauseFactory.create("New Account")); 68 | } 69 | return virtualService.getBalance(name, currency, CauseFactory.create("Get Balance")); 70 | } 71 | 72 | @Override 73 | public Map getBalances(Set contexts) { 74 | HashMap balances = new HashMap(); 75 | for (Currency currency : currencyService.getCurrencies()) { 76 | if (virtualService.accountExists(name, currency, CauseFactory.create("Get Balances"))) { 77 | balances.put(currency, virtualService.getBalance(name, currency, CauseFactory.create("Get Balances Put"))); 78 | } 79 | } 80 | return balances; 81 | } 82 | 83 | @Override 84 | public TransactionResult setBalance(Currency currency, BigDecimal amount, Cause cause, Set contexts) { 85 | // Check if the new balance is in bounds 86 | if (amount.compareTo(BigDecimal.ZERO) == -1 || amount.compareTo(BigDecimal.valueOf(999999999)) == 1) { 87 | return resultAndEvent(this, amount, currency, ResultType.ACCOUNT_NO_SPACE, TransactionTypes.DEPOSIT, cause); 88 | } 89 | if (virtualService.setBalance(name, amount, currency, cause)) { 90 | return resultAndEvent(this, amount, currency, ResultType.SUCCESS, TransactionTypes.DEPOSIT, cause); 91 | } else { 92 | return resultAndEvent(this, amount, currency, ResultType.FAILED, TransactionTypes.DEPOSIT, cause); 93 | } 94 | } 95 | 96 | @Override 97 | public Map resetBalances(Cause cause, Set contexts) { 98 | HashMap results = new HashMap<>(); 99 | for (Currency currency : currencyService.getCurrencies()) { 100 | if (virtualService.accountExists(name, currency, cause)) { 101 | if (virtualService.setBalance(name, getDefaultBalance(currency), currency, cause)) { 102 | results.put(currency, resultAndEvent(this, getBalance(currency), currency, ResultType.SUCCESS, TransactionTypes.WITHDRAW, cause)); 103 | } else { 104 | results.put(currency, resultAndEvent(this, getBalance(currency), currency, ResultType.FAILED, TransactionTypes.WITHDRAW, cause)); 105 | } 106 | } 107 | } 108 | return results; 109 | } 110 | 111 | @Override 112 | public TransactionResult resetBalance(Currency currency, Cause cause, Set contexts) { 113 | if (virtualService.setBalance(name, getDefaultBalance(currency), currency, cause)) { 114 | return resultAndEvent(this, BigDecimal.ZERO, currency, ResultType.SUCCESS, TransactionTypes.WITHDRAW, cause); 115 | } else { 116 | return resultAndEvent(this, BigDecimal.ZERO, currency, ResultType.FAILED, TransactionTypes.WITHDRAW, cause); 117 | } 118 | } 119 | 120 | @Override 121 | public TransactionResult deposit(Currency currency, BigDecimal amount, Cause cause, Set contexts) { 122 | BigDecimal newBal = getBalance(currency).add(amount); 123 | // Check if the new balance is in bounds 124 | if (newBal.compareTo(BigDecimal.ZERO) == -1 || newBal.compareTo(BigDecimal.valueOf(999999999)) == 1) { 125 | return resultAndEvent(this, amount, currency, ResultType.ACCOUNT_NO_SPACE, TransactionTypes.DEPOSIT, cause); 126 | } 127 | if (virtualService.deposit(name, amount, currency, cause)) { 128 | return resultAndEvent(this, amount, currency, ResultType.SUCCESS, TransactionTypes.DEPOSIT, cause); 129 | } else { 130 | return resultAndEvent(this, amount, currency, ResultType.FAILED, TransactionTypes.DEPOSIT, cause); 131 | } 132 | } 133 | 134 | @Override 135 | public TransactionResult withdraw(Currency currency, BigDecimal amount, Cause cause, Set contexts) { 136 | BigDecimal newBal = getBalance(currency).subtract(amount); 137 | // Check if the new balance is in bounds 138 | if (newBal.compareTo(BigDecimal.ZERO) == -1) { 139 | return resultAndEvent(this, amount, currency, ResultType.ACCOUNT_NO_FUNDS, TransactionTypes.WITHDRAW, cause); 140 | } 141 | if (newBal.compareTo(BigDecimal.valueOf(999999999)) == 1) { 142 | return resultAndEvent(this, amount, currency, ResultType.ACCOUNT_NO_SPACE, TransactionTypes.WITHDRAW, cause); 143 | } 144 | if (virtualService.withdraw(name, amount, currency, cause)) { 145 | return resultAndEvent(this, amount, currency, ResultType.SUCCESS, TransactionTypes.WITHDRAW, cause); 146 | } else { 147 | return resultAndEvent(this, amount, currency, ResultType.FAILED, TransactionTypes.WITHDRAW, cause); 148 | } 149 | } 150 | 151 | @Override 152 | public TransferResult transfer(Account to, Currency currency, BigDecimal amount, Cause cause, Set contexts) { 153 | BigDecimal newBal = to.getBalance(currency).add(amount); 154 | // Check if the new balance is in bounds 155 | if (newBal.compareTo(BigDecimal.ZERO) == -1 || newBal.compareTo(BigDecimal.valueOf(999999999)) == 1) { 156 | return resultAndEvent(this, amount, currency, ResultType.ACCOUNT_NO_SPACE, to, cause); 157 | } 158 | // Check if the account has enough funds 159 | if (amount.compareTo(getBalance(currency)) == 1) { 160 | return resultAndEvent(this, amount, currency, ResultType.ACCOUNT_NO_FUNDS, to, cause); 161 | } 162 | if (withdraw(currency, amount, cause).getResult().equals(ResultType.SUCCESS) 163 | && to.deposit(currency, amount, cause).getResult().equals(ResultType.SUCCESS)) { 164 | return resultAndEvent(this, amount, currency, ResultType.SUCCESS, to, cause); 165 | } else { 166 | return resultAndEvent(this, amount, currency, ResultType.FAILED, to, cause); 167 | } 168 | } 169 | 170 | @Override 171 | public String getIdentifier() { 172 | return name; 173 | } 174 | 175 | @Override 176 | public Set getActiveContexts() { 177 | return new HashSet(); 178 | } 179 | 180 | private TransactionResult resultAndEvent(Account account, BigDecimal amount, Currency currency, ResultType resultType, 181 | TransactionType transactionType, Cause cause) { 182 | TransactionResult result = new LiteTransactionResult(account, amount, currency, resultType, transactionType); 183 | Sponge.getEventManager().post(new LiteEconomyTransactionEvent(result, cause)); 184 | return result; 185 | } 186 | 187 | private TransferResult resultAndEvent(Account account, BigDecimal amount, Currency currency, ResultType resultType, Account toWho, Cause cause) { 188 | TransferResult result = new LiteTransferResult(account, amount, currency, resultType, toWho); 189 | Sponge.getEventManager().post(new LiteEconomyTransactionEvent(result, cause)); 190 | return result; 191 | } 192 | 193 | } 194 | -------------------------------------------------------------------------------- /src/main/java/io/github/flibio/economylite/impl/economy/event/LiteEconomyTransactionEvent.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of EconomyLite, licensed under the MIT License (MIT). See the LICENSE file at the root of this project for more information. 3 | */ 4 | package io.github.flibio.economylite.impl.economy.event; 5 | 6 | import io.github.flibio.economylite.EconomyLite; 7 | import org.spongepowered.api.event.cause.Cause; 8 | import org.spongepowered.api.event.cause.EventContext; 9 | import org.spongepowered.api.event.economy.EconomyTransactionEvent; 10 | import org.spongepowered.api.event.impl.AbstractEvent; 11 | import org.spongepowered.api.service.economy.transaction.TransactionResult; 12 | 13 | import java.util.UUID; 14 | 15 | public class LiteEconomyTransactionEvent extends AbstractEvent implements EconomyTransactionEvent { 16 | 17 | private TransactionResult result; 18 | private Cause cause; 19 | 20 | public LiteEconomyTransactionEvent(TransactionResult result) { 21 | this.result = result; 22 | } 23 | 24 | public LiteEconomyTransactionEvent(TransactionResult result, Cause cause) { 25 | this.result = result; 26 | this.cause = cause; 27 | } 28 | 29 | public LiteEconomyTransactionEvent(TransactionResult result, UUID user, Cause cause) { 30 | this.result = result; 31 | this.cause = Cause.of(EventContext.empty(), user); 32 | } 33 | 34 | @Override 35 | public Cause getCause() { 36 | if (cause != null) { 37 | return cause; 38 | } else { 39 | return Cause.of(EventContext.empty(), EconomyLite.getInstance().getPluginContainer()); 40 | } 41 | } 42 | 43 | @Override 44 | public TransactionResult getTransactionResult() { 45 | return this.result; 46 | } 47 | 48 | } 49 | -------------------------------------------------------------------------------- /src/main/java/io/github/flibio/economylite/impl/economy/registry/CurrencyRegistryModule.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of EconomyLite, licensed under the MIT License (MIT). See the LICENSE file at the root of this project for more information. 3 | */ 4 | package io.github.flibio.economylite.impl.economy.registry; 5 | 6 | import org.spongepowered.api.registry.CatalogRegistryModule; 7 | import org.spongepowered.api.service.economy.Currency; 8 | 9 | import io.github.flibio.economylite.EconomyLite; 10 | 11 | import java.util.Collection; 12 | import java.util.Optional; 13 | 14 | public class CurrencyRegistryModule implements CatalogRegistryModule { 15 | 16 | @Override 17 | public Optional getById(String id) { 18 | for (Currency cur : EconomyLite.getCurrencyService().getCurrencies()) { 19 | if (cur.getId().equals(id)) { 20 | return Optional.of(cur); 21 | } 22 | } 23 | return Optional.empty(); 24 | } 25 | 26 | @Override 27 | public Collection getAll() { 28 | return EconomyLite.getCurrencyService().getCurrencies(); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/io/github/flibio/economylite/impl/economy/result/LiteTransactionResult.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of EconomyLite, licensed under the MIT License (MIT). See the LICENSE file at the root of this project for more information. 3 | */ 4 | package io.github.flibio.economylite.impl.economy.result; 5 | 6 | import org.spongepowered.api.service.context.Context; 7 | import org.spongepowered.api.service.economy.Currency; 8 | import org.spongepowered.api.service.economy.account.Account; 9 | import org.spongepowered.api.service.economy.transaction.ResultType; 10 | import org.spongepowered.api.service.economy.transaction.TransactionResult; 11 | import org.spongepowered.api.service.economy.transaction.TransactionType; 12 | 13 | import java.math.BigDecimal; 14 | import java.util.HashSet; 15 | import java.util.Set; 16 | 17 | public class LiteTransactionResult implements TransactionResult { 18 | 19 | private Account account; 20 | private BigDecimal amount; 21 | private Set contexts; 22 | private Currency currency; 23 | private ResultType result; 24 | private TransactionType transactionType; 25 | 26 | public LiteTransactionResult(Account account, BigDecimal amount, Currency currency, ResultType result, TransactionType transactionType) { 27 | this.account = account; 28 | this.amount = amount; 29 | this.contexts = new HashSet(); 30 | this.currency = currency; 31 | this.result = result; 32 | this.transactionType = transactionType; 33 | } 34 | 35 | @Override 36 | public Account getAccount() { 37 | return this.account; 38 | } 39 | 40 | @Override 41 | public BigDecimal getAmount() { 42 | return this.amount; 43 | } 44 | 45 | @Override 46 | public Set getContexts() { 47 | return this.contexts; 48 | } 49 | 50 | @Override 51 | public Currency getCurrency() { 52 | return this.currency; 53 | } 54 | 55 | @Override 56 | public ResultType getResult() { 57 | return this.result; 58 | } 59 | 60 | @Override 61 | public TransactionType getType() { 62 | return this.transactionType; 63 | } 64 | 65 | } 66 | -------------------------------------------------------------------------------- /src/main/java/io/github/flibio/economylite/impl/economy/result/LiteTransferResult.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of EconomyLite, licensed under the MIT License (MIT). See the LICENSE file at the root of this project for more information. 3 | */ 4 | package io.github.flibio.economylite.impl.economy.result; 5 | 6 | import org.spongepowered.api.service.economy.Currency; 7 | import org.spongepowered.api.service.economy.account.Account; 8 | import org.spongepowered.api.service.economy.transaction.ResultType; 9 | import org.spongepowered.api.service.economy.transaction.TransactionTypes; 10 | import org.spongepowered.api.service.economy.transaction.TransferResult; 11 | 12 | import java.math.BigDecimal; 13 | 14 | public class LiteTransferResult extends LiteTransactionResult implements TransferResult { 15 | 16 | private Account toWho; 17 | 18 | public LiteTransferResult(Account account, BigDecimal amount, Currency currency, ResultType result, Account toWho) { 19 | super(account, amount, currency, result, TransactionTypes.TRANSFER); 20 | this.toWho = toWho; 21 | } 22 | 23 | @Override 24 | public Account getAccountTo() { 25 | return this.toWho; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/io/github/flibio/economylite/modules/Module.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of EconomyLite, licensed under the MIT License (MIT). See the LICENSE file at the root of this project for more information. 3 | */ 4 | package io.github.flibio.economylite.modules; 5 | 6 | import org.slf4j.Logger; 7 | 8 | public interface Module { 9 | 10 | /** 11 | * Initializes the module. The EconomyService is not available. 12 | * 13 | * @param logger An instance of the plugin's logger. 14 | * @param plugin An instance of the main plugin class. 15 | * @return If the initialization was successful or not. 16 | */ 17 | boolean initialize(Logger logger, Object plugin); 18 | 19 | /** 20 | * Post-initialization of the module. The EconomyService is now available. 21 | * 22 | * @param logger An instance of the plugin's logger. 23 | * @param plugin An instance of the main plugin class. 24 | */ 25 | default void postInitialization(Logger logger, Object plugin) { 26 | } 27 | 28 | /** 29 | * Sets all default config variables for the module. 30 | */ 31 | void initializeConfig(); 32 | 33 | /** 34 | * Gets the name of the module. 35 | * 36 | * @return The name of the module. 37 | */ 38 | String getName(); 39 | 40 | /** 41 | * Checks if a module is enabled. 42 | * 43 | * @return If the module is enabled or not. 44 | */ 45 | boolean isEnabled(); 46 | 47 | } 48 | -------------------------------------------------------------------------------- /src/main/java/io/github/flibio/economylite/modules/business/BusinessModule.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of EconomyLite, licensed under the MIT License (MIT). See the LICENSE file at the root of this project for more information. 3 | */ 4 | package io.github.flibio.economylite.modules.business; 5 | 6 | import org.slf4j.Logger; 7 | 8 | import io.github.flibio.economylite.modules.Module; 9 | 10 | public class BusinessModule implements Module { 11 | 12 | @Override 13 | public boolean initialize(Logger logger, Object plugin) { 14 | // TODO - Implementation has not yet been decided 15 | return false; 16 | } 17 | 18 | @Override 19 | public void initializeConfig() { 20 | // TODO - Implementation has not yet been decided 21 | } 22 | 23 | @Override 24 | public String getName() { 25 | return "Business"; 26 | } 27 | 28 | @Override 29 | public boolean isEnabled() { 30 | // TODO - Implementation has not yet been decided 31 | return false; 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/io/github/flibio/economylite/modules/loan/LoanListener.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of EconomyLite, licensed under the MIT License (MIT). See the LICENSE file at the root of this project for more information. 3 | */ 4 | package io.github.flibio.economylite.modules.loan; 5 | 6 | import org.spongepowered.api.text.serializer.TextSerializers; 7 | import org.spongepowered.api.util.Tristate; 8 | 9 | import org.spongepowered.api.service.permission.SubjectData; 10 | import io.github.flibio.economylite.modules.loan.event.LoanBalanceChangeEvent; 11 | import io.github.flibio.economylite.EconomyLite; 12 | import io.github.flibio.utils.message.MessageStorage; 13 | import org.spongepowered.api.Sponge; 14 | import org.spongepowered.api.entity.living.player.Player; 15 | import org.spongepowered.api.event.Listener; 16 | import org.spongepowered.api.event.economy.EconomyTransactionEvent; 17 | import org.spongepowered.api.service.economy.Currency; 18 | import org.spongepowered.api.service.economy.transaction.ResultType; 19 | import org.spongepowered.api.text.Text; 20 | 21 | import java.math.BigDecimal; 22 | import java.util.Locale; 23 | import java.util.Optional; 24 | import java.util.UUID; 25 | 26 | public class LoanListener { 27 | 28 | private MessageStorage messages = EconomyLite.getMessageStorage(); 29 | private LoanManager loans; 30 | private LoanModule module; 31 | private double maxLoanBal; 32 | private double intRate; 33 | 34 | public LoanListener(LoanModule module) { 35 | this.module = module; 36 | this.loans = module.getLoanManager(); 37 | this.maxLoanBal = module.getMaxLoan(); 38 | this.intRate = module.getInterestRate(); 39 | } 40 | 41 | @Listener 42 | public void onBalanceChange(EconomyTransactionEvent event) { 43 | // Check if the transaction failed due to insufficient funds 44 | if (event.getTransactionResult().getResult().equals(ResultType.ACCOUNT_NO_FUNDS)) { 45 | // Check if the UUID is in the event 46 | Optional uOpt = event.getCause().first(UUID.class); 47 | Optional sOpt = event.getCause().first(String.class); 48 | if (sOpt.isPresent()) { 49 | if (sOpt.get().equalsIgnoreCase("economylite:loan")) { 50 | return; 51 | } 52 | } 53 | if (uOpt.isPresent()) { 54 | UUID uuid = uOpt.get(); 55 | // Try to get the player 56 | Optional pOpt = Sponge.getServer().getPlayer(uuid); 57 | if (pOpt.isPresent()) { 58 | Player player = pOpt.get(); 59 | // Get loan balance of the player 60 | Optional dOpt = loans.getLoanBalance(uuid); 61 | if (dOpt.isPresent()) { 62 | double loanBalance = dOpt.get(); 63 | // Calculate amount of money the player is short of 64 | Currency cur = event.getTransactionResult().getCurrency(); 65 | BigDecimal bal = event.getTransactionResult().getAccount().getBalance(cur); 66 | BigDecimal mis = event.getTransactionResult().getAmount().subtract(bal); 67 | double misDouble = mis.doubleValue(); 68 | // Notify player of interest rate 69 | player.sendMessage(messages.getMessage("module.loan.interest", "rate", Double.toString(intRate))); 70 | // Check how much loan they can take out 71 | double maxLoan = (maxLoanBal - loanBalance) / intRate; 72 | if (maxLoan <= 0) { 73 | return; 74 | } 75 | if (maxLoan < misDouble) { 76 | // Offer the player a smaller loan 77 | player.sendMessage(messages.getMessage("module.loan.partial")); 78 | player.sendMessage(messages.getMessage("module.loan.ask", "amount", 79 | String.format(Locale.ENGLISH, "%,.2f", maxLoan), "label", getPrefix(maxLoan, cur))); 80 | double total = maxLoan * intRate; 81 | player.sendMessage(messages.getMessage("module.loan.payment", "amount", 82 | String.format(Locale.ENGLISH, "%,.2f", total), "label", getPrefix(total, cur))); 83 | module.tableLoans.remove(uuid); 84 | module.tableLoans.put(uuid, maxLoan); 85 | } else { 86 | // Ask the player if they want a full loan 87 | player.sendMessage(messages.getMessage("module.loan.ask", "amount", String.format(Locale.ENGLISH, "%,.2f", mis), 88 | "label", getPrefix(mis.doubleValue(), cur))); 89 | BigDecimal total = mis.multiply(BigDecimal.valueOf(intRate)); 90 | player.sendMessage(messages.getMessage("module.loan.payment", "amount", 91 | String.format(Locale.ENGLISH, "%,.2f", total), "label", getPrefix(total.doubleValue(), cur))); 92 | player.sendMessage(LoanTextUtils.yesOrNo("/loan accept", "/loan deny")); 93 | module.tableLoans.remove(uuid); 94 | module.tableLoans.put(uuid, mis.doubleValue()); 95 | } 96 | } 97 | } 98 | } 99 | } 100 | } 101 | 102 | @Listener 103 | public void onLoanChange(LoanBalanceChangeEvent event) { 104 | UUID uuid = event.getUser(); 105 | for (Player player : Sponge.getServer().getOnlinePlayers()) { 106 | if (player.getUniqueId().equals(uuid)) { 107 | if (event.getNewBalance() == 0) { 108 | // Remove the debtor permissions 109 | module.getPermissions().forEach((perm, val) -> { 110 | player.getSubjectData().setPermission(SubjectData.GLOBAL_CONTEXT, perm, Tristate.fromBoolean(!val)); 111 | }); 112 | } else { 113 | // Add the debtor permissions 114 | module.getPermissions().forEach((perm, val) -> { 115 | player.getSubjectData().setPermission(SubjectData.GLOBAL_CONTEXT, perm, Tristate.fromBoolean(val)); 116 | }); 117 | } 118 | } 119 | } 120 | } 121 | 122 | private String getPrefix(double amnt, Currency cur) { 123 | Text label = cur.getPluralDisplayName(); 124 | if (amnt == 1.0) { 125 | label = cur.getDisplayName(); 126 | } 127 | return TextSerializers.FORMATTING_CODE.serialize(label); 128 | } 129 | } 130 | -------------------------------------------------------------------------------- /src/main/java/io/github/flibio/economylite/modules/loan/LoanManager.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of EconomyLite, licensed under the MIT License (MIT). See the LICENSE file at the root of this project for more information. 3 | */ 4 | package io.github.flibio.economylite.modules.loan; 5 | 6 | import io.github.flibio.economylite.CauseFactory; 7 | import io.github.flibio.economylite.EconomyLite; 8 | import io.github.flibio.economylite.modules.loan.event.LoanBalanceChangeEvent; 9 | import io.github.flibio.utils.config.ConfigManager; 10 | import io.github.flibio.utils.file.FileManager; 11 | import org.spongepowered.api.Sponge; 12 | import org.spongepowered.api.service.economy.Currency; 13 | import org.spongepowered.api.service.economy.EconomyService; 14 | import org.spongepowered.api.service.economy.account.UniqueAccount; 15 | import org.spongepowered.api.service.economy.transaction.ResultType; 16 | 17 | import java.math.BigDecimal; 18 | import java.util.Optional; 19 | import java.util.UUID; 20 | 21 | public class LoanManager { 22 | 23 | private ConfigManager manager; 24 | private EconomyService eco = EconomyLite.getEconomyService(); 25 | private LoanModule module; 26 | 27 | public LoanManager(LoanModule module) { 28 | this.module = module; 29 | // Initialize the file 30 | manager = ConfigManager.create(EconomyLite.getInstance().getConfigDir(), "player-loans.data", EconomyLite.getInstance().getLogger()); 31 | } 32 | 33 | /** 34 | * Gets the loan balance of a player. 35 | * 36 | * @param uuid The player to get the balance of. 37 | * @return The player's balance, if no error has occurred. 38 | */ 39 | public Optional getLoanBalance(UUID uuid) { 40 | Currency cur = eco.getDefaultCurrency(); 41 | manager.setDefault(Double.class, 0.0, uuid.toString(), cur.getId(), "balance"); 42 | manager.save(); 43 | return manager.getValue(Double.class, uuid.toString(), cur.getId(), "balance"); 44 | } 45 | 46 | /** 47 | * Sets the balance of a player. 48 | * 49 | * @param uuid The player to set the balance of. 50 | * @param amount The balance that will be set. 51 | * @return If the balance was successfully set. 52 | */ 53 | public boolean setLoanBalance(UUID uuid, double amount) { 54 | // Make sure balance is within parameters 55 | if (amount < 0 || amount > module.getMaxLoan()) { 56 | return false; 57 | } 58 | // Fire loan balance change event 59 | Sponge.getEventManager().post(new LoanBalanceChangeEvent(amount, uuid)); 60 | Currency cur = eco.getDefaultCurrency(); 61 | manager.forceValue(amount, uuid.toString(), cur.getId(), "balance"); 62 | manager.save(); 63 | return true; 64 | } 65 | 66 | /** 67 | * Adds currency to a player's loan balance. Automatically charges interest 68 | * and adds to the player's account. 69 | * 70 | * @param uuid The player. 71 | * @param amount The amount to add. 72 | * @return If the amount was added successfully. 73 | */ 74 | public boolean addLoanBalance(UUID uuid, double amount) { 75 | Currency cur = eco.getDefaultCurrency(); 76 | Optional bOpt = getLoanBalance(uuid); 77 | Optional uOpt = eco.getOrCreateAccount(uuid); 78 | if (bOpt.isPresent() && uOpt.isPresent()) { 79 | double bal = bOpt.get(); 80 | if (amount < 0 || bal + (amount * module.getInterestRate()) > module.getMaxLoan()) { 81 | return false; 82 | } 83 | return (setLoanBalance(uuid, (amount * module.getInterestRate()) + bal) && uOpt.get() 84 | .deposit(cur, BigDecimal.valueOf(amount), CauseFactory.stringCause("loan")).getResult().equals(ResultType.SUCCESS)); 85 | } 86 | return false; 87 | } 88 | 89 | /** 90 | * Removes loan balance from a player. Automatically removes funds from the 91 | * player's account. 92 | * 93 | * @param uuid The player. 94 | * @param amount The amount to remove. 95 | * @return If the amount was removed successfully. 96 | */ 97 | public boolean removeLoanBalance(UUID uuid, double amount) { 98 | Currency cur = eco.getDefaultCurrency(); 99 | Optional bOpt = getLoanBalance(uuid); 100 | Optional uOpt = eco.getOrCreateAccount(uuid); 101 | if (bOpt.isPresent() && uOpt.isPresent()) { 102 | double bal = bOpt.get(); 103 | if (bal - amount < 0 || amount < 0) { 104 | return false; 105 | } 106 | return (uOpt.get().withdraw(cur, BigDecimal.valueOf(amount), CauseFactory.stringCause("loan")).getResult() 107 | .equals(ResultType.SUCCESS) && setLoanBalance(uuid, bal - amount)); 108 | } 109 | return false; 110 | } 111 | } 112 | -------------------------------------------------------------------------------- /src/main/java/io/github/flibio/economylite/modules/loan/LoanModule.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of EconomyLite, licensed under the MIT License (MIT). See the LICENSE file at the root of this project for more information. 3 | */ 4 | package io.github.flibio.economylite.modules.loan; 5 | 6 | import com.google.common.collect.ImmutableMap; 7 | import io.github.flibio.economylite.EconomyLite; 8 | import io.github.flibio.economylite.modules.Module; 9 | import io.github.flibio.economylite.modules.loan.command.LoanAcceptCommand; 10 | import io.github.flibio.economylite.modules.loan.command.LoanBalanceCommand; 11 | import io.github.flibio.economylite.modules.loan.command.LoanCommand; 12 | import io.github.flibio.economylite.modules.loan.command.LoanDenyCommand; 13 | import io.github.flibio.economylite.modules.loan.command.LoanPayCommand; 14 | import io.github.flibio.economylite.modules.loan.command.LoanTakeCommand; 15 | import io.github.flibio.utils.commands.CommandLoader; 16 | import io.github.flibio.utils.config.ConfigManager; 17 | import io.github.flibio.utils.file.FileManager; 18 | import io.github.flibio.utils.message.MessageStorage; 19 | import ninja.leaping.configurate.ConfigurationNode; 20 | import ninja.leaping.configurate.commented.CommentedConfigurationNode; 21 | import org.slf4j.Logger; 22 | import org.spongepowered.api.Sponge; 23 | import org.spongepowered.api.text.serializer.TextSerializers; 24 | 25 | import java.util.HashMap; 26 | import java.util.Map; 27 | import java.util.Optional; 28 | import java.util.UUID; 29 | 30 | public class LoanModule implements Module { 31 | 32 | private MessageStorage messages = EconomyLite.getMessageStorage(); 33 | private ConfigManager configManager = EconomyLite.getConfigManager(); 34 | private LoanManager loanManager; 35 | private double interestRate = 1.0; 36 | private double maxLoan = 1000.0; 37 | 38 | public HashMap tableLoans = new HashMap<>(); 39 | 40 | @Override 41 | public boolean initialize(Logger logger, Object plugin) { 42 | Optional iOpt = configManager.getValue(Double.class, "modules", "loan", "interest-rate"); 43 | Optional mOpt = configManager.getValue(Double.class, "modules", "loan", "max-loan-balance"); 44 | if (iOpt.isPresent() && mOpt.isPresent()) { 45 | interestRate = iOpt.get(); 46 | maxLoan = mOpt.get(); 47 | if (interestRate < 1) { 48 | logger.error("The interest rate must be greater than or equal to 1!"); 49 | return false; 50 | } 51 | if (maxLoan <= 0) { 52 | logger.error("The interest rate must be greater than 0!"); 53 | return false; 54 | } 55 | logger.info("Interest rate set to " + interestRate + "!"); 56 | logger.info("Maximum loan balance set to " + maxLoan + "!"); 57 | } else { 58 | return false; 59 | } 60 | return true; 61 | } 62 | 63 | @Override 64 | public void postInitialization(Logger logger, Object plugin) { 65 | // Create loan manager 66 | loanManager = new LoanManager(this); 67 | // Register listeners 68 | Sponge.getEventManager().registerListeners(plugin, new LoanListener(this)); 69 | // Register commands 70 | CommandLoader.registerCommands(plugin, TextSerializers.FORMATTING_CODE.serialize(messages.getMessage("command.invalidsource")), 71 | new LoanCommand(), 72 | new LoanBalanceCommand(this), 73 | new LoanPayCommand(this), 74 | new LoanTakeCommand(this), 75 | new LoanAcceptCommand(this), 76 | new LoanDenyCommand(this) 77 | ); 78 | } 79 | 80 | @Override 81 | public void initializeConfig() { 82 | configManager.setDefault(Boolean.class, false, "modules", "loan", "enabled"); 83 | configManager.setDefault(Double.class, 1.0, "modules", "loan", "interest-rate"); 84 | configManager.setDefault(Double.class, 1000.0, "modules", "loan", "max-loan-balance"); 85 | 86 | CommentedConfigurationNode con = configManager.getNode(); 87 | Map defaultPerms = ImmutableMap.of("reward.permission", true); 88 | if (con.getNode("modules").getNode("loan").getNode("debtor-perms").isVirtual()) { 89 | con.getNode("modules").getNode("loan").getNode("debtor-perms").setValue(defaultPerms); 90 | configManager.overwriteNode(con); 91 | } 92 | } 93 | 94 | @Override 95 | public String getName() { 96 | return "Loan"; 97 | } 98 | 99 | @Override 100 | public boolean isEnabled() { 101 | return configManager.getValue(Boolean.class, false, "modules", "loan", "enabled"); 102 | } 103 | 104 | public LoanManager getLoanManager() { 105 | return loanManager; 106 | } 107 | 108 | public double getMaxLoan() { 109 | return maxLoan; 110 | } 111 | 112 | public double getInterestRate() { 113 | return interestRate; 114 | } 115 | 116 | public Map getPermissions() { 117 | Map perms = new HashMap<>(); 118 | CommentedConfigurationNode con = configManager.getNode(); 119 | 120 | Map map = con.getNode("modules").getNode("loan").getNode("debtor-perms").getChildrenMap(); 121 | 122 | map.keySet().forEach(perm -> { 123 | perms.put(perm.toString(), map.get(perm).getBoolean()); 124 | }); 125 | return perms; 126 | } 127 | } 128 | -------------------------------------------------------------------------------- /src/main/java/io/github/flibio/economylite/modules/loan/LoanTextUtils.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of EconomyLite, licensed under the MIT License (MIT). See the LICENSE file at the root of this project for more information. 3 | */ 4 | package io.github.flibio.economylite.modules.loan; 5 | 6 | import org.spongepowered.api.text.action.TextActions; 7 | 8 | import org.spongepowered.api.text.format.TextColors; 9 | import org.spongepowered.api.text.Text; 10 | 11 | public class LoanTextUtils { 12 | 13 | public static Text yesOrNo(String yes, String no) { 14 | Text accept = 15 | Text.of(TextColors.DARK_GRAY, "[", TextColors.GREEN, "YES", TextColors.DARK_GRAY, "]").toBuilder() 16 | .onHover(TextActions.showText(Text.of(TextColors.GREEN, "Yes!"))) 17 | .onClick(TextActions.runCommand(yes)) 18 | .build(); 19 | Text deny = 20 | Text.of(TextColors.DARK_GRAY, "[", TextColors.RED, "NO", TextColors.DARK_GRAY, "]").toBuilder() 21 | .onHover(TextActions.showText(Text.of(TextColors.RED, "No!"))) 22 | .onClick(TextActions.runCommand(no)) 23 | .build(); 24 | return accept.toBuilder().append(Text.of(" "), deny).build(); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/io/github/flibio/economylite/modules/loan/command/LoanAcceptCommand.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of EconomyLite, licensed under the MIT License (MIT). See the LICENSE file at the root of this project for more information. 3 | */ 4 | package io.github.flibio.economylite.modules.loan.command; 5 | 6 | import io.github.flibio.economylite.EconomyLite; 7 | import io.github.flibio.economylite.modules.loan.LoanManager; 8 | import io.github.flibio.economylite.modules.loan.LoanModule; 9 | import io.github.flibio.utils.commands.AsyncCommand; 10 | import io.github.flibio.utils.commands.BaseCommandExecutor; 11 | import io.github.flibio.utils.commands.Command; 12 | import io.github.flibio.utils.commands.ParentCommand; 13 | import io.github.flibio.utils.message.MessageStorage; 14 | import org.spongepowered.api.command.args.CommandContext; 15 | import org.spongepowered.api.command.spec.CommandSpec; 16 | import org.spongepowered.api.command.spec.CommandSpec.Builder; 17 | import org.spongepowered.api.entity.living.player.Player; 18 | 19 | import java.util.UUID; 20 | 21 | @AsyncCommand 22 | @ParentCommand(parentCommand = LoanCommand.class) 23 | @Command(aliases = {"accept"}, permission = "economylite.loan.accept") 24 | public class LoanAcceptCommand extends BaseCommandExecutor { 25 | 26 | private LoanModule module; 27 | private LoanManager manager; 28 | private MessageStorage messages; 29 | 30 | public LoanAcceptCommand(LoanModule module) { 31 | this.module = module; 32 | this.manager = module.getLoanManager(); 33 | this.messages = EconomyLite.getMessageStorage(); 34 | } 35 | 36 | @Override 37 | public Builder getCommandSpecBuilder() { 38 | return CommandSpec.builder() 39 | .executor(this); 40 | } 41 | 42 | @Override 43 | public void run(Player src, CommandContext args) { 44 | UUID uuid = src.getUniqueId(); 45 | // Check if the player has a loan being offered 46 | if (module.tableLoans.containsKey(uuid)) { 47 | double amnt = module.tableLoans.get(uuid); 48 | if (manager.addLoanBalance(uuid, amnt)) { 49 | // Remove from the table 50 | module.tableLoans.remove(uuid); 51 | src.sendMessage(messages.getMessage("module.loan.yes")); 52 | } else { 53 | src.sendMessage(messages.getMessage("module.loan.fail")); 54 | } 55 | } else { 56 | src.sendMessage(messages.getMessage("module.loan.noloan")); 57 | } 58 | } 59 | 60 | } 61 | -------------------------------------------------------------------------------- /src/main/java/io/github/flibio/economylite/modules/loan/command/LoanBalanceCommand.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of EconomyLite, licensed under the MIT License (MIT). See the LICENSE file at the root of this project for more information. 3 | */ 4 | package io.github.flibio.economylite.modules.loan.command; 5 | 6 | import org.spongepowered.api.text.Text; 7 | import org.spongepowered.api.service.economy.Currency; 8 | import io.github.flibio.economylite.EconomyLite; 9 | import io.github.flibio.utils.message.MessageStorage; 10 | import io.github.flibio.economylite.modules.loan.LoanModule; 11 | import io.github.flibio.utils.commands.AsyncCommand; 12 | import io.github.flibio.utils.commands.BaseCommandExecutor; 13 | import io.github.flibio.utils.commands.Command; 14 | import io.github.flibio.utils.commands.ParentCommand; 15 | import org.spongepowered.api.command.args.CommandContext; 16 | import org.spongepowered.api.command.spec.CommandSpec; 17 | import org.spongepowered.api.command.spec.CommandSpec.Builder; 18 | import org.spongepowered.api.entity.living.player.Player; 19 | import org.spongepowered.api.text.serializer.TextSerializers; 20 | 21 | import java.util.Locale; 22 | import java.util.Optional; 23 | 24 | @AsyncCommand 25 | @ParentCommand(parentCommand = LoanCommand.class) 26 | @Command(aliases = {"balance", "bal"}, permission = "economylite.loan.balance") 27 | public class LoanBalanceCommand extends BaseCommandExecutor { 28 | 29 | private MessageStorage messages = EconomyLite.getMessageStorage(); 30 | private LoanModule module; 31 | 32 | public LoanBalanceCommand(LoanModule module) { 33 | this.module = module; 34 | } 35 | 36 | @Override 37 | public Builder getCommandSpecBuilder() { 38 | return CommandSpec.builder() 39 | .executor(this); 40 | } 41 | 42 | @Override 43 | public void run(Player src, CommandContext args) { 44 | Optional bOpt = module.getLoanManager().getLoanBalance(src.getUniqueId()); 45 | if (bOpt.isPresent()) { 46 | Currency cur = EconomyLite.getEconomyService().getDefaultCurrency(); 47 | src.sendMessage(messages.getMessage("module.loan.balance", "balance", String.format(Locale.ENGLISH, "%,.2f", bOpt.get()), 48 | "label", getPrefix(bOpt.get(), cur))); 49 | } else { 50 | src.sendMessage(messages.getMessage("command.error")); 51 | } 52 | } 53 | 54 | private String getPrefix(double amnt, Currency cur) { 55 | Text label = cur.getPluralDisplayName(); 56 | if (amnt == 1.0) { 57 | label = cur.getDisplayName(); 58 | } 59 | return TextSerializers.FORMATTING_CODE.serialize(label); 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /src/main/java/io/github/flibio/economylite/modules/loan/command/LoanCommand.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of EconomyLite, licensed under the MIT License (MIT). See the LICENSE file at the root of this project for more information. 3 | */ 4 | package io.github.flibio.economylite.modules.loan.command; 5 | 6 | import io.github.flibio.economylite.EconomyLite; 7 | import io.github.flibio.utils.message.MessageStorage; 8 | import org.spongepowered.api.command.args.CommandContext; 9 | import org.spongepowered.api.command.spec.CommandSpec; 10 | import org.spongepowered.api.command.spec.CommandSpec.Builder; 11 | 12 | import io.github.flibio.utils.commands.AsyncCommand; 13 | import io.github.flibio.utils.commands.BaseCommandExecutor; 14 | import io.github.flibio.utils.commands.Command; 15 | import org.spongepowered.api.command.CommandSource; 16 | 17 | @AsyncCommand 18 | @Command(aliases = {"loan"}, permission = "economylite.loan") 19 | public class LoanCommand extends BaseCommandExecutor { 20 | 21 | private MessageStorage messageStorage = EconomyLite.getMessageStorage(); 22 | 23 | @Override 24 | public Builder getCommandSpecBuilder() { 25 | return CommandSpec.builder() 26 | .executor(this); 27 | } 28 | 29 | @Override 30 | public void run(CommandSource src, CommandContext args) { 31 | src.sendMessage(messageStorage.getMessage("command.usage", "command", "/loan", "subcommands", "balance | pay | take | accept | deny")); 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/io/github/flibio/economylite/modules/loan/command/LoanDenyCommand.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of EconomyLite, licensed under the MIT License (MIT). See the LICENSE file at the root of this project for more information. 3 | */ 4 | package io.github.flibio.economylite.modules.loan.command; 5 | 6 | import io.github.flibio.economylite.EconomyLite; 7 | import io.github.flibio.economylite.modules.loan.LoanModule; 8 | import io.github.flibio.utils.commands.AsyncCommand; 9 | import io.github.flibio.utils.commands.BaseCommandExecutor; 10 | import io.github.flibio.utils.commands.Command; 11 | import io.github.flibio.utils.commands.ParentCommand; 12 | import io.github.flibio.utils.message.MessageStorage; 13 | import org.spongepowered.api.command.args.CommandContext; 14 | import org.spongepowered.api.command.spec.CommandSpec; 15 | import org.spongepowered.api.command.spec.CommandSpec.Builder; 16 | import org.spongepowered.api.entity.living.player.Player; 17 | 18 | import java.util.UUID; 19 | 20 | @AsyncCommand 21 | @ParentCommand(parentCommand = LoanCommand.class) 22 | @Command(aliases = {"deny"}, permission = "economylite.loan.deny") 23 | public class LoanDenyCommand extends BaseCommandExecutor { 24 | 25 | private LoanModule module; 26 | private MessageStorage messages; 27 | 28 | public LoanDenyCommand(LoanModule module) { 29 | this.module = module; 30 | this.messages = EconomyLite.getMessageStorage(); 31 | } 32 | 33 | @Override 34 | public Builder getCommandSpecBuilder() { 35 | return CommandSpec.builder() 36 | .executor(this); 37 | } 38 | 39 | @Override 40 | public void run(Player src, CommandContext args) { 41 | UUID uuid = src.getUniqueId(); 42 | // Check if the player has a loan being offered 43 | if (module.tableLoans.containsKey(uuid)) { 44 | module.tableLoans.remove(uuid); 45 | src.sendMessage(messages.getMessage("module.loan.no")); 46 | } else { 47 | src.sendMessage(messages.getMessage("module.loan.noloan")); 48 | } 49 | } 50 | 51 | } 52 | -------------------------------------------------------------------------------- /src/main/java/io/github/flibio/economylite/modules/loan/command/LoanPayCommand.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of EconomyLite, licensed under the MIT License (MIT). See the LICENSE file at the root of this project for more information. 3 | */ 4 | package io.github.flibio.economylite.modules.loan.command; 5 | 6 | import org.spongepowered.api.service.economy.Currency; 7 | 8 | import io.github.flibio.economylite.EconomyLite; 9 | import io.github.flibio.economylite.modules.loan.LoanModule; 10 | import io.github.flibio.utils.commands.AsyncCommand; 11 | import io.github.flibio.utils.commands.BaseCommandExecutor; 12 | import io.github.flibio.utils.commands.Command; 13 | import io.github.flibio.utils.commands.ParentCommand; 14 | import io.github.flibio.utils.message.MessageStorage; 15 | import org.spongepowered.api.command.args.CommandContext; 16 | import org.spongepowered.api.command.args.GenericArguments; 17 | import org.spongepowered.api.command.spec.CommandSpec; 18 | import org.spongepowered.api.command.spec.CommandSpec.Builder; 19 | import org.spongepowered.api.entity.living.player.Player; 20 | import org.spongepowered.api.text.Text; 21 | import org.spongepowered.api.text.serializer.TextSerializers; 22 | 23 | import java.util.Locale; 24 | import java.util.Optional; 25 | import java.util.UUID; 26 | 27 | @AsyncCommand 28 | @ParentCommand(parentCommand = LoanCommand.class) 29 | @Command(aliases = {"pay"}, permission = "economylite.loan.pay") 30 | public class LoanPayCommand extends BaseCommandExecutor { 31 | 32 | private MessageStorage messages = EconomyLite.getMessageStorage(); 33 | private LoanModule module; 34 | 35 | public LoanPayCommand(LoanModule module) { 36 | this.module = module; 37 | } 38 | 39 | @Override 40 | public Builder getCommandSpecBuilder() { 41 | return CommandSpec.builder() 42 | .arguments(GenericArguments.doubleNum(Text.of("amount"))) 43 | .executor(this); 44 | } 45 | 46 | @Override 47 | public void run(Player src, CommandContext args) { 48 | if (args.getOne("amount").isPresent()) { 49 | UUID uuid = src.getUniqueId(); 50 | double payment = args.getOne("amount").get(); 51 | Currency cur = EconomyLite.getEconomyService().getDefaultCurrency(); 52 | Optional bOpt = module.getLoanManager().getLoanBalance(uuid); 53 | if (bOpt.isPresent()) { 54 | double loanBal = bOpt.get(); 55 | if (payment > loanBal) { 56 | // Pay only what is needed 57 | if (module.getLoanManager().removeLoanBalance(uuid, loanBal)) { 58 | // Successfully payed loan 59 | src.sendMessage(messages.getMessage("module.loan.payed", "amount", String.format(Locale.ENGLISH, "%,.2f", loanBal), 60 | "label", getPrefix(loanBal, cur))); 61 | } else { 62 | // Failed to pay 63 | src.sendMessage(messages.getMessage("module.loan.payedfail")); 64 | } 65 | } else { 66 | // Pay entire request 67 | if (module.getLoanManager().removeLoanBalance(uuid, payment)) { 68 | // Successfully payed loan 69 | src.sendMessage(messages.getMessage("module.loan.payed", "amount", String.format(Locale.ENGLISH, "%,.2f", payment), 70 | "label", getPrefix(payment, cur))); 71 | } else { 72 | // Failed to pay 73 | src.sendMessage(messages.getMessage("module.loan.payedfail")); 74 | } 75 | } 76 | } 77 | } else { 78 | src.sendMessage(messages.getMessage("command.error")); 79 | } 80 | } 81 | 82 | private String getPrefix(double amnt, Currency cur) { 83 | Text label = cur.getPluralDisplayName(); 84 | if (amnt == 1.0) { 85 | label = cur.getDisplayName(); 86 | } 87 | return TextSerializers.FORMATTING_CODE.serialize(label); 88 | } 89 | } 90 | -------------------------------------------------------------------------------- /src/main/java/io/github/flibio/economylite/modules/loan/command/LoanTakeCommand.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of EconomyLite, licensed under the MIT License (MIT). See the LICENSE file at the root of this project for more information. 3 | */ 4 | package io.github.flibio.economylite.modules.loan.command; 5 | 6 | import io.github.flibio.economylite.EconomyLite; 7 | import io.github.flibio.economylite.modules.loan.LoanModule; 8 | import io.github.flibio.economylite.modules.loan.LoanTextUtils; 9 | import io.github.flibio.utils.commands.AsyncCommand; 10 | import io.github.flibio.utils.commands.BaseCommandExecutor; 11 | import io.github.flibio.utils.commands.Command; 12 | import io.github.flibio.utils.commands.ParentCommand; 13 | import io.github.flibio.utils.message.MessageStorage; 14 | import org.spongepowered.api.command.args.CommandContext; 15 | import org.spongepowered.api.command.args.GenericArguments; 16 | import org.spongepowered.api.command.spec.CommandSpec; 17 | import org.spongepowered.api.command.spec.CommandSpec.Builder; 18 | import org.spongepowered.api.entity.living.player.Player; 19 | import org.spongepowered.api.service.economy.Currency; 20 | import org.spongepowered.api.text.Text; 21 | import org.spongepowered.api.text.serializer.TextSerializers; 22 | 23 | import java.util.Locale; 24 | import java.util.Optional; 25 | import java.util.UUID; 26 | 27 | @AsyncCommand 28 | @ParentCommand(parentCommand = LoanCommand.class) 29 | @Command(aliases = {"take"}, permission = "economylite.loan.take") 30 | public class LoanTakeCommand extends BaseCommandExecutor { 31 | 32 | private MessageStorage messages = EconomyLite.getMessageStorage(); 33 | private LoanModule module; 34 | 35 | public LoanTakeCommand(LoanModule module) { 36 | this.module = module; 37 | } 38 | 39 | @Override 40 | public Builder getCommandSpecBuilder() { 41 | return CommandSpec.builder() 42 | .arguments(GenericArguments.doubleNum(Text.of("amount"))) 43 | .executor(this); 44 | } 45 | 46 | @Override 47 | public void run(Player src, CommandContext args) { 48 | if (args.getOne("amount").isPresent()) { 49 | UUID uuid = src.getUniqueId(); 50 | double loanAmount = args.getOne("amount").get(); 51 | Currency cur = EconomyLite.getEconomyService().getDefaultCurrency(); 52 | // Get player balance 53 | Optional dOpt = module.getLoanManager().getLoanBalance(uuid); 54 | if (dOpt.isPresent()) { 55 | double loanBalance = dOpt.get(); 56 | // Notify player of interest rate 57 | src.sendMessage(messages.getMessage("module.loan.interest", "rate", Double.toString(module.getInterestRate()))); 58 | // Check how much loan they can take out 59 | double maxLoan = (module.getMaxLoan() - loanBalance) / module.getInterestRate(); 60 | if (maxLoan <= 0) { 61 | // Tell player they are out of loan balance 62 | src.sendMessage(messages.getMessage("modules.loan.full")); 63 | } 64 | if (maxLoan < loanAmount) { 65 | // Offer the player a smaller loan 66 | src.sendMessage(messages.getMessage("module.loan.partial")); 67 | src.sendMessage(messages.getMessage("module.loan.ask", "amount", String.format(Locale.ENGLISH, "%,.2f", maxLoan), "label", 68 | getPrefix(maxLoan, cur))); 69 | double total = maxLoan * module.getInterestRate(); 70 | src.sendMessage(messages.getMessage("module.loan.payment", "amount", String.format(Locale.ENGLISH, "%,.2f", total), "label", 71 | getPrefix(total, cur))); 72 | module.tableLoans.remove(uuid); 73 | module.tableLoans.put(uuid, maxLoan); 74 | } else { 75 | // Ask the player if they want a full loan 76 | src.sendMessage(messages.getMessage("module.loan.ask", "amount", String.format(Locale.ENGLISH, "%,.2f", loanAmount), 77 | "label", getPrefix(loanAmount, cur))); 78 | double total = loanAmount * module.getInterestRate(); 79 | src.sendMessage(messages.getMessage("module.loan.payment", "amount", String.format(Locale.ENGLISH, "%,.2f", total), "label", 80 | getPrefix(total, cur))); 81 | src.sendMessage(LoanTextUtils.yesOrNo("/loan accept", "/loan deny")); 82 | module.tableLoans.remove(uuid); 83 | module.tableLoans.put(uuid, loanAmount); 84 | } 85 | } else { 86 | src.sendMessage(messages.getMessage("command.error")); 87 | } 88 | } else { 89 | src.sendMessage(messages.getMessage("command.error")); 90 | } 91 | } 92 | 93 | private String getPrefix(double amnt, Currency cur) { 94 | Text label = cur.getPluralDisplayName(); 95 | if (amnt == 1.0) { 96 | label = cur.getDisplayName(); 97 | } 98 | return TextSerializers.FORMATTING_CODE.serialize(label); 99 | } 100 | 101 | } 102 | -------------------------------------------------------------------------------- /src/main/java/io/github/flibio/economylite/modules/loan/event/LoanBalanceChangeEvent.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of EconomyLite, licensed under the MIT License (MIT). See the LICENSE file at the root of this project for more information. 3 | */ 4 | package io.github.flibio.economylite.modules.loan.event; 5 | 6 | import io.github.flibio.economylite.EconomyLite; 7 | import org.spongepowered.api.event.cause.Cause; 8 | import org.spongepowered.api.event.cause.EventContext; 9 | import org.spongepowered.api.event.impl.AbstractEvent; 10 | 11 | import java.util.UUID; 12 | 13 | public class LoanBalanceChangeEvent extends AbstractEvent { 14 | 15 | private UUID user; 16 | private Double balance; 17 | 18 | public LoanBalanceChangeEvent(double newBalance, UUID user) { 19 | this.user = user; 20 | this.balance = newBalance; 21 | } 22 | 23 | @Override 24 | public Cause getCause() { 25 | return Cause.of(EventContext.empty(), EconomyLite.getInstance().getPluginContainer()); 26 | } 27 | 28 | public UUID getUser() { 29 | return user; 30 | } 31 | 32 | public Double getNewBalance() { 33 | return balance; 34 | } 35 | 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/io/github/flibio/economylite/modules/sql/PlayerSqlService.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of EconomyLite, licensed under the MIT License (MIT). See the LICENSE file at the root of this project for more information. 3 | */ 4 | package io.github.flibio.economylite.modules.sql; 5 | 6 | import io.github.flibio.economylite.EconomyLite; 7 | import io.github.flibio.economylite.impl.PlayerServiceCommon; 8 | import io.github.flibio.utils.sql.RemoteSqlManager; 9 | 10 | public class PlayerSqlService extends PlayerServiceCommon { 11 | 12 | public PlayerSqlService(String hostname, String port, String database, String username, String password) { 13 | super(RemoteSqlManager.createInstance(EconomyLite.getInstance(), hostname, port, database, username, password).get(), false); 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/io/github/flibio/economylite/modules/sql/SqlModule.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of EconomyLite, licensed under the MIT License (MIT). See the LICENSE file at the root of this project for more information. 3 | */ 4 | package io.github.flibio.economylite.modules.sql; 5 | 6 | import io.github.flibio.economylite.EconomyLite; 7 | import io.github.flibio.economylite.modules.Module; 8 | import io.github.flibio.utils.config.ConfigManager; 9 | import org.slf4j.Logger; 10 | 11 | import java.util.Optional; 12 | 13 | public class SqlModule implements Module { 14 | 15 | private ConfigManager configManager = EconomyLite.getConfigManager(); 16 | 17 | @Override 18 | public boolean initialize(Logger logger, Object plugin) { 19 | String hostname = getDetail("hostname"); 20 | String port = getDetail("port"); 21 | String database = getDetail("database"); 22 | String username = getDetail("username"); 23 | String password = getDetail("password"); 24 | PlayerSqlService pService = new PlayerSqlService(hostname, port, database, username, password); 25 | VirtualSqlService vService = new VirtualSqlService(hostname, port, database, username, password); 26 | if (pService.isWorking() && vService.isWorking()) { 27 | EconomyLite.setPlayerService(pService); 28 | EconomyLite.setVirtualService(vService); 29 | } else { 30 | return false; 31 | } 32 | return true; 33 | } 34 | 35 | @Override 36 | public void initializeConfig() { 37 | configManager.setDefault(Boolean.class, false, "modules", "mysql", "enabled"); 38 | configManager.setDefault(String.class, "hostname", "modules", "mysql", "hostname"); 39 | configManager.setDefault(String.class, "3306", "modules", "mysql", "port"); 40 | configManager.setDefault(String.class, "database", "modules", "mysql", "database"); 41 | configManager.setDefault(String.class, "username", "modules", "mysql", "username"); 42 | configManager.setDefault(String.class, "password", "modules", "mysql", "password"); 43 | } 44 | 45 | @Override 46 | public String getName() { 47 | return "SQL"; 48 | } 49 | 50 | @Override 51 | public boolean isEnabled() { 52 | return configManager.getValue(Boolean.class, false, "modules", "mysql", "enabled"); 53 | } 54 | 55 | private String getDetail(String name) { 56 | return configManager.getValue("", String.class, "modules", "mysql", name); 57 | } 58 | 59 | } 60 | -------------------------------------------------------------------------------- /src/main/java/io/github/flibio/economylite/modules/sql/VirtualSqlService.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of EconomyLite, licensed under the MIT License (MIT). See the LICENSE file at the root of this project for more information. 3 | */ 4 | package io.github.flibio.economylite.modules.sql; 5 | 6 | import io.github.flibio.economylite.EconomyLite; 7 | import io.github.flibio.economylite.impl.VirtualServiceCommon; 8 | import io.github.flibio.utils.sql.RemoteSqlManager; 9 | 10 | public class VirtualSqlService extends VirtualServiceCommon { 11 | 12 | public VirtualSqlService(String hostname, String port, String database, String username, String password) { 13 | super(RemoteSqlManager.createInstance(EconomyLite.getInstance(), hostname, port, database, username, password).get(), false); 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /src/main/resources/messages.properties: -------------------------------------------------------------------------------- 1 | command.usage=&aUsage: &f{command} {subcommands} 2 | command.noperm=&cYou do not have permission to run this command! 3 | command.invalidsource=&cYou must be a {sourcetype} to use this command! 4 | command.error=&cAn internal error has occurred! 5 | 6 | command.baltop.head=&6&lTop Balances 7 | command.baltop.data=&7[&f{position}&7] &e{name}: &a{balance} &e{label} 8 | command.baltop.invalidpage=&cInvalid page number! 9 | command.baltop.nodata=&cNo data found for that page! 10 | command.baltop.navigation=&7[&a{button}&7] 11 | 12 | command.balance=&6Current Balance: &a{balance} &6{label} 13 | command.balanceother=&6{player}'s Balance: &a{balance} &6{label} 14 | 15 | command.currency.changed=&6Changed the currency to &a{currency}! 16 | command.currency.confirm=&6Click on this message to confirm the switch to &a{currency}! 17 | command.currency.current=&6Current Currency: &a{currency}! 18 | command.currency.invalid=&cThat currency could not be found! 19 | command.currency.selectnew=&6Run &a/currency set &6to change the currency or click on a new currency! 20 | command.currency.delete=&6Run &a/currency delete &6to delete a currency or click on a currency! 21 | command.currency.deleteconfirm=&6Click on this message to confirm the deletion of &a{currency}! 22 | command.currency.deleted=&6Deleted the currency &a{currency}! 23 | command.currency.deletedefault=&cYou may not delete the default currency! 24 | command.currency.created=&6Registered new currency: &a{currency}! 25 | command.currency.exists=&cThat currency already exists! 26 | 27 | command.econ.addfail=&cFailed to add currency to the balance of {name}! 28 | command.econ.addsuccess=&aSuccessfully added currency to the balance of &6{name}! 29 | command.econ.removefail=&cFailed to remove currency from the balance of {name}! 30 | command.econ.removesuccess=&aSuccessfully removed currency from the balance of &6{name}! 31 | command.econ.setfail=&cFailed to set the balance of {name}! 32 | command.econ.setsuccess=&aSuccessfully set the balance of &6{name}! 33 | command.econ.notify=&6Your balance has been modified! 34 | 35 | command.migrate.completed=&aMigration completed! 36 | command.migrate.confirm=&cMigrating will override any existing balances. &6Run &a/migrate yes &6to confirm the migration! 37 | command.migrate.fail=&cMigration failed! 38 | command.migrate.nomode=&cPlease choose a valid migration mode! 39 | 40 | command.refresh.fail=&cFailed to reset database cache! 41 | command.refresh.success=&aReset database cache! 42 | 43 | command.pay.notyou=&cYou can not pay yourself! 44 | command.pay.invalid=&cInvalid amount of currency specified! 45 | command.pay.failed=&cThe payment to {target} failed! 46 | command.pay.success=&6{target} &awas successfully payed &6{amountandlabel}&a! 47 | command.pay.target=&6You have received &a{amountandlabel} &6from &a{sender}! 48 | command.pay.confirm=&a{player} is not online! Do you still want to send the payment? 49 | command.pay.confirmno=&c{player} will not be paid! 50 | 51 | module.loan.ask=&6Would you like to take out a loan for &a{amount} &6{label}? (Use &a/loan accept &6or &a/loan deny&6) 52 | module.loan.partial=&cYou are being offered a partial loan! 53 | module.loan.interest=&6Loans will be paid back with an interest rate of &a{rate}&6! 54 | module.loan.full=&cYour loan balance is full, you must pay off some loans first! 55 | module.loan.no=&cLoan offer has been removed! 56 | module.loan.yes=&aLoan accepted! 57 | module.loan.fail=&cAn error occurred while taking out a loan! 58 | module.loan.balance=&6Current Loan Balance: &a{balance} &6{label} 59 | module.loan.payed=&6Payed &a{amount} &6{label} towards your loan balance! 60 | module.loan.payedfail=&cLoan payment failed! 61 | module.loan.payment=&6This will add &a{amount} &6{label} to your loan balance! 62 | module.loan.noloan=&cYou do not have a loan being offered! 63 | --------------------------------------------------------------------------------