Skip to content

Commit

Permalink
Merge pull request #23 from NextPlugins/uuid-method
Browse files Browse the repository at this point in the history
UUID method (NOT TESTED)
  • Loading branch information
Yuhtin authored Oct 22, 2021
2 parents af245e7 + 1eff651 commit b7d632d
Show file tree
Hide file tree
Showing 24 changed files with 184 additions and 100 deletions.
2 changes: 1 addition & 1 deletion build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ plugins {
}

group 'com.nextplugins'
version '2.0.3'
version '2.0.4'

tasks.build.dependsOn('shadowJar')

Expand Down
35 changes: 25 additions & 10 deletions src/main/java/com/nextplugins/economy/NextEconomy.java
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,10 @@
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.plugin.java.JavaPlugin;
import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
Expand Down Expand Up @@ -81,20 +83,22 @@ public final class NextEconomy extends JavaPlugin {

private File npcFile;
private File conversorsFile;
private File configFile;

private FileConfiguration npcConfig;
private FileConfiguration conversorsConfig;
private FileConfiguration config;

@Override
public void onLoad() {
saveDefaultConfig();
configFile = new File(getDataFolder(), "configuration.yml");
if (!configFile.exists()) saveResource("configuration.yml", false);

config = YamlConfiguration.loadConfiguration(configFile);

npcFile = new File(getDataFolder(), "npcs.yml");
if (!npcFile.exists()) saveResource("npcs.yml", false);

val discordSrv = new File(getDataFolder(), "libs/DiscordSRV.rar");
if (!discordSrv.exists()) saveResource("DiscordSRV.rar", false);

npcConfig = YamlConfiguration.loadConfiguration(npcFile);

conversorsFile = new File(getDataFolder(), "conversors.yml");
Expand Down Expand Up @@ -128,7 +132,10 @@ public void onEnable() {

internalTitleAPI = InternalAPIMapping.create();

accountStorage.init();
val nickValue = getConfig().getString("plugin.configuration.save-method", "NICK");
val nickMode = nickValue.equalsIgnoreCase("NICK");

accountStorage.init(nickMode);
interactionRegistry.init();

InventoryManager.enable(this);
Expand Down Expand Up @@ -162,23 +169,18 @@ public void onEnable() {

loadTime.stop();
getLogger().log(Level.INFO, "Plugin inicializado com sucesso. ({0})", loadTime);

}

@Override
public void onDisable() {

accountStorage.flushData();
unloadRanking();

if (FeatureValue.get(FeatureValue::autoBackup)) {

CompletableFuture.completedFuture(
backupManager.createBackup(null, null, accountRepository, false, false)
).join(); // freeze thread

}

}

private void unloadRanking() {
Expand Down Expand Up @@ -248,6 +250,19 @@ private void registerPayDiscordManager() {
payActionDiscordManager = new PayActionDiscordManager(accountStorage);
}

@Override
public void saveConfig() {
try {
getConfig().save(configFile);
} catch (IOException ex) {
getLogger().log(Level.SEVERE, "Não foi possível salvar o arquivo " + configFile, ex);
}
}

public @NotNull FileConfiguration getConfig() {
return config;
}

public static NextEconomy getInstance() {
return getPlugin(NextEconomy.class);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
import com.nextplugins.economy.api.conversor.impl.jheyson.JHEconomyConversor;
import com.nextplugins.economy.api.conversor.impl.soekd.SOEconomyConversor;
import com.nextplugins.economy.api.conversor.impl.solary.SolaryEconomyConversor;
import com.nextplugins.economy.api.conversor.impl.storm.StormEconomyConversor;
import com.nextplugins.economy.api.conversor.impl.tusk.TuskEconomyConversor;
import com.nextplugins.economy.api.conversor.impl.ystore.YEconomyConversor;
import lombok.Data;
Expand All @@ -37,6 +38,7 @@ public class ConversorRegistry {
put("TuskEconomy", new TuskEconomyConversor());
put("SOEconomy", new SOEconomyConversor());
put("SolaryEconomy", new SolaryEconomyConversor());
put("StormEconomy", new StormEconomyConversor());
put("Essentials", new EssentialsXConversor());
put("iConomy", new IConomyConversor());
}};
Expand Down Expand Up @@ -65,7 +67,7 @@ public void register() {
value.setTable(tableName);

conversorManager.registerConversor(value);
plugin.getLogger().info("[Converter] Registrado o conversor " + type);
plugin.getLogger().info("[Converter] Registrado o conversor " + type.getKey());
}

}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package com.nextplugins.economy.api.conversor.impl.storm;

import com.google.gson.Gson;
import com.henryfabio.sqlprovider.executor.adapter.SQLResultAdapter;
import com.henryfabio.sqlprovider.executor.result.SimpleResultSet;
import com.nextplugins.economy.api.model.account.Account;
import lombok.val;

public class StormEconomyAdapter implements SQLResultAdapter<Account> {

private final Gson accountParser = new Gson();

@Override
public Account adaptResult(SimpleResultSet resultSet) {
val user = accountParser.fromJson((String) resultSet.get("json"), StormEconomyUser.class);
return Account.generate()
.username(user.getJogador())
.balance(user.getCoins())
.transactions(user.getTransactions())
.result();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package com.nextplugins.economy.api.conversor.impl.storm;

import com.nextplugins.economy.api.conversor.Conversor;
import com.nextplugins.economy.api.model.account.Account;

import java.util.Set;

public class StormEconomyConversor extends Conversor {

@Override
public Set<Account> lookupPlayers() {
return getExecutor().resultManyQuery(
"SELECT * FROM " + getTable(),
statement -> {},
StormEconomyAdapter.class
);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package com.nextplugins.economy.api.conversor.impl.storm;

import com.google.common.collect.Lists;
import com.nextplugins.economy.api.model.account.historic.AccountBankHistoric;
import lombok.AllArgsConstructor;
import lombok.Getter;

import java.util.LinkedList;

@Getter
@AllArgsConstructor
public class StormEconomyUser {

private final double coins;
private final String jogador; // cringe
private final LinkedList<AccountBankHistoric> transactions = Lists.newLinkedList();

}
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
import lombok.*;
import net.milkbowl.vault.economy.EconomyResponse;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
Expand All @@ -27,22 +28,24 @@
@AllArgsConstructor(access = AccessLevel.PROTECTED)
public class Account {

private final String username;
private String username;
private String discordName;

private double balance;
private double movimentedBalance;

private int transactionsQuantity;

@Builder.Default private LinkedList<AccountBankHistoric> transactions = Lists.newLinkedList();
@Builder.Default
private LinkedList<AccountBankHistoric> transactions = Lists.newLinkedList();
private String transactionsJson;

@Builder.Default private boolean receiveCoins = true;
@Builder.Default
private boolean receiveCoins = true;

public static Account createDefault(String name) {
public static Account createDefault(OfflinePlayer player) {
return Account.generate()
.username(name)
.username(player.getName())
.balance(FeatureValue.get(FeatureValue::initialBalance))
.result();
}
Expand All @@ -59,11 +62,11 @@ public static Account createDefault(String name) {
* @deprecated Since 2.0.0
*/
@Deprecated
public static Account create(String name,
public static Account create(@NotNull String name,
double balance,
double movimentedBalance,
int transactionsQuantity,
LinkedList<AccountBankHistoric> transactions) {
@NotNull LinkedList<AccountBankHistoric> transactions) {
return new Account(
name,
"Nenhum configurado",
Expand Down Expand Up @@ -180,7 +183,8 @@ public synchronized EconomyResponse createTransaction(@Nullable Player player,
val value = quantity > valueWithoutPurse ? quantity - valueWithoutPurse : valueWithoutPurse - quantity;
val purseMessage = message.replace("$value", NumberUtils.format(value));

if (PurseValue.get(PurseValue::messageMethod).equalsIgnoreCase("message")) player.sendMessage(purseMessage);
if (PurseValue.get(PurseValue::messageMethod).equalsIgnoreCase("message"))
player.sendMessage(purseMessage);
else ActionBarUtils.sendActionBar(player, purseMessage);

}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
import com.github.benmanes.caffeine.cache.RemovalListener;
import com.nextplugins.economy.NextEconomy;
import com.nextplugins.economy.api.model.account.Account;
import com.nextplugins.economy.configuration.FeatureValue;
import com.nextplugins.economy.dao.repository.AccountRepository;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
Expand All @@ -22,16 +21,24 @@
@RequiredArgsConstructor
public final class AccountStorage {

private boolean nickMode;
@Getter private final AccountRepository accountRepository;

@Getter private final AsyncLoadingCache<String, Account> cache = Caffeine.newBuilder()
.maximumSize(1000)
.expireAfterWrite(5, TimeUnit.MINUTES)
.evictionListener((RemovalListener<String, Account>) (key, value, cause) -> saveOne(value))
.removalListener((key, value, cause) -> saveOne(value))
.evictionListener((RemovalListener<String, Account>) (key, value, cause) -> {
if (value == null) return;
saveOne(value);
})
.removalListener((key, value, cause) -> {
if (value == null) return;
saveOne(value);
})
.buildAsync((key, executor) -> CompletableFuture.completedFuture(selectOne(key)));

public void init() {
public void init(boolean nickMode) {
this.nickMode = nickMode;
accountRepository.createTable();
NextEconomy.getInstance().getLogger().info("DAO do plugin iniciado com sucesso.");
}
Expand Down Expand Up @@ -86,7 +93,8 @@ public Account findAccount(@NotNull OfflinePlayer offlinePlayer) {
if (player != null) return findAccount(player);
}

return findAccountByName(offlinePlayer.getName());
if (nickMode && offlinePlayer.getName() == null) return null;
return findAccountByName(nickMode ? offlinePlayer.getName() : offlinePlayer.getUniqueId().toString());
}

/**
Expand All @@ -97,12 +105,17 @@ public Account findAccount(@NotNull OfflinePlayer offlinePlayer) {
*/
@NotNull
public Account findAccount(@NotNull Player player) {
Account account = findAccountByName(player.getName());
Account account = findAccountByName(nickMode ? player.getName() : player.getUniqueId().toString());
if (account == null) {
account = Account.createDefault(player.getName());
account = Account.createDefault(player);
put(account);
}

// update username if player change (original users)
if (!account.getUsername().equalsIgnoreCase(player.getName())) {
account.setUsername(player.getName());
}

return account;
}

Expand All @@ -119,10 +132,10 @@ public void put(@NotNull Account account) {
* Flush data from cache
*/
public void flushData() {
val synchronous = cache.synchronous();
//synchronous.cleanUp(); ?
synchronous.invalidateAll();
synchronous.cleanUp();
val accountMap = cache.synchronous().asMap();
for (val entry : accountMap.entrySet()) {
accountRepository.saveOne(entry.getValue());
}
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
import net.skinsrestorer.api.SkinsRestorerAPI;
import org.bukkit.Bukkit;
import org.jetbrains.annotations.NotNull;
import skinsrestorer.shared.storage.SkinStorage;

/**
* @author Yuhtin
Expand All @@ -30,8 +29,7 @@ public void init() {
val skinName = SkinsRestorerAPI.getApi().getSkinName(player);
return skinName == null ? player : skinName;
} catch (Throwable ignored) {
val skinName = SkinStorage.getPlayerSkin(player);
return skinName == null ? player : skinName;
return player;
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ public final class NextEconomyCommand {

@Command(
name = "nexteconomy",
aliases = {"economy", "eco", "ne"},
aliases = {"economy", "neco", "eco", "ne"},
permission = "nexteconomy.admin",
async = true
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
import lombok.val;
import org.bukkit.event.Listener;

import java.io.File;
import java.util.logging.Level;

/**
Expand All @@ -29,14 +30,20 @@ public void init() {
if (!DiscordValue.get(DiscordValue::enable)) return;

val plugin = NextEconomy.getInstance();
if (plugin.getPayActionDiscordManager() == null) {
if (plugin.getConfig().getString("database.version", "1.1.4").equalsIgnoreCase("1.1.4")) {
val discordSrv = new File(plugin.getDataFolder(), "libs/DiscordSRV.rar");
if (!discordSrv.exists()) plugin.saveResource("DiscordSRV.rar", false);

plugin.getConfig().set("database.version", "2.0.0");
plugin.saveConfig();
}

if (plugin.getPayActionDiscordManager() == null) {
plugin.getLogger().log(Level.WARNING,
"Dependência não encontrada ({0}) A integração com o discord não será usada.",
"DiscordSRV"
);
return;

}

enabled = true;
Expand Down
Loading

0 comments on commit b7d632d

Please sign in to comment.