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

XFEEDToolBox

【WinUI】XFE精英危险工具箱

公开
关注 0 Fork 0 Star 0
UTF-8
using System.Buffers.Binary;
using System.Collections.Frozen;
using System.Globalization;

namespace XFEEDToolBox.Core.Galaxy;

public sealed class OriginalCacheUpdatingException(string message):IOException(message);

/// <summary>Positive original-client visitation evidence. A missing local entry never proves an unvisited system.</summary>
public sealed record OriginalVisitedStarsSnapshot(ulong UserId,ulong CommanderId,FrozenSet<long> SystemAddresses,string SourcePath,DateTimeOffset LastWriteTimeUtc)
{
    public int Count=>SystemAddresses.Count;
    public bool Contains(long address)=>SystemAddresses.Contains(address);
    public bool? Visited(long address)=>Contains(address)?true:null;
}

/// <summary>Read-only parser of the installed client's VisitedStars format 200 cache, with explicit account identity.</summary>
public static class OriginalVisitedStarsCache
{
    public const int HeaderBytes=48,RecordBytes=16,MaximumEntries=4_000_000;
    // The original writer emits the 12-byte magic and its NUL only. Bytes
    // 13..15 are uninitialized padding, not a format tag or bucket capacity.
    // The actual numeric layout version starts at offset 16.
    public const uint Version=200;
    public const ulong Terminator=0x5afec0de5afec0de;

    public static OriginalVisitedStarsSnapshot ReadForUser(string gameCacheDirectory,string fid)
    {
        var number=fid.StartsWith('F')||fid.StartsWith('f')?fid[1..]:fid;
        if(!ulong.TryParse(number,NumberStyles.None,CultureInfo.InvariantCulture,out var user)||user==0)throw new ArgumentException("原游戏账号标识无效。",nameof(fid));
        return Read(Path.Combine(gameCacheDirectory,user.ToString(CultureInfo.InvariantCulture),"VisitedStarsCache.dat"),user);
    }
    public static OriginalVisitedStarsSnapshot Read(string path,ulong expectedUserId,ulong? expectedCommanderId=null)
    {
        using var file=new FileStream(path,FileMode.Open,FileAccess.Read,FileShare.ReadWrite|FileShare.Delete);
        var modified=File.GetLastWriteTimeUtc(path);
        if(file.Length<HeaderBytes+8||file.Length>HeaderBytes+(long)MaximumEntries*RecordBytes+8)throw new InvalidDataException("原游戏访问缓存长度无效。");
        var data=new byte[checked((int)file.Length)];file.ReadExactly(data);
        if(file.Length!=data.Length||File.GetLastWriteTimeUtc(path)!=modified)throw new OriginalCacheUpdatingException("原游戏访问缓存正在更新,请稍后重试。");
        var result=Parse(data,expectedUserId,expectedCommanderId);
        return result with{SourcePath=Path.GetFullPath(path),LastWriteTimeUtc=new DateTimeOffset(modified)};
    }
    public static OriginalVisitedStarsSnapshot Parse(ReadOnlySpan<byte> data,ulong expectedUserId,ulong? expectedCommanderId=null)
    {
        if(expectedUserId==0||data.Length<HeaderBytes+8||!data[..13].SequenceEqual("VisitedStars\0"u8))throw new InvalidDataException("原游戏访问缓存标头无效。");
        static uint U32(ReadOnlySpan<byte> bytes,int at)=>BinaryPrimitives.ReadUInt32LittleEndian(bytes.Slice(at,4));
        static ulong U64(ReadOnlySpan<byte> bytes,int at)=>BinaryPrimitives.ReadUInt64LittleEndian(bytes.Slice(at,8));
        if(U32(data,16)!=Version||U32(data,20)!=HeaderBytes||U32(data,28)!=RecordBytes)
            throw new InvalidDataException($"不支持的原游戏访问缓存版本或记录长度(版本{U32(data,16)},头{U32(data,20)},记录{U32(data,28)})。");
        var count=U32(data,24);if(count>MaximumEntries||data.Length!=HeaderBytes+(long)count*RecordBytes+8||U64(data,data.Length-8)!=Terminator)throw new InvalidDataException("原游戏访问缓存记录不完整。");
        var user=U64(data,32);var commander=U64(data,40);
        if(user!=expectedUserId||commander==0||expectedCommanderId is {} expected&&commander!=expected)throw new InvalidDataException("原游戏访问缓存不属于当前账号。");
        var addresses=new HashSet<long>();
        for(var i=0;i<count;i++)
        {
            var address=U64(data,HeaderBytes+i*RecordBytes);
            if(address==0||address>long.MaxValue||!addresses.Add((long)address))throw new InvalidDataException("原游戏访问缓存星系地址无效或重复。");
        }
        return new(user,commander,addresses.ToFrozenSet(),"",DateTimeOffset.MinValue);
    }
}