diff --git a/README.md b/README.md index 673a80f..7dc6a5a 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ BlueMapMini: a BlueMap minimap and coordinates HUD for Paper, rendered in game f It's an unofficial add-on for BlueMap and isn't affiliated with BlueMap's authors. -**Status:** pre-release, version 0.5.2, for Posse 0.11.0. 0.5.2 makes map mode show the coordinate line where BlueMap has no map, instead of nothing. It passed unit tests and the live `coordsonly` and `dimensions` groups (45 checks) on throwaway Paper 26.2; the full live suite wasn't rerun. 0.5.1 only drops a load-order entry that looped with Posse (unit tests and a server rehearsal on a copy of a live server). 0.5.0 passed the full live suite and the real-Posse test (8 checks) on throwaway Paper 26.3 (337 checks, the client font check skipped), 2026-11-25, and on 26.1.2 and 26.2 (337 each) just before the old share keys were dropped; the config change is covered by unit tests there. 0.3.0 passed a full test suite on live Paper 26.1.2, 26.2 and 26.3 servers with real BlueMap tiles, using a protocol bot. 0.4.1 (the share audience setting) passed it again on 26.3 only, 334 of 335 with the client font check skipped, plus the real Posse test. It hasn't been seen in a real game client yet. See [Testing](#testing). +**Status:** pre-release, version 0.5.3. Shares need Posse 0.11.0 or newer, and `players.audience: posse` needs Posse 0.11.3 or newer. 0.5.3 adds `players.audience`, so player dots can follow Posse's circles. It passed the unit tests (113), the live `posse` test (46 checks, with the real Posse 0.11.3) and the rest of the live suite (341 checks, one font check skipped) on throwaway Paper 26.1.2, 26.2 and 26.3. It hasn't been seen in a real game client. 0.5.2 makes map mode show the coordinate line where BlueMap has no map, instead of nothing. It passed unit tests and the live `coordsonly` and `dimensions` groups (45 checks) on throwaway Paper 26.2; the full live suite wasn't rerun. 0.5.1 only drops a load-order entry that looped with Posse (unit tests and a server rehearsal on a copy of a live server). 0.5.0 passed the full live suite and the real-Posse test (8 checks) on throwaway Paper 26.3 (337 checks, the client font check skipped), 2026-11-25, and on 26.1.2 and 26.2 (337 each) just before the old share keys were dropped; the config change is covered by unit tests there. 0.3.0 passed a full test suite on live Paper 26.1.2, 26.2 and 26.3 servers with real BlueMap tiles, using a protocol bot. 0.4.1 (the share audience setting) passed it again on 26.3 only, 334 of 335 with the client font check skipped, plus the real Posse test. It hasn't been seen in a real game client yet. See [Testing](#testing). - Requires Paper 26.1 or newer, Java 25, and a BlueMap version that matches your server (see below). Java Edition only. Paper 1.21.11 and older aren't supported. - Works alongside other resource packs, because it never overrides a shader and only adds its own files. @@ -57,7 +57,7 @@ If another plugin owns a name, BlueMapMini backs off: `/map` to `/worldmap`, the | --- | --- | --- | | `bluemapmini.use` | everyone | Seeing the map at all. Removing it hides everything for that group. | | `bluemapmini.fullscreen` | everyone | The fullscreen map. | -| `bluemapmini.seeplayers` | everyone | Other players on the map. | +| `bluemapmini.seeplayers` | everyone | Other players on the map. `players.audience` can narrow who shows up. | | `bluemapmini.share.send` | everyone | Sharing your coordinates with `/hud share`. | | `bluemapmini.share.receive` | everyone | Receiving coordinates other players share. | | `bluemapmini.admin` | ops | `/bluemapmini reload`, `debug` and `pack`. | @@ -87,6 +87,23 @@ The clock follows the coordinates as a small picture and 24-hour time, such as ` Up to 8 themes fit in the pack. Every built-in theme passes the same readability test, and the plugin warns about one of yours that doesn't. Text needs a WCAG contrast of 4.5:1 against the plate, and three quarters of each clock picture needs 3:1. Both are checked over ten backgrounds from white to black, including the brightest pure colors. A theme that fails still loads, so you can fix it. +## Player dots + +The map shows other players in your world within `players.radius` blocks (512 by default) as dots, with arrows at the edge for those farther off the minimap. Players you can't see stay off it: vanished, spectating, invisible and hidden in BlueMap. `players.audience` decides who else is left out: + +- `world`: nobody. This is the default. +- `posse`: everyone who doesn't share a Posse circle with you, unless you or they have `posse.bypass`. Needs Posse 0.11.3 or newer. If Posse has no circles set up, nobody is left out. + +**Dots follow circles only.** Chat also reaches players in the same world, unless that world is circle-only. Dots don't: two players in different circles never see each other's dots in any world, apart from the `posse.bypass` case above. + +With `posse`, **no dots are shown** while Posse is missing, disabled, paused, older than 0.11.3 or failing a check. Any other value counts as `posse`, and so does a `config.yml` that's invalid, empty or unreadable. The console says why. When Posse can't be asked, it also warns at most once a minute, and a player who opens the fullscreen map, or runs `/hud show players` or `/hud` with the map hidden, is told that other players aren't shown. A Posse without the circles check (older than 0.11.3) is reported in the console once, with a line saying to update it. A paused Posse answers no, so dots are hidden without those messages, and Posse reports the pause itself. + +**Typos count as `posse` too.** Any key that looks like `audience` and isn't `players.audience` or `share.audience` makes the dots follow Posse, even if `players.audience` also says `world`. That covers an `audience:` line at the left edge, spellings such as `audiance` or `Audience`, and an `audience` in the wrong section. A setting written twice does the same. Other unknown keys under `players:` get a warning and change nothing. The spelling check allows up to two wrong letters, so a very mangled key under `players:` only gets the warning, and a mistyped section name with a mistyped key far from `audience` isn't noticed. + +A `config.yml` from before 0.5.3 doesn't have the key and stays `world`. To turn the filter on, add `audience: posse` under `players:`, run `/bluemapmini reload`, and check that the console says `Player dots: only players Posse's circles allow.` with no warning just above or below it. + +This setting covers BlueMapMini's in-game map only. BlueMap's web map has its own player settings. + ## Sharing coordinates `/hud share` sends your current coordinates to people you choose, as a chat message with the coordinates and the dimension, such as `Alex shared where they are: 120 64 -35 in the Overworld`. Clicking the numbers copies them. Nothing is shared unless a player asks, and there's no teleport link. @@ -127,6 +144,7 @@ The plugin sends its pack alongside any others using the multi-pack API, and pla - **Other pink boss bars:** the pack makes one boss bar color transparent, so another plugin's bar in that color disappears too. Choose a color with `pack.boss-bar-color` that nothing else uses. - **Repeated pack wipes:** the pack is re-sent once per session. If another plugin clears packs again, the map stays hidden for that player until they rejoin. This is what stops two plugins fighting in a loop. - **Bedrock players:** Geyser and Floodgate players don't get a map, because they can't use the pack. +- **BlueMap's web map:** `players.audience` doesn't change what BlueMap's own web map shows. Set that in BlueMap. ## How it works @@ -150,7 +168,7 @@ Real terrain has more color variation than the test map, so expect larger update The plugin has also been tested on live Paper 26.1.2, 26.2 and 26.3 servers with BlueMap 5.29. A protocol bot played the client. It speaks the 1.21.11 protocol and joined through ViaBackwards, so the packets were translated rather than sent by a real 26.x client. Every frame it received was decoded and compared cell by cell with BlueMap's tile files on disk. -The live tests are in [`test/live`](test/live/README.md), with what they cover and what's simulated. `test/live/run.sh` builds a throwaway server, runs them and deletes it. +The live tests are in [`test/live`](test/live/README.md), with what they cover and what's simulated. `test/live/run.sh` builds a throwaway server, runs them and deletes it. The lists below come from earlier releases. They don't include `players.audience`, which has unit tests only so far. **Passed on all three servers:** diff --git a/build.gradle.kts b/build.gradle.kts index 210a3bb..5d9223f 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -3,7 +3,7 @@ plugins { } group = "com.extantape" -version = "0.5.2" +version = "0.5.3" java { toolchain.languageVersion.set(JavaLanguageVersion.of(25)) diff --git a/docs/decisions.md b/docs/decisions.md index 249afe3..0536790 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -26,3 +26,16 @@ Owner decisions for BlueMapHUD, newest first. ## 2026-11-14 - **Name (owner, D194, D196):** the plugin is renamed BlueMapMini, so it starts with BlueMap like BlueMapAuth and the other BlueMap add-ons. Released as 0.3.0. The owner asked that no old names be kept, so the Java package, commands, permissions, pack ID, player settings key and folder all use the new name, with no aliases or copies. Sharing stays off until HouseRules is 0.5.0, which hooks the new share event, so shares can never skip chat circles. + +## 2026-11-30: Player dots can follow Posse (0.5.3) + +A kids' safety design from the Games division, built as handed over. No new owner decision is recorded here. + +- The 2026-11-07 row that keeps showing players within 512 blocks to everyone assumed that different groups of players never share a world. A server can't rely on that when it has shared worlds, so `players.audience: posse` filters the dots with Posse. `world` stays the default, so other servers don't change. +- **Dots follow circles only** (changed the same day, before release, after a safety review). The first build used Posse's reach check, the rule chat follows. That check also allows anyone in the same world unless the world is circle-only, so players in different circles saw each other's dots in a shared world. Dots now use `inSharedCircle`, added in Posse 0.11.3: a shared circle, or `posse.bypass` on either player. Posse with no circles set up allows everyone. Shares aren't changed and still follow chat. +- With `posse`, every doubt means no dots: Posse missing, disabled, older than 0.11.3 or without the circles check, not the owner of the registered service, or throwing. It never falls back to the reach check. One failed check drops all of that viewer's dots. A paused Posse refuses everyone through the circles check, bypass included. A Posse without the check is logged once, with no names. +- Only `world` and `posse` are accepted, read the way `share.audience` values are (trimmed, any case). Everything else is `posse`, including `off`. +- A typo never leaves the dots open (from a second safety review, the same day). A key that looks like `audience`, anywhere but `players.audience` and `share.audience`, means `posse`, whatever the right line says. A top-level `audience` is one of these. So is a repeated key. Other unknown keys under `players:` are only warned about. "Looks like" is a choice made in the build: any capitals, and up to two letters wrong, missing, extra or swapped, as the whole key or one word of it, and under `players:` any word starting "aud". +- The setting is read from `config.yml` itself. Bukkit hands out the jar's defaults for a broken file, which would turn the filter off. A readable file without the key stays `world`. +- Posse is found by reflection through the services manager, so there's still no load-order entry for it. + diff --git a/docs/releases/v0.5.3.md b/docs/releases/v0.5.3.md new file mode 100644 index 0000000..67019aa --- /dev/null +++ b/docs/releases/v0.5.3.md @@ -0,0 +1,18 @@ +# BlueMapMini 0.5.3 + +- **Player dots can follow Posse's circles.** The new setting `players.audience` takes `world` or `posse`. With `posse`, a player is a dot on your map only if you share a Posse circle, or either of you has `posse.bypass`. Being in the same world doesn't count, so this is stricter than chat: players in different circles never see each other's dots in any world, apart from that bypass. Every earlier rule still applies (same world, radius, permission, vanish, spectator, invisibility, hidden in BlueMap). This covers the minimap, the arrows at its edge and the fullscreen map. It needs Posse 0.11.3 or newer, the first version with a circles-only check. +- **Any doubt means no dots.** With `posse`, nobody is shown while Posse is missing, disabled, paused, older than 0.11.3 or failing a check. Any value other than `world` or `posse` counts as `posse`, and so does a `config.yml` that's invalid, empty or unreadable, because Bukkit would otherwise fall back to the jar's default. The console says why. +- **A typo doesn't leave the dots open.** A key that looks like `audience` and isn't `players.audience` or `share.audience` counts as `posse`, even beside `players.audience: world`: one at the left edge, one in the wrong section, or a spelling such as `audiance` or `Audience`. So does a `config.yml` with a setting written twice, because only the last copy would be read. Other unknown keys under `players:` get a console warning and change nothing. The spelling check allows up to two wrong letters. +- **Players are told.** When dots are off because Posse can't be asked, the console warns at most once a minute. A player who opens the fullscreen map, or runs `/hud show players` or `/hud` with the map hidden, sees "Other players aren't shown on the map right now, because the server's player group rules aren't answering." With a Posse older than 0.11.3, the console says once to update it, without naming anyone. While Posse is paused it answers no, so dots are hidden without that line or warning. Posse reports the pause itself. +- **Nothing changes until you turn it on.** The default is `world`, and an existing `config.yml` without the key stays `world`. + +**To turn it on**, add this line under `players:` in `plugins/BlueMapMini/config.yml` (an existing file doesn't have it), then run `bluemapmini reload`: + +```yaml +players: + audience: posse +``` + +The console should say "Player dots: only players Posse's circles allow." with no warning just above or below it. If Posse has no circles set up, it allows everyone. + +Tested: 113 unit tests, including 36 new ones for reading the setting and its typos, filtering dots, every refusal, finding Posse and the positions the HUD's player list sends. Those use stand-in players, and the invisibility filter isn't among them because it needs a running server. On throwaway Paper 26.1.2, 26.2 and 26.3 servers, the live `posse` test passed 46/46 with the real Posse 0.11.3, decoding what each viewer is sent. It covers players in different circles, `posse.bypass` both ways, no circles, a paused, disabled or missing Posse, and two misspelled keys with their console warnings. The rest of the live suite passed 341/341 on each version, with one font check skipped because it needs a Minecraft client. Not tested: no live check covers a repeated key, a broken `config.yml` or an older Posse. Not seen in a real game client. diff --git a/docs/test-audit.md b/docs/test-audit.md index ff311cf..ff0fc4a 100644 --- a/docs/test-audit.md +++ b/docs/test-audit.md @@ -2,6 +2,26 @@ Kept by this repo's owning session (Minecraft: Plugins Lead), per `~/Code/CLAUDE.md`, "Test self-audits". Newest first. +## 2026-11-30: Player dots follow Posse (0.5.3) + +Fails closed, so it's always covered. The unit tests passed (113). The live checks in `test/live/posse.js` passed 46/46 with the real Posse 0.11.3 on 26.1.2, 26.2 and 26.3, and the rest of the live suite passed 341/341 on each, with the client font check skipped. + +| Promise | Covered by | +| --- | --- | +| With `posse`, a refused player gets no dot and an allowed one does | unit `PlayerDotsTest.aRefusedPlayerGetsNoDotAndAnAllowedOneDoes`, `HudDotsTest.onlyAPlayerTheCirclesCheckAllowsHasAPositionSent`; live one dot for each of two players in one circle, none for a player in another, none for a player in no circle, minimap and fullscreen map; `posse.bypass` seen and seeing; every dot when Posse has no circles | +| Dots follow circles only, never chat's reach check, so a shared world adds nobody | unit `PosseLinkTest.theCirclesCheckAnswersAndChatsCheckIsNeverUsed`; live in a world that isn't circle-only, chat reaches a player in another circle (control) and neither gets the other's dot. Posse's own unit tests cover what the circles check answers | +| A Posse without the circles check means no dots, said once with no names | unit `PosseLinkTest.aPosseWithoutTheCirclesCheckIsMarkedAsLackingIt`, `PlayerDotsTest.aPosseWithoutTheCirclesCheckMeansNoDotsAndIsSaidOnceWithNoNames` | +| No dots with Posse missing, disabled, unregistered, someone else's service, or throwing | unit `PosseLinkTest`, `PlayerDotsTest.aMissingPosseMeansNoDots`, `oneFailingCallDropsEveryDotIncludingOnesAlreadyAllowed`, `aFailingLookupMeansNoDots`, `HudDotsTest.noPosseAnOldPosseOrAFailingCheckSendsNoPositions`; live without Posse, and Posse disabled while the server runs | +| No dots while Posse is paused | unit `aPosseThatSaysNoToEveryoneAsItDoesWhilePausedLeavesNoDots`; live Posse started paused by a broken Posse config, with two bots given `posse.bypass` as they log in | +| Being allowed by Posse doesn't undo the other filters | unit `HudDotsTest.sharingACircleDoesNotBringBackAPlayerAnotherFilterHides` (vanished, spectator, hidden in BlueMap, out of range); the existing live suite covers invisibility | +| Posse is asked every time, so a change takes effect on the next frame | unit `posseIsAskedAfreshEveryTimeSoDisablingItDropsTheDots` | +| A bad value, and a broken, empty or unreadable config, count as `posse` | unit `DotRuleTest`; live a bad value | +| A misspelled or misplaced `audience` key, or a repeated key, counts as `posse`; other unknown keys under `players:` only warn; real settings and ordinary words elsewhere are left alone | unit `DotRuleTest.aTopLevelAudienceIsPosse`, `aTopLevelAudienceIsPosseEvenBesideAGoodSetting`, `aMisspelledKeyThatLooksLikeAudienceIsPosse`, `aLookalikeIsPosseWhateverItSaysAndBesideAGoodSetting`, `anAudienceInTheWrongSectionIsPosse`, `aRepeatedKeyIsPosse`, `anUnknownKeyUnderPlayersWarnsAndKeepsTheSetting`, `everyRealPlayersSettingIsKnown`, `ordinaryWordsElsewhereAreNotTakenForAudience`, `theShippedConfigSaysWorld`; live a misspelled `players.audience`, alone and beside `audience: world`, counts as `posse` and the console says so. No live check of a repeated or misplaced key | +| `world` and a config without the key behave as before | unit `DotRuleTest.aReadableFileWithoutTheSettingKeepsTheOldBehavior`, `PlayerDotsTest.worldLeavesTheListAloneAndNeverAsksPosse`; live `world` shows everyone | + +- The unit tests call the filtering method with stand-in players. The live checks show what a bot's client is sent. No real game client has been used. +- Gap skipped: no live run with a Posse older than 0.11.3. It would need a second Posse jar, and the unit tests cover finding no circles check. +- Gap skipped: a broken `config.yml` isn't tried on a server. Bukkit would fall back to the jar's defaults for every setting, which opens the pack server on every address. `DotRuleTest` covers how the file is read. ## 2026-11-25: Posse rename (0.5.0) | Promise | Covered by | diff --git a/src/main/java/com/extantape/bluemapmini/BlueMapMiniPlugin.java b/src/main/java/com/extantape/bluemapmini/BlueMapMiniPlugin.java index 06d491c..c5fcac9 100644 --- a/src/main/java/com/extantape/bluemapmini/BlueMapMiniPlugin.java +++ b/src/main/java/com/extantape/bluemapmini/BlueMapMiniPlugin.java @@ -1,6 +1,7 @@ package com.extantape.bluemapmini; import com.extantape.bluemapmini.command.HudCommands; +import com.extantape.bluemapmini.config.DotRule; import com.extantape.bluemapmini.config.HudConfig; import com.extantape.bluemapmini.hud.FrameBuilder; import com.extantape.bluemapmini.hud.HudManager; @@ -53,6 +54,7 @@ public final class BlueMapMiniPlugin extends JavaPlugin implements Listener { private static final int LOOK_DOWN_PITCH = 80; private HudConfig config; + private DotRule dotRule; private PackService packs; private HudManager hud; private GridCache grid; @@ -70,6 +72,7 @@ public void onEnable() { config = HudConfig.from(getConfig()); packs = new PackService(this, getDataFolder().toPath().resolve("pack")); hud = new HudManager(this, packs); + readDotRule(); shares = new ShareService(this); shareMenu = new ShareMenu(this, shares); rebuildPack(); @@ -105,8 +108,10 @@ public void onDisable() { /** Re-reads config.yml. Players get the pack again only if its contents changed. */ public void reload() { reloadConfig(); + readDotRule(); config = HudConfig.from(getConfig()); logShareAudience(); + logDotAudience(); boolean changed = rebuildPack(); stopRendering(); BlueMapAPI.getInstance().ifPresent(this::startRendering); @@ -135,7 +140,17 @@ public void toggleFullscreen(Player player) { HudSession session = hud.session(player); boolean open = !session.fullscreen(); hud.setFullscreen(player, session, open); - if (open) explainIfNoMap(player); + if (open) { + explainIfNoMap(player); + explainIfNoDots(player); + } + } + + /** Says why there are no player dots, when it's because Posse can't be asked. */ + public void explainIfNoDots(Player player) { + if (!hud.session(player).settings().showPlayers || !Perms.has(player, "bluemapmini.seeplayers")) return; + if (!hud.dots().offForWantOfPosse()) return; + player.sendMessage(Component.text("Other players aren't shown on the map right now, because the server's player group rules aren't answering.", NamedTextColor.YELLOW)); } /** Says why nothing appeared, because otherwise a missing map looks like a broken command. */ @@ -282,6 +297,25 @@ private boolean isBedrock(Player player) { @EventHandler public void onServerLoad(ServerLoadEvent event) { logShareAudience(); + logDotAudience(); + } + + /** + * players.audience comes from the file itself: Bukkit answers a broken config.yml with the built-in defaults, and + * the default there is the open one. + */ + private void readDotRule() { + dotRule = DotRule.read(getDataFolder().toPath().resolve("config.yml")); + hud.dotAudience(dotRule.audience()); + } + + /** Says who can be a dot, and warns about a bad setting or a Posse that can't be asked. */ + private void logDotAudience() { + if (dotRule.problem() != null) getLogger().warning(dotRule.problem()); + getLogger().info("Player dots: " + (dotRule.audience() == DotRule.Audience.WORLD + ? "everyone nearby in the same world." + : "only players Posse's circles allow.")); + hud.dots().warnIfOff(); } /** Says who coordinates can be shared with, and warns about a bad setting. Also run after a reload. */ diff --git a/src/main/java/com/extantape/bluemapmini/command/HudCommands.java b/src/main/java/com/extantape/bluemapmini/command/HudCommands.java index cc15549..5931c28 100644 --- a/src/main/java/com/extantape/bluemapmini/command/HudCommands.java +++ b/src/main/java/com/extantape/bluemapmini/command/HudCommands.java @@ -230,6 +230,7 @@ private LiteralArgumentBuilder partOption(String part, boole return; } reply(p, (visible ? "Showing " : "Hiding ") + (part.equals("clock") ? "the clock" : part) + "."); + if (part.equals("players") && visible) plugin.explainIfNoDots(p); if (part.equals("clock") && visible && !plugin.config().hud().clock()) { error(p, "The clock is turned off on this server, so it won't show."); } @@ -307,7 +308,10 @@ private void setCoordsOnly(Player player, HudSession session, boolean coordsOnly private void explainIfHidden(Player player, HudSession session) { if (session.settings().coordsOnly) plugin.explainIfNoPack(player); - else plugin.explainMinimapIfNoMap(player, session.settings().showCoords); + else { + plugin.explainMinimapIfNoMap(player, session.settings().showCoords); + plugin.explainIfNoDots(player); + } } private static String hudName(HudSession session) { diff --git a/src/main/java/com/extantape/bluemapmini/config/DotRule.java b/src/main/java/com/extantape/bluemapmini/config/DotRule.java new file mode 100644 index 0000000..309876b --- /dev/null +++ b/src/main/java/com/extantape/bluemapmini/config/DotRule.java @@ -0,0 +1,179 @@ +package com.extantape.bluemapmini.config; + +import org.bukkit.configuration.InvalidConfigurationException; +import org.bukkit.configuration.file.YamlConfiguration; +import org.yaml.snakeyaml.LoaderOptions; +import org.yaml.snakeyaml.Yaml; +import org.yaml.snakeyaml.constructor.SafeConstructor; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Collections; +import java.util.IdentityHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Set; + +/** + * players.audience: who may be a dot on the map. It's read from the server's own config.yml, apart from the rest of + * the settings, because Bukkit answers a broken file with the built-in defaults, and the default here is the open one. + *

