Add new economy actions, update API docs to use new repo, add metrics to Sponge (#398)

This commit is contained in:
William authored and GitHub committed 2023-05-09 19:24:24 +01:00
1 parent 8b609010ec
commit 40cb340b15
33 files changed
+437 -159

No files matched your search

@@ -45,10 +45,7 @@ import net.william278.huskhomes.user.ConsoleUser;
import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.user.SavedUser;
import net.william278.huskhomes.user.User;
import net.william278.huskhomes.util.SafetyResolver;
import net.william278.huskhomes.util.TaskRunner;
import net.william278.huskhomes.util.UnsafeBlocks;
import net.william278.huskhomes.util.Validator;
import net.william278.huskhomes.util.*;
import org.intellij.lang.annotations.Subst;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@@ -66,7 +63,7 @@ import java.util.stream.Stream;
/**
* Represents a cross-platform instance of the plugin
*/
public interface HuskHomes extends TaskRunner, EventDispatcher, SafetyResolver {
public interface HuskHomes extends TaskRunner, EventDispatcher, SafetyResolver, TransactionResolver {
int SPIGOT_RESOURCE_ID = 83767;
@@ -267,10 +264,6 @@ public interface HuskHomes extends TaskRunner, EventDispatcher, SafetyResolver {
.findFirst();
}
default Optional<EconomyHook> getEconomyHook() {
return getHook(EconomyHook.class);
}
default Optional<MapHook> getMapHook() {
return getHook(MapHook.class);
}
@@ -283,49 +276,6 @@ public interface HuskHomes extends TaskRunner, EventDispatcher, SafetyResolver {
.collect(Collectors.toList());
}
/**
* Perform an economy check on the {@link OnlineUser}; returning {@code true} if it passes the check
*
* @param player the player to perform the check on
* @param action the action to perform
* @return {@code true} if the action passes the check, {@code false} if the user has insufficient funds
*/
@SuppressWarnings("BooleanMethodIsAlwaysInverted")
default boolean validateEconomyCheck(@NotNull OnlineUser player, @NotNull EconomyHook.Action action) {
final Optional<Double> cost = getSettings().getEconomyCost(action).map(Math::abs);
if (cost.isPresent() && !player.hasPermission(EconomyHook.BYPASS_PERMISSION)) {
final Optional<EconomyHook> hook = getEconomyHook();
if (hook.isPresent()) {
if (cost.get() > hook.get().getPlayerBalance(player)) {
getLocales().getLocale("error_insufficient_funds", hook.get().formatCurrency(cost.get()))
.ifPresent(player::sendMessage);
return false;
}
}
}
return true;
}
/**
* Execute an economy transaction if needed, updating the player's balance
*
* @param player the player to deduct the cost from if needed
* @param action the action to deduct the cost from if needed
*/
default void performEconomyTransaction(@NotNull OnlineUser player, @NotNull EconomyHook.Action action) {
if (!getSettings().doEconomy()) return;
final Optional<Double> cost = getSettings().getEconomyCost(action).map(Math::abs);
if (cost.isPresent() && !player.hasPermission(EconomyHook.BYPASS_PERMISSION)) {
final Optional<EconomyHook> hook = getEconomyHook();
if (hook.isPresent()) {
hook.get().changePlayerBalance(player, -cost.get());
getLocales().getLocale(action.confirmationLocaleId, hook.get().formatCurrency(cost.get()))
.ifPresent(player::sendMessage);
}
}
}
/**
* Returns a resource read from the plugin resources folder
*
@@ -171,7 +171,7 @@ public class EditHomeCommand extends SavedPositionCommand<Home> {
}
// Check against economy
if (executor instanceof OnlineUser user && !plugin.validateEconomyCheck(user, EconomyHook.Action.MAKE_HOME_PUBLIC)) {
if (executor instanceof OnlineUser user && !plugin.canPerformTransaction(user, EconomyHook.Action.MAKE_HOME_PUBLIC)) {
return;
}
@@ -191,7 +191,7 @@ public class EditHomeCommand extends SavedPositionCommand<Home> {
// Perform transaction
if (executor instanceof OnlineUser user) {
plugin.performEconomyTransaction(user, EconomyHook.Action.MAKE_HOME_PUBLIC);
plugin.performTransaction(user, EconomyHook.Action.MAKE_HOME_PUBLIC);
}
final String privacy = home.isPublic() ? "public" : "private";
@@ -20,6 +20,7 @@
package net.william278.huskhomes.command;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.hook.EconomyHook;
import net.william278.huskhomes.position.Home;
import net.william278.huskhomes.teleport.Teleportable;
import net.william278.huskhomes.user.CommandUser;
@@ -52,7 +53,11 @@ public abstract class HomeCommand extends SavedPositionCommand<Home> {
return;
}
this.teleport(executor, optionalTeleporter.get(), home);
this.teleport(
executor, optionalTeleporter.get(), home,
(executor instanceof OnlineUser user && home.getOwner().equals(user)
? EconomyHook.Action.HOME_TELEPORT : EconomyHook.Action.PUBLIC_HOME_TELEPORT)
);
}
}
@@ -100,7 +100,7 @@ public class RtpCommand extends Command implements UserListTabProvider {
}
// Check they have sufficient funds
if (!plugin.validateEconomyCheck(teleporter, EconomyHook.Action.RANDOM_TELEPORT)) {
if (!plugin.canPerformTransaction(teleporter, EconomyHook.Action.RANDOM_TELEPORT)) {
return Optional.empty();
}
@@ -20,6 +20,7 @@
package net.william278.huskhomes.command;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.hook.EconomyHook;
import net.william278.huskhomes.position.Home;
import net.william278.huskhomes.position.SavedPosition;
import net.william278.huskhomes.position.Warp;
@@ -95,7 +96,7 @@ public abstract class SavedPositionCommand<T extends SavedPosition> extends Comm
final Home home = optionalHome.get();
if (executor instanceof OnlineUser user && !home.isPublic() && !user.equals(home.getOwner())
&& !user.hasPermission(getOtherPermission())) {
&& !user.hasPermission(getOtherPermission())) {
plugin.getLocales().getLocale("error_public_home_invalid", ownerUsername, ownerHomeName)
.ifPresent(executor::sendMessage);
return Optional.empty();
@@ -137,7 +138,7 @@ public abstract class SavedPositionCommand<T extends SavedPosition> extends Comm
return Optional.empty();
}
if (executor instanceof OnlineUser user && plugin.getSettings().doPermissionRestrictWarps()
&& !user.hasPermission(Warp.getWildcardPermission()) && !user.hasPermission(Warp.getPermission(warpName))) {
&& !user.hasPermission(Warp.getWildcardPermission()) && !user.hasPermission(Warp.getPermission(warpName))) {
plugin.getLocales().getLocale("error_warp_invalid", warpName)
.ifPresent(executor::sendMessage);
return Optional.empty();
@@ -156,7 +157,8 @@ public abstract class SavedPositionCommand<T extends SavedPosition> extends Comm
});
}
protected void teleport(@NotNull CommandUser executor, @NotNull Teleportable teleporter, @NotNull T position) {
protected void teleport(@NotNull CommandUser executor, @NotNull Teleportable teleporter, @NotNull T position,
@NotNull EconomyHook.Action... economyActions) {
if (!teleporter.equals(executor) && !executor.hasPermission(getPermission("other"))) {
plugin.getLocales().getLocale("error_no_permission")
.ifPresent(executor::sendMessage);
@@ -165,6 +167,7 @@ public abstract class SavedPositionCommand<T extends SavedPosition> extends Comm
final TeleportBuilder builder = Teleport.builder(plugin)
.teleporter(teleporter)
.economyActions(economyActions)
.target(position);
try {
if (executor.equals(teleporter)) {
@@ -173,7 +176,7 @@ public abstract class SavedPositionCommand<T extends SavedPosition> extends Comm
builder.toTeleport().execute();
}
} catch (TeleportationException e) {
e.displayMessage(executor, plugin, new String[0]);
e.displayMessage(executor, plugin, teleporter.getUsername());
}
}
@@ -20,6 +20,7 @@
package net.william278.huskhomes.command;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.hook.EconomyHook;
import net.william278.huskhomes.position.Position;
import net.william278.huskhomes.teleport.Teleport;
import net.william278.huskhomes.teleport.TeleportBuilder;
@@ -68,6 +69,7 @@ public class SpawnCommand extends Command {
final TeleportBuilder builder = Teleport.builder(plugin)
.teleporter(teleporter)
.economyActions(EconomyHook.Action.SPAWN_TELEPORT)
.target(spawn);
try {
if (teleporter.equals(executor)) {
@@ -20,6 +20,7 @@
package net.william278.huskhomes.command;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.hook.EconomyHook;
import net.william278.huskhomes.manager.RequestsManager;
import net.william278.huskhomes.teleport.TeleportRequest;
import net.william278.huskhomes.user.OnlineUser;
@@ -53,6 +54,7 @@ public class TeleportRequestCommand extends InGameCommand implements UserListTab
return;
}
// Ensure the user does not send a request to themselves
final String target = optionalTarget.get();
if (target.equalsIgnoreCase(onlineUser.getUsername())) {
plugin.getLocales().getLocale("error_teleport_request_self")
@@ -60,6 +62,11 @@ public class TeleportRequestCommand extends InGameCommand implements UserListTab
return;
}
// Validate economy check
if (!plugin.canPerformTransaction(onlineUser, EconomyHook.Action.SEND_TELEPORT_REQUEST)) {
return;
}
try {
manager.sendTeleportRequest(onlineUser, target, requestType);
} catch (IllegalArgumentException e) {
@@ -68,6 +75,7 @@ public class TeleportRequestCommand extends InGameCommand implements UserListTab
return;
}
plugin.performTransaction(onlineUser, EconomyHook.Action.SEND_TELEPORT_REQUEST);
plugin.getLocales()
.getLocale((requestType == TeleportRequest.Type.TPA ? "tpa" : "tpahere")
+ "_request_sent", target)
@@ -20,6 +20,7 @@
package net.william278.huskhomes.command;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.hook.EconomyHook;
import net.william278.huskhomes.position.Warp;
import net.william278.huskhomes.teleport.Teleportable;
import net.william278.huskhomes.user.CommandUser;
@@ -61,6 +62,6 @@ public class WarpCommand extends SavedPositionCommand<Warp> {
return;
}
this.teleport(executor, optionalTeleporter.get(), warp);
this.teleport(executor, optionalTeleporter.get(), warp, EconomyHook.Action.WARP_TELEPORT);
}
}
@@ -29,10 +29,8 @@ import net.william278.huskhomes.network.Broker;
import net.william278.huskhomes.position.World;
import org.jetbrains.annotations.NotNull;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.*;
import java.util.stream.Collectors;
/**
* Plugin settings, read from config.yml
@@ -240,13 +238,14 @@ public class Settings {
@YamlKey("economy.free_home_slots")
private int freeHomeSlots = 5;
@YamlComment("Require money to perform certain actions. Check https://william278.net/docs/huskhomes/economy-hook for available actions")
@YamlKey("economy.costs")
private Map<String, Double> economyCosts = Map.of(
EconomyHook.Action.ADDITIONAL_HOME_SLOT.name().toLowerCase(), EconomyHook.Action.ADDITIONAL_HOME_SLOT.getDefaultCost(),
EconomyHook.Action.MAKE_HOME_PUBLIC.name().toLowerCase(), EconomyHook.Action.MAKE_HOME_PUBLIC.getDefaultCost(),
EconomyHook.Action.RANDOM_TELEPORT.name().toLowerCase(), EconomyHook.Action.RANDOM_TELEPORT.getDefaultCost(),
EconomyHook.Action.BACK_COMMAND.name().toLowerCase(), EconomyHook.Action.BACK_COMMAND.getDefaultCost()
);
private Map<String, Double> economyCosts = Arrays.stream(EconomyHook.Action.values())
.filter(action -> action.getDefaultCost() > 0)
.collect(Collectors.toMap(
action -> action.name().toLowerCase(Locale.ENGLISH),
EconomyHook.Action::getDefaultCost)
);
// Mapping plugins
@YamlComment("Display public homes/warps on your web map (supports Dynmap and BlueMap)")
@@ -488,7 +487,7 @@ public class Settings {
if (!doEconomy()) {
return Optional.empty();
}
final Double cost = economyCosts.get(action.name().toLowerCase());
final Double cost = economyCosts.get(action.name().toLowerCase(Locale.ENGLISH));
if (cost != null && cost > 0d) {
return Optional.of(cost);
}
@@ -20,9 +20,12 @@
package net.william278.huskhomes.hook;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.config.Locales;
import net.william278.huskhomes.user.OnlineUser;
import org.jetbrains.annotations.NotNull;
import java.util.Locale;
/**
* A hook that provides economy features
*/
@@ -59,25 +62,61 @@ public abstract class EconomyHook extends Hook {
public abstract String formatCurrency(final double amount);
/**
* Identifies actions that incur an economic cost if economy is enabled
* Send the player a message notifying them that they have been charged
* for performing an action
*
* @param user the user to notify
* @param plugin the plugin instance
* @param action the action that was performed
*/
public final void notifyDeducted(@NotNull OnlineUser user, @NotNull HuskHomes plugin, @NotNull Action action) {
plugin.getSettings().getEconomyCost(action)
.flatMap(cost -> plugin.getLocales().getLocale(
"economy_transaction_complete",
formatCurrency(cost),
Locales.escapeText(plugin.getLocales()
.getRawLocale("economy_action_" + action.name().toLowerCase(Locale.ENGLISH))
.orElse(action.name()))
))
.ifPresent(user::sendMessage);
}
/**
* Identifies actions that have a price associated with performing them
*/
public enum Action {
ADDITIONAL_HOME_SLOT(100.00, "economy_action_additional_home_slot"),
MAKE_HOME_PUBLIC(50.00, "economy_action_make_home_public"),
RANDOM_TELEPORT(25.00, "economy_action_random_teleport"),
BACK_COMMAND(0.00, "economy_action_back_command");
/*
* Home and public home slots
*/
ADDITIONAL_HOME_SLOT(100.00),
MAKE_HOME_PUBLIC(50.00),
BACK_COMMAND(0.00),
/*
* Teleportation actions
*/
RANDOM_TELEPORT(25.00),
HOME_TELEPORT(0.00),
PUBLIC_HOME_TELEPORT(0.00),
WARP_TELEPORT(0.00),
SPAWN_TELEPORT(0.00),
/*
* Teleport request actions
*/
SEND_TELEPORT_REQUEST(0.00),
ACCEPT_TELEPORT_REQUEST(0.00);
private final double defaultCost;
@NotNull
public final String confirmationLocaleId;
Action(final double defaultCost, @NotNull String confirmationLocaleId) {
Action(double defaultCost) {
this.defaultCost = defaultCost;
this.confirmationLocaleId = confirmationLocaleId;
}
public double getDefaultCost() {
return defaultCost;
}
}
}
@@ -176,11 +176,11 @@ public class HomesManager {
throw new ValidationException(ValidationException.Type.NOT_ENOUGH_HOME_SLOTS);
}
if (!plugin.validateEconomyCheck(online, EconomyHook.Action.ADDITIONAL_HOME_SLOT)) {
if (!plugin.canPerformTransaction(online, EconomyHook.Action.ADDITIONAL_HOME_SLOT)) {
throw new ValidationException(ValidationException.Type.NOT_ENOUGH_MONEY);
}
plugin.performEconomyTransaction(online, EconomyHook.Action.ADDITIONAL_HOME_SLOT);
plugin.performTransaction(online, EconomyHook.Action.ADDITIONAL_HOME_SLOT);
plugin.editUserData(online, (SavedUser saved) -> saved.setHomeSlots(saved.getHomeSlots() + 1));
}
@@ -21,6 +21,7 @@ package net.william278.huskhomes.manager;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.config.Settings;
import net.william278.huskhomes.hook.EconomyHook;
import net.william278.huskhomes.network.Message;
import net.william278.huskhomes.network.Payload;
import net.william278.huskhomes.teleport.Teleport;
@@ -254,6 +255,12 @@ public class RequestsManager {
.ifPresent(recipient::sendMessage);
return;
}
// Validate the economy check
if (accepted && !plugin.canPerformTransaction(recipient, EconomyHook.Action.ACCEPT_TELEPORT_REQUEST)) {
return;
}
handleRequestResponse(lastRequest.get(), recipient, accepted);
}
@@ -301,6 +308,7 @@ public class RequestsManager {
// If the request is a tpa here request, teleport the recipient to the sender
if (accepted && request.getType() == TeleportRequest.Type.TPA_HERE) {
final TeleportBuilder builder = Teleport.builder(plugin)
.economyActions(EconomyHook.Action.ACCEPT_TELEPORT_REQUEST)
.teleporter(recipient);
// Strict /tpahere requests will teleport to where the sender was when typing the command
@@ -313,7 +321,7 @@ public class RequestsManager {
try {
builder.toTimedTeleport().execute();
} catch (TeleportationException e) {
e.displayMessage(recipient, plugin, new String[0]);
e.displayMessage(recipient, plugin);
}
}
}));
@@ -344,10 +352,11 @@ public class RequestsManager {
Teleport.builder(plugin)
.teleporter(requester)
.target(request.getRecipientName())
.economyActions(EconomyHook.Action.ACCEPT_TELEPORT_REQUEST)
.toTimedTeleport()
.execute();
} catch (TeleportationException e) {
e.displayMessage(requester, plugin, new String[0]);
e.displayMessage(requester, plugin);
}
}
}
@@ -177,7 +177,7 @@ public class Teleport {
// Check economy actions
protected void validateEconomyActions() throws TeleportationException {
if (economyActions.stream()
.map(action -> plugin.validateEconomyCheck(executor, action))
.map(action -> plugin.canPerformTransaction(executor, action))
.anyMatch(result -> !result)) {
throw new TeleportationException(TeleportationException.Type.ECONOMY_ACTION_FAILED);
}
@@ -185,7 +185,7 @@ public class Teleport {
// Perform transactions on economy actions
private void executeEconomyActions() {
economyActions.forEach(action -> plugin.performEconomyTransaction(executor, action));
economyActions.forEach(action -> plugin.performTransaction(executor, action));
}
@NotNull
@@ -41,4 +41,12 @@ public interface Teleportable {
return new Username(teleporter);
}
/**
* Get the username of the teleporter
*
* @return the username string
*/
@NotNull
String getUsername();
}
@@ -51,4 +51,15 @@ public record Username(@NotNull String name) implements Teleportable, Target {
? plugin.getOnlineUserExact(name) : plugin.getOnlineUser(name);
}
/**
* Get the username {@link String} being represented by this object
*
* @return the username
*/
@NotNull
@Override
public String getUsername() {
return name;
}
}
@@ -0,0 +1,87 @@
/*
* This file is part of HuskHomes, licensed under the Apache License 2.0.
*
* Copyright (c) William278 <[email protected]>
* Copyright (c) contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.william278.huskhomes.util;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.hook.EconomyHook;
import net.william278.huskhomes.user.OnlineUser;
import org.jetbrains.annotations.NotNull;
import java.util.Optional;
/**
* Utility class for resolving and performing economy transactions through an {@link EconomyHook}
*/
public interface TransactionResolver {
/**
* Perform an economy check on the {@link OnlineUser}; returning {@code true} if it passes the check
*
* @param player the {@link OnlineUser player} to perform the check on
* @param action the {@link EconomyHook.Action action} to perform
* @return {@code true} if the action passes the check, {@code false} if the user has insufficient funds
*/
default boolean canPerformTransaction(@NotNull OnlineUser player, @NotNull EconomyHook.Action action) {
return getPlugin().getSettings().getEconomyCost(action)
.map(Math::abs)
.flatMap(c -> player.hasPermission(EconomyHook.BYPASS_PERMISSION) ? Optional.empty() : Optional.of(c))
.map(c -> getEconomyHook()
.map(hook -> {
if (hook.getPlayerBalance(player) < c) {
getPlugin().getLocales().getLocale("error_insufficient_funds", hook.formatCurrency(c))
.ifPresent(player::sendMessage);
return false;
}
return true;
})
.orElse(true))
.orElse(true);
}
/**
* Execute an economy transaction if needed, updating the player's balance
*
* @param player the {@link OnlineUser player} to deduct the cost from if needed
* @param action the {@link EconomyHook.Action action} to deduct the cost from if needed
*/
default void performTransaction(@NotNull OnlineUser player, @NotNull EconomyHook.Action action) {
getPlugin().getSettings().getEconomyCost(action)
.map(Math::abs)
.flatMap(c -> player.hasPermission(EconomyHook.BYPASS_PERMISSION) ? Optional.empty() : Optional.of(c))
.ifPresent(cost -> getEconomyHook().ifPresent(hook -> {
hook.changePlayerBalance(player, -cost);
hook.notifyDeducted(player, getPlugin(), action);
}));
}
/**
* Get the {@link EconomyHook} instance, if present
*
* @return the {@link EconomyHook} instance
*/
@NotNull
default Optional<EconomyHook> getEconomyHook() {
return getPlugin().getHook(EconomyHook.class);
}
@NotNull
HuskHomes getPlugin();
}