diff --git a/gradle.properties b/gradle.properties index 66e04bc..b6e4c8a 100644 --- a/gradle.properties +++ b/gradle.properties @@ -8,7 +8,7 @@ loader_version=0.19.3 fabric_version=0.141.4+1.21.11 loom_version=1.17.8 -mod_version=1.6.5 +mod_version=1.6.6 maven_group=tel.eden archives_base_name=edenmod modmenu_version=17.0.0 diff --git a/src/tel/eden/mod/EdenModClient.java b/src/tel/eden/mod/EdenModClient.java index 43840d8..f986b70 100644 --- a/src/tel/eden/mod/EdenModClient.java +++ b/src/tel/eden/mod/EdenModClient.java @@ -220,7 +220,9 @@ public enum BridgeStatus { /** Verified but not linked — the player is prompted to link. */ NOT_LINKED, /** Linked but not a guild member — the bridge stays inactive. */ - NOT_MEMBER + NOT_MEMBER, + /** Linked, not in the guild, holds a traveler role — a restricted feature set. */ + TRAVELER } private volatile BridgeStatus bridgeStatus = BridgeStatus.UNKNOWN; @@ -234,6 +236,17 @@ public BridgeStatus bridgeStatus() { return bridgeStatus; } + public boolean isTraveler() { + return bridgeStatus == BridgeStatus.TRAVELER; + } + + public boolean isFullMember() { + return bridgeStatus == BridgeStatus.FULL; + } + + /** Guild-only commands are hidden from travelers; an unverified player keeps them, as before. */ + private final java.util.function.Predicate guildOnly = source -> !isTraveler(); + /** In-game guild rank last reported by the backend, or empty if unknown. */ public String liveGuildRank() { return liveGuildRank; @@ -813,28 +826,28 @@ public void release() { Minecraft mc = Minecraft.getInstance(); mc.execute(() -> mc.setScreen(BridgeConfigScreen.create(mc.screen, EdenModClient.instance()))); return 1; - })).then(ClientCommandManager.literal("online").executes(ctx -> { + })).then(ClientCommandManager.literal("online").requires(guildOnly).executes(ctx -> { requestOnline(ctx.getSource()); return 1; - })).then(ClientCommandManager.literal("mail").then(ClientCommandManager.argument("player", StringArgumentType.word()).suggests(this::suggestMembers).then(ClientCommandManager.argument("message", StringArgumentType.greedyString()).executes(ctx -> sendMail(ctx.getSource(), StringArgumentType.getString(ctx, "player"), StringArgumentType.getString(ctx, "message")))))).then(ClientCommandManager.literal("aspects").then(ClientCommandManager.literal("pending").executes(ctx -> { + })).then(ClientCommandManager.literal("mail").then(ClientCommandManager.argument("player", StringArgumentType.word()).suggests(this::suggestMembers).then(ClientCommandManager.argument("message", StringArgumentType.greedyString()).executes(ctx -> sendMail(ctx.getSource(), StringArgumentType.getString(ctx, "player"), StringArgumentType.getString(ctx, "message")))))).then(ClientCommandManager.literal("aspects").requires(guildOnly).then(ClientCommandManager.literal("pending").executes(ctx -> { requestAspectsPending(ctx.getSource()); return 1; - })).then(ClientCommandManager.literal("optout").executes(ctx -> toggleRewardOptOut("aspects", true)).then(ClientCommandManager.argument("enabled", com.mojang.brigadier.arguments.BoolArgumentType.bool()).executes(ctx -> toggleRewardOptOut("aspects", com.mojang.brigadier.arguments.BoolArgumentType.getBool(ctx, "enabled"))))).then(ClientCommandManager.literal("optin").executes(ctx -> toggleRewardOptOut("aspects", false))).then(ClientCommandManager.literal("status").executes(ctx -> queryRewardStatus()))).then(ClientCommandManager.literal("emeralds").then(ClientCommandManager.literal("optout").executes(ctx -> toggleRewardOptOut("emeralds", true)).then(ClientCommandManager.argument("enabled", com.mojang.brigadier.arguments.BoolArgumentType.bool()).executes(ctx -> toggleRewardOptOut("emeralds", com.mojang.brigadier.arguments.BoolArgumentType.getBool(ctx, "enabled"))))).then(ClientCommandManager.literal("optin").executes(ctx -> toggleRewardOptOut("emeralds", false))).then(ClientCommandManager.literal("status").executes(ctx -> queryRewardStatus()))).then(ClientCommandManager.literal("warpay").executes(ctx -> queryRewardStatus()).then(ClientCommandManager.literal("optout").executes(ctx -> toggleRewardOptOut("warpay", true)).then(ClientCommandManager.argument("enabled", com.mojang.brigadier.arguments.BoolArgumentType.bool()).executes(ctx -> toggleRewardOptOut("warpay", com.mojang.brigadier.arguments.BoolArgumentType.getBool(ctx, "enabled"))))).then(ClientCommandManager.literal("optin").executes(ctx -> toggleRewardOptOut("warpay", false))).then(ClientCommandManager.literal("status").executes(ctx -> queryRewardStatus()))).then(ClientCommandManager.literal("rewards").executes(ctx -> queryRewardStatus()).then(ClientCommandManager.literal("status").executes(ctx -> queryRewardStatus()))).then(ClientCommandManager.literal("cf").executes(ctx -> { + })).then(ClientCommandManager.literal("optout").executes(ctx -> toggleRewardOptOut("aspects", true)).then(ClientCommandManager.argument("enabled", com.mojang.brigadier.arguments.BoolArgumentType.bool()).executes(ctx -> toggleRewardOptOut("aspects", com.mojang.brigadier.arguments.BoolArgumentType.getBool(ctx, "enabled"))))).then(ClientCommandManager.literal("optin").executes(ctx -> toggleRewardOptOut("aspects", false))).then(ClientCommandManager.literal("status").executes(ctx -> queryRewardStatus()))).then(ClientCommandManager.literal("emeralds").requires(guildOnly).then(ClientCommandManager.literal("optout").executes(ctx -> toggleRewardOptOut("emeralds", true)).then(ClientCommandManager.argument("enabled", com.mojang.brigadier.arguments.BoolArgumentType.bool()).executes(ctx -> toggleRewardOptOut("emeralds", com.mojang.brigadier.arguments.BoolArgumentType.getBool(ctx, "enabled"))))).then(ClientCommandManager.literal("optin").executes(ctx -> toggleRewardOptOut("emeralds", false))).then(ClientCommandManager.literal("status").executes(ctx -> queryRewardStatus()))).then(ClientCommandManager.literal("warpay").requires(guildOnly).executes(ctx -> queryRewardStatus()).then(ClientCommandManager.literal("optout").executes(ctx -> toggleRewardOptOut("warpay", true)).then(ClientCommandManager.argument("enabled", com.mojang.brigadier.arguments.BoolArgumentType.bool()).executes(ctx -> toggleRewardOptOut("warpay", com.mojang.brigadier.arguments.BoolArgumentType.getBool(ctx, "enabled"))))).then(ClientCommandManager.literal("optin").executes(ctx -> toggleRewardOptOut("warpay", false))).then(ClientCommandManager.literal("status").executes(ctx -> queryRewardStatus()))).then(ClientCommandManager.literal("rewards").requires(guildOnly).executes(ctx -> queryRewardStatus()).then(ClientCommandManager.literal("status").executes(ctx -> queryRewardStatus()))).then(ClientCommandManager.literal("cf").executes(ctx -> { requestCoinflip(ctx.getSource()); return 1; })).then(ClientCommandManager.literal("diceroll").executes(ctx -> { requestDiceroll(ctx.getSource()); return 1; - })).then(ClientCommandManager.literal("emojis").executes(ctx -> { + })).then(ClientCommandManager.literal("tc").then(ClientCommandManager.argument("message", StringArgumentType.greedyString()).executes(ctx -> sendTravelerChat(ctx.getSource(), StringArgumentType.getString(ctx, "message"))))).then(ClientCommandManager.literal("emojis").executes(ctx -> { showEmojis(ctx.getSource()); return 1; - })).then(buildPartyCommand()).then(buildAnnihilationCommand()).then(buildCommandCommand()).then(ClientCommandManager.literal("reply").then(ClientCommandManager.argument("messageId", StringArgumentType.word()).executes(ctx -> handleReplyCommand(StringArgumentType.getString(ctx, "messageId"))))).then(ClientCommandManager.literal("update").executes(ctx -> { + })).then(buildPartyCommand()).then(buildAnnihilationCommand()).then(buildCommandCommand()).then(ClientCommandManager.literal("reply").requires(guildOnly).then(ClientCommandManager.argument("messageId", StringArgumentType.word()).executes(ctx -> handleReplyCommand(StringArgumentType.getString(ctx, "messageId"))))).then(ClientCommandManager.literal("treply").then(ClientCommandManager.argument("messageId", StringArgumentType.word()).executes(ctx -> handleTravelerReplyCommand(StringArgumentType.getString(ctx, "messageId"))))).then(ClientCommandManager.literal("update").executes(ctx -> { updatePrompt(ctx.getSource()); return 1; }).then(ClientCommandManager.literal("download").executes(ctx -> { updateDownload(ctx.getSource()); return 1; - }))).then(buildGiftCommand()).then(buildDeductCommand()).then(buildAllyCommand()).then(buildEventCommand()).then(ClientCommandManager.literal("logscan").executes(ctx -> scanLog(ctx.getSource()))).then(ClientCommandManager.literal("dump").then(ClientCommandManager.argument("member", StringArgumentType.word()).suggests(this::suggestMembers).executes(ctx -> dumpEmeralds(ctx.getSource(), StringArgumentType.getString(ctx, "member"))))).then(ClientCommandManager.literal("wars").executes(ctx -> { + }))).then(buildGiftCommand()).then(buildDeductCommand()).then(buildAllyCommand()).then(buildEventCommand()).then(ClientCommandManager.literal("logscan").requires(guildOnly).executes(ctx -> scanLog(ctx.getSource()))).then(ClientCommandManager.literal("dump").requires(guildOnly).then(ClientCommandManager.argument("member", StringArgumentType.word()).suggests(this::suggestMembers).executes(ctx -> dumpEmeralds(ctx.getSource(), StringArgumentType.getString(ctx, "member"))))).then(ClientCommandManager.literal("wars").requires(guildOnly).executes(ctx -> { requestWarCounts(ctx.getSource(), 7); return 1; }).then(ClientCommandManager.argument("days", com.mojang.brigadier.arguments.IntegerArgumentType.integer(1, 365)).executes(ctx -> { @@ -861,6 +874,7 @@ public void release() { showHelp(ctx.getSource()); return 1; }))); + dispatcher.register(ClientCommandManager.literal("e").then(ClientCommandManager.argument("message", StringArgumentType.greedyString()).executes(ctx -> sendTravelerChat(ctx.getSource(), StringArgumentType.getString(ctx, "message"))))); }); Thread bootVerify = new Thread(() -> { @@ -1052,6 +1066,14 @@ public void onDiscordMessage(String author, String content, String replyTo, Stri displayColored(color, () -> DiscordChatFormatter.format(author, content, replyTo, replyExcerpt, messageId)); } + @Override + public void onTravelerChat(String author, String content, String source, String color, String replyTo, String replyExcerpt, String messageId) { + if (!config.travelerChat) { + return; + } + displayColored(color, () -> DiscordChatFormatter.travelerChat(author, content, replyTo, replyExcerpt, messageId)); + } + @Override public void onLoginNotice(String username, String color) { if (config.loginLogoutMode == BridgeConfig.LoginLogoutMode.HIDE_ALL) { @@ -1447,8 +1469,8 @@ public void onLongEventRewards(int pendingLe, String error) { } @Override - public void onAuthStatus(boolean linked, boolean member, String guildRank, String discordRank) { - handleAuthStatus(linked, member, guildRank, discordRank); + public void onAuthStatus(boolean linked, boolean member, boolean traveler, String guildRank, String discordRank) { + handleAuthStatus(linked, member, traveler, guildRank, discordRank); } }, EdenModClient::authenticateSession); socket.start(); @@ -1698,7 +1720,7 @@ private void requestAspectsPending(FabricClientCommandSource source) { /** Build {@code /eden gift } (Chiefs only). */ private LiteralArgumentBuilder buildGiftCommand() { - return ClientCommandManager.literal("gift").then(ClientCommandManager.argument("member", StringArgumentType.word()).suggests(this::suggestMembers).then(giftTypeArg("aspect", GuildRewards.RewardType.ASPECT)).then(giftTypeArg("emerald", GuildRewards.RewardType.EMERALD)).then(giftTypeArg("tome", GuildRewards.RewardType.TOME))); + return ClientCommandManager.literal("gift").requires(guildOnly).then(ClientCommandManager.argument("member", StringArgumentType.word()).suggests(this::suggestMembers).then(giftTypeArg("aspect", GuildRewards.RewardType.ASPECT)).then(giftTypeArg("emerald", GuildRewards.RewardType.EMERALD)).then(giftTypeArg("tome", GuildRewards.RewardType.TOME))); } private LiteralArgumentBuilder giftTypeArg(String literal, GuildRewards.RewardType type) { @@ -1707,7 +1729,7 @@ private LiteralArgumentBuilder giftTypeArg(String lit /** Build {@code /eden deduct } (Chiefs only). */ private LiteralArgumentBuilder buildDeductCommand() { - return ClientCommandManager.literal("deduct").then(deductKindArg("aspects")).then(deductKindArg("emeralds")); + return ClientCommandManager.literal("deduct").requires(guildOnly).then(deductKindArg("aspects")).then(deductKindArg("emeralds")); } private LiteralArgumentBuilder deductKindArg(String kind) { @@ -1736,7 +1758,7 @@ private int deductReward(FabricClientCommandSource source, String rewardKind, St /** Build {@code /eden ally (view | add | remove )}. */ private LiteralArgumentBuilder buildAllyCommand() { - return ClientCommandManager.literal("ally").executes(ctx -> { + return ClientCommandManager.literal("ally").requires(guildOnly).executes(ctx -> { requestAllyView(ctx.getSource()); return 1; }).then(ClientCommandManager.literal("view").executes(ctx -> { @@ -1776,7 +1798,7 @@ private void requestAllyView(FabricClientCommandSource source) { } private LiteralArgumentBuilder buildEventCommand() { - return ClientCommandManager.literal("event").executes(ctx -> openLongEventGui(ctx.getSource())).then(ClientCommandManager.literal("rewards").executes(ctx -> { + return ClientCommandManager.literal("event").requires(guildOnly).executes(ctx -> openLongEventGui(ctx.getSource())).then(ClientCommandManager.literal("rewards").executes(ctx -> { requestEventRewards(ctx.getSource()); return 1; })); @@ -2323,7 +2345,7 @@ private int partyOpen(FabricClientCommandSource source, String raid, int maxSize source.sendFeedback(notConnected()); return 0; } - current.sendPartyOpen(raid, maxSize, note, filled); + current.sendPartyOpen(raid, maxSize, note, filled, isTraveler(), ""); return 1; } @@ -2353,6 +2375,15 @@ private int partyLeave(FabricClientCommandSource source, Integer id) { // The pill label the bridge games (cf/diceroll/8ball) ride on; hidden by config toggle. private static final String GAMES_PILL_LABEL = "eden"; + private int sendTravelerChat(FabricClientCommandSource source, String message) { + BridgeWebSocketClient current = socket; + if (current == null || !current.sendTravelerChat(message, ChatReplyManager.takeTravelerReply())) { + source.sendFeedback(notConnected()); + return 0; + } + return 1; + } + private static Component notConnected() { return Component.literal("Not connected to the Eden bridge.").withStyle(net.minecraft.ChatFormatting.RED); } @@ -2679,10 +2710,25 @@ private int handleReplyCommand(String messageId) { return 1; } + private int handleTravelerReplyCommand(String messageId) { + ChatReplyManager.setActiveTravelerReply(messageId); + Minecraft mc = Minecraft.getInstance(); + mc.execute(() -> { + if (!(mc.screen instanceof net.minecraft.client.gui.screens.ChatScreen)) { + mc.setScreen(new net.minecraft.client.gui.screens.ChatScreen("/e ", false)); + } else { + ChatReplyManager.ensureGuildPrefix(); + } + }); + return 1; + } + private record HelpEntry(String command, String description) { } - private static final List HELP_ENTRIES = List.of(new HelpEntry("/eden config", "open the config screen"), new HelpEntry("/eden online", "who's connected to the bridge"), new HelpEntry("/eden mail ", "leave a member a message for their next login"), new HelpEntry("/eden cf", "flip a coin"), new HelpEntry("/eden diceroll", "roll a die"), new HelpEntry("/eden wars [days]", "guild war counts (same as Discord)"), new HelpEntry("/eden emojis", "open the chat emote picker"), new HelpEntry("/eden event", "open the event missions screen"), new HelpEntry("/eden event rewards", "check your pending event LE"), new HelpEntry("/eden party", "list open parties (click to join)"), new HelpEntry("/eden party create [note]", "open a raid party"), new HelpEntry("/eden party join ", "join a party"), new HelpEntry("/eden party leave [id]", "leave your party"), new HelpEntry("/eden party disband", "disband your hosted party"), new HelpEntry("/eden anni [note]", "open an Annihilation party (2-10)"), new HelpEntry("/eden command alias", "open the command alias editor"), new HelpEntry("/eden command keybind", "open the command keybind editor"), new HelpEntry("/eden update", "check for a pending update"), new HelpEntry("/eden update download", "download the update now (applies on exit)"), new HelpEntry("/eden aspects pending", "members' pending aspects — Chiefs only"), new HelpEntry("/eden gift ", "gift guild rewards — Chiefs only"), new HelpEntry("/eden dump ", "gift all guild-bank emeralds to a member — Chiefs only"), new HelpEntry("/eden deduct ", "deduct a payout from pending rewards — Chiefs only"), new HelpEntry("/eden ally view", "view guild ally activity (most inactive to active)"), new HelpEntry("/eden ally add ", "add a guild ally — Strategist+ only"), new HelpEntry("/eden ally remove ", "remove a guild ally — Strategist+ only"), new HelpEntry("/eden rewards", "check your pending aspects/emeralds/warpay and opt-out status"), new HelpEntry("/eden aspects optout [true|false]", "opt out of or into receiving aspects"), new HelpEntry("/eden emeralds optout [true|false]", "opt out of or into receiving emeralds"), new HelpEntry("/eden warpay optout [true|false]", "opt out of or into receiving warpay"), new HelpEntry("/eden help", "this help screen")); + private static final java.util.Set GUILD_ONLY_COMMANDS = java.util.Set.of("online", "wars", "event", "aspects", "emeralds", "warpay", "rewards", "gift", "dump", "deduct", "ally", "reply", "logscan"); + + private static final List HELP_ENTRIES = List.of(new HelpEntry("/eden config", "open the config screen"), new HelpEntry("/eden online", "who's connected to the bridge"), new HelpEntry("/eden mail ", "leave a member a message for their next login"), new HelpEntry("/eden cf", "flip a coin"), new HelpEntry("/eden diceroll", "roll a die"), new HelpEntry("/eden tc ", "chat with travelers and members (alias /e)"), new HelpEntry("/eden wars [days]", "guild war counts (same as Discord)"), new HelpEntry("/eden emojis", "open the chat emote picker"), new HelpEntry("/eden event", "open the event missions screen"), new HelpEntry("/eden event rewards", "check your pending event LE"), new HelpEntry("/eden party", "list open parties (click to join)"), new HelpEntry("/eden party create [note]", "open a raid party"), new HelpEntry("/eden party join ", "join a party"), new HelpEntry("/eden party leave [id]", "leave your party"), new HelpEntry("/eden party disband", "disband your hosted party"), new HelpEntry("/eden anni [note]", "open an Annihilation party (2-10)"), new HelpEntry("/eden command alias", "open the command alias editor"), new HelpEntry("/eden command keybind", "open the command keybind editor"), new HelpEntry("/eden update", "check for a pending update"), new HelpEntry("/eden update download", "download the update now (applies on exit)"), new HelpEntry("/eden aspects pending", "members' pending aspects — Chiefs only"), new HelpEntry("/eden gift ", "gift guild rewards — Chiefs only"), new HelpEntry("/eden dump ", "gift all guild-bank emeralds to a member — Chiefs only"), new HelpEntry("/eden deduct ", "deduct a payout from pending rewards — Chiefs only"), new HelpEntry("/eden ally view", "view guild ally activity (most inactive to active)"), new HelpEntry("/eden ally add ", "add a guild ally — Strategist+ only"), new HelpEntry("/eden ally remove ", "remove a guild ally — Strategist+ only"), new HelpEntry("/eden rewards", "check your pending aspects/emeralds/warpay and opt-out status"), new HelpEntry("/eden aspects optout [true|false]", "opt out of or into receiving aspects"), new HelpEntry("/eden emeralds optout [true|false]", "opt out of or into receiving emeralds"), new HelpEntry("/eden warpay optout [true|false]", "opt out of or into receiving warpay"), new HelpEntry("/eden help", "this help screen")); private static final class TrackedCommandKeybind { private final String input; @@ -2721,6 +2767,9 @@ private void setDown(boolean down) { private void showHelp(FabricClientCommandSource source) { MutableComponent help = Component.literal("EdenMod — in-game commands:").withStyle(net.minecraft.ChatFormatting.GREEN); for (HelpEntry entry : HELP_ENTRIES) { + if (isTraveler() && GUILD_ONLY_COMMANDS.contains(entry.command().split(" ")[1])) { + continue; + } help.append(helpLine(entry.command(), entry.description())); } help.append(Component.literal("\nPress ").withStyle(ChatFormatting.DARK_GRAY)).append(openConfigButton()).append(Component.literal(" to open the bridge config screen.").withStyle(ChatFormatting.DARK_GRAY)); @@ -2791,8 +2840,14 @@ private void handBackOutstandingDeducts(String reason) { * begins the session; otherwise the socket stays open with no guild access and the * player is prompted once per standing change. Runs off the game thread. */ - private void handleAuthStatus(boolean linked, boolean member, String guildRank, String discordRank) { + private void handleAuthStatus(boolean linked, boolean member, boolean traveler, String guildRank, String discordRank) { BridgeStatus previous = bridgeStatus; + if (config.wasMember == null || config.wasMember != member) { + config.wasMember = member; + // Saved on the game thread: serializing here could race with config edits and + // throw before the standing below is applied. + Minecraft.getInstance().execute(config::save); + } if (linked && member) { bridgeStatus = BridgeStatus.FULL; liveGuildRank = guildRank; @@ -2803,27 +2858,26 @@ private void handleAuthStatus(boolean linked, boolean member, String guildRank, if (previous != BridgeStatus.NOT_LINKED) { display(() -> DiscordChatFormatter.linkReminder(openConfigButton())); } + reportAttestationFailure(); + } else if (traveler) { + bridgeStatus = BridgeStatus.TRAVELER; + if (previous != BridgeStatus.TRAVELER) { + display(() -> DiscordChatFormatter.systemLine("Connected as an Eden Traveler — guild features are hidden.", ChatFormatting.GREEN)); + } + onTravelerConnected(); } else { bridgeStatus = BridgeStatus.NOT_MEMBER; if (previous != BridgeStatus.NOT_MEMBER) { display(() -> DiscordChatFormatter.systemLine("You're not in the Eden guild — the bridge is inactive.", ChatFormatting.YELLOW)); } + reportAttestationFailure(); } } /** On full access, begin this session: hand back deducts and announce login once. */ private void onBridgeConnected() { handBackOutstandingDeducts("were not confirmed deducted before the bridge dropped"); - if (!attestationFailureReported) { - String failedSha = updateInstaller.bootAttestationFailureSha(); - if (failedSha != null) { - attestationFailureReported = true; - BridgeWebSocketClient current = socket; - if (current != null) { - current.sendAttestationFailure(failedSha); - } - } - } + reportAttestationFailure(); if (loginPending) { loginPending = false; BridgeWebSocketClient current = socket; @@ -2838,10 +2892,49 @@ private void onBridgeConnected() { current.sendPresence(inGameWorld); // send whatever state we already detected } } + syncTravelerPrefs(config); syncRadianceGroup(config); queryRewardStatus(true); } + /** Report a failed boot attestation to the bridge, once per session, on the first connect with a standing. */ + private void reportAttestationFailure() { + if (attestationFailureReported) { + return; + } + String failedSha = updateInstaller.bootAttestationFailureSha(); + if (failedSha != null) { + attestationFailureReported = true; + BridgeWebSocketClient current = socket; + if (current != null) { + current.sendAttestationFailure(failedSha); + } + } + } + + /** A traveler gets presence and its chat/games preferences only — nothing guild-related. */ + private void onTravelerConnected() { + reportAttestationFailure(); + if (loginPending) { + loginPending = false; + BridgeWebSocketClient current = socket; + if (current != null) { + current.sendPresence(inGameWorld); + } + } + syncTravelerPrefs(config); + } + + public static void syncTravelerPrefs(BridgeConfig config) { + if (config == null || instance == null) { + return; + } + BridgeWebSocketClient current = instance.socket; + if (current != null) { + current.sendTravelerPrefs(config.travelerChat, BridgeWebSocketClient.gamesPref(instance.isTraveler(), config.memberGames, config.travelerGames)); + } + } + public static void syncRadianceGroup(BridgeConfig config) { if (config == null || instance == null) { return; diff --git a/src/tel/eden/mod/chat/ChatReplyManager.java b/src/tel/eden/mod/chat/ChatReplyManager.java index 48c8c1d..287da5e 100644 --- a/src/tel/eden/mod/chat/ChatReplyManager.java +++ b/src/tel/eden/mod/chat/ChatReplyManager.java @@ -10,7 +10,7 @@ * Manages active and pending Discord reply state for the in-game chat UI and bridge. */ public final class ChatReplyManager { - public record ReplyInfo(String messageId, String author, String excerpt) { + public record ReplyInfo(String messageId, String author, String excerpt, boolean traveler) { } private static final int MAX_CACHE_SIZE = 100; @@ -59,6 +59,15 @@ public static synchronized void ensureGuildPrefix() { /** Record a received Discord message so it can be replied to by ID. */ public static synchronized void recordDiscordMessage(String messageId, String author, String content) { + record(messageId, author, content, false); + } + + /** Record a received traveler-chat message so it can be replied to by ID. */ + public static synchronized void recordTravelerMessage(String messageId, String author, String content) { + record(messageId, author, content, true); + } + + private static void record(String messageId, String author, String content, boolean traveler) { if (messageId == null || messageId.isEmpty() || author == null) { return; } @@ -66,7 +75,7 @@ public static synchronized void recordDiscordMessage(String messageId, String au if (excerpt.length() > 60) { excerpt = excerpt.substring(0, 57).strip() + "..."; } - RECENT_MESSAGES.put(messageId, new ReplyInfo(messageId, author, excerpt)); + RECENT_MESSAGES.put(messageId, new ReplyInfo(messageId, author, excerpt, traveler)); } /** Retrieve cached message metadata by Discord message ID. */ @@ -76,12 +85,37 @@ static synchronized ReplyInfo getRecent(String messageId) { /** Set active reply context looking up cached metadata. */ public static synchronized void setActiveReply(String messageId) { + setActiveReply(messageId, false); + } + + /** As {@link #setActiveReply(String)} for a traveler-chat message; an unknown id is still a traveler reply. */ + public static synchronized void setActiveTravelerReply(String messageId) { + setActiveReply(messageId, true); + } + + private static void setActiveReply(String messageId, boolean traveler) { ReplyInfo info = RECENT_MESSAGES.get(messageId); - if (info != null) { - activeReply = info; - } else { - activeReply = new ReplyInfo(messageId, "Discord", ""); + activeReply = info != null ? new ReplyInfo(messageId, info.author(), info.excerpt(), traveler) : new ReplyInfo(messageId, "Discord", "", traveler); + } + + /** Whether the active reply targets a traveler-chat message. */ + public static synchronized boolean isActiveReplyTraveler() { + return activeReply != null && activeReply.traveler(); + } + + /** Chat prefix that routes a message to the active reply's channel: /e for traveler chat, /g otherwise. */ + public static synchronized String activeReplyPrefix() { + return isActiveReplyTraveler() ? "/e " : "/g "; + } + + /** If the active reply is a traveler one, return its message ID and clear it; otherwise null, state untouched. */ + public static synchronized String takeTravelerReply() { + if (!isActiveReplyTraveler()) { + return null; } + String id = activeReply.messageId(); + activeReply = null; + return id; } /** Currently active reply context in the chat UI. */ diff --git a/src/tel/eden/mod/chat/DiscordChatFormatter.java b/src/tel/eden/mod/chat/DiscordChatFormatter.java index efeee3c..8f07a05 100644 --- a/src/tel/eden/mod/chat/DiscordChatFormatter.java +++ b/src/tel/eden/mod/chat/DiscordChatFormatter.java @@ -225,12 +225,40 @@ public static Component format(String author, String content, String replyTo, St body.append(authorComp); if (replyTo != null && !replyTo.isEmpty()) { - body.append(Component.literal(" replied to ").withStyle(ChatFormatting.GRAY)).append(replyTarget(replyTo, replyExcerpt)).append(Component.literal(": ").withStyle(ChatFormatting.GREEN)); + body.append(Component.literal(" replied to ").withStyle(ChatFormatting.GRAY)).append(replyTarget(replyTo, replyExcerpt, Style.EMPTY.withColor(ChatFormatting.GREEN))).append(Component.literal(": ").withStyle(ChatFormatting.GREEN)); } body.append(linkify(content, replyStyle)); return withGuildPrefix(body); } + // Traveler chat's own color, lavender, so it never reads as guild (aqua) or Discord (green) chat. + private static final int TRAVELER_RGB = 0xB388FF; + // The message text is a lighter shade than the tag and name so the name stands out. + private static final int TRAVELER_TEXT_RGB = 0xD8C2FF; + + // Invisible line markers a Wynntils chat-tab regex can match: one zero-width + // non-joiner on every line this mod draws, two on traveler chat so it can be + // routed to (or kept out of) its own tab. + private static final String LINE_MARKER = "\u200C"; + private static final String TRAVELER_MARKER = "\u200C\u200C"; + + /** A traveler-chat line; links, images, GIFs, stickers and emotes render as in bridge chat. */ + public static Component travelerChat(String author, String content, String replyTo, String replyExcerpt, String messageId) { + boolean hasId = messageId != null && !messageId.isEmpty(); + if (hasId) { + ChatReplyManager.recordTravelerMessage(messageId, author, content); + } + Style color = Style.EMPTY.withColor(TRAVELER_RGB); + Style click = hasId ? color.withClickEvent(new ClickEvent.RunCommand("/eden treply " + messageId)).withHoverEvent(new HoverEvent.ShowText(Component.literal("Click to reply to @" + author).withStyle(ChatFormatting.GRAY))) : color; + boolean reply = replyTo != null && !replyTo.isEmpty(); + MutableComponent body = Component.empty().append(Component.literal(pillLabel("traveler")).withStyle(click.withFont(PILL_FONT))).append(Component.literal(reply ? " " + author : " " + author + ": ").withStyle(click)); + if (reply) { + body.append(Component.literal(" replied to ").withStyle(ChatFormatting.GRAY)).append(replyTarget(replyTo, replyExcerpt, color)).append(Component.literal(": ").withStyle(color)); + } + body.append(linkify(content, hasId ? click : null, Style.EMPTY.withColor(TRAVELER_TEXT_RGB))); + return withGuildPrefix(body, TRAVELER_MARKER); + } + /** * Build a gold-pill bridge line (Quick Reactions, {@code /eden cf}/{@code diceroll}): * a gold pill labelled {@code label}, then the {@code content} in gold. Mirrors @@ -265,8 +293,8 @@ public static Component pill(String label, String content, Integer colorRgb, boo } /** The "replyTo (excerpt)" segment: name in green, inline quote gray, full quote on hover. */ - private static MutableComponent replyTarget(String replyTo, String replyExcerpt) { - MutableComponent segment = Component.literal(replyTo).withStyle(ChatFormatting.GREEN); + private static MutableComponent replyTarget(String replyTo, String replyExcerpt, Style nameStyle) { + MutableComponent segment = Component.literal(replyTo).withStyle(nameStyle); String quote = replyExcerpt == null ? "" : ChatText.normalizeWhitespace(replyExcerpt); if (!quote.isEmpty()) { String shown = quote.length() > EXCERPT_MAX ? quote.substring(0, EXCERPT_MAX).strip() + "…" : quote; @@ -288,13 +316,17 @@ private static MutableComponent linkify(String content) { } private static MutableComponent linkify(String content, Style replyStyle) { + return linkify(content, replyStyle, Style.EMPTY.withColor(ChatFormatting.GREEN)); + } + + private static MutableComponent linkify(String content, Style replyStyle, Style textStyle) { MutableComponent out = Component.empty(); Matcher matcher = TOKEN_PATTERN.matcher(content); int last = 0; // Click event for the text body (without hover popup so reading isn't obstructed) ClickEvent textClick = replyStyle != null ? replyStyle.getClickEvent() : null; java.util.function.Consumer appendText = text -> { - MutableComponent comp = Component.literal(text).withStyle(ChatFormatting.GREEN); + MutableComponent comp = Component.literal(text).withStyle(textStyle); if (textClick != null) { comp.setStyle(comp.getStyle().withClickEvent(textClick)); } @@ -407,8 +439,12 @@ public static Component processEmotes(Component message) { /** Wrap the body to chat width, prefixing line 1 with the shield and the rest with bars. */ private static Component withGuildPrefix(Component body) { - Component shield = prefix(SHIELD); - Component continuation = prefix(CONTINUATION); + return withGuildPrefix(body, LINE_MARKER); + } + + private static Component withGuildPrefix(Component body, String marker) { + Component shield = prefix(SHIELD, marker); + Component continuation = prefix(CONTINUATION, marker); Minecraft mc = Minecraft.getInstance(); Font font = mc.font; int reserve = font.width(continuation); @@ -440,8 +476,12 @@ private static int chatWidth(Minecraft mc) { } private static Component prefix(int[] glyphs) { + return prefix(glyphs, LINE_MARKER); + } + + private static Component prefix(int[] glyphs, String marker) { StringBuilder out = new StringBuilder(); - out.append('\u200C'); + out.append(marker); for (int glyph : glyphs) { out.appendCodePoint(glyph); } diff --git a/src/tel/eden/mod/config/BridgeConfig.java b/src/tel/eden/mod/config/BridgeConfig.java index 8bfb6db..2d8b882 100644 --- a/src/tel/eden/mod/config/BridgeConfig.java +++ b/src/tel/eden/mod/config/BridgeConfig.java @@ -83,6 +83,19 @@ public String label() { /** Play a short chime when Eden mail arrives. On by default. */ public boolean mailSound = true; + /** Show traveler chat (non-guild players and members talking together). On by default. */ + public boolean travelerChat = true; + + public enum MemberGames { + GUILD, ALL, OFF + } + + /** Members: which game lines to show: guild games only (default), all, or none. */ + public MemberGames memberGames = MemberGames.GUILD; + + /** Travelers: show game lines at all ("all") or none ("off"). On by default. */ + public boolean travelerGames = true; + /** * Whether open/full raid parties are auto-announced in chat with a clickable * {@code [JOIN #id]} feed. When false, parties are only shown on demand via @@ -243,6 +256,17 @@ public void sanitize() { /** Master toggle for the Territory Preset Helper Wynntils add-on. On by default. */ public boolean territoryMenuSuite = true; + /** + * Last standing the backend reported: true = guild member. Null (older configs) counts as a + * member so presets do not vanish for members before their first connect after updating. + */ + public Boolean wasMember = null; + + /** Preset UI is for guild members only; wasMember is refreshed on every authOk, so it also covers an outage. */ + public boolean presetsEnabled() { + return territoryMenuSuite && (wasMember == null || wasMember); + } + /** Active territory preset encoded Base64 or JSON string, or empty. */ public String territoryActivePreset = ""; @@ -477,6 +501,9 @@ static void migrateLegacyFields(BridgeConfig config) { if (config.loginLogoutMode == null) { config.loginLogoutMode = LoginLogoutMode.ALL; } + if (config.memberGames == null) { + config.memberGames = MemberGames.GUILD; + } } /** Load the config from disk, or return defaults (and write them) if absent. */ diff --git a/src/tel/eden/mod/gui/BridgeConfigScreen.java b/src/tel/eden/mod/gui/BridgeConfigScreen.java index 46f99bd..dda7e88 100644 --- a/src/tel/eden/mod/gui/BridgeConfigScreen.java +++ b/src/tel/eden/mod/gui/BridgeConfigScreen.java @@ -112,15 +112,44 @@ protected void init() { }, popupSettings)); // --- One line per setting; the list handles layout + smooth scrolling. --- + // Travelers keep local features only: guild-bound rows are not built at all. + boolean traveler = mod.isTraveler(); // General addToggleRow(Category.GENERAL, "Bridge", () -> config.enabled, v -> config.enabled = v, "Enabled", "Disabled", true); - addToggleRow(Category.GENERAL, "Discord Bridge Messages", () -> config.discordBridgeMessages, v -> config.discordBridgeMessages = v, "On", "Off", true); - addCycleRow(Category.GENERAL, "Login/logout messages", () -> config.loginLogoutMode.label(), () -> config.loginLogoutMode = nextLoginLogoutMode(config.loginLogoutMode), () -> config.loginLogoutMode = BridgeConfig.LoginLogoutMode.ALL); + if (!traveler) { + addToggleRow(Category.GENERAL, "Discord Bridge Messages", () -> config.discordBridgeMessages, v -> config.discordBridgeMessages = v, "On", "Off", true); + } + addToggleRow(Category.GENERAL, "Traveler chat", () -> config.travelerChat, v -> { + config.travelerChat = v; + EdenModClient.syncTravelerPrefs(config); + }, "On", "Off", true); + if (!traveler) { + addCycleRow(Category.GENERAL, "Login/logout messages", () -> config.loginLogoutMode.label(), () -> config.loginLogoutMode = nextLoginLogoutMode(config.loginLogoutMode), () -> config.loginLogoutMode = BridgeConfig.LoginLogoutMode.ALL); + } + if (traveler) { + addToggleRow(Category.GENERAL, "Games shown", () -> config.travelerGames, v -> { + config.travelerGames = v; + EdenModClient.syncTravelerPrefs(config); + }, "All", "Off", true); + } else { + addCycleRow(Category.GENERAL, "Games shown", () -> MEMBER_GAMES_LABELS[config.memberGames.ordinal()], () -> { + BridgeConfig.MemberGames[] values = BridgeConfig.MemberGames.values(); + config.memberGames = values[(config.memberGames.ordinal() + 1) % values.length]; + EdenModClient.syncTravelerPrefs(config); + }, () -> { + config.memberGames = BridgeConfig.MemberGames.GUILD; + EdenModClient.syncTravelerPrefs(config); + }); + } addToggleRow(Category.GENERAL, "Mail sound", () -> config.mailSound, v -> config.mailSound = v, "On", "Off", true); addToggleRow(Category.GENERAL, "Party feed", () -> config.partyAnnounce, v -> config.partyAnnounce = v, "On", "Off", true); - addToggleRow(Category.GENERAL, "Event announcements", () -> config.eventAnnouncements, v -> config.eventAnnouncements = v, "On", "Off", true); + if (!traveler) { + addToggleRow(Category.GENERAL, "Event announcements", () -> config.eventAnnouncements, v -> config.eventAnnouncements = v, "On", "Off", true); + } addToggleRow(Category.GENERAL, "Auto /stream on join", () -> config.autoStream, v -> config.autoStream = v, "On", "Off", false); - addToggleRow(Category.GENERAL, "Click shouts to reply", () -> config.shoutsClickable, v -> config.shoutsClickable = v, "On", "Off", true); + if (!traveler) { + addToggleRow(Category.GENERAL, "Click shouts to reply", () -> config.shoutsClickable, v -> config.shoutsClickable = v, "On", "Off", true); + } addToggleRow(Category.GENERAL, "Click-to-congratulate", () -> config.clickToCongratulate, v -> config.clickToCongratulate = v, "On", "Off", false); EditBox congratsBox = new EditBox(this.font, 0, 0, CONTROL_W, 20, Component.literal("Congrats message")); congratsBox.setMaxLength(80); @@ -163,7 +192,9 @@ protected void init() { addSliderRow(Category.WAR, "Max attack-timer rows", rowsSlider, rowsSlider::syncFromConfig, () -> config.warAttackTimerMaxRows = 14); addToggleRow(Category.WAR, "Green beacon at soonest war", () -> config.warGreenBeacon, v -> config.warGreenBeacon = v, "On", "Off", true); addToggleRow(Category.WAR, "War info overlay (DPS/EHP)", () -> config.warDpsHud, v -> config.warDpsHud = v, "On", "Off", true); - addToggleRow(Category.WAR, "Weekly war count HUD", () -> config.warWeeklyCountHud, v -> config.warWeeklyCountHud = v, "On", "Off", false); + if (!traveler) { + addToggleRow(Category.WAR, "Weekly war count HUD", () -> config.warWeeklyCountHud, v -> config.warWeeklyCountHud = v, "On", "Off", false); + } addToggleRow(Category.WAR, "War start bell (25s)", () -> config.warBattleStartBell, v -> config.warBattleStartBell = v, "On", "Off", false); IntConfigSlider timerBellSlider = new IntConfigSlider(CONTROL_W, 20, 0, 120, 5, () -> config.warAttackTimerBellSeconds, v -> config.warAttackTimerBellSeconds = v, v -> Component.literal(v == 0 ? "Off" : v + "s")); addSliderRow(Category.WAR, "Attack timer bell (in territory)", timerBellSlider, timerBellSlider::syncFromConfig, () -> config.warAttackTimerBellSeconds = 0); @@ -171,30 +202,32 @@ protected void init() { addToggleRow(Category.WAR, "Territory loss sound", () -> config.territoryLossSound, v -> config.territoryLossSound = v, "On", "Off", false); addToggleRow(Category.WAR, "Territory loss blacklist", () -> config.territoryLossBlacklistEnabled, v -> config.territoryLossBlacklistEnabled = v, "On", "Off", true); addButtonRow(Category.WAR, "Territory blacklist", () -> Component.literal("Edit (" + config.territoryLossBlacklist.size() + ")"), () -> this.minecraft.setScreen(new TerritoryLossBlacklistScreen(this, config)), () -> config.territoryLossBlacklist = new ArrayList<>(BridgeConfig.DEFAULT_TERRITORY_LOSS_BLACKLIST)); - addToggleRow(Category.WAR, "Radiance tracker", () -> config.radianceTracker, v -> { - config.radianceTracker = v; - EdenModClient.syncRadianceGroup(config); - }, "On", "Off", false); - addCycleRow(Category.WAR, "Radiance aspect", () -> radianceAspectLabel(config.radianceSelfTier), () -> config.radianceSelfTier = (config.radianceSelfTier + 1) % 4, () -> config.radianceSelfTier = 0); - DoubleConfigSlider graceSlider = new DoubleConfigSlider(CONTROL_W, 20, 0.0, 3.0, 0.25, () -> config.radianceAdvanceNoticeSeconds, v -> config.radianceAdvanceNoticeSeconds = v, v -> Component.literal(formatGraceSeconds(v))); - addSliderRow(Category.WAR, "Radiance grace", graceSlider, graceSlider::syncFromConfig, () -> config.radianceAdvanceNoticeSeconds = 1.25); - addToggleRow(Category.WAR, "Radiance require war", () -> config.radianceRequireWar, v -> config.radianceRequireWar = v, "On", "Off", true); - addToggleRow(Category.WAR, "Radiance audio ping", () -> config.radiancePing, v -> config.radiancePing = v, "On", "Off", true); - EditBox radianceKeyBox = new EditBox(this.font, 0, 0, CONTROL_W, 20, Component.literal("Radiance group key")); - radianceKeyBox.setMaxLength(64); - radianceKeyBox.setValue(config.radianceGroupKey); - radianceKeyBox.setResponder(value -> config.radianceGroupKey = value.trim()); - addRow(Category.WAR, "Radiance group key", radianceKeyBox, () -> { - if (!radianceKeyBox.isFocused() && !radianceKeyBox.getValue().equals(config.radianceGroupKey)) { - radianceKeyBox.setValue(config.radianceGroupKey); - } - }, () -> { - config.radianceGroupKey = ""; - radianceKeyBox.setValue(""); - config.save(); - EdenModClient.syncRadianceGroup(config); - }); - addToggleRow(Category.WAR, "Territory preset helper", () -> config.territoryMenuSuite, v -> config.territoryMenuSuite = v, "On", "Off", true); + if (!traveler) { + addToggleRow(Category.WAR, "Radiance tracker", () -> config.radianceTracker, v -> { + config.radianceTracker = v; + EdenModClient.syncRadianceGroup(config); + }, "On", "Off", false); + addCycleRow(Category.WAR, "Radiance aspect", () -> radianceAspectLabel(config.radianceSelfTier), () -> config.radianceSelfTier = (config.radianceSelfTier + 1) % 4, () -> config.radianceSelfTier = 0); + DoubleConfigSlider graceSlider = new DoubleConfigSlider(CONTROL_W, 20, 0.0, 3.0, 0.25, () -> config.radianceAdvanceNoticeSeconds, v -> config.radianceAdvanceNoticeSeconds = v, v -> Component.literal(formatGraceSeconds(v))); + addSliderRow(Category.WAR, "Radiance grace", graceSlider, graceSlider::syncFromConfig, () -> config.radianceAdvanceNoticeSeconds = 1.25); + addToggleRow(Category.WAR, "Radiance require war", () -> config.radianceRequireWar, v -> config.radianceRequireWar = v, "On", "Off", true); + addToggleRow(Category.WAR, "Radiance audio ping", () -> config.radiancePing, v -> config.radiancePing = v, "On", "Off", true); + EditBox radianceKeyBox = new EditBox(this.font, 0, 0, CONTROL_W, 20, Component.literal("Radiance group key")); + radianceKeyBox.setMaxLength(64); + radianceKeyBox.setValue(config.radianceGroupKey); + radianceKeyBox.setResponder(value -> config.radianceGroupKey = value.trim()); + addRow(Category.WAR, "Radiance group key", radianceKeyBox, () -> { + if (!radianceKeyBox.isFocused() && !radianceKeyBox.getValue().equals(config.radianceGroupKey)) { + radianceKeyBox.setValue(config.radianceGroupKey); + } + }, () -> { + config.radianceGroupKey = ""; + radianceKeyBox.setValue(""); + config.save(); + EdenModClient.syncRadianceGroup(config); + }); + addToggleRow(Category.WAR, "Territory preset helper", () -> config.territoryMenuSuite, v -> config.territoryMenuSuite = v, "On", "Off", true); + } // Visuals & QoL if (config.isSecretUnlocked(BridgeConfig.SECRET_BABY_PLAYERS)) { @@ -284,6 +317,8 @@ private void startLinkFlow() { mod.startLinkFlow(() -> this.minecraft.execute(() -> this.minecraft.setScreen(BridgeConfigScreen.create(parent, mod)))); } + private static final String[] MEMBER_GAMES_LABELS = {"Guild only", "All", "Off"}; + private BridgeConfig.LoginLogoutMode nextLoginLogoutMode(BridgeConfig.LoginLogoutMode current) { BridgeConfig.LoginLogoutMode safe = current != null ? current : BridgeConfig.LoginLogoutMode.ALL; BridgeConfig.LoginLogoutMode[] values = BridgeConfig.LoginLogoutMode.values(); @@ -313,6 +348,7 @@ private Component linkStatusText() { return switch (mod.bridgeStatus()) { case FULL -> Component.literal(name == null || name.isEmpty() ? "Linked" : "Linked as " + name).withStyle(style -> style.withColor(0x55FF55)); case NOT_MEMBER -> Component.literal("Linked, but not in the Eden guild").withStyle(style -> style.withColor(0xFFAA00)); + case TRAVELER -> Component.literal(name == null || name.isEmpty() ? "Linked as a Traveler" : "Linked as " + name + " (Traveler)").withStyle(style -> style.withColor(0x55FFFF)); case NOT_LINKED -> Component.literal("Not linked").withStyle(style -> style.withColor(0xFFAA00)); case UNKNOWN -> Component.literal("Join Wynncraft to check status").withStyle(style -> style.withColor(0xAAAAAA)); }; @@ -550,6 +586,7 @@ public boolean mouseScrolled(double mouseX, double mouseY, double dx, double dy) public void onClose() { config.save(); EdenModClient.syncRadianceGroup(config); + EdenModClient.syncTravelerPrefs(config); this.minecraft.setScreen(parent); } diff --git a/src/tel/eden/mod/gui/EdenMenuScreen.java b/src/tel/eden/mod/gui/EdenMenuScreen.java index 6195a99..07db757 100644 --- a/src/tel/eden/mod/gui/EdenMenuScreen.java +++ b/src/tel/eden/mod/gui/EdenMenuScreen.java @@ -18,6 +18,8 @@ public class EdenMenuScreen extends EdenScreen { private static final int BUTTON_HEIGHT = 20; private static final int BUTTON_SPACING = 24; private static final int BUTTON_COUNT = 8; + // Event and Payouts are guild-only. + private static final int TRAVELER_HIDDEN_BUTTONS = 2; private static final int LOGO_WIDTH = 128; private static final int LOGO_GAP = 20; private static final int CONTENT_MARGIN = 12; @@ -46,26 +48,30 @@ public EdenMenuScreen() { protected void init() { super.init(); int baseLogoHeight = LOGO_WIDTH * LOGO_H / LOGO_W; - int baseStackHeight = BUTTON_HEIGHT + BUTTON_SPACING * (BUTTON_COUNT - 1); + int baseStackHeight = BUTTON_HEIGHT + BUTTON_SPACING * (buttonCount() - 1); int baseTotalHeight = baseLogoHeight + LOGO_GAP + baseStackHeight; layout = EdenPanelLayout.centered(this.width, this.height, BASE_CONTENT_WIDTH + (CONTENT_MARGIN * 2), baseTotalHeight + (MIN_TOP_SAFE_MARGIN * 2)); MenuMetrics metrics = menuMetrics(); + boolean traveler = isTraveler(); + int slot = 0; this.addRenderableWidget(Button.builder(Component.literal("Config"), button -> { this.minecraft.setScreen(BridgeConfigScreen.create(this, EdenModClient.instance())); - }).bounds(metrics.buttonX, metrics.startY, metrics.buttonWidth, metrics.buttonHeight).build()); + }).bounds(metrics.buttonX, metrics.startY + (metrics.buttonPitch * slot++), metrics.buttonWidth, metrics.buttonHeight).build()); - this.addRenderableWidget(Button.builder(Component.literal("Event"), button -> { - EdenModClient mod = EdenModClient.instance(); - if (mod != null && mod.socket() != null && mod.socket().isConnected()) { - mod.socket().sendLongEventStateRequest(); - } - this.minecraft.setScreen(new LongEventScreen(this, mod)); - }).bounds(metrics.buttonX, metrics.startY + metrics.buttonPitch, metrics.buttonWidth, metrics.buttonHeight).build()); + if (isMember()) { + this.addRenderableWidget(Button.builder(Component.literal("Event"), button -> { + EdenModClient mod = EdenModClient.instance(); + if (mod != null && mod.socket() != null && mod.socket().isConnected()) { + mod.socket().sendLongEventStateRequest(); + } + this.minecraft.setScreen(new LongEventScreen(this, mod)); + }).bounds(metrics.buttonX, metrics.startY + (metrics.buttonPitch * slot++), metrics.buttonWidth, metrics.buttonHeight).build()); + } this.addRenderableWidget(Button.builder(Component.literal("Create Party"), button -> { this.minecraft.setScreen(new PartyCreateScreen(this, EdenModClient.instance())); - }).bounds(metrics.buttonX, metrics.startY + (metrics.buttonPitch * 2), metrics.buttonWidth, metrics.buttonHeight).build()); + }).bounds(metrics.buttonX, metrics.startY + (metrics.buttonPitch * slot++), metrics.buttonWidth, metrics.buttonHeight).build()); this.addRenderableWidget(Button.builder(Component.literal("Manage Party"), button -> { tel.eden.mod.net.PartyInfo myParty = EdenModClient.instance() != null ? EdenModClient.instance().activeParty() : null; @@ -74,23 +80,25 @@ protected void init() { } else if (this.minecraft.player != null) { this.minecraft.player.displayClientMessage(Component.literal("You are not in an active party!").withStyle(net.minecraft.ChatFormatting.RED), false); } - }).bounds(metrics.buttonX, metrics.startY + (metrics.buttonPitch * 3), metrics.buttonWidth, metrics.buttonHeight).build()); + }).bounds(metrics.buttonX, metrics.startY + (metrics.buttonPitch * slot++), metrics.buttonWidth, metrics.buttonHeight).build()); this.addRenderableWidget(Button.builder(Component.literal("Party List"), button -> { this.minecraft.setScreen(new PartyListScreen(this, EdenModClient.instance())); - }).bounds(metrics.buttonX, metrics.startY + (metrics.buttonPitch * 4), metrics.buttonWidth, metrics.buttonHeight).build()); + }).bounds(metrics.buttonX, metrics.startY + (metrics.buttonPitch * slot++), metrics.buttonWidth, metrics.buttonHeight).build()); - this.addRenderableWidget(Button.builder(Component.literal("Payouts"), button -> { - this.minecraft.setScreen(new PayoutScreen(this, EdenModClient.instance())); - }).bounds(metrics.buttonX, metrics.startY + (metrics.buttonPitch * 5), metrics.buttonWidth, metrics.buttonHeight).build()); + if (!traveler) { + this.addRenderableWidget(Button.builder(Component.literal("Payouts"), button -> { + this.minecraft.setScreen(new PayoutScreen(this, EdenModClient.instance())); + }).bounds(metrics.buttonX, metrics.startY + (metrics.buttonPitch * slot++), metrics.buttonWidth, metrics.buttonHeight).build()); + } this.addRenderableWidget(Button.builder(Component.literal("Command Aliases"), button -> { this.minecraft.setScreen(new CommandAliasScreen(this, EdenModClient.instance())); - }).bounds(metrics.buttonX, metrics.startY + (metrics.buttonPitch * 6), metrics.buttonWidth, metrics.buttonHeight).build()); + }).bounds(metrics.buttonX, metrics.startY + (metrics.buttonPitch * slot++), metrics.buttonWidth, metrics.buttonHeight).build()); this.addRenderableWidget(Button.builder(Component.literal("Command Keybinds"), button -> { this.minecraft.setScreen(new CommandKeybindScreen(this, EdenModClient.instance())); - }).bounds(metrics.buttonX, metrics.startY + (metrics.buttonPitch * 7), metrics.buttonWidth, metrics.buttonHeight).build()); + }).bounds(metrics.buttonX, metrics.startY + (metrics.buttonPitch * slot++), metrics.buttonWidth, metrics.buttonHeight).build()); } @Override @@ -193,6 +201,22 @@ private static boolean matchesKonamiPosition(int position, int key) { }; } + private static boolean isTraveler() { + EdenModClient mod = EdenModClient.instance(); + return mod != null && mod.isTraveler(); + } + + private static boolean isMember() { + EdenModClient mod = EdenModClient.instance(); + return mod != null && mod.isFullMember(); + } + + private static int buttonCount() { + int count = isTraveler() ? BUTTON_COUNT - TRAVELER_HIDDEN_BUTTONS : BUTTON_COUNT; + // Event is member-only; a traveler already has it counted in TRAVELER_HIDDEN_BUTTONS. + return !isTraveler() && !isMember() ? count - 1 : count; + } + private int bottomSafeMargin() { return Math.max(MIN_BOTTOM_SAFE_MARGIN, this.height / 6); } @@ -202,7 +226,7 @@ private int topSafeMargin() { } private MenuMetrics menuMetrics() { - int stackHeight = BUTTON_HEIGHT + BUTTON_SPACING * (BUTTON_COUNT - 1); + int stackHeight = BUTTON_HEIGHT + BUTTON_SPACING * (buttonCount() - 1); int topPadding = topSafeMargin(); int bottomPadding = bottomSafeMargin(); int availableWidth = Math.max(1, this.width - (CONTENT_MARGIN * 2)); diff --git a/src/tel/eden/mod/gui/PartyCreateScreen.java b/src/tel/eden/mod/gui/PartyCreateScreen.java index 5ac1ae9..4f6c005 100644 --- a/src/tel/eden/mod/gui/PartyCreateScreen.java +++ b/src/tel/eden/mod/gui/PartyCreateScreen.java @@ -66,8 +66,10 @@ public PartyCreateScreen(Screen parent, EdenModClient mod) { } public PartyCreateScreen(Screen parent, EdenModClient mod, String initialTarget) { - super(Component.literal("Create Guild Party"), parent); + super(Component.literal(mod != null && mod.isTraveler() ? "Create Party" : "Create Guild Party"), parent); this.mod = mod; + // Travelers can only host ally parties. + this.sendToAlly = mod != null && mod.isTraveler(); this.initialTarget = initialTarget; this.filledSlots = 0; } @@ -124,7 +126,9 @@ protected void init() { // Send to Ally toggle btnSendToAlly = Button.builder(Component.literal(sendToAlly ? "§a[✔] Ally" : "§7[ ] Ally"), b -> toggleSendToAlly()).bounds(layout.x(200), layout.y(182), layout.w(135), layout.h(18)).build(); - this.addRenderableWidget(btnSendToAlly); + if (mod == null || !mod.isTraveler()) { + this.addRenderableWidget(btnSendToAlly); + } // Clear Added Members Button (only visible when addedMembers is non-empty) btnClearAdded = Button.builder(Component.literal("§cClear"), b -> onClearAdded()).bounds(layout.x(280), layout.y(204), layout.w(55), layout.h(16)).build(); diff --git a/src/tel/eden/mod/gui/PartyManageScreen.java b/src/tel/eden/mod/gui/PartyManageScreen.java index f0a2120..462fe9f 100644 --- a/src/tel/eden/mod/gui/PartyManageScreen.java +++ b/src/tel/eden/mod/gui/PartyManageScreen.java @@ -145,9 +145,11 @@ protected void init() { this.addRenderableWidget(btnPlayersPlus); // Open to Allies toggle button - btnOpenToAllies = Button.builder(Component.literal(openToAllies ? "§a[✔] Open to Allies" : "§7[ ] Open to Allies"), b -> onToggleAlly()).bounds(rightColX, layout.y(152), layout.w(160), layout.h(18)).build(); - btnOpenToAllies.active = isHost; - this.addRenderableWidget(btnOpenToAllies); + if (mod == null || !mod.isTraveler()) { + btnOpenToAllies = Button.builder(Component.literal(openToAllies ? "§a[✔] Open to Allies" : "§7[ ] Open to Allies"), b -> onToggleAlly()).bounds(rightColX, layout.y(152), layout.w(160), layout.h(18)).build(); + btnOpenToAllies.active = isHost; + this.addRenderableWidget(btnOpenToAllies); + } // Note field noteField = new EditBox(this.font, rightColX, layout.y(186), layout.w(160), layout.h(18), Component.literal("Party Note")); diff --git a/src/tel/eden/mod/gui/TerritoryMenuPanel.java b/src/tel/eden/mod/gui/TerritoryMenuPanel.java index 76f0c96..4a210eb 100644 --- a/src/tel/eden/mod/gui/TerritoryMenuPanel.java +++ b/src/tel/eden/mod/gui/TerritoryMenuPanel.java @@ -618,7 +618,7 @@ private static void renderWynntilsOverlay(Screen screen, GuiGraphics graphics, i private static void drawWynntilsOverlay(Screen screen, GuiGraphics graphics, int mouseX, int mouseY) { BridgeConfig config = EdenModClient.instance().config(); - if (config == null || !config.territoryMenuSuite) { + if (config == null || !config.presetsEnabled()) { return; } @@ -703,7 +703,7 @@ private static void renderButton(GuiGraphics graphics, Font font, int x, int y, public static boolean handleMouseClick(Screen screen, double mouseX, double mouseY, int button, Map fallbackLoadouts) { BridgeConfig config = EdenModClient.instance().config(); - if (config == null || !config.territoryMenuSuite || (button != 0 && button != 1)) { + if (config == null || !config.presetsEnabled() || (button != 0 && button != 1)) { return true; } diff --git a/src/tel/eden/mod/mixin/AbstractContainerScreenMixin.java b/src/tel/eden/mod/mixin/AbstractContainerScreenMixin.java index 92b5725..bd4c06f 100644 --- a/src/tel/eden/mod/mixin/AbstractContainerScreenMixin.java +++ b/src/tel/eden/mod/mixin/AbstractContainerScreenMixin.java @@ -303,7 +303,7 @@ public abstract class AbstractContainerScreenMixin { edenmod$skipBtnVisible = false; BridgeConfig config = EdenModClient.instance().config(); - if (config != null && config.territoryMenuSuite && mc != null && mc.font != null) { + if (config != null && config.presetsEnabled() && mc != null && mc.font != null) { String title = edenmod$title(); AbstractContainerMenu menu = getMenu(); if (!edenmod$checkAllowedEcoContainer(title, menu)) { @@ -574,7 +574,7 @@ else if (edenmod$isTerritoryOverview(title, menu)) { @Inject(method = "mouseClicked", at = @At("HEAD"), cancellable = true) private void edenmod$onMouseClicked(MouseButtonEvent event, boolean bl, CallbackInfoReturnable cir) { BridgeConfig config = EdenModClient.instance().config(); - if (config != null && config.territoryMenuSuite) { + if (config != null && config.presetsEnabled()) { String title = edenmod$title(); AbstractContainerMenu menu = getMenu(); if (edenmod$checkAllowedEcoContainer(title, menu)) { diff --git a/src/tel/eden/mod/mixin/ChatScreenMixin.java b/src/tel/eden/mod/mixin/ChatScreenMixin.java index 8902298..98dd476 100644 --- a/src/tel/eden/mod/mixin/ChatScreenMixin.java +++ b/src/tel/eden/mod/mixin/ChatScreenMixin.java @@ -166,9 +166,9 @@ public abstract class ChatScreenMixin { if (input != null) { String val = input.getValue(); if (val.isEmpty()) { - input.setValue("/g "); + input.setValue(ChatReplyManager.activeReplyPrefix()); } else if (!val.startsWith("/")) { - input.setValue("/g " + val); + input.setValue(ChatReplyManager.activeReplyPrefix() + val); } } }); @@ -184,7 +184,12 @@ public abstract class ChatScreenMixin { private void edenmod$captureReplyOnSend(String message, boolean addToHistory, CallbackInfo ci) { if (ChatReplyManager.hasActiveReply()) { String trimmed = message != null ? message.trim() : ""; - if (trimmed.startsWith("/g ") && trimmed.length() > 3 && !trimmed.substring(3).isBlank()) { + if (ChatReplyManager.isActiveReplyTraveler()) { + // The command takes the reply (takeTravelerReply); anything else drops it. + if (!trimmed.startsWith("/e ") && !trimmed.startsWith("/eden tc ")) { + ChatReplyManager.clearActiveReply(); + } + } else if (trimmed.startsWith("/g ") && trimmed.length() > 3 && !trimmed.substring(3).isBlank()) { ChatReplyManager.markPendingReply(trimmed.substring(3)); } else { ChatReplyManager.clearActiveReply(); diff --git a/src/tel/eden/mod/net/BridgeWebSocketClient.java b/src/tel/eden/mod/net/BridgeWebSocketClient.java index 69e2976..2a623bc 100644 --- a/src/tel/eden/mod/net/BridgeWebSocketClient.java +++ b/src/tel/eden/mod/net/BridgeWebSocketClient.java @@ -16,6 +16,7 @@ import java.util.regex.Pattern; import tel.eden.mod.EdenLogger; import tel.eden.mod.chat.PlayerNameResolver; +import tel.eden.mod.config.BridgeConfig; import tel.eden.mod.guild.GuildLogEvent; import tel.eden.mod.guild.GuildManageSnapshot; @@ -44,7 +45,7 @@ public final class BridgeWebSocketClient { * it (the last one, "guildLogSync", was retired once the server-side code * that checked for it was removed). */ - private static final java.util.Set SUPPORTED_FEATURES = java.util.Set.of("mail", "longEvent"); + private static final java.util.Set SUPPORTED_FEATURES = java.util.Set.of("traveler"); /** Callbacks for inbound bridge events (delivered off the game thread). */ public interface MessageSink { @@ -216,7 +217,11 @@ default void onLongEventRewards(int pendingLe, String error) { * {@code guildRank} (e.g. "Chief") and {@code discordRank} (e.g. "Senate") are * empty strings when not applicable. */ - void onAuthStatus(boolean linked, boolean member, String guildRank, String discordRank); + void onAuthStatus(boolean linked, boolean member, boolean traveler, String guildRank, String discordRank); + + /** A traveler-chat line from the game or Discord side. */ + default void onTravelerChat(String author, String content, String source, String color, String replyTo, String replyExcerpt, String messageId) { + } } /** @@ -245,6 +250,8 @@ public interface SessionAuthenticator { private volatile WebSocket socket; private volatile boolean authenticated = false; + // Set from authOk and reset with `authenticated`; gates every outbound frame (OutboundPolicy). + private volatile OutboundPolicy.Standing standing = OutboundPolicy.Standing.UNKNOWN; // Tail of the serialized outbound send queue — see enqueueSend(). private CompletableFuture sendChain = CompletableFuture.completedFuture(null); private volatile boolean running; @@ -296,6 +303,7 @@ public synchronized void close() { WebSocket current = socket; socket = null; authenticated = false; + standing = OutboundPolicy.Standing.UNKNOWN; if (current != null) { current.sendClose(WebSocket.NORMAL_CLOSURE, "client closing"); } @@ -317,8 +325,13 @@ public boolean isConnected() { * Chaining instead of blocking keeps every caller non-blocking; {@code handle} * swallows a prior failure so one bad send can't wedge every send after it. */ - private synchronized void enqueueSend(WebSocket ws, String text) { + private synchronized boolean enqueueSend(WebSocket ws, JsonObject obj) { + if (!OutboundPolicy.allowed(standing, get(obj, "type"))) { + return false; + } + String text = obj.toString(); sendChain = sendChain.handle((v, ex) -> null).thenCompose(ignored -> ws.sendText(text, true)); + return true; } /** Send one captured guild-chat line to the backend. */ @@ -343,7 +356,7 @@ public void sendGuildChat(String username, String nickname, String message, int if (replyToMessageId != null && !replyToMessageId.isEmpty()) { obj.addProperty("replyToMessageId", replyToMessageId); } - enqueueSend(current, obj.toString()); + enqueueSend(current, obj); } /** @@ -372,8 +385,7 @@ public boolean sendGuildAlliances(java.util.List guilds, java.util.List< } obj.add("guilds", names); obj.add("tags", tags); - enqueueSend(current, obj.toString()); - return true; + return enqueueSend(current, obj); } /** Report one typed root Guild Manage snapshot — season/weekly/territory status, surfaced on "Eden Standings". */ @@ -409,7 +421,7 @@ public void sendGuildManageStatus(GuildManageSnapshot snapshot) { if (snapshot.srPerHour() != null) { obj.addProperty("srPerHour", snapshot.srPerHour()); } - enqueueSend(current, obj.toString()); + enqueueSend(current, obj); } /** @@ -446,7 +458,7 @@ public void sendRaidCompletion(java.util.List party, String raidName, in if (seasonalRating != null) { obj.addProperty("seasonalRating", seasonalRating); } - enqueueSend(current, obj.toString()); + enqueueSend(current, obj); } /** Send one parsed guild rank change to the backend. */ @@ -461,7 +473,7 @@ public void sendRankChange(String target, String oldRank, String newRank, String obj.addProperty("oldRank", oldRank); obj.addProperty("newRank", newRank); obj.addProperty("setter", setter); - enqueueSend(current, obj.toString()); + enqueueSend(current, obj); } /** Tell the backend this player just started a bridge session (for login notices). */ @@ -505,8 +517,7 @@ public boolean sendRewardOptOutRequest(String rewardKind, boolean blocked) { return false; } JsonObject obj = rewardOptOutPayload(rewardKind, blocked); - enqueueSend(current, obj.toString()); - return true; + return enqueueSend(current, obj); } /** Ask the backend for the member list + aspect stock for the giveaway screen (Chiefs only). */ @@ -535,8 +546,7 @@ public boolean sendRewardDeductRequest(String rewardKind, String target, int amo if (manual) { obj.addProperty("source", "manual"); } - enqueueSend(current, obj.toString()); - return true; + return enqueueSend(current, obj); } /** @@ -567,8 +577,7 @@ private boolean sendTypeIfConnected(String type) { } JsonObject obj = new JsonObject(); obj.addProperty("type", type); - enqueueSend(current, obj.toString()); - return true; + return enqueueSend(current, obj); } /** Open a new party in-game for the given label (raid name, Annihilation, or Festival). */ @@ -600,7 +609,7 @@ public void sendPartyOpen(String raid, int maxSize, String note, int filled, boo } obj.add("members", arr); } - enqueueSend(current, obj.toString()); + enqueueSend(current, obj); } public void sendPartyOpen(String raid, int maxSize, String note, int filled, boolean ally, String world) { @@ -620,7 +629,7 @@ public void sendPartyJoin(int id) { JsonObject obj = new JsonObject(); obj.addProperty("type", "partyJoin"); obj.addProperty("id", id); - enqueueSend(current, obj.toString()); + enqueueSend(current, obj); } public void sendPartyAllyToggle(boolean ally) { @@ -638,7 +647,7 @@ public void sendPartyLeave(Integer id) { if (id != null) { obj.addProperty("id", id); } - enqueueSend(current, obj.toString()); + enqueueSend(current, obj); } /** Ask the backend for the list of open raid parties. */ @@ -664,7 +673,45 @@ public void sendPartyManage(String action, String text, int value, String ign) { if (ign != null && !ign.isEmpty()) { obj.addProperty("ign", ign); } - enqueueSend(current, obj.toString()); + enqueueSend(current, obj); + } + + /** Send a traveler-chat line (members and travelers). */ + public boolean sendTravelerChat(String content, String replyToMessageId) { + WebSocket current = socket; + return current != null && enqueueSend(current, travelerChatPayload(content, replyToMessageId)); + } + + /** Tell the backend whether to deliver traveler chat and which game lines to show ("guild", "all" or "off"). */ + public boolean sendTravelerPrefs(boolean chat, String games) { + WebSocket current = socket; + return current != null && enqueueSend(current, travelerPrefsPayload(chat, games)); + } + + /** The {@code games} value for travelerPrefs: members choose guild/all/off, travelers all/off. */ + public static String gamesPref(boolean traveler, BridgeConfig.MemberGames memberGames, boolean travelerGames) { + if (traveler) { + return travelerGames ? "all" : "off"; + } + return memberGames.name().toLowerCase(java.util.Locale.ROOT); + } + + static JsonObject travelerChatPayload(String content, String replyToMessageId) { + JsonObject obj = new JsonObject(); + obj.addProperty("type", "travelerChat"); + obj.addProperty("content", content); + if (replyToMessageId != null && !replyToMessageId.isEmpty()) { + obj.addProperty("replyToMessageId", replyToMessageId); + } + return obj; + } + + static JsonObject travelerPrefsPayload(boolean chat, String games) { + JsonObject obj = new JsonObject(); + obj.addProperty("type", "travelerPrefs"); + obj.addProperty("chat", chat); + obj.addProperty("games", games); + return obj; } /** Ask the backend to flip a coin and announce who flipped it + the result. */ @@ -743,7 +790,7 @@ private void sendTcc(JsonObject payload) { if (current == null || payload == null) { return; } - enqueueSend(current, payload.toString()); + enqueueSend(current, payload); } /** The raid party as a JSON array with blank names dropped, or null when no name is left. */ @@ -779,8 +826,7 @@ public boolean sendWarAttended(String territory, java.util.List members) array.add(member); } obj.add("members", array); - enqueueSend(current, obj.toString()); - return true; + return enqueueSend(current, obj); } /** @@ -795,8 +841,7 @@ public boolean sendTerritoryDefended(String territory, String attacker) { obj.addProperty("type", "territoryDefended"); obj.addProperty("territory", territory); obj.addProperty("attacker", attacker); - enqueueSend(current, obj.toString()); - return true; + return enqueueSend(current, obj); } /** @@ -815,8 +860,7 @@ public boolean sendWarDefense(String territory, String defense) { obj.addProperty("type", "warDefense"); obj.addProperty("territory", territory); obj.addProperty("defense", defense); - enqueueSend(current, obj.toString()); - return true; + return enqueueSend(current, obj); } /** @@ -832,8 +876,7 @@ public boolean sendRadianceGroup(String groupKey) { JsonObject obj = new JsonObject(); obj.addProperty("type", "radianceGroup"); obj.addProperty("groupKey", groupKey != null ? groupKey.trim() : ""); - enqueueSend(current, obj.toString()); - return true; + return enqueueSend(current, obj); } /** @@ -851,8 +894,7 @@ public boolean sendRadianceCast(String groupKey, int tier, long remainingMs) { obj.addProperty("groupKey", groupKey.trim()); obj.addProperty("tier", tier); obj.addProperty("remainingMs", remainingMs); - enqueueSend(current, obj.toString()); - return true; + return enqueueSend(current, obj); } /** @@ -865,8 +907,7 @@ public boolean sendWitnessKill(java.util.List partyMembers) { if (current == null) { return false; } - enqueueSend(current, witnessKillPayload(partyMembers).toString()); - return true; + return enqueueSend(current, witnessKillPayload(partyMembers)); } /** @@ -883,8 +924,7 @@ public boolean sendMail(String to, String content) { obj.addProperty("type", "mailSend"); obj.addProperty("to", to); obj.addProperty("content", content); - enqueueSend(current, obj.toString()); - return true; + return enqueueSend(current, obj); } /** Tell the bot these mails were shown, so it stops re-sending them. */ @@ -893,7 +933,7 @@ public void sendMailAck(java.util.List ids) { if (current == null || ids.isEmpty()) { return; } - enqueueSend(current, mailAckPayload(ids).toString()); + enqueueSend(current, mailAckPayload(ids)); } static JsonObject mailAckPayload(java.util.List ids) { @@ -938,7 +978,7 @@ public void sendWarGoing(String territory, Integer remaining) { if (remaining != null) { obj.addProperty("remaining", remaining); } - enqueueSend(current, obj.toString()); + enqueueSend(current, obj); } /** @@ -956,7 +996,7 @@ public void sendWarGoingInside(String territory, boolean inside) { obj.addProperty("territory", territory.trim()); } obj.addProperty("inside", inside); - enqueueSend(current, obj.toString()); + enqueueSend(current, obj); } /** @@ -975,7 +1015,7 @@ public void sendWarQueued(String territory, boolean inside, Integer remaining) { if (remaining != null) { obj.addProperty("remaining", remaining); } - enqueueSend(current, obj.toString()); + enqueueSend(current, obj); } /** @@ -995,7 +1035,7 @@ public void sendWarTimerEnded(String territory, boolean captured) { if (captured) { obj.addProperty("captured", true); } - enqueueSend(current, obj.toString()); + enqueueSend(current, obj); } /** Ask for the guild's per-member war counts over the last {@code days} days. */ @@ -1007,7 +1047,7 @@ public void sendWarCountsRequest(int days) { JsonObject obj = new JsonObject(); obj.addProperty("type", "warCountsRequest"); obj.addProperty("days", days); - enqueueSend(current, obj.toString()); + enqueueSend(current, obj); } /** Ask for the guild's current allies ordered by inactivity (same as Discord). */ @@ -1018,7 +1058,7 @@ public void sendAllyActivityRequest() { } JsonObject obj = new JsonObject(); obj.addProperty("type", "allyActivityRequest"); - enqueueSend(current, obj.toString()); + enqueueSend(current, obj); } /** Ask the backend for this player's current long-event mission state. */ @@ -1043,7 +1083,7 @@ public void sendLongEventReroll(String slot, boolean buy) { if (buy) { obj.addProperty("buy", true); } - enqueueSend(current, obj.toString()); + enqueueSend(current, obj); } /** Ask the backend for this player's pending event LE. */ @@ -1061,7 +1101,7 @@ public void sendLongEventMysteryGuess(String guess, boolean useTrivia) { obj.addProperty("type", "longEventMysteryGuess"); obj.addProperty("guess", guess.trim()); obj.addProperty("useTrivia", useTrivia); - enqueueSend(current, obj.toString()); + enqueueSend(current, obj); } /** @@ -1076,7 +1116,7 @@ public void sendPresence(boolean active) { JsonObject obj = new JsonObject(); obj.addProperty("type", "presence"); obj.addProperty("active", active); - enqueueSend(current, obj.toString()); + enqueueSend(current, obj); } private void sendType(String type) { @@ -1086,7 +1126,7 @@ private void sendType(String type) { } JsonObject obj = new JsonObject(); obj.addProperty("type", type); - enqueueSend(current, obj.toString()); + enqueueSend(current, obj); } /** Send one parsed guild-bank deposit/withdrawal to the backend. */ @@ -1108,7 +1148,7 @@ public void sendBankEvent(String action, String player, Integer quantity, String } obj.addProperty("accessTier", accessTier); obj.addProperty("seq", seq); - enqueueSend(current, obj.toString()); + enqueueSend(current, obj); } /** Report an in-game Annihilation warning (seconds until it begins). */ @@ -1120,7 +1160,7 @@ public void sendAnnihilation(int secondsUntil) { JsonObject obj = new JsonObject(); obj.addProperty("type", "annihilation"); obj.addProperty("secondsUntil", secondsUntil); - enqueueSend(current, obj.toString()); + enqueueSend(current, obj); } /** Mirror a guild flavour announcement (weekly objective/boost) into bridge chat. */ @@ -1132,7 +1172,7 @@ public void sendGuildAnnounce(String message) { JsonObject obj = new JsonObject(); obj.addProperty("type", "guildAnnounce"); obj.addProperty("message", message); - enqueueSend(current, obj.toString()); + enqueueSend(current, obj); } /** Send one parsed guild-management/alliance event to the backend. */ @@ -1146,7 +1186,7 @@ public void sendGuildEvent(String kind, String actor, String subject) { obj.addProperty("kind", kind); obj.addProperty("actor", actor); obj.addProperty("subject", subject); - enqueueSend(current, obj.toString()); + enqueueSend(current, obj); } /** Send one parsed guild reward handout to the backend. */ @@ -1161,7 +1201,7 @@ public void sendGuildReward(String giver, String reward, String receiver, int se obj.addProperty("reward", reward); obj.addProperty("receiver", receiver); obj.addProperty("seq", seq); - enqueueSend(current, obj.toString()); + enqueueSend(current, obj); } /** Send a rendered shared-item card (base64 PNG) to be relayed as the sender. */ @@ -1178,7 +1218,7 @@ public void sendItemCard(String username, String nickname, String imageBase64, S } obj.addProperty("image", imageBase64); obj.addProperty("signature", signature); - enqueueSend(current, obj.toString()); + enqueueSend(current, obj); } /** @@ -1305,7 +1345,7 @@ private void sendGuildLogSnapshot(String source, boolean fullScan, java.util.Lis obj.addProperty("fullScan", true); } obj.add("events", encoded); - enqueueSend(current, obj.toString()); + enqueueSend(current, obj); } /** Report that the running jar failed its boot-time Sigstore attestation check. */ @@ -1317,7 +1357,7 @@ public void sendAttestationFailure(String sha) { JsonObject obj = new JsonObject(); obj.addProperty("type", "attestationFailure"); obj.addProperty("sha", sha); - enqueueSend(current, obj.toString()); + enqueueSend(current, obj); } /** Relay the guild's current reward storage (aspects/tomes/emeralds) for the live counter. */ @@ -1331,7 +1371,7 @@ public void sendGuildStorage(int aspects, int tomes, long emeralds) { obj.addProperty("aspects", aspects); obj.addProperty("tomes", tomes); obj.addProperty("emeralds", emeralds); - enqueueSend(current, obj.toString()); + enqueueSend(current, obj); } private void connect() { @@ -1386,6 +1426,7 @@ private synchronized void scheduleReconnect(WebSocket disconnected) { } socket = null; authenticated = false; + standing = OutboundPolicy.Standing.UNKNOWN; if (!running || reconnectScheduled) { return; } @@ -1413,6 +1454,7 @@ private void rejectConnection(String code) { current = socket; socket = null; authenticated = false; + standing = OutboundPolicy.Standing.UNKNOWN; scheduler.shutdownNow(); } if (current != null) { @@ -1434,6 +1476,7 @@ public void onOpen(WebSocket webSocket) { pendingAuthUsername = null; socket = webSocket; authenticated = false; + standing = OutboundPolicy.Standing.UNKNOWN; } } if (!accepted) { @@ -1472,8 +1515,12 @@ public void onError(WebSocket webSocket, Throwable error) { private void handlePayload(String payload) { try { JsonObject obj = JsonParser.parseString(payload).getAsJsonObject(); + if (!OutboundPolicy.inboundAllowed(standing, get(obj, "type"))) { + return; + } switch (get(obj, "type")) { case "discordMessage" -> sink.onDiscordMessage(get(obj, "author"), get(obj, "content"), get(obj, "replyTo"), get(obj, "replyExcerpt"), get(obj, "color"), get(obj, "messageId")); + case "travelerChat" -> sink.onTravelerChat(cap(get(obj, "author"), 64), cap(get(obj, "content"), 512), get(obj, "source"), get(obj, "color"), cap(get(obj, "replyTo"), 64), cap(get(obj, "replyExcerpt"), 256), get(obj, "messageId").matches("[0-9]{1,20}") ? get(obj, "messageId") : ""); case "loginNotice" -> sink.onLoginNotice(get(obj, "username"), get(obj, "color")); case "logoutNotice" -> sink.onLogoutNotice(get(obj, "username"), get(obj, "color")); case "onlineList" -> sink.onOnlineList(getStringArray(obj, "users"), get(obj, "color")); @@ -1522,13 +1569,15 @@ private void handlePayload(String payload) { // on full access or prompts the player otherwise. boolean linked = getBool(obj, "linked"); boolean member = getBool(obj, "member"); + boolean traveler = getBool(obj, "traveler"); + standing = OutboundPolicy.Standing.of(linked, member, traveler); String guildRank = cap(get(obj, "guildRank"), 64); String discordRank = cap(get(obj, "discordRank"), 64); LOGGER.info("Bridge session verified as {} (linked={} member={})", pendingAuthUsername != null ? pendingAuthUsername : "?", linked, member); sessionVerifyRetries = 0; backoffSeconds = 1; try { - sink.onAuthStatus(linked, member, guildRank, discordRank); + sink.onAuthStatus(linked, member, traveler, guildRank, discordRank); } catch (RuntimeException e) { LOGGER.warn("onAuthStatus callback failed", e); } @@ -1599,7 +1648,7 @@ private void handleAuthChallenge(String serverNonce) { supported.add(feature); } obj.add("supported", supported); - enqueueSend(current, obj.toString()); + enqueueSend(current, obj); } catch (Exception e) { LOGGER.warn("Mojang session join failed: {}", e.toString()); } diff --git a/src/tel/eden/mod/net/OutboundPolicy.java b/src/tel/eden/mod/net/OutboundPolicy.java new file mode 100644 index 0000000..8935800 --- /dev/null +++ b/src/tel/eden/mod/net/OutboundPolicy.java @@ -0,0 +1,45 @@ +package tel.eden.mod.net; + +import java.util.Set; + +/** + * Which outbound message types the mod may send for the player's standing. The server + * enforces this too; this stops a traveler's own guild data from ever leaving the client. + */ +public final class OutboundPolicy { + public enum Standing { + /** Before {@code authOk}. */ + UNKNOWN, NOT_LINKED, NOT_MEMBER, TRAVELER, FULL; + + public static Standing of(boolean linked, boolean member, boolean traveler) { + if (!linked) { + return NOT_LINKED; + } + if (member) { + return FULL; + } + return traveler ? TRAVELER : NOT_MEMBER; + } + } + + static final Set TRAVELER_TYPES = Set.of("authResponse", "presence", "mailSend", "mailAck", "tccMapPos", "tccGolemDefeated", "tccExitReached", "witnessKill", "partyOpen", "partyJoin", "partyLeave", "partyList", "partyManage", "travelerChat", "travelerPrefs", "coinflip", "diceroll", "attestationFailure"); + + private OutboundPolicy() { + } + + private static final Set GUILD_ONLY_INBOUND = Set.of("warBoard", "discordMessage", "loginNotice", "logoutNotice", "onlineList"); + + /** Defence in depth: the server never sends these to a traveler, so drop them if one arrives. */ + public static boolean inboundAllowed(Standing standing, String type) { + return standing != Standing.TRAVELER || !GUILD_ONLY_INBOUND.contains(type); + } + + public static boolean allowed(Standing standing, String type) { + return switch (standing) { + case FULL -> true; + case TRAVELER -> TRAVELER_TYPES.contains(type); + case NOT_LINKED, NOT_MEMBER -> "authResponse".equals(type) || "attestationFailure".equals(type); + case UNKNOWN -> "authResponse".equals(type); + }; + } +} diff --git a/test/tel/eden/mod/chat/ChatReplyManagerTest.java b/test/tel/eden/mod/chat/ChatReplyManagerTest.java index f36e2a6..a50ab1d 100644 --- a/test/tel/eden/mod/chat/ChatReplyManagerTest.java +++ b/test/tel/eden/mod/chat/ChatReplyManagerTest.java @@ -17,6 +17,19 @@ void setUp() { ChatReplyManager.reset(); } + @Test + void takeTravelerReplyOnlyTakesTravelerReplies() { + ChatReplyManager.setActiveReply("111"); + assertNull(ChatReplyManager.takeTravelerReply()); + assertTrue(ChatReplyManager.hasActiveReply()); + assertEquals("/g ", ChatReplyManager.activeReplyPrefix()); + + ChatReplyManager.setActiveTravelerReply("222"); + assertEquals("/e ", ChatReplyManager.activeReplyPrefix()); + assertEquals("222", ChatReplyManager.takeTravelerReply()); + assertFalse(ChatReplyManager.hasActiveReply()); + } + @Test void recordsAndRetrievesDiscordMessages() { ChatReplyManager.recordDiscordMessage("123456789", "Alice", "Hello there!"); diff --git a/test/tel/eden/mod/config/BridgeConfigTest.java b/test/tel/eden/mod/config/BridgeConfigTest.java index 58a56d3..31e7917 100644 --- a/test/tel/eden/mod/config/BridgeConfigTest.java +++ b/test/tel/eden/mod/config/BridgeConfigTest.java @@ -8,6 +8,27 @@ import org.junit.jupiter.api.Test; class BridgeConfigTest { + @Test + void presetsNeedSuiteAndAKnownOrUnknownMember() { + BridgeConfig config = new Gson().fromJson("{\"enabled\":true}", BridgeConfig.class); + // Older configs have no wasMember: presets stay on until the first authOk says otherwise. + assertTrue(config.presetsEnabled()); + config.wasMember = false; + assertFalse(config.presetsEnabled()); + config.wasMember = true; + assertTrue(config.presetsEnabled()); + config.territoryMenuSuite = false; + assertFalse(config.presetsEnabled()); + } + + @Test + void travelerChatDefaultsOnAndGamesDefaultPerStanding() { + BridgeConfig config = new BridgeConfig(); + assertTrue(config.travelerChat); + assertEquals(BridgeConfig.MemberGames.GUILD, config.memberGames); + assertTrue(config.travelerGames); + } + @Test void defaultsDiscordBridgeMessagesToTrue() { BridgeConfig config = new BridgeConfig(); diff --git a/test/tel/eden/mod/net/OutboundPolicyTest.java b/test/tel/eden/mod/net/OutboundPolicyTest.java new file mode 100644 index 0000000..07a1c18 --- /dev/null +++ b/test/tel/eden/mod/net/OutboundPolicyTest.java @@ -0,0 +1,117 @@ +package tel.eden.mod.net; + +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 com.google.gson.JsonObject; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Set; +import java.util.TreeSet; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import org.junit.jupiter.api.Test; +import tel.eden.mod.config.BridgeConfig; +import tel.eden.mod.net.OutboundPolicy.Standing; + +class OutboundPolicyTest { + private static final Set TRAVELER = Set.of("authResponse", "presence", "mailSend", "mailAck", "tccMapPos", "tccGolemDefeated", "tccExitReached", "witnessKill", "partyOpen", "partyJoin", "partyLeave", "partyList", "partyManage", "travelerChat", "travelerPrefs", "coinflip", "diceroll", "attestationFailure"); + + // Every type BWSC sends that a traveler must NOT be able to send. A new send* type that is + // in neither set fails classifiesEveryTypeBwscCanSend until someone decides. + private static final Set GUILD_ONLY = Set.of("allyActivityRequest", "annihilation", "aspectGiveawayRequest", "aspectsPendingRequest", "bankEvent", "emeraldsPendingRequest", "giftLockAcquire", "giftLockRelease", "guildAlliances", "guildAnnounce", "guildEvent", "guildLogSnapshot", "guildManageStatus", "guildReward", "guildStorage", "itemCard", "login", "longEventMysteryGuess", "longEventReroll", "longEventRewardsRequest", "longEventStateRequest", "onlineRequest", "radianceCast", "radianceGroup", "raidCompletion", "rankChange", "rewardDeductRequest", "rewardOptOutRequest", "rewardStatusRequest", "territoryDefended", "warAttended", "warCountsRequest", "warDefense", "warGoing", "warGoingInside", "warQueued", "warTimerEnded", "wynnMessage"); + + @Test + void travelerGetsExactlyTheAllowlist() { + for (String type : TRAVELER) { + assertTrue(OutboundPolicy.allowed(Standing.TRAVELER, type), type); + } + for (String type : GUILD_ONLY) { + assertFalse(OutboundPolicy.allowed(Standing.TRAVELER, type), type); + } + assertEquals(TRAVELER, OutboundPolicy.TRAVELER_TYPES); + } + + @Test + void fullMemberMaySendEverything() { + for (String type : Set.copyOf(union())) { + assertTrue(OutboundPolicy.allowed(Standing.FULL, type), type); + } + } + + @Test + void unverifiedAndIneligibleStandingsOnlyMayAuthenticate() { + for (String type : union()) { + assertEquals("authResponse".equals(type), OutboundPolicy.allowed(Standing.UNKNOWN, type), "UNKNOWN " + type); + // Once verified, a player without access may also report a failed jar check. + boolean observer = "authResponse".equals(type) || "attestationFailure".equals(type); + assertEquals(observer, OutboundPolicy.allowed(Standing.NOT_LINKED, type), "NOT_LINKED " + type); + assertEquals(observer, OutboundPolicy.allowed(Standing.NOT_MEMBER, type), "NOT_MEMBER " + type); + } + } + + @Test + void standingFromAuthOk() { + assertEquals(Standing.FULL, Standing.of(true, true, false)); + assertEquals(Standing.FULL, Standing.of(true, true, true)); + assertEquals(Standing.TRAVELER, Standing.of(true, false, true)); + assertEquals(Standing.NOT_MEMBER, Standing.of(true, false, false)); + assertEquals(Standing.NOT_LINKED, Standing.of(false, false, false)); + assertEquals(Standing.NOT_LINKED, Standing.of(false, false, true)); + } + + @Test + void travelerIgnoresGuildOnlyInbound() { + for (String type : new String[]{"warBoard", "discordMessage", "loginNotice", "logoutNotice", "onlineList"}) { + assertFalse(OutboundPolicy.inboundAllowed(Standing.TRAVELER, type), type); + assertTrue(OutboundPolicy.inboundAllowed(Standing.FULL, type), type); + } + assertTrue(OutboundPolicy.inboundAllowed(Standing.TRAVELER, "pillMessage")); + assertTrue(OutboundPolicy.inboundAllowed(Standing.TRAVELER, "travelerChat")); + } + + @Test + void classifiesEveryTypeBwscCanSend() throws IOException { + String source = Files.readString(Path.of(System.getProperty("edenmod.srcDir")).resolve("tel/eden/mod/net/BridgeWebSocketClient.java")); + Matcher matcher = Pattern.compile("addProperty\\(\"type\", \"(\\w+)\"\\)|sendType(?:IfConnected)?\\(\"(\\w+)\"\\)").matcher(source); + Set found = new TreeSet<>(); + while (matcher.find()) { + found.add(matcher.group(1) != null ? matcher.group(1) : matcher.group(2)); + } + assertFalse(found.isEmpty()); + for (String type : found) { + assertTrue(TRAVELER.contains(type) || GUILD_ONLY.contains(type), "unclassified outbound type: " + type); + } + } + + @Test + void travelerPayloads() { + JsonObject chat = BridgeWebSocketClient.travelerChatPayload("hello", ""); + assertEquals("travelerChat", chat.get("type").getAsString()); + assertEquals("hello", chat.get("content").getAsString()); + assertFalse(chat.has("replyToMessageId")); + assertEquals("123", BridgeWebSocketClient.travelerChatPayload("hello", "123").get("replyToMessageId").getAsString()); + + JsonObject prefs = BridgeWebSocketClient.travelerPrefsPayload(false, "guild"); + assertEquals("travelerPrefs", prefs.get("type").getAsString()); + assertFalse(prefs.get("chat").getAsBoolean()); + assertEquals("guild", prefs.get("games").getAsString()); + } + + @Test + void gamesPrefPerStanding() { + assertEquals("guild", BridgeWebSocketClient.gamesPref(false, BridgeConfig.MemberGames.GUILD, true)); + assertEquals("all", BridgeWebSocketClient.gamesPref(false, BridgeConfig.MemberGames.ALL, false)); + assertEquals("off", BridgeWebSocketClient.gamesPref(false, BridgeConfig.MemberGames.OFF, true)); + assertEquals("all", BridgeWebSocketClient.gamesPref(true, BridgeConfig.MemberGames.GUILD, true)); + assertEquals("off", BridgeWebSocketClient.gamesPref(true, BridgeConfig.MemberGames.ALL, false)); + } + + private static Set union() { + Set all = new TreeSet<>(TRAVELER); + all.addAll(GUILD_ONLY); + return all; + } +}