mirror of
https://wget.la/https://github.com/Wxw-Gu/WechatExplorer
synced 2026-08-17 03:27:00 +08:00
feat: 支持多聊天合并导出
This commit is contained in:
@@ -0,0 +1,162 @@
|
||||
import { render, screen, waitFor } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { ExportWorkspace } from '../../src/renderer/src/components/export/ExportWorkspace'
|
||||
import { ExportTaskCenter } from '../../src/renderer/src/components/export/ExportTaskCenter'
|
||||
import type { ExportTaskRecord } from '../../src/shared/export'
|
||||
import type { Contact, Message } from '../../src/shared/types'
|
||||
|
||||
const contacts: Contact[] = Array.from({ length: 6 }, (_, index) => ({
|
||||
md5: `contact-${index + 1}`,
|
||||
m_nsUsrName: `wxid_contact_${index + 1}`,
|
||||
m_nsNickName: `聊天 ${String.fromCharCode(65 + index)}`,
|
||||
type: index === 2 ? 'group' : 'user'
|
||||
}))
|
||||
|
||||
const previewMessage = (contact: Contact): Message => ({
|
||||
id: `preview-${contact.md5}`,
|
||||
from: 'user',
|
||||
type: '普通文本',
|
||||
datetime: '',
|
||||
content: `${contact.m_nsNickName} 的预览`,
|
||||
isSender: false,
|
||||
createTime: contacts.indexOf(contact) + 1
|
||||
})
|
||||
|
||||
describe('ExportWorkspace multi-chat selection', () => {
|
||||
beforeEach(() => {
|
||||
Object.defineProperty(window, 'api', {
|
||||
configurable: true,
|
||||
value: {
|
||||
onExportProgress: vi.fn(() => vi.fn()),
|
||||
getGroupSnapshot: vi.fn(async () => ({ members: [] })),
|
||||
cancelExport: vi.fn(async () => ({ success: true })),
|
||||
revealExport: vi.fn(async () => ({ success: true }))
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
const renderWorkspace = (
|
||||
onStartExport = vi.fn(async () => ({ success: false }))
|
||||
): { loadPreviewMessages: ReturnType<typeof vi.fn> } => {
|
||||
const loadPreviewMessages = vi.fn(async (contact: Contact) => [previewMessage(contact)])
|
||||
render(
|
||||
<ExportWorkspace
|
||||
contacts={contacts}
|
||||
initialContact={contacts[0]}
|
||||
selfInfo={{ wxid: 'self', nickname: '本人', accountRoot: '/fixture' }}
|
||||
dbReady
|
||||
loadPreviewMessages={loadPreviewMessages}
|
||||
onOpenSettings={vi.fn()}
|
||||
exportTasks={[]}
|
||||
onStartExport={onStartExport}
|
||||
onCancelExport={vi.fn(async () => undefined)}
|
||||
/>
|
||||
)
|
||||
return { loadPreviewMessages }
|
||||
}
|
||||
|
||||
it('defaults to one chat, forces HTML after adding another, merges the preview, and resets locally', async () => {
|
||||
const onStartExport = vi.fn(async () => ({ success: false }))
|
||||
const { loadPreviewMessages } = renderWorkspace(onStartExport)
|
||||
|
||||
expect(screen.getAllByText('聊天 A')).toHaveLength(2)
|
||||
expect(screen.getByRole('button', { name: 'CSV' })).toBeEnabled()
|
||||
expect(await screen.findByText('聊天 A 的预览')).toBeVisible()
|
||||
|
||||
await userEvent.click(screen.getByRole('button', { name: '+ 添加聊天' }))
|
||||
await userEvent.click(screen.getByRole('button', { name: /聊天 B/ }))
|
||||
|
||||
expect(screen.getByText('已选 2 / 5 个')).toBeVisible()
|
||||
expect(screen.getByRole('button', { name: 'CSV' })).toBeDisabled()
|
||||
expect(screen.getByRole('button', { name: 'JSON' })).toBeDisabled()
|
||||
expect(screen.getByRole('button', { name: 'Markdown' })).toBeDisabled()
|
||||
expect(screen.getByRole('button', { name: /HTML/ })).toHaveClass('active')
|
||||
expect(await screen.findByText('聊天 B 的预览')).toBeVisible()
|
||||
expect(screen.getByText('2 个聊天 · 合并预览')).toBeVisible()
|
||||
|
||||
await userEvent.click(screen.getByRole('button', { name: '开始导出' }))
|
||||
await waitFor(() => expect(onStartExport).toHaveBeenCalledOnce())
|
||||
expect(onStartExport.mock.calls[0][0]).toMatchObject({
|
||||
format: 'html',
|
||||
outputName: '聊天 A等2个聊天_合并档案',
|
||||
targets: [
|
||||
{ userMd5: 'contact-1', name: '聊天 A' },
|
||||
{ userMd5: 'contact-2', name: '聊天 B' }
|
||||
]
|
||||
})
|
||||
|
||||
await userEvent.click(screen.getByRole('button', { name: '恢复默认' }))
|
||||
expect(screen.queryByText('已选 2 / 5 个')).not.toBeInTheDocument()
|
||||
expect(screen.getByRole('button', { name: 'CSV' })).toBeEnabled()
|
||||
expect(screen.getAllByText('聊天 A').length).toBeGreaterThanOrEqual(2)
|
||||
expect(loadPreviewMessages).toHaveBeenCalledWith(contacts[0])
|
||||
expect(contacts[0].md5).toBe('contact-1')
|
||||
})
|
||||
|
||||
it('does not allow removing the last chat and disables unselected chats at five', async () => {
|
||||
renderWorkspace()
|
||||
await userEvent.click(screen.getByRole('button', { name: '+ 添加聊天' }))
|
||||
|
||||
await userEvent.click(screen.getByRole('button', { name: /聊天 A/ }))
|
||||
expect(screen.getByText('已选 1 / 5 个')).toBeVisible()
|
||||
|
||||
for (const name of ['聊天 B', '聊天 C', '聊天 D', '聊天 E']) {
|
||||
await userEvent.click(screen.getByRole('button', { name: new RegExp(name) }))
|
||||
}
|
||||
expect(screen.getByText('已选 5 / 5 个')).toBeVisible()
|
||||
expect(screen.getByRole('button', { name: /聊天 F/ })).toBeDisabled()
|
||||
|
||||
await userEvent.click(screen.getByRole('button', { name: /聊天 B/ }))
|
||||
expect(screen.getByText('已选 4 / 5 个')).toBeVisible()
|
||||
expect(screen.getByRole('button', { name: /聊天 F/ })).toBeEnabled()
|
||||
})
|
||||
})
|
||||
|
||||
describe('ExportTaskCenter details', () => {
|
||||
it('shows the exported message count for success and the reason for failure', () => {
|
||||
const tasks: ExportTaskRecord[] = [
|
||||
{
|
||||
jobId: 'success',
|
||||
targetIds: ['contact-1'],
|
||||
targetNames: ['聊天 A'],
|
||||
targetLabel: '聊天 A',
|
||||
format: 'html',
|
||||
status: 'completed',
|
||||
progress: {
|
||||
jobId: 'success',
|
||||
phase: 'completed',
|
||||
processed: 125,
|
||||
total: 125,
|
||||
percent: 100
|
||||
},
|
||||
createdAt: 1
|
||||
},
|
||||
{
|
||||
jobId: 'failure',
|
||||
targetIds: ['contact-1', 'contact-2'],
|
||||
targetNames: ['聊天 A', '聊天 B'],
|
||||
targetLabel: '聊天 A 等 2 个聊天',
|
||||
format: 'html',
|
||||
status: 'failed',
|
||||
progress: {
|
||||
jobId: 'failure',
|
||||
phase: 'failed',
|
||||
processed: 0,
|
||||
percent: 0,
|
||||
error: '视频文件没有写入权限'
|
||||
},
|
||||
createdAt: 2
|
||||
}
|
||||
]
|
||||
|
||||
render(
|
||||
<ExportTaskCenter open taskCount={0} tasks={tasks} onToggle={vi.fn()} onCancel={vi.fn()} />
|
||||
)
|
||||
|
||||
expect(screen.getByText('HTML · 已完成')).toBeVisible()
|
||||
expect(screen.getByText('成功导出 125 条消息')).toBeVisible()
|
||||
expect(screen.getByText('HTML · 导出失败')).toBeVisible()
|
||||
expect(screen.getByText('失败原因:视频文件没有写入权限')).toBeVisible()
|
||||
})
|
||||
})
|
||||
@@ -114,6 +114,38 @@ test('NAV-01 NAV-02 every top-level page is unique and switchable', async () =>
|
||||
}
|
||||
})
|
||||
|
||||
test('EXPORT-01 multi-chat selection stays local to export and forces HTML', async () => {
|
||||
const fixture = await launchTestApp()
|
||||
try {
|
||||
const navigation = fixture.page.getByRole('navigation', { name: '一级导航' })
|
||||
await fixture.page.getByRole('button', { name: '联系人 (1)' }).click()
|
||||
await fixture.page.getByText('文件传输助手', { exact: true }).click()
|
||||
await expect(fixture.page.getByText('转发多条内容', { exact: true })).toBeVisible()
|
||||
|
||||
await navigation.getByRole('button', { name: '导出' }).click()
|
||||
const contactList = fixture.page.locator('.export-contact-list')
|
||||
await expect(contactList.getByRole('button', { name: /文件传输助手/ })).toHaveAttribute(
|
||||
'aria-pressed',
|
||||
'true'
|
||||
)
|
||||
await fixture.page.getByRole('button', { name: '+ 添加聊天' }).click()
|
||||
await contactList.getByRole('button', { name: /产品测试群/ }).click()
|
||||
|
||||
await expect(fixture.page.getByText('已选 2 / 5 个')).toBeVisible()
|
||||
await expect(fixture.page.getByRole('button', { name: 'CSV' })).toBeDisabled()
|
||||
await expect(fixture.page.getByRole('button', { name: /HTML/ })).toHaveClass(/active/)
|
||||
await expect(fixture.page.getByText('2 个聊天 · 合并预览')).toBeVisible()
|
||||
await expect(
|
||||
fixture.page.locator('.export-preview-bubble').filter({ hasText: '这是一条脱敏测试消息' })
|
||||
).toBeVisible()
|
||||
|
||||
await navigation.getByRole('button', { name: '档案' }).click()
|
||||
await expect(fixture.page.getByText('转发多条内容', { exact: true })).toBeVisible()
|
||||
} finally {
|
||||
await fixture.close()
|
||||
}
|
||||
})
|
||||
|
||||
test('ARCH-01 ARCH-02 folded chats and supported message types are represented explicitly', async () => {
|
||||
const fixture = await launchTestApp()
|
||||
try {
|
||||
|
||||
@@ -0,0 +1,170 @@
|
||||
import { expect, test } from '@playwright/test'
|
||||
import { execFileSync } from 'child_process'
|
||||
import { createWriteStream, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'fs'
|
||||
import { tmpdir } from 'os'
|
||||
import { dirname, join } from 'path'
|
||||
import { pathToFileURL } from 'url'
|
||||
import { ZipArchive } from 'archiver'
|
||||
import { renderExportPage } from '../../src/main/export-html-template'
|
||||
import type { Message } from '../../src/shared/types'
|
||||
|
||||
const archiveMessage = (
|
||||
id: string,
|
||||
conversationId: string,
|
||||
conversationName: string,
|
||||
content: string,
|
||||
createTime: number
|
||||
): Message => ({
|
||||
id,
|
||||
from: 'user',
|
||||
type: '普通文本',
|
||||
datetime: '',
|
||||
content,
|
||||
isSender: false,
|
||||
name: '脱敏成员',
|
||||
createTime,
|
||||
exportConversationId: conversationId,
|
||||
exportConversationName: conversationName
|
||||
})
|
||||
|
||||
const zipDirectory = async (
|
||||
sourceDir: string,
|
||||
zipPath: string,
|
||||
folderName: string
|
||||
): Promise<void> => {
|
||||
const output = createWriteStream(zipPath)
|
||||
const archive = new ZipArchive({ zlib: { level: 6 } })
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
output.on('close', resolve)
|
||||
output.on('error', reject)
|
||||
archive.on('error', reject)
|
||||
archive.pipe(output)
|
||||
archive.directory(sourceDir, folderName)
|
||||
void archive.finalize().catch(reject)
|
||||
})
|
||||
}
|
||||
|
||||
test('EXPORT-ARCHIVE-01 merged v2 archive is usable offline on desktop and mobile', async ({
|
||||
page
|
||||
}, testInfo) => {
|
||||
const fixtureRoot = mkdtempSync(join(tmpdir(), 'wxe-merged-archive-e2e-'))
|
||||
const outputDir = join(fixtureRoot, 'source')
|
||||
try {
|
||||
const dataPath = join(outputDir, 'data', 'messages.js')
|
||||
mkdirSync(dirname(dataPath), { recursive: true })
|
||||
writeFileSync(join(outputDir, 'index.html'), renderExportPage('合并聊天档案'), 'utf8')
|
||||
writeFileSync(
|
||||
dataPath,
|
||||
`window.__WECHAT_EXPORT__ = ${JSON.stringify({
|
||||
version: 2,
|
||||
name: '合并聊天档案',
|
||||
exportedAt: '2026-08-04T00:00:00.000Z',
|
||||
conversations: [
|
||||
{ id: 'alpha', name: '项目群', type: 'group', messageCount: 2 },
|
||||
{ id: 'beta', name: '文件传输助手', type: 'user', messageCount: 1 }
|
||||
],
|
||||
messages: [
|
||||
archiveMessage('alpha-1', 'alpha', '项目群', '项目群第一条', 1_764_547_200),
|
||||
archiveMessage('beta-1', 'beta', '文件传输助手', '个人聊天消息', 1_769_904_000),
|
||||
archiveMessage('alpha-2', 'alpha', '项目群', '项目群第二条', 1_769_990_400)
|
||||
]
|
||||
})};\n`,
|
||||
'utf8'
|
||||
)
|
||||
const zipPath = join(fixtureRoot, 'merged-archive.zip')
|
||||
const extractedDir = join(fixtureRoot, 'extracted')
|
||||
await zipDirectory(outputDir, zipPath, '合并聊天档案')
|
||||
mkdirSync(extractedDir, { recursive: true })
|
||||
execFileSync('unzip', ['-q', zipPath, '-d', extractedDir])
|
||||
const offlineIndex = join(extractedDir, '合并聊天档案', 'index.html')
|
||||
|
||||
await page.setViewportSize({ width: 1440, height: 900 })
|
||||
await page.goto(pathToFileURL(offlineIndex).href)
|
||||
const conversationSelect = page.getByLabel('筛选聊天')
|
||||
await expect(conversationSelect).toHaveValue('all')
|
||||
await expect(conversationSelect.locator('option')).toHaveCount(3)
|
||||
await expect(page.locator('#archive-title')).toBeHidden()
|
||||
await expect(page.locator('.archive-heading #conversation-filter')).toBeVisible()
|
||||
await expect(page.locator('#archive-meta')).toHaveText(/^更新于 /)
|
||||
await expect(page.locator('#archive-meta')).not.toContainText('条消息')
|
||||
await expect(page.locator('.message')).toHaveCount(3)
|
||||
await expect(page.locator('.conversation-source')).toHaveCount(3)
|
||||
expect(
|
||||
await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth)
|
||||
).toBe(true)
|
||||
await page.screenshot({ path: testInfo.outputPath('merged-archive-1440.png'), fullPage: true })
|
||||
|
||||
await conversationSelect.selectOption('beta')
|
||||
await expect(page.locator('.message')).toHaveCount(1)
|
||||
await expect(page.locator('.conversation-source')).toHaveCount(0)
|
||||
|
||||
await conversationSelect.selectOption('all')
|
||||
await page.setViewportSize({ width: 390, height: 844 })
|
||||
await expect(page.locator('.timeline-year')).toHaveCount(2)
|
||||
await expect(page.locator('.timeline-year').first()).toBeVisible()
|
||||
await expect(page.locator('.timeline-year').first()).toHaveText('2025 年')
|
||||
const positions = await page.evaluate(() => {
|
||||
const conversations = document.querySelector('#conversation-filter')!.getBoundingClientRect()
|
||||
const toolbar = document.querySelector('.toolbar')!.getBoundingClientRect()
|
||||
const timeline = document.querySelector('#timeline')!.getBoundingClientRect()
|
||||
return {
|
||||
conversationTop: conversations.top,
|
||||
conversationBottom: conversations.bottom,
|
||||
toolbarTop: toolbar.top,
|
||||
toolbarBottom: toolbar.bottom,
|
||||
timelineTop: timeline.top,
|
||||
documentWidth: document.documentElement.scrollWidth,
|
||||
viewportWidth: window.innerWidth
|
||||
}
|
||||
})
|
||||
expect(positions.conversationTop).toBeGreaterThanOrEqual(positions.toolbarTop)
|
||||
expect(positions.conversationBottom).toBeLessThanOrEqual(positions.toolbarBottom)
|
||||
expect(positions.timelineTop).toBeGreaterThanOrEqual(positions.toolbarBottom)
|
||||
expect(positions.documentWidth).toBeLessThanOrEqual(positions.viewportWidth)
|
||||
await expect(page.locator('.message')).toHaveCount(3)
|
||||
await page.screenshot({ path: testInfo.outputPath('merged-archive-390.png'), fullPage: true })
|
||||
} finally {
|
||||
rmSync(fixtureRoot, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
test('EXPORT-ARCHIVE-02 legacy single-chat archive keeps its original layout', async ({
|
||||
page
|
||||
}, testInfo) => {
|
||||
const outputDir = mkdtempSync(join(tmpdir(), 'wxe-single-archive-e2e-'))
|
||||
try {
|
||||
const dataPath = join(outputDir, 'data', 'messages.js')
|
||||
mkdirSync(dirname(dataPath), { recursive: true })
|
||||
writeFileSync(join(outputDir, 'index.html'), renderExportPage('单聊天档案'), 'utf8')
|
||||
writeFileSync(
|
||||
dataPath,
|
||||
`window.__WECHAT_EXPORT__ = ${JSON.stringify({
|
||||
version: 1,
|
||||
sourceId: 'single',
|
||||
name: '单聊天档案',
|
||||
exportedAt: '2026-08-04T00:00:00.000Z',
|
||||
messages: [archiveMessage('single-1', 'single', '单聊天档案', '单聊天消息', 1_767_225_600)]
|
||||
})};\n`,
|
||||
'utf8'
|
||||
)
|
||||
|
||||
await page.setViewportSize({ width: 1440, height: 900 })
|
||||
await page.goto(pathToFileURL(join(outputDir, 'index.html')).href)
|
||||
await expect(page.locator('#conversation-filter')).toBeHidden()
|
||||
await expect(page.locator('#archive-title')).toBeVisible()
|
||||
await expect(page.locator('#archive-title')).toHaveText('单聊天档案')
|
||||
await expect(page.locator('#archive-meta')).toContainText('1 条消息 · 更新于 ')
|
||||
await expect(page.locator('.archive-layout')).toHaveClass(/single-conversation/)
|
||||
await expect(page.locator('.message')).toHaveCount(1)
|
||||
await page.screenshot({ path: testInfo.outputPath('single-archive-1440.png'), fullPage: true })
|
||||
|
||||
await page.setViewportSize({ width: 390, height: 844 })
|
||||
expect(
|
||||
await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth)
|
||||
).toBe(true)
|
||||
await expect(page.locator('.message')).toHaveCount(1)
|
||||
await page.screenshot({ path: testInfo.outputPath('single-archive-390.png'), fullPage: true })
|
||||
} finally {
|
||||
rmSync(outputDir, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
@@ -1,7 +1,19 @@
|
||||
import { dirname, join } from 'path'
|
||||
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'fs'
|
||||
import {
|
||||
chmodSync,
|
||||
existsSync,
|
||||
mkdirSync,
|
||||
mkdtempSync,
|
||||
readFileSync,
|
||||
readdirSync,
|
||||
rmSync,
|
||||
statSync,
|
||||
writeFileSync
|
||||
} from 'fs'
|
||||
import { tmpdir } from 'os'
|
||||
import { execFileSync } from 'child_process'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import type { ExportTarget } from '../../src/shared/export'
|
||||
import type { Message } from '../../src/shared/types'
|
||||
|
||||
const state = vi.hoisted(() => ({
|
||||
@@ -9,6 +21,7 @@ const state = vi.hoisted(() => ({
|
||||
accountRoot: '',
|
||||
videoPath: '',
|
||||
messages: [] as Message[],
|
||||
messagesByUser: {} as Record<string, Message[]>,
|
||||
imageLookups: [] as {
|
||||
allowThumbnail?: boolean
|
||||
preferThumbnail?: boolean
|
||||
@@ -25,7 +38,8 @@ vi.mock('electron', () => ({
|
||||
}))
|
||||
vi.mock('../../src/main/services/chat-service', () => ({
|
||||
listMessages: () => structuredClone(state.messages),
|
||||
listMessagesAsync: async () => structuredClone(state.messages),
|
||||
listMessagesAsync: async (userMd5: string) =>
|
||||
structuredClone(state.messagesByUser[userMd5] || state.messages),
|
||||
getChatDb: () => ({
|
||||
getWcdb4Client: () => ({ getAccountRoot: () => state.accountRoot })
|
||||
}),
|
||||
@@ -129,17 +143,26 @@ const message = (overrides: Partial<Message>): Message => ({
|
||||
...overrides
|
||||
})
|
||||
|
||||
const readArchive = (outputPath: string): { sourceId: string; messages: Message[] } => {
|
||||
const target = (userMd5 = 'fixture-user', name = '脱敏会话'): ExportTarget => ({
|
||||
userMd5,
|
||||
name,
|
||||
type: 'user'
|
||||
})
|
||||
|
||||
const readArchive = (
|
||||
outputPath: string
|
||||
): {
|
||||
version: 2
|
||||
conversations: { id: string; name: string; avatarUrl?: string; messageCount: number }[]
|
||||
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', () => {
|
||||
@@ -152,6 +175,7 @@ describe('media export flow', () => {
|
||||
Buffer.from('000000186674797069736f6d0000020069736f6d69736f32', 'hex')
|
||||
)
|
||||
state.imageLookups = []
|
||||
state.messagesByUser = {}
|
||||
const fileMonth = join(state.accountRoot, 'msg', 'file', '2026-08')
|
||||
mkdirSync(fileMonth, { recursive: true })
|
||||
writeFileSync(join(fileMonth, '测试附件.txt'), '附件内容')
|
||||
@@ -201,8 +225,7 @@ describe('media export flow', () => {
|
||||
const result = await runExport(
|
||||
{
|
||||
jobId: 'fixture-export',
|
||||
userMd5: 'fixture-user',
|
||||
name: '脱敏会话',
|
||||
targets: [target()],
|
||||
format: 'html',
|
||||
outputName: 'fixture',
|
||||
kinds: ['voice', 'image', 'video', 'file'],
|
||||
@@ -249,8 +272,7 @@ describe('media export flow', () => {
|
||||
const win = { isDestroyed: () => true, webContents: { send: vi.fn() } }
|
||||
const request = {
|
||||
jobId: 'incremental-first',
|
||||
userMd5: 'fixture-user',
|
||||
name: '增量会话',
|
||||
targets: [target('fixture-user', '增量会话')],
|
||||
format: 'html' as const,
|
||||
outputName: 'incremental-fixture',
|
||||
kinds: ['voice', 'text'] as const,
|
||||
@@ -302,14 +324,245 @@ describe('media export flow', () => {
|
||||
expect(existsSync(join(dirname(second.outputPath!), 'data', 'messages.js.bak'))).toBe(true)
|
||||
})
|
||||
|
||||
it('keeps copied videos writable and can replace a legacy read-only video incrementally', async () => {
|
||||
const { runExport } = await import('../../src/main/export-service')
|
||||
const win = { isDestroyed: () => true, webContents: { send: vi.fn() } }
|
||||
chmodSync(state.videoPath, 0o444)
|
||||
state.messages = [
|
||||
message({
|
||||
id: 'read-only-video',
|
||||
type: '视频',
|
||||
contentData: { type: 'video', md5: 'b'.repeat(32) }
|
||||
})
|
||||
]
|
||||
const request = {
|
||||
targets: [target('fixture-user', '只读视频会话')],
|
||||
format: 'html' as const,
|
||||
outputName: 'read-only-video-fixture',
|
||||
kinds: ['video'] as const,
|
||||
includeMedia: true
|
||||
}
|
||||
|
||||
const first = await runExport(
|
||||
{ ...request, jobId: 'read-only-video-first', kinds: [...request.kinds] },
|
||||
win as never
|
||||
)
|
||||
expect(first.success, first.error).toBe(true)
|
||||
const firstArchive = readArchive(first.outputPath!)
|
||||
const videoPath = join(
|
||||
dirname(first.outputPath!),
|
||||
firstArchive.messages[0].exportMediaUrl as string
|
||||
)
|
||||
expect(statSync(videoPath).mode & 0o777).toBe(0o644)
|
||||
|
||||
chmodSync(videoPath, 0o444)
|
||||
const second = await runExport(
|
||||
{ ...request, jobId: 'read-only-video-second', kinds: [...request.kinds] },
|
||||
win as never
|
||||
)
|
||||
|
||||
expect(second.success, second.error).toBe(true)
|
||||
expect(second.outputPath).toBe(first.outputPath)
|
||||
expect(statSync(videoPath).mode & 0o777).toBe(0o644)
|
||||
})
|
||||
|
||||
it('merges two conversations in stable order without colliding identical message ids or media', async () => {
|
||||
const { runExport } = await import('../../src/main/export-service')
|
||||
const win = { isDestroyed: () => true, webContents: { send: vi.fn() } }
|
||||
state.messagesByUser = {
|
||||
alpha: [
|
||||
message({
|
||||
id: 'same-id',
|
||||
type: '图片',
|
||||
createTime: 100,
|
||||
contentData: { type: 'image', md5: 'a'.repeat(32), datName: 'same.dat' }
|
||||
}),
|
||||
message({ id: 'alpha-later', content: 'A2', createTime: 200 })
|
||||
],
|
||||
beta: [
|
||||
message({
|
||||
id: 'same-id',
|
||||
type: '图片',
|
||||
createTime: 100,
|
||||
contentData: { type: 'image', md5: 'a'.repeat(32), datName: 'same.dat' }
|
||||
}),
|
||||
message({ id: 'beta-later', content: 'B2', createTime: 150 })
|
||||
]
|
||||
}
|
||||
|
||||
const result = await runExport(
|
||||
{
|
||||
jobId: 'multi-conversation',
|
||||
targets: [target('alpha', '聊天 A'), target('beta', '聊天 B')],
|
||||
format: 'html',
|
||||
outputName: 'multi-conversation',
|
||||
kinds: ['text', 'image'],
|
||||
includeMedia: true
|
||||
},
|
||||
win as never
|
||||
)
|
||||
|
||||
expect(result.success).toBe(true)
|
||||
const archive = readArchive(result.outputPath!)
|
||||
expect(archive.version).toBe(2)
|
||||
expect(archive.conversations.map(({ id, messageCount }) => ({ id, messageCount }))).toEqual([
|
||||
{ id: 'alpha', messageCount: 2 },
|
||||
{ id: 'beta', messageCount: 2 }
|
||||
])
|
||||
expect(
|
||||
archive.messages.map((item) => [item.exportConversationId, item.id, item.createTime])
|
||||
).toEqual([
|
||||
['alpha', 'same-id', 100],
|
||||
['beta', 'same-id', 100],
|
||||
['beta', 'beta-later', 150],
|
||||
['alpha', 'alpha-later', 200]
|
||||
])
|
||||
const imagePaths = archive.messages
|
||||
.filter((item) => item.id === 'same-id')
|
||||
.map((item) => item.exportMediaUrl)
|
||||
expect(new Set(imagePaths).size).toBe(2)
|
||||
for (const imagePath of imagePaths) {
|
||||
expect(existsSync(join(dirname(result.outputPath!), imagePath!))).toBe(true)
|
||||
}
|
||||
})
|
||||
|
||||
it('creates a replaceable ZIP containing the complete top-level archive folder', async () => {
|
||||
const { runExport } = await import('../../src/main/export-service')
|
||||
const progress: unknown[][] = []
|
||||
const win = {
|
||||
isDestroyed: () => false,
|
||||
webContents: { send: (...args: unknown[]) => progress.push(args) }
|
||||
}
|
||||
state.messages = [
|
||||
message({
|
||||
id: 'zip-image',
|
||||
type: '图片',
|
||||
contentData: { type: 'image', md5: 'a'.repeat(32), datName: 'fixture.dat' }
|
||||
})
|
||||
]
|
||||
const request = {
|
||||
targets: [
|
||||
{
|
||||
...target('fixture-user', 'ZIP 会话'),
|
||||
avatarUrl:
|
||||
'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAusB9Y9ZQmcAAAAASUVORK5CYII='
|
||||
}
|
||||
],
|
||||
format: 'html' as const,
|
||||
outputName: 'zip-fixture',
|
||||
kinds: ['image'] as const,
|
||||
includeMedia: true,
|
||||
includeAvatars: true,
|
||||
zip: true
|
||||
}
|
||||
const first = await runExport(
|
||||
{ ...request, jobId: 'zip-first', kinds: [...request.kinds] },
|
||||
win as never
|
||||
)
|
||||
expect(first.success, first.error).toBe(true)
|
||||
const firstSize = readFileSync(first.outputPath!).length
|
||||
const second = await runExport(
|
||||
{ ...request, jobId: 'zip-second', kinds: [...request.kinds] },
|
||||
win as never
|
||||
)
|
||||
|
||||
expect(first.success).toBe(true)
|
||||
expect(second.success).toBe(true)
|
||||
expect(second.outputPath).toBe(first.outputPath)
|
||||
expect(firstSize).toBeGreaterThan(0)
|
||||
expect(readFileSync(second.outputPath!).subarray(0, 2).toString()).toBe('PK')
|
||||
const entries = execFileSync('unzip', ['-Z1', second.outputPath!], { encoding: 'utf8' })
|
||||
expect(entries).toContain('zip-fixture/index.html')
|
||||
expect(entries).toContain('zip-fixture/data/messages.js')
|
||||
expect(entries).toMatch(/zip-fixture\/avatars\/conversation_[0-9a-f]{16}\.png/)
|
||||
expect(entries).toMatch(/zip-fixture\/media\/image_[0-9a-f]{16}\.png/)
|
||||
expect(progress.some((args) => (args[1] as { phase?: string })?.phase === 'compressing')).toBe(
|
||||
true
|
||||
)
|
||||
expect(
|
||||
readdirSync(join(state.documents, 'WechatExplorer', '导出')).some((name) =>
|
||||
name.startsWith('zip-fixture.zip.tmp-')
|
||||
)
|
||||
).toBe(false)
|
||||
})
|
||||
|
||||
it('keeps the last complete ZIP when a replacement is cancelled during compression', async () => {
|
||||
const { cancelExport, runExport } = await import('../../src/main/export-service')
|
||||
state.messages = [message({ id: 'zip-cancel', content: '保留完整压缩包' })]
|
||||
const request = {
|
||||
targets: [target('fixture-user', '取消压缩会话')],
|
||||
format: 'html' as const,
|
||||
outputName: 'zip-cancel-fixture',
|
||||
kinds: ['text'] as const,
|
||||
includeMedia: false,
|
||||
zip: true
|
||||
}
|
||||
const silentWindow = { isDestroyed: () => true, webContents: { send: vi.fn() } }
|
||||
const first = await runExport(
|
||||
{ ...request, jobId: 'zip-cancel-first', kinds: [...request.kinds] },
|
||||
silentWindow as never
|
||||
)
|
||||
expect(first.success, first.error).toBe(true)
|
||||
const completeZip = readFileSync(first.outputPath!)
|
||||
const cancellingWindow = {
|
||||
isDestroyed: () => false,
|
||||
webContents: {
|
||||
send: (_channel: string, progress: { phase: string }): void => {
|
||||
if (progress.phase === 'compressing') cancelExport('zip-cancel-second')
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const cancelled = await runExport(
|
||||
{ ...request, jobId: 'zip-cancel-second', kinds: [...request.kinds] },
|
||||
cancellingWindow as never
|
||||
)
|
||||
|
||||
expect(cancelled).toEqual({ success: false, error: '已取消' })
|
||||
expect(readFileSync(first.outputPath!)).toEqual(completeZip)
|
||||
expect(
|
||||
readdirSync(join(state.documents, 'WechatExplorer', '导出')).some((name) =>
|
||||
name.startsWith('zip-cancel-fixture.zip.tmp-')
|
||||
)
|
||||
).toBe(false)
|
||||
})
|
||||
|
||||
it('normalizes a legacy v1 single-chat archive into v2', async () => {
|
||||
const { readHtmlArchive } = await import('../../src/main/export-service')
|
||||
const outputDir = join(state.documents, 'legacy-archive')
|
||||
mkdirSync(join(outputDir, 'data'), { recursive: true })
|
||||
writeFileSync(
|
||||
join(outputDir, 'data', 'messages.js'),
|
||||
`window.__WECHAT_EXPORT__ = ${JSON.stringify({
|
||||
version: 1,
|
||||
sourceId: 'legacy-user',
|
||||
name: '旧档案',
|
||||
exportedAt: '2026-08-01T00:00:00.000Z',
|
||||
messages: [message({ id: 'legacy-message', content: '旧消息' })]
|
||||
})};\n`,
|
||||
'utf8'
|
||||
)
|
||||
|
||||
const archive = await readHtmlArchive(outputDir, [target('legacy-user', '旧档案')], '旧档案')
|
||||
|
||||
expect(archive.version).toBe(2)
|
||||
expect(archive.conversations).toEqual([
|
||||
expect.objectContaining({ id: 'legacy-user', name: '旧档案', messageCount: 1 })
|
||||
])
|
||||
expect(archive.messages[0]).toMatchObject({
|
||||
id: 'legacy-message',
|
||||
exportConversationId: 'legacy-user',
|
||||
exportConversationName: '旧档案'
|
||||
})
|
||||
})
|
||||
|
||||
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: '第一个会话',
|
||||
targets: [target('first-user', '第一个会话')],
|
||||
format: 'html' as const,
|
||||
outputName: 'same-name',
|
||||
kinds: ['text'] as const,
|
||||
@@ -320,8 +573,7 @@ describe('media export flow', () => {
|
||||
{
|
||||
...baseRequest,
|
||||
jobId: 'source-second',
|
||||
userMd5: 'second-user',
|
||||
name: '第二个会话',
|
||||
targets: [target('second-user', '第二个会话')],
|
||||
kinds: [...baseRequest.kinds]
|
||||
},
|
||||
win as never
|
||||
@@ -329,8 +581,10 @@ describe('media export flow', () => {
|
||||
|
||||
expect(first.success).toBe(true)
|
||||
expect(second.success).toBe(false)
|
||||
expect(second.error).toContain('另一个会话')
|
||||
expect(readArchive(first.outputPath!).sourceId).toBe('first-user')
|
||||
expect(second.error).toContain('聊天集合不同')
|
||||
expect(readArchive(first.outputPath!).conversations.map((item) => item.id)).toEqual([
|
||||
'first-user'
|
||||
])
|
||||
})
|
||||
|
||||
it('uses message content as the stable fallback when the database supplies a random id', async () => {
|
||||
@@ -357,13 +611,16 @@ describe('media export flow', () => {
|
||||
const result = await runExport(
|
||||
{
|
||||
jobId: 'self-name',
|
||||
userMd5: 'fixture-user',
|
||||
name: '本人昵称',
|
||||
targets: [
|
||||
{
|
||||
...target('fixture-user', '本人昵称'),
|
||||
nameMap: { a969409112: 'a969409112' }
|
||||
}
|
||||
],
|
||||
format: 'html',
|
||||
outputName: 'self-name',
|
||||
kinds: ['text'],
|
||||
includeMedia: false,
|
||||
nameMap: { a969409112: 'a969409112' }
|
||||
includeMedia: false
|
||||
},
|
||||
win as never
|
||||
)
|
||||
@@ -376,8 +633,7 @@ describe('media export flow', () => {
|
||||
const { runExport } = await import('../../src/main/export-service')
|
||||
const win = { isDestroyed: () => true, webContents: { send: vi.fn() } }
|
||||
const request = {
|
||||
userMd5: 'fixture-user',
|
||||
name: '增量昵称',
|
||||
targets: [target('fixture-user', '增量昵称')],
|
||||
format: 'html' as const,
|
||||
outputName: 'incremental-self-name',
|
||||
kinds: ['text'] as const,
|
||||
|
||||
@@ -94,6 +94,60 @@ describe('export media', () => {
|
||||
dom.window.close()
|
||||
})
|
||||
|
||||
it('filters a v2 merged archive by conversation before search and month counts', () => {
|
||||
const html = renderExportPage('合并档案')
|
||||
const dom = new JSDOM(html, { runScripts: 'outside-only' })
|
||||
Object.assign(dom.window, {
|
||||
__WECHAT_EXPORT__: {
|
||||
version: 2,
|
||||
name: '合并档案',
|
||||
exportedAt: '2026-08-04T00:00:00.000Z',
|
||||
conversations: [
|
||||
{ id: 'alpha', name: '聊天 A', type: 'user', messageCount: 2 },
|
||||
{ id: 'beta', name: '聊天 B', type: 'group', messageCount: 1 }
|
||||
],
|
||||
messages: [
|
||||
messageForArchive('alpha-1', 'alpha', '聊天 A', '共同关键词', 1_767_225_600),
|
||||
messageForArchive('beta-1', 'beta', '聊天 B', '共同关键词', 1_769_904_000),
|
||||
messageForArchive('alpha-2', 'alpha', '聊天 A', '仅 A 可见', 1_769_990_400)
|
||||
]
|
||||
}
|
||||
})
|
||||
|
||||
dom.window.eval(inlineScriptOf(html))
|
||||
|
||||
const filter = dom.window.document.querySelector('#conversation-filter')!
|
||||
const select = dom.window.document.querySelector('#conversation-select') as HTMLSelectElement
|
||||
expect(filter.hasAttribute('hidden')).toBe(false)
|
||||
expect(filter.parentElement?.classList.contains('archive-heading')).toBe(true)
|
||||
expect((dom.window.document.querySelector('#archive-title') as HTMLElement).hidden).toBe(true)
|
||||
expect(dom.window.document.querySelector('#archive-meta')?.textContent).toMatch(/^更新于 /)
|
||||
expect(select.options).toHaveLength(3)
|
||||
expect(select.value).toBe('all')
|
||||
expect(select.options[0].textContent).toBe('全部聊天(3)')
|
||||
expect(dom.window.document.querySelectorAll('.conversation-source')).toHaveLength(3)
|
||||
expect(dom.window.document.querySelector('#count')?.textContent).toBe(
|
||||
'已显示 3 / 筛选 3 / 全部 3'
|
||||
)
|
||||
select.value = 'alpha'
|
||||
select.dispatchEvent(new dom.window.Event('change'))
|
||||
expect(dom.window.document.querySelectorAll('.message')).toHaveLength(2)
|
||||
expect(dom.window.document.querySelectorAll('.conversation-source')).toHaveLength(0)
|
||||
expect(dom.window.document.querySelector('#count')?.textContent).toBe(
|
||||
'已显示 2 / 筛选 2 / 当前聊天 2'
|
||||
)
|
||||
expect(dom.window.document.querySelectorAll('.timeline-month')).toHaveLength(2)
|
||||
|
||||
const search = dom.window.document.querySelector('#query') as HTMLInputElement
|
||||
search.value = '共同关键词'
|
||||
search.dispatchEvent(new dom.window.Event('input'))
|
||||
expect(dom.window.document.querySelectorAll('.message')).toHaveLength(1)
|
||||
expect(dom.window.document.querySelector('#count')?.textContent).toBe(
|
||||
'已显示 1 / 筛选 1 / 当前聊天 2'
|
||||
)
|
||||
dom.window.close()
|
||||
})
|
||||
|
||||
it('keeps relative media, file download, quote, and missing-media renderers', () => {
|
||||
const html = renderExportPage('媒体档案')
|
||||
|
||||
@@ -116,3 +170,23 @@ describe('export media', () => {
|
||||
expect(html).toContain("if (event.key === 'Escape') closeLightbox()")
|
||||
})
|
||||
})
|
||||
|
||||
function messageForArchive(
|
||||
id: string,
|
||||
conversationId: string,
|
||||
conversationName: string,
|
||||
content: string,
|
||||
createTime: number
|
||||
): Message {
|
||||
return {
|
||||
id,
|
||||
from: 'user',
|
||||
type: '普通文本',
|
||||
datetime: '',
|
||||
content,
|
||||
isSender: false,
|
||||
createTime,
|
||||
exportConversationId: conversationId,
|
||||
exportConversationName: conversationName
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user