// IltWikiGuide.cs - RynthILT's quest guide from the Leaftide wiki, opt-in (2026-11-27). // // The server's wiki shows no page without a login. A player who has a wiki login (and is willing to // use it) can let RynthILT read the wiki's quest pages with it, for RynthOracle's Guide tab, which gets // the guide through "RynthServer.QuestGuide" (Plugins/Shared/ServerQuestGuideHost.cs). OFF by default: // nothing is fetched and nothing is saved until the player signs in, in /ilt settings > Leaftide wiki // quest guide (or RynthOracle's Guide tab > "Its settings", which opens it). // - Sign in: the wiki's address (a setting with no default: RynthILT ships no wiki address), a login // name and a bot password. The sign-in is tried first; only a sign-in that works is saved // (WikiLoginStore: this PC only, DPAPI for this Windows user). Then the guide is read. // - The guide is saved per wiki (Wiki\wiki-guide-.json) and read again at login on ILT when it is // a day old (a switch), or on Refresh guide (at most every 5 minutes). Reads are spaced out // (WikiClient: the site's Crawl-delay, else 10 s between requests) and fetch only edited pages. // - Sign out stops a read and deletes the saved sign-in and the saved guide. // - "/ilt wiki [status|signin|signout|refresh|address |auto on|off|help]" answers in chat. The // password is never taken in chat. // Threads: Tick, the commands and the UI requests run on the plugin tick (the UI queues them from the // render thread); a sign-in or read runs on a pool thread and hands its result back through fields the // tick takes. The UI reads the volatile fields only. using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.IO; using System.Net.Http; using System.Text.Json; using System.Threading; using System.Threading.Tasks; using RynthCore.Plugin.Shared; namespace RynthCore.Plugin.RynthILT.IltWiki; internal sealed class IltWikiGuide { /// What RynthOracle calls the guide ("Leaftide Wiki"). public const string Tag = "Leaftide"; public const string PluginName = "RynthILT"; public const string SettingsFile = "wiki-settings.json"; public static readonly TimeSpan RefreshAfter = TimeSpan.FromHours(24); public static readonly TimeSpan RefreshCooldown = TimeSpan.FromMinutes(5); public const int MaxUserLength = 120; public const int MaxPasswordLength = 200; private readonly Func _handler; private readonly Func? _delay; private readonly Func _utcNow; private readonly Action _say; private readonly Action _log; private readonly ConcurrentQueue _requests = new(); private readonly ConcurrentQueue<(string Text, bool Ok)> _messages = new(); private CancellationTokenSource? _cts; private Task? _task; private volatile QuestGuide? _ready; private DateTime _lastStartUtc = DateTime.MinValue; private bool _loginReadDone; private string _published = string.Empty; private int _guideRevision; // Read by the UI (render thread). private volatile string _status = "off: not signed in"; private volatile string _user = string.Empty; private volatile bool _signedIn; private volatile string _address = string.Empty; private volatile bool _daily = true; /// The guide in use (tick thread): the saved one until a read replaces it. public QuestGuide Guide { get; private set; } = new(); /// One line for the UI and RynthOracle ("312 quests ... (read 2026-11-27 10:00)", "signing in..."). public string Status => _status; /// Signed in: a sign-in is saved on this PC. public bool SignedIn => _signedIn; /// The saved login's name ("" when signed out). public string User => _user; /// The wiki's API address (a setting; "" until the player types one). public string Address => _address; /// Read the guide again at login once it is a day old. public bool Daily => _daily; public bool Running => _task is { IsCompleted: false }; /// Opens RynthILT's settings window (RynthOracle's "settings" command, "/ilt wiki signin" without a saved login). public Action? OpenSettings; /// A chat line: (text, worked). /// A new HTTP handler per sign-in or read (WikiClient.NewHandler; the tests' fake wiki). /// The wait between requests (Task.Delay; the tests note the waits). public IltWikiGuide(Action say, Action? log = null, Func? handler = null, Func? delay = null, Func? utcNow = null) { _say = say; _log = log ?? (_ => { }); _handler = handler ?? WikiClient.NewHandler; _delay = delay; _utcNow = utcNow ?? (() => DateTime.UtcNow); } // ── Files ─────────────────────────────────────────────────────────────── public static string Folder => WikiLoginStore.Folder; public static string SettingsPath => Path.Combine(Folder, SettingsFile); public static string GuidePath(string api) => Path.Combine(Folder, "wiki-guide-" + WikiAddress.FileKey(api) + ".json"); /// Plugin start (tick thread): the address and switch, whether a sign-in is saved, and its saved guide. public void Load() { try { if (File.Exists(SettingsPath)) { using JsonDocument d = JsonDocument.Parse(File.ReadAllText(SettingsPath)); JsonElement r = d.RootElement; if (r.TryGetProperty("api", out JsonElement a) && a.ValueKind == JsonValueKind.String && WikiAddress.TryNormalize(a.GetString(), out string api, out _)) _address = api; if (r.TryGetProperty("daily", out JsonElement dy) && dy.ValueKind is JsonValueKind.True or JsonValueKind.False) _daily = dy.ValueKind == JsonValueKind.True; } } catch (Exception ex) { _log("wiki settings unreadable: " + ex.GetType().Name); } WikiLogin? login = WikiLoginStore.Load(out string error); if (login != null && WikiAddress.Same(login.Api, _address)) { _signedIn = true; _user = login.User; Guide = LoadGuide(_address); _guideRevision++; _status = Guide.IsEmpty ? "signed in as " + login.User + "; the guide isn't read yet" : Summary(Guide); } else if (login != null) { // A sign-in made for another address is never sent to this one. _status = "off: the saved sign-in was for another wiki address; sign in again"; } else if (error.Length > 0) _status = "off: " + error; else _status = "off: not signed in"; } private static QuestGuide LoadGuide(string api) { try { string path = GuidePath(api); if (File.Exists(path)) return QuestGuide.Parse(File.ReadAllText(path)); } catch { } return new QuestGuide(); } private void SaveSettings() { try { Directory.CreateDirectory(Folder); using var ms = new MemoryStream(); using (var w = new Utf8JsonWriter(ms)) { w.WriteStartObject(); w.WriteString("api", _address); w.WriteBoolean("daily", _daily); w.WriteEndObject(); } File.WriteAllBytes(SettingsPath + ".tmp", ms.ToArray()); File.Move(SettingsPath + ".tmp", SettingsPath, overwrite: true); } catch (Exception ex) { _log("wiki settings not saved: " + ex.GetType().Name); } } public static string Summary(QuestGuide g) => $"{g.Quests.Count} quests, {g.KillTasks.Count} kill tasks, {g.Society.Count} society quests, {g.Contracts.Count} contracts" + (g.UpdatedUtc == DateTime.MinValue ? "" : $" (read {g.UpdatedUtc.ToLocalTime():yyyy-MM-dd HH:mm})"); /// The saved guide wants reading: none yet, a day old, or made by an older page reader. internal static bool Due(QuestGuide g, DateTime utcNow) => g.IsEmpty || g.Reader < QuestWikiText.ReaderVersion || utcNow - g.UpdatedUtc >= RefreshAfter; // ── The tick ──────────────────────────────────────────────────────────── /// Plugin tick: the UI's requests, a finished read, RynthOracle's commands, the chat lines, the published guide. public void Tick() { while (_requests.TryDequeue(out Action? a)) { try { a(); } catch (Exception ex) { _log("wiki request failed: " + ex.GetType().Name); } } if (_ready is QuestGuide g) { _ready = null; // A read that ended after a sign-out is dropped. if (_signedIn) { Guide = g; _guideRevision++; } } while (ServerQuestGuideHost.TryTakeCommand(out string word)) { if (word == RynthServerQuestGuide.CommandRefresh) Refresh(fromChat: false); else if (word == RynthServerQuestGuide.CommandSettings) OpenSettings?.Invoke(); } while (_messages.TryDequeue(out var m)) _say("[RynthILT] Leaftide wiki: " + m.Text, m.Ok); Publish(); } /// Hands RynthOracle the guide and status when either changed (tick thread). private void Publish() { bool running = Running; string key = $"{_guideRevision}|{_signedIn}|{running}|{_status}"; if (key == _published) return; _published = key; string[] words = _signedIn ? new[] { RynthServerQuestGuide.CommandRefresh, RynthServerQuestGuide.CommandSettings } : new[] { RynthServerQuestGuide.CommandSettings }; string status = _signedIn ? _status : "Off. Sign in to the Leaftide wiki in /ilt settings to read its quests (your own wiki login)."; ServerQuestGuideHost.Publish(Tag, PluginName, _signedIn ? Guide : null, status, running, words); } /// /// After login (tick thread, until it has run once on an ILT world): one read a session when signed in, the switch /// on, and the saved guide due. True when it started one. /// public bool OnLogin(bool iltActive) { if (!iltActive || !_signedIn || !_daily || _loginReadDone || Running) return false; _loginReadDone = true; if (!Due(Guide, _utcNow())) return false; return StartSaved(announce: false); } public void Shutdown() { try { _cts?.Cancel(); _task?.Wait(2000); } catch { } ServerQuestGuideHost.Withdraw(); } // ── What the UI asks (render thread: queued for the tick) ─────────────── public void RequestSignIn(string address, string user, string password) => _requests.Enqueue(() => SignIn(address, user, password, fromChat: false)); public void RequestSignOut() => _requests.Enqueue(() => SignOut(fromChat: false)); public void RequestRefresh() => _requests.Enqueue(() => Refresh(fromChat: false)); public void RequestDaily(bool on) => _requests.Enqueue(() => SetDaily(on)); // ── The actions (tick thread) ─────────────────────────────────────────── /// Tries the sign-in; when it works it is saved and the guide is read. False (with the reason said) when it can't start. public bool SignIn(string address, string user, string password, bool fromChat) { user = (user ?? string.Empty).Trim(); password ??= string.Empty; if (Running) return Refuse("busy: " + _status + " (wait for it, or Sign out to stop it)", fromChat); if (!WikiAddress.TryNormalize(address, out string api, out string error)) return Refuse(error, fromChat); if (user.Length == 0) return Refuse("type the login name (a bot password's: YourName@botname)", fromChat); if (password.Length == 0) return Refuse("type the bot password", fromChat); if (user.Length > MaxUserLength || password.Length > MaxPasswordLength) return Refuse("that login is too long", fromChat); if (_signedIn && !WikiAddress.Same(api, _address)) return Refuse("sign out first to change the wiki's address", fromChat); if (!WikiAddress.Same(api, _address)) { _address = api; Guide = LoadGuide(api); _guideRevision++; SaveSettings(); } _status = "signing in to " + WikiAddress.HostOf(api) + " as " + user + "..."; Start(new WikiLogin(api, user, password), save: true, announce: true); return true; } /// Signs in again with the saved login and reads ("/ilt wiki signin" when signed in). private bool StartSaved(bool announce) { WikiLogin? login = WikiLoginStore.Load(out string error); if (login == null) { SetSignedOut(error.Length > 0 ? error : "the saved sign-in is gone; sign in again"); if (announce) _messages.Enqueue((_status, false)); return false; } if (!WikiAddress.Same(login.Api, _address)) { SetSignedOut("the saved sign-in was for another wiki address; sign in again"); if (announce) _messages.Enqueue((_status, false)); return false; } Start(login, save: false, announce: announce); return true; } /// Stops a read, deletes the saved sign-in and the saved guide. True when nothing of the wiki is left on this PC. public bool SignOut(bool fromChat) { // The read stops first (it would save the guide again); a request under way ends at once when cancelled. try { _cts?.Cancel(); _task?.Wait(2000); } catch { } bool was = _signedIn || WikiLoginStore.Exists; bool ok = WikiLoginStore.Delete(out string error); string guideError = string.Empty; try { if (Directory.Exists(Folder)) foreach (string f in Directory.GetFiles(Folder, "wiki-guide-*.json*")) File.Delete(f); } catch (Exception ex) { guideError = "couldn't delete the saved guide: " + ex.GetType().Name; ok = false; } _ready = null; Guide = new QuestGuide(); _guideRevision++; SetSignedOut(ok ? "off: signed out" : "off: " + (error.Length > 0 ? error : guideError)); string line = !ok ? "sign out didn't finish: " + (error.Length > 0 ? error : guideError) : was ? "signed out; the saved sign-in and the saved guide are deleted from this PC." : "not signed in; nothing was saved."; if (fromChat) _say("[RynthILT] Leaftide wiki: " + line, ok); else if (ok) _status = was ? "off: signed out; the saved sign-in and guide are deleted" : "off: not signed in"; return ok; } /// Reads the wiki again now (signed in, not reading, not read in the last 5 minutes). public bool Refresh(bool fromChat) { if (!_signedIn) return Refuse("not signed in. Sign in in /ilt settings > Leaftide wiki quest guide first.", fromChat); if (Running) return Refuse("already reading: " + _status, fromChat); TimeSpan since = _utcNow() - _lastStartUtc; if (since < RefreshCooldown) return Refuse($"read {Math.Max(1, (int)since.TotalMinutes)} min ago; again in {(int)Math.Ceiling((RefreshCooldown - since).TotalSeconds)} s (the wiki is read gently)", fromChat); bool started = StartSaved(announce: true); if (started && fromChat) _say("[RynthILT] Leaftide wiki: reading the quest pages again (a request every few seconds; the status says how far).", true); return started; } public bool SetAddress(string typed, bool fromChat) { if (_signedIn) return Refuse("sign out first to change the wiki's address", fromChat); if (!WikiAddress.TryNormalize(typed, out string api, out string error)) return Refuse(error, fromChat); _address = api; Guide = LoadGuide(api); _guideRevision++; SaveSettings(); if (fromChat) _say("[RynthILT] Leaftide wiki: address set to " + api + ". Sign in in /ilt settings.", true); return true; } public void SetDaily(bool on) { _daily = on; SaveSettings(); } private bool Refuse(string why, bool fromChat) { if (fromChat) _say("[RynthILT] Leaftide wiki: " + why, false); else _status = _signedIn ? why : "off: " + why; return false; } private void SetSignedOut(string status) { _signedIn = false; _user = string.Empty; _status = status; } // ── The background part ───────────────────────────────────────────────── private void Start(WikiLogin login, bool save, bool announce) { _cts?.Dispose(); _cts = new CancellationTokenSource(); CancellationToken token = _cts.Token; QuestGuide old = Guide; _lastStartUtc = _utcNow(); _task = Task.Run(async () => { try { await RunAsync(login, save, announce, old, token).ConfigureAwait(false); } catch (OperationCanceledException) { _status = _signedIn ? "stopped" : _status; } catch (Exception ex) { // Never the exception's whole text: it could carry a request. Its kind is enough. _status = "couldn't read the wiki (" + ex.GetType().Name + ")"; _messages.Enqueue((_status, false)); } }, token); } private async Task RunAsync(WikiLogin login, bool save, bool announce, QuestGuide old, CancellationToken token) { using var client = new WikiClient(login.Api, _handler(), _delay); _status = "signing in to " + WikiAddress.HostOf(login.Api) + " as " + login.User + "..."; WikiSignIn s = await client.SignInAsync(login.User, login.Password, token).ConfigureAwait(false); token.ThrowIfCancellationRequested(); if (!s.Ok) { // A saved sign-in the wiki turns down stays saved (the wiki may be down); the player can sign in again or out. _status = (save ? "not signed in: " : "the saved sign-in didn't work: ") + s.Message + (save ? string.Empty : ". Sign in again in /ilt settings, or Sign out."); _messages.Enqueue((_status, false)); return; } if (save) { if (!WikiLoginStore.Save(login, out string error)) { _status = "signed in, but " + error; _messages.Enqueue((_status, false)); return; } _signedIn = true; _user = login.User; if (announce) _messages.Enqueue(("signed in as " + s.UserName + "; reading the quest pages (a request every " + client.Gap.TotalSeconds.ToString("0") + " s; the status says how far).", true)); } string source = WikiAddress.HostOf(login.Api); QuestGuide guide; int fetched; try { (guide, fetched) = await IltWikiReader.ReadAsync(client, old, source, s.ArticleBase, async t => { WikiSignIn again = await client.SignInAsync(login.User, login.Password, t).ConfigureAwait(false); return (again.Ok, again.Message); }, st => _status = st, _utcNow(), token).ConfigureAwait(false); } catch (WikiException ex) { // The saved guide stays as it was; a failure always gets its line (a login read too). _status = "couldn't read the wiki: " + ex.Message + (Guide.IsEmpty ? string.Empty : " (the guide read before stays)"); _messages.Enqueue((_status, false)); return; } token.ThrowIfCancellationRequested(); string saved = string.Empty; try { Directory.CreateDirectory(Folder); string path = GuidePath(login.Api); File.WriteAllText(path + ".tmp", guide.ToJson()); File.Move(path + ".tmp", path, overwrite: true); } catch (Exception ex) { saved = "; couldn't save it: " + ex.GetType().Name; } token.ThrowIfCancellationRequested(); _ready = guide; _status = Summary(guide) + saved; if (announce) _messages.Enqueue(($"{Summary(guide)}; {fetched} pages read now{saved}.", saved.Length == 0)); } /// The tests: waits for a sign-in or read to end. internal bool WaitForTests(int ms = 10_000) { try { return _task?.Wait(ms) ?? true; } catch { return true; } } // ── "/ilt wiki ..." (tick thread) ─────────────────────────────────────── /// "/ilt wiki [status|signin|signout|refresh|address <url>|auto on|off|help]". Every form answers. public void HandleCommand(string[] args) { string sub = args.Length > 0 ? args[0].ToLowerInvariant() : "status"; switch (sub) { case "status": case "": foreach (string line in StatusLines()) _say("[RynthILT] Leaftide wiki: " + line, true); return; case "signin": case "login": case "sign-in": if (args.Length > 1) { // Never in chat: the line could be seen, logged or sent. Nothing of it was kept. _say("[RynthILT] Leaftide wiki: logins aren't taken in chat; nothing was sent or saved. Type it in /ilt settings > Leaftide wiki quest guide.", false); OpenSettings?.Invoke(); return; } if (_signedIn) { if (Running) { _say("[RynthILT] Leaftide wiki: already working: " + _status, false); return; } if (StartSaved(announce: true)) _say("[RynthILT] Leaftide wiki: signing in again as " + _user + "...", true); return; } OpenSettings?.Invoke(); _say(OpenSettings != null ? "[RynthILT] Leaftide wiki: not signed in. The ILT settings window is open: type the wiki's address, the login name and the bot password under Leaftide wiki quest guide, then Sign in." : "[RynthILT] Leaftide wiki: not signed in. Sign in in /ilt settings > Leaftide wiki quest guide.", OpenSettings != null); return; case "signout": case "logout": case "sign-out": SignOut(fromChat: true); return; case "refresh": case "read": Refresh(fromChat: true); return; case "address": case "url": if (args.Length < 2) { _say("[RynthILT] Leaftide wiki: address " + (_address.Length > 0 ? _address : "not set") + ". /ilt wiki address ", _address.Length > 0); return; } SetAddress(args[1], fromChat: true); return; case "auto": case "daily": { string v = args.Length > 1 ? args[1].ToLowerInvariant() : "toggle"; bool on = v is "on" or "true" or "1" ? true : v is "off" or "false" or "0" ? false : !_daily; SetDaily(on); _say($"[RynthILT] Leaftide wiki: read again at login once a day is {(on ? "on" : "off")}.", true); return; } case "help": _say("[RynthILT] /ilt wiki [status] - the Leaftide wiki quest guide (off until you sign in, in /ilt settings), /ilt wiki signin - sign in again with the saved login (or open the settings),", true); _say("[RynthILT] /ilt wiki signout - delete the saved login and guide, /ilt wiki refresh - read the wiki again, /ilt wiki address , /ilt wiki auto on|off - read again at login once a day.", true); return; default: _say("[RynthILT] Leaftide wiki: unknown '" + WikiClient.Short(sub) + "'. /ilt wiki help", false); return; } } /// The status in a few lines (no secret in any of them). public List StatusLines() { var lines = new List(); if (!_signedIn) lines.Add(_status + ". Off until you sign in (/ilt settings > Leaftide wiki quest guide)."); else { lines.Add("signed in as " + _user + " on " + WikiAddress.HostOf(_address) + (Running ? "; reading now" : string.Empty) + "."); lines.Add(_status + "."); lines.Add("read again at login once a day: " + (_daily ? "on" : "off") + "."); } lines.Add("address: " + (_address.Length > 0 ? _address : "not set") + "."); return lines; } }