// Moved here from RynthInventory (Scanning/VaultFeed.cs) on 2026-10-20: RynthInventory asked every server
// for an Aelrynth vault; now only RynthAelrynth asks, on Aelrynth, and hands the vault to RynthInventory
// through the generic storage feed (Plugins/Shared/StorageFeed.cs).
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Globalization;
using System.Text.Json;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthAelrynth;
///
/// The Aelrynth account vault (the Aeshnidae.Mule mod): item storage the retail client is never
/// shown, so the only way to see inside is to ask. RynthAelrynth types /mule-data, exactly as a
/// player could, and the server answers one chat line a page:
///
/// ~ael1 {"t":"mule","ready":true,"page":1,"pages":3,"count":57,"max":1000,"items":[{...}]}
///
/// (the same "~ael1" lines the Aelrynth Companion reads; only lines whose "t" is "mule" are ours).
/// The pages are collected into one StorageFeedRecord, which RynthAelrynth sends to RynthInventory
/// (StorageFeed): it is kept with the character's storage, so the vault is searched, shown with
/// icons and merged across characters like any other storage; the newest copy wins, and a vault
/// belongs to the account, so every character sees the same one.
///
/// A server without the command (Aelrynth without the mod, or a world wrongly taken for Aelrynth)
/// is asked once after login; its "Unknown command" reply is eaten and the feed stays quiet. A
/// vault the server says is not ready yet is asked again a few times, and is never recorded as empty.
///
/// Threads: only queues; everything else runs on the plugin tick.
/// Pure: RynthServerPack.Tests covers it.
///
internal sealed class VaultFeed
{
public const string Command = "/mule-data";
public const string Prefix = "~ael1 ";
public const string Label = "Account vault";
public const string VaultName = "Aelrynth vault";
/// After login, before the first /mule-data; then every .
public const long FirstAskMs = 8_000, RefreshMs = 10 * 60_000;
public enum State { Idle, Asking, Unsupported, Waiting }
private const long AnswerWindowMs = 15_000, RetryReadyMs = 3_000;
private const int MaxReadyRetries = 6, MaxPages = 80;
private const string UnknownMarker = "\u0001unknown";
private readonly Func _send;
private readonly ConcurrentQueue _lines = new();
private long _sentAtMs;
private volatile bool _expecting;
private int _readyTries;
private long _retryAtMs;
private readonly List _pages = new();
private bool _changed;
public VaultFeed(Func send) => _send = send;
public State Status { get; private set; } = State.Idle;
/// The vault once a full read finished (null until then).
public StorageFeedRecord? Record { get; private set; }
public int Max { get; private set; }
/// For /rserver info.
public string Describe() => Status switch
{
State.Unsupported => "no vault on this server",
State.Asking => "reading the vault...",
State.Waiting => "the vault is still loading on the server",
_ => Record == null ? "vault not read yet" : $"vault: {Record.Items.Count} item(s)" + (Max > 0 ? $" of {Max}" : ""),
};
/// True once after was replaced.
public bool TakeChanged() { bool c = _changed; _changed = false; return c; }
/// Login and logout: a fresh read (the record from before is forgotten).
public void Reset()
{
Status = State.Idle;
_expecting = false;
_pages.Clear();
_readyTries = 0;
Record = null;
_changed = false;
Max = 0;
while (_lines.TryDequeue(out _)) { }
}
/// Starts a read from page 1, unless one is under way or the server has no vault ( asks anyway).
public bool Ask(long nowMs, bool force = false)
{
if (Status == State.Asking || Status == State.Waiting) return false;
if (Status == State.Unsupported && !force) return false;
_readyTries = 0;
_pages.Clear();
return SendPage(nowMs, 1);
}
private bool SendPage(long nowMs, int page)
{
_sentAtMs = nowMs;
Status = State.Asking;
_expecting = true;
if (_send(page <= 1 ? Command : Command + " " + page.ToString(CultureInfo.InvariantCulture))) return true;
_expecting = false;
Status = State.Idle;
return false;
}
///
/// True for a line this feed answers, so the caller keeps it out of the chat window. Cheap; any thread.
/// is the line's eChatTypes (-1 = not known). Server lines only: a line
/// in a player's chat type, or one that doesn't start with the marker (a player's copy has their
/// name in front), is left alone, so nobody can feed the vault view or hide chat by typing "~ael1".
///
public bool ShouldEat(string? text, int chatType = -1)
{
if (string.IsNullOrEmpty(text) || ChatSource.IsPlayerAuthored(chatType)) return false;
int at = ChatSource.ContentStart(text);
if (ChatSource.StartsWithMarker(text, Prefix))
{
// Only our own kind: another plugin's ~ael1 line (the Companion's) stays visible to it.
if (text.IndexOf("\"t\":\"mule\"", at, StringComparison.Ordinal) < 0) return false;
_lines.Enqueue(text.Substring(at + Prefix.Length));
return true;
}
// The reply of a server that has no such command: swallowed only while we wait for one.
if (_expecting && IsUnknownCommandReply(text))
{
_lines.Enqueue(UnknownMarker);
return true;
}
return false;
}
/// ACE's "Unknown command: mule-data" (GameActionTalk names the bare command; a leading / or @ is allowed).
private static bool IsUnknownCommandReply(string text)
{
const string marker = "Unknown command:";
if (!ChatSource.StartsWithMarker(text, marker, StringComparison.OrdinalIgnoreCase)) return false;
string named = text.Substring(ChatSource.ContentStart(text) + marker.Length).Trim().TrimStart('/', '@');
return string.Equals(named, "mule-data", StringComparison.OrdinalIgnoreCase);
}
/// Applies what arrived and decides what to send next. Plugin tick.
public void Tick(long nowMs, string account)
{
while (_lines.TryDequeue(out string? line)) Apply(line, nowMs, account);
if (Status == State.Waiting && nowMs >= _retryAtMs) SendPage(nowMs, 1);
else if (Status == State.Asking && nowMs - _sentAtMs > AnswerWindowMs)
{
// Nothing came back: a server without the mod, or a lost line. The next refresh retries.
_expecting = false;
Status = State.Idle;
_pages.Clear();
}
}
private void Apply(string line, long nowMs, string account)
{
if (line == UnknownMarker)
{
if (Status == State.Asking) { _expecting = false; Status = State.Unsupported; _pages.Clear(); }
return;
}
if (Status != State.Asking) return; // a line we did not ask for (typed by hand, say)
_expecting = false;
try
{
using JsonDocument doc = JsonDocument.Parse(line);
JsonElement root = doc.RootElement;
if (root.ValueKind != JsonValueKind.Object) { Status = State.Idle; return; }
if (!(root.TryGetProperty("ready", out JsonElement ready) && ready.ValueKind == JsonValueKind.True))
{
string why = Str(root, "why");
if (why == "loading" && ++_readyTries <= MaxReadyRetries) { Status = State.Waiting; _retryAtMs = nowMs + RetryReadyMs; }
else Status = State.Idle; // closed / fault / error: try again at the next refresh
_pages.Clear();
return;
}
int page = Int(root, "page", 1), pages = Math.Min(Math.Max(Int(root, "pages", 1), 1), MaxPages);
Max = Int(root, "max", Max);
int count = Int(root, "count", 0);
if (page == 1) _pages.Clear();
if (root.TryGetProperty("items", out JsonElement items) && items.ValueKind == JsonValueKind.Array)
foreach (JsonElement e in items.EnumerateArray())
if (e.ValueKind == JsonValueKind.Object) _pages.Add(Item(e));
if (page < pages) { SendPage(nowMs, page + 1); return; }
// Last page. A total that disagrees with what was read means the vault changed under
// the read (a deposit between pages): keep the old copy and read again shortly.
if (count != _pages.Count && _readyTries++ < MaxReadyRetries)
{
Status = State.Waiting; _retryAtMs = nowMs + RetryReadyMs; _pages.Clear(); return;
}
Record = new StorageFeedRecord(VaultId(account), VaultName, Label, new List(_pages));
_pages.Clear();
_changed = true;
Status = State.Idle;
}
catch (JsonException)
{
Status = State.Idle;
_pages.Clear();
}
}
private static StorageFeedItem Item(JsonElement e) => new(
UInt(e, "o"), UInt(e, "w"), Str(e, "n"), UInt(e, "i"), UInt(e, "u"), UInt(e, "v"),
Math.Max(1, Int(e, "s", 1)), Int(e, "m", 0), UInt(e, "y"));
///
/// A stand-in container id for the account's vault. Storage is merged by (server, id) with the
/// newest copy winning, so the same id on every character of the account shows ONE vault. It is
/// in the top of the id space, where no object the client has seen lives (StorageFeed.IsStandInId).
/// The same formula as RynthInventory used, so vaults saved before the move are replaced, not doubled.
///
public static uint VaultId(string account)
{
uint h = 2166136261u;
foreach (char c in (account ?? "").Trim().ToLowerInvariant()) { h ^= c; h *= 16777619u; }
return 0xFF000000u | (h & 0x00FFFFFFu);
}
private static int Int(JsonElement e, string name, int fallback) =>
e.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.Number && v.TryGetInt32(out int i) ? i : fallback;
private static uint UInt(JsonElement e, string name) =>
e.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.Number && v.TryGetUInt32(out uint u) ? u : 0u;
private static string Str(JsonElement e, string name) =>
e.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.String ? v.GetString() ?? string.Empty : string.Empty;
}