feat: 完善聊天导出与档案浏览

1. 修复数据量较大时,历史数据可能无法完整导出的问题
2. 优化分享 Tab 的信息展示,支持小程序、链接、地图等消息
3. 优化系统 Tab 的信息展示,支持红包、转账、拍一拍、撤回等消息
4. 修复默认进入时,时间轴不随消息自动定位的问题
5. 增加“定位到聊天位置”功能
This commit is contained in:
majun.jason
2026-08-05 00:14:28 +08:00
parent 66a6ee3e32
commit 4e84b52cc4
12 changed files with 1615 additions and 75 deletions
+100
View File
@@ -148,6 +148,97 @@ describe('export media', () => {
dom.window.close()
})
it('locates every filtered message kind in all messages, including outside the latest window', () => {
const html = renderExportPage('定位消息')
const dom = new JSDOM(html, { runScripts: 'outside-only' })
const categorized: Message[] = [
{
...messageForArchive('target-text', 'fixture', '定位消息', '目标文字', 1),
type: '普通文本'
},
{
...messageForArchive('target-media', 'fixture', '定位消息', '', 2),
type: '图片',
exportMediaType: 'image',
exportMediaUrl: 'media/target.jpg'
},
{
...messageForArchive('target-voice', 'fixture', '定位消息', '', 3),
type: '语音',
voiceDataUrl: 'voices/target.wav'
},
{
...messageForArchive('target-file', 'fixture', '定位消息', '', 4),
type: '文件',
exportMediaType: 'file',
exportMediaUrl: 'files/target.pdf'
},
{
...messageForArchive('target-share', 'fixture', '定位消息', '', 5),
type: '分享',
contentData: { type: 'share', typeVal: '5', title: '目标分享' }
},
{
...messageForArchive('target-system', 'fixture', '定位消息', '目标系统消息', 6),
from: 'system',
type: '系统消息',
contentData: { type: 'system', content: '目标系统消息' }
}
]
const laterMessages = Array.from({ length: EXPORT_PAGE_SIZE }, (_, index) => ({
...messageForArchive(
`later-${index}`,
'fixture',
'定位消息',
`稍后消息-${index}`,
100 + index
),
type: '普通文本'
}))
Object.assign(dom.window, {
__WECHAT_EXPORT__: {
version: 1,
sourceId: 'fixture',
name: '定位消息',
messages: [...categorized, ...laterMessages]
}
})
dom.window.eval(inlineScriptOf(html))
expect(dom.window.document.querySelectorAll('.locate-all')).toHaveLength(0)
for (const kind of ['media', 'voice', 'file', 'share', 'system']) {
const filterButton = dom.window.document.querySelector(`[data-kind="${kind}"]`) as HTMLElement
filterButton.click()
const locateButton = dom.window.document.querySelector('.locate-all') as HTMLElement
expect(locateButton?.getAttribute('aria-label')).toBe('定位到聊天位置')
expect(locateButton?.querySelector('.locate-icon')?.textContent).toBe('⌖')
expect(locateButton?.querySelector('.locate-label')?.textContent).toBe('定位到聊天位置')
locateButton.click()
expect(
dom.window.document.querySelector('[data-kind="all"]')?.classList.contains('active')
).toBe(true)
expect(
dom.window.document.querySelector('.message.located')?.getAttribute('data-index')
).toBe(String(categorized.findIndex((message) => kindOfFixture(message) === kind)))
}
const textFilter = dom.window.document.querySelector('[data-kind="text"]') as HTMLElement
textFilter.click()
const search = dom.window.document.querySelector('#query') as HTMLInputElement
search.value = '目标文字'
search.dispatchEvent(new dom.window.Event('input'))
;(dom.window.document.querySelector('.locate-all') as HTMLElement).click()
expect(
dom.window.document.querySelector('[data-kind="all"]')?.classList.contains('active')
).toBe(true)
expect(dom.window.document.querySelector('.message.located')?.getAttribute('data-index')).toBe(
'0'
)
expect(dom.window.document.querySelector('.message.located')?.textContent).toContain('目标文字')
dom.window.close()
})
it('keeps relative media, file download, quote, and missing-media renderers', () => {
const html = renderExportPage('媒体档案')
@@ -190,3 +281,12 @@ function messageForArchive(
exportConversationName: conversationName
}
}
function kindOfFixture(message: Message): string {
if (message.exportMediaType === 'image') return 'media'
if (message.voiceDataUrl) return 'voice'
if (message.exportMediaType === 'file') return 'file'
if (message.contentData?.type === 'share') return 'share'
if (message.contentData?.type === 'system') return 'system'
return 'text'
}
+78
View File
@@ -0,0 +1,78 @@
import crypto from 'crypto'
import { mkdirSync, mkdtempSync, writeFileSync } from 'fs'
import { tmpdir } from 'os'
import { join } from 'path'
import { beforeAll, describe, expect, it, vi } from 'vitest'
import type { Message } from '../../src/shared/types'
const state = vi.hoisted(() => ({ userData: '' }))
vi.mock('electron', () => ({
app: { getPath: () => state.userData }
}))
const message = (createTime: number, serverId?: string): Message => ({
id: `message-${createTime}`,
from: 'user',
isSender: false,
type: '普通文本',
datetime: new Date(createTime * 1000).toISOString(),
content: String(createTime),
img: '',
name: 'Jamie',
sessionId: 'fixture-user',
localId: 1,
serverId,
createTime
})
describe('recall archive message identity', () => {
beforeAll(() => {
state.userData = mkdtempSync(join(tmpdir(), 'wxe-recall-identity-'))
})
it('does not collapse messages whose local ids repeat across database shards', async () => {
const accountRoot = '/fixture/account'
const sessionMd5 = 'fixture-session'
const archiveDir = join(state.userData, 'recall-archive')
const archiveName = crypto
.createHash('sha1')
.update(`${process.platform}:${accountRoot}`)
.digest('hex')
.slice(0, 16)
mkdirSync(archiveDir, { recursive: true })
writeFileSync(
join(archiveDir, `${archiveName}.json`),
JSON.stringify({
version: 1,
accountRoot,
updatedAt: Date.now(),
sessions: {
[sessionMd5]: {
username: 'fixture-user',
updatedAt: Date.now(),
messages: [],
recalls: []
}
}
})
)
const { configureRecallArchive, mergeRecallArchiveMessages, messageIdentity } =
await import('../../src/main/services/recall-archive-service')
configureRecallArchive(accountRoot)
const oldMessage = message(1_731_327_263)
const newMessage = message(1_765_000_000)
expect(messageIdentity(oldMessage)).not.toBe(messageIdentity(newMessage))
expect(mergeRecallArchiveMessages(sessionMd5, [oldMessage, newMessage])).toEqual([
oldMessage,
newMessage
])
})
it('prefers the globally unique server id when one is available', async () => {
const { messageIdentity } = await import('../../src/main/services/recall-archive-service')
expect(messageIdentity(message(1_731_327_263, 'server-2024'))).toBe('server:server-2024')
})
})
+17 -2
View File
@@ -1,9 +1,9 @@
import { describe, expect, it, vi } from 'vitest'
import { Wcdb4Client, type Wcdb4Message } from '../../src/main/wcdb4-client'
const message = (id: string, year: number): Wcdb4Message => ({
const message = (id: string, year: number, serverId = `server-${id}`): Wcdb4Message => ({
mesLocalID: id,
serverId: `server-${id}`,
serverId,
mesDes: 0,
messageType: '1',
msgCreateTime: String(Math.floor(Date.UTC(year, 0, 1) / 1000)),
@@ -12,6 +12,21 @@ const message = (id: string, year: number): Wcdb4Message => ({
})
describe('WCDB message shard pagination', () => {
it('keeps messages whose local ids repeat across database shards', async () => {
const cursor = vi.fn(async () => [
message('1', 2024, 'server-2024'),
message('1', 2025, 'server-2025')
])
const client = Object.assign(Object.create(Wcdb4Client.prototype), {
getMessagesByCursorAsync: cursor
}) as Wcdb4Client
const result = await client.getMessagesAsync('fixture@chatroom')
expect(result).toHaveLength(2)
expect(result.map((item) => item.serverId)).toEqual(['server-2024', 'server-2025'])
})
it('merges cursor and all-store rows for a bounded cross-year page', async () => {
const cursor = vi.fn(async () => [message('2025', 2025)])
const tableScan = vi.fn(async () => [message('2017', 2017), message('2025', 2025)])
+71
View File
@@ -0,0 +1,71 @@
import { describe, expect, it, vi } from 'vitest'
import { WechatDb, type WechatMessage } from '../../src/main/wechat-db'
describe('WechatDb normalized messages', () => {
it('keeps normalized identity fields when raw table columns conflict', async () => {
const normalized = {
mesLocalID: '1',
serverId: 'server-1',
mesDes: 0,
messageType: '1',
msgCreateTime: '1731327263',
msgContent: 'fixture',
sender: 'wxid_self',
senderNickname: 'Nanin',
raw: {
mesDes: 1,
sender: '',
senderNickname: ''
}
}
const client = { getMessagesAsync: vi.fn(async () => [normalized]) }
const db = Object.assign(Object.create(WechatDb.prototype), {
wcdb4Client: client,
chatMd5ToUsername: new Map([['fixture-md5', 'fixture-user']]),
ensureChatTableMapping: vi.fn()
}) as WechatDb
const start = Math.floor(new Date(2024, 10, 11).getTime() / 1000)
const end = Math.floor(new Date(2024, 11, 1).getTime() / 1000)
const messages = await db.getUserMessagesForExport('fixture-md5', start, end)
expect(messages[0]).toMatchObject({
mesDes: 0,
sender: 'wxid_self',
senderNickname: 'Nanin'
})
})
it('scans without time bounds, then filters, deduplicates and sorts in application code', async () => {
const row = (id: string, createTime: number): WechatMessage => ({
mesLocalID: id,
serverId: `server-${id}`,
mesDes: 0,
messageType: '1',
msgCreateTime: String(createTime),
msgContent: id,
raw: {}
})
const start = Math.floor(new Date(2025, 0, 1).getTime() / 1000)
const end = Math.floor(new Date(2025, 0, 4).getTime() / 1000)
const shardBoundaryMessage = row('jan-2-boundary', start + 32 * 60 * 60)
const getMessagesAsync = vi.fn(async () => [
row('before-range', start - 1),
row('newest', start + 48 * 60 * 60),
shardBoundaryMessage,
{ ...shardBoundaryMessage },
row('after-range', end + 1)
])
const db = Object.assign(Object.create(WechatDb.prototype), {
wcdb4Client: { getMessagesAsync },
chatMd5ToUsername: new Map([['fixture-md5', 'fixture-user']]),
ensureChatTableMapping: vi.fn()
}) as WechatDb
const messages = await db.getUserMessagesForExport('fixture-md5', start, end)
expect(getMessagesAsync).toHaveBeenCalledOnce()
expect(getMessagesAsync).toHaveBeenCalledWith('fixture-user')
expect(messages.map((message) => message.mesLocalID)).toEqual(['jan-2-boundary', 'newest'])
})
})