// ============================================================================
// RynthSuite - Plugins/Shared/QuestGuideData.cs
// A quest guide (2026-11-27): wiki quests as a quest reader shows them, each
// with its summary, its walkthrough as steps (the coordinates, the quest flags
// ("stamps") each step gives, the items it names), its loot and its rewards;
// plus a wiki's kill task list, society quests by rank, and contracts.
// One JSON form, written by whoever reads a wiki (RynthOracle's AC Community
// Wiki feed, or a server plugin for its own wiki, handed over through
// "RynthServer.QuestGuide") and read by RynthOracle's Guide tab. Linked source,
// so writer and reader can't drift. No reflection serializer (NativeAOT
// plugins): written with Utf8JsonWriter, read with JsonDocument, leniently.
// The shape follows SilentKelpie's guide (Forgejo rynth PR #12); re-implemented.
// ============================================================================
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Text.Json;
using System.Text.RegularExpressions;
namespace RynthCore.Plugin.Shared;
/// One walkthrough step: what to do, where, the stamps it gives and the items it names.
internal sealed class GuideStep
{
public string Text = "";
/// The step's sub-lines (tips), plain text.
public List Notes = new();
/// Coordinates the step gives, written "28.5S, 90.9W".
public List Coords = new();
/// The quest flags the step gives, as the wiki writes them.
public List Stamps = new();
/// The items the step names.
public List Items = new();
}
/// One quest of a guide.
internal sealed class GuideQuest
{
public string Title = "";
public string Url = "";
/// The page's revision id (an unchanged page isn't fetched again); 0 unknown.
public long Rev;
public string Level = "";
public string RecommendedLevel = "";
public string Type = "";
/// The summary box's "Kill Task" value as written ("Yes", "No", ""), see .
public string KillTask = "";
public string StartsWith = "";
public string StartsAt = "";
/// The repeat timer as the wiki writes it ("20 Hours"); "" = none given.
public string Repeat = "";
/// The repeat timer in seconds: 0 one-time (or none given), -1 given but not understood.
public long RepeatSec;
public string TimeToComplete = "";
/// The society rank the quest is for ("Initiate", ...), from the summary box; "" none.
public string SocietyRank = "";
public List Categories = new();
public string Overview = "";
public List Steps = new();
/// Stamps the page lists that no step could be tied to.
public List ExtraStamps = new();
/// Items to pick up on the way (named in a step that kills, loots or finds something).
public List Loot = new();
public List Rewards = new();
/// Every stamp of the quest, steps first, each once.
public List AllStamps()
{
var seen = new HashSet(StringComparer.Ordinal);
var list = new List();
foreach (GuideStep s in Steps)
foreach (string st in s.Stamps)
if (seen.Add(GuideStamp.Key(st))) list.Add(st);
foreach (string st in ExtraStamps)
if (seen.Add(GuideStamp.Key(st))) list.Add(st);
return list;
}
/// Repeats within a day (26 h allows for the wiki's "about a day").
public bool IsDaily => RepeatSec > 0 && RepeatSec <= 26 * 3600;
/// Repeats in more than a day, up to about a month.
public bool IsWeekly => RepeatSec > 26 * 3600 && RepeatSec <= 31L * 86400;
/// No repeat timer given: a one-time (story) quest.
public bool IsOneTime => RepeatSec == 0;
///
/// A kill task by its own page: the summary box says "Kill Task = Yes" (or True), or, when the box doesn't
/// say, the title does ("... Kill Task", "Kill: ..."). The guide's Kill Tasks category also counts
/// ().
///
public bool IsKillTaskPage
{
get
{
string k = KillTask.Trim();
if (k.Length > 0) return k.StartsWith("y", StringComparison.OrdinalIgnoreCase) || k.StartsWith("t", StringComparison.OrdinalIgnoreCase);
return Title.Contains("Kill Task", StringComparison.OrdinalIgnoreCase)
|| Title.Contains("Killtask", StringComparison.OrdinalIgnoreCase)
|| Title.StartsWith("Kill:", StringComparison.OrdinalIgnoreCase);
}
}
private static readonly Regex KillCountRx = new(
@"\b(?:kill|slay|hunt|defeat|destroy)\s+(?:a\s+total\s+of\s+)?(?\d{1,5})\b",
RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
/// How many kills the walkthrough asks for ("Kill 100 Drudge Lurkers"), from the first step that says; 0 none.
public int KillTarget
{
get
{
foreach (GuideStep s in Steps)
{
Match m = KillCountRx.Match(s.Text);
if (m.Success && int.TryParse(m.Groups["n"].Value, NumberStyles.None, CultureInfo.InvariantCulture, out int n) && n > 0) return n;
}
return 0;
}
}
/// The creature a kill task names, as a key ("Drudge Lurker Kill Task" -> "drudgelurker").
public string KillCreatureKey
{
get
{
string t = Title;
foreach (string cut in new[] { "Kill Task", "Killtask", "Kill:" })
t = t.Replace(cut, " ", StringComparison.OrdinalIgnoreCase);
return KillKey(t);
}
}
/// A creature name as a key, a plural "s" dropped ("Drudge Lurkers" -> "drudgelurker").
public static string KillKey(string name)
{
string k = GuideStamp.Key(name);
return k.Length > 4 && k.EndsWith('s') ? k[..^1] : k;
}
}
/// A contract: the item bought or given that starts or repeats a quest, where it comes from, and its quests.
internal sealed class GuideContract
{
public string Title = "";
public string Name = "";
public string Url = "";
public long Rev;
public string Description = "";
public string Level = "";
/// Where it comes from, as the page's notes say.
public string Where = "";
/// The person it comes from (the first link in ), for RynthNav.
public string Npc = "";
/// The quests it is for.
public List Quests = new();
}
/// Stamp names as the server and the wikis write them, compared alike.
internal static class GuideStamp
{
/// Lower-case letters and digits only: "Shiny_Red_Stone", "shinyredstone" and "Shiny Red Stone" are one stamp.
public static string Key(string? stamp)
{
if (string.IsNullOrEmpty(stamp)) return "";
var sb = new StringBuilder(stamp.Length);
foreach (char ch in stamp)
if (char.IsLetterOrDigit(ch)) sb.Append(char.ToLowerInvariant(ch));
return sb.ToString();
}
private static readonly Regex Qualifier = new(
@"^(?\S+)\s+(?:(?:on|after|when|at|for|per|if|once|each|every|until|then|from)\b|\().*$",
RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
///
/// A stamp as a page writes it, cut to the flag: "KillTaskFoo_0101 on first completion" is the flag, and so
/// is "You've stamped Foo!". A stamp of plain words ("Shiny Red Stone Found") is left whole.
///
public static string Clean(string? stamp)
{
if (string.IsNullOrWhiteSpace(stamp)) return "";
string s = stamp.Trim();
if (FromChat(s) is string chat) s = chat;
Match m = Qualifier.Match(s);
if (m.Success) s = m.Groups["stamp"].Value;
return s.TrimEnd('!', '.', ',', ';', ':', ' ');
}
/// The stamp in a "You've stamped X!" chat line, or null.
public static string? FromChat(string? line)
{
if (string.IsNullOrEmpty(line)) return null;
const string Lead = "You've stamped ";
int i = line.IndexOf(Lead, StringComparison.OrdinalIgnoreCase);
if (i < 0) return null;
string rest = line.Substring(i + Lead.Length).Trim().TrimEnd('!', '.', ' ');
return rest.Length is > 0 and <= 120 ? rest : null;
}
}
/// A whole guide: its quests and lists, where they came from and when.
internal sealed class QuestGuide
{
public const int Schema = 1;
/// The page reader that made it (QuestWikiText.ReaderVersion): a guide from an older reader is read again whole.
public int Reader = 1;
/// Where it was read from, for the reader to show ("asheron.fandom.com").
public string Source = "";
public DateTime UpdatedUtc = DateTime.MinValue;
public List Quests = new();
/// The wiki's kill task list (page titles).
public List KillTasks = new();
/// Society quests by the rank they are for (title -> "Initiate", ...), from the wiki's society categories.
public Dictionary Society = new(StringComparer.OrdinalIgnoreCase);
public List Contracts = new();
public bool IsEmpty => Quests.Count == 0 && Contracts.Count == 0;
/// The society rank a quest is for: its summary box's, else its society category's; "" none.
public string SocietyRankOf(GuideQuest q) =>
q.SocietyRank.Length > 0 ? q.SocietyRank : Society.TryGetValue(q.Title, out string? r) ? r : "";
private HashSet? _killSet;
private List? _killSetOf;
/// A kill task: its own page says so, or the guide's kill task list names it.
public bool IsKillTask(GuideQuest q)
{
if (q.IsKillTaskPage) return true;
if (KillTasks.Count == 0) return false;
if (!ReferenceEquals(_killSetOf, KillTasks))
{
_killSet = new HashSet(KillTasks, StringComparer.OrdinalIgnoreCase);
_killSetOf = KillTasks;
}
return _killSet!.Contains(q.Title);
}
public GuideQuest? Find(string title)
{
foreach (GuideQuest q in Quests)
if (string.Equals(q.Title, title, StringComparison.OrdinalIgnoreCase)) return q;
return null;
}
// ── JSON ────────────────────────────────────────────────────────────────
public string ToJson()
{
using var ms = new MemoryStream();
using (var w = new Utf8JsonWriter(ms))
{
w.WriteStartObject();
w.WriteNumber("schema", Schema);
w.WriteNumber("reader", Reader);
w.WriteString("source", Source);
w.WriteString("updated", UpdatedUtc == DateTime.MinValue ? "" : UpdatedUtc.ToString("o", CultureInfo.InvariantCulture));
w.WriteStartArray("quests");
foreach (GuideQuest q in Quests)
{
w.WriteStartObject();
w.WriteString("title", q.Title);
Opt(w, "url", q.Url);
if (q.Rev != 0) w.WriteNumber("rev", q.Rev);
Opt(w, "level", q.Level);
Opt(w, "recLevel", q.RecommendedLevel);
Opt(w, "type", q.Type);
Opt(w, "killTask", q.KillTask);
Opt(w, "startsWith", q.StartsWith);
Opt(w, "startsAt", q.StartsAt);
Opt(w, "repeat", q.Repeat);
if (q.RepeatSec != 0) w.WriteNumber("repeatSec", q.RepeatSec);
Opt(w, "time", q.TimeToComplete);
Opt(w, "societyRank", q.SocietyRank);
Arr(w, "categories", q.Categories);
Opt(w, "overview", q.Overview);
if (q.Steps.Count > 0)
{
w.WriteStartArray("steps");
foreach (GuideStep s in q.Steps)
{
w.WriteStartObject();
w.WriteString("text", s.Text);
Arr(w, "notes", s.Notes);
Arr(w, "coords", s.Coords);
Arr(w, "stamps", s.Stamps);
Arr(w, "items", s.Items);
w.WriteEndObject();
}
w.WriteEndArray();
}
Arr(w, "extraStamps", q.ExtraStamps);
Arr(w, "loot", q.Loot);
Arr(w, "rewards", q.Rewards);
w.WriteEndObject();
}
w.WriteEndArray();
Arr(w, "killTasks", KillTasks);
if (Society.Count > 0)
{
w.WriteStartObject("society");
foreach (KeyValuePair kv in Society) w.WriteString(kv.Key, kv.Value);
w.WriteEndObject();
}
if (Contracts.Count > 0)
{
w.WriteStartArray("contracts");
foreach (GuideContract c in Contracts)
{
w.WriteStartObject();
w.WriteString("title", c.Title);
Opt(w, "name", c.Name == c.Title ? "" : c.Name);
Opt(w, "url", c.Url);
if (c.Rev != 0) w.WriteNumber("rev", c.Rev);
Opt(w, "description", c.Description);
Opt(w, "level", c.Level);
Opt(w, "where", c.Where);
Opt(w, "npc", c.Npc);
Arr(w, "quests", c.Quests);
w.WriteEndObject();
}
w.WriteEndArray();
}
w.WriteEndObject();
}
return Encoding.UTF8.GetString(ms.ToArray());
}
private static void Opt(Utf8JsonWriter w, string name, string value)
{
if (!string.IsNullOrEmpty(value)) w.WriteString(name, value);
}
private static void Arr(Utf8JsonWriter w, string name, List items)
{
if (items.Count == 0) return;
w.WriteStartArray(name);
foreach (string s in items) w.WriteStringValue(s);
w.WriteEndArray();
}
/// Reads a guide; an empty guide when the text isn't one (missing fields read as empty).
public static QuestGuide Parse(string? json)
{
var g = new QuestGuide();
if (string.IsNullOrWhiteSpace(json)) return g;
try
{
using JsonDocument doc = JsonDocument.Parse(json);
JsonElement root = doc.RootElement;
if (root.ValueKind != JsonValueKind.Object) return g;
if (Long(root, "schema") is long schema && schema != 0 && schema != Schema) return g;
g.Reader = (int)Math.Max(1, Long(root, "reader"));
g.Source = Str(root, "source");
if (DateTime.TryParse(Str(root, "updated"), CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out DateTime t))
g.UpdatedUtc = t.ToUniversalTime();
if (root.TryGetProperty("quests", out JsonElement qs) && qs.ValueKind == JsonValueKind.Array)
foreach (JsonElement e in qs.EnumerateArray())
if (ReadQuest(e) is GuideQuest q) g.Quests.Add(q);
g.KillTasks = Strs(root, "killTasks");
if (root.TryGetProperty("society", out JsonElement so) && so.ValueKind == JsonValueKind.Object)
foreach (JsonProperty p in so.EnumerateObject())
if (p.Value.ValueKind == JsonValueKind.String) g.Society[p.Name] = p.Value.GetString() ?? "";
if (root.TryGetProperty("contracts", out JsonElement cs) && cs.ValueKind == JsonValueKind.Array)
foreach (JsonElement e in cs.EnumerateArray())
{
if (e.ValueKind != JsonValueKind.Object) continue;
var c = new GuideContract
{
Title = Str(e, "title"), Url = Str(e, "url"), Rev = Long(e, "rev"), Description = Str(e, "description"),
Level = Str(e, "level"), Where = Str(e, "where"), Npc = Str(e, "npc"), Quests = Strs(e, "quests"),
};
string n = Str(e, "name");
c.Name = n.Length > 0 ? n : c.Title;
if (c.Title.Length > 0) g.Contracts.Add(c);
}
}
catch (JsonException)
{
return new QuestGuide();
}
return g;
}
private static GuideQuest? ReadQuest(JsonElement e)
{
if (e.ValueKind != JsonValueKind.Object) return null;
var q = new GuideQuest
{
Title = Str(e, "title"), Url = Str(e, "url"), Rev = Long(e, "rev"),
Level = Str(e, "level"), RecommendedLevel = Str(e, "recLevel"), Type = Str(e, "type"), KillTask = Str(e, "killTask"),
StartsWith = Str(e, "startsWith"), StartsAt = Str(e, "startsAt"), Repeat = Str(e, "repeat"), RepeatSec = Long(e, "repeatSec"),
TimeToComplete = Str(e, "time"), SocietyRank = Str(e, "societyRank"), Categories = Strs(e, "categories"),
Overview = Str(e, "overview"), ExtraStamps = Stamps(Strs(e, "extraStamps")), Loot = Strs(e, "loot"), Rewards = Strs(e, "rewards"),
};
if (q.Title.Length == 0) return null;
if (e.TryGetProperty("steps", out JsonElement ss) && ss.ValueKind == JsonValueKind.Array)
foreach (JsonElement s in ss.EnumerateArray())
{
if (s.ValueKind != JsonValueKind.Object) continue;
q.Steps.Add(new GuideStep
{
Text = Str(s, "text"), Notes = Strs(s, "notes"), Coords = Strs(s, "coords"),
Stamps = Stamps(Strs(s, "stamps")), Items = Strs(s, "items"),
});
}
return q;
}
/// Stamps cut to their flags (GuideStamp.Clean), each once.
private static List Stamps(List raw)
{
var list = new List(raw.Count);
foreach (string r in raw)
{
string s = GuideStamp.Clean(r);
if (s.Length > 0 && !list.Exists(x => GuideStamp.Key(x) == GuideStamp.Key(s))) list.Add(s);
}
return list;
}
private static string Str(JsonElement o, string name) =>
o.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.String ? v.GetString() ?? "" : "";
private static long Long(JsonElement o, string name) =>
o.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.Number && v.TryGetInt64(out long n) ? n : 0;
private static List Strs(JsonElement o, string name)
{
var list = new List();
if (!o.TryGetProperty(name, out JsonElement a) || a.ValueKind != JsonValueKind.Array) return list;
foreach (JsonElement e in a.EnumerateArray())
if (e.ValueKind == JsonValueKind.String && e.GetString() is { Length: > 0 } s) list.Add(s);
return list;
}
}