mirror of
https://wget.la/https://github.com/Wxw-Gu/WechatExplorer
synced 2026-08-17 11:37:06 +08:00
feat: 增强 HTML 聊天档案导出
- 增加时间轴、消息筛选、搜索和完整时间显示 - 使用窗口化懒加载优化大消息档案 - 支持同名档案增量合并并安全复用媒体资源
This commit is contained in:
@@ -1,5 +1,5 @@
|
||||
import { dirname, join } from 'path'
|
||||
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'fs'
|
||||
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'fs'
|
||||
import { tmpdir } from 'os'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import type { Message } from '../../src/shared/types'
|
||||
@@ -19,6 +19,7 @@ vi.mock('electron', () => ({
|
||||
}))
|
||||
vi.mock('../../src/main/services/chat-service', () => ({
|
||||
listMessages: () => structuredClone(state.messages),
|
||||
listMessagesAsync: async () => structuredClone(state.messages),
|
||||
getChatDb: () => ({
|
||||
getWcdb4Client: () => ({ getAccountRoot: () => state.accountRoot })
|
||||
}),
|
||||
@@ -92,6 +93,19 @@ const message = (overrides: Partial<Message>): Message => ({
|
||||
...overrides
|
||||
})
|
||||
|
||||
const readArchive = (outputPath: string): { sourceId: string; messages: Message[] } => {
|
||||
const source = readFileSync(join(dirname(outputPath), 'data', 'messages.js'), 'utf8')
|
||||
return JSON.parse(
|
||||
source
|
||||
.slice(source.indexOf('=') + 1)
|
||||
.trim()
|
||||
.replace(/;\s*$/, '')
|
||||
) as {
|
||||
sourceId: string
|
||||
messages: Message[]
|
||||
}
|
||||
}
|
||||
|
||||
describe('media export flow', () => {
|
||||
beforeEach(() => {
|
||||
state.documents = mkdtempSync(join(tmpdir(), 'wxe-export-fixture-'))
|
||||
@@ -167,21 +181,124 @@ describe('media export flow', () => {
|
||||
expect(result.success).toBe(true)
|
||||
const html = readFileSync(result.outputPath!, 'utf8')
|
||||
const outputDir = dirname(result.outputPath!)
|
||||
expect(readFileSync(join(outputDir, 'voices/voice_1_1.wav')).subarray(0, 4).toString()).toBe(
|
||||
const archive = readArchive(result.outputPath!)
|
||||
const voice = archive.messages.find((item) => item.id === 'voice-ok')!
|
||||
const video = archive.messages.find((item) => item.id === 'video')!
|
||||
const file = archive.messages.find((item) => item.id === 'file')!
|
||||
const missingVoice = archive.messages.find((item) => item.id === 'voice-missing')!
|
||||
expect(readFileSync(join(outputDir, voice.voiceDataUrl!)).subarray(0, 4).toString()).toBe(
|
||||
'RIFF'
|
||||
)
|
||||
expect(readFileSync(join(outputDir, 'media/video_4.mp4')).subarray(4, 8).toString()).toBe(
|
||||
expect(readFileSync(join(outputDir, video.exportMediaUrl!)).subarray(4, 8).toString()).toBe(
|
||||
'ftyp'
|
||||
)
|
||||
expect(readFileSync(join(outputDir, 'media/file_5_测试附件.txt'), 'utf8')).toBe('附件内容')
|
||||
expect(html).toContain('src="voices/voice_1_1.wav"')
|
||||
expect(html).toContain('src="media/video_4.mp4"')
|
||||
expect(html).toContain('href="media/file_5_测试附件.txt" download')
|
||||
expect(html).toContain('语音文件缺失:本地未找到语音数据')
|
||||
expect(readFileSync(join(outputDir, file.exportMediaUrl!), 'utf8')).toBe('附件内容')
|
||||
expect(html).toContain('<script src="data/messages.js"></script>')
|
||||
expect(voice.voiceDataUrl).toMatch(/^voices\/voice_[0-9a-f]{16}\.wav$/)
|
||||
expect(video.exportMediaUrl).toMatch(/^media\/video_[0-9a-f]{16}\.mp4$/)
|
||||
expect(file.exportMediaUrl).toMatch(/^media\/file_[0-9a-f]{16}_测试附件\.txt$/)
|
||||
expect(missingVoice.exportMediaError).toBe('语音文件缺失:本地未找到语音数据')
|
||||
expect(state.imageLookups[0]).toMatchObject({
|
||||
allowThumbnail: false,
|
||||
preferThumbnail: false
|
||||
})
|
||||
expect(progress.length).toBeGreaterThan(0)
|
||||
})
|
||||
|
||||
it('incrementally merges the same HTML archive, deduplicates messages, and keeps old media', async () => {
|
||||
const { runExport } = await import('../../src/main/export-service')
|
||||
const win = { isDestroyed: () => true, webContents: { send: vi.fn() } }
|
||||
const request = {
|
||||
jobId: 'incremental-first',
|
||||
userMd5: 'fixture-user',
|
||||
name: '增量会话',
|
||||
format: 'html' as const,
|
||||
outputName: 'incremental-fixture',
|
||||
kinds: ['voice', 'text'] as const,
|
||||
includeMedia: true,
|
||||
keepMissing: true
|
||||
}
|
||||
state.messages = [
|
||||
message({
|
||||
id: 'voice-old',
|
||||
type: '语音',
|
||||
sessionId: 'fixture-session',
|
||||
localId: 1,
|
||||
contentData: { type: 'voice', duration: 1 }
|
||||
}),
|
||||
message({ id: 'text-old', content: '第一次导出', createTime: 1_785_549_660 })
|
||||
]
|
||||
const first = await runExport({ ...request, kinds: [...request.kinds] }, win as never)
|
||||
expect(first.success).toBe(true)
|
||||
const firstArchive = readArchive(first.outputPath!)
|
||||
const oldVoiceUrl = firstArchive.messages.find((item) => item.id === 'voice-old')!.voiceDataUrl
|
||||
|
||||
state.messages = [
|
||||
message({ id: 'text-old', content: '同一条消息已更新', createTime: 1_785_549_660 }),
|
||||
message({ id: 'text-new', content: '第二次新增', createTime: 1_785_549_720 })
|
||||
]
|
||||
const second = await runExport(
|
||||
{
|
||||
...request,
|
||||
jobId: 'incremental-second',
|
||||
kinds: [...request.kinds],
|
||||
includeMedia: false
|
||||
},
|
||||
win as never
|
||||
)
|
||||
expect(second.success).toBe(true)
|
||||
expect(second.outputPath).toBe(first.outputPath)
|
||||
const secondArchive = readArchive(second.outputPath!)
|
||||
expect(secondArchive.messages.map((item) => item.id)).toEqual([
|
||||
'voice-old',
|
||||
'text-old',
|
||||
'text-new'
|
||||
])
|
||||
expect(secondArchive.messages.find((item) => item.id === 'text-old')?.content).toBe(
|
||||
'同一条消息已更新'
|
||||
)
|
||||
expect(secondArchive.messages.find((item) => item.id === 'voice-old')?.voiceDataUrl).toBe(
|
||||
oldVoiceUrl
|
||||
)
|
||||
expect(existsSync(join(dirname(second.outputPath!), 'data', 'messages.js.bak'))).toBe(true)
|
||||
})
|
||||
|
||||
it('refuses to merge a different conversation into an existing named archive', async () => {
|
||||
const { runExport } = await import('../../src/main/export-service')
|
||||
const win = { isDestroyed: () => true, webContents: { send: vi.fn() } }
|
||||
state.messages = [message({ id: 'text', content: 'fixture' })]
|
||||
const baseRequest = {
|
||||
jobId: 'source-first',
|
||||
userMd5: 'first-user',
|
||||
name: '第一个会话',
|
||||
format: 'html' as const,
|
||||
outputName: 'same-name',
|
||||
kinds: ['text'] as const,
|
||||
includeMedia: false
|
||||
}
|
||||
const first = await runExport({ ...baseRequest, kinds: [...baseRequest.kinds] }, win as never)
|
||||
const second = await runExport(
|
||||
{
|
||||
...baseRequest,
|
||||
jobId: 'source-second',
|
||||
userMd5: 'second-user',
|
||||
name: '第二个会话',
|
||||
kinds: [...baseRequest.kinds]
|
||||
},
|
||||
win as never
|
||||
)
|
||||
|
||||
expect(first.success).toBe(true)
|
||||
expect(second.success).toBe(false)
|
||||
expect(second.error).toContain('另一个会话')
|
||||
expect(readArchive(first.outputPath!).sourceId).toBe('first-user')
|
||||
})
|
||||
|
||||
it('uses message content as the stable fallback when the database supplies a random id', async () => {
|
||||
const { exportMessageKey } = await import('../../src/main/export-service')
|
||||
const first = message({ id: '0.123456', content: '同一条无本地 ID 消息' })
|
||||
const second = message({ id: '0.987654', content: '同一条无本地 ID 消息' })
|
||||
|
||||
expect(exportMessageKey(first, 'fixture-user')).toBe(exportMessageKey(second, 'fixture-user'))
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,17 +1,13 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { renderExportPage } from '../../src/main/export-html-template'
|
||||
import { JSDOM } from 'jsdom'
|
||||
import { EXPORT_PAGE_SIZE, renderExportPage } from '../../src/main/export-html-template'
|
||||
import { getImageExportAttempts } from '../../src/shared/export-media'
|
||||
import type { Message } from '../../src/shared/types'
|
||||
|
||||
const baseMessage = (overrides: Partial<Message>): Message => ({
|
||||
id: 'fixture-message',
|
||||
from: 'fixture',
|
||||
type: '文本',
|
||||
datetime: '2026-08-01 10:00:00',
|
||||
content: '',
|
||||
isSender: false,
|
||||
...overrides
|
||||
})
|
||||
const inlineScriptOf = (html: string): string =>
|
||||
Array.from(html.matchAll(/<script(?:\s[^>]*)?>([\s\S]*?)<\/script>/g))
|
||||
.map((match) => match[1].trim())
|
||||
.find(Boolean) || ''
|
||||
|
||||
describe('export media', () => {
|
||||
it('always attempts the original before an explicitly enabled thumbnail fallback', () => {
|
||||
@@ -25,47 +21,85 @@ describe('export media', () => {
|
||||
expect(repeated).toEqual(first)
|
||||
})
|
||||
|
||||
it('renders movable relative audio and video assets plus accurate missing-media details', () => {
|
||||
const html = renderExportPage('脱敏导出', [
|
||||
baseMessage({ id: 'voice', type: '语音', voiceDataUrl: 'voices/voice_1.wav' }),
|
||||
baseMessage({
|
||||
id: 'video',
|
||||
type: '视频',
|
||||
exportMediaType: 'video',
|
||||
exportMediaUrl: 'media/video_2.mp4'
|
||||
}),
|
||||
baseMessage({
|
||||
id: 'missing',
|
||||
type: '语音',
|
||||
exportMediaError: '语音文件缺失:本地未找到语音数据'
|
||||
}),
|
||||
baseMessage({
|
||||
id: 'file',
|
||||
type: '文件',
|
||||
contentData: { type: 'share', typeVal: '6', title: '示例附件.zip', url: '' },
|
||||
exportMediaType: 'file',
|
||||
exportMediaName: '示例附件.zip',
|
||||
exportMediaUrl: 'media/file_4_示例附件.zip'
|
||||
})
|
||||
])
|
||||
it('loads archive data and provides timeline, filters, search, and bounded lazy rendering', () => {
|
||||
const html = renderExportPage('脱敏导出')
|
||||
|
||||
expect(html).toContain(
|
||||
'audio class="audio" controls preload="metadata" src="voices/voice_1.wav"'
|
||||
expect(EXPORT_PAGE_SIZE).toBe(240)
|
||||
expect(html).toContain('<script src="data/messages.js"></script>')
|
||||
expect(html).toContain('aria-label="聊天时间轴"')
|
||||
expect(html).toContain('data-kind="media"')
|
||||
expect(html).toContain('placeholder="搜索发送者或消息内容…"')
|
||||
expect(html).toContain('filtered.slice(windowStart, windowEnd)')
|
||||
expect(html).toContain('windowStart = Math.max(0, windowEnd - PAGE_SIZE)')
|
||||
expect(html).toContain('date.getSeconds()')
|
||||
const inlineScript = inlineScriptOf(html)
|
||||
expect(inlineScript).toBeTruthy()
|
||||
expect(() => new Function(inlineScript)).not.toThrow()
|
||||
})
|
||||
|
||||
it('initially renders only one page and searches the full archive dataset', () => {
|
||||
const html = renderExportPage('大量消息')
|
||||
const dom = new JSDOM(html, { runScripts: 'outside-only' })
|
||||
const messages = Array.from(
|
||||
{ length: 500 },
|
||||
(_, index): Message => ({
|
||||
id: `message-${index}`,
|
||||
from: 'user',
|
||||
type: '普通文本',
|
||||
datetime: '',
|
||||
content: index % 100 === 0 ? `needle-${index}` : `普通消息-${index}`,
|
||||
isSender: false,
|
||||
createTime: 1_767_225_600 + index * 86_400
|
||||
})
|
||||
)
|
||||
expect(html).toContain('video class="media-image" controls src="media/video_2.mp4"')
|
||||
expect(html).toContain('语音文件缺失:本地未找到语音数据')
|
||||
expect(html).toContain('class="file-attachment" href="media/file_4_示例附件.zip" download')
|
||||
Object.assign(dom.window, {
|
||||
__WECHAT_EXPORT__: {
|
||||
version: 1,
|
||||
sourceId: 'fixture',
|
||||
name: '大量消息',
|
||||
exportedAt: '2026-08-04T00:00:00.000Z',
|
||||
messages
|
||||
}
|
||||
})
|
||||
|
||||
dom.window.eval(inlineScriptOf(html))
|
||||
|
||||
expect(dom.window.document.querySelectorAll('.message')).toHaveLength(EXPORT_PAGE_SIZE)
|
||||
expect(dom.window.document.querySelector('#count')?.textContent).toBe(
|
||||
'已显示 240 / 筛选 500 / 全部 500'
|
||||
)
|
||||
const list = dom.window.document.querySelector('#messages')!
|
||||
for (let index = 0; index < 5; index += 1) {
|
||||
list.dispatchEvent(new dom.window.Event('scroll'))
|
||||
expect(dom.window.document.querySelectorAll('.message').length).toBeLessThanOrEqual(
|
||||
EXPORT_PAGE_SIZE
|
||||
)
|
||||
}
|
||||
const search = dom.window.document.querySelector('#query') as HTMLInputElement
|
||||
search.value = 'needle'
|
||||
search.dispatchEvent(new dom.window.Event('input'))
|
||||
expect(dom.window.document.querySelectorAll('.message')).toHaveLength(5)
|
||||
expect(dom.window.document.querySelectorAll('.timeline-month').length).toBeGreaterThan(1)
|
||||
dom.window.close()
|
||||
})
|
||||
|
||||
it('keeps relative media, file download, quote, and missing-media renderers', () => {
|
||||
const html = renderExportPage('媒体档案')
|
||||
|
||||
expect(html).toContain('audio class="audio" controls preload="metadata"')
|
||||
expect(html).toContain('video class="media-image" controls preload="metadata"')
|
||||
expect(html).toContain('class="file-attachment" href="')
|
||||
expect(html).toContain('class="quote-reference"')
|
||||
expect(html).toContain('message.exportMediaError')
|
||||
expect(html).not.toMatch(/(?:src|href)="[A-Za-z]:\\/)
|
||||
})
|
||||
|
||||
it('renders explicit and keyboard-accessible lightbox closing controls', () => {
|
||||
const html = renderExportPage('图片预览', [
|
||||
baseMessage({ id: 'image', type: '图片', exportMediaUrl: 'media/image.jpg' })
|
||||
])
|
||||
const html = renderExportPage('图片预览')
|
||||
|
||||
expect(html).toContain('aria-label="关闭图片预览"')
|
||||
expect(html).toContain("closeButton.addEventListener('click',closeLightbox)")
|
||||
expect(html).toContain('if(event.target===box)closeLightbox()')
|
||||
expect(html).toContain("if(event.key==='Escape')closeLightbox()")
|
||||
expect(html).toContain("closeButton.addEventListener('click', closeLightbox)")
|
||||
expect(html).toContain('if (event.target === box) closeLightbox()')
|
||||
expect(html).toContain("if (event.key === 'Escape') closeLightbox()")
|
||||
})
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user