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

XFEWarframe

【WinUI】基于Warframe游戏本体的公开服务器以及安装器

公开
关注 0 Fork 0 Star 0
UTF-8
using System.Security.Cryptography;
using System.Diagnostics;
using System.Text;
using System.Text.Json;

namespace XFEWarframe.Client.Runtime;

public static class RuntimeDiscovery
{
    public static async Task<RuntimeSession[]> FindAllAsync(CancellationToken cancellation = default)
    {
        var root = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "XFEWarframe", "Runtime");
        if (!Directory.Exists(root)) return [];
        var result = new List<RuntimeSession>();
        foreach (var folder in Directory.EnumerateDirectories(root).Take(64))
        // A crashed game can leave discovery files behind. Inspect recent
        // sessions first so old files cannot hide the currently running game.
        foreach (var path in Directory.EnumerateFiles(folder, "*.json").OrderByDescending(File.GetLastWriteTimeUtc).Take(32))
        {
            cancellation.ThrowIfCancellationRequested();
            try
            {
                if (new FileInfo(path).Length > 8192) continue;
                var session = JsonSerializer.Deserialize(await File.ReadAllTextAsync(path, cancellation).ConfigureAwait(false), RuntimeJson.Default.RuntimeSession);
                if (session is null) continue; Validate(session);
                using var process = Process.GetProcessById(session.ProcessId);
                if (!process.HasExited && process.StartTime.ToUniversalTime() <= session.StartedAt.UtcDateTime &&
                    process.MainModule?.FileName.Equals(Path.Combine(Path.GetFullPath(session.GameDirectory), "Warframe.x64.exe"), StringComparison.OrdinalIgnoreCase) == true)
                    result.Add(session);
            }
            catch (Exception ex) when (ex is IOException or JsonException or ArgumentException or InvalidDataException or System.ComponentModel.Win32Exception or InvalidOperationException) { }
        }
        return result.OrderByDescending(x => x.StartedAt).ToArray();
    }
    public static string DirectoryFor(string gameDirectory) => Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
        "XFEWarframe", "Runtime", Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(Path.GetFullPath(gameDirectory).TrimEnd(Path.DirectorySeparatorChar).ToUpperInvariant()))));
    public static async Task<RuntimeSession[]> FindAsync(string gameDirectory, CancellationToken cancellation = default)
    {
        var directory = DirectoryFor(gameDirectory);
        if (!Directory.Exists(directory)) return [];
        var found = new List<RuntimeSession>();
        foreach (var path in Directory.EnumerateFiles(directory, "*.json").OrderByDescending(File.GetLastWriteTimeUtc).Take(32))
        {
            cancellation.ThrowIfCancellationRequested();
            try
            {
                if (new FileInfo(path).Length > 8192) continue;
                var session = JsonSerializer.Deserialize(await File.ReadAllTextAsync(path, cancellation).ConfigureAwait(false), RuntimeJson.Default.RuntimeSession);
                if (session is not null && Path.GetFullPath(session.GameDirectory).Equals(Path.GetFullPath(gameDirectory), StringComparison.OrdinalIgnoreCase))
                {
                    Validate(session);
                    using var process = Process.GetProcessById(session.ProcessId);
                    if (!process.HasExited && process.StartTime.ToUniversalTime() <= session.StartedAt.UtcDateTime) found.Add(session);
                }
            }
            catch (Exception ex) when (ex is IOException or JsonException or ArgumentException or InvalidDataException or System.ComponentModel.Win32Exception or InvalidOperationException) { }
        }
        return found.ToArray();
    }
    public static void Validate(RuntimeSession session)
    {
        if (!Uri.TryCreate(session.Endpoint, UriKind.Absolute, out var uri) || uri.Scheme != "http" || uri.Host != "127.0.0.1" || uri.UserInfo.Length > 0 ||
            uri.AbsolutePath != "/" || uri.Query.Length > 0 || uri.Fragment.Length > 0 || uri.Port < 1 || session.Token is not { Length: 64 } || !session.Token.All(Uri.IsHexDigit) ||
            !Guid.TryParseExact(session.Instance, "N", out _) || session.ProcessId <= 0)
            throw new InvalidDataException("运行时连接文件无效。");
    }
}