mirror of
https://wget.la/https://github.com/Wxw-Gu/WechatExplorer
synced 2026-12-01 01:05:30 +08:00
Merge branch 'develop' of https://github.com/Wxw-Gu/TraceMemo into develop
This commit is contained in:
commit
a47756795c
20 files changed
+1101
-61
No files matched your search
@@ -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