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;
using XFEEDToolBox.Core.Plugins;

namespace XFEEDToolBox.Core.Session;

public interface IOriginalSessionMenuRecovery
{
    Task PrepareAsync(CancellationToken token);
    Task<JsonElement> ReadAsync(CancellationToken token);
    Task LeaveAsync(string requestId,string action,ulong sequence,CancellationToken token);
}

/// <summary>The verified pause-menu extension returns to the menu; the entry-only channel restores the original mode.</summary>
public sealed class NativeSessionRecoveryChannel(INativeRelogChannel pause,INativeRelogChannel entry,IOriginalSessionMenuRecovery recovery):INativeRelogChannel,INativeMenuExitWitness
{
    private bool entryAttempted;
    private string witnessOwner="";
    private int mainMenuObserved;
    public bool ReachedMainMenu=>Volatile.Read(ref mainMenuObserved)!=0;
    private void RememberMainMenu()=>Volatile.Write(ref mainMenuObserved,1);
    public event Action<string>? Progress;
    public TimeSpan StepTimeout{get;init;}=TimeSpan.FromSeconds(20);
    public TimeSpan PollInterval{get;init;}=TimeSpan.FromMilliseconds(40);

    public NativeSessionRecoveryChannel(int processId,string gameHash,string packageDirectory,Func<CancellationToken,Task>? verifyProcess=null)
        :this(new NativeRelogChannel(processId,gameHash,verifyProcess,returnToMenuTrial:true),
            new NativeRelogChannel(processId,gameHash,verifyProcess,entryOnly:true),
            new NativeOriginalSessionMenuRecovery(processId,gameHash,packageDirectory,verifyProcess)){}

