feat: 防撤回支持反序撤回,退群内提示改为覆盖全部群聊

退群提示:范围改为全部群聊,与退群监控勾选解耦(勾选只服务自动化通知)
This commit is contained in:
Wxw-Gu committed 2026-10-12 18:50:28 +08:00
1 parent 632ec9ee13
commit 7ce0475b3f
7 files changed
+421 -42

No files matched your search

+133 -14
View File
@@ -132,6 +132,7 @@ import {
readMsgInsertSwitches,
reconcileMsgInsertRules,
resolveHelperPath,
resolveTargetRooms,
type MsgInsertScopeInput,
type MsgInsertSwitchName
} from './services/msg-insert-switch-service'
@@ -141,16 +142,31 @@ import {
wechatLocalExitNoticeService
} from './services/wechat-local-exit-notice-service'
/** 「微信内退群监控消息」覆盖的群聊数(开关卡片的范围说明用,不是覆盖率)。 */
function exitNoticeGroupCount(): number {
return groupExitMonitorService.getNoticeGroupCount()
}
/**
* 把「微信内退群监控消息」的开关状态同步给退群监控。
*
* 注入的只是**开关**:群清单由 monitor 自己在刷新群名时一并更新,
* 这里不维护第二份。检测范围会成为「勾选的群 ∪ 全部群聊」,两个消费者都能拿到事件。
*/
function syncExitNoticeScope(): void {
try {
groupExitMonitorService.setNoticeEnabled(wechatLocalExitNoticeService.isEnabled())
} catch (error) {
console.warn('[MsgInsert] 同步退群内提示范围失败:', error)
}
}
/**
* 微信消息插入开关的作用面输入。
*
* 目标群列表**复用退群监控的配置**,不在这里另维护一份。
* 防撤回用「全部可定位会话」;退群监控的勾选只服务自动化通知,不再是内提示的范围。
* 数据库没连上时返回 null,调用方据此禁用写入而不是假装能改。
*/
function monitoredRoomCount(): number {
return (groupExitMonitorService.getState().monitoredRoomIds || []).length
}
function resolveMsgInsertScopeInput(): MsgInsertScopeInput | null {
const client = chat.getChatDb()?.getWcdb4Client()
if (!client) return null
@@ -203,16 +219,27 @@ async function reconcileMsgInsertRulesOnStart(): Promise<void> {
return
}
if (!enabled) return
await reconcileMsgInsertRulesNow()
await reconcileMsgInsertRulesNow(recallRoomsForReconcile(scope))
}
async function reconcileMsgInsertRulesNow(): Promise<boolean> {
/**
* 防撤回的作用面 = 全部可定位会话(群聊 + 私聊)。
*
* native 侧有「定义漂移就 DROP + 重建」的能力,但只有显式复核时才会跑;
* 规则定义变了不自动铺开,用户就得手动关-开一次开关。
*/
function recallRoomsForReconcile(scope: MsgInsertScopeInput): string[] {
return resolveTargetRooms(scope, 'recall_notice').rooms
}
async function reconcileMsgInsertRulesNow(extraRooms: string[] = []): Promise<boolean> {
const scope = resolveMsgInsertScopeInput()
const client = chat.getChatDb()?.getWcdb4Client()
if (!scope || !client) return false
try {
const result = await reconcileMsgInsertRules({
...scope,
extraRooms,
myWxid: String(chat.getSelfAccountInfo()?.wxid || ''),
databaseKey: client.getKey()
})
@@ -229,6 +256,78 @@ async function reconcileMsgInsertRulesNow(): Promise<boolean> {
return true
}
}
/**
* 清理老版防撤回保护(recall journal)留在微信库里的 `_wxe_capture_*` 触发器。
*
* 那批触发器装进库里就没人卸载(应用关闭该功能时直接 return),会一直抓取;而且它
* 和新机制的触发器挂在同一张 `Msg_*` 表上抢事件。
*
* 边界:先只读扫描、有残留才写库;只删触发器、不删老日志表(表里是微信已删、可能
* 只剩一份的副本);日志只记数量(对象名含 sha1(会话表名) 派生的稳定标识)。
*/
async function cleanupLegacyRecallResidueOnStart(): Promise<void> {
const client = chat.getChatDb()?.getWcdb4Client()
if (!client) return
try {
const report = client.scanLegacyRecallResidue()
if (!report.found) return
console.log(
`[RecallResidue] 检测到老版防撤回残留 shards=${report.shards.length} triggers=${report.triggerCount}` +
` journals=${report.journalCount} blockingDelete=${report.blockingDeleteCount}` +
` blockingInsert=${report.blockingInsertCount} passive=${report.passiveCount}`
)
appLogger.write({
level: 'warn',
scope: 'recall-residue',
message: '检测到老版防撤回残留,开始清理',
details: {
shards: report.shards.length,
triggers: report.triggerCount,
journals: report.journalCount,
blockingDelete: report.blockingDeleteCount,
blockingInsert: report.blockingInsertCount,
passive: report.passiveCount
}
})
/*
* 删除必须借 helper 的可写连接:本进程对分片只有只读连接,自己发 DROP 一定失败。
* helper 那条链路会在装规则时顺手清掉残留,顺带把新规则铺到所有会话。
*/
const scope = resolveMsgInsertScopeInput()
const applied = scope ? await reconcileMsgInsertRulesNow(recallRoomsForReconcile(scope)) : false
/* 收尾结论以「重新扫描」为准,不采信 helper 的自述。 */
const after = client.scanLegacyRecallResidue()
const cleared = after.triggerCount === 0
console.log(
`[RecallResidue] 清理${cleared ? '完成' : '未完成'} applied=${applied} remainingTriggers=${after.triggerCount}` +
` remainingJournals=${after.journalCount}`
)
appLogger.write({
level: cleared ? 'info' : 'warn',
scope: 'recall-residue',
message: cleared ? '老版防撤回残留清理完成' : '老版防撤回残留清理未完成',
details: {
requested: report.triggerCount,
remainingTriggers: after.triggerCount,
remainingJournals: after.journalCount,
helperApplied: applied
}
})
} catch (error) {
/* 清理失败绝不能挡住启动 —— 它只是收尾工作。 */
console.warn('[RecallResidue] 清理失败:', error)
appLogger.write({
level: 'warn',
scope: 'recall-residue',
message: '老版防撤回残留清理失败',
details: { reason: error instanceof Error ? error.message : String(error) }
})
}
}
import { wechatActionLogService } from './services/wechat-action-log-service'
import { toPersonalWechatSendResult, wechatActionGateway } from './services/wechat-action-gateway'
import { personalWechatSendService } from './services/personal-wechat-send-service'
@@ -430,6 +529,11 @@ function configureRecallProtection(
recallJournalTimer = null
}
configureRecallArchive(enabled ? accountRoot : '')
/*
* 读取路径必须跟开关一起走:老 recall journal 的合并以前是无条件的,
* 于是「关掉防撤回」对用户等于没关(消息照样在,且不带撤回标记)。
*/
wcdb4Client.setRecallJournalEnabled(enabled)
if (!enabled) return
const monitor = new RecallArchiveMonitor(
@@ -1208,15 +1312,26 @@ app.whenReady().then(async () => {
* 渲染层读状态、群列表变化都不会触发 DDL。
*/
void reconcileMsgInsertRulesOnStart()
/*
* 老防撤回残留收尾:只读扫描 → 有残留才写库(清理走 helper 的可写通道,
* 判定规则与边界见函数注释)。
*/
void cleanupLegacyRecallResidueOnStart()
groupExitMonitorService.setGroupExitHandler((event) => {
/*
* 微信内退群监控消息:一次性往群里插一条本地提示。
* 同一个退群事件按**各自的范围**分发给两个消费者:
*
* 与下面的自动化通知**完全独立**:自己不抛异常(handleExitEvent 内部兜底)、
* 不 await、失败只记日志 —— 插入失败绝不能影响退群监控循环或自动化通知。
* - 微信内退群监控消息:范围 = 全部群聊(开关开着就全覆盖);
* - 自动化退群通知:范围 = 退群监控里勾选的群。
*
* 两者互不依赖:内提示不抛异常、不 await(handleExitEvent 内部兜底),
* 插入失败不会影响自动化通知,反之亦然。
*/
void wechatLocalExitNoticeService.handleExitEvent(event)
if (groupExitMonitorService.isNoticeRoom(event.conversationId)) {
void wechatLocalExitNoticeService.handleExitEvent(event)
}
if (!groupExitMonitorService.isMonitoredRoom(event.conversationId)) return undefined
try {
return getAutomationService()
.handleGroupExit(event)
@@ -1236,6 +1351,8 @@ app.whenReady().then(async () => {
return undefined
}
})
/* 把「微信内退群监控消息」的开关交给 monitor:开着时检测范围扩到全部群聊。 */
syncExitNoticeScope()
messageListener.onMessage((message) => {
// 日志只允许出现「类型 / 群或私聊 / 是否自己发 / @ 数量」这类不可逆标识,
// 不含 wxid、昵称、群名、正文与 source。
@@ -1907,7 +2024,7 @@ app.whenReady().then(async () => {
snapshot.switches.group_exit_notice = eventModeStatus(
'group_exit_notice',
wechatLocalExitNoticeService.isEnabled(),
monitoredRoomCount()
exitNoticeGroupCount()
)
return snapshot
}
@@ -1952,14 +2069,16 @@ app.whenReady().then(async () => {
if (toggled.error) {
return {
success: false,
status: eventModeStatus(name, toggled.enabled, monitoredRoomCount()),
status: eventModeStatus(name, toggled.enabled, exitNoticeGroupCount()),
errorCode: 'UNKNOWN',
message: '保存开关状态失败'
}
}
/* 开关一变,检测范围随之变(开 → 全部群聊;关 → 只剩勾选的群)。 */
syncExitNoticeScope()
return {
success: true,
status: eventModeStatus(name, toggled.enabled, monitoredRoomCount())
status: eventModeStatus(name, toggled.enabled, exitNoticeGroupCount())
}
}
+101 -14
View File
@@ -101,6 +101,15 @@ class GroupExitMonitorService {
private events: GroupExitMonitorEvent[] = []
private monitorSelectionConfigured = true
private monitoredRoomIds = new Set<string>()
/*
* 「微信内退群监控消息」的范围:**全部群聊**,与退群监控勾选的群无关。
*
* 勾选只决定「哪些群的退群走自动化通知」;内提示是面向全体的展示能力。
* 所以这里只持有开关状态 + 全部群 id(随群名刷新一起更新),
* 检测范围取两者的并集 —— 两个消费者都要拿到事件。
*/
private noticeEnabled = false
private allGroupRoomIds = new Set<string>()
private loaded = false
private accountRoot = ''
private groupNamesByRoomId = new Map<string, string>()
@@ -131,6 +140,11 @@ class GroupExitMonitorService {
/** 永久保留的事件总数(`events` 只是最新的一批)。 */
totalEventCount: this.events.length,
enabled: this.enabled,
/*
* 这里仍然按「用户勾选的那套监控」报状态,不掺内提示的范围:
* `running` 同时是本地 Agent API 的可用性判据,改语义会波及它。
* 注意:内提示开着时检测其实也在跑(见 detectionEnabled),只是不算「退群监控在跑」。
*/
running: this.enabled && this.active && chat.isReady(),
nativeMonitorActive: this.nativeMonitorActive,
monitoredGroupCount: this.snapshots.size,
@@ -168,7 +182,7 @@ class GroupExitMonitorService {
this.active = true
this.nativeMonitorActive = nativeMonitorActive
this.checkQueued = false
if (!this.enabled) {
if (!this.detectionEnabled()) {
this.save()
this.broadcast()
return
@@ -194,6 +208,77 @@ class GroupExitMonitorService {
}
}
/**
* 由主进程注入「微信内退群监控消息」开关状态。
*
* 注入的是**开关**而不是群列表:群列表由本服务在刷新群名时一并更新(同一份会话快照),
* 所以群变动后不会过期,上层也不必维护第二份群清单。
*/
setNoticeEnabled(enabled: boolean): void {
this.ensureLoaded()
const next = enabled === true
if (this.noticeEnabled === next) return
this.noticeEnabled = next
this.eventSequence += 1
this.scopeGeneration += 1
this.dropOutOfScopeSnapshots()
this.lastCheckedAt = undefined
this.groupNamesRefreshPending = true
this.broadcast()
if (!this.detectionEnabled() || !chat.isReady()) return
if (!this.active) void this.start(false)
else void this.check()
}
/** 内提示开关是否打开。 */
isNoticeEnabled(): boolean {
return this.noticeEnabled
}
/** 内提示覆盖的群聊数(开关卡片的范围说明用)。 */
getNoticeGroupCount(): number {
return this.allGroupRoomIds.size
}
/** 该房间是否属于内提示范围(= 全部群聊)。 */
isNoticeRoom(roomId: string): boolean {
const normalized = String(roomId || '').trim()
return this.noticeEnabled && this.allGroupRoomIds.has(normalized)
}
/**
* 该房间是否要走自动化通知:**退群监控开着** 且 该房间在勾选范围内。
*
* 保留 `enabled` 这个前提是有意的 —— 关掉退群监控就等于「这些群我不看了」,
* 自动化通知不该因为内提示开关开着而偷偷恢复。
*/
isMonitoredRoom(roomId: string): boolean {
return this.enabled && this.monitoredRoomIds.has(String(roomId || '').trim())
}
/** 检测范围 = 勾选的群 ∪ 内提示覆盖的群。 */
private detectionRoomIds(): Set<string> {
const ids = new Set(this.monitoredRoomIds)
if (this.noticeEnabled) for (const roomId of this.allGroupRoomIds) ids.add(roomId)
return ids
}
/** 是否要继续检测:任一消费者开着就要跑。 */
private detectionEnabled(): boolean {
return this.enabled || this.noticeEnabled
}
/** 丢掉已不在检测范围内的快照(换号、改范围、切开关都会用到)。 */
private dropOutOfScopeSnapshots(): void {
const inScope = this.detectionRoomIds()
for (const roomId of this.snapshots.keys()) {
if (!inScope.has(roomId)) this.snapshots.delete(roomId)
}
for (const roomId of this.hydrationQueue) {
if (!inScope.has(roomId)) this.hydrationQueue.delete(roomId)
}
}
stop(): void {
this.active = false
this.nativeMonitorActive = false
@@ -208,7 +293,7 @@ class GroupExitMonitorService {
}
notifyDatabaseChanged(rawPayload: string): void {
if (!this.enabled || !this.active || !isContactEvent(rawPayload)) return
if (!this.detectionEnabled() || !this.active || !isContactEvent(rawPayload)) return
try {
chat.getChatDb()?.getWcdb4Client().invalidateGroupNicknameCache()
} catch {
@@ -224,7 +309,7 @@ class GroupExitMonitorService {
async checkNow(): Promise<GroupExitMonitorState> {
this.ensureLoaded()
if (!this.enabled) return this.getState()
if (!this.detectionEnabled()) return this.getState()
if (!this.active && chat.isReady()) await this.start(false)
await this.check()
return this.getState()
@@ -261,14 +346,8 @@ class GroupExitMonitorService {
this.eventSequence += 1
this.scopeGeneration += 1
this.monitorSelectionConfigured = true
const nextMonitoredRoomIds = normalizeRoomIds(configuration.monitoredRoomIds || [])
for (const roomId of this.snapshots.keys()) {
if (!nextMonitoredRoomIds.has(roomId)) this.snapshots.delete(roomId)
}
for (const roomId of this.hydrationQueue) {
if (!nextMonitoredRoomIds.has(roomId)) this.hydrationQueue.delete(roomId)
}
this.monitoredRoomIds = nextMonitoredRoomIds
this.monitoredRoomIds = normalizeRoomIds(configuration.monitoredRoomIds || [])
this.dropOutOfScopeSnapshots()
this.groupNamesRefreshPending = true
this.lastCheckedAt = undefined
}
@@ -394,7 +473,12 @@ class GroupExitMonitorService {
const result = await this.readMemberships()
const membershipCostMs = Date.now() - startedAt
let changedGroups = 0
if (result.groups && this.enabled && this.active && scopeGeneration === this.scopeGeneration) {
if (
result.groups &&
this.detectionEnabled() &&
this.active &&
scopeGeneration === this.scopeGeneration
) {
changedGroups = await this.applyCurrentMemberships(result.groups, scopeGeneration)
}
console.log(
@@ -406,7 +490,7 @@ class GroupExitMonitorService {
private async readMemberships(): Promise<MembershipReadResult> {
await this.refreshGroupNamesIfNeeded()
const database = chat.getChatDb()
const roomIds = Array.from(this.monitoredRoomIds)
const roomIds = Array.from(this.detectionRoomIds())
const batchAvailable = chat.isGroupMemberIdsBatchAvailable()
const mode: MembershipMode = batchAvailable ? 'batch' : 'legacy'
if (!database) return { mode, groupCount: roomIds.length, groups: null }
@@ -536,7 +620,7 @@ class GroupExitMonitorService {
}
this.hydrationQueue.delete(roomId)
const baseline = this.snapshots.get(roomId)
if (!baseline || !this.monitoredRoomIds.has(roomId)) {
if (!baseline || !this.detectionRoomIds().has(roomId)) {
this.startNextSnapshotHydration()
return
}
@@ -610,6 +694,9 @@ class GroupExitMonitorService {
const resolved = normalizeKnownGroupName(roomId, name)
if (resolved) this.groupNamesByRoomId.set(roomId, resolved)
}
/* 内提示覆盖的「全部群聊」与群名同源、同频刷新(都是会话表里的群聊),
* 这样群变动后自然跟上,上层不需要再维护第二份群清单。 */
this.allGroupRoomIds = new Set(Object.keys(names || {}))
} catch {
// Session 群名是展示信息;读取失败时继续使用快照中的已知群名。
}
+39 -8
View File
@@ -72,8 +72,8 @@ function ruleName(base: string, roomId: string): string {
const SWITCH_SCOPE: Record<MsgInsertSwitchName, MsgInsertScope> = {
// 防撤回:群聊和私聊都要覆盖,所以目标是「全部可定位会话」
recall_notice: 'all_sessions',
// 退群监控:只作用于退群监控当前选中的群
group_exit_notice: 'monitored_rooms'
// 退群提示:任意群有人退出都要提示,所以目标是「全部群聊」(与退群监控的勾选无关)
group_exit_notice: 'all_group_chats'
}
interface HelperRunResult {
@@ -338,7 +338,8 @@ export interface MsgInsertScopeInput {
/**
* 解析某个开关的目标会话集合。
*
* - group_exit_notice → 退群监控选中的群(复用现有配置,不重新维护第二份群列表)
* - group_exit_notice → 全部群聊(事件驱动:真实范围由 GroupExitMonitorService 持有,
* 退群监控勾选的群只决定「哪些群的退群走自动化通知」)
* - recall_notice → 全部可定位会话(群聊 + 私聊)
*/
export function resolveTargetRooms(
@@ -350,6 +351,27 @@ export function resolveTargetRooms(
const rooms = Array.from(new Set(input.monitoredRoomIds.filter(Boolean)))
return { scope, rooms }
}
if (scope === 'all_group_chats') {
/* 事件驱动型:不装规则,真实范围由 GroupExitMonitorService 持有。
* 这里回一份群聊清单只为状态展示口径一致(调用方不拿它装规则)。 */
try {
const rooms = Array.from(
new Set(
input.client
.getSessions()
.map((session) => String(session.username || '').trim())
.filter((username) => username.endsWith('@chatroom'))
)
)
return { scope, rooms }
} catch (error) {
return {
scope,
rooms: [],
error: error instanceof Error ? error.message : String(error)
}
}
}
try {
const rooms = Array.from(
new Set(
@@ -692,7 +714,7 @@ export async function applyMsgInsertSwitch(
* 微信新建 message_4.db 并把某个目标群的新表放进去时,下一次触发就会自动补上。
*/
export async function reconcileMsgInsertRules(
input: MsgInsertScopeInput & { myWxid: string; databaseKey: string }
input: MsgInsertScopeInput & { myWxid: string; databaseKey: string; extraRooms?: string[] }
): Promise<{ done: boolean; rooms: number; written: number; errorCode?: MsgInsertErrorCode }> {
const helperPath = resolveHelperPath()
if (!helperPath || !input.databaseKey) {
@@ -707,15 +729,24 @@ export async function reconcileMsgInsertRules(
if (shards.length === 0) {
return { done: false, rooms: 0, written: 0, errorCode: 'DATABASE_UNAVAILABLE' }
}
/* 只补退群监控选中的群 —— 防撤回的作用面由「打开开关」那一刻决定,
* 启动时不做全量扫描,避免每次启动都摸一遍全部会话。 */
const rooms = Array.from(new Set(input.monitoredRoomIds.filter(Boolean)))
/*
* 目标会话 = 退群监控选中的群 ∪ 调用方额外指定的会话。
* 清残留与规则定义自愈都复用这条链路,只是换会话集合。
*/
const rooms = Array.from(
new Set([
...input.monitoredRoomIds.filter(Boolean),
...(input.extraRooms || []).filter(Boolean)
])
)
if (rooms.length === 0) return { done: true, rooms: 0, written: 0 }
const run = await runHelper(
helperPath,
['--account-root', accountRootFromShard(shards[0]), '--action', 'ensure-rules'],
{ key: input.databaseKey, rooms, myWxid: input.myWxid }
{ key: input.databaseKey, rooms, myWxid: input.myWxid },
/* 目标会话可能是「全部可定位会话」(几百个),比默认 60s 给宽一点。 */
180_000
)
if (!run.json) {
return { done: false, rooms: rooms.length, written: 0, errorCode: run.errorCode || 'UNKNOWN' }
+136 -1
View File
@@ -458,6 +458,41 @@ export function parseMonitorEvent(rawPayload: string): Wcdb4MonitorEvent {
}
}
/** 老版「防撤回保护」在某个消息分片上留下的残留。 */
export interface LegacyRecallResidueShard {
/** 分片文件名,如 `message_0.db`(不含会话信息,可以进日志)。 */
shard: string
dbPath: string
/** 本应用自己装的抓取触发器:`_wxe_capture_<sha1(表名)[0:16]>` */
triggers: string[]
/** 老日志表:`_wxe_recall_journal_<sha1(表名)[0:16]>` */
journals: string[]
}
export interface LegacyRecallResidueReport {
found: boolean
shards: LegacyRecallResidueShard[]
triggerCount: number
journalCount: number
/**
* 行为分类:`blocking*` 带 `RAISE(IGNORE)`、会吃掉微信写库动作;
* `passive` 只复制行,不改变微信行为。
*/
blockingDeleteCount: number
blockingInsertCount: number
passiveCount: number
}
/**
* 老版防撤回保护(recall journal)的命名规则,安装侧与扫描侧共用。
*/
const LEGACY_RECALL_TRIGGER_PREFIX = '_wxe_capture_'
const LEGACY_RECALL_JOURNAL_PREFIX = '_wxe_recall_journal_'
/**
* 触发器体里必须同时出现这两个列名才算「本应用装的」(安装时写入的私有标记)。
*/
const LEGACY_RECALL_TRIGGER_MARKERS = ['_wxe_source_table', '_wxe_captured_at'] as const
export class Wcdb4Client {
static readonly defaultRoot = Wcdb4Client.findExistingDefaultRoot()
@@ -1191,7 +1226,12 @@ export class Wcdb4Client {
try {
const cursorMessages = this.getMessagesByCursor(username, startTime, endTime, maxRows)
if (cursorMessages && cursorMessages.length > 0) {
const recoveredMessages = this.readRecallJournal(username, startTime, endTime)
/*
* 老 recall journal 的合并必须跟开关联动:无条件合并会让「关掉防撤回」失效。
*/
const recoveredMessages = this.recallJournalEnabled
? this.readRecallJournal(username, startTime, endTime)
: []
const mergedMessages = this.mergeMessageRows(cursorMessages, recoveredMessages, maxRows)
console.log(
`[WCDB4] getMessages cursor ok username=${username} rows=${mergedMessages.length} recovered=${recoveredMessages.length} cost=${Date.now() - startedAt}ms`
@@ -1921,6 +1961,15 @@ export class Wcdb4Client {
}
}
/**
* 老「防撤回保护」(recall journal)是否活动。只影响读取路径,默认 false。
*/
private recallJournalEnabled = false
setRecallJournalEnabled(enabled: boolean): void {
this.recallJournalEnabled = enabled
}
installRecallJournal(usernames: string[]): { installed: number; failed: number } {
const stores = new Map<string, Wcdb4MessageStore>()
for (const username of this.uniq(usernames)) {
@@ -2199,6 +2248,92 @@ export class Wcdb4Client {
.slice(0, 16)}`
}
/**
* 只读扫描:老版防撤回保护在微信库里留下的 `_wxe_capture_*` 触发器与老日志表。
*
* 认领规则(保守:只认本应用装的):触发器名以 `_wxe_capture_` 开头、挂在 `Msg_*`
* 上、且触发器体里同时出现 `_wxe_source_table` / `_wxe_captured_at` 私有列名;
* 表则要求名字以 `_wxe_recall_journal_` 开头。WeFlow 的 `anti_revoke_*`、新机制的
* `_tm_msg_insert_*`、微信自己的触发器都不在结果里。
*
* 顺带按触发器体判行为(blocking* / passive,见返回值)。纯只读;没有残留时不写库。
*/
scanLegacyRecallResidue(): LegacyRecallResidueReport {
const shards: LegacyRecallResidueShard[] = []
let triggerCount = 0
let journalCount = 0
let blockingDeleteCount = 0
let blockingInsertCount = 0
let passiveCount = 0
for (const dbPath of this.listMessageShardPaths()) {
const triggers: string[] = []
const journals: string[] = []
for (const row of this.queryShardSqliteMaster(dbPath)) {
const name = String(row.name || '')
const type = String(row.type || '')
const tblName = String(row.tbl_name || '')
const sql = String(row.sql || '')
if (
type === 'trigger' &&
name.startsWith(LEGACY_RECALL_TRIGGER_PREFIX) &&
/^Msg_/i.test(tblName) &&
LEGACY_RECALL_TRIGGER_MARKERS.every((marker) => sql.includes(marker))
) {
triggers.push(name)
/* 分类只看定义文本,不执行任何语句。合并空白便于匹配多行写法。 */
const normalized = sql.replace(/\s+/g, ' ').toUpperCase()
const blocks = normalized.includes('RAISE(IGNORE)')
if (normalized.includes('BEFORE DELETE')) {
if (blocks) blockingDeleteCount += 1
else passiveCount += 1
} else if (normalized.includes('BEFORE INSERT') && blocks) {
blockingInsertCount += 1
} else {
passiveCount += 1
}
continue
}
if (type === 'table' && name.startsWith(LEGACY_RECALL_JOURNAL_PREFIX)) {
journals.push(name)
}
}
if (triggers.length === 0 && journals.length === 0) continue
triggerCount += triggers.length
journalCount += journals.length
shards.push({ shard: path.basename(dbPath), dbPath, triggers, journals })
}
return {
found: triggerCount > 0 || journalCount > 0,
shards,
triggerCount,
journalCount,
blockingDeleteCount,
blockingInsertCount,
passiveCount
}
}
/*
* DROP 不在本进程做:对分片只有只读连接,发 DDL 必然失败。删除由 native 在其可写
* 连接里顺手完成(见 dll 侧 `_wxe_capture_*` 清理段);调用方只做扫描与复核。
*/
/**
* 读分片 sqlite_master 里可能属于老防撤回的对象。用 GLOB 而非 LIKE:
* `_` 在 LIKE 里是单字符通配,会误伤相似名字。
*/
private queryShardSqliteMaster(dbPath: string): Record<string, unknown>[] {
if (!this.wcdbExecQuery) throw new Error('当前 WCDB 数据服务不支持 SQL 通道')
const sql =
"SELECT name, type, tbl_name, COALESCE(sql, '') AS sql FROM sqlite_master" +
` WHERE (type = 'trigger' AND name GLOB '${LEGACY_RECALL_TRIGGER_PREFIX}*')` +
` OR (type = 'table' AND name GLOB '${LEGACY_RECALL_JOURNAL_PREFIX}*')`
const rows = this.callJson<Record<string, unknown>[]>((handle, outJson) =>
this.wcdbExecQuery!(handle, 'message', dbPath, sql, outJson)
)
return Array.isArray(rows) ? rows : []
}
getMyAvatarUrl(): string | undefined {
const candidates = this.getMyUsernameCandidates()
this.hydrateAvatarUrls(candidates)