RynthServers/Plugins/RynthCore.Plugin.RynthILT/IltWiki/IltWikiReader.cs

262 lines
14 KiB
C#

// IltWikiReader.cs - Reading the Leaftide wiki's quest pages into a quest guide (2026-11-27).
//
// The wiki is a fork of the AC Community Wiki and writes its quests the same way (the {{Quest Summary}}
// box, "== Overview ==" or "== Discord Description ==", "== Walkthrough & Notes ==" with {{stamped|X}}
// and {{Itemlink|X}}, "== QB Stamps ==", "== Rewards ==" with {{Rewards Table}}), so the page reader is
// RynthSuite's shared one (Plugins/Shared/QuestWikiText.cs, linked). This file is the listing and the
// fetching, over WikiClient (signed in, requests spaced out):
// - the quests: every page with the Quest Summary box (generator=embeddedin, with each page's last
// revision in the same answer, so no separate revision checks);
// - the kill tasks: Category:Kill_Tasks and its sub-categories;
// - the society quests by rank: Category:Society_Quests' sub-categories;
// - the contracts: Category:Contracts' pages.
// Only pages new or edited since the saved guide are fetched (50 a request). A category tree is followed
// at most MaxCategories deep (each one is a request, and the wiki asks for seconds between requests).
// When the wiki drops the session mid-read the reader signs in once more (the relogin it is given) and
// goes on; a second loss ends the read with a plain message.
// The listing follows SilentKelpie's reader (Forgejo rynth PR #12); re-implemented. Pool thread only.
using System;
using System.Collections.Generic;
using System.Text.Json;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthILT.IltWiki;
internal static class IltWikiReader
{
public const string QuestTemplate = "Template:Quest_Summary";
public const string KillTasksCategory = "Category:Kill_Tasks";
public const string SocietyCategory = "Category:Society_Quests";
public const string ContractsCategory = "Category:Contracts";
/// <summary>Categories followed per tree, at most (a request each).</summary>
internal const int MaxCategories = 25;
/// <summary>Pages listed per read, at most (a wiki that grew wildly, or a loop).</summary>
internal const int MaxPages = 4000;
/// <summary>Continuation pages per list, at most.</summary>
private const int MaxContinues = 40;
/// <summary>One read: lists the pages, fetches the changed ones, and returns the new guide (old pages kept where unchanged).</summary>
/// <param name="relogin">Signs in again after a lost session; false (with a message) when that didn't work.</param>
public static async Task<(QuestGuide Guide, int Fetched)> ReadAsync(WikiClient client, QuestGuide old, string source, string articleBase,
Func<CancellationToken, Task<(bool Ok, string Message)>> relogin, Action<string> status, DateTime utcNow, CancellationToken token)
{
var q = new Query(client, relogin);
var listed = new Dictionary<string, long>(StringComparer.Ordinal);
var killTasks = new SortedSet<string>(StringComparer.Ordinal);
var contracts = new HashSet<string>(StringComparer.Ordinal);
var society = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
void Add(string title, long rev)
{
if (listed.Count < MaxPages || listed.ContainsKey(title)) listed[title] = rev;
}
status("listing the quest pages...");
await ListAsync(q, new[] { ("generator", "embeddedin"), ("geititle", QuestTemplate), ("geinamespace", "0"), ("geilimit", "max") },
(t, r) => Add(t, r), _ => { }, token).ConfigureAwait(false);
status("listing the kill tasks...");
await WalkAsync(q, KillTasksCategory, (t, r, _) => { killTasks.Add(t); Add(t, r); }, token).ConfigureAwait(false);
status("listing the society quests...");
await WalkAsync(q, SocietyCategory, (t, r, cat) =>
{
Add(t, r);
string rank = RankOf(cat);
if (rank.Length > 0) society.TryAdd(t, rank);
}, token).ConfigureAwait(false);
status("listing the contracts...");
await ListAsync(q, new[] { ("generator", "categorymembers"), ("gcmtitle", ContractsCategory), ("gcmtype", "page"), ("gcmlimit", "max") },
(t, r) => { contracts.Add(t); Add(t, r); }, _ => { }, token).ConfigureAwait(false);
if (listed.Count == 0) throw new WikiException("the wiki listed no quest pages (no page has the Quest Summary box)");
List<string> changed = PagesToRead(old, listed);
var fresh = new Dictionary<string, GuideQuest>(StringComparer.Ordinal);
var freshContracts = new Dictionary<string, GuideContract>(StringComparer.Ordinal);
int read = 0;
foreach (string batch in QuestWikiText.Batches(changed))
{
status($"reading pages ({read}/{changed.Count})...");
string json = await q.GetAsync(token, ("prop", "revisions"), ("rvprop", "content|ids"), ("rvslots", "main"), ("titles", batch)).ConfigureAwait(false);
foreach (var (title, rev, text) in QuestWikiText.Contents(json))
{
if (QuestWikiText.IsQuestPage(text)) fresh[title] = QuestWikiText.ParseQuest(title, text, rev, articleBase);
else if (contracts.Contains(title) && QuestWikiText.IsContractPage(title, text))
freshContracts[title] = QuestWikiText.ParseContract(title, text, rev, articleBase);
}
read = Math.Min(changed.Count, read + QuestWikiText.TitlesPerRequest);
}
token.ThrowIfCancellationRequested();
QuestGuide g = Merge(old, listed, fresh, freshContracts, source, utcNow);
g.KillTasks = new List<string>(killTasks);
g.Society = society;
return (g, fresh.Count + freshContracts.Count);
}
/// <summary>A query that signs in once more after a lost session.</summary>
private sealed class Query
{
private readonly WikiClient _client;
private readonly Func<CancellationToken, Task<(bool Ok, string Message)>> _relogin;
private bool _relogged;
public Query(WikiClient client, Func<CancellationToken, Task<(bool Ok, string Message)>> relogin)
{
_client = client;
_relogin = relogin;
}
public async Task<string> GetAsync(CancellationToken token, params (string Key, string Value)[] args)
{
try
{
return await _client.QueryAsync(token, args).ConfigureAwait(false);
}
catch (WikiException ex) when (ex.SessionLost && !_relogged)
{
_relogged = true;
var (ok, message) = await _relogin(token).ConfigureAwait(false);
if (!ok) throw new WikiException("the wiki's session ended and signing in again didn't work: " + message);
try { return await _client.QueryAsync(token, args).ConfigureAwait(false); }
catch (WikiException again) when (again.SessionLost)
{
throw new WikiException("the wiki keeps ending the session; sign in again in /ilt settings");
}
}
catch (WikiException ex) when (ex.SessionLost)
{
throw new WikiException("the wiki keeps ending the session; sign in again in /ilt settings");
}
}
}
/// <summary>A generator listing with its continuations: each page (ns 0) with its last revision, each sub-category (ns 14).</summary>
private static async Task ListAsync(Query q, (string, string)[] args, Action<string, long> page, Action<string> sub, CancellationToken token)
{
var cont = new List<(string, string)>();
for (int i = 0; i < MaxContinues; i++)
{
var all = new List<(string, string)> { ("prop", "info") };
all.AddRange(args);
all.AddRange(cont);
string json = await q.GetAsync(token, all.ToArray()).ConfigureAwait(false);
var (pages, next) = Generated(json);
foreach (var (title, ns, rev) in pages)
{
if (ns == 0) page(title, rev);
else if (ns == 14) sub(title);
}
if (next.Count == 0) return;
cont = next;
}
}
/// <summary>A category's pages and, breadth first, its sub-categories' (each page with the category it was in).</summary>
private static async Task WalkAsync(Query q, string root, Action<string, long, string> page, CancellationToken token)
{
var queue = new Queue<string>();
var seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { root, root.Replace('_', ' ') };
queue.Enqueue(root);
int walked = 0;
while (queue.Count > 0 && walked < MaxCategories)
{
string cat = queue.Dequeue();
walked++;
await ListAsync(q, new[] { ("generator", "categorymembers"), ("gcmtitle", cat), ("gcmtype", "page|subcat"), ("gcmlimit", "max") },
(t, r) => page(t, r, cat), s => { if (!SkipCategory(s) && seen.Add(s)) queue.Enqueue(s); }, token).ConfigureAwait(false);
}
}
// ── Pure parts (the tests feed them) ────────────────────────────────────
/// <summary>A generator answer (prop=info): each page's title, namespace and last revision; and the "continue" parameters (empty = done).</summary>
internal static (List<(string Title, int Ns, long Rev)> Pages, List<(string Key, string Value)> Continue) Generated(string json)
{
var pages = new List<(string, int, long)>();
var cont = new List<(string, string)>();
try
{
using JsonDocument d = JsonDocument.Parse(json);
JsonElement root = d.RootElement;
if (root.TryGetProperty("query", out JsonElement q) && q.TryGetProperty("pages", out JsonElement ps))
{
IEnumerable<JsonElement> list = ps.ValueKind == JsonValueKind.Array ? ps.EnumerateArray() : Values(ps);
foreach (JsonElement p in list)
{
if (p.ValueKind != JsonValueKind.Object || p.TryGetProperty("missing", out _)) continue;
string title = p.TryGetProperty("title", out JsonElement t) && t.ValueKind == JsonValueKind.String ? t.GetString() ?? "" : "";
if (title.Length == 0) continue;
int ns = p.TryGetProperty("ns", out JsonElement n) && n.TryGetInt32(out int nv) ? nv : 0;
long rev = p.TryGetProperty("lastrevid", out JsonElement r) && r.TryGetInt64(out long rv) ? rv : 0;
pages.Add((title, ns, rev));
}
}
if (root.TryGetProperty("continue", out JsonElement c) && c.ValueKind == JsonValueKind.Object)
foreach (JsonProperty p in c.EnumerateObject())
cont.Add((p.Name, p.Value.ValueKind == JsonValueKind.String ? p.Value.GetString() ?? "" : p.Value.GetRawText()));
}
catch (JsonException) { }
return (pages, cont);
}
private static IEnumerable<JsonElement> Values(JsonElement obj)
{
var list = new List<JsonElement>();
if (obj.ValueKind == JsonValueKind.Object)
foreach (JsonProperty p in obj.EnumerateObject()) list.Add(p.Value);
return list;
}
private static readonly Regex RankRx = new(@"(?:^|:\s*)(\w+)\s+Rank\b", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
/// <summary>The society rank a society sub-category stands for ("Society Quests: Knight Rank" is Knight), or "".</summary>
internal static string RankOf(string category)
{
Match m = RankRx.Match(category);
if (m.Success) return char.ToUpperInvariant(m.Groups[1].Value[0]) + m.Groups[1].Value.Substring(1).ToLowerInvariant();
return category.Contains("Joining", StringComparison.OrdinalIgnoreCase) ? "Joining" : "";
}
/// <summary>A sub-category not followed: item, NPC, image and map lists, not quests.</summary>
internal static bool SkipCategory(string category) =>
category.Contains("Items", StringComparison.OrdinalIgnoreCase)
|| category.Contains("NPC", StringComparison.OrdinalIgnoreCase)
|| category.Contains("Images", StringComparison.OrdinalIgnoreCase)
|| category.Contains("Maps", StringComparison.OrdinalIgnoreCase);
/// <summary>The pages to fetch: new or edited since the saved guide; all of them when it came from an older page reader.</summary>
internal static List<string> PagesToRead(QuestGuide old, IReadOnlyDictionary<string, long> listed)
{
var known = new Dictionary<string, long>(StringComparer.Ordinal);
foreach (GuideQuest x in old.Quests) known[x.Title] = x.Rev;
foreach (GuideContract x in old.Contracts) known[x.Title] = x.Rev;
bool whole = old.Reader < QuestWikiText.ReaderVersion;
var changed = new List<string>();
foreach (KeyValuePair<string, long> kv in listed)
if (whole || kv.Value == 0 || !known.TryGetValue(kv.Key, out long rev) || rev != kv.Value) changed.Add(kv.Key);
changed.Sort(StringComparer.Ordinal);
return changed;
}
/// <summary>The new guide: the pages listed now, each the fresh read when there is one, else the saved one; a page no longer listed goes.</summary>
internal static QuestGuide Merge(QuestGuide old, IReadOnlyDictionary<string, long> listed, IReadOnlyDictionary<string, GuideQuest> fresh,
IReadOnlyDictionary<string, GuideContract> freshContracts, string source, DateTime utcNow)
{
var oldQuests = new Dictionary<string, GuideQuest>(StringComparer.Ordinal);
foreach (GuideQuest x in old.Quests) oldQuests[x.Title] = x;
var oldContracts = new Dictionary<string, GuideContract>(StringComparer.Ordinal);
foreach (GuideContract x in old.Contracts) oldContracts[x.Title] = x;
var g = new QuestGuide { Source = source, UpdatedUtc = utcNow, Reader = QuestWikiText.ReaderVersion };
foreach (string title in listed.Keys)
{
if (fresh.TryGetValue(title, out GuideQuest? f)) g.Quests.Add(f);
else if (oldQuests.TryGetValue(title, out GuideQuest? o)) g.Quests.Add(o);
if (freshContracts.TryGetValue(title, out GuideContract? fc)) g.Contracts.Add(fc);
else if (oldContracts.TryGetValue(title, out GuideContract? oc)) g.Contracts.Add(oc);
}
g.Quests.Sort((a, b) => string.Compare(a.Title, b.Title, StringComparison.OrdinalIgnoreCase));
g.Contracts.Sort((a, b) => string.Compare(a.Name, b.Name, StringComparison.OrdinalIgnoreCase));
return g;
}
}