// The AC Community Wiki feed (2026-11-27): RynthOracle's own quest guide, read from asheron.fandom.com's public // MediaWiki API (no login), on every server. OFF by default: nothing is fetched until the player turns it on, and // the About tab, the Guide tab and "/ro wiki on" say what is read and from where before the first read. // Only the reader ships: no wiki text is bundled. The read follows SilentKelpie's (Forgejo rynth PR #12); // re-implemented here. What it reads: // - the quests: every page with the {{Quest Summary}} box, and the pages under Category:Quests (its // sub-categories followed, item / NPC / image lists left out); // - the kill tasks: Category:Kill_Tasks and its sub-categories; // - the society quests: Category:Society_Quests, each page's rank from the sub-category it is in; // - the contracts: Category:Contracts' item pages. // Only pages edited since the last read are fetched (their revision ids), unless the page reader is newer // (QuestWikiText.ReaderVersion). Saved to %APPDATA%\RynthCore\RynthOracle\community-wiki-guide.json. The read runs // on a pool thread and only builds a new guide and writes the file; the pump takes it (TakeResult). With the feed // on, it reads at login when the saved copy is a day old (or none), and on "Read now". using System; using System.Collections.Generic; using System.IO; using System.Net.Http; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using RynthCore.Plugin.Shared; namespace RynthCore.Plugin.RynthOracle.Data; internal sealed class CommunityWikiFeed { public const string Host = "asheron.fandom.com"; public const string Api = "https://asheron.fandom.com/api.php"; public const string WikiBase = "https://asheron.fandom.com/wiki/"; public const string QuestTemplate = "Template:Quest_Summary"; public const string QuestsCategory = "Category:Quests"; public const string KillTasksCategory = "Category:Kill_Tasks"; public const string SocietyCategory = "Category:Society_Quests"; public const string ContractsCategory = "Category:Contracts"; public static readonly TimeSpan RefreshAfter = TimeSpan.FromHours(24); /// Category:Quests is a tree: at most this many categories are followed. internal const int MaxCategories = 400; /// No read lists more pages than this (a wiki that grew wildly, or a loop). internal const int MaxPages = 5000; private const int RequestGapMs = 250; /// What the feed reads and from where: said before the first read (About, Guide, /ro wiki on). public const string WhatItReads = "the quest, kill task, society quest and contract pages of the AC Community Wiki, from " + Api + " (public pages, no login; about a thousand pages the first time, then only the pages edited since; " + "requests a quarter second apart). Nothing about you or your character is sent."; /// Where the tests keep the guide file (a scratch path); null is the player's %APPDATA% copy. internal static string? PathOverride; public static string DefaultPath => PathOverride ?? Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "RynthCore", "RynthOracle", "community-wiki-guide.json"); private readonly string _path; private CancellationTokenSource? _cts; private Task? _task; private volatile QuestGuide? _ready; private volatile string _status; private bool _loginReadDone; /// The guide in use (pump thread): the saved one until a read replaces it. public QuestGuide Guide { get; private set; } = new(); /// Goes up when is replaced. public int Revision { get; private set; } public bool Running => _task is { IsCompleted: false }; public string Status => _status; public string FilePath => _path; public CommunityWikiFeed(string? path = null) { _path = path ?? DefaultPath; try { if (File.Exists(_path)) Guide = QuestGuide.Parse(File.ReadAllText(_path)); } catch { Guide = new QuestGuide(); } _status = Guide.IsEmpty ? "not read yet" : Summary(Guide); } public static string Summary(QuestGuide g) => $"{g.Quests.Count} quests, {g.KillTasks.Count} kill tasks, {g.Society.Count} society quests, {g.Contracts.Count} contracts" + (g.UpdatedUtc == DateTime.MinValue ? "" : $" (read {g.UpdatedUtc.ToLocalTime():yyyy-MM-dd HH:mm})"); /// The saved guide wants reading: none yet, a day old, or made by an older page reader. internal static bool Due(QuestGuide g, DateTime utcNow) => g.IsEmpty || g.Reader < QuestWikiText.ReaderVersion || utcNow - g.UpdatedUtc >= RefreshAfter; /// Pump thread, at login with the feed on: one read a session, when the saved guide is due. True when it started one. public bool LoginRead(bool on, bool daily, DateTime utcNow) { if (!on || !daily || _loginReadDone) return false; _loginReadDone = true; return Due(Guide, utcNow) && Start(on); } /// Starts a read: only with the feed on, and not while one runs. Pump thread. public bool Start(bool on) { if (!on || Running) return false; _cts?.Dispose(); _cts = new CancellationTokenSource(); CancellationToken token = _cts.Token; QuestGuide old = Guide; _status = "reading..."; _task = Task.Run(async () => { try { _status = await ReadAsync(old, token).ConfigureAwait(false); } catch (OperationCanceledException) { _status = "stopped"; } catch (Exception ex) { _status = "couldn't read the wiki: " + ex.GetType().Name + ": " + ex.Message; } }, token); return true; } /// Stops a read under way (the feed turned off). Pump thread. public void Stop() { try { _cts?.Cancel(); } catch { } } /// Pump thread: takes a finished read's guide; true when the guide changed. public bool TakeResult() { QuestGuide? g = _ready; if (g == null) return false; _ready = null; Guide = g; Revision++; return true; } /// Uses a guide (the tests). internal void Use(QuestGuide g) { Guide = g; Revision++; } public void Shutdown() { try { _cts?.Cancel(); _task?.Wait(2000); } catch { } } // ── The read (pool thread) ────────────────────────────────────────────── private static readonly Regex RankRx = new(@"(?:^|:\s*)(\w+)\s+Rank\b", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); /// The society rank a society sub-category stands for ("Society Quests: Knight Rank" is Knight), or "". 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" : ""; } /// A sub-category not followed: item, NPC, image and map lists, not quests. internal static bool SkipCategory(string category) => category.Contains("Quest Items", StringComparison.OrdinalIgnoreCase) || category.Contains("Items", StringComparison.OrdinalIgnoreCase) && !category.Contains("Quest", StringComparison.OrdinalIgnoreCase) || category.Contains("NPC", StringComparison.OrdinalIgnoreCase) || category.Contains("Images", StringComparison.OrdinalIgnoreCase) || category.Contains("Maps", StringComparison.OrdinalIgnoreCase); private async Task ReadAsync(QuestGuide old, CancellationToken token) { using var http = new HttpClient { Timeout = TimeSpan.FromSeconds(30) }; http.DefaultRequestHeaders.UserAgent.ParseAdd("RynthOracle/" + RynthOraclePlugin.Version + " (RynthCore quest guide)"); var titles = new SortedSet(StringComparer.Ordinal); var killTasks = new SortedSet(StringComparer.Ordinal); var contracts = new SortedSet(StringComparer.Ordinal); var society = new Dictionary(StringComparer.OrdinalIgnoreCase); void Add(string p) { if (titles.Count < MaxPages) titles.Add(p); } _status = "listing the quest pages..."; await ListAsync(http, "embeddedin", new[] { ("list", "embeddedin"), ("eititle", QuestTemplate), ("einamespace", "0"), ("eilimit", "max") }, Add, _ => { }, token).ConfigureAwait(false); await WalkAsync(http, QuestsCategory, (p, _) => Add(p), token).ConfigureAwait(false); _status = "listing the kill tasks..."; await WalkAsync(http, KillTasksCategory, (p, _) => { killTasks.Add(p); Add(p); }, token).ConfigureAwait(false); _status = "listing the society quests..."; await WalkAsync(http, SocietyCategory, (p, cat) => { Add(p); string rank = RankOf(cat); if (rank.Length > 0) society.TryAdd(p, rank); }, token).ConfigureAwait(false); _status = "listing the contracts..."; await ListAsync(http, "categorymembers", new[] { ("list", "categorymembers"), ("cmtitle", ContractsCategory), ("cmlimit", "max"), ("cmtype", "page") }, p => { contracts.Add(p); Add(p); }, _ => { }, token).ConfigureAwait(false); if (titles.Count == 0) return "the wiki listed no quest pages"; var list = new List(titles); var revs = new Dictionary(StringComparer.Ordinal); int done = 0; foreach (string batch in QuestWikiText.Batches(list)) { _status = $"checking pages ({done}/{list.Count})..."; string json = await GetAsync(http, QuestWikiText.ApiUrl(Api, ("action", "query"), ("prop", "info"), ("titles", batch)), token).ConfigureAwait(false); foreach (KeyValuePair kv in QuestWikiText.LastRevisions(json)) revs[kv.Key] = kv.Value; done += QuestWikiText.TitlesPerRequest; } List changed = PagesToRead(old, revs); var fresh = new Dictionary(StringComparer.Ordinal); var freshContracts = new Dictionary(StringComparer.Ordinal); int read = 0; foreach (string batch in QuestWikiText.Batches(changed)) { _status = $"reading pages ({read}/{changed.Count})..."; string json = await GetAsync(http, QuestWikiText.ApiUrl(Api, ("action", "query"), ("prop", "revisions"), ("rvprop", "content|ids"), ("rvslots", "main"), ("titles", batch)), token).ConfigureAwait(false); foreach (var (title, rev, text) in QuestWikiText.Contents(json)) { if (QuestWikiText.IsQuestPage(text)) fresh[title] = QuestWikiText.ParseQuest(title, text, rev, WikiBase); else if (contracts.Contains(title) && QuestWikiText.IsContractPage(title, text)) freshContracts[title] = QuestWikiText.ParseContract(title, text, rev, WikiBase); } read += QuestWikiText.TitlesPerRequest; } QuestGuide g = Merge(old, revs, fresh, freshContracts, DateTime.UtcNow); g.KillTasks = new List(killTasks); g.Society = society; token.ThrowIfCancellationRequested(); string saved = ""; try { Directory.CreateDirectory(Path.GetDirectoryName(_path)!); File.WriteAllText(_path + ".tmp", g.ToJson()); File.Move(_path + ".tmp", _path, overwrite: true); } catch (Exception ex) { saved = "; couldn't save it: " + ex.Message; } _ready = g; return $"{Summary(g)}; {fresh.Count + freshContracts.Count} pages read now{saved}"; } /// The pages to read: new or edited since the saved guide; every one when it came from an older reader. internal static List PagesToRead(QuestGuide old, IReadOnlyDictionary revs) { var known = new Dictionary(StringComparer.Ordinal); foreach (GuideQuest q in old.Quests) known[q.Title] = q.Rev; foreach (GuideContract c in old.Contracts) known[c.Title] = c.Rev; bool whole = old.Reader < QuestWikiText.ReaderVersion; var changed = new List(); foreach (KeyValuePair kv in revs) if (whole || kv.Value == 0 || !known.TryGetValue(kv.Key, out long rev) || rev != kv.Value) changed.Add(kv.Key); return changed; } /// /// 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; a page that isn't a quest or contract isn't kept (it is checked again next time). /// internal static QuestGuide Merge(QuestGuide old, IReadOnlyDictionary listed, IReadOnlyDictionary fresh, IReadOnlyDictionary freshContracts, DateTime utcNow) { var oldQuests = new Dictionary(StringComparer.Ordinal); foreach (GuideQuest q in old.Quests) oldQuests[q.Title] = q; var oldContracts = new Dictionary(StringComparer.Ordinal); foreach (GuideContract c in old.Contracts) oldContracts[c.Title] = c; var g = new QuestGuide { Source = Host, UpdatedUtc = utcNow, Reader = QuestWikiText.ReaderVersion, KillTasks = old.KillTasks, Society = old.Society }; 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; } /// A category's pages and, breadth first, its sub-categories' (each page with the category it was in). private static async Task WalkAsync(HttpClient http, string root, Action page, CancellationToken token) { var queue = new Queue(); var seen = new HashSet(StringComparer.OrdinalIgnoreCase) { root.Replace('_', ' '), root }; queue.Enqueue(root); while (queue.Count > 0 && seen.Count <= MaxCategories) { string cat = queue.Dequeue(); await ListAsync(http, "categorymembers", new[] { ("list", "categorymembers"), ("cmtitle", cat), ("cmlimit", "max"), ("cmtype", "page|subcat") }, p => page(p, cat), sub => { if (!SkipCategory(sub) && seen.Add(sub)) queue.Enqueue(sub); }, token).ConfigureAwait(false); } } private static async Task ListAsync(HttpClient http, string listName, (string, string)[] args, Action page, Action sub, CancellationToken token) { var cont = new List<(string, string)>(); for (int i = 0; i < 100; i++) { var all = new List<(string, string)> { ("action", "query") }; all.AddRange(args); all.AddRange(cont); string json = await GetAsync(http, QuestWikiText.ApiUrl(Api, all.ToArray()), token).ConfigureAwait(false); var (pages, subs, next) = QuestWikiText.Members(json, listName); foreach (string p in pages) page(p); foreach (string s in subs) sub(s); if (next.Count == 0) return; cont = next; } } private static async Task GetAsync(HttpClient http, string url, CancellationToken token) { await Task.Delay(RequestGapMs, token).ConfigureAwait(false); using HttpResponseMessage resp = await http.GetAsync(url + "&maxlag=5", token).ConfigureAwait(false); resp.EnsureSuccessStatusCode(); return await resp.Content.ReadAsStringAsync(token).ConfigureAwait(false); } }