diff --git a/electron/services/wcdbCore.ts b/electron/services/wcdbCore.ts index df535fa..4f0d97b 100644 --- a/electron/services/wcdbCore.ts +++ b/electron/services/wcdbCore.ts @@ -2596,13 +2596,34 @@ export class WcdbCore { } } + /** + * 强制重新打开账号连接(绕过路径缓存),用于微信重装后消息数据库刷新失败时的自动恢复。 + * 返回重新打开是否成功。 + */ + private async forceReopen(): Promise { + if (!this.currentPath || !this.currentKey || !this.currentWxid) return false + const path = this.currentPath + const key = this.currentKey + const wxid = this.currentWxid + this.writeLog('forceReopen: clearing cached handle and reopening...', true) + // 清空缓存状态,让 open() 真正重新打开 + try { this.wcdbShutdown() } catch { } + this.handle = null + this.currentPath = null + this.currentKey = null + this.currentWxid = null + this.currentDbStoragePath = null + this.initialized = false + return this.open(path, key, wxid) + } + async openMessageCursor(sessionId: string, batchSize: number, ascending: boolean, beginTimestamp: number, endTimestamp: number): Promise<{ success: boolean; cursor?: number; error?: string }> { if (!this.ensureReady()) { return { success: false, error: 'WCDB 未连接' } } try { const outCursor = [0] - const result = this.wcdbOpenMessageCursor( + let result = this.wcdbOpenMessageCursor( this.handle, sessionId, batchSize, @@ -2611,13 +2632,37 @@ export class WcdbCore { endTimestamp, outCursor ) + // result=-3 表示 WCDB_STATUS_NO_MESSAGE_DB:消息数据库缓存为空(常见于微信重装后) + // 自动强制重连并重试一次 + if (result === -3 && outCursor[0] <= 0) { + this.writeLog('openMessageCursor: result=-3 (no message db), attempting forceReopen...', true) + const reopened = await this.forceReopen() + if (reopened && this.handle !== null) { + outCursor[0] = 0 + result = this.wcdbOpenMessageCursor( + this.handle, + sessionId, + batchSize, + ascending ? 1 : 0, + beginTimestamp, + endTimestamp, + outCursor + ) + this.writeLog(`openMessageCursor retry after forceReopen: result=${result} cursor=${outCursor[0]}`, true) + } else { + this.writeLog('openMessageCursor forceReopen failed, giving up', true) + } + } if (result !== 0 || outCursor[0] <= 0) { await this.printLogs(true) this.writeLog( `openMessageCursor failed: sessionId=${sessionId} batchSize=${batchSize} ascending=${ascending ? 1 : 0} begin=${beginTimestamp} end=${endTimestamp} result=${result} cursor=${outCursor[0]}`, true ) - return { success: false, error: `创建游标失败: ${result},请查看日志` } + const hint = result === -3 + ? `创建游标失败: ${result}(消息数据库未找到)。如果你最近重装过微信,请尝试重新指定数据目录后重试` + : `创建游标失败: ${result},请查看日志` + return { success: false, error: hint } } return { success: true, cursor: outCursor[0] } } catch (e) {