    public async Task BeginAsync(string owner,CancellationToken token)
    {
        token.ThrowIfCancellationRequested();
        if(witnessOwner==owner&&ReachedMainMenu)
        {entryAttempted=true;await entry.BeginAsync(owner,token);return;}
        witnessOwner=owner;Volatile.Write(ref mainMenuObserved,0);entryAttempted=false;
        await recovery.PrepareAsync(token);
        var initialMenu=await ReadUntilAsync(()=>recovery.ReadAsync(token),DateTimeOffset.UtcNow+StepTimeout,token);
        if(IsMainMenu(initialMenu))
        {RememberMainMenu();entryAttempted=true;await entry.BeginAsync(owner,token);return;}
        var initialState=initialMenu.GetProperty("state").GetString();
        Progress?.Invoke("原始会话状态:"+initialState);
        var mainMenu=false;var paused=Fresh(initialMenu)&&Flag(initialMenu,"menuReady")&&initialState==initialMenu.GetProperty("nextState").GetString()
            &&initialState is "Pause" or "ExitOptions";
        var submitted=false;var request=Guid.NewGuid().ToString("N");
        if(!paused)
        {
        Progress?.Invoke("正在打开游戏原始暂停菜单");
        try
        {
            await pause.BeginAsync(owner,token);
            var until=DateTimeOffset.UtcNow+StepTimeout;
            do
            {
                var frame=await ReadUntilAsync(()=>pause.ReadAsync(owner,token),until,token);
                if(frame.Sequence<=0||!Fresh(frame.ObservedAt.ToUnixTimeMilliseconds())){await Task.Delay(PollInterval,token);continue;}
                if(frame.Stable&&frame.State=="MainMenu"){mainMenu=true;RememberMainMenu();break;}
                if(frame.Stable&&frame.State=="Pause"){paused=true;break;}
                if(frame.Stable&&frame.State=="InGame"&&!submitted)
                {
                    submitted=true;
                    try{await pause.SubmitAsync(owner,request,frame,"@pause",token);}
                    catch(IOException){}catch(OperationCanceledException)when(!token.IsCancellationRequested){}
                }
                await Task.Delay(PollInterval,token);
            }while(DateTimeOffset.UtcNow<until);
        }
        finally{await pause.EndAsync(owner);}
        }
        if(!mainMenu&&!paused)throw new IOException("游戏尚未确认暂停菜单;原请求未重复提交。");
        for(var step=0;step<2&&!mainMenu;step++)
        {
            JsonElement menu=default;var until=DateTimeOffset.UtcNow+StepTimeout;
            do
            {
                menu=await ReadUntilAsync(()=>recovery.ReadAsync(token),until,token);
                if(!Fresh(menu)){await Task.Delay(PollInterval,token);continue;}
                if(IsMainMenu(menu)){mainMenu=true;RememberMainMenu();break;}
                if(Flag(menu,"menuReady")&&menu.GetProperty("state").GetString()==menu.GetProperty("nextState").GetString())break;
                await Task.Delay(PollInterval,token);
            }while(DateTimeOffset.UtcNow<until);
            if(mainMenu)break;
            var state=menu.GetProperty("state").GetString();
            var expected=state switch{"Pause"=>"ExitOptions","ExitOptions"=>"Confirmed Quit To Main Menu",_=>null};
            if(expected is null||!Fresh(menu)||!Flag(menu,"menuReady")||menu.GetProperty("state").GetString()!=menu.GetProperty("nextState").GetString())throw new IOException("原始返回主菜单选项尚未就绪。");
            var actions=menu.GetProperty("actions").EnumerateArray().Where(row=>Flag(row,"enabled")&&Flag(row,"recoveryAction")&&row.GetProperty("name").GetString()==expected).ToArray();
            if(actions.Length!=1)throw new InvalidDataException("没有唯一、启用且属于当前页面的返回主菜单选项。");
            var id=Guid.NewGuid().ToString("N");Progress?.Invoke("正在通过游戏原始菜单返回主菜单");
            try{await recovery.LeaveAsync(id,expected,menu.GetProperty("menuSequence").GetUInt64(),token);}
            catch(IOException){}catch(OperationCanceledException)when(!token.IsCancellationRequested){}
            var applied=false;until=DateTimeOffset.UtcNow+StepTimeout;
            do
            {
                var current=await ReadUntilAsync(()=>recovery.ReadAsync(token),until,token);
                if(!Fresh(current)){await Task.Delay(PollInterval,token);continue;}
                if(IsMainMenu(current)){mainMenu=true;RememberMainMenu();break;}
                if(current.TryGetProperty("requestId",out var receipt)&&receipt.GetString()==id)
                {
                    if(Flag(current,"failed"))throw new IOException("原始菜单请求失败;不会重新选择或退出游戏客户端。");
                    applied=Flag(current,"applied");
                }
                if(expected=="ExitOptions"&&applied&&current.GetProperty("state").GetString()=="ExitOptions"&&Flag(current,"menuReady"))break;
                await Task.Delay(PollInterval,token);
            }while(DateTimeOffset.UtcNow<until);
            if(!mainMenu&&(!applied||expected!="ExitOptions"))throw new IOException("返回主菜单的结果尚未确认,原请求未重复提交。");
        }
        if(!mainMenu)throw new IOException("尚未确认游戏实际返回主菜单,未启动后续选择。");
        entryAttempted=true;await entry.BeginAsync(owner,token);
    }
    public Task<NativeSessionFrame> ReadAsync(string owner,CancellationToken token)=>entry.ReadAsync(owner,token);
    public async Task<NativeSessionFrame> ReadOriginalMenuStateAsync(CancellationToken token)
    {
        var value=await recovery.ReadAsync(token);
        var sequence=value.TryGetProperty("sequence",out var actualSequence)?actualSequence.GetInt64():value.GetProperty("menuSequence").GetInt64();
        var frame=new NativeSessionFrame(sequence,DateTimeOffset.FromUnixTimeMilliseconds(value.GetProperty("observedAtUnixMilliseconds").GetInt64()),
            value.GetProperty("state").GetString()??"",value.GetProperty("nextState").GetString()??"",[]);
        if(NativeMenuExitSafety.Fresh(frame,DateTimeOffset.UtcNow)&&frame.Stable&&frame.State=="MainMenu")RememberMainMenu();
        return frame;
    }
    public Task SubmitAsync(string owner,string requestId,NativeSessionFrame frame,string action,CancellationToken token)=>entry.SubmitAsync(owner,requestId,frame,action,token);
    public Task EndAsync(string owner)=>entryAttempted?entry.EndAsync(owner):Task.CompletedTask;
    private async Task<T> ReadUntilAsync<T>(Func<Task<T>> read,DateTimeOffset until,CancellationToken token)
    {
        do
        {
            token.ThrowIfCancellationRequested();
            try{return await read().ConfigureAwait(false);}
            catch(Exception error)when(!token.IsCancellationRequested&&error is not InvalidDataException&&error is IOException or OperationCanceledException){}
            await Task.Delay(PollInterval,token).ConfigureAwait(false);
        }while(DateTimeOffset.UtcNow<until);
        throw new TimeoutException("等待当前原生菜单观测超时;未重发菜单操作。");
    }
    private static bool Fresh(long at){var age=DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()-at;return age is >=-100 and <=350;}
    private static bool Fresh(JsonElement value)=>value.TryGetProperty("observedAtUnixMilliseconds",out var at)&&at.TryGetInt64(out var time)&&Fresh(time);
    private static bool Flag(JsonElement value,string name)=>value.TryGetProperty(name,out var flag)&&flag.ValueKind==JsonValueKind.True;
    private static bool IsMainMenu(JsonElement value)=>Fresh(value)&&value.GetProperty("state").GetString()=="MainMenu"&&value.GetProperty("nextState").GetString()=="MainMenu";
}

