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

XFEWorkflow

【WinUI】XFE基于windows的工作流

公开
关注 0 Fork 0 Star 0
UTF-8
using System.Collections.Concurrent;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Threading.Channels;
using XFEWorkflow.Abstractions;
using XFEWorkflow.Plugins.WeCom.Native.Core;
using XFEWorkflow.Plugins.WeCom.Native.Integrations;

namespace XFEWorkflow.Plugins.WeCom;

/// <summary>One native connection, shared routing and durable deduplication across all workflow Runners.</summary>
public sealed class WeComHostService(string directory, string runtimeDirectory, Func<IWeComTransport>? transportFactory = null, Func<int?, ClientTarget>? clientProbe = null) : IAsyncDisposable
{
    private readonly SemaphoreSlim connectionGate = new(1), sendGate = new(1), pumpGate = new(1);
    private readonly ConcurrentDictionary<string, Subscription> subscriptions = [];
    private readonly ConcurrentDictionary<string, Dispatch> dispatches = [];
    private IWeComTransport? transport;
    private ClientSession? session;
    private WeComGroup? group;
    private WeComMember? member;
    private IReadOnlyDictionary<string, string> groupNames = new Dictionary<string, string>();
    private IReadOnlyDictionary<string, string> senderNames = new Dictionary<string, string>();
    private CancellationTokenSource? listening;
    private Task? pump;
    private DateTimeOffset connectedAt;
    private string error = "";
    public event Action<string>? Log;
    public JsonObject Status => new() { ["connected"] = session is not null && error.Length == 0, ["listening"] = pump is { IsCompleted: false } && listening?.IsCancellationRequested != true, ["version"] = session?.ClientVersion,
        ["accountId"] = session?.AccountId, ["groupId"] = group?.Id, ["groupName"] = group?.Name, ["senderId"] = member?.Id, ["senderName"] = member?.DisplayName,
        ["subscriptions"] = subscriptions.Count, ["error"] = error, ["hasContent"] = false, ["supportedVersion"] = "5.0.11.6029", ["nativeArchitecture"] = "x86", ["hostArchitecture"] = "x64" };
    public async Task<JsonObject> InvokeAsync(string owner, string operation, JsonObject input, CancellationToken ct)
    {
        switch (operation)
        {
            case "wecom.status": return Status;
            case "wecom.probe":
                var clients = new JsonArray();
                foreach (var process in System.Diagnostics.Process.GetProcessesByName("WXWork")) using (process)
                { try { var target = ClientProbe.FindRunningClient(process.Id); clients.Add(JsonSerializer.SerializeToNode(target, WorkflowJson.Options)); } catch (Exception ex) { clients.Add(new JsonObject { ["processId"] = process.Id, ["error"] = ex.Message }); } }
                return new() { ["clients"] = clients, ["installation"] = JsonSerializer.SerializeToNode(ClientProbe.InspectInstallation(), WorkflowJson.Options),
                    ["cache"] = JsonSerializer.SerializeToNode(ClientProbe.InspectDefaultCache(), WorkflowJson.Options), ["supportedVersion"] = "5.0.11.6029" };
            case "wecom.connect": return await ConnectAsync(input, ct);
            case "wecom.disconnect": await DisconnectAsync(); return Status;
            case "wecom.groups": EnsureConnected(); return new() { ["groups"] = JsonSerializer.SerializeToNode(await transport!.GetGroupsAsync(ct), WorkflowJson.Options) };
            case "wecom.members":
                EnsureConnected();
                var selectedGroup = input.String("groupId"); if (selectedGroup.Length == 0) selectedGroup = group?.Id ?? "";
                var knownMembers = transport is NativeMemoryTransport && group?.Id == selectedGroup && member is not null
                    ? new[] { member } : await transport!.GetMembersAsync(selectedGroup, ct);
                return new() { ["members"] = JsonSerializer.SerializeToNode(knownMembers, WorkflowJson.Options), ["completeRoster"] = false };
            case "wecom.contacts":
                EnsureConnected(); if (transport is not NativeMemoryTransport native) throw new NotSupportedException("当前适配器不提供缓存联系人");
                return new() { ["contacts"] = JsonSerializer.SerializeToNode(ContactLookup.Search(await native.GetCachedContactsAsync(ct), input.String("query")), WorkflowJson.Options), ["completeRoster"] = false };
            case "wecom.subscribe": return await SubscribeAsync(owner, input, ct);
            case "wecom.next":
                var subscription = OwnSubscription(owner, input.String("subscription"));
                return await subscription.Events.Reader.ReadAsync(ct);
            case "wecom.ack":
                var acknowledged = OwnSubscription(owner, input.String("subscription"));
                if (dispatches.TryGetValue(input.String("dispatchId"), out var dispatch) && dispatch.Subscription == acknowledged.Id) dispatch.Finished.TrySetResult();
                return new() { ["acknowledged"] = true };
            case "wecom.unsubscribe": await ReleaseAsync(owner); return new();
            case "wecom.reply": return await ReplyAsync(input, ct);
            case "wecom.selfTest":
                EnsureConnected(); if (transport is not NativeMemoryTransport testable) throw new NotSupportedException("当前适配器不提供发送自测");
                await sendGate.WaitAsync(ct); try { var receipt = await testable.SendSelfTestAsync(ct); Log?.Invoke(receipt); return new() { ["detail"] = receipt }; } finally { sendGate.Release(); }
            case "wecom.attempts": return new() { ["reserved"] = Directory.Exists(AttemptDirectory) ? Directory.EnumerateFiles(AttemptDirectory, "*.json").Count() : 0 };
            default: throw new NotSupportedException(operation);
        }
    }
    private async Task<JsonObject> ConnectAsync(JsonObject input, CancellationToken ct)
    {
        await connectionGate.WaitAsync(ct);
        try
        {
            await DisconnectCoreAsync(); error = "";
            if (transportFactory is null && (!OperatingSystem.IsWindows() || System.Runtime.InteropServices.RuntimeInformation.ProcessArchitecture != System.Runtime.InteropServices.Architecture.X64)) throw new PlatformNotSupportedException("本机企业微信原生连接仅支持 Windows x64 宿主;群机器人能力仍可使用");
            var pid = input.Integer("processId"); var target = (clientProbe ?? ClientProbe.FindRunningClient)(pid == 0 ? null : pid);
            transport = transportFactory?.Invoke() ?? new NativeMemoryTransport(directory, input.String("groupName"), input.String("senderName"), runtimeDirectory);
            TransportValidation.ValidateProvider(transport.Info, target.Version);
            session = await transport.ConnectAsync(target, ct); TransportValidation.ValidateSession(session, target.Version);
            var groups = await transport.GetGroupsAsync(ct);
            groupNames = groups.DistinctBy(x => x.Id).ToDictionary(x => x.Id, x => x.Name);
            group = input.String("groupName").Length > 0 ? groups.Single(x => TextMatching.SameDisplayName(x.Name, input.String("groupName"))) : groups.Count == 1 ? groups[0] : null;
            var contacts = transport is NativeMemoryTransport native ? native.CachedContacts : group is null ? [] : await transport.GetMembersAsync(group.Id, ct);
            senderNames = contacts.DistinctBy(x => x.Id).ToDictionary(x => x.Id, x => x.DisplayName);
            member = input.String("senderName").Length > 0 ? contacts.Single(x => TextMatching.SameDisplayName(x.DisplayName, input.String("senderName"))) : contacts.Count == 1 ? contacts[0] : null;
            // Previously saved display names only resolve optional legacy defaults.
            // Missing/ambiguous names never prevent the new receive-all connection.
            if (input.String("legacyGroupName") is { Length: > 0 } oldGroupName)
            {
                var matches = groups.Where(x => TextMatching.SameDisplayName(x.Name, oldGroupName)).ToArray(); if (matches.Length == 1) group = matches[0];
            }
            if (input.String("legacyMemberName") is { Length: > 0 } oldMemberName)
            {
                var matches = contacts.Where(x => TextMatching.SameDisplayName(x.DisplayName, oldMemberName)).ToArray(); if (matches.Length == 1) member = matches[0];
            }
            if (input.String("legacyGroupId") is { Length: > 0 } defaultGroup)
            {
                if (!ReplySettings.ValidId(defaultGroup)) throw new ArgumentException("旧版默认群 ID 无效");
                group = new(defaultGroup, groupNames.GetValueOrDefault(defaultGroup, ""));
            }
            if (input.String("legacyMemberId") is { Length: > 0 } defaultMember)
            {
                if (!MemberIdFilter.IsNativeId(defaultMember)) throw new ArgumentException("旧版默认成员 ID 须为完整数字");
                member = new(defaultMember, senderNames.GetValueOrDefault(defaultMember, ""));
            }
            connectedAt = DateTimeOffset.UtcNow;
            Log?.Invoke("企业微信已连接 · " + target.Version + " · 接收所有新消息,筛选由工作流条件节点处理"); return Status;
        }
        catch (Exception ex) { error = ex.Message; await DisconnectCoreAsync(); throw; }
        finally { connectionGate.Release(); }
    }
    private async Task<JsonObject> SubscribeAsync(string owner, JsonObject input, CancellationToken ct)
    {
        await connectionGate.WaitAsync(ct);
        try
        {
        EnsureConnected();
        var all = input.String("_deliveryMode") == "all";
        // Older locked plugin assemblies still request their original subscription
        // scope. The new trigger opts into unfiltered delivery explicitly.
        var groupId = all ? "" : input.String("groupId", group?.Id ?? "");
        if (!all && groupId.Length == 0) groupId = group?.Id ?? "";
        if (!all && input.String("memberIds").Length > MemberIdFilter.MaximumTextLength) throw new ArgumentException("成员 ID 列表过长");
        var members = all ? [] : MemberIdFilter.Resolve(input.String("memberIds"), member?.Id ?? "").ToHashSet();
        if (!all && (!ReplySettings.ValidId(groupId) || members.Any(x => !MemberIdFilter.IsNativeId(x)))) throw new ArgumentException("旧版监听需要明确的群与完整成员 ID;请升级为收到消息节点并使用条件分支筛选");
        var age = all ? 300 : input.Integer("maxAgeSeconds", 15); if (age is < 1 or > 300) throw new ArgumentException("消息有效期必须为 1 到 300 秒");
        var kind = all ? "Any" : input.String("messageKind", "MergedForward"); if (kind is not ("Any" or "Text" or "MergedForward")) throw new ArgumentException("消息类型应为 Any、Text 或 MergedForward");
        var id = Guid.NewGuid().ToString("N"); var value = new Subscription(id, owner, input.String("_workflowId", owner), input.Integer("_priority"), groupId, members, kind, age, !all && input.Boolean("dryRun"), all);
        subscriptions[id] = value;
        try { await EnsurePumpAsync(ct); return new() { ["subscription"] = id }; }
        catch { subscriptions.TryRemove(id, out _); throw; }
        }
        finally { connectionGate.Release(); }
    }
    private async Task EnsurePumpAsync(CancellationToken ct)
    {
        await pumpGate.WaitAsync(ct);
        try
        {
            EnsureConnected();
            if (pump is { IsCompleted: false } && listening?.IsCancellationRequested != true) return;
            if (pump is not null) await pump;
            listening?.Dispose(); listening = new(); var token = listening.Token; var provider = transport!;
            pump = Task.Run(() => PumpAsync(provider, DateTimeOffset.UtcNow, token), CancellationToken.None);
        }
        finally { pumpGate.Release(); }
    }
    private async Task PumpAsync(IWeComTransport provider, DateTimeOffset since, CancellationToken ct)
    {
        HashSet<string> seen = [];
        try
        {
            await foreach (var message in provider.WatchMessagesAsync(since, ct))
            {
                if (!Fresh(message, since, 300) || !seen.Add(message.ConversationId + ":" + message.MessageId)) continue;
                if (seen.Count > 100000) throw new InvalidOperationException("接收去重缓存已满,请重新连接");
                var key = AttemptId(message); if (File.Exists(Path.Combine(AttemptDirectory, key + ".json"))) continue;
                var handled = false;
                foreach (var subscription in subscriptions.Values.OrderByDescending(x => x.Priority).ThenBy(x => x.WorkflowId, StringComparer.Ordinal).ThenBy(x => x.Id, StringComparer.Ordinal))
                {
                    if (!subscriptions.ContainsKey(subscription.Id) || !subscription.AllMessages && (handled || message.ConversationId != subscription.GroupId || !subscription.Members.Contains(message.SenderId)
                        || subscription.Kind != "Any" && subscription.Kind != message.Kind.ToString()) || !Fresh(message, since, subscription.MaxAge)) continue;
                    var id = Guid.NewGuid().ToString("N"); var dispatch = new Dispatch(id, subscription.Id, message, subscription.MaxAge, subscription.DryRun); dispatches[id] = dispatch;
                    try
                    {
                        await subscription.Events.Writer.WriteAsync(Event(dispatch), ct);
                        // The trigger acknowledges after the desktop has handled its workflow event.
                        await dispatch.Finished.Task.WaitAsync(TimeSpan.FromSeconds(300), ct);
                        handled |= dispatch.Consumed || File.Exists(Path.Combine(AttemptDirectory, key + ".json"));
                    }
                    catch (ChannelClosedException) { }
                    finally { dispatches.TryRemove(id, out _); }
                }
            }
            if (!ct.IsCancellationRequested) throw new IOException("企业微信消息监听已结束,请重新连接");
        }
        catch (OperationCanceledException) when (ct.IsCancellationRequested) { }
        catch (Exception ex) { error = ex.Message; Log?.Invoke("企业微信监听已停止:" + ex.Message); foreach (var subscription in subscriptions.Values) subscription.Events.Writer.TryComplete(ex); }
    }
    private bool Fresh(WeComMessage message, DateTimeOffset since, int age) => session is not null && ReplySettings.ValidId(message.ConversationId) && MemberIdFilter.IsNativeId(message.SenderId) && ReplySettings.ValidId(message.MessageId)
        && !message.IsHistorical && !message.IsSelf && message.SenderId != session.SelfUserId && message.CreatedAtUtc >= since.AddSeconds(-1)
        && message.ReceivedAtUtc >= since && message.CreatedAtUtc <= DateTimeOffset.UtcNow.AddSeconds(2) && DateTimeOffset.UtcNow - message.CreatedAtUtc <= TimeSpan.FromSeconds(age);
    private JsonObject Event(Dispatch dispatch)
    {
        var message = dispatch.Message;
        return new() { ["dispatchId"] = dispatch.Id, ["messageId"] = message.MessageId, ["conversationId"] = message.ConversationId, ["senderId"] = message.SenderId,
            ["nativeLocalId"] = message.NativeLocalId, ["kind"] = message.Kind.ToString(), ["content"] = message.Content, ["hasContent"] = false,
            ["createdAtUtc"] = message.CreatedAtUtc.ToString("O"), ["receivedAtUtc"] = message.ReceivedAtUtc.ToString("O"), ["accountId"] = session!.AccountId,
            ["groupName"] = groupNames.GetValueOrDefault(message.ConversationId, ""), ["senderName"] = senderNames.GetValueOrDefault(message.SenderId, ""),
            ["ageSeconds"] = Math.Max(0, (DateTimeOffset.UtcNow - message.CreatedAtUtc).TotalSeconds), ["dryRun"] = dispatch.DryRun };
    }
    private async Task<JsonObject> ReplyAsync(JsonObject input, CancellationToken ct)
    {
        EnsureConnected(); var supplied = input["message"] as JsonObject ?? throw new ArgumentException("请连接接收节点的 message 消息引用输出");
        if (!dispatches.TryGetValue(supplied.String("dispatchId"), out var dispatch)) throw new InvalidOperationException("消息不是当前待处理事件,已完成、过期或来自旧连接");
        var content = input["content"].Text(); if (string.IsNullOrWhiteSpace(content) || content.Length > 256 || content.Any(char.IsControl)) throw new ArgumentException("本机回复须为 1 到 256 字符,不能包含控制字符或换行");
        await sendGate.WaitAsync(ct);
        try
        {
            if (!Fresh(dispatch.Message, connectedAt, dispatch.MaxAge)) throw new InvalidOperationException("消息已过有效期,停止发送");
            if (dispatch.Consumed) return new() { ["status"] = "Duplicate", ["sent"] = false };
            var dryRun = dispatch.DryRun || input.Boolean("dryRun"); var quote = input.Boolean("quoteOriginal");
            if (dryRun) { dispatch.Consumed = true; Log?.Invoke("试运行:" + (quote ? "引用" : "普通") + "回复 · " + dispatch.Message.MessageId); return new() { ["status"] = "DryRun", ["sent"] = false, ["content"] = content, ["quoteOriginal"] = quote }; }
            var key = AttemptId(dispatch.Message); Directory.CreateDirectory(AttemptDirectory);
            FileStream reservation;
            try
            {
                reservation = new FileStream(Path.Combine(AttemptDirectory, key + ".json"), FileMode.CreateNew, FileAccess.Write, FileShare.Read, 4096, FileOptions.WriteThrough);
            }
            catch (IOException) when (File.Exists(Path.Combine(AttemptDirectory, key + ".json"))) { dispatch.Consumed = true; return new() { ["status"] = "Duplicate", ["sent"] = false }; }
            dispatch.Consumed = true;
            try
            {
                await using (reservation)
                {
                    await JsonSerializer.SerializeAsync(reservation, new { session!.AccountId, dispatch.Message.ConversationId, dispatch.Message.MessageId, reservedAt = DateTimeOffset.UtcNow, quoteOriginal = quote }, WorkflowJson.Options, ct);
                    await reservation.FlushAsync(ct); reservation.Flush(true);
                }
                var receipt = await transport!.SendTextAsync(new(dispatch.Message.ConversationId, content, dispatch.Message.MessageId, key, quote, dispatch.Message.NativeLocalId, dispatch.Message.SenderId), ct);
                if (receipt.Status != SendStatus.Accepted) throw new IOException("原生发送未确认受理:" + receipt.Status + ",监听已暂停;不会重试");
                Log?.Invoke("企业微信客户端已受理回复(不代表服务器送达) · " + dispatch.Message.MessageId);
                return new() { ["status"] = receipt.Status.ToString(), ["sent"] = true, ["delivered"] = false, ["nativeMessageId"] = receipt.NativeMessageId, ["detail"] = receipt.Detail };
            }
            catch (Exception ex) { error = "发送结果不确定,需重新连接:" + ex.Message; if (listening is not null) await listening.CancelAsync(); foreach (var sub in subscriptions.Values) sub.Events.Writer.TryComplete(new IOException(error)); Log?.Invoke(error); throw; }
        }
        finally { sendGate.Release(); }
    }
    private string AttemptDirectory => Path.Combine(directory, "attempts");
    private string AttemptId(WeComMessage message) => Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(JsonSerializer.Serialize(new[] { session!.AccountId, message.ConversationId, message.MessageId }))));
    private void EnsureConnected() { if (transport is null || session is null) throw new InvalidOperationException("请先在插件中心连接本机企业微信"); if (error.Length > 0) throw new InvalidOperationException(error); }
    private Subscription OwnSubscription(string owner, string id) => subscriptions.TryGetValue(id, out var value) && value.Owner == owner ? value : throw new InvalidOperationException("监听已关闭或不属于当前执行进程");
    public async Task ReleaseAsync(string owner)
    {
        foreach (var value in subscriptions.Values.Where(x => x.Owner == owner))
            if (subscriptions.TryRemove(value.Id, out _)) { value.Events.Writer.TryComplete(); foreach (var dispatch in dispatches.Values.Where(x => x.Subscription == value.Id)) dispatch.Finished.TrySetResult(); }
        await pumpGate.WaitAsync();
        try { if (subscriptions.IsEmpty && listening is not null) { await listening.CancelAsync(); if (pump is not null) await pump; } }
        finally { pumpGate.Release(); }
    }
    public async Task DisconnectAsync() { await connectionGate.WaitAsync(); try { await DisconnectCoreAsync(); } finally { connectionGate.Release(); } }
    private async Task DisconnectCoreAsync()
    {
        await pumpGate.WaitAsync();
        try
        {
        if (listening is not null) await listening.CancelAsync(); foreach (var dispatch in dispatches.Values) dispatch.Finished.TrySetResult();
        foreach (var subscription in subscriptions.Values) subscription.Events.Writer.TryComplete(new IOException("企业微信已断开")); subscriptions.Clear();
        if (pump is not null) await pump; pump = null; listening?.Dispose(); listening = null; dispatches.Clear();
        await sendGate.WaitAsync();
        try { if (transport is not null) await transport.DisposeAsync(); transport = null; session = null; group = null; member = null; groupNames = new Dictionary<string, string>(); senderNames = new Dictionary<string, string>(); }
        finally { sendGate.Release(); }
        }
        finally { pumpGate.Release(); }
    }
    public ValueTask DisposeAsync() => new(DisconnectAsync());
    private sealed record Subscription(string Id, string Owner, string WorkflowId, int Priority, string GroupId, HashSet<string> Members, string Kind, int MaxAge, bool DryRun, bool AllMessages)
    { public Channel<JsonObject> Events { get; } = Channel.CreateBounded<JsonObject>(new BoundedChannelOptions(64) { FullMode = BoundedChannelFullMode.Wait }); }
    private sealed record Dispatch(string Id, string Subscription, WeComMessage Message, int MaxAge, bool DryRun)
    { public TaskCompletionSource Finished { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); public bool Consumed { get; set; } }
}