5 Commits

Author SHA1 Message Date
87b5efed8c Allows not generating initial home and requiring users to acquire one when they want. 2026-09-27 05:10:05 -07:00
Tom
de3651f22c Merge pull request #11 from headhunter45/2-add-a-command-to-teleport-to-a-reservation-you-are-part-of
Adds /metropolis-plot-go command to teleport to a plot.
2026-09-27 05:04:08 -07:00
da46d3e4b9 Adds /metropolis-plot-go command to teleport to a plot. 2026-09-27 04:59:16 -07:00
Tom
b6b30621f0 Merge pull request #10 from headhunter45/1-add-a-command-to-move-to-a-different-home
Some checks failed
Java CI with Gradle / build (push) Has been cancelled
Adds /metropolis-home-move command to switch to another home.
2026-09-27 04:40:37 -07:00
efc39365c3 Adds /metropolis-home-move command to switch to another home. 2026-09-27 04:38:43 -07:00
14 changed files with 575 additions and 72 deletions

View File

@@ -21,6 +21,7 @@ Use this checklist for behavior that depends on a real Paper world, player inter
### Join and plot allocation
- Join as a new player. Confirm one home is allocated and the welcome message reports its actual bounds. Check the corresponding `h_1_<UUID>` region has the player as owner and its bounds match the configured plot size.
- Set `plot.initial: 0` on a disposable server, restart, and join as a fresh player. Confirm no home is created until the player runs `/metropolis-home-acquire`; then verify the command creates the initial home and makes it active.
- Join with a second new player. Confirm the new home is distinct, does not overlap the first home or spawn, and the City region grows to include it.
- Join again as an existing player. Confirm the same home is selected and no duplicate region or plot is created.
- Reserve an area before allocating another home. Confirm future allocations skip it. Repeat with reservations near the city edge and near existing roads to look for overlaps or gaps.
@@ -41,6 +42,11 @@ Use this checklist for behavior that depends on a real Paper world, player inter
- As the home owner, build and interact inside the home. As another non-op player, try the same actions. Verify ownership and protection behave as intended in homes, reservations, City, and Spawn.
- Verify representative protection flags in-game, including PvP, mob damage/spawning, explosions, and fire/lava behavior where applicable. Run `/metropolis-flag-reset` and confirm the expected flags are restored without changing region bounds or ownership.
- Restart the server and confirm reservations and their protection are still present in WorldGuard and remain excluded from home allocation.
- Add a non-op test player as a WorldGuard member of a Metropolis reservation. Run `/metropolis-plot-go` and confirm they arrive inside that reservation at a safe location; repeat with an owner.
- Confirm a player who is neither owner nor member cannot use a reservation name to teleport there. Check that a region they own/member outside homes, City, and Spawn is treated as expected by the Metropolis reservation lookup.
- Add a player to two reservations. Confirm the no-argument form reports both names without teleporting, then specify one reservation and verify the chosen destination.
- As an authorized admin, target another online member with `/metropolis-plot-go <playerName>`. Confirm the target receives a notification. Repeat without `metropolis.plot.go` and verify targeting another player is denied.
- Test a reservation with no safe destination. Confirm the command reports failure and does not claim teleportation succeeded. Also test console use with an online player name and an unknown/offline name.
### Commands, permissions, and player state
@@ -52,6 +58,9 @@ Use this checklist for behavior that depends on a real Paper world, player inter
- With plot multipliers of 1 and 2, acquire homes and inspect their WorldGuard bounds. Confirm size follows the tier, a larger footprint does not overlap an existing home, and the multiplier is applied to the X and Z footprint only once.
- Exercise `/metropolis-home-acquire` below and at each effective home limit. Confirm every successful request creates a distinct next-numbered home, creates none beyond the limit, and does not change other players' homes.
- After acquiring a second home, verify it becomes active: check the player's selected home in `plugins/Metropolis/currentHomes.yml` and use `/metropolis-home-go` to confirm travel to that home. Switch homes with `/metropolis-home-move` and verify the selection changes as expected.
- Run `/metropolis-home-move <homeNumber>` as a player with multiple homes. Verify the command confirms the selected home, updates `currentHomes.yml`, and `/metropolis-home-go` now travels to it.
- Run `/metropolis-home-move <homeNumber> <playerName>` as an authorized administrator, then repeat from console. Check an online target is notified and a cached offline target uses the selected home on their next join.
- Try zero, negative, non-numeric, nonexistent home numbers, unknown player names, and extra arguments. Confirm each request is rejected with useful feedback and does not change the stored active home.
- Restart after acquiring multiple homes. Confirm all home regions remain owned by the player, the active home selection persists, and joining does not allocate another first home.
- Generate a home for an offline player administratively. Confirm permission tiers are not assumed for offline players; the username override or global settings determine plot size and limit.
- Exercise `/metropolis-home-go` with a safe bed spawn inside the home and with no such bed spawn. Confirm teleportation chooses a valid location inside the home and reports a clear failure if no safe location exists.
@@ -62,7 +71,7 @@ Use this checklist for behavior that depends on a real Paper world, player inter
## Existing Automated Coverage
Run `./gradlew test` for the server-free JUnit suite. It has 17 tests covering:
Run `./gradlew test` for the server-free JUnit suite. It has 26 tests covering:
- `CuboidTest`: WorldEdit bound conversion, vector ordering/null handling, touching intersections, and point containment.
- `CurrentHomesStoreTest`: UUID-based persistence and resolving a legacy player-name key.
@@ -71,6 +80,9 @@ Run `./gradlew test` for the server-free JUnit suite. It has 17 tests covering:
- `PlayerHomeTest`: UUID-based region identity and display-name retention.
- `HomePermissionOverrideTest`: dotted permission-node parsing, priority and tie resolution, invalid entries, and username/permission/default precedence.
- `HomeNumberAllocatorTest`: choosing the first unused positive home number.
- `MetropolisHomeMoveCommandTest`: selecting a sender's home, selecting an offline target's home, and rejecting invalid requests.
- `PlotReservationLookupTest`: owner/member matching, exclusion of homes/City/Spawn, legacy reservation markers, and region-name aliases.
- `MetropolisPlotGoCommandTest`: self and target teleportation, ambiguous memberships, absent membership, and unsafe-destination feedback.
- `MetropolisPlotReserveCommandTest`: parsing six coordinates and rejecting malformed coordinates.
- `MetropolisHomeAcquireTest`: acquisition below the limit and refusal at the limit.

