mirror of
https://wget.la/https://github.com/Wxw-Gu/WechatExplorer
synced 2026-08-18 20:19:09 +08:00
feat: 支持多聊天合并导出
This commit is contained in:
@@ -39,8 +39,16 @@ body {
|
||||
padding: 16px 20px;
|
||||
box-shadow: 0 8px 24px #29483b12;
|
||||
}
|
||||
.archive-heading {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px 12px;
|
||||
min-width: 0;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.title { font-size: 18px; font-weight: 750; }
|
||||
.meta { color: var(--muted); margin-left: 12px; font-size: 13px; }
|
||||
.archive-heading .meta { margin-left: 0; }
|
||||
.controls { display: flex; gap: 8px; align-items: center; justify-content: flex-end; }
|
||||
.controls input, .filter-button {
|
||||
border: 1px solid var(--border);
|
||||
@@ -63,13 +71,66 @@ body {
|
||||
.count { margin-left: auto; color: var(--muted); font-size: 13px; }
|
||||
.archive-layout {
|
||||
display: grid;
|
||||
grid-template-columns: 150px minmax(0, 1fr);
|
||||
grid-template-columns: 168px minmax(0, 1fr);
|
||||
gap: 18px;
|
||||
min-height: 0;
|
||||
flex: 1;
|
||||
margin-top: 16px;
|
||||
}
|
||||
.archive-layout.single-conversation { grid-template-columns: 168px minmax(0, 1fr); }
|
||||
.archive-navigation {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
min-width: 0;
|
||||
min-height: 0;
|
||||
}
|
||||
.conversation-filter {
|
||||
position: relative;
|
||||
display: inline-flex;
|
||||
flex: 0 1 320px;
|
||||
min-width: 210px;
|
||||
max-width: 100%;
|
||||
}
|
||||
.conversation-filter[hidden] { display: none; }
|
||||
.conversation-filter::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
right: 15px;
|
||||
top: 50%;
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
border-right: 2px solid var(--accent);
|
||||
border-bottom: 2px solid var(--accent);
|
||||
transform: translateY(-65%) rotate(45deg);
|
||||
pointer-events: none;
|
||||
}
|
||||
.conversation-select {
|
||||
appearance: none;
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
height: 42px;
|
||||
padding: 0 42px 0 14px;
|
||||
border: 1px solid #b8cec5;
|
||||
border-radius: 10px;
|
||||
outline: 0;
|
||||
background: #f7fbf9;
|
||||
color: var(--text);
|
||||
font: inherit;
|
||||
font-size: 17px;
|
||||
font-weight: 700;
|
||||
cursor: pointer;
|
||||
box-shadow: 0 2px 8px #29483b12;
|
||||
transition: border-color .15s ease, background .15s ease, box-shadow .15s ease;
|
||||
}
|
||||
.conversation-select:hover { border-color: #70a392; background: #fff; }
|
||||
.conversation-select:focus {
|
||||
border-color: var(--accent);
|
||||
background: #fff;
|
||||
box-shadow: 0 0 0 3px #176b571c;
|
||||
}
|
||||
.timeline {
|
||||
flex: 1;
|
||||
overflow: auto;
|
||||
background: #f7faf8;
|
||||
border: 1px solid var(--border);
|
||||
@@ -133,6 +194,14 @@ body {
|
||||
}
|
||||
.message.system .sender { display: none; }
|
||||
.time { color: var(--muted); font-size: 11px; margin: 0 12px; }
|
||||
.conversation-source {
|
||||
display: inline-block;
|
||||
margin-left: 8px;
|
||||
padding: 2px 6px;
|
||||
border-radius: 5px;
|
||||
background: var(--accent-soft);
|
||||
color: var(--accent);
|
||||
}
|
||||
.row { display: flex; gap: 12px; align-items: flex-end; max-width: 100%; }
|
||||
.sent .row { flex-direction: row-reverse; }
|
||||
.avatar {
|
||||
@@ -249,9 +318,19 @@ body {
|
||||
.controls input[type=search] { width: 100%; }
|
||||
.filters { grid-column: 1; }
|
||||
.count { width: 100%; margin-left: 0; }
|
||||
.archive-layout { grid-template-columns: 1fr; margin-top: 10px; }
|
||||
.timeline { display: flex; gap: 6px; overflow: auto; padding: 8px; }
|
||||
.timeline-year { display: none; }
|
||||
.archive-layout { grid-template-columns: 1fr; align-content: start; margin-top: 10px; }
|
||||
.archive-layout.single-conversation { grid-template-columns: 1fr; }
|
||||
.archive-navigation { align-self: start; gap: 8px; }
|
||||
.timeline { align-self: start; display: flex; gap: 6px; overflow: auto; padding: 8px; }
|
||||
.archive-heading { align-items: flex-start; }
|
||||
.conversation-filter { flex-basis: 100%; width: 100%; }
|
||||
.timeline-year {
|
||||
flex: 0 0 auto;
|
||||
align-self: center;
|
||||
margin: 0 2px 0 0;
|
||||
padding: 7px 5px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.timeline-month {
|
||||
flex: 0 0 auto;
|
||||
width: auto;
|
||||
@@ -281,8 +360,24 @@ const renderExportScript = (name: string): string => `
|
||||
const PAGE_SIZE = ${EXPORT_PAGE_SIZE}
|
||||
const WINDOW_STEP = Math.floor(PAGE_SIZE / 2)
|
||||
const archive = window.__WECHAT_EXPORT__ || { name: ${JSON.stringify(name)}, messages: [] }
|
||||
const allMessages = Array.isArray(archive.messages) ? archive.messages : []
|
||||
const legacyConversation = archive.sourceId
|
||||
? [{ id: archive.sourceId, name: archive.name || ${JSON.stringify(name)}, type: 'user', messageCount: 0 }]
|
||||
: []
|
||||
const conversations = Array.isArray(archive.conversations) && archive.conversations.length
|
||||
? archive.conversations
|
||||
: legacyConversation
|
||||
const allMessages = (Array.isArray(archive.messages) ? archive.messages : []).map((message) =>
|
||||
message.exportConversationId || conversations.length !== 1
|
||||
? message
|
||||
: Object.assign({}, message, {
|
||||
exportConversationId: conversations[0].id,
|
||||
exportConversationName: conversations[0].name
|
||||
})
|
||||
)
|
||||
const list = document.querySelector('#messages')
|
||||
const layout = document.querySelector('.archive-layout')
|
||||
const conversationFilter = document.querySelector('#conversation-filter')
|
||||
const conversationSelect = document.querySelector('#conversation-select')
|
||||
const timeline = document.querySelector('#timeline')
|
||||
const query = document.querySelector('#query')
|
||||
const count = document.querySelector('#count')
|
||||
@@ -293,6 +388,7 @@ const renderExportScript = (name: string): string => `
|
||||
const preview = document.querySelector('#lightbox-image')
|
||||
const closeButton = document.querySelector('#lightbox-close')
|
||||
let activeKind = 'all'
|
||||
let activeConversation = 'all'
|
||||
let filtered = []
|
||||
let windowStart = 0
|
||||
let windowEnd = 0
|
||||
@@ -345,6 +441,7 @@ const renderExportScript = (name: string): string => `
|
||||
return 'text'
|
||||
}
|
||||
const searchText = (message) => [
|
||||
message.exportConversationName,
|
||||
message.name,
|
||||
message.senderId,
|
||||
message.content,
|
||||
@@ -389,14 +486,42 @@ const renderExportScript = (name: string): string => `
|
||||
: avatarFallback) + '</div>'
|
||||
const text = message.content || (data.type === 'quote' ? data.title : '')
|
||||
const content = esc(text || (!media && !audio && !quote ? '[' + (message.type || '消息') + ']' : ''))
|
||||
const source = conversations.length > 1 && activeConversation === 'all'
|
||||
? '<span class="conversation-source">' + esc(message.exportConversationName || '聊天') + '</span>'
|
||||
: ''
|
||||
return '<article class="message' + (message.isSender ? ' sent' : '') + (isSystem ? ' system' : '') +
|
||||
'" data-index="' + archiveIndex + '" data-month="' + esc(monthKey(message)) + '">' +
|
||||
'<div class="time">' + esc(fullTime(message)) + '</div><div class="row">' +
|
||||
'<div class="time">' + esc(fullTime(message)) + source + '</div><div class="row">' +
|
||||
(isSystem ? '' : avatar) + '<div class="bubble"><div class="sender">' +
|
||||
(isSystem ? '' : esc(sender)) + '</div>' + media + audio + quote +
|
||||
'<div class="content">' + content + '</div>' + mediaStatus + '</div></div></article>'
|
||||
}
|
||||
|
||||
const renderConversations = () => {
|
||||
if (conversations.length <= 1) {
|
||||
conversationFilter.hidden = true
|
||||
title.hidden = false
|
||||
layout.classList.add('single-conversation')
|
||||
return
|
||||
}
|
||||
const counts = new Map()
|
||||
for (const message of allMessages) {
|
||||
const id = message.exportConversationId || ''
|
||||
counts.set(id, (counts.get(id) || 0) + 1)
|
||||
}
|
||||
const option = (id, label, total) =>
|
||||
'<option value="' + esc(id) + '">' + esc(label) + '(' + total + ')</option>'
|
||||
title.hidden = true
|
||||
conversationFilter.hidden = false
|
||||
conversationSelect.innerHTML = option('all', '全部聊天', allMessages.length) +
|
||||
conversations.map((conversation) => option(
|
||||
conversation.id,
|
||||
conversation.name,
|
||||
counts.get(conversation.id) || 0
|
||||
)).join('')
|
||||
conversationSelect.value = activeConversation
|
||||
}
|
||||
|
||||
const renderTimeline = () => {
|
||||
if (filtered.length === 0) {
|
||||
timeline.innerHTML = '<div class="timeline-empty">没有可跳转的月份</div>'
|
||||
@@ -431,7 +556,11 @@ const renderExportScript = (name: string): string => `
|
||||
}
|
||||
const updateCount = () => {
|
||||
const shown = Math.max(0, windowEnd - windowStart)
|
||||
count.textContent = '已显示 ' + shown + ' / 筛选 ' + filtered.length + ' / 全部 ' + allMessages.length
|
||||
const scopeTotal = activeConversation === 'all'
|
||||
? allMessages.length
|
||||
: allMessages.filter((message) => message.exportConversationId === activeConversation).length
|
||||
const scopeLabel = activeConversation === 'all' ? '全部' : '当前聊天'
|
||||
count.textContent = '已显示 ' + shown + ' / 筛选 ' + filtered.length + ' / ' + scopeLabel + ' ' + scopeTotal
|
||||
}
|
||||
const setScrollTop = (value) => {
|
||||
scrollLoadSuppressed = true
|
||||
@@ -472,6 +601,7 @@ const renderExportScript = (name: string): string => `
|
||||
const applyFilters = () => {
|
||||
const term = query.value.trim().toLowerCase()
|
||||
filtered = allMessages.filter((message) =>
|
||||
(activeConversation === 'all' || message.exportConversationId === activeConversation) &&
|
||||
(activeKind === 'all' || kindOf(message) === activeKind) &&
|
||||
(!term || searchText(message).includes(term))
|
||||
)
|
||||
@@ -540,6 +670,10 @@ const renderExportScript = (name: string): string => `
|
||||
filters.querySelectorAll('[data-kind]').forEach((item) => item.classList.toggle('active', item === button))
|
||||
applyFilters()
|
||||
})
|
||||
conversationSelect.addEventListener('change', () => {
|
||||
activeConversation = conversationSelect.value
|
||||
applyFilters()
|
||||
})
|
||||
timeline.addEventListener('click', (event) => {
|
||||
const button = event.target.closest('[data-month]')
|
||||
if (button) jumpToMonth(button.dataset.month)
|
||||
@@ -577,10 +711,12 @@ const renderExportScript = (name: string): string => `
|
||||
})
|
||||
|
||||
title.textContent = archive.name || ${JSON.stringify(name)}
|
||||
meta.textContent = allMessages.length.toLocaleString() + ' 条消息 · 更新于 ' +
|
||||
(archive.exportedAt
|
||||
? new Date(archive.exportedAt).toLocaleString('zh-CN', { hour12: false })
|
||||
: '未知时间')
|
||||
const updatedAt = archive.exportedAt
|
||||
? new Date(archive.exportedAt).toLocaleString('zh-CN', { hour12: false })
|
||||
: '未知时间'
|
||||
meta.textContent = (conversations.length > 1 ? '' : allMessages.length.toLocaleString() + ' 条消息 · ') +
|
||||
'更新于 ' + updatedAt
|
||||
renderConversations()
|
||||
applyFilters()
|
||||
})()
|
||||
`
|
||||
@@ -597,8 +733,11 @@ export function renderExportPage(name: string): string {
|
||||
<body>
|
||||
<main class="page">
|
||||
<header class="toolbar">
|
||||
<div>
|
||||
<div class="archive-heading">
|
||||
<span class="title" id="archive-title">${safe(name)}</span>
|
||||
<label class="conversation-filter" id="conversation-filter" hidden>
|
||||
<select class="conversation-select" id="conversation-select" aria-label="筛选聊天"></select>
|
||||
</label>
|
||||
<span class="meta" id="archive-meta">正在读取消息…</span>
|
||||
</div>
|
||||
<div class="controls">
|
||||
@@ -616,7 +755,9 @@ export function renderExportPage(name: string): string {
|
||||
</div>
|
||||
</header>
|
||||
<section class="archive-layout">
|
||||
<nav class="timeline" id="timeline" aria-label="聊天时间轴"></nav>
|
||||
<aside class="archive-navigation">
|
||||
<nav class="timeline" id="timeline" aria-label="聊天时间轴"></nav>
|
||||
</aside>
|
||||
<section class="scroll" id="messages">
|
||||
<div class="empty">正在加载聊天档案…</div>
|
||||
</section>
|
||||
|
||||
+277
-44
@@ -1,14 +1,16 @@
|
||||
import { app, BrowserWindow, shell } from 'electron'
|
||||
import { createHash } from 'crypto'
|
||||
import { promises as fs } from 'fs'
|
||||
import { createWriteStream, promises as fs } from 'fs'
|
||||
import { extname, join } from 'path'
|
||||
import { fileURLToPath } from 'url'
|
||||
import { ZipArchive, type Archiver } from 'archiver'
|
||||
import * as chat from './services/chat-service'
|
||||
import type {
|
||||
ExportJobProgress,
|
||||
ExportMessageKind,
|
||||
ExportRequest,
|
||||
ExportResult
|
||||
ExportResult,
|
||||
ExportTarget
|
||||
} from '../shared/export'
|
||||
import type { Message } from '../shared/types'
|
||||
import { VoiceService } from './voice-service'
|
||||
@@ -22,8 +24,18 @@ import { FileAssetService } from './file-asset-service'
|
||||
import { mergeCachedSelfInfo } from './services/bootstrap-cache'
|
||||
|
||||
const jobs = new Set<string>()
|
||||
const activeArchives = new Map<string, Archiver>()
|
||||
const safeFilePart = (value: string): string =>
|
||||
value.replace(/[\\/:*?"<>|]/g, '_').trim() || '聊天档案'
|
||||
const copyWritableExportFile = async (source: string, destination: string): Promise<void> => {
|
||||
try {
|
||||
await fs.chmod(destination, 0o644)
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error
|
||||
}
|
||||
await fs.copyFile(source, destination)
|
||||
await fs.chmod(destination, 0o644)
|
||||
}
|
||||
const exportStamp = (): string => {
|
||||
const date = new Date()
|
||||
const pad = (value: number): string => String(value).padStart(2, '0')
|
||||
@@ -31,7 +43,15 @@ const exportStamp = (): string => {
|
||||
}
|
||||
const imageKeys = new ImageKeyConfigService()
|
||||
|
||||
export interface HtmlExportArchive {
|
||||
export interface HtmlExportConversation {
|
||||
id: string
|
||||
name: string
|
||||
type: 'user' | 'group'
|
||||
avatarUrl?: string
|
||||
messageCount: number
|
||||
}
|
||||
|
||||
interface HtmlExportArchiveV1 {
|
||||
version: 1
|
||||
sourceId: string
|
||||
name: string
|
||||
@@ -39,20 +59,29 @@ export interface HtmlExportArchive {
|
||||
messages: Message[]
|
||||
}
|
||||
|
||||
export interface HtmlExportArchive {
|
||||
version: 2
|
||||
name: string
|
||||
exportedAt: string
|
||||
conversations: HtmlExportConversation[]
|
||||
messages: Message[]
|
||||
}
|
||||
|
||||
const archiveDataPrefix = 'window.__WECHAT_EXPORT__ = '
|
||||
const hashPart = (value: string, length = 16): string =>
|
||||
createHash('sha1').update(value).digest('hex').slice(0, length)
|
||||
|
||||
export const exportMessageKey = (message: Message, sourceId = ''): string => {
|
||||
const conversationId = message.exportConversationId || sourceId
|
||||
const sessionId = message.sessionId || sourceId
|
||||
if (message.localId && message.createTime) {
|
||||
return `${sessionId}:local:${message.localId}:${message.createTime}`
|
||||
return `${conversationId}:${sessionId}:local:${message.localId}:${message.createTime}`
|
||||
}
|
||||
if (message.serverId) return `${sessionId}:server:${message.serverId}`
|
||||
if (message.serverId) return `${conversationId}:${sessionId}:server:${message.serverId}`
|
||||
if (message.id && message.createTime && !/^0\.\d+$/.test(message.id)) {
|
||||
return `${sessionId}:id:${message.id}:${message.createTime}`
|
||||
return `${conversationId}:${sessionId}:id:${message.id}:${message.createTime}`
|
||||
}
|
||||
return `${sessionId}:fallback:${hashPart(
|
||||
return `${conversationId}:${sessionId}:fallback:${hashPart(
|
||||
JSON.stringify([
|
||||
message.createTime || 0,
|
||||
message.senderId || '',
|
||||
@@ -89,7 +118,8 @@ const mergeArchiveMessage = (previous: Message, current: Message): Message => {
|
||||
export function mergeHtmlArchiveMessages(
|
||||
previous: Message[],
|
||||
current: Message[],
|
||||
sourceId = ''
|
||||
sourceId = '',
|
||||
conversationOrder: string[] = []
|
||||
): Message[] {
|
||||
const merged = new Map<string, Message>()
|
||||
for (const message of previous) merged.set(exportMessageKey(message, sourceId), message)
|
||||
@@ -101,6 +131,10 @@ export function mergeHtmlArchiveMessages(
|
||||
return Array.from(merged.values()).sort((left, right) => {
|
||||
const byTime = Number(left.createTime || 0) - Number(right.createTime || 0)
|
||||
if (byTime !== 0) return byTime
|
||||
const byConversation =
|
||||
conversationOrder.indexOf(left.exportConversationId || sourceId) -
|
||||
conversationOrder.indexOf(right.exportConversationId || sourceId)
|
||||
if (byConversation !== 0) return byConversation
|
||||
return Number(left.localId || 0) - Number(right.localId || 0)
|
||||
})
|
||||
}
|
||||
@@ -127,7 +161,7 @@ export function normalizeHtmlArchiveSelfNames(
|
||||
|
||||
export async function readHtmlArchive(
|
||||
outputDir: string,
|
||||
sourceId: string,
|
||||
targets: ExportTarget[],
|
||||
name: string
|
||||
): Promise<HtmlExportArchive> {
|
||||
const dataPath = join(outputDir, 'data', 'messages.js')
|
||||
@@ -136,7 +170,18 @@ export async function readHtmlArchive(
|
||||
source = await fs.readFile(dataPath, 'utf8')
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code === 'ENOENT') {
|
||||
return { version: 1, sourceId, name, exportedAt: new Date(0).toISOString(), messages: [] }
|
||||
return {
|
||||
version: 2,
|
||||
name,
|
||||
exportedAt: new Date(0).toISOString(),
|
||||
conversations: targets.map((target) => ({
|
||||
id: target.userMd5,
|
||||
name: target.name,
|
||||
type: target.type,
|
||||
messageCount: 0
|
||||
})),
|
||||
messages: []
|
||||
}
|
||||
}
|
||||
throw error
|
||||
}
|
||||
@@ -146,21 +191,100 @@ export async function readHtmlArchive(
|
||||
.slice(assignment + 1)
|
||||
.trim()
|
||||
.replace(/;\s*$/, '')
|
||||
let archive: HtmlExportArchive
|
||||
let parsed: HtmlExportArchive | HtmlExportArchiveV1
|
||||
try {
|
||||
archive = JSON.parse(json) as HtmlExportArchive
|
||||
parsed = JSON.parse(json) as HtmlExportArchive | HtmlExportArchiveV1
|
||||
} catch {
|
||||
throw new Error('现有 HTML 档案数据已损坏,请从 messages.js.bak 恢复或更换导出名称')
|
||||
}
|
||||
if (archive.sourceId && archive.sourceId !== sourceId) {
|
||||
throw new Error('同名导出目录已属于另一个会话,请修改文件名称后重试')
|
||||
const expectedIds = targets.map((target) => target.userMd5).sort()
|
||||
if (parsed.version === 1) {
|
||||
if (targets.length !== 1 || parsed.sourceId !== targets[0].userMd5) {
|
||||
throw new Error('同名导出目录的聊天集合不同,请修改文件名称后重试')
|
||||
}
|
||||
return {
|
||||
version: 2,
|
||||
name: parsed.name || name,
|
||||
exportedAt: parsed.exportedAt || new Date(0).toISOString(),
|
||||
conversations: [
|
||||
{
|
||||
id: targets[0].userMd5,
|
||||
name: targets[0].name,
|
||||
type: targets[0].type,
|
||||
messageCount: Array.isArray(parsed.messages) ? parsed.messages.length : 0
|
||||
}
|
||||
],
|
||||
messages: (Array.isArray(parsed.messages) ? parsed.messages : []).map((message) => ({
|
||||
...message,
|
||||
exportConversationId: targets[0].userMd5,
|
||||
exportConversationName: targets[0].name
|
||||
}))
|
||||
}
|
||||
}
|
||||
const actualIds = (Array.isArray(parsed.conversations) ? parsed.conversations : [])
|
||||
.map((conversation) => conversation.id)
|
||||
.sort()
|
||||
if (actualIds.join('|') !== expectedIds.join('|')) {
|
||||
throw new Error('同名导出目录的聊天集合不同,请修改文件名称后重试')
|
||||
}
|
||||
return {
|
||||
version: 1,
|
||||
sourceId,
|
||||
name: archive.name || name,
|
||||
exportedAt: archive.exportedAt || new Date(0).toISOString(),
|
||||
messages: Array.isArray(archive.messages) ? archive.messages : []
|
||||
version: 2,
|
||||
name: parsed.name || name,
|
||||
exportedAt: parsed.exportedAt || new Date(0).toISOString(),
|
||||
conversations: parsed.conversations,
|
||||
messages: Array.isArray(parsed.messages) ? parsed.messages : []
|
||||
}
|
||||
}
|
||||
|
||||
async function writeZipArchive(
|
||||
outputDir: string,
|
||||
zipPath: string,
|
||||
folderName: string,
|
||||
jobId: string
|
||||
): Promise<void> {
|
||||
const temporaryPath = `${zipPath}.tmp-${process.pid}-${Date.now()}`
|
||||
await fs.rm(temporaryPath, { force: true })
|
||||
const output = createWriteStream(temporaryPath)
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
output.once('open', () => resolve())
|
||||
output.once('error', reject)
|
||||
})
|
||||
const archive = new ZipArchive({ zlib: { level: 6 } })
|
||||
activeArchives.set(jobId, archive)
|
||||
try {
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
let settled = false
|
||||
const finish = (error?: Error): void => {
|
||||
if (settled) return
|
||||
settled = true
|
||||
if (error) reject(error)
|
||||
else resolve()
|
||||
}
|
||||
output.on('close', () => finish())
|
||||
output.on('error', finish)
|
||||
archive.on('warning', (error) => {
|
||||
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') finish(error)
|
||||
})
|
||||
archive.on('error', finish)
|
||||
archive.pipe(output)
|
||||
archive.directory(outputDir, safeFilePart(folderName))
|
||||
void archive.finalize().catch(finish)
|
||||
})
|
||||
if (!jobs.has(jobId)) throw new Error('已取消')
|
||||
try {
|
||||
await fs.rename(temporaryPath, zipPath)
|
||||
} catch (error) {
|
||||
if (!['EEXIST', 'EPERM'].includes((error as NodeJS.ErrnoException).code || '')) throw error
|
||||
await fs.rm(zipPath, { force: true })
|
||||
await fs.rename(temporaryPath, zipPath)
|
||||
}
|
||||
} finally {
|
||||
activeArchives.delete(jobId)
|
||||
if (!output.closed) {
|
||||
output.destroy()
|
||||
await new Promise<void>((resolve) => output.once('close', () => resolve()))
|
||||
}
|
||||
await fs.rm(temporaryPath, { force: true })
|
||||
}
|
||||
}
|
||||
|
||||
@@ -298,11 +422,57 @@ export async function runExport(request: ExportRequest, win: BrowserWindow): Pro
|
||||
if (!win.isDestroyed()) win.webContents.send('export:progress', p)
|
||||
}
|
||||
try {
|
||||
const targets = request.targets || []
|
||||
if (targets.length < 1 || targets.length > 5) {
|
||||
throw new Error('一次导出必须选择 1 到 5 个聊天')
|
||||
}
|
||||
if (new Set(targets.map((target) => target.userMd5)).size !== targets.length) {
|
||||
throw new Error('导出聊天不能重复')
|
||||
}
|
||||
if (targets.length > 1 && request.format !== 'html') {
|
||||
throw new Error('多聊天合并仅支持 HTML 格式')
|
||||
}
|
||||
const archiveName =
|
||||
targets.length > 1 ? `${targets[0].name} 等 ${targets.length} 个聊天` : targets[0].name
|
||||
const targetById = new Map(targets.map((target) => [target.userMd5, target]))
|
||||
send({ jobId: request.jobId, phase: 'reading', processed: 0, total: 100, percent: 0 })
|
||||
await new Promise<void>((resolve) => setImmediate(resolve))
|
||||
const messages = (
|
||||
await chat.listMessagesAsync(request.userMd5, request.startTime, request.endTime)
|
||||
).filter((message) => request.kinds.includes(kindOf(message)))
|
||||
const messageEntries: { message: Message; targetOrder: number; messageOrder: number }[] = []
|
||||
for (const [targetOrder, target] of targets.entries()) {
|
||||
if (!jobs.has(request.jobId)) {
|
||||
send({ jobId: request.jobId, phase: 'cancelled', processed: 0, percent: 5 })
|
||||
return { success: false, error: '已取消' }
|
||||
}
|
||||
const targetMessages = (
|
||||
await chat.listMessagesAsync(target.userMd5, request.startTime, request.endTime)
|
||||
).filter((message) => request.kinds.includes(kindOf(message)))
|
||||
for (const [messageOrder, message] of targetMessages.entries()) {
|
||||
messageEntries.push({
|
||||
message: {
|
||||
...message,
|
||||
exportConversationId: target.userMd5,
|
||||
exportConversationName: target.name
|
||||
},
|
||||
targetOrder,
|
||||
messageOrder
|
||||
})
|
||||
}
|
||||
send({
|
||||
jobId: request.jobId,
|
||||
phase: 'reading',
|
||||
processed: targetOrder + 1,
|
||||
total: targets.length,
|
||||
percent: Math.max(1, Math.round(((targetOrder + 1) / targets.length) * 10))
|
||||
})
|
||||
}
|
||||
const messages = messageEntries
|
||||
.sort((left, right) => {
|
||||
const byTime = Number(left.message.createTime || 0) - Number(right.message.createTime || 0)
|
||||
if (byTime !== 0) return byTime
|
||||
if (left.targetOrder !== right.targetOrder) return left.targetOrder - right.targetOrder
|
||||
return left.messageOrder - right.messageOrder
|
||||
})
|
||||
.map((entry) => entry.message)
|
||||
const rawSelfInfo = await chat.getSelfAccountInfoAsync()
|
||||
const selfInfo = rawSelfInfo ? mergeCachedSelfInfo(rawSelfInfo.accountRoot, rawSelfInfo) : null
|
||||
const isUsableSelfName = (value: string | undefined): value is string => {
|
||||
@@ -313,13 +483,14 @@ export async function runExport(request: ExportRequest, win: BrowserWindow): Pro
|
||||
return true
|
||||
}
|
||||
for (const message of messages) {
|
||||
const target = targetById.get(message.exportConversationId || '')
|
||||
message.exportMediaUrl = undefined
|
||||
message.exportMediaType = undefined
|
||||
message.exportMediaName = undefined
|
||||
message.exportMediaError = undefined
|
||||
message.voiceDataUrl = undefined
|
||||
message.exportShowAvatar = request.includeAvatars !== false
|
||||
const mappedName = message.senderId ? request.nameMap?.[message.senderId] : undefined
|
||||
const mappedName = message.senderId ? target?.nameMap?.[message.senderId] : undefined
|
||||
if (mappedName && (!message.isSender || isUsableSelfName(mappedName))) {
|
||||
message.name = mappedName
|
||||
} else if (message.isSender && isUsableSelfName(selfInfo?.nickname)) {
|
||||
@@ -357,7 +528,7 @@ export async function runExport(request: ExportRequest, win: BrowserWindow): Pro
|
||||
? join(outputDir, 'index.html')
|
||||
: join(root, `${outputFolder}.${ext}`)
|
||||
if (request.format === 'html') {
|
||||
const previousArchive = await readHtmlArchive(outputDir, request.userMd5, request.name)
|
||||
const previousArchive = await readHtmlArchive(outputDir, targets, archiveName)
|
||||
await fs.mkdir(join(outputDir, 'voices'), { recursive: true })
|
||||
await fs.mkdir(join(outputDir, 'media'), { recursive: true })
|
||||
await fs.mkdir(join(outputDir, 'avatars'), { recursive: true })
|
||||
@@ -369,10 +540,14 @@ export async function runExport(request: ExportRequest, win: BrowserWindow): Pro
|
||||
.filter((value): value is string => Boolean(value))
|
||||
)
|
||||
)
|
||||
const requestedAvatarUrls = Object.assign(
|
||||
{},
|
||||
...targets.map((target) => target.avatarUrls || {})
|
||||
) as Record<string, string>
|
||||
const avatarMap =
|
||||
request.includeAvatars === false
|
||||
? {}
|
||||
: { ...chat.getContactAvatars(avatarUsernames), ...(request.avatarUrls || {}) }
|
||||
: { ...(await chat.getContactAvatars(avatarUsernames)), ...requestedAvatarUrls }
|
||||
const imageConfig = imageKeys.getConfig()
|
||||
const imageService =
|
||||
client && imageConfig.aesKey
|
||||
@@ -382,13 +557,27 @@ export async function runExport(request: ExportRequest, win: BrowserWindow): Pro
|
||||
const stickerService = client ? new StickerService(client) : null
|
||||
const fileService = client ? new FileAssetService(client) : null
|
||||
const exportedAvatars = new Map<string, string>()
|
||||
const conversationAvatarUrls = new Map<string, string>()
|
||||
if (request.includeAvatars !== false) {
|
||||
for (const target of targets) {
|
||||
if (!jobs.has(request.jobId)) throw new Error('已取消')
|
||||
if (!target.avatarUrl) continue
|
||||
const resolved = await readAvatarAsset(target.avatarUrl)
|
||||
if (!resolved) continue
|
||||
const avatarName = `conversation_${hashPart(target.userMd5)}.${resolved.extension}`
|
||||
await fs.writeFile(join(outputDir, 'avatars', avatarName), resolved.buffer)
|
||||
conversationAvatarUrls.set(target.userMd5, `avatars/${avatarName}`)
|
||||
}
|
||||
}
|
||||
const voiceService =
|
||||
request.includeMedia && chat.getChatDb()
|
||||
? new VoiceService(chat.getChatDb()!.getWcdb4Client())
|
||||
: null
|
||||
if (voiceService) {
|
||||
for (const message of messages) {
|
||||
if (!jobs.has(request.jobId)) throw new Error('已取消')
|
||||
if (kindOf(message) !== 'voice') continue
|
||||
const conversationId = message.exportConversationId || targets[0].userMd5
|
||||
if (!message.sessionId || message.localId == null || !message.createTime) {
|
||||
keepMediaError(request, message, '语音标识不完整,无法定位本地语音')
|
||||
continue
|
||||
@@ -410,7 +599,7 @@ export async function runExport(request: ExportRequest, win: BrowserWindow): Pro
|
||||
keepMediaError(request, message, reason)
|
||||
continue
|
||||
}
|
||||
const voiceName = `voice_${hashPart(exportMessageKey(message, request.userMd5))}.wav`
|
||||
const voiceName = `voice_${hashPart(exportMessageKey(message, conversationId))}.wav`
|
||||
const audioBuffer = Buffer.from(voice.data, 'base64')
|
||||
await fs.writeFile(join(outputDir, 'voices', voiceName), audioBuffer)
|
||||
message.voiceDataUrl = `voices/${voiceName}`
|
||||
@@ -431,14 +620,26 @@ export async function runExport(request: ExportRequest, win: BrowserWindow): Pro
|
||||
}
|
||||
}
|
||||
for (const [index, message] of messages.entries()) {
|
||||
if (!jobs.has(request.jobId)) {
|
||||
send({
|
||||
jobId: request.jobId,
|
||||
phase: 'cancelled',
|
||||
processed: index,
|
||||
total: messages.length,
|
||||
percent: 15 + Math.round((index / Math.max(messages.length, 1)) * 75)
|
||||
})
|
||||
return { success: false, error: '已取消' }
|
||||
}
|
||||
const conversationId = message.exportConversationId || targets[0].userMd5
|
||||
message.exportShowAvatar = request.includeAvatars !== false
|
||||
const avatar = (message.senderId ? avatarMap[message.senderId] : undefined) || message.img
|
||||
const resolvedAvatar = avatar ? await readAvatarAsset(avatar) : null
|
||||
const avatarBuffer = resolvedAvatar?.buffer || null
|
||||
const avatarExtension = resolvedAvatar?.extension || 'jpg'
|
||||
if (avatarBuffer) {
|
||||
const avatarKey =
|
||||
message.senderId || avatar || `message_${exportMessageKey(message, request.userMd5)}`
|
||||
const avatarKey = `${conversationId}:${
|
||||
message.senderId || avatar || `message_${exportMessageKey(message, conversationId)}`
|
||||
}`
|
||||
let avatarName = exportedAvatars.get(avatarKey)
|
||||
if (!avatarName) {
|
||||
avatarName = `avatar_${hashPart(avatarKey)}.${avatarExtension}`
|
||||
@@ -472,7 +673,7 @@ export async function runExport(request: ExportRequest, win: BrowserWindow): Pro
|
||||
allowThumbnail: attempt.allowThumbnail,
|
||||
preferThumbnail: attempt.preferThumbnail,
|
||||
sessionId: message.sessionId,
|
||||
sessionMd5: request.userMd5,
|
||||
sessionMd5: conversationId,
|
||||
createTime: message.createTime
|
||||
}
|
||||
)
|
||||
@@ -497,7 +698,7 @@ export async function runExport(request: ExportRequest, win: BrowserWindow): Pro
|
||||
}
|
||||
const decoded = decryptedImage ? decodeDataUrl(decryptedImage.data) : null
|
||||
if (decoded) {
|
||||
const name = `image_${hashPart(exportMessageKey(message, request.userMd5))}.${decoded.extension}`
|
||||
const name = `image_${hashPart(exportMessageKey(message, conversationId))}.${decoded.extension}`
|
||||
await fs.writeFile(join(outputDir, 'media', name), decoded.buffer)
|
||||
message.exportMediaUrl = `media/${name}`
|
||||
message.exportMediaType = 'image'
|
||||
@@ -534,8 +735,8 @@ export async function runExport(request: ExportRequest, win: BrowserWindow): Pro
|
||||
} else if (extname(source).toLowerCase() !== '.mp4') {
|
||||
keepMediaError(request, message, '视频格式不支持,仅支持本地 MP4 文件')
|
||||
} else {
|
||||
const name = `video_${hashPart(exportMessageKey(message, request.userMd5))}.mp4`
|
||||
await fs.copyFile(source, join(outputDir, 'media', name))
|
||||
const name = `video_${hashPart(exportMessageKey(message, conversationId))}.mp4`
|
||||
await copyWritableExportFile(source, join(outputDir, 'media', name))
|
||||
message.exportMediaUrl = `media/${name}`
|
||||
message.exportMediaType = 'video'
|
||||
}
|
||||
@@ -549,7 +750,7 @@ export async function runExport(request: ExportRequest, win: BrowserWindow): Pro
|
||||
? await readAvatarAsset(stickerSource)
|
||||
: null
|
||||
if (decoded) {
|
||||
const name = `sticker_${hashPart(exportMessageKey(message, request.userMd5))}.${decoded.extension}`
|
||||
const name = `sticker_${hashPart(exportMessageKey(message, conversationId))}.${decoded.extension}`
|
||||
await fs.writeFile(join(outputDir, 'media', name), decoded.buffer)
|
||||
message.exportMediaUrl = `media/${name}`
|
||||
message.exportMediaType = 'sticker'
|
||||
@@ -564,8 +765,8 @@ export async function runExport(request: ExportRequest, win: BrowserWindow): Pro
|
||||
if (!resolved.success || !resolved.filePath || !resolved.fileName) {
|
||||
keepMediaError(request, message, resolved.error || '本地文件附件缺失')
|
||||
} else {
|
||||
const name = `file_${hashPart(exportMessageKey(message, request.userMd5))}_${safeFilePart(resolved.fileName)}`
|
||||
await fs.copyFile(resolved.filePath, join(outputDir, 'media', name))
|
||||
const name = `file_${hashPart(exportMessageKey(message, conversationId))}_${safeFilePart(resolved.fileName)}`
|
||||
await copyWritableExportFile(resolved.filePath, join(outputDir, 'media', name))
|
||||
message.exportMediaUrl = `media/${name}`
|
||||
message.exportMediaType = 'file'
|
||||
message.exportMediaName = message.contentData.title || resolved.fileName
|
||||
@@ -583,26 +784,53 @@ export async function runExport(request: ExportRequest, win: BrowserWindow): Pro
|
||||
const mergedMessages = mergeHtmlArchiveMessages(
|
||||
previousArchive.messages,
|
||||
messages,
|
||||
request.userMd5
|
||||
'',
|
||||
targets.map((target) => target.userMd5)
|
||||
)
|
||||
const normalizedMessages = normalizeHtmlArchiveSelfNames(mergedMessages, selfInfo)
|
||||
const archive: HtmlExportArchive = {
|
||||
version: 1,
|
||||
sourceId: request.userMd5,
|
||||
name: request.name,
|
||||
version: 2,
|
||||
name: archiveName,
|
||||
exportedAt: new Date().toISOString(),
|
||||
messages: normalizeHtmlArchiveSelfNames(mergedMessages, selfInfo)
|
||||
conversations: targets.map((target) => ({
|
||||
id: target.userMd5,
|
||||
name: target.name,
|
||||
type: target.type,
|
||||
avatarUrl:
|
||||
conversationAvatarUrls.get(target.userMd5) ||
|
||||
previousArchive.conversations.find((item) => item.id === target.userMd5)?.avatarUrl,
|
||||
messageCount: normalizedMessages.filter(
|
||||
(message) => message.exportConversationId === target.userMd5
|
||||
).length
|
||||
})),
|
||||
messages: normalizedMessages
|
||||
}
|
||||
await fs.writeFile(outputPath, renderExportPage(request.name), 'utf8')
|
||||
if (!jobs.has(request.jobId)) throw new Error('已取消')
|
||||
await fs.writeFile(outputPath, renderExportPage(archiveName), 'utf8')
|
||||
await writeHtmlArchive(outputDir, archive)
|
||||
let completedPath = outputPath
|
||||
if (request.zip) {
|
||||
if (!jobs.has(request.jobId)) return { success: false, error: '已取消' }
|
||||
const zipPath = join(root, `${outputFolder}.zip`)
|
||||
send({
|
||||
jobId: request.jobId,
|
||||
phase: 'compressing',
|
||||
processed: archive.messages.length,
|
||||
total: archive.messages.length,
|
||||
percent: 95
|
||||
})
|
||||
await writeZipArchive(outputDir, zipPath, outputFolder, request.jobId)
|
||||
completedPath = zipPath
|
||||
}
|
||||
send({
|
||||
jobId: request.jobId,
|
||||
phase: 'completed',
|
||||
processed: archive.messages.length,
|
||||
total: archive.messages.length,
|
||||
percent: 100,
|
||||
outputPath
|
||||
outputPath: completedPath
|
||||
})
|
||||
return { success: true, outputPath, messageCount: archive.messages.length }
|
||||
return { success: true, outputPath: completedPath, messageCount: archive.messages.length }
|
||||
} else {
|
||||
send({
|
||||
jobId: request.jobId,
|
||||
@@ -612,7 +840,7 @@ export async function runExport(request: ExportRequest, win: BrowserWindow): Pro
|
||||
percent: 90
|
||||
})
|
||||
}
|
||||
await fs.writeFile(outputPath, render(request.format, messages, request.name), 'utf8')
|
||||
await fs.writeFile(outputPath, render(request.format, messages, archiveName), 'utf8')
|
||||
send({
|
||||
jobId: request.jobId,
|
||||
phase: 'completed',
|
||||
@@ -624,6 +852,10 @@ export async function runExport(request: ExportRequest, win: BrowserWindow): Pro
|
||||
return { success: true, outputPath, messageCount: messages.length }
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : String(error)
|
||||
if (!jobs.has(request.jobId) || message === '已取消') {
|
||||
send({ jobId: request.jobId, phase: 'cancelled', processed: 0, error: '已取消' })
|
||||
return { success: false, error: '已取消' }
|
||||
}
|
||||
send({ jobId: request.jobId, phase: 'failed', processed: 0, error: message })
|
||||
return { success: false, error: message }
|
||||
} finally {
|
||||
@@ -632,6 +864,7 @@ export async function runExport(request: ExportRequest, win: BrowserWindow): Pro
|
||||
}
|
||||
export function cancelExport(jobId: string): void {
|
||||
jobs.delete(jobId)
|
||||
activeArchives.get(jobId)?.abort()
|
||||
}
|
||||
export async function revealExport(path: string): Promise<void> {
|
||||
shell.showItemInFolder(path)
|
||||
|
||||
Reference in New Issue
Block a user