mirror of
https://wget.la/https://github.com/Wxw-Gu/WechatExplorer
synced 2026-11-30 16:02:58 +08:00
Merge branch 'develop' of https://github.com/Wxw-Gu/TraceMemo into develop
This commit is contained in:
commit
d9d0672072
3 files changed
+353
-28
No files matched your search
+75
-28
@@ -569,9 +569,6 @@ export class Wcdb4Client {
|
||||
private wcdbMsgInsertGetSwitches:
|
||||
| ((handle: number, dbPath: string, outJson: WcdbVoidOut) => number)
|
||||
| null = null
|
||||
private wcdbMsgInsertListShardCatalog:
|
||||
| ((handle: number, outJson: WcdbVoidOut) => number)
|
||||
| null = null
|
||||
private wcdbGetGroupNicknames:
|
||||
| ((handle: number, chatroomId: string, outJson: WcdbVoidOut) => number)
|
||||
| null = null
|
||||
@@ -1938,7 +1935,7 @@ export class Wcdb4Client {
|
||||
/**
|
||||
* 读取「微信消息插入规则」的分片目录(只读)。
|
||||
*
|
||||
* 每个分片只跑两条查询(表清单 + 规则清单),拿回来之后调用方可以在本地用
|
||||
* 每个分片只跑一条 sqlite_master 查询,拿回来之后调用方可以在本地用
|
||||
* md5(roomId) 匹配出「每个会话落在哪些分片、规则齐不齐」。这样即使会话很多,
|
||||
* 判断全部会话的状态也只是一次目录读取,不需要按会话逐个查库。
|
||||
*/
|
||||
@@ -1950,29 +1947,40 @@ export class Wcdb4Client {
|
||||
shard: string
|
||||
dbPath: string
|
||||
configTable: boolean
|
||||
storeTables: { capture: boolean; names: boolean; queue: boolean }
|
||||
tables: string[]
|
||||
rules: Array<{ name: string; table: string }>
|
||||
}>
|
||||
}
|
||||
error?: string
|
||||
} {
|
||||
if (!this.wcdbMsgInsertListShardCatalog) {
|
||||
if (!this.wcdbExecQuery) {
|
||||
return { success: false, error: '当前 WCDB 服务不支持消息插入规则目录' }
|
||||
}
|
||||
try {
|
||||
const catalog = this.callJson<{
|
||||
shardCount: number
|
||||
shards: Array<{
|
||||
shard: string
|
||||
dbPath: string
|
||||
configTable: boolean
|
||||
storeTables: { capture: boolean; names: boolean; queue: boolean }
|
||||
tables: string[]
|
||||
rules: Array<{ name: string; table: string }>
|
||||
}>
|
||||
}>((handle, outJson) => this.wcdbMsgInsertListShardCatalog!(handle, outJson))
|
||||
return { success: true, catalog }
|
||||
// 专用 native 目录接口在部分 Windows 数据库上会终止进程,改走已有的只读 SQL 通道。
|
||||
const shards = this.listMessageShardPaths().map((dbPath) => {
|
||||
const rows = this.callJson<{ name: string; type: string; tbl_name: string }[]>(
|
||||
(handle, outJson) =>
|
||||
this.wcdbExecQuery!(
|
||||
handle,
|
||||
'message',
|
||||
dbPath,
|
||||
"SELECT name, type, tbl_name FROM sqlite_master WHERE type IN ('table', 'trigger')",
|
||||
outJson
|
||||
)
|
||||
)
|
||||
const tables = rows.filter((row) => row.type === 'table').map((row) => row.name)
|
||||
return {
|
||||
shard: path.basename(dbPath),
|
||||
dbPath,
|
||||
configTable: tables.includes('_tm_config'),
|
||||
tables,
|
||||
rules: rows
|
||||
.filter((row) => row.type === 'trigger')
|
||||
.map((row) => ({ name: row.name, table: row.tbl_name }))
|
||||
}
|
||||
})
|
||||
return { success: true, catalog: { shardCount: shards.length, shards } }
|
||||
} catch (error) {
|
||||
return { success: false, error: error instanceof Error ? error.message : String(error) }
|
||||
}
|
||||
@@ -2923,7 +2931,7 @@ export class Wcdb4Client {
|
||||
|
||||
const handle = this.ensureHandle()
|
||||
const fn = this.wcdbGetVoiceData as unknown as KoffiAsyncFunction
|
||||
return this.createTrackedNativeCall<Wcdb4VoiceDataResult>((resolve, reject) => {
|
||||
const result = await this.createTrackedNativeCall<Wcdb4VoiceDataResult>((resolve, reject) => {
|
||||
const outHex: WcdbVoidOut = [null]
|
||||
fn.async(
|
||||
handle,
|
||||
@@ -2948,7 +2956,9 @@ export class Wcdb4Client {
|
||||
resolve(
|
||||
hex === null
|
||||
? { success: false, error: '解析语音数据失败' }
|
||||
: { success: true, hex, error: '' }
|
||||
: hex
|
||||
? { success: true, hex, error: '' }
|
||||
: { success: false, error: '语音数据为空' }
|
||||
)
|
||||
} finally {
|
||||
this.wcdbFreeString?.(outHex[0])
|
||||
@@ -2956,6 +2966,51 @@ export class Wcdb4Client {
|
||||
}
|
||||
)
|
||||
})
|
||||
if (result.success) return result
|
||||
return (
|
||||
(await this.getVoiceDataFromMediaShards(sessionId, createTime, candidates, localId, svrId)) || result
|
||||
)
|
||||
}
|
||||
|
||||
private async getVoiceDataFromMediaShards(
|
||||
sessionId: string,
|
||||
createTime: number,
|
||||
candidates: string[],
|
||||
localId: number,
|
||||
svrId: string | number
|
||||
): Promise<Wcdb4VoiceDataResult | null> {
|
||||
if (!this.wcdbExecQuery || !sessionId) return null
|
||||
const serverId = String(svrId || 0)
|
||||
const identity = /^-?[1-9]\d*$/.test(serverId)
|
||||
? `v.svr_id = ${serverId}`
|
||||
: Number.isSafeInteger(localId) &&
|
||||
localId > 0 &&
|
||||
Number.isSafeInteger(createTime) &&
|
||||
createTime > 0
|
||||
? `v.local_id = ${localId} AND v.create_time = ${createTime}`
|
||||
: ''
|
||||
if (!identity) return null
|
||||
const sessions = this.uniq([sessionId, ...candidates])
|
||||
.map((name) => `'${name.replace(/'/g, "''")}'`)
|
||||
.join(',')
|
||||
const messageRoot = path.join(this.dbStoragePath, 'message')
|
||||
if (!fs.existsSync(messageRoot)) return null
|
||||
// 部分 native 版本漏读后续媒体分片;按完整消息身份查询,避免同秒语音串条。
|
||||
const shards = fs.readdirSync(messageRoot).filter((file) => /^media_\d+\.db$/.test(file)).sort()
|
||||
for (const name of shards) {
|
||||
try {
|
||||
const rows = await this.callJsonAsync<{ hex?: string }[]>(
|
||||
this.wcdbExecQuery as unknown as KoffiAsyncFunction,
|
||||
'message',
|
||||
path.join(messageRoot, name),
|
||||
`SELECT hex(v.voice_data) AS hex FROM VoiceInfo v JOIN Name2Id n ON n.rowid = v.chat_name_id WHERE n.user_name IN (${sessions}) AND ${identity} AND length(v.voice_data) > 0 LIMIT 1`
|
||||
)
|
||||
if (rows[0]?.hex) return { success: true, hex: rows[0].hex, error: '' }
|
||||
} catch (error) {
|
||||
console.warn(`[WCDB4] voice lookup failed in ${name}:`, error)
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
async getVoiceDataBatch(requests: Wcdb4VoiceDataRequest[]): Promise<Wcdb4VoiceDataResult[]> {
|
||||
@@ -3340,14 +3395,6 @@ export class Wcdb4Client {
|
||||
this.wcdbMsgInsertGetSwitches = null
|
||||
}
|
||||
|
||||
try {
|
||||
this.wcdbMsgInsertListShardCatalog = lib.func(
|
||||
'int32 wcdb_msg_insert_list_shard_catalog(int64 handle, _Out_ void** outJson)'
|
||||
) as (handle: number, outJson: WcdbVoidOut) => number
|
||||
} catch {
|
||||
this.wcdbMsgInsertListShardCatalog = null
|
||||
}
|
||||
|
||||
try {
|
||||
this.wcdbGetGroupNicknames = lib.func(
|
||||
'int32 wcdb_get_group_nicknames(int64 handle, const char* chatroomId, _Out_ void** outJson)'
|
||||
|
||||
@@ -0,0 +1,142 @@
|
||||
import { createHash } from 'crypto'
|
||||
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'fs'
|
||||
import { tmpdir } from 'os'
|
||||
import { basename, join } from 'path'
|
||||
import { DatabaseSync } from 'node:sqlite'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { Wcdb4Client } from '../../src/main/wcdb4-client'
|
||||
import { readMsgInsertSwitches } from '../../src/main/services/msg-insert-switch-service'
|
||||
|
||||
vi.mock('../../src/main/resource-paths', () => ({
|
||||
getResourceRoots: () => [],
|
||||
findResource: () => null
|
||||
}))
|
||||
|
||||
describe('message insert shard catalog', () => {
|
||||
const roots: string[] = []
|
||||
const room = 'fixture-group@chatroom'
|
||||
const hash = createHash('md5').update(room).digest('hex')
|
||||
const table = `Msg_${hash}`
|
||||
const capture = `_tm_msg_insert_capture_${hash}`
|
||||
|
||||
afterEach(() => {
|
||||
roots.splice(0).forEach((root) => rmSync(root, { recursive: true, force: true }))
|
||||
})
|
||||
|
||||
function fixture() {
|
||||
const root = mkdtempSync(join(tmpdir(), 'wcdb-insert-catalog-'))
|
||||
roots.push(root)
|
||||
const messageRoot = join(root, 'message')
|
||||
mkdirSync(messageRoot)
|
||||
for (const name of ['message_0.db', 'message_1.db']) {
|
||||
const db = new DatabaseSync(join(messageRoot, name))
|
||||
try {
|
||||
db.exec(`CREATE TABLE ${table}(content TEXT);`)
|
||||
if (name === 'message_0.db') {
|
||||
db.exec(`
|
||||
CREATE TABLE _tm_config(key TEXT PRIMARY KEY, value INTEGER);
|
||||
CREATE TRIGGER ${capture} AFTER INSERT ON ${table} BEGIN SELECT 1; END;
|
||||
`)
|
||||
}
|
||||
} finally {
|
||||
db.close()
|
||||
}
|
||||
}
|
||||
for (const name of ['media_0.db', 'message_0 (SFConflict).db', 'message_0.db-wal']) {
|
||||
writeFileSync(join(messageRoot, name), '')
|
||||
}
|
||||
const nativeCatalog = vi.fn(() => {
|
||||
throw new Error('unsafe native catalog called')
|
||||
})
|
||||
const query = vi.fn((_handle, kind, dbPath: string, sql: string, out: unknown[]) => {
|
||||
expect(kind).toBe('message')
|
||||
const db = new DatabaseSync(dbPath, { readOnly: true })
|
||||
try {
|
||||
out[0] = db.prepare(sql).all()
|
||||
} finally {
|
||||
db.close()
|
||||
}
|
||||
return 0
|
||||
})
|
||||
const client = Object.assign(Object.create(Wcdb4Client.prototype), {
|
||||
dbStoragePath: root,
|
||||
wcdbMsgInsertListShardCatalog: nativeCatalog,
|
||||
wcdbExecQuery: query,
|
||||
callJson: (call: (handle: number, out: unknown[]) => number) => {
|
||||
const out: unknown[] = [null]
|
||||
call(1, out)
|
||||
return out[0]
|
||||
},
|
||||
getSessions: () => [{ username: room }],
|
||||
getMsgInsertSwitches: () => ({ success: true, switches: { recall_notice: true } })
|
||||
}) as Wcdb4Client
|
||||
return { client, nativeCatalog, query, messageRoot }
|
||||
}
|
||||
|
||||
it('reads tables and trigger attachments through read-only SQL without the crashing native API', () => {
|
||||
const { client, nativeCatalog, query, messageRoot } = fixture()
|
||||
|
||||
expect(client.listMsgInsertShardCatalog()).toEqual({
|
||||
success: true,
|
||||
catalog: {
|
||||
shardCount: 2,
|
||||
shards: [
|
||||
{
|
||||
shard: 'message_0.db',
|
||||
dbPath: join(messageRoot, 'message_0.db'),
|
||||
configTable: true,
|
||||
tables: [table, '_tm_config'],
|
||||
rules: [{ name: capture, table }]
|
||||
},
|
||||
{
|
||||
shard: 'message_1.db',
|
||||
dbPath: join(messageRoot, 'message_1.db'),
|
||||
configTable: false,
|
||||
tables: [table],
|
||||
rules: []
|
||||
}
|
||||
]
|
||||
}
|
||||
})
|
||||
expect(nativeCatalog).not.toHaveBeenCalled()
|
||||
expect(query.mock.calls.map((call) => basename(call[2]))).toEqual([
|
||||
'message_0.db',
|
||||
'message_1.db'
|
||||
])
|
||||
})
|
||||
|
||||
it('preserves the rule coverage calculation across shards', () => {
|
||||
const { client } = fixture()
|
||||
|
||||
const snapshot = readMsgInsertSwitches({ client, monitoredRoomIds: [] })
|
||||
expect(snapshot.success).toBe(true)
|
||||
expect(snapshot.switches.recall_notice).toMatchObject({
|
||||
desiredEnabled: true,
|
||||
effectiveEnabled: false,
|
||||
totalShards: 2,
|
||||
totalInstallableRooms: 1,
|
||||
readyInstallableRooms: 0,
|
||||
notReadyRooms: [{ roomId: room, notReadyShards: ['message_1.db'] }]
|
||||
})
|
||||
})
|
||||
|
||||
it('reports a query failure instead of returning a partial catalog', () => {
|
||||
const { client, query } = fixture()
|
||||
query.mockImplementationOnce(() => {
|
||||
throw new Error('fixture shard unavailable')
|
||||
})
|
||||
|
||||
expect(client.listMsgInsertShardCatalog()).toEqual({
|
||||
success: false,
|
||||
error: 'fixture shard unavailable'
|
||||
})
|
||||
})
|
||||
|
||||
it('reports an unsupported SQL channel without calling the unsafe native API', () => {
|
||||
const { client, nativeCatalog } = fixture()
|
||||
Reflect.set(client, 'wcdbExecQuery', null)
|
||||
|
||||
expect(client.listMsgInsertShardCatalog()).toMatchObject({ success: false })
|
||||
expect(nativeCatalog).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,136 @@
|
||||
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'fs'
|
||||
import { tmpdir } from 'os'
|
||||
import { join } from 'path'
|
||||
import { DatabaseSync } from 'node:sqlite'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { Wcdb4Client } from '../../src/main/wcdb4-client'
|
||||
|
||||
describe('WCDB voice media shards', () => {
|
||||
const roots: string[] = []
|
||||
const databases: DatabaseSync[] = []
|
||||
const session = "wxid_fixture'peer"
|
||||
const serverId = '1234567890123456789'
|
||||
const createTime = 1_790_000_000
|
||||
const localId = 42
|
||||
const audio = Buffer.from('02532345', 'hex')
|
||||
|
||||
afterEach(() => {
|
||||
databases.splice(0).forEach((db) => db.close())
|
||||
roots.splice(0).forEach((root) => rmSync(root, { recursive: true, force: true }))
|
||||
})
|
||||
|
||||
function fixture(nativeHex = '', nativeCode = 0) {
|
||||
const root = mkdtempSync(join(tmpdir(), 'wcdb-voice-shards-'))
|
||||
roots.push(root)
|
||||
const messageRoot = join(root, 'message')
|
||||
mkdirSync(messageRoot)
|
||||
const stores = new Map<string, DatabaseSync>()
|
||||
for (const name of ['media_0.db', 'media_1.db']) {
|
||||
const dbPath = join(messageRoot, name)
|
||||
const db = new DatabaseSync(dbPath)
|
||||
databases.push(db)
|
||||
db.exec(`
|
||||
CREATE TABLE Name2Id(user_name TEXT PRIMARY KEY);
|
||||
CREATE TABLE VoiceInfo(chat_name_id INTEGER, create_time INTEGER, local_id INTEGER, svr_id INTEGER, voice_data BLOB);
|
||||
`)
|
||||
db.prepare('INSERT INTO Name2Id VALUES (?)').run(session)
|
||||
db.prepare('INSERT INTO Name2Id VALUES (?)').run('other-session')
|
||||
stores.set(dbPath, db)
|
||||
}
|
||||
writeFileSync(join(messageRoot, 'media_0 (SFConflict).db'), '')
|
||||
const query = vi.fn(async (_fn, _kind, dbPath: string, sql: string) => {
|
||||
const db = stores.get(dbPath)
|
||||
if (!db) throw new Error('Unexpected media shard')
|
||||
return db.prepare(sql).all()
|
||||
})
|
||||
const freeString = vi.fn()
|
||||
const client = Object.assign(Object.create(Wcdb4Client.prototype), {
|
||||
dbStoragePath: root,
|
||||
wcdbGetVoiceData: {
|
||||
async: (...args: unknown[]) => {
|
||||
;(args.at(-2) as [unknown])[0] = {}
|
||||
;(args.at(-1) as (error: unknown, code: number) => void)(null, nativeCode)
|
||||
}
|
||||
},
|
||||
wcdbExecQuery: vi.fn(),
|
||||
wcdbFreeString: freeString,
|
||||
callJsonAsync: query,
|
||||
decodeHexPtr: () => nativeHex,
|
||||
handle: 1,
|
||||
closing: false,
|
||||
nativeCallsInFlight: new Set()
|
||||
}) as Wcdb4Client
|
||||
const insert = (shard: number, chat: number, id: number, svr: string, bytes = audio) => {
|
||||
stores
|
||||
.get(join(messageRoot, `media_${shard}.db`))!
|
||||
.prepare('INSERT INTO VoiceInfo VALUES (?, ?, ?, ?, ?)')
|
||||
.run(chat, createTime, id, BigInt(svr), bytes)
|
||||
}
|
||||
return { client, query, freeString, insert }
|
||||
}
|
||||
|
||||
it.each([0, -3003])(
|
||||
'reads a later shard when native lookup returns empty data or fails (%s)',
|
||||
async (code) => {
|
||||
const { client, query, freeString, insert } = fixture('', code)
|
||||
insert(0, 1, localId, '1234567890123456790', Buffer.from('bad1', 'hex'))
|
||||
insert(0, 2, localId, serverId, Buffer.from('bad2', 'hex'))
|
||||
insert(0, 1, localId, serverId, Buffer.alloc(0))
|
||||
insert(1, 1, localId, serverId)
|
||||
|
||||
await expect(
|
||||
client.getVoiceData(session, createTime, [session], localId, serverId)
|
||||
).resolves.toEqual({ success: true, hex: audio.toString('hex'), error: '' })
|
||||
expect(query).toHaveBeenCalledTimes(2)
|
||||
expect(freeString).toHaveBeenCalledOnce()
|
||||
}
|
||||
)
|
||||
|
||||
it('uses both local id and time within the session when no server id is available', async () => {
|
||||
const { client, insert } = fixture()
|
||||
insert(0, 1, localId + 1, '123')
|
||||
insert(0, 2, localId, '456')
|
||||
insert(1, 1, localId, '789')
|
||||
|
||||
await expect(
|
||||
client.getVoiceData(session, createTime, [session], localId)
|
||||
).resolves.toMatchObject({ success: true, hex: audio.toString('hex') })
|
||||
await expect(
|
||||
client.getVoiceData(session, createTime + 1, [session], localId)
|
||||
).resolves.toMatchObject({ success: false })
|
||||
})
|
||||
|
||||
it('does not substitute another message when the known server id is missing', async () => {
|
||||
const { client, insert } = fixture()
|
||||
insert(0, 1, localId, '1234567890123456790')
|
||||
|
||||
await expect(
|
||||
client.getVoiceData(session, createTime, [session], localId, serverId)
|
||||
).resolves.toEqual({ success: false, error: '语音数据为空' })
|
||||
})
|
||||
|
||||
it('continues after an unreadable shard', async () => {
|
||||
const { client, query, insert } = fixture()
|
||||
vi.spyOn(console, 'warn').mockImplementation(() => {})
|
||||
query.mockRejectedValueOnce(new Error('unreadable shard'))
|
||||
insert(1, 1, localId, serverId)
|
||||
|
||||
await expect(
|
||||
client.getVoiceData(session, createTime, [session], localId, serverId)
|
||||
).resolves.toMatchObject({ success: true, hex: audio.toString('hex') })
|
||||
})
|
||||
|
||||
it('skips SQL when native lookup succeeds or the message identity is incomplete', async () => {
|
||||
const successful = fixture('aabb')
|
||||
await expect(
|
||||
successful.client.getVoiceData(session, createTime, [], localId, serverId)
|
||||
).resolves.toMatchObject({ success: true, hex: 'aabb' })
|
||||
expect(successful.query).not.toHaveBeenCalled()
|
||||
|
||||
const missing = fixture()
|
||||
await expect(missing.client.getVoiceData(session, createTime, [])).resolves.toMatchObject({
|
||||
success: false
|
||||
})
|
||||
expect(missing.query).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
Reference in new issue
Block a user