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

XFEEDToolBox

【WinUI】XFE精英危险工具箱

公开
关注 0 Fork 0 Star 0
UTF-8
using System.Diagnostics;
namespace XFEEDToolBox.Core.Session;

public enum SessionOperation { Relog, Restart, Start }
public sealed record GameSessionTarget(int ProcessId, long StartedUtcTicks, string Executable, string Launcher, bool Steam);
public sealed record SessionProgress(bool Active, string Message);
public interface IGameSessionDriver
{
    bool CanRelog { get; }
    Task<GameSessionTarget> FindTargetAsync(CancellationToken token);
    Task<GameSessionTarget> FindLaunchTargetAsync(CancellationToken token);
    Task ValidateLaunchAsync(GameSessionTarget target, CancellationToken token);
    Task ValidateRestartAsync(GameSessionTarget target, CancellationToken token);
    Task ValidateExitAsync(GameSessionTarget target,CancellationToken token)=>ValidateRestartAsync(target,token);
    Task TerminateAsync(GameSessionTarget target, CancellationToken token);
    Task<bool> HasExitedAsync(GameSessionTarget target, CancellationToken token);
    Task LaunchAsync(GameSessionTarget previous, CancellationToken token);
    Task<GameSessionTarget?> FindReplacementAsync(GameSessionTarget previous, CancellationToken token);
    Task RelogAsync(GameSessionTarget target, CancellationToken token);
}

