// WikiClient.cs - Talking to a MediaWiki API with the player's own sign-in (2026-11-27). // // The Leaftide wiki is MediaWiki (1.39) and shows no page without a login, so the quest guide signs in // with the player's bot password (Special:BotPasswords on the wiki: a login name "YourName@botname" and // a generated password, "Basic rights" only, which the player can revoke there at any time): // 1. GET api.php?action=query&meta=tokens&type=login -> query.tokens.logintoken (+ a session cookie) // 2. POST api.php action=login lgname, lgpassword, lgtoken -> login.result "Success" (or "Failed" + reason) // 3. GET api.php?action=query&meta=userinfo|siteinfo&assert=user -> the user id (> 0 = signed in) and the // site's article path (the quests' page addresses) // Every read after that carries assert=user: when the wiki has dropped the session the answer is the // error "assertuserfailed" (or "readapidenied"), which this reports as a lost session so the reader can // sign in once more. The session cookies live in memory only, for one read; nothing of them is saved. // // Politeness: one request at a time, at least Gap apart. Gap is the site's robots.txt Crawl-delay // (read once per client) kept between 5 and 60 seconds, else 10 seconds. The User-Agent names the plugin // only. Redirects are not followed (the sign-in is never sent anywhere but the typed address). // The password goes only into the login POST's body: never into an address, a message or a log line. using System; using System.Collections.Generic; using System.Globalization; using System.Net; using System.Net.Http; using System.Text.Json; using System.Threading; using System.Threading.Tasks; using RynthCore.Plugin.Shared; namespace RynthCore.Plugin.RynthILT.IltWiki; /// A wiki request that didn't work, said plainly; when the wiki no longer knows the sign-in. internal sealed class WikiException : Exception { public WikiException(string message, bool sessionLost = false) : base(message) => SessionLost = sessionLost; public bool SessionLost { get; } } /// What a sign-in came to: whether it worked, a plain message, the wiki's name for the user, and the article address base. internal readonly record struct WikiSignIn(bool Ok, string Message, string UserName, string ArticleBase); internal sealed class WikiClient : IDisposable { /// The User-Agent: the plugin only (nothing about the player, the PC or the character). public const string UserAgent = "RynthILT/1.0 (quest guide)"; public static readonly TimeSpan DefaultGap = TimeSpan.FromSeconds(10); public static readonly TimeSpan MinGap = TimeSpan.FromSeconds(5); public static readonly TimeSpan MaxGap = TimeSpan.FromSeconds(60); public static readonly TimeSpan Timeout = TimeSpan.FromSeconds(30); public const int MaxAnswerBytes = 16 * 1024 * 1024; private readonly string _api; private readonly Uri _apiUri; private readonly HttpClient _http; private readonly CookieContainer _cookies = new(); private readonly Func _delay; private bool _robotsRead; private bool _anySent; /// The gap kept between requests (robots.txt's Crawl-delay once read). public TimeSpan Gap { get; private set; } = DefaultGap; /// Requests sent (the tests count them). public int Requests { get; private set; } /// The API address (WikiAddress.TryNormalize). /// The HTTP handler (the plugin's: no cookies of its own, no redirects; the tests' fake wiki). /// Waits between requests (Task.Delay; the tests note the waits instead). public WikiClient(string api, HttpMessageHandler handler, Func? delay = null) { _api = api; _apiUri = new Uri(api); _http = new HttpClient(handler, disposeHandler: true) { Timeout = Timeout, MaxResponseContentBufferSize = MaxAnswerBytes }; _http.DefaultRequestHeaders.UserAgent.ParseAdd(UserAgent); _delay = delay ?? Task.Delay; } /// The plugin's handler: cookies kept by this client (in memory), redirects not followed. public static HttpMessageHandler NewHandler() => new SocketsHttpHandler { UseCookies = false, AllowAutoRedirect = false, AutomaticDecompression = DecompressionMethods.All, ConnectTimeout = TimeSpan.FromSeconds(15), PooledConnectionLifetime = TimeSpan.FromMinutes(5), }; public void Dispose() => _http.Dispose(); // ── Sign in ───────────────────────────────────────────────────────────── /// Signs in with a bot password (steps 1-3 above). Never throws for the wiki's answers; cancellation still throws. public async Task SignInAsync(string user, string password, CancellationToken token) { try { string result = string.Empty, reason = string.Empty; for (int attempt = 0; attempt < 2; attempt++) { string tokenJson = await SendAsync(HttpMethod.Get, QuestWikiText.ApiUrl(_api, ("action", "query"), ("meta", "tokens"), ("type", "login")), null, token).ConfigureAwait(false); string loginToken = LoginToken(tokenJson); if (loginToken.Length == 0) return Fail("the wiki gave no sign-in token (is the address the wiki's api.php?)"); var form = new FormUrlEncodedContent(new[] { new KeyValuePair("action", "login"), new KeyValuePair("lgname", user), new KeyValuePair("lgpassword", password), new KeyValuePair("lgtoken", loginToken), new KeyValuePair("format", "json"), new KeyValuePair("formatversion", "2"), }); string loginJson = await SendAsync(HttpMethod.Post, _api, form, token).ConfigureAwait(false); (result, reason) = LoginResult(loginJson); // A token the wiki didn't take (its session went between the two requests): once more with a fresh one. if (!result.Equals("WrongToken", StringComparison.OrdinalIgnoreCase) && !result.Equals("NeedToken", StringComparison.OrdinalIgnoreCase)) break; } if (!result.Equals("Success", StringComparison.OrdinalIgnoreCase)) return Fail(Refusal(result, reason, user)); string info = await QueryAsync(token, ("meta", "userinfo|siteinfo"), ("siprop", "general")).ConfigureAwait(false); var (id, name, articleBase) = UserAndSite(info, _api); if (id <= 0) return Fail("the wiki took the sign-in but didn't keep it; try again"); return new WikiSignIn(true, "signed in as " + name, name, articleBase); } catch (WikiException ex) { return Fail(ex.Message); } static WikiSignIn Fail(string message) => new(false, message, string.Empty, string.Empty); } /// The wiki's "no" in plain words (its own reason when it gives one; never the password). internal static string Refusal(string result, string reason, string user) { string why = Short(reason); string hint = user.Contains('@') ? string.Empty : " A bot password's login name looks like YourName@botname (the wiki shows it when the bot password is made)."; return result.ToLowerInvariant() switch { "failed" => "the wiki turned the sign-in down" + (why.Length > 0 ? ": " + why : " (wrong login name or password)") + hint, "aborted" => "the wiki won't take this kind of sign-in" + (why.Length > 0 ? ": " + why : string.Empty) + " Use a bot password (on the wiki: Special:BotPasswords).", "throttled" => "too many sign-in tries; the wiki asks to wait" + (why.Length > 0 ? ": " + why : " a few minutes"), "wrongtoken" or "needtoken" => "the wiki didn't take its own sign-in token twice; try again in a minute", "" => "the wiki didn't answer the sign-in" + (why.Length > 0 ? ": " + why : string.Empty), _ => "the wiki said " + Short(result) + (why.Length > 0 ? ": " + why : string.Empty), }; } // ── Reading ───────────────────────────────────────────────────────────── /// /// An action=query GET as the signed-in user (assert=user). Throws : with SessionLost when /// the wiki no longer knows the sign-in, else for the wiki's other errors. /// public async Task QueryAsync(CancellationToken token, params (string Key, string Value)[] args) { var all = new List<(string, string)>(args.Length + 2) { ("action", "query") }; all.AddRange(args); all.Add(("assert", "user")); string json = await SendAsync(HttpMethod.Get, QuestWikiText.ApiUrl(_api, all.ToArray()), null, token).ConfigureAwait(false); var (code, info) = ApiError(json); if (code.Length == 0) return json; if (code is "assertuserfailed" or "assertnameduserfailed" or "readapidenied" or "notloggedin" or "badtoken") throw new WikiException("the wiki's session ended", sessionLost: true); throw new WikiException("the wiki said " + code + (info.Length > 0 ? ": " + Short(info) : string.Empty)); } private async Task SendAsync(HttpMethod method, string url, HttpContent? body, CancellationToken token) { if (!_robotsRead) { _robotsRead = true; await ReadRobotsAsync(token).ConfigureAwait(false); } string text = await RawAsync(method, url, body, token).ConfigureAwait(false); string t = text.TrimStart(); if (t.Length == 0 || t[0] != '{') throw new WikiException("that address didn't answer like a MediaWiki API (it should be the wiki's api.php)"); return text; } /// robots.txt's Crawl-delay for every robot (or this plugin) becomes the gap; none or no file keeps 10 s. private async Task ReadRobotsAsync(CancellationToken token) { string robots = WikiAddress.RobotsOf(_api); if (robots.Length == 0) return; try { string text = await RawAsync(HttpMethod.Get, robots, null, token).ConfigureAwait(false); if (CrawlDelay(text) is double s) Gap = TimeSpan.FromSeconds(Math.Clamp(s, MinGap.TotalSeconds, MaxGap.TotalSeconds)); } catch (WikiException) { /* no robots.txt: the default gap */ } } /// One request, after the gap; the cookies in and out. Throws with a plain reason. private async Task RawAsync(HttpMethod method, string url, HttpContent? body, CancellationToken token) { if (_anySent) await _delay(Gap, token).ConfigureAwait(false); _anySent = true; Requests++; using var req = new HttpRequestMessage(method, url) { Content = body }; var uri = new Uri(url); string cookie = _cookies.GetCookieHeader(uri); if (cookie.Length > 0) req.Headers.TryAddWithoutValidation("Cookie", cookie); HttpResponseMessage resp; try { resp = await _http.SendAsync(req, token).ConfigureAwait(false); } catch (TaskCanceledException) when (!token.IsCancellationRequested) { throw new WikiException($"the wiki didn't answer within {Timeout.TotalSeconds:0} s"); } catch (HttpRequestException ex) { throw new WikiException("couldn't reach the wiki (" + Short(ex.Message) + ")"); } using (resp) { if (resp.Headers.TryGetValues("Set-Cookie", out IEnumerable? setCookies)) foreach (string c in setCookies) { try { _cookies.SetCookies(uri, c); } catch (CookieException) { } } int status = (int)resp.StatusCode; if (status is >= 300 and < 400) throw new WikiException("the wiki's address sent the request somewhere else; check the address (the wiki's api.php)"); if (status == 429 || status == 503) throw new WikiException($"the wiki is busy (HTTP {status}); try again later"); if (status is 401 or 403) throw new WikiException($"the wiki refused the request (HTTP {status})", sessionLost: true); if (status < 200 || status >= 300) throw new WikiException($"the wiki answered HTTP {status}"); try { return await resp.Content.ReadAsStringAsync(token).ConfigureAwait(false); } catch (HttpRequestException ex) { throw new WikiException("the wiki's answer couldn't be read (" + Short(ex.Message) + ")"); } } } // ── Reading the answers (pure; the tests feed them) ───────────────────── internal static double? CrawlDelay(string robots) { bool ours = false, inAgents = false; double? delay = null; foreach (string raw in robots.Split('\n')) { string line = raw; int hash = line.IndexOf('#'); if (hash >= 0) line = line.Substring(0, hash); int colon = line.IndexOf(':'); if (colon <= 0) continue; string key = line.Substring(0, colon).Trim().ToLowerInvariant(); string value = line.Substring(colon + 1).Trim(); if (key == "user-agent") { if (!inAgents) ours = false; inAgents = true; if (value == "*" || value.StartsWith("RynthILT", StringComparison.OrdinalIgnoreCase)) ours = true; continue; } inAgents = false; if (ours && key == "crawl-delay" && double.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out double s) && s >= 0) delay = Math.Max(delay ?? 0, s); } return delay; } internal static string LoginToken(string json) { try { using JsonDocument d = JsonDocument.Parse(json); return d.RootElement.TryGetProperty("query", out JsonElement q) && q.TryGetProperty("tokens", out JsonElement t) && t.TryGetProperty("logintoken", out JsonElement lt) && lt.ValueKind == JsonValueKind.String ? lt.GetString() ?? string.Empty : string.Empty; } catch (JsonException) { return string.Empty; } } internal static (string Result, string Reason) LoginResult(string json) { try { using JsonDocument d = JsonDocument.Parse(json); JsonElement r = d.RootElement; if (r.TryGetProperty("login", out JsonElement l) && l.ValueKind == JsonValueKind.Object) return (Str(l, "result"), Str(l, "reason")); var (code, info) = ApiError(json); return (string.Empty, code.Length > 0 ? code + (info.Length > 0 ? ": " + info : string.Empty) : string.Empty); } catch (JsonException) { return (string.Empty, string.Empty); } } /// meta=userinfo|siteinfo: the user id and name, and the article address base ("https://wiki.example/" + title). internal static (long Id, string Name, string ArticleBase) UserAndSite(string json, string api) { long id = 0; string name = string.Empty, articleBase = string.Empty; try { using JsonDocument d = JsonDocument.Parse(json); if (d.RootElement.TryGetProperty("query", out JsonElement q)) { if (q.TryGetProperty("userinfo", out JsonElement u) && u.ValueKind == JsonValueKind.Object) { if (u.TryGetProperty("id", out JsonElement i) && i.TryGetInt64(out long v)) id = v; if (u.TryGetProperty("anon", out JsonElement anon) && anon.ValueKind != JsonValueKind.False) id = 0; name = Str(u, "name"); } if (q.TryGetProperty("general", out JsonElement g) && g.ValueKind == JsonValueKind.Object) { string server = Str(g, "server"), path = Str(g, "articlepath"); if (server.StartsWith("//", StringComparison.Ordinal)) server = "https:" + server; if (server.Length > 0 && path.Contains("$1", StringComparison.Ordinal)) articleBase = server + path.Substring(0, path.IndexOf("$1", StringComparison.Ordinal)); } } } catch (JsonException) { } if (articleBase.Length == 0 && Uri.TryCreate(api, UriKind.Absolute, out Uri? a)) articleBase = new Uri(a, "./").ToString() + "index.php?title="; return (id, name, articleBase); } internal static (string Code, string Info) ApiError(string json) { try { using JsonDocument d = JsonDocument.Parse(json); return d.RootElement.TryGetProperty("error", out JsonElement e) && e.ValueKind == JsonValueKind.Object ? (Str(e, "code").ToLowerInvariant(), Str(e, "info")) : (string.Empty, string.Empty); } catch (JsonException) { return (string.Empty, string.Empty); } } private static string Str(JsonElement o, string name) => o.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.String ? (v.GetString() ?? string.Empty).Trim() : string.Empty; /// A wiki's or the network's words cut to one short line. internal static string Short(string? text) { string s = (text ?? string.Empty).Replace('\r', ' ').Replace('\n', ' ').Trim(); return s.Length > 200 ? s.Substring(0, 200).TrimEnd() + "..." : s; } }