XFE Git
XFE Studio Git
Git 首页 全局搜索
XFE 主站 文档 NuGet

XFEEDToolBox

【WinUI】XFE精英危险工具箱

公开
关注 0 Fork 0 Star 0
UTF-8
using System.Text;
using System.Text.Json;
using XFEEDToolBox.Core.Models;

namespace XFEEDToolBox.Core.Data;

public sealed record ObservedJournalEvent(long Sequence, DateTimeOffset ObservedAt, JsonElement Data);

public sealed class JournalMonitor : IAsyncDisposable
{
    private sealed class Tail { public long Position; public List<byte> Pending = []; }
    private readonly Dictionary<string, Tail> tails = new(StringComparer.OrdinalIgnoreCase);
    private readonly Dictionary<string, DateTime> snapshots = new(StringComparer.OrdinalIgnoreCase);
    private readonly PlayerProjector projector = new();
    private readonly CancellationTokenSource stop = new();
    private Task? loop;
    private long sequence;
    private long eventsRead;
    private string? statusContent;
    public string DirectoryPath { get; }
    public PlayerState State => projector.State;
    public long Sequence => Interlocked.Read(ref sequence);
    public long EventsRead => Interlocked.Read(ref eventsRead);
    public MarketSnapshot? LocalMarket { get; private set; }
    public Navigation.JournalSystemOrbitCatalogue SystemOrbits { get; } = new();
    public event Action<PlayerState>? PlayerChanged;
    public event Action<MarketSnapshot>? MarketChanged;
    public event Action<Station>? StationObserved;
    public event Action<ObservedJournalEvent>? JournalEvent;
    public event Action<IReadOnlyList<GameJournalRecord>>? EventBatch;
    public event Action<string>? Diagnostic;

    public JournalMonitor(string directory) => DirectoryPath = directory;

    public async Task StartAsync(CancellationToken token = default)
    {
        if (loop != null) throw new InvalidOperationException("Journal 监听已启动。");
        await ScanAsync(true, token);
        loop = Task.Run(async () =>
        {
            using var timer = new PeriodicTimer(TimeSpan.FromMilliseconds(750));
            try
            {
                while (await timer.WaitForNextTickAsync(stop.Token))
                    try { await ScanAsync(false, stop.Token); }
                    catch (IOException) { Diagnostic?.Invoke("Journal 暂时被占用,将自动重试。"); }
                    catch (UnauthorizedAccessException) { Diagnostic?.Invoke("Journal 目录不可访问,请检查设置。"); }
            }
            catch (OperationCanceledException) when (stop.IsCancellationRequested) { }
        }, CancellationToken.None);
    }

