From 55e75e0dcb8697c77ef7d9de335902b7e4519672 Mon Sep 17 00:00:00 2001 From: BlankenshipG Date: Sun, 11 Oct 2026 11:22:44 -0400 Subject: [PATCH] feat(chat): Discord relay configured from the chat window Chat > gear > Discord switches the relay and opens a Discord panel: routes (webhook or bot + channel), speech channels and chat tabs per route, keywords, batch window and message spacing (relay default or per route), who relays, message format, limits and a send log. /rc discord on|off| status|window|test|resume. Secrets are DPAPI-protected; settings are shared in %AppData%\RynthCore\rynthchat_discord.json. Tests: tools/ChatDiscordTests (218 checks). --- Changelog/2026-10-11-chat-discord-relay.md | 84 +++ .../Compatibility/RynthCoreChatCommands.cs | 33 ++ src/RynthCore.Engine/EngineLifecycle.cs | 2 + src/RynthCore.Engine/EntryPoint.cs | 4 + .../ImGui/Panels/ChatDiscordFace.cs | 421 ++++++++++++++ src/RynthCore.Engine/ImGui/Panels/ChatFace.cs | 21 + src/RynthCore.Engine/UI/Data/ChatData.cs | 19 +- .../UI/Data/Discord/ChatDiscord.cs | 537 ++++++++++++++++++ .../UI/Data/Discord/ChatDiscordLogic.cs | 91 +++ .../UI/Data/Discord/ChatDiscordSettings.cs | 373 ++++++++++++ .../UI/Data/Discord/ChatSpeech.cs | 213 +++++++ .../UI/Data/Discord/DiscordClient.cs | 227 ++++++++ .../UI/Data/Discord/DiscordFormat.cs | 219 +++++++ .../UI/Data/Discord/DiscordSecrets.cs | 116 ++++ .../ChatDiscordTests/ChatDiscordTests.csproj | 31 + tools/ChatDiscordTests/Program.cs | 435 ++++++++++++++ 16 files changed, 2824 insertions(+), 2 deletions(-) create mode 100644 Changelog/2026-10-11-chat-discord-relay.md create mode 100644 src/RynthCore.Engine/ImGui/Panels/ChatDiscordFace.cs create mode 100644 src/RynthCore.Engine/UI/Data/Discord/ChatDiscord.cs create mode 100644 src/RynthCore.Engine/UI/Data/Discord/ChatDiscordLogic.cs create mode 100644 src/RynthCore.Engine/UI/Data/Discord/ChatDiscordSettings.cs create mode 100644 src/RynthCore.Engine/UI/Data/Discord/ChatSpeech.cs create mode 100644 src/RynthCore.Engine/UI/Data/Discord/DiscordClient.cs create mode 100644 src/RynthCore.Engine/UI/Data/Discord/DiscordFormat.cs create mode 100644 src/RynthCore.Engine/UI/Data/Discord/DiscordSecrets.cs create mode 100644 tools/ChatDiscordTests/ChatDiscordTests.csproj create mode 100644 tools/ChatDiscordTests/Program.cs diff --git a/Changelog/2026-10-11-chat-discord-relay.md b/Changelog/2026-10-11-chat-discord-relay.md new file mode 100644 index 0000000..0e02e4f --- /dev/null +++ b/Changelog/2026-10-11-chat-discord-relay.md @@ -0,0 +1,84 @@ +# Chat: Discord relay in RynthChat's settings + +**Date:** 2026-10-11 +**Area:** Engine (`RynthCore.Engine`), RynthChat face. Needs the RynthChat plugin; no RynthSuite +change is required. + +## What's new + +The chat window can copy chat to Discord, configured from the chat window itself: + +- **Chat > gear menu > Discord:** a "Copy chat to Discord" switch, the relay's status, and + **Discord settings…**, which opens the new **Discord** panel. +- **Discord panel, Routes tab:** a route is one Discord channel and the chat it receives. You can + have as many routes as you like, for example tells to one channel and allegiance to another. + - **Connection:** a webhook URL, or a bot token plus channel ID, with Save, Clear and + **Send test**. The webhook display name defaults to the character's name. Paused routes have a + **Resume** button. + - **Speech channels:** Local, Tell, Fellowship, Allegiance, Patron, Vassals, Covassals, Monarch, + General, Trade, LFG, Roleplay, Society and Olthoi, with All, None and Defaults buttons. The + defaults are tells, fellowship and the allegiance channels. + - **Chat tabs:** every line that shows in a ticked tab is relayed. This covers the built-in tabs + (Chat, Channels, System, Combat, Rynth, Other) and any tabs you have made with chat rules. + - **Keywords:** optional. When set, only lines that contain one of the words are sent. + - **How often:** each route uses the relay's default pacing or its own. The batch window + (0–60 s) groups lines that arrive close together into one message. The message spacing + (1 s–10 min) sets the minimum time between posts. The panel shows the resulting messages per + minute. +- **Settings tab:** + - Who relays: only these characters, skip your own lines, and skip lines a chat rule hides. + - Message format: game time and a `[Character]` tag. + - The default pacing. + - Queue and log limits. +- **Log tab:** what was sent, errors, and pauses. +- **`/rc discord [on|off|status|window|test [route]|resume [route]]`**. + +## Behaviour + +- The relay reads RynthChat's own line feed. It keeps that feed running while the relay is on, + even with the Chat window closed. Scrollback from before the relay started (engine start, hot + reload, switching the relay on) is never re-posted. +- Discord limits are honoured: + - Messages are packed to 2000 characters. + - 429 responses wait for `retry_after`, and the `X-RateLimit-*` buckets are respected. + - 5xx and network errors retry with backoff. + - 400, 401, 403 and 404 pause the route until **Resume**, so a bad credential isn't retried. +- Mentions can't ping (`allowed_mentions.parse = []`), Markdown and `@everyone` are escaped, and + embeds are suppressed. +- Webhook URLs and bot tokens are encrypted with Windows DPAPI for the current user. The plain + text is never saved or logged, and errors are redacted. Encryption and file writes run off AC's + thread. +- Settings are shared by every client and character in + `%AppData%\RynthCore\rynthchat_discord.json`. With several clients in one fellowship or + allegiance, set "only these characters" so each line is posted once. +- **Import:** the first start with no settings file imports `RynthAi\discord.json` if one exists. + That file was written by a short-lived RynthAi build, 0.5.33 on the SK fork, which had its own + relay. The import keeps the routes, saved secrets (same DPAPI entropy), channels and keywords; + "other lines" become the Other tab. Without that file nothing is imported. + +## Files + +- New: `src/RynthCore.Engine/UI/Data/Discord/`: + - `ChatDiscord.cs` (runtime) + - `ChatDiscordLogic.cs` (per-line decisions) + - `ChatDiscordSettings.cs` (settings, store and import) + - `ChatSpeech.cs` (speech channel parsing) + - `DiscordClient.cs`, `DiscordFormat.cs`, `DiscordSecrets.cs` +- New: `src/RynthCore.Engine/ImGui/Panels/ChatDiscordFace.cs` (the Discord panel). +- Changed: + - `UI/Data/ChatData.cs`: new lines and a tick go to the relay from the chat poll. + - `ImGui/Panels/ChatFace.cs`: the Discord section in the gear menu. + - `EntryPoint.cs`: loads the settings and registers the panel when RynthChat is present. + - `EngineLifecycle.cs`: cancels in-flight posts on shutdown. + - `Compatibility/RynthCoreChatCommands.cs`: `/rc discord`. +- New tests: `tools/ChatDiscordTests` (`dotnet run -c Release`): 218 checks, all passing. + +## Verification + +- `dotnet build -c Release` of the engine: no errors and no new warnings. +- NativeAOT `dotnet publish -c Release`: no new trim or AOT warnings. The Avalonia ones are + unchanged. +- `tools/ChatDiscordTests`: PASS (218 checks). The tests cover speech parsing, route selection, + formatting and escaping, scrollback detection, batching, validation of pasted values, the request + body and 429 handling, settings round-trip and repair, the RynthAi import, and DPAPI. +- Not yet tried in game against a live Discord channel. diff --git a/src/RynthCore.Engine/Compatibility/RynthCoreChatCommands.cs b/src/RynthCore.Engine/Compatibility/RynthCoreChatCommands.cs index 85f4f44..e960354 100644 --- a/src/RynthCore.Engine/Compatibility/RynthCoreChatCommands.cs +++ b/src/RynthCore.Engine/Compatibility/RynthCoreChatCommands.cs @@ -34,6 +34,9 @@ namespace RynthCore.Engine.Compatibility; /// /rc chathold [on|off|status] — incoming chat waits for the plugins' /// verdict before AC prints it, so a line a plugin eats is kept out of AC's chat /// window too (). On at every start; not saved. +/// /rc discord [on|off|status|window|test [route]|resume [route]] — RynthChat's +/// Discord relay (): switch it, list the routes, +/// post a test line, clear a pause; window opens its panel (Chat > gear > Discord). /// /rv plates (aliases /rv nameplates, /rc plates) — the /// RynthVision nameplates and combat text: monster plates on|off, self, debuffs, /// numbers, gains [on|off] (with their sub-switches), all on|off, all|engaged, @@ -142,6 +145,14 @@ internal static class RynthCoreChatCommands return true; } + // /rc discord [on|off|status|window|test [route]|resume [route]] : RynthChat's Discord relay + if (IsVerb(sub, "discord", out string discordArgs)) + { + try { HandleDiscordCommand(discordArgs); } + catch (Exception ex) { RynthLog.Compat($"RynthCoreChatCommands: /rc discord failed - {ex.GetType().Name}: {ex.Message}"); } + return true; + } + // /rc plates [on|off|all|engaged|dist N|max N|scale X|opacity X|lift X|names|hp|level|weak|distance|fade|reset|status] if (IsVerb(sub, "plates", out string platesArgs) || IsVerb(sub, "nameplates", out platesArgs)) { @@ -805,6 +816,28 @@ internal static class RynthCoreChatCommands private static bool Flag(string? value, bool current) => value?.ToLowerInvariant() switch { "on" or "1" or "true" => true, "off" or "0" or "false" => false, _ => !current }; + /// + /// /rc discord: the relay's switch, status, test and resume (UI.Data.Discord.ChatDiscord); + /// "window" opens its panel, like Chat > gear > Discord settings. + /// + private static void HandleDiscordCommand(string args) + { + if (!ImGuiBackend.ImGuiPanelHost.HasFace(ImGuiBackend.Panels.ChatDiscordFace.Title)) + { + Reply("The Discord relay needs the RynthChat plugin."); + return; + } + string verb = args.Trim(); + if (verb.Equals("window", StringComparison.OrdinalIgnoreCase) || verb.Equals("show", StringComparison.OrdinalIgnoreCase) + || verb.Equals("settings", StringComparison.OrdinalIgnoreCase)) + { + UI.PanelRouter.Toggle(ImGuiBackend.Panels.ChatDiscordFace.Title); + return; + } + foreach (string line in UI.Data.Discord.ChatDiscord.HandleCommand(verb)) + Reply(line); + } + private static void Reply(string text) { RynthLog.Compat($"RynthCoreChatCommands: {text}"); diff --git a/src/RynthCore.Engine/EngineLifecycle.cs b/src/RynthCore.Engine/EngineLifecycle.cs index 990338b..d38048f 100644 --- a/src/RynthCore.Engine/EngineLifecycle.cs +++ b/src/RynthCore.Engine/EngineLifecycle.cs @@ -174,6 +174,8 @@ internal static class EngineLifecycle // The chat log is written on the tick pump (UiDataHub), now stopped. Left open, // it outlived this generation and locked the next one out of the file. Step("ChatModel.CloseLog", () => UI.Data.ChatModel.CloseLog()); + // Discord posts still in flight would finish in this dying generation's code. + Step("ChatDiscord.Shutdown", () => UI.Data.Discord.ChatDiscord.Shutdown()); Step("ServerMessageStream.Shutdown", () => Net.ServerMessageStream.Shutdown()); Step("FlightRecorder.Shutdown", () => Net.FlightRecorder.Shutdown()); diff --git a/src/RynthCore.Engine/EntryPoint.cs b/src/RynthCore.Engine/EntryPoint.cs index 1354fe2..aebffdf 100644 --- a/src/RynthCore.Engine/EntryPoint.cs +++ b/src/RynthCore.Engine/EntryPoint.cs @@ -944,6 +944,9 @@ public static class EntryPoint { UI.Data.ChatModel.EnsureSettingsLoaded(); UI.Data.ChatModel.InstallInput(); + // Discord relay settings (file read here, not on AC's thread); a relay left + // on keeps the chat feed running with the Chat panel closed. + UI.Data.Discord.ChatDiscord.EnsureLoaded(); } // ImGui faces for panels docked in the client (UI.PanelRouter // picks the face). Registered even while the ImGui layer is off, @@ -958,6 +961,7 @@ public static class EntryPoint { ImGuiBackend.Panels.ChatFace.Register(); ImGuiBackend.Panels.ChatFiltersFace.Register(); + ImGuiBackend.Panels.ChatDiscordFace.Register(); } ImGuiBackend.Panels.RadarFace.Register(); ImGuiBackend.Panels.SettingsFace.Register(); diff --git a/src/RynthCore.Engine/ImGui/Panels/ChatDiscordFace.cs b/src/RynthCore.Engine/ImGui/Panels/ChatDiscordFace.cs new file mode 100644 index 0000000..c304517 --- /dev/null +++ b/src/RynthCore.Engine/ImGui/Panels/ChatDiscordFace.cs @@ -0,0 +1,421 @@ +// ============================================================================ +// RynthCore.Engine - ImGui/Panels/ChatDiscordFace.cs +// The Discord panel: everything about copying chat to Discord +// (UI/Data/Discord/ChatDiscord.cs). Opened from the Chat panel's gear menu +// (Discord settings...) or /rc discord window. +// +// Routes one tab per destination: webhook URL, or bot token + channel ID; +// which speech channels and which chat tabs it gets, keywords, +// and optionally its own pacing; Send test / Resume +// Settings who relays (character filter, your own lines, hidden lines), +// the message format, and the default pacing and limits +// Log messages sent, rate limits and errors +// +// Settings fields are edited in place (single-value writes the pump +// tolerates); adding or removing a route replaces the Routes array, and a +// route's tab list is replaced too. Each change saves (ChatDiscord.Save, on +// the background writer). Secrets go to ChatDiscord, which encrypts them off +// this thread; the box is cleared at once and the text is never shown again. +// AC's render thread only. +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.Numerics; +using ImGuiNET; +using RynthCore.Engine.UI.Data; +using RynthCore.Engine.UI.Data.Discord; +using static RynthCore.Engine.ImGuiBackend.Panels.FaceKit; + +namespace RynthCore.Engine.ImGuiBackend.Panels; + +internal sealed class ChatDiscordFace : IImGuiPanel +{ + public const string Title = "Discord"; + + public static void Register() => ImGuiPanelHost.Register(Title, + new PanelSpec(new Vector2(560, 520), new Vector2(420, 300)), + () => new ChatDiscordFace()); + + private string _secretInput = string.Empty; + private string _secretMessage = string.Empty; + private bool _secretMessageIsError; + private DiscordRoute? _secretFor; + private int _lastLogCount; + + public void OnShown() + { + ChatModel.EnsureSettingsLoaded(); + ChatDiscord.EnsureLoaded(); + ChatDiscord.PanelShown(true); + } + + public void OnHidden() => ChatDiscord.PanelShown(false); + + public void Draw() + { + var s = ChatDiscord.Settings; + bool on = s.Enabled; + if (ImGuiNET.ImGui.Checkbox("Copy chat to Discord##dc_on", ref on)) ChatDiscord.SetEnabled(on); + ImGuiNET.ImGui.SetItemTooltip("Master switch. Off: nothing is queued or sent (Send test still works while this panel is open)."); + ImGuiNET.ImGui.SameLine(); + Label("| " + ChatDiscord.StatusLine(), Mute); + string me = ChatDiscord.CharacterName; + if (me.Length > 0 && !DiscordFormat.CharacterAllowed(s.OnlyCharacters, me)) + Wrapped($"{me} isn't in \"Only these characters\" (Settings tab), so this client relays nothing.", Amber); + ImGuiNET.ImGui.Separator(); + + if (ImGuiNET.ImGui.BeginTabBar("##dc_tabs")) + { + if (ImGuiNET.ImGui.BeginTabItem("Routes")) { DrawRoutes(s); ImGuiNET.ImGui.EndTabItem(); } + if (ImGuiNET.ImGui.BeginTabItem("Settings")) { DrawSettings(s); ImGuiNET.ImGui.EndTabItem(); } + if (ImGuiNET.ImGui.BeginTabItem("Log")) { DrawLog(); ImGuiNET.ImGui.EndTabItem(); } + ImGuiNET.ImGui.EndTabBar(); + } + } + + // ── Routes ─────────────────────────────────────────────────────────── + + private void DrawRoutes(ChatDiscordSettings s) + { + if (ImGuiNET.ImGui.SmallButton("Add route")) + { + var r = new DiscordRoute { Name = $"Route {s.Routes.Length + 1}" }; + ChatDiscordStore.NormalizeRoute(r); + s.Routes = new List(s.Routes) { r }.ToArray(); + ChatDiscord.Save(); + } + ImGuiNET.ImGui.SetItemTooltip("A route is one Discord channel and the chat it receives."); + + if (s.Routes.Length == 0) + { + ImGuiNET.ImGui.Spacing(); + Wrapped("No routes yet. Add one, then paste a webhook URL from Discord: Server Settings > Integrations > " + + "Webhooks > New Webhook > pick the channel > Copy Webhook URL.", Text); + return; + } + + if (!ImGuiNET.ImGui.BeginTabBar("##dc_routes", ImGuiTabBarFlags.FittingPolicyScroll)) return; + DiscordRoute? remove = null; + for (int i = 0; i < s.Routes.Length; i++) + { + DiscordRoute r = s.Routes[i]; + string label = (r.Status?.Paused == true ? "! " : r.Enabled ? "" : "(off) ") + r.Name + "###dc_route" + i; + if (!ImGuiNET.ImGui.BeginTabItem(label)) continue; + ImGuiNET.ImGui.PushID(i); + if (DrawRoute(s, r)) remove = r; + ImGuiNET.ImGui.PopID(); + ImGuiNET.ImGui.EndTabItem(); + } + ImGuiNET.ImGui.EndTabBar(); + + if (remove != null) + { + var list = new List(s.Routes); + list.Remove(remove); + s.Routes = list.ToArray(); + if (ReferenceEquals(_secretFor, remove)) ClearSecretBox(null); + ChatDiscord.Save(); + } + } + + /// One route's editor; true when the player asked to remove it. + private bool DrawRoute(ChatDiscordSettings s, DiscordRoute r) + { + if (!ReferenceEquals(_secretFor, r)) ClearSecretBox(r); + + DiscordRouteStatus? st = r.Status; + if (st != null) + { + if (st.Paused) Wrapped("Paused: " + st.LastError, Red); + else if (st.LastError.Length > 0) Wrapped("Last problem: " + st.LastError, Amber); + Label($"{st.MessagesSent} message(s), {st.LinesSent} line(s) sent, {st.Queued} queued, {st.Dropped} dropped" + + (st.LastSent != default ? $", last {st.LastSent:HH:mm:ss}" : string.Empty), Mute); + } + + if (ImGuiNET.ImGui.Checkbox("Enabled##r_on", ref r.Enabled)) ChatDiscord.Save(); + ImGuiNET.ImGui.SameLine(); + ImGuiNET.ImGui.SetNextItemWidth(200f); + string name = r.Name; + if (Input("Name##r_name", "route name", ref name, 40)) r.Name = name; + if (ImGuiNET.ImGui.IsItemDeactivatedAfterEdit()) + { + if (string.IsNullOrWhiteSpace(r.Name)) r.Name = "Discord"; + ChatDiscord.Save(); + } + + // Connection + Heading("Connection"); + int mode = Math.Max(0, Array.IndexOf(DiscordRoute.Modes, r.Mode)); + ImGuiNET.ImGui.SetNextItemWidth(220f); + if (ImGuiNET.ImGui.Combo("Send with##r_mode", ref mode, DiscordRoute.ModeNames, DiscordRoute.ModeNames.Length)) + { + r.Mode = DiscordRoute.Modes[mode]; + ClearSecretBox(r); + ChatDiscord.Resume(r); + ChatDiscord.Save(); + } + ImGuiNET.ImGui.SetItemTooltip("Webhook: simplest, one URL per channel, posts under any name.\n" + + "Bot: your own Discord bot posts it (it must be in the server with Send Messages there)."); + + bool bot = r.Mode == DiscordRoute.ModeBot; + bool saved = bot ? r.BotTokenProtected.Length > 0 : r.WebhookProtected.Length > 0; + ImGuiNET.ImGui.SetNextItemWidth(330f); + Input((bot ? "Bot token" : "Webhook URL") + "##r_secret", + saved ? "saved (paste a new one to replace it)" : bot ? "paste the bot token" : "https://discord.com/api/webhooks/...", + ref _secretInput, 512, ImGuiInputTextFlags.Password); + ImGuiNET.ImGui.SameLine(); + if (ImGuiNET.ImGui.Button("Save##r_secret_save") && _secretInput.Trim().Length > 0) + { + string err = bot ? ChatDiscord.SetBotToken(r, _secretInput) : ChatDiscord.SetWebhook(r, _secretInput); + _secretInput = string.Empty; + _secretMessageIsError = err.Length > 0; + _secretMessage = err.Length > 0 ? err : "Saved, encrypted for this Windows user. Use Send test to check it."; + } + if (saved) + { + ImGuiNET.ImGui.SameLine(); + if (ImGuiNET.ImGui.Button("Clear##r_secret_clear")) + { + if (bot) r.BotTokenProtected = string.Empty; else r.WebhookProtected = string.Empty; + _secretMessage = "Cleared."; + _secretMessageIsError = false; + ChatDiscord.Save(); + } + } + if (_secretMessage.Length > 0) Wrapped(_secretMessage, _secretMessageIsError ? Red : Green); + + if (bot) + { + ImGuiNET.ImGui.SetNextItemWidth(200f); + string chId = r.ChannelId; + if (Input("Channel ID##r_chid", "e.g. 123456789012345678", ref chId, 24, ImGuiInputTextFlags.CharsDecimal)) + { + r.ChannelId = chId.Trim(); + ChatDiscord.Resume(r); + } + if (ImGuiNET.ImGui.IsItemDeactivatedAfterEdit()) ChatDiscord.Save(); + ImGuiNET.ImGui.SetItemTooltip("Discord: User Settings > Advanced > Developer Mode on, then right-click the channel > Copy Channel ID."); + if (r.ChannelId.Length > 0 && !DiscordFormat.IsSnowflake(r.ChannelId)) + Label("A channel ID is 15-22 digits.", Red); + } + else + { + ImGuiNET.ImGui.SetNextItemWidth(200f); + Input("Post as##r_name_as", "character name", ref r.DisplayName, 80); + if (ImGuiNET.ImGui.IsItemDeactivatedAfterEdit()) ChatDiscord.Save(); + ImGuiNET.ImGui.SetItemTooltip("Name shown on the webhook's messages. Blank uses the character's name.\n" + + "Discord refuses names containing \"discord\" or \"clyde\"; those fall back to the webhook's own name."); + } + + if (ImGuiNET.ImGui.Button("Send test##r_test")) ChatDiscord.SendTest(r); + ImGuiNET.ImGui.SetItemTooltip("Posts one test line to this route now (also clears a pause)."); + if (st?.Paused == true) + { + ImGuiNET.ImGui.SameLine(); + if (ImGuiNET.ImGui.Button("Resume##r_resume")) ChatDiscord.Resume(r); + } + + DrawSpeech(r); + DrawTabs(r); + + Heading("Filter"); + ImGuiNET.ImGui.SetNextItemWidth(330f); + Input("Keywords##r_kw", "blank = every line; e.g. rare, Asheron", ref r.Keywords, 300); + if (ImGuiNET.ImGui.IsItemDeactivatedAfterEdit()) ChatDiscord.Save(); + ImGuiNET.ImGui.SetItemTooltip("Comma-separated. When set, only lines containing one of these words (any case) are relayed."); + + Heading("How often"); + if (ImGuiNET.ImGui.Checkbox("Own pacing for this route##r_pace", ref r.CustomPace)) ChatDiscord.Save(); + ImGuiNET.ImGui.SetItemTooltip("Off: the route uses the pacing on the Settings tab."); + if (r.CustomPace) + DrawPacing(ref r.BatchMs, ref r.MinIntervalMs, "##r"); + else + Label($"Using the default: batch {s.BatchMs / 1000.0:0.#} s, at most one message every {s.MinIntervalMs / 1000.0:0.#} s.", Mute); + + ImGuiNET.ImGui.Spacing(); + ImGuiNET.ImGui.Separator(); + bool remove = ImGuiNET.ImGui.SmallButton("Remove route##r_remove"); + ImGuiNET.ImGui.SetItemTooltip("Deletes this route and its saved credential."); + return remove; + } + + private static void DrawSpeech(DiscordRoute r) + { + Heading("Speech channels"); + if (ImGuiNET.ImGui.SmallButton("All##sp_all")) SetSpeech(r, DiscordRoute.AllSpeechMask()); + ImGuiNET.ImGui.SameLine(); + if (ImGuiNET.ImGui.SmallButton("None##sp_none")) SetSpeech(r, 0); + ImGuiNET.ImGui.SameLine(); + if (ImGuiNET.ImGui.SmallButton("Defaults##sp_def")) SetSpeech(r, DiscordRoute.DefaultSpeechMask()); + ImGuiNET.ImGui.SameLine(); + Label("what players say, by channel", Mute); + if (!ImGuiNET.ImGui.BeginTable("##sp_grid", 4, ImGuiTableFlags.SizingStretchSame)) return; + foreach (SpeechChannel ch in ChatSpeech.All) + { + ImGuiNET.ImGui.TableNextColumn(); + uint bit = ChatSpeech.Bit(ch); + bool ticked = (r.SpeechMask & bit) != 0; + if (ImGuiNET.ImGui.Checkbox(ChatSpeech.Name(ch) + "##sp" + (int)ch, ref ticked)) + SetSpeech(r, ticked ? r.SpeechMask | bit : r.SpeechMask & ~bit); + if (ch == SpeechChannel.Local) ImGuiNET.ImGui.SetItemTooltip("Local speech includes every NPC and player near you; it can be busy."); + } + ImGuiNET.ImGui.EndTable(); + } + + private static void SetSpeech(DiscordRoute r, uint mask) + { + r.SpeechMask = mask; + ChatDiscord.Save(); + } + + /// Chat tabs: every line that shows in a ticked tab goes, whatever it is. + private static void DrawTabs(DiscordRoute r) + { + Heading("Chat tabs"); + Label("every line that shows in the tab (System, Combat, or tabs your chat rules fill)", Mute); + string[] all = ChatModel.AllTabs(); + var shown = new List(all); + foreach (string t in r.Tabs) + if (!shown.Exists(x => string.Equals(x, t, StringComparison.OrdinalIgnoreCase))) shown.Add(t); + if (!ImGuiNET.ImGui.BeginTable("##tab_grid", 4, ImGuiTableFlags.SizingStretchSame)) return; + for (int i = 0; i < shown.Count; i++) + { + string tab = shown[i]; + ImGuiNET.ImGui.TableNextColumn(); + bool ticked = Array.Exists(r.Tabs, t => string.Equals(t, tab, StringComparison.OrdinalIgnoreCase)); + bool missing = Array.IndexOf(all, tab) < 0; + if (ImGuiNET.ImGui.Checkbox((missing ? tab + " (gone)" : tab) + "##tab" + i, ref ticked)) + { + var list = new List(r.Tabs); + list.RemoveAll(t => string.Equals(t, tab, StringComparison.OrdinalIgnoreCase)); + if (ticked) list.Add(tab); + r.Tabs = list.ToArray(); + ChatDiscord.Save(); + } + if (tab == "All") ImGuiNET.ImGui.SetItemTooltip("Every line in the All tab: very busy. Pair it with keywords."); + else if (missing) ImGuiNET.ImGui.SetItemTooltip("This tab no longer exists; untick it to drop it."); + } + ImGuiNET.ImGui.EndTable(); + } + + private void ClearSecretBox(DiscordRoute? forRoute) + { + _secretFor = forRoute; + _secretInput = string.Empty; + _secretMessage = string.Empty; + _secretMessageIsError = false; + } + + // ── Settings ───────────────────────────────────────────────────────── + + private static void DrawSettings(ChatDiscordSettings s) + { + Heading("Who relays"); + ImGuiNET.ImGui.SetNextItemWidth(300f); + Input("Only these characters##s_only", "blank = every character", ref s.OnlyCharacters, 400); + if (ImGuiNET.ImGui.IsItemDeactivatedAfterEdit()) ChatDiscord.Save(); + ImGuiNET.ImGui.SetItemTooltip("Comma-separated character names. With several clients in one allegiance or fellowship,\n" + + "list just one of them so each line is posted once."); + if (ImGuiNET.ImGui.Checkbox("Skip lines I type##s_own", ref s.SkipOwn)) ChatDiscord.Save(); + if (ImGuiNET.ImGui.Checkbox("Skip lines my chat rules hide##s_hidden", ref s.SkipHidden)) ChatDiscord.Save(); + ImGuiNET.ImGui.SetItemTooltip("Lines a Hide rule or standard filter hides in the chat aren't sent either."); + + Heading("Message format"); + if (ImGuiNET.ImGui.Checkbox("Timestamp (HH:mm:ss)##s_ts", ref s.IncludeTimestamp)) ChatDiscord.Save(); + if (ImGuiNET.ImGui.Checkbox("Start lines with [Character]##s_tag", ref s.TagCharacter)) ChatDiscord.Save(); + ImGuiNET.ImGui.SetItemTooltip("Useful when several characters post into the same Discord channel."); + + Heading("How often (default for every route)"); + DrawPacing(ref s.BatchMs, ref s.MinIntervalMs, "##s"); + + Heading("Limits"); + ImGuiNET.ImGui.SetNextItemWidth(200f); + if (ImGuiNET.ImGui.SliderInt("Queue limit (lines)##s_queue", ref s.MaxQueue, ChatDiscordSettings.QueueMin, ChatDiscordSettings.QueueMax)) + s.MaxQueue = Math.Clamp(s.MaxQueue, ChatDiscordSettings.QueueMin, ChatDiscordSettings.QueueMax); + if (ImGuiNET.ImGui.IsItemDeactivatedAfterEdit()) ChatDiscord.Save(); + ImGuiNET.ImGui.SetItemTooltip("Lines waiting per route; past this the oldest are dropped."); + ImGuiNET.ImGui.SetNextItemWidth(200f); + if (ImGuiNET.ImGui.SliderInt("Log size##s_log", ref s.MaxLog, ChatDiscordSettings.LogMin, ChatDiscordSettings.LogMax)) + s.MaxLog = Math.Clamp(s.MaxLog, ChatDiscordSettings.LogMin, ChatDiscordSettings.LogMax); + if (ImGuiNET.ImGui.IsItemDeactivatedAfterEdit()) ChatDiscord.Save(); + + ImGuiNET.ImGui.Spacing(); + Wrapped("Shared by every client and character (%AppData%\\RynthCore\\rynthchat_discord.json). Webhook URLs and bot tokens " + + "are encrypted for this Windows user; on another PC or user they must be pasted again.", Mute); + Wrapped("Relayed text never pings: @everyone, @here and user mentions are sent as plain text, and links don't unfurl.", Mute); + } + + /// Batch window and message spacing sliders (seconds on screen, ms stored). + private static void DrawPacing(ref int batchMs, ref int intervalMs, string id) + { + float batch = batchMs / 1000f; + ImGuiNET.ImGui.SetNextItemWidth(200f); + if (ImGuiNET.ImGui.SliderFloat("Batch window" + id + "_batch", ref batch, ChatDiscordSettings.BatchMinMs / 1000f, + ChatDiscordSettings.BatchMaxMs / 1000f, "%.1f s", ImGuiSliderFlags.Logarithmic)) + batchMs = Math.Clamp((int)MathF.Round(batch * 1000f), ChatDiscordSettings.BatchMinMs, ChatDiscordSettings.BatchMaxMs); + if (ImGuiNET.ImGui.IsItemDeactivatedAfterEdit()) ChatDiscord.Save(); + ImGuiNET.ImGui.SetItemTooltip("Lines arriving this close together go out as one Discord message.\n" + + "Longer = fewer, bigger messages (a digest); 0 = each line as soon as allowed."); + + float interval = intervalMs / 1000f; + ImGuiNET.ImGui.SetNextItemWidth(200f); + if (ImGuiNET.ImGui.SliderFloat("At most one message every" + id + "_interval", ref interval, ChatDiscordSettings.IntervalMinMs / 1000f, + ChatDiscordSettings.IntervalMaxMs / 1000f, "%.1f s", ImGuiSliderFlags.Logarithmic)) + intervalMs = Math.Clamp((int)MathF.Round(interval * 1000f), ChatDiscordSettings.IntervalMinMs, ChatDiscordSettings.IntervalMaxMs); + if (ImGuiNET.ImGui.IsItemDeactivatedAfterEdit()) ChatDiscord.Save(); + ImGuiNET.ImGui.SetItemTooltip("Spacing between messages to one route. Discord allows about 30 a minute per channel;\n" + + "2 s stays under it. Lines that arrive meanwhile wait and go in the next message."); + Label($"Up to {60000.0 / Math.Max(1, intervalMs):0.#} messages a minute per route.", Mute); + } + + // ── Log ────────────────────────────────────────────────────────────── + + private void DrawLog() + { + DiscordLogEntry[] log = ChatDiscord.LogSnapshot(); + if (ImGuiNET.ImGui.SmallButton("Clear##log_clear")) ChatDiscord.ClearLog(); + ImGuiNET.ImGui.SameLine(); + Label($"{log.Length} entries", Mute); + + if (!ImGuiNET.ImGui.BeginChild("##dc_log", new Vector2(0, 0), ImGuiChildFlags.Borders)) { ImGuiNET.ImGui.EndChild(); return; } + foreach (DiscordLogEntry e in log) + { + uint col = e.Kind switch { DiscordLogKind.Sent => Green, DiscordLogKind.Error => Red, _ => Amber }; + Label(e.Time.ToString("HH:mm:ss"), Mute); + ImGuiNET.ImGui.SameLine(); + Label(e.Route, col); + ImGuiNET.ImGui.SameLine(); + ImGuiNET.ImGui.TextWrapped(e.Text); + } + // Follow new lines unless the player scrolled up. + if (log.Length != _lastLogCount && ImGuiNET.ImGui.GetScrollY() >= ImGuiNET.ImGui.GetScrollMaxY() - 20f) + ImGuiNET.ImGui.SetScrollHereY(1f); + _lastLogCount = log.Length; + ImGuiNET.ImGui.EndChild(); + } + + // ── Helpers ────────────────────────────────────────────────────────── + + private static void Heading(string text) + { + ImGuiNET.ImGui.Spacing(); + Label(text, Teal); + } + + private static void Wrapped(string text, uint color) + { + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, color); + ImGuiNET.ImGui.TextWrapped(text); + ImGuiNET.ImGui.PopStyleColor(); + } + + /// A text box that keeps the keyboard from AC while it's being typed in. + private static bool Input(string label, string hint, ref string value, uint maxLength, + ImGuiInputTextFlags flags = ImGuiInputTextFlags.None) + { + bool changed = ImGuiNET.ImGui.InputTextWithHint(label, hint, ref value, maxLength, flags); + if (ImGuiNET.ImGui.IsItemActive()) ImGuiTextFocus.NoteActive(label); + return changed; + } +} diff --git a/src/RynthCore.Engine/ImGui/Panels/ChatFace.cs b/src/RynthCore.Engine/ImGui/Panels/ChatFace.cs index 24c81b3..843de79 100644 --- a/src/RynthCore.Engine/ImGui/Panels/ChatFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/ChatFace.cs @@ -937,6 +937,7 @@ internal sealed class ChatFace : IImGuiPanel ImGuiNET.ImGui.Separator(); if (ImGuiNET.ImGui.CollapsingHeader("Line colours")) DrawLineColours(); + DrawDiscordSettings(); if (!ChatModel.PluginBound) Label("Plugin not bound", Mute); // A colour drag changes it every frame: save once the picker lets go. if (_coloursDirty && !ImGuiNET.ImGui.IsAnyItemActive()) SaveColours(); @@ -1024,6 +1025,26 @@ internal sealed class ChatFace : IImGuiPanel ImGuiNET.ImGui.PopID(); } + /// Settings menu: the Discord relay's switch and status, and the way into its panel. + private static void DrawDiscordSettings() + { + ImGuiNET.ImGui.Separator(); + Label("Discord", Teal); + var discord = UI.Data.Discord.ChatDiscord.Settings; + bool relay = discord.Enabled; + if (ImGuiNET.ImGui.Checkbox("Copy chat to Discord", ref relay)) + UI.Data.Discord.ChatDiscord.SetEnabled(relay); + ImGuiNET.ImGui.SetItemTooltip("Sends the chat you choose (tells, fellowship, allegiance, any chat tab...)\n" + + "to Discord channels by webhook or bot. Set up the connection, channels and pacing in Discord settings."); + Label(UI.Data.Discord.ChatDiscord.StatusLine(), Mute); + if (ImGuiNET.ImGui.Button("Discord settings…")) + { + if (!ImGuiPanelHost.IsOpen(ChatDiscordFace.Title)) PanelRouter.Toggle(ChatDiscordFace.Title); + ImGuiNET.ImGui.CloseCurrentPopup(); + } + ImGuiNET.ImGui.SetItemTooltip("Connection (webhook or bot), which channels and tabs go where, keywords, how often, and the send log."); + } + private void DrawNewTabPopup() { if (!ImGuiNET.ImGui.BeginPopup("##chat_newtab")) diff --git a/src/RynthCore.Engine/UI/Data/ChatData.cs b/src/RynthCore.Engine/UI/Data/ChatData.cs index d53a72a..5b73aab 100644 --- a/src/RynthCore.Engine/UI/Data/ChatData.cs +++ b/src/RynthCore.Engine/UI/Data/ChatData.cs @@ -5,7 +5,9 @@ // // • ChatSource (hub, 100 ms) pulls new lines from RynthChatGetScrollbackJson // on the pump thread, keeps the newest 500, routes and colours them with -// the rules, and writes the chat log. +// the rules, and writes the chat log. It also hands each new line to the +// Discord relay and ticks it (UI/Data/Discord/ChatDiscord.cs), which keeps +// this source subscribed while it is on. // • ChatModel holds the settings (rynthchat_settings.json), the regex // rules and custom tabs, and the chat input line. // @@ -247,7 +249,7 @@ internal sealed class ChatFilterRule } } -/// New RynthChat lines while a chat face is open (100 ms). Publishes the newest 500, routed. +/// New RynthChat lines while a chat face or the Discord relay holds it (100 ms). Publishes the newest 500, routed. internal sealed unsafe class ChatSource : UiSource { private const int MaxLines = 500; @@ -261,6 +263,17 @@ internal sealed unsafe class ChatSource : UiSource public ChatSource() : base("Chat", periodMs: 100) { } protected internal override void Poll() + { + try { PollLines(); } + finally + { + // Every poll, new lines or not: due Discord posts, results, retries. + try { Discord.ChatDiscord.PumpTick(); } + catch (Exception ex) { RynthLog.UI($"ChatSource: Discord relay tick failed ({ex.GetType().Name}: {ex.Message})."); } + } + } + + private void PollLines() { if (_get == null) { @@ -329,6 +342,8 @@ internal sealed unsafe class ChatSource : UiSource added.CopyTo(skipAdded, lines, keepOld, added.Count - skipAdded); Publish(lines); ChatModel.PumpLog(added); + try { Discord.ChatDiscord.PumpLines(added); } + catch (Exception ex) { RynthLog.UI($"ChatSource: Discord relay skipped {added.Count} line(s) ({ex.GetType().Name}: {ex.Message})."); } } private int _badLinesLogged; diff --git a/src/RynthCore.Engine/UI/Data/Discord/ChatDiscord.cs b/src/RynthCore.Engine/UI/Data/Discord/ChatDiscord.cs new file mode 100644 index 0000000..1dee9ed --- /dev/null +++ b/src/RynthCore.Engine/UI/Data/Discord/ChatDiscord.cs @@ -0,0 +1,537 @@ +// ============================================================================ +// RynthCore.Engine - UI/Data/Discord/ChatDiscord.cs +// RynthChat's Discord relay: copies chosen chat (speech channels, or every +// line that shows in a chat tab) to Discord channels by webhook or bot. +// Configured in the Chat panel's settings (gear > Discord) and its Discord +// panel (ImGui/Panels/ChatDiscordFace.cs); /rc discord for quick control. +// +// Threads +// • ChatSource.Poll (the pump) hands every new chat line to PumpLines and +// calls PumpTick each poll: routing, batching, at most one HTTP post per +// route in flight, applying results. The relay keeps the chat feed +// subscribed while it is on (or its panel is open), so it runs with the +// Chat panel closed. +// • The panel and /rc discord (AC's thread) edit Settings in place and +// queue Resume / Send test / Clear log; secrets are encrypted and the +// file written on UiBackgroundWriter, never on AC's thread. +// • HTTP posts run on the thread pool and hand results back through a queue. +// +// Per route, lines arriving within the batch window go out as one message +// (<= 2000 characters), spaced by the route's minimum interval or whatever +// Discord's rate limit asks for. Network / 5xx failures retry with backoff; +// 400 / 401 / 403 / 404 pause the route until it's resumed or its +// credential changes. Scrollback read when the relay starts (engine start, +// hot reload, switching it on) is not sent. +// ============================================================================ + +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; + +namespace RynthCore.Engine.UI.Data.Discord; + +internal enum DiscordLogKind { Sent, Error, Info } + +/// One line in the Discord panel's log (immutable once added). +internal sealed record DiscordLogEntry(DateTime Time, DiscordLogKind Kind, string Route, string Text); + +internal static class ChatDiscord +{ + private const int DedupWindowMs = 3000; + private const int MaxTransientRetries = 5; + private const int MaxBackoffMs = 60000; + + /// A packed message waiting for, or in, an HTTP post. + private sealed class Batch + { + public required List Lines; + public required string Content; + public bool IsTest; + public int Attempts; + } + + /// Pump-thread state for one route. + private sealed class RouteState + { + public readonly List Pending = new(); + public long FirstPendingMs; + public long NextAllowedMs; + public Batch? InFlight; + public Batch? Retry; + public int BackoffMs; + public bool Paused; + public string LastError = string.Empty; + public int MessagesSent, LinesSent, Dropped; + public DateTime LastSent; + public readonly Dictionary Recent = new(StringComparer.Ordinal); + } + + private static ChatDiscordSettings _settings = new(); + private static int _loaded; + private static readonly string FilePath = ChatDiscordStore.DefaultPath; + + // Any thread -> pump. + private static readonly ConcurrentQueue<(DiscordRoute Route, Batch Batch, DiscordSendResult Result)> Done = new(); + private static readonly ConcurrentQueue ResumeQueue = new(); + private static readonly ConcurrentQueue TestQueue = new(); + private static volatile bool _clearLog; + private static volatile bool _shutdown; + private static readonly CancellationTokenSource Cts = new(); + + // Pump only. + private static readonly Dictionary States = new(ReferenceEqualityComparer.Instance); + private static readonly List Log = new(); + + // Pump writes, panel reads. + private static DiscordLogEntry[] _logSnapshot = Array.Empty(); + + // The chat feed (UiSources.Chat) is held while the relay is on or its panel is open. + private static int _feedHeld, _panelsOpen; + private static long _activeSinceTicks = DateTime.Now.Ticks; + + // The character playing, as the pump last saw it (the panel can't ask: the lookup may read a file). + private static string _characterName = string.Empty; + + /// The live settings. Any thread; fields are edited in place (see ChatDiscordSettings). + public static ChatDiscordSettings Settings => Volatile.Read(ref _settings); + + /// The character this client relays as ("" before login). Any thread. + public static string CharacterName => Volatile.Read(ref _characterName); + + // ── Setup (InitWorker / panel) ─────────────────────────────────────── + + /// Loads the settings once (file I/O: InitWorker or a background thread) and opens the feed if on. + public static void EnsureLoaded() + { + if (Interlocked.Exchange(ref _loaded, 1) != 0) return; + ChatDiscordSettings s = ChatDiscordStore.Load(FilePath, ChatDiscordStore.LegacyRynthAiPath, out string note); + Volatile.Write(ref _settings, s); + if (note.Length > 0) RynthLog.UI($"ChatDiscord: {note}."); + if (note.StartsWith("imported", StringComparison.Ordinal)) Save(); + Interlocked.Exchange(ref _activeSinceTicks, DateTime.Now.Ticks); + // Subscribing touches UiSources; done on the pump, like every other hub change. + UiDataHub.Post("chat discord feed", SyncFeed); + } + + /// Turns the relay on or off (and saves). Any thread. + public static void SetEnabled(bool on) + { + var s = Settings; + if (s.Enabled == on) return; + // Lines already in the chat when it's switched on are history, not news. + if (on) Interlocked.Exchange(ref _activeSinceTicks, DateTime.Now.Ticks); + s.Enabled = on; + Save(); + SyncFeed(); + } + + /// The Discord panel opened / closed: it keeps the feed (and so the relay's tick) running. AC thread. + public static void PanelShown(bool shown) + { + int n = shown ? Interlocked.Increment(ref _panelsOpen) : Interlocked.Decrement(ref _panelsOpen); + if (n < 0) Interlocked.Exchange(ref _panelsOpen, 0); + SyncFeed(); + } + + private static void SyncFeed() + { + bool want = !_shutdown && (Settings.Enabled || Volatile.Read(ref _panelsOpen) > 0); + if (want) + { + if (Interlocked.CompareExchange(ref _feedHeld, 1, 0) == 0) + { + UiSources.Chat.Subscribe(); + UiSources.Chat.RequestRefresh(); + } + } + else if (Interlocked.CompareExchange(ref _feedHeld, 0, 1) == 1) + UiSources.Chat.Unsubscribe(); + } + + /// Saves in the background (the JSON is taken now). Any thread. + public static void Save() + { + string json; + try { json = ChatDiscordStore.Serialize(Settings); } + catch (Exception ex) + { + RynthLog.UI($"ChatDiscord: settings not saved ({ex.GetType().Name}: {ex.Message})."); + return; + } + UiBackgroundWriter.Enqueue("persist chat discord", () => ChatDiscordStore.Write(FilePath, json)); + } + + /// Engine shutdown, after the pump stopped: cancels posts in flight. + public static void Shutdown() + { + _shutdown = true; + try { Cts.Cancel(); } catch { } + } + + // ── Panel / command requests (any thread) ──────────────────────────── + + /// Clears a pause on (the Resume button, or a credential change). + public static void Resume(DiscordRoute route) => ResumeQueue.Enqueue(route); + + /// Posts a test line to (ignoring its filters) and resumes it. + public static void SendTest(DiscordRoute route) + { + ResumeQueue.Enqueue(route); + TestQueue.Enqueue(route); + } + + public static void ClearLog() => _clearLog = true; + + public static DiscordLogEntry[] LogSnapshot() => Volatile.Read(ref _logSnapshot); + + /// + /// Stores a pasted webhook URL on , encrypted on the background writer. + /// Returns an error for the panel, or empty when accepted. The plain text is not kept. + /// + public static string SetWebhook(DiscordRoute route, string url) + { + if (!DiscordFormat.TryNormalizeWebhookUrl(url, out string normalized)) + return "That isn't a Discord webhook URL (https://discord.com/api/webhooks//)."; + UiBackgroundWriter.Enqueue("protect discord webhook", () => + { + route.WebhookProtected = DiscordSecrets.Protect(normalized); + Save(); + Resume(route); + }); + return string.Empty; + } + + /// Stores a pasted bot token (encrypted on the background writer). Returns an error, or empty. + public static string SetBotToken(DiscordRoute route, string token) + { + if (!DiscordFormat.LooksLikeBotToken(token)) + return "That doesn't look like a bot token (Developer Portal > Bot > Reset Token)."; + string trimmed = token.Trim(); + UiBackgroundWriter.Enqueue("protect discord bot token", () => + { + route.BotTokenProtected = DiscordSecrets.Protect(trimmed); + Save(); + Resume(route); + }); + return string.Empty; + } + + // ── Pump ───────────────────────────────────────────────────────────── + + /// New chat lines (already routed by the chat rules). ChatSource.Poll, pump thread. + internal static void PumpLines(IReadOnlyList added) + { + var s = Settings; + if (_shutdown || !s.Enabled || added.Count == 0) return; + DiscordRoute[] routes = s.Routes; + if (routes.Length == 0) return; + string me = SafeName(ChatModel.PumpCharacterName()); + if (!DiscordFormat.CharacterAllowed(s.OnlyCharacters, me)) return; + + DateTime now = DateTime.Now; + long nowMs = Environment.TickCount64; + var since = new DateTime(Interlocked.Read(ref _activeSinceTicks)); + // Keyword lists parsed once per batch of lines (the panel may edit them between polls). + var keywords = new List[routes.Length]; + for (int i = 0; i < routes.Length; i++) keywords[i] = DiscordFormat.SplitList(routes[i].Keywords); + + foreach (ChatLine line in added) + { + ChatRoute chatRoute = line.Route; + if (s.SkipHidden && chatRoute.Hidden) continue; + DateTime time = DiscordFormat.LineTime(line.Timestamp, now); + if (ChatDiscordLogic.IsBacklog(time, since)) continue; + if (!ChatDiscordLogic.TryClassify(line.Text, line.ChatType, me, out DiscordLineParts parts)) continue; + if (parts.Own && s.SkipOwn) continue; + + string channel = line.Channel; + bool ShowsIn(string tab) => chatRoute.ShowsIn(tab, channel); + for (int i = 0; i < routes.Length; i++) + { + DiscordRoute route = routes[i]; + if (!route.Enabled || !route.HasSecret) continue; + if (!ChatDiscordLogic.Wants(route, parts.Speech, ShowsIn, out string label)) continue; + if (!DiscordFormat.MatchesKeywords(parts.Haystack, keywords[i])) continue; + + RouteState st = State(route); + if (st.Paused) continue; + string key = ChatDiscordLogic.DedupKey(parts, label); + if (st.Recent.TryGetValue(key, out long seen) && nowMs - seen < DedupWindowMs) continue; + st.Recent[key] = nowMs; + if (st.Recent.Count > 256) ChatDiscordLogic.PruneRecent(st.Recent, nowMs, DedupWindowMs); + + Enqueue(s, st, ChatDiscordLogic.Format(s, time, parts, label, me), nowMs); + } + } + } + + /// Applies requests and results, starts due posts, publishes status. ChatSource.Poll, pump thread. + internal static void PumpTick() + { + if (_shutdown) return; + long now = Environment.TickCount64; + var s = Settings; + DiscordRoute[] routes = s.Routes; + Volatile.Write(ref _characterName, SafeName(ChatModel.PumpCharacterName())); + + PruneStates(routes); + while (ResumeQueue.TryDequeue(out var r)) + { + if (!States.TryGetValue(r, out var st)) continue; + st.Paused = false; + st.LastError = string.Empty; + st.BackoffMs = 0; + st.NextAllowedMs = 0; + } + while (Done.TryDequeue(out var d)) ApplyResult(d.Route, d.Batch, d.Result, now); + while (TestQueue.TryDequeue(out var t)) QueueTest(t); + if (_clearLog) + { + _clearLog = false; + Log.Clear(); + Volatile.Write(ref _logSnapshot, Array.Empty()); + } + + foreach (var route in routes) StartNextPost(s, route, now); + PublishStatus(routes); + } + + private static RouteState State(DiscordRoute route) + { + if (!States.TryGetValue(route, out var st)) States[route] = st = new RouteState(); + return st; + } + + private static void PruneStates(DiscordRoute[] routes) + { + if (States.Count <= routes.Length) return; + var live = new HashSet(routes, ReferenceEqualityComparer.Instance); + var gone = new List(); + foreach (var r in States.Keys) if (!live.Contains(r)) gone.Add(r); + foreach (var r in gone) States.Remove(r); + } + + private static void Enqueue(ChatDiscordSettings s, RouteState st, string line, long now) + { + if (st.Pending.Count == 0) st.FirstPendingMs = now; + st.Pending.Add(line); + int over = st.Pending.Count - s.MaxQueue; + if (over > 0) + { + st.Pending.RemoveRange(0, over); + st.Dropped += over; + } + } + + private static void QueueTest(DiscordRoute route) + { + string me = SafeName(ChatModel.PumpCharacterName()); + string line = DiscordFormat.FormatLine(DateTime.Now, null, null, + $"RynthChat Discord relay test from {(me.Length > 0 ? me : "RynthCore")} (route \"{route.Name}\").", + Settings.IncludeTimestamp, null); + var st = State(route); + st.Retry = new Batch { Lines = new List { line }, Content = line, IsTest = true }; + st.NextAllowedMs = 0; + } + + private static void StartNextPost(ChatDiscordSettings s, DiscordRoute route, long now) + { + if (!States.TryGetValue(route, out var st) || st.InFlight != null || st.Paused) return; + if (now < st.NextAllowedMs) return; + + Batch? batch = st.Retry; + if (batch == null) + { + if (!route.Enabled || !s.Enabled) { st.Pending.Clear(); return; } + if (st.Pending.Count == 0) return; + // Wait out the batch window unless the pending text already fills a message. + int chars = 0; + foreach (string l in st.Pending) chars += l.Length + 1; + if (now - st.FirstPendingMs < s.BatchFor(route) && chars < DiscordFormat.MaxContent) return; + + string content = DiscordFormat.Pack(st.Pending, out int taken); + batch = new Batch { Lines = st.Pending.GetRange(0, taken), Content = content }; + st.Pending.RemoveRange(0, taken); + st.FirstPendingMs = now; + } + st.Retry = null; + + // Decrypt only now, on the way out; the plain text lives in the request task alone. + string mode = route.Mode, channelId = route.ChannelId; + string blob = mode == DiscordRoute.ModeBot ? route.BotTokenProtected : route.WebhookProtected; + if (blob.Length == 0) + { + ApplyResult(route, batch, DiscordSendResult.Fail( + mode == DiscordRoute.ModeBot ? "no bot token saved" : "no webhook URL saved", permanent: true), now); + return; + } + if (!DiscordSecrets.TryUnprotect(blob, out string secret)) + { + ApplyResult(route, batch, DiscordSendResult.Fail( + "the saved credential can't be read on this Windows user; paste it again", permanent: true), now); + return; + } + string displayName = route.DisplayName.Length > 0 ? route.DisplayName : SafeName(ChatModel.PumpCharacterName()); + + st.InFlight = batch; + st.NextAllowedMs = now + s.IntervalFor(route); + CancellationToken ct = Cts.Token; + _ = Task.Run(async () => + { + DiscordSendResult r; + try + { + r = mode == DiscordRoute.ModeBot + ? await DiscordClient.PostBotAsync(secret, channelId, batch.Content, ct).ConfigureAwait(false) + : await DiscordClient.PostWebhookAsync(secret, batch.Content, displayName, ct).ConfigureAwait(false); + } + catch (Exception ex) { r = DiscordSendResult.Fail(DiscordFormat.Redact(ex.Message, secret)); } + Done.Enqueue((route, batch, r)); + }); + } + + private static void ApplyResult(DiscordRoute route, Batch batch, DiscordSendResult r, long now) + { + var st = State(route); + st.InFlight = null; + var s = Settings; + + if (r.Ok) + { + st.LastError = string.Empty; + st.BackoffMs = 0; + st.MessagesSent++; + st.LinesSent += batch.Lines.Count; + st.LastSent = DateTime.Now; + st.NextAllowedMs = Math.Max(st.NextAllowedMs, now + Math.Max(s.IntervalFor(route), r.RetryAfterMs)); + AddLog(s, DiscordLogKind.Sent, route.Name, batch.IsTest ? "Test message sent." : $"{batch.Lines.Count} line(s): {batch.Content}"); + return; + } + + st.LastError = r.Error; + if (r.Permanent) + { + st.Paused = true; + st.Dropped += batch.Lines.Count + st.Pending.Count; + st.Pending.Clear(); + AddLog(s, DiscordLogKind.Error, route.Name, $"Paused: {r.Error}"); + RynthLog.UI($"ChatDiscord: route '{route.Name}' paused: {r.Error}"); + return; + } + + if (r.Status == 429) + { + // Rate limits don't count as a failed attempt; Discord says exactly when to come back. + st.Retry = batch; + st.NextAllowedMs = now + Math.Max(r.RetryAfterMs, s.IntervalFor(route)); + AddLog(s, DiscordLogKind.Info, route.Name, r.Error); + return; + } + + batch.Attempts++; + if (batch.Attempts >= MaxTransientRetries) + { + st.Dropped += batch.Lines.Count; + AddLog(s, DiscordLogKind.Error, route.Name, $"Gave up after {batch.Attempts} tries ({r.Error}); {batch.Lines.Count} line(s) dropped."); + RynthLog.UI($"ChatDiscord: route '{route.Name}' dropped a batch: {r.Error}"); + st.BackoffMs = 0; + return; + } + st.BackoffMs = st.BackoffMs == 0 ? 2000 : Math.Min(st.BackoffMs * 2, MaxBackoffMs); + st.Retry = batch; + st.NextAllowedMs = now + Math.Max(st.BackoffMs, r.RetryAfterMs); + AddLog(s, DiscordLogKind.Error, route.Name, $"{r.Error}; retrying in {st.BackoffMs / 1000}s."); + } + + private static void PublishStatus(DiscordRoute[] routes) + { + foreach (var route in routes) + { + if (!States.TryGetValue(route, out var st)) continue; + int queued = st.Pending.Count + (st.InFlight?.Lines.Count ?? 0) + (st.Retry?.Lines.Count ?? 0); + DiscordRouteStatus? old = route.Status; + if (old != null && old.Queued == queued && old.MessagesSent == st.MessagesSent && old.Dropped == st.Dropped + && old.Paused == st.Paused && ReferenceEquals(old.LastError, st.LastError) && old.LastSent == st.LastSent) + continue; + route.Status = new DiscordRouteStatus(queued, st.MessagesSent, st.LinesSent, st.Dropped, st.Paused, st.LastError, st.LastSent); + } + } + + private static void AddLog(ChatDiscordSettings s, DiscordLogKind kind, string route, string text) + { + Log.Add(new DiscordLogEntry(DateTime.Now, kind, route, text)); + if (Log.Count > s.MaxLog) Log.RemoveRange(0, Log.Count - s.MaxLog); + Volatile.Write(ref _logSnapshot, Log.ToArray()); + } + + private static string SafeName(string? name) => (name ?? string.Empty).Trim().TrimStart('+'); + + // ── Status and /rc discord ─────────────────────────────────────────── + + /// "2 of 3 route(s) ready, only Bob." Any thread. + public static string StatusLine() + { + var s = Settings; + int ready = 0; + foreach (var r in s.Routes) if (r.Enabled && r.HasSecret) ready++; + string only = s.OnlyCharacters.Trim().Length > 0 ? $", only {s.OnlyCharacters.Trim()}" : string.Empty; + return $"{ready} of {s.Routes.Length} route(s) ready{only}."; + } + + /// + /// /rc discord [on|off|status|test [route]|resume [route]]. Returns the reply lines ("window" + /// is handled by the caller: it opens the panel). AC's thread. + /// + public static List HandleCommand(string args) + { + var reply = new List(); + var s = Settings; + string[] parts = (args ?? string.Empty).Trim().Split(' ', 2, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); + string verb = parts.Length > 0 ? parts[0].ToLowerInvariant() : "status"; + string rest = parts.Length > 1 ? parts[1] : string.Empty; + switch (verb) + { + case "on": + SetEnabled(true); + reply.Add($"Discord relay on. {StatusLine()}"); + break; + case "off": + SetEnabled(false); + reply.Add("Discord relay off."); + break; + case "test": + case "resume": + if (verb == "test" && !s.Enabled && Volatile.Read(ref _panelsOpen) == 0) + { + reply.Add("The relay is off: /rc discord on, or use Send test in the Discord panel (/rc discord window)."); + break; + } + int n = 0; + foreach (var r in s.Routes) + { + if (rest.Length > 0 && !r.Name.Equals(rest, StringComparison.OrdinalIgnoreCase)) continue; + if (verb == "test") SendTest(r); else Resume(r); + n++; + } + reply.Add(n == 0 + ? $"No route{(rest.Length > 0 ? $" named '{rest}'" : "s")}. Add one in Chat > gear > Discord (or /rc discord window)." + : $"{(verb == "test" ? "Test sent to" : "Resumed")} {n} route(s)."); + break; + default: + reply.Add($"Discord relay {(s.Enabled ? "on" : "off")}. {StatusLine()}"); + foreach (var r in s.Routes) + { + var st = r.Status; + reply.Add($" {r.Name}: {(r.Enabled ? "on" : "off")}, {(r.HasSecret ? r.Mode : "no destination set")}" + + (st == null ? string.Empty + : $", {st.MessagesSent} sent, {st.Queued} queued, {st.Dropped} dropped{(st.Paused ? ", PAUSED" : string.Empty)}" + + (st.LastError.Length > 0 ? $" - {st.LastError}" : string.Empty))); + } + reply.Add("/rc discord on|off | window | test [route] | resume [route] | status"); + break; + } + return reply; + } +} diff --git a/src/RynthCore.Engine/UI/Data/Discord/ChatDiscordLogic.cs b/src/RynthCore.Engine/UI/Data/Discord/ChatDiscordLogic.cs new file mode 100644 index 0000000..2cb0b27 --- /dev/null +++ b/src/RynthCore.Engine/UI/Data/Discord/ChatDiscordLogic.cs @@ -0,0 +1,91 @@ +// ============================================================================ +// RynthCore.Engine - UI/Data/Discord/ChatDiscordLogic.cs +// The relay's per-line decisions, kept free of engine state so +// tools/ChatDiscordTests can run them: what a chat line is (speech on a +// channel, or plain text), whether a route wants it and under which label, +// how it is written for Discord, and whether it is scrollback from before +// the relay started. +// ============================================================================ + +using System; +using System.Collections.Generic; + +namespace RynthCore.Engine.UI.Data.Discord; + +/// A chat line split for the relay. null: not player speech. +internal readonly record struct DiscordLineParts(SpeechChannel? Speech, string Speaker, string Message, bool Own) +{ + /// "Speaker message" (or the message alone): what route keywords are matched against. + public string Haystack => Speaker.Length > 0 ? Speaker + " " + Message : Message; +} + +internal static class ChatDiscordLogic +{ + /// + /// Splits (AC's name links already stripped). Player speech gets its + /// channel and speaker (yours as when known); anything else is the text + /// alone. False for blank lines. + /// + public static bool TryClassify(string? text, int chatType, string me, out DiscordLineParts parts) + { + parts = default; + if (string.IsNullOrWhiteSpace(text)) return false; + if (ChatSpeech.TryParse(text, chatType, out var ch, out string who, out string msg, out bool own)) + { + parts = new DiscordLineParts(ch, own && me.Length > 0 ? me : who, msg, own); + return true; + } + string plain = ChatSpeech.Decode(text).Trim(); + if (plain.Length == 0) return false; + parts = new DiscordLineParts(null, string.Empty, plain, false); + return true; + } + + /// + /// True when takes the line: its speech channel is ticked, or the line + /// shows in one of the route's tabs (). is + /// what the Discord line is tagged with: the speech channel, else the tab that matched. + /// + public static bool Wants(DiscordRoute route, SpeechChannel? speech, Func showsInTab, out string label) + { + label = string.Empty; + if (speech is { } ch && route.RelaysSpeech(ch)) + { + label = ChatSpeech.Name(ch); + return true; + } + foreach (string tab in route.Tabs) + { + if (!showsInTab(tab)) continue; + label = speech is { } c ? ChatSpeech.Name(c) : tab; + return true; + } + return false; + } + + /// The Discord text for one relayed line. + public static string Format(ChatDiscordSettings s, DateTime time, in DiscordLineParts parts, string label, string me) + => DiscordFormat.FormatLine(time, label.Length > 0 ? label : null, + parts.Speech != null && parts.Speaker.Length > 0 ? parts.Speaker : null, + parts.Message, s.IncludeTimestamp, s.TagCharacter && me.Length > 0 ? me : null); + + /// + /// True for a line printed before the relay started (the scrollback a fresh engine, or a hot + /// reload, reads in its first poll): those were sent already or are history, not news. Stamps + /// only have whole seconds, so the line's second counts as "after". + /// + public static bool IsBacklog(DateTime lineTime, DateTime activeSince) + => lineTime < activeSince.AddTicks(-(activeSince.Ticks % TimeSpan.TicksPerSecond)); + + /// Key for the per-route repeat filter (the same line twice within a few seconds). + public static string DedupKey(in DiscordLineParts parts, string label) => $"{label}|{parts.Speaker}|{parts.Message}"; + + /// Drops dedup entries older than . + public static void PruneRecent(Dictionary recent, long now, int windowMs) + { + List? stale = null; + foreach (var kv in recent) + if (now - kv.Value > windowMs) (stale ??= new List()).Add(kv.Key); + if (stale != null) foreach (string k in stale) recent.Remove(k); + } +} diff --git a/src/RynthCore.Engine/UI/Data/Discord/ChatDiscordSettings.cs b/src/RynthCore.Engine/UI/Data/Discord/ChatDiscordSettings.cs new file mode 100644 index 0000000..b03eac5 --- /dev/null +++ b/src/RynthCore.Engine/UI/Data/Discord/ChatDiscordSettings.cs @@ -0,0 +1,373 @@ +// ============================================================================ +// RynthCore.Engine - UI/Data/Discord/ChatDiscordSettings.cs +// RynthChat's Discord relay settings, shared by every client and character +// (%AppData%\RynthCore\rynthchat_discord.json, beside rynthchat_settings.json). +// +// Threads: the Discord panel (AC's render thread) edits fields in place, each +// a single reference or 32-bit value, so the pump's reads never tear. Arrays +// (Routes, a route's Tabs) are replaced, never changed in place, so the pump +// can walk the one it read without a lock. +// +// Secrets (webhook URL, bot token) are stored only as DPAPI blobs +// (DiscordSecrets); the JSON never holds them in plain text. +// +// The first load with no file imports RynthAi 0.5.33's discord.json (the +// relay lived in RynthAi for one release); its blobs use the same DPAPI +// entropy, so saved webhooks keep working. +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace RynthCore.Engine.UI.Data.Discord; + +/// Route state the panel shows; replaced as a whole by the pump. +internal sealed record DiscordRouteStatus(int Queued, int MessagesSent, int LinesSent, int Dropped, bool Paused, + string LastError, DateTime LastSent); + +/// One Discord destination and the chat it receives. +internal sealed class DiscordRoute +{ + public const string ModeWebhook = "webhook"; + public const string ModeBot = "bot"; + public static readonly string[] Modes = { ModeWebhook, ModeBot }; + public static readonly string[] ModeNames = { "Webhook URL", "Bot token + channel ID" }; + + /// Label shown in the panel, the log and /rc discord. + public string Name = "Discord"; + + public bool Enabled = true; + + public string Mode = ModeWebhook; + + /// DPAPI blob of the webhook URL (the URL embeds the webhook token). + public string WebhookProtected = string.Empty; + + /// DPAPI blob of the bot token (bot mode). + public string BotTokenProtected = string.Empty; + + /// Target channel snowflake (bot mode). Not secret. + public string ChannelId = string.Empty; + + /// Webhook display name; blank uses the character's name. Ignored in bot mode. + public string DisplayName = string.Empty; + + /// Speech channels relayed (names, ). Saved form of . + public string[]? Speech; + + /// + /// Chat tabs relayed: every line that shows in one of them (channel tabs like System, or + /// tabs the chat rules fill). Replaced, never changed in place. + /// + public string[] Tabs = Array.Empty(); + + /// Comma-separated words; when set, only lines containing one of them are relayed. + public string Keywords = string.Empty; + + /// Use this route's own pacing instead of the relay's. + public bool CustomPace; + + /// With : lines arriving within this window go out in one message. + public int BatchMs = 1500; + + /// With : minimum spacing between this route's messages. + public int MinIntervalMs = 2000; + + // ── Runtime only ───────────────────────────────────────────────────── + + /// Bits of (). + [JsonIgnore] public uint SpeechMask; + + /// Written by the pump, read by the panel. + [JsonIgnore] public volatile DiscordRouteStatus? Status; + + /// True when a send secret is stored for the current mode (the plain text is never kept here). + [JsonIgnore] + public bool HasSecret => Mode == ModeBot + ? BotTokenProtected.Length > 0 && ChannelId.Length > 0 + : WebhookProtected.Length > 0; + + public bool RelaysSpeech(SpeechChannel ch) => (SpeechMask & ChatSpeech.Bit(ch)) != 0; + + /// Tells, fellowship and the allegiance channels: private chat a player usually wants on their phone. + public static uint DefaultSpeechMask() + { + uint m = 0; + foreach (var ch in new[] + { + SpeechChannel.Tell, SpeechChannel.Fellowship, SpeechChannel.Allegiance, + SpeechChannel.Patron, SpeechChannel.Vassals, SpeechChannel.Covassals, SpeechChannel.Monarch, + }) + m |= ChatSpeech.Bit(ch); + return m; + } + + public static uint AllSpeechMask() + { + uint m = 0; + foreach (var ch in ChatSpeech.All) m |= ChatSpeech.Bit(ch); + return m; + } + + public static string[] NamesFromMask(uint mask) + { + var names = new List(); + foreach (var ch in ChatSpeech.All) + if ((mask & ChatSpeech.Bit(ch)) != 0) names.Add(ChatSpeech.Name(ch)); + return names.ToArray(); + } + + /// The mask for ; when there is no list at all. + public static uint MaskFromNames(IEnumerable? names, uint fallback) + { + if (names == null) return fallback; + uint m = 0; + foreach (string n in names) + if (ChatSpeech.TryParseName(n, out var ch)) m |= ChatSpeech.Bit(ch); + return m; + } +} + +internal sealed class ChatDiscordSettings +{ + public const int CurrentVersion = 1; + + public int Version = CurrentVersion; + + /// Master switch; off means nothing is queued or sent (and the chat feed isn't kept open for it). + public bool Enabled; + + /// Destinations. Replaced (copy-on-write) when one is added or removed. + public DiscordRoute[] Routes = Array.Empty(); + + /// + /// Comma-separated character names allowed to relay; blank = every character. With several + /// clients in the same allegiance or fellowship, set this so only one of them posts each line. + /// + public string OnlyCharacters = string.Empty; + + /// Leave out lines you typed yourself ("You say", "You tell"). + public bool SkipOwn; + + /// Leave out lines a chat rule hides. + public bool SkipHidden = true; + + /// Start each relayed line with the game time (HH:mm:ss). + public bool IncludeTimestamp = true; + + /// Start each relayed line with "[Character]" (useful when several characters share a channel). + public bool TagCharacter; + + /// Lines arriving within this window go out in one Discord message. + public int BatchMs = 1500; + + /// Minimum spacing between messages to one route (Discord allows about 30 per minute per channel). + public int MinIntervalMs = 2000; + + /// Lines waiting per route; the oldest are dropped beyond this. + public int MaxQueue = 200; + + /// Entries kept in the panel's log. + public int MaxLog = 200; + + // Pacing limits, shared by the panel's sliders and Normalize. + public const int BatchMinMs = 0, BatchMaxMs = 60_000; + public const int IntervalMinMs = 1000, IntervalMaxMs = 600_000; + public const int QueueMin = 20, QueueMax = 2000; + public const int LogMin = 20, LogMax = 2000; + + /// The batch window uses. + public int BatchFor(DiscordRoute route) => route.CustomPace ? route.BatchMs : BatchMs; + + /// The message spacing uses. + public int IntervalFor(DiscordRoute route) => route.CustomPace ? route.MinIntervalMs : MinIntervalMs; +} + +/// Loads / saves . +internal static class ChatDiscordStore +{ + public static string DefaultPath => + Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "RynthCore", "rynthchat_discord.json"); + + /// RynthAi 0.5.33's settings, imported once when doesn't exist yet. + public static string LegacyRynthAiPath => Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "discord.json"); + + /// + /// Reads the settings (or imports RynthAi's, or the defaults). says what + /// happened, for the log. Never throws. + /// + public static ChatDiscordSettings Load(string path, string? legacyPath, out string note) + { + note = string.Empty; + ChatDiscordSettings? s = null; + try + { + if (File.Exists(path)) + s = JsonSerializer.Deserialize(File.ReadAllText(path), ChatDiscordJsonContext.Default.ChatDiscordSettings); + else if (legacyPath != null && File.Exists(legacyPath)) + { + s = ImportRynthAi(File.ReadAllText(legacyPath)); + if (s != null) note = $"imported {s.Routes.Length} route(s) from RynthAi's discord.json"; + } + } + catch (Exception ex) + { + note = $"settings unreadable ({ex.GetType().Name}: {ex.Message}); using defaults"; + KeepUnreadable(path); + s = null; + } + s ??= new ChatDiscordSettings(); + Normalize(s); + return s; + } + + /// The settings as JSON (speech names refreshed from the masks first). Any thread. + public static string Serialize(ChatDiscordSettings s) + { + foreach (var r in s.Routes) r.Speech = DiscordRoute.NamesFromMask(r.SpeechMask); + return JsonSerializer.Serialize(s, ChatDiscordJsonContext.Default.ChatDiscordSettings); + } + + /// Writes beside the file and swaps it in. Background writer thread. + public static void Write(string path, string json) + { + Directory.CreateDirectory(Path.GetDirectoryName(path)!); + string tmp = $"{path}.{Environment.ProcessId}.tmp"; // every client shares the file + try + { + File.WriteAllText(tmp, json); + File.Move(tmp, path, overwrite: true); + } + catch + { + try { File.Delete(tmp); } catch { } + throw; + } + } + + /// Repairs missing / out-of-range values and builds the runtime speech masks. + internal static void Normalize(ChatDiscordSettings s) + { + s.Version = ChatDiscordSettings.CurrentVersion; + s.Routes = (s.Routes ?? Array.Empty()).Where(r => r != null).ToArray(); + foreach (var r in s.Routes) NormalizeRoute(r); + s.OnlyCharacters ??= string.Empty; + s.BatchMs = Math.Clamp(s.BatchMs, ChatDiscordSettings.BatchMinMs, ChatDiscordSettings.BatchMaxMs); + s.MinIntervalMs = Math.Clamp(s.MinIntervalMs, ChatDiscordSettings.IntervalMinMs, ChatDiscordSettings.IntervalMaxMs); + s.MaxQueue = Math.Clamp(s.MaxQueue, ChatDiscordSettings.QueueMin, ChatDiscordSettings.QueueMax); + s.MaxLog = Math.Clamp(s.MaxLog, ChatDiscordSettings.LogMin, ChatDiscordSettings.LogMax); + } + + internal static void NormalizeRoute(DiscordRoute r) + { + r.Name = string.IsNullOrWhiteSpace(r.Name) ? "Discord" : r.Name.Trim(); + if (Array.IndexOf(DiscordRoute.Modes, r.Mode ?? string.Empty) < 0) r.Mode = DiscordRoute.ModeWebhook; + r.WebhookProtected ??= string.Empty; + r.BotTokenProtected ??= string.Empty; + r.ChannelId = (r.ChannelId ?? string.Empty).Trim(); + r.DisplayName ??= string.Empty; + r.Keywords ??= string.Empty; + r.SpeechMask = DiscordRoute.MaskFromNames(r.Speech, DiscordRoute.DefaultSpeechMask()); + r.Tabs = (r.Tabs ?? Array.Empty()) + .Where(t => !string.IsNullOrWhiteSpace(t)).Select(t => t.Trim()) + .Distinct(StringComparer.OrdinalIgnoreCase).ToArray(); + r.BatchMs = Math.Clamp(r.BatchMs, ChatDiscordSettings.BatchMinMs, ChatDiscordSettings.BatchMaxMs); + r.MinIntervalMs = Math.Clamp(r.MinIntervalMs, ChatDiscordSettings.IntervalMinMs, ChatDiscordSettings.IntervalMaxMs); + } + + /// + /// RynthAi 0.5.33's discord.json: the same routes, with "Channels" for the speech channels and + /// "IncludeOther" for lines that aren't speech (the Other tab here). Null when unreadable. + /// + internal static ChatDiscordSettings? ImportRynthAi(string json) + { + var old = JsonSerializer.Deserialize(json, ChatDiscordJsonContext.Default.RynthAiDiscordDto); + if (old == null) return null; + var s = new ChatDiscordSettings + { + Enabled = old.Enabled, + OnlyCharacters = old.OnlyCharacters ?? string.Empty, + SkipOwn = old.SkipOwn, + IncludeTimestamp = old.IncludeTimestamp, + TagCharacter = old.TagCharacter, + BatchMs = old.BatchMs, + MinIntervalMs = old.MinIntervalMs, + MaxQueue = old.MaxQueue, + MaxLog = old.MaxLog, + }; + var routes = new List(); + foreach (var r in old.Routes ?? Array.Empty()) + { + if (r == null) continue; + routes.Add(new DiscordRoute + { + Name = r.Name ?? "Discord", + Enabled = r.Enabled, + Mode = r.Mode ?? DiscordRoute.ModeWebhook, + WebhookProtected = r.WebhookProtected ?? string.Empty, + BotTokenProtected = r.BotTokenProtected ?? string.Empty, + ChannelId = r.ChannelId ?? string.Empty, + DisplayName = r.DisplayName ?? string.Empty, + Speech = r.Channels?.ToArray(), + Tabs = r.IncludeOther ? new[] { "Other" } : Array.Empty(), + Keywords = r.Keywords ?? string.Empty, + }); + } + s.Routes = routes.ToArray(); + return s; + } + + private static void KeepUnreadable(string path) + { + try + { + if (!File.Exists(path)) return; + File.Copy(path, Path.ChangeExtension(path, $".unreadable-{DateTime.Now:yyyyMMdd-HHmmss}.json"), overwrite: false); + } + catch { } + } +} + +// ── RynthAi 0.5.33 import shapes (read only) ───────────────────────────── + +internal sealed class RynthAiDiscordRouteDto +{ + public string? Name; + public bool Enabled = true; + public string? Mode; + public string? WebhookProtected; + public string? BotTokenProtected; + public string? ChannelId; + public string? DisplayName; + public List? Channels; + public bool IncludeOther; + public string? Keywords; +} + +internal sealed class RynthAiDiscordDto +{ + public bool Enabled; + public RynthAiDiscordRouteDto[]? Routes; + public string? OnlyCharacters; + public bool SkipOwn; + public bool IncludeTimestamp = true; + public bool TagCharacter; + public int BatchMs = 1500; + public int MinIntervalMs = 2000; + public int MaxQueue = 200; + public int MaxLog = 200; +} + +// JsonSerializerContext must be at namespace scope (not nested) for source generation. +[JsonSerializable(typeof(ChatDiscordSettings))] +[JsonSerializable(typeof(RynthAiDiscordDto))] +[JsonSourceGenerationOptions( + WriteIndented = true, + IncludeFields = true, + PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase, + PropertyNameCaseInsensitive = true)] +internal partial class ChatDiscordJsonContext : JsonSerializerContext { } diff --git a/src/RynthCore.Engine/UI/Data/Discord/ChatSpeech.cs b/src/RynthCore.Engine/UI/Data/Discord/ChatSpeech.cs new file mode 100644 index 0000000..4360c32 --- /dev/null +++ b/src/RynthCore.Engine/UI/Data/Discord/ChatSpeech.cs @@ -0,0 +1,213 @@ +// ============================================================================ +// RynthCore.Engine - UI/Data/Discord/ChatSpeech.cs +// Player speech in a chat line: which channel it was said on (local, tell, +// fellowship, the allegiance channels, the global chat channels), who said +// it and what. The Discord relay uses it to pick lines finer than a chat tab +// ("tells and fellowship only") and to print them as [Channel] Speaker: text. +// +// Ported from RynthAi's translator (ChatTranslator.TryParseInbound) when the +// relay moved into RynthChat (2026-10-11). Pure; covered by +// tools/ChatDiscordTests. +// ============================================================================ + +using System; +using System.Globalization; +using System.Text.RegularExpressions; + +namespace RynthCore.Engine.UI.Data.Discord; + +/// Speech channels. Saved by name (), never by number. +internal enum SpeechChannel +{ + Local = 0, + Tell, + Fellowship, + Allegiance, + Patron, + Vassals, + Covassals, + Monarch, + General, + Trade, + Lfg, + Roleplay, + Society, + Olthoi, +} + +internal static class ChatSpeech +{ + public static readonly SpeechChannel[] All = Enum.GetValues(); + + /// AC's ChatMessageType for spell words ("Zojak Bor"): speech-shaped, never relayed as speech. + public const int ChatTypeSpellcasting = 0x11; + + public static uint Bit(SpeechChannel ch) => 1u << (int)ch; + + public static string Name(SpeechChannel ch) => ch switch + { + SpeechChannel.Lfg => "LFG", + _ => ch.ToString(), + }; + + /// Accepts channel names and the usual short forms (case-insensitive). + public static bool TryParseName(string? text, out SpeechChannel ch) + { + ch = SpeechChannel.Local; + if (string.IsNullOrWhiteSpace(text)) return false; + switch (text.Trim().ToLowerInvariant()) + { + case "local": case "say": case "area": ch = SpeechChannel.Local; return true; + case "tell": case "tells": case "t": ch = SpeechChannel.Tell; return true; + case "fellowship": case "fellow": case "f": ch = SpeechChannel.Fellowship; return true; + case "allegiance": case "alleg": case "a": ch = SpeechChannel.Allegiance; return true; + case "patron": case "p": ch = SpeechChannel.Patron; return true; + case "vassals": case "vassal": case "v": ch = SpeechChannel.Vassals; return true; + case "covassals": case "covassal": case "c": ch = SpeechChannel.Covassals; return true; + case "monarch": case "m": ch = SpeechChannel.Monarch; return true; + case "general": case "cg": case "g": ch = SpeechChannel.General; return true; + case "trade": case "ct": ch = SpeechChannel.Trade; return true; + case "lfg": case "looking for group": case "clfg": ch = SpeechChannel.Lfg; return true; + case "roleplay": case "rp": case "crp": ch = SpeechChannel.Roleplay; return true; + case "society": case "cs": ch = SpeechChannel.Society; return true; + case "olthoi": case "co": ch = SpeechChannel.Olthoi; return true; + default: return false; + } + } + + /// Channel implied by an inbound chat type; null for generic types (Channels / Social). + public static SpeechChannel? FromChatType(int chatType) => chatType switch + { + 0x02 => SpeechChannel.Local, + 0x03 => SpeechChannel.Tell, + 0x12 => SpeechChannel.Allegiance, + 0x13 => SpeechChannel.Fellowship, + 0x1B => SpeechChannel.General, + 0x1C => SpeechChannel.Trade, + 0x1D => SpeechChannel.Lfg, + 0x1E => SpeechChannel.Roleplay, + 0x20 => SpeechChannel.Olthoi, + 0x21 => SpeechChannel.Society, + _ => null, + }; + + // "[General] " style tab prefix some servers / chat options put in front of channel lines. + private static readonly Regex RxBracket = new(@"^\[(?[A-Za-z ]{1,24})\]\s*", RegexOptions.CultureInvariant, + TimeSpan.FromMilliseconds(20)); + + // "You say ...", "You tell Bob, ..." - the server echo of your own lines. + private static readonly Regex RxOwn = new(@"^You\s+(?:say|tell)\b(?[^""]*)""(?.*)""\s*$", + RegexOptions.Singleline | RegexOptions.CultureInvariant, TimeSpan.FromMilliseconds(20)); + + // "Bob says, "..."" / "Bob says on the General channel, "..."" / "Bob tells you, "..."" + private static readonly Regex RxSpeech = new(@"^(?.+?)\s+(?says|tells)\b(?[^""]*)""(?.*)""\s*$", + RegexOptions.Singleline | RegexOptions.CultureInvariant, TimeSpan.FromMilliseconds(20)); + + private static readonly Regex RxOnChannel = new(@"on the (?[A-Za-z ]+?) channel", + RegexOptions.IgnoreCase | RegexOptions.CultureInvariant, TimeSpan.FromMilliseconds(20)); + + private static readonly Regex RxEscape = new(@"<([0-9a-fA-F]{4})>", RegexOptions.CultureInvariant, + TimeSpan.FromMilliseconds(20)); + + /// + /// Splits a chat line (AC's name links already stripped) into channel, speaker and message. + /// The channel comes from, in order: a "[Name]" prefix, "on the X channel", "tells you", the + /// chat type, then words like "patron" / "vassal". False for anything that isn't player speech, + /// and for spell words. + /// + public static bool TryParse(string? text, int chatType, out SpeechChannel channel, + out string speaker, out string message, out bool own) + { + channel = SpeechChannel.Local; + speaker = message = string.Empty; + own = false; + if (chatType == ChatTypeSpellcasting || string.IsNullOrEmpty(text)) return false; + + string t = text.Trim(); + if (t.Length < 6 || t.IndexOf('"') < 0) return false; + try + { + SpeechChannel? hint = null; + var b = RxBracket.Match(t); + if (b.Success && TryParseName(b.Groups["b"].Value, out var bc)) + { + hint = bc; + t = t.Substring(b.Length); + } + + string mid; + bool tellsYou; + var mo = RxOwn.Match(t); + if (mo.Success) + { + own = true; + speaker = "You"; + mid = mo.Groups["mid"].Value; + message = mo.Groups["msg"].Value; + tellsYou = t.StartsWith("You tell", StringComparison.OrdinalIgnoreCase); + } + else + { + var m = RxSpeech.Match(t); + if (!m.Success) return false; + speaker = m.Groups["name"].Value.Trim().TrimStart('+'); + mid = m.Groups["mid"].Value; + message = m.Groups["msg"].Value; + tellsYou = m.Groups["verb"].Value == "tells" && mid.TrimStart().StartsWith("you", StringComparison.OrdinalIgnoreCase); + if (speaker.Length == 0 || speaker.Length > 40) return false; + } + + SpeechChannel? ch = hint; + if (ch == null) + { + var oc = RxOnChannel.Match(mid); + if (oc.Success && TryParseName(oc.Groups["ch"].Value, out var named)) ch = named; + } + if (ch == null && tellsYou) ch = SpeechChannel.Tell; + ch ??= FromChatType(chatType); + ch ??= FromWords(mid); + if (ch == null) return false; + + channel = ch.Value; + message = Decode(message).Trim(); + return message.Length > 0; + } + catch (RegexMatchTimeoutException) + { + return false; + } + } + + private static SpeechChannel? FromWords(string mid) + { + string m = mid.ToLowerInvariant(); + if (m.Contains("covassal")) return SpeechChannel.Covassals; + if (m.Contains("vassal")) return SpeechChannel.Vassals; + if (m.Contains("patron")) return SpeechChannel.Patron; + if (m.Contains("monarch")) return SpeechChannel.Monarch; + if (m.Contains("fellowship")) return SpeechChannel.Fellowship; + if (m.Contains("allegiance")) return SpeechChannel.Allegiance; + return null; + } + + /// + /// Expands AC's "<c2dc>" escapes (characters above Latin-1 travel as UTF-16 hex in chat) + /// into the characters they stand for. + /// + public static string Decode(string text) + { + if (string.IsNullOrEmpty(text) || text.IndexOf('<') < 0) return text ?? string.Empty; + try + { + return RxEscape.Replace(text, m => + { + int cp = int.Parse(m.Groups[1].Value, NumberStyles.HexNumber, CultureInfo.InvariantCulture); + return cp is > 0 and <= 0xFFFF ? ((char)cp).ToString() : m.Value; + }); + } + catch (RegexMatchTimeoutException) + { + return text; + } + } +} diff --git a/src/RynthCore.Engine/UI/Data/Discord/DiscordClient.cs b/src/RynthCore.Engine/UI/Data/Discord/DiscordClient.cs new file mode 100644 index 0000000..6163806 --- /dev/null +++ b/src/RynthCore.Engine/UI/Data/Discord/DiscordClient.cs @@ -0,0 +1,227 @@ +// ============================================================================ +// RynthCore.Engine - UI/Data/Discord/DiscordClient.cs +// Posts relay messages to Discord. NativeAOT-safe: request JSON is written +// with Utf8JsonWriter and responses are read with JsonDocument (no +// reflection serialization). +// +// webhook POST {webhook url} (no auth header; the URL is the secret) +// bot POST https://discord.com/api/v10/channels/{id}/messages Authorization: Bot {token} +// +// Every message sets allowed_mentions.parse = [] (nobody is pinged) and +// SUPPRESS_EMBEDS (no link previews). 429 returns the wait Discord asks for. +// 400 / 401 / 403 / 404 are permanent: the relay pauses the route so a bad +// credential isn't retried (Discord temporarily bans clients that keep +// sending invalid requests). +// ============================================================================ + +using System; +using System.Globalization; +using System.IO; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; + +namespace RynthCore.Engine.UI.Data.Discord; + +/// +/// Outcome of one post. is how long to wait before the next post to +/// this route (rate limit or bucket exhausted); means stop until the +/// settings change. +/// +internal readonly record struct DiscordSendResult(bool Ok, int Status, int RetryAfterMs, bool Permanent, string Error) +{ + public static DiscordSendResult Fail(string error, bool permanent = false, int status = 0, int retryAfterMs = 0) + => new(false, status, retryAfterMs, permanent, error); +} + +internal static class DiscordClient +{ + public const string ApiBase = "https://discord.com/api/v10"; + + /// MessageFlags.SUPPRESS_EMBEDS: chat links don't unfurl into previews. + private const int FlagSuppressEmbeds = 1 << 2; + + // Built on first post, so an engine that never relays never opens a socket. + private static readonly Lazy Http = new(CreateHttp, LazyThreadSafetyMode.ExecutionAndPublication); + + private static HttpClient CreateHttp() + { + var handler = new SocketsHttpHandler + { + AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate, + PooledConnectionLifetime = TimeSpan.FromMinutes(5), + AllowAutoRedirect = false, + }; + var http = new HttpClient(handler) { Timeout = TimeSpan.FromSeconds(15) }; + // Discord asks bots to send "DiscordBot (url, version)"; webhooks accept it too. + http.DefaultRequestHeaders.UserAgent.ParseAdd("DiscordBot (https://aelrynth.com, 1.0) RynthChat-Relay"); + http.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + return http; + } + + /// + /// Posts through a webhook. must + /// already be validated by . Never throws. + /// + public static Task PostWebhookAsync(string webhookUrl, string content, string displayName, CancellationToken ct) + { + if (!DiscordFormat.TryNormalizeWebhookUrl(webhookUrl, out string url)) + return Task.FromResult(DiscordSendResult.Fail("the saved webhook URL is not a Discord webhook URL", permanent: true)); + string body = BuildBody(content, DiscordFormat.SafeWebhookName(displayName)); + var req = new HttpRequestMessage(HttpMethod.Post, url) + { + Content = new StringContent(body, Encoding.UTF8, "application/json"), + }; + return SendAsync(req, url, ct); + } + + /// Posts as a bot to . Never throws. + public static Task PostBotAsync(string botToken, string channelId, string content, CancellationToken ct) + { + if (!DiscordFormat.LooksLikeBotToken(botToken)) + return Task.FromResult(DiscordSendResult.Fail("the saved bot token doesn't look like a Discord bot token", permanent: true)); + if (!DiscordFormat.IsSnowflake(channelId)) + return Task.FromResult(DiscordSendResult.Fail("the channel ID must be the channel's number (Developer Mode > Copy Channel ID)", permanent: true)); + string body = BuildBody(content, string.Empty); + var req = new HttpRequestMessage(HttpMethod.Post, $"{ApiBase}/channels/{channelId.Trim()}/messages") + { + Content = new StringContent(body, Encoding.UTF8, "application/json"), + }; + req.Headers.TryAddWithoutValidation("Authorization", "Bot " + botToken.Trim()); + return SendAsync(req, botToken.Trim(), ct); + } + + /// {"content":..., "username":..., "allowed_mentions":{"parse":[]}, "flags":4} + internal static string BuildBody(string content, string username) + { + using var ms = new MemoryStream(); + using (var w = new Utf8JsonWriter(ms)) + { + w.WriteStartObject(); + w.WriteString("content", content); + if (username.Length > 0) w.WriteString("username", username); + w.WriteStartObject("allowed_mentions"); + w.WriteStartArray("parse"); + w.WriteEndArray(); + w.WriteEndObject(); + w.WriteNumber("flags", FlagSuppressEmbeds); + w.WriteEndObject(); + } + return Encoding.UTF8.GetString(ms.ToArray()); + } + + private static async Task SendAsync(HttpRequestMessage req, string secret, CancellationToken ct) + { + try + { + using (req) + using (var resp = await Http.Value.SendAsync(req, ct).ConfigureAwait(false)) + { + int status = (int)resp.StatusCode; + string json = await resp.Content.ReadAsStringAsync(ct).ConfigureAwait(false); + int bucketWait = BucketWaitMs(resp.Headers); + + if (resp.IsSuccessStatusCode) return new DiscordSendResult(true, status, bucketWait, false, string.Empty); + + if (status == 429) + { + int wait = ParseRetryAfterMs(json, HeaderValue(resp.Headers, "Retry-After")); + return DiscordSendResult.Fail($"rate limited, waiting {wait / 1000.0:0.0}s", status: status, retryAfterMs: Math.Max(wait, bucketWait)); + } + + string msg = DiscordFormat.Redact(ErrorText(status, json), secret); + return DiscordSendResult.Fail(msg, permanent: IsPermanent(status), status: status, retryAfterMs: bucketWait); + } + } + catch (OperationCanceledException) when (!ct.IsCancellationRequested) + { + return DiscordSendResult.Fail("request timed out"); + } + catch (OperationCanceledException) + { + return DiscordSendResult.Fail("cancelled"); + } + catch (HttpRequestException ex) + { + return DiscordSendResult.Fail("network error: " + DiscordFormat.Redact(ex.Message, secret)); + } + catch (Exception ex) + { + return DiscordSendResult.Fail($"{ex.GetType().Name}: {DiscordFormat.Redact(ex.Message, secret)}"); + } + } + + /// + /// 400 (bad body), 401 (bad token), 403 (no permission), 404 (webhook / channel deleted): + /// retrying the same request can't succeed. + /// + internal static bool IsPermanent(int status) => status is 400 or 401 or 403 or 404; + + /// + /// Wait for a 429, in ms: the JSON "retry_after" (seconds, may be fractional), else the + /// Retry-After header (seconds), else 5 s. Clamped to 0.25 s .. 10 min. + /// + internal static int ParseRetryAfterMs(string? json, string? header) + { + double seconds = -1; + if (!string.IsNullOrWhiteSpace(json)) + { + try + { + using var doc = JsonDocument.Parse(json); + if (doc.RootElement.ValueKind == JsonValueKind.Object + && doc.RootElement.TryGetProperty("retry_after", out var ra) + && ra.ValueKind == JsonValueKind.Number) + seconds = ra.GetDouble(); + } + catch (JsonException) { } + } + if (seconds < 0 && double.TryParse(header, NumberStyles.Float, CultureInfo.InvariantCulture, out double h)) seconds = h; + if (seconds < 0) seconds = 5; + return (int)Math.Clamp(seconds * 1000.0, 250.0, 600_000.0); + } + + /// When the route's bucket is empty (X-RateLimit-Remaining: 0), ms until it resets. + private static int BucketWaitMs(HttpResponseHeaders headers) + { + if (HeaderValue(headers, "X-RateLimit-Remaining") != "0") return 0; + return double.TryParse(HeaderValue(headers, "X-RateLimit-Reset-After"), NumberStyles.Float, CultureInfo.InvariantCulture, out double s) + ? (int)Math.Clamp(s * 1000.0, 0.0, 600_000.0) + : 0; + } + + private static string? HeaderValue(HttpResponseHeaders headers, string name) + { + if (!headers.TryGetValues(name, out var values)) return null; + foreach (string v in values) return v.Trim(); + return null; + } + + private static string ErrorText(int status, string json) + { + string detail = string.Empty; + try + { + if (!string.IsNullOrWhiteSpace(json)) + { + using var doc = JsonDocument.Parse(json); + if (doc.RootElement.ValueKind == JsonValueKind.Object && doc.RootElement.TryGetProperty("message", out var m)) + detail = m.GetString() ?? string.Empty; + } + } + catch (JsonException) { } + + string hint = status switch + { + 401 => " (the token or webhook is invalid)", + 403 => " (the bot can't post in that channel; check its permissions)", + 404 => " (the webhook or channel no longer exists)", + _ => string.Empty, + }; + return $"HTTP {status}{(detail.Length > 0 ? ": " + detail : string.Empty)}{hint}"; + } +} diff --git a/src/RynthCore.Engine/UI/Data/Discord/DiscordFormat.cs b/src/RynthCore.Engine/UI/Data/Discord/DiscordFormat.cs new file mode 100644 index 0000000..45e6b8f --- /dev/null +++ b/src/RynthCore.Engine/UI/Data/Discord/DiscordFormat.cs @@ -0,0 +1,219 @@ +// ============================================================================ +// RynthCore.Engine - UI/Data/Discord/DiscordFormat.cs +// Pure helpers for the Discord relay: Markdown escaping, line formatting, +// message packing, credential-shape checks, the character / keyword filters +// and reading a chat line's "HH:mm:ss" time. No I/O; covered by +// tools/ChatDiscordTests. +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Text; +using System.Text.RegularExpressions; + +namespace RynthCore.Engine.UI.Data.Discord; + +internal static class DiscordFormat +{ + /// Discord rejects message content over 2000 characters. + public const int MaxContent = 2000; + + /// Longest single relayed line; longer chat is cut with an ellipsis. + public const int MaxLine = 1900; + + // discord.com / discordapp.com, optional ptb. / canary., optional /v{n}, then /webhooks/{id}/{token}. + private static readonly Regex RxWebhook = new( + @"^https://(?:(?:ptb|canary)\.)?discord(?:app)?\.com/api/(?:v\d{1,2}/)?webhooks/(?\d{15,22})/(?[A-Za-z0-9_\-]{30,100})/?$", + RegexOptions.CultureInvariant); + + private static readonly Regex RxSnowflake = new(@"^\d{15,22}$", RegexOptions.CultureInvariant); + + // Bot tokens are three base64url segments separated by dots. + private static readonly Regex RxBotToken = new(@"^[A-Za-z0-9_\-]{20,}\.[A-Za-z0-9_\-]{4,}\.[A-Za-z0-9_\-]{20,}$", + RegexOptions.CultureInvariant); + + /// + /// Checks a pasted webhook URL. Only Discord's own webhook endpoints are accepted, so a typo + /// can't send chat to some other server. Returns the URL without any query string. + /// + public static bool TryNormalizeWebhookUrl(string? url, out string normalized) + { + normalized = string.Empty; + if (string.IsNullOrWhiteSpace(url)) return false; + string u = url.Trim(); + int q = u.IndexOfAny(new[] { '?', '#' }); + if (q >= 0) u = u.Substring(0, q); + if (!RxWebhook.IsMatch(u)) return false; + normalized = u.TrimEnd('/'); + return true; + } + + public static bool IsSnowflake(string? id) => !string.IsNullOrWhiteSpace(id) && RxSnowflake.IsMatch(id.Trim()); + + public static bool LooksLikeBotToken(string? token) => !string.IsNullOrWhiteSpace(token) && RxBotToken.IsMatch(token.Trim()); + + /// + /// Escapes inline Discord Markdown so chat text shows literally: emphasis, code, spoilers, + /// quotes, masked links, and the <@id> / <#id> / <t:..> tags. Newlines become + /// spaces. "@everyone" / "@here" also get a zero-width space; allowed_mentions already blocks + /// the ping, this keeps the text from looking live. + /// + public static string Escape(string? text) + { + if (string.IsNullOrEmpty(text)) return string.Empty; + var sb = new StringBuilder(text.Length + 8); + foreach (char c in text) + { + switch (c) + { + case '\\': case '*': case '_': case '~': case '`': case '|': + case '>': case '<': case '[': case ']': + sb.Append('\\').Append(c); + break; + case '\r': case '\n': + sb.Append(' '); + break; + default: + sb.Append(c); + break; + } + } + return sb.Replace("@everyone", "@\u200Beveryone").Replace("@here", "@\u200Bhere").ToString(); + } + + /// + /// One relayed line: optional `HH:mm:ss`, optional [Character], **[Channel] Speaker:** message. + /// A line with no channel or speaker is relayed as plain text. + /// + public static string FormatLine(DateTime time, string? channel, string? speaker, string message, + bool timestamp, string? characterTag) + { + var sb = new StringBuilder(message.Length + 48); + if (timestamp) sb.Append('`').Append(time.ToString("HH:mm:ss", CultureInfo.InvariantCulture)).Append("` "); + if (!string.IsNullOrEmpty(characterTag)) sb.Append('\\').Append('[').Append(Escape(characterTag)).Append("\\] "); + bool hasChannel = !string.IsNullOrEmpty(channel); + bool hasSpeaker = !string.IsNullOrEmpty(speaker); + if (hasChannel || hasSpeaker) + { + sb.Append("**"); + if (hasChannel) sb.Append("\\[").Append(Escape(channel)).Append("\\]"); + if (hasChannel && hasSpeaker) sb.Append(' '); + if (hasSpeaker) sb.Append(Escape(speaker)).Append(':'); + sb.Append("** "); + } + string body = Escape(message); + // Headings, lists and subtext only parse at the start of a line. + if (sb.Length == 0) body = EscapeLineStart(body); + sb.Append(body); + return Truncate(sb.ToString(), MaxLine); + } + + // "# x", "-# x", "- x", "+ x" and "1. x" are block syntax when they open a line. + private static readonly Regex RxBlockStart = new(@"^(?:#{1,3}\s|-#\s|[-+]\s|\d+\.\s)", RegexOptions.CultureInvariant); + + private static string EscapeLineStart(string s) => RxBlockStart.IsMatch(s) ? "\\" + s : s; + + /// Cuts to characters, ending with an ellipsis. + public static string Truncate(string s, int max) + { + if (s.Length <= max) return s; + int cut = max - 1; + // Don't leave a dangling escape backslash or split a surrogate pair at the cut. + if (cut > 0 && char.IsHighSurrogate(s[cut - 1])) cut--; + if (cut > 0 && s[cut - 1] == '\\') cut--; + return s.Substring(0, cut) + "\u2026"; + } + + /// + /// Takes lines from the front of while they fit one message (newline + /// separated, at most characters). Always takes at least one line. + /// + public static string Pack(List lines, out int taken) + { + taken = 0; + if (lines.Count == 0) return string.Empty; + var sb = new StringBuilder(); + foreach (string line in lines) + { + string l = Truncate(line, MaxContent); + int add = l.Length + (sb.Length > 0 ? 1 : 0); + if (taken > 0 && sb.Length + add > MaxContent) break; + if (sb.Length > 0) sb.Append('\n'); + sb.Append(l); + taken++; + } + return sb.ToString(); + } + + /// + /// Webhook display name: Discord refuses names containing "discord" or "clyde" and limits them + /// to 1-80 characters. Returns empty (use the webhook's own name) when the name can't be used. + /// + public static string SafeWebhookName(string? name) + { + if (string.IsNullOrWhiteSpace(name)) return string.Empty; + string n = name.Trim().TrimStart('+'); + if (n.Contains("discord", StringComparison.OrdinalIgnoreCase) || n.Contains("clyde", StringComparison.OrdinalIgnoreCase)) + return string.Empty; + if (n.Equals("everyone", StringComparison.OrdinalIgnoreCase) || n.Equals("here", StringComparison.OrdinalIgnoreCase)) + return string.Empty; + return n.Length > 80 ? n.Substring(0, 80) : n; + } + + /// Splits a comma-separated list into trimmed, non-empty entries. + public static List SplitList(string? csv) + { + var list = new List(); + if (string.IsNullOrWhiteSpace(csv)) return list; + foreach (string part in csv.Split(',')) + { + string p = part.Trim(); + if (p.Length > 0) list.Add(p); + } + return list; + } + + /// True when contains any keyword (case-insensitive), or there are none. + public static bool MatchesKeywords(string text, List keywords) + { + if (keywords.Count == 0) return true; + foreach (string k in keywords) + if (text.Contains(k, StringComparison.OrdinalIgnoreCase)) return true; + return false; + } + + /// True when may relay: the list is blank, or it names the character. + public static bool CharacterAllowed(string onlyCharacters, string character) + { + var names = SplitList(onlyCharacters); + if (names.Count == 0) return true; + string me = (character ?? string.Empty).Trim().TrimStart('+'); + if (me.Length == 0) return false; + foreach (string n in names) + if (string.Equals(n.TrimStart('+'), me, StringComparison.OrdinalIgnoreCase)) return true; + return false; + } + + /// Removes from an error text before it is shown or logged. + public static string Redact(string text, string? secret) + { + if (string.IsNullOrEmpty(text) || string.IsNullOrEmpty(secret)) return text ?? string.Empty; + return text.Replace(secret, "***", StringComparison.Ordinal); + } + + /// + /// The local time a chat line was printed, from its "HH:mm:ss" stamp, on the day closest to + /// (a stamp more than a minute in the future is from yesterday). + /// when the stamp can't be read. + /// + public static DateTime LineTime(string? stamp, DateTime now) + { + if (string.IsNullOrEmpty(stamp) + || !TimeSpan.TryParseExact(stamp.Trim(), @"hh\:mm\:ss", CultureInfo.InvariantCulture, out TimeSpan tod)) + return now; + DateTime t = now.Date + tod; + if (t > now.AddMinutes(1)) t = t.AddDays(-1); + return t; + } +} diff --git a/src/RynthCore.Engine/UI/Data/Discord/DiscordSecrets.cs b/src/RynthCore.Engine/UI/Data/Discord/DiscordSecrets.cs new file mode 100644 index 0000000..babaab5 --- /dev/null +++ b/src/RynthCore.Engine/UI/Data/Discord/DiscordSecrets.cs @@ -0,0 +1,116 @@ +// ============================================================================ +// RynthCore.Engine - UI/Data/Discord/DiscordSecrets.cs +// Windows DPAPI (CurrentUser) protection for the Discord relay's webhook URLs +// and bot tokens. +// +// A webhook URL is itself a credential: anyone holding it can post to the +// channel. Both secrets are kept in rynthchat_discord.json only as base64 +// DPAPI blobs, readable by the Windows user who saved them. Decrypt at the +// moment of use; never log, display or echo the plain text. +// ============================================================================ + +using System; +using System.ComponentModel; +using System.Runtime.InteropServices; +using System.Text; + +namespace RynthCore.Engine.UI.Data.Discord; + +internal static class DiscordSecrets +{ + // Changing this makes every saved secret unreadable, including the ones imported from + // RynthAi 0.5.33's discord.json (same value on purpose). Change it only with a migration. + private static readonly byte[] Entropy = Encoding.UTF8.GetBytes("RynthCore.RynthAi.DiscordRelay.v1"); + + private const int CryptProtectUiForbidden = 0x1; + + /// Encrypts for this Windows user. Empty in, empty out. + public static string Protect(string? plainText) + { + if (string.IsNullOrEmpty(plainText)) return string.Empty; + byte[] plain = Encoding.UTF8.GetBytes(plainText); + try { return Convert.ToBase64String(Transform(plain, protect: true)); } + finally { Array.Clear(plain); } + } + + /// + /// Decrypts a value written by . False when it can't be read on this + /// Windows user (copied from another user or PC, damaged base64, wrong entropy). + /// + public static bool TryUnprotect(string? protectedBase64, out string plainText) + { + plainText = string.Empty; + if (string.IsNullOrEmpty(protectedBase64)) return false; + + byte[] blob; + try { blob = Convert.FromBase64String(protectedBase64); } + catch (FormatException) { return false; } + + byte[]? plain = null; + try + { + plain = Transform(blob, protect: false); + plainText = Encoding.UTF8.GetString(plain); + return true; + } + catch (Exception ex) when (ex is Win32Exception or PlatformNotSupportedException or EntryPointNotFoundException or DllNotFoundException) + { + return false; + } + finally + { + if (plain != null) Array.Clear(plain); + } + } + + private static byte[] Transform(byte[] input, bool protect) + { + GCHandle inputHandle = GCHandle.Alloc(input, GCHandleType.Pinned); + GCHandle entropyHandle = GCHandle.Alloc(Entropy, GCHandleType.Pinned); + var output = new DataBlob(); + try + { + var inputBlob = new DataBlob { cbData = input.Length, pbData = inputHandle.AddrOfPinnedObject() }; + var entropyBlob = new DataBlob { cbData = Entropy.Length, pbData = entropyHandle.AddrOfPinnedObject() }; + + bool ok = 0 != (protect + ? CryptProtectData(ref inputBlob, IntPtr.Zero, ref entropyBlob, IntPtr.Zero, IntPtr.Zero, CryptProtectUiForbidden, ref output) + : CryptUnprotectData(ref inputBlob, IntPtr.Zero, ref entropyBlob, IntPtr.Zero, IntPtr.Zero, CryptProtectUiForbidden, ref output)); + if (!ok) throw new Win32Exception(Marshal.GetLastWin32Error()); + + byte[] result = new byte[output.cbData]; + if (output.cbData > 0) Marshal.Copy(output.pbData, result, 0, output.cbData); + return result; + } + finally + { + if (output.pbData != IntPtr.Zero) + { + // Wipe the native copy (the plain text, when decrypting) before freeing it. + for (int i = 0; i < output.cbData; i++) Marshal.WriteByte(output.pbData, i, 0); + LocalFree(output.pbData); + } + inputHandle.Free(); + entropyHandle.Free(); + } + } + + [StructLayout(LayoutKind.Sequential)] + private struct DataBlob + { + public int cbData; + public IntPtr pbData; + } + + // Win32 BOOL is returned as int so the signatures stay blittable under NativeAOT. + [DllImport("crypt32.dll", SetLastError = true)] + private static extern int CryptProtectData(ref DataBlob pDataIn, IntPtr szDataDescr, ref DataBlob pOptionalEntropy, + IntPtr pvReserved, IntPtr pPromptStruct, int dwFlags, ref DataBlob pDataOut); + + [DllImport("crypt32.dll", SetLastError = true)] + private static extern int CryptUnprotectData(ref DataBlob pDataIn, IntPtr ppszDataDescr, ref DataBlob pOptionalEntropy, + IntPtr pvReserved, IntPtr pPromptStruct, int dwFlags, ref DataBlob pDataOut); + + [DllImport("kernel32.dll")] + private static extern IntPtr LocalFree(IntPtr hMem); +} diff --git a/tools/ChatDiscordTests/ChatDiscordTests.csproj b/tools/ChatDiscordTests/ChatDiscordTests.csproj new file mode 100644 index 0000000..0ad1011 --- /dev/null +++ b/tools/ChatDiscordTests/ChatDiscordTests.csproj @@ -0,0 +1,31 @@ + + + + + Exe + net10.0-windows + enable + enable + true + ChatDiscordTests + + $(NoWarn);CS0649 + + + + + + + + + + + + + diff --git a/tools/ChatDiscordTests/Program.cs b/tools/ChatDiscordTests/Program.cs new file mode 100644 index 0000000..3dfe1bd --- /dev/null +++ b/tools/ChatDiscordTests/Program.cs @@ -0,0 +1,435 @@ +using System.Text.Json; +using RynthCore.Engine.UI.Data.Discord; + +namespace ChatDiscordTests; + +/// +/// RynthChat's Discord relay, the parts that don't need the engine: what a chat line is, which +/// routes take it, how it reads in Discord, scrollback, settings files, the request body and +/// rate-limit waits, and the DPAPI wrapper. Fake webhook URLs and tokens are built at run time +/// (no credential-shaped literals in the source). +/// +internal static class Program +{ + private static int _checks, _failed; + + // A well-formed but fake webhook URL / bot token / channel id. + private static readonly string FakeWebhook = + "https://discord.com/api/webhooks/" + new string('1', 18) + "/" + new string('x', 68); + private static readonly string FakeBotToken = + string.Join(".", new string('A', 24), new string('b', 6), new string('c', 38)); + private static readonly string FakeChannel = new string('7', 19); + + private static int Main() + { + Speech(); + Classify(); + Routing(); + Formatting(); + Times(); + Packing(); + Validation(); + RequestBody(); + Settings(); + Import(); + Secrets(); + Dedup(); + + Console.WriteLine(_failed == 0 && _checks > 0 ? $"PASS ({_checks} checks)" : $"FAIL ({_failed} of {_checks})"); + return _failed == 0 && _checks > 0 ? 0 : 1; + } + + // ── Speech parsing ─────────────────────────────────────────────────── + + private static void Speech() + { + Said("Bob tells you, \"hi there\"", 0x03, SpeechChannel.Tell, "Bob", "hi there", own: false); + Said("You tell Bob, \"yo\"", 0x03, SpeechChannel.Tell, "You", "yo", own: true); + Said("Bob says on the General channel, \"wts pyreal\"", 0x1B, SpeechChannel.General, "Bob", "wts pyreal", own: false); + Said("[Trade] Bob says, \"wtb mana stones\"", 0x00, SpeechChannel.Trade, "Bob", "wtb mana stones", own: false); + Said("Bob says, \"hello\"", 0x02, SpeechChannel.Local, "Bob", "hello", own: false); + Said("+Bob says to your fellowship, \"pull\"", 0x00, SpeechChannel.Fellowship, "Bob", "pull", own: false); + Said("Bob says to your covassals, \"gz\"", 0x00, SpeechChannel.Covassals, "Bob", "gz", own: false); + Said("Bob says to your vassals, \"hi\"", 0x00, SpeechChannel.Vassals, "Bob", "hi", own: false); + Said("Bob says, \"caf<00e9> time\"", 0x12, SpeechChannel.Allegiance, "Bob", "caf\u00e9 time", own: false); + Said("Bob says on the LFG channel, \"lf colo\"", 0x00, SpeechChannel.Lfg, "Bob", "lf colo", own: false); + + NotSpeech("You say, \"Zojak Bor\"", ChatSpeech.ChatTypeSpellcasting); // spell words + NotSpeech("You have gained 500 experience.", 0x00); + NotSpeech("Bob says, \" \"", 0x02); // nothing said + NotSpeech("", 0x02); + NotSpeech(null, 0x02); + NotSpeech("He says \"hi\"", 0x00); // no channel at all + + Check(ChatSpeech.Name(SpeechChannel.Lfg) == "LFG", "LFG is shown upper case"); + Check(ChatSpeech.TryParseName("lfg", out var lfg) && lfg == SpeechChannel.Lfg, "LFG parses back"); + Check(ChatSpeech.TryParseName(" Fellow ", out var fel) && fel == SpeechChannel.Fellowship, "short names parse"); + Check(!ChatSpeech.TryParseName("guild", out _), "unknown names don't parse"); + foreach (var ch in ChatSpeech.All) + Check(ChatSpeech.TryParseName(ChatSpeech.Name(ch), out var back) && back == ch, $"{ch} survives a save"); + Check(ChatSpeech.Decode(" and <0041>") == " and A", "only hex escapes decode"); + } + + private static void Said(string text, int chatType, SpeechChannel ch, string who, string msg, bool own) + { + bool ok = ChatSpeech.TryParse(text, chatType, out var c, out string s, out string m, out bool o); + Check(ok, $"speech: {text}"); + if (!ok) return; + Check(c == ch, $"{text} -> {ch} (got {c})"); + Check(s == who, $"{text} speaker {who} (got {s})"); + Check(m == msg, $"{text} message \"{msg}\" (got \"{m}\")"); + Check(o == own, $"{text} own={own}"); + } + + private static void NotSpeech(string? text, int chatType) + => Check(!ChatSpeech.TryParse(text, chatType, out _, out _, out _, out _), $"not speech: {text ?? "(null)"}"); + + // ── Line classification ────────────────────────────────────────────── + + private static void Classify() + { + Check(ChatDiscordLogic.TryClassify("You tell Bob, \"omw\"", 0x03, "Alice", out var mine), "own tell classifies"); + Check(mine.Own && mine.Speaker == "Alice" && mine.Speech == SpeechChannel.Tell, "own lines are shown as the character"); + Check(ChatDiscordLogic.TryClassify("You tell Bob, \"omw\"", 0x03, "", out var anon) && anon.Speaker == "You", + "own lines before login keep \"You\""); + + Check(ChatDiscordLogic.TryClassify("You gain 500 xp.", 0x00, "Alice", out var plain), "plain text classifies"); + Check(plain.Speech == null && plain.Speaker.Length == 0 && plain.Message == "You gain 500 xp.", "plain text has no channel"); + Check(plain.Haystack == "You gain 500 xp.", "plain haystack is the text"); + Check(ChatDiscordLogic.TryClassify("Bob tells you, \"rare drop\"", 0x03, "", out var tell) && tell.Haystack == "Bob rare drop", + "speech haystack is speaker + message"); + + Check(!ChatDiscordLogic.TryClassify(" ", 0x00, "Alice", out _), "blank lines are skipped"); + Check(!ChatDiscordLogic.TryClassify(null, 0x00, "Alice", out _), "null lines are skipped"); + } + + // ── Which routes take a line ───────────────────────────────────────── + + private static void Routing() + { + var route = Route(DiscordRoute.DefaultSpeechMask(), "System"); + + Check(ChatDiscordLogic.Wants(route, SpeechChannel.Tell, _ => false, out string l1) && l1 == "Tell", "default routes take tells"); + Check(ChatDiscordLogic.Wants(route, SpeechChannel.Monarch, _ => false, out _), "default routes take the allegiance channels"); + Check(!ChatDiscordLogic.Wants(route, SpeechChannel.Local, _ => false, out _), "default routes skip local"); + Check(!ChatDiscordLogic.Wants(route, SpeechChannel.General, _ => false, out _), "default routes skip General"); + + Check(ChatDiscordLogic.Wants(route, null, t => t == "System", out string l2) && l2 == "System", + "a line in a ticked tab is taken, labelled with the tab"); + Check(ChatDiscordLogic.Wants(route, SpeechChannel.Local, t => t == "System", out string l3) && l3 == "Local", + "speech taken through a tab keeps its channel label"); + Check(!ChatDiscordLogic.Wants(route, null, t => t == "Combat", out _), "lines only in other tabs are skipped"); + + var none = Route(0); + Check(!ChatDiscordLogic.Wants(none, SpeechChannel.Tell, _ => true, out _), "a route with nothing ticked takes nothing"); + + var all = Route(DiscordRoute.AllSpeechMask()); + foreach (var ch in ChatSpeech.All) + Check(all.RelaysSpeech(ch), $"all-channels route relays {ch}"); + + Check(DiscordFormat.MatchesKeywords("Bob rare drop", DiscordFormat.SplitList("loot, RARE ,")), "keywords match case-insensitively"); + Check(!DiscordFormat.MatchesKeywords("Bob hi", DiscordFormat.SplitList("loot,rare")), "keywords filter"); + Check(DiscordFormat.MatchesKeywords("anything", DiscordFormat.SplitList(" , ")), "no keywords = everything"); + + Check(DiscordFormat.CharacterAllowed("", "Alice"), "blank allow-list allows everyone"); + Check(DiscordFormat.CharacterAllowed("bob, +Alice", "Alice"), "allow-list match (case, + prefix)"); + Check(!DiscordFormat.CharacterAllowed("bob", "Alice"), "allow-list excludes others"); + Check(!DiscordFormat.CharacterAllowed("bob", ""), "allow-list needs a character name"); + + var s = new ChatDiscordSettings { BatchMs = 1500, MinIntervalMs = 2000 }; + var own = new DiscordRoute { CustomPace = true, BatchMs = 0, MinIntervalMs = 60_000 }; + Check(s.BatchFor(route) == 1500 && s.IntervalFor(route) == 2000, "routes use the relay's pacing by default"); + Check(s.BatchFor(own) == 0 && s.IntervalFor(own) == 60_000, "own pacing overrides it"); + + Check(!new DiscordRoute().HasSecret, "a new route has no secret"); + Check(new DiscordRoute { WebhookProtected = "blob" }.HasSecret, "webhook routes need the webhook"); + Check(!new DiscordRoute { Mode = DiscordRoute.ModeBot, BotTokenProtected = "blob" }.HasSecret, "bot routes need a channel too"); + Check(new DiscordRoute { Mode = DiscordRoute.ModeBot, BotTokenProtected = "blob", ChannelId = FakeChannel }.HasSecret, "bot route ready"); + } + + private static DiscordRoute Route(uint speech, params string[] tabs) + => new() { SpeechMask = speech, Tabs = tabs }; + + // ── Discord text ───────────────────────────────────────────────────── + + private static void Formatting() + { + var at = new DateTime(2026, 10, 11, 12, 34, 56); + var s = new ChatDiscordSettings { IncludeTimestamp = true, TagCharacter = false }; + ChatDiscordLogic.TryClassify("Bob tells you, \"hi *there*\"", 0x03, "Alice", out var tell); + Same(ChatDiscordLogic.Format(s, at, tell, "Tell", "Alice"), "`12:34:56` **\\[Tell\\] Bob:** hi \\*there\\*", "speech line"); + + s.IncludeTimestamp = false; + s.TagCharacter = true; + Same(ChatDiscordLogic.Format(s, at, tell, "Tell", "Alice"), "\\[Alice\\] **\\[Tell\\] Bob:** hi \\*there\\*", "character tag"); + Same(ChatDiscordLogic.Format(s, at, tell, "Tell", ""), "**\\[Tell\\] Bob:** hi \\*there\\*", "no tag before login"); + + s.TagCharacter = false; + ChatDiscordLogic.TryClassify("# You found a rare!", 0x00, "Alice", out var plain); + Same(ChatDiscordLogic.Format(s, at, plain, "", "Alice"), "\\# You found a rare!", "plain text can't become a heading"); + Same(ChatDiscordLogic.Format(s, at, plain, "System", "Alice"), "**\\[System\\]** # You found a rare!", "tab label"); + + string pinged = DiscordFormat.Escape("@everyone look <@123> [x](y)"); + Check(!pinged.Contains("@everyone"), "@everyone is defused"); + Check(pinged.Contains("\\<@123\\>") && pinged.Contains("\\[x\\]"), "mentions and links are escaped"); + Same(DiscordFormat.Escape("a\r\nb"), "a b", "newlines flatten"); + + string longLine = DiscordFormat.FormatLine(at, null, null, new string('z', 5000), false, null); + Check(longLine.Length == DiscordFormat.MaxLine && longLine.EndsWith('\u2026'), "long lines are cut"); + string cut = DiscordFormat.Truncate(new string('a', 8) + "\\*", 10); + Check(cut.Length <= 10 && !cut.TrimEnd('\u2026').EndsWith('\\'), "cuts don't strand an escape"); + + Same(DiscordFormat.SafeWebhookName("+Bob"), "Bob", "webhook name drops +"); + Same(DiscordFormat.SafeWebhookName("Discord Bob"), "", "Discord refuses names with 'discord'"); + Same(DiscordFormat.SafeWebhookName("everyone"), "", "no 'everyone' name"); + Check(DiscordFormat.SafeWebhookName(new string('n', 100)).Length == 80, "webhook names cap at 80"); + } + + // ── Line times and scrollback ──────────────────────────────────────── + + private static void Times() + { + var now = new DateTime(2026, 10, 11, 0, 0, 30); + Check(DiscordFormat.LineTime("23:59:50", now) == new DateTime(2026, 10, 10, 23, 59, 50), "a late stamp just after midnight is yesterday"); + Check(DiscordFormat.LineTime("00:00:20", now) == new DateTime(2026, 10, 11, 0, 0, 20), "earlier today"); + Check(DiscordFormat.LineTime("00:01:00", now) == new DateTime(2026, 10, 11, 0, 1, 0), "a little clock skew stays today"); + Check(DiscordFormat.LineTime("noon", now) == now, "unreadable stamps are now"); + Check(DiscordFormat.LineTime(null, now) == now, "missing stamps are now"); + + var since = new DateTime(2026, 10, 11, 10, 0, 0, 700); + Check(!ChatDiscordLogic.IsBacklog(new DateTime(2026, 10, 11, 10, 0, 0), since), "the start second is live"); + Check(ChatDiscordLogic.IsBacklog(new DateTime(2026, 10, 11, 9, 59, 59), since), "older lines are scrollback"); + Check(!ChatDiscordLogic.IsBacklog(new DateTime(2026, 10, 11, 10, 5, 0), since), "newer lines are live"); + } + + // ── Batching ───────────────────────────────────────────────────────── + + private static void Packing() + { + var lines = new List { new('a', 900), new('b', 900), new('c', 900) }; + string first = DiscordFormat.Pack(lines, out int taken); + Check(taken == 2 && first.Length == 1801, $"two 900-char lines fit one message (took {taken}, {first.Length} chars)"); + + var huge = new List { new('h', 2500), "next" }; + string one = DiscordFormat.Pack(huge, out int t2); + Check(t2 == 1 && one.Length == DiscordFormat.MaxContent, "an oversized line still goes, cut to 2000"); + + Check(DiscordFormat.Pack(new List(), out int t3) == string.Empty && t3 == 0, "nothing to pack"); + } + + // ── Pasted values ──────────────────────────────────────────────────── + + private static void Validation() + { + Check(DiscordFormat.TryNormalizeWebhookUrl(FakeWebhook, out string n1) && n1 == FakeWebhook, "webhook URL accepted"); + Check(DiscordFormat.TryNormalizeWebhookUrl(" " + FakeWebhook + "/?wait=true ", out string n2) && n2 == FakeWebhook, + "query and trailing slash are dropped"); + Check(DiscordFormat.TryNormalizeWebhookUrl(FakeWebhook.Replace("discord.com", "ptb.discordapp.com").Replace("/api/", "/api/v10/"), out _), + "ptb / discordapp / versioned URLs accepted"); + Check(!DiscordFormat.TryNormalizeWebhookUrl(FakeWebhook.Replace("https:", "http:"), out _), "plain http refused"); + Check(!DiscordFormat.TryNormalizeWebhookUrl(FakeWebhook.Replace("discord.com", "discord.com.example.net"), out _), "other hosts refused"); + Check(!DiscordFormat.TryNormalizeWebhookUrl("", out _), "blank refused"); + + Check(DiscordFormat.LooksLikeBotToken(FakeBotToken), "bot token shape accepted"); + Check(!DiscordFormat.LooksLikeBotToken("Bot " + FakeBotToken), "the 'Bot ' prefix isn't part of the token"); + Check(!DiscordFormat.LooksLikeBotToken("short.x.y"), "short tokens refused"); + Check(DiscordFormat.IsSnowflake(FakeChannel), "channel id accepted"); + Check(!DiscordFormat.IsSnowflake("#general"), "channel names refused"); + + string secret = new string('s', 40); + Same(DiscordFormat.Redact("error near " + secret, secret), "error near ***", "secrets are redacted"); + Same(DiscordFormat.Redact("no secret here", ""), "no secret here", "nothing to redact"); + } + + // ── Request body and status handling ───────────────────────────────── + + private static void RequestBody() + { + using (var doc = JsonDocument.Parse(DiscordClient.BuildBody("line \"one\"\nline two", "Alice"))) + { + var root = doc.RootElement; + Check(root.GetProperty("content").GetString() == "line \"one\"\nline two", "content round-trips"); + Check(root.GetProperty("username").GetString() == "Alice", "username sent"); + Check(root.GetProperty("allowed_mentions").GetProperty("parse").GetArrayLength() == 0, "no mentions can ping"); + Check(root.GetProperty("flags").GetInt32() == 4, "embeds suppressed"); + } + using (var doc = JsonDocument.Parse(DiscordClient.BuildBody("x", ""))) + Check(!doc.RootElement.TryGetProperty("username", out _), "no username when blank (bot / webhook default)"); + + Check(DiscordClient.ParseRetryAfterMs("{\"retry_after\":1.5,\"global\":false}", null) == 1500, "retry_after from JSON"); + Check(DiscordClient.ParseRetryAfterMs(null, "3") == 3000, "Retry-After header"); + Check(DiscordClient.ParseRetryAfterMs("not json", null) == 5000, "unknown wait is 5 s"); + Check(DiscordClient.ParseRetryAfterMs("{\"retry_after\":0.01}", null) == 250, "waits at least 0.25 s"); + Check(DiscordClient.ParseRetryAfterMs("{\"retry_after\":99999}", null) == 600_000, "waits at most 10 min"); + + foreach (int st in new[] { 400, 401, 403, 404 }) Check(DiscordClient.IsPermanent(st), $"HTTP {st} pauses the route"); + foreach (int st in new[] { 429, 500, 502, 503 }) Check(!DiscordClient.IsPermanent(st), $"HTTP {st} is retried"); + } + + // ── Settings file ──────────────────────────────────────────────────── + + private static void Settings() + { + string dir = TempDir(); + try + { + string path = Path.Combine(dir, "rynthchat_discord.json"); + + var fresh = ChatDiscordStore.Load(path, legacyPath: null, out string n0); + Check(!fresh.Enabled && fresh.Routes.Length == 0 && n0.Length == 0, "no file: defaults, off"); + + var s = new ChatDiscordSettings + { + Enabled = true, + OnlyCharacters = "Alice", + SkipOwn = true, + TagCharacter = true, + BatchMs = 999_999, // clamped on load + MinIntervalMs = 5, // clamped on load + Routes = new[] + { + new DiscordRoute + { + Name = "Guild", Mode = DiscordRoute.ModeBot, ChannelId = FakeChannel, BotTokenProtected = "blob", + SpeechMask = ChatSpeech.Bit(SpeechChannel.Tell) | ChatSpeech.Bit(SpeechChannel.Lfg), + Tabs = new[] { "System", "Loot" }, Keywords = "rare", CustomPace = true, BatchMs = 0, MinIntervalMs = 30_000, + }, + new DiscordRoute { Name = " ", SpeechMask = 0 }, + }, + }; + string json = ChatDiscordStore.Serialize(s); + Check(json.Contains("\"speech\"") && json.Contains("\"LFG\""), "speech channels are saved by name"); + Check(!json.Contains("speechMask", StringComparison.OrdinalIgnoreCase), "the runtime mask isn't saved"); + Check(!json.Contains("hasSecret", StringComparison.OrdinalIgnoreCase) && !json.Contains("\"status\""), "runtime state isn't saved"); + ChatDiscordStore.Write(path, json); + Check(Directory.GetFiles(dir, "*.tmp").Length == 0, "the temp file is swapped in"); + + var back = ChatDiscordStore.Load(path, legacyPath: null, out string n1); + Check(n1.Length == 0, "clean load has no note"); + Check(back.Enabled && back.SkipOwn && back.TagCharacter && back.OnlyCharacters == "Alice", "switches round-trip"); + Check(back.BatchMs == ChatDiscordSettings.BatchMaxMs, "batch window clamped"); + Check(back.MinIntervalMs == ChatDiscordSettings.IntervalMinMs, "message spacing clamped"); + Check(back.Routes.Length == 2, "routes round-trip"); + var g = back.Routes[0]; + Check(g.Name == "Guild" && g.Mode == DiscordRoute.ModeBot && g.ChannelId == FakeChannel && g.BotTokenProtected == "blob", + "route connection round-trips"); + Check(g.RelaysSpeech(SpeechChannel.Tell) && g.RelaysSpeech(SpeechChannel.Lfg) && !g.RelaysSpeech(SpeechChannel.Fellowship), + "speech channels round-trip"); + Check(g.Tabs.SequenceEqual(new[] { "System", "Loot" }) && g.Keywords == "rare", "tabs and keywords round-trip"); + Check(g.CustomPace && g.BatchMs == 0 && g.MinIntervalMs == 30_000, "route pacing round-trips"); + Check(back.Routes[1].Name == "Discord", "blank route names get a name"); + Check(back.Routes[1].SpeechMask == 0, "a route with every channel unticked stays empty"); + + // Hand-edited file: no speech list means the defaults; bad values repaired. + File.WriteAllText(path, "{ \"enabled\": true, \"routes\": [ { \"name\": \"x\", \"mode\": \"carrier pigeon\", " + + "\"tabs\": [\"System\", \"system\", \" \", null] }, null ], \"maxQueue\": 1 }"); + var hand = ChatDiscordStore.Load(path, legacyPath: null, out _); + Check(hand.Routes.Length == 1, "null routes dropped"); + Check(hand.Routes[0].Mode == DiscordRoute.ModeWebhook, "unknown modes become webhook"); + Check(hand.Routes[0].SpeechMask == DiscordRoute.DefaultSpeechMask(), "no speech list = the defaults"); + Check(hand.Routes[0].Tabs.Length == 1, $"tabs de-duplicated (got {hand.Routes[0].Tabs.Length})"); + Check(hand.MaxQueue == ChatDiscordSettings.QueueMin, "queue size clamped"); + + // A damaged file: defaults, a note for the log, and a copy kept for the user. + File.WriteAllText(path, "{ not json"); + var bad = ChatDiscordStore.Load(path, legacyPath: null, out string n2); + Check(!bad.Enabled && bad.Routes.Length == 0, "damaged file: defaults"); + Check(n2.Contains("unreadable"), "damaged file is reported"); + Check(Directory.GetFiles(dir, "*.unreadable-*.json").Length == 1, "damaged file is kept aside"); + } + finally { TryDelete(dir); } + } + + // ── RynthAi 0.5.33 import ──────────────────────────────────────────── + + private static void Import() + { + string dir = TempDir(); + try + { + string path = Path.Combine(dir, "rynthchat_discord.json"); + string legacy = Path.Combine(dir, "discord.json"); + // RynthAi wrote PascalCase fields. + File.WriteAllText(legacy, "{ \"Enabled\": true, \"SkipOwn\": true, \"BatchMs\": 3000, \"OnlyCharacters\": \"Alice\", " + + "\"ShowWindow\": true, \"Routes\": [ { \"Name\": \"Guild\", \"Enabled\": false, \"Mode\": \"bot\", " + + $"\"ChannelId\": \"{FakeChannel}\", \"BotTokenProtected\": \"blob\", \"Channels\": [\"Tell\", \"LFG\"], " + + "\"IncludeOther\": true, \"Keywords\": \"rare\" }, { \"Name\": \"Fellow\" } ] }"); + + var s = ChatDiscordStore.Load(path, legacy, out string note); + Check(note.Contains("imported 2 route"), $"import is reported (\"{note}\")"); + Check(s.Enabled && s.SkipOwn && s.BatchMs == 3000 && s.OnlyCharacters == "Alice", "relay switches imported"); + Check(s.Routes.Length == 2, "routes imported"); + var g = s.Routes[0]; + Check(!g.Enabled && g.Mode == DiscordRoute.ModeBot && g.ChannelId == FakeChannel && g.BotTokenProtected == "blob", + "route connection imported"); + Check(g.SpeechMask == (ChatSpeech.Bit(SpeechChannel.Tell) | ChatSpeech.Bit(SpeechChannel.Lfg)), "channels become speech channels"); + Check(g.Tabs.SequenceEqual(new[] { "Other" }), "IncludeOther becomes the Other tab"); + Check(s.Routes[1].SpeechMask == DiscordRoute.DefaultSpeechMask() && s.Routes[1].Tabs.Length == 0, + "a route with no channel list gets the defaults"); + + // Once the engine has its own file, RynthAi's is never read again. + ChatDiscordStore.Write(path, ChatDiscordStore.Serialize(new ChatDiscordSettings())); + var mine = ChatDiscordStore.Load(path, legacy, out string n2); + Check(!mine.Enabled && mine.Routes.Length == 0 && n2.Length == 0, "the engine's own file wins"); + + Check(ChatDiscordStore.ImportRynthAi("null") == null, "empty import is null"); + } + finally { TryDelete(dir); } + } + + // ── DPAPI ──────────────────────────────────────────────────────────── + + private static void Secrets() + { + string blob = DiscordSecrets.Protect(FakeWebhook); + Check(blob.Length > 0 && !blob.Contains(FakeWebhook) && !blob.Contains("webhooks"), "protected blobs hide the secret"); + Check(DiscordSecrets.TryUnprotect(blob, out string plain) && plain == FakeWebhook, "protect / unprotect round-trip"); + Check(DiscordSecrets.Protect(FakeWebhook) != blob, "each protect is salted"); + + byte[] raw = Convert.FromBase64String(blob); + raw[raw.Length / 2] ^= 0x55; + Check(!DiscordSecrets.TryUnprotect(Convert.ToBase64String(raw), out _), "damaged blobs don't open"); + Check(!DiscordSecrets.TryUnprotect("not base64 !!", out _), "garbage doesn't open"); + Check(!DiscordSecrets.TryUnprotect("", out _), "empty doesn't open"); + Check(DiscordSecrets.Protect("") == string.Empty && DiscordSecrets.Protect(null) == string.Empty, "empty in, empty out"); + } + + // ── Repeat filter ──────────────────────────────────────────────────── + + private static void Dedup() + { + ChatDiscordLogic.TryClassify("Bob tells you, \"hi\"", 0x03, "", out var a); + ChatDiscordLogic.TryClassify("Bob tells you, \"hi!\"", 0x03, "", out var b); + Check(ChatDiscordLogic.DedupKey(a, "Tell") != ChatDiscordLogic.DedupKey(b, "Tell"), "different lines, different keys"); + Check(ChatDiscordLogic.DedupKey(a, "Tell") != ChatDiscordLogic.DedupKey(a, "General"), "the label is part of the key"); + + var recent = new Dictionary { ["old"] = 1_000, ["new"] = 9_000 }; + ChatDiscordLogic.PruneRecent(recent, now: 10_000, windowMs: 5_000); + Check(!recent.ContainsKey("old") && recent.ContainsKey("new"), "old repeat entries are pruned"); + } + + // ── Helpers ────────────────────────────────────────────────────────── + + private static string TempDir() + { + string dir = Path.Combine(Path.GetTempPath(), "ChatDiscordTests-" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(dir); + return dir; + } + + private static void TryDelete(string dir) + { + try { Directory.Delete(dir, recursive: true); } catch { } + } + + private static void Same(string got, string want, string what) + => Check(got == want, $"{what}: want \"{want}\", got \"{got}\""); + + private static void Check(bool ok, string what) + { + _checks++; + if (ok) return; + _failed++; + Console.WriteLine("FAIL: " + what); + } +}