├── .github
└── ISSUE_TEMPLATE
│ ├── bug_report.yml
│ ├── feature_request.yml
│ └── question.yml
├── .gitignore
├── README.md
├── build.gradle.kts
├── gradle.properties
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── settings.gradle.kts
└── src
└── main
├── java
└── com
│ └── github
│ └── encryptsl
│ └── lite
│ └── eco
│ └── LiteEcoLoader.java
├── kotlin
└── com
│ └── github
│ └── encryptsl
│ └── lite
│ └── eco
│ ├── LiteEco.kt
│ ├── api
│ ├── ComponentPaginator.kt
│ ├── ConfigAPI.kt
│ ├── PlayerAccount.kt
│ ├── UpdateNotifier.kt
│ ├── economy
│ │ ├── Currency.kt
│ │ ├── EconomyOperations.kt
│ │ ├── ModernLiteEcoEconomyImpl.kt
│ │ └── SuspendLiteEcoEconomyWrapper.kt
│ ├── enums
│ │ ├── CheckLevel.kt
│ │ ├── ExportKeys.kt
│ │ └── PurgeKey.kt
│ ├── events
│ │ ├── PlayerEconomyPayEvent.kt
│ │ └── admin
│ │ │ ├── EconomyGlobalDepositEvent.kt
│ │ │ ├── EconomyGlobalSetEvent.kt
│ │ │ ├── EconomyGlobalWithdrawEvent.kt
│ │ │ ├── EconomyMoneyDepositEvent.kt
│ │ │ ├── EconomyMoneySetEvent.kt
│ │ │ └── EconomyMoneyWithdrawEvent.kt
│ ├── interfaces
│ │ ├── AccountAPI.kt
│ │ ├── ConfigAPIProvider.kt
│ │ ├── DatabaseConnectorProvider.kt
│ │ ├── EconomyImporter.kt
│ │ ├── LiteEconomyAPI.kt
│ │ ├── PlayerSQL.kt
│ │ └── TransactionLogger.kt
│ ├── migrator
│ │ ├── CSVFileExporter.kt
│ │ ├── Export.kt
│ │ ├── SQLFileExporter.kt
│ │ └── entity
│ │ │ └── PlayerBalances.kt
│ └── objects
│ │ └── ModernText.kt
│ ├── commands
│ ├── EcoCMD.kt
│ ├── InternalCmd.kt
│ ├── MoneyCMD.kt
│ └── parsers
│ │ ├── CurrencyParser.kt
│ │ ├── ImportEconomyParser.kt
│ │ └── LangParser.kt
│ ├── common
│ ├── AccountManager.kt
│ ├── config
│ │ └── Locales.kt
│ ├── database
│ │ ├── DatabaseConfigLoader.kt
│ │ ├── DatabaseConnector.kt
│ │ ├── SqlPluginLogger.kt
│ │ ├── entity
│ │ │ ├── EconomyLog.kt
│ │ │ └── User.kt
│ │ ├── models
│ │ │ ├── DatabaseEcoModel.kt
│ │ │ ├── DatabaseMonologModel.kt
│ │ │ └── legacy
│ │ │ │ └── LegacyDatabaseEcoModel.kt
│ │ └── tables
│ │ │ ├── Account.kt
│ │ │ ├── MonologTable.kt
│ │ │ └── legacy
│ │ │ └── LegacyAccountTable.kt
│ ├── extensions
│ │ ├── DatabaseLoggerTransaction.kt
│ │ ├── KotlinHelper.kt
│ │ ├── MoneyFormat.kt
│ │ ├── NumberControl.kt
│ │ ├── StringExtentions.kt
│ │ └── TopPosition.kt
│ ├── hook
│ │ ├── HookListener.kt
│ │ ├── HookManager.kt
│ │ ├── bettereconomy
│ │ │ └── BetterEconomyHook.kt
│ │ ├── craftconomy3
│ │ │ └── CraftConomyHook.kt
│ │ ├── miniplaceholder
│ │ │ ├── EconomyMiniPlaceholder.kt
│ │ │ └── MiniPlaceholdersHook.kt
│ │ ├── placeholderapi
│ │ │ ├── EconomyPlaceholderAPI.kt
│ │ │ └── PlaceholderAPIHook.kt
│ │ ├── scruffyboy13
│ │ │ └── ScruffyboyEconomyHook.kt
│ │ └── vault
│ │ │ ├── AdaptiveEconomyVaultAPI.kt
│ │ │ ├── DeprecatedEconomy.kt
│ │ │ ├── VaultHook.kt
│ │ │ └── unlocked
│ │ │ ├── AdaptiveEconomyVaultUnlockedAPI.kt
│ │ │ └── UnusedVaultUnlockedAPI.kt
│ └── manager
│ │ ├── ExportManager.kt
│ │ ├── ImportManager.kt
│ │ ├── MonologManager.kt
│ │ ├── PurgeManager.kt
│ │ └── importer
│ │ ├── EconomyImportResults.kt
│ │ ├── ImportEconomy.kt
│ │ └── economies
│ │ ├── BetterEconomyImporter.kt
│ │ ├── CraftConomy3Importer.kt
│ │ ├── EssentialsXImporter.kt
│ │ └── ScruffyBoyImporter.kt
│ ├── listeners
│ ├── PlayerAsyncPreLoginListener.kt
│ ├── PlayerEconomyPayListener.kt
│ ├── PlayerJoinListener.kt
│ ├── PlayerQuitListener.kt
│ └── admin
│ │ ├── EconomyGlobalDepositListener.kt
│ │ ├── EconomyGlobalSetListener.kt
│ │ ├── EconomyGlobalWithdrawListener.kt
│ │ ├── EconomyMoneyDepositListener.kt
│ │ ├── EconomyMoneySetListener.kt
│ │ └── EconomyMoneyWithdrawListener.kt
│ └── utils
│ ├── ClassUtil.kt
│ ├── Debugger.kt
│ ├── Helper.kt
│ └── PlayerUtils.kt
└── resources
├── config.yml
├── database.db
├── locale
├── cs_cz.yml
├── de_de.yml
├── en_us.yml
├── es_es.yml
├── ja_jp.yml
├── pl_pl.yml
├── pt_br.yml
├── tr_tr.yml
└── zh_cn.yml
├── paper-libraries.yml
├── paper-plugin.yml
└── plugin.yml
/.github/ISSUE_TEMPLATE/bug_report.yml:
--------------------------------------------------------------------------------
1 | name: Bug Report
2 | description: Template for bug report
3 | title: "[Bug]: "
4 | labels: ["Bug", "NotFixed"]
5 | assignees:
6 | - EncryptSL
7 | body:
8 | - type: markdown
9 | attributes:
10 | value: |
11 | Thanks for taking the time to fill out this bug report!
12 | Remember only last version is supported !
13 | - type: textarea
14 | id: what-happened
15 | attributes:
16 | label: What happened?
17 | description: Also tell us, what did you expect to happen?
18 | placeholder: Tell us what you see!
19 | value: "A bug happened!"
20 | validations:
21 | required: true
22 | - type: input
23 | id: version
24 | attributes:
25 | label: Plugin Version
26 | description: What version of plugin are you running?
27 | placeholder: ex. 1.1.6-SNAPSHOT
28 | validations:
29 | required: true
30 | - type: dropdown
31 | id: serversoftware
32 | attributes:
33 | label: You detected problem on this server platform ?
34 | multiple: true
35 | options:
36 | - PaperMC
37 | - PurpurMC
38 | validations:
39 | required: true
40 | - type: textarea
41 | id: version_verbose
42 | attributes:
43 | label: Version /version - output
44 | description: Please copy and paste version output from console thanks.
45 | render: shell
46 | validations:
47 | required: true
48 | - type: textarea
49 | id: logs
50 | attributes:
51 | label: Relevant log output
52 | description: Please copy and paste any relevant log output. This will be automatically formatted into code, so no need for backticks.
53 | render: shell
54 | validations:
55 | required: true
56 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/feature_request.yml:
--------------------------------------------------------------------------------
1 | name: Feature request
2 | description: Template for future request
3 | title: "[Feature Request]: "
4 | labels: ["Improvements"]
5 | assignees:
6 | - EncryptSL
7 | body:
8 | - type: markdown
9 | attributes:
10 | value: |
11 | Thanks for taking the time to fill out this form!
12 | - type: dropdown
13 | id: type_of_feature
14 | attributes:
15 | label: Type of function to add or improvement
16 | multiple: true
17 | options:
18 | - API
19 | - Others
20 | - type: textarea
21 | id: relevant_area
22 | attributes:
23 | label: Your ideas
24 | description: There you can write your idea for implement.
25 | placeholder: Tell whats is your idea about feature request.
26 | value: "I have something new for plugin !"
27 | validations:
28 | required: true
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/question.yml:
--------------------------------------------------------------------------------
1 | name: Question
2 | description: Template for question
3 | title: "[Question]: "
4 | labels: ["Question"]
5 | assignees:
6 | - EncryptSL
7 | body:
8 | - type: markdown
9 | attributes:
10 | value: |
11 | Thanks for taking the time to fill out this form!
12 | - type: textarea
13 | id: question
14 | attributes:
15 | label: Your Question
16 | description: There you can write your question.
17 | placeholder: Tell what is your question.
18 | value: "I have question aboout...."
19 | validations:
20 | required: true
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | /.gradle
2 | /.idea
3 | /.kotlin
4 | /build/
5 | /gradlew.bat
6 | /logs
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 |
3 | ![[liteeco]](https://github.com/user-attachments/assets/f58e36ab-a54f-4b93-bca1-518f3f2ce476)
4 |
5 | ***
6 | # 💸 LiteEco - Minecraft Economy Plugin
7 | *A lightweight, Vault-compatible economy plugin for Minecraft servers.*
8 |
9 | 
10 | 
11 | 
12 | 
13 |
14 | ---
15 |
16 |
17 | ## ✨ Features
18 |
19 | - 🦹 **Vault support** – compatible with any plugin using Vault or VaultUnlocked
20 | - 💱 **Multi-currency** system
21 | - 📁 **YAML-based locale system** with placeholder support
22 | - 📚 **Pagination support** for `/baltop` and `/eco monolog`
23 | - 🗂️ Support for **SQLite**, **MySQL**, **MariaDB**, and **PostgreSQL**
24 | - 🗂️ Support for **PlaceholderAPI**, **MiniPlaceholders**
25 | - 📈 Integrated with [bStats](https://bstats.org/plugin/bukkit/LiteEco)
26 | - 💡 Lightweight and performance-optimized
27 | - 🔧 Easy to configure with clean `config.yml`
28 |
29 | ---
30 |
31 | ## 📅 Download
32 |
33 | ➡️ [Get the latest release](https://www.spigotmc.org/resources/liteeco-simple-economy-plugin-1-21-x.101934/updates)
34 |
35 | ---
36 |
37 | ## 📘 Wiki & Configuration
38 |
39 | Find full documentation and configuration examples in the **[GitHub Wiki](https://github.com/EncryptSL/LiteEco/wiki)**.
40 |
41 | Popular sections:
42 | - [Plugin Settings](https://github.com/EncryptSL/LiteEco/wiki/Plugin-Settings)
43 | - [Database Configuration](https://github.com/EncryptSL/LiteEco/wiki/Database-Settings)
44 | - [Economy & Currencies](https://github.com/EncryptSL/LiteEco/wiki/Economy-Settings)
45 | - [Commands & Overview](https://github.com/EncryptSL/LiteEco/wiki/Commands-&-Permissions)
46 | - [Placeholders](https://github.com/EncryptSL/LiteEco/wiki/Placeholders)
47 | ---
48 |
49 | ## 🧪 bStats Metrics
50 |
51 | LiteEco collects **anonymous usage statistics** via [bStats](https://bstats.org/), which helps improve development:
52 |
53 | - Online servers
54 | - Plugin version usage
55 | - Command usage
56 |
57 | You can disable this in `config.yml` under `plugin.metrics`.
58 |
59 | ---
60 |
61 | ## 🖠️ Development
62 |
63 | ### Build Locally
64 |
65 | ```bash
66 | git clone https://github.com/EncryptSL/LiteEco.git
67 | cd LiteEco
68 | ./gradlew build
69 | ```
70 |
71 | Compiled JAR will be located in: `build/libs/`
72 |
73 | ---
74 |
75 | ## ☕ Support Development
76 |
77 | If you enjoy LiteEco and want to support its future:
78 |
79 | [](https://ko-fi.com/encryptsl)
80 |
81 | > Built with ❤️ by [EncryptSL](https://encryptsl.github.io)
82 |
--------------------------------------------------------------------------------
/build.gradle.kts:
--------------------------------------------------------------------------------
1 | import io.papermc.paperweight.userdev.ReobfArtifactConfiguration
2 | import org.jetbrains.kotlin.gradle.dsl.JvmTarget
3 |
4 | plugins {
5 | kotlin("jvm") version "2.2.0-RC"
6 | id("com.gradleup.shadow") version "9.0.0-beta15"
7 | id("io.papermc.paperweight.userdev") version "2.0.0-beta.17"
8 | id("maven-publish")
9 | }
10 |
11 | group = "com.github.encryptsl"
12 | version = providers.gradleProperty("plugin_version").get()
13 | description = providers.gradleProperty("plugin_description").get()
14 |
15 | val props = project.properties.mapValues { it.value.toString() }
16 |
17 | repositories {
18 | flatDir {
19 | dirs("lib")
20 | }
21 | mavenLocal()
22 | mavenCentral()
23 | maven("https://repo.papermc.io/repository/maven-public/")
24 | maven("https://s01.oss.sonatype.org/content/repositories/snapshots/")
25 | maven("https://jitpack.io")
26 | maven("https://repo.extendedclip.com/content/repositories/placeholderapi/")
27 | maven("https://repo.codemc.io/repository/maven-public/")
28 | }
29 |
30 | kotlin {
31 | jvmToolchain(21)
32 | compilerOptions {
33 | jvmTarget.set(JvmTarget.JVM_21)
34 | freeCompilerArgs.add("-Xcontext-parameters")
35 | }
36 | }
37 |
38 | dependencies {
39 | paperweight.paperDevBundle(providers.gradleProperty("server_version").get())
40 | compileOnly("com.github.MilkBowl:VaultAPI:1.7") {
41 | exclude("org.bukkit", "bukkit")
42 | }
43 | compileOnly("me.clip:placeholderapi:2.11.5")
44 |
45 | //Exposed Database Orm
46 | compileOnly("org.jetbrains.exposed:exposed-core:0.60.0")
47 | compileOnly("org.jetbrains.exposed:exposed-jdbc:0.60.0")
48 | compileOnly("org.jetbrains.exposed:exposed-kotlin-datetime:0.60.0")
49 | //Database Pool HikariCP
50 | compileOnly("com.zaxxer:HikariCP:6.2.1")
51 |
52 | //EconomyAPI
53 | compileOnly("net.milkbowl.vault:VaultUnlockedAPI:2.9")
54 |
55 | //Coding Utils
56 | compileOnly("com.squareup.okhttp3:okhttp:4.12.0")
57 | compileOnly("com.tchristofferson:ConfigUpdater:2.2-SNAPSHOT")
58 | compileOnly("org.apache.commons:commons-csv:1.14.0")
59 |
60 | //Command Framework
61 | compileOnly("org.incendo:cloud-annotations:2.0.0-SNAPSHOT") {
62 | exclude("org.incendo", "cloud-core")
63 | }
64 | compileOnly("org.incendo:cloud-paper:2.0.0-SNAPSHOT")
65 | compileOnly("org.incendo:cloud-minecraft-extras:2.0.0-SNAPSHOT") {
66 | exclude("org.incendo", "cloud-core")
67 | exclude("net.kyori", "adventure-text-api")
68 | exclude("net.kyori", "adventure-text-minimessage")
69 | exclude("net.kyori", "adventure-text-serializer-plain")
70 | }
71 | compileOnly("org.incendo:cloud-kotlin-extensions:2.0.0")
72 |
73 | // Plugins for import economy to LiteEco
74 | compileOnly("me.hsgamer:bettereconomy:3.1")
75 | compileOnly("me.scruffyboy13:Economy:2.0")
76 | compileOnly("com.greatmancode:Craftconomy3:3.3.3-SNAPSHOT")
77 |
78 | //Metrics
79 | implementation("org.bstats:bstats-bukkit:3.0.1")
80 |
81 | //MiniPlaceholders
82 | implementation("io.github.miniplaceholders:miniplaceholders-kotlin-ext:2.3.0")
83 |
84 | testImplementation(kotlin("test", "2.2.0-RC"))
85 | testImplementation("com.zaxxer:HikariCP:6.2.1")
86 | testImplementation("org.xerial:sqlite-jdbc:3.49.1.0")
87 | testImplementation("org.jetbrains.exposed:exposed-core:0.60.0")
88 | testImplementation("org.jetbrains.exposed:exposed-jdbc:0.60.0")
89 | }
90 |
91 | sourceSets {
92 | getByName("main") {
93 | java {
94 | srcDir("src/main/java")
95 | }
96 | kotlin {
97 | srcDir("src/main/kotlin")
98 | }
99 | }
100 | }
101 |
102 | tasks {
103 | processResources {
104 | filesMatching(listOf("plugin.yml", "paper-plugin.yml")) {
105 | expand(props)
106 | }
107 | }
108 |
109 | shadowJar {
110 | archiveFileName.set("${providers.gradleProperty("plugin_name").get()}-${project.version}.jar")
111 | minimize {
112 | relocate("org.bstats", "com.github.encryptsl.metrics")
113 | }
114 | }
115 | //test {
116 | // useJUnitPlatform()
117 | //}
118 | compileJava {
119 | options.encoding = "UTF-8"
120 | options.release.set(21)
121 | options.compilerArgs.add("-Xlint:deprecation")
122 | }
123 | build {
124 | dependsOn(shadowJar)
125 | }
126 | }
127 |
128 | publishing {
129 | repositories {
130 | mavenLocal()
131 | }
132 | publications.create("libs").from(components["kotlin"])
133 | }
134 |
135 | paperweight.reobfArtifactConfiguration = ReobfArtifactConfiguration.MOJANG_PRODUCTION
136 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | #Plugin Settings
2 | plugin_name=LiteEco
3 | plugin_version=1.5.9-SNAPSHOT
4 | plugin_description=LiteEco is an economy plugin using VaultAPI
5 |
6 | #Server Dependency
7 | server_version=1.21.5-R0.1-SNAPSHOT
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/EncryptSL/LiteEco/19ccadd412c6136c476ff321bd6c7865eb49284e/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | distributionBase=GRADLE_USER_HOME
2 | distributionPath=wrapper/dists
3 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.14-bin.zip
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
--------------------------------------------------------------------------------
/settings.gradle.kts:
--------------------------------------------------------------------------------
1 | plugins {
2 | id("org.gradle.toolchains.foojay-resolver-convention") version "0.8.0"
3 | }
4 | rootProject.name = "LiteEco"
5 |
--------------------------------------------------------------------------------
/src/main/java/com/github/encryptsl/lite/eco/LiteEcoLoader.java:
--------------------------------------------------------------------------------
1 | package com.github.encryptsl.lite.eco;
2 |
3 | import io.papermc.paper.plugin.loader.PluginClasspathBuilder;
4 | import io.papermc.paper.plugin.loader.PluginLoader;
5 | import io.papermc.paper.plugin.loader.library.impl.MavenLibraryResolver;
6 | import org.eclipse.aether.artifact.DefaultArtifact;
7 | import org.eclipse.aether.graph.Dependency;
8 | import org.eclipse.aether.repository.RemoteRepository;
9 | import org.jetbrains.annotations.NotNull;
10 | import org.yaml.snakeyaml.Yaml;
11 |
12 | import java.io.IOException;
13 | import java.io.InputStream;
14 | import java.util.ArrayList;
15 | import java.util.List;
16 | import java.util.Map;
17 |
18 | @SuppressWarnings({"UnstableApiUsage", "unused"})
19 | public class LiteEcoLoader implements PluginLoader {
20 |
21 | @Override
22 | public void classloader(@NotNull PluginClasspathBuilder pluginClasspath) {
23 | MavenLibraryResolver resolver = new MavenLibraryResolver();
24 |
25 | resolveLibraries().stream()
26 | .map(DefaultArtifact::new)
27 | .forEach(artifact -> resolver.addDependency(new Dependency(artifact, null)));
28 |
29 | resolver.addRepository(new RemoteRepository.Builder("paper", "default", "https://repo.papermc.io/repository/maven-public/").build());
30 | pluginClasspath.addLibrary(resolver);
31 | }
32 |
33 | private List resolveLibraries() {
34 | try {
35 | return readLibraryListFromYaml();
36 | } catch (IOException e) {
37 | e.fillInStackTrace();
38 | }
39 | return new ArrayList<>();
40 | }
41 |
42 | private List readLibraryListFromYaml() throws IOException {
43 | Yaml yaml = new Yaml();
44 | InputStream inputStream = LiteEcoLoader.class.getClassLoader()
45 | .getResourceAsStream("paper-libraries.yml");
46 |
47 | if (inputStream == null) {
48 | System.err.println("paper-libraries.yml not found in the classpath.");
49 | }
50 |
51 | Map> data = yaml.load(inputStream);
52 |
53 | return data.get("libraries");
54 | }
55 | }
56 |
--------------------------------------------------------------------------------
/src/main/kotlin/com/github/encryptsl/lite/eco/api/ComponentPaginator.kt:
--------------------------------------------------------------------------------
1 | package com.github.encryptsl.lite.eco.api
2 |
3 | import com.github.encryptsl.lite.eco.LiteEco
4 | import com.github.encryptsl.lite.eco.api.objects.ModernText
5 | import net.kyori.adventure.text.Component
6 | import net.kyori.adventure.text.JoinConfiguration
7 | import net.kyori.adventure.text.event.ClickEvent
8 | import net.kyori.adventure.text.format.NamedTextColor
9 | import net.kyori.adventure.text.format.TextDecoration
10 | import net.kyori.adventure.text.minimessage.tag.resolver.Placeholder
11 | import net.kyori.adventure.text.minimessage.tag.resolver.TagResolver
12 | import kotlin.math.ceil
13 | import kotlin.math.max
14 | import kotlin.math.min
15 |
16 | class ComponentPaginator(
17 | private val components: List,
18 | options: PaginationOptions.() -> Unit = {}
19 | ) {
20 |
21 | private val paginationOptions = PaginationOptions().apply(options)
22 |
23 | val maxPages get() = ceil(components.size.toDouble() / paginationOptions.itemsPerPage).toInt()
24 | fun currentPage() = paginationOptions.selectedPage
25 |
26 | fun isAboveMaxPage(page: Int) = page > maxPages
27 |
28 | fun page(newPage: Int) {
29 | val targetPage = min(max(newPage, 1), maxPages)
30 | paginationOptions.selectedPage = targetPage
31 | }
32 |
33 | fun display(): List {
34 | val selectedPage = paginationOptions.selectedPage
35 | val itemsPerPage = paginationOptions.itemsPerPage
36 |
37 | if (components.isEmpty()) return emptyList()
38 |
39 | val indexStart = (selectedPage - 1) * itemsPerPage
40 | val indexEnd = min(indexStart + itemsPerPage, components.size)
41 |
42 | return components.subList(indexStart, indexEnd)
43 | }
44 |
45 | fun displayPage(page: Int): List {
46 | val targetPage = min(max(page, 1), maxPages)
47 | val indexStart = (targetPage - 1) * paginationOptions.itemsPerPage
48 | val indexEnd = min(indexStart + paginationOptions.itemsPerPage, components.size)
49 |
50 | return components.subList(indexStart, indexEnd)
51 | }
52 |
53 | /**
54 | * Generates translated and styled pagination component, inserted into custom wrapper.
55 | */
56 | fun navigationBar(commandLabel: String, param: String = ""): Component {
57 | val page = currentPage()
58 | val prevPage = page - 1
59 | val nextPage = page + 1
60 |
61 | val prevComponent = if (page > 1) {
62 | LiteEco.instance.locale.translation("messages.pagination.previous")
63 | .color(NamedTextColor.GRAY)
64 | .clickEvent(ClickEvent.runCommand("/$commandLabel $prevPage $param"))
65 | .decorate(TextDecoration.UNDERLINED)
66 | } else {
67 | LiteEco.instance.locale.translation("messages.pagination.previous")
68 | .color(NamedTextColor.DARK_GRAY)
69 | }
70 |
71 | val nextComponent = if (page < maxPages) {
72 | LiteEco.instance.locale.translation("messages.pagination.next")
73 | .color(NamedTextColor.GRAY)
74 | .clickEvent(ClickEvent.runCommand("/$commandLabel $nextPage $param"))
75 | .decorate(TextDecoration.UNDERLINED)
76 | } else {
77 | LiteEco.instance.locale.translation("messages.pagination.next")
78 | .color(NamedTextColor.DARK_GRAY)
79 | }
80 |
81 | val center = LiteEco.instance.locale.translation("messages.pagination.center", TagResolver.resolver(
82 | Placeholder.parsed("page", page.toString()),
83 | Placeholder.parsed("max_page", maxPages.toString())
84 | ))
85 |
86 | val joined = Component.join(
87 | JoinConfiguration.separator(Component.space()),
88 | listOf(prevComponent, center, nextComponent)
89 | )
90 |
91 | return injectIntoFormat(paginationOptions.navigationFormat, joined)
92 | }
93 |
94 | fun header(commandLabel: String): Component {
95 | val headerFormat = paginationOptions.headerFormat
96 | val baseNav = navigationBar(commandLabel)
97 | return injectIntoFormat(headerFormat, baseNav)
98 | }
99 |
100 | /**
101 | * Injects pagination component into provided format with placeholder
102 | */
103 | private fun injectIntoFormat(format: String, paginationComponent: Component): Component {
104 | val template = format.replace("", "")
105 | val built = ModernText.miniModernText(template)
106 | return built.replaceText {
107 | it.matchLiteral("").replacement(paginationComponent)
108 | }
109 | }
110 |
111 | inner class PaginationOptions(
112 | var selectedPage: Int = 1,
113 | var itemsPerPage: Int = 10,
114 | var navigationFormat: String = "─━━━━━━─ [ ] ─━━━━━━─",
115 | var headerFormat: String = "─━━━━━━─ [ LiteEco ] ─━━━━━━─"
116 | )
117 | }
--------------------------------------------------------------------------------
/src/main/kotlin/com/github/encryptsl/lite/eco/api/ConfigAPI.kt:
--------------------------------------------------------------------------------
1 | package com.github.encryptsl.lite.eco.api
2 |
3 | import com.github.encryptsl.lite.eco.LiteEco
4 | import com.github.encryptsl.lite.eco.api.interfaces.ConfigAPIProvider
5 | import java.io.File
6 |
7 | /**
8 | * @author EncryptSL(Patrik Kolařík)
9 | * This is part of Config API from ForgeCore by EncryptSL
10 | * This componentAPI is for Loading custom config.
11 | * Called static in mainMethod.
12 | */
13 | class ConfigAPI(private val liteEco: LiteEco) : ConfigAPIProvider {
14 | override fun create(fileName: String) : ConfigAPI {
15 | val file = File(liteEco.dataFolder, fileName)
16 | if (!file.exists()) {
17 | saveResource(fileName, false)
18 | } else {
19 | liteEco.logger.info("Resource $fileName exists [!]")
20 | }
21 | return this
22 | }
23 |
24 | override fun createConfig(configName: String): ConfigAPI {
25 | val file = File(liteEco.dataFolder, configName)
26 | if (!file.exists()) {
27 | saveResource(configName, false)
28 | liteEco.logger.info("Configuration $configName was successfully created !")
29 | }
30 | return this
31 | }
32 |
33 | private fun saveResource(configName: String, replace: Boolean = true) {
34 | try {
35 | liteEco.saveResource(configName, replace)
36 | } catch (e : Exception) {
37 | liteEco.logger.severe(e.message ?: e.localizedMessage)
38 | }
39 | }
40 | }
--------------------------------------------------------------------------------
/src/main/kotlin/com/github/encryptsl/lite/eco/api/PlayerAccount.kt:
--------------------------------------------------------------------------------
1 | package com.github.encryptsl.lite.eco.api
2 |
3 | import com.github.encryptsl.lite.eco.LiteEco
4 | import com.github.encryptsl.lite.eco.api.interfaces.AccountAPI
5 | import com.github.encryptsl.lite.eco.common.database.models.DatabaseEcoModel
6 | import org.bukkit.Bukkit
7 | import java.math.BigDecimal
8 | import java.util.*
9 |
10 | object PlayerAccount : AccountAPI {
11 |
12 | private val databaseEcoModel: DatabaseEcoModel by lazy { DatabaseEcoModel() }
13 | private val cache = mutableMapOf>()
14 |
15 | override fun cacheAccount(uuid: UUID, currency: String, value: BigDecimal) {
16 | if (!isAccountCached(uuid, currency)) {
17 | cache.computeIfAbsent(uuid) { mutableMapOf() } [currency] = value
18 | } else {
19 | cache[uuid]?.computeIfPresent(currency) { _, _ -> value }
20 | }
21 | }
22 |
23 | override fun getBalance(uuid: UUID, currency: String): BigDecimal {
24 | return cache[uuid]?.getOrDefault(currency, BigDecimal.ZERO) ?: BigDecimal.ZERO
25 | }
26 |
27 | override fun syncAccount(uuid: UUID, currency: String, value: BigDecimal) {
28 | try {
29 | databaseEcoModel.setMoney(uuid, currency, value)
30 | } catch (e : Exception) {
31 | LiteEco.instance.logger.severe(e.message ?: e.localizedMessage)
32 | }
33 | }
34 |
35 | override fun syncAccount(uuid: UUID) {
36 | try {
37 | val iterator = cache[uuid]?.iterator()
38 | while (iterator?.hasNext() == true) {
39 | val balance = iterator.next()
40 | databaseEcoModel.setMoney(uuid, balance.key, balance.value)
41 | }
42 | cache.remove(uuid)
43 | } catch (e : Exception) {
44 | LiteEco.instance.logger.severe(e.message ?: e.localizedMessage)
45 | }
46 | }
47 |
48 | override fun syncAccounts() {
49 | try {
50 | cache.entries.forEach { user -> user.value.forEach {
51 | databaseEcoModel.setMoney(user.key, it.key, it.value) }
52 | }
53 | cache.clear()
54 | } catch (e : Exception) {
55 | LiteEco.instance.logger.severe(e.message ?: e.localizedMessage)
56 | }
57 | }
58 |
59 | override fun clearFromCache(uuid: UUID) {
60 | val player = cache.keys.find { key -> key == uuid } ?: return
61 |
62 | cache.remove(player)
63 | }
64 |
65 | override fun isAccountCached(uuid: UUID, currency: String?): Boolean {
66 | return cache.containsKey(uuid) && cache[uuid]?.containsKey(currency) == true
67 | }
68 |
69 | override fun isPlayerOnline(uuid: UUID): Boolean {
70 | return Bukkit.getPlayer(uuid) != null
71 | }
72 | }
--------------------------------------------------------------------------------
/src/main/kotlin/com/github/encryptsl/lite/eco/api/UpdateNotifier.kt:
--------------------------------------------------------------------------------
1 | package com.github.encryptsl.lite.eco.api
2 |
3 | import com.github.encryptsl.lite.eco.LiteEco
4 | import com.github.encryptsl.lite.eco.api.objects.ModernText
5 | import com.google.gson.Gson
6 | import okhttp3.Call
7 | import okhttp3.OkHttpClient
8 | import okhttp3.Request
9 | import okhttp3.Response
10 |
11 |
12 | class UpdateNotifier(private val liteEco: LiteEco, private val id: String, private val pluginVersion: String) {
13 |
14 | private val okHttpClient = OkHttpClient()
15 | private val requestClient = Request.Builder()
16 |
17 | companion object {
18 | const val API_LINK = "https://api.spiget.org/v2/resources/%s/versions/latest"
19 | }
20 |
21 | fun makeUpdateCheck() {
22 | try {
23 | val request: Request = requestClient.url(String.format(API_LINK, id)).build()
24 | val call: Call = okHttpClient.newCall(request)
25 | call.execute().use { r ->
26 | if (!r.isSuccessful) { r.close() }
27 | liteEco.componentLogger.info(ModernText.miniModernText(logUpdate(r)))
28 | }
29 | } catch (e : Exception) {
30 | liteEco.componentLogger.error(e.message ?: e.localizedMessage)
31 | }
32 | }
33 |
34 | private fun logUpdate(response: Response): String {
35 | if (response.code != 200)
36 | return "Error during check update.. response code, ${response.code}"
37 |
38 | val data = Gson().fromJson(response.body?.string(), Version::class.java)
39 |
40 | return when(data.name.equals(pluginVersion, true)) {
41 | true -> "You are using current version !"
42 | false -> {
43 | "New version is here [${data.name}] you are using [$pluginVersion]"
44 | }
45 | }
46 | }
47 | data class Version(val name: String, val id: String)
48 | }
--------------------------------------------------------------------------------
/src/main/kotlin/com/github/encryptsl/lite/eco/api/economy/Currency.kt:
--------------------------------------------------------------------------------
1 | package com.github.encryptsl.lite.eco.api.economy
2 |
3 | import com.github.encryptsl.lite.eco.LiteEco
4 | import java.math.BigDecimal
5 |
6 | class Currency(private val liteEco: LiteEco) {
7 |
8 | fun defaultCurrency(): String = getCurrenciesKeys().first()
9 |
10 | fun defaultStartBalance(): BigDecimal
11 | = liteEco.config.getDouble("economy.currencies.${defaultCurrency()}.starting_balance", 30.00).toBigDecimal()
12 |
13 | fun getCurrencyPlural(currency: String): String {
14 | return liteEco.config.getString("economy.currencies.$currency.currency_plural_name").toString()
15 | }
16 |
17 | fun getCurrencySingular(currency: String): String {
18 | return liteEco.config.getString("economy.currencies.$currency.currency_singular_name").toString()
19 | }
20 |
21 | fun getCurrencyFormat(currency: String): String {
22 | return liteEco.config.getString("economy.currencies.$currency.currency_format").toString()
23 | }
24 |
25 | fun getCurrencyStartBalance(currency: String): BigDecimal {
26 | return liteEco.config.getDouble("economy.currencies.$currency.starting_balance", 30.00).toBigDecimal()
27 | }
28 |
29 | fun getCurrencyLimit(currency: String): BigDecimal {
30 | return liteEco.config.getDouble("economy.currencies.$currency.balance_limit", 0.00).toBigDecimal()
31 | }
32 |
33 | fun getCurrencyLimitEnabled(currency: String): Boolean {
34 | return liteEco.config.getBoolean("economy.currencies.$currency.balance_limit_check")
35 | }
36 |
37 | fun isCurrencyDisplayCompactEnabled(currency: String): Boolean
38 | = liteEco.config.getBoolean("economy.currencies.$currency.compact_display")
39 |
40 | fun getCurrencyNameExist(currency: String): Boolean {
41 | return getCurrenciesKeys().contains(currency)
42 | }
43 |
44 | private fun getCurrenciesNames(): List = getCurrenciesKeys().map {
45 | liteEco.config.getString("economy.currencies.$it.currency_name").toString()
46 | }
47 |
48 | fun getKeyOfCurrency(currency: String): String {
49 | return getCurrenciesKeys().singleOrNull { it.contains(currency) } ?: defaultCurrency()
50 | }
51 |
52 | fun getCurrenciesKeys(): MutableSet {
53 | return liteEco.config.getConfigurationSection("economy.currencies")?.getKeys(false) ?: mutableSetOf()
54 | }
55 |
56 | fun currencyModularNameConvert(currency: String, value: BigDecimal): String {
57 | return if (value.compareTo(BigDecimal.ONE) == 0) {
58 | getCurrencySingular(currency)
59 | } else {
60 | getCurrencyPlural(currency)
61 | }
62 | }
63 |
64 | }
--------------------------------------------------------------------------------
/src/main/kotlin/com/github/encryptsl/lite/eco/api/economy/EconomyOperations.kt:
--------------------------------------------------------------------------------
1 | package com.github.encryptsl.lite.eco.api.economy
2 |
3 | enum class EconomyOperations {
4 | WITHDRAW, DEPOSIT, SET, TRANSFER
5 | }
--------------------------------------------------------------------------------
/src/main/kotlin/com/github/encryptsl/lite/eco/api/economy/ModernLiteEcoEconomyImpl.kt:
--------------------------------------------------------------------------------
1 | package com.github.encryptsl.lite.eco.api.economy
2 |
3 | import com.github.encryptsl.lite.eco.LiteEco
4 | import com.github.encryptsl.lite.eco.api.PlayerAccount
5 | import com.github.encryptsl.lite.eco.api.interfaces.LiteEconomyAPI
6 | import com.github.encryptsl.lite.eco.api.objects.ModernText
7 | import com.github.encryptsl.lite.eco.common.database.entity.User
8 | import com.github.encryptsl.lite.eco.common.extensions.compactFormat
9 | import com.github.encryptsl.lite.eco.common.extensions.moneyFormat
10 | import net.kyori.adventure.text.minimessage.tag.resolver.Placeholder
11 | import org.bukkit.Bukkit
12 | import org.bukkit.OfflinePlayer
13 | import java.math.BigDecimal
14 | import java.util.*
15 |
16 | class ModernLiteEcoEconomyImpl : LiteEconomyAPI {
17 |
18 | override fun createAccount(player: OfflinePlayer, currency: String, startAmount: BigDecimal): Boolean {
19 | val user = getUserByUUID(player.uniqueId, currency).orElse(null)
20 | return if (user == null) {
21 | LiteEco.instance.databaseEcoModel.createPlayerAccount(player.name.toString(), player.uniqueId, currency, startAmount)
22 | true
23 | } else {
24 | LiteEco.instance.databaseEcoModel.updatePlayerName(player.uniqueId, player.name.toString(), currency)
25 | false
26 | }
27 | }
28 |
29 | override fun createAccount(uuid: UUID, username: String, currency: String, startAmount: BigDecimal): Boolean {
30 | val user = getUserByUUID(uuid, currency).orElse(null)
31 | return if (user == null) {
32 | LiteEco.instance.databaseEcoModel.createPlayerAccount(username, uuid, currency, startAmount)
33 | true
34 | } else {
35 | LiteEco.instance.databaseEcoModel.updatePlayerName(uuid, username, currency)
36 | false
37 | }
38 | }
39 |
40 | override fun getUserByUUID(uuid: UUID, currency: String): Optional {
41 | return if (PlayerAccount.isPlayerOnline(uuid) || PlayerAccount.isAccountCached(uuid, currency)) {
42 | Optional.of(User(Bukkit.getPlayer(uuid)?.name.toString(), uuid, PlayerAccount.getBalance(uuid, currency)))
43 | } else {
44 | Optional.ofNullable(LiteEco.instance.databaseEcoModel.getUserByUUID(uuid, currency))
45 | }
46 | }
47 |
48 | override fun deleteAccount(uuid: UUID, currency: String): Boolean {
49 | return try {
50 | getUserByUUID(uuid, currency).orElse(null)?.let {
51 | PlayerAccount.clearFromCache(uuid)
52 | LiteEco.instance.databaseEcoModel.deletePlayerAccount(uuid, currency)
53 | true
54 | } ?: false
55 | } catch (e: Exception) {
56 | LiteEco.instance.logger.severe("Chyba při mazání účtu: ${e.message}")
57 | false
58 | }
59 | }
60 |
61 | override fun hasAccount(uuid: UUID, currency: String): Boolean {
62 | return LiteEco.instance.databaseEcoModel.getExistPlayerAccount(uuid, currency)
63 | }
64 |
65 | override fun has(uuid: UUID, currency: String, amount: BigDecimal): Boolean {
66 | return amount <= getBalance(uuid, currency)
67 | }
68 |
69 | override fun depositMoney(uuid: UUID, currency: String, amount: BigDecimal) {
70 | if (PlayerAccount.isPlayerOnline(uuid) && PlayerAccount.isAccountCached(uuid, currency)) {
71 | cacheAccount(uuid, currency, getBalance(uuid, currency).plus(amount))
72 | } else {
73 | LiteEco.instance.databaseEcoModel.depositMoney(uuid, currency, amount)
74 | }
75 | }
76 |
77 | override fun withDrawMoney(uuid: UUID, currency: String, amount: BigDecimal) {
78 | if (PlayerAccount.isPlayerOnline(uuid) && PlayerAccount.isAccountCached(uuid, currency)) {
79 | cacheAccount(uuid, currency, getBalance(uuid, currency).minus(amount))
80 | } else {
81 | LiteEco.instance.databaseEcoModel.withdrawMoney(uuid, currency, amount)
82 | }
83 | }
84 |
85 | override fun setMoney(uuid: UUID, currency: String, amount: BigDecimal) {
86 | if (PlayerAccount.isPlayerOnline(uuid)) {
87 | cacheAccount(uuid, currency, amount)
88 | } else {
89 | LiteEco.instance.databaseEcoModel.setMoney(uuid, currency, amount)
90 | }
91 | }
92 |
93 | override fun getBalance(uuid: UUID, currency: String): BigDecimal {
94 | return getUserByUUID(uuid, currency).map { it.money }.orElse(BigDecimal.ZERO)
95 | }
96 |
97 | override fun getCheckBalanceLimit(amount: BigDecimal, currency: String): Boolean {
98 | return (amount > LiteEco.instance.currencyImpl.getCurrencyLimit(currency)) && LiteEco.instance.currencyImpl.getCurrencyLimitEnabled(currency)
99 | }
100 |
101 | override fun getCheckBalanceLimit(uuid: UUID, currentBalance: BigDecimal, currency: String, amount: BigDecimal): Boolean {
102 | return ((currentBalance.plus(amount) > LiteEco.instance.currencyImpl.getCurrencyLimit(currency)) && LiteEco.instance.currencyImpl.getCurrencyLimitEnabled(currency))
103 | }
104 |
105 | override fun transfer(fromUUID: UUID, target: UUID, currency: String, amount: BigDecimal) {
106 | withDrawMoney(fromUUID, currency, amount)
107 | depositMoney(target, currency, amount)
108 | }
109 |
110 | override fun cacheAccount(uuid: UUID, currency: String, amount: BigDecimal) {
111 | PlayerAccount.cacheAccount(uuid, currency, amount)
112 | }
113 |
114 | override fun syncAccount(uuid: UUID, currency: String) {
115 | if (getCheckBalanceLimit(getBalance(uuid, currency), currency))
116 | return PlayerAccount.syncAccount(uuid, currency, LiteEco.instance.currencyImpl.getCurrencyLimit(currency))
117 |
118 | PlayerAccount.syncAccount(uuid)
119 | }
120 |
121 | override fun syncAccounts() {
122 | PlayerAccount.syncAccounts()
123 | }
124 |
125 | override fun getTopBalance(currency: String): Map {
126 | val database = LiteEco.instance.databaseEcoModel.getTopBalance(currency)
127 | .mapValues { e -> if (PlayerAccount.isAccountCached(e.value.uuid, currency)) PlayerAccount.getBalance(e.value.uuid, currency) else e.value.money}
128 | .filterKeys { e -> !e.equals("NULL", true) }.toList()
129 |
130 | return database.sortedByDescending { (_, e) -> e }.toMap()
131 | }
132 |
133 |
134 | override fun getUUIDNameMap(currency: String): MutableMap {
135 | return LiteEco.instance.databaseEcoModel.getUUIDNameMap(currency)
136 | }
137 |
138 | override fun compacted(amount: BigDecimal): String {
139 | return amount.compactFormat(
140 | LiteEco.instance.config.getString("formatting.currency_pattern").toString(),
141 | LiteEco.instance.config.getString("formatting.compacted_pattern").toString(),
142 | LiteEco.instance.config.getString("formatting.currency_locale").toString()
143 | )
144 | }
145 |
146 | override fun formatted(amount: BigDecimal): String {
147 | return amount.moneyFormat(
148 | LiteEco.instance.config.getString("formatting.currency_pattern").toString(),
149 | LiteEco.instance.config.getString("formatting.currency_locale").toString()
150 | )
151 | }
152 |
153 | override fun fullFormatting(amount: BigDecimal, currency: String): String {
154 |
155 | val value = when(LiteEco.instance.currencyImpl.isCurrencyDisplayCompactEnabled(currency)) {
156 | true -> compacted(amount)
157 | false -> formatted(amount)
158 | }
159 | return LiteEco.instance.locale.plainTextTranslation(
160 | ModernText.miniModernText(
161 | LiteEco.instance.currencyImpl.getCurrencyFormat(currency), Placeholder.parsed("money", value))
162 | )
163 | }
164 |
165 | }
--------------------------------------------------------------------------------
/src/main/kotlin/com/github/encryptsl/lite/eco/api/economy/SuspendLiteEcoEconomyWrapper.kt:
--------------------------------------------------------------------------------
1 | package com.github.encryptsl.lite.eco.api.economy
2 |
3 | import com.github.encryptsl.lite.eco.LiteEco
4 | import com.github.encryptsl.lite.eco.api.PlayerAccount
5 | import com.github.encryptsl.lite.eco.common.database.entity.User
6 | import com.github.encryptsl.lite.eco.common.extensions.runBlockingIO
7 | import org.bukkit.OfflinePlayer
8 | import java.math.BigDecimal
9 | import java.util.*
10 |
11 | class SuspendLiteEcoEconomyWrapper {
12 |
13 | private val economyImpl: ModernLiteEcoEconomyImpl = ModernLiteEcoEconomyImpl()
14 |
15 | suspend fun getUserByUUID(uuid: UUID, currency: String = "dollars"): Optional =
16 | runBlockingIO { economyImpl.getUserByUUID(uuid, currency) }
17 |
18 | suspend fun createAccount(player: OfflinePlayer, currency: String = "dollars", startAmount: BigDecimal): Boolean =
19 | runBlockingIO {
20 | val userOpt = economyImpl.getUserByUUID(player.uniqueId, currency)
21 | if (!userOpt.isPresent) {
22 | LiteEco.instance.databaseEcoModel.createPlayerAccount(
23 | player.name.toString(),
24 | player.uniqueId,
25 | currency,
26 | startAmount
27 | )
28 | true
29 | } else {
30 | LiteEco.instance.databaseEcoModel.updatePlayerName(
31 | player.uniqueId,
32 | player.name.toString(),
33 | currency
34 | )
35 | false
36 | }
37 | }
38 |
39 | suspend fun createAccount(uuid: UUID, username: String, currency: String = "dollars", startAmount: BigDecimal): Boolean =
40 | runBlockingIO {
41 | val userOpt = economyImpl.getUserByUUID(uuid, currency)
42 | if (!userOpt.isPresent) {
43 | LiteEco.instance.databaseEcoModel.createPlayerAccount(
44 | username,
45 | uuid,
46 | currency,
47 | startAmount
48 | )
49 | true
50 | } else {
51 | LiteEco.instance.databaseEcoModel.updatePlayerName(
52 | uuid,
53 | username,
54 | currency
55 | )
56 | false
57 | }
58 | }
59 |
60 | suspend fun deleteAccount(uuid: UUID, currency: String = "dollars"): Boolean = runBlockingIO {
61 | val user = economyImpl.getUserByUUID(uuid, currency).orElse(null)
62 | if (user == null) {
63 | false
64 | } else {
65 | PlayerAccount.clearFromCache(uuid)
66 | LiteEco.instance.databaseEcoModel.deletePlayerAccount(uuid, currency)
67 | true
68 | }
69 | }
70 |
71 | suspend fun purgeAccounts(currency: String) = runBlockingIO {
72 | LiteEco.instance.databaseEcoModel.purgeAccounts(currency)
73 | }
74 |
75 | suspend fun purgeInvalidAccounts(currency: String) = runBlockingIO {
76 | LiteEco.instance.databaseEcoModel.purgeInvalidAccounts(currency)
77 | }
78 |
79 | suspend fun purgeDefaultAccounts(currency: String, defaultValue: BigDecimal) = runBlockingIO {
80 | LiteEco.instance.databaseEcoModel.purgeDefaultAccounts(defaultValue, currency)
81 | }
82 |
83 | suspend fun withdraw(uuid: UUID, currency: String = "dollars", amount: BigDecimal) = runBlockingIO {
84 | economyImpl.withDrawMoney(uuid, currency, amount)
85 | }
86 |
87 | suspend fun deposit(uuid: UUID, currency: String = "dollars", amount: BigDecimal) = runBlockingIO {
88 | economyImpl.depositMoney(uuid, currency, amount)
89 | }
90 |
91 | suspend fun set(uuid: UUID, currency: String = "dollars", amount: BigDecimal) = runBlockingIO {
92 | economyImpl.setMoney(uuid, currency, amount)
93 | }
94 |
95 | suspend fun syncAccount(uuid: UUID, currency: String = "dollars") {
96 | economyImpl.syncAccount(uuid, currency)
97 | }
98 |
99 | suspend fun transfer(sender: UUID, target: UUID, currency: String = "dollars", amount: BigDecimal) = runBlockingIO {
100 | economyImpl.transfer(sender, target, currency, amount)
101 | }
102 |
103 | suspend fun hasAccount(uuid: UUID, currency: String = "dollars"): Boolean = runBlockingIO {
104 | economyImpl.hasAccount(uuid, currency)
105 | }
106 |
107 | suspend fun getBalance(uuid: UUID, currency: String = "dollars"): BigDecimal = runBlockingIO {
108 | economyImpl.getBalance(uuid, currency)
109 | }
110 | }
--------------------------------------------------------------------------------
/src/main/kotlin/com/github/encryptsl/lite/eco/api/enums/CheckLevel.kt:
--------------------------------------------------------------------------------
1 | package com.github.encryptsl.lite.eco.api.enums
2 |
3 | enum class CheckLevel {
4 | FULL,
5 | ONLY_NEGATIVE,
6 | }
--------------------------------------------------------------------------------
/src/main/kotlin/com/github/encryptsl/lite/eco/api/enums/ExportKeys.kt:
--------------------------------------------------------------------------------
1 | package com.github.encryptsl.lite.eco.api.enums
2 |
3 | enum class ExportKeys {
4 | CSV, SQL, LEGACY_TABLE, SQL_LITE_FILE
5 | }
--------------------------------------------------------------------------------
/src/main/kotlin/com/github/encryptsl/lite/eco/api/enums/PurgeKey.kt:
--------------------------------------------------------------------------------
1 | package com.github.encryptsl.lite.eco.api.enums
2 |
3 | enum class PurgeKey {
4 | ACCOUNTS,
5 | NULL_ACCOUNTS,
6 | DEFAULT_ACCOUNTS,
7 | MONO_LOG,
8 | }
--------------------------------------------------------------------------------
/src/main/kotlin/com/github/encryptsl/lite/eco/api/events/PlayerEconomyPayEvent.kt:
--------------------------------------------------------------------------------
1 | package com.github.encryptsl.lite.eco.api.events
2 |
3 | import org.bukkit.OfflinePlayer
4 | import org.bukkit.entity.Player
5 | import org.bukkit.event.Cancellable
6 | import org.bukkit.event.Event
7 | import org.bukkit.event.HandlerList
8 | import java.math.BigDecimal
9 |
10 | @Suppress("UNUSED")
11 | class PlayerEconomyPayEvent(val sender: Player, val target: OfflinePlayer, val currency: String, val money: BigDecimal) : Event(), Cancellable {
12 |
13 | private var isCancelled: Boolean = false
14 |
15 | override fun getHandlers(): HandlerList {
16 | return HANDLERS
17 | }
18 |
19 | override fun isCancelled(): Boolean {
20 | return isCancelled
21 | }
22 |
23 | override fun setCancelled(cancel: Boolean) {
24 | this.isCancelled = cancel
25 | }
26 |
27 | companion object {
28 | private val HANDLERS = HandlerList()
29 | @JvmStatic
30 | fun getHandlerList(): HandlerList {
31 | return HANDLERS
32 | }
33 | }
34 | }
--------------------------------------------------------------------------------
/src/main/kotlin/com/github/encryptsl/lite/eco/api/events/admin/EconomyGlobalDepositEvent.kt:
--------------------------------------------------------------------------------
1 | package com.github.encryptsl.lite.eco.api.events.admin
2 |
3 | import org.bukkit.OfflinePlayer
4 | import org.bukkit.command.CommandSender
5 | import org.bukkit.event.Cancellable
6 | import org.bukkit.event.Event
7 | import org.bukkit.event.HandlerList
8 | import java.math.BigDecimal
9 |
10 | @Suppress("UNUSED")
11 | class EconomyGlobalDepositEvent(
12 | val commandSender: CommandSender,
13 | val currency: String,
14 | val money: BigDecimal,
15 | val players: MutableCollection
16 | ): Event(), Cancellable {
17 |
18 | private var isCancelled: Boolean = false
19 |
20 | override fun getHandlers(): HandlerList {
21 | return HANDLERS
22 | }
23 |
24 | override fun isCancelled(): Boolean {
25 | return isCancelled
26 | }
27 |
28 | override fun setCancelled(cancel: Boolean) {
29 | this.isCancelled = cancel
30 | }
31 |
32 | companion object {
33 | private val HANDLERS = HandlerList()
34 | @JvmStatic
35 | fun getHandlerList(): HandlerList {
36 | return HANDLERS
37 | }
38 | }
39 | }
--------------------------------------------------------------------------------
/src/main/kotlin/com/github/encryptsl/lite/eco/api/events/admin/EconomyGlobalSetEvent.kt:
--------------------------------------------------------------------------------
1 | package com.github.encryptsl.lite.eco.api.events.admin
2 |
3 | import org.bukkit.OfflinePlayer
4 | import org.bukkit.command.CommandSender
5 | import org.bukkit.event.Cancellable
6 | import org.bukkit.event.Event
7 | import org.bukkit.event.HandlerList
8 | import java.math.BigDecimal
9 |
10 | @Suppress("UNUSED")
11 | class EconomyGlobalSetEvent(
12 | val commandSender: CommandSender,
13 | val currency: String,
14 | val money: BigDecimal,
15 | val players: MutableCollection
16 | ) : Event(), Cancellable {
17 |
18 | private var isCancelled: Boolean = false
19 |
20 | override fun getHandlers(): HandlerList {
21 | return HANDLERS
22 | }
23 |
24 | override fun isCancelled(): Boolean {
25 | return isCancelled
26 | }
27 |
28 | override fun setCancelled(cancel: Boolean) {
29 | this.isCancelled = cancel
30 | }
31 |
32 | companion object {
33 | private val HANDLERS = HandlerList()
34 | @JvmStatic
35 | fun getHandlerList(): HandlerList {
36 | return HANDLERS
37 | }
38 | }
39 | }
--------------------------------------------------------------------------------
/src/main/kotlin/com/github/encryptsl/lite/eco/api/events/admin/EconomyGlobalWithdrawEvent.kt:
--------------------------------------------------------------------------------
1 | package com.github.encryptsl.lite.eco.api.events.admin
2 |
3 | import org.bukkit.OfflinePlayer
4 | import org.bukkit.command.CommandSender
5 | import org.bukkit.event.Cancellable
6 | import org.bukkit.event.Event
7 | import org.bukkit.event.HandlerList
8 | import java.math.BigDecimal
9 |
10 | @Suppress("UNUSED")
11 | class EconomyGlobalWithdrawEvent(
12 | val commandSender: CommandSender,
13 | val currency: String,
14 | val money: BigDecimal,
15 | val players: MutableCollection
16 | ): Event(), Cancellable {
17 |
18 | private var isCancelled: Boolean = false
19 |
20 | override fun getHandlers(): HandlerList {
21 | return HANDLERS
22 | }
23 |
24 | override fun isCancelled(): Boolean {
25 | return isCancelled
26 | }
27 |
28 | override fun setCancelled(cancel: Boolean) {
29 | this.isCancelled = cancel
30 | }
31 |
32 | companion object {
33 | private val HANDLERS = HandlerList()
34 | @JvmStatic
35 | fun getHandlerList(): HandlerList {
36 | return HANDLERS
37 | }
38 | }
39 | }
--------------------------------------------------------------------------------
/src/main/kotlin/com/github/encryptsl/lite/eco/api/events/admin/EconomyMoneyDepositEvent.kt:
--------------------------------------------------------------------------------
1 | package com.github.encryptsl.lite.eco.api.events.admin
2 |
3 | import org.bukkit.OfflinePlayer
4 | import org.bukkit.command.CommandSender
5 | import org.bukkit.event.Cancellable
6 | import org.bukkit.event.Event
7 | import org.bukkit.event.HandlerList
8 | import java.math.BigDecimal
9 |
10 | @Suppress("UNUSED")
11 | class EconomyMoneyDepositEvent(val commandSender: CommandSender, val offlinePlayer: OfflinePlayer, val currency: String, val money: BigDecimal, val silent: Boolean): Event(), Cancellable {
12 |
13 | private var isCancelled: Boolean = false
14 |
15 | override fun getHandlers(): HandlerList {
16 | return HANDLERS
17 | }
18 |
19 | override fun isCancelled(): Boolean {
20 | return isCancelled
21 | }
22 |
23 | override fun setCancelled(cancel: Boolean) {
24 | this.isCancelled = cancel
25 | }
26 |
27 | companion object {
28 | private val HANDLERS = HandlerList()
29 | @JvmStatic
30 | fun getHandlerList(): HandlerList {
31 | return HANDLERS
32 | }
33 | }
34 | }
--------------------------------------------------------------------------------
/src/main/kotlin/com/github/encryptsl/lite/eco/api/events/admin/EconomyMoneySetEvent.kt:
--------------------------------------------------------------------------------
1 | package com.github.encryptsl.lite.eco.api.events.admin
2 |
3 | import org.bukkit.OfflinePlayer
4 | import org.bukkit.command.CommandSender
5 | import org.bukkit.event.Cancellable
6 | import org.bukkit.event.Event
7 | import org.bukkit.event.HandlerList
8 | import java.math.BigDecimal
9 |
10 | @Suppress("UNUSED")
11 | class EconomyMoneySetEvent(val commandSender: CommandSender, val offlinePlayer: OfflinePlayer, val currency: String, val money: BigDecimal): Event(), Cancellable {
12 |
13 | private var isCancelled: Boolean = false
14 |
15 | override fun getHandlers(): HandlerList {
16 | return HANDLERS
17 | }
18 |
19 | override fun isCancelled(): Boolean {
20 | return isCancelled
21 | }
22 |
23 | override fun setCancelled(cancel: Boolean) {
24 | this.isCancelled = cancel
25 | }
26 |
27 | companion object {
28 | private val HANDLERS = HandlerList()
29 | @JvmStatic
30 | fun getHandlerList(): HandlerList {
31 | return HANDLERS
32 | }
33 | }
34 | }
--------------------------------------------------------------------------------
/src/main/kotlin/com/github/encryptsl/lite/eco/api/events/admin/EconomyMoneyWithdrawEvent.kt:
--------------------------------------------------------------------------------
1 | package com.github.encryptsl.lite.eco.api.events.admin
2 | import org.bukkit.OfflinePlayer
3 | import org.bukkit.command.CommandSender
4 | import org.bukkit.event.Cancellable
5 | import org.bukkit.event.Event
6 | import org.bukkit.event.HandlerList
7 | import java.math.BigDecimal
8 |
9 | @Suppress("UNUSED")
10 | class EconomyMoneyWithdrawEvent(val commandSender: CommandSender, val offlinePlayer: OfflinePlayer, val currency: String, val money: BigDecimal, val silent: Boolean): Event(), Cancellable {
11 |
12 | private var isCancelled: Boolean = false
13 |
14 | override fun getHandlers(): HandlerList {
15 | return HANDLERS
16 | }
17 |
18 | override fun isCancelled(): Boolean {
19 | return isCancelled
20 | }
21 |
22 | override fun setCancelled(cancel: Boolean) {
23 | this.isCancelled = cancel
24 | }
25 |
26 | companion object {
27 | private val HANDLERS = HandlerList()
28 | @JvmStatic
29 | fun getHandlerList(): HandlerList {
30 | return HANDLERS
31 | }
32 | }
33 | }
--------------------------------------------------------------------------------
/src/main/kotlin/com/github/encryptsl/lite/eco/api/interfaces/AccountAPI.kt:
--------------------------------------------------------------------------------
1 | package com.github.encryptsl.lite.eco.api.interfaces
2 |
3 | import java.math.BigDecimal
4 | import java.util.*
5 |
6 | interface AccountAPI {
7 | fun cacheAccount(uuid: UUID, currency: String, value: BigDecimal)
8 | fun syncAccount(uuid: UUID, currency: String, value: BigDecimal)
9 | fun syncAccount(uuid: UUID)
10 | fun syncAccounts()
11 | fun clearFromCache(uuid: UUID)
12 | fun getBalance(uuid: UUID, currency: String): BigDecimal
13 | fun isAccountCached(uuid: UUID, currency: String?): Boolean
14 | fun isPlayerOnline(uuid: UUID): Boolean
15 | }
--------------------------------------------------------------------------------
/src/main/kotlin/com/github/encryptsl/lite/eco/api/interfaces/ConfigAPIProvider.kt:
--------------------------------------------------------------------------------
1 | package com.github.encryptsl.lite.eco.api.interfaces
2 |
3 | interface ConfigAPIProvider {
4 | fun create(fileName: String): com.github.encryptsl.lite.eco.api.ConfigAPI
5 |
6 | /**
7 | * Create config.yml
8 | * @param configName - Config name example config.yml
9 | * @return ConfigLoaderAPI
10 | */
11 | fun createConfig(configName: String): com.github.encryptsl.lite.eco.api.ConfigAPI
12 | }
--------------------------------------------------------------------------------
/src/main/kotlin/com/github/encryptsl/lite/eco/api/interfaces/DatabaseConnectorProvider.kt:
--------------------------------------------------------------------------------
1 | package com.github.encryptsl.lite.eco.api.interfaces
2 |
3 | interface DatabaseConnectorProvider {
4 | fun load()
5 | fun initConnect(driver: String, jdbcHost: String, user: String, pass: String)
6 | }
--------------------------------------------------------------------------------
/src/main/kotlin/com/github/encryptsl/lite/eco/api/interfaces/EconomyImporter.kt:
--------------------------------------------------------------------------------
1 | package com.github.encryptsl.lite.eco.api.interfaces
2 |
3 | import com.github.encryptsl.lite.eco.LiteEco
4 | import com.github.encryptsl.lite.eco.common.manager.importer.EconomyImportResults
5 | import org.bukkit.OfflinePlayer
6 |
7 | interface EconomyImporter {
8 | val name: String
9 | fun import(currency: String, liteEco: LiteEco, offlinePlayers: Array): EconomyImportResults
10 | }
--------------------------------------------------------------------------------
/src/main/kotlin/com/github/encryptsl/lite/eco/api/interfaces/LiteEconomyAPI.kt:
--------------------------------------------------------------------------------
1 | package com.github.encryptsl.lite.eco.api.interfaces
2 |
3 | import com.github.encryptsl.lite.eco.common.database.entity.User
4 | import org.bukkit.OfflinePlayer
5 | import java.math.BigDecimal
6 | import java.util.*
7 |
8 | interface LiteEconomyAPI {
9 | /**
10 | * Creates a player account in the database.
11 | *
12 | * @param player The offline player instance.
13 | * @param currency The name of the currency. Defaults to "dollars".
14 | * @param startAmount The initial amount to be added to the account.
15 | * @return `true` if the account was successfully created, otherwise `false`.
16 | */
17 | fun createAccount(player: OfflinePlayer, currency: String = "dollars", startAmount: BigDecimal): Boolean
18 |
19 | /**
20 | * Creates a player account in the database.
21 | *
22 | * @param uuid The player's UUID.
23 | * @param username The player's username.
24 | * @param currency The name of the currency. Defaults to "dollars".
25 | * @param startAmount The initial amount to be added to the account.
26 | * @return `true` if the account was successfully created, otherwise `false`.
27 | */
28 | fun createAccount(uuid: UUID, username: String, currency: String = "dollars", startAmount: BigDecimal): Boolean
29 |
30 | /**
31 | * Caches a player's account during login.
32 | *
33 | * @param uuid The player's UUID.
34 | * @param currency The name of the currency. Defaults to "dollars".
35 | * @param amount The account balance from the database.
36 | */
37 | fun cacheAccount(uuid: UUID, currency: String = "dollars", amount: BigDecimal)
38 |
39 | /**
40 | * Deletes a player's account from the database.
41 | *
42 | * @param uuid The player's UUID.
43 | * @param currency The name of the currency. Defaults to "dollars".
44 | * @return `true` if the account was successfully deleted, otherwise `false`.
45 | */
46 | fun deleteAccount(uuid: UUID, currency: String = "dollars" ): Boolean
47 |
48 | /**
49 | * Checks if a player has an account in the database.
50 | *
51 | * @param uuid The player's UUID.
52 | * @param currency The name of the currency. Defaults to "dollars".
53 | * @return `true` if the account exists, otherwise `false`.
54 | */
55 | fun hasAccount(uuid: UUID, currency: String = "dollars" ): Boolean
56 |
57 | /**
58 | * Checks if a player has at least a certain amount of money.
59 | *
60 | * @param uuid The player's UUID.
61 | * @param currency The name of the currency. Defaults to "dollars".
62 | * @param amount The amount to check against.
63 | * @return `true` if the player has at least the specified amount, otherwise `false`.
64 | */
65 | fun has(uuid: UUID, currency: String = "dollars", amount: BigDecimal): Boolean
66 |
67 | /**
68 | * Retrieves a player's account by UUID.
69 | *
70 | * @param uuid The player's UUID.
71 | * @param currency The name of the currency. Defaults to "dollars".
72 | * @return An [Optional] containing the [User], if found.
73 | */
74 | fun getUserByUUID(uuid: UUID, currency: String = "dollars" ): Optional
75 |
76 | /**
77 | * Retrieves the balance of a player's account.
78 | *
79 | * @param uuid The player's UUID.
80 | * @param currency The name of the currency. Defaults to "dollars".
81 | * @return The account balance.
82 | */
83 | fun getBalance(uuid: UUID, currency: String = "dollars" ): BigDecimal
84 |
85 | /**
86 | * Checks whether the specified amount exceeds the allowed balance limit.
87 | *
88 | * @param amount The amount to check.
89 | * @param currency The name of the currency. Defaults to "dollars".
90 | * @return `true` if the amount is within the limit, otherwise `false`.
91 | */
92 | fun getCheckBalanceLimit(amount: BigDecimal, currency: String = "dollars" ): Boolean
93 |
94 | /**
95 | * Checks whether the specified new balance exceeds the allowed balance limit for a player.
96 | *
97 | * @param uuid The player's UUID.
98 | * @param currentBalance The player's current balance.
99 | * @param currency The name of the currency. Defaults to "dollars".
100 | * @param amount The new amount to add.
101 | * @return `true` if the resulting balance is within the limit, otherwise `false`.
102 | */
103 | fun getCheckBalanceLimit(uuid: UUID, currentBalance: BigDecimal, currency: String = "dollars", amount: BigDecimal): Boolean
104 |
105 | /**
106 | * Deposits money into a player's account.
107 | *
108 | * @param uuid The player's UUID.
109 | * @param currency The name of the currency. Defaults to "dollars".
110 | * @param amount The amount to deposit.
111 | */
112 | fun depositMoney(uuid: UUID, currency: String = "dollars", amount: BigDecimal)
113 |
114 | /**
115 | * Withdraws money from a player's account.
116 | *
117 | * @param uuid The player's UUID.
118 | * @param currency The name of the currency. Defaults to "dollars".
119 | * @param amount The amount to withdraw.
120 | */
121 | fun withDrawMoney(uuid: UUID, currency: String = "dollars", amount: BigDecimal)
122 |
123 | /**
124 | * Transfers money from one player to another.
125 | *
126 | * @param fromUUID The UUID of the sender.
127 | * @param target The UUID of the receiver.
128 | * @param currency The name of the currency. Defaults to "dollars".
129 | * @param amount The amount to transfer.
130 | */
131 | fun transfer(fromUUID: UUID, target: UUID, currency: String = "dollars", amount: BigDecimal)
132 |
133 | /**
134 | * Sets a fixed amount of money for a player's account.
135 | *
136 | * @param uuid The player's UUID.
137 | * @param currency The name of the currency. Defaults to "dollars".
138 | * @param amount The amount to set.
139 | */
140 | fun setMoney(uuid: UUID, currency: String = "dollars", amount: BigDecimal)
141 |
142 | /**
143 | * Synchronizes a player's cached account with the database.
144 | *
145 | * @param uuid The player's UUID.
146 | * @param currency The name of the currency. Defaults to "dollars".
147 | */
148 | fun syncAccount(uuid: UUID, currency: String = "dollars")
149 |
150 | /**
151 | * Synchronizes all cached accounts with the database.
152 | */
153 | fun syncAccounts()
154 |
155 | /**
156 | * Retrieves the top player accounts by balance.
157 | *
158 | * @param currency The name of the currency. Defaults to "dollars".
159 | * @return A map of usernames to their balances.
160 | */
161 | fun getTopBalance(currency: String = "dollars" ): Map
162 |
163 | /**
164 | * Retrieves a map of UUIDs to player names.
165 | *
166 | * @param currency The name of the currency. Defaults to "dollars".
167 | * @return A mutable map of UUIDs to player names.
168 | */
169 | fun getUUIDNameMap(currency: String = "dollars" ): MutableMap
170 |
171 | /**
172 | * Formats a value to a compact money representation.
173 | *
174 | * @param amount The amount to format.
175 | * @return A compacted string representation.
176 | */
177 | fun compacted(amount: BigDecimal): String
178 |
179 | /**
180 | * Formats a value to a human-readable money representation.
181 | *
182 | * @param amount The amount to format.
183 | * @return A formatted string representation.
184 | */
185 | fun formatted(amount: BigDecimal): String
186 |
187 | /**
188 | * Formats a value to a full string representation including the currency.
189 | *
190 | * @param amount The amount to format.
191 | * @param currency The name of the currency. Defaults to "dollars".
192 | * @return A fully formatted currency string.
193 | */
194 | fun fullFormatting(amount: BigDecimal, currency: String = "dollars" ): String
195 | }
--------------------------------------------------------------------------------
/src/main/kotlin/com/github/encryptsl/lite/eco/api/interfaces/PlayerSQL.kt:
--------------------------------------------------------------------------------
1 | package com.github.encryptsl.lite.eco.api.interfaces
2 |
3 | import com.github.encryptsl.lite.eco.common.database.entity.User
4 | import java.math.BigDecimal
5 | import java.util.*
6 |
7 | interface PlayerSQL {
8 | fun createPlayerAccount(username: String, uuid: UUID, currency: String, money: BigDecimal)
9 | fun updatePlayerName(uuid: UUID, username: String, currency: String)
10 | fun getUserByUUID(uuid: UUID, currency: String): User?
11 | fun getBalance(uuid: UUID, currency: String): BigDecimal
12 | fun deletePlayerAccount(uuid: UUID, currency: String)
13 | fun getExistPlayerAccount(uuid: UUID, currency: String): Boolean
14 | fun getTopBalance(currency: String): MutableMap
15 | fun getUUIDNameMap(currency: String): MutableMap
16 | fun getPlayersIds(currency: String): MutableCollection
17 | fun depositMoney(uuid: UUID, currency: String, money: BigDecimal)
18 | fun withdrawMoney(uuid: UUID, currency: String, money: BigDecimal)
19 | fun setMoney(uuid: UUID, currency: String, money: BigDecimal)
20 | fun purgeAccounts(currency: String)
21 | fun purgeDefaultAccounts(defaultMoney: BigDecimal, currency: String)
22 | fun purgeInvalidAccounts(currency: String)
23 | }
--------------------------------------------------------------------------------
/src/main/kotlin/com/github/encryptsl/lite/eco/api/interfaces/TransactionLogger.kt:
--------------------------------------------------------------------------------
1 | package com.github.encryptsl.lite.eco.api.interfaces
2 |
3 | import com.github.encryptsl.lite.eco.api.economy.EconomyOperations
4 | import com.github.encryptsl.lite.eco.common.database.entity.EconomyLog
5 | import java.math.BigDecimal
6 |
7 | interface TransactionLogger {
8 | suspend fun logging(economyOperations: EconomyOperations, sender:String, target: String, currency: String, previousBalance: BigDecimal, newBalance: BigDecimal)
9 | fun clearLogs()
10 | suspend fun getLog(): List
11 | }
--------------------------------------------------------------------------------
/src/main/kotlin/com/github/encryptsl/lite/eco/api/migrator/CSVFileExporter.kt:
--------------------------------------------------------------------------------
1 | package com.github.encryptsl.lite.eco.api.migrator
2 |
3 | import com.github.encryptsl.lite.eco.api.migrator.entity.PlayerBalances
4 | import kotlinx.coroutines.Dispatchers
5 | import kotlinx.coroutines.withContext
6 | import org.apache.commons.csv.CSVFormat
7 | import org.apache.commons.csv.CSVPrinter
8 | import org.bukkit.plugin.Plugin
9 | import java.io.BufferedWriter
10 | import java.io.File
11 | import java.io.IOException
12 | import java.nio.charset.Charset
13 | import java.nio.charset.StandardCharsets
14 | import java.nio.file.Files
15 |
16 | class CSVFileExporter(private val plugin: Plugin, fileName: String, currency: String = "dollars") : Export() {
17 |
18 | private val file: File = File("${plugin.dataFolder}/migration/${fileName}_${currency}_${timestamp}.csv")
19 |
20 |
21 | suspend fun exportToCSVFile(balances: List) : Boolean {
22 |
23 | return withContext(Dispatchers.IO) {
24 | try {
25 | val writer: BufferedWriter = Files.newBufferedWriter(file.toPath(), StandardCharsets.UTF_8)
26 | file.parentFile.mkdirs()
27 | val format = CSVFormat.DEFAULT.builder().setHeader("id", "username", "uuid", "money").get()
28 | format.print(file, Charset.forName("UTF-8")).use { printer ->
29 | balances.forEach { it ->
30 | printer.printRecord(it.id, it.username, "0x${it.uuid.toString().replace("-", "")}", it.money)
31 | }
32 | }
33 | val csvPrinter = CSVPrinter(writer, format)
34 | csvPrinter.flush()
35 | csvPrinter.close()
36 | true
37 | } catch (e: IOException) {
38 | plugin.logger.severe("Error while migrating to CSV file: ${e.message}")
39 | e.printStackTrace()
40 | false
41 | }
42 | }
43 | }
44 |
45 | @Deprecated("Replaced with better alternative exporting")
46 | suspend fun exportToCsvFile(balances: List): Boolean {
47 | return exportToCSVFile(balances)
48 | }
49 |
50 | }
--------------------------------------------------------------------------------
/src/main/kotlin/com/github/encryptsl/lite/eco/api/migrator/Export.kt:
--------------------------------------------------------------------------------
1 | package com.github.encryptsl.lite.eco.api.migrator
2 |
3 | abstract class Export {
4 | val timestamp = System.currentTimeMillis()
5 | }
--------------------------------------------------------------------------------
/src/main/kotlin/com/github/encryptsl/lite/eco/api/migrator/SQLFileExporter.kt:
--------------------------------------------------------------------------------
1 | package com.github.encryptsl.lite.eco.api.migrator
2 |
3 | import com.github.encryptsl.lite.eco.api.migrator.entity.PlayerBalances
4 | import kotlinx.coroutines.Dispatchers
5 | import kotlinx.coroutines.withContext
6 | import org.bukkit.plugin.Plugin
7 | import java.io.BufferedWriter
8 | import java.io.File
9 | import java.io.FileWriter
10 | import java.io.IOException
11 |
12 | class SQLFileExporter(private val plugin: Plugin, private val fileName: String, private val currency: String) : Export() {
13 |
14 | suspend fun exportToSQLFile(balances: List) : Boolean {
15 | val file = File("${plugin.dataFolder}/migration/", "${fileName}_${currency}_${timestamp}.sql")
16 |
17 | return withContext(Dispatchers.IO) {
18 | try {
19 | file.parentFile.mkdirs()
20 |
21 | val insertStatement = balances.joinToString {
22 | "\n(${it.id}, '${it.username}', 0x${it.uuid.toString().replace("-", "")}, ${it.money})"
23 | }
24 |
25 | BufferedWriter(FileWriter(file)).use { writer ->
26 | writer.write("DROP TABLE IF EXISTS lite_eco_$currency;\n")
27 | writer.write("CREATE TABLE lite_eco_$currency (id INT(11), username VARCHAR(36), uuid BINARY(16), money DECIMAL(18,9));")
28 | writer.write("\nINSERT INTO lite_eco_$currency (id, username, uuid, money) VALUES $insertStatement;")
29 | writer.write("\nALTER TABLE `lite_eco_$currency` ADD PRIMARY KEY(`id`);")
30 | writer.flush()
31 | writer.close()
32 | }
33 | true
34 | } catch (e : IOException) {
35 | plugin.logger.severe("Error while migrating to SQL file: ${e.message}")
36 | e.printStackTrace()
37 | false
38 | }
39 | }
40 |
41 | }
42 |
43 | suspend fun exportToSQLFileLite(balances: List) : Boolean {
44 | val file = File("${plugin.dataFolder}/migration/", "${fileName}_${currency}_${timestamp}.sql")
45 | return withContext(Dispatchers.IO) {
46 | try {
47 | file.parentFile.mkdirs()
48 | BufferedWriter(FileWriter(file)).use { writer ->
49 | writer.write("CREATE TABLE lite_eco_$currency (id INT(11), username VARCHAR(36), uuid BINARY(16), money DECIMAL(18,9));")
50 | val insertStatements = balances.joinToString {
51 | "\n(${it.id}, '${it.username}', X'${it.uuid.toString().replace("-", "")}', ${it.money})"
52 | }
53 | writer.write("INSERT INTO lite_eco_$currency (id, username, uuid, money) VALUES $insertStatements;")
54 | writer.flush()
55 | writer.close()
56 | }
57 | true
58 | } catch (e : IOException) {
59 | plugin.logger.severe("Error while migrating to SQL file: ${e.message}")
60 | e.printStackTrace()
61 | false
62 | }
63 | }
64 | }
65 | }
--------------------------------------------------------------------------------
/src/main/kotlin/com/github/encryptsl/lite/eco/api/migrator/entity/PlayerBalances.kt:
--------------------------------------------------------------------------------
1 | package com.github.encryptsl.lite.eco.api.migrator.entity
2 |
3 | import java.math.BigDecimal
4 | import java.util.*
5 |
6 | class PlayerBalances {
7 | data class PlayerBalance(val id: Int, val uuid: UUID, val username: String?, val money: BigDecimal)
8 | }
--------------------------------------------------------------------------------
/src/main/kotlin/com/github/encryptsl/lite/eco/api/objects/ModernText.kt:
--------------------------------------------------------------------------------
1 | package com.github.encryptsl.lite.eco.api.objects
2 |
3 | import net.kyori.adventure.text.Component
4 | import net.kyori.adventure.text.minimessage.MiniMessage
5 | import net.kyori.adventure.text.minimessage.tag.resolver.TagResolver
6 | import net.kyori.adventure.text.minimessage.tag.standard.StandardTags
7 |
8 | object ModernText {
9 |
10 | private val miniMessage: MiniMessage by lazy { initMiniMessage() }
11 |
12 | @JvmStatic
13 | fun miniModernText(message: String): Component {
14 | return miniMessage.deserialize(convertVariables(message))
15 | }
16 |
17 | @JvmStatic
18 | fun miniModernText(message: String, resolver: TagResolver): Component {
19 | return miniMessage.deserialize(convertVariables(message), resolver)
20 | }
21 |
22 | @JvmStatic
23 | fun miniModernTextSerialize(component: Component): String {
24 | return miniMessage.serialize(component)
25 | }
26 |
27 | private fun initMiniMessage(): MiniMessage {
28 | return MiniMessage.builder()
29 | .strict(false)
30 | .tags(
31 | TagResolver.builder()
32 | .resolver(StandardTags.color())
33 | .resolver(StandardTags.clickEvent())
34 | .resolver(StandardTags.decorations())
35 | .resolver(StandardTags.font())
36 | .resolver(StandardTags.hoverEvent())
37 | .resolver(StandardTags.insertion())
38 | .resolver(StandardTags.rainbow())
39 | .resolver(StandardTags.newline())
40 | .resolver(StandardTags.transition())
41 | .resolver(StandardTags.gradient())
42 | .build()
43 | )
44 | .build()
45 | }
46 |
47 | private fun convertVariables(value: String): String {
48 | val regex = """[{](\w+)[}]""".toRegex()
49 | return regex.replace(value) { matchResult ->
50 | "<${matchResult.groupValues[1]}>"
51 | }
52 | }
53 | }
--------------------------------------------------------------------------------
/src/main/kotlin/com/github/encryptsl/lite/eco/commands/InternalCmd.kt:
--------------------------------------------------------------------------------
1 | package com.github.encryptsl.lite.eco.commands
2 |
3 | import org.incendo.cloud.paper.PaperCommandManager
4 | import org.incendo.cloud.paper.util.sender.Source
5 |
6 | interface InternalCmd {
7 | fun execute(commandManager: PaperCommandManager)
8 | }
--------------------------------------------------------------------------------
/src/main/kotlin/com/github/encryptsl/lite/eco/commands/parsers/CurrencyParser.kt:
--------------------------------------------------------------------------------
1 | package com.github.encryptsl.lite.eco.commands.parsers
2 |
3 | import com.github.encryptsl.lite.eco.LiteEco
4 | import org.bukkit.command.CommandSender
5 | import org.incendo.cloud.context.CommandContext
6 | import org.incendo.cloud.context.CommandInput
7 | import org.incendo.cloud.paper.util.sender.Source
8 | import org.incendo.cloud.parser.ArgumentParseResult
9 | import org.incendo.cloud.parser.ArgumentParser
10 | import org.incendo.cloud.suggestion.Suggestion
11 | import org.incendo.cloud.suggestion.SuggestionProvider
12 |
13 |
14 | class CurrencyParser : ArgumentParser {
15 | override fun parse(
16 | commandContext: CommandContext,
17 | commandInput: CommandInput
18 | ): ArgumentParseResult {
19 | val input = commandInput.peekString()
20 |
21 | if (!LiteEco.instance.currencyImpl.getCurrencyNameExist(input)) {
22 | val message = LiteEco.instance.locale.getMessage("messages.parser.error.currency_not_exist")
23 | return ArgumentParseResult.failure(Exception(String.format(message, input)))
24 | }
25 | commandInput.readString()
26 | return ArgumentParseResult.success(input)
27 | }
28 |
29 | override fun suggestionProvider(): SuggestionProvider {
30 | return SuggestionProvider.blockingStrings { s, i ->
31 | LiteEco.instance.currencyImpl.getCurrenciesKeys().filter {
32 | val sender: CommandSender = s.sender().source()
33 | sender.hasPermission("lite.eco.balance.$it") || sender.hasPermission("lite.eco.balance.*")
34 | }.map { Suggestion.suggestion(it).suggestion() }
35 | }
36 | }
37 | }
--------------------------------------------------------------------------------
/src/main/kotlin/com/github/encryptsl/lite/eco/commands/parsers/ImportEconomyParser.kt:
--------------------------------------------------------------------------------
1 | package com.github.encryptsl.lite.eco.commands.parsers
2 |
3 | import com.github.encryptsl.lite.eco.LiteEco
4 | import com.github.encryptsl.lite.eco.common.manager.importer.ImportEconomy
5 | import org.incendo.cloud.context.CommandContext
6 | import org.incendo.cloud.context.CommandInput
7 | import org.incendo.cloud.paper.util.sender.Source
8 | import org.incendo.cloud.parser.ArgumentParseResult
9 | import org.incendo.cloud.parser.ArgumentParser
10 | import org.incendo.cloud.suggestion.Suggestion
11 | import org.incendo.cloud.suggestion.SuggestionProvider
12 |
13 | class ImportEconomyParser(private val importer: ImportEconomy) : ArgumentParser {
14 | override fun parse(
15 | commandContext: CommandContext,
16 | commandInput: CommandInput
17 | ): ArgumentParseResult {
18 | val input = commandInput.peekString()
19 | commandInput.readString()
20 | if (importer.getAvailableImporters().contains(input)) {
21 | commandInput.readString()
22 | return ArgumentParseResult.success(input)
23 | }
24 |
25 | return ArgumentParseResult.failure(Exception(LiteEco.instance.locale.getMessage("messages.parser.error.convert_fail")))
26 | }
27 |
28 | override fun suggestionProvider(): SuggestionProvider {
29 | return SuggestionProvider.suggesting(importer.getAvailableImporters().map { Suggestion.suggestion(it) })
30 | }
31 | }
--------------------------------------------------------------------------------
/src/main/kotlin/com/github/encryptsl/lite/eco/commands/parsers/LangParser.kt:
--------------------------------------------------------------------------------
1 | package com.github.encryptsl.lite.eco.commands.parsers
2 |
3 | import com.github.encryptsl.lite.eco.LiteEco
4 | import com.github.encryptsl.lite.eco.common.config.Locales
5 | import org.incendo.cloud.context.CommandContext
6 | import org.incendo.cloud.context.CommandInput
7 | import org.incendo.cloud.paper.util.sender.Source
8 | import org.incendo.cloud.parser.ArgumentParseResult
9 | import org.incendo.cloud.parser.ArgumentParser
10 | import org.incendo.cloud.suggestion.Suggestion
11 | import org.incendo.cloud.suggestion.SuggestionProvider
12 |
13 | class LangParser : ArgumentParser {
14 | override fun parse(
15 | commandContext: CommandContext,
16 | commandInput: CommandInput
17 | ): ArgumentParseResult {
18 | val input = commandInput.peekString()
19 |
20 | try {
21 | commandInput.readString()
22 | return ArgumentParseResult.success(Locales.LangKey.valueOf(input))
23 | } catch (_ : IllegalArgumentException) {
24 | val message = LiteEco.instance.locale.getMessage("messages.parser.error.language_not_exist")
25 | return ArgumentParseResult.failure(Exception(String.format(message, input)))
26 | }
27 | }
28 |
29 | override fun suggestionProvider(): SuggestionProvider {
30 | return SuggestionProvider.suggesting(Locales.LangKey.entries.map { Suggestion.suggestion(it.name) })
31 | }
32 | }
--------------------------------------------------------------------------------
/src/main/kotlin/com/github/encryptsl/lite/eco/common/AccountManager.kt:
--------------------------------------------------------------------------------
1 | package com.github.encryptsl.lite.eco.common
2 |
3 | import com.github.encryptsl.lite.eco.LiteEco
4 | import kotlinx.coroutines.launch
5 | import java.util.*
6 |
7 | class AccountManager(private val liteEco: LiteEco) {
8 |
9 | fun createAccount(uuid: UUID, username: String) {
10 | liteEco.pluginScope.launch {
11 | liteEco.currencyImpl.getCurrenciesKeys()
12 | .map { it to liteEco.currencyImpl.getCurrencyStartBalance(it) }
13 | .forEach { (currency, amount) ->
14 | liteEco.suspendApiWrapper.createAccount(uuid, username, currency, amount)
15 | }
16 | }
17 | }
18 |
19 | fun syncAccount(uuid: UUID) {
20 | liteEco.pluginScope.launch {
21 | liteEco.suspendApiWrapper.syncAccount(uuid)
22 | }
23 | }
24 |
25 | fun cachingAccount(uuid: UUID) {
26 | liteEco.pluginScope.launch {
27 | liteEco.currencyImpl.getCurrenciesKeys()
28 | .mapNotNull { currency ->
29 | liteEco.databaseEcoModel.getUserByUUID(uuid, currency)?.let { user -> currency to user.money }
30 | }
31 | .forEach { (currency, money) -> liteEco.api.cacheAccount(uuid, currency, money) }
32 | }
33 | }
34 |
35 |
36 | }
--------------------------------------------------------------------------------
/src/main/kotlin/com/github/encryptsl/lite/eco/common/config/Locales.kt:
--------------------------------------------------------------------------------
1 | package com.github.encryptsl.lite.eco.common.config
2 |
3 | import com.github.encryptsl.lite.eco.LiteEco
4 | import com.github.encryptsl.lite.eco.api.objects.ModernText
5 | import com.tchristofferson.configupdater.ConfigUpdater
6 | import net.kyori.adventure.text.Component
7 | import net.kyori.adventure.text.minimessage.tag.resolver.TagResolver
8 | import net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer
9 | import org.bukkit.configuration.file.FileConfiguration
10 | import org.bukkit.configuration.file.YamlConfiguration
11 | import java.io.File
12 |
13 | class Locales(private val liteEco: LiteEco) {
14 | enum class LangKey { CS_CZ, EN_US, ES_ES, JA_JP, DE_DE, PL_PL, PT_BR, TR_TR, ZH_CN }
15 |
16 | private lateinit var langYml: FileConfiguration
17 | private val config get() = liteEco.config
18 | private val logger get() = liteEco.logger
19 |
20 | private val localeDir = File(liteEco.dataFolder, "locale")
21 |
22 | val prefix: String
23 | get() = config.getString("plugin.prefix").orEmpty()
24 |
25 | fun translation(translationKey: String): Component {
26 | return ModernText.miniModernText(getMessage(translationKey))
27 | }
28 |
29 | fun translation(translationKey: String, tagResolver: TagResolver): Component {
30 | return ModernText.miniModernText(getMessage(translationKey), tagResolver)
31 | }
32 |
33 | fun plainTextTranslation(component: Component): String {
34 |
35 | return PlainTextComponentSerializer.plainText().serialize(component)
36 | }
37 |
38 | fun getMessage(key: String): String {
39 | val raw = langYml.getString(key)
40 | ?: langYml.getString("messages.admin.translation_missing")?.replace("", key)
41 | return raw?.replace("", prefix)
42 | ?: "Translation missing: $key"
43 | }
44 |
45 | fun getList(key: String): List {
46 | return langYml.getList(key)
47 | ?.mapNotNull { it?.toString()?.replace("", prefix) }
48 | ?: emptyList()
49 | }
50 |
51 | fun setLocale(langKey: LangKey) {
52 | val selectedLocale = resolveLocale(langKey)
53 | val fileName = "$selectedLocale.yml"
54 | val file = File(localeDir, fileName)
55 |
56 | try {
57 | if (!file.exists()) {
58 | file.parentFile.mkdirs()
59 | liteEco.saveResource("locale/$fileName", false)
60 | }
61 |
62 | ConfigUpdater.update(liteEco, "locale/$fileName", file)
63 | langYml = YamlConfiguration.loadConfiguration(file)
64 |
65 | config.set("plugin.translation", langKey.name)
66 | liteEco.saveConfig()
67 |
68 | logger.info("✅ Translation loaded: $fileName")
69 |
70 | } catch (ex: Exception) {
71 | logger.warning("⚠️ Failed to load translation for ${langKey.name}")
72 | logger.severe(ex.message ?: ex.toString())
73 | }
74 | }
75 |
76 | fun reloadCurrentLocale() {
77 | val current = config.getString("plugin.translation").orEmpty()
78 | val langKey = runCatching { LangKey.valueOf(current) }.getOrDefault(LangKey.EN_US)
79 | setLocale(langKey)
80 | }
81 |
82 | fun load() {
83 | val selected = config.getString("plugin.translation").orEmpty()
84 | val langKey = runCatching { LangKey.valueOf(selected) }.getOrDefault(LangKey.EN_US)
85 | setLocale(langKey)
86 | }
87 |
88 | private fun resolveLocale(langKey: LangKey): String {
89 | return LangKey.entries
90 | .firstOrNull { it.name.equals(langKey.name, ignoreCase = true) }
91 | ?.name?.lowercase()
92 | ?: "en_us"
93 | }
94 | }
--------------------------------------------------------------------------------
/src/main/kotlin/com/github/encryptsl/lite/eco/common/database/DatabaseConfigLoader.kt:
--------------------------------------------------------------------------------
1 | package com.github.encryptsl.lite.eco.common.database
2 |
3 | import org.bukkit.configuration.ConfigurationSection
4 |
5 | class DatabaseConfigLoader(private val config: ConfigurationSection) {
6 |
7 | data class DbConfig(
8 | val driver: String,
9 | val jdbcUrl: String,
10 | val username: String,
11 | val password: String
12 | )
13 |
14 | fun load(): DbConfig {
15 | val driver = config.getString("database.connection.driverClassName")
16 | ?: throw IllegalArgumentException("Missing database.connection.driverClassName in config")
17 |
18 | val jdbcUrl = config.getString("database.connection.jdbc_url")
19 | ?: throw IllegalArgumentException("Missing database.connection.jdbc_url in config")
20 |
21 | val username = config.getString("database.connection.username")
22 | ?: throw IllegalArgumentException("Missing database.connection.username in config")
23 |
24 | val password = config.getString("database.connection.password")
25 | ?: throw IllegalArgumentException("Missing database.connection.password in config")
26 |
27 | return DbConfig(
28 | driver = driver,
29 | jdbcUrl = jdbcUrl,
30 | username = username,
31 | password = password
32 | )
33 | }
34 | }
--------------------------------------------------------------------------------
/src/main/kotlin/com/github/encryptsl/lite/eco/common/database/DatabaseConnector.kt:
--------------------------------------------------------------------------------
1 | package com.github.encryptsl.lite.eco.common.database
2 |
3 | import com.github.encryptsl.lite.eco.LiteEco
4 | import com.github.encryptsl.lite.eco.api.interfaces.DatabaseConnectorProvider
5 | import com.github.encryptsl.lite.eco.common.database.tables.Account
6 | import com.github.encryptsl.lite.eco.common.database.tables.MonologTable
7 | import com.github.encryptsl.lite.eco.common.extensions.loggedTransaction
8 | import com.zaxxer.hikari.HikariDataSource
9 | import org.jetbrains.exposed.jdbc.ExposedConnectionImpl
10 | import org.jetbrains.exposed.sql.Database
11 | import org.jetbrains.exposed.sql.DatabaseConfig
12 | import org.jetbrains.exposed.sql.ExperimentalKeywordApi
13 | import org.jetbrains.exposed.sql.SchemaUtils
14 |
15 | class DatabaseConnector(private val liteEco: LiteEco) : DatabaseConnectorProvider {
16 |
17 | override fun load() {
18 | val configLoader = DatabaseConfigLoader(liteEco.config)
19 | val (driver, jdbcUrl, username, password) = configLoader.load()
20 |
21 | initConnect(driver, jdbcUrl, username, password)
22 | }
23 |
24 | override fun initConnect(driver: String, jdbcHost: String, user: String, pass: String) {
25 | try {
26 | Database.connect(HikariDataSource().apply {
27 | this.driverClassName = driver
28 | this.jdbcUrl = jdbcHost
29 | this.username = user
30 | this.password = pass
31 | this.poolName = liteEco.javaClass.simpleName
32 | this.maximumPoolSize = 20
33 | this.isReadOnly = false
34 | this.transactionIsolation = "TRANSACTION_SERIALIZABLE"
35 | }, databaseConfig = DatabaseConfig {
36 | @OptIn(ExperimentalKeywordApi::class)
37 | preserveKeywordCasing = true
38 | }, connectionAutoRegistration = ExposedConnectionImpl())
39 |
40 | liteEco.currencyImpl.getCurrenciesKeys().forEach { currency ->
41 | loggedTransaction {
42 | SchemaUtils.create(Account(currency), MonologTable)
43 | }
44 | }
45 | } catch (e: Exception) {
46 | liteEco.logger.severe("Database initialization failed: ${e.message}")
47 | }
48 | }
49 | }
--------------------------------------------------------------------------------
/src/main/kotlin/com/github/encryptsl/lite/eco/common/database/SqlPluginLogger.kt:
--------------------------------------------------------------------------------
1 | package com.github.encryptsl.lite.eco.common.database
2 |
3 | import com.github.encryptsl.lite.eco.LiteEco
4 | import com.github.encryptsl.lite.eco.api.objects.ModernText
5 | import org.jetbrains.exposed.sql.SqlLogger
6 | import org.jetbrains.exposed.sql.Transaction
7 | import org.jetbrains.exposed.sql.statements.StatementContext
8 | import org.jetbrains.exposed.sql.statements.expandArgs
9 | import org.jetbrains.exposed.sql.transactions.TransactionManager
10 |
11 | class SqlPluginLogger : SqlLogger {
12 | override fun log(context: StatementContext, transaction: Transaction) {
13 | if (!LiteEco.instance.config.getBoolean("database.sql-plugin-logger")) return
14 | LiteEco.instance.componentLogger.info(ModernText.miniModernText("${context.expandArgs(TransactionManager.current())}"))
15 | }
16 | }
--------------------------------------------------------------------------------
/src/main/kotlin/com/github/encryptsl/lite/eco/common/database/entity/EconomyLog.kt:
--------------------------------------------------------------------------------
1 | package com.github.encryptsl.lite.eco.common.database.entity
2 |
3 | import kotlinx.datetime.Instant
4 | import java.math.BigDecimal
5 |
6 | data class EconomyLog(
7 | val action: String,
8 | val sender: String,
9 | val target: String,
10 | val currency: String,
11 | val previousBalance: BigDecimal,
12 | val newBalance: BigDecimal,
13 | val timestamp: Instant
14 | )
15 |
--------------------------------------------------------------------------------
/src/main/kotlin/com/github/encryptsl/lite/eco/common/database/entity/User.kt:
--------------------------------------------------------------------------------
1 | package com.github.encryptsl.lite.eco.common.database.entity
2 |
3 | import java.math.BigDecimal
4 | import java.util.*
5 |
6 | data class User(val userName: String, val uuid: UUID, val money: BigDecimal)
--------------------------------------------------------------------------------
/src/main/kotlin/com/github/encryptsl/lite/eco/common/database/models/DatabaseEcoModel.kt:
--------------------------------------------------------------------------------
1 | package com.github.encryptsl.lite.eco.common.database.models
2 |
3 | import com.github.encryptsl.lite.eco.LiteEco
4 | import com.github.encryptsl.lite.eco.api.interfaces.PlayerSQL
5 | import com.github.encryptsl.lite.eco.common.database.entity.User
6 | import com.github.encryptsl.lite.eco.common.database.tables.Account
7 | import com.github.encryptsl.lite.eco.common.extensions.loggedTransaction
8 | import org.bukkit.Bukkit
9 | import org.jetbrains.exposed.exceptions.ExposedSQLException
10 | import org.jetbrains.exposed.sql.*
11 | import org.jetbrains.exposed.sql.SqlExpressionBuilder.eq
12 | import org.jetbrains.exposed.sql.SqlExpressionBuilder.notInList
13 | import java.math.BigDecimal
14 | import java.util.*
15 |
16 | class DatabaseEcoModel : PlayerSQL {
17 |
18 | override fun createPlayerAccount(username: String, uuid: UUID, currency: String, money: BigDecimal) {
19 | loggedTransaction {
20 | try {
21 | val table = Account(currency)
22 | table.insertIgnore {
23 | it[table.username] = username
24 | it[table.uuid] = uuid
25 | it[table.money] = money
26 | }
27 | } catch (e : ExposedSQLException) {
28 | LiteEco.instance.logger.severe(e.message ?: e.localizedMessage)
29 | }
30 | }
31 | }
32 |
33 | override fun updatePlayerName(uuid: UUID, username: String, currency: String) {
34 | loggedTransaction {
35 | try {
36 | val table = Account(currency)
37 | table.update ({ table.uuid eq uuid }) {
38 | it[table.username] = username
39 | }
40 | } catch (e : ExposedSQLException) {
41 | LiteEco.instance.logger.severe(e.message ?: e.localizedMessage)
42 | }
43 | }
44 | }
45 |
46 | override fun getUserByUUID(uuid: UUID, currency: String): User? {
47 | return loggedTransaction {
48 | try {
49 | val table = Account(currency)
50 | val row = table.select(table.uuid, table.username, table.money).where(table.uuid eq uuid).single()
51 | User(row[table.username], row[table.uuid], row[table.money])
52 | } catch (e : Exception) {
53 | LiteEco.instance.logger.severe(e.message ?: e.localizedMessage)
54 | null
55 | }
56 | }
57 | }
58 |
59 | override fun getBalance(uuid: UUID, currency: String): BigDecimal {
60 | return loggedTransaction {
61 | try {
62 | val table = Account(currency)
63 | table.select(table.uuid, table.money).where { table.uuid eq uuid }.single()[table.money]
64 | } catch (e : ExposedSQLException) {
65 | LiteEco.instance.logger.severe(e.message ?: e.localizedMessage)
66 | BigDecimal.ZERO
67 | }
68 | }
69 | }
70 |
71 | override fun deletePlayerAccount(uuid: UUID, currency: String) {
72 | loggedTransaction {
73 | try {
74 | val table = Account(currency)
75 | table.deleteWhere { table.uuid eq uuid }
76 | } catch (e : ExposedSQLException) {
77 | LiteEco.instance.logger.severe(e.message ?: e.localizedMessage)
78 | }
79 | }
80 | }
81 |
82 | override fun getExistPlayerAccount(uuid: UUID, currency: String): Boolean {
83 | return loggedTransaction {
84 | try {
85 | val table = Account(currency)
86 | !table.select(table.uuid).where(table.uuid eq uuid).empty()
87 | } catch (e : ExposedSQLException) {
88 | LiteEco.instance.logger.severe(e.message ?: e.localizedMessage)
89 | false
90 | }
91 | }
92 | }
93 |
94 | override fun getTopBalance(currency: String): MutableMap = loggedTransaction {
95 | val table = Account(currency)
96 |
97 | table.selectAll().orderBy(table.money, SortOrder.DESC).associate {
98 | it[table.username] to User(it[table.username], it[table.uuid], it[table.money])
99 | }.toMutableMap()
100 | }
101 |
102 | override fun getUUIDNameMap(currency: String): MutableMap = loggedTransaction {
103 | val table = Account(currency)
104 | table.selectAll().associate {
105 | it[table.uuid] to it[table.username]
106 | }.toMutableMap()
107 | }
108 |
109 | override fun getPlayersIds(currency: String): MutableCollection {
110 | return loggedTransaction {
111 | try {
112 | val table = Account(currency)
113 | table.selectAll().map {it[table.uuid] }.toMutableList()
114 | } catch (e : ExposedSQLException) {
115 | LiteEco.instance.logger.severe(e.message ?: e.localizedMessage)
116 | mutableListOf()
117 | }
118 | }
119 | }
120 |
121 | override fun depositMoney(uuid: UUID, currency: String, money: BigDecimal) {
122 | loggedTransaction {
123 | try {
124 | val table = Account(currency)
125 | table.update({ table.uuid eq uuid }) {
126 | with(SqlExpressionBuilder) {
127 | it[table.money] = table.money + money
128 | }
129 | }
130 | } catch (e : ExposedSQLException) {
131 | LiteEco.instance.logger.severe(e.message ?: e.localizedMessage)
132 | }
133 | }
134 | }
135 | override fun withdrawMoney(uuid: UUID, currency: String, money: BigDecimal) {
136 | loggedTransaction {
137 | try {
138 | val table = Account(currency)
139 | table.update({ table.uuid eq uuid }) {
140 | with(SqlExpressionBuilder) {
141 | it[table.money] = table.money - money
142 | }
143 | }
144 | } catch (e : ExposedSQLException) {
145 | LiteEco.instance.logger.severe(e.message ?: e.localizedMessage)
146 | }
147 | }
148 | }
149 | override fun setMoney(uuid: UUID, currency: String, money: BigDecimal) {
150 | loggedTransaction {
151 | try {
152 | val table = Account(currency)
153 | table.update({ table.uuid eq uuid }) {
154 | with(SqlExpressionBuilder) {
155 | it[table.money] = money
156 | }
157 | }
158 | } catch (e : ExposedSQLException) {
159 | LiteEco.instance.logger.severe(e.message ?: e.localizedMessage)
160 | }
161 | }
162 | }
163 |
164 | override fun purgeAccounts(currency: String) {
165 | loggedTransaction {
166 | try {
167 | val table = Account(currency)
168 | table.deleteAll()
169 | } catch (e : ExposedSQLException) {
170 | LiteEco.instance.logger.severe(e.message ?: e.localizedMessage)
171 | }
172 | }
173 | }
174 |
175 | override fun purgeDefaultAccounts(defaultMoney: BigDecimal, currency: String) {
176 | loggedTransaction {
177 | try {
178 | val table = Account(currency)
179 | table.deleteWhere { money eq defaultMoney }
180 | } catch (e : ExposedSQLException) {
181 | LiteEco.instance.logger.severe(e.message ?: e.localizedMessage)
182 | }
183 | }
184 | }
185 |
186 | override fun purgeInvalidAccounts(currency: String) {
187 | loggedTransaction {
188 | try {
189 | val table = Account(currency)
190 | table.deleteWhere {
191 | uuid notInList Bukkit.getOfflinePlayers().map { it.uniqueId }
192 | }
193 | } catch (e : ExposedSQLException) {
194 | LiteEco.instance.logger.severe(e.message ?: e.localizedMessage)
195 | }
196 | }
197 | }
198 | }
--------------------------------------------------------------------------------
/src/main/kotlin/com/github/encryptsl/lite/eco/common/database/models/DatabaseMonologModel.kt:
--------------------------------------------------------------------------------
1 | package com.github.encryptsl.lite.eco.common.database.models
2 |
3 | import com.github.encryptsl.lite.eco.LiteEco
4 | import com.github.encryptsl.lite.eco.api.economy.EconomyOperations
5 | import com.github.encryptsl.lite.eco.api.interfaces.TransactionLogger
6 | import com.github.encryptsl.lite.eco.common.database.entity.EconomyLog
7 | import com.github.encryptsl.lite.eco.common.database.tables.MonologTable
8 | import com.github.encryptsl.lite.eco.common.extensions.convertInstant
9 | import com.github.encryptsl.lite.eco.common.extensions.loggedTransaction
10 | import com.github.encryptsl.lite.eco.common.extensions.runBlockingIO
11 | import kotlinx.datetime.Instant
12 | import net.kyori.adventure.text.Component
13 | import net.kyori.adventure.text.minimessage.tag.resolver.Placeholder
14 | import net.kyori.adventure.text.minimessage.tag.resolver.TagResolver
15 | import org.bukkit.plugin.Plugin
16 | import org.jetbrains.exposed.sql.SortOrder
17 | import org.jetbrains.exposed.sql.deleteAll
18 | import org.jetbrains.exposed.sql.insert
19 | import org.jetbrains.exposed.sql.selectAll
20 | import java.math.BigDecimal
21 |
22 | class DatabaseMonologModel(val plugin: Plugin) : TransactionLogger {
23 |
24 | override suspend fun logging(
25 | economyOperations: EconomyOperations,
26 | sender: String,
27 | target: String,
28 | currency: String,
29 | previousBalance: BigDecimal,
30 | newBalance: BigDecimal
31 | ) {
32 | log(economyOperations, sender, target, currency, previousBalance, newBalance)
33 | }
34 |
35 | override fun clearLogs() {
36 | loggedTransaction { MonologTable.deleteAll() }
37 | }
38 |
39 | override suspend fun getLog(): List {
40 | return loggedTransaction {
41 | MonologTable.selectAll().orderBy(MonologTable.timestamp, SortOrder.DESC).mapNotNull {
42 | EconomyLog(it[MonologTable.action], it[MonologTable.sender], it[MonologTable.target], it[MonologTable.currency], it[MonologTable.previousBalance], it[MonologTable.newBalance], it[MonologTable.timestamp])
43 | }
44 | }
45 | }
46 |
47 | fun message(
48 | translation: String,
49 | economyOperations: EconomyOperations,
50 | sender: String,
51 | target: String,
52 | currency: String,
53 | previousBalance: BigDecimal,
54 | newBalance: BigDecimal,
55 | instant: Instant,
56 | ): Component {
57 | return LiteEco.instance.locale.translation(translation, TagResolver.resolver(
58 | Placeholder.parsed("action", economyOperations.name),
59 | Placeholder.parsed("sender", sender),
60 | Placeholder.parsed("target", target),
61 | Placeholder.parsed("currency", currency),
62 | Placeholder.parsed("previous_balance", LiteEco.instance.api.fullFormatting(previousBalance)),
63 | Placeholder.parsed("new_balance", LiteEco.instance.api.fullFormatting(newBalance)),
64 | Placeholder.parsed("timestamp", convertInstant(instant)),
65 | ))
66 | }
67 |
68 | private suspend fun log(
69 | economyOperations: EconomyOperations,
70 | sender: String,
71 | target: String,
72 | currency: String,
73 | previousBalance: BigDecimal,
74 | newBalance: BigDecimal
75 | ) {
76 | if (!plugin.config.getBoolean("economy.monolog_activity", true)) return
77 | runBlockingIO {
78 | loggedTransaction {
79 | MonologTable.insert {
80 | it[action] = economyOperations.name
81 | it[MonologTable.sender] = sender
82 | it[MonologTable.target] = target
83 | it[MonologTable.currency] = currency
84 | it[MonologTable.previousBalance] = previousBalance
85 | it[MonologTable.newBalance] = newBalance
86 | }
87 | }
88 | }
89 | }
90 |
91 | }
--------------------------------------------------------------------------------
/src/main/kotlin/com/github/encryptsl/lite/eco/common/database/models/legacy/LegacyDatabaseEcoModel.kt:
--------------------------------------------------------------------------------
1 | package com.github.encryptsl.lite.eco.common.database.models.legacy
2 |
3 | import com.github.encryptsl.lite.eco.LiteEco
4 | import com.github.encryptsl.lite.eco.api.migrator.entity.PlayerBalances
5 | import com.github.encryptsl.lite.eco.common.database.tables.Account
6 | import com.github.encryptsl.lite.eco.common.database.tables.legacy.LegacyAccountTable
7 | import kotlinx.coroutines.Dispatchers
8 | import kotlinx.coroutines.withContext
9 | import org.jetbrains.exposed.exceptions.ExposedSQLException
10 | import org.jetbrains.exposed.sql.ResultRow
11 | import org.jetbrains.exposed.sql.SchemaUtils
12 | import org.jetbrains.exposed.sql.insert
13 | import org.jetbrains.exposed.sql.selectAll
14 | import org.jetbrains.exposed.sql.transactions.transaction
15 | import java.util.*
16 |
17 | class LegacyDatabaseEcoModel(
18 | private val liteEco: LiteEco,
19 | private val currency: String
20 | ) {
21 |
22 | private val playersBalances = mutableMapOf()
23 |
24 | private fun getPlayerBalances(): MutableMap {
25 |
26 | transaction {
27 | LegacyAccountTable.selectAll().forEach { resultRow: ResultRow ->
28 | playersBalances[UUID.fromString(resultRow[LegacyAccountTable.uuid])] = PlayerBalances.PlayerBalance(
29 | resultRow[LegacyAccountTable.id],
30 | UUID.fromString(resultRow[LegacyAccountTable.uuid]),
31 | resultRow[LegacyAccountTable.username],
32 | resultRow[LegacyAccountTable.money].toBigDecimal()
33 | )
34 | }
35 | }
36 |
37 | return playersBalances
38 | }
39 |
40 | suspend fun exportToLiteEcoDollarsTable() : Boolean {
41 | return withContext(Dispatchers.IO) {
42 | transaction {
43 | try {
44 | val table = Account(currency)
45 | SchemaUtils.create(table)
46 | for (eco in getPlayerBalances()) {
47 | table.insert {
48 | it[uuid] = eco.key
49 | it[username] = eco.value.username ?: "null"
50 | it[money] = eco.value.money
51 | }
52 | }
53 | return@transaction true
54 | } catch (e : ExposedSQLException) {
55 | liteEco.logger.severe(e.sqlState)
56 | return@transaction false
57 | }
58 | }
59 | }
60 | }
61 | }
--------------------------------------------------------------------------------
/src/main/kotlin/com/github/encryptsl/lite/eco/common/database/tables/Account.kt:
--------------------------------------------------------------------------------
1 | package com.github.encryptsl.lite.eco.common.database.tables
2 |
3 | import org.jetbrains.exposed.dao.id.LongIdTable
4 |
5 | class Account(currency: String) : LongIdTable("lite_eco_$currency") {
6 | val username = varchar("username", 36)
7 | val uuid = uuid("uuid")
8 | val money = decimal("money", 18, 9)
9 | }
--------------------------------------------------------------------------------
/src/main/kotlin/com/github/encryptsl/lite/eco/common/database/tables/MonologTable.kt:
--------------------------------------------------------------------------------
1 | package com.github.encryptsl.lite.eco.common.database.tables
2 |
3 | import org.jetbrains.exposed.sql.Table
4 | import org.jetbrains.exposed.sql.kotlin.datetime.CurrentTimestamp
5 | import org.jetbrains.exposed.sql.kotlin.datetime.timestamp
6 |
7 | object MonologTable : Table("lite_eco_monolog") {
8 | private val id = integer( "id").autoIncrement()
9 | val action = varchar("action", 8)
10 | val sender = varchar("sender", 36)
11 | val target = varchar("target", 36)
12 | val currency = varchar("currency", 16)
13 | val previousBalance = decimal("previous_balance", 18, 9)
14 | val newBalance = decimal("new_balance", 18, 9)
15 | val timestamp = timestamp("timestamp").defaultExpression(CurrentTimestamp)
16 |
17 | override val primaryKey: PrimaryKey = PrimaryKey(id)
18 | }
--------------------------------------------------------------------------------
/src/main/kotlin/com/github/encryptsl/lite/eco/common/database/tables/legacy/LegacyAccountTable.kt:
--------------------------------------------------------------------------------
1 | package com.github.encryptsl.lite.eco.common.database.tables.legacy
2 |
3 | import org.jetbrains.exposed.sql.Table
4 |
5 | object LegacyAccountTable : Table("lite_eco") {
6 | val id = integer("id").autoIncrement()
7 | val username = varchar("username", 36)
8 | val uuid = varchar("uuid", 36)
9 | val money = double("money")
10 |
11 | override val primaryKey: PrimaryKey = PrimaryKey(id)
12 | }
--------------------------------------------------------------------------------
/src/main/kotlin/com/github/encryptsl/lite/eco/common/extensions/DatabaseLoggerTransaction.kt:
--------------------------------------------------------------------------------
1 | package com.github.encryptsl.lite.eco.common.extensions
2 |
3 | import com.github.encryptsl.lite.eco.common.database.SqlPluginLogger
4 | import org.jetbrains.exposed.sql.Database
5 | import org.jetbrains.exposed.sql.Transaction
6 | import org.jetbrains.exposed.sql.addLogger
7 | import org.jetbrains.exposed.sql.transactions.transaction
8 | import org.jetbrains.exposed.sql.transactions.transactionManager
9 |
10 | fun loggedTransaction(db: Database? = null, statement: Transaction.() -> T): T {
11 | return transaction(db.transactionManager.defaultIsolationLevel, db.transactionManager.defaultReadOnly, db
12 | ) {
13 | addLogger(SqlPluginLogger())
14 | statement.invoke(this)
15 | }
16 | }
--------------------------------------------------------------------------------
/src/main/kotlin/com/github/encryptsl/lite/eco/common/extensions/KotlinHelper.kt:
--------------------------------------------------------------------------------
1 | package com.github.encryptsl.lite.eco.common.extensions
2 |
3 | import kotlinx.coroutines.Dispatchers
4 | import kotlinx.coroutines.withContext
5 |
6 | suspend inline fun runBlockingIO(crossinline block: () -> T): T =
7 | withContext(Dispatchers.IO) { block() }
--------------------------------------------------------------------------------
/src/main/kotlin/com/github/encryptsl/lite/eco/common/extensions/MoneyFormat.kt:
--------------------------------------------------------------------------------
1 | package com.github.encryptsl.lite.eco.common.extensions
2 | import java.math.BigDecimal
3 | import java.math.RoundingMode
4 | import java.text.DecimalFormat
5 | import java.text.DecimalFormatSymbols
6 | import java.util.*
7 |
8 | private val units = charArrayOf('\u0000', 'K', 'M', 'B', 'T', 'Q')
9 |
10 | fun String.toValidDecimal(): BigDecimal? {
11 | return decompressNumber(this)
12 | }
13 |
14 | fun BigDecimal.compactFormat(pattern: String, compactPattern: String, locale: String): String {
15 | val (value, unit) = compactNumber(this) ?: (null to null)
16 |
17 | return value?.let { formatNumber(value, compactPattern, locale) + unit }
18 | ?: formatNumber(this, pattern, locale)
19 | }
20 |
21 | fun BigDecimal.moneyFormat(pattern: String, locale: String): String {
22 | return formatNumber(this, pattern, locale)
23 | }
24 |
25 | private fun formatNumber(number: BigDecimal, pattern: String, locale: String, compacted: Boolean = false): String {
26 | val formatter = DecimalFormat().apply {
27 | decimalFormatSymbols = DecimalFormatSymbols.getInstance(getLocale(locale))
28 | roundingMode = if (compacted) {
29 | RoundingMode.UNNECESSARY
30 | } else {
31 | RoundingMode.HALF_UP
32 | }
33 | applyPattern(pattern)
34 | }
35 | return formatter.format(number)
36 | }
37 |
38 | private fun decompressNumber(str: String): BigDecimal? {
39 | if (str.isBlank()) return null
40 |
41 | val lastChar = str.last().uppercaseChar()
42 |
43 | return if (lastChar in units) {
44 | val multiplier = BigDecimal.valueOf(10.0).pow(units.indexOf(lastChar) * 3)
45 | str.dropLast(1).toBigDecimal().times(multiplier)
46 | }
47 | else str.toBigDecimal()
48 | }
49 |
50 | private fun compactNumber(number: BigDecimal): Pair? {
51 | var value = number
52 | for (unit in units) {
53 | if (value < BigDecimal.valueOf(1000)) {
54 | return if (unit == units[0]) null
55 | else {
56 | return Pair(value, unit)
57 | }
58 | }
59 | value /= BigDecimal.valueOf(1000)
60 | }
61 | throw IllegalStateException("This shouldn't happen")
62 | }
63 |
64 | private fun getLocale(localeStr: String): Locale {
65 | val parts = localeStr.split("-", "_")
66 | return when (parts.size) {
67 | 1 -> Locale.of(parts[0])
68 | 2 -> Locale.of(parts[0], parts[1])
69 | else -> Locale.of(parts[0], parts[1], parts[2])
70 | }
71 | }
--------------------------------------------------------------------------------
/src/main/kotlin/com/github/encryptsl/lite/eco/common/extensions/NumberControl.kt:
--------------------------------------------------------------------------------
1 | package com.github.encryptsl.lite.eco.common.extensions
2 |
3 | import java.math.BigDecimal
4 |
5 | fun BigDecimal.isNegative(): Boolean {
6 | return this < BigDecimal.ZERO
7 | }
8 |
9 | fun BigDecimal.isZero(): Boolean {
10 | return this == BigDecimal.ZERO
11 | }
12 |
13 | fun BigDecimal.isApproachingZero(): Boolean {
14 | return this < BigDecimal.valueOf(0.01)
15 | }
--------------------------------------------------------------------------------
/src/main/kotlin/com/github/encryptsl/lite/eco/common/extensions/StringExtentions.kt:
--------------------------------------------------------------------------------
1 | package com.github.encryptsl.lite.eco.common.extensions
2 |
3 | import kotlinx.datetime.Instant
4 | import kotlinx.datetime.toJavaInstant
5 | import java.time.ZoneId
6 | import java.time.format.DateTimeFormatter
7 |
8 | fun getRandomString(length: Int) : String {
9 | val allowedChars = ('A'..'Z') + ('a'..'z') + ('0'..'9')
10 | return (1..length)
11 | .map { allowedChars.random() }
12 | .joinToString("")
13 | }
14 |
15 | fun convertInstant(instant: Instant): String {
16 | return instant
17 | .toJavaInstant()
18 | .atZone(ZoneId.systemDefault())
19 | .format(DateTimeFormatter.ofPattern("YYYY-MM-dd HH:mm:ss"))
20 | }
--------------------------------------------------------------------------------
/src/main/kotlin/com/github/encryptsl/lite/eco/common/extensions/TopPosition.kt:
--------------------------------------------------------------------------------
1 | package com.github.encryptsl.lite.eco.common.extensions
2 |
3 | inline fun Iterable.positionIndexed(transform: (index: Int, T) -> R): List {
4 | return mapIndexedTo(ArrayList(collectionSizeOrDefault(10)), transform)
5 | }
6 |
7 | inline fun > Iterable.mapIndexedTo(destination: C, transform: (index: Int, T) -> R): C {
8 | var index = 1
9 | for (item in this)
10 | destination.add(transform(index++, item))
11 | return destination
12 | }
13 |
14 | fun Iterable.collectionSizeOrDefault(default: Int): Int = if (this is Collection<*>) this.size else default
--------------------------------------------------------------------------------
/src/main/kotlin/com/github/encryptsl/lite/eco/common/hook/HookListener.kt:
--------------------------------------------------------------------------------
1 | package com.github.encryptsl.lite.eco.common.hook
2 |
3 | abstract class HookListener(
4 | val pluginName: String, val description: String,
5 | ) {
6 | var registered: Boolean = false
7 | protected set
8 |
9 | abstract fun canRegister(): Boolean
10 |
11 | abstract fun register()
12 |
13 | abstract fun unregister()
14 | }
--------------------------------------------------------------------------------
/src/main/kotlin/com/github/encryptsl/lite/eco/common/hook/HookManager.kt:
--------------------------------------------------------------------------------
1 | package com.github.encryptsl.lite.eco.common.hook
2 |
3 | import com.github.encryptsl.lite.eco.LiteEco
4 | import com.github.encryptsl.lite.eco.api.objects.ModernText
5 | import com.github.encryptsl.lite.eco.common.hook.bettereconomy.BetterEconomyHook
6 | import com.github.encryptsl.lite.eco.common.hook.craftconomy3.CraftConomyHook
7 | import com.github.encryptsl.lite.eco.common.hook.miniplaceholder.MiniPlaceholdersHook
8 | import com.github.encryptsl.lite.eco.common.hook.placeholderapi.PlaceholderAPIHook
9 | import com.github.encryptsl.lite.eco.common.hook.scruffyboy13.ScruffyboyEconomyHook
10 | import com.github.encryptsl.lite.eco.common.hook.vault.VaultHook
11 | import kotlin.system.measureTimeMillis
12 |
13 | class HookManager(private val liteEco: LiteEco) {
14 |
15 | private val hooks: Set = mutableSetOf(
16 | BetterEconomyHook(liteEco),
17 | CraftConomyHook(liteEco),
18 | ScruffyboyEconomyHook(liteEco),
19 | MiniPlaceholdersHook(liteEco),
20 | PlaceholderAPIHook(liteEco),
21 | VaultHook(liteEco)
22 | )
23 |
24 | /**
25 | * Method for disable plugin if is detected unsupported plugin.
26 | * @param plugins
27 | */
28 | fun blockPlugin(vararg plugins: String) {
29 | for (plugin in plugins) {
30 | if (liteEco.pluginManager.isPluginEnabled(plugin)) {
31 | liteEco.componentLogger.error("Please don't use $plugin, because there can be conflict.")
32 | liteEco.pluginManager.disablePlugin(liteEco)
33 | }
34 | }
35 | liteEco.componentLogger.warn("Blocked plugins are now ${plugins.size}")
36 | }
37 |
38 | fun registerHooks() {
39 | val timeTaken = measureTimeMillis {
40 | liteEco.componentLogger.info("Registering ${hooks.size} hooks...")
41 |
42 | hooks.filter(HookListener::canRegister).forEach {
43 | it.register()
44 | liteEco.componentLogger.info("${it.pluginName} found hook ${it.javaClass.simpleName} registered !.")
45 | liteEco.componentLogger.info(it.description)
46 | }
47 | }
48 | liteEco.componentLogger.info(ModernText.miniModernText("Registered ${hooks.count { it.registered }} of ${hooks.size} hooks took ${timeTaken} ms"))
49 | }
50 |
51 | fun unregisterHooks() {
52 | liteEco.componentLogger.info("Unregistering hooks...")
53 | hooks.filter(HookListener::canRegister).forEach {
54 | liteEco.componentLogger.info("Unregistering hook ${it.pluginName}.")
55 | it.unregister()
56 | liteEco.componentLogger.info("Unregistered hook ${it.pluginName}.")
57 | }
58 | }
59 | }
--------------------------------------------------------------------------------
/src/main/kotlin/com/github/encryptsl/lite/eco/common/hook/bettereconomy/BetterEconomyHook.kt:
--------------------------------------------------------------------------------
1 | package com.github.encryptsl.lite.eco.common.hook.bettereconomy
2 |
3 | import com.github.encryptsl.lite.eco.LiteEco
4 | import com.github.encryptsl.lite.eco.common.hook.HookListener
5 | import com.github.encryptsl.lite.eco.utils.ClassUtil
6 | import me.hsgamer.bettereconomy.BetterEconomy
7 | import me.hsgamer.bettereconomy.api.EconomyHandler
8 | import me.hsgamer.bettereconomy.provider.EconomyHandlerProvider
9 | import java.util.*
10 |
11 | class BetterEconomyHook(
12 | private val liteEco: LiteEco
13 | ) : HookListener(
14 | PLUGIN_NAME,
15 | "You can now export economy from plugin BetterEconomy to LiteEco with /eco database import BetterEconomy "
16 | ) {
17 | private lateinit var economyHandler: EconomyHandler
18 |
19 | companion object {
20 | const val PLUGIN_NAME = "BetterEconomy"
21 | fun isBetterEconomy(): Boolean
22 | = ClassUtil.isValidClasspath("me.hsgamer.bettereconomy.BetterEconomy")
23 | }
24 |
25 | override fun canRegister(): Boolean {
26 | return !registered && liteEco.pluginManager.isPluginEnabled(PLUGIN_NAME)
27 | }
28 |
29 | override fun register() {
30 | if (isBetterEconomy()) {
31 | economyHandler = BetterEconomy().get(EconomyHandlerProvider::class.java).economyHandler
32 | }
33 | registered = true
34 | }
35 |
36 | override fun unregister() {}
37 |
38 | fun getBalance(uuid: UUID): Double {
39 | if (!isBetterEconomy())
40 | throw Exception("Plugin BetterEconomy missing !")
41 | return economyHandler.get(uuid)
42 | }
43 | }
--------------------------------------------------------------------------------
/src/main/kotlin/com/github/encryptsl/lite/eco/common/hook/craftconomy3/CraftConomyHook.kt:
--------------------------------------------------------------------------------
1 | package com.github.encryptsl.lite.eco.common.hook.craftconomy3
2 |
3 | import com.github.encryptsl.lite.eco.LiteEco
4 | import com.github.encryptsl.lite.eco.common.hook.HookListener
5 | import com.github.encryptsl.lite.eco.common.hook.bettereconomy.BetterEconomyHook
6 | import com.github.encryptsl.lite.eco.common.hook.bettereconomy.BetterEconomyHook.Companion.isBetterEconomy
7 | import com.github.encryptsl.lite.eco.utils.ClassUtil
8 | import com.greatmancode.craftconomy3.Common
9 | import com.greatmancode.craftconomy3.account.AccountManager
10 |
11 | class CraftConomyHook(
12 | private val liteEco: LiteEco
13 | ) : HookListener(
14 | PLUGIN_NAME,
15 | "You can now export economy from plugin CraftConomy3 to LiteEco with /eco database import CraftConomy3 "
16 | ) {
17 | private lateinit var economyHandler: AccountManager
18 |
19 | companion object {
20 | const val PLUGIN_NAME = "CraftConomy3"
21 | fun isCraftEconomy(): Boolean
22 | = ClassUtil.isValidClasspath("com.greatmancode.craftconomy3.Common")
23 | }
24 |
25 | override fun canRegister(): Boolean {
26 | return !registered && liteEco.pluginManager.isPluginEnabled(BetterEconomyHook.Companion.PLUGIN_NAME)
27 | }
28 |
29 | override fun register() {
30 | if (isCraftEconomy()) {
31 | economyHandler = Common.getInstance().accountManager
32 | }
33 | registered = true
34 | }
35 |
36 | override fun unregister() {}
37 |
38 | fun getBalance(name: String, currency: String = "Dollar"): Double {
39 | if (!isBetterEconomy())
40 | throw Exception("Plugin BetterEconomy missing !")
41 | return economyHandler.getAccount(name, false).getBalance(null, currency)
42 | }
43 | }
--------------------------------------------------------------------------------
/src/main/kotlin/com/github/encryptsl/lite/eco/common/hook/miniplaceholder/EconomyMiniPlaceholder.kt:
--------------------------------------------------------------------------------
1 | package com.github.encryptsl.lite.eco.common.hook.miniplaceholder
2 |
3 | import com.github.encryptsl.lite.eco.LiteEco
4 | import io.github.miniplaceholders.kotlin.asInsertingTag
5 | import io.github.miniplaceholders.kotlin.expansion
6 | import net.kyori.adventure.text.Component
7 | import org.bukkit.OfflinePlayer
8 | import java.math.BigDecimal
9 | import java.util.*
10 |
11 |
12 | class EconomyMiniPlaceholder(private val liteEco: LiteEco) {
13 |
14 | fun register() {
15 | val expansion = expansion("lite-eco") {
16 | audiencePlaceholder("balance") { p, s, _ ->
17 | val player: OfflinePlayer = p as OfflinePlayer
18 | val currency = if (s.hasNext()) s.pop().value() else liteEco.currencyImpl.defaultCurrency()
19 | if (!liteEco.currencyImpl.getCurrencyNameExist(currency))
20 | return@audiencePlaceholder null
21 |
22 | return@audiencePlaceholder Component.text(liteEco.api.getBalance(player.uniqueId, currency).toPlainString()).asInsertingTag()
23 | }
24 | audiencePlaceholder("balance_formatted") { p, s, _ ->
25 | val player: OfflinePlayer = p as OfflinePlayer
26 | val currency = if (s.hasNext()) s.pop().value() else liteEco.currencyImpl.defaultCurrency()
27 | if (!liteEco.currencyImpl.getCurrencyNameExist(currency))
28 | return@audiencePlaceholder null
29 |
30 | return@audiencePlaceholder Component.text(liteEco.api.fullFormatting(liteEco.api.getBalance(player.uniqueId, currency))).asInsertingTag()
31 | }
32 | audiencePlaceholder("balance_compacted") { p, s, _ ->
33 | val player: OfflinePlayer = p as OfflinePlayer
34 | val currency = if (s.hasNext()) s.pop().value() else liteEco.currencyImpl.defaultCurrency()
35 | return@audiencePlaceholder Component.text(liteEco.api.fullFormatting(liteEco.api.getBalance(player.uniqueId, currency))).asInsertingTag()
36 | }
37 | globalPlaceholder("top_rank_player") { i, _ ->
38 | val currency = if (i.hasNext()) i.pop().value() else liteEco.currencyImpl.defaultCurrency()
39 | if (!liteEco.currencyImpl.getCurrencyNameExist(currency))
40 | return@globalPlaceholder null
41 |
42 | return@globalPlaceholder Component.text(nameByRank(1, currency)).asInsertingTag()
43 | }
44 | globalPlaceholder("total_balance") { i, _ ->
45 | val currency = if (i.hasNext()) i.pop().value() else liteEco.currencyImpl.defaultCurrency()
46 | if (!liteEco.currencyImpl.getCurrencyNameExist(currency))
47 | return@globalPlaceholder null
48 |
49 | return@globalPlaceholder Component.text(liteEco.currencyImpl.getCurrencyFormat(totalBalanceOfServerByCurrency(currency))).asInsertingTag()
50 | }
51 | globalPlaceholder("top_balance_formatted") { i, _ ->
52 | val argument = i.popOr("You need provide context").value().split("_")
53 | val rank = extractPlaceholderIdentifierName(0, argument).toInt()
54 | val currency = Optional.ofNullable(extractPlaceholderIdentifierName(1, argument)).orElse(liteEco.currencyImpl.defaultCurrency())
55 | if (!liteEco.currencyImpl.getCurrencyNameExist(currency))
56 | return@globalPlaceholder null
57 |
58 | return@globalPlaceholder Component.text(liteEco.api.fullFormatting(balanceByRank(rank, currency))).asInsertingTag()
59 | }
60 | globalPlaceholder("top_balance_compacted") { i, _ ->
61 | val argument = i.popOr("You need provide context").value().split("_")
62 | val rank = extractPlaceholderIdentifierName(0, argument).toInt()
63 | val currency = Optional.ofNullable(extractPlaceholderIdentifierName(1, argument)).orElse(liteEco.currencyImpl.defaultCurrency())
64 | if (!liteEco.currencyImpl.getCurrencyNameExist(currency))
65 | return@globalPlaceholder null
66 |
67 | return@globalPlaceholder Component.text(liteEco.api.compacted(balanceByRank(rank, currency))).asInsertingTag()
68 | }
69 | globalPlaceholder("top_balance") { i, _ ->
70 | val argument = i.popOr("You need provide context").value().split("_")
71 | val rank = extractPlaceholderIdentifierName(0, argument).toInt()
72 | val currency = Optional.ofNullable(extractPlaceholderIdentifierName(1, argument)).orElse(liteEco.currencyImpl.defaultCurrency())
73 | if (!liteEco.currencyImpl.getCurrencyNameExist(currency))
74 | return@globalPlaceholder null
75 |
76 | return@globalPlaceholder Component.text(balanceByRank(rank, currency).toPlainString()).asInsertingTag()
77 | }
78 | globalPlaceholder("top_player") { i, _ ->
79 | val argument = i.popOr("You need provide context").value().split("_")
80 | val rank = extractPlaceholderIdentifierName(0, argument).toInt()
81 | val currency = Optional.ofNullable(extractPlaceholderIdentifierName(1, argument)).orElse(liteEco.currencyImpl.defaultCurrency())
82 | if (!liteEco.currencyImpl.getCurrencyNameExist(currency))
83 | return@globalPlaceholder null
84 |
85 | return@globalPlaceholder Component.text(nameByRank(rank, currency)).asInsertingTag()
86 | }
87 | }
88 | expansion.register()
89 | }
90 |
91 | private fun extractPlaceholderIdentifierName(position: Int, list: List): String {
92 | return list[position]
93 | }
94 |
95 | private fun nameByRank(rank: Int, currency: String): String {
96 | val topBalance = topBalance(currency)
97 | return if (rank in 1..topBalance.size) {
98 | topBalance.keys.elementAt(rank - 1)
99 | } else {
100 | liteEco.config.getString("formatting.placeholders.empty-name", "EMPTY").toString()
101 | }
102 | }
103 |
104 | private fun balanceByRank(rank: Int, currency: String): BigDecimal {
105 | val topBalance = topBalance(currency)
106 | return if (rank in 1..topBalance.size) {
107 | topBalance.values.elementAt(rank - 1)
108 | } else {
109 | BigDecimal.ZERO
110 | }
111 | }
112 |
113 | private fun totalBalanceOfServerByCurrency(currency: String): String {
114 | return topBalance(currency).values.sumOf { it }.toString()
115 | }
116 |
117 | private fun topBalance(currency: String): Map {
118 | return liteEco.api.getTopBalance(currency)
119 | }
120 |
121 | }
--------------------------------------------------------------------------------
/src/main/kotlin/com/github/encryptsl/lite/eco/common/hook/miniplaceholder/MiniPlaceholdersHook.kt:
--------------------------------------------------------------------------------
1 | package com.github.encryptsl.lite.eco.common.hook.miniplaceholder
2 |
3 | import com.github.encryptsl.lite.eco.LiteEco
4 | import com.github.encryptsl.lite.eco.common.hook.HookListener
5 |
6 | class MiniPlaceholdersHook(
7 | val liteEco: LiteEco
8 | ) : HookListener(
9 | PLUGIN_NAME,
10 | "You can now use placeholders from https://github.com/EncryptSL/LiteEco/wiki/Placeholders#mini-available-placeholders"
11 | ) {
12 | companion object {
13 | const val PLUGIN_NAME = "MiniPlaceholders"
14 | }
15 |
16 | override fun canRegister(): Boolean {
17 | return !registered && liteEco.pluginManager.getPlugin(PLUGIN_NAME) != null
18 | }
19 |
20 | override fun register() {
21 | EconomyMiniPlaceholder(liteEco).register()
22 |
23 | registered = true
24 | }
25 |
26 | override fun unregister() {}
27 | }
--------------------------------------------------------------------------------
/src/main/kotlin/com/github/encryptsl/lite/eco/common/hook/placeholderapi/EconomyPlaceholderAPI.kt:
--------------------------------------------------------------------------------
1 | package com.github.encryptsl.lite.eco.common.hook.placeholderapi
2 |
3 | import com.github.encryptsl.lite.eco.LiteEco
4 | import me.clip.placeholderapi.expansion.PlaceholderExpansion
5 | import org.bukkit.OfflinePlayer
6 | import java.math.BigDecimal
7 | import java.util.*
8 |
9 | class EconomyPlaceholderAPI(private val liteEco: LiteEco, private val extVersion: String) : PlaceholderExpansion() {
10 |
11 | override fun getIdentifier(): String = "liteeco"
12 |
13 | override fun getAuthor(): String = "EncryptSL"
14 |
15 | override fun getVersion(): String = extVersion
16 |
17 | override fun getRequiredPlugin(): String = liteEco.name
18 |
19 | override fun persist(): Boolean = true
20 |
21 | override fun canRegister(): Boolean {
22 | return liteEco.server.pluginManager.isPluginEnabled(requiredPlugin)
23 | }
24 |
25 | override fun onRequest(player: OfflinePlayer?, identifier: String): String? {
26 | if (player == null) return null
27 | val args = identifier.split("_")
28 | val rank = args.getOrNull(2)?.toIntOrNull()
29 |
30 | return when (identifier) {
31 | "balance" -> liteEco.api.getBalance(player.uniqueId, liteEco.currencyImpl.defaultCurrency()).toString()
32 | "balance_formatted" -> liteEco.api.fullFormatting(liteEco.api.getBalance(player.uniqueId, liteEco.currencyImpl.defaultCurrency()))
33 | "balance_compacted" -> liteEco.api.compacted(liteEco.api.getBalance(player.uniqueId, liteEco.currencyImpl.defaultCurrency()))
34 | "top_rank_player" -> nameByRank(1, liteEco.currencyImpl.defaultCurrency())
35 | else -> {
36 | when {
37 | identifier.startsWith("balance_") -> {
38 | if (identifier.startsWith("balance_formatted_")) {
39 | val currency = extractPlaceholderIdentifierName(2, args)
40 | return liteEco.api.fullFormatting(liteEco.api.getBalance(player.uniqueId, currency), currency)
41 | }
42 |
43 | if (identifier.startsWith("balance_compacted_")) {
44 | val currency = extractPlaceholderIdentifierName(2, args)
45 | return liteEco.api.compacted(liteEco.api.getBalance(player.uniqueId, currency))
46 | }
47 | val currency = extractPlaceholderIdentifierName(1, args)
48 |
49 | return liteEco.api.getBalance(player.uniqueId, currency).toString()
50 | }
51 | identifier.startsWith("top_rank_player_") -> {
52 | val currency = extractPlaceholderIdentifierName(3, args)
53 | return nameByRank(1, currency)
54 | }
55 | identifier.startsWith("total_balance_") -> {
56 | val currency = extractPlaceholderIdentifierName(2, args)
57 | return liteEco.currencyImpl.getCurrencyFormat(totalBalanceOfServerByCurrency(currency))
58 | }
59 | }
60 | return rank?.let {
61 | when {
62 | identifier.startsWith("top_formatted_") -> {
63 | val currency = extractPlaceholderIdentifierName(3, args)
64 | return liteEco.api.fullFormatting(balanceByRank(rank, currency), currency)
65 | }
66 | identifier.startsWith("top_compacted_") -> {
67 | val currency = extractPlaceholderIdentifierName(3, args)
68 | return liteEco.api.compacted(balanceByRank(rank, currency))
69 | }
70 | identifier.startsWith("top_balance_") -> {
71 | val currency = extractPlaceholderIdentifierName(3, args)
72 | return balanceByRank(rank, currency).toString()
73 | }
74 | identifier.startsWith("top_player_") -> {
75 | val currency = extractPlaceholderIdentifierName(3, args)
76 | return nameByRank(rank, currency)
77 | }
78 | else -> null
79 | }
80 | }
81 | }
82 | }
83 | }
84 |
85 | private fun extractPlaceholderIdentifierName(position: Int, args: List): String {
86 | return Optional.ofNullable(args.getOrNull(position))
87 | .orElse(liteEco.currencyImpl.defaultCurrency())
88 | }
89 |
90 | private fun nameByRank(rank: Int, currency: String): String {
91 | val topBalance = topBalance(currency)
92 | return if (rank in 1..topBalance.size) {
93 | val name = topBalance.keys.elementAt(rank - 1)
94 | Optional.ofNullable(name).orElse("UNKNOWN")
95 | } else {
96 | liteEco.config.getString("formatting.placeholders.empty-name", "EMPTY").toString()
97 | }
98 | }
99 |
100 | private fun balanceByRank(rank: Int, currency: String): BigDecimal {
101 | val topBalance = topBalance(currency)
102 | return if (rank in 1..topBalance.size) {
103 | topBalance.values.elementAt(rank - 1)
104 | } else {
105 | BigDecimal.ZERO
106 | }
107 | }
108 |
109 | private fun totalBalanceOfServerByCurrency(currency: String): String {
110 | return topBalance(currency).values.sumOf { it }.toString()
111 | }
112 |
113 | private fun topBalance(currency: String): Map {
114 | return liteEco.api.getTopBalance(currency)
115 | }
116 | }
117 |
--------------------------------------------------------------------------------
/src/main/kotlin/com/github/encryptsl/lite/eco/common/hook/placeholderapi/PlaceholderAPIHook.kt:
--------------------------------------------------------------------------------
1 | package com.github.encryptsl.lite.eco.common.hook.placeholderapi
2 |
3 | import com.github.encryptsl.lite.eco.LiteEco
4 | import com.github.encryptsl.lite.eco.common.hook.HookListener
5 |
6 | class PlaceholderAPIHook(
7 | private val liteEco: LiteEco
8 | ) : HookListener(
9 | PLUGIN_NAME,
10 | "You can now use placeholders from https://github.com/EncryptSL/LiteEco/wiki/Placeholders#papi-available-placeholders"
11 | ) {
12 | companion object {
13 | const val PLUGIN_NAME = "PlaceholderAPI"
14 | }
15 |
16 | override fun canRegister(): Boolean {
17 | return !registered && liteEco.pluginManager.getPlugin(PLUGIN_NAME) != null
18 | }
19 |
20 | override fun register() {
21 | EconomyPlaceholderAPI(liteEco, LiteEco.PAPI_VERSION).register()
22 |
23 | registered = true
24 | }
25 |
26 | override fun unregister() {
27 | EconomyPlaceholderAPI(liteEco, LiteEco.PAPI_VERSION).unregister()
28 | }
29 | }
--------------------------------------------------------------------------------
/src/main/kotlin/com/github/encryptsl/lite/eco/common/hook/scruffyboy13/ScruffyboyEconomyHook.kt:
--------------------------------------------------------------------------------
1 | package com.github.encryptsl.lite.eco.common.hook.scruffyboy13
2 |
3 | import com.github.encryptsl.lite.eco.LiteEco
4 | import com.github.encryptsl.lite.eco.common.hook.HookListener
5 | import com.github.encryptsl.lite.eco.common.hook.bettereconomy.BetterEconomyHook.Companion.isBetterEconomy
6 | import com.github.encryptsl.lite.eco.common.hook.placeholderapi.PlaceholderAPIHook
7 | import com.github.encryptsl.lite.eco.utils.ClassUtil
8 | import me.scruffyboy13.Economy.EconomyMain
9 | import me.scruffyboy13.Economy.eco.Economy
10 | import java.util.*
11 |
12 | class ScruffyboyEconomyHook(
13 | private val liteEco: LiteEco
14 | ) : HookListener(
15 | PLUGIN_NAME,
16 | "You can now export economy from plugin Economy to LiteEco with /eco database import ScruffyboyEconomy "
17 | ) {
18 |
19 | private lateinit var economy: Economy
20 |
21 | companion object {
22 | const val PLUGIN_NAME = "Economy"
23 | fun isScruffyboyEconomy(): Boolean
24 | = ClassUtil.isValidClasspath("me.scruffyboy13.Economy.EconomyMain")
25 | }
26 |
27 | override fun canRegister(): Boolean {
28 | return !registered && liteEco.pluginManager.isPluginEnabled(PlaceholderAPIHook.PLUGIN_NAME)
29 | }
30 |
31 | override fun register() {
32 | if (isBetterEconomy()) {
33 | economy = EconomyMain.getEco()
34 | }
35 | registered = true
36 | }
37 |
38 | override fun unregister() {}
39 |
40 | fun getBalance(uuid: UUID): Double {
41 | if (!isScruffyboyEconomy())
42 | throw Exception("Plugin $PLUGIN_NAME missing !")
43 | return economy.getBalance(uuid).balance
44 | }
45 |
46 |
47 | }
--------------------------------------------------------------------------------
/src/main/kotlin/com/github/encryptsl/lite/eco/common/hook/vault/AdaptiveEconomyVaultAPI.kt:
--------------------------------------------------------------------------------
1 | package com.github.encryptsl.lite.eco.common.hook.vault
2 |
3 | import com.github.encryptsl.lite.eco.LiteEco
4 | import com.github.encryptsl.lite.eco.api.PlayerAccount
5 | import com.github.encryptsl.lite.eco.common.extensions.isApproachingZero
6 | import net.milkbowl.vault.economy.EconomyResponse
7 | import org.bukkit.OfflinePlayer
8 | import java.util.*
9 |
10 | class AdaptiveEconomyVaultAPI(private val liteEco: LiteEco) : DeprecatedEconomy() {
11 |
12 | companion object {
13 | private const val BANK_NOT_SUPPORTED_MESSAGE = "LiteEco does not support bank accounts!"
14 | }
15 |
16 | override fun isEnabled(): Boolean = liteEco.isEnabled
17 |
18 | override fun getName(): String = liteEco.name
19 |
20 | override fun hasBankSupport(): Boolean = false
21 |
22 | override fun fractionalDigits(): Int = -1
23 |
24 | override fun format(amount: Double): String = liteEco.api.fullFormatting(amount.toBigDecimal())
25 |
26 | override fun currencyNamePlural(): String? {
27 | return null
28 | }
29 |
30 | override fun currencyNameSingular(): String? {
31 | return null
32 | }
33 |
34 | override fun hasAccount(player: OfflinePlayer): Boolean {
35 | return liteEco.api.hasAccount(player.uniqueId)
36 | }
37 |
38 | override fun hasAccount(player: OfflinePlayer, worldName: String?): Boolean {
39 | return hasAccount(player)
40 | }
41 |
42 | override fun getBalance(player: OfflinePlayer?): Double {
43 | return try {
44 | player?.let {
45 | if (PlayerAccount.isPlayerOnline(it.uniqueId)) {
46 | liteEco.api.getBalance(it.uniqueId).toDouble()
47 | } else {
48 | liteEco.databaseEcoModel.getBalance(it.uniqueId, liteEco.currencyImpl.defaultCurrency()).toDouble()
49 | }
50 | } ?: 0.0
51 | } catch (_ : Exception) {
52 | return player?.let { Optional.ofNullable(liteEco.databaseEcoModel.getBalance(it.uniqueId, liteEco.currencyImpl.defaultCurrency()).toDouble()).orElse(0.0) } ?: 0.0
53 | }
54 | }
55 |
56 | override fun getBalance(player: OfflinePlayer, world: String?): Double {
57 | return this.getBalance(player)
58 | }
59 |
60 | override fun has(player: OfflinePlayer?, amount: Double): Boolean {
61 | return if(player != null) liteEco.api.has(player.uniqueId, liteEco.currencyImpl.defaultCurrency(), amount.toBigDecimal()) else false
62 | }
63 |
64 | override fun has(player: OfflinePlayer?, worldName: String?, amount: Double): Boolean {
65 | return has(player, amount)
66 | }
67 |
68 | override fun withdrawPlayer(player: OfflinePlayer?, amount: Double): EconomyResponse {
69 | liteEco.debugger.debug(AdaptiveEconomyVaultAPI::class.java, "try withdraw from ${player?.name} amount $amount")
70 | if (player == null || amount.toBigDecimal().isApproachingZero()) {
71 | return EconomyResponse(0.0, 0.0, EconomyResponse.ResponseType.FAILURE, null)
72 | }
73 |
74 | return if (has(player, amount)) {
75 | liteEco.debugger.debug(AdaptiveEconomyVaultAPI::class.java, "successfully withdraw ${player.name} from his balance ${getBalance(player)} amount $amount")
76 | liteEco.api.withDrawMoney(player.uniqueId, liteEco.currencyImpl.defaultCurrency(), amount.toBigDecimal())
77 | EconomyResponse(amount, getBalance(player), EconomyResponse.ResponseType.SUCCESS, null)
78 | } else {
79 | EconomyResponse(0.0, getBalance(player), EconomyResponse.ResponseType.FAILURE, null)
80 | }
81 | }
82 |
83 | override fun withdrawPlayer(player: OfflinePlayer?, worldName: String?, amount: Double): EconomyResponse {
84 | return withdrawPlayer(player, amount)
85 | }
86 |
87 | override fun depositPlayer(player: OfflinePlayer?, amount: Double): EconomyResponse {
88 | liteEco.debugger.debug(AdaptiveEconomyVaultAPI::class.java, "try deposit to ${player?.name} amount $amount")
89 | if (player == null || !hasAccount(player) || amount.toBigDecimal().isApproachingZero() || liteEco.api.getCheckBalanceLimit(player.uniqueId, getBalance(player).toBigDecimal(), amount = amount.toBigDecimal())) {
90 | return EconomyResponse(0.0, 0.0, EconomyResponse.ResponseType.FAILURE, null)
91 | }
92 |
93 | liteEco.debugger.debug(AdaptiveEconomyVaultAPI::class.java, "successfully deposit ${player.name} to his balance ${getBalance(player)} amount $amount")
94 | liteEco.api.depositMoney(player.uniqueId, liteEco.currencyImpl.defaultCurrency(), amount.toBigDecimal())
95 |
96 | return EconomyResponse(amount, getBalance(player), EconomyResponse.ResponseType.SUCCESS, null)
97 | }
98 |
99 | override fun depositPlayer(player: OfflinePlayer?, worldName: String?, amount: Double): EconomyResponse {
100 | return depositPlayer(player, amount)
101 | }
102 |
103 | override fun createPlayerAccount(player: OfflinePlayer?): Boolean {
104 | return liteEco.api.createAccount(player!!, liteEco.currencyImpl.defaultCurrency(), liteEco.currencyImpl.defaultStartBalance())
105 | }
106 |
107 | override fun createPlayerAccount(player: OfflinePlayer?, worldName: String?): Boolean {
108 | return createPlayerAccount(player)
109 | }
110 |
111 | override fun createBank(name: String?, player: OfflinePlayer?): EconomyResponse {
112 | return EconomyResponse(0.0, 0.0, EconomyResponse.ResponseType.NOT_IMPLEMENTED, BANK_NOT_SUPPORTED_MESSAGE)
113 | }
114 |
115 | override fun deleteBank(name: String?): EconomyResponse {
116 | return EconomyResponse(0.0, 0.0, EconomyResponse.ResponseType.NOT_IMPLEMENTED, BANK_NOT_SUPPORTED_MESSAGE)
117 | }
118 |
119 | override fun bankBalance(name: String?): EconomyResponse {
120 | return EconomyResponse(0.0, 0.0, EconomyResponse.ResponseType.NOT_IMPLEMENTED, BANK_NOT_SUPPORTED_MESSAGE)
121 | }
122 |
123 | override fun bankHas(name: String?, amount: Double): EconomyResponse {
124 | return EconomyResponse(0.0, 0.0, EconomyResponse.ResponseType.NOT_IMPLEMENTED, BANK_NOT_SUPPORTED_MESSAGE)
125 | }
126 |
127 | override fun bankWithdraw(name: String?, amount: Double): EconomyResponse {
128 | return EconomyResponse(0.0, 0.0, EconomyResponse.ResponseType.NOT_IMPLEMENTED, BANK_NOT_SUPPORTED_MESSAGE)
129 | }
130 |
131 | override fun bankDeposit(name: String?, amount: Double): EconomyResponse {
132 | return EconomyResponse(0.0, 0.0, EconomyResponse.ResponseType.NOT_IMPLEMENTED, BANK_NOT_SUPPORTED_MESSAGE)
133 | }
134 |
135 | override fun isBankOwner(name: String?, player: OfflinePlayer?): EconomyResponse {
136 | return EconomyResponse(0.0, 0.0, EconomyResponse.ResponseType.NOT_IMPLEMENTED, BANK_NOT_SUPPORTED_MESSAGE)
137 | }
138 |
139 | override fun isBankMember(name: String?, player: OfflinePlayer?): EconomyResponse {
140 | return EconomyResponse(0.0, 0.0, EconomyResponse.ResponseType.NOT_IMPLEMENTED, BANK_NOT_SUPPORTED_MESSAGE)
141 | }
142 |
143 | override fun getBanks(): MutableList {
144 | return Collections.emptyList()
145 | }
146 | }
--------------------------------------------------------------------------------
/src/main/kotlin/com/github/encryptsl/lite/eco/common/hook/vault/DeprecatedEconomy.kt:
--------------------------------------------------------------------------------
1 | package com.github.encryptsl.lite.eco.common.hook.vault
2 |
3 | import net.milkbowl.vault.economy.Economy
4 | import net.milkbowl.vault.economy.EconomyResponse
5 | import org.bukkit.Bukkit
6 |
7 | abstract class DeprecatedEconomy : Economy {
8 |
9 | companion object {
10 | private const val BANK_NOT_SUPPORTED_MESSAGE = "LiteEco does not support bank accounts!"
11 | }
12 |
13 | @Deprecated("Deprecated in Java", ReplaceWith("hasAccount(player)"))
14 | override fun hasAccount(playerName: String?): Boolean {
15 | return hasAccount(Bukkit.getOfflinePlayer(playerName.toString()))
16 | }
17 |
18 | @Deprecated("Deprecated in Java", ReplaceWith("hasAccount(player)"))
19 | override fun hasAccount(playerName: String?, worldName: String?): Boolean {
20 | return hasAccount(Bukkit.getOfflinePlayer(playerName.toString()))
21 | }
22 |
23 | @Deprecated("Deprecated in Java", ReplaceWith("getBalance(player)"))
24 | override fun getBalance(playerName: String?): Double {
25 | return getBalance(Bukkit.getOfflinePlayer(playerName.toString()))
26 | }
27 |
28 | @Deprecated("Deprecated in Java", ReplaceWith("getBalance(player)"))
29 | override fun getBalance(playerName: String?, world: String?): Double {
30 | return getBalance(Bukkit.getOfflinePlayer(playerName.toString()))
31 | }
32 |
33 | @Deprecated("Deprecated in Java", ReplaceWith("has(player, amount)"))
34 | override fun has(playerName: String?, amount: Double): Boolean {
35 | return has(Bukkit.getOfflinePlayer(playerName.toString()), amount)
36 | }
37 |
38 | @Deprecated("Deprecated in Java", ReplaceWith("has(player, amount)"))
39 | override fun has(playerName: String?, worldName: String?, amount: Double): Boolean {
40 | return has(Bukkit.getOfflinePlayer(playerName.toString()), amount)
41 | }
42 |
43 | @Deprecated("Deprecated in Java", ReplaceWith("withdrawPlayer(player, amount)"))
44 | override fun withdrawPlayer(playerName: String?, amount: Double): EconomyResponse {
45 | return withdrawPlayer(Bukkit.getOfflinePlayer(playerName.toString()), amount)
46 | }
47 |
48 | @Deprecated("Deprecated in Java", ReplaceWith("withdrawPlayer(player, amount)"))
49 | override fun withdrawPlayer(playerName: String?, worldName: String?, amount: Double): EconomyResponse {
50 | return withdrawPlayer(Bukkit.getOfflinePlayer(playerName.toString()), amount)
51 | }
52 |
53 | @Deprecated("Deprecated in Java", ReplaceWith("depositPlayer(player, amount)"))
54 | override fun depositPlayer(playerName: String?, amount: Double): EconomyResponse {
55 | return depositPlayer(Bukkit.getOfflinePlayer(playerName.toString()), amount)
56 | }
57 |
58 | @Deprecated("Deprecated in Java", ReplaceWith("depositPlayer(player, amount)"))
59 | override fun depositPlayer(playerName: String?, worldName: String?, amount: Double): EconomyResponse {
60 | return depositPlayer(Bukkit.getOfflinePlayer(playerName.toString()), amount)
61 | }
62 |
63 | @Deprecated("Deprecated in Java", ReplaceWith("createPlayerAccount(player)"))
64 | override fun createPlayerAccount(playerName: String?): Boolean {
65 | return createPlayerAccount(Bukkit.getOfflinePlayer(playerName.toString()))
66 | }
67 |
68 | @Deprecated("Deprecated in Java", ReplaceWith("createPlayerAccount(player)"))
69 | override fun createPlayerAccount(playerName: String?, worldName: String?): Boolean {
70 | return createPlayerAccount(Bukkit.getOfflinePlayer(playerName.toString()))
71 | }
72 |
73 | @Deprecated("Deprecated in Java", ReplaceWith("createBank(name, player)"))
74 | override fun createBank(name: String?, playerName: String?): EconomyResponse {
75 | return EconomyResponse(0.0, 0.0, EconomyResponse.ResponseType.NOT_IMPLEMENTED, BANK_NOT_SUPPORTED_MESSAGE)
76 | }
77 |
78 | @Deprecated("Deprecated in Java", ReplaceWith("isBankOwner(name, player)"))
79 | override fun isBankOwner(name: String?, playerName: String?): EconomyResponse {
80 | return EconomyResponse(0.0, 0.0, EconomyResponse.ResponseType.NOT_IMPLEMENTED, BANK_NOT_SUPPORTED_MESSAGE)
81 | }
82 |
83 | @Deprecated("Deprecated in Java", ReplaceWith("isBankMember(name, player)"))
84 | override fun isBankMember(name: String?, playerName: String?): EconomyResponse {
85 | return EconomyResponse(0.0, 0.0, EconomyResponse.ResponseType.NOT_IMPLEMENTED, BANK_NOT_SUPPORTED_MESSAGE)
86 | }
87 | }
--------------------------------------------------------------------------------
/src/main/kotlin/com/github/encryptsl/lite/eco/common/hook/vault/VaultHook.kt:
--------------------------------------------------------------------------------
1 | package com.github.encryptsl.lite.eco.common.hook.vault
2 |
3 | import com.github.encryptsl.lite.eco.LiteEco
4 | import com.github.encryptsl.lite.eco.common.hook.HookListener
5 | import com.github.encryptsl.lite.eco.common.hook.vault.unlocked.AdaptiveEconomyVaultUnlockedAPI
6 | import com.github.encryptsl.lite.eco.utils.ClassUtil
7 | import net.milkbowl.vault.economy.Economy
8 | import org.bukkit.plugin.ServicePriority
9 |
10 | class VaultHook(
11 | val liteEco: LiteEco
12 | ) : HookListener(
13 | PLUGIN_NAME,
14 | "You can now use Vault API !"
15 | ) {
16 |
17 | companion object {
18 | const val PLUGIN_NAME = "Vault"
19 |
20 | fun isVaultUnlocked(): Boolean
21 | = ClassUtil.isValidClasspath("net.milkbowl.vault2.economy.Economy")
22 | }
23 |
24 |
25 | override fun canRegister(): Boolean {
26 | return !registered && liteEco.pluginManager.getPlugin(PLUGIN_NAME) != null
27 | }
28 |
29 | override fun register() {
30 | if (isVaultUnlocked()) {
31 | liteEco.server.servicesManager.register(net.milkbowl.vault2.economy.Economy::class.java, AdaptiveEconomyVaultUnlockedAPI(liteEco), liteEco, ServicePriority.Highest)
32 | liteEco.componentLogger.info("You can now use modern VaultUnlocked API.")
33 | }
34 |
35 | liteEco.server.servicesManager.register(Economy::class.java, AdaptiveEconomyVaultAPI(liteEco), liteEco, ServicePriority.Highest)
36 | registered = true
37 | }
38 |
39 | override fun unregister() {
40 | liteEco.server.servicesManager.unregister(AdaptiveEconomyVaultAPI::class.java)
41 |
42 | if (isVaultUnlocked()) {
43 | liteEco.server.servicesManager.unregister(AdaptiveEconomyVaultUnlockedAPI::class.java)
44 | }
45 | }
46 | }
--------------------------------------------------------------------------------
/src/main/kotlin/com/github/encryptsl/lite/eco/common/hook/vault/unlocked/UnusedVaultUnlockedAPI.kt:
--------------------------------------------------------------------------------
1 | package com.github.encryptsl.lite.eco.common.hook.vault.unlocked
2 |
3 | import net.milkbowl.vault2.economy.AccountPermission
4 | import net.milkbowl.vault2.economy.Economy
5 | import net.milkbowl.vault2.economy.EconomyResponse
6 | import java.math.BigDecimal
7 | import java.util.*
8 |
9 | abstract class UnusedVaultUnlockedAPI : Economy {
10 | companion object {
11 | private const val SHARED_ACCOUNTS_NOT_SUPPORTED_MESSAGE = "LiteEco does not support shared accounts !"
12 | private const val PERMISSIONS_NOT_SUPPORTED_MESSAGE = "LiteEco does not support permissions operation!"
13 | }
14 |
15 | @Deprecated("Deprecated in Java", ReplaceWith("createAccount(accountID: UUID, name: String, player: Boolean)"))
16 | override fun createAccount(accountID: UUID, name: String): Boolean {
17 | return false
18 | }
19 |
20 | @Deprecated("Deprecated in Java", ReplaceWith("createAccount(accountID: UUID, name: String, worldName: String, player: Boolean)"))
21 | override fun createAccount(accountID: UUID, name: String, worldName: String): Boolean {
22 | return false
23 | }
24 |
25 | @Deprecated("Deprecated in Java", ReplaceWith("format(pluginName, amount)"))
26 | override fun format(amount: BigDecimal): String {
27 | return format("", amount)
28 | }
29 |
30 | @Deprecated("Deprecated in Java", ReplaceWith("format(pluginName, amount, currency)"))
31 | override fun format(amount: BigDecimal, currency: String): String {
32 | return format("pluginName", amount, currency)
33 | }
34 |
35 | override fun createSharedAccount(pluginName: String, accountID: UUID, name: String, owner: UUID): Boolean {
36 | return EconomyResponse(BigDecimal.ZERO, BigDecimal.ZERO, EconomyResponse.ResponseType.NOT_IMPLEMENTED, SHARED_ACCOUNTS_NOT_SUPPORTED_MESSAGE).transactionSuccess()
37 | }
38 |
39 | override fun hasSharedAccountSupport(): Boolean {
40 | return EconomyResponse(BigDecimal.ZERO, BigDecimal.ZERO, EconomyResponse.ResponseType.NOT_IMPLEMENTED, SHARED_ACCOUNTS_NOT_SUPPORTED_MESSAGE).transactionSuccess()
41 | }
42 |
43 | override fun isAccountOwner(pluginName: String, accountID: UUID, uuid: UUID): Boolean {
44 | return EconomyResponse(BigDecimal.ZERO, BigDecimal.ZERO, EconomyResponse.ResponseType.NOT_IMPLEMENTED, SHARED_ACCOUNTS_NOT_SUPPORTED_MESSAGE).transactionSuccess()
45 | }
46 |
47 | override fun setOwner(pluginName: String, accountID: UUID, uuid: UUID): Boolean {
48 | return EconomyResponse(BigDecimal.ZERO, BigDecimal.ZERO, EconomyResponse.ResponseType.NOT_IMPLEMENTED, SHARED_ACCOUNTS_NOT_SUPPORTED_MESSAGE).transactionSuccess()
49 | }
50 |
51 | override fun isAccountMember(pluginName: String, accountID: UUID, uuid: UUID): Boolean {
52 | return EconomyResponse(BigDecimal.ZERO, BigDecimal.ZERO, EconomyResponse.ResponseType.NOT_IMPLEMENTED, SHARED_ACCOUNTS_NOT_SUPPORTED_MESSAGE).transactionSuccess()
53 | }
54 |
55 | override fun addAccountMember(pluginName: String, accountID: UUID, uuid: UUID): Boolean {
56 | return EconomyResponse(BigDecimal.ZERO, BigDecimal.ZERO, EconomyResponse.ResponseType.NOT_IMPLEMENTED, SHARED_ACCOUNTS_NOT_SUPPORTED_MESSAGE).transactionSuccess()
57 | }
58 |
59 | override fun addAccountMember(pluginName: String, accountID: UUID, uuid: UUID, vararg initialPermissions: AccountPermission): Boolean {
60 | return EconomyResponse(BigDecimal.ZERO, BigDecimal.ZERO, EconomyResponse.ResponseType.NOT_IMPLEMENTED, SHARED_ACCOUNTS_NOT_SUPPORTED_MESSAGE).transactionSuccess()
61 | }
62 |
63 | override fun removeAccountMember(pluginName: String, accountID: UUID, uuid: UUID): Boolean {
64 | return EconomyResponse(BigDecimal.ZERO, BigDecimal.ZERO, EconomyResponse.ResponseType.NOT_IMPLEMENTED, SHARED_ACCOUNTS_NOT_SUPPORTED_MESSAGE).transactionSuccess()
65 | }
66 |
67 | override fun hasAccountPermission(pluginName: String, accountID: UUID, uuid: UUID, permission: AccountPermission): Boolean {
68 | return EconomyResponse(BigDecimal.ZERO, BigDecimal.ZERO, EconomyResponse.ResponseType.NOT_IMPLEMENTED, PERMISSIONS_NOT_SUPPORTED_MESSAGE).transactionSuccess()
69 | }
70 |
71 | override fun updateAccountPermission(
72 | pluginName: String,
73 | accountID: UUID,
74 | uuid: UUID,
75 | permission: AccountPermission,
76 | value: Boolean
77 | ): Boolean {
78 | return EconomyResponse(BigDecimal.ZERO, BigDecimal.ZERO, EconomyResponse.ResponseType.NOT_IMPLEMENTED, PERMISSIONS_NOT_SUPPORTED_MESSAGE).transactionSuccess()
79 | }
80 |
81 | }
--------------------------------------------------------------------------------
/src/main/kotlin/com/github/encryptsl/lite/eco/common/manager/ExportManager.kt:
--------------------------------------------------------------------------------
1 | package com.github.encryptsl.lite.eco.common.manager
2 |
3 | import com.github.encryptsl.lite.eco.LiteEco
4 | import com.github.encryptsl.lite.eco.api.enums.ExportKeys
5 | import com.github.encryptsl.lite.eco.api.migrator.CSVFileExporter
6 | import com.github.encryptsl.lite.eco.api.migrator.SQLFileExporter
7 | import com.github.encryptsl.lite.eco.api.migrator.entity.PlayerBalances
8 | import com.github.encryptsl.lite.eco.api.objects.ModernText
9 | import com.github.encryptsl.lite.eco.common.database.models.legacy.LegacyDatabaseEcoModel
10 | import com.github.encryptsl.lite.eco.common.extensions.positionIndexed
11 | import kotlinx.coroutines.runBlocking
12 | import net.kyori.adventure.text.minimessage.tag.resolver.Placeholder
13 | import net.kyori.adventure.text.minimessage.tag.resolver.TagResolver
14 | import org.bukkit.command.CommandSender
15 | import kotlin.system.measureTimeMillis
16 |
17 | class ExportManager(
18 | private val liteEco: LiteEco
19 | ) {
20 | fun export(sender: CommandSender, exportKeys: ExportKeys, currency: String) {
21 | try {
22 | runBlocking {
23 | val timer = measureTimeMillis {
24 | // This is better method to not crash server because data is exported from database and from game cache if is player connected and cached.
25 | val output = liteEco.api.getUUIDNameMap(currency.lowercase()).toList().positionIndexed { index, pair ->
26 | PlayerBalances.PlayerBalance(index, pair.first, pair.second, liteEco.api.getBalance(pair.first))
27 | }
28 |
29 | val result = when(exportKeys) {
30 | ExportKeys.CSV -> getCSVFileExporter("economy_migration", currency.lowercase()).exportToCSVFile(output)
31 | ExportKeys.SQL -> getSQLFileExporter("economy_migration", currency.lowercase()).exportToSQLFile(output)
32 | ExportKeys.LEGACY_TABLE -> getLegacyTableExporter(currency.lowercase()).exportToLiteEcoDollarsTable()
33 | ExportKeys.SQL_LITE_FILE -> getSQLFileExporter("economy_migration_sql_lite", currency.lowercase()).exportToSQLFileLite(output)
34 | }
35 |
36 | val messageKey = if (result) {
37 | "messages.admin.export_success"
38 | } else {
39 | "messages.error.export_failed"
40 | }
41 |
42 | sender.sendMessage(liteEco.locale.translation(messageKey, TagResolver.resolver(
43 | Placeholder.parsed("type", exportKeys.name), Placeholder.parsed("currency", currency)
44 | )))
45 | }
46 | liteEco.componentLogger.info(ModernText.miniModernText("Exporting of ${exportKeys.name} elapsed $timer ms"))
47 | }
48 | } catch (e : Exception) {
49 | liteEco.componentLogger.error(ModernText.miniModernText(e.message ?: e.localizedMessage))
50 | }
51 | }
52 |
53 | fun getSQLFileExporter(fileName: String, currency: String) = SQLFileExporter(liteEco, fileName, currency)
54 |
55 | fun getCSVFileExporter(fileName: String, currency: String) = CSVFileExporter(liteEco, fileName, currency)
56 |
57 | fun getLegacyTableExporter(currency: String) = LegacyDatabaseEcoModel(liteEco, currency)
58 |
59 | }
--------------------------------------------------------------------------------
/src/main/kotlin/com/github/encryptsl/lite/eco/common/manager/ImportManager.kt:
--------------------------------------------------------------------------------
1 | package com.github.encryptsl.lite.eco.common.manager
2 |
3 | import com.github.encryptsl.lite.eco.LiteEco
4 | import com.github.encryptsl.lite.eco.common.manager.importer.ImportEconomy
5 | import net.kyori.adventure.text.minimessage.tag.resolver.Placeholder
6 | import net.kyori.adventure.text.minimessage.tag.resolver.TagResolver
7 | import org.bukkit.command.CommandSender
8 |
9 | class ImportManager(
10 | private val liteEco: LiteEco,
11 | private val importEconomy: ImportEconomy
12 | ) {
13 |
14 | fun importEconomy(sender: CommandSender, economyName: String, currency: String) {
15 | val (converted, balances) = try {
16 | importEconomy.import(economyName, currency)
17 | } catch (_: IllegalArgumentException) {
18 | sender.sendMessage(liteEco.locale.translation("messages.error.import_failed"))
19 | return
20 | }
21 |
22 | if (converted == 0) {
23 | sender.sendMessage(liteEco.locale.translation("messages.error.import_failed"))
24 | return
25 | }
26 |
27 | sender.sendMessage(
28 | liteEco.locale.translation(
29 | "messages.admin.import_success",
30 | TagResolver.resolver(
31 | Placeholder.parsed("economy", economyName),
32 | Placeholder.parsed("converted", converted.toString()),
33 | Placeholder.parsed("balances", balances.toPlainString())
34 | )
35 | )
36 | )
37 | }
38 |
39 | }
--------------------------------------------------------------------------------
/src/main/kotlin/com/github/encryptsl/lite/eco/common/manager/MonologManager.kt:
--------------------------------------------------------------------------------
1 | package com.github.encryptsl.lite.eco.common.manager
2 |
3 | import com.github.encryptsl.lite.eco.LiteEco
4 | import com.github.encryptsl.lite.eco.api.ComponentPaginator
5 | import com.github.encryptsl.lite.eco.utils.Helper
6 | import kotlinx.coroutines.launch
7 | import net.kyori.adventure.text.minimessage.tag.resolver.Placeholder
8 | import org.bukkit.command.CommandSender
9 |
10 | class MonologManager(
11 | private val liteEco: LiteEco,
12 | private val helper: Helper
13 | ) {
14 |
15 | fun displayMonolog(sender: CommandSender, parameter: String, page: Int) {
16 | liteEco.pluginScope.launch {
17 | val log = helper.validateLog(parameter)
18 | val pagination = ComponentPaginator(log) {
19 | selectedPage = page
20 | itemsPerPage = 10
21 | headerFormat = liteEco.locale.getMessage("messages.monolog.header")
22 | navigationFormat = liteEco.locale.getMessage("messages.monolog.footer")
23 | }
24 |
25 | if (pagination.isAboveMaxPage(page))
26 | return@launch sender.sendMessage(liteEco.locale.translation("messages.error.maximum_page",
27 | Placeholder.parsed("max_page", pagination.maxPages.toString()))
28 | )
29 | pagination.header("").let { sender.sendMessage(it) }
30 | pagination.display().forEach {
31 | sender.sendMessage(it)
32 | }
33 | sender.sendMessage(pagination.navigationBar("eco monolog", parameter))
34 | }
35 | }
36 | }
--------------------------------------------------------------------------------
/src/main/kotlin/com/github/encryptsl/lite/eco/common/manager/PurgeManager.kt:
--------------------------------------------------------------------------------
1 | package com.github.encryptsl.lite.eco.common.manager
2 |
3 | import com.github.encryptsl.lite.eco.LiteEco
4 | import com.github.encryptsl.lite.eco.api.enums.PurgeKey
5 | import kotlinx.coroutines.launch
6 | import net.kyori.adventure.text.minimessage.tag.resolver.Placeholder
7 | import org.bukkit.command.CommandSender
8 |
9 | class PurgeManager(private val liteEco: LiteEco) {
10 |
11 | fun purge(sender: CommandSender, purgeKey: PurgeKey, currency: String) {
12 | liteEco.pluginScope.launch {
13 | @Suppress("REDUNDANT_ELSE_IN_WHEN")
14 | when (purgeKey) {
15 | PurgeKey.ACCOUNTS -> {
16 | liteEco.suspendApiWrapper.purgeAccounts(currency)
17 | sender.sendMessage(liteEco.locale.translation("messages.admin.purge_accounts"))
18 | }
19 | PurgeKey.NULL_ACCOUNTS -> {
20 | liteEco.suspendApiWrapper.purgeInvalidAccounts(currency)
21 | sender.sendMessage(liteEco.locale.translation("messages.admin.purge_null_accounts"))
22 | }
23 | PurgeKey.DEFAULT_ACCOUNTS -> {
24 | liteEco.suspendApiWrapper.purgeDefaultAccounts(currency,liteEco.currencyImpl.getCurrencyStartBalance(currency))
25 | sender.sendMessage(liteEco.locale.translation("messages.admin.purge_default_accounts"))
26 | }
27 | PurgeKey.MONO_LOG -> {
28 | val monolog = liteEco.loggerModel.getLog()
29 | if (monolog.isEmpty()) {
30 | return@launch sender.sendMessage(liteEco.locale.translation("messages.error.purge_monolog_fail"))
31 | }
32 | liteEco.loggerModel.clearLogs()
33 | sender.sendMessage(liteEco.locale.translation("messages.admin.purge_monolog_success", Placeholder.parsed("deleted", monolog.size.toString())))
34 | }
35 | else -> {
36 | sender.sendMessage(liteEco.locale.translation("messages.error.purge_argument"))
37 | }
38 | }
39 | }
40 | }
41 |
42 | }
--------------------------------------------------------------------------------
/src/main/kotlin/com/github/encryptsl/lite/eco/common/manager/importer/EconomyImportResults.kt:
--------------------------------------------------------------------------------
1 | package com.github.encryptsl.lite.eco.common.manager.importer
2 |
3 | import java.math.BigDecimal
4 |
5 | data class EconomyImportResults(
6 | val converted: Int,
7 | val balances: BigDecimal
8 | )
--------------------------------------------------------------------------------
/src/main/kotlin/com/github/encryptsl/lite/eco/common/manager/importer/ImportEconomy.kt:
--------------------------------------------------------------------------------
1 | package com.github.encryptsl.lite.eco.common.manager.importer
2 |
3 | import com.github.encryptsl.lite.eco.LiteEco
4 | import com.github.encryptsl.lite.eco.api.interfaces.EconomyImporter
5 | import com.github.encryptsl.lite.eco.common.manager.importer.economies.BetterEconomyImporter
6 | import com.github.encryptsl.lite.eco.common.manager.importer.economies.CraftConomy3Importer
7 | import com.github.encryptsl.lite.eco.common.manager.importer.economies.EssentialsXImporter
8 | import com.github.encryptsl.lite.eco.common.manager.importer.economies.ScruffyBoyImporter
9 | import org.bukkit.Bukkit
10 |
11 | class ImportEconomy(private val liteEco: LiteEco) {
12 |
13 | private val offlinePlayers = Bukkit.getOfflinePlayers()
14 | private val importers = mutableMapOf()
15 |
16 | init {
17 | registerImporter(EssentialsXImporter())
18 | registerImporter(BetterEconomyImporter())
19 | registerImporter(ScruffyBoyImporter())
20 | registerImporter(CraftConomy3Importer())
21 | }
22 |
23 | private fun registerImporter(importer: EconomyImporter) {
24 | importers[importer.name] = importer
25 | }
26 |
27 | fun import(pluginName: String, currency: String): EconomyImportResults {
28 | val importer = importers[pluginName] ?: throw IllegalArgumentException("Importer $pluginName not found")
29 | return importer.import(currency, liteEco, offlinePlayers)
30 | }
31 |
32 | fun getAvailableImporters(): Set = importers.keys
33 | }
--------------------------------------------------------------------------------
/src/main/kotlin/com/github/encryptsl/lite/eco/common/manager/importer/economies/BetterEconomyImporter.kt:
--------------------------------------------------------------------------------
1 | package com.github.encryptsl.lite.eco.common.manager.importer.economies
2 |
3 | import com.github.encryptsl.lite.eco.LiteEco
4 | import com.github.encryptsl.lite.eco.api.interfaces.EconomyImporter
5 | import com.github.encryptsl.lite.eco.common.hook.bettereconomy.BetterEconomyHook
6 | import com.github.encryptsl.lite.eco.common.manager.importer.EconomyImportResults
7 | import org.bukkit.OfflinePlayer
8 | import java.math.BigDecimal
9 |
10 | class BetterEconomyImporter : EconomyImporter {
11 | override val name = "BetterEconomy"
12 |
13 | override fun import(currency: String, liteEco: LiteEco, offlinePlayers: Array): EconomyImportResults {
14 | var converted = 0
15 | var balances = BigDecimal.ZERO
16 |
17 | try {
18 | val betterEconomy = BetterEconomyHook(liteEco)
19 | for (p in offlinePlayers) {
20 | val balance = BigDecimal.valueOf(betterEconomy.getBalance(p.uniqueId))
21 | if (liteEco.api.createAccount(p, currency, balance)) {
22 | balances += balance
23 | converted++
24 | }
25 | }
26 | } catch (e: Exception) {
27 | liteEco.logger.severe("BetterEconomy import error: ${e.message ?: e.localizedMessage}")
28 | }
29 |
30 | return EconomyImportResults(converted, balances)
31 | }
32 | }
--------------------------------------------------------------------------------
/src/main/kotlin/com/github/encryptsl/lite/eco/common/manager/importer/economies/CraftConomy3Importer.kt:
--------------------------------------------------------------------------------
1 | package com.github.encryptsl.lite.eco.common.manager.importer.economies
2 |
3 | import com.github.encryptsl.lite.eco.LiteEco
4 | import com.github.encryptsl.lite.eco.api.interfaces.EconomyImporter
5 | import com.github.encryptsl.lite.eco.common.hook.craftconomy3.CraftConomyHook
6 | import com.github.encryptsl.lite.eco.common.manager.importer.EconomyImportResults
7 | import org.bukkit.OfflinePlayer
8 | import java.math.BigDecimal
9 |
10 | class CraftConomy3Importer : EconomyImporter {
11 |
12 | override val name = "CraftConomy3"
13 |
14 | override fun import(currency: String, liteEco: LiteEco, offlinePlayers: Array): EconomyImportResults {
15 | var converted = 0
16 | var balances = BigDecimal.ZERO
17 |
18 | try {
19 | val craftConomy = CraftConomyHook(liteEco)
20 | for (p in offlinePlayers) {
21 | val balance = BigDecimal.valueOf(craftConomy.getBalance(p.name.toString())) // Pozor na getName() vs. name
22 | if (liteEco.api.createAccount(p, currency, balance)) {
23 | balances += balance
24 | converted++
25 | }
26 | }
27 | } catch (e: Exception) {
28 | liteEco.logger.severe("CraftConomy3 import error: ${e.message ?: e.localizedMessage}")
29 | }
30 |
31 | return EconomyImportResults(converted, balances)
32 | }
33 | }
--------------------------------------------------------------------------------
/src/main/kotlin/com/github/encryptsl/lite/eco/common/manager/importer/economies/EssentialsXImporter.kt:
--------------------------------------------------------------------------------
1 | package com.github.encryptsl.lite.eco.common.manager.importer.economies
2 |
3 | import com.github.encryptsl.lite.eco.LiteEco
4 | import com.github.encryptsl.lite.eco.api.interfaces.EconomyImporter
5 | import com.github.encryptsl.lite.eco.common.manager.importer.EconomyImportResults
6 | import org.bukkit.OfflinePlayer
7 | import org.bukkit.configuration.file.YamlConfiguration
8 | import java.io.File
9 | import java.math.BigDecimal
10 |
11 | class EssentialsXImporter : EconomyImporter {
12 |
13 | override val name: String = "EssentialsX"
14 |
15 | override fun import(
16 | currency: String,
17 | liteEco: LiteEco,
18 | offlinePlayers: Array
19 | ): EconomyImportResults {
20 | var converted = 0
21 | var balances = BigDecimal.ZERO
22 |
23 | for (p in offlinePlayers) {
24 | val playerFile = File("plugins/Essentials/userdata/", "${p.uniqueId}.yml")
25 | if (playerFile.exists()) {
26 | val config = YamlConfiguration.loadConfiguration(playerFile)
27 | val balance = config.getString("money")?.toBigDecimalOrNull() ?: BigDecimal.ZERO
28 | if (liteEco.api.createAccount(p, currency, balance)) {
29 | converted++
30 | balances += balance
31 | }
32 | }
33 | }
34 |
35 | return EconomyImportResults(converted, balances)
36 | }
37 | }
--------------------------------------------------------------------------------
/src/main/kotlin/com/github/encryptsl/lite/eco/common/manager/importer/economies/ScruffyBoyImporter.kt:
--------------------------------------------------------------------------------
1 | package com.github.encryptsl.lite.eco.common.manager.importer.economies
2 |
3 | import com.github.encryptsl.lite.eco.LiteEco
4 | import com.github.encryptsl.lite.eco.api.interfaces.EconomyImporter
5 | import com.github.encryptsl.lite.eco.common.hook.scruffyboy13.ScruffyboyEconomyHook
6 | import com.github.encryptsl.lite.eco.common.manager.importer.EconomyImportResults
7 | import org.bukkit.OfflinePlayer
8 | import java.math.BigDecimal
9 |
10 | class ScruffyBoyImporter : EconomyImporter {
11 | override val name = "ScruffyBoyEconomy"
12 |
13 | override fun import(currency: String, liteEco: LiteEco, offlinePlayers: Array): EconomyImportResults {
14 | var converted = 0
15 | var balances = BigDecimal.ZERO
16 |
17 | try {
18 | val scruffyboyEconomy = ScruffyboyEconomyHook(liteEco)
19 | for (p in offlinePlayers) {
20 | val balance = BigDecimal.valueOf(scruffyboyEconomy.getBalance(p.uniqueId))
21 | if (liteEco.api.createAccount(p, currency, balance)) {
22 | balances += balance
23 | converted++
24 | }
25 | }
26 | } catch (e: Exception) {
27 | liteEco.logger.severe("ScruffyBoy import error: ${e.message ?: e.localizedMessage}")
28 | }
29 |
30 | return EconomyImportResults(converted, balances)
31 | }
32 | }
--------------------------------------------------------------------------------
/src/main/kotlin/com/github/encryptsl/lite/eco/listeners/PlayerAsyncPreLoginListener.kt:
--------------------------------------------------------------------------------
1 | package com.github.encryptsl.lite.eco.listeners
2 |
3 | import com.github.encryptsl.lite.eco.LiteEco
4 | import org.bukkit.event.EventHandler
5 | import org.bukkit.event.Listener
6 | import org.bukkit.event.player.AsyncPlayerPreLoginEvent
7 |
8 | class PlayerAsyncPreLoginListener(
9 | private val liteEco: LiteEco
10 | ) : Listener {
11 |
12 | @EventHandler
13 | fun onPreLogin(event: AsyncPlayerPreLoginEvent) {
14 | val uuid = event.uniqueId
15 | val username = event.name
16 | liteEco.accountManager.createAccount(uuid, username)
17 | }
18 |
19 | }
--------------------------------------------------------------------------------
/src/main/kotlin/com/github/encryptsl/lite/eco/listeners/PlayerEconomyPayListener.kt:
--------------------------------------------------------------------------------
1 | package com.github.encryptsl.lite.eco.listeners
2 |
3 | import com.github.encryptsl.lite.eco.LiteEco
4 | import com.github.encryptsl.lite.eco.api.economy.EconomyOperations
5 | import com.github.encryptsl.lite.eco.api.events.PlayerEconomyPayEvent
6 | import kotlinx.coroutines.launch
7 | import net.kyori.adventure.text.minimessage.tag.resolver.Placeholder
8 | import net.kyori.adventure.text.minimessage.tag.resolver.TagResolver
9 | import org.bukkit.OfflinePlayer
10 | import org.bukkit.entity.Player
11 | import org.bukkit.event.EventHandler
12 | import org.bukkit.event.Listener
13 | import java.math.BigDecimal
14 | import kotlin.jvm.optionals.getOrNull
15 |
16 | class PlayerEconomyPayListener(private val liteEco: LiteEco) : Listener {
17 | @EventHandler
18 | fun onEconomyPay(event: PlayerEconomyPayEvent) {
19 | val sender: Player = event.sender
20 | val target: OfflinePlayer = event.target
21 | val money: BigDecimal = event.money
22 | val currency: String = event.currency
23 |
24 | liteEco.pluginScope.launch {
25 | val user = liteEco.suspendApiWrapper.getUserByUUID(target.uniqueId, currency).getOrNull()
26 | if (user == null) {
27 | sender.sendMessage(liteEco.locale.translation("messages.error.account_not_exist",
28 | Placeholder.parsed("account", target.name.toString())
29 | ))
30 | return@launch
31 | }
32 |
33 | if (!liteEco.api.has(sender.uniqueId, currency, money))
34 | return@launch sender.sendMessage(liteEco.locale.translation("messages.error.insufficient_funds"))
35 |
36 | if (liteEco.api.getCheckBalanceLimit(target.uniqueId, user.money, currency, money)) {
37 | sender.sendMessage(liteEco.locale.translation("messages.error.balance_above_limit",
38 | Placeholder.parsed("account", target.name.toString())
39 | ))
40 | return@launch
41 | }
42 |
43 | liteEco.loggerModel.logging(EconomyOperations.TRANSFER,
44 | sender.name, target.name.toString(), currency, user.money, user.money.plus(money)
45 | )
46 | liteEco.suspendApiWrapper.transfer(sender.uniqueId, target.uniqueId, currency, money)
47 | }
48 |
49 | sender.sendMessage(liteEco.locale.translation("messages.sender.add_money", TagResolver.resolver(
50 | Placeholder.parsed("target", target.name.toString()),
51 | Placeholder.parsed("money", liteEco.api.fullFormatting(money, currency)),
52 | Placeholder.parsed("currency", liteEco.currencyImpl.currencyModularNameConvert(currency, money))
53 | )))
54 |
55 | liteEco.increaseTransactions(1)
56 |
57 | if (target.isOnline) {
58 | target.player?.sendMessage(liteEco.locale.translation("messages.target.add_money", TagResolver.resolver(
59 | Placeholder.parsed("sender", sender.name),
60 | Placeholder.parsed("money", liteEco.api.fullFormatting(money, currency)),
61 | Placeholder.parsed("currency", liteEco.currencyImpl.currencyModularNameConvert(currency, money))
62 | )))
63 | }
64 | }
65 | }
--------------------------------------------------------------------------------
/src/main/kotlin/com/github/encryptsl/lite/eco/listeners/PlayerJoinListener.kt:
--------------------------------------------------------------------------------
1 | package com.github.encryptsl.lite.eco.listeners
2 |
3 | import com.github.encryptsl.lite.eco.LiteEco
4 | import org.bukkit.entity.Player
5 | import org.bukkit.event.EventHandler
6 | import org.bukkit.event.Listener
7 | import org.bukkit.event.player.PlayerJoinEvent
8 |
9 | class PlayerJoinListener(private val liteEco: LiteEco) : Listener {
10 |
11 | @EventHandler
12 | fun onJoin(event: PlayerJoinEvent) {
13 | val player: Player = event.player
14 | liteEco.accountManager.cachingAccount(player.uniqueId)
15 | }
16 | }
--------------------------------------------------------------------------------
/src/main/kotlin/com/github/encryptsl/lite/eco/listeners/PlayerQuitListener.kt:
--------------------------------------------------------------------------------
1 | package com.github.encryptsl.lite.eco.listeners
2 |
3 | import com.github.encryptsl.lite.eco.LiteEco
4 | import org.bukkit.event.EventHandler
5 | import org.bukkit.event.Listener
6 | import org.bukkit.event.player.PlayerQuitEvent
7 |
8 | class PlayerQuitListener(private val liteEco: LiteEco) : Listener {
9 |
10 | @EventHandler
11 | fun onQuit(event: PlayerQuitEvent) {
12 | val player = event.player
13 | liteEco.accountManager.syncAccount(player.uniqueId)
14 | }
15 |
16 | }
--------------------------------------------------------------------------------
/src/main/kotlin/com/github/encryptsl/lite/eco/listeners/admin/EconomyGlobalDepositListener.kt:
--------------------------------------------------------------------------------
1 | package com.github.encryptsl.lite.eco.listeners.admin
2 |
3 | import com.github.encryptsl.lite.eco.LiteEco
4 | import com.github.encryptsl.lite.eco.api.economy.EconomyOperations
5 | import com.github.encryptsl.lite.eco.api.events.admin.EconomyGlobalDepositEvent
6 | import kotlinx.coroutines.launch
7 | import net.kyori.adventure.text.minimessage.tag.resolver.Placeholder
8 | import net.kyori.adventure.text.minimessage.tag.resolver.TagResolver
9 | import org.bukkit.Bukkit
10 | import org.bukkit.command.CommandSender
11 | import org.bukkit.event.EventHandler
12 | import org.bukkit.event.Listener
13 | import kotlin.jvm.optionals.getOrNull
14 |
15 | class EconomyGlobalDepositListener(private val liteEco: LiteEco) : Listener {
16 |
17 | @EventHandler
18 | fun onAdminEconomyGlobalDeposit(event: EconomyGlobalDepositEvent) {
19 | val sender: CommandSender = event.commandSender
20 | val currency = event.currency
21 | val money = event.money
22 | val players = event.players
23 |
24 | if (liteEco.api.getUUIDNameMap(currency).isEmpty())
25 | return sender.sendMessage(liteEco.locale.translation("messages.error.database_exception", Placeholder.parsed("exception", "Collection is empty !")))
26 |
27 | if (liteEco.api.getCheckBalanceLimit(money) && !sender.hasPermission("lite.eco.admin.bypass.limit"))
28 | return sender.sendMessage(liteEco.locale.translation("messages.error.amount_above_limit"))
29 |
30 | liteEco.pluginScope.launch {
31 | players.forEach { player ->
32 | val user = liteEco.suspendApiWrapper
33 | .getUserByUUID(player.uniqueId, currency)
34 | .getOrNull()
35 |
36 | user?.takeIf { u ->
37 | !liteEco.api.getCheckBalanceLimit(u.uuid, u.money, currency, money)
38 | }?.also { u ->
39 | with(liteEco) {
40 | loggerModel.logging(
41 | EconomyOperations.DEPOSIT,
42 | sender.name,
43 | u.userName,
44 | currency,
45 | u.money,
46 | u.money + money
47 | )
48 | suspendApiWrapper.deposit(u.uuid, currency, money)
49 | }
50 | }
51 | }
52 | }
53 |
54 | liteEco.increaseTransactions(players.size)
55 |
56 | sender.sendMessage(
57 | liteEco.locale.translation("messages.global.add_money", TagResolver.resolver(
58 | Placeholder.parsed("money", liteEco.api.fullFormatting(money)),
59 | Placeholder.parsed("currency", liteEco.currencyImpl.currencyModularNameConvert(currency, money))
60 | )
61 | ))
62 | if (liteEco.config.getBoolean("messages.global.notify_add")) {
63 | Bukkit.broadcast(liteEco.locale.translation("messages.broadcast.add_money", TagResolver.resolver(
64 | Placeholder.parsed("sender", sender.name),
65 | Placeholder.parsed("money", liteEco.api.fullFormatting(money, currency)),
66 | Placeholder.parsed("currency", liteEco.currencyImpl.currencyModularNameConvert(currency, money))
67 | )))
68 | }
69 | }
70 |
71 | }
--------------------------------------------------------------------------------
/src/main/kotlin/com/github/encryptsl/lite/eco/listeners/admin/EconomyGlobalSetListener.kt:
--------------------------------------------------------------------------------
1 | package com.github.encryptsl.lite.eco.listeners.admin
2 |
3 | import com.github.encryptsl.lite.eco.LiteEco
4 | import com.github.encryptsl.lite.eco.api.economy.EconomyOperations
5 | import com.github.encryptsl.lite.eco.api.events.admin.EconomyGlobalSetEvent
6 | import kotlinx.coroutines.launch
7 | import net.kyori.adventure.text.minimessage.tag.resolver.Placeholder
8 | import net.kyori.adventure.text.minimessage.tag.resolver.TagResolver
9 | import org.bukkit.Bukkit
10 | import org.bukkit.command.CommandSender
11 | import org.bukkit.event.EventHandler
12 | import org.bukkit.event.Listener
13 | import kotlin.jvm.optionals.getOrNull
14 |
15 | class EconomyGlobalSetListener(private val liteEco: LiteEco) : Listener {
16 | @EventHandler
17 | fun onAdminEconomyGlobalSet(event: EconomyGlobalSetEvent) {
18 | val sender: CommandSender = event.commandSender
19 | val currency = event.currency
20 | val money = event.money
21 | val players = event.players
22 |
23 | if (liteEco.api.getUUIDNameMap(currency).isEmpty())
24 | return sender.sendMessage(liteEco.locale.translation("messages.error.database_exception", Placeholder.parsed("exception", "Collection is empty !")))
25 |
26 | if (liteEco.api.getCheckBalanceLimit(money) && !sender.hasPermission("lite.eco.admin.bypass.limit"))
27 | return sender.sendMessage(liteEco.locale.translation("messages.error.amount_above_limit"))
28 |
29 | liteEco.pluginScope.launch {
30 | players.forEach { player ->
31 | val user = liteEco.suspendApiWrapper
32 | .getUserByUUID(player.uniqueId, currency)
33 | .getOrNull()
34 |
35 | user?.also { u ->
36 | with(liteEco) {
37 | loggerModel.logging(
38 | EconomyOperations.SET,
39 | sender.name,
40 | u.userName,
41 | currency,
42 | u.money,
43 | money
44 | )
45 | suspendApiWrapper.set(player.uniqueId, currency, money)
46 | }
47 | }
48 | }
49 | }
50 |
51 | liteEco.increaseTransactions(players.size)
52 |
53 | sender.sendMessage(liteEco.locale.translation("messages.global.set_money", TagResolver.resolver(
54 | Placeholder.parsed("money", liteEco.api.fullFormatting(money, currency)),
55 | Placeholder.parsed("currency", liteEco.currencyImpl.currencyModularNameConvert(currency, money))
56 | )))
57 |
58 | if (liteEco.config.getBoolean("messages.global.notify_set")) {
59 | Bukkit.broadcast(liteEco.locale.translation("messages.broadcast.set_money", TagResolver.resolver(
60 | Placeholder.parsed("sender", sender.name),
61 | Placeholder.parsed("money", liteEco.api.fullFormatting(money)),
62 | Placeholder.parsed("currency", liteEco.currencyImpl.currencyModularNameConvert(currency, money))
63 | )))
64 | }
65 | }
66 | }
--------------------------------------------------------------------------------
/src/main/kotlin/com/github/encryptsl/lite/eco/listeners/admin/EconomyGlobalWithdrawListener.kt:
--------------------------------------------------------------------------------
1 | package com.github.encryptsl.lite.eco.listeners.admin
2 |
3 | import com.github.encryptsl.lite.eco.LiteEco
4 | import com.github.encryptsl.lite.eco.api.economy.EconomyOperations
5 | import com.github.encryptsl.lite.eco.api.events.admin.EconomyGlobalWithdrawEvent
6 | import kotlinx.coroutines.launch
7 | import net.kyori.adventure.text.minimessage.tag.resolver.Placeholder
8 | import net.kyori.adventure.text.minimessage.tag.resolver.TagResolver
9 | import org.bukkit.Bukkit
10 | import org.bukkit.command.CommandSender
11 | import org.bukkit.event.EventHandler
12 | import org.bukkit.event.Listener
13 | import kotlin.jvm.optionals.getOrNull
14 |
15 | class EconomyGlobalWithdrawListener(private val liteEco: LiteEco) : Listener {
16 | @EventHandler
17 | fun onAdminEconomyGlobalWithdraw(event: EconomyGlobalWithdrawEvent) {
18 | val sender: CommandSender = event.commandSender
19 | val currency = event.currency
20 | val money = event.money
21 | val players = event.players
22 |
23 | if (liteEco.api.getUUIDNameMap(currency).isEmpty())
24 | return sender.sendMessage(liteEco.locale.translation("messages.error.database_exception", Placeholder.parsed("exception", "Collection is empty !")))
25 |
26 | liteEco.pluginScope.launch {
27 | players.forEach { player ->
28 | val user = liteEco.suspendApiWrapper
29 | .getUserByUUID(player.uniqueId, currency)
30 | .getOrNull()
31 | user?.also { u ->
32 | with(liteEco) {
33 | loggerModel.logging(
34 | EconomyOperations.WITHDRAW,
35 | sender.name,
36 | u.userName,
37 | currency,
38 | u.money,
39 | u.money - money
40 | )
41 | suspendApiWrapper.withdraw(u.uuid, currency, money)
42 | }
43 | }
44 | }
45 | }
46 |
47 | liteEco.increaseTransactions(players.size)
48 |
49 | sender.sendMessage(
50 | liteEco.locale.translation("messages.global.withdraw_money",
51 | TagResolver.resolver(
52 | Placeholder.parsed("money", liteEco.api.fullFormatting(money)),
53 | Placeholder.parsed("currency", liteEco.currencyImpl.currencyModularNameConvert(currency, money))
54 | )
55 | ))
56 | if (liteEco.config.getBoolean("messages.global.notify_withdraw")) {
57 | Bukkit.broadcast(liteEco.locale.translation("messages.broadcast.withdraw_money", TagResolver.resolver(
58 | Placeholder.parsed("sender", sender.name),
59 | Placeholder.parsed("money", liteEco.api.fullFormatting(money, currency)),
60 | Placeholder.parsed("currency", liteEco.currencyImpl.currencyModularNameConvert(currency, money))
61 | )))
62 | }
63 | }
64 | }
--------------------------------------------------------------------------------
/src/main/kotlin/com/github/encryptsl/lite/eco/listeners/admin/EconomyMoneyDepositListener.kt:
--------------------------------------------------------------------------------
1 | package com.github.encryptsl.lite.eco.listeners.admin
2 |
3 | import com.github.encryptsl.lite.eco.LiteEco
4 | import com.github.encryptsl.lite.eco.api.economy.EconomyOperations
5 | import com.github.encryptsl.lite.eco.api.events.admin.EconomyMoneyDepositEvent
6 | import kotlinx.coroutines.launch
7 | import net.kyori.adventure.text.minimessage.tag.resolver.Placeholder
8 | import net.kyori.adventure.text.minimessage.tag.resolver.TagResolver
9 | import org.bukkit.OfflinePlayer
10 | import org.bukkit.command.CommandSender
11 | import org.bukkit.event.EventHandler
12 | import org.bukkit.event.Listener
13 | import java.math.BigDecimal
14 | import kotlin.jvm.optionals.getOrNull
15 |
16 | class EconomyMoneyDepositListener(private val liteEco: LiteEco) : Listener {
17 |
18 | @EventHandler
19 | fun onAdminEconomyDeposit(event: EconomyMoneyDepositEvent) {
20 | val sender: CommandSender = event.commandSender
21 | val target: OfflinePlayer = event.offlinePlayer
22 | val currency = event.currency
23 | val money: BigDecimal = event.money
24 | val silent: Boolean = event.silent
25 |
26 | if (liteEco.api.getCheckBalanceLimit(money) && !sender.hasPermission("lite.eco.admin.bypass.limit"))
27 | return sender.sendMessage(liteEco.locale.translation("messages.error.amount_above_limit"))
28 |
29 | liteEco.pluginScope.launch {
30 | val user = liteEco.suspendApiWrapper.getUserByUUID(target.uniqueId, currency).getOrNull()
31 | if (user == null) {
32 | sender.sendMessage(liteEco.locale.translation("messages.error.account_not_exist", Placeholder.parsed("account", target.name.toString())))
33 | return@launch
34 | }
35 | if (liteEco.api.getCheckBalanceLimit(target.uniqueId, user.money, currency, money) || !sender.hasPermission("lite.eco.admin.bypass.limit")) {
36 | sender.sendMessage(liteEco.locale.translation("messages.error.balance_above_limit",
37 | Placeholder.parsed("account", target.name.toString())
38 | ))
39 | return@launch
40 | }
41 |
42 | liteEco.increaseTransactions(1)
43 | liteEco.loggerModel.logging(EconomyOperations.DEPOSIT, sender.name, user.userName, currency, user.money, user.money.plus(money))
44 | liteEco.suspendApiWrapper.deposit(target.uniqueId, currency, money)
45 | }
46 |
47 | if (sender.name == target.name) {
48 | sender.sendMessage(liteEco.locale.translation("messages.self.add_money", TagResolver.resolver(
49 | Placeholder.parsed("money", liteEco.api.fullFormatting(money, currency)),
50 | Placeholder.parsed("currency", liteEco.currencyImpl.currencyModularNameConvert(currency, money))
51 | )))
52 | return
53 | }
54 |
55 | sender.sendMessage(liteEco.locale.translation("messages.sender.add_money",
56 | TagResolver.resolver(
57 | Placeholder.parsed("target", target.name.toString()), Placeholder.parsed("money", liteEco.api.fullFormatting(money, currency)),
58 | Placeholder.parsed("currency", liteEco.currencyImpl.currencyModularNameConvert(currency, money))
59 | )
60 | ))
61 |
62 | if (target.isOnline && liteEco.config.getBoolean("messages.target.notify_add")) {
63 | if (silent) {
64 | target.player?.sendMessage(liteEco.locale.translation(
65 | "messages.target.add_money_silent",
66 | Placeholder.parsed("money", liteEco.api.fullFormatting(money, currency))
67 | ))
68 | return
69 | }
70 | target.player?.sendMessage(liteEco.locale.translation("messages.target.add_money", TagResolver.resolver(
71 | Placeholder.parsed("sender", sender.name),
72 | Placeholder.parsed("money", liteEco.api.fullFormatting(money, currency)),
73 | Placeholder.parsed("currency", liteEco.currencyImpl.currencyModularNameConvert(currency, money)))
74 | ))
75 | }
76 |
77 | }
78 |
79 | }
--------------------------------------------------------------------------------
/src/main/kotlin/com/github/encryptsl/lite/eco/listeners/admin/EconomyMoneySetListener.kt:
--------------------------------------------------------------------------------
1 | package com.github.encryptsl.lite.eco.listeners.admin
2 |
3 | import com.github.encryptsl.lite.eco.LiteEco
4 | import com.github.encryptsl.lite.eco.api.economy.EconomyOperations
5 | import com.github.encryptsl.lite.eco.api.events.admin.EconomyMoneySetEvent
6 | import kotlinx.coroutines.launch
7 | import net.kyori.adventure.text.minimessage.tag.resolver.Placeholder
8 | import net.kyori.adventure.text.minimessage.tag.resolver.TagResolver
9 | import org.bukkit.OfflinePlayer
10 | import org.bukkit.command.CommandSender
11 | import org.bukkit.event.EventHandler
12 | import org.bukkit.event.Listener
13 | import java.math.BigDecimal
14 | import kotlin.jvm.optionals.getOrNull
15 |
16 | class EconomyMoneySetListener(private val liteEco: LiteEco) : Listener {
17 |
18 | @EventHandler
19 | fun onAdminEconomyMoneySet(event: EconomyMoneySetEvent) {
20 | val sender: CommandSender = event.commandSender
21 | val target: OfflinePlayer = event.offlinePlayer
22 | val currency = event.currency
23 | val money: BigDecimal = event.money
24 |
25 | if (liteEco.api.getCheckBalanceLimit(money) && !sender.hasPermission("lite.eco.admin.bypass.limit"))
26 | return sender.sendMessage(liteEco.locale.translation("messages.error.amount_above_limit"))
27 |
28 | liteEco.pluginScope.launch {
29 | val user = liteEco.suspendApiWrapper.getUserByUUID(target.uniqueId, currency).getOrNull()
30 | if (user == null) {
31 | sender.sendMessage(liteEco.locale.translation("messages.error.account_not_exist", Placeholder.parsed("account", target.name.toString())))
32 | return@launch
33 | }
34 | liteEco.loggerModel.logging(EconomyOperations.SET, sender.name, target.name.toString(), currency, user.money, money)
35 | liteEco.increaseTransactions(1)
36 | liteEco.suspendApiWrapper.set(target.uniqueId, currency, money)
37 | }
38 |
39 | if (sender.name == target.name) {
40 | sender.sendMessage(liteEco.locale.translation("messages.self.set_money", TagResolver.resolver(
41 | Placeholder.parsed("money", liteEco.api.fullFormatting(money, currency)),
42 | Placeholder.parsed("currency", liteEco.currencyImpl.currencyModularNameConvert(currency, money))
43 | )))
44 | return
45 | }
46 |
47 | sender.sendMessage(liteEco.locale.translation("messages.sender.set_money", TagResolver.resolver(
48 | Placeholder.parsed("target", target.name.toString()),
49 | Placeholder.parsed("money", liteEco.api.fullFormatting(money, currency)),
50 | Placeholder.parsed("currency", liteEco.currencyImpl.currencyModularNameConvert(currency, money))
51 | )))
52 |
53 | if (target.isOnline && liteEco.config.getBoolean("messages.target.notify_set")) {
54 | target.player?.sendMessage(liteEco.locale.translation("messages.target.set_money", TagResolver.resolver(
55 | Placeholder.parsed("sender", sender.name),
56 | Placeholder.parsed("money", liteEco.api.fullFormatting(money, currency)),
57 | Placeholder.parsed("currency", liteEco.currencyImpl.currencyModularNameConvert(currency, money))
58 | )))
59 | }
60 | }
61 |
62 | }
--------------------------------------------------------------------------------
/src/main/kotlin/com/github/encryptsl/lite/eco/listeners/admin/EconomyMoneyWithdrawListener.kt:
--------------------------------------------------------------------------------
1 | package com.github.encryptsl.lite.eco.listeners.admin
2 |
3 | import com.github.encryptsl.lite.eco.LiteEco
4 | import com.github.encryptsl.lite.eco.api.economy.EconomyOperations
5 | import com.github.encryptsl.lite.eco.api.events.admin.EconomyMoneyWithdrawEvent
6 | import kotlinx.coroutines.launch
7 | import net.kyori.adventure.text.minimessage.tag.resolver.Placeholder
8 | import net.kyori.adventure.text.minimessage.tag.resolver.TagResolver
9 | import org.bukkit.OfflinePlayer
10 | import org.bukkit.command.CommandSender
11 | import org.bukkit.event.EventHandler
12 | import org.bukkit.event.Listener
13 | import java.math.BigDecimal
14 | import kotlin.jvm.optionals.getOrNull
15 |
16 | class EconomyMoneyWithdrawListener(private val liteEco: LiteEco) : Listener {
17 |
18 | @EventHandler
19 | fun onAdminEconomyMoneyWithdraw(event: EconomyMoneyWithdrawEvent) {
20 | val sender: CommandSender = event.commandSender
21 | val target: OfflinePlayer = event.offlinePlayer
22 | val currency = event.currency
23 | val money: BigDecimal = event.money
24 | val silent: Boolean = event.silent
25 |
26 | if (!liteEco.api.has(target.uniqueId, currency, money))
27 | return sender.sendMessage(liteEco.locale.translation("messages.error.insufficient_funds"))
28 |
29 |
30 | liteEco.pluginScope.launch {
31 | val userOpt = liteEco.suspendApiWrapper.getUserByUUID(target.uniqueId, currency).getOrNull()
32 | if (userOpt == null) {
33 | sender.sendMessage(liteEco.locale.translation("messages.error.account_not_exist",
34 | Placeholder.parsed("account", target.name.toString())
35 | ))
36 | return@launch
37 | }
38 |
39 | liteEco.loggerModel.logging(EconomyOperations.WITHDRAW, sender.name, target.name.toString(), currency, userOpt.money, userOpt.money.minus(money))
40 |
41 | liteEco.increaseTransactions(1)
42 | liteEco.suspendApiWrapper.withdraw(target.uniqueId, currency, money)
43 | }
44 |
45 | if (sender.name == target.name) {
46 | sender.sendMessage(liteEco.locale.translation("messages.self.withdraw_money", TagResolver.resolver(
47 | Placeholder.parsed("money", liteEco.api.fullFormatting(money, currency)),
48 | Placeholder.parsed("currency", liteEco.currencyImpl.currencyModularNameConvert(currency, money))
49 | )))
50 | return
51 | }
52 |
53 | sender.sendMessage(liteEco.locale.translation("messages.sender.withdraw_money", TagResolver.resolver(
54 | Placeholder.parsed("target", target.name.toString()),
55 | Placeholder.parsed("money", liteEco.api.fullFormatting(money, currency)),
56 | Placeholder.parsed("currency", liteEco.currencyImpl.currencyModularNameConvert(currency, money))
57 | )))
58 |
59 | if (target.isOnline && liteEco.config.getBoolean("messages.target.notify_withdraw")) {
60 | if (silent) {
61 | target.player?.sendMessage(liteEco.locale.translation(
62 | "messages.target.withdraw_money_silent",
63 | Placeholder.parsed("currency", liteEco.currencyImpl.currencyModularNameConvert(currency, money))
64 | ))
65 | return
66 | }
67 |
68 | target.player?.sendMessage(liteEco.locale.translation("messages.target.withdraw_money", TagResolver.resolver(
69 | Placeholder.parsed("sender", sender.name),
70 | Placeholder.parsed("money", liteEco.api.fullFormatting(money, currency)),
71 | Placeholder.parsed("currency", liteEco.currencyImpl.currencyModularNameConvert(currency, money))
72 | )))
73 | }
74 | }
75 |
76 | }
--------------------------------------------------------------------------------
/src/main/kotlin/com/github/encryptsl/lite/eco/utils/ClassUtil.kt:
--------------------------------------------------------------------------------
1 | package com.github.encryptsl.lite.eco.utils
2 |
3 | object ClassUtil {
4 | fun isValidClasspath(classpath: String): Boolean {
5 | return try {
6 | Class.forName(classpath, false, javaClass.classLoader)
7 | true
8 | } catch (_: ClassNotFoundException) {
9 | false
10 | }
11 | }
12 | }
--------------------------------------------------------------------------------
/src/main/kotlin/com/github/encryptsl/lite/eco/utils/Debugger.kt:
--------------------------------------------------------------------------------
1 | package com.github.encryptsl.lite.eco.utils
2 |
3 | import com.github.encryptsl.lite.eco.LiteEco
4 | import com.github.encryptsl.lite.eco.api.objects.ModernText
5 |
6 | class Debugger(private val liteEco: LiteEco) {
7 |
8 | fun debug(provider: Class, message: String) {
9 | if (liteEco.config.getBoolean("plugin.vault-debug")) {
10 | liteEco.componentLogger.info(ModernText.miniModernText(" ${provider.name} $message"))
11 | }
12 | }
13 |
14 | }
--------------------------------------------------------------------------------
/src/main/kotlin/com/github/encryptsl/lite/eco/utils/Helper.kt:
--------------------------------------------------------------------------------
1 | package com.github.encryptsl.lite.eco.utils
2 |
3 | import com.github.encryptsl.lite.eco.LiteEco
4 | import com.github.encryptsl.lite.eco.api.economy.EconomyOperations
5 | import com.github.encryptsl.lite.eco.api.enums.CheckLevel
6 | import com.github.encryptsl.lite.eco.common.database.entity.User
7 | import com.github.encryptsl.lite.eco.common.extensions.isApproachingZero
8 | import com.github.encryptsl.lite.eco.common.extensions.isNegative
9 | import com.github.encryptsl.lite.eco.common.extensions.positionIndexed
10 | import com.github.encryptsl.lite.eco.common.extensions.toValidDecimal
11 | import net.kyori.adventure.text.Component
12 | import net.kyori.adventure.text.minimessage.tag.resolver.Placeholder
13 | import net.kyori.adventure.text.minimessage.tag.resolver.TagResolver
14 | import org.bukkit.command.CommandSender
15 | import java.math.BigDecimal
16 |
17 | class Helper(private val liteEco: LiteEco) {
18 | fun validateAmount(amountStr: String, commandSender: CommandSender, checkLevel: CheckLevel = CheckLevel.FULL): BigDecimal? {
19 | val amount = amountStr.toValidDecimal()
20 | return when {
21 | amount == null -> {
22 | commandSender.sendMessage(liteEco.locale.translation("messages.error.format_amount"))
23 | null
24 | }
25 | checkLevel == CheckLevel.ONLY_NEGATIVE && amount.isNegative() || checkLevel == CheckLevel.FULL && (amount.isApproachingZero()) -> {
26 | commandSender.sendMessage(liteEco.locale.translation("messages.error.negative_amount"))
27 | null
28 | }
29 | else -> amount
30 | }
31 | }
32 |
33 | suspend fun validateLog(parameter: String): List {
34 | val log = liteEco.loggerModel.getLog()
35 | .let { if (parameter != "all") it.filter { p -> p.target == parameter } else it }
36 |
37 | return log.map { el ->
38 | liteEco.loggerModel.message("messages.monolog.formatting",
39 | EconomyOperations.valueOf(el.action),
40 | el.sender,
41 | el.target,
42 | el.currency,
43 | el.previousBalance,
44 | el.newBalance,
45 | el.timestamp
46 | )
47 | }
48 | }
49 |
50 | fun getTopBalancesFormatted(currency: String): List {
51 | return liteEco.api.getTopBalance(currency).toList().positionIndexed { index, pair ->
52 | liteEco.locale.translation("messages.balance.top_format", TagResolver.resolver(
53 | Placeholder.parsed("position", index.toString()),
54 | Placeholder.parsed("player", pair.first),
55 | Placeholder.parsed("money", liteEco.api.fullFormatting(pair.second, currency)),
56 | Placeholder.parsed("currency", liteEco.currencyImpl.currencyModularNameConvert(currency, pair.second))
57 | ))
58 | }
59 | }
60 |
61 | fun getComponentBal(user: User, currency: String): TagResolver {
62 | return TagResolver.resolver(
63 | Placeholder.parsed("target", user.userName),
64 | Placeholder.parsed("money", liteEco.api.fullFormatting(user.money, currency)),
65 | Placeholder.parsed("currency", liteEco.currencyImpl.currencyModularNameConvert(currency, user.money))
66 | )
67 | }
68 | }
--------------------------------------------------------------------------------
/src/main/kotlin/com/github/encryptsl/lite/eco/utils/PlayerUtils.kt:
--------------------------------------------------------------------------------
1 | package com.github.encryptsl.lite.eco.utils
2 |
3 | import org.bukkit.Bukkit
4 | import org.bukkit.OfflinePlayer
5 | import org.bukkit.entity.Player
6 | import java.util.*
7 |
8 | object PlayerUtils {
9 | fun getOfflinePlayer(uuid: UUID): OfflinePlayer {
10 | return Bukkit.getPlayer(uuid) ?: Bukkit.getOfflinePlayer(uuid)
11 | }
12 |
13 | fun getUniqueId(offlinePlayer: OfflinePlayer): UUID {
14 | return Optional.ofNullable(offlinePlayer.player).map(Player::getUniqueId).orElseGet(offlinePlayer::getUniqueId)
15 | }
16 | }
--------------------------------------------------------------------------------
/src/main/resources/config.yml:
--------------------------------------------------------------------------------
1 | #Official settings for this plugin.
2 | plugin:
3 | # Translations list of supported locales below
4 | # https://github.com/EncryptSL/LiteEco/blob/main/src/main/kotlin/encryptsl/cekuj/net/api/enums/LangKey.kt
5 | translation: EN_US
6 | # Plugin prefix
7 | prefix: "[Eco] »"
8 | # Enable or disable Metrics
9 | metrics: true
10 | # Enable or disable Vault Debug
11 | vault-debug: false
12 | # Settings for modifiable players suggestion.
13 | # Enabled: Offline Players Suggestion..
14 | # Disabled: Online Players Suggestion...
15 | offline-suggestion-players: true
16 |
17 | economy:
18 | currencies: # Since 1.4.8 to newer versions
19 | # Don't change this currency because this is implemented for vault....
20 | # Key of currencies is name of table please don't change this value if you don't want to lose data.
21 | dollars:
22 | currency_name: dollars
23 | currency_plural_name: dollars
24 | currency_singular_name: dollar
25 | # Currency Format
26 | currency_format: '$ '
27 | # This amount is granted to players who don't have an existing account in the database.
28 | starting_balance: 30
29 | # This amount is checked when player is above allowed limit
30 | balance_limit: 1000000
31 | # Enabled or disable balance limit, disabled check mean fully for paid amounts by player, given/set by admins.
32 | balance_limit_check: true
33 | # Convert large currency values into a more compact format.
34 | compact_display: false
35 |
36 | # Example of other currencies
37 | # Don't change this currency because this is implemented for vault....
38 | # Key of currencies is name of table please don't change this value if you don't want to lose data.
39 | # credits:
40 | # currency_name: credits
41 | # currency_plural_name: credits
42 | # currency_singular_name: credit
43 | # Currency Format
44 | # currency_format: '€ '
45 | # # This amount is granted to players who don't have an existing account in the database.
46 | # starting_balance: 30
47 | # # This amount is checked when player is above allowed limit
48 | # balance_limit: 1000000
49 | # # Enabled or disable balance limit, disabled check mean fully for paid amounts by player, given/set by admins.
50 | # balance_limit_check: true
51 | # # Convert large currency values into a more compact format.
52 | # compact_display: false
53 |
54 | # Enable logging about economies activities add, set, withdraw, pay money.
55 | # Command /eco monolog [player]
56 | monolog_activity: true
57 |
58 | formatting:
59 | # Currency value format
60 | currency_pattern: "#,##0.00"
61 | # Compact value format
62 | compacted_pattern: "#,##0.0##"
63 | # Locale symbol format
64 | currency_locale: en-US
65 |
66 | placeholders:
67 | empty-name: "EMPTY"
68 |
69 | # These settings toggle messages.
70 | messages:
71 | global:
72 | notify_add: true
73 | notify_withdraw: true
74 | notify_set: true
75 | target:
76 | notify_add: true
77 | notify_withdraw: true
78 | notify_set: true
79 |
80 | # Settings for Database or SQLite connection.
81 | database:
82 | # For SQLite, the path to the SQLite database file: jdbc:sqlite:plugins/LiteEco/database.db
83 | # For MySQL, the JDBC connection URL in the format: jdbc:mysql://your_host:port/name_of_database
84 | # For MariaDB, the JDBC connection URL in the format: jdbc:mariadb://your_host:port/name_of_database
85 | # For PostgreSQL, the JDBC connection URL in the format: jdbc:postgresql://your_host:port/name_of_database
86 |
87 | # Drivers:
88 | #
89 | # MariaDB - org.mariadb.jdbc.Driver (https://youtrack.jetbrains.com/issue/EXPOSED-170)
90 | # MySQL - com.mysql.cj.jdbc.Driver Don't use if you have MariaDB version 11.X and newer.
91 | # PostgreSQL - org.postgresql.Driver
92 | # SQL - org.sqlite.JDBC
93 | connection:
94 | # Settings for DriverClassName
95 | driverClassName: "org.sqlite.JDBC"
96 | # Settings for JDBC_HOST
97 | jdbc_url: "jdbc:sqlite:plugins/LiteEco/database.db"
98 | # The username of the user to connect to your database (MySQL only).
99 | username: user_name
100 | # The password of the user to connect to your database (MySQL only).
101 | password: password
102 |
103 | # You can enable sql-plugin-logger for some problems with database...
104 | sql-plugin-logger: false
--------------------------------------------------------------------------------
/src/main/resources/database.db:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/EncryptSL/LiteEco/19ccadd412c6136c476ff321bd6c7865eb49284e/src/main/resources/database.db
--------------------------------------------------------------------------------
/src/main/resources/locale/zh_cn.yml:
--------------------------------------------------------------------------------
1 | messages:
2 | # 余额消息
3 | balance:
4 | format: " 你拥有 . [!]"
5 | format_target: " 玩家 <#13AFFE>#13AFFE> 拥有 . [!]"
6 | top_format: "# - "
7 | top_header: "─━━━━━━─ <#64646F>[ <#F9AD47>排行榜#F9AD47> ]#64646F> ─━━━━━━─"
8 | top_footer: "─━━━━━━─ <#64646F>[ <#F9AD47>#F9AD47> ]#64646F> ─━━━━━━─"
9 |
10 | # 转账消息
11 | self:
12 | add_money: " 你向自己的账户中添加了 ."
13 | withdraw_money: " 你从自己的账户中取出了 ."
14 | set_money: " 你将自己的账户 余额设置为了 ."
15 |
16 | # 被操作方交易信息
17 | target:
18 | add_money: " 支付了 ."
19 | add_money_silent: "+ "
20 | withdraw_money: " 从你的账户中支出了 ."
21 | withdraw_money_silent: "- "
22 | set_money: " 将你的账户 余额设置为了 ."
23 |
24 | # 操作方交易信息
25 | sender:
26 | add_money: " 你给予了玩家 ."
27 | withdraw_money: " 你拿走了玩家 ."
28 | set_money: " 你将玩家 的 数量设置为了 ."
29 |
30 | # 全局操作消息 (发送给操作者)
31 | global:
32 | add_money: " 你给予了所有玩家 ."
33 | withdraw_money: " 你从所有玩家账户中取出了 ."
34 | set_money: " 你将所有玩家的 数量设置为了 ."
35 |
36 | # 公告消息 (发送给被操作者)
37 | broadcast:
38 | add_money: " 向所有玩家发放了 ."
39 | withdraw_money: " 向所有玩家收取了 ."
40 | set_money: " 将所有玩家的 数量设置为了 ."
41 |
42 | # 错误消息
43 | error:
44 | account_not_exist: " 账号 不存在 [!]"
45 | account_now_exist: " 账号 已存在 [!]"
46 | missing_balance_others_permission: " You do not have permission to view the account balance of others [!]"
47 | missing_currency_permission: " 你没有权限使用此货币 [!]"
48 | format_amount: " 数量无效. 请使用小数或缩写 (如 1K) [!]"
49 | insufficient_funds: " 余额不足! [!]"
50 | maximum_page: "最大页码为 "
51 | negative_amount: " 请勿输入负数. [!]"
52 | export_argument: " 参数 <参数> 无效或尚不可用."
53 | export_failed: " 迁移过程遇到问题. 请检查控制台获取信息."
54 | import_failed: " There was an issue during the import or missing data !"
55 | purge_argument: " 参数 <参数> 无效或尚不可用."
56 | purge_monolog_fail: " 无法删除日志, 表为空 [!]"
57 | player_is_null: " 请输入有效的玩家名称 [!]"
58 | self_pay: " 你不能付款给自己 [!]"
59 | convert_fail: " 转化过程出现问题, 请查看控制台 [!]"
60 | amount_above_limit: " 交易数量超出服务器允许上限!"
61 | balance_above_limit: " 账号 持有的货币数量超出服务器允许上限!"
62 | database_exception: " 与数据库交互时出现问题: [!]"
63 |
64 | # This messages not support MiniMessage and Style Formatting !
65 | # Please don't try edit this messages !
66 | parser:
67 | error:
68 | currency_not_exist: "货币 %s 不存在!"
69 | language_not_exist: "This %s language is not supported [!]"
70 | convert_fail: "转化过程出现问题, 请查看控制台 [!]"
71 |
72 | # Monolog message formatting
73 | monolog:
74 | header: "─━━━━━━─ [ Transaction History ] ─━━━━━━─"
75 | footer: "─━━━━━━─ [ / ] ─━━━━━━─"
76 | formatting: "['>] to Old balance'> New balance'> []"
77 |
78 | # 管理员命令
79 | admin:
80 | create_account: " 账号 已被创建 [!]"
81 | config_reload: " 配置成功重载 [!]"
82 | translation_switch: " 显示语言已切换为 ."
83 | translation_missing: " 对应文本确实. 请联系插件开发者."
84 | purge_accounts: " 所有玩家账户已被清理."
85 | purge_null_accounts: " 所有存在非法值的账户已被清理."
86 | purge_default_accounts: " 所有存在默认值的账户已被清理."
87 | purge_monolog_success: " 所有交易日志已被清理 [!]"
88 | delete_account: " 玩家 的账户已被删除!"
89 | export_success: " 迁移 成功 [!]"
90 | import_success: " 转化来自