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.Data;
using XFEEDToolBox.Core.Models;
using XFEEDToolBox.Core.Navigation;
using XFEEDToolBox.Core.Session;
using XFEEDToolBox.Services;

internal static class ShipHealthObservation
{
    public static async Task RunAsync(int pid,string reportPath,int seconds)
    {
        if(seconds is <0 or >14400||seconds is >0 and <30||File.Exists(reportPath)||File.Exists(reportPath+".jsonl"))throw new ArgumentException("Use a new report and a valid observation duration.");
        reportPath=Path.GetFullPath(reportPath);
        using var serviceLock=new FileStream(Path.Combine(Path.GetDirectoryName(reportPath)!,"ship-protection-service.lock"),FileMode.OpenOrCreate,FileAccess.ReadWrite,FileShare.None);
        var settings=ToolboxSettings.Load(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),"XFEstudio","XFEEDToolBox","settings.json"));
        await using var journal=new JournalMonitor(settings.JournalDirectory);await journal.StartAsync();
        var sessions=new WindowsGameSessionDriver(()=>journal.State);
        await using var monitor=new ShipProtectionMonitor(sessions,()=>journal.State,()=>{});
        await monitor.EnableAsync();
        if(monitor.BoundTarget?.ProcessId!=pid)throw new InvalidOperationException("Protection is bound to a different game instance.");
        using var observerProcess=System.Diagnostics.Process.GetCurrentProcess();var observerStarted=observerProcess.StartTime.ToUniversalTime().Ticks;
        var binding=monitor.BoundTarget!;
        var registry=Path.Combine(Path.GetDirectoryName(reportPath)!,"active-ship-protection.json");
        var registration=JsonSerializer.Serialize(new{gamePid=pid,gameStartedUtcTicks=binding.StartedUtcTicks,observerPid=observerProcess.Id,observerStartedUtcTicks=observerStarted,report=reportPath});
        await File.WriteAllTextAsync(registry+".tmp",registration);File.Move(registry+".tmp",registry,true);
        void ObserveJournal(ObservedJournalEvent observed)=>monitor.Observe(observed,journal.State);
        journal.JournalEvent+=ObserveJournal;
        Console.WriteLine(JsonSerializer.Serialize(new{pid,journalMonitoringEnabled=true,nativeProtectionArmed=false,readyForFlight=false,flightInputsSent=0}));
        var pipe=new NavigationPipeClient(pid);var hello=await pipe.CallAsync(new{op="describe"});var hash=hello.GetProperty("gameSha256").GetString()!;
        var healthOperation=hello.TryGetProperty("independentShipHealth",out var independent)&&independent.ValueKind==JsonValueKind.True?"health.read":"read";
        await using var log=new StreamWriter(new FileStream(reportPath+".jsonl",FileMode.CreateNew,FileAccess.Write,FileShare.Read));
        NativeFlightTestProtection? protection=null;DateTimeOffset start=DateTimeOffset.UtcNow;long samples=0;double? minimumHull=null,minimumShield=null;string? failure=null;
        try
        {
            while((seconds==0||DateTimeOffset.UtcNow-start<TimeSpan.FromSeconds(seconds))&&!File.Exists(reportPath+".stop"))
            {
                if(await sessions.HasExitedAsync(binding,CancellationToken.None))break;
                JsonElement frame;
                try{frame=await pipe.CallAsync(new{op=healthOperation});}
                catch(Exception error)when(error is InvalidOperationException or IOException or OperationCanceledException)
                {
                    if(protection?.Stopped==true)
                    {
                        try{using var process=System.Diagnostics.Process.GetProcessById(pid);if(process.HasExited)throw new InvalidOperationException("受保护游戏已退出。",error);}
                        catch(ArgumentException){throw new InvalidOperationException("受保护游戏已退出。",error);}
                    }
                    await log.WriteLineAsync(JsonSerializer.Serialize(new{at=DateTimeOffset.UtcNow,waiting=error.Message,flightInputsSent=0}));await log.FlushAsync();
                    await Task.Delay(100);continue;
                }
                if(protection is null)
                {
                    if(!journal.State.InGame||journal.State.CurrentShipId is null||!frame.GetProperty("shipHealth").GetProperty("verified").GetBoolean()){await Task.Delay(100);continue;}
                    protection=await NativeFlightTestProtection.ArmAsync(pid,hash,sessions,()=>journal.State,()=>{},sharedMonitor:monitor);
                    Console.WriteLine("Continuous main-ship health protection armed.");
                }
                // A legitimate entity transition may bar old inputs. Continue
                // observing health; stopping test input must not drop protection.
                var h=frame.GetProperty("shipHealth");var hull=h.GetProperty("hullFraction").GetDouble();
                var shield=h.GetProperty("shieldFraction").ValueKind==JsonValueKind.Number?h.GetProperty("shieldFraction").GetDouble():(double?)null;
                minimumHull=Math.Min(minimumHull??1,hull);if(shield is {} s)minimumShield=Math.Min(minimumShield??1,s);samples++;
                var ready=journal.State.InGame&&!monitor.EmergencyActive&&!monitor.TestingBlocked&&hull>=.5
                    &&!h.GetProperty("emergency").GetBoolean();
                var witness=JsonSerializer.Serialize(new{gamePid=pid,gameStartedUtcTicks=binding.StartedUtcTicks,observerPid=observerProcess.Id,observerStartedUtcTicks=observerStarted,
                    shipId=journal.State.CurrentShipId,healthAtUnixMilliseconds=h.GetProperty("observedAtUnixMilliseconds").GetInt64(),ready});
                try
                {await File.WriteAllTextAsync(reportPath+".ready.json.tmp",witness);File.Move(reportPath+".ready.json.tmp",reportPath+".ready.json",true);}
                catch(Exception error)when(error is IOException or UnauthorizedAccessException)
                {
                    // A reader can briefly deny Windows rename/delete sharing.
                    // Let the old witness expire and bar input, but never stop
                    // the actual damage monitor because publication is busy.
                    await log.WriteLineAsync(JsonSerializer.Serialize(new{at=DateTimeOffset.UtcNow,witnessPublication=error.Message,monitoringContinues=true}));
                }
                await log.WriteLineAsync(JsonSerializer.Serialize(new{at=DateTimeOffset.UtcNow,sequence=frame.GetProperty("sequence").GetInt64(),hull,shield,
                    journalHull=journal.State.Ships.FirstOrDefault(x=>x.ShipId==journal.State.CurrentShipId)?.HullHealth,
                    journalShieldUp=journal.State.Status is {} flags?(flags.Flags&8)!=0:(bool?)null,system=journal.State.SystemName,
                    entity=frame.GetProperty("entityId").GetString(),h,inputPermitted=protection.Fresh,protection.LastIssue,flightInputsSent=0}));await log.FlushAsync();
                if(samples==1)Console.WriteLine(JsonSerializer.Serialize(new{pid,hull,shield,journal.State.SystemName,armed=true,flightInputsSent=0}));
                await Task.Delay(100);
            }
            if(samples==0)throw new InvalidOperationException("No real main-ship health samples were observed.");
        }
        catch(Exception error){failure=error.ToString();Console.Error.WriteLine(error.Message);}
        finally
        {
            journal.JournalEvent-=ObserveJournal;
            if(protection is not null)await protection.DisposeAsync();
            await monitor.Completion;
            await File.WriteAllTextAsync(reportPath,JsonSerializer.Serialize(new{pid,start,finished=DateTimeOffset.UtcNow,samples,minimumHull,minimumShield,failure,flightInputsSent=0},ToolboxSettings.JsonOptions));
        }
    }
}