using System.IO.Compression; using System.Text; using System.Text.Json; using XFEExtension.NetCore.AutoConfig; using XFEWorkflow.Abstractions; namespace XFEWorkflow.Infrastructure.Storage; public sealed class WorkspacePaths { public string Root { get; } public string Workflows => Path.Combine(Root, "Workflows"); public string Plugins => Path.Combine(Root, "Plugins"); public string Runs => Path.Combine(Root, "Runs"); public string Temp => Path.Combine(Root, "Temp"); public string BrowserProfiles => Path.Combine(Root, "BrowserProfiles"); public string Logs => Path.Combine(Root, "Logs"); public WorkspacePaths(string root) { Root = Path.GetFullPath(root); foreach (var directory in new[] { Root, Workflows, Plugins, Runs, Temp, BrowserProfiles, Logs }) Directory.CreateDirectory(directory); } public static string Inside(string root, string relative) { var fullRoot = Path.GetFullPath(root).TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar; var path = Path.GetFullPath(Path.Combine(fullRoot, relative)); if (!path.StartsWith(fullRoot, StringComparison.OrdinalIgnoreCase)) throw new InvalidDataException("路径越界"); return path; } public static void RequireId(string id) { if (id.Length is < 1 or > 100 || id.Any(c => !char.IsAsciiLetterOrDigit(c) && c is not '-' and not '_')) throw new InvalidDataException("无效的标识符"); } } public static class AtomicJson { public static async Task WriteAsync(string path, T value, CancellationToken ct = default) { Directory.CreateDirectory(Path.GetDirectoryName(Path.GetFullPath(path))!); var temporary = path + "." + Guid.NewGuid().ToString("N") + ".tmp"; try { await using (var stream = new FileStream(temporary, FileMode.CreateNew, FileAccess.Write, FileShare.None, 81920, FileOptions.Asynchronous | FileOptions.WriteThrough)) { await JsonSerializer.SerializeAsync(stream, value, WorkflowJson.Options, ct); await stream.FlushAsync(ct); } for (var attempt = 0; ; attempt++) { try { File.Move(temporary, path, true); break; } catch (IOException) when (OperatingSystem.IsWindows() && attempt < 9 && File.Exists(temporary)) { await Task.Delay(50 * (attempt + 1), ct); } catch (UnauthorizedAccessException) when (OperatingSystem.IsWindows() && attempt < 9 && File.Exists(temporary)) { await Task.Delay(50 * (attempt + 1), ct); } } } finally { if (File.Exists(temporary)) File.Delete(temporary); } } public static async Task ReadAsync(string path, CancellationToken ct = default) { if (!File.Exists(path)) return default; await using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete); return await JsonSerializer.DeserializeAsync(stream, WorkflowJson.Options, ct); } } public sealed class WorkflowRepository(WorkspacePaths paths) { private readonly SemaphoreSlim gate = new(1); public async Task> ListAsync(CancellationToken ct = default) { List workflows = []; foreach (var file in Directory.EnumerateFiles(paths.Workflows, "workflow.json", SearchOption.AllDirectories)) { try { if (await AtomicJson.ReadAsync(file, ct) is { } workflow) { WorkflowTriggerNodes.Migrate(workflow); workflows.Add(workflow); } } catch (JsonException ex) { Console.WriteLine($"[WARN]无法读取工作流 {Path.GetFileName(Path.GetDirectoryName(file))}:{ex.Message}"); } } return workflows.OrderByDescending(x => x.ModifiedAt).ToList(); } public async Task GetAsync(string id, CancellationToken ct = default) { WorkspacePaths.RequireId(id); var workflow = await AtomicJson.ReadAsync(WorkspacePaths.Inside(paths.Workflows, id + "/workflow.json"), ct) ?? throw new FileNotFoundException("工作流不存在:" + id); WorkflowTriggerNodes.Migrate(workflow); return workflow; } public async Task SaveAsync(WorkflowDefinition workflow, CancellationToken ct = default) { WorkspacePaths.RequireId(workflow.Id); await gate.WaitAsync(ct); try { WorkflowTriggerNodes.Migrate(workflow); var saved = await AtomicJson.ReadAsync(WorkspacePaths.Inside(paths.Workflows, workflow.Id + "/workflow.json"), ct); if (saved is not null) { WorkflowTriggerNodes.Migrate(saved); workflow.Enabled = saved.Enabled; workflow.Priority = saved.Priority; } workflow.ModifiedAt = DateTimeOffset.UtcNow; await AtomicJson.WriteAsync(WorkspacePaths.Inside(paths.Workflows, workflow.Id + "/workflow.json"), workflow, ct); } finally { gate.Release(); } } public async Task SetActivationAsync(string id, bool enabled, int? priority = null, CancellationToken ct = default) { await gate.WaitAsync(ct); try { var workflow = await GetAsync(id, ct); workflow.Enabled = enabled; if (priority is not null) workflow.Priority = priority.Value; workflow.ModifiedAt = DateTimeOffset.UtcNow; await AtomicJson.WriteAsync(WorkspacePaths.Inside(paths.Workflows, id + "/workflow.json"), workflow, ct); } finally { gate.Release(); } } public async Task DeleteAsync(string id, CancellationToken ct = default) { WorkspacePaths.RequireId(id); await gate.WaitAsync(ct); try { var source = WorkspacePaths.Inside(paths.Workflows, id); var trash = WorkspacePaths.Inside(paths.Root, "Deleted/" + id + "-" + DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()); Directory.CreateDirectory(Path.GetDirectoryName(trash)!); if (Directory.Exists(source)) Directory.Move(source, trash); } finally { gate.Release(); } } public async Task ExportAsync(WorkflowDefinition workflow, string output, CancellationToken ct = default) { await using var stream = new FileStream(output, FileMode.Create, FileAccess.Write); using var archive = new ZipArchive(stream, ZipArchiveMode.Create); await using var entry = archive.CreateEntry("workflow.json", CompressionLevel.Optimal).Open(); await entry.WriteAsync(Encoding.UTF8.GetBytes(WorkflowJson.SerializeDisplay(workflow)), ct); } public async Task ImportAsync(string input, CancellationToken ct = default) { if (new FileInfo(input).Length > 32 * 1024 * 1024) throw new InvalidDataException("工作流文件过大"); WorkflowDefinition? workflow; if (Path.GetExtension(input).Equals(".json", StringComparison.OrdinalIgnoreCase)) workflow = await AtomicJson.ReadAsync(input, ct); else { using var archive = ZipFile.OpenRead(input); var entry = archive.GetEntry("workflow.json") ?? throw new InvalidDataException("缺少 workflow.json"); if (entry.Length > 32 * 1024 * 1024) throw new InvalidDataException("工作流定义过大"); await using var entryStream = entry.Open(); workflow = await JsonSerializer.DeserializeAsync(entryStream, WorkflowJson.Options, ct); } if (workflow is null || workflow.SchemaVersion != 1) throw new InvalidDataException("工作流格式不兼容"); workflow.Id = Guid.NewGuid().ToString("N"); workflow.Enabled = false; await SaveAsync(workflow, ct); return workflow; } } public partial class ClientStateProfile : XFEProfile { [ProfileProperty] private List _plugins = []; [ProfileProperty] private string _deviceId = Guid.NewGuid().ToString("N"); [ProfileProperty] private string _desktopBackend = "standard"; [ProfileProperty] private Dictionary _credentials = []; [ProfileProperty] private string _spaceSession = ""; [ProfileProperty] private string _spaceUserJson = ""; [ProfileProperty] private string _spaceUserAddress = ""; [ProfileProperty] private Dictionary _paneSizes = []; [ProfileProperty] private List _favoriteCapabilities = []; [ProfileProperty] private List _recentCapabilities = []; [ProfileProperty] private List _expandedPaletteCategories = ["触发器", "流程"]; [ProfileProperty] private string _weComSettingsJson = "{}"; [ProfileProperty] private Dictionary _pluginSettings = []; } public sealed class ClientState : IAsyncDisposable { public const string LocalServerAddress = "http://localhost:3300/space/v1/"; private string serverAddress = LocalServerAddress; public ProfileStore Store { get; } public ClientState(WorkspacePaths paths) { Store = new(Path.Combine(paths.Root, "ClientState.xpf")); Store.Load(); } public List Plugins => Store.Read(p => WorkflowJson.Clone(p.InstancePlugins)); // The desktop product owns its server endpoint. Persisted legacy addresses // are ignored; only the internal UI fixture can substitute a loopback server. public string SpaceAddress { get => serverAddress; internal set => serverAddress = Space.SpaceClient.ValidateAddress(value); } public string DeviceId => Store.Read(p => p.InstanceDeviceId); public string DesktopBackend { get => Store.Read(p => p.InstanceDesktopBackend); set => Store.Update(p => p.InstanceDesktopBackend = value); } public double PaneSize(string key, double fallback) => Store.Read(p => p.InstancePaneSizes.TryGetValue(key, out var value) && double.IsFinite(value) && value > 0 ? value : fallback); public void SetPaneSize(string key, double value) { if (!double.IsFinite(value) || value <= 0) throw new ArgumentOutOfRangeException(nameof(value)); Store.Update(p => p.InstancePaneSizes = new(p.InstancePaneSizes) { [key] = value }); } public HashSet FavoriteCapabilities => Store.Read(p => p.InstanceFavoriteCapabilities.ToHashSet(StringComparer.Ordinal)); public List RecentCapabilities => Store.Read(p => p.InstanceRecentCapabilities.ToList()); public System.Text.Json.Nodes.JsonObject WeComSettings { get => Store.Read(p => System.Text.Json.Nodes.JsonNode.Parse(p.InstanceWeComSettingsJson)?.AsObject() ?? new()); set => Store.Update(p => p.InstanceWeComSettingsJson = value.ToJsonString()); } public HashSet ExpandedPaletteCategories => Store.Read(p => p.InstanceExpandedPaletteCategories.ToHashSet(StringComparer.Ordinal)); public System.Text.Json.Nodes.JsonObject PluginSettings(string id) => Store.Read(p => System.Text.Json.Nodes.JsonNode.Parse(p.InstancePluginSettings.GetValueOrDefault(id, "{}"))?.AsObject() ?? new()); public void SetPluginSettings(string id, System.Text.Json.Nodes.JsonObject value) => Store.Update(p => p.InstancePluginSettings = new(p.InstancePluginSettings) { [id] = value.ToJsonString() }); public void SetFavorite(string id, bool favorite) => Store.Update(p => { var values = p.InstanceFavoriteCapabilities.ToHashSet(StringComparer.Ordinal); if (favorite) values.Add(id); else values.Remove(id); p.InstanceFavoriteCapabilities = values.Order(StringComparer.Ordinal).ToList(); }); public void RecordCapability(string id) => Store.Update(p => p.InstanceRecentCapabilities = new[] { id } .Concat(p.InstanceRecentCapabilities.Where(x => x != id)).Take(12).ToList()); public void SetExpandedPaletteCategories(IEnumerable names) => Store.Update(p => p.InstanceExpandedPaletteCategories = names.Distinct(StringComparer.Ordinal).ToList()); public Task SaveAsync(CancellationToken ct = default) => Store.SaveAsync(ct); public async ValueTask DisposeAsync() { await Store.SaveAsync(); } }