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

XFEWorkflow

【WinUI】XFE基于windows的工作流

公开
关注 0 Fork 0 Star 0
UTF-8
using System.Security.Cryptography;
using System.Text.Json;
using System.Text.Json.Nodes;
using XFEExtension.NetCore.AutoConfig;
using XFEExtension.NetCore.ServerInteractive.Interfaces;
using XFEExtension.NetCore.ServerInteractive.Models.UserModels;
using XFEWorkflow.Abstractions;
using XFEWorkflow.Space.Contracts;

namespace XFEWorkflow.Space.Server;

public partial class SpaceProfile : XFEProfile
{
    [ProfileProperty] private List<User> _users = [];
    [ProfileProperty] private List<EncryptedUserLoginModel> _sessions = [];
    [ProfileProperty] private Dictionary<string, string> _userAvatars = [];
    [ProfileProperty] private List<PluginPublication> _publications = [];
    [ProfileProperty] private List<WorkflowPublication> _workflowPublications = [];
    [ProfileProperty] private List<UploadSession> _uploads = [];
    [ProfileProperty] private string _listenUrl = "http://localhost:3300/";
    [ProfileProperty] private string _pfxPath = "";
    [ProfileProperty] private long _maxPackageBytes = PluginPackage.MaximumPackageBytes;
}

