feat(wecom): 支持企业微信插件会话的消息读取与检索

企业微信插件(Mac 微信 4.2)的群 @qy_g 与会话 @qy_u 消息落在
biz_message_*.db,群/成员元数据落在 bizchat/bizchat.db,而原实现
只把 gh_ 前缀路由到 biz_message_*.db,其余一律读 message_*.db,
导致这些会话在档案/会话列表/搜索中完全缺失。

核心改动:
- wcdb4-client: isBizSession/isEnterpriseSession 判定;getMessageDatabasePaths
  把 @qy_g/@qy_u 路由到 biz_message_*.db;企业会话跳过本库 Name2Id 联表
- wcdb4-client: parseEnterpriseSource 从 zstd 压缩的 source XML
  enterprise_info 解析 sender/nickname/bizchat_id
- wcdb4-client: hydrateEnterpriseGroupNamesAsync 从 bizchat.chat_group 注入群名
- wcdb4-client: getEnterpriseGroupMembers(Async) 从 chat_group.user_list +
  user_info.user_name 构建成员列表
- message-parser: 企业图片 <img> 无 md5 但有 aeskey,按 aeskey 补判图片类型
- shared/wechat-identities: isGroupSession/isEnterpriseSession 统一判定
- chat-service/wechat-db/index/local-agent-api/agent-group-report/knowledge-search:
  读取与展示链路改用 isGroupSession,覆盖会话列表、群快照、群成员统计、
  群日报、知识检索、撤回归档映射
- .gitignore: 排除诊断产物、数据库快照、密钥派生脚本与消息正文 blob

只读改造,未触及发送/插入/退群监控/语音转写/群管理等写入链路。
普通微信好友、@chatroom 群、gh_ 公众号行为保持不变。

验证:4 个 @qy_g 群 + 2 个 @qy_u 单聊可读;chatlog/query-search/
group_snapshot/member-stats 全通过;typecheck:node EXIT=0。
This commit is contained in:
TraceMemo Custom Build committed 2026-11-23 11:11:40 +08:00
1 parent 518a9662a7
commit eac16ad8a7
10 files changed
+347 -29

No files matched your search

+15
View File
@@ -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/
+2 -1
View File
@@ -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)
)
}
+6 -1
View File
@@ -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')
}
+23 -10
View File
@@ -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,9 +1052,11 @@ 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 rawMembers = roomId.endsWith('@qy_g')
? wcdb4Client.getEnterpriseGroupMembers(roomId)
: wcdb4Client.getGroupMembers(roomId)
const members = (Array.isArray(rawMembers) ? rawMembers : [])
.filter((member) => member?.m_nsUsrName)
.map((member) => ({
@@ -1072,9 +1075,11 @@ 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 rawMembers = roomId.endsWith('@qy_g')
? await wcdb4Client.getEnterpriseGroupMembersAsync(roomId)
: await wcdb4Client.getGroupMembersAsync(roomId)
const members = (Array.isArray(rawMembers) ? rawMembers : [])
.filter((member) => member?.m_nsUsrName)
.map((member) => ({
@@ -1105,15 +1110,23 @@ 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)
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 +1147,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,
+2 -1
View File
@@ -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) {
+260 -8
View File
@@ -2204,7 +2204,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 +2226,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 +2243,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 +2307,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 +2347,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,
@@ -2487,6 +2527,9 @@ export class Wcdb4Client {
for (const message of [...recovered, ...current]) {
const recoveredRow = Boolean(message.raw?.['_wxe_recovered'])
const serverId = String(message.serverId || '').trim()
// Enterprise (@qy_g/@qy_u) messages carry a non-empty server_id as a
// string, so they dedupe on the same account-unique `server:` key as
// ordinary messages — no enterprise-specific dedup key is required.
const localIdentity = message.mesLocalID
? `local:${message.mesLocalID}:${message.msgCreateTime || 0}`
: ''
@@ -3376,9 +3419,29 @@ 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')) {
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)
@@ -4617,6 +4680,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 +4689,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 +4777,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 +4798,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 +4850,37 @@ 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`)。
*/
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)
}
} 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 +4909,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))
@@ -4790,6 +4933,115 @@ 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[] {
return this.readEnterpriseGroupMembers(roomId)
}
async getEnterpriseGroupMembersAsync(roomId: string): Promise<Wcdb4GroupMember[]> {
return this.readEnterpriseGroupMembersAsync(roomId)
}
private readEnterpriseGroupMembers(roomId: string): Wcdb4GroupMember[] {
if (!this.wcdbExecQuery || !roomId || !roomId.endsWith('@qy_g')) return []
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 {
return []
}
}
private async readEnterpriseGroupMembersAsync(roomId: string): Promise<Wcdb4GroupMember[]> {
if (!this.wcdbExecQuery || !roomId || !roomId.endsWith('@qy_g')) return []
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 []
}
}
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
+16 -7
View File
@@ -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,18 @@ export class WechatDb {
)
}
/**
* 统一读取群成员:@chatroom 走 native getGroupMembers,@qy_g 走 bizchat 企业群成员。
*/
private readGroupMembers(roomId: string): Wcdb4GroupMember[] {
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 +162,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 +175,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 +189,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
)
}
+19
View File
@@ -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')
}