using System.Collections.Concurrent;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Text;
using System.Text.Json;
using System.Threading.Channels;
using XFEWorkflow.Plugins.WeCom.Native.Core;
namespace XFEWorkflow.Plugins.WeCom.Native.Integrations;
/// Version-pinned native ia32 transport. Native calls run in the client's Frida agent.
public sealed class NativeMemoryTransport(string dataDirectory, string groupName, string senderName, string runtimeDirectory) : IWeComTransport
{
public ProviderInfo Info { get; } = new("本机原生内存接口", ["5.0.11.6029"], ReceiveMethod.MemoryHook, SendMethod.ClientInternalCall, true);
private readonly ConcurrentDictionary> pending = new();
private readonly SemaphoreSlim commands = new(1, 1);
private readonly TaskCompletionSource ready = new(TaskCreationOptions.RunContinuationsAsynchronously);
private readonly Channel messages = Channel.CreateBounded(new BoundedChannelOptions(256)
{ SingleReader = true, SingleWriter = false, FullMode = BoundedChannelFullMode.Wait });
private Process? worker;
private NativeBinding? binding;
private ClientSession? session;
private Task? outputTask;
private string? configPath;
private long sequence;
private int watchSession;
private volatile bool watching;
private bool disposed;
public int CacheBaselineCount { get; private set; }
public async ValueTask ConnectAsync(ClientTarget target, CancellationToken cancellationToken)
{
if (worker is not null) throw new InvalidOperationException("接口已经连接。");
binding = await Task.Run(() => NativeDiscovery.Read(target.ProcessId, groupName, senderName, cancellationToken), cancellationToken).ConfigureAwait(false);
string python = Path.Combine(runtimeDirectory, "python", "python.exe");
string bridge = Path.Combine(runtimeDirectory, "worker.py");
if (!File.Exists(python) || !File.Exists(bridge)) throw new FileNotFoundException("缺少随软件分发的企业微信桥接运行时。");
string directory = Path.Combine(dataDirectory, "native-sessions");
Directory.CreateDirectory(directory);
configPath = Path.Combine(directory, Guid.NewGuid().ToString("N") + ".json");
var config = new
{
pid = target.ProcessId, executablePath = target.ExecutablePath,
managerControl = $"0x{binding.ManagerControl:X8}", managerObject = $"0x{binding.ManagerObject:X8}",
baselineIds = binding.Snapshot.Messages.Select(m => m.ConversationId + ":" + (string.IsNullOrEmpty(m.ClientMessageId) ? "L:" + m.LocalId : m.ClientMessageId)).ToArray(),
developmentDependencyPath = (string?)null
};
await File.WriteAllTextAsync(configPath, JsonSerializer.Serialize(config), cancellationToken).ConfigureAwait(false);
ProcessStartInfo start = new(python)
{
UseShellExecute = false, CreateNoWindow = true, WindowStyle = ProcessWindowStyle.Hidden,
RedirectStandardInput = true, RedirectStandardOutput = true, RedirectStandardError = true,
StandardInputEncoding = new UTF8Encoding(false), StandardOutputEncoding = Encoding.UTF8,
StandardErrorEncoding = Encoding.UTF8, WorkingDirectory = runtimeDirectory
};
start.ArgumentList.Add("-u"); start.ArgumentList.Add(bridge); start.ArgumentList.Add(configPath);
start.Environment["PYTHONUTF8"] = "1";
worker = Process.Start(start) ?? throw new InvalidOperationException("无法启动原生接口。");
outputTask = ReadOutputAsync(worker);
_ = ReadErrorsAsync(worker);
JsonElement connected = await ready.Task.WaitAsync(TimeSpan.FromSeconds(20), cancellationToken).ConfigureAwait(false);
if (!connected.GetProperty("hookVerified").GetBoolean()) throw new InvalidOperationException("原生通知入口未启用。");
string self = connected.GetProperty("selfId").GetString()!;
session = new(self, self, target.Version);
TransportValidation.ValidateSession(session, target.Version);
return session;
}
public ValueTask> GetGroupsAsync(CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested(); EnsureConnected();
return ValueTask.FromResult(binding!.Snapshot.Groups);
}
public ValueTask> GetMembersAsync(string conversationId, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested(); EnsureConnected();
throw new NotSupportedException("原生接口未提供完整群成员名册;请使用缓存联系人查询名字或 ID。");
}
public async IAsyncEnumerable WatchMessagesAsync(DateTimeOffset listenSinceUtc,
[EnumeratorCancellation] CancellationToken cancellationToken)
{
EnsureConnected();
if (Interlocked.Exchange(ref watchSession, 1) != 0) throw new InvalidOperationException("已在监听。");
while (messages.Reader.TryRead(out _)) { }
using CancellationTokenSource cacheCancellation = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
Task? cacheTask = null;
try
{
IReadOnlyList baseline = await Task.Run(() => NativeDiscovery.ReadReceivedMessages(binding!, session!.SelfUserId, cancellationToken), cancellationToken).ConfigureAwait(false);
HashSet cacheSeen = new(baseline.Select(MessageKey), StringComparer.Ordinal);
CacheBaselineCount = cacheSeen.Count;
watching = true;
await CommandAsync(new { operation = "watch", since = listenSinceUtc.ToString("O"), baselineIds = cacheSeen.ToArray() }, cancellationToken).ConfigureAwait(false);
cacheTask = PollMemoryAsync(cacheSeen, listenSinceUtc, cacheCancellation.Token);
await foreach (var message in messages.Reader.ReadAllAsync(cancellationToken).ConfigureAwait(false)) yield return message;
}
finally
{
watching = false;
await cacheCancellation.CancelAsync().ConfigureAwait(false);
if (cacheTask is not null) await cacheTask.ConfigureAwait(false);
try { await CommandAsync(new { operation = "unwatch" }, CancellationToken.None).WaitAsync(TimeSpan.FromSeconds(3)).ConfigureAwait(false); }
catch (Exception) { /* Stream or connection failure is already reported. */ }
Interlocked.Exchange(ref watchSession, 0);
}
}
private async Task PollMemoryAsync(HashSet seen, DateTimeOffset listenSinceUtc, CancellationToken token)
{
try
{
while (true)
{
await Task.Delay(150, token).ConfigureAwait(false);
IReadOnlyList found = await Task.Run(() => NativeDiscovery.ReadReceivedMessages(binding!, session!.SelfUserId, token), token).ConfigureAwait(false);
foreach (WeComMessage message in found)
{
if (!seen.Add(MessageKey(message))) continue;
if (seen.Count >= 100000) throw new InvalidOperationException("内存增量去重缓存已满,请重新连接。");
if (message.CreatedAtUtc < listenSinceUtc.AddSeconds(-1)) continue;
if (!messages.Writer.TryWrite(message)) throw new InvalidOperationException("消息缓冲已满,监听已停止。");
}
}
}
catch (OperationCanceledException) when (token.IsCancellationRequested) { }
catch (Exception error) { Fail(error); }
}
public async ValueTask SendTextAsync(TextReply reply, CancellationToken cancellationToken)
{
EnsureConnected();
if (!ReplySettings.ValidId(reply.ConversationId) || !ReplySettings.ValidId(reply.TriggerMessageId) || !MemberIdFilter.IsNativeId(reply.TriggerSenderId ?? "")) throw new InvalidOperationException("回复必须引用有效的接收事件。");
JsonElement result = await CommandAsync(new { operation = "send", conversationId = reply.ConversationId, content = reply.Content,
triggerMessageId = reply.TriggerMessageId, triggerLocalId = reply.TriggerLocalId, triggerSenderId = reply.TriggerSenderId,
quoteOriginal = reply.QuoteOriginal }, cancellationToken).ConfigureAwait(false);
return Receipt(result);
}
public async Task SendSelfTestAsync(CancellationToken cancellationToken)
{
EnsureConnected();
JsonElement result = await CommandAsync(new { operation = "sendSelfTest" }, cancellationToken).ConfigureAwait(false);
SendReceipt receipt = Receipt(result);
if (receipt.Status != SendStatus.Accepted) throw new InvalidOperationException("文件传输助手测试未受理;不会自动重发。");
for (int attempt = 0; attempt < 8; attempt++)
{
await Task.Delay(250, cancellationToken).ConfigureAwait(false);
string? serverId = await Task.Run(() => NativeDiscovery.FindSelfTestServerId(binding!.Snapshot.ProcessId,
Convert.ToUInt32(binding.Snapshot.ImageBase[2..], 16), receipt.NativeMessageId!, session!.SelfUserId), cancellationToken).ConfigureAwait(false);
if (serverId is not null) return $"原生发送成功:文件传输助手收到「1」;服务器消息 ID {serverId}。";
}
return $"客户端已受理测试消息 {receipt.NativeMessageId};尚未读到服务器回执,不自动重发。";
}
public Task> GetCachedContactsAsync(CancellationToken token)
{
EnsureConnected();
return Task.Run(() => NativeDiscovery.ReadCachedContacts(binding!.Snapshot.ProcessId,
Convert.ToUInt32(binding.Snapshot.ImageBase[2..], 16), token), token);
}
private static SendReceipt Receipt(JsonElement result)
{
string? status = result.GetProperty("status").GetString();
string? localId = result.GetProperty("localId").GetString();
return new(status == "Accepted" ? SendStatus.Accepted : status == "Rejected" ? SendStatus.Rejected : SendStatus.Unknown,
localId, "原生发送任务 " + result.GetProperty("taskId").GetString());
}
private static string MessageKey(WeComMessage message) => message.ConversationId + ":" + message.MessageId;
public IReadOnlyList CachedContacts => binding?.Snapshot.Contacts ?? [];
private async Task CommandAsync(object command, CancellationToken cancellationToken)
{
if (worker is null || worker.HasExited) throw new InvalidOperationException("原生接口已退出。");
await commands.WaitAsync(cancellationToken).ConfigureAwait(false);
long id = Interlocked.Increment(ref sequence);
TaskCompletionSource completion = new(TaskCreationOptions.RunContinuationsAsynchronously);
pending[id] = completion;
try
{
cancellationToken.ThrowIfCancellationRequested();
JsonElement content = JsonSerializer.SerializeToElement(command);
var request = content.EnumerateObject().ToDictionary(p => p.Name, p => p.Value);
request.Add("id", JsonSerializer.SerializeToElement(id));
await worker.StandardInput.WriteLineAsync(JsonSerializer.Serialize(request).AsMemory(), cancellationToken).ConfigureAwait(false);
await worker.StandardInput.FlushAsync(cancellationToken).ConfigureAwait(false);
return await completion.Task.WaitAsync(TimeSpan.FromSeconds(10), cancellationToken).ConfigureAwait(false);
}
finally { pending.TryRemove(id, out _); commands.Release(); }
}
private async Task ReadOutputAsync(Process process)
{
try
{
while (await process.StandardOutput.ReadLineAsync().ConfigureAwait(false) is string line)
{
using JsonDocument document = JsonDocument.Parse(line);
JsonElement value = document.RootElement;
if (value.TryGetProperty("id", out var id))
{
if (!pending.TryGetValue(id.GetInt64(), out var response)) continue;
if (value.TryGetProperty("error", out var error)) response.TrySetException(new InvalidOperationException(error.GetString()));
else response.TrySetResult(value.GetProperty("result").Clone());
continue;
}
string? name = value.GetProperty("event").GetString();
if (name == "ready") { ready.TrySetResult(value.Clone()); continue; }
if (name == "fatal") throw new InvalidOperationException(value.GetProperty("detail").GetString());
if (name != "message" || !watching) continue;
uint rawType = value.GetProperty("rawType").GetUInt32();
string senderId = value.GetProperty("senderId").GetString()!;
WeComMessage message = new(value.GetProperty("messageId").GetString()!, value.GetProperty("conversationId").GetString()!, senderId,
rawType == 4 ? MessageKind.MergedForward : rawType == 2 ? MessageKind.Text : MessageKind.Unknown, "",
DateTimeOffset.FromUnixTimeSeconds(value.GetProperty("createdSeconds").GetInt64()),
DateTimeOffset.Parse(value.GetProperty("receivedAtUtc").GetString()!, System.Globalization.CultureInfo.InvariantCulture),
false, senderId == session?.SelfUserId, value.GetProperty("localId").GetString());
if (!messages.Writer.TryWrite(message)) throw new InvalidOperationException("消息缓冲已满,监听已停止。");
}
if (!disposed) throw new IOException("原生接口消息流已结束。");
}
catch (Exception error) { Fail(error); }
}
private async Task ReadErrorsAsync(Process process)
{
try { while (await process.StandardError.ReadLineAsync().ConfigureAwait(false) is string line) Debug.WriteLine(line); }
catch (Exception) { /* A disposed worker can close stderr during shutdown. */ }
}
private void Fail(Exception error)
{
ready.TrySetException(error); messages.Writer.TryComplete(error);
foreach (var request in pending.Values) request.TrySetException(error);
}
private void EnsureConnected()
{
if (disposed || session is null || worker is null || worker.HasExited) throw new InvalidOperationException("请先连接企业微信。");
}
public async ValueTask DisposeAsync()
{
if (disposed) return;
watching = false;
if (worker is not null)
{
try { if (!worker.HasExited) await CommandAsync(new { operation = "stop" }, CancellationToken.None).WaitAsync(TimeSpan.FromSeconds(3)).ConfigureAwait(false); }
catch (Exception) { /* Do not retry native commands on disconnect. */ }
disposed = true;
worker.StandardInput.Close();
try { await worker.WaitForExitAsync().WaitAsync(TimeSpan.FromSeconds(3)).ConfigureAwait(false); }
catch (TimeoutException) { worker.Kill(true); }
if (outputTask is not null) await outputTask.ConfigureAwait(false);
worker.Dispose();
}
disposed = true;
messages.Writer.TryComplete();
if (configPath is not null && File.Exists(configPath)) File.Delete(configPath);
}
}