From b86582e60622f5d702ca5b98e43d61ee28614f41 Mon Sep 17 00:00:00 2001
From: Wxw-Gu <84499436+Wxw-Gu@users.noreply.github.com>
Date: Thu, 19 Nov 2026 17:53:35 +0800
Subject: [PATCH] =?UTF-8?q?feat:=20=E6=A1=A3=E6=A1=88=E5=92=8C=E5=AF=BC?=
=?UTF-8?q?=E5=87=BA=E9=A1=B5=E9=9D=A2=E6=94=AF=E6=8C=81=E6=9F=A5=E7=9C=8B?=
=?UTF-8?q?=E5=A4=9A=E9=80=89=E6=B6=88=E6=81=AF?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
examples/extensions/group-chat-bot/README.md | 5 +
examples/extensions/template-lock.json | 4 +-
src/main/export-html-template.ts | 450 ++++++++++++++++--
src/main/export-service.ts | 86 ++++
src/main/image-decrypt-service.ts | 189 +++++++-
src/main/message-parser.ts | 259 ++++++++--
src/main/services/automation-action-runner.ts | 4 +-
src/main/services/chat-service.ts | 4 +
src/main/video-asset-service.ts | 7 +-
src/main/wcdb4-client.ts | 196 +++++++-
.../src/components/ForwardBundleModal.tsx | 241 ++++++++++
.../src/components/RichMessageBubble.tsx | 136 ++++--
src/renderer/src/styles/rich-message.scss | 262 ++++++++++
src/shared/image-quality.ts | 7 +-
src/shared/types.ts | 14 +
tests/component/forward-bundle-modal.test.tsx | 75 +++
tests/unit/export-media.test.ts | 50 ++
tests/unit/message-parser.test.ts | 41 +-
tests/unit/video-asset-service.test.ts | 19 +
19 files changed, 1897 insertions(+), 152 deletions(-)
create mode 100644 src/renderer/src/components/ForwardBundleModal.tsx
create mode 100644 tests/component/forward-bundle-modal.test.tsx
diff --git a/examples/extensions/group-chat-bot/README.md b/examples/extensions/group-chat-bot/README.md
index 9aa51ad..fd3ef86 100644
--- a/examples/extensions/group-chat-bot/README.md
+++ b/examples/extensions/group-chat-bot/README.md
@@ -1,5 +1,10 @@
# 群聊机器人 (`com.example.group-chat-bot`)
+> **这是模板壳,不是完整运行包。** 本目录的 `lib/bot-engine.js` 只含纯函数,不含
+> `activateBotRuntime` 运行时。直接把本目录打成 ZIP 安装,后台会走
+> `background/index.js` 的 fallback,预览与测试发送都会提示「当前功能暂不可用」。
+> 可安装的完整包必须包含带运行时的 `lib/bot-engine.js`;不要把本目录当成品分发。
+
TraceMemo 官方扩展模板。结合 TraceMemo 已配置的 AI 模型与文字转语音(TTS)音色,在指定微信群聊中按角色设定自然接话,支持单群长期记忆与随机回复文字 / 随机发送语音。
## 核心特性
diff --git a/examples/extensions/template-lock.json b/examples/extensions/template-lock.json
index e3c3747..2410c53 100644
--- a/examples/extensions/template-lock.json
+++ b/examples/extensions/template-lock.json
@@ -14,8 +14,8 @@
"bytes": 33471
},
"group-chat-bot@1.0.0": {
- "sha256": "122a4da7710cf882975f09440819e9dc1b619e4bd6f94153085a7d6fe8a33885",
- "bytes": 24981
+ "sha256": "eb672f076710619dc363756d854319a8ded9b8f6a4833c258c1493c57bb89629",
+ "bytes": 25231
},
"keyword-bot@1.0.0": {
"sha256": "3d8e5453e7ae6de7e29c16eb3c9e718a98bae27e9ed2edfd10399fb158e1c87d",
diff --git a/src/main/export-html-template.ts b/src/main/export-html-template.ts
index 04af63a..718000e 100644
--- a/src/main/export-html-template.ts
+++ b/src/main/export-html-template.ts
@@ -646,18 +646,245 @@ body {
border-radius: 4px;
object-fit: cover;
}
-.forward-content details { margin-top: 2px; }
-.forward-content summary {
- color: var(--accent);
+.forward-content.is-clickable {
cursor: pointer;
+}
+.forward-content.is-clickable:hover .forward-footer-action {
+ color: var(--accent);
+}
+.forward-preview-list {
+ display: grid;
+ gap: 5px;
+ margin-top: 6px;
+}
+.forward-preview-line {
+ display: flex;
+ gap: 5px;
+ color: var(--muted);
font-size: 12px;
+ line-height: 1.45;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+.forward-preview-line strong {
+ color: var(--ink);
+ font-weight: 600;
+ flex: 0 0 auto;
+}
+.forward-footer {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ margin-top: 8px;
+ padding-top: 7px;
+ border-top: 1px solid var(--line);
+ color: var(--muted);
+ font-size: 11px;
+}
+.forward-footer-action {
+ transition: color .15s ease;
+}
+.forward-modal-backdrop {
+ position: fixed;
+ inset: 0;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ padding: 24px;
+ background: rgba(15, 23, 42, 0.36);
+}
+.forward-modal-window {
+ display: flex;
+ flex-direction: column;
+ width: min(560px, calc(100vw - 48px));
+ max-height: min(78vh, 720px);
+ overflow: hidden;
+ border: 1px solid var(--line);
+ border-radius: 14px;
+ background: #ffffff;
+ color: var(--ink);
+ box-shadow: 0 20px 48px rgba(15, 23, 42, 0.22);
+}
+.forward-modal-header {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 12px;
+ padding: 14px 18px;
+ border-bottom: 1px solid var(--line);
+ background: #f8fafc;
+}
+.forward-modal-header-text {
+ min-width: 0;
+ display: flex;
+ flex-direction: column;
+ gap: 2px;
+}
+.forward-modal-title {
+ margin: 0;
+ overflow: hidden;
+ font-size: 15px;
+ font-weight: 650;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+.forward-modal-subtitle {
+ color: var(--muted);
+ font-size: 12px;
+}
+.forward-modal-close {
+ flex: 0 0 auto;
+ width: 28px;
+ height: 28px;
+ border: 0;
+ border-radius: 8px;
+ background: transparent;
+ color: var(--muted);
+ font-size: 20px;
+ line-height: 1;
+ cursor: pointer;
+}
+.forward-modal-close:hover {
+ background: rgba(15, 23, 42, 0.08);
+ color: var(--ink);
+}
+.forward-modal-body {
+ flex: 1;
+ overflow-y: auto;
+ padding: 16px 18px;
+ display: flex;
+ flex-direction: column;
+ gap: 16px;
+}
+.forward-modal-row {
+ display: grid;
+ grid-template-columns: 36px minmax(0, 1fr);
+ gap: 10px;
+ align-items: start;
+}
+.forward-modal-avatar {
+ width: 36px;
+ height: 36px;
+ border-radius: 8px;
+ overflow: hidden;
+ background: rgba(7, 193, 96, 0.14);
+ color: var(--accent);
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ font-size: 14px;
font-weight: 650;
}
-.forward-list, .forward-list ol {
+.forward-modal-avatar img {
+ width: 100%;
+ height: 100%;
+ object-fit: cover;
+}
+.forward-modal-row-main {
+ min-width: 0;
+ display: flex;
+ flex-direction: column;
+ gap: 6px;
+ padding-bottom: 12px;
+ border-bottom: 1px solid var(--line);
+}
+.forward-modal-row:last-child .forward-modal-row-main {
+ padding-bottom: 0;
+ border-bottom: 0;
+}
+.forward-modal-row-meta {
+ display: flex;
+ align-items: baseline;
+ justify-content: space-between;
+ gap: 12px;
+}
+.forward-modal-sender {
+ font-size: 13px;
+ font-weight: 650;
+ color: var(--ink);
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+.forward-modal-time {
+ flex: 0 0 auto;
+ font-size: 11px;
+ color: var(--muted);
+}
+.forward-modal-text {
+ font-size: 13px;
+ line-height: 1.6;
+ white-space: pre-wrap;
+ word-break: break-word;
+}
+.forward-modal-link {
+ margin-left: 8px;
+ color: var(--accent);
+ font-size: 12px;
+ text-decoration: none;
+}
+.forward-modal-link:hover {
+ text-decoration: underline;
+}
+.forward-modal-image {
+ display: block;
+ max-width: min(240px, 100%);
+ max-height: 320px;
+ border-radius: 8px;
+ border: 1px solid var(--line);
+ object-fit: contain;
+ cursor: zoom-in;
+}
+.forward-modal-image-missing {
+ display: inline-block;
+ padding: 6px 10px;
+ border-radius: 8px;
+ background: #f1f5f9;
+ color: var(--muted);
+ font-size: 12px;
+}
+.forward-modal-nested-card {
+ width: min(320px, 100%);
+ padding: 10px 12px;
+ border: 1px solid var(--line);
+ border-radius: 10px;
+ background: #f8fafc;
+ color: inherit;
+ text-align: left;
display: grid;
- gap: 7px;
- margin: 8px 0 0;
- padding-left: 18px;
+ gap: 6px;
+ cursor: pointer;
+}
+.forward-modal-nested-card:hover {
+ border-color: var(--accent);
+}
+.forward-modal-nested-title {
+ font-size: 13px;
+ font-weight: 650;
+ color: var(--ink);
+}
+.forward-modal-nested-line {
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ font-size: 12px;
+ color: var(--muted);
+}
+.forward-modal-nested-footer {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ padding-top: 6px;
+ border-top: 1px solid var(--line);
+ font-size: 11px;
+ color: var(--muted);
+}
+.forward-modal-empty {
+ padding: 32px 0;
+ text-align: center;
+ color: var(--muted);
+ font-size: 13px;
}
.forward-item { color: var(--muted); font-size: 12px; line-height: 1.5; }
.forward-item strong { color: var(--text); font-weight: 650; }
@@ -687,7 +914,7 @@ body {
display: none;
place-items: center;
background: #14231ddd;
- z-index: 10;
+ z-index: 80;
padding: 24px;
overflow: auto;
}
@@ -705,7 +932,7 @@ body {
position: fixed;
top: 20px;
right: 20px;
- z-index: 11;
+ z-index: 81;
width: 42px;
height: 42px;
border: 1px solid #ffffff66;
@@ -1121,27 +1348,26 @@ const renderExportScript = (name: string): string => `
(iconUrl ? '
' : '') +
'' + displayText(data.appName || '小程序') + ''
}
- const renderForwardItems = (items, depth = 0) => {
- if (!Array.isArray(items) || !items.length || depth > 4) return ''
- return '
' + items.map((item) =>
- '- ' +
- (item.sender ? '' + displayText(item.sender) + '' : '') +
- (item.sentAt ? '' : '') +
- '' + displayText(item.text || '[消息]') + '' +
- renderForwardItems(item.nested, depth + 1) + '
'
- ).join('') + '
'
- }
- const renderForwardContent = (data) => {
+ const renderForwardContent = (data, archiveIndex) => {
const items = Array.isArray(data.items) ? data.items : []
- return '' +
+ const previewItems = items.slice(0, 4)
+ const previewHtml = previewItems.length
+ ? '
' + previewItems.map((item) =>
+ '
' +
+ (item.sender ? '' + displayText(item.sender) + ':' : '') +
+ '' + displayText(item.text || '[消息]') + '
'
+ ).join('') + '
'
+ : (data.description
+ ? '
' + displayText(data.description) + '
'
+ : '')
+ return '
' +
'
聊天记录
' +
'
' + displayText(data.title || '聊天记录') + '
' +
- (!items.length && data.description
- ? '
' + displayText(data.description) + '
'
- : '') +
- (items.length
- ? '
展开 ' + items.length + ' 条消息
' + renderForwardItems(items) + ''
- : '') + '
'
+ previewHtml +
+ '
'
}
const renderLocationContent = (data) => {
const latitude = Number(data.lat)
@@ -1195,7 +1421,7 @@ const renderExportScript = (name: string): string => `
displayText([data.status, durationText].filter(Boolean).join(' · ') || '通话消息') +
''
}
- const renderStructuredContent = (data) => {
+ const renderStructuredContent = (data, archiveIndex) => {
if (data.type === 'share') {
const typeVal = String(data.typeVal || '')
if (typeVal === '6' || typeVal === '74') return ''
@@ -1203,7 +1429,7 @@ const renderExportScript = (name: string): string => `
return renderShareContent(data)
}
if (data.type === 'miniProgram') return renderMiniProgramContent(data)
- if (data.type === 'forwardBundle') return renderForwardContent(data)
+ if (data.type === 'forwardBundle') return renderForwardContent(data, archiveIndex)
if (data.type === 'location') return renderLocationContent(data)
if (data.type === 'redPacket') return renderPaymentContent(data, 'redPacket')
if (data.type === 'voip') return renderVoipContent(data)
@@ -1248,7 +1474,7 @@ const renderExportScript = (name: string): string => `
const quote = data.type === 'quote'
? '' + esc(data.quotedSender || '引用消息') + '' + esc(data.quotedContent || '[引用消息]') + '
'
: ''
- const structured = renderStructuredContent(data)
+ const structured = renderStructuredContent(data, archiveIndex)
const isSystem = data.type === 'system'
const sender = message.name || (message.isSender ? '我' : '联系人')
const avatarFallback = esc(String(sender || '友').slice(0, 1))
@@ -1803,25 +2029,174 @@ const renderExportScript = (name: string): string => `
if (dayButton) jumpToDate(dayButton.dataset.date)
})
+ const forwardModalRoot = document.getElementById('forward-modal-root')
+ let forwardModalLayers = []
+
+ const formatForwardTime = (raw) => {
+ const value = String(raw || '').trim()
+ if (!value) return ''
+ if (/^\\d{9,13}$/.test(value)) {
+ const ms = value.length > 10 ? Number(value) : Number(value) * 1000
+ const date = new Date(ms)
+ if (!Number.isNaN(date.getTime())) {
+ return date.getFullYear() + '-' + pad(date.getMonth() + 1) + '-' + pad(date.getDate()) +
+ ' ' + pad(date.getHours()) + ':' + pad(date.getMinutes())
+ }
+ }
+ return value
+ }
+
+ const renderForwardModalRow = (item, layerIndex, itemIndex) => {
+ const sender = item.sender || '未知发送者'
+ const initial = esc(Array.from(String(sender).trim())[0] || '?')
+ const headUrl = externalUrl(item.sourceHeadUrl || '')
+ const avatarHtml = headUrl
+ ? ''
+ : '' + initial + '
'
+ const timeText = formatForwardTime(item.sentAt)
+ const isNested = item.messageType === 17 || (Array.isArray(item.nested) && item.nested.length > 0)
+ const isImage = !isNested && (item.messageType === 2 || Boolean(item.exportMediaUrl || item.imageMd5 || item.thumbMd5 || item.imageDatName))
+ let bodyHtml = ''
+ if (isNested) {
+ const nestedTitle = item.nestedTitle || item.title || '聊天记录'
+ const nestedItems = Array.isArray(item.nested) ? item.nested : []
+ const previewLines = nestedItems.slice(0, 3).map((child) =>
+ '' +
+ (child.sender ? esc(child.sender) + ': ' : '') +
+ displayText(child.text || '[消息]') + '
'
+ ).join('')
+ bodyHtml = ''
+ } else if (isImage) {
+ bodyHtml = item.exportMediaUrl
+ ? '
'
+ : '[图片未导出到本地]'
+ } else {
+ const linkHref = externalUrl(item.linkUrl || '')
+ bodyHtml = '' + displayText(item.text || item.title || '[消息]') +
+ (linkHref ? '
打开链接 ↗' : '') +
+ '
'
+ }
+ return '' + avatarHtml +
+ ''
+ }
+
+ const renderForwardModals = () => {
+ if (!forwardModalRoot) return
+ if (!forwardModalLayers.length) {
+ forwardModalRoot.innerHTML = ''
+ return
+ }
+ forwardModalRoot.innerHTML = forwardModalLayers.map((layer, index) => {
+ const zIndex = Math.min(75, 30 + index)
+ const offsetX = Math.min(index, 5) * 28
+ const offsetY = Math.min(index, 5) * 24
+ const items = Array.isArray(layer.items) ? layer.items : []
+ const rowsHtml = items.length
+ ? items.map((item, itemIdx) => renderForwardModalRow(item, index, itemIdx)).join('')
+ : '暂未解析到可展示的记录
'
+ return ''
+ }).join('')
+ }
+
+ const openForwardModal = (titleText, items) => {
+ forwardModalLayers = [{ title: titleText || '聊天记录', items: Array.isArray(items) ? items : [] }]
+ renderForwardModals()
+ }
+
+ const pushNestedForwardModal = (layerIndex, itemIndex) => {
+ const parentLayer = forwardModalLayers[layerIndex]
+ const item = parentLayer && Array.isArray(parentLayer.items) ? parentLayer.items[itemIndex] : null
+ if (!item || !Array.isArray(item.nested) || !item.nested.length) return
+ forwardModalLayers = forwardModalLayers.slice(0, layerIndex + 1).concat([{
+ title: item.nestedTitle || item.title || '聊天记录',
+ items: item.nested
+ }])
+ renderForwardModals()
+ }
+
+ const closeForwardModalFrom = (index) => {
+ forwardModalLayers = forwardModalLayers.slice(0, index)
+ renderForwardModals()
+ }
+
const updateZoom = () => preview.style.setProperty('--zoom', zoom)
const closeLightbox = () => {
box.classList.remove('open')
zoom = 1
updateZoom()
}
+ const openLightbox = (src) => {
+ preview.src = src
+ zoom = 1
+ updateZoom()
+ box.classList.add('open')
+ }
list.addEventListener('click', (event) => {
const locateButton = event.target.closest('[data-locate-index]')
if (locateButton) {
locateInAll(Number(locateButton.dataset.locateIndex))
return
}
+ const forwardCard = event.target.closest('[data-forward-open]')
+ if (forwardCard) {
+ const msgIndex = Number(forwardCard.dataset.forwardOpen)
+ // data-forward-open 写的是 filtered 下标(renderWindow 用 windowStart + index),
+ // 不能用 allMessages[msgIndex]:切会话 / 搜索 / 按类型筛选后 filtered 会比全集短。
+ const targetMessage = filtered[msgIndex]
+ const bundle = targetMessage && targetMessage.contentData
+ if (bundle && bundle.type === 'forwardBundle') {
+ openForwardModal(bundle.title || '聊天记录', bundle.items || [])
+ }
+ return
+ }
const image = event.target.closest('img[data-preview]')
if (!image) return
- preview.src = image.src
- zoom = 1
- updateZoom()
- box.classList.add('open')
+ openLightbox(image.src)
})
+ if (forwardModalRoot) {
+ forwardModalRoot.addEventListener('click', (event) => {
+ const closeBtn = event.target.closest('[data-forward-close]')
+ if (closeBtn) {
+ closeForwardModalFrom(Number(closeBtn.dataset.forwardClose))
+ return
+ }
+ const nestedBtn = event.target.closest('[data-forward-nested-layer]')
+ if (nestedBtn) {
+ pushNestedForwardModal(
+ Number(nestedBtn.dataset.forwardNestedLayer),
+ Number(nestedBtn.dataset.forwardNestedItem)
+ )
+ return
+ }
+ const img = event.target.closest('img[data-preview]')
+ if (img) {
+ openLightbox(img.src)
+ return
+ }
+ const backdrop = event.target.closest('[data-forward-backdrop]')
+ if (backdrop && event.target === backdrop) {
+ closeForwardModalFrom(Number(backdrop.dataset.forwardBackdrop))
+ }
+ })
+ }
preview.addEventListener('wheel', (event) => {
event.preventDefault()
zoom = Math.min(5, Math.max(.5, zoom + (event.deltaY < 0 ? .2 : -.2)))
@@ -1837,7 +2212,11 @@ const renderExportScript = (name: string): string => `
closeButton.addEventListener('click', closeLightbox)
document.addEventListener('keydown', (event) => {
if (event.key === 'Escape') {
- closeLightbox()
+ if (box.classList.contains('open')) {
+ closeLightbox()
+ } else if (forwardModalLayers.length > 0) {
+ closeForwardModalFrom(forwardModalLayers.length - 1)
+ }
setConversationMenuOpen(false)
}
})
@@ -1940,6 +2319,7 @@ export function renderExportPage(name: string): string {
+
![预览]()
diff --git a/src/main/export-service.ts b/src/main/export-service.ts
index 08b8801..5a315a3 100644
--- a/src/main/export-service.ts
+++ b/src/main/export-service.ts
@@ -524,11 +524,28 @@ export async function pruneHtmlArchiveResources(
referenced[directory].add(fileName)
}
+ const addForwardBundleReferences = (
+ items?: Array<{ exportMediaUrl?: string; nested?: Array<{ exportMediaUrl?: string; nested?: unknown[] }> }>
+ ): void => {
+ if (!Array.isArray(items)) return
+ for (const item of items) {
+ addReference(item.exportMediaUrl)
+ if (Array.isArray(item.nested)) {
+ addForwardBundleReferences(
+ item.nested as Array<{ exportMediaUrl?: string; nested?: Array<{ exportMediaUrl?: string; nested?: unknown[] }> }>
+ )
+ }
+ }
+ }
+
for (const conversation of archive.conversations) addReference(conversation.avatarUrl)
for (const message of archive.messages) {
addReference(message.voiceDataUrl)
addReference(message.exportMediaUrl)
addReference(message.exportAvatarUrl)
+ if (message.contentData?.type === 'forwardBundle') {
+ addForwardBundleReferences(message.contentData.items)
+ }
}
for (const [directory, prefixes] of Object.entries(htmlArchiveResourcePrefixes) as [
@@ -1513,6 +1530,75 @@ async function runSingleExport(
} else {
keepMediaError(request, message, result.error || '表情资源缺失或下载失败')
}
+ } else if (message.contentData.type === 'forwardBundle' && imageService) {
+ const exportForwardItems = async (
+ items: Array<{
+ messageType: number
+ imageMd5?: string
+ thumbMd5?: string
+ imageDatName?: string
+ exportMediaUrl?: string
+ nested?: unknown[]
+ }>,
+ depth = 0
+ ): Promise
=> {
+ if (!Array.isArray(items) || depth > 8) return
+ for (const item of items) {
+ if (Array.isArray(item.nested) && item.nested.length > 0) {
+ await exportForwardItems(
+ item.nested as typeof items,
+ depth + 1
+ )
+ continue
+ }
+ const isForwardImage =
+ item.messageType === 2 ||
+ Boolean(item.imageMd5 || item.thumbMd5 || item.imageDatName)
+ if (!isForwardImage) continue
+ if (item.exportMediaUrl && (await resourceExists(item.exportMediaUrl))) {
+ continue
+ }
+ let decryptedImage: { data: string; filePath: string } | null = null
+ for (const attempt of getImageExportAttempts(request)) {
+ const file = await imageService.findImageFileAsync(
+ item.imageMd5 || item.thumbMd5,
+ item.imageDatName,
+ {
+ allowThumbnail: attempt.allowThumbnail,
+ preferThumbnail: attempt.preferThumbnail,
+ sessionId: message.sessionId,
+ sessionMd5: conversationId,
+ createTime: message.createTime
+ }
+ )
+ if (!file) continue
+ let decrypted = await imageService.decryptImageToBase64WithFallbackAsync(
+ file,
+ attempt.allowThumbnail
+ )
+ if (!decrypted) {
+ decrypted = imageService.decryptImageToBase64WithFallback(
+ file,
+ attempt.allowThumbnail
+ )
+ }
+ if (!decrypted) continue
+ decryptedImage = decrypted
+ break
+ }
+ const decoded = decryptedImage ? decodeDataUrl(decryptedImage.data) : null
+ if (decoded) {
+ const name = `image_${bufferHashPart(decoded.buffer)}.${decoded.extension}`
+ const mediaUrl = `media/${name}`
+ if (!(await resourceExists(mediaUrl))) {
+ await fs.writeFile(join(outputDir, 'media', name), decoded.buffer)
+ markResourceExists(mediaUrl)
+ }
+ item.exportMediaUrl = mediaUrl
+ }
+ }
+ }
+ await exportForwardItems(message.contentData.items)
} else if (message.contentData.type === 'share' && message.contentData.typeVal === '6') {
if (!fileService) {
keepMediaError(request, message, '数据库未连接,无法定位本地文件附件')
diff --git a/src/main/image-decrypt-service.ts b/src/main/image-decrypt-service.ts
index c21a00e..53be875 100644
--- a/src/main/image-decrypt-service.ts
+++ b/src/main/image-decrypt-service.ts
@@ -210,12 +210,16 @@ function normalizeDatBase(value) {
function isThumbnailName(fileName) {
const lower = fileName.toLowerCase()
+ if (!lower.endsWith('.dat')) {
+ return /(?:_t(?:_m)?|_thumb|\.thumb)$/i.test(lower)
+ }
return /(?:_t(?:_m)?|_thumb|\.thumb|_b|_w|_c)\.dat$/i.test(lower)
}
function imageQualityRank(fileName) {
const lower = fileName.toLowerCase()
- if (/(?:_t(?:_m)?|_thumb|\.thumb|_b|_w|_c)\.dat$/i.test(lower)) return 1
+ if (isThumbnailName(lower)) return 1
+ if (!lower.endsWith('.dat')) return 3
if (/(?:_hd|\.hd|_h_m|_h|\.h)\.dat$/i.test(lower)) return 3
return 2
}
@@ -239,6 +243,20 @@ function buildPreferredDatNames(baseName) {
]
}
+function buildExtensionlessVariantNames(baseName) {
+ const base = normalizeDatBase(baseName)
+ if (!base) return []
+ return [
+ base + '_hd',
+ base + '_h_M',
+ base + '_h',
+ base + '_M',
+ base,
+ base + '_t_M',
+ base + '_t'
+ ]
+}
+
function detectImageExtension(buffer) {
if (buffer.length < 4) return null
if (buffer[0] === 0xff && buffer[1] === 0xd8 && buffer[2] === 0xff) return '.jpg'
@@ -386,10 +404,6 @@ function decryptCandidate(filePath, aesKey, xorKey, ffmpegPath) {
filePath
}
}
- if (!path.extname(filePath).toLowerCase().includes('dat')) {
- const extension = path.extname(filePath).toLowerCase()
- return { data: 'data:' + getMimeType(extension) + ';base64,' + bytes.toString('base64'), filePath }
- }
if (
bytes.length < 15 ||
bytes[0] !== 0x07 ||
@@ -440,10 +454,12 @@ function decryptCandidate(filePath, aesKey, xorKey, ffmpegPath) {
function collectCandidates(datPath, allowThumbnail) {
const candidates = [datPath]
- if (!path.extname(datPath).toLowerCase().includes('dat')) return candidates
const directory = path.dirname(datPath)
const base = normalizeDatBase(path.basename(datPath))
- const siblings = buildPreferredDatNames(base)
+ const names = path.extname(datPath).toLowerCase().includes('dat')
+ ? buildPreferredDatNames(base)
+ : buildExtensionlessVariantNames(base).concat(buildPreferredDatNames(base))
+ const siblings = names
.filter((name) => allowThumbnail || !isThumbnailName(name))
.map((name) => path.join(directory, name))
.filter((candidate) => fs.existsSync(candidate))
@@ -606,9 +622,23 @@ export class ImageDecryptService {
})
const attachDir = join(accountDir, 'msg', 'attach')
+ const recRef = this.parseForwardRecordImageRef(imageDatName)
+ if (recRef && existsSync(attachDir)) {
+ const recHit = this.findForwardRecordImage(
+ attachDir,
+ recRef.recordDir,
+ recRef.fileIndex,
+ allowThumbnail,
+ options?.preferThumbnail,
+ sessionDirectory,
+ options?.createTime
+ )
+ if (recHit) return rememberPath(recHit)
+ }
+
// The attach directory stores DAT filenames, while the message MD5 often
// identifies the original image rather than the local file.
- const searchKeys = this.uniq([normalizedDatName, normalizedMd5])
+ const searchKeys = this.uniq([recRef ? '' : normalizedDatName, normalizedMd5])
if (sessionDirectory && allowThumbnail && options?.preferThumbnail) {
const bubblePreview = this.findBubblePreview(
@@ -939,7 +969,21 @@ export class ImageDecryptService {
if (!accountDir) return null
const attachDir = join(accountDir, 'msg', 'attach')
- const searchKeys = this.uniq([normalizedDatName, normalizedMd5])
+ const recRef = this.parseForwardRecordImageRef(imageDatName)
+ if (recRef && existsSync(attachDir)) {
+ const recHit = await this.findForwardRecordImageAsync(
+ attachDir,
+ recRef.recordDir,
+ recRef.fileIndex,
+ allowThumbnail,
+ options?.preferThumbnail,
+ sessionDirectory,
+ options?.createTime
+ )
+ if (recHit) return rememberPath(recHit)
+ }
+
+ const searchKeys = this.uniq([recRef ? '' : normalizedDatName, normalizedMd5])
if (allowThumbnail && options?.preferThumbnail) {
const bubblePreview = await this.findBubblePreviewAsync(
accountDir,
@@ -1422,15 +1466,19 @@ export class ImageDecryptService {
if (!extname(datPath).toLowerCase().includes('dat')) {
try {
const data = readFileSync(datPath)
- const ext = this.detectImageExtension(data) || extname(datPath).toLowerCase()
- const mimeType = this.getMimeType(ext)
- this.lastDecodeDiagnostic = {
- code: 'DIRECT_IMAGE',
- detail: '文件本身是可直接读取的图片',
- fileSize: data.length,
- imageFormat: ext.replace(/^\./, '').toUpperCase()
+ const detectedExt = this.detectImageExtension(data)
+ if (detectedExt) {
+ const mimeType = this.getMimeType(detectedExt)
+ this.lastDecodeDiagnostic = {
+ code: 'DIRECT_IMAGE',
+ detail: '文件本身是可直接读取的图片',
+ fileSize: data.length,
+ imageFormat: detectedExt.replace(/^\./, '').toUpperCase()
+ }
+ return `data:${mimeType};base64,${data.toString('base64')}`
}
- return `data:${mimeType};base64,${data.toString('base64')}`
+ // 合并转发 Rec/{token}/Img/{index} 文件没有 .dat 扩展名,但内部仍是 WeChat 4.0 V2 加密 DAT,
+ // 若不是明文图片头则继续向下走 decryptImage 解密。
} catch {
this.lastDecodeDiagnostic = {
code: 'FILE_NOT_FOUND',
@@ -1798,6 +1846,108 @@ export class ImageDecryptService {
]
}
+ private parseForwardRecordImageRef(
+ imageDatName?: string
+ ): { recordDir: string; fileIndex: string } | null {
+ const raw = String(imageDatName || '').trim()
+ const match = /^rec:([a-zA-Z0-9_-]+):(\d+)$/i.exec(raw)
+ if (!match) return null
+ return { recordDir: match[1], fileIndex: match[2] }
+ }
+
+ private buildForwardRecordImageNames(fileIndex: string): string[] {
+ return [
+ `${fileIndex}_hd`,
+ `${fileIndex}_h_M`,
+ `${fileIndex}_h`,
+ `${fileIndex}_M`,
+ `${fileIndex}`,
+ `${fileIndex}_t_M`,
+ `${fileIndex}_t`,
+ `${fileIndex}.dat`,
+ `${fileIndex}_t.dat`
+ ]
+ }
+
+ private findForwardRecordImage(
+ attachDir: string,
+ recordDir: string,
+ fileIndex: string,
+ allowThumbnail: boolean,
+ preferThumbnail = false,
+ sessionDirectory = '',
+ createTime?: number
+ ): string | null {
+ const candidateNames = this.buildForwardRecordImageNames(fileIndex)
+ const sessionDirs = sessionDirectory
+ ? existsSync(join(attachDir, sessionDirectory))
+ ? [sessionDirectory]
+ : []
+ : readdirSync(attachDir).filter((name) => name.length === 32 && /^[a-f0-9]+$/i.test(name))
+
+ for (const sessDir of sessionDirs) {
+ const sessionRoot = join(attachDir, sessDir)
+ const months = sessionDirectory
+ ? this.getImageMonthDirectories(sessionRoot, createTime)
+ : this.getRecentImageMonths(24)
+ for (const month of months) {
+ const recImgDir = join(sessionRoot, month, 'Rec', recordDir, 'Img')
+ if (!existsSync(recImgDir)) continue
+ const found = this.getLargestExistingPath(
+ candidateNames.map((name) => join(recImgDir, name)),
+ allowThumbnail,
+ preferThumbnail
+ )
+ if (found) return found
+ }
+ }
+ return null
+ }
+
+ private async findForwardRecordImageAsync(
+ attachDir: string,
+ recordDir: string,
+ fileIndex: string,
+ allowThumbnail: boolean,
+ preferThumbnail = false,
+ sessionDirectory = '',
+ createTime?: number
+ ): Promise {
+ if (!sessionDirectory) {
+ return this.findForwardRecordImage(
+ attachDir,
+ recordDir,
+ fileIndex,
+ allowThumbnail,
+ preferThumbnail,
+ '',
+ createTime
+ )
+ }
+ const sessionRoot = join(attachDir, sessionDirectory)
+ let months: string[]
+ try {
+ months = (await fsPromises.readdir(sessionRoot, { withFileTypes: true }))
+ .filter((entry) => entry.isDirectory() && /^\d{4}-\d{2}$/.test(entry.name))
+ .map((entry) => entry.name)
+ .sort((left, right) => right.localeCompare(left))
+ } catch {
+ return null
+ }
+ months = this.prioritizeImageMonth(months, createTime)
+ const candidateNames = this.buildForwardRecordImageNames(fileIndex)
+ for (const month of months) {
+ const recImgDir = join(sessionRoot, month, 'Rec', recordDir, 'Img')
+ const found = await this.getLargestExistingPathAsync(
+ candidateNames.map((name) => join(recImgDir, name)),
+ allowThumbnail,
+ preferThumbnail
+ )
+ if (found) return found
+ }
+ return null
+ }
+
private getPreferredDatVariantPath(
inputPath: string,
allowThumbnail: boolean,
@@ -1805,7 +1955,10 @@ export class ImageDecryptService {
): string {
const actualDir = dirname(inputPath)
const base = this.normalizeDatBase(basename(inputPath))
- const variants = this.buildPreferredDatNames(base)
+ const hasDatExtension = basename(inputPath).toLowerCase().endsWith('.dat')
+ const variants = hasDatExtension
+ ? this.buildPreferredDatNames(base)
+ : [...this.buildForwardRecordImageNames(base), ...this.buildPreferredDatNames(base)]
const ordered = allowThumbnail
? variants
: variants.filter((name) => !this.isThumbnailName(name))
diff --git a/src/main/message-parser.ts b/src/main/message-parser.ts
index 4be0c35..7ddfb69 100644
--- a/src/main/message-parser.ts
+++ b/src/main/message-parser.ts
@@ -26,14 +26,28 @@ type ShareContent = {
type ForwardedMessageItem = {
messageType: number
sender?: string
+ sourceHeadUrl?: string
sentAt?: string
text: string
+ title?: string
+ dataId?: string
+ dataIndex?: number
+ imageMd5?: string
+ thumbMd5?: string
+ imageDatName?: string
+ exportMediaUrl?: string
+ dataSize?: number
+ thumbSize?: number
+ fileExt?: string
+ linkUrl?: string
+ nestedTitle?: string
nested?: ForwardedMessageItem[]
}
type ForwardBundleContent = {
type: 'forwardBundle'
title: string
description?: string
+ recordDir?: string
items: ForwardedMessageItem[]
}
type MiniProgramContent = {
@@ -601,58 +615,206 @@ function parseForwardBundle(content: string): ForwardBundleContent {
const normalized = decodeXmlEntities(stripChatroomPrefix(content))
const title = decodeXmlEntities(extractXmlValue(normalized, 'title')) || '聊天记录'
const description = decodeXmlEntities(extractXmlValue(normalized, 'des')) || undefined
- const containers = Array.from(
- normalized.matchAll(/]*>([\s\S]*?)<\/recorditem>/gi),
- (match) => match[1] || ''
- )
+ const containers = splitBalancedXmlTags(normalized, 'recorditem').map((node) => node.inner)
const sources = containers.length ? containers : [normalized]
const items = dedupeForwardedItems(sources.flatMap((source) => parseForwardedItems(source)))
return { type: 'forwardBundle', title, description, items }
}
-function parseForwardedItems(container: string, depth = 0): ForwardedMessageItem[] {
- if (!container || depth > 4) return []
- const variants = new Set([container, decodeXmlEntities(container)])
- for (const match of container.matchAll(//g)) {
- if (match[1]) variants.add(decodeXmlEntities(match[1]))
- }
+/**
+ * 按标签嵌套深度提取顶层 XML 元素,避免合并转发套娃( 内嵌套 )
+ * 时被非贪婪正则在第一个内层 处截断。
+ */
+function splitBalancedXmlTags(
+ source: string,
+ tagName: string
+): Array<{ attrs: string; inner: string }> {
+ const xml = source || ''
+ if (!xml) return []
+ const pattern = new RegExp(`<(/?)${tagName}\\b([^>]*)>`, 'gi')
+ const result: Array<{ attrs: string; inner: string }> = []
+ let match: RegExpExecArray | null
+ let depth = 0
+ let openStart = -1
+ let openEnd = -1
+ let openAttrs = ''
- const items: ForwardedMessageItem[] = []
- for (const variant of variants) {
- for (const match of variant.matchAll(/]*)>([\s\S]*?)<\/dataitem>/gi)) {
- const attributes = match[1] || ''
- const body = match[2] || ''
- const attrType = /datatype\s*=\s*["']?(\d+)/i.exec(attributes)?.[1]
- const messageType = Number.parseInt(attrType || extractXmlValue(body, 'datatype') || '0', 10)
- const sender = decodeXmlEntities(extractXmlValue(body, 'sourcename')) || undefined
- const sentAt = extractXmlValue(body, 'sourcetime') || undefined
- const title = decodeXmlEntities(extractXmlValue(body, 'datatitle'))
- const description = decodeXmlEntities(
- extractXmlValue(body, 'datadesc') || extractXmlValue(body, 'content')
- )
- const nestedXml = extractXmlBody(body, 'recordxml')
- const nested =
- messageType === 17 && nestedXml
- ? parseForwardedItems(decodeXmlEntities(nestedXml), depth + 1)
- : undefined
- const text = description || title || forwardedTypeLabel(messageType)
- if (!sender && !text && !nested?.length) continue
- items.push({
- messageType: Number.isFinite(messageType) ? messageType : 0,
- sender,
- sentAt,
- text: text || '[消息]',
- nested: nested?.length ? nested : undefined
+ while ((match = pattern.exec(xml)) !== null) {
+ const isClosing = match[1] === '/'
+ const attrs = match[2] || ''
+ const rawTag = match[0] || ''
+ const selfClosing = !isClosing && /\/\s*>$/.test(rawTag)
+
+ if (!isClosing) {
+ if (depth === 0) {
+ openStart = match.index
+ openEnd = pattern.lastIndex
+ openAttrs = attrs
+ }
+ if (!selfClosing) {
+ depth += 1
+ } else if (depth === 0 && openEnd >= 0) {
+ result.push({ attrs: openAttrs, inner: '' })
+ openStart = -1
+ openEnd = -1
+ openAttrs = ''
+ }
+ continue
+ }
+
+ if (depth <= 0) continue
+ depth -= 1
+ if (depth === 0 && openEnd >= 0 && openStart >= 0) {
+ result.push({
+ attrs: openAttrs,
+ inner: xml.slice(openEnd, match.index)
})
+ openStart = -1
+ openEnd = -1
+ openAttrs = ''
}
}
- return dedupeForwardedItems(items)
+ return result
+}
+
+function parseForwardedItems(container: string, depth = 0): ForwardedMessageItem[] {
+ if (!container || depth > 8) return []
+ const variants: string[] = []
+ const pushVariant = (value: string): void => {
+ const trimmed = String(value || '').trim()
+ if (trimmed && !variants.includes(trimmed)) variants.push(trimmed)
+ }
+
+ for (const match of container.matchAll(//g)) {
+ if (match[1]) {
+ pushVariant(match[1])
+ pushVariant(decodeXmlEntities(match[1]))
+ }
+ }
+ pushVariant(container)
+ pushVariant(decodeXmlEntities(container))
+
+ for (const variant of variants) {
+ const dataItemNodes = splitBalancedXmlTags(variant, 'dataitem')
+ if (dataItemNodes.length === 0) continue
+
+ const items: ForwardedMessageItem[] = []
+ dataItemNodes.forEach((node, index) => {
+ const attributes = node.attrs || ''
+ const body = node.inner || ''
+ const nestedXml = splitBalancedXmlTags(body, 'recordxml')[0]?.inner || ''
+ // 剥离嵌套 后再提取外层字段,防止内层 的 fullmd5/datadesc/sourcename 泄漏到外层 datatype=17 节点。
+ const ownBody = nestedXml
+ ? body.replace(/]*>[\s\S]*<\/recordxml>/i, '')
+ : body
+ const attrType = /datatype\s*=\s*["']?(\d+)/i.exec(attributes)?.[1]
+ const dataId = /dataid\s*=\s*["']([^"']+)["']/i.exec(attributes)?.[1] || undefined
+ const messageType = Number.parseInt(
+ attrType || extractXmlValue(ownBody, 'datatype') || '0',
+ 10
+ )
+ const normalizedType = Number.isFinite(messageType) ? messageType : 0
+ const sender = decodeXmlEntities(extractXmlValue(ownBody, 'sourcename')) || undefined
+ const sourceHeadUrl = decodeXmlUrl(extractXmlValue(ownBody, 'sourceheadurl')) || undefined
+ const sentAt = extractXmlValue(ownBody, 'sourcetime') || undefined
+ const title = decodeXmlEntities(extractXmlValue(ownBody, 'datatitle')) || undefined
+ const description = decodeXmlEntities(
+ extractXmlValue(ownBody, 'datadesc') || extractXmlValue(ownBody, 'content')
+ )
+ const isNestedRecord = normalizedType === 17
+ const imageMd5 =
+ !isNestedRecord && normalizedType === 2
+ ? normalizeMd5(
+ extractXmlValue(ownBody, 'fullmd5') ||
+ extractXmlValue(ownBody, 'md5') ||
+ extractXmlValue(ownBody, 'datamd5')
+ )
+ : undefined
+ const thumbMd5 =
+ !isNestedRecord && normalizedType === 2
+ ? normalizeMd5(extractXmlValue(ownBody, 'thumbfullmd5'))
+ : undefined
+ const dataSize =
+ Number.parseInt(extractXmlValue(ownBody, 'datasize') || '0', 10) || undefined
+ const thumbSize =
+ Number.parseInt(extractXmlValue(ownBody, 'thumbsize') || '0', 10) || undefined
+ const fileExt = extractXmlValue(ownBody, 'fileext') || undefined
+ const linkUrl =
+ decodeXmlUrl(extractXmlValue(ownBody, 'link') || extractXmlValue(ownBody, 'streamweburl')) ||
+ undefined
+ const nestedTitle = isNestedRecord
+ ? decodeXmlEntities((nestedXml && extractXmlValue(nestedXml, 'title')) || title || '') ||
+ '聊天记录'
+ : undefined
+ const nested =
+ isNestedRecord && nestedXml ? parseForwardedItems(nestedXml, depth + 1) : undefined
+ const text =
+ normalizedType === 2
+ ? '[图片]'
+ : isNestedRecord
+ ? nestedTitle || '[聊天记录]'
+ : description || title || forwardedTypeLabel(normalizedType)
+ if (!sender && !text && !nested?.length && !imageMd5 && !thumbMd5) return
+ items.push({
+ messageType: normalizedType,
+ sender,
+ sourceHeadUrl,
+ sentAt,
+ text: text || '[消息]',
+ title,
+ dataId,
+ dataIndex: index,
+ imageMd5,
+ thumbMd5,
+ dataSize,
+ thumbSize,
+ fileExt,
+ linkUrl,
+ nestedTitle,
+ nested: nested?.length ? nested : undefined
+ })
+ })
+ if (items.length > 0) return dedupeForwardedItems(items)
+ }
+ return []
+}
+
+export function attachForwardBundleRecordDir(
+ bundle: ForwardBundleContent,
+ recordDir?: string
+): ForwardBundleContent {
+ const normalizedDir = String(recordDir || '').trim()
+ if (!normalizedDir) return bundle
+ const items = bundle.items.map((item, idx) => {
+ const dataIndex = typeof item.dataIndex === 'number' ? item.dataIndex : idx
+ if (item.messageType === 2 && !item.imageDatName) {
+ return {
+ ...item,
+ dataIndex,
+ imageDatName: `rec:${normalizedDir}:${dataIndex}`
+ }
+ }
+ return item
+ })
+ return {
+ ...bundle,
+ recordDir: normalizedDir,
+ items
+ }
}
function dedupeForwardedItems(items: ForwardedMessageItem[]): ForwardedMessageItem[] {
const seen = new Set()
return items.filter((item) => {
- const key = `${item.messageType}|${item.sender || ''}|${item.sentAt || ''}|${item.text}`
+ const key = [
+ item.messageType,
+ item.dataId || '',
+ item.dataIndex ?? '',
+ item.sender || '',
+ item.sentAt || '',
+ item.imageMd5 || '',
+ item.text
+ ].join('|')
if (seen.has(key)) return false
seen.add(key)
return true
@@ -661,30 +823,33 @@ function dedupeForwardedItems(items: ForwardedMessageItem[]): ForwardedMessageIt
function forwardedTypeLabel(messageType: number): string {
switch (messageType) {
- case 3:
+ case 2:
return '[图片]'
+ case 3:
case 34:
return '[语音]'
+ case 4:
case 43:
return '[视频]'
- case 47:
- return '[表情包]'
+ case 5:
+ return '[链接]'
+ case 6:
+ return '[位置]'
case 8:
case 49:
return '[文件或分享]'
case 17:
return '[聊天记录]'
+ case 22:
+ return '[视频号]'
+ case 37:
+ case 47:
+ return '[表情包]'
default:
return '[消息]'
}
}
-function extractXmlBody(xml: string, tagName: string): string {
- const match = new RegExp(`<${tagName}[^>]*>([\\s\\S]*?)<\\/${tagName}>`, 'i').exec(xml)
- if (!match?.[1]) return ''
- return match[1].replace(/^$/, '$1').trim()
-}
-
function parseQuoteMessage(content: string): {
content?: string
sender?: string
diff --git a/src/main/services/automation-action-runner.ts b/src/main/services/automation-action-runner.ts
index 912a36c..a095781 100644
--- a/src/main/services/automation-action-runner.ts
+++ b/src/main/services/automation-action-runner.ts
@@ -761,7 +761,7 @@ export class AutomationActionRunner {
* 定时日报的统一发送出口。
*
* **必须走 `WechatActionGateway`**:幂等 + 3 秒发送间隔 + 审计落盘都在那里。
- * Automation 层不允许知道 OneBot / WCHook / native host / Windows hook 的存在。
+ * Automation 层不允许知道 native host 的存在。
*/
private async sendScheduledReportImage(
input: ScheduledReportRunInput,
@@ -879,7 +879,7 @@ export class AutomationActionRunner {
*
* **必须走 `WechatActionGateway`**:幂等 + 3 秒发送间隔 + 审计落盘都在那里,
* 直接调个人微信发送会绕过全部三样。Automation 层也不允许知道
- * OneBot / WCHook / native host / Windows hook 的存在。
+ * native host 的存在。
*
* 幂等键由 **eventId** 派生(不是 executionId):审计是落盘的,
* 于是"重启后重复投递同一退群事件"会被持久层直接短路。
diff --git a/src/main/services/chat-service.ts b/src/main/services/chat-service.ts
index 286d24a..772a4a0 100644
--- a/src/main/services/chat-service.ts
+++ b/src/main/services/chat-service.ts
@@ -1,6 +1,7 @@
import { createHash, randomUUID } from 'node:crypto'
import { WechatDb, WechatMessage } from '../wechat-db'
import {
+ attachForwardBundleRecordDir,
parseImageBufferDataUrlFromRow,
parseImageDatNameFromRow,
parseMessageContent,
@@ -613,6 +614,9 @@ function listSourceMessages(
thumbDatName: parsed.thumbDatName || parseImageDatNameFromRow(msg),
thumbDataUrl: parsed.thumbDataUrl || parseImageBufferDataUrlFromRow(msg.raw || msg)
}
+ } else if (parsed.type === 'forwardBundle') {
+ const recordDir = parseImageDatNameFromRow(msg.raw || msg)
+ contentData = attachForwardBundleRecordDir(parsed, recordDir)
} else if (parsed.type !== 'system') {
if (parsed.type === 'sticker' && !parsed.url && parsed.md5) {
parsed.url = wcdb4Client.resolveEmoticonCdnUrl(parsed.md5)
diff --git a/src/main/video-asset-service.ts b/src/main/video-asset-service.ts
index 3577105..c442fa5 100644
--- a/src/main/video-asset-service.ts
+++ b/src/main/video-asset-service.ts
@@ -77,12 +77,15 @@ export class VideoAssetService {
const index = this.getIndex()
for (const key of lookupKeys) {
- const asset = index.get(key) || index.get(`${key}_raw`)
+ const rawAsset = index.get(`${key}_raw`)
+ const compressedAsset = index.get(key)
+ const asset = rawAsset || compressedAsset
if (!asset) continue
+ const posterPath = asset.posterPath || compressedAsset?.posterPath
return {
success: true,
url: this.createLocalMediaUrl(asset.filePath),
- poster: asset.posterPath ? this.createLocalMediaUrl(asset.posterPath) : undefined
+ poster: posterPath ? this.createLocalMediaUrl(posterPath) : undefined
}
}
diff --git a/src/main/wcdb4-client.ts b/src/main/wcdb4-client.ts
index 25599b5..b7b8162 100644
--- a/src/main/wcdb4-client.ts
+++ b/src/main/wcdb4-client.ts
@@ -3334,12 +3334,15 @@ export class Wcdb4Client {
}
resolveImageHardlink(md5: string): Wcdb4ImageHardlink | null {
- if (!this.wcdbResolveImageHardlink) return null
const normalizedMd5 = String(md5 || '')
.trim()
.toLowerCase()
if (!normalizedMd5) return null
+ const sqlHit = this.resolveImageHardlinkViaSql(normalizedMd5)
+ if (sqlHit) return sqlHit
+
+ if (!this.wcdbResolveImageHardlink) return null
try {
return this.callJson((handle, outJson) =>
this.wcdbResolveImageHardlink!(handle, normalizedMd5, this.nativeAccountRoot, outJson)
@@ -3351,12 +3354,15 @@ export class Wcdb4Client {
}
async resolveImageHardlinkAsync(md5: string): Promise {
- if (!this.wcdbResolveImageHardlink) return null
const normalizedMd5 = String(md5 || '')
.trim()
.toLowerCase()
if (!normalizedMd5) return null
+ const sqlHit = await this.resolveImageHardlinkViaSqlAsync(normalizedMd5)
+ if (sqlHit) return sqlHit
+
+ if (!this.wcdbResolveImageHardlink) return null
try {
return await this.callJsonAsync(
this.wcdbResolveImageHardlink as unknown as KoffiAsyncFunction,
@@ -3369,6 +3375,192 @@ export class Wcdb4Client {
}
}
+ private findHardlinkDb(): string {
+ const candidates = [
+ path.join(this.dbStoragePath, 'hardlink', 'hardlink.db'),
+ path.join(this.dbStoragePath, 'hardlink.db')
+ ]
+ return candidates.find((candidate) => fs.existsSync(candidate)) || ''
+ }
+
+ private buildImageHardlinkSql(normalizedMd5: string): string {
+ const escaped = normalizedMd5.replace(/'/g, "''")
+ return (
+ `SELECT f.md5, f.type AS link_kind, f.file_name, f.file_size, f.modify_time, ` +
+ `hex(f.extra_buffer) AS extra_hex, IFNULL(d1.username, '') AS dir1, IFNULL(d2.username, '') AS dir2 ` +
+ `FROM image_hardlink_info_v4 f ` +
+ `LEFT JOIN dir2id d1 ON d1.rowid = f.dir1 ` +
+ `LEFT JOIN dir2id d2 ON d2.rowid = f.dir2 ` +
+ `WHERE f.md5 = '${escaped}' OR f.file_name LIKE '${escaped}%'`
+ )
+ }
+
+ /**
+ * 解析 image_hardlink_info_v4.extra_buffer 中的 Protobuf 字段,提取合并转发 Rec 子目录名(如 16 位 hex 目录名)。
+ */
+ private decodeRecSubdirTokens(extraHex: string): string[] {
+ const trimmed = String(extraHex || '').trim()
+ if (!trimmed || trimmed.length % 2 !== 0 || !/^[0-9a-fA-F]+$/.test(trimmed)) return []
+ const buf = Buffer.from(trimmed, 'hex')
+ const tokens: string[] = []
+ const collectTokens = (text: string): void => {
+ const matches = text.match(/[a-zA-Z0-9_-]+/g)
+ if (!matches) return
+ for (const token of matches) {
+ if (token.trim()) tokens.push(token.trim())
+ }
+ }
+ const isAsciiText = (slice: Buffer): boolean => {
+ if (slice.length === 0) return false
+ for (let i = 0; i < slice.length; i += 1) {
+ if (slice[i] < 0x20 || slice[i] >= 0x7f) return false
+ }
+ return true
+ }
+
+ if (isAsciiText(buf)) {
+ collectTokens(buf.toString('ascii'))
+ return tokens
+ }
+
+ let offset = 0
+ while (offset < buf.length) {
+ const tag = buf[offset]
+ offset += 1
+ const wireType = tag & 0x07
+ if (wireType === 0) {
+ while (offset < buf.length && (buf[offset] & 0x80) !== 0) offset += 1
+ offset += 1
+ } else if (wireType === 1) {
+ offset += 8
+ } else if (wireType === 2) {
+ let length = 0
+ let shift = 0
+ while (offset < buf.length) {
+ const byte = buf[offset]
+ offset += 1
+ length |= (byte & 0x7f) << shift
+ if ((byte & 0x80) === 0) break
+ shift += 7
+ }
+ if (length < 0 || offset + length > buf.length) break
+ const value = buf.subarray(offset, offset + length)
+ offset += length
+ if (isAsciiText(value)) {
+ collectTokens(value.toString('ascii'))
+ }
+ } else if (wireType === 5) {
+ offset += 4
+ } else {
+ break
+ }
+ }
+ return tokens
+ }
+
+ private pickImageHardlinkFromRows(
+ normalizedMd5: string,
+ rows: Record[]
+ ): Wcdb4ImageHardlink | null {
+ if (!Array.isArray(rows) || rows.length === 0) return null
+
+ const candidates: Array<{
+ fullPath: string
+ fileName: string
+ dir1: string
+ dir2: string
+ linkKind: number
+ fileSize: number
+ modifyTime: number
+ exists: boolean
+ }> = []
+
+ for (const row of rows) {
+ const fileName = String(row.file_name || '').trim()
+ const dir1 = String(row.dir1 || '').trim()
+ const dir2 = String(row.dir2 || '').trim()
+ if (!fileName || !dir1 || !dir2) continue
+ const linkKind = Number(row.link_kind || row.type || 0)
+ const fileSize = Number(row.file_size || 0)
+ const modifyTime = Number(row.modify_time || 0)
+ const subdirTokens = this.decodeRecSubdirTokens(String(row.extra_hex || ''))
+
+ const fullPath =
+ linkKind === 4 && subdirTokens.length > 0
+ ? path.join(this.accountRoot, 'msg', 'attach', dir1, dir2, 'Rec', subdirTokens[0], 'Img', fileName)
+ : path.join(this.accountRoot, 'msg', 'attach', dir1, dir2, 'Img', fileName)
+
+ candidates.push({
+ fullPath,
+ fileName,
+ dir1,
+ dir2,
+ linkKind,
+ fileSize,
+ modifyTime,
+ exists: fs.existsSync(fullPath)
+ })
+ }
+
+ if (candidates.length === 0) return null
+ candidates.sort((left, right) => {
+ if (left.exists !== right.exists) return left.exists ? -1 : 1
+ if (left.fileSize !== right.fileSize) return right.fileSize - left.fileSize
+ return right.modifyTime - left.modifyTime
+ })
+
+ const best = candidates[0]
+ if (!best.exists) return null
+ return {
+ success: true,
+ md5: normalizedMd5,
+ dir1: best.dir1,
+ dir2: best.dir2,
+ link_kind: best.linkKind,
+ file_name: best.fileName,
+ full_path: best.fullPath
+ }
+ }
+
+ private resolveImageHardlinkViaSql(normalizedMd5: string): Wcdb4ImageHardlink | null {
+ if (!this.wcdbExecQuery || this.handle === null) return null
+ const hardlinkDb = this.findHardlinkDb()
+ if (!hardlinkDb) return null
+ try {
+ const rows = this.callJson[]>((handle, outJson) =>
+ this.wcdbExecQuery!(
+ handle,
+ 'media',
+ hardlinkDb,
+ this.buildImageHardlinkSql(normalizedMd5),
+ outJson
+ )
+ )
+ return this.pickImageHardlinkFromRows(normalizedMd5, rows)
+ } catch {
+ return null
+ }
+ }
+
+ private async resolveImageHardlinkViaSqlAsync(
+ normalizedMd5: string
+ ): Promise {
+ if (!this.wcdbExecQuery || this.handle === null) return null
+ const hardlinkDb = this.findHardlinkDb()
+ if (!hardlinkDb) return null
+ try {
+ const rows = await this.callJsonAsync[]>(
+ this.wcdbExecQuery as unknown as KoffiAsyncFunction,
+ 'media',
+ hardlinkDb,
+ this.buildImageHardlinkSql(normalizedMd5)
+ )
+ return this.pickImageHardlinkFromRows(normalizedMd5, rows)
+ } catch {
+ return null
+ }
+ }
+
resolveVideoHardlink(md5: string, dbPath: string): Wcdb4VideoHardlink | null {
if (!this.wcdbResolveVideoHardlink) return null
const normalizedMd5 = String(md5 || '')
diff --git a/src/renderer/src/components/ForwardBundleModal.tsx b/src/renderer/src/components/ForwardBundleModal.tsx
new file mode 100644
index 0000000..13a7762
--- /dev/null
+++ b/src/renderer/src/components/ForwardBundleModal.tsx
@@ -0,0 +1,241 @@
+import { useEffect, useState } from 'react'
+import { createPortal } from 'react-dom'
+import type { JSX, MouseEvent } from 'react'
+import type { ForwardedMessageItem } from '../../../shared/types'
+import { renderWechatEmojiText } from '../utils/wechatEmojiText'
+import { ImageBubble } from './ImageBubble'
+
+export interface ForwardBundleWindowLayer {
+ id: string
+ title: string
+ items: ForwardedMessageItem[]
+}
+
+interface ForwardBundleModalStackProps {
+ layers: ForwardBundleWindowLayer[]
+ sessionId?: string
+ onOpenNested: (title: string, items: ForwardedMessageItem[]) => void
+ onCloseFromIndex: (index: number) => void
+ onImageClick?: (imageUrl: string) => void
+}
+
+function formatSentAt(value?: string): string {
+ const raw = String(value || '').trim()
+ if (!raw) return ''
+ if (/^\d{9,13}$/.test(raw)) {
+ const ms = raw.length > 10 ? Number(raw) : Number(raw) * 1000
+ const date = new Date(ms)
+ if (!Number.isNaN(date.getTime())) {
+ const yyyy = date.getFullYear()
+ const mm = String(date.getMonth() + 1).padStart(2, '0')
+ const dd = String(date.getDate()).padStart(2, '0')
+ const hh = String(date.getHours()).padStart(2, '0')
+ const min = String(date.getMinutes()).padStart(2, '0')
+ return `${yyyy}-${mm}-${dd} ${hh}:${min}`
+ }
+ }
+ return raw
+}
+
+function ForwardAvatar({ src, name }: { src?: string; name?: string }): JSX.Element {
+ const [failed, setFailed] = useState(false)
+ const initial = Array.from(String(name || '?').trim())[0] || '?'
+
+ if (src && !failed) {
+ return (
+
+

setFailed(true)}
+ />
+
+ )
+ }
+
+ return {initial}
+}
+
+function ForwardModalItemRow({
+ item,
+ sessionId,
+ onOpenNested,
+ onImageClick
+}: {
+ item: ForwardedMessageItem
+ sessionId?: string
+ onOpenNested: (title: string, items: ForwardedMessageItem[]) => void
+ onImageClick?: (imageUrl: string) => void
+}): JSX.Element {
+ const isNested = item.messageType === 17 || Boolean(item.nested?.length)
+ const isImage =
+ !isNested &&
+ (item.messageType === 2 || Boolean(item.imageMd5 || item.thumbMd5 || item.imageDatName))
+ const senderName = item.sender || '未知发送者'
+ const formattedTime = formatSentAt(item.sentAt)
+
+ const handleOpenNested = (event: MouseEvent): void => {
+ event.stopPropagation()
+ if (!item.nested?.length) return
+ onOpenNested(item.nestedTitle || item.title || '聊天记录', item.nested)
+ }
+
+ return (
+
+
+
+
+ {senderName}
+ {formattedTime ? : null}
+
+
+ {isImage ? (
+
+
+
+ ) : isNested ? (
+
+ ) : (
+
+ )}
+
+
+
+ )
+}
+
+export function ForwardBundleModalStack({
+ layers,
+ sessionId,
+ onOpenNested,
+ onCloseFromIndex,
+ onImageClick
+}: ForwardBundleModalStackProps): JSX.Element | null {
+ useEffect(() => {
+ if (layers.length === 0) return
+ const handleKeyDown = (event: KeyboardEvent): void => {
+ if (event.key !== 'Escape') return
+ // 若此时已打开更上层的 Radix Dialog(例如 ChatImageViewer),优先交由其处理 Escape。
+ if (document.querySelector('[role="dialog"][data-state="open"]')) return
+ event.preventDefault()
+ event.stopPropagation()
+ onCloseFromIndex(layers.length - 1)
+ }
+ window.addEventListener('keydown', handleKeyDown)
+ return () => window.removeEventListener('keydown', handleKeyDown)
+ }, [layers.length, onCloseFromIndex])
+
+ if (layers.length === 0 || typeof document === 'undefined') return null
+
+ return createPortal(
+ <>
+ {layers.map((layer, index) => {
+ const zIndex = Math.min(58, 45 + index)
+ const offsetX = Math.min(index, 5) * 28
+ const offsetY = Math.min(index, 5) * 24
+
+ return (
+ onCloseFromIndex(index)}
+ >
+
event.stopPropagation()}
+ >
+
+
+ {layer.items.length > 0 ? (
+ layer.items.map((item, itemIdx) => (
+
+ ))
+ ) : (
+
暂未解析到可展示的记录
+ )}
+
+
+
+ )
+ })}
+ >,
+ document.body
+ )
+}
diff --git a/src/renderer/src/components/RichMessageBubble.tsx b/src/renderer/src/components/RichMessageBubble.tsx
index 8059283..4c592d0 100644
--- a/src/renderer/src/components/RichMessageBubble.tsx
+++ b/src/renderer/src/components/RichMessageBubble.tsx
@@ -1,8 +1,9 @@
-import { ParsedContent } from '../../../shared/types'
-import { useEffect, useState } from 'react'
+import { ParsedContent, type ForwardedMessageItem } from '../../../shared/types'
+import { useCallback, useEffect, useState } from 'react'
import type { JSX, MouseEvent } from 'react'
import { renderWechatEmojiText } from '../utils/wechatEmojiText'
import { ImageBubble } from './ImageBubble'
+import { ForwardBundleModalStack, type ForwardBundleWindowLayer } from './ForwardBundleModal'
const stickerDataUrlCache = new Map()
@@ -25,7 +26,13 @@ export function RichMessageBubble({
case 'share':
return
case 'forwardBundle':
- return
+ return (
+
+ )
case 'miniProgram':
return (
@@ -55,52 +62,97 @@ export function RichMessageBubble({
}
function ForwardBundleBubble({
- data
+ data,
+ sessionId,
+ onImageClick
}: {
data: Extract
+ sessionId?: string
+ onImageClick?: (imageUrl: string) => void
}): JSX.Element {
- const [expanded, setExpanded] = useState(false)
- const visibleItems = expanded ? data.items : data.items.slice(0, 3)
- const hiddenCount = Math.max(0, data.items.length - visibleItems.length)
+ const [modalLayers, setModalLayers] = useState([])
+ const previewItems = data.items.slice(0, 4)
+
+ const openRootModal = useCallback((): void => {
+ setModalLayers([
+ {
+ id: `forward-root-${Date.now()}`,
+ title: data.title || '聊天记录',
+ items: data.items
+ }
+ ])
+ }, [data.items, data.title])
+
+ const openNestedModal = useCallback(
+ (title: string, items: ForwardedMessageItem[]): void => {
+ setModalLayers((current) => [
+ ...current,
+ {
+ id: `forward-nested-${current.length}-${Date.now()}`,
+ title: title || '聊天记录',
+ items
+ }
+ ])
+ },
+ []
+ )
+
+ const closeFromIndex = useCallback((index: number): void => {
+ setModalLayers((current) => current.slice(0, index))
+ }, [])
return (
-
-