public sealed partial class SpaceStore
{
    private readonly SemaphoreSlim writes = new(1);
    public ProfileStore<SpaceProfile> Profile { get; }
    public string Root { get; }
    public SpaceStore(string root)
    {
        Root = Path.GetFullPath(root);
        foreach (var folder in new[] { Root, Path.Combine(Root, "packages"), Path.Combine(Root, "uploads"), Path.Combine(Root, "logs") }) Directory.CreateDirectory(folder);
        Profile = new(Path.Combine(Root, "Space.xpf")); Profile.Load();
    }
    public List<User> Users => Profile.Read(p => p.InstanceUsers.ToList());
    public List<EncryptedUserLoginModel> Sessions => Profile.Read(p => p.InstanceSessions.ToList());
    public void UpdateUser(IUserInfo user) => Persist(p =>
    {
        p.InstanceUsers.RemoveAll(x => x.Id == user.Id);
        p.InstanceUsers.Add((User)user);
    });
    public void AddSession(EncryptedUserLoginModel session) => Persist(p => p.InstanceSessions.Add(session));
    public void RemoveSession(EncryptedUserLoginModel session) => Persist(p => p.InstanceSessions.RemoveAll(x => x.SessionId == session.SessionId));
    private void Persist(Action<SpaceProfile> update)
    {
        writes.Wait();
        try { Profile.Update(update); Profile.SaveAsync().GetAwaiter().GetResult(); }
        finally { writes.Release(); }
    }
    public async Task<SpaceUser> RegisterAsync(string name, string password, string nickname, bool administrator = false)
    {
        if (name.Length is < 3 or > 64 || name.Any(c => !char.IsAsciiLetterOrDigit(c) && c is not '_' and not '-')) throw new ArgumentException("账号只能包含 3~64 位字母、数字、横线或下划线");
        if (password.Length is < 12 or > 1024) throw new ArgumentException("密码长度必须为 12~1024");
        if (nickname.Length > 100) throw new ArgumentException("昵称过长");
        var credential = PasswordHasher.Hash(password);
        await writes.WaitAsync();
        try
        {
            if (Users.Any(x => x.UserName.Equals(name, StringComparison.OrdinalIgnoreCase))) throw new InvalidOperationException("用户名已存在");
            if (administrator && Users.Any(x => x.PermissionLevel >= (int)SpaceRole.Administrator)) throw new InvalidOperationException("管理员已初始化");
            if (Users.Count >= 100_000) throw new InvalidOperationException("用户数量达到限制");
            var user = new User { UserName = name, NickName = nickname.Length == 0 ? name : nickname, PasswordCredential = credential, PermissionLevel = (int)(administrator ? SpaceRole.Administrator : SpaceRole.Author) };
            Profile.Update(p => p.InstanceUsers.Add(user)); await Profile.SaveAsync();
            return PublicUser(user);
        }
        finally { writes.Release(); }
    }
    public SpaceUser PublicUser(IUserInfo user) => new(user.Id, user.UserName, user.NickName, user.PermissionLevel >= 100 ? SpaceRole.Administrator : SpaceRole.Author,
        Profile.Read(p => p.InstanceUserAvatars.GetValueOrDefault(user.Id, "")));
    private static void Admin(SpaceUser user) { if (user.Role != SpaceRole.Administrator) throw new UnauthorizedAccessException("需要管理员权限"); }
    private string UploadPath(string id, string suffix)
    {
        RequireId(id); return Path.Combine(Root, "uploads", id + suffix);
    }
    private string PackagePath(string id) { RequireId(id); return Path.Combine(Root, "packages", id + ".xfeplugin"); }
    private static void RequireId(string id)
    {
        if (id.Length != 32 || id.Any(c => !char.IsAsciiHexDigit(c))) throw new InvalidDataException("无效标识符");
    }
    private UploadSession OwnedUpload(string id, SpaceUser user)
    {
        var upload = Profile.Read(p => p.InstanceUploads.FirstOrDefault(x => x.Id == id)) ?? throw new FileNotFoundException("上传会话不存在");
        if (upload.AuthorId != user.Id) throw new UnauthorizedAccessException("上传会话不属于当前作者");
        if (DateTimeOffset.UtcNow - upload.CreatedAt > TimeSpan.FromHours(24)) throw new InvalidOperationException("上传会话已过期");
        return upload;
    }
    private static JsonNode Node(object value) => JsonSerializer.SerializeToNode(value, WorkflowJson.Options)!;
    public async Task<JsonNode> PublicAsync(string route, JsonObject input)
    {
        switch (route)
        {
            case "workflows/preview": return await WorkflowPreviewAsync(input);
            case "workflows/search":
            case "workflows/detail": return WorkflowCatalog(route, input);
            case "health": return Node(new { name = "XFEWorkflow Space", sdk = 1, chunkBytes = PluginPackage.ChunkBytes });
            case "register": return Node(await RegisterAsync(input.String("account"), input.String("password"), input.String("nickname")));
            case "plugins/search":
                var query = input.String("query");
                var all = Profile.Read(p => WorkflowJson.Clone(p.InstancePublications)).Where(x => x.Status == PublicationStatus.Published
                    && (x.Manifest.Name.Contains(query, StringComparison.OrdinalIgnoreCase) || x.Manifest.Id.Contains(query, StringComparison.OrdinalIgnoreCase)
                        || x.Manifest.Description.Contains(query, StringComparison.OrdinalIgnoreCase)))
                    .GroupBy(x => x.Manifest.Id).Select(x => x.MaxBy(p => SemanticVersion.Parse(p.Manifest.Version))!)
                    .OrderByDescending(x => x.SubmittedAt).ToList();
                return Node(new CatalogPage { Total = all.Count, Items = all.Skip(Math.Max(0, input.Integer("offset"))).Take(Math.Clamp(input.Integer("limit", 50), 1, 100)).ToList() });
            case "plugins/detail":
                return Node(Profile.Read(p => WorkflowJson.Clone(p.InstancePublications)).Where(x => x.Status == PublicationStatus.Published && x.Manifest.Id == input.String("pluginId"))
                    .OrderByDescending(x => SemanticVersion.Parse(x.Manifest.Version)).ToList());
            case "packages/chunk":
                if (ResourceKind(input) == SpaceResourceKind.Workflow) return await WorkflowChunkAsync(input);
                var publication = Profile.Read(p => p.InstancePublications.SingleOrDefault(x => x.Id == input.String("id") && x.Status == PublicationStatus.Published))
                    ?? throw new FileNotFoundException("已上架版本不存在");
                var index = input.Integer("index", -1);
                if (index < 0 || (long)index * PluginPackage.ChunkBytes >= publication.PackageBytes) throw new ArgumentOutOfRangeException(nameof(input));
                await using (var file = new FileStream(PackagePath(publication.Id), FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    file.Position = (long)index * PluginPackage.ChunkBytes;
                    var buffer = new byte[(int)Math.Min(PluginPackage.ChunkBytes, file.Length - file.Position)];
                    await file.ReadExactlyAsync(buffer);
                    return Node(new { data = Convert.ToBase64String(buffer), index });
                }
            default: throw new NotSupportedException(route);
        }
    }
    public async Task<JsonNode> AuthorAsync(string route, JsonObject input, SpaceUser user)
    {
        await writes.WaitAsync();
        try
        {
            switch (route)
            {
                case "account/profile":
                    return Node(PublicUser(Users.Single(x => x.Id == user.Id)));
                case "account/update":
                    var nickname = input.String("nickname").Trim(); var avatar = input.String("avatarUrl").Trim();
                    if (nickname.Length > 100) throw new ArgumentException("昵称不能超过 100 个字符");
                    if (avatar.Length > 2048 || avatar.Length > 0 && (!Uri.TryCreate(avatar, UriKind.Absolute, out var imageUri) || imageUri.Scheme is not ("http" or "https")))
                        throw new ArgumentException("头像地址必须是 HTTP 或 HTTPS 图片地址");
                    Profile.Update(p =>
                    {
                        var account = p.InstanceUsers.Single(x => x.Id == user.Id);
                        account.NickName = nickname.Length == 0 ? account.UserName : nickname;
                        if (avatar.Length == 0) p.InstanceUserAvatars.Remove(user.Id); else p.InstanceUserAvatars[user.Id] = avatar;
                    });
                    await Profile.SaveAsync(); return Node(PublicUser(Users.Single(x => x.Id == user.Id)));
                case "plugins/mine": return Node(Profile.Read(p => WorkflowJson.Clone(p.InstancePublications.Where(x => x.AuthorId == user.Id).ToList())));
                case "workflows/mine": return Node(Profile.Read(p => WorkflowJson.Clone(p.InstanceWorkflowPublications.Where(x => x.AuthorId == user.Id).OrderByDescending(x => x.SubmittedAt).ToList())));
                case "workflows/preview/private": return await WorkflowPreviewAsync(input, user);
                case "workflows/withdraw": return await WorkflowReviewAsync(input, user, true);
                case "reviews/list":
                    if (ResourceKind(input) == SpaceResourceKind.Workflow) { Admin(user); return Node(Profile.Read(p => WorkflowJson.Clone(p.InstanceWorkflowPublications.OrderByDescending(x => x.SubmittedAt).ToList()))); }
                    Admin(user); return Node(Profile.Read(p => WorkflowJson.Clone(p.InstancePublications.OrderByDescending(x => x.SubmittedAt).ToList())));
                case "uploads/begin":
                    var kind = ResourceKind(input); var version = input.String("version");
                    if (kind == SpaceResourceKind.Workflow && !SemanticVersion.TryParse(version, out _)) throw new InvalidDataException("工作流发布版本必须为语义版本,例如 1.0.0");
                    _ = long.TryParse(input["length"].Text(), System.Globalization.NumberStyles.None, System.Globalization.CultureInfo.InvariantCulture, out var length);
                    var hash = input.String("sha256");
                    if (length <= 0 || length > Math.Min(PluginPackage.MaximumPackageBytes, Profile.Read(p => p.InstanceMaxPackageBytes))) throw new InvalidDataException("资源包超过允许大小");
                    if (kind == SpaceResourceKind.Workflow && length > WorkflowPackage.MaximumBytes) throw new InvalidDataException("工作流包超过 32 MiB");
                    if (hash.Length != 64 || hash.Any(c => !char.IsAsciiHexDigit(c))) throw new InvalidDataException("无效 SHA256");
                    // Reclaim abandoned uploads on each new upload, including their bounded staging files.
                    foreach (var expired in Profile.Read(p => p.InstanceUploads.Where(x => DateTimeOffset.UtcNow - x.CreatedAt > TimeSpan.FromHours(24)).ToList()))
                    {
                        for (var i = 0; i < expired.ChunkCount; i++) File.Delete(UploadPath(expired.Id, "." + i));
                        File.Delete(UploadPath(expired.Id, ".package"));
                        Profile.Update(p => p.InstanceUploads.RemoveAll(x => x.Id == expired.Id));
                    }
                    if (Profile.Read(p => p.InstanceUploads.Count(x => x.AuthorId == user.Id)) >= 5) throw new InvalidOperationException("最多同时上传 5 个资源包");
                    var upload = new UploadSession { Kind = kind, Version = version, AuthorId = user.Id, Length = length, Sha256 = hash.ToLowerInvariant(), ChunkCount = (int)((length + PluginPackage.ChunkBytes - 1) / PluginPackage.ChunkBytes) };
                    Profile.Update(p => p.InstanceUploads.Add(upload)); await Profile.SaveAsync();
                    return Node(upload);
                case "uploads/chunk":
                    var chunkUpload = OwnedUpload(input.String("id"), user);
                    var chunkIndex = input.Integer("index", -1);
                    if (chunkIndex < 0 || chunkIndex >= chunkUpload.ChunkCount) throw new InvalidDataException("分片索引越界");
                    var encoded = input.String("data");
                    if (encoded.Length > (PluginPackage.ChunkBytes + 2) / 3 * 4) throw new InvalidDataException("分片过大");
                    var bytes = Convert.FromBase64String(encoded);
                    var expected = (int)Math.Min(PluginPackage.ChunkBytes, chunkUpload.Length - (long)chunkIndex * PluginPackage.ChunkBytes);
                    if (bytes.Length != expected) throw new InvalidDataException("分片长度错误");
                    var chunkFile = UploadPath(chunkUpload.Id, "." + chunkIndex);
                    if (File.Exists(chunkFile))
                    {
                        if (!SHA256.HashData(await File.ReadAllBytesAsync(chunkFile)).SequenceEqual(SHA256.HashData(bytes))) throw new InvalidOperationException("分片内容不可覆盖");
                    }
                    else await File.WriteAllBytesAsync(chunkFile, bytes);
                    return Node(new { accepted = true });
                case "uploads/cancel":
                    var cancelled = OwnedUpload(input.String("id"), user);
                    for (var i = 0; i < cancelled.ChunkCount; i++) File.Delete(UploadPath(cancelled.Id, "." + i));
                    File.Delete(UploadPath(cancelled.Id, ".package"));
                    Profile.Update(p => p.InstanceUploads.RemoveAll(x => x.Id == cancelled.Id)); await Profile.SaveAsync();
                    return Node(new { cancelled = true });
                case "uploads/complete":
                    var complete = OwnedUpload(input.String("id"), user);
                    var staging = UploadPath(complete.Id, ".package");
                    await using (var destination = new FileStream(staging, FileMode.Create, FileAccess.Write, FileShare.None))
                        for (var i = 0; i < complete.ChunkCount; i++)
                        {
                            await using var part = File.OpenRead(UploadPath(complete.Id, "." + i));
                            await part.CopyToAsync(destination);
                        }
                    await using (var file = File.OpenRead(staging))
                    {
                        if (file.Length != complete.Length || !Convert.ToHexString(await SHA256.HashDataAsync(file)).Equals(complete.Sha256, StringComparison.OrdinalIgnoreCase)) throw new InvalidDataException("资源包哈希校验失败");
                    }
                    if (complete.Kind == SpaceResourceKind.Workflow) return await CompleteWorkflowAsync(complete, staging, user);
                    var manifest = PluginPackage.Inspect(staging);
                    var versions = Profile.Read(p => p.InstancePublications.Where(x => x.Manifest.Id == manifest.Id).ToList());
                    if (versions.Any(x => x.AuthorId != user.Id)) throw new UnauthorizedAccessException("插件 ID 已属于其他作者");
                    if (versions.Any(x => x.Manifest.Version == manifest.Version)) throw new InvalidOperationException("版本已经提交,内容不可覆盖");
                    var published = new PluginPublication { Manifest = manifest, AuthorId = user.Id, AuthorName = user.NickName, Sha256 = complete.Sha256, PackageBytes = complete.Length, Status = PublicationStatus.Pending };
                    File.Move(staging, PackagePath(published.Id), false);
                    Profile.Update(p => { p.InstancePublications.Add(published); p.InstanceUploads.RemoveAll(x => x.Id == complete.Id); });
                    await Profile.SaveAsync();
                    for (var i = 0; i < complete.ChunkCount; i++) File.Delete(UploadPath(complete.Id, "." + i));
                    return Node(published);
                case "reviews/decide":
                    if (ResourceKind(input) == SpaceResourceKind.Workflow) return await WorkflowReviewAsync(input, user, false);
                    Admin(user);
                    var decision = input.String("decision");
                    var review = Profile.Read(p => p.InstancePublications.SingleOrDefault(x => x.Id == input.String("id"))) ?? throw new FileNotFoundException("版本不存在");
                    if (decision is not ("publish" or "reject" or "withdraw")) throw new ArgumentException("未知审核决定");
                    if (decision is "publish" or "reject" && review.Status != PublicationStatus.Pending) throw new InvalidOperationException("只能审核待审核版本");
                    if (decision == "withdraw" && review.Status != PublicationStatus.Published) throw new InvalidOperationException("只能下架已上架版本");
                    Profile.Update(_ => { review.Status = decision == "publish" ? PublicationStatus.Published : decision == "reject" ? PublicationStatus.Rejected : PublicationStatus.Withdrawn; review.ReviewReason = input.String("reason"); review.ReviewedAt = DateTimeOffset.UtcNow; });
                    await Profile.SaveAsync(); return Node(review);
                case "plugins/withdraw":
                    var withdraw = Profile.Read(p => p.InstancePublications.SingleOrDefault(x => x.Id == input.String("id"))) ?? throw new FileNotFoundException("版本不存在");
                    if (withdraw.AuthorId != user.Id && user.Role != SpaceRole.Administrator) throw new UnauthorizedAccessException("不能下架其他作者的插件");
                    if (withdraw.Status != PublicationStatus.Published) throw new InvalidOperationException("版本尚未上架");
                    Profile.Update(_ => { withdraw.Status = PublicationStatus.Withdrawn; withdraw.ReviewedAt = DateTimeOffset.UtcNow; }); await Profile.SaveAsync();
                    return Node(withdraw);
                default: throw new NotSupportedException(route);
            }
        }
        finally { writes.Release(); }
    }
}