RynthSuite/Plugins/Shared/QuestGuideData.cs

440 lines
19 KiB
C#

// ============================================================================
// 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;
/// <summary>One walkthrough step: what to do, where, the stamps it gives and the items it names.</summary>
internal sealed class GuideStep
{
public string Text = "";
/// <summary>The step's sub-lines (tips), plain text.</summary>
public List<string> Notes = new();
/// <summary>Coordinates the step gives, written "28.5S, 90.9W".</summary>
public List<string> Coords = new();
/// <summary>The quest flags the step gives, as the wiki writes them.</summary>
public List<string> Stamps = new();
/// <summary>The items the step names.</summary>
public List<string> Items = new();
}
/// <summary>One quest of a guide.</summary>
internal sealed class GuideQuest
{
public string Title = "";
public string Url = "";
/// <summary>The page's revision id (an unchanged page isn't fetched again); 0 unknown.</summary>
public long Rev;
public string Level = "";
public string RecommendedLevel = "";
public string Type = "";
/// <summary>The summary box's "Kill Task" value as written ("Yes", "No", ""), see <see cref="IsKillTask"/>.</summary>
public string KillTask = "";
public string StartsWith = "";
public string StartsAt = "";
/// <summary>The repeat timer as the wiki writes it ("20 Hours"); "" = none given.</summary>
public string Repeat = "";
/// <summary>The repeat timer in seconds: 0 one-time (or none given), -1 given but not understood.</summary>
public long RepeatSec;
public string TimeToComplete = "";
/// <summary>The society rank the quest is for ("Initiate", ...), from the summary box; "" none.</summary>
public string SocietyRank = "";
public List<string> Categories = new();
public string Overview = "";
public List<GuideStep> Steps = new();
/// <summary>Stamps the page lists that no step could be tied to.</summary>
public List<string> ExtraStamps = new();
/// <summary>Items to pick up on the way (named in a step that kills, loots or finds something).</summary>
public List<string> Loot = new();
public List<string> Rewards = new();
/// <summary>Every stamp of the quest, steps first, each once.</summary>
public List<string> AllStamps()
{
var seen = new HashSet<string>(StringComparer.Ordinal);
var list = new List<string>();
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;
}
/// <summary>Repeats within a day (26 h allows for the wiki's "about a day").</summary>
public bool IsDaily => RepeatSec > 0 && RepeatSec <= 26 * 3600;
/// <summary>Repeats in more than a day, up to about a month.</summary>
public bool IsWeekly => RepeatSec > 26 * 3600 && RepeatSec <= 31L * 86400;
/// <summary>No repeat timer given: a one-time (story) quest.</summary>
public bool IsOneTime => RepeatSec == 0;
/// <summary>
/// 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
/// (<see cref="QuestGuide.IsKillTask"/>).
/// </summary>
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+)?(?<n>\d{1,5})\b",
RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
/// <summary>How many kills the walkthrough asks for ("Kill 100 Drudge Lurkers"), from the first step that says; 0 none.</summary>
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;
}
}
/// <summary>The creature a kill task names, as a key ("Drudge Lurker Kill Task" -> "drudgelurker").</summary>
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);
}
}
/// <summary>A creature name as a key, a plural "s" dropped ("Drudge Lurkers" -> "drudgelurker").</summary>
public static string KillKey(string name)
{
string k = GuideStamp.Key(name);
return k.Length > 4 && k.EndsWith('s') ? k[..^1] : k;
}
}
/// <summary>A contract: the item bought or given that starts or repeats a quest, where it comes from, and its quests.</summary>
internal sealed class GuideContract
{
public string Title = "";
public string Name = "";
public string Url = "";
public long Rev;
public string Description = "";
public string Level = "";
/// <summary>Where it comes from, as the page's notes say.</summary>
public string Where = "";
/// <summary>The person it comes from (the first link in <see cref="Where"/>), for RynthNav.</summary>
public string Npc = "";
/// <summary>The quests it is for.</summary>
public List<string> Quests = new();
}
/// <summary>Stamp names as the server and the wikis write them, compared alike.</summary>
internal static class GuideStamp
{
/// <summary>Lower-case letters and digits only: "Shiny_Red_Stone", "shinyredstone" and "Shiny Red Stone" are one stamp.</summary>
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(
@"^(?<stamp>\S+)\s+(?:(?:on|after|when|at|for|per|if|once|each|every|until|then|from)\b|\().*$",
RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
/// <summary>
/// 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.
/// </summary>
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('!', '.', ',', ';', ':', ' ');
}
/// <summary>The stamp in a "You've stamped X!" chat line, or null.</summary>
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;
}
}
/// <summary>A whole guide: its quests and lists, where they came from and when.</summary>
internal sealed class QuestGuide
{
public const int Schema = 1;
/// <summary>The page reader that made it (QuestWikiText.ReaderVersion): a guide from an older reader is read again whole.</summary>
public int Reader = 1;
/// <summary>Where it was read from, for the reader to show ("asheron.fandom.com").</summary>
public string Source = "";
public DateTime UpdatedUtc = DateTime.MinValue;
public List<GuideQuest> Quests = new();
/// <summary>The wiki's kill task list (page titles).</summary>
public List<string> KillTasks = new();
/// <summary>Society quests by the rank they are for (title -> "Initiate", ...), from the wiki's society categories.</summary>
public Dictionary<string, string> Society = new(StringComparer.OrdinalIgnoreCase);
public List<GuideContract> Contracts = new();
public bool IsEmpty => Quests.Count == 0 && Contracts.Count == 0;
/// <summary>The society rank a quest is for: its summary box's, else its society category's; "" none.</summary>
public string SocietyRankOf(GuideQuest q) =>
q.SocietyRank.Length > 0 ? q.SocietyRank : Society.TryGetValue(q.Title, out string? r) ? r : "";
private HashSet<string>? _killSet;
private List<string>? _killSetOf;
/// <summary>A kill task: its own page says so, or the guide's kill task list names it.</summary>
public bool IsKillTask(GuideQuest q)
{
if (q.IsKillTaskPage) return true;
if (KillTasks.Count == 0) return false;
if (!ReferenceEquals(_killSetOf, KillTasks))
{
_killSet = new HashSet<string>(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<string, string> 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<string> items)
{
if (items.Count == 0) return;
w.WriteStartArray(name);
foreach (string s in items) w.WriteStringValue(s);
w.WriteEndArray();
}
/// <summary>Reads a guide; an empty guide when the text isn't one (missing fields read as empty).</summary>
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;
}
/// <summary>Stamps cut to their flags (GuideStamp.Clean), each once.</summary>
private static List<string> Stamps(List<string> raw)
{
var list = new List<string>(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<string> Strs(JsonElement o, string name)
{
var list = new List<string>();
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;
}
}