/// <summary>Explicit session actions share one operation gate. Starting never terminates a process.</summary>
public sealed class GameSessionController(IGameSessionDriver driver, Func<bool> routeActive)
{
    private int active;
    public bool Active => Volatile.Read(ref active) != 0;
    public bool CanRelog => driver.CanRelog;
    public TimeSpan ExitTimeout { get; init; } = TimeSpan.FromSeconds(20);
    public TimeSpan StartTimeout { get; init; } = TimeSpan.FromSeconds(120);
    public TimeSpan PollInterval { get; init; } = TimeSpan.FromMilliseconds(500);
    public event Action<SessionProgress>? Progress;
    public event Action<SessionReentryEvent>? Reentry;
    private SessionReentryEvent BeginReentry(SessionOperation operation,GameSessionTarget target,bool protection=false)
    {
        var entry=new SessionReentryEvent(Guid.NewGuid(),operation,target,protection,SessionReentryStage.Requested,DateTimeOffset.UtcNow);
        PublishReentry(entry);return entry;
    }
    private void PublishReentry(SessionReentryEvent entry)
    {
        if(Reentry is not {} handlers)return;
        foreach(Action<SessionReentryEvent> handler in handlers.GetInvocationList())
            try{handler(entry);}catch{ /* Notification observers must never delay or interrupt a session action. */ }
    }
    private void Report(string text) => Progress?.Invoke(new(Active, text));
    public Task RunAsync(SessionOperation operation,CancellationToken token=default)=>RunForTargetAsync(operation,null,token);
    public async Task EmergencyExitAsync(GameSessionTarget expected,CancellationToken token=default)
    {
        if(Interlocked.CompareExchange(ref active,1,0)!=0)throw new InvalidOperationException("飞船保护正在处理此会话。");
        try
        {
            await driver.ValidateExitAsync(expected,token);
            await driver.TerminateAsync(expected,token);
            var watch=Stopwatch.StartNew();
            while(!await driver.HasExitedAsync(expected,token))
            {
                if(watch.Elapsed>=ExitTimeout)throw new TimeoutException("未确认受保护游戏实例结束。");
                await Task.Delay(PollInterval,token);
            }
            Report("受保护游戏实例已退出;自动操作已停止。");
        }
        finally{Interlocked.Exchange(ref active,0);}
    }
    // Emergency protection already has a verified session identity. Do not wait for a
    // trading/navigation worker or launcher validation before exiting the endangered ship.
    public async Task EmergencyRestartAsync(GameSessionTarget expected,CancellationToken token=default)
    {
        if(Interlocked.CompareExchange(ref active,1,0)!=0)throw new InvalidOperationException("飞船保护正在处理此会话。");
        SessionReentryEvent? reentry=null;
        try
        {
            token.ThrowIfCancellationRequested();
            await driver.ValidateExitAsync(expected,token);
            reentry=BeginReentry(SessionOperation.Restart,expected,protection:true);
            await driver.TerminateAsync(expected,token);
            var exitWatch=Stopwatch.StartNew();
            while(!await driver.HasExitedAsync(expected,token))
            {
                if(exitWatch.Elapsed>=ExitTimeout)throw new TimeoutException("未确认受保护游戏实例结束。");
                await Task.Delay(PollInterval,token);
            }
            Report("受保护游戏实例已大退;自动操作已停止。");
            token.ThrowIfCancellationRequested();
            await driver.ValidateLaunchAsync(expected,token);
            token.ThrowIfCancellationRequested();
            await driver.LaunchAsync(expected,token);
            var watch=Stopwatch.StartNew();
            while(watch.Elapsed<StartTimeout)
            {
                if(await driver.FindReplacementAsync(expected,token) is {} replacement&&replacement.StartedUtcTicks>expected.StartedUtcTicks
                    &&string.Equals(replacement.Executable,expected.Executable,StringComparison.OrdinalIgnoreCase))
                {PublishReentry(reentry with{Stage=SessionReentryStage.ProcessReady,Target=replacement});return;}
                await Task.Delay(PollInterval,token);
            }
            throw new TimeoutException("飞船已大退保护,但尚未确认游戏重新启动。");
        }
        catch{if(reentry is not null)PublishReentry(reentry with{Stage=SessionReentryStage.Aborted});throw;}
        finally{Interlocked.Exchange(ref active,0);}
    }
    public async Task RunForTargetAsync(SessionOperation operation,GameSessionTarget? expected,CancellationToken token=default)
    {
        if (Interlocked.CompareExchange(ref active, 1, 0) != 0) throw new InvalidOperationException("已有会话操作正在进行。");
        SessionReentryEvent? reentry=null;
        try
        {
            token.ThrowIfCancellationRequested();
            if (routeActive()) throw new InvalidOperationException("请先停止工具箱路线,再进行会话操作。");
            if (operation == SessionOperation.Relog && !CanRelog) throw new NotSupportedException("重进接口未就绪,请检查已加载的插件和当前游戏模式。");
            var starting = operation == SessionOperation.Start;
            var target = starting ? await driver.FindLaunchTargetAsync(token) : await driver.FindTargetAsync(token);
            if(expected is not null&&target!=expected)throw new InvalidOperationException("游戏进程已变化,已取消自动重启。");
            if (operation == SessionOperation.Relog)
            {
                reentry=BeginReentry(operation,target);await driver.RelogAsync(target, token);
                PublishReentry(reentry with{Stage=SessionReentryStage.ProcessReady});Report("已重新进入游戏");return;
            }
            if (starting)
            {
                if (target.ProcessId > 0) { Report($"游戏已运行 · PID {target.ProcessId},无需重复启动。"); return; }
                await driver.ValidateLaunchAsync(target, token);
                reentry=BeginReentry(operation,target);
                Report("正在通过官方启动器启动游戏 · 非 VR 模式");
            }
            else
            {
                await driver.ValidateRestartAsync(target, token);
                token.ThrowIfCancellationRequested();
                reentry=BeginReentry(operation,target);
                Report($"正在直接结束游戏进程 PID {target.ProcessId}");
                await driver.TerminateAsync(target, token);
                var exitWatch = Stopwatch.StartNew();
                while (!await driver.HasExitedAsync(target, token))
                {
                    if (exitWatch.Elapsed >= ExitTimeout) throw new TimeoutException("未确认原游戏进程结束,已停止重启。");
                    await Task.Delay(PollInterval, token);
                }
                Report("原游戏进程已结束,正在通过官方启动器重新启动");
            }
            token.ThrowIfCancellationRequested();
            await driver.LaunchAsync(target, token);
            var watch = Stopwatch.StartNew();
            while (watch.Elapsed < StartTimeout)
            {
                token.ThrowIfCancellationRequested();
                if (await driver.FindReplacementAsync(target, token) is { } p && p.StartedUtcTicks > target.StartedUtcTicks && string.Equals(p.Executable, target.Executable, StringComparison.OrdinalIgnoreCase))
                { PublishReentry(reentry with{Stage=SessionReentryStage.ProcessReady,Target=p});Report($"游戏已{(starting ? "启动" : "重新启动")} · PID {p.ProcessId}"); return; }
                await Task.Delay(PollInterval, token);
            }
            throw new TimeoutException("启动请求已发出,但未确认到同一安装目录的新游戏进程。请查看官方启动器的登录或更新提示。");
        }
        catch (OperationCanceledException) { if(reentry is not null)PublishReentry(reentry with{Stage=SessionReentryStage.Aborted});Report(operation == SessionOperation.Start ? "已取消启动等待;已经交给官方启动器的请求不会强制撤回。" : operation == SessionOperation.Relog ? "已取消后续重进操作,已提交给游戏的菜单操作仍会完成。" : "已取消后续操作;已经结束的游戏进程无法撤销。"); throw; }
        catch (Exception e) { if(reentry is not null)PublishReentry(reentry with{Stage=SessionReentryStage.Aborted});Report("会话操作已停止:" + e.Message); throw; }
        finally { Interlocked.Exchange(ref active, 0); Progress?.Invoke(new(false, "")); }
    }
}