RynthSuite as of 2026-11-29 (internal 46bae49): release 2026.11.28.1
This commit is contained in:
parent
25552fa794
commit
598f49c899
131 changed files with 11825 additions and 329 deletions
313
Plugins/RynthCore.Plugin.RynthOracle/Data/CommunityWikiFeed.cs
Normal file
313
Plugins/RynthCore.Plugin.RynthOracle/Data/CommunityWikiFeed.cs
Normal file
|
|
@ -0,0 +1,313 @@
|
|||
// 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);
|
||||
/// <summary>Category:Quests is a tree: at most this many categories are followed.</summary>
|
||||
internal const int MaxCategories = 400;
|
||||
/// <summary>No read lists more pages than this (a wiki that grew wildly, or a loop).</summary>
|
||||
internal const int MaxPages = 5000;
|
||||
private const int RequestGapMs = 250;
|
||||
|
||||
/// <summary>What the feed reads and from where: said before the first read (About, Guide, /ro wiki on).</summary>
|
||||
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.";
|
||||
|
||||
/// <summary>Where the tests keep the guide file (a scratch path); null is the player's %APPDATA% copy.</summary>
|
||||
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;
|
||||
|
||||
/// <summary>The guide in use (pump thread): the saved one until a read replaces it.</summary>
|
||||
public QuestGuide Guide { get; private set; } = new();
|
||||
/// <summary>Goes up when <see cref="Guide"/> is replaced.</summary>
|
||||
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})");
|
||||
|
||||
/// <summary>The saved guide wants reading: none yet, a day old, or made by an older page reader.</summary>
|
||||
internal static bool Due(QuestGuide g, DateTime utcNow) =>
|
||||
g.IsEmpty || g.Reader < QuestWikiText.ReaderVersion || utcNow - g.UpdatedUtc >= RefreshAfter;
|
||||
|
||||
/// <summary>Pump thread, at login with the feed on: one read a session, when the saved guide is due. True when it started one.</summary>
|
||||
public bool LoginRead(bool on, bool daily, DateTime utcNow)
|
||||
{
|
||||
if (!on || !daily || _loginReadDone) return false;
|
||||
_loginReadDone = true;
|
||||
return Due(Guide, utcNow) && Start(on);
|
||||
}
|
||||
|
||||
/// <summary>Starts a read: only with the feed on, and not while one runs. Pump thread.</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>Stops a read under way (the feed turned off). Pump thread.</summary>
|
||||
public void Stop()
|
||||
{
|
||||
try { _cts?.Cancel(); } catch { }
|
||||
}
|
||||
|
||||
/// <summary>Pump thread: takes a finished read's guide; true when the guide changed.</summary>
|
||||
public bool TakeResult()
|
||||
{
|
||||
QuestGuide? g = _ready;
|
||||
if (g == null) return false;
|
||||
_ready = null;
|
||||
Guide = g;
|
||||
Revision++;
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>Uses a guide (the tests).</summary>
|
||||
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);
|
||||
|
||||
/// <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("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<string> 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<string>(StringComparer.Ordinal);
|
||||
var killTasks = new SortedSet<string>(StringComparer.Ordinal);
|
||||
var contracts = new SortedSet<string>(StringComparer.Ordinal);
|
||||
var society = new Dictionary<string, string>(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<string>(titles);
|
||||
var revs = new Dictionary<string, long>(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<string, long> kv in QuestWikiText.LastRevisions(json)) revs[kv.Key] = kv.Value;
|
||||
done += QuestWikiText.TitlesPerRequest;
|
||||
}
|
||||
List<string> changed = PagesToRead(old, revs);
|
||||
|
||||
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 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<string>(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}";
|
||||
}
|
||||
|
||||
/// <summary>The pages to read: new or edited since the saved guide; every one when it came from an older reader.</summary>
|
||||
internal static List<string> PagesToRead(QuestGuide old, IReadOnlyDictionary<string, long> revs)
|
||||
{
|
||||
var known = new Dictionary<string, long>(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<string>();
|
||||
foreach (KeyValuePair<string, long> kv in revs)
|
||||
if (whole || kv.Value == 0 || !known.TryGetValue(kv.Key, out long rev) || rev != kv.Value) changed.Add(kv.Key);
|
||||
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; a page that isn't a quest or contract isn't kept (it is checked again next time).
|
||||
/// </summary>
|
||||
internal static QuestGuide Merge(QuestGuide old, IReadOnlyDictionary<string, long> listed,
|
||||
IReadOnlyDictionary<string, GuideQuest> fresh, IReadOnlyDictionary<string, GuideContract> freshContracts, DateTime utcNow)
|
||||
{
|
||||
var oldQuests = new Dictionary<string, GuideQuest>(StringComparer.Ordinal);
|
||||
foreach (GuideQuest q in old.Quests) oldQuests[q.Title] = q;
|
||||
var oldContracts = new Dictionary<string, GuideContract>(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;
|
||||
}
|
||||
|
||||
/// <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(HttpClient http, string root, Action<string, string> page, CancellationToken token)
|
||||
{
|
||||
var queue = new Queue<string>();
|
||||
var seen = new HashSet<string>(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<string> page, Action<string> 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<string> 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);
|
||||
}
|
||||
}
|
||||
383
Plugins/RynthCore.Plugin.RynthOracle/Data/GuideProgress.cs
Normal file
383
Plugins/RynthCore.Plugin.RynthOracle/Data/GuideProgress.cs
Normal file
|
|
@ -0,0 +1,383 @@
|
|||
// Where a guide quest stands for this character (2026-11-27), worked out from the quest flags (/myquests) and the
|
||||
// stamps seen in chat this session. The four states, the kill tasks' counts and "first time / done before", and the
|
||||
// kill lines in chat follow SilentKelpie's Guide (Forgejo rynth PR #12); re-implemented here.
|
||||
// - A stamp is held when /myquests has its flag (any spelling: GuideStamp.Key) or it was stamped this session.
|
||||
// - For a repeatable quest, a held stamp counts for this run while its flag's timer runs (or, with no timer on the
|
||||
// flag, while the quest's repeat time since it was stamped hasn't passed); after that it was done "earlier".
|
||||
// - The quest's wait is the longest redo time left on any held stamp.
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.Text.RegularExpressions;
|
||||
using RynthCore.Plugin.Shared;
|
||||
|
||||
namespace RynthCore.Plugin.RynthOracle.Data;
|
||||
|
||||
/// <summary>A quest's state in the guide's lists.</summary>
|
||||
internal enum GuideState
|
||||
{
|
||||
/// <summary>No stamp held.</summary>
|
||||
NotDone,
|
||||
/// <summary>Some stamps held, some still to get, the held ones' redo timer still running.</summary>
|
||||
PartWaiting,
|
||||
/// <summary>Some stamps held, some still to get, no timer left.</summary>
|
||||
PartReady,
|
||||
/// <summary>Every stamp held.</summary>
|
||||
Done,
|
||||
}
|
||||
|
||||
/// <summary>A stamp of a quest for this run.</summary>
|
||||
internal enum StampState { Missing, Done, Earlier }
|
||||
|
||||
/// <summary>A kill task's progress, in the order the Kill Tasks list shows them.</summary>
|
||||
internal enum KillState { TurnIn, Counting, Ready, NotStarted, Waiting, Completed }
|
||||
|
||||
/// <summary>What the guide knows of this character: its flags, the stamps seen this session and the kill lines.</summary>
|
||||
internal sealed class GuideProgress
|
||||
{
|
||||
private readonly QuestFlagStore _flags;
|
||||
private readonly HashSet<string> _sessionStamps;
|
||||
private readonly KillChat _kills;
|
||||
private Dictionary<string, QuestFlag>? _byKey;
|
||||
private int _byKeyRevision = -1;
|
||||
|
||||
public GuideProgress(QuestFlagStore flags, HashSet<string> sessionStamps, KillChat kills)
|
||||
{
|
||||
_flags = flags;
|
||||
_sessionStamps = sessionStamps;
|
||||
_kills = kills;
|
||||
}
|
||||
|
||||
/// <summary>The flag a stamp is in /myquests, by any spelling of it, or null.</summary>
|
||||
public QuestFlag? FlagOf(string stamp)
|
||||
{
|
||||
if (_flags.TryGet(stamp, out QuestFlag f)) return f;
|
||||
if (_byKeyRevision != _flags.Revision || _byKey == null)
|
||||
{
|
||||
_byKey = new Dictionary<string, QuestFlag>(StringComparer.Ordinal);
|
||||
foreach (KeyValuePair<string, QuestFlag> kv in _flags.Flags) _byKey.TryAdd(GuideStamp.Key(kv.Key), kv.Value);
|
||||
_byKeyRevision = _flags.Revision;
|
||||
}
|
||||
return _byKey.TryGetValue(GuideStamp.Key(stamp), out QuestFlag? byKey) ? byKey : null;
|
||||
}
|
||||
|
||||
public bool StampedThisSession(string stamp) => _sessionStamps.Contains(GuideStamp.Key(stamp));
|
||||
|
||||
/// <summary>A stamp of <paramref name="q"/> for this run (see the file's note).</summary>
|
||||
public StampState StateOf(GuideQuest q, string stamp, DateTime utcNow)
|
||||
{
|
||||
if (StampedThisSession(stamp)) return StampState.Done;
|
||||
if (FlagOf(stamp) is not QuestFlag f) return StampState.Missing;
|
||||
if (q.RepeatSec == 0) return StampState.Done;
|
||||
if (f.RepeatTime > TimeSpan.Zero) return f.NextAvailableTime(utcNow) > TimeSpan.Zero ? StampState.Done : StampState.Earlier;
|
||||
if (q.RepeatSec > 0 && f.CompletedOnUtc != DateTime.MinValue)
|
||||
return f.CompletedOnUtc.AddSeconds(q.RepeatSec) > utcNow ? StampState.Done : StampState.Earlier;
|
||||
return StampState.Done;
|
||||
}
|
||||
|
||||
/// <summary>The longest redo time left on the quest's held stamps; zero when none runs.</summary>
|
||||
public TimeSpan Wait(GuideQuest q, DateTime utcNow)
|
||||
{
|
||||
TimeSpan wait = TimeSpan.Zero;
|
||||
foreach (string st in q.AllStamps())
|
||||
{
|
||||
if (FlagOf(st) is not QuestFlag f) continue;
|
||||
TimeSpan left = TimeSpan.Zero;
|
||||
if (f.RepeatTime > TimeSpan.Zero) left = f.NextAvailableTime(utcNow);
|
||||
else if (q.RepeatSec > 0 && f.CompletedOnUtc != DateTime.MinValue) left = f.CompletedOnUtc.AddSeconds(q.RepeatSec) - utcNow;
|
||||
if (left > wait) wait = left;
|
||||
}
|
||||
return wait;
|
||||
}
|
||||
|
||||
/// <summary>A quest's row: its state, the list's short text, the tooltip's sentence, and whether "Hide done" leaves it out.</summary>
|
||||
public readonly record struct Row(GuideState State, string Status, string Tip, bool HideWhenDone, int Held, int All);
|
||||
|
||||
/// <summary>
|
||||
/// A quest with stamps: the four states from the stamps held and the wait. Without stamps (the AC Community Wiki
|
||||
/// lists none for most quests), <paramref name="flagDone"/> (the quest list's flag of its name) gives Done or Not done,
|
||||
/// and null means its state isn't known.
|
||||
/// </summary>
|
||||
public Row RowOf(GuideQuest q, DateTime utcNow, bool? flagDone = null)
|
||||
{
|
||||
List<string> stamps = q.AllStamps();
|
||||
if (stamps.Count == 0)
|
||||
{
|
||||
if (flagDone is bool fd)
|
||||
return fd ? new Row(GuideState.Done, "Done", "Done: the quest list's flag for it is held.", q.RepeatSec == 0, 1, 1)
|
||||
: new Row(GuideState.NotDone, "Not done", "Not done: the quest list's flag for it isn't held yet.", false, 0, 1);
|
||||
return new Row(GuideState.NotDone, "no stamps", "The wiki lists no stamps for this quest and the quest list has no flag of its name, so its state isn't known.", false, 0, 0);
|
||||
}
|
||||
int held = 0, now = 0;
|
||||
foreach (string st in stamps)
|
||||
{
|
||||
StampState s = StateOf(q, st, utcNow);
|
||||
if (s != StampState.Missing) held++;
|
||||
if (s == StampState.Done) now++;
|
||||
}
|
||||
TimeSpan wait = Wait(q, utcNow);
|
||||
bool repeats = q.RepeatSec != 0 || wait > TimeSpan.Zero;
|
||||
GuideState state = held == 0 ? GuideState.NotDone : held >= stamps.Count ? GuideState.Done
|
||||
: wait > TimeSpan.Zero ? GuideState.PartWaiting : GuideState.PartReady;
|
||||
(string status, string tip) = Text(state, held, stamps.Count, wait, repeats);
|
||||
bool hide = state == GuideState.Done && (!repeats || wait > TimeSpan.Zero || now == stamps.Count);
|
||||
return new Row(state, status, tip, hide, held, stamps.Count);
|
||||
}
|
||||
|
||||
/// <summary>The list's short status and the tooltip's sentence.</summary>
|
||||
public static (string Status, string Tip) Text(GuideState s, int held, int all, TimeSpan wait, bool repeats) => s switch
|
||||
{
|
||||
GuideState.Done when wait > TimeSpan.Zero => ("Done " + Short(wait), $"Done: all {all} stamps held. It can be done again in {Short(wait)}."),
|
||||
GuideState.Done when repeats => ("Done, redo", $"Done: all {all} stamps held, and its timer is up: it can be done again now."),
|
||||
GuideState.Done => ("Done", $"Done: all {all} stamps held."),
|
||||
GuideState.PartWaiting => ($"{held}/{all} wait {Short(wait)}", $"Part done: {held} of {all} stamps held, {all - held} still to get. The redo timer has {Short(wait)} left."),
|
||||
GuideState.PartReady => ($"{held}/{all} ready", $"Part done: {held} of {all} stamps held, {all - held} still to get. No timer is running: go get them."),
|
||||
_ => ("Not done", $"Not done: none of its {all} stamps held yet."),
|
||||
};
|
||||
|
||||
/// <summary>"3d 4h", "5h 12m", "9m".</summary>
|
||||
public static string Short(TimeSpan t)
|
||||
{
|
||||
if (t.TotalDays >= 1) return $"{(int)t.TotalDays}d {t.Hours}h";
|
||||
if (t.TotalHours >= 1) return $"{(int)t.TotalHours}h {t.Minutes:00}m";
|
||||
return $"{Math.Max(1, (int)Math.Ceiling(t.TotalMinutes))}m";
|
||||
}
|
||||
|
||||
/// <summary>"Daily (every 20h 00m)", "Weekly (every 7d 0h)", "One-time", or the wiki's own words.</summary>
|
||||
public static string RepeatText(GuideQuest q)
|
||||
{
|
||||
if (q.RepeatSec == 0) return q.Repeat.Length > 0 ? "One-time (" + q.Repeat + ")" : "One-time";
|
||||
if (q.RepeatSec < 0) return "Repeats: " + q.Repeat;
|
||||
string every = Short(TimeSpan.FromSeconds(q.RepeatSec));
|
||||
return q.IsDaily ? $"Daily (every {every})" : q.IsWeekly ? $"Weekly (every {every})" : $"Repeats every {every}";
|
||||
}
|
||||
|
||||
// ── Kill tasks ──────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>A kill task's progress: kills and goal, where the count came from, its state and whether it was done before.</summary>
|
||||
public sealed record Kill(KillState State, int Kills, int Goal, QuestFlag? Counter, bool FromChat, string Status, bool DoneBefore);
|
||||
|
||||
/// <summary>
|
||||
/// The task's counter flag: a stamp of it /myquests holds with a solve limit over 1, else a kill-task flag that names its creature.
|
||||
/// </summary>
|
||||
public QuestFlag? KillCounter(GuideQuest q)
|
||||
{
|
||||
foreach (string st in q.AllStamps())
|
||||
if (FlagOf(st) is QuestFlag f && f.MaxSolves > 1) return f;
|
||||
string key = q.KillCreatureKey;
|
||||
if (key.Length < 5) return null;
|
||||
foreach (QuestFlag f in _flags.Flags.Values)
|
||||
if (QuestTimer.IsKillTask(f) && GuideStamp.Key(f.Key).Contains(key, StringComparison.Ordinal)) return f;
|
||||
return null;
|
||||
}
|
||||
|
||||
public Kill KillOf(GuideQuest q, DateTime utcNow, bool? flagDone = null)
|
||||
{
|
||||
int goal = q.KillTarget, kills = 0;
|
||||
QuestFlag? counter = KillCounter(q);
|
||||
if (counter != null)
|
||||
{
|
||||
kills = counter.Solves;
|
||||
if (counter.MaxSolves > 1) goal = counter.MaxSolves;
|
||||
}
|
||||
bool fromChat = false;
|
||||
// A kill line newer than the last /myquests read wins: it moves with every kill.
|
||||
if (_kills.For(q.KillCreatureKey) is KillCount k && k.AtUtc > _flags.LastReadUtc && (k.Goal > 0 || k.Kills > 0))
|
||||
{
|
||||
kills = k.Kills;
|
||||
if (k.Goal > 0) goal = k.Goal;
|
||||
fromChat = true;
|
||||
}
|
||||
Row row = RowOf(q, utcNow, flagDone);
|
||||
TimeSpan wait = Wait(q, utcNow);
|
||||
bool counted = counter != null || fromChat;
|
||||
KillState state;
|
||||
string status;
|
||||
if (counted && goal > 0 && kills < goal && !(row.HideWhenDone && wait > TimeSpan.Zero)) { state = KillState.Counting; status = $"{kills} / {goal}"; }
|
||||
else if (counted && goal > 0 && kills >= goal && wait <= TimeSpan.Zero && row.State != GuideState.Done) { state = KillState.TurnIn; status = "Turn in"; }
|
||||
else if (row.State == GuideState.Done && wait > TimeSpan.Zero) { state = KillState.Waiting; status = "Done " + Short(wait); }
|
||||
else if (row.State == GuideState.Done && q.RepeatSec == 0) { state = KillState.Completed; status = "Completed"; }
|
||||
else if (row.State == GuideState.Done || counter != null) { state = KillState.Ready; status = "Ready"; }
|
||||
else { state = KillState.NotStarted; status = goal > 0 ? $"0 / {goal}" : "Not started"; }
|
||||
bool before = state is KillState.Waiting or KillState.Completed || DoneBefore(q, counter, flagDone);
|
||||
return new Kill(state, kills, goal, counter, fromChat, status, before);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Done before: a stamp of the task is held other than those a first run holds too (the live counter, a "start" flag,
|
||||
/// the first step's), a flag of it is on a redo timer, or the quest list's flag of its name is held.
|
||||
/// </summary>
|
||||
private bool DoneBefore(GuideQuest q, QuestFlag? counter, bool? flagDone)
|
||||
{
|
||||
string counterKey = counter != null ? GuideStamp.Key(counter.Key) : "";
|
||||
var first = new HashSet<string>(StringComparer.Ordinal);
|
||||
if (q.Steps.Count > 1)
|
||||
foreach (string st in q.Steps[0].Stamps) first.Add(GuideStamp.Key(st));
|
||||
foreach (string st in q.AllStamps())
|
||||
{
|
||||
string k = GuideStamp.Key(st);
|
||||
if (k == counterKey || first.Contains(k) || k.Contains("start", StringComparison.Ordinal)) continue;
|
||||
if (StampedThisSession(st) || FlagOf(st) != null) return true;
|
||||
}
|
||||
return flagDone == true;
|
||||
}
|
||||
|
||||
/// <summary>The two-word tag a kill task row shows, and its tooltip.</summary>
|
||||
public static (string Tag, string Tip) KillTag(bool doneBefore) => doneBefore
|
||||
? ("Again", "Done before: a stamp or flag of this kill task is held.")
|
||||
: ("1st", "First time: no stamp or flag of this kill task held yet.");
|
||||
|
||||
/// <summary>"KillTaskSampleBeasts_0101" -> "Kill Task Sample Beasts 0101".</summary>
|
||||
public static string FlagLabel(string flag)
|
||||
{
|
||||
var sb = new System.Text.StringBuilder(flag.Length + 8);
|
||||
for (int i = 0; i < flag.Length; i++)
|
||||
{
|
||||
char c = flag[i];
|
||||
if (c == '_') { if (sb.Length > 0 && sb[^1] != ' ') sb.Append(' '); continue; }
|
||||
bool brk = i > 0 && (char.IsUpper(c) && (char.IsLower(flag[i - 1]) || char.IsDigit(flag[i - 1])) || char.IsDigit(c) && char.IsLetter(flag[i - 1]));
|
||||
if (brk && sb.Length > 0 && sb[^1] != ' ') sb.Append(' ');
|
||||
sb.Append(c);
|
||||
}
|
||||
return sb.ToString().Trim();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>One creature's last kill line this session: the count and the goal (0: the line gave none), and when.</summary>
|
||||
internal readonly record struct KillCount(string Creature, int Kills, int Goal, DateTime AtUtc);
|
||||
|
||||
/// <summary>
|
||||
/// Kill task counts from chat: the server's "You have killed 27 Sample Beasts! You must kill 50 to complete your task."
|
||||
/// (and "You have killed some ..."), so the Kill Tasks list moves with every kill though /myquests is read at most once a
|
||||
/// minute. The last line per creature this session. Pump thread.
|
||||
/// </summary>
|
||||
internal sealed class KillChat
|
||||
{
|
||||
private static readonly Regex CountRx = new(
|
||||
@"^You have killed (?<n>\d{1,6}) (?<what>.+?)! You must kill (?<max>\d{1,6}) to complete your task", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);
|
||||
private static readonly Regex SomeRx = new(@"^You have killed (?:some|enough|all(?: the)?) (?<what>.+?)[.!]*$", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);
|
||||
|
||||
private readonly Dictionary<string, KillCount> _byKey = new(StringComparer.Ordinal);
|
||||
|
||||
/// <summary>Goes up with every kill line taken.</summary>
|
||||
public int Revision { get; private set; }
|
||||
|
||||
public void Clear()
|
||||
{
|
||||
if (_byKey.Count == 0) return;
|
||||
_byKey.Clear();
|
||||
Revision++;
|
||||
}
|
||||
|
||||
/// <summary>Takes a chat line; true when it was a kill task's kill line.</summary>
|
||||
public bool OnChatLine(string? line, DateTime utcNow)
|
||||
{
|
||||
if (string.IsNullOrEmpty(line) || !line.StartsWith("You have killed ", StringComparison.OrdinalIgnoreCase)) return false;
|
||||
string text = line.Trim();
|
||||
Match m = CountRx.Match(text);
|
||||
if (m.Success)
|
||||
{
|
||||
string what = m.Groups["what"].Value.Trim();
|
||||
_byKey[GuideQuest.KillKey(what)] = new KillCount(what,
|
||||
int.Parse(m.Groups["n"].Value, NumberStyles.None, CultureInfo.InvariantCulture),
|
||||
int.Parse(m.Groups["max"].Value, NumberStyles.None, CultureInfo.InvariantCulture), utcNow);
|
||||
Revision++;
|
||||
return true;
|
||||
}
|
||||
m = SomeRx.Match(text);
|
||||
if (!m.Success) return false;
|
||||
string some = m.Groups["what"].Value.Trim();
|
||||
string key = GuideQuest.KillKey(some);
|
||||
_byKey[key] = _byKey.TryGetValue(key, out KillCount had) ? had with { AtUtc = utcNow } : new KillCount(some, 0, 0, utcNow);
|
||||
Revision++;
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>The last line for a creature key: the same key, else one holding the other (keys of 5+ letters only), newest first.</summary>
|
||||
public KillCount? For(string creatureKey)
|
||||
{
|
||||
if (creatureKey.Length == 0) return null;
|
||||
if (_byKey.TryGetValue(creatureKey, out KillCount k)) return k;
|
||||
if (creatureKey.Length < 5) return null;
|
||||
KillCount? best = null;
|
||||
foreach (KeyValuePair<string, KillCount> kv in _byKey)
|
||||
if (kv.Key.Length >= 5 && (kv.Key.Contains(creatureKey, StringComparison.Ordinal) || creatureKey.Contains(kv.Key, StringComparison.Ordinal))
|
||||
&& (best == null || kv.Value.AtUtc > best.Value.AtUtc))
|
||||
best = kv.Value;
|
||||
return best;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The guides in use, merged: the active server plugin's own guide first (its quests replace the AC Community Wiki's of the
|
||||
/// same name), then the AC Community Wiki's. Kill tasks, society ranks and contracts come from either.
|
||||
/// </summary>
|
||||
internal sealed class GuideSet
|
||||
{
|
||||
public readonly List<GuideQuest> Quests = new();
|
||||
public readonly List<GuideContract> Contracts = new();
|
||||
private readonly QuestGuide? _server;
|
||||
private readonly QuestGuide _wiki;
|
||||
private readonly HashSet<GuideQuest> _fromServer = new();
|
||||
|
||||
public GuideSet(QuestGuide? server, QuestGuide wiki)
|
||||
{
|
||||
_server = server is { IsEmpty: false } ? server : null;
|
||||
_wiki = wiki;
|
||||
var names = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
if (_server != null)
|
||||
foreach (GuideQuest q in _server.Quests)
|
||||
if (names.Add(q.Title)) { Quests.Add(q); _fromServer.Add(q); }
|
||||
foreach (GuideQuest q in wiki.Quests)
|
||||
if (names.Add(q.Title)) Quests.Add(q);
|
||||
var contracts = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
if (_server != null)
|
||||
foreach (GuideContract c in _server.Contracts) if (contracts.Add(c.Title)) Contracts.Add(c);
|
||||
foreach (GuideContract c in wiki.Contracts) if (contracts.Add(c.Title)) Contracts.Add(c);
|
||||
}
|
||||
|
||||
public bool IsEmpty => Quests.Count == 0 && Contracts.Count == 0;
|
||||
|
||||
/// <summary>The quest came from the server plugin's guide.</summary>
|
||||
public bool FromServer(GuideQuest q) => _fromServer.Contains(q);
|
||||
|
||||
public bool IsKillTask(GuideQuest q) => (_server?.IsKillTask(q) ?? false) || _wiki.IsKillTask(q);
|
||||
|
||||
public string SocietyRankOf(GuideQuest q)
|
||||
{
|
||||
string r = _server?.SocietyRankOf(q) ?? "";
|
||||
return r.Length > 0 ? r : _wiki.SocietyRankOf(q);
|
||||
}
|
||||
|
||||
public GuideQuest? Find(string title)
|
||||
{
|
||||
foreach (GuideQuest q in Quests)
|
||||
if (string.Equals(q.Title, title, StringComparison.OrdinalIgnoreCase)) return q;
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>Society ranks in order (the wiki's names); a rank not in the list sorts last.</summary>
|
||||
public static readonly string[] SocietyRanks = { "Joining", "Initiate", "Adept", "Knight", "Lord", "Master" };
|
||||
|
||||
public static int RankOrder(string rank)
|
||||
{
|
||||
for (int i = 0; i < SocietyRanks.Length; i++)
|
||||
if (string.Equals(SocietyRanks[i], rank, StringComparison.OrdinalIgnoreCase)) return i;
|
||||
return SocietyRanks.Length;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The seam for running a guide quest later (RynthNav walking its steps; not in this version). Nothing implements it
|
||||
/// yet: the Guide tab draws run controls only when <see cref="OracleContext.GuideRunner"/> is set.
|
||||
/// </summary>
|
||||
internal interface IGuideQuestRunner
|
||||
{
|
||||
/// <summary>The quest being run, or null.</summary>
|
||||
GuideQuest? Running { get; }
|
||||
/// <summary>The step under way (0-based), -1 none.</summary>
|
||||
int Step { get; }
|
||||
/// <summary>Starts the quest at a step; the answer to show.</summary>
|
||||
string Start(GuideQuest q, int fromStep);
|
||||
void Stop();
|
||||
}
|
||||
|
|
@ -25,6 +25,9 @@ internal sealed class QuestCatalogUpdater
|
|||
|
||||
public bool Running => _task is { IsCompleted: false };
|
||||
|
||||
/// <summary>A day or more since the last check started.</summary>
|
||||
public static bool Due(DateTime nowUtc, DateTime lastCheckUtc) => nowUtc - lastCheckUtc >= Interval;
|
||||
|
||||
/// <summary>Starts a check unless one is running. Pump thread.</summary>
|
||||
public void Start()
|
||||
{
|
||||
|
|
|
|||
Loading…
Reference in a new issue