RynthSuite/Plugins/Shared/QuestWikiText.cs

623 lines
31 KiB
C#

// ============================================================================
// RynthSuite - Plugins/Shared/QuestWikiText.cs
// Reading MediaWiki quest pages into a quest guide (QuestGuideData.cs), 2026-11-27.
// Pure text work: whoever fetches the pages (RynthOracle's AC Community Wiki feed,
// or a server plugin for a wiki of its own built on the same templates) hands the
// wikitext here, and the offline tests feed it made-up pages. Linked source.
//
// What a quest page looks like on the AC Community Wiki and the wikis made from it:
// {{Quest Summary | Level = 50+ | Quest Type = Solo | Starts With = [[Someone]]
// | Starts At = [[Some Town]] | Repeat Timer = 20 Hours | Kill Task = Yes }}
// == Overview == a paragraph
// == Walkthrough == numbered "# " steps with "#* " tips, or bullets, or paragraphs;
// {{stamped|Flag}} marks a step's quest flag, {{Itemlink|Item}} an item
// == Stamps == stamps listed apart from the steps
// == Rewards == {{Rewards Table | ...}} or a plain list
// [[Category:...]]
// Coordinates are written every which way ("28.5S, 90.9W", "62.7s 66.6W").
// Also the MediaWiki API's JSON answers (list=categorymembers, list=embeddedin,
// prop=info, prop=revisions), read without the HTTP so the tests can feed them.
// The reader follows SilentKelpie's (Forgejo rynth PR #12); re-implemented here.
// ============================================================================
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using System.Text.Json;
using System.Text.RegularExpressions;
namespace RynthCore.Plugin.Shared;
internal static class QuestWikiText
{
/// <summary>
/// This reader's version, saved in a guide (QuestGuide.Reader). Raise it when the reader changes what it takes
/// from a page: a feed then reads every page again, not only those edited since.
/// </summary>
public const int ReaderVersion = 1;
private const RegexOptions Ci = RegexOptions.IgnoreCase | RegexOptions.CultureInvariant;
private static readonly Regex CommentRx = new(@"<!--.*?-->", RegexOptions.Singleline | RegexOptions.CultureInvariant);
private static readonly Regex RefRx = new(@"<ref[^>/]*/>|<ref[^>]*>.*?</ref>", RegexOptions.Singleline | Ci);
private static readonly Regex HeadingRx = new(@"^\s*==\s*([^=].*?)\s*==\s*$", RegexOptions.CultureInvariant);
private static readonly Regex StampRx = new(@"\{\{\s*stamped\s*\|\s*([^}|]+?)\s*\}\}", Ci);
private static readonly Regex ItemRx = new(@"\{\{\s*Item\s*link\s*\|\s*([^}|]+?)\s*(?:\|[^}]*)?\}\}", Ci);
private static readonly Regex CategoryRx = new(@"\[\[\s*Category\s*:\s*([^\]|]+?)\s*(?:\|[^\]]*)?\]\]", Ci);
private static readonly Regex FirstLinkRx = new(@"\[\[([^\[\]|#]+)(?:\|[^\[\]]*)?\]\]", RegexOptions.CultureInvariant);
private static readonly Regex CoordsRx = new(
@"(?<ns>\d+(?:\.\d+)?)\s*(?<nsc>[NnSs])[\s,]*(?<ew>\d+(?:\.\d+)?)\s*(?<ewc>[EeWw])\b", RegexOptions.CultureInvariant);
/// <summary>The page is a quest page (it has the Quest Summary box).</summary>
public static bool IsQuestPage(string? wikitext) =>
!string.IsNullOrEmpty(wikitext) && wikitext.IndexOf("{{Quest Summary", StringComparison.OrdinalIgnoreCase) >= 0;
/// <summary>A contract's item page: the {{Item}} box, and a contract's title or category.</summary>
public static bool IsContractPage(string title, string? wikitext) =>
!string.IsNullOrEmpty(wikitext) && wikitext.IndexOf("{{Item", StringComparison.OrdinalIgnoreCase) >= 0
&& (title.StartsWith("Contract for ", StringComparison.OrdinalIgnoreCase)
|| wikitext.IndexOf("[[Category:Contracts", StringComparison.OrdinalIgnoreCase) >= 0);
/// <summary>A page's address: the wiki's article path plus the title with underscores.</summary>
public static string UrlOf(string wikiBase, string title) =>
wikiBase + Uri.EscapeDataString(title.Trim().Replace(' ', '_')).Replace("%2F", "/");
private static string Prepare(string? wikitext) =>
RefRx.Replace(CommentRx.Replace(wikitext ?? "", ""), "").Replace("\r\n", "\n").Replace('\r', '\n');
/// <summary>Reads a quest page (<paramref name="rev"/>: its revision id, 0 unknown).</summary>
public static GuideQuest ParseQuest(string title, string wikitext, long rev, string wikiBase)
{
var q = new GuideQuest { Title = title.Trim(), Url = UrlOf(wikiBase, title), Rev = rev };
string text = Prepare(wikitext);
foreach (Match m in CategoryRx.Matches(text))
{
string c = m.Groups[1].Value.Trim();
if (c.Length > 0 && !q.Categories.Contains(c)) q.Categories.Add(c);
}
Dictionary<string, string> box = TemplateParams(text, "Quest Summary");
q.Level = Clean(Param(box, "Level"));
q.RecommendedLevel = Clean(Param(box, "Recommended Level", "Recommended"));
q.Type = Clean(Param(box, "Quest Type", "Type"));
q.KillTask = Clean(Param(box, "Kill Task"));
q.StartsWith = Clean(Param(box, "Starts With", "NPC"));
q.StartsAt = Clean(Param(box, "Starts At", "Location"));
q.Repeat = Clean(Param(box, "Repeat Timer", "Timer", "Repeat"));
q.RepeatSec = RepeatSeconds(q.Repeat);
q.TimeToComplete = Clean(Param(box, "Time to Complete"));
q.SocietyRank = Clean(Param(box, "Society Rank"));
string overview = "";
List<string>? walk = null;
var loose = new List<string>();
foreach (var (heading, lines) in Sections(text))
{
string h = heading.ToLowerInvariant();
if (h.StartsWith("overview", StringComparison.Ordinal) || h.Contains("description", StringComparison.Ordinal))
{
string o = Clean(string.Join(" ", lines));
if (o.Length > 0 && (h.StartsWith("overview", StringComparison.Ordinal) || overview.Length == 0)) overview = o;
}
else if (h.StartsWith("walkthrough", StringComparison.Ordinal) || h == "steps" || h.StartsWith("quest steps", StringComparison.Ordinal)
|| h == "notes" && walk == null)
walk = lines;
else if (h.Contains("stamp", StringComparison.Ordinal))
{
foreach (string l in lines)
foreach (Match m in StampRx.Matches(l))
if (GuideStamp.Clean(m.Groups[1].Value) is { Length: > 0 } s) loose.Add(s);
}
else if (h.StartsWith("reward", StringComparison.Ordinal))
q.Rewards = Rewards(string.Join("\n", lines));
}
q.Overview = overview.Length > 700 ? overview.Substring(0, 700).TrimEnd() + "..." : overview;
if (walk != null) q.Steps = Steps(walk);
// Stamps listed apart: tied to the step that names them, else (one per stampless step) in order, else kept apart.
var have = new HashSet<string>(StringComparer.Ordinal);
foreach (GuideStep s in q.Steps) foreach (string st in s.Stamps) have.Add(GuideStamp.Key(st));
var left = new List<string>();
foreach (string st in loose)
{
if (!have.Add(GuideStamp.Key(st))) continue;
if (StepNamed(q.Steps, st) is GuideStep byName) byName.Stamps.Add(st);
else left.Add(st);
}
List<GuideStep> bare = q.Steps.FindAll(s => s.Stamps.Count == 0);
if (left.Count > 0 && left.Count == bare.Count)
{
for (int i = 0; i < left.Count; i++) bare[i].Stamps.Add(left[i]);
left.Clear();
}
q.ExtraStamps = left;
q.Loot = LootItems(q.Steps);
return q;
}
/// <summary>A contract's item page: {{Item | Name, Description, Recommended Level}}, {{Intro | Related Quests}}, the notes' "Purchased from [[X]]".</summary>
public static GuideContract ParseContract(string title, string wikitext, long rev, string wikiBase)
{
string text = Prepare(wikitext);
var c = new GuideContract { Title = title.Trim(), Url = UrlOf(wikiBase, title), Rev = rev };
Dictionary<string, string> item = TemplateParams(text, "Item");
Dictionary<string, string> intro = TemplateParams(text, "Intro");
string name = Clean(Param(item, "Name"));
c.Name = name.Length > 0 ? name : c.Title;
c.Description = Clean(Param(item, "Description"));
c.Level = Clean(Param(item, "Recommended Level", "Level"));
foreach (Match m in FirstLinkRx.Matches(Param(intro, "Related Quests", "Related Quest", "Quest")))
{
string t = m.Groups[1].Value.Trim().TrimStart(':');
if (t.Length > 0 && !c.Quests.Contains(t)) c.Quests.Add(t);
}
foreach (var (heading, lines) in Sections(text))
{
if (!heading.StartsWith("note", StringComparison.OrdinalIgnoreCase)) continue;
foreach (string l in lines)
{
if (l.IndexOf("purchase", StringComparison.OrdinalIgnoreCase) < 0 && l.IndexOf("sold by", StringComparison.OrdinalIgnoreCase) < 0
&& l.IndexOf("given by", StringComparison.OrdinalIgnoreCase) < 0 && l.IndexOf("from [[", StringComparison.OrdinalIgnoreCase) < 0) continue;
c.Where = Clean(l.TrimStart('*', '#', ':', ' '));
Match m = FirstLinkRx.Match(l);
if (m.Success) c.Npc = Clean("[[" + m.Groups[1].Value + "]]");
break;
}
if (c.Where.Length > 0) break;
}
return c;
}
// ── Sections and steps ──────────────────────────────────────────────────
/// <summary>The page's "== X ==" sections with their lines (the text before the first heading is "").</summary>
internal static List<(string Heading, List<string> Lines)> Sections(string text)
{
var list = new List<(string, List<string>)>();
string heading = "";
var lines = new List<string>();
foreach (string raw in text.Split('\n'))
{
Match m = HeadingRx.Match(raw);
if (m.Success)
{
list.Add((heading, lines));
heading = m.Groups[1].Value.Trim();
lines = new List<string>();
continue;
}
lines.Add(raw);
}
list.Add((heading, lines));
return list;
}
/// <summary>
/// The walkthrough's steps: its numbered "# " lines with the "#*", "#:" and "##" lines under them; with no
/// numbered lines, its top-level bullets; with neither, its paragraphs (one step each).
/// </summary>
internal static List<GuideStep> Steps(List<string> lines)
{
var steps = new List<GuideStep>();
bool numbered = lines.Exists(l => IsTopLevel(l, '#'));
bool bullets = !numbered && lines.Exists(l => IsTopLevel(l, '*'));
if (numbered || bullets)
{
char lead = numbered ? '#' : '*';
GuideStep? cur = null;
foreach (string raw in lines)
{
string l = raw.TrimEnd();
if (l.Length == 0) continue;
if (IsTopLevel(l, lead)) steps.Add(cur = NewStep(l.Substring(1)));
else if (cur != null && (l[0] == lead || l[0] == '*' || l[0] == ':')) AddSub(cur, l.TrimStart('#', '*', ':', ';'));
// A paragraph or a table between steps is left out.
}
}
else
{
var para = new StringBuilder();
void Flush()
{
string p = para.ToString().Trim();
para.Clear();
if (p.Length > 0) steps.Add(NewStep(p));
}
foreach (string raw in lines)
{
string l = raw.Trim();
if (l.Length == 0 || l.StartsWith("===", StringComparison.Ordinal) || l.StartsWith("{|", StringComparison.Ordinal)
|| l.StartsWith("|}", StringComparison.Ordinal) || l.StartsWith("[[File:", StringComparison.OrdinalIgnoreCase))
{
Flush();
continue;
}
if (para.Length > 0) para.Append(' ');
para.Append(l);
}
Flush();
}
steps.RemoveAll(s => s.Text.Length == 0 && s.Stamps.Count == 0 && s.Coords.Count == 0);
return steps;
}
private static bool IsTopLevel(string l, char lead) =>
l.Length > 1 && l[0] == lead && l[1] != '*' && l[1] != '#' && l[1] != ':' && l[1] != ';';
private static GuideStep NewStep(string raw)
{
var s = new GuideStep();
Collect(s, raw);
s.Text = Clean(raw);
return s;
}
private static void AddSub(GuideStep s, string raw)
{
Collect(s, raw);
string note = Clean(raw);
if (note.Length > 0) s.Notes.Add(note);
}
/// <summary>The stamps, items and coordinates in one line of a step.</summary>
private static void Collect(GuideStep s, string raw)
{
foreach (Match m in StampRx.Matches(raw))
{
string st = GuideStamp.Clean(m.Groups[1].Value);
if (st.Length > 0 && !s.Stamps.Exists(x => GuideStamp.Key(x) == GuideStamp.Key(st))) s.Stamps.Add(st);
}
foreach (Match m in ItemRx.Matches(raw))
{
string it = m.Groups[1].Value.Trim();
if (it.Length > 0 && !s.Items.Exists(x => x.Equals(it, StringComparison.OrdinalIgnoreCase))) s.Items.Add(it);
}
foreach (string c in Coords(Clean(raw)))
if (!s.Coords.Contains(c)) s.Coords.Add(c);
}
/// <summary>Every coordinate pair in the text, written "12.3N, 45.6E", in order.</summary>
public static List<string> Coords(string? text)
{
var list = new List<string>();
if (string.IsNullOrEmpty(text)) return list;
foreach (Match m in CoordsRx.Matches(text))
{
string c = string.Create(CultureInfo.InvariantCulture,
$"{m.Groups["ns"].Value}{char.ToUpperInvariant(m.Groups["nsc"].Value[0])}, {m.Groups["ew"].Value}{char.ToUpperInvariant(m.Groups["ewc"].Value[0])}");
if (!list.Contains(c)) list.Add(c);
}
return list;
}
private static readonly Regex LootVerbRx = new(
@"\b(kill|kills|killing|loot|loots|looted|drop|drops|dropped|collect|collects|gather|find|finds|obtain|obtains|pick\s+up|grab|hunt|hunts)\b", Ci);
private static readonly Regex HandInRx = new(@"^\s*(instead|return|turn\s+in|hand\s+in|give|bring|upgrade)\b", Ci);
/// <summary>The items worth picking up: named in a step that kills, loots or finds something (not one only handed in), each once.</summary>
internal static List<string> LootItems(List<GuideStep> steps)
{
var loot = new List<string>();
foreach (GuideStep s in steps)
{
if (s.Items.Count == 0) continue;
if (!LootVerbRx.IsMatch(s.Text + " " + string.Join(" ", s.Notes)) || HandInRx.IsMatch(s.Text)) continue;
foreach (string it in s.Items)
if (!loot.Exists(x => x.Equals(it, StringComparison.OrdinalIgnoreCase))) loot.Add(it);
}
return loot;
}
private static readonly HashSet<string> StampNoise = new(StringComparer.Ordinal)
{ "quest", "stamp", "found", "turnin", "turned", "done", "complete", "completed", "kill", "killed", "the", "obtained", "timer", "flag", "started", "start" };
/// <summary>The one step a stamp listed apart belongs to by its words ("SampleFang" goes with the step about the fang), or null.</summary>
internal static GuideStep? StepNamed(List<GuideStep> steps, string stamp)
{
List<string> tokens = StampTokens(stamp);
if (tokens.Count == 0) return null;
GuideStep? best = null;
int bestScore = 0;
bool tie = false;
foreach (GuideStep s in steps)
{
var words = Words(s.Text + " " + string.Join(" ", s.Notes) + " " + string.Join(" ", s.Items));
int score = 0;
foreach (string t in tokens)
foreach (string w in words)
if (w.Length >= 4 && (w == t || w.StartsWith(t, StringComparison.Ordinal) || t.StartsWith(w, StringComparison.Ordinal))) { score++; break; }
if (score > bestScore) { best = s; bestScore = score; tie = false; }
else if (score == bestScore && score > 0) tie = true;
}
return tie ? null : best;
}
/// <summary>"Shiny_Red_Stone_Found" -> shiny, red, stone; "SampleFangs" -> sample, fang (3+ letters, noise words left out).</summary>
internal static List<string> StampTokens(string stamp)
{
string spaced = Regex.Replace(stamp, @"(?<=[a-z0-9])(?=[A-Z])", " ");
var list = new List<string>();
foreach (string w in Words(spaced))
{
string t = w.Length > 4 && w.EndsWith('s') ? w[..^1] : w;
if (t.Length >= 3 && !StampNoise.Contains(t) && !list.Contains(t)) list.Add(t);
}
return list;
}
private static HashSet<string> Words(string text)
{
var set = new HashSet<string>(StringComparer.Ordinal);
foreach (Match m in Regex.Matches(text.ToLowerInvariant(), "[a-z0-9]+")) set.Add(m.Value);
return set;
}
// ── Rewards ─────────────────────────────────────────────────────────────
/// <summary>The rewards section as short lines ("For X:", then each reward); a plain list when there is no table. At most 30.</summary>
internal static List<string> Rewards(string section)
{
var lines = new List<string>();
int at = 0;
bool anyTable = false;
while (true)
{
int i = section.IndexOf("{{Rewards Table", at, StringComparison.OrdinalIgnoreCase);
if (i < 0) break;
int end = TemplateEnd(section, i);
if (end < 0) break;
anyTable = true;
Dictionary<string, string> p = SplitParams(section.Substring(i + 2, end - i - 4));
string task = Clean(Param(p, "Quest Task", "Task"));
if (task.Length > 0) lines.Add("For " + task + ":");
foreach (string key in new[] { "Item Reward", "Items", "XP Reward", "Experience", "Luminance Reward", "Luminance", "Other Reward", "Other" })
{
string v = Param(p, key);
foreach (string part in v.Split('\n'))
{
string c = Clean(part.TrimStart('*', ' ', '#'));
if (c.Length == 0) continue;
lines.Add(key.StartsWith("XP", StringComparison.Ordinal) || key.StartsWith("Exp", StringComparison.Ordinal) ? "XP: " + c
: key.StartsWith("Lum", StringComparison.Ordinal) ? "Luminance: " + c : c);
}
}
at = end;
}
if (!anyTable)
foreach (string l in section.Split('\n'))
if (Clean(l.TrimStart('*', '#', ':', ' ')) is { Length: > 0 } c) lines.Add(c);
if (lines.Count > 30) lines.RemoveRange(30, lines.Count - 30);
return lines;
}
// ── Templates ───────────────────────────────────────────────────────────
/// <summary>The first {{name ...}} template's named parameters (keys trimmed, any case).</summary>
internal static Dictionary<string, string> TemplateParams(string text, string name)
{
var none = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
int i = text.IndexOf("{{" + name, StringComparison.OrdinalIgnoreCase);
if (i < 0) return none;
int end = TemplateEnd(text, i);
if (end < 0) end = text.Length;
int bodyEnd = Math.Max(i + 2, end - 2);
return SplitParams(text.Substring(i + 2, bodyEnd - (i + 2)));
}
/// <summary>Just past the "}}" that closes the template starting at <paramref name="start"/>, or -1.</summary>
private static int TemplateEnd(string text, int start)
{
int depth = 0;
for (int i = start; i < text.Length - 1; i++)
{
if (text[i] == '{' && text[i + 1] == '{') { depth++; i++; }
else if (text[i] == '}' && text[i + 1] == '}') { depth--; i++; if (depth == 0) return i + 1; }
}
return -1;
}
/// <summary>"| key = value" parameters split at the top level only (links and inner templates kept whole).</summary>
private static Dictionary<string, string> SplitParams(string body)
{
var parts = new List<string>();
int depthT = 0, depthL = 0, from = 0;
for (int i = 0; i < body.Length; i++)
{
char c = body[i];
char n = i + 1 < body.Length ? body[i + 1] : '\0';
if (c == '{' && n == '{') { depthT++; i++; }
else if (c == '}' && n == '}') { depthT--; i++; }
else if (c == '[' && n == '[') { depthL++; i++; }
else if (c == ']' && n == ']') { depthL--; i++; }
else if (c == '|' && depthT == 0 && depthL == 0)
{
parts.Add(body.Substring(from, i - from));
from = i + 1;
}
}
parts.Add(body.Substring(from));
var map = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
for (int k = 1; k < parts.Count; k++)
{
int eq = parts[k].IndexOf('=');
if (eq <= 0) continue;
string key = Regex.Replace(parts[k].Substring(0, eq), @"\s+", " ").Trim();
if (key.Length > 0 && !map.ContainsKey(key)) map[key] = parts[k].Substring(eq + 1).Trim();
}
return map;
}
private static string Param(Dictionary<string, string> p, params string[] names)
{
foreach (string n in names)
if (p.TryGetValue(n, out string? v) && v.Trim().Length > 0) return v.Trim();
return "";
}
// ── Text ────────────────────────────────────────────────────────────────
private static readonly Regex FileRx = new(@"\[\[\s*(File|Image)\s*:[^\[\]]*(\[\[[^\]]*\]\][^\[\]]*)*\]\]", Ci);
private static readonly Regex LinkRx = new(@"\[\[([^\[\]|]*)\|([^\[\]]*)\]\]", RegexOptions.CultureInvariant);
private static readonly Regex PlainLinkRx = new(@"\[\[([^\[\]|]*)\]\]", RegexOptions.CultureInvariant);
private static readonly Regex ExtLinkRx = new(@"\[(https?://[^\s\]]+)(?:\s+([^\]]*))?\]", RegexOptions.CultureInvariant);
private static readonly Regex NamedTemplateRx = new(@"\{\{\s*(?:Item\s*link|Icon\s*Link|Creature\s*link|NPC\s*link|Link)\s*\|\s*([^}|]+?)\s*(?:\|[^{}]*)?\}\}", Ci);
private static readonly Regex AnyTemplateRx = new(@"\{\{[^{}]*\}\}", RegexOptions.CultureInvariant);
private static readonly Regex BrRx = new(@"<br\s*/?>", Ci);
private static readonly Regex TagRx = new(@"<[^>]+>", RegexOptions.CultureInvariant);
private static readonly Regex SpaceRx = new(@"\s+", RegexOptions.CultureInvariant);
/// <summary>Wikitext as plain text: links as their words, item templates as the item; other templates, files, bold and tags dropped.</summary>
public static string Clean(string? wikitext)
{
if (string.IsNullOrEmpty(wikitext)) return "";
string s = StampRx.Replace(wikitext, "");
s = FileRx.Replace(s, "");
s = CategoryRx.Replace(s, "");
s = LinkRx.Replace(s, "$2");
s = PlainLinkRx.Replace(s, m => m.Groups[1].Value.TrimStart(':'));
s = ExtLinkRx.Replace(s, m => m.Groups[2].Success && m.Groups[2].Value.Length > 0 ? m.Groups[2].Value : m.Groups[1].Value);
s = NamedTemplateRx.Replace(s, "$1");
for (int pass = 0; pass < 4 && s.Contains("{{", StringComparison.Ordinal); pass++) s = AnyTemplateRx.Replace(s, "");
s = BrRx.Replace(s, " ");
s = TagRx.Replace(s, "");
s = s.Replace("'''", "").Replace("''", "");
s = s.Replace("&nbsp;", " ").Replace("&amp;", "&").Replace("&lt;", "<").Replace("&gt;", ">").Replace("&quot;", "\"");
return SpaceRx.Replace(s, " ").Trim().TrimStart('*', '#', ':', ' ').Trim();
}
/// <summary>
/// A repeat timer in seconds: "20 Hours", "7 days", "1 Week", "3d 12h", "Daily", "Weekly"; 0 for none
/// ("", "None", "Once", "One time", "Non Repeatable"); -1 for words it doesn't understand.
/// </summary>
public static long RepeatSeconds(string? repeat)
{
if (string.IsNullOrWhiteSpace(repeat)) return 0;
string r = repeat.Trim().ToLowerInvariant();
if (r is "none" or "n/a" or "na" or "-" or "once" or "no" or "never"
|| r.StartsWith("one time", StringComparison.Ordinal) || r.StartsWith("one-time", StringComparison.Ordinal)
|| r.StartsWith("not repeatable", StringComparison.Ordinal) || r.StartsWith("non repeatable", StringComparison.Ordinal)
|| r.StartsWith("non-repeatable", StringComparison.Ordinal) || r.StartsWith("unrepeatable", StringComparison.Ordinal)) return 0;
if (r.StartsWith("daily", StringComparison.Ordinal)) return 86400;
if (r.StartsWith("weekly", StringComparison.Ordinal)) return 7 * 86400;
long total = 0;
foreach (Match m in Regex.Matches(r, @"(\d+(?:\.\d+)?)\s*(weeks?|w|days?|d|hours?|hrs?|h|minutes?|mins?|m|seconds?|secs?|s)\b"))
{
double n = double.Parse(m.Groups[1].Value, CultureInfo.InvariantCulture);
double mult = m.Groups[2].Value[0] switch { 'w' => 7 * 86400, 'd' => 86400, 'h' => 3600, 'm' => 60, _ => 1 };
total += (long)Math.Round(n * mult);
}
return total > 0 ? total : -1;
}
// ── The MediaWiki API's answers ─────────────────────────────────────────
/// <summary>Titles per prop=info / prop=revisions request (the API's limit for an anonymous reader).</summary>
public const int TitlesPerRequest = 50;
/// <summary>A GET URL with these parameters (format=json, formatversion=2 added; every value escaped).</summary>
public static string ApiUrl(string api, params (string Key, string Value)[] args)
{
var sb = new StringBuilder(api);
sb.Append(api.Contains('?') ? '&' : '?').Append("format=json&formatversion=2");
foreach (var (k, v) in args) sb.Append('&').Append(Uri.EscapeDataString(k)).Append('=').Append(Uri.EscapeDataString(v));
return sb.ToString();
}
/// <summary>list=categorymembers / list=embeddedin: the pages (namespace 0), sub-categories (14), and the "continue" parameters (empty = done).</summary>
public static (List<string> Pages, List<string> SubCats, List<(string Key, string Value)> Continue) Members(string json, string listName)
{
var pages = new List<string>();
var cats = new List<string>();
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(listName, out JsonElement list) && list.ValueKind == JsonValueKind.Array)
foreach (JsonElement m in list.EnumerateArray())
{
string title = Str(m, "title");
if (title.Length == 0) continue;
int ns = m.TryGetProperty("ns", out JsonElement n) && n.TryGetInt32(out int v) ? v : 0;
if (ns == 14) cats.Add(title);
else if (ns == 0) pages.Add(title);
}
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, cats, cont);
}
/// <summary>prop=info: each page's last revision id (missing pages left out).</summary>
public static Dictionary<string, long> LastRevisions(string json)
{
var map = new Dictionary<string, long>(StringComparer.Ordinal);
foreach (JsonElement p in Pages(json))
{
if (p.TryGetProperty("missing", out _)) continue;
string title = Str(p, "title");
if (title.Length > 0) map[title] = p.TryGetProperty("lastrevid", out JsonElement r) && r.TryGetInt64(out long v) ? v : 0;
}
return map;
}
/// <summary>prop=revisions (rvprop=content|ids, rvslots=main): each page's title, revision id and wikitext.</summary>
public static List<(string Title, long Rev, string Text)> Contents(string json)
{
var list = new List<(string, long, string)>();
foreach (JsonElement p in Pages(json))
{
string title = Str(p, "title");
if (title.Length == 0 || !p.TryGetProperty("revisions", out JsonElement revs) || revs.ValueKind != JsonValueKind.Array) continue;
foreach (JsonElement r in revs.EnumerateArray())
{
long id = r.TryGetProperty("revid", out JsonElement i) && i.TryGetInt64(out long v) ? v : 0;
string text = r.TryGetProperty("slots", out JsonElement slots) && slots.TryGetProperty("main", out JsonElement main)
? Str(main, "content") : Str(r, "content");
list.Add((title, id, text));
break;
}
}
return list;
}
/// <summary>query.pages (an array in formatversion=2, keyed by id in 1), copied out so the document can go.</summary>
private static List<JsonElement> Pages(string json)
{
var list = new List<JsonElement>();
try
{
using JsonDocument d = JsonDocument.Parse(json);
if (d.RootElement.TryGetProperty("query", out JsonElement q) && q.TryGetProperty("pages", out JsonElement pages))
{
if (pages.ValueKind == JsonValueKind.Array)
foreach (JsonElement p in pages.EnumerateArray()) list.Add(p.Clone());
else if (pages.ValueKind == JsonValueKind.Object)
foreach (JsonProperty p in pages.EnumerateObject()) list.Add(p.Value.Clone());
}
}
catch (JsonException) { }
return list;
}
/// <summary>Titles in requests of at most <see cref="TitlesPerRequest"/>, joined with '|'.</summary>
public static List<string> Batches(IReadOnlyList<string> titles)
{
var list = new List<string>();
for (int i = 0; i < titles.Count; i += TitlesPerRequest)
{
int n = Math.Min(TitlesPerRequest, titles.Count - i);
var part = new string[n];
for (int k = 0; k < n; k++) part[k] = titles[i + k];
list.Add(string.Join("|", part));
}
return list;
}
private static string Str(JsonElement o, string name) =>
o.ValueKind == JsonValueKind.Object && o.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.String ? v.GetString() ?? "" : "";
}