using System.Security.Cryptography; using System.Text.Json; using System.Text.Json.Nodes; using XFEExtension.NetCore.ServerInteractive.Utilities.Requester; using XFEWorkflow.Abstractions; using XFEWorkflow.Infrastructure.Plugins; using XFEWorkflow.Infrastructure.Storage; using XFEWorkflow.Space.Contracts; namespace XFEWorkflow.Infrastructure.Space; public sealed partial class SpaceClient { private readonly SemaphoreSlim installGate = new(1); private readonly ClientState state; private readonly CredentialVault vault; private ClientRequester requester = null!; public SpaceUser? User { get; private set; } public event Action? UserChanged; public SpaceClient(ClientState state, CredentialVault vault) { this.state = state; this.vault = vault; Reconnect(); } private string SessionReference => "space.session." + Convert.ToHexString(SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(state.SpaceAddress)))[..16]; public static string ValidateAddress(string value) { if (!Uri.TryCreate(value.Trim(), UriKind.Absolute, out var uri) || uri.Scheme is not ("http" or "https") || uri.Query.Length > 0 || uri.Fragment.Length > 0) throw new ArgumentException("Space 地址必须是 HTTP 或 HTTPS 服务地址"); return uri.AbsoluteUri.TrimEnd('/') + "/"; } public void Reconnect() { _ = ValidateAddress(state.SpaceAddress); var builder = ClientRequesterBuilder.CreateBuilder(); foreach (var route in SpaceRoutes.All) builder.AddRequest(route, (session, device, args) => { var body = args.FirstOrDefault() is JsonObject obj ? WorkflowJson.Copy(obj) : new JsonObject(); body["session"] = session; body["deviceInfo"] = device; return body; }, response => JsonNode.Parse(response)!); requester = builder.Build(options => { options.RequestAddress = state.SpaceAddress.TrimEnd('/') + "/"; options.DeviceInfo = state.DeviceId; }); try { requester.Session = vault.Get(SessionReference); } catch (Exception ex) when (ex is KeyNotFoundException or CryptographicException or PlatformNotSupportedException) { } var userJson = state.Store.Read(p => p.InstanceSpaceUserJson); try { User = userJson.Length == 0 || state.Store.Read(p => p.InstanceSpaceUserAddress) != state.SpaceAddress ? null : JsonSerializer.Deserialize(userJson, WorkflowJson.Options); } catch (JsonException) { User = null; } UserChanged?.Invoke(); } public async Task RequestAsync(string route, JsonObject? body = null, CancellationToken ct = default) { var response = await requester.RequestAsync(route, ct, body ?? []); ct.ThrowIfCancellationRequested(); if ((int)response.StatusCode is < 200 or >= 300 || response.Result is null) throw new InvalidOperationException($"Space {(int)response.StatusCode}:{response.Message}"); return response.Result; } public async Task LoginAsync(string account, string password, CancellationToken ct = default) { var result = (await RequestAsync("login", new() { ["account"] = account, ["password"] = password }, ct)).Deserialize(WorkflowJson.Options) ?? throw new InvalidDataException("登录响应无效"); requester.Session = result.Session; await vault.SetAsync(SessionReference, result.Session, ct); await SaveUserAsync(result.UserInfo ?? throw new InvalidDataException("登录响应缺少用户信息"), ct); } public async Task LogoutAsync() { await vault.RemoveAsync(SessionReference); requester.Session = ""; User = null; state.Store.Update(p => p.InstanceSpaceUserJson = ""); await state.SaveAsync(); UserChanged?.Invoke(); } private async Task SaveUserAsync(SpaceUser user, CancellationToken ct) { state.Store.Update(p => { p.InstanceSpaceUserJson = JsonSerializer.Serialize(user, WorkflowJson.Options); p.InstanceSpaceUserAddress = state.SpaceAddress; }); await state.SaveAsync(ct); User = user; UserChanged?.Invoke(); } public async Task UpdateProfileAsync(string nickname, string avatarUrl, CancellationToken ct = default) => await SaveUserAsync((await RequestAsync("account/update", new() { ["nickname"] = nickname, ["avatarUrl"] = avatarUrl }, ct)).Deserialize(WorkflowJson.Options) ?? throw new InvalidDataException("用户资料响应无效"), ct); public async Task RefreshProfileAsync(CancellationToken ct = default) => await SaveUserAsync((await RequestAsync("account/profile", ct: ct)).Deserialize(WorkflowJson.Options) ?? throw new InvalidDataException("用户资料响应无效"), ct); public async Task UploadAsync(string package, IProgress? progress = null, CancellationToken ct = default) { await Task.Run(() => PluginPackage.Inspect(package), ct); return (await UploadResourceAsync(package, "plugin", "", progress, ct)).Deserialize(WorkflowJson.Options)!; } public async Task DownloadAsync(PluginPublication publication, WorkspacePaths paths, PluginManager plugins, IProgress? progress = null, CancellationToken ct = default) => await InstallWithDependenciesAsync(publication.Manifest, null, publication, paths, plugins, progress, ct); public async Task InstallLocalAsync(string package, WorkspacePaths paths, PluginManager plugins, CancellationToken ct = default) => await InstallWithDependenciesAsync(PluginPackage.Inspect(package), package, null, paths, plugins, null, ct); private async Task InstallWithDependenciesAsync(PluginManifest root, string? localPackage, PluginPublication? rootPublication, WorkspacePaths paths, PluginManager plugins, IProgress? progress, CancellationToken ct) { await installGate.WaitAsync(ct); var staged = new Dictionary(); var publications = new Dictionary(); try { if (rootPublication is not null) publications[root.Id + "/" + root.Version] = rootPublication; var plan = await PluginDependencyResolver.ResolveAsync(root, async (id, cancellation) => { var local = plugins.Installed.Where(x => !x.PendingRemoval && x.Manifest.Id == id).Select(x => x.Manifest).ToList(); // Exact installed dependencies work offline. Ranges also inspect Space to resolve shared constraints correctly. if (local.Count > 0 && root.Dependencies.Any(x => x.Id == id && x.ExactVersion is { } exact && local.Any(m => m.Version == exact))) return local; var remote = (await RequestAsync("plugins/detail", new() { ["pluginId"] = id }, cancellation)).Deserialize>(WorkflowJson.Options)!; foreach (var item in remote) publications[item.Manifest.Id + "/" + item.Manifest.Version] = item; return local.Concat(remote.Select(x => x.Manifest)).DistinctBy(x => x.Version).ToList(); }, ct); foreach (var manifest in plan) { var key = manifest.Id + "/" + manifest.Version; if (plugins.Installed.Any(x => x.Manifest.Id == manifest.Id && x.Manifest.Version == manifest.Version && !x.PendingRemoval)) continue; if (manifest.Id == root.Id && localPackage is not null) staged[key] = localPackage; else if (publications.TryGetValue(key, out var remote)) staged[key] = await DownloadPackageAsync(remote, paths, progress, ct); else throw new InvalidOperationException("依赖版本无法下载:" + key); var actual = PluginPackage.Inspect(staged[key]); if (JsonSerializer.Serialize(actual, WorkflowJson.Options) != JsonSerializer.Serialize(manifest, WorkflowJson.Options)) throw new InvalidDataException("下载内容与目录声明不一致:" + key); } // All dependency packages are verified before changing the installed set. foreach (var manifest in plan) { var existing = plugins.Installed.FirstOrDefault(x => x.Manifest.Id == manifest.Id && x.Manifest.Version == manifest.Version && !x.PendingRemoval); if (existing is null) await plugins.InstallAsync(staged[manifest.Id + "/" + manifest.Version], localPackage is null ? state.SpaceAddress : "本地导入", ct); else if (!existing.Enabled) await plugins.SetEnabledAsync(existing, true, ct); } return plugins.Installed.Single(x => x.Manifest.Id == root.Id && x.Manifest.Version == root.Version); } finally { foreach (var file in staged.Values.Where(x => x != localPackage)) if (File.Exists(file)) File.Delete(file); installGate.Release(); } } private async Task DownloadPackageAsync(PluginPublication publication, WorkspacePaths paths, IProgress? progress = null, CancellationToken ct = default) => await DownloadResourceAsync(publication.Id, publication.PackageBytes, publication.Sha256, "plugin", paths, progress, ct); private async Task DownloadResourceAsync(string id, long length, string hash, string kind, WorkspacePaths paths, IProgress? progress, CancellationToken ct) { if (length <= 0 || length > (kind == "workflow" ? WorkflowPackage.MaximumBytes : PluginPackage.MaximumPackageBytes)) throw new InvalidDataException("资源大小无效"); var package = WorkspacePaths.Inside(paths.Temp, Guid.NewGuid().ToString("N") + (kind == "workflow" ? ".xfeworkflow" : ".xfeplugin")); try { await using (var stream = new FileStream(package, FileMode.CreateNew, FileAccess.Write, FileShare.None)) for (var i = 0; stream.Length < length; i++) { var chunk = await RequestAsync("packages/chunk", new() { ["id"] = id, ["index"] = i, ["kind"] = kind }, ct); var data = Convert.FromBase64String(chunk["data"]!.GetValue()); if (data.Length != Math.Min(PluginPackage.ChunkBytes, length - stream.Length)) throw new InvalidDataException("下载分片长度错误"); await stream.WriteAsync(data, ct); progress?.Report((double)stream.Length / length); } await using (var stream = File.OpenRead(package)) if (!Convert.ToHexString(await SHA256.HashDataAsync(stream, ct)).Equals(hash, StringComparison.OrdinalIgnoreCase)) throw new InvalidDataException("下载哈希校验失败"); return package; } catch { if (File.Exists(package)) File.Delete(package); throw; } } }