353 lines
18 KiB
C#
353 lines
18 KiB
C#
// 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;
|
|
|
|
/// <summary>A wiki request that didn't work, said plainly; <see cref="SessionLost"/> when the wiki no longer knows the sign-in.</summary>
|
|
internal sealed class WikiException : Exception
|
|
{
|
|
public WikiException(string message, bool sessionLost = false) : base(message) => SessionLost = sessionLost;
|
|
|
|
public bool SessionLost { get; }
|
|
}
|
|
|
|
/// <summary>What a sign-in came to: whether it worked, a plain message, the wiki's name for the user, and the article address base.</summary>
|
|
internal readonly record struct WikiSignIn(bool Ok, string Message, string UserName, string ArticleBase);
|
|
|
|
internal sealed class WikiClient : IDisposable
|
|
{
|
|
/// <summary>The User-Agent: the plugin only (nothing about the player, the PC or the character).</summary>
|
|
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<TimeSpan, CancellationToken, Task> _delay;
|
|
private bool _robotsRead;
|
|
private bool _anySent;
|
|
|
|
/// <summary>The gap kept between requests (robots.txt's Crawl-delay once read).</summary>
|
|
public TimeSpan Gap { get; private set; } = DefaultGap;
|
|
|
|
/// <summary>Requests sent (the tests count them).</summary>
|
|
public int Requests { get; private set; }
|
|
|
|
/// <param name="api">The API address (WikiAddress.TryNormalize).</param>
|
|
/// <param name="handler">The HTTP handler (the plugin's: no cookies of its own, no redirects; the tests' fake wiki).</param>
|
|
/// <param name="delay">Waits between requests (Task.Delay; the tests note the waits instead).</param>
|
|
public WikiClient(string api, HttpMessageHandler handler, Func<TimeSpan, CancellationToken, Task>? 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;
|
|
}
|
|
|
|
/// <summary>The plugin's handler: cookies kept by this client (in memory), redirects not followed.</summary>
|
|
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 ─────────────────────────────────────────────────────────────
|
|
|
|
/// <summary>Signs in with a bot password (steps 1-3 above). Never throws for the wiki's answers; cancellation still throws.</summary>
|
|
public async Task<WikiSignIn> 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<string, string>("action", "login"),
|
|
new KeyValuePair<string, string>("lgname", user),
|
|
new KeyValuePair<string, string>("lgpassword", password),
|
|
new KeyValuePair<string, string>("lgtoken", loginToken),
|
|
new KeyValuePair<string, string>("format", "json"),
|
|
new KeyValuePair<string, string>("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);
|
|
}
|
|
|
|
/// <summary>The wiki's "no" in plain words (its own reason when it gives one; never the password).</summary>
|
|
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 ─────────────────────────────────────────────────────────────
|
|
|
|
/// <summary>
|
|
/// An action=query GET as the signed-in user (assert=user). Throws <see cref="WikiException"/>: with SessionLost when
|
|
/// the wiki no longer knows the sign-in, else for the wiki's other errors.
|
|
/// </summary>
|
|
public async Task<string> 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<string> 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;
|
|
}
|
|
|
|
/// <summary>robots.txt's Crawl-delay for every robot (or this plugin) becomes the gap; none or no file keeps 10 s.</summary>
|
|
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 */ }
|
|
}
|
|
|
|
/// <summary>One request, after the gap; the cookies in and out. Throws <see cref="WikiException"/> with a plain reason.</summary>
|
|
private async Task<string> 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<string>? 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); }
|
|
}
|
|
|
|
/// <summary>meta=userinfo|siteinfo: the user id and name, and the article address base ("https://wiki.example/" + title).</summary>
|
|
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;
|
|
|
|
/// <summary>A wiki's or the network's words cut to one short line.</summary>
|
|
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;
|
|
}
|
|
}
|