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

XFEEDToolBox

【WinUI】XFE精英危险工具箱

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

namespace XFEEDToolBox.Core.Session;

public sealed class NativeRelogChannel(int processId, string gameSha256, Func<CancellationToken, Task>? verifyProcess = null, bool entryOnly = false, bool returnToMenuTrial = false, Func<CancellationToken,Task>? prepareEntry = null) : INativeRelogChannel,INativeSessionEntryStatus
{
    public const string SupportedGameSha256 = "ed5a8f8cd10f9a80d3bda5badd7ba1d4fcfc15996c8c7e018852cb170e264b63";
    private readonly NavigationPipeClient pipe = new(processId);

    private async Task<JsonElement> CallAsync(object request, CancellationToken token)
    {
        if (verifyProcess is not null) await verifyProcess(token);
        var frame = await pipe.CallAsync(request, token);
        if (frame.GetProperty("schema").GetInt32() != 1 || frame.GetProperty("name").GetString() != "XFEEDToolBox.Session"
            || frame.GetProperty("processId").GetInt32() != processId || frame.GetProperty("gameSha256").GetString() != gameSha256)
            throw new InvalidDataException("原生重进接口与当前游戏实例不匹配。");
        return frame;
    }

    public async Task BeginAsync(string owner, CancellationToken token)
    {
        token.ThrowIfCancellationRequested();
        if(verifyProcess is not null)await verifyProcess(token);
        if(prepareEntry is not null)await prepareEntry(token);
        var hello = await pipe.CallAsync(new { op = "describe" }, token);
        if (hello.GetProperty("processId").GetInt32() != processId || hello.GetProperty("gameSha256").GetString() != gameSha256)
            throw new InvalidDataException("游戏重进握手的进程或构建不匹配。");
        if (!hello.TryGetProperty("nativeRelog", out var enabled) || enabled.ValueKind != JsonValueKind.True)
            throw new NotSupportedException("当前加载的插件尚未提供重进接口,请在游戏退出后更新插件。");
        // Entry from the main menu has live evidence. Returning from InGame
        // currently stalls at PrePauseMenu on this build; its presence must
        // not be inferred from the entry capability or offline ABI tests.
        if(!entryOnly&&!returnToMenuTrial&&(!hello.TryGetProperty("nativeReturnToMenuVerified",out var menuExit)||menuExit.ValueKind!=JsonValueKind.True))
            throw new NotSupportedException("当前构建的返回主菜单路径尚未通过实机验证,已停止原生重进;游戏状态未改变。");
        await CallAsync(new { op = "session.begin", owner, entryOnly }, token);
    }

    public async Task<NativeSessionFrame> ReadAsync(string owner, CancellationToken token)
    {
        var result = await CallAsync(new { op = "session.read", owner }, token);
        return Parse(result);
    }
    public async Task<NativeSessionFrame> ReadEntryStatusAsync(CancellationToken token)
        =>Parse(await CallAsync(new{op="session.status"},token));
    public static NativeSessionFrame Parse(JsonElement result)
    {
        return new(result.GetProperty("sequence").GetInt64(), DateTimeOffset.FromUnixTimeMilliseconds(result.GetProperty("observedAtUnixMilliseconds").GetInt64()),
            result.GetProperty("state").GetString()!, result.GetProperty("nextState").GetString()!,
            result.GetProperty("actions").EnumerateArray().Select(a => new NativeSessionMenuAction(a.GetProperty("name").GetString()!, a.GetProperty("enabled").GetBoolean())).ToArray(),
            result.GetProperty("lastRequestId").GetString()!, result.GetProperty("actionApplied").GetBoolean(), result.GetProperty("actionFailed").GetBoolean())
            {Available=result.TryGetProperty("available",out var available)&&available.ValueKind==JsonValueKind.True};
    }

    public async Task SubmitAsync(string owner, string requestId, NativeSessionFrame frame, string action, CancellationToken token)
    {
        try { await CallAsync(new { op = "session.action", owner, requestId, sequence = frame.Sequence, state = frame.State, action, ttlMilliseconds = 250 }, token); }
        catch (InvalidOperationException error) when (error.Message.StartsWith("Original game menu changed;", StringComparison.Ordinal))
        { throw new NativeSessionStateChangedException(error.Message); }
    }

    public async Task EndAsync(string owner)
    {
        // Releasing a lease never selects another game menu or changes its state.
        using var stop = new CancellationTokenSource(TimeSpan.FromSeconds(1));
        try { await CallAsync(new { op = "session.end", owner }, stop.Token); }
        catch (Exception error) when (error is IOException or OperationCanceledException or InvalidOperationException) { }
    }
}