View File

@@ -15,10 +15,13 @@ Metropolis targets Paper only; Bukkit and Spigot servers are not supported.
## Features
- Automatically assigns a protected home plot when a player joins.
- Allows players to acquire additional homes up to their configured limit, with per-player overrides.
- Allows players to acquire additional homes up to their effective limit, configured globally, per user, or through permission-manager groups.
- Supports permission-based plot-size and home-limit tiers with configurable priorities; explicit per-user overrides take precedence.
- Lets players and authorized administrators select an existing home as active; selections persist by player UUID across restarts.
- Expands the protected city region as plots are occupied.
- Configures plot dimensions, roads, floors, supports, signs, spawn behavior, and perimeter walls.
- Reserves named plots by coordinates or a WorldEdit selection.
- Lets WorldGuard owners and members teleport to reservations they belong to, with a named choice when they have multiple.
- Tracks home ownership and selected homes by player UUID.
- Supports home and plot teleportation, administration, and WorldGuard protection flags.
@@ -33,10 +36,10 @@ Metropolis creates `plugins/Metropolis/config.yml` on first startup. Configure p
- `/metropolis-home-generate <playerName>` - Generates a home for a known online or cached offline player.
- `/metropolis-home-list` - Lists occupied and reserved plots.
- `/metropolis-home-go [playerName]` - Teleports to a home.
- `/metropolis-home-move <homeNumber> [playerName]` - Selects a player's home.
- `/metropolis-home-move <homeNumber> [playerName]` - Selects an existing home as active. The player name defaults to the sender; authorized administrators and console can target online or cached offline players.
- `/metropolis-home-evict <playerName>` - Removes a player's ownership from their selected home region.
- `/metropolis-plot-reserve <name> <minX> <minY> <minZ> <maxX> <maxY> <maxZ>` - Reserves a region by coordinates; players can use `/metropolis-plot-reserve <name>` with a WorldEdit selection.
- `/metropolis-plot-go <plotName> [playerName]` - Teleports to a named plot.
- `/metropolis-plot-go [playerName]` - Teleports to the sender's or an online player's reservation. Specify a reservation name to choose among multiple memberships; `metropolis.plot.go` allows targeting others or bypassing membership.
- `/metropolis-flag-reset` - Reapplies Metropolis protection flags.
- `/metropolis-debug-generatetesthomes <count>` - Generates test homes; intended for development servers.

View File

@@ -2,4 +2,4 @@
Metropolis turns player onboarding into city planning. As players arrive, the Paper plugin finds the next available plot, builds the surrounding roads and infrastructure, and extends a WorldGuard-protected city that feels designed rather than randomly generated.
The project combines procedural spatial logic, persistent UUID-based ownership, configurable construction rules, WorldEdit-assisted reservations, and a command suite for moving, acquiring, listing, and administering homes. It is also a modernization case study: a legacy plugin brought forward to Paper 26.2 and 26.3 with Gradle, focused unit tests, and opt-in live-server integration tests. Bukkit and Spigot servers are outside the support target.
The project combines procedural spatial logic, persistent UUID-based ownership, configurable construction rules, WorldEdit-assisted reservations, and a command suite for acquiring and selecting multiple homes. Home limits and plot sizes can be assigned per user or through permission-manager groups using configurable permission tiers. Reservation owners and members can teleport to their reserved plots, with explicit selection when they belong to multiple reservations. Active-home selections persist across reconnects and server restarts. It is also a modernization case study: a legacy plugin brought forward to Paper 26.2 and 26.3 with Gradle, focused unit tests, and opt-in live-server integration tests. Bukkit and Spigot servers are outside the support target.

View File

