Merge branch 'develop' of https://github.com/Wxw-Gu/TraceMemo into develop

This commit is contained in:
Wxw-Gu committed 2026-11-25 16:05:02 +08:00
commit a47756795c
20 files changed
+1101 -61

No files matched your search

+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 {
@@ -998,7 +999,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')
}
+74 -18
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,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 {
+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) {
+357 -32
View File
@@ -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
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,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
)
}
+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')
}