feat: 档案和导出页面支持查看多选消息

This commit is contained in:
Wxw-Gu committed 2026-11-19 17:53:35 +08:00
1 parent 2fb519a373
commit b86582e606
19 files changed
+1897 -152

No files matched your search

+415 -35
View File
@@ -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 ? '<img class="mini-program-icon" src="' + iconUrl + '" alt="">' : '') +
'<span>' + displayText(data.appName || '小程序') + '</span></div></div>'
}
const renderForwardItems = (items, depth = 0) => {
if (!Array.isArray(items) || !items.length || depth > 4) return ''
return '<ol class="forward-list">' + items.map((item) =>
'<li class="forward-item">' +
(item.sender ? '<strong>' + displayText(item.sender) + '</strong>' : '') +
(item.sentAt ? '<time>' + displayText(item.sentAt) + '</time>' : '') +
'<span>' + displayText(item.text || '[消息]') + '</span>' +
renderForwardItems(item.nested, depth + 1) + '</li>'
).join('') + '</ol>'
}
const renderForwardContent = (data) => {
const renderForwardContent = (data, archiveIndex) => {
const items = Array.isArray(data.items) ? data.items : []
return '<div class="structured-content forward-content" data-rich-kind="forwardBundle">' +
const previewItems = items.slice(0, 4)
const previewHtml = previewItems.length
? '<div class="forward-preview-list">' + previewItems.map((item) =>
'<div class="forward-preview-line">' +
(item.sender ? '<strong>' + displayText(item.sender) + ':</strong>' : '') +
'<span>' + displayText(item.text || '[消息]') + '</span></div>'
).join('') + '</div>'
: (data.description
? '<div class="structured-description">' + displayText(data.description) + '</div>'
: '')
return '<div class="structured-content forward-content is-clickable" data-rich-kind="forwardBundle" data-forward-open="' +
archiveIndex + '" role="button" tabindex="0">' +
'<div class="structured-kicker">聊天记录</div>' +
'<div class="structured-title">' + displayText(data.title || '聊天记录') + '</div>' +
(!items.length && data.description
? '<div class="structured-description">' + displayText(data.description) + '</div>'
: '') +
(items.length
? '<details><summary>展开 ' + items.length + ' 条消息</summary>' + renderForwardItems(items) + '</details>'
: '') + '</div>'
previewHtml +
'<div class="forward-footer"><span>' +
(items.length ? '共 ' + items.length + ' 条消息' : '聊天记录') +
'</span><span class="forward-footer-action">查看详情</span></div></div>'
}
const renderLocationContent = (data) => {
const latitude = Number(data.lat)
@@ -1195,7 +1421,7 @@ const renderExportScript = (name: string): string => `
displayText([data.status, durationText].filter(Boolean).join(' · ') || '通话消息') +
'</div></div>'
}
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'
? '<div class="quote-reference"><strong>' + esc(data.quotedSender || '引用消息') + '</strong><span>' + esc(data.quotedContent || '[引用消息]') + '</span></div>'
: ''
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
? '<div class="forward-modal-avatar"><img src="' + headUrl + '" alt="" loading="lazy" referrerpolicy="no-referrer" onerror="this.remove()"></div>'
: '<div class="forward-modal-avatar">' + initial + '</div>'
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) =>
'<div class="forward-modal-nested-line">' +
(child.sender ? esc(child.sender) + ': ' : '') +
displayText(child.text || '[消息]') + '</div>'
).join('')
bodyHtml = '<button type="button" class="forward-modal-nested-card" data-forward-nested-layer="' +
layerIndex + '" data-forward-nested-item="' + itemIndex + '"' +
(nestedItems.length ? '' : ' disabled') + '>' +
'<div class="forward-modal-nested-title">' + displayText(nestedTitle) + '</div>' +
(previewLines || '<div class="forward-modal-nested-line">' + displayText(item.text || '[聊天记录]') + '</div>') +
'<div class="forward-modal-nested-footer"><span>聊天记录</span><span>' +
(nestedItems.length ? '共 ' + nestedItems.length + ' 条 · 打开新窗口' : '') +
'</span></div></button>'
} else if (isImage) {
bodyHtml = item.exportMediaUrl
? '<img class="forward-modal-image" data-preview src="' + esc(item.exportMediaUrl) + '" alt="图片">'
: '<span class="forward-modal-image-missing">[图片未导出到本地]</span>'
} else {
const linkHref = externalUrl(item.linkUrl || '')
bodyHtml = '<div class="forward-modal-text">' + displayText(item.text || item.title || '[消息]') +
(linkHref ? '<a class="forward-modal-link" href="' + linkHref + '" target="_blank" rel="noreferrer noopener">打开链接 ↗</a>' : '') +
'</div>'
}
return '<article class="forward-modal-row">' + avatarHtml +
'<div class="forward-modal-row-main"><header class="forward-modal-row-meta">' +
'<span class="forward-modal-sender">' + displayText(sender) + '</span>' +
(timeText ? '<time class="forward-modal-time">' + esc(timeText) + '</time>' : '') +
'</header><div>' + bodyHtml + '</div></div></article>'
}
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('')
: '<div class="forward-modal-empty">暂未解析到可展示的记录</div>'
return '<div class="forward-modal-backdrop" data-forward-backdrop="' + index + '" style="z-index:' + zIndex + '">' +
'<section class="forward-modal-window" role="dialog" aria-modal="true" aria-label="' + esc(layer.title || '聊天记录') +
'" style="transform:translate(' + offsetX + 'px,' + offsetY + 'px)">' +
'<header class="forward-modal-header"><div class="forward-modal-header-text">' +
'<h3 class="forward-modal-title">' + displayText(layer.title || '聊天记录') + '</h3>' +
'<span class="forward-modal-subtitle">共 ' + items.length + ' 条消息' +
(index > 0 ? ' · 嵌套窗口 #' + (index + 1) : '') + '</span></div>' +
'<button type="button" class="forward-modal-close" data-forward-close="' + index + '" aria-label="关闭聊天记录窗口">×</button>' +
'</header><div class="forward-modal-body">' + rowsHtml + '</div></section></div>'
}).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 {
</section>
</section>
</main>
<div id="forward-modal-root"></div>
<div class="lightbox" id="lightbox">
<button class="lightbox-close" id="lightbox-close" type="button" aria-label="关闭图片预览">×</button>
<img id="lightbox-image" alt="预览">
+86
View File
@@ -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<void> => {
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, '数据库未连接,无法定位本地文件附件')
+171 -18
View File
@@ -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<string | null> {
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))
+212 -47
View File
@@ -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(/<recorditem\b[^>]*>([\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<string>([container, decodeXmlEntities(container)])
for (const match of container.matchAll(/<!\[CDATA\[([\s\S]*?)\]\]>/g)) {
if (match[1]) variants.add(decodeXmlEntities(match[1]))
}
/**
* 按标签嵌套深度提取顶层 XML 元素,避免合并转发套娃(<dataitem> 内嵌套 <recordxml><dataitem>)
* 时被非贪婪正则在第一个内层 </dataitem> 处截断。
*/
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(/<dataitem\b([^>]*)>([\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(/<!\[CDATA\[([\s\S]*?)\]\]>/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 || ''
// 剥离嵌套 <recordxml> 后再提取外层字段,防止内层 <dataitem> 的 fullmd5/datadesc/sourcename 泄漏到外层 datatype=17 节点。
const ownBody = nestedXml
? body.replace(/<recordxml\b[^>]*>[\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<string>()
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(/^<!\[CDATA\[([\s\S]*?)\]\]>$/, '$1').trim()
}
function parseQuoteMessage(content: string): {
content?: string
sender?: string
@@ -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):审计是落盘的,
* 于是"重启后重复投递同一退群事件"会被持久层直接短路。
+4
View File
@@ -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)
+5 -2
View File
@@ -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
}
}
+194 -2
View File
@@ -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<Wcdb4ImageHardlink>((handle, outJson) =>
this.wcdbResolveImageHardlink!(handle, normalizedMd5, this.nativeAccountRoot, outJson)
@@ -3351,12 +3354,15 @@ export class Wcdb4Client {
}
async resolveImageHardlinkAsync(md5: string): Promise<Wcdb4ImageHardlink | null> {
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<Wcdb4ImageHardlink>(
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<string, unknown>[]
): 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<Record<string, unknown>[]>((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<Wcdb4ImageHardlink | null> {
if (!this.wcdbExecQuery || this.handle === null) return null
const hardlinkDb = this.findHardlinkDb()
if (!hardlinkDb) return null
try {
const rows = await this.callJsonAsync<Record<string, unknown>[]>(
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 || '')