+ * A readable file without the setting means {@code world}, as before the setting existed. A plain {@code world} or + * {@code posse} means what it says. A key that looks like the setting, misspelled or in the wrong place, means + * {@code posse} whatever else the file says, and so does every other case of doubt. Any other unknown key under + * players is only warned about. + * + * @param audience who may be a dot + * @param problem what to warn the log about, or null + */ +public record DotRule(Audience audience, String problem) { + public enum Audience { + /** Anyone nearby in the viewer's world, subject to the other players settings. */ + WORLD, + /** Only players Posse's circles-only check allows. Nobody while Posse is missing, too old, paused or failing. */ + POSSE + } + + private static final String PATH = "players.audience"; + /** The other setting with "audience" in it, which is about shared locations and is read elsewhere. */ + private static final String SHARE_PATH = "share.audience"; + private static final String PLAYERS = "players."; + private static final String WORD = "audience"; + /** Every setting read under players. {@link HudConfig} reads all of these but audience. */ + private static final Set PLAYER_KEYS = Set.of("audience", "radius", "hide-vanished", "hide-spectators", + "hide-invisible", "hide-bluemap-hidden", "edge-arrows"); + + private static DotRule world() { + return new DotRule(Audience.WORLD, null); + } + + private static DotRule doubt(String why) { + return new DotRule(Audience.POSSE, why + ", so player dots follow Posse. Set players.audience to world or posse."); + } + + /** Reads the rule from config.yml. A file that's missing or can't be read means posse. */ + public static DotRule read(Path configFile) { + try { + return parse(Files.readString(configFile, StandardCharsets.UTF_8)); + } catch (IOException e) { + return doubt("config.yml couldn't be read"); + } + } + + /** The rule in this config.yml text. */ + public static DotRule parse(String text) { + YamlConfiguration yaml = new YamlConfiguration(); + Object raw; + try { + // Bukkit drops a key with no value, so the raw document is needed to tell that apart from no key. + // A repeated key would quietly keep only the last one, which could swap posse for world. + LoaderOptions options = new LoaderOptions(); + options.setAllowDuplicateKeys(false); + raw = new Yaml(new SafeConstructor(options)).load(text); + yaml.loadFromString(text); + } catch (InvalidConfigurationException | RuntimeException e) { + String detail = String.valueOf(e.getMessage()); + return doubt(detail.contains("duplicate key") + ? "config.yml has the same setting twice" + : "config.yml isn't valid YAML"); + } + if (!(raw instanceof Map root)) return doubt("config.yml is empty or isn't a list of settings"); + + List strays = new ArrayList<>(); + List unknown = new ArrayList<>(); + scan(root, "", Collections.newSetFromMap(new IdentityHashMap<>()), strays, unknown); + DotRule rule = setting(yaml, root); + + List notes = new ArrayList<>(); + if (rule.problem() != null) notes.add(rule.problem()); + if (!strays.isEmpty()) { + notes.add("config.yml has " + String.join(", ", strays) + ", which looks like players.audience misspelled or" + + " in the wrong place, so player dots follow Posse. Remove it and set players.audience to world or posse."); + } + if (!unknown.isEmpty()) { + notes.add("config.yml has settings under players that BlueMapMini doesn't know: " + String.join(", ", unknown) + + ". They do nothing. Check the spelling."); + } + Audience audience = strays.isEmpty() ? rule.audience() : Audience.POSSE; + return new DotRule(audience, notes.isEmpty() ? null : String.join(" ", notes)); + } + + /** What players.audience itself says, before looking for stray or unknown keys. */ + private static DotRule setting(YamlConfiguration yaml, Map root) { + if (yaml.contains(PATH)) { + HudConfig.ShareAudience value = HudConfig.ShareAudience.of(String.valueOf(yaml.get(PATH))); + if (value == HudConfig.ShareAudience.WORLD) return world(); + if (value == HudConfig.ShareAudience.POSSE) return new DotRule(Audience.POSSE, null); + return doubt("players.audience isn't world or posse"); + } + if (root.containsKey(PATH)) return doubt("players.audience has no value"); + if (!root.containsKey("players")) return world(); + if (!(root.get("players") instanceof Map players)) return doubt("The players section of config.yml has no settings in it"); + return players.containsKey("audience") ? doubt("players.audience has no value") : world(); + } + + /** + * Walks every key in the file. {@code strays} collects keys that look like they were meant to be players.audience, + * and {@code unknown} collects other keys under players that the plugin doesn't read. + * + * @param open the sections being walked, so a file that refers back to itself can't loop + */ + private static void scan(Object node, String parent, Set open, List strays, List unknown) { + if (!(node instanceof Map) && !(node instanceof List)) return; + if (!open.add(node)) return; + if (node instanceof List list) { + for (Object item : list) scan(item, parent, open, strays, unknown); + } else { + for (Map.Entry entry : ((Map) node).entrySet()) { + String key = String.valueOf(entry.getKey()); + String path = parent.isEmpty() ? key : parent + "." + key; + if (!path.equals(PATH) && !path.equals(SHARE_PATH)) { + boolean underPlayers = path.startsWith(PLAYERS); + if (looksLikeAudience(key, underPlayers)) { + strays.add(path); + } else if (underPlayers && !path.substring(PLAYERS.length()).contains(".") + && !PLAYER_KEYS.contains(path.substring(PLAYERS.length()))) { + unknown.add(path); + } + } + scan(entry.getValue(), path, open, strays, unknown); + } + } + open.remove(node); + } + + /** + * Whether a key reads as "audience": any capitals, with up to two letters wrong, missing, extra or swapped, on its + * own or as one word of a longer name. Under players, a word that starts "aud" counts too. + */ + private static boolean looksLikeAudience(String key, boolean underPlayers) { + String lower = key.toLowerCase(Locale.ROOT); + String joined = lower.replaceAll("[^a-z]", ""); + if (joined.contains("audien") || distance(joined, WORD) <= 2) return true; + for (String word : lower.split("[^a-z]+")) { + if (distance(word, WORD) <= 2 || underPlayers && word.startsWith("aud")) return true; + } + return false; + } + + /** Edits needed to turn one word into the other, counting two swapped neighbors as one. */ + private static int distance(String a, String b) { + int[][] d = new int[a.length() + 1][b.length() + 1]; + for (int i = 0; i <= a.length(); i++) d[i][0] = i; + for (int j = 0; j <= b.length(); j++) d[0][j] = j; + for (int i = 1; i <= a.length(); i++) { + for (int j = 1; j <= b.length(); j++) { + int change = a.charAt(i - 1) == b.charAt(j - 1) ? 0 : 1; + d[i][j] = Math.min(d[i - 1][j - 1] + change, Math.min(d[i - 1][j], d[i][j - 1]) + 1); + if (i > 1 && j > 1 && a.charAt(i - 1) == b.charAt(j - 2) && a.charAt(i - 2) == b.charAt(j - 1)) { + d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1); + } + } + } + return d[a.length()][b.length()]; + } +} diff --git a/src/main/java/com/extantape/bluemapmini/hud/HudManager.java b/src/main/java/com/extantape/bluemapmini/hud/HudManager.java index d0cb12f..fe7fda1 100644 --- a/src/main/java/com/extantape/bluemapmini/hud/HudManager.java +++ b/src/main/java/com/extantape/bluemapmini/hud/HudManager.java @@ -1,5 +1,6 @@ package com.extantape.bluemapmini.hud; +import com.extantape.bluemapmini.config.DotRule; import com.extantape.bluemapmini.config.HudConfig; import com.extantape.bluemapmini.pack.PackService; import de.bluecolored.bluemap.api.BlueMapAPI; @@ -31,6 +32,7 @@ import java.util.concurrent.Executors; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.atomic.AtomicLong; +import java.util.function.Predicate; /** * The update loop. Each cycle snapshots players on the main thread, then background threads compare @@ -42,6 +44,7 @@ public final class HudManager { private final Plugin plugin; private final PackService packs; + private final PlayerDots dots; private final Map sessions = new ConcurrentHashMap<>(); private final WorldMapCache worldMaps = new WorldMapCache(System::currentTimeMillis); private final Map bedrock = new ConcurrentHashMap<>(); @@ -66,6 +69,17 @@ public final class HudManager { public HudManager(Plugin plugin, PackService packs) { this.plugin = plugin; this.packs = packs; + this.dots = new PlayerDots(() -> PosseLink.find(Bukkit.getPluginManager(), Bukkit.getServicesManager()), + plugin.getLogger()::warning, System::currentTimeMillis); + } + + /** Sets who may be a dot, from players.audience. */ + public void dotAudience(DotRule.Audience audience) { + dots.audience(audience); + } + + public PlayerDots dots() { + return dots; } /** @@ -265,23 +279,34 @@ private int[] visiblePlayers(Player viewer, HudSession session, Location at) { if (!session.settings.showPlayers || !com.extantape.bluemapmini.Perms.has(viewer, "bluemapmini.seeplayers")) return new int[0]; HudConfig.Players rules = config.players(); BlueMapAPI api = rules.hideBlueMapHidden() ? BlueMapAPI.getInstance().orElse(null) : null; + Predicate hiddenOnWebMap = + other -> api != null && !api.getWebApp().getPlayerVisibility(other.getUniqueId()); + return dotPositions(dots, viewer, at, viewer.getWorld().getPlayers(), rules, hiddenOnWebMap); + } + + /** The x and z of every player this viewer is sent as a dot, in pairs. */ + static int[] dotPositions(PlayerDots dots, Player viewer, Location at, List others, HudConfig.Players rules, + Predicate hiddenOnWebMap) { double radiusSquared = (double) rules.radius() * rules.radius(); - List others = viewer.getWorld().getPlayers(); - int[] positions = new int[others.size() * 2]; - int count = 0; + List candidates = new ArrayList<>(others.size()); for (Player other : others) { if (other == viewer) continue; if (rules.hideVanished() && (isVanished(other) || !viewer.canSee(other))) continue; if (rules.hideSpectators() && other.getGameMode() == GameMode.SPECTATOR) continue; if (rules.hideInvisible() && other.hasPotionEffect(PotionEffectType.INVISIBILITY)) continue; - if (api != null && !api.getWebApp().getPlayerVisibility(other.getUniqueId())) continue; - Location position = other.getLocation(); - if (position.distanceSquared(at) > radiusSquared) continue; - positions[count * 2] = position.getBlockX(); - positions[count * 2 + 1] = position.getBlockZ(); - count++; + if (hiddenOnWebMap.test(other)) continue; + if (other.getLocation().distanceSquared(at) > radiusSquared) continue; + candidates.add(other); + } + // players.audience has the last word, after every check above. + List shown = dots.keep(viewer, candidates); + int[] positions = new int[shown.size() * 2]; + for (int i = 0; i < shown.size(); i++) { + Location position = shown.get(i).getLocation(); + positions[i * 2] = position.getBlockX(); + positions[i * 2 + 1] = position.getBlockZ(); } - return count * 2 == positions.length ? positions : java.util.Arrays.copyOf(positions, count * 2); + return positions; } /** diff --git a/src/main/java/com/extantape/bluemapmini/hud/PlayerDots.java b/src/main/java/com/extantape/bluemapmini/hud/PlayerDots.java new file mode 100644 index 0000000..c397a7d --- /dev/null +++ b/src/main/java/com/extantape/bluemapmini/hud/PlayerDots.java @@ -0,0 +1,125 @@ +package com.extantape.bluemapmini.hud; + +import com.extantape.bluemapmini.config.DotRule; +import org.bukkit.entity.Player; + +import java.util.ArrayList; +import java.util.List; +import java.util.function.BiPredicate; +import java.util.function.Consumer; +import java.util.function.LongSupplier; +import java.util.function.Supplier; + +/** + * Applies players.audience to the players who passed every other check for a dot. Under {@code posse} a player stays + * only if Posse's circles-only check allows it: a shared circle, or posse.bypass. Being in the same world doesn't + * count. If Posse can't be found, has no such check, or any call fails, the viewer gets no dots at all. Main thread + * only. + */ +public final class PlayerDots { + static final String OFF_WARNING = "Player dots are off: players.audience follows Posse, and Posse isn't answering"; + static final String LACKS_WARNING = "Player dots are off: players.audience follows Posse, and this Posse has no " + + "circles-only check. Update Posse to 0.11.3 or newer."; + static final long WARN_EVERY_MILLIS = 60_000; + /** Stands for an installed Posse without the circles-only check. It says no to everyone. */ + static final BiPredicate NO_CIRCLES_CHECK = (viewer, other) -> false; + + private final Supplier> posse; + private final Consumer warn; + private final LongSupplier clock; + private long warnedAt; + private boolean warned; + private boolean lastCallFailed; + private boolean saidItLacksTheCheck; + /** Starts strict, so nothing is shown unfiltered before the config has been read. */ + private DotRule.Audience audience = DotRule.Audience.POSSE; + + /** + * @param posse gives Posse's circles-only check as it is right now, {@link #NO_CIRCLES_CHECK} if the installed + * Posse doesn't have it, or null if Posse isn't there to ask + */ + PlayerDots(Supplier> posse, Consumer warn, LongSupplier clock) { + this.posse = posse; + this.warn = warn; + this.clock = clock; + } + + void audience(DotRule.Audience audience) { + this.audience = audience; + } + + public DotRule.Audience audience() { + return audience; + } + + /** The candidates this viewer may see as dots. Posse is looked up again on every call. */ + List keep(Player viewer, List candidates) { + if (audience == DotRule.Audience.WORLD) return candidates; + try { + BiPredicate reach = posse.get(); + if (reach == null) return off(); + if (reach == NO_CIRCLES_CHECK) { + warnLacking(); + return List.of(); + } + List kept = new ArrayList<>(candidates.size()); + for (Player other : candidates) if (reach.test(viewer, other)) kept.add(other); + if (!candidates.isEmpty()) lastCallFailed = false; + return kept; + } catch (RuntimeException | LinkageError e) { + lastCallFailed = true; + return off(); + } + } + + /** + * Whether dots are off because Posse is missing, too old or failing. A paused Posse still answers, with a no for + * everyone, so it isn't counted here. + */ + public boolean offForWantOfPosse() { + if (audience == DotRule.Audience.WORLD) return false; + try { + BiPredicate reach = posse.get(); + return reach == null || reach == NO_CIRCLES_CHECK || lastCallFailed; + } catch (RuntimeException | LinkageError e) { + return true; + } + } + + /** + * Logs the warning if dots are off for want of Posse, at most once a minute. A Posse without the circles-only check + * is reported once. + */ + public void warnIfOff() { + if (!offForWantOfPosse()) return; + if (lacksTheCheck()) warnLacking(); + else warnNow(); + } + + private boolean lacksTheCheck() { + try { + return posse.get() == NO_CIRCLES_CHECK; + } catch (RuntimeException | LinkageError e) { + return false; + } + } + + private void warnLacking() { + if (saidItLacksTheCheck) return; + saidItLacksTheCheck = true; + warn.accept(LACKS_WARNING); + } + + private List off() { + warnNow(); + return List.of(); + } + + private void warnNow() { + long now = clock.getAsLong(); + if (warned && now - warnedAt < WARN_EVERY_MILLIS) return; + warned = true; + warnedAt = now; + warn.accept(OFF_WARNING); + } +} diff --git a/src/main/java/com/extantape/bluemapmini/hud/PosseLink.java b/src/main/java/com/extantape/bluemapmini/hud/PosseLink.java new file mode 100644 index 0000000..be113d8 --- /dev/null +++ b/src/main/java/com/extantape/bluemapmini/hud/PosseLink.java @@ -0,0 +1,64 @@ +package com.extantape.bluemapmini.hud; + +import com.extantape.bluemapmini.config.HudConfig; +import com.extantape.bluemapmini.share.ShareService; +import org.bukkit.entity.Player; +import org.bukkit.plugin.Plugin; +import org.bukkit.plugin.PluginManager; +import org.bukkit.plugin.RegisteredServiceProvider; +import org.bukkit.plugin.ServicesManager; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.function.BiPredicate; + +/** + * Posse's ReachService, reached by reflection through the services manager. BlueMapMini has no compile or load-order + * dependency on Posse: a load-order entry once made a loop between the two (see LoadOrderTest). + */ +final class PosseLink { + private static final String SERVICE = "com.extantape.posse.api.ReachService"; + + private PosseLink() {} + + /** + * Posse's circles-only check as it is right now ({@code inSharedCircle}, added in Posse 0.11.3). Chat's reach check + * isn't used for dots, because it also lets in anyone in the same world. + *

+ * Null if Posse is missing, disabled or not offering the service itself. {@link PlayerDots#NO_CIRCLES_CHECK} if + * the installed Posse is too old to have the check. The check returned throws if a call fails, and never turns a + * failure into a yes. + */ + static BiPredicate find(PluginManager plugins, ServicesManager services) { + return find(plugins, services, SERVICE); + } + + /** The same under another interface name, so a test can stand in for a Posse without the check. */ + static BiPredicate find(PluginManager plugins, ServicesManager services, String serviceName) { + Plugin posse = plugins.getPlugin("Posse"); + if (posse == null || !posse.isEnabled()) return null; + if (ShareService.posseGuard(HudConfig.ShareAudience.POSSE, posse.getPluginMeta().getVersion()) != null) { + return PlayerDots.NO_CIRCLES_CHECK; + } + try { + // The interface as Posse's own class loader knows it, which is the key Posse registered it under. + Class type = Class.forName(serviceName, false, posse.getClass().getClassLoader()); + Method inSharedCircle = type.getMethod("inSharedCircle", Player.class, Player.class); + RegisteredServiceProvider registration = services.getRegistration(type); + if (registration == null || registration.getPlugin() != posse) return null; + return check(registration.getProvider(), inSharedCircle); + } catch (ClassNotFoundException | NoSuchMethodException e) { + return PlayerDots.NO_CIRCLES_CHECK; + } + } + + private static BiPredicate check(Object service, Method inSharedCircle) { + return (viewer, other) -> { + try { + return Boolean.TRUE.equals(inSharedCircle.invoke(service, viewer, other)); + } catch (IllegalAccessException | InvocationTargetException e) { + throw new IllegalStateException("Posse's circles check failed", e); + } + }; + } +} diff --git a/src/main/java/com/extantape/bluemapmini/share/ShareService.java b/src/main/java/com/extantape/bluemapmini/share/ShareService.java index 4fd4da0..6c2c610 100644 --- a/src/main/java/com/extantape/bluemapmini/share/ShareService.java +++ b/src/main/java/com/extantape/bluemapmini/share/ShareService.java @@ -193,7 +193,7 @@ private static String place(World world) { * BlueMapMini doesn't send and would let shares skip its groups. The version is null when Posse isn't running. * Returns why sharing is off, or null. */ - static String posseGuard(HudConfig.ShareAudience audience, String version) { + public static String posseGuard(HudConfig.ShareAudience audience, String version) { boolean needsPosse = audience == HudConfig.ShareAudience.POSSE || audience == HudConfig.ShareAudience.POSSE_WORLD_GROUP; if (version == null && !needsPosse) return null; if (version == null) return "Coordinate sharing is off: share.audience follows Posse's player groups, and Posse isn't running. Install Posse 0.11.0 or newer, or pick another share.audience."; diff --git a/src/main/resources/config.yml b/src/main/resources/config.yml index 908b166..e43bea2 100644 --- a/src/main/resources/config.yml +++ b/src/main/resources/config.yml @@ -76,6 +76,15 @@ fullscreen: brightness: 0.75 players: + # Who can be a dot on the map: world or posse. + # world anyone nearby in your world, subject to the settings below + # posse only players who share a Posse circle with you, or when either of you has posse.bypass. Being in the + # same world doesn't count, so this is stricter than chat. With no circles set up in Posse, everyone + # nearby is shown. Needs Posse 0.11.3 or newer. Nobody is shown while Posse is missing, older, disabled, + # paused or failing. + # Any other value counts as posse, and so does a config.yml that can't be read. So does a key that looks like + # audience but is misspelled or in the wrong section, or a setting written twice. The console says which. + audience: world # Blocks. Players farther away are not shown. radius: 512 hide-vanished: true diff --git a/src/test/java/com/extantape/bluemapmini/config/DotRuleTest.java b/src/test/java/com/extantape/bluemapmini/config/DotRuleTest.java new file mode 100644 index 0000000..40993ee --- /dev/null +++ b/src/test/java/com/extantape/bluemapmini/config/DotRuleTest.java @@ -0,0 +1,171 @@ +package com.extantape.bluemapmini.config; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; + +import static com.extantape.bluemapmini.config.DotRule.Audience.POSSE; +import static com.extantape.bluemapmini.config.DotRule.Audience.WORLD; +import static org.junit.jupiter.api.Assertions.*; + +/** players.audience. Only a plain world, or no setting in a readable file, leaves dots unfiltered. */ +class DotRuleTest { + private static DotRule of(String value) { + return DotRule.parse("players:\n radius: 512\n audience: " + value + "\n"); + } + + @Test + void worldAndPosseMeanWhatTheySay() { + for (String value : new String[] {"world", "World", "\" WORLD \""}) { + assertEquals(new DotRule(WORLD, null), of(value), value); + } + for (String value : new String[] {"posse", "POSSE", "\" posse \""}) { + assertEquals(new DotRule(POSSE, null), of(value), value); + } + } + + @Test + void anyOtherValueIsPosseAndSaysSo() { + for (String value : new String[] {"posses", "off", "false", "true", "server", "world-group", "posse-world-group", + "everyone", "\"\"", "7", "[world]", "[]", "{}"}) { + DotRule rule = of(value); + assertEquals(POSSE, rule.audience(), value); + assertNotNull(rule.problem(), value); + } + } + + @Test + void aKeyWithNoValueIsPosse() { + for (String value : new String[] {"", "~", "null"}) { + assertEquals(POSSE, of(value).audience(), "audience: " + value); + } + assertEquals(POSSE, DotRule.parse("players.audience:\n").audience()); + } + + @Test + void aPlayersSectionThatIsNotASectionIsPosse() { + assertEquals(POSSE, DotRule.parse("players: posse\n").audience()); + assertEquals(POSSE, DotRule.parse("players:\nmarkers:\n enabled: true\n").audience()); + } + + @Test + void aBrokenOrEmptyFileIsPosse() { + for (String text : new String[] {"players:\n audience: posse\n radius: [\n", "players:\n\taudience: posse\n", + "", " \n", "# nothing but a comment\n", "just some words\n", "- a\n- list\n"}) { + DotRule rule = DotRule.parse(text); + assertEquals(POSSE, rule.audience(), text); + assertNotNull(rule.problem(), text); + } + } + + @Test + void aReadableFileWithoutTheSettingKeepsTheOldBehavior() { + assertEquals(new DotRule(WORLD, null), DotRule.parse("players:\n radius: 200\n")); + assertEquals(new DotRule(WORLD, null), DotRule.parse("share:\n audience: posse\n")); + } + + /** The rule must be posse, with a warning that names the line to fix. */ + private static void assertStrays(String text, String named) { + DotRule rule = DotRule.parse(text); + assertEquals(POSSE, rule.audience(), text); + assertNotNull(rule.problem(), text); + assertTrue(rule.problem().contains(named), rule.problem()); + } + + @Test + void aTopLevelAudienceIsPosse() { + assertStrays("audience: posse\nplayers:\n radius: 200\n", "audience"); + assertStrays("audience: world\n", "audience"); + assertStrays("audience:\n", "audience"); + } + + @Test + void aTopLevelAudienceIsPosseEvenBesideAGoodSetting() { + assertStrays("players:\n audience: world\naudience: posse\n", "audience"); + } + + @Test + void aMisspelledKeyThatLooksLikeAudienceIsPosse() { + for (String key : new String[] {"audiance", "Audience", "AUDIENCE", "audence", "aduience", "audeince", "audienc", + "audiences", "audi-ence", "audie_nce", "\"audience \"", "dot-audience", "audiance-mode"}) { + assertStrays("players:\n radius: 200\n " + key + ": posse\n", "players." + key.replace("\"", "").trim()); + } + } + + @Test + void aLookalikeIsPosseWhateverItSaysAndBesideAGoodSetting() { + assertStrays("players:\n audiance: world\n", "players.audiance"); + assertStrays("players:\n audience: world\n Audience: posse\n", "players.Audience"); + assertStrays("players.audiance: posse\n", "players.audiance"); + } + + @Test + void anAudienceInTheWrongSectionIsPosse() { + assertStrays("player:\n audience: posse\n", "player.audience"); + assertStrays("Players:\n audience: posse\n", "Players.audience"); + assertStrays("markers:\n enabled: true\n audience: posse\n", "markers.audience"); + assertStrays("players:\n radius: 200\nmap:\n players:\n audience: posse\n", "map.players.audience"); + assertStrays("players:\n extra:\n audience: posse\n", "players.extra.audience"); + assertStrays("player:\n - audience: posse\n", "audience"); + } + + @Test + void aRepeatedKeyIsPosse() { + assertStrays("players:\n audience: posse\n radius: 200\n audience: world\n", "twice"); + assertStrays("players:\n audience: posse\nmarkers:\n enabled: true\nplayers:\n radius: 200\n", "twice"); + } + + @Test + void ordinaryWordsElsewhereAreNotTakenForAudience() { + assertEquals(new DotRule(WORLD, null), DotRule.parse("players:\n radius: 200\n" + + "worlds:\n claude: Home\n auden_isle: Isle\nsounds:\n audio: true\n")); + } + + @Test + void anUnknownKeyUnderPlayersWarnsAndKeepsTheSetting() { + DotRule world = DotRule.parse("players:\n hide-vanised: false\n visibility: posse\n"); + assertEquals(WORLD, world.audience()); + assertNotNull(world.problem()); + assertTrue(world.problem().contains("players.hide-vanised"), world.problem()); + assertTrue(world.problem().contains("players.visibility"), world.problem()); + + DotRule posse = DotRule.parse("players:\n audience: posse\n radios: 5\n"); + assertEquals(POSSE, posse.audience()); + assertTrue(posse.problem().contains("players.radios"), posse.problem()); + + DotRule bad = DotRule.parse("players:\n audience: nobody\n radios: 5\n"); + assertEquals(POSSE, bad.audience()); + assertTrue(bad.problem().contains("players.audience isn't world or posse"), bad.problem()); + assertTrue(bad.problem().contains("players.radios"), bad.problem()); + } + + @Test + void everyRealPlayersSettingIsKnown() { + assertEquals(new DotRule(WORLD, null), DotRule.parse("players:\n audience: world\n radius: 200\n" + + " hide-vanished: true\n hide-spectators: true\n hide-invisible: true\n hide-bluemap-hidden: true\n" + + " edge-arrows: false\n")); + } + + @Test + void aMissingOrUnreadableFileIsPosse(@TempDir Path dir) throws IOException { + assertEquals(POSSE, DotRule.read(dir.resolve("config.yml")).audience()); + assertEquals(POSSE, DotRule.read(dir).audience(), "a folder where the file should be"); + Path notText = Files.write(dir.resolve("bytes.yml"), new byte[] {(byte) 0xC3, (byte) 0x28}); + assertEquals(POSSE, DotRule.read(notText).audience(), "bytes that aren't UTF-8"); + } + + @Test + void theShippedConfigSaysWorld() throws IOException { + try (InputStream in = getClass().getResourceAsStream("/config.yml")) { + String text = new String(in.readAllBytes(), StandardCharsets.UTF_8); + assertTrue(text.contains("\n audience: world\n"), "the key is in the file, so an owner can find it"); + assertEquals(new DotRule(WORLD, null), DotRule.parse(text)); + assertEquals(POSSE, DotRule.parse(text.replace("\n audience: world\n", "\n audience: posse\n")).audience()); + } + } +} diff --git a/src/test/java/com/extantape/bluemapmini/hud/Fakes.java b/src/test/java/com/extantape/bluemapmini/hud/Fakes.java new file mode 100644 index 0000000..8b74ea7 --- /dev/null +++ b/src/test/java/com/extantape/bluemapmini/hud/Fakes.java @@ -0,0 +1,24 @@ +package com.extantape.bluemapmini.hud; + +import java.lang.reflect.Proxy; +import java.util.Map; +import java.util.function.Function; + +/** Stand-ins for Bukkit interfaces. A call that wasn't given an answer fails the test. */ +final class Fakes { + private Fakes() {} + + static T fake(Class type, String name, Map> answers) { + return type.cast(Proxy.newProxyInstance(type.getClassLoader(), new Class[] {type}, (self, method, args) -> { + switch (method.getName()) { + case "equals": return self == args[0]; + case "hashCode": return System.identityHashCode(self); + case "toString": return name; + default: + Function answer = answers.get(method.getName()); + if (answer == null) throw new AssertionError("Unexpected call: " + name + "." + method.getName()); + return answer.apply(args); + } + })); + } +} diff --git a/src/test/java/com/extantape/bluemapmini/hud/HudDotsTest.java b/src/test/java/com/extantape/bluemapmini/hud/HudDotsTest.java new file mode 100644 index 0000000..a1d4927 --- /dev/null +++ b/src/test/java/com/extantape/bluemapmini/hud/HudDotsTest.java @@ -0,0 +1,72 @@ +package com.extantape.bluemapmini.hud; + +import com.extantape.bluemapmini.config.DotRule; +import com.extantape.bluemapmini.config.HudConfig; +import org.bukkit.GameMode; +import org.bukkit.Location; +import org.bukkit.World; +import org.bukkit.entity.Player; +import org.bukkit.metadata.FixedMetadataValue; +import org.bukkit.plugin.Plugin; +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.function.BiPredicate; +import java.util.function.Predicate; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; + +/** The positions the HUD's player list sends as dots: the other filters first, then players.audience. */ +class HudDotsTest { + private final World world = Fakes.fake(World.class, "world", Map.of()); + private final Player viewer = at("viewer", 0, 0, GameMode.SURVIVAL, false); + private final Player friend = at("friend", 10, 20, GameMode.SURVIVAL, false); + private final Player stranger = at("stranger", -30, 40, GameMode.SURVIVAL, false); + /** Hide the vanished and spectators. Invisibility stays off, because its effect type needs a running server. */ + private final HudConfig.Players rules = new HudConfig.Players(100, true, true, false, true, false); + + /** The metadata flag vanish plugins set is deprecated in Paper, and the HUD still reads it. */ + @SuppressWarnings("deprecation") + private Player at(String name, int x, int z, GameMode mode, boolean vanished) { + return Fakes.fake(Player.class, name, Map.of( + "getLocation", a -> new Location(world, x, 64, z), + "getGameMode", a -> mode, + "getMetadata", a -> vanished + ? List.of(new FixedMetadataValue(Fakes.fake(Plugin.class, "vanisher", Map.of()), true)) + : List.of(), + "canSee", a -> true)); + } + + private int[] sent(BiPredicate posse, Predicate hiddenOnWebMap, Player... others) { + PlayerDots dots = new PlayerDots(() -> posse, line -> {}, () -> 0); + dots.audience(DotRule.Audience.POSSE); + List nearby = new ArrayList<>(List.of(others)); + nearby.add(viewer); + return HudManager.dotPositions(dots, viewer, new Location(world, 0, 64, 0), nearby, rules, hiddenOnWebMap); + } + + @Test + void onlyAPlayerTheCirclesCheckAllowsHasAPositionSent() { + assertArrayEquals(new int[] {10, 20}, sent((a, b) -> b == friend, p -> false, friend, stranger)); + } + + @Test + void noPosseAnOldPosseOrAFailingCheckSendsNoPositions() { + assertArrayEquals(new int[0], sent(null, p -> false, friend, stranger)); + assertArrayEquals(new int[0], sent(PlayerDots.NO_CIRCLES_CHECK, p -> false, friend, stranger)); + assertArrayEquals(new int[0], sent((a, b) -> { + throw new IllegalStateException("broken"); + }, p -> false, friend, stranger)); + } + + @Test + void sharingACircleDoesNotBringBackAPlayerAnotherFilterHides() { + Player vanished = at("vanished", 1, 1, GameMode.SURVIVAL, true); + Player spectator = at("spectator", 2, 2, GameMode.SPECTATOR, false); + Player farAway = at("far", 500, 0, GameMode.SURVIVAL, false); + assertArrayEquals(new int[] {10, 20}, + sent((a, b) -> true, p -> p == stranger, friend, stranger, vanished, spectator, farAway)); + } +} diff --git a/src/test/java/com/extantape/bluemapmini/hud/PlayerDotsTest.java b/src/test/java/com/extantape/bluemapmini/hud/PlayerDotsTest.java new file mode 100644 index 0000000..7afa765 --- /dev/null +++ b/src/test/java/com/extantape/bluemapmini/hud/PlayerDotsTest.java @@ -0,0 +1,155 @@ +package com.extantape.bluemapmini.hud; + +import com.extantape.bluemapmini.config.DotRule; +import org.bukkit.entity.Player; +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.concurrent.atomic.AtomicLong; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.BiPredicate; + +import static org.junit.jupiter.api.Assertions.*; + +/** players.audience: posse. A dot only when Posse allows it, and no dots at all on any doubt. */ +class PlayerDotsTest { + private final Player viewer = player("viewer"); + private final Player friend = player("friend"); + private final Player stranger = player("stranger"); + private final List nearby = List.of(friend, stranger); + + private final AtomicReference> posse = new AtomicReference<>(); + private final AtomicLong clock = new AtomicLong(); + private final List log = new ArrayList<>(); + + private static Player player(String name) { + return Fakes.fake(Player.class, name, Map.of()); + } + + private PlayerDots dots(DotRule.Audience audience) { + PlayerDots dots = new PlayerDots(posse::get, log::add, clock::get); + dots.audience(audience); + return dots; + } + + @Test + void aRefusedPlayerGetsNoDotAndAnAllowedOneDoes() { + posse.set((from, to) -> from == viewer && to == friend); + assertEquals(List.of(friend), dots(DotRule.Audience.POSSE).keep(viewer, nearby)); + assertTrue(log.isEmpty()); + } + + @Test + void aPosseThatSaysNoToEveryoneAsItDoesWhilePausedLeavesNoDots() { + posse.set((from, to) -> false); + PlayerDots dots = dots(DotRule.Audience.POSSE); + assertEquals(List.of(), dots.keep(viewer, nearby)); + assertFalse(dots.offForWantOfPosse(), "it answered, with a no"); + } + + @Test + void aMissingPosseMeansNoDots() { + PlayerDots dots = dots(DotRule.Audience.POSSE); + assertEquals(List.of(), dots.keep(viewer, nearby)); + assertTrue(dots.offForWantOfPosse()); + assertEquals(List.of(PlayerDots.OFF_WARNING), log); + } + + @Test + void oneFailingCallDropsEveryDotIncludingOnesAlreadyAllowed() { + List failures = List.of( + () -> { throw new IllegalStateException("broken"); }, + () -> { throw new NoSuchMethodError("old jar"); }); + for (Runnable failure : failures) { + posse.set((from, to) -> { + if (to == stranger) failure.run(); + return true; + }); + PlayerDots dots = dots(DotRule.Audience.POSSE); + assertEquals(List.of(), dots.keep(viewer, nearby)); + assertTrue(dots.offForWantOfPosse()); + } + } + + @Test + void aFailingLookupMeansNoDots() { + PlayerDots dots = new PlayerDots(() -> { + throw new IllegalStateException("services manager"); + }, log::add, clock::get); + dots.audience(DotRule.Audience.POSSE); + assertEquals(List.of(), dots.keep(viewer, nearby)); + assertTrue(dots.offForWantOfPosse()); + } + + @Test + void posseIsAskedAfreshEveryTimeSoDisablingItDropsTheDots() { + PlayerDots dots = dots(DotRule.Audience.POSSE); + posse.set((from, to) -> true); + assertEquals(nearby, dots.keep(viewer, nearby)); + posse.set(null); + assertEquals(List.of(), dots.keep(viewer, nearby)); + posse.set((from, to) -> true); + assertEquals(nearby, dots.keep(viewer, nearby)); + assertFalse(dots.offForWantOfPosse()); + } + + @Test + void aFailureIsRememberedUntilACallWorks() { + PlayerDots dots = dots(DotRule.Audience.POSSE); + posse.set((from, to) -> { + throw new IllegalStateException("broken"); + }); + dots.keep(viewer, nearby); + posse.set((from, to) -> true); + dots.keep(viewer, List.of()); + assertTrue(dots.offForWantOfPosse(), "nobody was nearby, so nothing was asked"); + dots.keep(viewer, nearby); + assertFalse(dots.offForWantOfPosse()); + } + + @Test + void theWarningIsLoggedOnceAMinute() { + PlayerDots dots = dots(DotRule.Audience.POSSE); + for (long at : new long[] {0, 1_000, 59_999}) { + clock.set(at); + dots.keep(viewer, nearby); + dots.warnIfOff(); + } + assertEquals(1, log.size()); + clock.set(60_000); + dots.keep(viewer, nearby); + assertEquals(2, log.size()); + } + + @Test + void aPosseWithoutTheCirclesCheckMeansNoDotsAndIsSaidOnceWithNoNames() { + posse.set(PlayerDots.NO_CIRCLES_CHECK); + PlayerDots dots = dots(DotRule.Audience.POSSE); + for (long at : new long[] {0, 60_000, 600_000}) { + clock.set(at); + assertEquals(List.of(), dots.keep(viewer, nearby)); + dots.warnIfOff(); + } + assertTrue(dots.offForWantOfPosse(), "so the player is told why"); + assertEquals(List.of(PlayerDots.LACKS_WARNING), log); + for (String name : new String[] {"viewer", "friend", "stranger"}) assertFalse(log.getFirst().contains(name)); + } + + @Test + void worldLeavesTheListAloneAndNeverAsksPosse() { + PlayerDots dots = new PlayerDots(() -> fail("Posse was asked"), log::add, clock::get); + dots.audience(DotRule.Audience.WORLD); + assertEquals(nearby, dots.keep(viewer, nearby)); + assertFalse(dots.offForWantOfPosse()); + assertTrue(log.isEmpty()); + } + + @Test + void beforeTheConfigIsReadTheRuleIsPosse() { + PlayerDots dots = new PlayerDots(posse::get, log::add, clock::get); + assertEquals(DotRule.Audience.POSSE, dots.audience()); + assertEquals(List.of(), dots.keep(viewer, nearby)); + } +} diff --git a/src/test/java/com/extantape/bluemapmini/hud/PosseLinkTest.java b/src/test/java/com/extantape/bluemapmini/hud/PosseLinkTest.java new file mode 100644 index 0000000..0026350 --- /dev/null +++ b/src/test/java/com/extantape/bluemapmini/hud/PosseLinkTest.java @@ -0,0 +1,111 @@ +package com.extantape.bluemapmini.hud; + +import com.extantape.posse.api.ReachService; +import io.papermc.paper.plugin.configuration.PluginMeta; +import org.bukkit.entity.Player; +import org.bukkit.plugin.Plugin; +import org.bukkit.plugin.PluginManager; +import org.bukkit.plugin.RegisteredServiceProvider; +import org.bukkit.plugin.ServicePriority; +import org.bukkit.plugin.ServicesManager; +import org.junit.jupiter.api.Test; + +import java.util.Map; +import java.util.function.BiPredicate; + +import static org.junit.jupiter.api.Assertions.*; + +/** Finding Posse's circles-only check by reflection. Anything short of Posse's own service shows nobody. */ +class PosseLinkTest { + private final Player viewer = Fakes.fake(Player.class, "viewer", Map.of()); + private final Player friend = Fakes.fake(Player.class, "friend", Map.of()); + private final Player stranger = Fakes.fake(Player.class, "stranger", Map.of()); + + /** The interface as Posse 0.11.0 to 0.11.2 had it. */ + public interface OlderReachService { + boolean mayReach(Player from, Player to); + } + + /** A service whose chat check always says yes, so only the circles check can refuse. */ + private static ReachService circles(BiPredicate answer) { + return new ReachService() { + @Override + public boolean mayReach(Player from, Player to) { + return true; + } + + @Override + public boolean inSharedCircle(Player viewer, Player to) { + return answer.test(viewer, to); + } + }; + } + + private static Plugin plugin(String version, boolean enabled) { + PluginMeta meta = Fakes.fake(PluginMeta.class, "meta", Map.of("getVersion", a -> version)); + return Fakes.fake(Plugin.class, "Posse", Map.of("isEnabled", a -> enabled, "getPluginMeta", a -> meta)); + } + + private static PluginManager plugins(Plugin posse) { + return Fakes.fake(PluginManager.class, "plugins", Map.of("getPlugin", a -> "Posse".equals(a[0]) ? posse : null)); + } + + private static ServicesManager services(Plugin owner, ReachService service) { + return Fakes.fake(ServicesManager.class, "services", Map.of("getRegistration", a -> { + assertEquals(ReachService.class, a[0]); + return service == null ? null + : new RegisteredServiceProvider<>(ReachService.class, service, ServicePriority.Normal, owner); + })); + } + + @Test + void theCirclesCheckAnswersAndChatsCheckIsNeverUsed() { + Plugin posse = plugin("0.11.3", true); + BiPredicate reach = PosseLink.find(plugins(posse), + services(posse, circles((from, to) -> from == viewer && to == friend))); + assertNotNull(reach); + assertTrue(reach.test(viewer, friend)); + assertFalse(reach.test(viewer, stranger), "chat would allow this one, as in a shared world"); + } + + @Test + void aMissingOrDisabledPosseIsNoPosse() { + ReachService yes = circles((from, to) -> true); + assertNull(PosseLink.find(plugins(null), services(null, yes)), "missing"); + Plugin disabled = plugin("0.11.3", false); + assertNull(PosseLink.find(plugins(disabled), services(disabled, yes)), "disabled"); + } + + @Test + void aPosseWithoutTheCirclesCheckIsMarkedAsLackingIt() { + for (String version : new String[] {"0.10.0", "something odd"}) { + Plugin posse = plugin(version, true); + assertSame(PlayerDots.NO_CIRCLES_CHECK, + PosseLink.find(plugins(posse), services(posse, circles((from, to) -> true))), version); + } + Plugin older = plugin("0.11.2", true); + for (String name : new String[] {OlderReachService.class.getName(), "com.extantape.posse.api.NoSuchService"}) { + assertSame(PlayerDots.NO_CIRCLES_CHECK, PosseLink.find(plugins(older), + Fakes.fake(ServicesManager.class, "services", Map.of()), name), name); + } + assertFalse(PlayerDots.NO_CIRCLES_CHECK.test(viewer, friend)); + } + + @Test + void noServiceOrSomeoneElsesServiceIsNoPosse() { + Plugin posse = plugin("0.11.3", true); + assertNull(PosseLink.find(plugins(posse), services(posse, null)), "nothing registered"); + Plugin other = Fakes.fake(Plugin.class, "Other", Map.of()); + assertNull(PosseLink.find(plugins(posse), services(other, circles((from, to) -> true))), + "another plugin's answer"); + } + + @Test + void aCheckThatThrowsInsidePosseThrowsHereAndIsNeverAYes() { + Plugin posse = plugin("0.11.3", true); + BiPredicate reach = PosseLink.find(plugins(posse), services(posse, circles((from, to) -> { + throw new UnsupportedOperationException("broken"); + }))); + assertThrows(IllegalStateException.class, () -> reach.test(viewer, friend)); + } +} diff --git a/src/test/java/com/extantape/posse/api/ReachService.java b/src/test/java/com/extantape/posse/api/ReachService.java new file mode 100644 index 0000000..f0fed59 --- /dev/null +++ b/src/test/java/com/extantape/posse/api/ReachService.java @@ -0,0 +1,13 @@ +package com.extantape.posse.api; + +import org.bukkit.entity.Player; + +/** + * A test stand-in with the real interface's name, the circles-only check BlueMapMini looks for, and chat's check, + * which BlueMapMini must not use for dots. BlueMapMini reaches the real interface by reflection. + */ +public interface ReachService { + boolean mayReach(Player from, Player to); + + boolean inSharedCircle(Player viewer, Player to); +} diff --git a/test/live/README.md b/test/live/README.md index 4f2ab69..b2c2d14 100644 --- a/test/live/README.md +++ b/test/live/README.md @@ -51,7 +51,7 @@ BMM_ACCEPT_EULA=1 test/live/run.sh 26.1.2 suite:coordsonly,onebar | `packurl` | `public-url` with `{sha1}`, the hosted-pack check, and `/bluemapmini pack export`. | 3 min | | `storage` | BlueMap starting 8 times next to the plugin, and BlueMap on SQLite read through the HTTP source. | 6 min | | `backoff` | Another plugin owning `/map` and `/hud`, and getting them back once it's removed. | 2 min | -| `posse` | The real Posse with BlueMapMini: shares stay inside chat circles with Posse 0.11.0; without Posse, sharing stays off with `share.audience: posse`, and works with `share.audience: server`. Needs `BMM_POSSE_JAR`. | +| `posse` | The real Posse with BlueMapMini: shares stay inside chat circles; without Posse, sharing stays off with `share.audience: posse`, and works with `share.audience: server`. With `players.audience: posse` it decodes each viewer's minimap and fullscreen map and counts the player dots: only players in the viewer's circle, in a world that isn't circle-only (chat reaches another circle there, dots don't), none after Posse is disabled, none without Posse, none after Posse starts paused, and everyone again with `world`. It also checks `posse.bypass` seen and seeing, everyone shown when Posse has no circles, and that a misspelled `players.audience` key counts as `posse` and is reported. Needs `BMM_POSSE_JAR`, Posse 0.11.3 or newer. | not timed | Logs go to `test/live/work/server--.log`. Each test prints a summary, with any failures and skipped checks. @@ -67,4 +67,4 @@ export BMM_CLIENT_CP="/path/to/client.jar:/path/to/libraries/*" ## The test-only plugins -`helper/` and `conflict/` are built by `./gradlew build` and are never shipped. The helper is a Paper plugin with one console command, `/bmt`. The conflict plugin is deliberately an old-style Bukkit plugin with `/map` and `/hud` in its `plugin.yml`, to test the back-off. Never install either on a real server. +`helper/` and `conflict/` are built by `./gradlew build` and are never shipped. The helper is a Paper plugin with one console command, `/bmt`, which can also disable a plugin while the server runs. The conflict plugin is deliberately an old-style Bukkit plugin with `/map` and `/hud` in its `plugin.yml`, to test the back-off. Never install either on a real server. diff --git a/test/live/helper/src/main/java/com/extantape/bluemapmini/livetest/Helper.java b/test/live/helper/src/main/java/com/extantape/bluemapmini/livetest/Helper.java index c13eeb7..3f8bcf1 100644 --- a/test/live/helper/src/main/java/com/extantape/bluemapmini/livetest/Helper.java +++ b/test/live/helper/src/main/java/com/extantape/bluemapmini/livetest/Helper.java @@ -39,9 +39,18 @@ public final class Helper extends JavaPlugin { private final Map permissions = new HashMap<>(); private final Map adventureBars = new HashMap<>(); private org.bukkit.boss.BossBar plainBar; + /** Permissions to give a player as they log in, by name, for checks made before they can be online. */ + private final Map joinPermissions = new HashMap<>(); @Override + @SuppressWarnings("deprecation") // The login event is where Posse's paused join check reads permissions. public void onEnable() { + getServer().getPluginManager().registerEvent(org.bukkit.event.player.PlayerLoginEvent.class, + new org.bukkit.event.Listener() {}, org.bukkit.event.EventPriority.LOWEST, (listener, event) -> { + Player p = ((org.bukkit.event.player.PlayerLoginEvent) event).getPlayer(); + String node = joinPermissions.get(p.getName()); + if (node != null) p.addAttachment(this, node, true); + }, this); getLifecycleManager().registerEventHandler(LifecycleEvents.COMMANDS, event -> event.registrar().register("bmt", "Live test helper", new BasicCommand() { @Override @@ -86,6 +95,10 @@ private void run(String[] a) { p.updateCommands(); say("perm " + a[2] + " " + a[3]); } + case "joinperm" -> { // joinperm + joinPermissions.put(a[1], a[2]); + say("joinperm " + a[2]); + } case "magicpack" -> { // The old one-pack method, as Magic uses, which clears every other pack. sendSinglePack(player(a[1]), a[2]); say("magicpack sent"); @@ -159,6 +172,11 @@ private void run(String[] a) { org.bukkit.World world = Bukkit.createWorld(new org.bukkit.WorldCreator(a[1]).type(org.bukkit.WorldType.FLAT)); say("mkworld " + (world != null ? world.getName() : "failed")); } + case "disableplugin" -> { // As a plugin manager would, while players are on. + org.bukkit.plugin.Plugin target = Bukkit.getPluginManager().getPlugin(a[1]); + Bukkit.getPluginManager().disablePlugin(target); + say("disableplugin " + a[1] + " enabled=" + target.isEnabled()); + } case "execute" -> say("perform " + player(a[1]).performCommand(String.join(" ", Arrays.copyOfRange(a, 2, a.length)))); default -> say("unknown " + a[0]); } diff --git a/test/live/posse.js b/test/live/posse.js index f3ac028..0202507 100644 --- a/test/live/posse.js +++ b/test/live/posse.js @@ -1,15 +1,20 @@ -// BlueMapMini with the real Posse: shares follow chat circles. Without Posse, sharing is off by default rather than -// unfiltered, and a server without chat rules can choose another audience, such as server. +// BlueMapMini with the real Posse (0.11.3 or newer): shares follow chat, and with players.audience: posse, player +// dots follow circles only, so two players in different circles never see each other's dots, even in a shared world. +// Without Posse, sharing is off and there are no dots, never an unfiltered list, and a server without chat rules can +// choose another audience, such as server or world. Dots are read from the map each bot is actually sent. // Usage: node posse.js

, and relative to the work folder. -const { Server, Bot, check, section, summary, sleep, until } = require('./lib.js'); +const { Server, Bot, Pack, gridOf, iconCell, check, section, summary, sleep, until } = require('./lib.js'); const fs = require('fs'); const [dir, jar, portS, newJar] = process.argv.slice(2); const port = +portS; const s = new Server(dir, jar, port); const installed = s.path('plugins', 'Posse.jar'); -// Made-up circles. The overworld is circle-only, so only circles decide who hears whom there. -const CONFIG = 'circles: [red, blue]\ncircle-only-worlds: [world]\n'; +// Made-up circles. For shares the overworld is circle-only, so only circles decide who receives one. For dots it +// isn't: chat then reaches everyone in the world, and the dots must still follow the circles. +const SHARE_CONFIG = 'circles: [red, blue]\ncircle-only-worlds: [world]\n'; +const DOTS_CONFIG = 'circles: [red, blue]\n'; +const MEMBERS = [['Tester', 'red'], ['Alex', 'red'], ['Blair', 'blue']]; // Casey is in no circle. async function say(bot, command, pattern) { const from = bot.chat.length; @@ -18,6 +23,53 @@ async function say(bot, command, pattern) { } const heard = (bot, from) => bot.chat.slice(from).some((m) => /shared where they are/.test(m)); +// Who is where, so a dot can be told apart: east of Tester is red like Tester, west is blue, south has no circle. +const SPOTS = { Tester: [0, 0], Alex: [8, 0], Blair: [-8, 0], Casey: [0, 8] }; +const PLAYER_ICON = 16; +const OFF_WARNING = /Player dots are off: players\.audience follows Posse, and Posse isn't answering/; + +async function gather(bots) { + for (const n of Object.keys(bots)) { s.cmd(`tp ${n} ${SPOTS[n][0]} 120 ${SPOTS[n][1]} 180 0`); await sleep(100); } + await sleep(1200); +} + +/** The dots on this bot's map, as cells east and south of the middle, or null if it isn't being sent a map. */ +function dotsOf(bot, step = 2) { + if (!bot.packBytes) return null; + bot.pk = bot.pk || new Pack(bot.packBytes); + const frame = bot.hudFrame(bot.pk), grid = frame && gridOf(frame, step); + if (!grid) return null; + return frame.icons.filter((i) => i.icon === PLAYER_ICON).map((i) => { + const cell = iconCell(i, grid); + return { east: cell.x - grid.cols / 2, south: cell.z - grid.rows / 2 }; + }); +} + +/** Passes only if the bot is sent a map, its dots come to match, and they still match for 1.5 more seconds. */ +async function checkDots(name, bot, matches, step = 2) { + const ok = () => { const d = dotsOf(bot, step); return d !== null && matches(d); }; + let held = !!(await until(ok, 8000, 100)); + for (let i = 0; held && i < 15; i++) { await sleep(100); held = ok(); } + return check(name, held, JSON.stringify(dotsOf(bot, step))); +} +const none = (d) => d.length === 0; +const onlyTheEastOne = (d) => d.length === 1 && d[0].east > 1; +const count = (n) => (d) => d.length === n; + +async function reloadWith(edits) { + s.setConfig(edits); + const mark = s.mark(); + s.cmd('bluemapmini reload'); + await s.waitLog(/Player dots: /, 20000, mark); + await sleep(1500); + return mark; +} + +async function giveCircles() { + for (const [who, circle] of MEMBERS) s.cmd(`bmt perm ${who} posse.circle.${circle} true`); + await sleep(800); +} + async function joinAll(names) { const bots = {}; for (const n of names) { @@ -32,16 +84,18 @@ async function joinAll(names) { (async () => { let bots = {}; try { - section('BlueMapMini with Posse 0.11.0: shares follow the circles'); + section('BlueMapMini with Posse: shares follow chat'); fs.copyFileSync(newJar, installed); fs.mkdirSync(s.path('plugins', 'Posse'), { recursive: true }); - fs.writeFileSync(s.path('plugins', 'Posse', 'config.yml'), CONFIG); - s.setConfig({ 'share.audience': 'posse' }); + fs.writeFileSync(s.path('plugins', 'Posse', 'config.yml'), SHARE_CONFIG); + s.setConfig({ 'share.audience': 'posse', 'players.audience': 'posse' }); await s.start(); await sleep(4000); + check('The log says dots follow Posse, with no warning', /Player dots: only players Posse's circles allow\./.test(s.log) && !OFF_WARNING.test(s.log)); + const posseVersion = (s.log.match(/Enabling Posse v(\S+)/) || [])[1]; + check('The real Posse jar is running, with the circles-only check', !!posseVersion && !/has no circles-only check/.test(s.log), posseVersion); check('Posse found BlueMapMini\'s share event', /BlueMapMini found: coordinate shares follow the same rules as chat/.test(s.log)); bots = await joinAll(['Tester', 'Alex', 'Blair', 'Casey']); - for (const [who, circle] of [['Tester', 'red'], ['Alex', 'red'], ['Blair', 'blue']]) s.cmd(`bmt perm ${who} posse.circle.${circle} true`); - await sleep(800); + await giveCircles(); let marks = Object.fromEntries(Object.entries(bots).map(([n, b]) => [n, b.chat.length])); const sent = await say(bots.Tester, '/hud share everyone', /Sent your coordinates|weren't sent|can receive/); await sleep(600); @@ -51,6 +105,90 @@ async function joinAll(names) { const lonely = await say(bots.Casey, '/hud share everyone', /Sent your coordinates|weren't sent|can receive|can't/); await sleep(600); check('Someone with no circle in a circle-only world sends nothing', !Object.entries(bots).some(([n, b]) => n !== 'Casey' && heard(b, marks[n])), lonely); + + for (const b of Object.values(bots)) await b.cleanQuit(); + await s.stop(); + + section('players.audience: posse, in a world that is not circle-only: dots follow the circles'); + fs.writeFileSync(s.path('plugins', 'Posse', 'config.yml'), DOTS_CONFIG); + await s.start(); await sleep(4000); + bots = await joinAll(['Tester', 'Alex', 'Blair', 'Casey']); + await giveCircles(); + await gather(bots); + const heardAt = bots.Blair.chat.length; + bots.Tester.say('same world check'); + check('Control: chat from one circle reaches another circle in this world', + !!(await until(() => bots.Blair.chat.slice(heardAt).find((line) => /same world check/.test(line)), 5000))); + await checkDots('Tester is sent one dot, for the player in their circle', bots.Tester, onlyTheEastOne); + await checkDots('Alex is sent one dot back', bots.Alex, (d) => d.length === 1 && d[0].east < -1); + await checkDots('A player in another circle, in the same world, is sent no dots', bots.Blair, none); + await checkDots('A player with no circle is sent no dots', bots.Casey, none); + bots.Tester.say('/map'); await sleep(800); + await checkDots('The fullscreen map has the same one dot', bots.Tester, (d) => d.length === 1 && d[0].east > 0, 3); + bots.Tester.say('/map'); await sleep(800); + // The control: with world, the other filters hide nobody here, so it's the Posse rule that did. + await reloadWith({ 'players.audience': 'world' }); + await checkDots('Control: with world, Tester is sent all three dots', bots.Tester, count(3)); + let badMark = await reloadWith({ 'players.audience': 'everyone' }); + check('A bad value is reported', /players\.audience isn't world or posse, so player dots follow Posse/.test(s.since(badMark))); + await checkDots('and counts as posse', bots.Tester, onlyTheEastOne); + await reloadWith({ 'players.audience': 'posse' }); + await checkDots('Back on posse, one dot', bots.Tester, onlyTheEastOne); + + // A mistyped key, as an owner might leave it. Both forms must count as posse, even though they say world. + const configFile = s.path('plugins', 'BlueMapMini', 'config.yml'); + const goodConfig = fs.readFileSync(configFile, 'utf8'); + const audienceLine = /^( +)audience: "posse"$/m; + check('The config has the players.audience line the mistyped-key checks edit', audienceLine.test(goodConfig)); + for (const [what, replacement] of [ + ['A misspelled players.audience key', '$1audiance: "world"'], + ['A misspelled key beside audience: world', '$1audience: "world"\n$1audiance: "world"'], + ]) { + fs.writeFileSync(configFile, goodConfig.replace(audienceLine, replacement)); + // Show every dot first, so one dot afterwards is the reload's doing. + badMark = await reloadWith({}); + check(`${what} is reported`, /looks like players\.audience misspelled/.test(s.since(badMark))); + await checkDots(`${what} counts as posse: one dot`, bots.Tester, onlyTheEastOne); + await checkDots(`${what}: another circle still gets none`, bots.Blair, none); + } + fs.writeFileSync(configFile, goodConfig); + await reloadWith({}); + + // posse.bypass, both ways. Casey is in no circle and stands south of Tester. + s.cmd('bmt perm Casey posse.bypass true'); + await sleep(800); + await checkDots('With posse.bypass, a player with no circle sees all three dots', bots.Casey, count(3)); + await checkDots('and is seen by Tester, beside the circle-mate', bots.Tester, + (d) => d.length === 2 && d.some((x) => x.east > 1) && d.some((x) => x.south > 1 && Math.abs(x.east) <= 1)); + await checkDots('and by another circle, which sees nobody else', bots.Blair, + (d) => d.length === 1 && d[0].east > 1 && d[0].south > 1); + s.cmd('bmt perm Casey posse.bypass false'); + await sleep(800); + await checkDots('Without posse.bypass again, Casey is sent no dots', bots.Casey, none); + await checkDots('and Tester is back to one', bots.Tester, onlyTheEastOne); + + // No circles set up in Posse: its rules are off, so every dot shows. + const posseConfig = s.path('plugins', 'Posse', 'config.yml'); + const posseReload = async (text) => { + fs.writeFileSync(posseConfig, text); + const from = s.mark(); + await s.run('posse reload', /Chat rules are on|No circles are set up/, 20000); + await sleep(1500); + return s.since(from); + }; + check('Posse reloads with no circles', /No circles are set up/.test(await posseReload('circles: []\n'))); + await checkDots('With no circles, Tester is sent all three dots', bots.Tester, count(3)); + await checkDots('and so is another player', bots.Blair, count(3)); + check('Posse reloads with the circles back', /Chat rules are on/.test(await posseReload(DOTS_CONFIG))); + await checkDots('With circles back, one dot again', bots.Tester, onlyTheEastOne); + await checkDots('and none for the other circle', bots.Blair, none); + + badMark = s.mark(); + await s.run('bmt disableplugin Posse', /BMT disableplugin Posse enabled=false/, 20000); + await checkDots('Posse disabled mid-run: no dots', bots.Tester, none); + check('and the log warns', OFF_WARNING.test(s.since(badMark))); + const told = await say(bots.Tester, '/hud show players', /Other players aren't shown on the map right now/); + check('and /hud show players says why there are none', !!told); for (const b of Object.values(bots)) await b.cleanQuit(); await s.stop(); @@ -65,6 +203,13 @@ async function joinAll(names) { check('The sender is told sharing is off', /Sharing coordinates is off on this server for now/.test(off || ''), off); check('and nobody receives anything', !heard(bots.Alex, m)); check("The log says Posse isn't installed", /share\.audience follows Posse's player groups, and Posse isn't running/.test(s.since(mark))); + + section('BlueMapMini without Posse, players.audience: posse: no dots, not unfiltered'); + await gather(bots); + await checkDots('Tester is sent a map with no dots', bots.Tester, none); + check('The log warns that dots are off', OFF_WARNING.test(s.log)); + await reloadWith({ 'players.audience': 'world' }); + await checkDots('Control: with world, Tester is sent the dot', bots.Tester, count(1)); for (const b of Object.values(bots)) await b.cleanQuit(); await s.stop(); @@ -78,6 +223,22 @@ async function joinAll(names) { check('A server without chat rules can share', /Sent your coordinates/.test(plain || '') && heard(bots.Alex, m), plain); for (const b of Object.values(bots)) await b.cleanQuit(); await s.stop(); + + // A Posse that started paused refuses joins without posse.bypass, so both bots are given it as they log in, on + // this throwaway server. Its circles check still says no to everyone, bypass included. + section('Posse paused by a broken config.yml, players.audience: posse: no dots, even with posse.bypass'); + fs.copyFileSync(newJar, installed); + fs.writeFileSync(s.path('plugins', 'Posse', 'config.yml'), 'circles: [red, blue\n'); + s.setConfig({ 'players.audience': 'posse' }); + await s.start(); await sleep(4000); + for (const n of ['Tester', 'Alex']) await s.run(`bmt joinperm ${n} posse.bypass`, /BMT joinperm posse\.bypass/, 5000); + bots = await joinAll(['Tester', 'Alex']); + await gather(bots); + await checkDots('Tester is sent a map with no dots', bots.Tester, none); + await reloadWith({ 'players.audience': 'world' }); + await checkDots('Control: with world, Tester is sent the dot', bots.Tester, count(1)); + for (const b of Object.values(bots)) await b.cleanQuit(); + await s.stop(); } catch (e) { check('posse finished', false, e.stack?.slice(0, 400)); for (const b of Object.values(bots)) try { await b.cleanQuit(); } catch {} diff --git a/test/live/run.sh b/test/live/run.sh index 3cf66f7..f25998b 100755 --- a/test/live/run.sh +++ b/test/live/run.sh @@ -3,7 +3,7 @@ # test fails. See README.md in this folder. # # Usage: test/live/run.sh [test...] -# tests: suite (default), suite:, packurl, storage, load, backoff +# tests: suite (default), suite:, packurl, storage, load, backoff, posse (needs BMM_POSSE_JAR) # e.g. test/live/run.sh 26.3 suite packurl storage load backoff set -euo pipefail