mirror of
https://wget.la/https://github.com/Wxw-Gu/WechatExplorer
synced 2026-11-30 16:02:58 +08:00
Merge pull request #77 from stevenosean904/feat/wecom-message-support
feat: 支持企业微信插件群聊与单聊消息读取
This commit is contained in:
20 files changed
+1101
-61
No files matched your search
+15
@@ -39,3 +39,18 @@ debug-originals
|
||||
|
||||
# 官方扩展模板构建产物(由 scripts/build-extension-templates.cjs 生成)
|
||||
/build/extension-templates/
|
||||
|
||||
# 诊断产物与数据库快照(含密钥派生脚本、消息正文、zstd blob)——严禁入库
|
||||
/dump*.js
|
||||
/dump*.cjs
|
||||
*.db
|
||||
*.db-wal
|
||||
*.db-shm
|
||||
*.sqlite
|
||||
*.sqlite3
|
||||
*.zst
|
||||
/snapshot/
|
||||
/blobs/
|
||||
/database-keys/
|
||||
|
||||
.dev-verify/
|
||||
@@ -54,6 +54,7 @@ Agent Hub 让微信机器人调用本机 TraceMemo;Reader Skill / Local HTTP A
|
||||
- [扩展 API 参考](./extensions/api-reference.md)
|
||||
- [界面开发规范:按钮与主题色](./development/ui-guidelines.md)
|
||||
- [微信系统消息解析与格式兼容](./development/wechat-system-message-parsing.md)
|
||||
- [企业微信插件会话只读验收](./development/wecom-enterprise-acceptance.md)
|
||||
- [Query Agent POC(开发测试入口)](./development/query-agent-poc.md)
|
||||
- [本地启动排障](./development/local-startup-troubleshooting.md)
|
||||
- [macOS 数据访问说明](./platform/macos.md)
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
# 企业微信插件会话:只读验收报告
|
||||
|
||||
本文记录 Mac 微信 4.x 企业微信插件会话(群 `*@qy_g`、单聊 `*@qy_u`)在 TraceMemo 中的
|
||||
真实数据验收结果,用于回答 review 中「需要真实环境证据」的那一项。
|
||||
|
||||
结论先行:**会话列表、群名、群成员、消息、发送者、图片六条链路在真实库上都已跑通**,
|
||||
且全程只读;报告中所有会话 id、群名、成员名、消息正文均以 sha256 前缀代替,不含原文。
|
||||
|
||||
## 验收环境
|
||||
|
||||
| 项 | 值 |
|
||||
| --- | --- |
|
||||
| 客户端 | Mac 微信 4.x(企业微信插件会话已存在) |
|
||||
| 账号规模 | 5521 个会话,其中企业会话 7 个 = 5 个 `@qy_g` 群 + 2 个 `@qy_u` 单聊 |
|
||||
| 消息库 | `db_storage`(会话/消息)+ `bizchat/bizchat.db`(企业群名与成员) |
|
||||
| 运行方式 | 以只读模式(`TRACEMEMO_READ_ONLY=1`)直接调用主进程的 `Wcdb4Client` / `chat-service` |
|
||||
| 数据隔离 | 数据库目录用 APFS clone(写时复制)复制后再读;媒体目录只做 `existsSync`/`readFileSync` |
|
||||
|
||||
### 只读是怎么保证的
|
||||
|
||||
1. 数据库侧:`src/main/wcdb4-client.ts` 中不存在 `writeFileSync` / `mkdirSync` / `renameSync` /
|
||||
`unlinkSync` 等写调用,所有 SQL 都是 `SELECT`;验收时读的是 clone 出来的副本。
|
||||
2. 媒体侧:只读取 `msg/attach/<session md5>/<YYYY-MM>/Img|Thumb` 下的 `.dat` 文件,
|
||||
不写回、不删除、不改名。
|
||||
3. 密钥:数据库密钥与图片 AES 密钥从本机已有的安全存储中取出后仅用于本次进程内解密,
|
||||
不落盘、不进入任何报告或提交。
|
||||
|
||||
## 六条链路的实测结果
|
||||
|
||||
### 1. 会话列表与群名(冷启动顺序无关)
|
||||
|
||||
`getSessions()` 是同步路径,会在异步 hydration 之前返回;旧实现只读 `displayNameCache`,
|
||||
冷启动第一次取群名时缓存为空,就会把 `ww...@qy_g` 原样当群名显示。现在的
|
||||
`resolveSessionNickname()` 统一走「企业群名 → 缓存 → 会话昵称 → username」,
|
||||
并且 `getEnterpriseGroupName()` 在缓存未命中时同步查一次 `bizchat.chat_group.chat_name`。
|
||||
|
||||
| 检查 | 结果 |
|
||||
| --- | --- |
|
||||
| 冷启动同步列表里 5 个企业群是否用 raw id 当群名 | 0/5(全部已解析) |
|
||||
| 2 个企业单聊 | 保持自身昵称(单聊本无群名,符合预期) |
|
||||
| 异步 `getSessionsAsync({hydrateDisplayNames:true})` 之后 | 5 个群名与冷启动完全一致 |
|
||||
| `getGroupNamesAsync()`(退群提示/自动化取群名) | 5/5 企业群在列,名字与会话列表一致 |
|
||||
|
||||
### 2. 联系人列表(群列表与群日报的群名来源)
|
||||
|
||||
群日报的 `groupName` 取 `contact.m_nsNickName`,并过滤内部标识符
|
||||
(`src/renderer/src/utils/group-report-facts.ts:114`)。用真实的 `listContactsAsync()` 复核:
|
||||
|
||||
| 检查 | 结果 |
|
||||
| --- | --- |
|
||||
| 7 个企业会话是否都出现在联系人列表 | 7/7 |
|
||||
| `type` 判定 | 5 个 `group`(`@qy_g`)、2 个 `user`(`@qy_u`) |
|
||||
| 群名能否通过 `isInternalIdentifier` 过滤(即日报不显示「未命名会话」) | 7/7 |
|
||||
|
||||
### 3. 群成员(失败与空列表已区分)
|
||||
|
||||
`getEnterpriseGroupMembers(Async)` 现在返回 `Wcdb4GroupMember[] | null`:
|
||||
读不到(缺 native 入口、非 `@qy_g`、查询抛错)返回 `null`,只有 `user_list` 真正为空才返回 `[]`。
|
||||
|
||||
| 检查 | 结果 |
|
||||
| --- | --- |
|
||||
| 5 个企业群的群快照 | 5/5 可解析 |
|
||||
| 群名与同步通道一致 | 5/5 |
|
||||
| 成员数 | 每群 2 人 |
|
||||
| 成员显示名(`user_info.user_name`) | 2/2 每群都解析到非 id 名称 |
|
||||
|
||||
### 4. 消息数量与发送者
|
||||
|
||||
90 天窗口,每会话最多 500 条:
|
||||
|
||||
| 会话 | 消息数 | 发送者已解析 | 不同发送者 |
|
||||
| --- | --- | --- | --- |
|
||||
| 企业群 A | 350 | 350/350 | 2 |
|
||||
| 企业群 B | 500 | 500/500 | 1 |
|
||||
| 企业群 C | 379 | 379/379 | 1 |
|
||||
| 企业群 D | 369 | 369/369 | 2 |
|
||||
| 企业群 E | 61 | 61/61 | 1 |
|
||||
| 企业单聊 1 | 10 | 10/10 | 2 |
|
||||
| 企业单聊 2 | 3 | 3/3 | 1 |
|
||||
|
||||
所有会话的发送者解析率均为 100%:企业消息的 `source` 是 zstd 压缩的
|
||||
`enterprise_info` XML,`parseEnterpriseSource()` 从中取 `sender` / `nickname` / `bizchat_id`。
|
||||
|
||||
### 5. 图片
|
||||
|
||||
企业图片的 `message_content` 里**没有 md5**(只有 `aeskey` / `encryver` / CDN 地址等属性),
|
||||
所以不能用普通消息的 md5 路线定位文件。实际链路是:`packed_info_data` → `parseImageDatNameFromRow()`
|
||||
解出 32 位 datName → 在 `msg/attach/<session md5>/<YYYY-MM>/Img` 命中 `.dat` → 用图片 AES 密钥解密。
|
||||
|
||||
| 会话 | 图片数 | 抽样 | 定位到文件 | 解密成功 | 格式 |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| 企业群 A | 188 | 5 | 5/5 | 5/5 | JPEG / PNG |
|
||||
| 企业群 B | 316 | 5 | 5/5 | 5/5 | JPEG |
|
||||
| 企业群 C | 184 | 5 | 5/5 | 5/5 | JPEG |
|
||||
| 企业群 D | 184 | 5 | 5/5 | 5/5 | JPEG / PNG |
|
||||
| 企业群 E | 0 | — | — | — | 该群 90 天内只有文字 |
|
||||
| 企业单聊 1 | 1 | 1 | 1/1 | 1/1 | PNG |
|
||||
| 企业单聊 2 | 0 | — | — | — | — |
|
||||
|
||||
解密结果按文件头判定(`FF D8 FF` / `89 50 4E 47`),不是「解出非空 buffer」就算通过。
|
||||
|
||||
### 6. 企业群的成员批量读取与退群监控
|
||||
|
||||
native 的 `wcdb_get_group_members_batch` **只认 `@chatroom`**。实测:
|
||||
|
||||
- 只请求 3 个普通群 → 正常返回,成员数 500 / 412 / 488;
|
||||
- 只请求 5 个企业群 → 整批失败(nativeCode `-2001`);
|
||||
- 混合请求 3 个普通群 + 5 个企业群 → **整批失败**,普通群的结果也一起丢掉。
|
||||
|
||||
因此在 `chat-service.getGroupMemberIdsBatchAsync()` 里按通道分流:普通群仍走一次 native 批量,
|
||||
企业群逐个走 bizchat 成员通道,最后按调用方请求顺序合并。修复后同一批 8 个会话返回 8 条结果
|
||||
(普通群 500 / 412 / 488,企业群各 2),不再互相拖累。
|
||||
|
||||
退群监控侧(`src/main/services/group-exit-monitor-service.ts`):
|
||||
|
||||
- `normalizeRoomIds()`(:914)与 `normalizeSnapshots()`(:951)都要求 `@chatroom`,
|
||||
所以 `@qy_g` 永远进不了 `monitoredRoomIds`,也不会被写进持久化快照;
|
||||
- 只有「微信内退群提示」开着时,`@qy_g` 才会经 `getGroupNamesAsync()` 进入检测范围;
|
||||
- 此时成员读取失败(`null`)会得到 `membersValid === false`,`applyCurrentMemberships()`
|
||||
直接 `continue`,不会把「读不到」当成「全员退群」。
|
||||
|
||||
## 复现方式(不含任何密钥)
|
||||
|
||||
1. 以只读模式启动主进程,指向 clone 出来的 `db_storage`;
|
||||
2. 调 `getSessions()` 看冷启动群名,再调 `getSessionsAsync({hydrateDisplayNames:true})` 比对;
|
||||
3. 调 `listContactsAsync()` / `getGroupNamesAsync()` / `getGroupSnapshotAsync()` 复核群名与成员;
|
||||
4. 调 `getMessages()` 统计消息数、发送者解析率与图片数;
|
||||
5. 对图片样本调 `parseImageDatNameFromRow()` + `ImageDecryptService.findImageFileAsync()` + `decryptImage()`;
|
||||
6. 调 `getGroupMemberIdsBatchAsync()` 混合普通群与企业群,确认不再整批失败。
|
||||
|
||||
## 隐私说明
|
||||
|
||||
- 本文只出现 sha256 前缀、计数与布尔判定,不含 wxid、群名、成员名、消息正文、文件路径或密钥;
|
||||
- 验收脚本与原始 JSON 均为本机临时产物,不在仓库内,也不会进入提交历史。
|
||||
+2
-1
@@ -78,6 +78,7 @@ import type { SystemOcrCapability, SystemOcrRequest, SystemOcrResult } from '../
|
||||
import { KeyServiceMac } from './key-service-mac'
|
||||
import { getMacArchSnapshot } from './macos-arch'
|
||||
import { shouldProbeIntelEnvironment } from '../shared/macos-arch'
|
||||
import { isGroupSession } from '../shared/wechat-identities'
|
||||
import { KeyService as KeyServiceWin } from './key-service-win'
|
||||
import * as chat from './services/chat-service'
|
||||
import {
|
||||
@@ -1000,7 +1001,7 @@ function configureRecallProtection(
|
||||
wcdb4Client.getSessions().map((session) => ({
|
||||
md5: wcdb4Client.md5(session.username),
|
||||
m_nsUsrName: session.username,
|
||||
type: session.username.endsWith('@chatroom') ? 'group' : 'user',
|
||||
type: isGroupSession(session.username) ? 'group' : 'user',
|
||||
activityKey: [
|
||||
session.raw['last_timestamp'],
|
||||
session.raw['sort_timestamp'],
|
||||
|
||||
@@ -108,6 +108,8 @@ function looksLikeOpaqueSenderId(value: string | undefined): boolean {
|
||||
return (
|
||||
normalized.startsWith('wxid_') ||
|
||||
normalized.endsWith('@chatroom') ||
|
||||
normalized.endsWith('@qy_u') ||
|
||||
normalized.endsWith('@qy_g') ||
|
||||
/^\d{6,}$/.test(normalized)
|
||||
)
|
||||
}
|
||||
|
||||
@@ -348,7 +348,12 @@ function parseImageMessage(content: string): ParsedContent {
|
||||
|
||||
const encrypVer = parseInt(encrypVerStr, 10)
|
||||
|
||||
if (!md5 && !datName) {
|
||||
// 企业微信插件的图片消息:message_content 解压后是 `<img aeskey="..." encryver="0"
|
||||
// cdnthumburl="..." cdnmidimgurl="..." cdnbigimgurl="..." length="..." hdlength="..."/>`,
|
||||
// **没有 md5 属性**(datName 也藏在 packed_info_data 的 protobuf 里,由
|
||||
// parseImageDatNameFromRow 从 row 提取)。普通微信图片的 <img> 带 md5,这里按 aeskey
|
||||
// 存在与否补判图片身份,避免这类消息被误判成「不支持的消息」。
|
||||
if (!md5 && !datName && !aeskey) {
|
||||
return { type: 'unknown', raw: content }
|
||||
}
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@ import type { Contact, Message } from '../../shared/types'
|
||||
import type { GroupDailyReport, GroupReportMetadata } from '../../shared/group-report'
|
||||
import { exportGroupReport } from '../group-report-service'
|
||||
import { getGroupSnapshot, listMessages, resolveMd5 } from './chat-service'
|
||||
import { isGroupSession } from '../../shared/wechat-identities'
|
||||
import { AIProviderService } from './ai-provider-service'
|
||||
import type {
|
||||
ScheduledReportMemberNameMode,
|
||||
@@ -105,7 +106,7 @@ export async function generateAgentGroupReport(
|
||||
if (!query) return reportFailure('缺少群聊名称', 'data', 'CHAT_NOT_FOUND')
|
||||
const contact = resolveMd5(query)
|
||||
if (!contact) return reportFailure(`没有找到群聊“${query}”`, 'data', 'CHAT_NOT_FOUND')
|
||||
if (contact.type !== 'group' && !contact.m_nsUsrName.endsWith('@chatroom')) {
|
||||
if (contact.type !== 'group' && !isGroupSession(contact.m_nsUsrName)) {
|
||||
return reportFailure(`“${query}”不是群聊`, 'data', 'CHAT_NOT_FOUND')
|
||||
}
|
||||
|
||||
|
||||
@@ -27,6 +27,7 @@ import {
|
||||
filterContactSearchIndex,
|
||||
type ContactSearchIndex
|
||||
} from '../../shared/contact-search'
|
||||
import { isGroupSession } from '../../shared/wechat-identities'
|
||||
|
||||
/**
|
||||
* 谁在读消息。
|
||||
@@ -348,7 +349,7 @@ export function listContacts(filter?: string): FormattedContact[] {
|
||||
|
||||
for (const user of userList) {
|
||||
const md5 = dbRef.md5(user.m_nsUsrName)
|
||||
const isGroup = user.m_nsUsrName.endsWith('@chatroom')
|
||||
const isGroup = isGroupSession(user.m_nsUsrName)
|
||||
existingMd5s.add(md5)
|
||||
contacts.push({
|
||||
m_nsUsrName: user.m_nsUsrName,
|
||||
@@ -437,7 +438,7 @@ export async function getGroupNamesAsync(): Promise<Record<string, string>> {
|
||||
const sessions = await dbRef.getWcdb4Client().getSessionsAsync({ hydrateDisplayNames: false })
|
||||
const names: Record<string, string> = {}
|
||||
for (const session of sessions) {
|
||||
if (!session.username.endsWith('@chatroom')) continue
|
||||
if (!isGroupSession(session.username)) continue
|
||||
const name = String(session.nickname || '').trim()
|
||||
if (name) names[session.username] = name
|
||||
}
|
||||
@@ -1051,10 +1052,13 @@ export function getGroupSnapshot(userMd5: string): GroupSnapshot | null {
|
||||
if (!dbRef) return null
|
||||
const wcdb4Client = dbRef.getWcdb4Client()
|
||||
const roomId = wcdb4Client.getUsernameByMd5(userMd5)
|
||||
if (!roomId || !roomId.endsWith('@chatroom')) return null
|
||||
if (!roomId || !isGroupSession(roomId)) return null
|
||||
|
||||
const rawMembers = wcdb4Client.getGroupMembers(roomId)
|
||||
const members = (Array.isArray(rawMembers) ? rawMembers : [])
|
||||
const rawMembers = roomId.endsWith('@qy_g')
|
||||
? wcdb4Client.getEnterpriseGroupMembers(roomId)
|
||||
: wcdb4Client.getGroupMembers(roomId)
|
||||
if (!Array.isArray(rawMembers)) return null
|
||||
const members = rawMembers
|
||||
.filter((member) => member?.m_nsUsrName)
|
||||
.map((member) => ({
|
||||
wxid: member.m_nsUsrName,
|
||||
@@ -1072,10 +1076,13 @@ export async function getGroupSnapshotAsync(userMd5: string): Promise<GroupSnaps
|
||||
if (!dbRef) return null
|
||||
const wcdb4Client = dbRef.getWcdb4Client()
|
||||
const roomId = wcdb4Client.getUsernameByMd5(userMd5)
|
||||
if (!roomId || !roomId.endsWith('@chatroom')) return null
|
||||
if (!roomId || !isGroupSession(roomId)) return null
|
||||
|
||||
const rawMembers = await wcdb4Client.getGroupMembersAsync(roomId)
|
||||
const members = (Array.isArray(rawMembers) ? rawMembers : [])
|
||||
const rawMembers = roomId.endsWith('@qy_g')
|
||||
? await wcdb4Client.getEnterpriseGroupMembersAsync(roomId)
|
||||
: await wcdb4Client.getGroupMembersAsync(roomId)
|
||||
if (!Array.isArray(rawMembers)) return null
|
||||
const members = rawMembers
|
||||
.filter((member) => member?.m_nsUsrName)
|
||||
.map((member) => ({
|
||||
wxid: member.m_nsUsrName,
|
||||
@@ -1085,10 +1092,15 @@ export async function getGroupSnapshotAsync(userMd5: string): Promise<GroupSnaps
|
||||
remark: member.remark || '',
|
||||
avatar: member.m_nsHeadImgUrl || ''
|
||||
}))
|
||||
// 群名与调用顺序无关:企业群名优先走 bizchat 同步解析(会回填缓存),
|
||||
// 再退回会话昵称;否则冷启动时第一次取快照会把 raw username 当群名。
|
||||
const session = wcdb4Client.getSessions().find((item) => item.username === roomId)
|
||||
const enterpriseName = roomId.endsWith('@qy_g')
|
||||
? wcdb4Client.getEnterpriseGroupName(roomId)
|
||||
: ''
|
||||
return {
|
||||
roomId,
|
||||
groupName: session?.nickname || undefined,
|
||||
groupName: enterpriseName || session?.nickname || undefined,
|
||||
memberCount: members.length,
|
||||
members
|
||||
}
|
||||
@@ -1105,15 +1117,24 @@ export async function getGroupSnapshotAsync(userMd5: string): Promise<GroupSnaps
|
||||
export function resolveGroupRoomId(userMd5: string): string | null {
|
||||
if (!dbRef) return null
|
||||
const roomId = dbRef.getWcdb4Client().getUsernameByMd5(userMd5)
|
||||
return roomId && roomId.endsWith('@chatroom') ? roomId : null
|
||||
return roomId && isGroupSession(roomId) ? roomId : null
|
||||
}
|
||||
|
||||
/** 退群检测专用轻量读取,不执行成员名称或头像 hydration。 */
|
||||
export async function getGroupMemberIdsAsync(
|
||||
roomId: string
|
||||
): Promise<GroupMembershipSnapshot | null> {
|
||||
if (!dbRef || !roomId.endsWith('@chatroom')) return null
|
||||
const memberIds = await dbRef.getWcdb4Client().getGroupMemberIdsAsync(roomId)
|
||||
if (!dbRef) return null
|
||||
const wcdb4Client = dbRef.getWcdb4Client()
|
||||
// 企业群:成员清单走 bizchat.chat_group.user_list(native 只认 @chatroom)。
|
||||
if (roomId.endsWith('@qy_g')) {
|
||||
const members = await wcdb4Client.getEnterpriseGroupMembersAsync(roomId)
|
||||
if (!members) return null
|
||||
const memberIds = members.map((member) => member.m_nsUsrName).filter(Boolean)
|
||||
return { roomId, memberIds }
|
||||
}
|
||||
if (!roomId.endsWith('@chatroom')) return null
|
||||
const memberIds = await wcdb4Client.getGroupMemberIdsAsync(roomId)
|
||||
return memberIds ? { roomId, memberIds } : null
|
||||
}
|
||||
|
||||
@@ -1134,7 +1155,7 @@ export async function getGroupMemberNamesAsync(
|
||||
if (requested.length === 0) return []
|
||||
const wcdb4Client = dbRef.getWcdb4Client()
|
||||
const roomId = wcdb4Client.getUsernameByMd5(userMd5)
|
||||
if (!roomId || !roomId.endsWith('@chatroom')) return []
|
||||
if (!roomId || !isGroupSession(roomId)) return []
|
||||
const members = await wcdb4Client.getGroupMemberNamesAsync(roomId, requested)
|
||||
return members.map((member) => ({
|
||||
wxid: member.m_nsUsrName,
|
||||
@@ -1154,14 +1175,49 @@ export async function getGroupMemberIdsBatchAsync(
|
||||
roomIds: string[]
|
||||
): Promise<GroupMembershipBatchSnapshot[] | null> {
|
||||
if (!dbRef) return null
|
||||
const results = await dbRef.getWcdb4Client().getGroupMemberIdsBatchAsync(roomIds)
|
||||
return results
|
||||
? results.map((result) => ({
|
||||
const requested = Array.from(
|
||||
new Set(
|
||||
(Array.isArray(roomIds) ? roomIds : [])
|
||||
.map((roomId) => String(roomId || '').trim())
|
||||
.filter(Boolean)
|
||||
)
|
||||
)
|
||||
if (requested.length === 0) return []
|
||||
/*
|
||||
* native `wcdb_get_group_members_batch` 只认 `@chatroom`:只要请求里混进一个
|
||||
* `@qy_g`,整批查询就会失败(nativeCode -2001),连普通群的结果一起丢掉 ——
|
||||
* 而「微信内退群提示」开着时检测范围是全部群聊,企业群正好混在里面。
|
||||
*
|
||||
* 所以这里按通道拆分:普通群仍走一次批量 native 调用,企业群逐个走 bizchat
|
||||
* 成员通道,最后按调用方请求的顺序合并,保持接口契约不变。
|
||||
*/
|
||||
const nativeRoomIds = requested.filter((roomId) => !roomId.endsWith('@qy_g'))
|
||||
const enterpriseRoomIds = requested.filter((roomId) => roomId.endsWith('@qy_g'))
|
||||
const byRoomId = new Map<string, GroupMembershipBatchSnapshot>()
|
||||
|
||||
if (nativeRoomIds.length > 0) {
|
||||
const results = await dbRef.getWcdb4Client().getGroupMemberIdsBatchAsync(nativeRoomIds)
|
||||
if (!results) return null
|
||||
for (const result of results) {
|
||||
byRoomId.set(result.roomId, {
|
||||
roomId: result.roomId,
|
||||
status: result.status,
|
||||
memberIds: result.memberWxids
|
||||
}))
|
||||
: null
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
for (const roomId of enterpriseRoomIds) {
|
||||
const snapshot = await getGroupMemberIdsAsync(roomId)
|
||||
byRoomId.set(roomId, {
|
||||
roomId,
|
||||
// 读取失败(null)不能伪装成「群已空」:用 not_found 让调用方保留上一份有效基线。
|
||||
status: snapshot ? 'ok' : 'not_found',
|
||||
memberIds: snapshot?.memberIds || []
|
||||
})
|
||||
}
|
||||
|
||||
return requested.map((roomId) => byRoomId.get(roomId)!)
|
||||
}
|
||||
|
||||
export function searchMessages(keyword: string): string | null {
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
type AutomationRuleType
|
||||
} from '../../shared/automation'
|
||||
import { resolveContact } from './contact-resolution-service'
|
||||
import { isGroupSession } from '../../shared/wechat-identities'
|
||||
import { validateAutomationDraftShape } from '../../shared/agent-api/automation-validation'
|
||||
import type {
|
||||
AgentAutomationExecution,
|
||||
@@ -459,7 +460,7 @@ export class LocalAgentApiService {
|
||||
if (contact.type !== 'group') {
|
||||
throw new LocalAgentApiError(422, 'NOT_GROUP_CONVERSATION', 'conversationId 不是群会话')
|
||||
}
|
||||
if (!contact.m_nsUsrName.endsWith('@chatroom')) {
|
||||
if (!isGroupSession(contact.m_nsUsrName)) {
|
||||
throw new LocalAgentApiError(422, 'NOT_GROUP_CONVERSATION', 'conversationId 不是有效的群会话 ID')
|
||||
}
|
||||
if (!this.deps.getGroupMemberStats) {
|
||||
|
||||
+357
-32
@@ -635,6 +635,8 @@ export class Wcdb4Client {
|
||||
private koffi: KoffiModule | null = null
|
||||
private handle: number | null = null
|
||||
private displayNameCache = new Map<string, string>()
|
||||
/** 企业群名查过但 bizchat 里没有的会话,避免同步路径反复打库。 */
|
||||
private enterpriseGroupNameMisses = new Set<string>()
|
||||
private contactIdentityCache = new Map<string, Wcdb4ContactIdentity>()
|
||||
private avatarCache = new Map<string, string>()
|
||||
private sessionStatusCache = new Map<string, { isFolded: boolean; isMuted: boolean }>()
|
||||
@@ -1018,6 +1020,7 @@ export class Wcdb4Client {
|
||||
this.sessionStatusesInFlight = null
|
||||
this.sessionStatusesUpdatedAt = 0
|
||||
this.displayNameCache.clear()
|
||||
this.enterpriseGroupNameMisses?.clear()
|
||||
this.contactIdentityCache?.clear()
|
||||
this.avatarCache.clear()
|
||||
this.sessionStatusCache.clear()
|
||||
@@ -1214,7 +1217,7 @@ export class Wcdb4Client {
|
||||
|
||||
this.cachedSessions = sessions.map((session) => ({
|
||||
...session,
|
||||
nickname: this.displayNameCache.get(session.username) || session.nickname || session.username
|
||||
nickname: this.resolveSessionNickname(session)
|
||||
}))
|
||||
this.sessionDisplayNamesHydrated = false
|
||||
|
||||
@@ -2204,7 +2207,9 @@ export class Wcdb4Client {
|
||||
)
|
||||
stores = this.parseMessageStores(rows)
|
||||
} catch (error) {
|
||||
if (!username.startsWith('gh_')) throw error
|
||||
// 公众号与企业微信插件会话在 native 统计侧没有对应分片元数据,失败属预期;
|
||||
// 统一回退到基于文件枚举 + sqlite_master 探测的 fallback 路径。
|
||||
if (!this.isBizSession(username)) throw error
|
||||
}
|
||||
}
|
||||
return stores.length > 0 ? stores : this.listFallbackMessageStores(username)
|
||||
@@ -2224,7 +2229,9 @@ export class Wcdb4Client {
|
||||
if (strict && !Array.isArray(rows)) throw new Error('消息分片目录返回格式无效')
|
||||
stores = this.parseMessageStores(rows)
|
||||
} catch (error) {
|
||||
if (!username.startsWith('gh_')) throw error
|
||||
// 公众号与企业微信插件会话在 native 统计侧没有对应分片元数据,失败属预期;
|
||||
// 统一回退到基于文件枚举 + sqlite_master 探测的 fallback 路径。
|
||||
if (!this.isBizSession(username)) throw error
|
||||
}
|
||||
}
|
||||
return stores.length > 0 ? stores : this.listFallbackMessageStoresAsync(username, strict)
|
||||
@@ -2239,11 +2246,39 @@ export class Wcdb4Client {
|
||||
.filter((row) => row.tableName && row.dbPath)
|
||||
}
|
||||
|
||||
/**
|
||||
* 是否为「业务消息」会话 —— 消息落在 biz_message_*.db 分片,而非 message_*.db。
|
||||
*
|
||||
* - 公众号 `gh_*`:既有逻辑已路由到 biz_message_*.db。
|
||||
* - 企业微信插件群 `*@qy_g`:企业群消息,正文库为 biz_message_*.db。
|
||||
* - 企业微信插件单聊/成员 `*@qy_u`:企业单聊消息,同样落在 biz_message_*.db。
|
||||
*
|
||||
* 其余(普通好友、`@chatroom` 群)仍走 message_*.db,保持原有行为。
|
||||
*/
|
||||
private isBizSession(username: string): boolean {
|
||||
const value = String(username || '').trim()
|
||||
return value.startsWith('gh_') || value.endsWith('@qy_g') || value.endsWith('@qy_u')
|
||||
}
|
||||
|
||||
/**
|
||||
* 是否为企业微信插件会话(群 `*@qy_g` 或单聊/成员 `*@qy_u`)。
|
||||
*
|
||||
* 与 `isBizSession` 的区别:`isBizSession` 还包含公众号 `gh_*`(其消息也落在
|
||||
* biz_message_*.db,但发送者走本库 Name2Id 联表即可)。企业会话的
|
||||
* `real_sender_id` 指向 bizchat.db 的统一 id 空间(user_info / chat_group 交错),
|
||||
* 与本库 Name2Id 的 rowid 不一致,因此不能做 sender 联表,发送者必须从
|
||||
* source XML 的 enterprise_info 解析。
|
||||
*/
|
||||
private isEnterpriseSession(username: string): boolean {
|
||||
const value = String(username || '').trim()
|
||||
return value.endsWith('@qy_g') || value.endsWith('@qy_u')
|
||||
}
|
||||
|
||||
private getMessageDatabasePaths(username: string, strict = false): string[] {
|
||||
// Native shard discovery can return no stores on Windows even when SQL reads work.
|
||||
// Enumerate only canonical databases; sync-conflict copies are not message shards.
|
||||
const messageRoot = path.join(this.dbStoragePath, 'message')
|
||||
const pattern = username.startsWith('gh_')
|
||||
const pattern = this.isBizSession(username)
|
||||
? /^biz_message(?:_\d+)?\.db$/i
|
||||
: /^message(?:_\d+)?\.db$/i
|
||||
try {
|
||||
@@ -2275,7 +2310,12 @@ export class Wcdb4Client {
|
||||
)
|
||||
)
|
||||
if (Array.isArray(rows) && rows.some((row) => row.name === tableName)) {
|
||||
const senderTableName = rows.find((row) => /^Name2Id/i.test(String(row.name)))?.name
|
||||
// 企业会话的 real_sender_id 指向 bizchat.db 的统一 id 空间,本库 Name2Id
|
||||
// 的 rowid 与之不对应,联表会产生错位/空 sender;发送者改从 source XML
|
||||
// 解析(见 normalizeMessage),故此处不记录 senderTableName。
|
||||
const senderTableName = this.isEnterpriseSession(username)
|
||||
? undefined
|
||||
: rows.find((row) => /^Name2Id/i.test(String(row.name)))?.name
|
||||
stores.push({
|
||||
tableName,
|
||||
dbPath,
|
||||
@@ -2310,7 +2350,10 @@ export class Wcdb4Client {
|
||||
)
|
||||
if (strict && !Array.isArray(rows)) throw new Error('消息分片目录返回格式无效')
|
||||
if (Array.isArray(rows) && rows.some((row) => row.name === tableName)) {
|
||||
const senderTableName = rows.find((row) => /^Name2Id/i.test(String(row.name)))?.name
|
||||
// 企业会话发送者从 source XML 解析,本库 Name2Id 联表无效,见同步路径说明。
|
||||
const senderTableName = this.isEnterpriseSession(username)
|
||||
? undefined
|
||||
: rows.find((row) => /^Name2Id/i.test(String(row.name)))?.name
|
||||
stores.push({
|
||||
tableName,
|
||||
dbPath,
|
||||
@@ -2455,6 +2498,8 @@ export class Wcdb4Client {
|
||||
limit?: number
|
||||
): Wcdb4Message[] {
|
||||
const merged = new Map<string, Wcdb4Message>()
|
||||
// local_id + create_time 索引:同一行可能先以「缺 server_id 的中间态」到达,
|
||||
// 再以回填后的快照到达,靠这条索引对齐到当前主键(而不是靠 server_id)。
|
||||
const localKeyToPrimary = new Map<string, string>()
|
||||
|
||||
const hasUsableServerId = (value?: string): boolean => {
|
||||
@@ -2462,6 +2507,17 @@ export class Wcdb4Client {
|
||||
return Boolean(normalized && normalized !== '0')
|
||||
}
|
||||
|
||||
// server_id 可能跨会话/跨时间复用(企业插件库尤其明显);只有在
|
||||
// (create_time, local_id, server_id) 完全一致时才视为同一条消息的快照,
|
||||
// 避免不同消息被错误合并。server_key 仅作为已匹配快照的次级索引。
|
||||
const snapshotKey = (message: Wcdb4Message): string => {
|
||||
const serverId = String(message.serverId || '').trim()
|
||||
return [
|
||||
String(message.msgCreateTime || 0),
|
||||
String(message.mesLocalID || ''),
|
||||
hasUsableServerId(serverId) ? serverId : ''
|
||||
].join(':')
|
||||
}
|
||||
// 同一条消息的两个快照合并时,不能用缺发送者或未回填的旧快照覆盖已确定的本人身份。
|
||||
const mergePair = (older: Wcdb4Message, newer: Wcdb4Message): Wcdb4Message => ({
|
||||
...older,
|
||||
@@ -2486,38 +2542,32 @@ export class Wcdb4Client {
|
||||
|
||||
for (const message of [...recovered, ...current]) {
|
||||
const recoveredRow = Boolean(message.raw?.['_wxe_recovered'])
|
||||
const serverId = String(message.serverId || '').trim()
|
||||
const localIdentity = message.mesLocalID
|
||||
? `local:${message.mesLocalID}:${message.msgCreateTime || 0}`
|
||||
: ''
|
||||
const identity = hasUsableServerId(serverId)
|
||||
? `server:${serverId}`
|
||||
// 只有快照身份完全一致才合并;local_id 仅用于同库两路读取
|
||||
// (cursor / table scan)的同一行对齐。缺 local_id 时退回原文本身份,
|
||||
// 不再仅凭可能复用的 server_id 把不同消息折叠。
|
||||
const key = recoveredRow
|
||||
? `recovered:${snapshotKey(message)}`
|
||||
: snapshotKey(message)
|
||||
const fallbackKey = recoveredRow
|
||||
? `recovered:${localIdentity || `${message.msgCreateTime}:${message.msgContent}`}`
|
||||
: localIdentity || `${message.msgCreateTime}:${message.msgContent}`
|
||||
const key = recoveredRow ? `recovered:${identity}` : identity
|
||||
const localLookupKey = !recoveredRow && localIdentity ? localIdentity : ''
|
||||
const existingKey =
|
||||
merged.has(key)
|
||||
? key
|
||||
: localLookupKey && localKeyToPrimary.has(localLookupKey)
|
||||
? localKeyToPrimary.get(localLookupKey)!
|
||||
: undefined
|
||||
const indexedLocalKey = localLookupKey ? localKeyToPrimary.get(localLookupKey) : undefined
|
||||
const existingKey = [key, fallbackKey, indexedLocalKey].find(
|
||||
(candidate) => candidate && merged.has(candidate)
|
||||
)
|
||||
const existing = existingKey ? merged.get(existingKey) : undefined
|
||||
if (existing && existingKey) {
|
||||
const combined = mergePair(existing, message)
|
||||
const targetKey = hasUsableServerId(combined.serverId)
|
||||
? recoveredRow
|
||||
? `recovered:server:${String(combined.serverId).trim()}`
|
||||
: `server:${String(combined.serverId).trim()}`
|
||||
: existingKey
|
||||
if (targetKey !== existingKey) {
|
||||
merged.delete(existingKey)
|
||||
}
|
||||
merged.set(targetKey, combined)
|
||||
if (localLookupKey) localKeyToPrimary.set(localLookupKey, targetKey)
|
||||
if (existingKey !== key) merged.delete(existingKey)
|
||||
merged.set(key, combined)
|
||||
} else {
|
||||
merged.set(key, message)
|
||||
if (localLookupKey) localKeyToPrimary.set(localLookupKey, key)
|
||||
}
|
||||
if (localLookupKey) localKeyToPrimary.set(localLookupKey, key)
|
||||
}
|
||||
const messages = Array.from(merged.values()).sort(
|
||||
(left, right) =>
|
||||
@@ -3376,9 +3426,30 @@ export class Wcdb4Client {
|
||||
chatroomId: string,
|
||||
usernames: string[]
|
||||
): Promise<Wcdb4GroupMember[]> {
|
||||
if (!chatroomId || !chatroomId.endsWith('@chatroom')) return []
|
||||
const requested = this.uniq(usernames.filter(Boolean))
|
||||
if (requested.length === 0) return []
|
||||
if (!chatroomId) return []
|
||||
|
||||
// 企业群:成员显示名来自 bizchat.user_info,走企业成员通道(复用 Name2Id 之外的映射)。
|
||||
if (chatroomId.endsWith('@qy_g')) {
|
||||
// 读取失败(null)时退回占位名,而不是把「读不到」伪装成「群已空」。
|
||||
const members = (await this.getEnterpriseGroupMembersAsync(chatroomId)) || []
|
||||
const byId = new Map(members.map((member) => [member.m_nsUsrName, member]))
|
||||
return requested.map((username) => {
|
||||
const member = byId.get(username)
|
||||
return (
|
||||
member || {
|
||||
m_nsUsrName: username,
|
||||
nickname: username,
|
||||
groupNickname: '',
|
||||
wechatNickname: '',
|
||||
remark: '',
|
||||
m_nsHeadImgUrl: ''
|
||||
}
|
||||
)
|
||||
})
|
||||
}
|
||||
if (!chatroomId.endsWith('@chatroom')) return []
|
||||
|
||||
try {
|
||||
const groupNicknames = await this.getGroupNicknamesAsync(chatroomId)
|
||||
@@ -3409,6 +3480,15 @@ export class Wcdb4Client {
|
||||
return Boolean(this.wcdbGetGroupMembersBatch)
|
||||
}
|
||||
|
||||
/**
|
||||
* native 批量群成员读取(`wcdb_get_group_members_batch`)。
|
||||
*
|
||||
* **只接受 `@chatroom`**:实测只要请求里混进一个 `@qy_g`,整批查询就会失败
|
||||
* (nativeCode -2001),普通群的结果也会一起丢掉。企业群成员必须走
|
||||
* bizchat 通道(`getEnterpriseGroupMembersAsync`),分流由
|
||||
* `chat-service.getGroupMemberIdsBatchAsync` 负责,这里不做静默过滤 ——
|
||||
* 免得调用方以为企业群已经被读到了。
|
||||
*/
|
||||
async getGroupMemberIdsBatchAsync(
|
||||
roomIds: string[]
|
||||
): Promise<Wcdb4GroupMemberIdsBatchItem[] | null> {
|
||||
@@ -4617,6 +4697,7 @@ export class Wcdb4Client {
|
||||
])
|
||||
const content = this.decodeMessageContent(contentRaw, compressRaw)
|
||||
const contentSender = this.extractSenderFromMessageContent(content)
|
||||
const enterpriseSource = this.parseEnterpriseSource(row)
|
||||
const sender =
|
||||
this.pickString(row, [
|
||||
'sender_username',
|
||||
@@ -4625,7 +4706,9 @@ export class Wcdb4Client {
|
||||
'fromUsername',
|
||||
'from_username',
|
||||
'WCDB_CT_sender_username'
|
||||
]) || contentSender
|
||||
]) ||
|
||||
enterpriseSource.senderId ||
|
||||
contentSender
|
||||
const createTime = this.pickNumber(row, [
|
||||
'create_time',
|
||||
'createTime',
|
||||
@@ -4711,7 +4794,9 @@ export class Wcdb4Client {
|
||||
msgCreateTime: String(createTime),
|
||||
msgContent: content,
|
||||
sender,
|
||||
senderNickname: sender ? this.displayNameCache.get(sender) : undefined,
|
||||
senderNickname: sender
|
||||
? enterpriseSource.senderNickname || this.displayNameCache.get(sender)
|
||||
: undefined,
|
||||
senderAvatar: sender ? this.avatarCache.get(sender) : undefined,
|
||||
raw: row
|
||||
}
|
||||
@@ -4730,6 +4815,47 @@ export class Wcdb4Client {
|
||||
return this.getMyUsernameCandidates().includes(candidate) ? candidate : ''
|
||||
}
|
||||
|
||||
/**
|
||||
* 企业微信插件的 source 列为 zstd 压缩的 XML(魔数 0xfd2fb528),
|
||||
* 其中 enterprise_info 携带发送者 user_id(格式 ww_*_<cropid>_<userid>@qy_u)、
|
||||
* user_nickname(发送者昵称)与 bizchat_id(群归属 = 完整 @qy_g)。
|
||||
* real_sender_id 指向 bizchat.db 的统一 id 空间,本库 Name2Id 联表对企业消息无效,
|
||||
* 故发送者/昵称必须从这里解析。
|
||||
*/
|
||||
private parseEnterpriseSource(row: Record<string, unknown>): {
|
||||
senderId: string
|
||||
senderNickname: string
|
||||
bizChatId: string
|
||||
} {
|
||||
const sourceRaw = this.pickValue(row, [
|
||||
'source',
|
||||
'origin_source',
|
||||
'msg_source',
|
||||
'msgSource',
|
||||
'WCDB_CT_source'
|
||||
])
|
||||
const xml = this.decodeMaybeCompressed(sourceRaw)
|
||||
if (!xml || !xml.trim().startsWith('<')) {
|
||||
return { senderId: '', senderNickname: '', bizChatId: '' }
|
||||
}
|
||||
const userId = this.extractXmlTag(xml, 'user_id')
|
||||
const userNickname = this.extractXmlTag(xml, 'user_nickname')
|
||||
const bizChatId = this.extractXmlTag(xml, 'bizchat_id')
|
||||
// 仅接受企业发送者标识(@qy_u),避免把普通 XML 源误判为企业消息。
|
||||
const senderId = userId.endsWith('@qy_u') ? userId : ''
|
||||
if (senderId && userNickname) this.displayNameCache.set(senderId, userNickname)
|
||||
return { senderId, senderNickname: userNickname, bizChatId }
|
||||
}
|
||||
|
||||
private extractXmlTag(xml: string, tag: string): string {
|
||||
const match = xml.match(new RegExp(`<${tag}(?:\\s[^>]*)?>([\\s\\S]*?)</${tag}>`))
|
||||
if (!match) return ''
|
||||
return match[1]
|
||||
.replace(/^<!\[CDATA\[/, '')
|
||||
.replace(/\]\]>$/, '')
|
||||
.trim()
|
||||
}
|
||||
|
||||
private shouldHydrateSessionDisplayName(session: Wcdb4Session): boolean {
|
||||
const username = String(session.username || '').trim()
|
||||
const nickname = String(session.nickname || '').trim()
|
||||
@@ -4741,6 +4867,93 @@ export class Wcdb4Client {
|
||||
return false
|
||||
}
|
||||
|
||||
/**
|
||||
* 从 bizchat/bizchat.db 的 chat_group 表读取企业群真实群名(chat_name),
|
||||
* 注入 displayNameCache。native wcdbGetDisplayNames 不认识 @qy_g 会话,
|
||||
* 企业群名缺失时会被显示为 raw username,故单独走 SQL 通道补齐。
|
||||
* chat_group.group_id 即完整会话键(`ww{cropid}_{id}@qy_g`)。
|
||||
*/
|
||||
/**
|
||||
* 同步解析单个企业群名(冷启动 / 同步快照路径专用)。
|
||||
*
|
||||
* 群名 hydration 是异步批量的,但 `getGroupSnapshot()` 这类同步读路径不能 await;
|
||||
* 若只读 displayNameCache,第一次调用(缓存为空)就会把 `ww...@qy_g` 当成群名。
|
||||
* 这里先查缓存,未命中时按 bizchat 通道同步取一次并回填缓存,使同步与异步两条
|
||||
* 路径的结果与调用顺序无关。
|
||||
*/
|
||||
/**
|
||||
* 会话显示名的唯一解析入口:企业群名 → displayNameCache → 原始昵称 → username。
|
||||
*
|
||||
* 同步 `getSessions()` 与异步 hydration 都走这里,保证「冷启动第一次读会话列表」
|
||||
* 与「hydration 之后再读」得到同一个群名,而不是 raw `ww...@qy_g`。
|
||||
*/
|
||||
private resolveSessionNickname(session: Wcdb4Session): string {
|
||||
const username = String(session.username || '')
|
||||
const enterpriseName = this.getEnterpriseGroupName(username)
|
||||
return (
|
||||
enterpriseName || this.displayNameCache.get(username) || session.nickname || username
|
||||
)
|
||||
}
|
||||
|
||||
getEnterpriseGroupName(roomId: string): string {
|
||||
if (!roomId || !roomId.endsWith('@qy_g')) return ''
|
||||
const cached = this.displayNameCache.get(roomId)
|
||||
if (cached) return cached
|
||||
if (!this.wcdbExecQuery || this.enterpriseGroupNameMisses.has(roomId)) return ''
|
||||
const bizchatPath = path.join(this.dbStoragePath, 'bizchat', 'bizchat.db')
|
||||
try {
|
||||
const rows = this.callJson<Record<string, unknown>[]>((handle, outJson) =>
|
||||
this.wcdbExecQuery!(
|
||||
handle,
|
||||
'message',
|
||||
bizchatPath,
|
||||
`SELECT chat_name FROM chat_group WHERE group_id = '${roomId.replace(/'/g, "''")}'`,
|
||||
outJson
|
||||
)
|
||||
)
|
||||
const chatName = Array.isArray(rows) && rows.length > 0
|
||||
? this.pickString(rows[0], ['chat_name', 'chatName'])
|
||||
: ''
|
||||
if (!chatName) {
|
||||
this.enterpriseGroupNameMisses.add(roomId)
|
||||
return ''
|
||||
}
|
||||
this.displayNameCache.set(roomId, chatName)
|
||||
return chatName
|
||||
} catch {
|
||||
// 群名可选;失败时调用方回退到会话昵称或 raw username。
|
||||
return ''
|
||||
}
|
||||
}
|
||||
|
||||
private async hydrateEnterpriseGroupNamesAsync(usernames: string[]): Promise<void> {
|
||||
if (!this.wcdbExecQuery) return
|
||||
const groupIds = this.uniq(usernames).filter((username) => username.endsWith('@qy_g'))
|
||||
if (groupIds.length === 0) return
|
||||
|
||||
const bizchatPath = path.join(this.dbStoragePath, 'bizchat', 'bizchat.db')
|
||||
const inList = groupIds.map((id) => `'${id.replace(/'/g, "''")}'`).join(',')
|
||||
try {
|
||||
const rows = await this.callJsonAsync<Record<string, unknown>[]>(
|
||||
this.wcdbExecQuery as unknown as KoffiAsyncFunction,
|
||||
'message',
|
||||
bizchatPath,
|
||||
`SELECT group_id, chat_name FROM chat_group WHERE group_id IN (${inList})`
|
||||
)
|
||||
if (!Array.isArray(rows)) return
|
||||
for (const row of rows) {
|
||||
const groupId = this.pickString(row, ['group_id', 'groupId', 'brand_user_name'])
|
||||
const chatName = this.pickString(row, ['chat_name', 'chatName'])
|
||||
if (groupId && chatName) {
|
||||
this.displayNameCache.set(groupId, chatName)
|
||||
this.enterpriseGroupNameMisses.delete(groupId)
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// 企业群名可选;读取失败时回退到 raw username,不影响消息读取。
|
||||
}
|
||||
}
|
||||
|
||||
private async hydrateDisplayNamesAsync(usernames: string[]): Promise<void> {
|
||||
if (!this.wcdbGetDisplayNames) return
|
||||
const missing = this.uniq(usernames).filter((username) => !this.displayNameCache.has(username))
|
||||
@@ -4769,6 +4982,9 @@ export class Wcdb4Client {
|
||||
const generation = this.sessionCacheGeneration
|
||||
const sessions = this.cachedSessions
|
||||
const request = (async (): Promise<void> => {
|
||||
await this.hydrateEnterpriseGroupNamesAsync(
|
||||
sessions.map((session) => session.username)
|
||||
)
|
||||
await this.hydrateDisplayNamesAsync(
|
||||
sessions
|
||||
.filter((session) => this.shouldHydrateSessionDisplayName(session))
|
||||
@@ -4777,8 +4993,7 @@ export class Wcdb4Client {
|
||||
if (generation !== this.sessionCacheGeneration || this.cachedSessions !== sessions) return
|
||||
this.cachedSessions = sessions.map((session) => ({
|
||||
...session,
|
||||
nickname:
|
||||
this.displayNameCache.get(session.username) || session.nickname || session.username
|
||||
nickname: this.resolveSessionNickname(session)
|
||||
}))
|
||||
this.sessionDisplayNamesHydrated = true
|
||||
})()
|
||||
@@ -4790,6 +5005,116 @@ export class Wcdb4Client {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 企业微信群成员(bizchat 通道,同步)。
|
||||
*
|
||||
* native wcdbGetGroupMembers 只认 `@chatroom`,对 `@qy_g` 返回空。企业群成员清单
|
||||
* 存在 bizchat.db 的 `chat_group.user_list`(分号分隔的 username 文本),成员显示名
|
||||
* 存在 `user_info.user_name`。这里走既有 `wcdbExecQuery('message', bizchatPath, sql)`
|
||||
* 按路径键式开库读取,与 P1 的群名注入同源。
|
||||
*/
|
||||
getEnterpriseGroupMembers(roomId: string): Wcdb4GroupMember[] | null {
|
||||
return this.readEnterpriseGroupMembers(roomId)
|
||||
}
|
||||
|
||||
async getEnterpriseGroupMembersAsync(roomId: string): Promise<Wcdb4GroupMember[] | null> {
|
||||
return this.readEnterpriseGroupMembersAsync(roomId)
|
||||
}
|
||||
|
||||
private readEnterpriseGroupMembers(roomId: string): Wcdb4GroupMember[] | null {
|
||||
if (!this.wcdbExecQuery || !roomId || !roomId.endsWith('@qy_g')) return null
|
||||
const bizchatPath = path.join(this.dbStoragePath, 'bizchat', 'bizchat.db')
|
||||
try {
|
||||
const groupRows = this.callJson<Record<string, unknown>[]>((handle, outJson) =>
|
||||
this.wcdbExecQuery!(
|
||||
handle,
|
||||
'message',
|
||||
bizchatPath,
|
||||
`SELECT user_list FROM chat_group WHERE group_id = '${roomId.replace(/'/g, "''")}'`,
|
||||
outJson
|
||||
)
|
||||
)
|
||||
const memberIds = this.enterpriseMemberIdsFromRows(groupRows)
|
||||
if (memberIds.length === 0) return []
|
||||
const inList = memberIds.map((id) => `'${id.replace(/'/g, "''")}'`).join(',')
|
||||
const nameRows = this.callJson<Record<string, unknown>[]>((handle, outJson) =>
|
||||
this.wcdbExecQuery!(
|
||||
handle,
|
||||
'message',
|
||||
bizchatPath,
|
||||
`SELECT user_id, user_name FROM user_info WHERE user_id IN (${inList})`,
|
||||
outJson
|
||||
)
|
||||
)
|
||||
return this.enterpriseMembersFromRows(memberIds, nameRows)
|
||||
} catch (error) {
|
||||
console.warn(`[WCDB4] enterprise group members failed groupId=${roomId}:`, error)
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
private async readEnterpriseGroupMembersAsync(roomId: string): Promise<Wcdb4GroupMember[] | null> {
|
||||
if (!this.wcdbExecQuery || !roomId || !roomId.endsWith('@qy_g')) return null
|
||||
const bizchatPath = path.join(this.dbStoragePath, 'bizchat', 'bizchat.db')
|
||||
try {
|
||||
const groupRows = await this.callJsonAsync<Record<string, unknown>[]>(
|
||||
this.wcdbExecQuery as unknown as KoffiAsyncFunction,
|
||||
'message',
|
||||
bizchatPath,
|
||||
`SELECT user_list FROM chat_group WHERE group_id = '${roomId.replace(/'/g, "''")}'`
|
||||
)
|
||||
const memberIds = this.enterpriseMemberIdsFromRows(groupRows)
|
||||
if (memberIds.length === 0) return []
|
||||
const inList = memberIds.map((id) => `'${id.replace(/'/g, "''")}'`).join(',')
|
||||
const nameRows = await this.callJsonAsync<Record<string, unknown>[]>(
|
||||
this.wcdbExecQuery as unknown as KoffiAsyncFunction,
|
||||
'message',
|
||||
bizchatPath,
|
||||
`SELECT user_id, user_name FROM user_info WHERE user_id IN (${inList})`
|
||||
)
|
||||
return this.enterpriseMembersFromRows(memberIds, nameRows)
|
||||
} catch (error) {
|
||||
console.warn(`[WCDB4] enterprise group members failed groupId=${roomId}:`, error)
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
private enterpriseMemberIdsFromRows(rows: Record<string, unknown>[] | null | undefined): string[] {
|
||||
if (!Array.isArray(rows) || rows.length === 0) return []
|
||||
const userList = this.pickString(rows[0], ['user_list', 'userList'])
|
||||
return this.uniq(
|
||||
userList
|
||||
.split(';')
|
||||
.map((id) => id.trim())
|
||||
.filter(Boolean)
|
||||
)
|
||||
}
|
||||
|
||||
private enterpriseMembersFromRows(
|
||||
memberIds: string[],
|
||||
nameRows: Record<string, unknown>[] | null | undefined
|
||||
): Wcdb4GroupMember[] {
|
||||
const names = new Map<string, string>()
|
||||
if (Array.isArray(nameRows)) {
|
||||
for (const row of nameRows) {
|
||||
const userId = this.pickString(row, ['user_id', 'userId', 'brand_user_name'])
|
||||
const name = this.pickString(row, ['user_name', 'userName'])
|
||||
if (userId && name) names.set(userId, name)
|
||||
}
|
||||
}
|
||||
return memberIds.map((memberId) => {
|
||||
const name = names.get(memberId) || ''
|
||||
return {
|
||||
m_nsUsrName: memberId,
|
||||
nickname: name || memberId,
|
||||
groupNickname: '',
|
||||
wechatNickname: name,
|
||||
remark: '',
|
||||
m_nsHeadImgUrl: ''
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
private hydrateAvatarUrls(usernames: string[]): void {
|
||||
const missing = this.uniq(usernames).filter((username) => !this.avatarCache.has(username))
|
||||
if (missing.length === 0) return
|
||||
|
||||
+18
-7
@@ -1,5 +1,6 @@
|
||||
import { Wcdb4Client, Wcdb4MessageQueryOptions } from './wcdb4-client'
|
||||
import { Wcdb4Client, Wcdb4GroupMember, Wcdb4MessageQueryOptions } from './wcdb4-client'
|
||||
import { wcdbDebugLog } from './wcdb-debug'
|
||||
import { isGroupSession } from '../shared/wechat-identities'
|
||||
|
||||
export interface UserContact {
|
||||
m_nsUsrName: string
|
||||
@@ -140,10 +141,20 @@ export class WechatDb {
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 统一读取群成员:@chatroom 走 native getGroupMembers,@qy_g 走 bizchat 企业群成员。
|
||||
*/
|
||||
private readGroupMembers(roomId: string): Wcdb4GroupMember[] {
|
||||
// 这里是「尽力而为的名称映射」路径:企业群读取失败(null)退化为空集合,
|
||||
// 由调用方继续用 username 兜底;需要区分失败与空群的地方走 chat-service。
|
||||
if (roomId.endsWith('@qy_g')) return this.wcdb4Client.getEnterpriseGroupMembers(roomId) || []
|
||||
return this.wcdb4Client.getGroupMembers(roomId)
|
||||
}
|
||||
|
||||
public getAllGroupContacts(): Record<string, string> {
|
||||
const groupContacts: Record<string, string> = {}
|
||||
for (const session of this.wcdb4Client.getSessions()) {
|
||||
if (session.username.endsWith('@chatroom')) {
|
||||
if (isGroupSession(session.username)) {
|
||||
groupContacts[this.md5(session.username)] = session.nickname || session.username
|
||||
}
|
||||
}
|
||||
@@ -153,8 +164,8 @@ export class WechatDb {
|
||||
public getAllGroupMembers(): Record<string, string> {
|
||||
const members: Record<string, string> = {}
|
||||
for (const session of this.wcdb4Client.getSessions()) {
|
||||
if (!session.username.endsWith('@chatroom')) continue
|
||||
for (const member of this.wcdb4Client.getGroupMembers(session.username)) {
|
||||
if (!isGroupSession(session.username)) continue
|
||||
for (const member of this.readGroupMembers(session.username)) {
|
||||
if (member.m_nsUsrName) {
|
||||
members[member.m_nsUsrName] = member.nickname || member.m_nsUsrName
|
||||
}
|
||||
@@ -166,10 +177,10 @@ export class WechatDb {
|
||||
public getGroupMembersForChat(userMd5: string): Record<string, string> {
|
||||
this.ensureChatTableMapping()
|
||||
const username = this.chatMd5ToUsername.get(userMd5)
|
||||
if (!username || !username.endsWith('@chatroom')) return {}
|
||||
if (!username || !isGroupSession(username)) return {}
|
||||
|
||||
const members: Record<string, string> = {}
|
||||
for (const member of this.wcdb4Client.getGroupMembers(username)) {
|
||||
for (const member of this.readGroupMembers(username)) {
|
||||
if (member.m_nsUsrName) {
|
||||
members[member.m_nsUsrName] = member.nickname || member.m_nsUsrName
|
||||
}
|
||||
@@ -180,7 +191,7 @@ export class WechatDb {
|
||||
public getGroupMember(wxid: string, chatroomId?: string): GroupMemberInfo | null {
|
||||
if (!chatroomId) return null
|
||||
return (
|
||||
this.wcdb4Client.getGroupMembers(chatroomId).find((member) => member.m_nsUsrName === wxid) ||
|
||||
this.readGroupMembers(chatroomId).find((member) => member.m_nsUsrName === wxid) ||
|
||||
null
|
||||
)
|
||||
}
|
||||
|
||||
@@ -17,3 +17,22 @@ export const WECHAT_FILE_HELPER_USERNAME = 'filehelper'
|
||||
export function isFileHelperUsername(value: string | undefined | null): boolean {
|
||||
return String(value || '').trim().toLowerCase() === WECHAT_FILE_HELPER_USERNAME
|
||||
}
|
||||
|
||||
/**
|
||||
* 群会话判定(统一入口)。
|
||||
*
|
||||
* 普通微信群会话以 `@chatroom` 结尾;企业微信插件群会话以 `@qy_g` 结尾。
|
||||
* 二者在「读取 / 展示」链路上语义一致(有成员列表、能出群日报、能被群档案检索),
|
||||
* 故收敛到同一个判定,避免 P2 阶段在 40+ 处 `@chatroom` 判断里机械复制条件。
|
||||
* 企业单聊 `@qy_u` 仍是单聊(user),不在此列。
|
||||
*/
|
||||
export function isGroupSession(value: string | undefined | null): boolean {
|
||||
const username = String(value || '').trim()
|
||||
return username.endsWith('@chatroom') || username.endsWith('@qy_g')
|
||||
}
|
||||
|
||||
/** 企业微信插件会话(群 `*@qy_g` 或单聊/成员 `*@qy_u`)。 */
|
||||
export function isEnterpriseSession(value: string | undefined | null): boolean {
|
||||
const username = String(value || '').trim()
|
||||
return username.endsWith('@qy_g') || username.endsWith('@qy_u')
|
||||
}
|
||||
@@ -655,6 +655,37 @@ describe('GroupExitMonitorService', () => {
|
||||
expect(mocks.chat.getGroupSnapshotAsync).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('detects enterprise groups in notice scope without persisting an unreadable baseline', async () => {
|
||||
installGroupDb()
|
||||
// 「微信内退群提示」开着时,检测范围是全部群聊 —— 企业群也会进来。
|
||||
mocks.chat.getGroupNamesAsync.mockResolvedValue({
|
||||
'room@chatroom': '测试群',
|
||||
'wwfixture_group@qy_g': '企业群'
|
||||
})
|
||||
mocks.chat.getGroupMemberIdsBatchAsync.mockImplementation(async (roomIds: string[]) =>
|
||||
roomIds.map((roomId) => ({
|
||||
roomId,
|
||||
status: roomId.endsWith('@qy_g') ? 'not_found' : 'ok',
|
||||
memberIds: roomId.endsWith('@qy_g') ? [] : [member.wxid]
|
||||
}))
|
||||
)
|
||||
const service = new GroupExitMonitorService()
|
||||
service.setNoticeEnabled(true)
|
||||
await service.start(true)
|
||||
|
||||
// 企业群确实进了检测范围(否则这条用例证明不了任何事)。
|
||||
expect(mocks.chat.getGroupMemberIdsBatchAsync).toHaveBeenCalledWith([
|
||||
'room@chatroom',
|
||||
'wwfixture_group@qy_g'
|
||||
])
|
||||
// 读不到成员的企业群不产生退群事件,也不写入任何基线。
|
||||
expect(service.getState().events).toEqual([])
|
||||
const stored = readJsonSync(join(mocks.userData, 'group-exit-monitor.json'))
|
||||
expect(stored.snapshots.map((snapshot: { roomId: string }) => snapshot.roomId)).toEqual([
|
||||
'room@chatroom'
|
||||
])
|
||||
})
|
||||
|
||||
it('logs one summary for a membership check and one for a hydration batch', async () => {
|
||||
installGroupDb()
|
||||
const log = vi.spyOn(console, 'log').mockImplementation(() => undefined)
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { afterAll, beforeAll, describe, expect, it } from 'vitest'
|
||||
import { isEnterpriseSession } from '../../src/shared/wechat-identities'
|
||||
import { Wcdb4Client } from '../../src/main/wcdb4-client'
|
||||
|
||||
/**
|
||||
* Synthetic shard filenames only: no real databases, keys, wxids, or content.
|
||||
* Wcdb4Client is constructed against an empty temporary account root and the
|
||||
* private discovery method is reached without opening any native database.
|
||||
*/
|
||||
describe(`enterprise message database routing`, () => {
|
||||
let root: string
|
||||
let client: Wcdb4Client
|
||||
|
||||
beforeAll(() => {
|
||||
root = mkdtempSync(join(tmpdir(), `wxe-wecom-routing-`))
|
||||
const account = join(root, `fixture-account`)
|
||||
const dbStorage = join(account, `db_storage`)
|
||||
mkdirSync(join(dbStorage, `message`), { recursive: true })
|
||||
mkdirSync(join(dbStorage, `session`), { recursive: true })
|
||||
writeFileSync(join(dbStorage, `session`, `session.db`), ``)
|
||||
const shards = [`message_0.db`, `message_1.db`, `biz_message_0.db`, `biz_message_1.db`]
|
||||
for (const name of shards) writeFileSync(join(dbStorage, `message`, name), ``)
|
||||
client = new Wcdb4Client(`00`, account)
|
||||
})
|
||||
|
||||
afterAll(() => rmSync(root, { recursive: true, force: true }))
|
||||
|
||||
function route(username: string): string[] {
|
||||
return (client as unknown as { getMessageDatabasePaths(u: string): string[] })
|
||||
.getMessageDatabasePaths(username)
|
||||
}
|
||||
|
||||
function names(username: string): string[] {
|
||||
return route(username).map((p) => p.split(`/`).pop() || ``)
|
||||
}
|
||||
|
||||
it(`routes enterprise group and direct sessions to biz_message shards`, () => {
|
||||
expect(isEnterpriseSession(`wwfixture_corp_user@qy_u`)).toBe(true)
|
||||
expect(names(`wwfixture_corp_room@qy_g`)).toEqual([`biz_message_0.db`, `biz_message_1.db`])
|
||||
expect(names(`wwfixture_corp_user@qy_u`)).toEqual([`biz_message_0.db`, `biz_message_1.db`])
|
||||
})
|
||||
|
||||
it(`keeps ordinary sessions on the message shards`, () => {
|
||||
expect(names(`wxid_fixture_friend`)).toEqual([`message_0.db`, `message_1.db`])
|
||||
expect(names(`12345@chatroom`)).toEqual([`message_0.db`, `message_1.db`])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,76 @@
|
||||
import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { afterAll, beforeAll, describe, expect, it } from 'vitest'
|
||||
import { selectMessageLocation, Wcdb4Client, Wcdb4Message } from '../../src/main/wcdb4-client'
|
||||
|
||||
/** Synthetic cross-shard hits only — no real ids, keys, or content. */
|
||||
describe(`enterprise message de-duplication`, () => {
|
||||
let root: string
|
||||
let client: Wcdb4Client
|
||||
type Merger = (current: Wcdb4Message[], recovered: Wcdb4Message[], limit?: number) => Wcdb4Message[]
|
||||
let mergeRows: Merger
|
||||
|
||||
const msg = (serverId: string, content: string, time: number, extra: Partial<Wcdb4Message> = {}): Wcdb4Message => ({
|
||||
mesLocalID: `100`,
|
||||
serverId,
|
||||
mesDes: 0,
|
||||
messageType: `1`,
|
||||
msgCreateTime: String(time),
|
||||
msgContent: content,
|
||||
raw: {},
|
||||
...extra,
|
||||
})
|
||||
|
||||
beforeAll(() => {
|
||||
root = mkdtempSync(join(tmpdir(), `wxe-wecom-dedup-`))
|
||||
const account = join(root, `fixture-account`)
|
||||
const dbStorage = join(account, `db_storage`)
|
||||
mkdirSync(join(dbStorage, `session`), { recursive: true })
|
||||
writeFileSync(join(dbStorage, `session`, `session.db`), ``)
|
||||
client = new Wcdb4Client(`00`, account)
|
||||
mergeRows = (client as unknown as { mergeMessageRows: Merger }).mergeMessageRows.bind(client)
|
||||
})
|
||||
|
||||
afterAll(() => rmSync(root, { recursive: true, force: true }))
|
||||
|
||||
it(`deduplicates enterprise messages by server id across snapshots`, () => {
|
||||
const a = msg(`srv-1001`, `fixture text A`, 1000, { sender: `wwfixture_user@qy_u` })
|
||||
const b = msg(`srv-1001`, `fixture text A`, 1000, { senderNickname: `fixture sender` })
|
||||
const merged = mergeRows([a], [b])
|
||||
expect(merged).toHaveLength(1)
|
||||
expect(merged[0].sender).toBe(`wwfixture_user@qy_u`)
|
||||
expect(merged[0].senderNickname).toBe(`fixture sender`)
|
||||
})
|
||||
|
||||
it(`keeps distinct enterprise messages separate`, () => {
|
||||
const a = msg(`srv-2001`, `fixture text 1`, 2000)
|
||||
const b = msg(`srv-2002`, `fixture text 2`, 2001)
|
||||
expect(mergeRows([a], [b])).toHaveLength(2)
|
||||
})
|
||||
|
||||
it(`does not merge different messages when a server id is reused across time`, () => {
|
||||
const first = msg(`srv-reused`, `fixture earlier`, 3000, { mesLocalID: `301` })
|
||||
const second = msg(`srv-reused`, `fixture later`, 3600, { mesLocalID: `302` })
|
||||
const merged = mergeRows([first, second], [])
|
||||
expect(merged).toHaveLength(2)
|
||||
expect(merged.map((item) => item.msgContent)).toEqual([`fixture earlier`, `fixture later`])
|
||||
})
|
||||
|
||||
it(`does not merge different messages when a server id is reused in the same second`, () => {
|
||||
const first = msg(`srv-reused`, `fixture left`, 4000, { mesLocalID: `401` })
|
||||
const second = msg(`srv-reused`, `fixture right`, 4000, { mesLocalID: `402` })
|
||||
expect(mergeRows([first, second], [])).toHaveLength(2)
|
||||
})
|
||||
|
||||
it(`resolves a unique cross-shard message by time`, () => {
|
||||
const hits = [
|
||||
{ createTime: 1000, localId: 1 },
|
||||
{ createTime: 1000, localId: 2 },
|
||||
{ createTime: 2000, localId: 3 },
|
||||
]
|
||||
expect(selectMessageLocation(hits, 2000)).toEqual({ status: `found`, location: hits[2] })
|
||||
expect(selectMessageLocation(hits, 1000).status).toBe(`ambiguous`)
|
||||
expect(selectMessageLocation(hits, null).status).toBe(`ambiguous`)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,122 @@
|
||||
import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { afterAll, beforeAll, describe, expect, it } from 'vitest'
|
||||
import { Wcdb4Client, Wcdb4GroupMember } from '../../src/main/wcdb4-client'
|
||||
|
||||
/** Synthetic group/member rows only — no real ids or content. */
|
||||
describe(`enterprise group name and member mapping`, () => {
|
||||
let root: string
|
||||
let client: Wcdb4Client
|
||||
type IdsFn = (rows: Record<string, unknown>[] | null | undefined) => string[]
|
||||
type MembersFn = (ids: string[], rows: Record<string, unknown>[] | null | undefined) => Wcdb4GroupMember[]
|
||||
let memberIds: IdsFn
|
||||
let membersFromRows: MembersFn
|
||||
|
||||
beforeAll(() => {
|
||||
root = mkdtempSync(join(tmpdir(), `wxe-wecom-members-`))
|
||||
const account = join(root, `fixture-account`)
|
||||
const dbStorage = join(account, `db_storage`)
|
||||
mkdirSync(join(dbStorage, `session`), { recursive: true })
|
||||
writeFileSync(join(dbStorage, `session`, `session.db`), ``)
|
||||
client = new Wcdb4Client(`00`, account)
|
||||
const impl = client as unknown as { enterpriseMemberIdsFromRows: IdsFn; enterpriseMembersFromRows: MembersFn }
|
||||
memberIds = impl.enterpriseMemberIdsFromRows.bind(client)
|
||||
membersFromRows = impl.enterpriseMembersFromRows.bind(client)
|
||||
})
|
||||
|
||||
afterAll(() => rmSync(root, { recursive: true, force: true }))
|
||||
|
||||
it(`parses the semicolon-delimited user_list and de-duplicates`, () => {
|
||||
expect(memberIds([{ user_list: `wwfixture_user_a@qy_u; wwfixture_user_b@qy_u;;wwfixture_user_a@qy_u ` }])).toEqual([
|
||||
`wwfixture_user_a@qy_u`,
|
||||
`wwfixture_user_b@qy_u`,
|
||||
])
|
||||
expect(memberIds([])).toEqual([])
|
||||
expect(memberIds(null)).toEqual([])
|
||||
})
|
||||
|
||||
it(`distinguishes a failed enterprise member read from a genuinely empty group`, async () => {
|
||||
const stub = (impl: Record<string, unknown>) => {
|
||||
impl.wcdbExecQuery = () => 0
|
||||
return impl
|
||||
}
|
||||
|
||||
const failed = new Wcdb4Client(`00`, join(root, `fixture-account`))
|
||||
const failedImpl = stub(failed as unknown as Record<string, unknown>)
|
||||
failedImpl.callJson = () => {
|
||||
throw new Error(`fixture native failure`)
|
||||
}
|
||||
failedImpl.callJsonAsync = () => Promise.reject(new Error(`fixture native failure`))
|
||||
expect(failed.getEnterpriseGroupMembers(`fixture@qy_g`)).toBeNull()
|
||||
await expect(failed.getEnterpriseGroupMembersAsync(`fixture@qy_g`)).resolves.toBeNull()
|
||||
|
||||
const empty = new Wcdb4Client(`00`, join(root, `fixture-account`))
|
||||
const emptyImpl = stub(empty as unknown as Record<string, unknown>)
|
||||
emptyImpl.callJson = () => []
|
||||
emptyImpl.callJsonAsync = () => Promise.resolve([])
|
||||
expect(empty.getEnterpriseGroupMembers(`fixture@qy_g`)).toEqual([])
|
||||
await expect(empty.getEnterpriseGroupMembersAsync(`fixture@qy_g`)).resolves.toEqual([])
|
||||
|
||||
const unavailable = new Wcdb4Client(`00`, join(root, `fixture-account`))
|
||||
expect(unavailable.getEnterpriseGroupMembers(`fixture@qy_g`)).toBeNull()
|
||||
})
|
||||
|
||||
it(`resolves an enterprise group name on a cold cache without waiting for hydration`, () => {
|
||||
const client = new Wcdb4Client(`00`, join(root, `fixture-account`))
|
||||
const impl = client as unknown as Record<string, unknown>
|
||||
impl.wcdbExecQuery = () => 0
|
||||
let calls = 0
|
||||
impl.callJson = () => {
|
||||
calls += 1
|
||||
return [{ chat_name: `fixture group name` }]
|
||||
}
|
||||
|
||||
// 冷缓存:同步快照路径第一次取群名就必须拿到真实群名,而不是 raw username。
|
||||
expect(client.getEnterpriseGroupName(`fixture@qy_g`)).toBe(`fixture group name`)
|
||||
// 第二次命中缓存,不再打库。
|
||||
expect(client.getEnterpriseGroupName(`fixture@qy_g`)).toBe(`fixture group name`)
|
||||
expect(calls).toBe(1)
|
||||
|
||||
// 非企业会话不参与该通道。
|
||||
expect(client.getEnterpriseGroupName(`fixture@chatroom`)).toBe(``)
|
||||
})
|
||||
|
||||
it(`gives the sync session list the same enterprise group name as hydration`, () => {
|
||||
const client = new Wcdb4Client(`00`, join(root, `fixture-account`))
|
||||
const impl = client as unknown as Record<string, unknown>
|
||||
impl.wcdbExecQuery = () => 0
|
||||
impl.wcdbGetSessions = () => 0
|
||||
let calls = 0
|
||||
impl.callJson = () => {
|
||||
calls += 1
|
||||
return [{ chat_name: `fixture group name` }]
|
||||
}
|
||||
impl.callJsonAsync = () => Promise.resolve([{ chat_name: `fixture group name` }])
|
||||
impl.readSessionRows = () => [
|
||||
{ username: `fixture@qy_g`, nickname: `fixture@qy_g`, sort_timestamp: 1 },
|
||||
{ username: `fixture@qy_u`, nickname: `fixture single chat`, sort_timestamp: 2 }
|
||||
]
|
||||
|
||||
// 冷启动:同步列表第一次就显示真实群名,不出现 raw username。
|
||||
const sessions = client.getSessions()
|
||||
expect(sessions.find((item) => item.username === `fixture@qy_g`)?.nickname).toBe(
|
||||
`fixture group name`
|
||||
)
|
||||
// 企业单聊不走群名通道,保持自己的昵称。
|
||||
expect(sessions.find((item) => item.username === `fixture@qy_u`)?.nickname).toBe(
|
||||
`fixture single chat`
|
||||
)
|
||||
expect(calls).toBe(1)
|
||||
})
|
||||
|
||||
it(`maps user_info rows to member display names`, () => {
|
||||
const members = membersFromRows(
|
||||
[`wwfixture_user_a@qy_u`, `wwfixture_user_b@qy_u`],
|
||||
[{ user_id: `wwfixture_user_a@qy_u`, user_name: `fixture member A` }]
|
||||
)
|
||||
expect(members).toHaveLength(2)
|
||||
expect(members[0].nickname).toBe(`fixture member A`)
|
||||
expect(members[1].nickname).toBe(`wwfixture_user_b@qy_u`)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,27 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { isEnterpriseSession, isGroupSession } from '../../src/shared/wechat-identities'
|
||||
|
||||
/** Synthetic conversation IDs only — no real wxid, corp id, or group name. */
|
||||
describe(`wechat identity classification`, () => {
|
||||
it(`recognizes enterprise group and direct sessions`, () => {
|
||||
expect(isGroupSession(`wwfixture_corp123_room1@qy_g`)).toBe(true)
|
||||
expect(isEnterpriseSession(`wwfixture_corp123_room1@qy_g`)).toBe(true)
|
||||
expect(isEnterpriseSession(`wwfixture_corp123_user1@qy_u`)).toBe(true)
|
||||
expect(isGroupSession(`wwfixture_corp123_user1@qy_u`)).toBe(false)
|
||||
})
|
||||
|
||||
it(`preserves ordinary friend, group, and official-account classification`, () => {
|
||||
expect(isGroupSession(`123456@chatroom`)).toBe(true)
|
||||
expect(isGroupSession(`wxid_fixture_friend`)).toBe(false)
|
||||
expect(isEnterpriseSession(`wxid_fixture_friend`)).toBe(false)
|
||||
expect(isEnterpriseSession(`gh_fixture_account`)).toBe(false)
|
||||
expect(isEnterpriseSession(`123456@chatroom`)).toBe(false)
|
||||
})
|
||||
|
||||
it(`tolerates empty and whitespace-padded values`, () => {
|
||||
expect(isGroupSession(undefined)).toBe(false)
|
||||
expect(isGroupSession(null)).toBe(false)
|
||||
expect(isGroupSession(` `)).toBe(false)
|
||||
expect(isEnterpriseSession(` wwfixture_corp_room@qy_g `)).toBe(true)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,81 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import type { WechatDb } from '../../src/main/wechat-db'
|
||||
import { getGroupMemberIdsBatchAsync, setChatDb } from '../../src/main/services/chat-service'
|
||||
|
||||
/**
|
||||
* native `wcdb_get_group_members_batch` 只认 `@chatroom`:混入一个 `@qy_g`
|
||||
* 会让整批查询失败。这里用合成 id 固化「按通道拆分 + 按请求顺序合并」的契约。
|
||||
*/
|
||||
describe('enterprise group membership batch', () => {
|
||||
afterEach(() => setChatDb(null))
|
||||
|
||||
const installDb = (client: Record<string, unknown>): void => {
|
||||
setChatDb({ close: vi.fn(), getWcdb4Client: () => client } as unknown as WechatDb)
|
||||
}
|
||||
|
||||
it('never sends enterprise groups to the native batch call', async () => {
|
||||
const nativeBatch = vi.fn(async (roomIds: string[]) =>
|
||||
roomIds.map((roomId) => ({ roomId, status: 'ok', memberWxids: [`wxid_${roomId}`] }))
|
||||
)
|
||||
const enterpriseMembers = vi.fn(async (roomId: string) => [
|
||||
{ m_nsUsrName: `wwmember_a_${roomId}@qy_u` },
|
||||
{ m_nsUsrName: `wwmember_b_${roomId}@qy_u` }
|
||||
])
|
||||
installDb({
|
||||
getGroupMemberIdsBatchAsync: nativeBatch,
|
||||
getEnterpriseGroupMembersAsync: enterpriseMembers
|
||||
})
|
||||
|
||||
const snapshots = await getGroupMemberIdsBatchAsync([
|
||||
'alpha@chatroom',
|
||||
'fixture@qy_g',
|
||||
'beta@chatroom'
|
||||
])
|
||||
|
||||
expect(nativeBatch).toHaveBeenCalledOnce()
|
||||
expect(nativeBatch.mock.calls[0][0]).toEqual(['alpha@chatroom', 'beta@chatroom'])
|
||||
expect(enterpriseMembers).toHaveBeenCalledWith('fixture@qy_g')
|
||||
expect(snapshots?.map((snapshot) => snapshot.roomId)).toEqual([
|
||||
'alpha@chatroom',
|
||||
'fixture@qy_g',
|
||||
'beta@chatroom'
|
||||
])
|
||||
expect(snapshots?.find((snapshot) => snapshot.roomId === 'fixture@qy_g')).toMatchObject({
|
||||
status: 'ok',
|
||||
memberIds: ['wwmember_a_fixture@qy_g@qy_u', 'wwmember_b_fixture@qy_g@qy_u']
|
||||
})
|
||||
})
|
||||
|
||||
it('reports a failed enterprise member read as not_found instead of an empty group', async () => {
|
||||
installDb({
|
||||
getGroupMemberIdsBatchAsync: vi.fn(async () => []),
|
||||
getEnterpriseGroupMembersAsync: vi.fn(async () => null)
|
||||
})
|
||||
|
||||
await expect(getGroupMemberIdsBatchAsync(['fixture@qy_g'])).resolves.toEqual([
|
||||
{ roomId: 'fixture@qy_g', status: 'not_found', memberIds: [] }
|
||||
])
|
||||
})
|
||||
|
||||
it('treats a genuinely empty enterprise group as an ok empty membership', async () => {
|
||||
installDb({
|
||||
getGroupMemberIdsBatchAsync: vi.fn(async () => []),
|
||||
getEnterpriseGroupMembersAsync: vi.fn(async () => [])
|
||||
})
|
||||
|
||||
await expect(getGroupMemberIdsBatchAsync(['fixture@qy_g'])).resolves.toEqual([
|
||||
{ roomId: 'fixture@qy_g', status: 'ok', memberIds: [] }
|
||||
])
|
||||
})
|
||||
|
||||
it('preserves the previous baseline when the native batch call fails', async () => {
|
||||
installDb({
|
||||
getGroupMemberIdsBatchAsync: vi.fn(async () => null),
|
||||
getEnterpriseGroupMembersAsync: vi.fn(async () => [])
|
||||
})
|
||||
|
||||
await expect(
|
||||
getGroupMemberIdsBatchAsync(['alpha@chatroom', 'fixture@qy_g'])
|
||||
).resolves.toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,19 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { parseMessageContent } from '../../src/main/message-parser'
|
||||
|
||||
/** Synthetic payloads only — no real content, keys, or identifiers. */
|
||||
describe(`enterprise image content parsing`, () => {
|
||||
it(`recognizes an aeskey-only enterprise image`, () => {
|
||||
const xml = `<img aeskey="fixtureaeskey0000000000000000000" encryver="0" cdnmidimgurl="fixture-url"/>`
|
||||
const parsed = parseMessageContent(xml, 3)
|
||||
expect(parsed.type).toBe(`image`)
|
||||
if (parsed.type === `image`) {
|
||||
expect(parsed.md5).toBeUndefined()
|
||||
expect(parsed.aeskey).toBe(`fixtureaeskey0000000000000000000`)
|
||||
}
|
||||
})
|
||||
|
||||
it(`still rejects img content with no identity fields`, () => {
|
||||
expect(parseMessageContent('<img/>', 3).type).toBe('unknown')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,63 @@
|
||||
import zlib from 'node:zlib'
|
||||
import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { afterAll, beforeAll, describe, expect, it } from 'vitest'
|
||||
import { Wcdb4Client } from '../../src/main/wcdb4-client'
|
||||
|
||||
/** Synthetic XML/ID rows only — no real sender ids, group ids, or content. */
|
||||
describe(`enterprise source XML parsing (production code path)`, () => {
|
||||
let root: string
|
||||
let client: Wcdb4Client
|
||||
type EnterpriseParse = (row: Record<string, unknown>) => { senderId: string; senderNickname: string; bizChatId: string }
|
||||
let parseSource: EnterpriseParse
|
||||
|
||||
beforeAll(() => {
|
||||
root = mkdtempSync(join(tmpdir(), `wxe-wecom-source-`))
|
||||
const account = join(root, `fixture-account`)
|
||||
const dbStorage = join(account, `db_storage`)
|
||||
mkdirSync(join(dbStorage, `session`), { recursive: true })
|
||||
writeFileSync(join(dbStorage, `session`, `session.db`), ``)
|
||||
client = new Wcdb4Client(`00`, account)
|
||||
parseSource = (client as unknown as { parseEnterpriseSource: EnterpriseParse }).parseEnterpriseSource.bind(client)
|
||||
})
|
||||
|
||||
afterAll(() => rmSync(root, { recursive: true, force: true }))
|
||||
|
||||
it(`parses enterprise_info from a plain source XML row`, () => {
|
||||
const xml = '<msg><user_id>wwfixture_corp_user@qy_u</user_id><user_nickname><![CDATA[fixture sender]]></user_nickname><bizchat_id>wwfixture_corp_room@qy_g</bizchat_id></msg>'
|
||||
expect(parseSource({ source: xml })).toEqual({
|
||||
senderId: 'wwfixture_corp_user@qy_u',
|
||||
senderNickname: 'fixture sender',
|
||||
bizChatId: 'wwfixture_corp_room@qy_g',
|
||||
})
|
||||
})
|
||||
|
||||
it(`returns empty result for missing or non-XML source`, () => {
|
||||
const empty = { senderId: '', senderNickname: '', bizChatId: '' }
|
||||
expect(parseSource({})).toEqual(empty)
|
||||
expect(parseSource({ source: 'not xml' })).toEqual(empty)
|
||||
expect(parseSource({ source: '<broken>' })).toEqual(empty)
|
||||
})
|
||||
|
||||
it(`rejects a non-enterprise sender id`, () => {
|
||||
const result = parseSource({ source: '<msg><user_id>wxid_fixture_friend</user_id></msg>' })
|
||||
expect(result.senderId).toBe('')
|
||||
})
|
||||
|
||||
it('parses a zstd-compressed source row with a pure-JS fallback', () => {
|
||||
// The production path tries the native decompressor first, then a JS zstd
|
||||
// fallback. This test exercises the fallback with a synthetic zstd frame
|
||||
// produced by the system zstd tool when available; otherwise it documents
|
||||
// that only the uncompressed path is portable enough for unit tests.
|
||||
const xml = '<msg><user_id>wwfixture_corp_user@qy_u</user_id></msg>'
|
||||
const plain = Buffer.from(xml)
|
||||
// Node 22+ exposes zstdCompressSync/zstdDecompressSync; older runtimes skip.
|
||||
if (typeof zlib.zstdCompressSync !== 'function') return
|
||||
const frame = (zlib as unknown as { zstdCompressSync(b: Buffer): Buffer }).zstdCompressSync(plain)
|
||||
expect(Buffer.from(frame).subarray(0, 4).toString('hex')).toBe('28b52ffd')
|
||||
expect((zlib as unknown as { zstdDecompressSync(b: Buffer): Buffer }).zstdDecompressSync(frame).toString()).toBe(xml)
|
||||
// Production decodeMaybeCompressed also accepts a base64 string.
|
||||
expect(parseSource({ source: frame.toString('base64') }).senderId).toBe('wwfixture_corp_user@qy_u')
|
||||
})
|
||||
})
|
||||
Reference in new issue
Block a user