diff --git a/src/main/java/pro/cloudnode/smp/bankaccounts/Account.java b/src/main/java/pro/cloudnode/smp/bankaccounts/Account.java index 4fe7f8e9..ae5b839d 100644 --- a/src/main/java/pro/cloudnode/smp/bankaccounts/Account.java +++ b/src/main/java/pro/cloudnode/smp/bankaccounts/Account.java @@ -23,11 +23,13 @@ import java.time.ZoneOffset; import java.util.ArrayList; import java.util.Arrays; +import java.util.Date; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.UUID; import java.util.logging.Level; +import java.util.stream.Collectors; /** * Bank account @@ -40,7 +42,7 @@ public class Account { /** * Account owner */ - public final @NotNull OfflinePlayer owner; + public @NotNull OfflinePlayer owner; /** * Account type */ @@ -381,13 +383,14 @@ public void insert() { */ public void update() { try (final @NotNull Connection conn = BankAccounts.getInstance().getDb().getConnection(); - final @NotNull PreparedStatement stmt = conn.prepareStatement("UPDATE `bank_accounts` SET `name` = ?, `balance` = ?, `frozen` = ? WHERE `id` = ?")) { - if (name == null) stmt.setNull(1, java.sql.Types.VARCHAR); - else stmt.setString(1, name); - if (balance == null) stmt.setNull(2, java.sql.Types.DECIMAL); - else stmt.setBigDecimal(2, balance); - stmt.setBoolean(3, frozen); - stmt.setString(4, id); + final @NotNull PreparedStatement stmt = conn.prepareStatement("UPDATE `bank_accounts` SET `owner` = ?, `name` = ?, `balance` = ?, `frozen` = ? WHERE `id` = ?")) { + stmt.setString(1, owner.getUniqueId().toString()); + if (name == null) stmt.setNull(2, java.sql.Types.VARCHAR); + else stmt.setString(2, name); + if (balance == null) stmt.setNull(3, java.sql.Types.DECIMAL); + else stmt.setBigDecimal(3, balance); + stmt.setBoolean(4, frozen); + stmt.setString(5, id); stmt.executeUpdate(); } catch (final @NotNull Exception e) { @@ -406,6 +409,7 @@ public void delete() { } catch (final @NotNull Exception e) { BankAccounts.getInstance().getLogger().log(Level.SEVERE, "Could not delete account: " + id, e); } + ChangeOwnerRequest.delete(id); } /** @@ -525,4 +529,210 @@ public enum Type { USERNAME } } + + /** + * A request to change the owner of a bank account (sent to the new owner) + */ + public final static class ChangeOwnerRequest { + /** + * Account id + */ + private final @NotNull String account; + + /** + * New owner + */ + public final @NotNull OfflinePlayer newOwner; + + /** + * Request creation timestamp + */ + public final @NotNull Date created; + + /** + * Create a new account ownership transfer request instance + * + * @param account Account to transfer ownership of + * @param newOwner The new account owner + */ + public ChangeOwnerRequest(final @NotNull Account account, final @NotNull OfflinePlayer newOwner) { + this.account = account.id; + this.newOwner = newOwner; + this.created = new Date(); + } + + private ChangeOwnerRequest(final @NotNull ResultSet rs) throws SQLException { + this.account = rs.getString("account"); + this.newOwner = BankAccounts.getInstance().getServer().getOfflinePlayer(UUID.fromString(rs.getString("new_owner"))); + this.created = new Date(rs.getTimestamp("created").getTime()); + } + + /** + * Get account + */ + public @NotNull Optional<@NotNull Account> account() { + return Account.get(account); + } + + /** + * Check if request has expired + */ + public boolean expired() { + return System.currentTimeMillis() - created.getTime() > BankAccounts.getInstance().config().changeOwnerTimeout() * 60_000L; + } + + /** + * Confirm/accept the request + *
+ * This also deletes any other pending requests for the same account. + * + * @return Whether the change was successful + */ + public boolean confirm() { + final @NotNull Optional<@NotNull Account> account = this.account(); + if (account.isEmpty()) return false; + if (account.get().frozen) return false; + account.get().owner = newOwner; + account.get().update(); + ChangeOwnerRequest.delete(this.account); + return true; + } + + /** + * Insert into database, replacing any existing request for the same account and new owner + */ + public void insert() { + this.delete(); + try (final @NotNull Connection conn = BankAccounts.getInstance().getDb().getConnection(); + final @NotNull PreparedStatement stmt = conn.prepareStatement("INSERT INTO `change_owner_requests` (`account`, `new_owner`, `created`) VALUES (?, ?, ?)")) { + stmt.setString(1, account); + stmt.setString(2, newOwner.getUniqueId().toString()); + stmt.setTimestamp(3, new java.sql.Timestamp(created.getTime())); + + stmt.executeUpdate(); + } + catch (final @NotNull Exception e) { + BankAccounts.getInstance().getLogger().log(Level.SEVERE, "Could not save account ownership change request. account: " + account + ", newOwner: " + newOwner.getUniqueId(), e); + } + } + + /** + * Delete from database + */ + public void delete() { + try (final @NotNull Connection conn = BankAccounts.getInstance().getDb().getConnection(); + final @NotNull PreparedStatement stmt = conn.prepareStatement("DELETE FROM `change_owner_requests` WHERE `account` = ? AND `new_owner` = ?")) { + stmt.setString(1, account); + stmt.setString(2, newOwner.getUniqueId().toString()); + stmt.executeUpdate(); + } + catch (final @NotNull Exception e) { + BankAccounts.getInstance().getLogger().log(Level.SEVERE, "Could not delete account ownership change request. account: " + account + ", newOwner: " + newOwner.getUniqueId(), e); + } + } + + /** + * Delete all requests to transfer a certain account + * + * @param account Account ID + */ + public static void delete(final @NotNull String account) { + try (final @NotNull Connection conn = BankAccounts.getInstance().getDb().getConnection(); + final @NotNull PreparedStatement stmt = conn.prepareStatement("DELETE FROM `change_owner_requests` WHERE `account` = ?")) { + stmt.setString(1, account); + stmt.executeUpdate(); + } + catch (final @NotNull Exception e) { + BankAccounts.getInstance().getLogger().log(Level.SEVERE, "Could not delete account ownership change requests. account: " + account, e); + } + } + + /** + * Delete expired requests + */ + public static void deleteExpired() { + try (final @NotNull Connection conn = BankAccounts.getInstance().getDb().getConnection(); + final @NotNull PreparedStatement stmt = conn.prepareStatement("DELETE FROM `change_owner_requests` WHERE `created` < ?")) { + stmt.setTimestamp(1, new java.sql.Timestamp(System.currentTimeMillis() - BankAccounts.getInstance().config().changeOwnerTimeout() * 60_000L)); + stmt.executeUpdate(); + } + catch (final @NotNull Exception e) { + BankAccounts.getInstance().getLogger().log(Level.SEVERE, "Could not delete expired account ownership change requests", e); + } + } + + /** + * Get account ownership change request + * + * @param account Account ID + * @param newOwner New owner + */ + public static @NotNull Optional<@NotNull ChangeOwnerRequest> get(final @NotNull String account, final @NotNull OfflinePlayer newOwner) { + try (final @NotNull Connection conn = BankAccounts.getInstance().getDb().getConnection(); + final @NotNull PreparedStatement stmt = conn.prepareStatement("SELECT * FROM `change_owner_requests` WHERE `account` = ? AND `new_owner` = ? LIMIT 1")) { + stmt.setString(1, account); + stmt.setString(2, newOwner.getUniqueId().toString()); + final @NotNull ResultSet rs = stmt.executeQuery(); + return rs.next() ? Optional.of(new ChangeOwnerRequest(rs)) : Optional.empty(); + } + catch (final @NotNull Exception e) { + BankAccounts.getInstance().getLogger().log(Level.SEVERE, "Could not get account ownership change request. account: " + account + ", newOwner: " + newOwner.getUniqueId(), e); + return Optional.empty(); + } + } + + /** + * List a player's incoming (received) account ownership change requests that have not expired. + * + * @param player The player whose requests to list + */ + public static @NotNull ChangeOwnerRequest @NotNull [] incoming(final @NotNull OfflinePlayer player) { + try (final @NotNull Connection conn = BankAccounts.getInstance().getDb().getConnection(); + final @NotNull PreparedStatement stmt = conn.prepareStatement("SELECT * FROM `change_owner_requests` WHERE `new_owner` = ?")) { + stmt.setString(1, player.getUniqueId().toString()); + final @NotNull ResultSet rs = stmt.executeQuery(); + + final @NotNull List<@NotNull ChangeOwnerRequest> requests = new ArrayList<>(); + while (rs.next()) { + final @NotNull ChangeOwnerRequest request = new ChangeOwnerRequest(rs); + if (!request.expired()) requests.add(request); + } + return requests.toArray(new ChangeOwnerRequest[0]); + } + catch (final @NotNull Exception e) { + BankAccounts.getInstance().getLogger().log(Level.SEVERE, "Could not get incoming account ownership change requests. player: " + player.getUniqueId(), e); + return new ChangeOwnerRequest[0]; + } + } + + /** + * List a player's outgoing (sent) account ownership change requests that have not expired. + *
+ * These are requests for accounts that the player currently owns.
+ *
+ * @param player The player whose requests to list
+ */
+ public static @NotNull ChangeOwnerRequest @NotNull [] outgoing(final @NotNull OfflinePlayer player) {
+ final @NotNull String @NotNull [] ids = Arrays.stream(Account.get(player)).map(a -> a.id).toArray(String[]::new);
+ if (ids.length == 0) return new ChangeOwnerRequest[0];
+ final @NotNull String placeholders = Arrays.stream(ids).map(id -> "?").collect(Collectors.joining(", "));
+ try (final @NotNull Connection conn = BankAccounts.getInstance().getDb().getConnection();
+ final @NotNull PreparedStatement stmt = conn.prepareStatement("SELECT * FROM `change_owner_requests` WHERE `account` IN (" + placeholders + ")")) {
+ for (int i = 0; i < ids.length; i++)
+ stmt.setString(i + 1, ids[i]);
+ final @NotNull ResultSet rs = stmt.executeQuery();
+
+ final @NotNull List<@NotNull ChangeOwnerRequest> requests = new ArrayList<>();
+ while (rs.next()) {
+ final @NotNull ChangeOwnerRequest request = new ChangeOwnerRequest(rs);
+ if (!request.expired()) requests.add(request);
+ }
+ return requests.toArray(new ChangeOwnerRequest[0]);
+ }
+ catch (final @NotNull Exception e) {
+ BankAccounts.getInstance().getLogger().log(Level.SEVERE, "Could not get outgoing account ownership change requests. player: " + player.getUniqueId(), e);
+ return new ChangeOwnerRequest[0];
+ }
+ }
+ }
}
diff --git a/src/main/java/pro/cloudnode/smp/bankaccounts/BankAccounts.java b/src/main/java/pro/cloudnode/smp/bankaccounts/BankAccounts.java
index 14cbc993..93cfe545 100644
--- a/src/main/java/pro/cloudnode/smp/bankaccounts/BankAccounts.java
+++ b/src/main/java/pro/cloudnode/smp/bankaccounts/BankAccounts.java
@@ -171,6 +171,7 @@ public static void reload() {
getInstance().invoiceNotificationTask = null;
}
getInstance().setupInvoiceNotificationTimer();
+ getInstance().setupChangeOwnerCleanupTimer();
}
/**
@@ -270,6 +271,16 @@ private void setupInvoiceNotificationTimer() {
}, config().invoiceNotifyInterval() * 20L, config().invoiceNotifyInterval() * 20L);
}
+ private @Nullable BukkitTask changeOwnerCleanupTask = null;
+
+ /**
+ * Periodically delete expired account ownership change requests
+ */
+ private void setupChangeOwnerCleanupTimer() {
+ if (changeOwnerCleanupTask != null) changeOwnerCleanupTask.cancel();
+ changeOwnerCleanupTask = getServer().getScheduler().runTaskTimerAsynchronously(this, Account.ChangeOwnerRequest::deleteExpired, 0L, 20L * 60 * 5);
+ }
+
private void interestPayment(final @NotNull Account account, final @NotNull BigDecimal amount, final double rate, final @NotNull Account serverAccount) {
if (account.balance == null) return;
if (account.id.equals(serverAccount.id)) return;
diff --git a/src/main/java/pro/cloudnode/smp/bankaccounts/BankConfig.java b/src/main/java/pro/cloudnode/smp/bankaccounts/BankConfig.java
index 66fff30e..33249760 100644
--- a/src/main/java/pro/cloudnode/smp/bankaccounts/BankConfig.java
+++ b/src/main/java/pro/cloudnode/smp/bankaccounts/BankConfig.java
@@ -7,6 +7,7 @@
import net.kyori.adventure.text.minimessage.tag.resolver.Placeholder;
import org.bukkit.Material;
import org.bukkit.NamespacedKey;
+import org.bukkit.OfflinePlayer;
import org.bukkit.Registry;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.enchantments.Enchantment;
@@ -238,6 +239,21 @@ public boolean instrumentsGlintEnabled() {
return Objects.requireNonNull(Registry.ENCHANTMENT.get(NamespacedKey.minecraft(Objects.requireNonNull(config.getString("instruments.glint.enchantment")))));
}
+ // change-owner.confirm
+ public boolean changeOwnerConfirm() {
+ return config.getBoolean("change-owner.confirm");
+ }
+
+ // change-owner.timeout
+ public int changeOwnerTimeout() {
+ return config.getInt("change-owner.timeout");
+ }
+
+ // change-owner.limit-send
+ public int changeOwnerLimitSend() {
+ return config.getInt("change-owner.limit-send");
+ }
+
// pos.allow-personal
public boolean posAllowPersonal() {
return config.getBoolean("pos.allow-personal");
@@ -766,6 +782,42 @@ public int invoiceNotifyInterval() {
return MiniMessage.miniMessage().deserialize(Objects.requireNonNull(config.getString("messages.errors.player-never-joined")));
}
+ // messages.errors.change-owner-same
+ public @NotNull Component messagesErrorsAlreadyOwnsAccount(final @NotNull Account account) {
+ return MiniMessage.miniMessage().deserialize(
+ Objects.requireNonNull(config.getString("messages.errors.change-owner-same")),
+ Placeholder.parsed("player", account.ownerNameUnparsed())
+ );
+ }
+
+ // messages.errors.change-owner-limit-send
+ public @NotNull Component messagesErrorsChangeOwnerLimitSend() {
+ return MiniMessage.miniMessage().deserialize(
+ Objects.requireNonNull(config.getString("messages.errors.change-owner-limit-send")),
+ Placeholder.unparsed("limit", String.valueOf(this.changeOwnerLimitSend()))
+ );
+ }
+
+ // messages.errors.change-owner-not-found
+ public @NotNull Component messagesErrorsChangeOwnerNotFound() {
+ return MiniMessage.miniMessage().deserialize(Objects.requireNonNull(config.getString("messages.errors.change-owner-not-found")));
+ }
+
+ // messages.errors.change-owner-accept-failed
+ public @NotNull Component messagesErrorsChangeOwnerAcceptFailed() {
+ return MiniMessage.miniMessage().deserialize(Objects.requireNonNull(config.getString("messages.errors.change-owner-accept-failed")));
+ }
+
+ // messages.errors.change-owner-vault-account
+ public @NotNull Component messagesErrorsChangeOwnerVaultAccount() {
+ return MiniMessage.miniMessage().deserialize(Objects.requireNonNull(config.getString("messages.errors.change-owner-vault-account")));
+ }
+
+ // messages.errors.change-owner-frozen
+ public @NotNull Component messagesErrorsChangeOwnerFrozen() {
+ return MiniMessage.miniMessage().deserialize(Objects.requireNonNull(config.getString("messages.errors.change-owner-frozen")));
+ }
+
// messages.errors.async-failed
public @NotNull Component messagesErrorsAsyncFailed() {
return MiniMessage.miniMessage().deserialize(Objects.requireNonNull(config.getString("messages.errors.async-failed")));
@@ -1449,6 +1501,94 @@ public int invoiceNotifyInterval() {
Formatter.choice("unpaid-choice", unpaid)
));
}
+
+ // messages.change-owner.request
+ public @NotNull Component messagesChangeOwnerRequest(final @NotNull Account.ChangeOwnerRequest request, final @NotNull String acceptCommand) {
+ final @NotNull Account account = request.account().orElse(new Account.ClosedAccount());
+ return MiniMessage.miniMessage().deserialize(
+ Objects.requireNonNull(config.getString("messages.change-owner.request"))
+ .replace("
diff --git a/src/main/java/pro/cloudnode/smp/bankaccounts/commands/result/Message.java b/src/main/java/pro/cloudnode/smp/bankaccounts/commands/result/Message.java
index 5c6fde2e..0374968a 100644
--- a/src/main/java/pro/cloudnode/smp/bankaccounts/commands/result/Message.java
+++ b/src/main/java/pro/cloudnode/smp/bankaccounts/commands/result/Message.java
@@ -5,22 +5,24 @@
import net.kyori.adventure.text.minimessage.MiniMessage;
import net.kyori.adventure.text.minimessage.tag.resolver.TagResolver;
import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
public final class Message extends CommandResult {
- public final @NotNull Audience audience;
+ public final @Nullable Audience audience;
public final @NotNull Component message;
- public Message(@NotNull Audience audience, @NotNull Component message) {
+ public Message(@Nullable Audience audience, @NotNull Component message) {
super();
this.audience = audience;
this.message = message;
}
- public Message(@NotNull Audience audience, @NotNull String message, final @NotNull TagResolver @NotNull ... placeholders) {
+ public Message(@Nullable Audience audience, @NotNull String message, final @NotNull TagResolver @NotNull ... placeholders) {
this(audience, MiniMessage.miniMessage().deserialize(message, placeholders));
}
public void send() {
- audience.sendMessage(message);
+ if (audience != null)
+ audience.sendMessage(message);
}
}
diff --git a/src/main/java/pro/cloudnode/smp/bankaccounts/events/Join.java b/src/main/java/pro/cloudnode/smp/bankaccounts/events/Join.java
index ebc8493d..4f384db4 100644
--- a/src/main/java/pro/cloudnode/smp/bankaccounts/events/Join.java
+++ b/src/main/java/pro/cloudnode/smp/bankaccounts/events/Join.java
@@ -38,6 +38,15 @@ else if (BankAccounts.getInstance().config().integrationsVaultEnabled()) {
player.sendMessage(BankAccounts.getInstance().config().messagesUpdateAvailable(latestVersion))
), 20L);
}
+ if (player.hasPermission(Permissions.CHANGE_OWNER_ACCEPT)) {
+ BankAccounts.getInstance().getServer().getScheduler().runTaskLaterAsynchronously(BankAccounts.getInstance(), () -> {
+ for (final @NotNull Account.ChangeOwnerRequest request : Account.ChangeOwnerRequest.incoming(player)) {
+ final @NotNull Optional<@NotNull Account> account = request.account();
+ if (account.isEmpty()) continue;
+ player.sendMessage(BankAccounts.getInstance().config().messagesChangeOwnerRequest(request, "/bank acceptchangeowner " + account.get().id));
+ }
+ }, 20L);
+ }
if (player.hasPermission(Permissions.INVOICE_NOTIFY) && BankAccounts.getInstance().config().invoiceNotifyJoin() && Invoice.countUnpaid(player) > 0) {
BankAccounts.getInstance().getServer().getScheduler().runTaskLater(BankAccounts.getInstance(), () -> {
final @NotNull Optional<@NotNull Component> message = BankAccounts.getInstance().config().messagesInvoiceNotify(Invoice.countUnpaid(player));
diff --git a/src/main/resources/config.yml b/src/main/resources/config.yml
index 18f07da3..f9f97f89 100644
--- a/src/main/resources/config.yml
+++ b/src/main/resources/config.yml
@@ -182,6 +182,23 @@ instruments:
# BankAccounts will always use level 1 of the enchantment.
enchantment: unbreaking
+# Change account owner
+# The current owner first confirms that they want to offer the account, then the new owner must accept it.
+# To change the owner without the new owner’s acceptance, use the ‘bank.change.owner.force’ permission.
+change-owner:
+ # Ask the current owner to confirm before the account is offered to the new owner.
+ # This only affects the sender: the new owner must always accept, unless the sender uses the
+ # ‘bank.change.owner.force’ permission.
+ confirm: true
+
+ # In minutes, when should an ownership change request expire.
+ timeout: 15
+
+ # The maximum number of pending sent ownership change requests that a player can have (to prevent spam).
+ # Set to ‘-1’ for unlimited. Set to ‘0’ to disallow sending ownership change requests.
+ # To bypass this limit, use the ‘bank.change.owner.bypass.limit’ permission.
+ limit-send: 5
+
# Point of Sale.
# This is a chest that can have any items.
# Players can buy all the items in the POS for the specified price.
@@ -361,6 +378,7 @@ messages:
freeze: