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

XFEWorkflow

【WinUI】XFE基于windows的工作流

公开
关注 0 Fork 0 Star 0
UTF-8
using System.Diagnostics;
using System.Reflection.PortableExecutable;
using XFEWorkflow.Plugins.WeCom.Native.Core;

namespace XFEWorkflow.Plugins.WeCom.Native.Integrations;

public sealed record ClientInstallation(string Path, string Version, string Architecture);
public sealed record DatabaseProbe(int ProfileNumber, string Database, bool? PlainSqliteHeader,
    bool WalPresent, string? Error);

public static class ClientProbe
{
    public static ClientInstallation? InspectInstallation()
    {
        string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86),
            "WXWork", "WXWork.exe");
        if (!File.Exists(path)) return null;
        string version = FileVersionInfo.GetVersionInfo(path).FileVersion ?? "未知";
        using FileStream stream = File.OpenRead(path);
        using PEReader pe = new(stream);
        return new(path, version, pe.PEHeaders.CoffHeader.Machine.ToString());
    }

    public static ClientTarget FindRunningClient(int? processId = null)
    {
        Process[] processes = Process.GetProcessesByName("WXWork");
        try
        {
            int[] ids = processes.Select(p => p.Id).ToArray();
            int selectedId;
            if (processId is int requested)
            {
                if (!ids.Contains(requested)) throw new InvalidOperationException("指定 PID 不是正在运行的企业微信进程。");
                selectedId = requested;
            }
            else
            {
                // Account switching leaves a --broker root and background account
                // processes. Parentage alone cannot identify the active chat client.
                int[] windowed = processes.Where(p => p.MainWindowHandle != 0).Select(p => p.Id).ToArray();
                selectedId = ProcessTree.SelectActiveClient(ids, windowed);
            }
            Process root = processes.Single(p => p.Id == selectedId);
            string path = root.MainModule?.FileName
                ?? throw new InvalidOperationException("无法读取企业微信程序路径。");
            string version = FileVersionInfo.GetVersionInfo(path).FileVersion
                ?? throw new InvalidOperationException("无法读取企业微信版本。");
            return new(root.Id, path, version);
        }
        finally { foreach (Process process in processes) process.Dispose(); }
    }

    // Header-only inspection. No keys, account IDs, contact rows or chat rows are read.
    public static IReadOnlyList<DatabaseProbe> InspectDefaultCache()
    {
        string root = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "WXWork");
        List<DatabaseProbe> result = [];
        if (!Directory.Exists(root)) return result;
        int profile = 0;
        Span<byte> header = stackalloc byte[16];
        foreach (string directory in Directory.EnumerateDirectories(root))
        {
            if (!Path.GetFileName(directory).All(char.IsDigit)) continue;
            profile++;
            foreach (string name in new[] { "message.db", "session.db", "user.db" })
            {
                string file = Path.Combine(directory, "Data", name);
                if (!File.Exists(file)) continue;
                bool wal = File.Exists(file + "-wal");
                try
                {
                    using FileStream stream = new(file, FileMode.Open, FileAccess.Read,
                        FileShare.ReadWrite | FileShare.Delete);
                    stream.ReadExactly(header);
                    bool plain = header.SequenceEqual("SQLite format 3\0"u8);
                    result.Add(new(profile, name, plain, wal, null));
                }
                catch (Exception error) when (error is IOException or UnauthorizedAccessException)
                {
                    result.Add(new(profile, name, null, wal, error.GetType().Name));
                }
            }
        }
        return result;
    }
}