public sealed class NativeOriginalSessionMenuRecovery(int processId,string gameHash,string packageDirectory,Func<CancellationToken,Task>? verifyProcess=null):IOriginalSessionMenuRecovery
{
    private const string Service="SessionRecovery0514k";
    private readonly NavigationPipeClient pipe=new(processId,Service);
    public async Task PrepareAsync(CancellationToken token)
    {
        if(verifyProcess is not null)await verifyProcess(token);
        try{await ReadAsync(token);return;}
        catch(Exception error)when(!token.IsCancellationRequested&&error is not InvalidDataException&&error is IOException or OperationCanceledException){}
        var hello=await new NavigationPipeClient(processId).CallAsync(new{op="describe"},token);
        if(hello.GetProperty("processId").GetInt32()!=processId||hello.GetProperty("gameSha256").GetString()!=gameHash)
            throw new InvalidDataException("重进扩展与当前游戏实例不匹配。");
        await RuntimeInteractionModule.LoadAsync(processId,gameHash,hello.GetProperty("owningThread").GetInt32(),packageDirectory,token);
        await ReadAsync(token);
    }
    public async Task<JsonElement> ReadAsync(CancellationToken token)
    {
        if(verifyProcess is not null)await verifyProcess(token);
        var result=await pipe.CallAsync(new{op="read"},token);
        if(result.GetProperty("schema").GetInt32()!=1||result.GetProperty("name").GetString()!="XFEEDToolBox.SessionRecovery"
            ||result.GetProperty("service").GetString()!=Service||result.GetProperty("processId").GetInt32()!=processId
            ||result.GetProperty("gameSha256").GetString()!=gameHash||!result.GetProperty("enabled").GetBoolean())
            throw new InvalidDataException("返回主菜单扩展握手不匹配或已停用。");
        return result;
    }
    public async Task LeaveAsync(string requestId,string action,ulong sequence,CancellationToken token)
    {
        if(verifyProcess is not null)await verifyProcess(token);
        if(action is not("ExitOptions" or "Confirmed Quit To Main Menu"))throw new InvalidOperationException("重进只允许返回主菜单。");
        await pipe.CallAsync(new{op="session.recovery.leave",requestId,action,menuSequence=sequence,ttlMilliseconds=250},token);
    }
}