mirror of
https://wget.la/https://github.com/Wxw-Gu/WechatExplorer
synced 2026-12-01 09:15:41 +08:00
feat: 新增微信图片文字索引与问问微信图片检索能力
This commit is contained in:
1 parent
24399f1d70
commit
b8f08d54c8
46 files changed
+6938
-75
No files matched your search
+203
-1
@@ -6,6 +6,7 @@ import { createRequire } from 'module'
|
||||
import { createConnection, Socket } from 'net'
|
||||
import { getResourceRoots } from './resource-paths'
|
||||
import { wcdbDebugLog } from './wcdb-debug'
|
||||
import type { ImageMessageCountProbe } from '../shared/image-text-index'
|
||||
|
||||
export interface Wcdb4Session {
|
||||
username: string
|
||||
@@ -1232,11 +1233,15 @@ export class Wcdb4Client {
|
||||
}
|
||||
|
||||
async countVoiceMessagesAsync(
|
||||
username: string,
|
||||
md5OrUsername: string,
|
||||
startTime?: number,
|
||||
endTime?: number
|
||||
): Promise<number | null> {
|
||||
if (!this.wcdbGetMessageTableStats || !this.wcdbExecQuery) return null
|
||||
// 与图片计数同因的修正:同一个 md5/username 混淆在这里也存在,
|
||||
// 而且它更隐蔽 —— 匹配不到表时循环不执行,函数会**返回 0 而不是报错**。
|
||||
const username = this.resolveMessageUsername(md5OrUsername)
|
||||
if (!username) return null
|
||||
|
||||
let tables: Wcdb4MessageStore[]
|
||||
try {
|
||||
@@ -1276,6 +1281,203 @@ export class Wcdb4Client {
|
||||
return total
|
||||
}
|
||||
|
||||
/**
|
||||
* 消息类型列的可能名字(按顺序探测,命中即用)。
|
||||
*
|
||||
* 为什么不能直接硬编码 `"local_type"`:`pickValue(row, [...别名])` 那套别名列表只作用于
|
||||
* **已经读出来的行**;一旦把列名写进 WHERE,列名不同的库会当场抛错,再被 catch 吞成
|
||||
* `null` —— 表现就是"检测到 0 张图片"。所以必须先探测真实列名。
|
||||
*/
|
||||
private readonly messageTypeColumnCandidates = [
|
||||
'local_type',
|
||||
'localType',
|
||||
'msg_type',
|
||||
'msgType',
|
||||
'message_type',
|
||||
'messageType',
|
||||
'type',
|
||||
'WCDB_CT_local_type'
|
||||
]
|
||||
|
||||
/** 每个消息分片的真实类型列名;探测一次即缓存,避免每个会话都跑一次 PRAGMA。 */
|
||||
private readonly messageTypeColumnCache = new Map<string, string | null>()
|
||||
|
||||
private resolveMessageTypeColumn(store: Wcdb4MessageStore): string | null {
|
||||
const cacheKey = `${store.dbPath}\u0000${store.tableName}`
|
||||
const cached = this.messageTypeColumnCache.get(cacheKey)
|
||||
if (cached !== undefined) return cached
|
||||
let resolved: string | null = null
|
||||
try {
|
||||
const columns = this.readMessageColumns(store).map((column) => column.name)
|
||||
for (const candidate of this.messageTypeColumnCandidates) {
|
||||
const hit = columns.find((name) => name.toLowerCase() === candidate.toLowerCase())
|
||||
if (hit) {
|
||||
resolved = hit
|
||||
break
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
resolved = null
|
||||
}
|
||||
this.messageTypeColumnCache.set(cacheKey, resolved)
|
||||
return resolved
|
||||
}
|
||||
|
||||
/**
|
||||
* 把「会话 md5」解析成原生接口真正需要的 username。
|
||||
*
|
||||
* `contact.md5` 是 `md5(wxid)` 的**哈希**(见 chat-service 的 `dbRef.md5(user.m_nsUsrName)`),
|
||||
* 而 `wcdbGetMessageTableStats` / `wcdbGetMessages` 这些原生接口要的是**原始 username**。
|
||||
* 直接把 md5 当 username 传,原生侧匹配不到任何表 —— 表现为"未找到该会话的消息表",
|
||||
* 而按表统计的计数会静默变成 0。
|
||||
*
|
||||
* 既有读消息路径一直做了这层转换(`listSourceMessages` 里的 `getUsernameByMd5`),
|
||||
* **统计/水位路径漏了**,所以这里统一补上。
|
||||
*
|
||||
* 解析不到时原样返回:调用方本来就传 username 的路径仍然可用。
|
||||
*/
|
||||
private resolveMessageUsername(md5OrUsername: string): string {
|
||||
const value = String(md5OrUsername || '').trim()
|
||||
if (!value) return value
|
||||
const bySession = this.getUsernameByMd5(value)
|
||||
if (bySession) return bySession
|
||||
// 有些群只以 `Chat_<md5>` 表存在、不在 session 列表里;退回按聊天表映射解析
|
||||
// (与 wechat-db 的 `chatMd5ToUsername` 同一套依据)。
|
||||
try {
|
||||
const byChatTable = this.getChatTables().find((table) => table.name === `Chat_${value}`)
|
||||
if (byChatTable?.db_number) return byChatTable.db_number
|
||||
} catch {
|
||||
// 映射不可用时退回原值。
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
/** 图片消息的 WHERE 片段;`sinceMs` 用于只统计某个时间点之后的消息(测试小窗口)。 */
|
||||
private imageMessageWhere(column: string, sinceMs?: number): string {
|
||||
const clauses = [`(${this.quoteSqlIdentifier(column)} & 65535) = 3`]
|
||||
// 微信的 create_time 是**秒**,调用方给的是毫秒。
|
||||
if (sinceMs && Number.isFinite(sinceMs) && sinceMs > 0) {
|
||||
clauses.push(`"create_time" >= ${Math.floor(sinceMs / 1000)}`)
|
||||
}
|
||||
return clauses.join(' AND ')
|
||||
}
|
||||
|
||||
/**
|
||||
* 统计图片消息条数。
|
||||
*
|
||||
* 与 `countVoiceMessagesAsync` 同构:纯 SQL COUNT,**不解密任何图片** ——
|
||||
* 这是「点击索引前先告诉用户有多少张图片」能足够快的前提。
|
||||
*
|
||||
* 与语音版本的关键差别:这里**必须区分「0 张」与「统计失败」**。
|
||||
* `count: null` 表示没数成,调用方绝不能把它当成 0。
|
||||
*/
|
||||
async countImageMessagesAsync(
|
||||
md5OrUsername: string,
|
||||
sinceMs?: number
|
||||
): Promise<ImageMessageCountProbe> {
|
||||
if (!this.wcdbGetMessageTableStats || !this.wcdbExecQuery) {
|
||||
return { count: null, typeColumn: null, error: '当前数据服务不支持消息表统计' }
|
||||
}
|
||||
const username = this.resolveMessageUsername(md5OrUsername)
|
||||
if (!username) {
|
||||
return { count: null, typeColumn: null, error: '无法解析该会话的标识' }
|
||||
}
|
||||
|
||||
let tables: Wcdb4MessageStore[]
|
||||
try {
|
||||
tables = await this.listMessageStoresAsync(username)
|
||||
} catch {
|
||||
return { count: null, typeColumn: null, error: '读取消息分片失败' }
|
||||
}
|
||||
if (!tables.length) {
|
||||
return { count: null, typeColumn: null, error: '未找到该会话的消息表' }
|
||||
}
|
||||
|
||||
let total = 0
|
||||
let typeColumn: string | null = null
|
||||
for (const table of tables) {
|
||||
const column = this.resolveMessageTypeColumn(table)
|
||||
if (!column) {
|
||||
return { count: null, typeColumn: null, error: '消息表缺少可识别的消息类型列' }
|
||||
}
|
||||
if (!typeColumn) typeColumn = column
|
||||
try {
|
||||
const rows = await this.callJsonAsync<Record<string, unknown>[]>(
|
||||
this.wcdbExecQuery as unknown as KoffiAsyncFunction,
|
||||
'message',
|
||||
table.dbPath,
|
||||
`SELECT COUNT(*) AS "image_count" FROM ${this.quoteSqlIdentifier(table.tableName)} WHERE ${this.imageMessageWhere(column, sinceMs)}`
|
||||
)
|
||||
const value = Number(this.pickValue(rows[0] || {}, ['image_count', 'count', 'COUNT(*)']))
|
||||
if (Number.isFinite(value)) total += value
|
||||
} catch {
|
||||
return { count: null, typeColumn: null, error: '图片消息统计查询失败' }
|
||||
}
|
||||
}
|
||||
return { count: total, typeColumn }
|
||||
}
|
||||
|
||||
/**
|
||||
* 图片消息的增量水位:`count` + `max(local_id)`。
|
||||
*
|
||||
* 为什么不能只靠 `countImageMessagesAsync`:
|
||||
* 图片总数相同**不代表**图片集合没变。撤回一张旧图 + 新增一张新图,count 不变,
|
||||
* 但新图的 `local_id` 更大。只看 count 会静默跳过该会话,新图片永远搜不到。
|
||||
*
|
||||
* `local_id` 是 WCDB 每张消息表内的插入序(自增),所以:
|
||||
* - 任何 append → `max_local_id` 严格变大;
|
||||
* - 「删旧 + 增新」且总数不变 → `max_local_id` 也变大,照样被发现;
|
||||
* - 只有「删掉非最大的那张且不新增」才不变,而此时集合缩小、无需重扫。
|
||||
*
|
||||
* 仍然是一条 SQL 聚合,**不解密任何图片**,成本与 count 同量级。
|
||||
*/
|
||||
async imageConversationWatermarkAsync(
|
||||
md5OrUsername: string,
|
||||
sinceMs?: number
|
||||
): Promise<{ count: number; maxLocalId: number } | null> {
|
||||
if (!this.wcdbGetMessageTableStats || !this.wcdbExecQuery) return null
|
||||
// 与计数同因:必须先把会话 md5 解析成原生接口要的 username,否则永远匹配不到消息表。
|
||||
const username = this.resolveMessageUsername(md5OrUsername)
|
||||
if (!username) return null
|
||||
|
||||
let tables: Wcdb4MessageStore[]
|
||||
try {
|
||||
tables = await this.listMessageStoresAsync(username)
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
|
||||
let count = 0
|
||||
let maxLocalId = 0
|
||||
for (const table of tables) {
|
||||
// 同样探测真实列名:硬编码列名会让水位查询静默失败,进而退化成"永远重扫"或"永远跳过"。
|
||||
const column = this.resolveMessageTypeColumn(table)
|
||||
if (!column) return null
|
||||
try {
|
||||
const rows = await this.callJsonAsync<Record<string, unknown>[]>(
|
||||
this.wcdbExecQuery as unknown as KoffiAsyncFunction,
|
||||
'message',
|
||||
table.dbPath,
|
||||
`SELECT COUNT(*) AS "image_count", MAX("local_id") AS "image_max_local_id" FROM ${this.quoteSqlIdentifier(table.tableName)} WHERE ${this.imageMessageWhere(column, sinceMs)}`
|
||||
)
|
||||
const row = rows[0] || {}
|
||||
const tableCount = Number(this.pickValue(row, ['image_count', 'count', 'COUNT(*)']))
|
||||
const tableMax = Number(
|
||||
this.pickValue(row, ['image_max_local_id', 'max_local_id', 'MAX("local_id")'])
|
||||
)
|
||||
if (Number.isFinite(tableCount)) count += tableCount
|
||||
if (Number.isFinite(tableMax) && tableMax > maxLocalId) maxLocalId = tableMax
|
||||
} catch (error) {
|
||||
console.warn(
|
||||
`[WCDB4] image watermark failed username=${username} db=${table.dbPath} table=${table.tableName}:`,
|
||||
error
|
||||
)
|
||||
return null
|
||||
}
|
||||
}
|
||||
return { count, maxLocalId }
|
||||
}
|
||||
|
||||
private readSessionRows(): Record<string, unknown>[] {
|
||||
if (!this.wcdbGetSessions) return []
|
||||
const rows = this.callJson<Record<string, unknown>[]>((handle, outJson) =>
|
||||
|
||||
Reference in new issue
Block a user