@@ -4,10 +4,12 @@ Metropolis expands a protected Minecraft city as players join. Each player can r
## Features
- Assigns a protected home plot when a player joins and supports acquiring additional homes up to the configured player limit.
- Assigns a protected home plot when a player joins by default and supports acquiring additional homes up to the configured player limit; set `plot.initial` to `0` to require `/metropolis-home-acquire` for the first home.
- Supports per-player plot sizes and home limits through `userOverrides` or configurable permission tiers; acquired homes can be selected as the active home.
- Expands the City region as plots are occupied, with optional spawn generation, world-spawn placement, floors, support blocks, signs, and perimeter walls.
- Generates roads around plots with configurable width, level, material, clearance, and supports.
- Creates named protected reservations from coordinates or a WorldEdit selection so reserved plots are not assigned as homes.
- Lets WorldGuard reservation owners and members teleport to their reservations, with explicit selection when they belong to several.
- Persists selected homes by player UUID and recognizes legacy name-based home data during migration.
- Supports online/offline player administration for home generation, movement, and eviction.
@@ -55,9 +57,9 @@ Copy `.env.example` to `.env` and configure the Paper version/build and server p
## Configuration
`plugins/Metropolis/config.yml` controls plot dimensions and limits, floor and support generation, signs, road width/level/material/clearance, spawn behavior, wall generation, world name, and per-player overrides. `plot.multiplier` sets the default plot-size multiplier; `plot.maxPerPlayer` sets the default home limit.
`plugins/Metropolis/config.yml` controls plot dimensions and limits, floor and support generation, signs, road width/level/material/clearance, spawn behavior, wall generation, world name, and per-player overrides. `plot.multiplier` sets the default plot-size multiplier; `plot.maxPerPlayer` sets the default home limit; `plot.initial` sets how many homes are auto-generated on join, and `0` requires `/metropolis-home-acquire` for the player's first home.
Use `permissionOverrides` to assign plot size and home limits through any permission manager. Each permission node maps to a `priority`, `plotMultiplier`, and `maxPlots`; the matching node with the highest priority wins, and the last matching entry in YAML order wins ties. An explicit username entry in `userOverrides` takes precedence over permission rules. If no override matches, the global `plot.*` defaults apply. For example:
Use `permissionOverrides` to assign plot size and home limits through any permission manager. Each permission node maps to a `priority`, `plotMultiplier`, and `maxPlots`; the matching node with the highest priority wins, and the last matching entry in YAML order wins ties. An explicit username entry in `userOverrides` takes precedence over permission rules. If no override matches, the global `plot.*` defaults apply. Permission rules are checked for online players; offline home generation uses username overrides or global defaults. For example:
```yaml
permissionOverrides:
@@ -82,10 +84,10 @@ Assign these permission nodes to groups or individual users in your permission p
| `/metropolis-home-generate <playerName>` | `metropolis.home.generate` | Generates a home for an online or cached offline player. |
| `/metropolis-home-list` | `metropolis.home.list` | Lists the occupied and reserved Metropolis plots with their bounds. |
| `/metropolis-home-go [playerName]` | `metropolis.home.go` | Teleports the sender, or a permitted target player, to their home. |
| `/metropolis-home-move <homeNumber> [playerName]` | `metropolis.home.move` | Selects one of a player's existing home regions. The player argument defaults to the sender. |
| `/metropolis-home-move <homeNumber> [playerName]` | `metropolis.home.move` | Selects one of a player's existing homes as active. The player argument defaults to the sender; console and authorized admins can target online or cached offline players. The selection persists across restarts. |
| `/metropolis-home-evict <playerName>` | `metropolis.home.evict` | Removes the player's ownership from their selected home region. |
| `/metropolis-plot-reserve <name> <minX> <minY> <minZ> <maxX> <maxY> <maxZ>` | `metropolis.plot.reserve` | Creates a named reservation from explicit bounds. A player can instead run `/metropolis-plot-reserve <name>` with a WorldEdit selection. |
| `/metropolis-plot-go <plotName> [playerName]` | `metropolis.plot.go` | Teleports the sender or target player to a named occupied or reserved plot. |
| `/metropolis-plot-go [playerName]` | Reservation owner/member; `metropolis.plot.go` to target others or bypass membership | Teleports the sender or an online target to a reservation they own or belong to. If they have several, specify one with `/metropolis-plot-go <reservationName> [playerName]`. |
| `/metropolis-flag-reset` | `metropolis.flag.reset` | Reapplies Metropolis protection flags to the City and home regions. |
| `/metropolis-debug-generatetesthomes <count>` | `metropolis.debug` | Generates test homes; intended for development servers. |

35
TODO.md
View File

@@ -33,28 +33,24 @@
| GIT-007 | Planning | Allow buying and selling of homes via an ecnoomy plugin. |
| GIT-006 | Ready | Add levels support. |
| GIT-005 | Planning | Add the possibility to create multiple plot homes in shapes. |
| GIT-004 | Planning | Add a command to request home allocation. |
| GIT-004 | Done | Add a command to request home allocation. |
| GIT-003 | Ready | Add support for multiple homes. |
| GIT-002 | Planning | Add a command to teleport to a reservation you are part of. |
| GIT-001 | Planning | Add a command to move to a different home. |
| GIT-002 | Done | Add a command to teleport to a reservation you are part of. |
| GIT-001 | Done | Add a command to move to a different home. |
# GIT-001 - Add a command to move to a different home.
**Status:** Ready
**Depends On:** [GIT-003](#git-003---add-support-for-multiple-homes)
**Descriptioon:**
/metropolis-home-move [playerName]
The target player will be the callee or if specified [playerName].
This command should set the target player's home to the plot defined by .
# GIT-002 - Add a command to teleport to a reservation you are part of.
**Status:** Ready
**Status:** Done
**Depends On:** [GIT-003](#git-003---add-support-for-multiple-homes)
**Description:**
/metropolis-plot-go [playerName]
The target player should be [playerName] if specified and otherwise should be the callee.
The reservation to teleport to is
`/metropolis-home-move <homeNumber> [playerName]` selects one of a player's existing homes as active. Without a player name, the command acts on the player who ran it; console and authorized administrators can specify an online or cached offline player. Reject non-positive or malformed numbers, unknown players, nonexistent homes, and extra arguments with clear feedback. Persist the selection by player UUID and confirm the change to the sender and, when online, the target player.
# GIT-002 - Add a command to teleport to a reservation you are part of.
**Status:** Done
**Depends On:** [GIT-003](#git-003---add-support-for-multiple-homes)
**Description:**
`/metropolis-plot-go [playerName]` teleports the sender, or the specified online player, to a Metropolis WorldGuard cuboid reservation where that player is an owner or member. If the player belongs to more than one reservation, report the available region names and require an explicit choice with `/metropolis-plot-go <reservationName> [playerName]`. The explicit-name form only permits destinations where the target is a member/owner, unless the sender has `metropolis.plot.go`. Remove the command-level permission gate so reservation members can use self-service teleportation; enforce admin-only target and membership bypass checks in the command. Report unknown players, missing membership, ambiguous reservations, and reservations without a safe teleport location. Do not report success unless teleportation succeeds.
### Comments
@@ -72,14 +68,11 @@ On join, automatically allocate one home only when the player has no existing ho
The alternative login allocation policies are tracked separately in MET-023 and MET-024; they are not part of the default policy in this task.
# GIT-004 - Add a command to request home allocation.
**Status:** Ready
**Status:** Done
**Depends On:** [GIT-003](#git-003---add-support-for-multiple-homes)
**Description:**
Add a command that users can type to get their first or subsequent homes.
Add a config option to not generate any homes automatically, but to require this command to generate a user's first home.
This could be used so that homes won't be generated until a user has read the server rules which would include telling them to type the command towards the end.
`/metropolis-home-acquire` gives players their next available home, including the first home when `plot.initial` is `0`. The command allocates the lowest unused positive home number, makes it active, and refuses requests once the player has reached their effective limit. The default policy remains automatic first-home generation, but servers can disable it by setting `plot.initial: 0` and requiring the command for new players.
# GIT-005 - Add the possibility to create multiple plot homes in shapes.
**Status:** Planning

View File

@@ -119,6 +119,7 @@ public class MetropolisPlugin extends JavaPlugin {
private int wallHeight = 128;
int _maxPlots = 1;
int _plotMultiplier = 1;
private int initialHomeCount = 1;
private Cuboid _spawnCuboid = null;
private Cuboid _cityCuboid = null;
@@ -199,6 +200,7 @@ public class MetropolisPlugin extends JavaPlugin {
worldName = safeGetStringFromConfig(config, "worldname");
_plotMultiplier = safeGetIntFromConfig(config, "plot.multiplier");
_maxPlots = safeGetIntFromConfig(config, "plot.maxPerPlayer");
initialHomeCount = normalizeInitialHomeCount(safeGetIntFromConfig(config, "plot.initial"));
buildUserOverrides();
_permissionOverrides =
@@ -556,6 +558,9 @@ public class MetropolisPlugin extends JavaPlugin {
setHome(playerId, existingHome.getNumber());
return existingHome;
}
if (!shouldAutoGenerateInitialHome()) {
return null;
}
if (DEBUG) {
getLogger().info(String.format("Creating home for player %s", player.getName()));
}
@@ -568,6 +573,26 @@ public class MetropolisPlugin extends JavaPlugin {
return home;
}
public static int normalizeInitialHomeCount(int count) {
return Math.max(0, count);
}
public static boolean shouldAutoGenerateInitialHome(int count) {
return count > 0;
}
public int getInitialHomeCount() {
return initialHomeCount;
}
public void setInitialHomeCount(int count) {
initialHomeCount = normalizeInitialHomeCount(count);
}
public boolean shouldAutoGenerateInitialHome() {
return shouldAutoGenerateInitialHome(initialHomeCount);
}
private void generateFloor(Cuboid plotCuboid) {
int x = 0;
int y = roadLevel;
@@ -1237,11 +1262,17 @@ public class MetropolisPlugin extends JavaPlugin {
public String teleportPlayerToPlot(Player player, Plot plot) {
Location loc = plot.getViableSpawnLocation(world);
if (loc != null) {
player.teleport(loc);
if (loc == null) {
return "No safe teleport location exists in plot " + plot.getRegionName() + ".";
}
return player.teleport(loc) ? null : "Unable to teleport to plot " + plot.getRegionName() + ".";
}
return null;
public List<Plot> getReservationsForPlayer(UUID playerId) {
if (regionManager == null) {
return List.of();
}
return PlotReservationLookup.forPlayer(regionManager.getRegions().values(), playerId);
}
public boolean homeExists(UUID playerId, int homeNumber) {

View File

@@ -0,0 +1,72 @@
/*
This file is part of Metropolis.
Metropolis is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Metropolis is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with Metropolis. If not, see <https://www.gnu.org/licenses/agpl-3.0.txt>.
*/
package com.majinnaibu.bukkitplugins.metropolis;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.UUID;
import com.sk89q.worldguard.protection.flags.Flags;
import com.sk89q.worldguard.protection.flags.StateFlag;
import com.sk89q.worldguard.protection.regions.ProtectedCuboidRegion;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
public final class PlotReservationLookup {
private PlotReservationLookup() {}
public static List<Plot> forPlayer(Iterable<ProtectedRegion> regions, UUID playerId) {
List<Plot> reservations = new ArrayList<>();
for (ProtectedRegion region : regions) {
if (!(region instanceof ProtectedCuboidRegion) || !isReservation(region)) {
continue;
}
if (region.getOwners().getUniqueIds().contains(playerId)
|| region.getMembers().getUniqueIds().contains(playerId)) {
reservations.add(Plot.get(region));
}
}
reservations.sort(Comparator.comparing(Plot::getRegionName));
return List.copyOf(reservations);
}
public static Plot findByName(List<Plot> reservations, String requestedName) {
String prefixedName = requestedName.startsWith("r_") ? requestedName : "r_" + requestedName;
for (Plot reservation : reservations) {
if (reservation.getRegionName().equals(requestedName)
|| reservation.getRegionName().equals(prefixedName)) {
return reservation;
}
}
return null;
}
private static boolean isReservation(ProtectedRegion region) {
String regionId = region.getId();
if (regionId.startsWith("r_")) {
return true;
}
if (regionId.startsWith("h_")
|| regionId.equalsIgnoreCase("City")
|| regionId.equalsIgnoreCase("Spawn")) {
return false;
}
return region.getFlag(Flags.LAVA_FLOW) == StateFlag.State.DENY
&& region.getFlag(Flags.SNOW_FALL) == StateFlag.State.DENY;
}
}

View File

@@ -23,6 +23,7 @@ import org.bukkit.OfflinePlayer;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public class MetropolisHomeMoveCommand implements CommandExecutor {
MetropolisPlugin _plugin;
@@ -33,37 +34,53 @@ public class MetropolisHomeMoveCommand implements CommandExecutor {
@Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
OfflinePlayer player = null;
int newHomeNumber = 0;
if (sender instanceof OfflinePlayer) {
player = (OfflinePlayer) sender;
if (args.length < 1 || args.length > 2) {
sender.sendMessage("Usage: /metropolis-home-move <homeNumber> [playerName]");
return false;
}
int homeNumber;
try {
homeNumber = Integer.parseInt(args[0]);
} catch (NumberFormatException ex) {
sender.sendMessage("Home number must be a positive integer.");
return false;
}
if (homeNumber < 1) {
sender.sendMessage("Home number must be a positive integer.");
return false;
}
OfflinePlayer target;
if (args.length == 1) {
try {
newHomeNumber = Integer.parseInt(args[0]);
} catch (NumberFormatException ex) {
if (!(sender instanceof Player player)) {
sender.sendMessage("Console must specify a player name.");
return false;
}
} else if (args.length >= 2) {
try {
newHomeNumber = Integer.parseInt(args[0]);
} catch (NumberFormatException ex) {
return false;
}
player = _plugin.getOfflinePlayer(args[1]);
target = player;
} else {
target = _plugin.getOfflinePlayer(args[1]);
if (target == null) {
sender.sendMessage("No known player named " + args[1] + ".");
return false;
}
}
if (!_plugin.homeExists(target.getUniqueId(), homeNumber)) {
String targetName =
target.getName() == null ? target.getUniqueId().toString() : target.getName();
sender.sendMessage(targetName + " does not have home " + homeNumber + ".");
return false;
}
if (player == null || !_plugin.homeExists(player.getUniqueId(), newHomeNumber)) {
return false;
_plugin.setHome(target.getUniqueId(), homeNumber);
String targetName =
target.getName() == null ? target.getUniqueId().toString() : target.getName();
sender.sendMessage("Home " + homeNumber + " is now active for " + targetName + ".");
if (target instanceof Player targetPlayer && targetPlayer != sender) {
targetPlayer.sendMessage("Your active Metropolis home is now home " + homeNumber + ".");
}
_plugin.setHome(player.getUniqueId(), newHomeNumber);
return true;
}
}

View File

@@ -19,6 +19,7 @@ package com.majinnaibu.bukkitplugins.metropolis.commands;
import com.majinnaibu.bukkitplugins.metropolis.MetropolisPlugin;
import com.majinnaibu.bukkitplugins.metropolis.Plot;
import com.majinnaibu.bukkitplugins.metropolis.PlotReservationLookup;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
@@ -34,23 +35,85 @@ public class MetropolisPlotGoCommand implements CommandExecutor {
@Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
Player player = null;
Plot plot = null;
if (sender instanceof Player) {
player = (Player) sender;
}
if (args.length == 1 && player != null) {
plot = _plugin.getPlot(args[0]);
} else if (args.length >= 2) {
player = _plugin.getPlayer(args[1]);
plot = _plugin.getPlot(args[0]);
} else {
if (args.length > 2) {
sender.sendMessage(
"Usage: /metropolis-plot-go [playerName] or /metropolis-plot-go <reservationName> [playerName]");
return false;
}
if (plot == null || player == null) {
Player player;
String requestedReservation = null;
if (args.length == 0) {
if (!(sender instanceof Player senderPlayer)) {
sender.sendMessage("Console must specify an online player name.");
return false;
}
player = senderPlayer;
} else if (args.length == 1) {
Player namedPlayer = _plugin.getPlayer(args[0]);
if (namedPlayer != null) {
player = namedPlayer;
} else if (sender instanceof Player senderPlayer) {
player = senderPlayer;
requestedReservation = args[0];
} else {
sender.sendMessage("No online player named " + args[0] + ".");
return false;
}
} else {
requestedReservation = args[0];
player = _plugin.getPlayer(args[1]);
if (player == null) {
sender.sendMessage("No online player named " + args[1] + ".");
return false;
}
}
boolean canManagePlots = sender.hasPermission("metropolis.plot.go");
if (player != sender && !canManagePlots) {
sender.sendMessage("You do not have permission to teleport another player.");
return false;
}
var reservations = _plugin.getReservationsForPlayer(player.getUniqueId());
Plot plot;
if (requestedReservation == null) {
if (reservations.isEmpty()) {
sender.sendMessage(
player.getName() + " is not a member or owner of a Metropolis reservation.");
return false;
}
if (reservations.size() > 1) {
String names =
reservations.stream()
.map(Plot::getRegionName)
.reduce((first, second) -> first + ", " + second)
.orElse("");
sender.sendMessage(
player.getName()
+ " belongs to multiple reservations: "
+ names
+ ". Specify one with /metropolis-plot-go <reservationName> [playerName].");
return false;
}
plot = reservations.get(0);
} else {
plot = PlotReservationLookup.findByName(reservations, requestedReservation);
if (plot == null && canManagePlots) {
plot = _plugin.getPlot(requestedReservation);
}
if (plot == null) {
sender.sendMessage(
player.getName()
+ " is not a member or owner of reservation "
+ requestedReservation
+ ".");
return false;
}
}
if (player != sender && !canManagePlots) {
sender.sendMessage("You do not have permission to teleport another player.");
return false;
}
@@ -60,6 +123,11 @@ public class MetropolisPlotGoCommand implements CommandExecutor {
return false;
}
String destination = "reservation " + plot.getRegionName();
sender.sendMessage("Teleported " + player.getName() + " to " + destination + ".");
if (player != sender) {
player.sendMessage("You were teleported to " + destination + ".");
}
return true;
}
}

View File

@@ -22,7 +22,6 @@ commands:
permission: metropolis.home.evict
usage: /metropolis-home-evict <playerName>
metropolis-home-move:
description: This command swaps a player's current home with a reserved plot.
permission: metropolis.home.move
usage: /metropolis-home-move <newHomeNumber> [player]
metropolis-home-go:
@@ -41,9 +40,8 @@ commands:
permission: metropolis.plot.reserve
usage: /metropolis-plot-reserve <name> <minX> <minY> <minZ> <maxX> <maxY> <maxZ>
metropolis-plot-go:
description: This command teleports the user or another player to a plot.
permission: metropolis.plot.go
usage: /metropolis-plot-go <plotName> [playerName]
description: Teleports the sender or an authorized target to a reservation.
usage: /metropolis-plot-go [playerName] or /metropolis-plot-go <reservationName> [playerName]
metropolis-debug-generatetesthomes:
description: This command is ignored on non-debug builds.
permission: metropolis.debug

View File

@@ -0,0 +1,83 @@
/*
This file is part of Metropolis.
Metropolis is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Metropolis is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with Metropolis. If not, see <https://www.gnu.org/licenses/agpl-3.0.txt>.
*/
package com.majinnaibu.bukkitplugins.metropolis;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.List;
import java.util.UUID;
import com.sk89q.worldedit.math.BlockVector3;
import com.sk89q.worldguard.protection.flags.Flags;
import com.sk89q.worldguard.protection.flags.StateFlag;
import com.sk89q.worldguard.protection.regions.ProtectedCuboidRegion;
import org.junit.jupiter.api.Test;
class PlotReservationLookupTest {
private static final UUID PLAYER_ID = UUID.fromString("123e4567-e89b-12d3-a456-426614174000");
@Test
void findsReservationsWherePlayerIsOwnerOrMemberButExcludesHomeCityAndSpawn() {
ProtectedCuboidRegion memberReservation = region("r_member");
memberReservation.getMembers().addPlayer(PLAYER_ID);
ProtectedCuboidRegion ownerReservation = region("private-yard");
ownerReservation.getOwners().addPlayer(PLAYER_ID);
ProtectedCuboidRegion home = region("h_1_" + PLAYER_ID);
home.getMembers().addPlayer(PLAYER_ID);
ProtectedCuboidRegion city = region("City");
city.getMembers().addPlayer(PLAYER_ID);
ProtectedCuboidRegion spawn = region("Spawn");
spawn.getMembers().addPlayer(PLAYER_ID);
ProtectedCuboidRegion unrelated = region("other-region", false);
unrelated.getMembers().addPlayer(PLAYER_ID);
List<Plot> reservations =
PlotReservationLookup.forPlayer(
List.of(memberReservation, ownerReservation, home, city, spawn, unrelated), PLAYER_ID);
assertEquals(
List.of("private-yard", "r_member"),
reservations.stream().map(Plot::getRegionName).toList());
}
@Test
void findsNamedReservationWithOrWithoutPrefix() {
ProtectedCuboidRegion reservation = region("r_camp");
reservation.getMembers().addPlayer(PLAYER_ID);
List<Plot> reservations = PlotReservationLookup.forPlayer(List.of(reservation), PLAYER_ID);
assertEquals("r_camp", PlotReservationLookup.findByName(reservations, "camp").getRegionName());
assertEquals(
"r_camp", PlotReservationLookup.findByName(reservations, "r_camp").getRegionName());
}
private static ProtectedCuboidRegion region(String id) {
return region(id, true);
}
private static ProtectedCuboidRegion region(String id, boolean reservedFlags) {
ProtectedCuboidRegion region =
new ProtectedCuboidRegion(id, BlockVector3.ZERO, BlockVector3.at(5, 5, 5));
if (reservedFlags) {
region.setFlag(Flags.LAVA_FLOW, StateFlag.State.DENY);
region.setFlag(Flags.SNOW_FALL, StateFlag.State.DENY);
}
return region;
}
}

View File

@@ -17,6 +17,7 @@ along with Metropolis. If not, see <https://www.gnu.org/licenses/agpl-3.0.txt>.
package com.majinnaibu.bukkitplugins.metropolis.commands;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
@@ -64,4 +65,14 @@ class MetropolisHomeAcquireTest {
verify(plugin, never()).acquireHome(player);
}
@Test
void supportsDisablingAutomaticInitialHomeAllocation() {
assertEquals(1, MetropolisPlugin.normalizeInitialHomeCount(1));
assertTrue(MetropolisPlugin.shouldAutoGenerateInitialHome(1));
int zero = MetropolisPlugin.normalizeInitialHomeCount(0);
assertEquals(0, zero);
assertFalse(MetropolisPlugin.shouldAutoGenerateInitialHome(zero));
}
}

View File

@@ -0,0 +1,98 @@
/*
This file is part of Metropolis.
Metropolis is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Metropolis is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with Metropolis. If not, see <https://www.gnu.org/licenses/agpl-3.0.txt>.
*/
package com.majinnaibu.bukkitplugins.metropolis.commands;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.contains;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.UUID;
import com.majinnaibu.bukkitplugins.metropolis.MetropolisPlugin;
import org.bukkit.OfflinePlayer;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.junit.jupiter.api.Test;
class MetropolisHomeMoveCommandTest {
private static final UUID PLAYER_ID = UUID.fromString("123e4567-e89b-12d3-a456-426614174000");
@Test
void selectsTheSendersExistingHome() {
MetropolisPlugin plugin = mock(MetropolisPlugin.class);
Player sender = mock(Player.class);
when(sender.getUniqueId()).thenReturn(PLAYER_ID);
when(sender.getName()).thenReturn("PlayerName");
when(plugin.homeExists(PLAYER_ID, 2)).thenReturn(true);
MetropolisHomeMoveCommand command = new MetropolisHomeMoveCommand(plugin);
assertTrue(command.onCommand(sender, mock(Command.class), "move", new String[] {"2"}));
verify(plugin).setHome(PLAYER_ID, 2);
verify(sender).sendMessage(contains("Home 2 is now active for PlayerName"));
}
@Test
void selectsAnOfflineTargetsExistingHome() {
MetropolisPlugin plugin = mock(MetropolisPlugin.class);
CommandSender sender = mock(CommandSender.class);
OfflinePlayer target = mock(OfflinePlayer.class);
when(plugin.getOfflinePlayer("OfflineName")).thenReturn(target);
when(target.getUniqueId()).thenReturn(PLAYER_ID);
when(target.getName()).thenReturn("OfflineName");
when(plugin.homeExists(PLAYER_ID, 3)).thenReturn(true);
MetropolisHomeMoveCommand command = new MetropolisHomeMoveCommand(plugin);
assertTrue(
command.onCommand(sender, mock(Command.class), "move", new String[] {"3", "OfflineName"}));
verify(plugin).setHome(PLAYER_ID, 3);
verify(sender).sendMessage(contains("Home 3 is now active for OfflineName"));
}
@Test
void rejectsInvalidNumbersMissingPlayersAndNonexistentHomes() {
MetropolisPlugin plugin = mock(MetropolisPlugin.class);
Player sender = mock(Player.class);
when(sender.getUniqueId()).thenReturn(PLAYER_ID);
MetropolisHomeMoveCommand command = new MetropolisHomeMoveCommand(plugin);
assertFalse(command.onCommand(sender, mock(Command.class), "move", new String[] {"0"}));
assertFalse(command.onCommand(sender, mock(Command.class), "move", new String[] {"nope"}));
assertFalse(
command.onCommand(sender, mock(Command.class), "move", new String[] {"1", "unknown"}));
when(plugin.getOfflinePlayer("unknown")).thenReturn(null);
assertFalse(
command.onCommand(sender, mock(Command.class), "move", new String[] {"1", "unknown"}));
assertFalse(
command.onCommand(sender, mock(Command.class), "move", new String[] {"1", "2", "extra"}));
assertFalse(command.onCommand(sender, mock(Command.class), "move", new String[] {"1"}));
verify(plugin, never()).setHome(PLAYER_ID, 0);
verify(sender, times(2)).sendMessage(contains("positive integer"));
verify(sender).sendMessage(contains("does not have home 1"));
verify(sender).sendMessage(contains("Usage:"));
}
}

View File

@@ -0,0 +1,115 @@
/*
This file is part of Metropolis.
Metropolis is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Metropolis is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with Metropolis. If not, see <https://www.gnu.org/licenses/agpl-3.0.txt>.
*/
package com.majinnaibu.bukkitplugins.metropolis.commands;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.contains;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.List;
import java.util.UUID;
import com.majinnaibu.bukkitplugins.metropolis.MetropolisPlugin;
import com.majinnaibu.bukkitplugins.metropolis.Plot;
import com.sk89q.worldedit.math.BlockVector3;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.junit.jupiter.api.Test;
class MetropolisPlotGoCommandTest {
private static final UUID PLAYER_ID = UUID.fromString("123e4567-e89b-12d3-a456-426614174000");
@Test
void teleportsPlayerToTheirOnlyReservation() {
MetropolisPlugin plugin = mock(MetropolisPlugin.class);
Player player = player("Member", PLAYER_ID);
Plot reservation = plot("r_camp");
when(plugin.getReservationsForPlayer(PLAYER_ID)).thenReturn(List.of(reservation));
MetropolisPlotGoCommand command = new MetropolisPlotGoCommand(plugin);
assertTrue(command.onCommand(player, mock(Command.class), "plot-go", new String[0]));
verify(plugin).teleportPlayerToPlot(player, reservation);
verify(player).sendMessage(contains("reservation r_camp"));
}
@Test
void asksForAReservationNameWhenPlayerBelongsToSeveral() {
MetropolisPlugin plugin = mock(MetropolisPlugin.class);
Player player = player("Member", PLAYER_ID);
when(plugin.getReservationsForPlayer(PLAYER_ID))
.thenReturn(List.of(plot("r_camp"), plot("r_garden")));
MetropolisPlotGoCommand command = new MetropolisPlotGoCommand(plugin);
assertFalse(command.onCommand(player, mock(Command.class), "plot-go", new String[0]));
verify(player).sendMessage(contains("r_camp, r_garden"));
verify(plugin, never()).teleportPlayerToPlot(player, plot("r_camp"));
}
@Test
void authorizedSenderCanTargetAnOnlineMember() {
MetropolisPlugin plugin = mock(MetropolisPlugin.class);
CommandSender sender = mock(CommandSender.class);
Player target = player("Member", PLAYER_ID);
Plot reservation = plot("r_camp");
when(sender.hasPermission("metropolis.plot.go")).thenReturn(true);
when(plugin.getPlayer("Member")).thenReturn(target);
when(plugin.getReservationsForPlayer(PLAYER_ID)).thenReturn(List.of(reservation));
MetropolisPlotGoCommand command = new MetropolisPlotGoCommand(plugin);
assertTrue(command.onCommand(sender, mock(Command.class), "plot-go", new String[] {"Member"}));
verify(plugin).teleportPlayerToPlot(target, reservation);
verify(target).sendMessage(contains("You were teleported"));
}
@Test
void reportsNoMembershipAndUnsafeDestinations() {
MetropolisPlugin plugin = mock(MetropolisPlugin.class);
Player player = player("Member", PLAYER_ID);
when(plugin.getReservationsForPlayer(PLAYER_ID)).thenReturn(List.of());
MetropolisPlotGoCommand command = new MetropolisPlotGoCommand(plugin);
assertFalse(command.onCommand(player, mock(Command.class), "plot-go", new String[0]));
verify(player).sendMessage(contains("not a member or owner"));
Plot reservation = plot("r_camp");
when(plugin.getReservationsForPlayer(PLAYER_ID)).thenReturn(List.of(reservation));
when(plugin.teleportPlayerToPlot(player, reservation)).thenReturn("No safe teleport location");
assertFalse(command.onCommand(player, mock(Command.class), "plot-go", new String[0]));
verify(player).sendMessage(contains("No safe teleport location"));
}
private static Player player(String name, UUID id) {
Player player = mock(Player.class);
when(player.getName()).thenReturn(name);
when(player.getUniqueId()).thenReturn(id);
return player;
}
private static Plot plot(String name) {
return new Plot(name, BlockVector3.ZERO, BlockVector3.at(5, 5, 5));
}
}