    private async Task ScanAsync(bool replay, CancellationToken token)
    {
        if (!Directory.Exists(DirectoryPath))
        {
            if (replay) Diagnostic?.Invoke("未找到 Journal 目录,可在数据接入中修改。");
            return;
        }
        var changed = false;
        var records=new List<GameJournalRecord>();
        void Record(GameJournalRecord record){records.Add(record);if(records.Count>=500){EventBatch?.Invoke(records.ToArray());records.Clear();}}
        foreach (var path in Directory.EnumerateFiles(DirectoryPath, "Journal.*.log").Order(StringComparer.Ordinal))
        {
            token.ThrowIfCancellationRequested();
            if (!tails.TryGetValue(path, out var tail)) tails[path] = tail = new();
            await using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete, 65536, true);
            if (stream.Length < tail.Position) { tail.Position = 0; tail.Pending.Clear(); }
            if (stream.Length == tail.Position) continue;
            stream.Position = tail.Position;
            var bytes = new byte[65536];
            int read;
            while ((read = await stream.ReadAsync(bytes, token)) > 0)
            {
                tail.Position += read;
                for (var i = 0; i < read; i++)
                {
                    if (bytes[i] != 10)
                    {
                        tail.Pending.Add(bytes[i]);
                        if (tail.Pending.Count > 4 * 1024 * 1024) { tail.Pending.Clear(); Diagnostic?.Invoke("已跳过超长 Journal 行。"); }
                        continue;
                    }
                    if (tail.Pending.Count == 0) continue;
                    try
                    {
                        using var doc = JsonDocument.Parse(Encoding.UTF8.GetString(tail.Pending.ToArray()).TrimStart('\uFEFF'));
                        var e = doc.RootElement;
                        projector.Apply(e);
                        SystemOrbits.Apply(e);
                        Interlocked.Increment(ref eventsRead);
                        changed = true;
                        ObserveStation(e);
                        Record(new(path,stream.Position-read+i+1,e.Time()??DateTimeOffset.UtcNow,e.Text("event"),e.GetRawText()));
                        if (!replay) JournalEvent?.Invoke(new(Interlocked.Increment(ref sequence), DateTimeOffset.UtcNow, e.Clone()));
                    }
                    catch (JsonException) { Diagnostic?.Invoke("已跳过一条损坏的完整 Journal 行。"); }
                    catch (InvalidDataException e) { Diagnostic?.Invoke("已跳过无效 Journal 数据:"+e.Message); }
                    finally { tail.Pending.Clear(); }
                }
            }
        }
        foreach (var file in new[] { "Cargo.json", "ShipLocker.json", "Backpack.json", "Status.json", "Market.json", "NavRoute.json" })
        {
            var path = Path.Combine(DirectoryPath, file);
            if (!File.Exists(path)) continue;
            var modified = File.GetLastWriteTimeUtc(path);
            var sameWrite=snapshots.TryGetValue(path,out var seen)&&seen==modified;
            // Status is a change-driven snapshot. Read it again to verify access
            // and integrity without fabricating a new event or refreshing the UI.
            if(sameWrite&&file!="Status.json")continue;
            try
            {
                await using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete);
                using var doc = await JsonDocument.ParseAsync(stream, cancellationToken: token);
                var root = doc.RootElement;
                if(file=="Status.json")
                {
                    if(File.GetLastWriteTimeUtc(path)!=modified)continue;
                    var statusFlags=root.Get("Flags");
                    if(root.Text("event")!="Status"||root.Time() is not {} statusAt||statusFlags.ValueKind!=JsonValueKind.Number||!statusFlags.TryGetInt64(out var flags)||flags<0)
                        throw new InvalidDataException("座舱状态快照缺少事件、时间或设备标志。");
                    var content=root.GetRawText();
                    if(statusContent==content)
                    {
                        projector.ConfirmStatusRead(statusAt,DateTimeOffset.UtcNow,new DateTimeOffset(modified,TimeSpan.Zero));snapshots[path]=modified;continue;
                    }
                    statusContent=content;
                }
                if (file == "Market.json")
                {
                    // The file can remain at the previous station after departure; retain its own identity/time.
                    var p = State;
                    var known = root.Long("MarketID") == p.MarketId ? new Station { MarketId = p.MarketId!.Value, Position = p.Position } : null;
                    LocalMarket = MarketParser.ParseLocalMarket(root, known);
                    MarketChanged?.Invoke(LocalMarket);
                }
                else
                {
                    projector.Apply(root); changed = true;
                    if(file=="Status.json")projector.ConfirmStatusRead(root.Time()!.Value,DateTimeOffset.UtcNow,new DateTimeOffset(modified,TimeSpan.Zero));
                    Record(new(path,modified.Ticks,root.Time()??new DateTimeOffset(modified,TimeSpan.Zero),root.Text("event",Path.GetFileNameWithoutExtension(file)),root.GetRawText()));
                    if(!replay&&file=="Status.json")JournalEvent?.Invoke(new(Interlocked.Increment(ref sequence),DateTimeOffset.UtcNow,root.Clone()));
                }
                snapshots[path] = modified;
            }
            catch (JsonException) { /* Game is writing the snapshot. Retry without recording its mtime. */ }
            catch (InvalidDataException e) { snapshots[path]=modified;Diagnostic?.Invoke(Path.GetFileName(path)+":"+e.Message); }
        }
        if (changed) PlayerChanged?.Invoke(State);
        if(records.Count>0)EventBatch?.Invoke(records.ToArray());
    }

    private void ObserveStation(JsonElement e)
    {
        if (e.Text("event") is not ("Docked" or "Location" or "CarrierJump")) return;
        var id = e.Long("MarketID");
        if (id <= 0) return;
        var type = e.Text("StationType");
        StationObserved?.Invoke(new()
        {
            MarketId = id, Name = e.Text("StationName"), SystemName = e.Text("StarSystem", State.SystemName),
            Position = e.Position() ?? State.Position, Type = type,
            DistanceToArrivalLs = e.Number("DistFromStarLS"), MaxLandingPad = JsonFields.PadFromType(type),
            Security = JsonFields.Security(e.Text("SystemSecurity")), IsFleetCarrier = type == "FleetCarrier",
            IsPlanetary = type.StartsWith("Crater"), UpdatedAt = e.Time() ?? DateTimeOffset.UtcNow
        });
    }

    public async ValueTask DisposeAsync()
    {
        await stop.CancelAsync();
        if (loop is not null) await loop;
        stop.Dispose();
    }
}