mirror of
https://wget.la/https://github.com/Wxw-Gu/WechatExplorer
synced 2026-12-01 17:25:15 +08:00
feat: mac 档案与导出支持加载原图原视频
This commit is contained in:
1 parent
fccca5b459
commit
b20e514c90
31 files changed
+1854
-81
No files matched your search
+290
-7
@@ -26,6 +26,21 @@ import type { VoiceRecognitionUseCase } from './voice-pipeline/voice-recognition
|
|||||||
import { imageFileQuality } from '../shared/image-quality'
|
import { imageFileQuality } from '../shared/image-quality'
|
||||||
import { resolveMemberName } from '../shared/member-names'
|
import { resolveMemberName } from '../shared/member-names'
|
||||||
import { filesystemSafeName } from '../shared/contact-name'
|
import { filesystemSafeName } from '../shared/contact-name'
|
||||||
|
import { macWechatRuntimeManager } from './services/mac-wechat-runtime-manager'
|
||||||
|
import { isReadOnlyMode } from './services/read-only-mode'
|
||||||
|
|
||||||
|
const unescapeXmlForExport = (text: string): string =>
|
||||||
|
text
|
||||||
|
.replace(/</g, '<')
|
||||||
|
.replace(/>/g, '>')
|
||||||
|
.replace(/"/g, '"')
|
||||||
|
.replace(/'/g, "'")
|
||||||
|
.replace(/&/g, '&')
|
||||||
|
|
||||||
|
const extractXmlAttrForExport = (xmlText: string, attrName: string): string => {
|
||||||
|
const match = new RegExp(`(?:\\s|^)${attrName}\\s*=\\s*["']([^"']*)["']`, 'i').exec(xmlText)
|
||||||
|
return match?.[1]?.trim() || ''
|
||||||
|
}
|
||||||
|
|
||||||
const jobs = new Set<string>()
|
const jobs = new Set<string>()
|
||||||
const activeArchives = new Map<string, Archiver>()
|
const activeArchives = new Map<string, Archiver>()
|
||||||
@@ -1369,6 +1384,11 @@ async function runSingleExport(
|
|||||||
})
|
})
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
const shouldDownloadOriginalMedia = Boolean(
|
||||||
|
request.downloadOriginalMedia &&
|
||||||
|
request.preferOriginal !== false &&
|
||||||
|
process.platform === 'darwin'
|
||||||
|
)
|
||||||
const reusableMediaType =
|
const reusableMediaType =
|
||||||
message.contentData.type === 'image' ||
|
message.contentData.type === 'image' ||
|
||||||
message.contentData.type === 'video' ||
|
message.contentData.type === 'video' ||
|
||||||
@@ -1380,6 +1400,8 @@ async function runSingleExport(
|
|||||||
const reusableImageQuality =
|
const reusableImageQuality =
|
||||||
previous?.exportMediaQuality === 'original' ||
|
previous?.exportMediaQuality === 'original' ||
|
||||||
(request.preferOriginal === false && previous?.exportMediaQuality === 'thumbnail')
|
(request.preferOriginal === false && previous?.exportMediaQuality === 'thumbnail')
|
||||||
|
const reusableVideoQuality =
|
||||||
|
!shouldDownloadOriginalMedia || previous?.exportMediaQuality === 'original'
|
||||||
let reusableMediaExists = false
|
let reusableMediaExists = false
|
||||||
if (reusableMediaType && previous?.exportMediaUrl) {
|
if (reusableMediaType && previous?.exportMediaUrl) {
|
||||||
reusableMediaExists = await resourceExists(previous.exportMediaUrl)
|
reusableMediaExists = await resourceExists(previous.exportMediaUrl)
|
||||||
@@ -1401,6 +1423,7 @@ async function runSingleExport(
|
|||||||
previous?.exportMediaUrl &&
|
previous?.exportMediaUrl &&
|
||||||
(!previous.exportMediaType || previous.exportMediaType === reusableMediaType) &&
|
(!previous.exportMediaType || previous.exportMediaType === reusableMediaType) &&
|
||||||
(reusableMediaType !== 'image' || reusableImageQuality) &&
|
(reusableMediaType !== 'image' || reusableImageQuality) &&
|
||||||
|
(reusableMediaType !== 'video' || reusableVideoQuality) &&
|
||||||
reusableMediaExists
|
reusableMediaExists
|
||||||
) {
|
) {
|
||||||
message.exportMediaUrl = previous.exportMediaUrl
|
message.exportMediaUrl = previous.exportMediaUrl
|
||||||
@@ -1452,6 +1475,69 @@ async function runSingleExport(
|
|||||||
decryptedImage = decrypted
|
decryptedImage = decrypted
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
|
let downloadedOriginalImage = false
|
||||||
|
let originalDownloadError = ''
|
||||||
|
if (
|
||||||
|
shouldDownloadOriginalMedia &&
|
||||||
|
(!decryptedImage || imageFileQuality(decryptedImage.filePath) !== 'original') &&
|
||||||
|
message.sessionId &&
|
||||||
|
message.localId != null &&
|
||||||
|
typeof client?.getRawMessageContent === 'function'
|
||||||
|
) {
|
||||||
|
try {
|
||||||
|
const raw = client.getRawMessageContent(
|
||||||
|
message.sessionId,
|
||||||
|
message.localId,
|
||||||
|
message.createTime || undefined
|
||||||
|
)
|
||||||
|
const xml = raw
|
||||||
|
? raw.trim().includes('<')
|
||||||
|
? raw.trim()
|
||||||
|
: unescapeXmlForExport(raw.trim())
|
||||||
|
: ''
|
||||||
|
if (xml && /<img\b/i.test(xml)) {
|
||||||
|
const saveDir = join(app.getPath('userData'), 'original-images')
|
||||||
|
await fs.mkdir(saveDir, { recursive: true })
|
||||||
|
const hostResult = await macWechatRuntimeManager.downloadOriginalImage({
|
||||||
|
xml,
|
||||||
|
...(message.contentData.md5 ? { md5: message.contentData.md5 } : {}),
|
||||||
|
save_path: saveDir,
|
||||||
|
timeout_ms: 45_000
|
||||||
|
})
|
||||||
|
if (
|
||||||
|
hostResult.success &&
|
||||||
|
hostResult.file_path &&
|
||||||
|
(await pathExists(hostResult.file_path))
|
||||||
|
) {
|
||||||
|
const decryptedDl = await imageService.decryptImageToBase64WithFallbackAsync(
|
||||||
|
hostResult.file_path,
|
||||||
|
false
|
||||||
|
)
|
||||||
|
if (decryptedDl) {
|
||||||
|
decryptedImage = decryptedDl
|
||||||
|
fileFound = true
|
||||||
|
downloadedOriginalImage = true
|
||||||
|
} else {
|
||||||
|
const rawBuf = await fs.readFile(hostResult.file_path)
|
||||||
|
const ext = detectAssetExtension(rawBuf)
|
||||||
|
if (ext) {
|
||||||
|
const mime = ext === 'jpg' ? 'image/jpeg' : `image/${ext}`
|
||||||
|
decryptedImage = {
|
||||||
|
data: `data:${mime};base64,${rawBuf.toString('base64')}`,
|
||||||
|
filePath: hostResult.file_path
|
||||||
|
}
|
||||||
|
fileFound = true
|
||||||
|
downloadedOriginalImage = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else if (hostResult.error) {
|
||||||
|
originalDownloadError = hostResult.error
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
originalDownloadError = error instanceof Error ? error.message : String(error)
|
||||||
|
}
|
||||||
|
}
|
||||||
const decoded = decryptedImage ? decodeDataUrl(decryptedImage.data) : null
|
const decoded = decryptedImage ? decodeDataUrl(decryptedImage.data) : null
|
||||||
if (decoded) {
|
if (decoded) {
|
||||||
const name = `image_${bufferHashPart(decoded.buffer)}.${decoded.extension}`
|
const name = `image_${bufferHashPart(decoded.buffer)}.${decoded.extension}`
|
||||||
@@ -1462,15 +1548,25 @@ async function runSingleExport(
|
|||||||
}
|
}
|
||||||
message.exportMediaUrl = mediaUrl
|
message.exportMediaUrl = mediaUrl
|
||||||
message.exportMediaType = 'image'
|
message.exportMediaType = 'image'
|
||||||
message.exportMediaQuality = imageFileQuality(decryptedImage!.filePath)
|
message.exportMediaQuality = downloadedOriginalImage
|
||||||
|
? 'original'
|
||||||
|
: imageFileQuality(decryptedImage!.filePath)
|
||||||
if (request.preferOriginal !== false && message.exportMediaQuality === 'thumbnail') {
|
if (request.preferOriginal !== false && message.exportMediaQuality === 'thumbnail') {
|
||||||
keepMediaError(request, message, '原图不可用,已降级使用缩略图')
|
keepMediaError(
|
||||||
|
request,
|
||||||
|
message,
|
||||||
|
originalDownloadError
|
||||||
|
? `原图下载失败(${originalDownloadError}),已降级使用缩略图`
|
||||||
|
: '原图不可用,已降级使用缩略图'
|
||||||
|
)
|
||||||
}
|
}
|
||||||
} else if (!fileFound) {
|
} else if (!fileFound) {
|
||||||
keepMediaError(
|
keepMediaError(
|
||||||
request,
|
request,
|
||||||
message,
|
message,
|
||||||
request.fallbackThumbnail === false
|
originalDownloadError
|
||||||
|
? `原图下载失败(${originalDownloadError}),且本地无图片缓存`
|
||||||
|
: request.fallbackThumbnail === false
|
||||||
? '原图文件缺失,未启用缩略图降级'
|
? '原图文件缺失,未启用缩略图降级'
|
||||||
: '原图和缩略图文件均缺失'
|
: '原图和缩略图文件均缺失'
|
||||||
)
|
)
|
||||||
@@ -1494,9 +1590,144 @@ async function runSingleExport(
|
|||||||
width: message.contentData.width,
|
width: message.contentData.width,
|
||||||
height: message.contentData.height
|
height: message.contentData.height
|
||||||
})
|
})
|
||||||
const source = resolved.url ? videoService.pathForUrl(resolved.url) : undefined
|
let source = resolved.url ? videoService.pathForUrl(resolved.url) : undefined
|
||||||
if (!resolved.success || !source) {
|
let videoDownloadError = ''
|
||||||
keepMediaError(request, message, resolved.error || '视频文件缺失或已移动')
|
if (
|
||||||
|
shouldDownloadOriginalMedia &&
|
||||||
|
(!source || !/_raw\.mp4$/i.test(source)) &&
|
||||||
|
message.sessionId &&
|
||||||
|
message.localId != null &&
|
||||||
|
typeof client?.getRawMessageContent === 'function'
|
||||||
|
) {
|
||||||
|
try {
|
||||||
|
const raw = client.getRawMessageContent(
|
||||||
|
message.sessionId,
|
||||||
|
message.localId,
|
||||||
|
message.createTime || undefined
|
||||||
|
)
|
||||||
|
const xml = raw
|
||||||
|
? raw.trim().includes('<')
|
||||||
|
? raw.trim()
|
||||||
|
: unescapeXmlForExport(raw.trim())
|
||||||
|
: ''
|
||||||
|
if (xml && /<videomsg\b/i.test(xml)) {
|
||||||
|
const rawFileId = extractXmlAttrForExport(xml, 'cdnrawvideourl')
|
||||||
|
const rawAesKey = extractXmlAttrForExport(xml, 'cdnrawvideoaeskey')
|
||||||
|
const xmlRawMd5 =
|
||||||
|
extractXmlAttrForExport(xml, 'rawmd5').toLowerCase() ||
|
||||||
|
message.contentData.rawMd5
|
||||||
|
const videoFileId = extractXmlAttrForExport(xml, 'cdnvideourl')
|
||||||
|
const videoAesKey = extractXmlAttrForExport(xml, 'aeskey')
|
||||||
|
const xmlMd5 =
|
||||||
|
extractXmlAttrForExport(xml, 'md5').toLowerCase() || message.contentData.md5
|
||||||
|
const xmlNewMd5 =
|
||||||
|
extractXmlAttrForExport(xml, 'newmd5').toLowerCase() ||
|
||||||
|
message.contentData.newMd5
|
||||||
|
const baseHash =
|
||||||
|
xmlMd5 ||
|
||||||
|
xmlNewMd5 ||
|
||||||
|
xmlRawMd5 ||
|
||||||
|
`video_${message.localId || Date.now()}`
|
||||||
|
|
||||||
|
const candidates: Array<{
|
||||||
|
fileId: string
|
||||||
|
aesKey: string
|
||||||
|
md5?: string
|
||||||
|
isRaw: boolean
|
||||||
|
targetFileName: string
|
||||||
|
}> = []
|
||||||
|
if (rawFileId && rawAesKey) {
|
||||||
|
candidates.push({
|
||||||
|
fileId: rawFileId,
|
||||||
|
aesKey: rawAesKey,
|
||||||
|
md5: xmlRawMd5 || baseHash,
|
||||||
|
isRaw: true,
|
||||||
|
targetFileName: `${baseHash}_raw.mp4`
|
||||||
|
})
|
||||||
|
}
|
||||||
|
if (!source && videoFileId && videoAesKey) {
|
||||||
|
candidates.push({
|
||||||
|
fileId: videoFileId,
|
||||||
|
aesKey: videoAesKey,
|
||||||
|
md5: xmlMd5 || xmlNewMd5 || baseHash,
|
||||||
|
isRaw: false,
|
||||||
|
targetFileName: `${baseHash}.mp4`
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
if (candidates.length > 0) {
|
||||||
|
const accountRoot = client.getAccountRoot() || ''
|
||||||
|
const dateObj =
|
||||||
|
message.createTime && message.createTime > 0
|
||||||
|
? new Date(
|
||||||
|
message.createTime > 10_000_000_000
|
||||||
|
? message.createTime
|
||||||
|
: message.createTime * 1000
|
||||||
|
)
|
||||||
|
: new Date()
|
||||||
|
const monthFolder = Number.isNaN(dateObj.getTime())
|
||||||
|
? 'downloaded'
|
||||||
|
: `${dateObj.getFullYear()}-${String(dateObj.getMonth() + 1).padStart(2, '0')}`
|
||||||
|
let saveDir = join(app.getPath('userData'), 'downloaded-videos', monthFolder)
|
||||||
|
if (accountRoot && !isReadOnlyMode()) {
|
||||||
|
const accountVideoMonthDir = join(accountRoot, 'msg', 'video', monthFolder)
|
||||||
|
try {
|
||||||
|
await fs.mkdir(accountVideoMonthDir, { recursive: true })
|
||||||
|
saveDir = accountVideoMonthDir
|
||||||
|
} catch {
|
||||||
|
await fs.mkdir(saveDir, { recursive: true })
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
await fs.mkdir(saveDir, { recursive: true })
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const candidate of candidates) {
|
||||||
|
const hostResult = await macWechatRuntimeManager.downloadVideo({
|
||||||
|
fileid: candidate.fileId,
|
||||||
|
aeskey: candidate.aesKey,
|
||||||
|
md5: candidate.md5,
|
||||||
|
save_dir: saveDir,
|
||||||
|
target_file_name: candidate.targetFileName,
|
||||||
|
timeout_ms: 90_000
|
||||||
|
})
|
||||||
|
if (
|
||||||
|
hostResult.success &&
|
||||||
|
hostResult.file_path &&
|
||||||
|
(await pathExists(hostResult.file_path))
|
||||||
|
) {
|
||||||
|
const allVideoHashes = [
|
||||||
|
xmlRawMd5,
|
||||||
|
xmlNewMd5,
|
||||||
|
xmlMd5,
|
||||||
|
...hashes,
|
||||||
|
hostResult.md5
|
||||||
|
].filter((v): v is string => Boolean(v))
|
||||||
|
videoService.registerDownloadedVideo(
|
||||||
|
allVideoHashes,
|
||||||
|
hostResult.file_path,
|
||||||
|
candidate.isRaw
|
||||||
|
)
|
||||||
|
source = hostResult.file_path
|
||||||
|
videoDownloadError = ''
|
||||||
|
break
|
||||||
|
} else if (hostResult.error) {
|
||||||
|
videoDownloadError = hostResult.error
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
videoDownloadError = error instanceof Error ? error.message : String(error)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!source) {
|
||||||
|
keepMediaError(
|
||||||
|
request,
|
||||||
|
message,
|
||||||
|
videoDownloadError
|
||||||
|
? `原视频下载失败(${videoDownloadError}),且${resolved.error || '本地未找到该视频文件'}`
|
||||||
|
: resolved.error || '视频文件缺失或已移动'
|
||||||
|
)
|
||||||
} else if (extname(source).toLowerCase() !== '.mp4') {
|
} else if (extname(source).toLowerCase() !== '.mp4') {
|
||||||
keepMediaError(request, message, '视频格式不支持,仅支持本地 MP4 文件')
|
keepMediaError(request, message, '视频格式不支持,仅支持本地 MP4 文件')
|
||||||
} else {
|
} else {
|
||||||
@@ -1508,6 +1739,7 @@ async function runSingleExport(
|
|||||||
}
|
}
|
||||||
message.exportMediaUrl = mediaUrl
|
message.exportMediaUrl = mediaUrl
|
||||||
message.exportMediaType = 'video'
|
message.exportMediaType = 'video'
|
||||||
|
message.exportMediaQuality = /_raw\.mp4$/i.test(source) ? 'original' : 'medium'
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else if (message.contentData.type === 'sticker' && stickerService) {
|
} else if (message.contentData.type === 'sticker' && stickerService) {
|
||||||
@@ -1537,6 +1769,8 @@ async function runSingleExport(
|
|||||||
imageMd5?: string
|
imageMd5?: string
|
||||||
thumbMd5?: string
|
thumbMd5?: string
|
||||||
imageDatName?: string
|
imageDatName?: string
|
||||||
|
cdnFileId?: string
|
||||||
|
cdnAesKey?: string
|
||||||
exportMediaUrl?: string
|
exportMediaUrl?: string
|
||||||
nested?: unknown[]
|
nested?: unknown[]
|
||||||
}>,
|
}>,
|
||||||
@@ -1555,7 +1789,11 @@ async function runSingleExport(
|
|||||||
item.messageType === 2 ||
|
item.messageType === 2 ||
|
||||||
Boolean(item.imageMd5 || item.thumbMd5 || item.imageDatName)
|
Boolean(item.imageMd5 || item.thumbMd5 || item.imageDatName)
|
||||||
if (!isForwardImage) continue
|
if (!isForwardImage) continue
|
||||||
if (item.exportMediaUrl && (await resourceExists(item.exportMediaUrl))) {
|
if (
|
||||||
|
!shouldDownloadOriginalMedia &&
|
||||||
|
item.exportMediaUrl &&
|
||||||
|
(await resourceExists(item.exportMediaUrl))
|
||||||
|
) {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
let decryptedImage: { data: string; filePath: string } | null = null
|
let decryptedImage: { data: string; filePath: string } | null = null
|
||||||
@@ -1586,6 +1824,51 @@ async function runSingleExport(
|
|||||||
decryptedImage = decrypted
|
decryptedImage = decrypted
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
|
if (
|
||||||
|
shouldDownloadOriginalMedia &&
|
||||||
|
(!decryptedImage || imageFileQuality(decryptedImage.filePath) !== 'original') &&
|
||||||
|
item.cdnFileId &&
|
||||||
|
item.cdnAesKey
|
||||||
|
) {
|
||||||
|
try {
|
||||||
|
const saveDir = join(app.getPath('userData'), 'original-images')
|
||||||
|
await fs.mkdir(saveDir, { recursive: true })
|
||||||
|
const hostResult = await macWechatRuntimeManager.downloadOriginalImage({
|
||||||
|
fileid: item.cdnFileId,
|
||||||
|
aeskey: item.cdnAesKey,
|
||||||
|
...(item.imageMd5 || item.thumbMd5
|
||||||
|
? { md5: item.imageMd5 || item.thumbMd5 }
|
||||||
|
: {}),
|
||||||
|
save_path: saveDir,
|
||||||
|
timeout_ms: 45_000
|
||||||
|
})
|
||||||
|
if (
|
||||||
|
hostResult.success &&
|
||||||
|
hostResult.file_path &&
|
||||||
|
(await pathExists(hostResult.file_path))
|
||||||
|
) {
|
||||||
|
const decryptedDl = await imageService.decryptImageToBase64WithFallbackAsync(
|
||||||
|
hostResult.file_path,
|
||||||
|
false
|
||||||
|
)
|
||||||
|
if (decryptedDl) {
|
||||||
|
decryptedImage = decryptedDl
|
||||||
|
} else {
|
||||||
|
const rawBuf = await fs.readFile(hostResult.file_path)
|
||||||
|
const ext = detectAssetExtension(rawBuf)
|
||||||
|
if (ext) {
|
||||||
|
const mime = ext === 'jpg' ? 'image/jpeg' : `image/${ext}`
|
||||||
|
decryptedImage = {
|
||||||
|
data: `data:${mime};base64,${rawBuf.toString('base64')}`,
|
||||||
|
filePath: hostResult.file_path
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// Ignore and fall back to local decryptedImage
|
||||||
|
}
|
||||||
|
}
|
||||||
const decoded = decryptedImage ? decodeDataUrl(decryptedImage.data) : null
|
const decoded = decryptedImage ? decodeDataUrl(decryptedImage.data) : null
|
||||||
if (decoded) {
|
if (decoded) {
|
||||||
const name = `image_${bufferHashPart(decoded.buffer)}.${decoded.extension}`
|
const name = `image_${bufferHashPart(decoded.buffer)}.${decoded.extension}`
|
||||||
|
|||||||
+325
-1
@@ -105,7 +105,14 @@ import {
|
|||||||
type ImageDebugPayload,
|
type ImageDebugPayload,
|
||||||
type ImageDebugQuality
|
type ImageDebugQuality
|
||||||
} from '../shared/image-debug-info'
|
} from '../shared/image-debug-info'
|
||||||
import type { ImageMessageXmlRequest, ImageMessageXmlResult } from '../shared/image-message-xml'
|
import type {
|
||||||
|
DownloadOriginalImageRequest,
|
||||||
|
DownloadOriginalImageResult,
|
||||||
|
DownloadVideoRequest,
|
||||||
|
DownloadVideoResult,
|
||||||
|
ImageMessageXmlRequest,
|
||||||
|
ImageMessageXmlResult
|
||||||
|
} from '../shared/image-message-xml'
|
||||||
import {
|
import {
|
||||||
loadSettings,
|
loadSettings,
|
||||||
saveSettings,
|
saveSettings,
|
||||||
@@ -2361,6 +2368,323 @@ app.whenReady().then(async () => { if (isLegacyMigrationHelper) {
|
|||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 触发微信进程下载图片原图,并在校验落盘后更新本地解码缓存与返回可直接渲染的图片 URL。
|
||||||
|
*/
|
||||||
|
ipcMain.handle(
|
||||||
|
'image:downloadOriginal',
|
||||||
|
async (_, request: DownloadOriginalImageRequest): Promise<DownloadOriginalImageResult> => {
|
||||||
|
const sessionId = String(request?.sessionId || '').trim()
|
||||||
|
const localId = Math.trunc(Number(request?.localId) || 0)
|
||||||
|
const createTime = Math.trunc(Number(request?.createTime) || 0)
|
||||||
|
const imageMd5 = String(request?.imageMd5 || '').trim() || undefined
|
||||||
|
const imageDatName = String(request?.imageDatName || '').trim() || undefined
|
||||||
|
const fileId = String(request?.fileId || '').trim() || undefined
|
||||||
|
const aesKey = String(request?.aesKey || '').trim() || undefined
|
||||||
|
const rawXml = String(request?.rawXml || '').trim() || undefined
|
||||||
|
|
||||||
|
try {
|
||||||
|
let xml: string | undefined
|
||||||
|
if (sessionId && localId > 0) {
|
||||||
|
const client = chat.getChatDb()?.getWcdb4Client()
|
||||||
|
if (client) {
|
||||||
|
const raw = client.getRawMessageContent(sessionId, localId, createTime || undefined)
|
||||||
|
if (raw) {
|
||||||
|
const candidate = raw.trim().includes('<') ? raw.trim() : unescapeXmlText(raw.trim())
|
||||||
|
if (/<img\b/i.test(candidate)) {
|
||||||
|
xml = candidate
|
||||||
|
} else if (/<refermsg\b/i.test(candidate)) {
|
||||||
|
const referMatch = /<refermsg\b[^>]*>[\s\S]*?<content>([\s\S]*?)<\/content>/i.exec(
|
||||||
|
candidate
|
||||||
|
)
|
||||||
|
const inner = referMatch?.[1] ? unescapeXmlText(referMatch[1].trim()) : ''
|
||||||
|
if (/<img\b/i.test(inner)) xml = inner
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!xml && rawXml && /<img\b/i.test(rawXml)) {
|
||||||
|
xml = rawXml
|
||||||
|
}
|
||||||
|
if (!xml && (!fileId || !aesKey)) {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
errorCode: 'MISSING_DOWNLOAD_PARAMS',
|
||||||
|
error: '无法定位该图片消息的 XML 或下载参数'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const saveDir = join(app.getPath('userData'), 'original-images')
|
||||||
|
await fsPromises.mkdir(saveDir, { recursive: true })
|
||||||
|
|
||||||
|
const hostResult = await macWechatRuntimeManager.downloadOriginalImage({
|
||||||
|
...(xml ? { xml } : {}),
|
||||||
|
...(fileId ? { fileid: fileId } : {}),
|
||||||
|
...(aesKey ? { aeskey: aesKey } : {}),
|
||||||
|
...(imageMd5 ? { md5: imageMd5 } : {}),
|
||||||
|
save_path: saveDir,
|
||||||
|
timeout_ms: 180_000
|
||||||
|
})
|
||||||
|
|
||||||
|
if (!hostResult.success || !hostResult.file_path || !existsSync(hostResult.file_path)) {
|
||||||
|
const errorCode = hostResult.error_code || 'DOWNLOAD_FAILED'
|
||||||
|
const friendlyErrorMap: Record<string, string> = {
|
||||||
|
NO_MANAGER_YET: '微信下载组件尚未就绪,请先在微信内任意点开一张图片后再试',
|
||||||
|
TEMPLATE_MISSING: '当前微信版本暂未配置原图下载模板',
|
||||||
|
TEMPLATE_INCOMPLETE: '当前微信版本原图下载模板未就绪',
|
||||||
|
WECHAT_NOT_RUNNING: '微信未运行,请先启动并登录微信',
|
||||||
|
NOT_BOUND: '尚未绑定当前微信,请先绑定微信运行时',
|
||||||
|
CDN_TIMEOUT: '微信下载原图超时(该原图可能已在服务器过期)'
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
errorCode,
|
||||||
|
error: friendlyErrorMap[errorCode] || hostResult.error || '原图下载失败'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let service = ensureImageDecryptService()
|
||||||
|
if (!service) {
|
||||||
|
const { xorKey, aesKey: configuredAesKey } = getConfiguredImageKeys()
|
||||||
|
service = new ImageDecryptService(
|
||||||
|
xorKey,
|
||||||
|
configuredAesKey,
|
||||||
|
chat.getChatDb()?.getWcdb4Client(),
|
||||||
|
loadSettings().dbRoot
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
const decrypted = await service.decryptImageToBase64WithFallbackAsync(
|
||||||
|
hostResult.file_path,
|
||||||
|
false
|
||||||
|
)
|
||||||
|
let responseData = decrypted?.data
|
||||||
|
if (!responseData) {
|
||||||
|
const rawBytes = await fsPromises.readFile(hostResult.file_path)
|
||||||
|
const mimeType = getLocalMediaMimeType(hostResult.file_path)
|
||||||
|
responseData = `data:${mimeType.startsWith('image/') ? mimeType : 'image/png'};base64,${rawBytes.toString('base64')}`
|
||||||
|
}
|
||||||
|
|
||||||
|
const decodedImage: DecodedImage = {
|
||||||
|
data: responseData,
|
||||||
|
filePath: decrypted?.filePath || hostResult.file_path,
|
||||||
|
isThumbnail: false
|
||||||
|
}
|
||||||
|
const resolvedMd5 = imageMd5 || hostResult.md5 || ''
|
||||||
|
for (const mode of ['original', 'thumbnail', 'auto'] as const) {
|
||||||
|
const cacheKey = [resolvedMd5, imageDatName || '', mode].join('|')
|
||||||
|
await service.cacheDecodedImage(cacheKey, decodedImage)
|
||||||
|
}
|
||||||
|
if (imageMd5 && hostResult.md5 && imageMd5 !== hostResult.md5) {
|
||||||
|
for (const mode of ['original', 'thumbnail', 'auto'] as const) {
|
||||||
|
const altCacheKey = [hostResult.md5, imageDatName || '', mode].join('|')
|
||||||
|
await service.cacheDecodedImage(altCacheKey, decodedImage)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const built = buildImageResponse(decodedImage, false)
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
data: built.data,
|
||||||
|
filePath: hostResult.file_path,
|
||||||
|
fileType: hostResult.file_type,
|
||||||
|
fileSize: hostResult.file_size,
|
||||||
|
md5: hostResult.md5 || imageMd5,
|
||||||
|
width: hostResult.width,
|
||||||
|
height: hostResult.height,
|
||||||
|
isOriginal: hostResult.is_original,
|
||||||
|
byteIdentical: hostResult.byte_identical,
|
||||||
|
verification: hostResult.verification,
|
||||||
|
rendition: hostResult.rendition
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
errorCode: 'INTERNAL_ERROR',
|
||||||
|
error: error instanceof Error ? error.message : String(error)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 触发微信进程下载聊天视频(优先尝试 cdnrawvideourl 原视频,回退 cdnvideourl),
|
||||||
|
* 落盘到账号 `msg/video/<YYYY-MM>`(或应用缓存目录)后注册到 `VideoAssetService` 并返回 `wxe-media://` URL。
|
||||||
|
*/
|
||||||
|
ipcMain.handle(
|
||||||
|
'video:download',
|
||||||
|
async (_, request: DownloadVideoRequest): Promise<DownloadVideoResult> => {
|
||||||
|
const sessionId = String(request?.sessionId || '').trim()
|
||||||
|
const localId = Math.trunc(Number(request?.localId) || 0)
|
||||||
|
const createTime = Math.trunc(Number(request?.createTime) || 0)
|
||||||
|
const reqMd5 = String(request?.md5 || '').trim().toLowerCase() || undefined
|
||||||
|
const reqNewMd5 = String(request?.newMd5 || '').trim().toLowerCase() || undefined
|
||||||
|
const reqRawMd5 = String(request?.rawMd5 || '').trim().toLowerCase() || undefined
|
||||||
|
const rawXml = String(request?.rawXml || '').trim() || undefined
|
||||||
|
|
||||||
|
const extractXmlAttr = (xmlText: string, attrName: string): string => {
|
||||||
|
const match = new RegExp(`(?:\\s|^)${attrName}\\s*=\\s*["']([^"']*)["']`, 'i').exec(
|
||||||
|
xmlText
|
||||||
|
)
|
||||||
|
return match?.[1]?.trim() || ''
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const client = chat.getChatDb()?.getWcdb4Client()
|
||||||
|
let xml = rawXml || ''
|
||||||
|
if (!xml && sessionId && localId > 0 && client) {
|
||||||
|
const raw = client.getRawMessageContent(sessionId, localId, createTime || undefined)
|
||||||
|
if (raw) {
|
||||||
|
xml = raw.trim().includes('<') ? raw.trim() : unescapeXmlText(raw.trim())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!xml || !/<videomsg\b/i.test(xml)) {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
errorCode: 'MISSING_VIDEO_XML',
|
||||||
|
error: '无法定位该视频消息的 XML 下载参数'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const rawFileId = extractXmlAttr(xml, 'cdnrawvideourl')
|
||||||
|
const rawAesKey = extractXmlAttr(xml, 'cdnrawvideoaeskey')
|
||||||
|
const xmlRawMd5 = extractXmlAttr(xml, 'rawmd5').toLowerCase() || reqRawMd5
|
||||||
|
const videoFileId = extractXmlAttr(xml, 'cdnvideourl')
|
||||||
|
const videoAesKey = extractXmlAttr(xml, 'aeskey')
|
||||||
|
const xmlMd5 = extractXmlAttr(xml, 'md5').toLowerCase() || reqMd5
|
||||||
|
const xmlNewMd5 = extractXmlAttr(xml, 'newmd5').toLowerCase() || reqNewMd5
|
||||||
|
|
||||||
|
const baseHash = xmlMd5 || xmlNewMd5 || xmlRawMd5 || `video_${localId || Date.now()}`
|
||||||
|
const candidates: Array<{
|
||||||
|
fileId: string
|
||||||
|
aesKey: string
|
||||||
|
md5?: string
|
||||||
|
isRaw: boolean
|
||||||
|
targetFileName: string
|
||||||
|
}> = []
|
||||||
|
|
||||||
|
if (rawFileId && rawAesKey) {
|
||||||
|
candidates.push({
|
||||||
|
fileId: rawFileId,
|
||||||
|
aesKey: rawAesKey,
|
||||||
|
md5: xmlRawMd5 || baseHash,
|
||||||
|
isRaw: true,
|
||||||
|
targetFileName: `${baseHash}_raw.mp4`
|
||||||
|
})
|
||||||
|
}
|
||||||
|
if (videoFileId && videoAesKey) {
|
||||||
|
candidates.push({
|
||||||
|
fileId: videoFileId,
|
||||||
|
aesKey: videoAesKey,
|
||||||
|
md5: xmlMd5 || xmlNewMd5 || baseHash,
|
||||||
|
isRaw: false,
|
||||||
|
targetFileName: `${baseHash}.mp4`
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
if (candidates.length === 0) {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
errorCode: 'NO_VIDEO_DOWNLOAD_SPEC',
|
||||||
|
error: '该视频消息不包含可用的下载凭证(cdnvideourl / aeskey)'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const accountRoot = client?.getAccountRoot() || chat.getCurrentAccountRoot() || ''
|
||||||
|
const dateObj =
|
||||||
|
createTime > 0
|
||||||
|
? new Date(createTime > 10_000_000_000 ? createTime : createTime * 1000)
|
||||||
|
: new Date()
|
||||||
|
const monthFolder = Number.isNaN(dateObj.getTime())
|
||||||
|
? 'downloaded'
|
||||||
|
: `${dateObj.getFullYear()}-${String(dateObj.getMonth() + 1).padStart(2, '0')}`
|
||||||
|
|
||||||
|
let saveDir = join(app.getPath('userData'), 'downloaded-videos', monthFolder)
|
||||||
|
if (accountRoot && !isReadOnlyMode()) {
|
||||||
|
const accountVideoMonthDir = join(accountRoot, 'msg', 'video', monthFolder)
|
||||||
|
try {
|
||||||
|
await fsPromises.mkdir(accountVideoMonthDir, { recursive: true })
|
||||||
|
saveDir = accountVideoMonthDir
|
||||||
|
} catch {
|
||||||
|
await fsPromises.mkdir(saveDir, { recursive: true })
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
await fsPromises.mkdir(saveDir, { recursive: true })
|
||||||
|
}
|
||||||
|
|
||||||
|
let lastError = '视频下载失败'
|
||||||
|
let lastErrorCode = 'DOWNLOAD_FAILED'
|
||||||
|
|
||||||
|
for (const candidate of candidates) {
|
||||||
|
const hostResult = await macWechatRuntimeManager.downloadVideo({
|
||||||
|
fileid: candidate.fileId,
|
||||||
|
aeskey: candidate.aesKey,
|
||||||
|
md5: candidate.md5,
|
||||||
|
save_dir: saveDir,
|
||||||
|
target_file_name: candidate.targetFileName,
|
||||||
|
timeout_ms: 180_000
|
||||||
|
})
|
||||||
|
|
||||||
|
if (hostResult.success && hostResult.file_path && existsSync(hostResult.file_path)) {
|
||||||
|
if (!videoAssetService && client) {
|
||||||
|
videoAssetService = new VideoAssetService(client)
|
||||||
|
}
|
||||||
|
const allHashes = [
|
||||||
|
xmlRawMd5,
|
||||||
|
xmlNewMd5,
|
||||||
|
xmlMd5,
|
||||||
|
reqRawMd5,
|
||||||
|
reqNewMd5,
|
||||||
|
reqMd5,
|
||||||
|
hostResult.md5
|
||||||
|
].filter((v): v is string => Boolean(v))
|
||||||
|
|
||||||
|
const registered = videoAssetService
|
||||||
|
? videoAssetService.registerDownloadedVideo(
|
||||||
|
allHashes,
|
||||||
|
hostResult.file_path,
|
||||||
|
candidate.isRaw
|
||||||
|
)
|
||||||
|
: { url: `file://${hostResult.file_path}` }
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
url: registered.url,
|
||||||
|
poster: registered.poster,
|
||||||
|
filePath: hostResult.file_path,
|
||||||
|
fileSize: hostResult.file_size,
|
||||||
|
md5: hostResult.md5,
|
||||||
|
isRaw: candidate.isRaw
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
lastErrorCode = hostResult.error_code || 'DOWNLOAD_FAILED'
|
||||||
|
const friendlyErrorMap: Record<string, string> = {
|
||||||
|
NO_MANAGER_YET: '微信下载组件尚未就绪,请先在微信内任意点开一张图片或视频后再试',
|
||||||
|
TEMPLATE_MISSING: '当前微信版本暂未配置媒体下载模板',
|
||||||
|
TEMPLATE_INCOMPLETE: '当前微信版本媒体下载模板未就绪',
|
||||||
|
WECHAT_NOT_RUNNING: '微信未运行,请先启动并登录微信',
|
||||||
|
NOT_BOUND: '尚未绑定当前微信,请先绑定微信运行时',
|
||||||
|
TIMEOUT: '微信下载视频超时(该视频可能已在微信服务器过期)'
|
||||||
|
}
|
||||||
|
lastError = friendlyErrorMap[lastErrorCode] || hostResult.error || '视频下载失败'
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
errorCode: lastErrorCode,
|
||||||
|
error: lastError
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
errorCode: 'INTERNAL_ERROR',
|
||||||
|
error: error instanceof Error ? error.message : String(error)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
ipcMain.handle('image:getStatus', async () =>
|
ipcMain.handle('image:getStatus', async () =>
|
||||||
inspectImageDecryptionStatus(imageKeyConfigService.getConfig())
|
inspectImageDecryptionStatus(imageKeyConfigService.getConfig())
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -35,6 +35,9 @@ type ForwardedMessageItem = {
|
|||||||
imageMd5?: string
|
imageMd5?: string
|
||||||
thumbMd5?: string
|
thumbMd5?: string
|
||||||
imageDatName?: string
|
imageDatName?: string
|
||||||
|
cdnFileId?: string
|
||||||
|
cdnAesKey?: string
|
||||||
|
rawXml?: string
|
||||||
exportMediaUrl?: string
|
exportMediaUrl?: string
|
||||||
dataSize?: number
|
dataSize?: number
|
||||||
thumbSize?: number
|
thumbSize?: number
|
||||||
@@ -739,6 +742,22 @@ function parseForwardedItems(container: string, depth = 0): ForwardedMessageItem
|
|||||||
!isNestedRecord && normalizedType === 2
|
!isNestedRecord && normalizedType === 2
|
||||||
? normalizeMd5(extractXmlValue(ownBody, 'thumbfullmd5'))
|
? normalizeMd5(extractXmlValue(ownBody, 'thumbfullmd5'))
|
||||||
: undefined
|
: undefined
|
||||||
|
const cdnFileId =
|
||||||
|
!isNestedRecord && normalizedType === 2
|
||||||
|
? extractXmlValue(ownBody, 'cdndataurl') ||
|
||||||
|
extractXmlValue(ownBody, 'cdnthumburl') ||
|
||||||
|
undefined
|
||||||
|
: undefined
|
||||||
|
const cdnAesKey =
|
||||||
|
!isNestedRecord && normalizedType === 2
|
||||||
|
? extractXmlValue(ownBody, 'cdndatakey') ||
|
||||||
|
extractXmlValue(ownBody, 'cdnthumbkey') ||
|
||||||
|
undefined
|
||||||
|
: undefined
|
||||||
|
const rawXml =
|
||||||
|
!isNestedRecord && normalizedType === 2
|
||||||
|
? `<dataitem${attributes ? ` ${attributes.trim()}` : ''}>${ownBody}</dataitem>`
|
||||||
|
: undefined
|
||||||
const dataSize =
|
const dataSize =
|
||||||
Number.parseInt(extractXmlValue(ownBody, 'datasize') || '0', 10) || undefined
|
Number.parseInt(extractXmlValue(ownBody, 'datasize') || '0', 10) || undefined
|
||||||
const thumbSize =
|
const thumbSize =
|
||||||
@@ -771,6 +790,9 @@ function parseForwardedItems(container: string, depth = 0): ForwardedMessageItem
|
|||||||
dataIndex: index,
|
dataIndex: index,
|
||||||
imageMd5,
|
imageMd5,
|
||||||
thumbMd5,
|
thumbMd5,
|
||||||
|
cdnFileId,
|
||||||
|
cdnAesKey,
|
||||||
|
rawXml,
|
||||||
dataSize,
|
dataSize,
|
||||||
thumbSize,
|
thumbSize,
|
||||||
fileExt,
|
fileExt,
|
||||||
|
|||||||
@@ -2,7 +2,14 @@ import { execFile, execFileSync, spawn, type ChildProcess } from 'child_process'
|
|||||||
import { createECDH, createHash } from 'node:crypto'
|
import { createECDH, createHash } from 'node:crypto'
|
||||||
import { homedir } from 'node:os'
|
import { homedir } from 'node:os'
|
||||||
import { promisify } from 'node:util'
|
import { promisify } from 'node:util'
|
||||||
import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'fs'
|
import {
|
||||||
|
chmodSync,
|
||||||
|
existsSync,
|
||||||
|
mkdirSync,
|
||||||
|
readFileSync,
|
||||||
|
renameSync,
|
||||||
|
writeFileSync
|
||||||
|
} from 'fs'
|
||||||
import { get, request as httpRequest } from 'http'
|
import { get, request as httpRequest } from 'http'
|
||||||
import { join } from 'path'
|
import { join } from 'path'
|
||||||
|
|
||||||
@@ -1253,6 +1260,202 @@ export class MacWechatRuntimeManager {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 调用原生运行时的 `POST /downloadOriginalImage`,让微信进程用原生下载器下载并解密原图。
|
||||||
|
*/
|
||||||
|
async downloadOriginalImage(payload: {
|
||||||
|
xml?: string
|
||||||
|
fileid?: string
|
||||||
|
aeskey?: string
|
||||||
|
md5?: string
|
||||||
|
file_type?: number
|
||||||
|
save_path: string
|
||||||
|
task_id?: string
|
||||||
|
timeout_ms?: number
|
||||||
|
}): Promise<{
|
||||||
|
success: boolean
|
||||||
|
task_id?: string
|
||||||
|
status?: string
|
||||||
|
file_path?: string
|
||||||
|
file_type?: string
|
||||||
|
file_size?: number
|
||||||
|
md5?: string
|
||||||
|
width?: number
|
||||||
|
height?: number
|
||||||
|
is_original?: boolean
|
||||||
|
byte_identical?: boolean
|
||||||
|
verification?: string
|
||||||
|
rendition?: string
|
||||||
|
error_code?: string
|
||||||
|
error?: string
|
||||||
|
}> {
|
||||||
|
if (process.platform !== 'darwin') {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
status: 'failed',
|
||||||
|
error_code: 'PLATFORM_UNSUPPORTED',
|
||||||
|
error: '当前仅支持 macOS 微信原图下载'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (this.lifecycle !== 'online') {
|
||||||
|
const snapshot = await this.ensureStarted({ allowManualRestart: true })
|
||||||
|
if (snapshot.lifecycle !== 'online' && !(await this.ping())) {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
status: 'failed',
|
||||||
|
error_code: 'RUNTIME_OFFLINE',
|
||||||
|
error: snapshot.error || '微信原生运行时未在线,无法下载原图'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let binding = (await this.getBindingStatus()) || (await this.refreshBinding().catch(() => null))
|
||||||
|
if (!binding?.bound || !binding?.sessionAttached || !binding?.scriptLoaded) {
|
||||||
|
const bindResult = await this.bind()
|
||||||
|
if (!bindResult.ok) {
|
||||||
|
const fallbackBind = await this.request('POST', '/bindWeChat')
|
||||||
|
binding = await this.refreshBinding().catch(() => null)
|
||||||
|
if (
|
||||||
|
fallbackBind.status !== 200 ||
|
||||||
|
!binding?.bound ||
|
||||||
|
!binding?.sessionAttached ||
|
||||||
|
!binding?.scriptLoaded
|
||||||
|
) {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
status: 'failed',
|
||||||
|
error_code: bindResult.state || 'BIND_FAILED',
|
||||||
|
error: bindResult.message || '绑定微信失败,无法下载原图'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
binding = (await this.getBindingStatus()) || (await this.refreshBinding().catch(() => null))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (binding && !binding.wechatRunning) {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
status: 'failed',
|
||||||
|
error_code: 'WECHAT_NOT_RUNNING',
|
||||||
|
error: '微信未运行,请先启动并登录微信'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const timeoutMs =
|
||||||
|
typeof payload.timeout_ms === 'number' && payload.timeout_ms > 0
|
||||||
|
? payload.timeout_ms
|
||||||
|
: 180_000
|
||||||
|
const { status, body } = await this.request(
|
||||||
|
'POST',
|
||||||
|
'/downloadOriginalImage',
|
||||||
|
timeoutMs + 10_000,
|
||||||
|
JSON.stringify({ ...payload, timeout_ms: timeoutMs })
|
||||||
|
)
|
||||||
|
if (status === null || !body) {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
status: 'failed',
|
||||||
|
error_code: 'HOST_UNREACHABLE',
|
||||||
|
error: '原图下载服务无响应,请检查微信发送组件状态'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const parsed = JSON.parse(body) as {
|
||||||
|
success?: boolean
|
||||||
|
task_id?: string
|
||||||
|
status?: string
|
||||||
|
file_path?: string
|
||||||
|
file_type?: string
|
||||||
|
file_size?: number
|
||||||
|
md5?: string
|
||||||
|
width?: number
|
||||||
|
height?: number
|
||||||
|
is_original?: boolean
|
||||||
|
byte_identical?: boolean
|
||||||
|
verification?: string
|
||||||
|
rendition?: string
|
||||||
|
error_code?: string
|
||||||
|
error?: string | { code?: string; message?: string }
|
||||||
|
}
|
||||||
|
const errObj = parsed.error && typeof parsed.error === 'object' ? parsed.error : undefined
|
||||||
|
return {
|
||||||
|
...parsed,
|
||||||
|
success: Boolean(parsed.success),
|
||||||
|
error_code: parsed.error_code || errObj?.code,
|
||||||
|
error: typeof parsed.error === 'string' ? parsed.error : errObj?.message
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
status: 'failed',
|
||||||
|
error_code: 'BAD_RESPONSE',
|
||||||
|
error: `媒体下载响应无法解析(HTTP ${status})`
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 复用 `/downloadOriginalImage`(`file_type=4`)取视频,再 `rename` 成 `target_file_name`。
|
||||||
|
* `rename` 要求与 host 落盘目录同卷,跨卷抛 EXDEV,调用方需保证同盘。
|
||||||
|
*/
|
||||||
|
async downloadVideo(payload: {
|
||||||
|
fileid: string
|
||||||
|
aeskey: string
|
||||||
|
md5?: string
|
||||||
|
save_dir: string
|
||||||
|
target_file_name?: string
|
||||||
|
task_id?: string
|
||||||
|
timeout_ms?: number
|
||||||
|
}): Promise<{
|
||||||
|
success: boolean
|
||||||
|
task_id?: string
|
||||||
|
status?: string
|
||||||
|
file_path?: string
|
||||||
|
file_size?: number
|
||||||
|
md5?: string
|
||||||
|
error_code?: string
|
||||||
|
error?: string
|
||||||
|
}> {
|
||||||
|
mkdirSync(payload.save_dir, { recursive: true })
|
||||||
|
const result = await this.downloadOriginalImage({
|
||||||
|
fileid: payload.fileid,
|
||||||
|
aeskey: payload.aeskey,
|
||||||
|
...(payload.md5 ? { md5: payload.md5 } : {}),
|
||||||
|
file_type: 4,
|
||||||
|
save_path: payload.save_dir,
|
||||||
|
task_id: payload.task_id,
|
||||||
|
timeout_ms: payload.timeout_ms
|
||||||
|
})
|
||||||
|
|
||||||
|
if (!result.success || !result.file_path || !existsSync(result.file_path)) {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
task_id: result.task_id,
|
||||||
|
status: result.status || 'failed',
|
||||||
|
error_code: result.error_code || 'DOWNLOAD_FAILED',
|
||||||
|
error: result.error || '视频下载失败'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let finalPath = result.file_path
|
||||||
|
const targetName = String(payload.target_file_name || '').trim()
|
||||||
|
if (targetName) {
|
||||||
|
const targetPath = join(payload.save_dir, targetName)
|
||||||
|
if (targetPath !== result.file_path) {
|
||||||
|
renameSync(result.file_path, targetPath)
|
||||||
|
finalPath = targetPath
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
task_id: result.task_id,
|
||||||
|
status: result.status || 'completed',
|
||||||
|
file_path: finalPath,
|
||||||
|
file_size: result.file_size,
|
||||||
|
md5: result.md5
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* 重新加载发送组件:优雅停掉当前 host 进程,再启动一个新实例。
|
* 重新加载发送组件:优雅停掉当前 host 进程,再启动一个新实例。
|
||||||
* 用于:更新二进制后换新代码;或 host 卡死时的手动恢复。
|
* 用于:更新二进制后换新代码;或 host 卡死时的手动恢复。
|
||||||
|
|||||||
@@ -34,6 +34,7 @@ export class VideoAssetService {
|
|||||||
private readonly fileHashes = new Map<string, Promise<string | undefined>>()
|
private readonly fileHashes = new Map<string, Promise<string | undefined>>()
|
||||||
private readonly videoDurations = new Map<string, number | undefined>()
|
private readonly videoDurations = new Map<string, number | undefined>()
|
||||||
private readonly imageDimensions = new Map<string, ImageDimensions | undefined>()
|
private readonly imageDimensions = new Map<string, ImageDimensions | undefined>()
|
||||||
|
private readonly posterIndex = new Map<string, string>()
|
||||||
private index: Map<string, VideoAsset> | null = null
|
private index: Map<string, VideoAsset> | null = null
|
||||||
|
|
||||||
constructor(private readonly client: Wcdb4Client) {}
|
constructor(private readonly client: Wcdb4Client) {}
|
||||||
@@ -97,7 +98,56 @@ export class VideoAssetService {
|
|||||||
poster: fallback.posterPath ? this.createLocalMediaUrl(fallback.posterPath) : undefined
|
poster: fallback.posterPath ? this.createLocalMediaUrl(fallback.posterPath) : undefined
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return { success: false, error: '本地未找到该视频文件' }
|
let posterOnlyPath: string | undefined
|
||||||
|
for (const key of lookupKeys) {
|
||||||
|
posterOnlyPath = this.posterIndex.get(`${key}_raw`) || this.posterIndex.get(key)
|
||||||
|
if (posterOnlyPath) break
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
...(posterOnlyPath ? { poster: this.createLocalMediaUrl(posterOnlyPath) } : {}),
|
||||||
|
error: '本地未找到该视频文件'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** raw 版本写入 `_raw` 键;同时补齐空着的普通键,否则只有原视频的消息仍会被判为无视频。 */
|
||||||
|
registerDownloadedVideo(
|
||||||
|
hashes: string[],
|
||||||
|
filePath: string,
|
||||||
|
isRaw = false
|
||||||
|
): { url: string; poster?: string } {
|
||||||
|
const index = this.getIndex()
|
||||||
|
const normalizedHashes = Array.from(
|
||||||
|
new Set(
|
||||||
|
hashes
|
||||||
|
.map((value) =>
|
||||||
|
String(value || '')
|
||||||
|
.trim()
|
||||||
|
.toLowerCase()
|
||||||
|
)
|
||||||
|
.filter((value) => /^[a-f0-9]{32}$/.test(value))
|
||||||
|
)
|
||||||
|
)
|
||||||
|
let posterPath: string | undefined
|
||||||
|
for (const hash of normalizedHashes) {
|
||||||
|
posterPath =
|
||||||
|
index.get(`${hash}_raw`)?.posterPath ||
|
||||||
|
index.get(hash)?.posterPath ||
|
||||||
|
this.posterIndex.get(`${hash}_raw`) ||
|
||||||
|
this.posterIndex.get(hash)
|
||||||
|
if (posterPath) break
|
||||||
|
}
|
||||||
|
const asset: VideoAsset = { filePath, ...(posterPath ? { posterPath } : {}) }
|
||||||
|
for (const hash of normalizedHashes) {
|
||||||
|
index.set(isRaw ? `${hash}_raw` : hash, asset)
|
||||||
|
if (!index.has(hash)) {
|
||||||
|
index.set(hash, asset)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
url: this.createLocalMediaUrl(filePath),
|
||||||
|
...(posterPath ? { poster: this.createLocalMediaUrl(posterPath) } : {})
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pathForToken(token: string): string | undefined {
|
pathForToken(token: string): string | undefined {
|
||||||
@@ -165,6 +215,9 @@ export class VideoAssetService {
|
|||||||
|
|
||||||
const assets: VideoAsset[] = []
|
const assets: VideoAsset[] = []
|
||||||
for (const [key, asset] of monthly) {
|
for (const [key, asset] of monthly) {
|
||||||
|
if (asset.posterPath) {
|
||||||
|
this.posterIndex.set(key, asset.posterPath)
|
||||||
|
}
|
||||||
if (!asset.filePath) continue
|
if (!asset.filePath) continue
|
||||||
result.set(key, asset)
|
result.set(key, asset)
|
||||||
assets.push(asset)
|
assets.push(asset)
|
||||||
|
|||||||
Vendored
+12
-1
@@ -56,7 +56,14 @@ import type {
|
|||||||
TestImageDecryptionRequest
|
TestImageDecryptionRequest
|
||||||
} from '../shared/image-decryption'
|
} from '../shared/image-decryption'
|
||||||
import type { ImageDebugInfoRequest, ImageDebugInfoResult } from '../shared/image-debug-info'
|
import type { ImageDebugInfoRequest, ImageDebugInfoResult } from '../shared/image-debug-info'
|
||||||
import type { ImageMessageXmlRequest, ImageMessageXmlResult } from '../shared/image-message-xml'
|
import type {
|
||||||
|
DownloadOriginalImageRequest,
|
||||||
|
DownloadOriginalImageResult,
|
||||||
|
DownloadVideoRequest,
|
||||||
|
DownloadVideoResult,
|
||||||
|
ImageMessageXmlRequest,
|
||||||
|
ImageMessageXmlResult
|
||||||
|
} from '../shared/image-message-xml'
|
||||||
import type {
|
import type {
|
||||||
AIChatRequestOptions,
|
AIChatRequestOptions,
|
||||||
AiSearchExternalAuthorizationRequest,
|
AiSearchExternalAuthorizationRequest,
|
||||||
@@ -502,6 +509,10 @@ declare global {
|
|||||||
}>
|
}>
|
||||||
getImageDebugInfo: (request: ImageDebugInfoRequest) => Promise<ImageDebugInfoResult>
|
getImageDebugInfo: (request: ImageDebugInfoRequest) => Promise<ImageDebugInfoResult>
|
||||||
getImageMessageXml: (request: ImageMessageXmlRequest) => Promise<ImageMessageXmlResult>
|
getImageMessageXml: (request: ImageMessageXmlRequest) => Promise<ImageMessageXmlResult>
|
||||||
|
downloadOriginalImage: (
|
||||||
|
request: DownloadOriginalImageRequest
|
||||||
|
) => Promise<DownloadOriginalImageResult>
|
||||||
|
downloadVideo: (request: DownloadVideoRequest) => Promise<DownloadVideoResult>
|
||||||
getVideo: (
|
getVideo: (
|
||||||
hashes: string[],
|
hashes: string[],
|
||||||
options?: {
|
options?: {
|
||||||
|
|||||||
+15
-1
@@ -91,7 +91,14 @@ import type { CacheClearScope, CacheSummary } from '../shared/cache'
|
|||||||
import type { ExportRequest, ExportJobProgress } from '../shared/export'
|
import type { ExportRequest, ExportJobProgress } from '../shared/export'
|
||||||
import type { ImageDecoderSelectionResult, ImageDecoderStatus } from '../shared/image-decryption'
|
import type { ImageDecoderSelectionResult, ImageDecoderStatus } from '../shared/image-decryption'
|
||||||
import type { ImageDebugInfoRequest, ImageDebugInfoResult } from '../shared/image-debug-info'
|
import type { ImageDebugInfoRequest, ImageDebugInfoResult } from '../shared/image-debug-info'
|
||||||
import type { ImageMessageXmlRequest, ImageMessageXmlResult } from '../shared/image-message-xml'
|
import type {
|
||||||
|
DownloadOriginalImageRequest,
|
||||||
|
DownloadOriginalImageResult,
|
||||||
|
DownloadVideoRequest,
|
||||||
|
DownloadVideoResult,
|
||||||
|
ImageMessageXmlRequest,
|
||||||
|
ImageMessageXmlResult
|
||||||
|
} from '../shared/image-message-xml'
|
||||||
import type { AccountDiscoveryResult } from '../shared/database-key'
|
import type { AccountDiscoveryResult } from '../shared/database-key'
|
||||||
import type {
|
import type {
|
||||||
VoiceBatchConversationSummary,
|
VoiceBatchConversationSummary,
|
||||||
@@ -541,6 +548,13 @@ const api = {
|
|||||||
/** 图片消息原始 XML。 */
|
/** 图片消息原始 XML。 */
|
||||||
getImageMessageXml: (request: ImageMessageXmlRequest): Promise<ImageMessageXmlResult> =>
|
getImageMessageXml: (request: ImageMessageXmlRequest): Promise<ImageMessageXmlResult> =>
|
||||||
ipcRenderer.invoke('image:getMessageXml', request),
|
ipcRenderer.invoke('image:getMessageXml', request),
|
||||||
|
/** 触发微信进程下载图片原图并刷新缓存。 */
|
||||||
|
downloadOriginalImage: (
|
||||||
|
request: DownloadOriginalImageRequest
|
||||||
|
): Promise<DownloadOriginalImageResult> => ipcRenderer.invoke('image:downloadOriginal', request),
|
||||||
|
/** 触发微信进程下载聊天视频并刷新本地视频索引。 */
|
||||||
|
downloadVideo: (request: DownloadVideoRequest): Promise<DownloadVideoResult> =>
|
||||||
|
ipcRenderer.invoke('video:download', request),
|
||||||
getVideo: (
|
getVideo: (
|
||||||
hashes: string[],
|
hashes: string[],
|
||||||
options?: {
|
options?: {
|
||||||
|
|||||||
@@ -2205,6 +2205,7 @@ function App(): React.ReactElement {
|
|||||||
dbReady={isDatabaseConnected}
|
dbReady={isDatabaseConnected}
|
||||||
loadPreviewMessages={loadExportPreviewMessages}
|
loadPreviewMessages={loadExportPreviewMessages}
|
||||||
onOpenSettings={openSettings}
|
onOpenSettings={openSettings}
|
||||||
|
onOpenSendSettings={openWechatSendSettings}
|
||||||
exportTasks={exportTasks}
|
exportTasks={exportTasks}
|
||||||
onStartExport={handleStartExport}
|
onStartExport={handleStartExport}
|
||||||
onCancelExport={handleCancelExport}
|
onCancelExport={handleCancelExport}
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import React, { useCallback, useEffect, useRef, useState } from 'react'
|
|||||||
import { Message, Contact } from '../../../shared/types'
|
import { Message, Contact } from '../../../shared/types'
|
||||||
import { ChatHeader } from './chat/ChatHeader'
|
import { ChatHeader } from './chat/ChatHeader'
|
||||||
import { ChatImageViewer } from './chat/ChatImageViewer'
|
import { ChatImageViewer } from './chat/ChatImageViewer'
|
||||||
|
import type { ImagePreviewOptions } from './ImageBubble'
|
||||||
import { ChatStatusBar } from './chat/ChatStatusBar'
|
import { ChatStatusBar } from './chat/ChatStatusBar'
|
||||||
import { DataTrustBar } from './chat/DataTrustBar'
|
import { DataTrustBar } from './chat/DataTrustBar'
|
||||||
import { EmptyConversationState } from './chat/EmptyConversationState'
|
import { EmptyConversationState } from './chat/EmptyConversationState'
|
||||||
@@ -54,7 +55,11 @@ const ChatWindow: React.FC<ChatWindowProps> = ({
|
|||||||
)
|
)
|
||||||
const messageListRef = useRef<HTMLDivElement>(null)
|
const messageListRef = useRef<HTMLDivElement>(null)
|
||||||
const messagesEndRef = useRef<HTMLDivElement>(null)
|
const messagesEndRef = useRef<HTMLDivElement>(null)
|
||||||
const [previewImage, setPreviewImage] = useState<string | null>(null)
|
const [previewImage, setPreviewImage] = useState<{
|
||||||
|
url: string
|
||||||
|
onDownloadOriginal?: ImagePreviewOptions['onDownloadOriginal']
|
||||||
|
} | null>(null)
|
||||||
|
const [hasMacHookMediaDownload, setHasMacHookMediaDownload] = useState(false)
|
||||||
const [showAvatar, setShowAvatar] = useState(true)
|
const [showAvatar, setShowAvatar] = useState(true)
|
||||||
const [isAtLatest, setIsAtLatest] = useState(true)
|
const [isAtLatest, setIsAtLatest] = useState(true)
|
||||||
const [isReloadingAvatars, setIsReloadingAvatars] = useState(false)
|
const [isReloadingAvatars, setIsReloadingAvatars] = useState(false)
|
||||||
@@ -83,6 +88,31 @@ const ChatWindow: React.FC<ChatWindowProps> = ({
|
|||||||
setIsAtLatest(true)
|
setIsAtLatest(true)
|
||||||
}, [contact?.md5])
|
}, [contact?.md5])
|
||||||
|
|
||||||
|
const isPreviewOpen = previewImage !== null
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
let active = true
|
||||||
|
void Promise.all([
|
||||||
|
window.api.getPersonalWechatSendCapability?.().catch(() => null),
|
||||||
|
window.api.getMacSendRuntimeAvailability?.().catch(() => null)
|
||||||
|
]).then(([capability, runtimeAvailability]) => {
|
||||||
|
if (!active) return
|
||||||
|
const isMacHookCapable =
|
||||||
|
runtimeAvailability?.state === 'available' ||
|
||||||
|
(capability?.senderStatus?.platform === 'darwin' &&
|
||||||
|
Boolean(
|
||||||
|
capability.ready ||
|
||||||
|
capability.senderStatus.runtimeReady ||
|
||||||
|
capability.senderStatus.attachReady ||
|
||||||
|
capability.senderStatus.canSend
|
||||||
|
))
|
||||||
|
setHasMacHookMediaDownload(Boolean(isMacHookCapable))
|
||||||
|
})
|
||||||
|
return () => {
|
||||||
|
active = false
|
||||||
|
}
|
||||||
|
}, [isPreviewOpen])
|
||||||
|
|
||||||
// 一次跳转 = 有精确目标或有时间目标。用统一判据,避免"只带了 messageId 但没带时间"
|
// 一次跳转 = 有精确目标或有时间目标。用统一判据,避免"只带了 messageId 但没带时间"
|
||||||
// 时自动滚到底把跳转结果顶掉(那会让用户看到"跳过去了但又被弹回最新")。
|
// 时自动滚到底把跳转结果顶掉(那会让用户看到"跳过去了但又被弹回最新")。
|
||||||
const hasJumpTarget =
|
const hasJumpTarget =
|
||||||
@@ -108,8 +138,11 @@ const ChatWindow: React.FC<ChatWindowProps> = ({
|
|||||||
return () => observer.disconnect()
|
return () => observer.disconnect()
|
||||||
}, [contact?.md5, isAtLatest, hasJumpTarget, scrollToBottom])
|
}, [contact?.md5, isAtLatest, hasJumpTarget, scrollToBottom])
|
||||||
|
|
||||||
const openImagePreview = (imageUrl: string): void => {
|
const openImagePreview = (imageUrl: string, options?: ImagePreviewOptions): void => {
|
||||||
setPreviewImage(imageUrl)
|
setPreviewImage({
|
||||||
|
url: imageUrl,
|
||||||
|
onDownloadOriginal: options?.onDownloadOriginal
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
const closeImagePreview = (): void => {
|
const closeImagePreview = (): void => {
|
||||||
@@ -168,17 +201,6 @@ const ChatWindow: React.FC<ChatWindowProps> = ({
|
|||||||
setSendDialogOpen(true)
|
setSendDialogOpen(true)
|
||||||
}, [onOpenPersonalWechatSettings])
|
}, [onOpenPersonalWechatSettings])
|
||||||
|
|
||||||
const handleSendFile = useCallback(async (): Promise<void> => {
|
|
||||||
try {
|
|
||||||
const picked = await window.api.selectPersonalWechatFile()
|
|
||||||
if (picked.canceled || !picked.path || !picked.name) return
|
|
||||||
setPendingFile({ path: picked.path, name: picked.name })
|
|
||||||
setSendDialogOpen(true)
|
|
||||||
} catch {
|
|
||||||
// 选择器本身失败(无窗口、无权限)时什么都不做,不要弹出一个空对话框。
|
|
||||||
}
|
|
||||||
}, [])
|
|
||||||
|
|
||||||
if (!contact) return <EmptyConversationState />
|
if (!contact) return <EmptyConversationState />
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@@ -193,7 +215,6 @@ const ChatWindow: React.FC<ChatWindowProps> = ({
|
|||||||
onContentFilterChange={onContentFilterChange || (() => undefined)}
|
onContentFilterChange={onContentFilterChange || (() => undefined)}
|
||||||
onRefresh={onRefresh}
|
onRefresh={onRefresh}
|
||||||
onTestSend={() => void handleOpenPersonalWechatSend()}
|
onTestSend={() => void handleOpenPersonalWechatSend()}
|
||||||
onSendFile={() => void handleSendFile()}
|
|
||||||
onOpenAiSettings={onCreateGroupReport || (() => undefined)}
|
onOpenAiSettings={onCreateGroupReport || (() => undefined)}
|
||||||
onOpenLocalIndexSettings={onOpenLocalIndexSettings}
|
onOpenLocalIndexSettings={onOpenLocalIndexSettings}
|
||||||
/>
|
/>
|
||||||
@@ -238,7 +259,16 @@ const ChatWindow: React.FC<ChatWindowProps> = ({
|
|||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{previewImage && <ChatImageViewer imageUrl={previewImage} onClose={closeImagePreview} />}
|
{previewImage && (
|
||||||
|
<ChatImageViewer
|
||||||
|
imageUrl={previewImage.url}
|
||||||
|
onDownloadOriginal={hasMacHookMediaDownload ? previewImage.onDownloadOriginal : undefined}
|
||||||
|
onImageChange={(nextUrl) =>
|
||||||
|
setPreviewImage((prev) => (prev ? { ...prev, url: nextUrl } : prev))
|
||||||
|
}
|
||||||
|
onClose={closeImagePreview}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ import { createPortal } from 'react-dom'
|
|||||||
import type { JSX, MouseEvent } from 'react'
|
import type { JSX, MouseEvent } from 'react'
|
||||||
import type { ForwardedMessageItem } from '../../../shared/types'
|
import type { ForwardedMessageItem } from '../../../shared/types'
|
||||||
import { renderWechatEmojiText } from '../utils/wechatEmojiText'
|
import { renderWechatEmojiText } from '../utils/wechatEmojiText'
|
||||||
import { ImageBubble } from './ImageBubble'
|
import { ImageBubble, type ImageClickHandler } from './ImageBubble'
|
||||||
|
|
||||||
export interface ForwardBundleWindowLayer {
|
export interface ForwardBundleWindowLayer {
|
||||||
id: string
|
id: string
|
||||||
@@ -16,7 +16,7 @@ interface ForwardBundleModalStackProps {
|
|||||||
sessionId?: string
|
sessionId?: string
|
||||||
onOpenNested: (title: string, items: ForwardedMessageItem[]) => void
|
onOpenNested: (title: string, items: ForwardedMessageItem[]) => void
|
||||||
onCloseFromIndex: (index: number) => void
|
onCloseFromIndex: (index: number) => void
|
||||||
onImageClick?: (imageUrl: string) => void
|
onImageClick?: ImageClickHandler
|
||||||
}
|
}
|
||||||
|
|
||||||
function formatSentAt(value?: string): string {
|
function formatSentAt(value?: string): string {
|
||||||
@@ -67,7 +67,7 @@ function ForwardModalItemRow({
|
|||||||
item: ForwardedMessageItem
|
item: ForwardedMessageItem
|
||||||
sessionId?: string
|
sessionId?: string
|
||||||
onOpenNested: (title: string, items: ForwardedMessageItem[]) => void
|
onOpenNested: (title: string, items: ForwardedMessageItem[]) => void
|
||||||
onImageClick?: (imageUrl: string) => void
|
onImageClick?: ImageClickHandler
|
||||||
}): JSX.Element {
|
}): JSX.Element {
|
||||||
const isNested = item.messageType === 17 || Boolean(item.nested?.length)
|
const isNested = item.messageType === 17 || Boolean(item.nested?.length)
|
||||||
const isImage =
|
const isImage =
|
||||||
@@ -96,6 +96,9 @@ function ForwardModalItemRow({
|
|||||||
<ImageBubble
|
<ImageBubble
|
||||||
imageMd5={item.imageMd5 || item.thumbMd5}
|
imageMd5={item.imageMd5 || item.thumbMd5}
|
||||||
imageDatName={item.imageDatName}
|
imageDatName={item.imageDatName}
|
||||||
|
fileId={item.cdnFileId}
|
||||||
|
aesKey={item.cdnAesKey}
|
||||||
|
rawXml={item.rawXml}
|
||||||
sessionId={sessionId}
|
sessionId={sessionId}
|
||||||
onImageClick={onImageClick}
|
onImageClick={onImageClick}
|
||||||
/>
|
/>
|
||||||
|
|||||||
@@ -1,6 +1,19 @@
|
|||||||
import { useState, useCallback, useEffect, useRef } from 'react'
|
import { useState, useCallback, useEffect, useRef } from 'react'
|
||||||
|
import { createPortal } from 'react-dom'
|
||||||
import type { JSX, KeyboardEvent, MouseEvent } from 'react'
|
import type { JSX, KeyboardEvent, MouseEvent } from 'react'
|
||||||
import { getCachedLoadedImage, requestImage } from './image-loader'
|
import { getCachedLoadedImage, requestImage, setCachedLoadedImage } from './image-loader'
|
||||||
|
|
||||||
|
export interface ImageOriginalDownloadOutcome {
|
||||||
|
success: boolean
|
||||||
|
data?: string
|
||||||
|
error?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ImagePreviewOptions {
|
||||||
|
onDownloadOriginal?: () => Promise<ImageOriginalDownloadOutcome>
|
||||||
|
}
|
||||||
|
|
||||||
|
export type ImageClickHandler = (imageUrl: string, options?: ImagePreviewOptions) => void
|
||||||
|
|
||||||
interface ImageBubbleProps {
|
interface ImageBubbleProps {
|
||||||
imageMd5?: string
|
imageMd5?: string
|
||||||
@@ -9,9 +22,12 @@ interface ImageBubbleProps {
|
|||||||
localId?: number
|
localId?: number
|
||||||
serverId?: string
|
serverId?: string
|
||||||
createTime?: number
|
createTime?: number
|
||||||
|
fileId?: string
|
||||||
|
aesKey?: string
|
||||||
|
rawXml?: string
|
||||||
isThumb?: boolean
|
isThumb?: boolean
|
||||||
fallbackUrl?: string
|
fallbackUrl?: string
|
||||||
onImageClick?: (imageUrl: string) => void
|
onImageClick?: ImageClickHandler
|
||||||
}
|
}
|
||||||
|
|
||||||
export function ImageBubble({
|
export function ImageBubble({
|
||||||
@@ -21,6 +37,9 @@ export function ImageBubble({
|
|||||||
localId,
|
localId,
|
||||||
serverId,
|
serverId,
|
||||||
createTime,
|
createTime,
|
||||||
|
fileId,
|
||||||
|
aesKey,
|
||||||
|
rawXml,
|
||||||
fallbackUrl,
|
fallbackUrl,
|
||||||
onImageClick
|
onImageClick
|
||||||
}: ImageBubbleProps): JSX.Element {
|
}: ImageBubbleProps): JSX.Element {
|
||||||
@@ -30,9 +49,13 @@ export function ImageBubble({
|
|||||||
const [imageUrl, setImageUrl] = useState<string | null>(initialCachedImage?.data || null)
|
const [imageUrl, setImageUrl] = useState<string | null>(initialCachedImage?.data || null)
|
||||||
const [loading, setLoading] = useState(false)
|
const [loading, setLoading] = useState(false)
|
||||||
const [upgrading, setUpgrading] = useState(false)
|
const [upgrading, setUpgrading] = useState(false)
|
||||||
|
const [downloadingOriginal, setDownloadingOriginal] = useState(false)
|
||||||
|
const [originalReadyNotice, setOriginalReadyNotice] = useState(false)
|
||||||
|
const [contextMenuPos, setContextMenuPos] = useState<{ x: number; y: number } | null>(null)
|
||||||
const [error, setError] = useState<string | null>(null)
|
const [error, setError] = useState<string | null>(null)
|
||||||
const [usingFallback, setUsingFallback] = useState(false)
|
const [usingFallback, setUsingFallback] = useState(false)
|
||||||
const containerRef = useRef<HTMLDivElement>(null)
|
const containerRef = useRef<HTMLDivElement>(null)
|
||||||
|
const menuRef = useRef<HTMLDivElement>(null)
|
||||||
const mountedRef = useRef(true)
|
const mountedRef = useRef(true)
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -42,6 +65,30 @@ export function ImageBubble({
|
|||||||
}
|
}
|
||||||
}, [])
|
}, [])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!contextMenuPos) return
|
||||||
|
const handlePointerDown = (event: globalThis.MouseEvent): void => {
|
||||||
|
if (menuRef.current && menuRef.current.contains(event.target as Node)) return
|
||||||
|
setContextMenuPos(null)
|
||||||
|
}
|
||||||
|
const handleKeyDown = (event: globalThis.KeyboardEvent): void => {
|
||||||
|
if (event.key === 'Escape') {
|
||||||
|
setContextMenuPos(null)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const handleScroll = (): void => {
|
||||||
|
setContextMenuPos(null)
|
||||||
|
}
|
||||||
|
window.addEventListener('mousedown', handlePointerDown, true)
|
||||||
|
window.addEventListener('keydown', handleKeyDown, true)
|
||||||
|
window.addEventListener('scroll', handleScroll, true)
|
||||||
|
return () => {
|
||||||
|
window.removeEventListener('mousedown', handlePointerDown, true)
|
||||||
|
window.removeEventListener('keydown', handleKeyDown, true)
|
||||||
|
window.removeEventListener('scroll', handleScroll, true)
|
||||||
|
}
|
||||||
|
}, [contextMenuPos])
|
||||||
|
|
||||||
const loadImage = useCallback(
|
const loadImage = useCallback(
|
||||||
async (priority = 0) => {
|
async (priority = 0) => {
|
||||||
if (imageUrl) return
|
if (imageUrl) return
|
||||||
@@ -131,11 +178,117 @@ export function ImageBubble({
|
|||||||
alert('图片已复制')
|
alert('图片已复制')
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 右键复制消息原始 XML。 */
|
/** 右键打开图片操作菜单(下载原图 / 复制 XML)。 */
|
||||||
|
const handleOpenContextMenu = (event: MouseEvent): void => {
|
||||||
|
event.preventDefault()
|
||||||
|
event.stopPropagation()
|
||||||
|
const menuWidth = 152
|
||||||
|
const menuHeight = 88
|
||||||
|
const maxX =
|
||||||
|
typeof window !== 'undefined'
|
||||||
|
? Math.max(8, window.innerWidth - menuWidth - 8)
|
||||||
|
: event.clientX
|
||||||
|
const maxY =
|
||||||
|
typeof window !== 'undefined'
|
||||||
|
? Math.max(8, window.innerHeight - menuHeight - 8)
|
||||||
|
: event.clientY
|
||||||
|
setContextMenuPos({
|
||||||
|
x: Math.min(Math.max(8, event.clientX), maxX),
|
||||||
|
y: Math.min(Math.max(8, event.clientY), maxY)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 副作用:无论谁调用,都会写图片缓存并替换气泡里的图。 */
|
||||||
|
const downloadOriginalImageCore = useCallback(async (): Promise<ImageOriginalDownloadOutcome> => {
|
||||||
|
if (downloadingOriginal) {
|
||||||
|
return { success: false, error: '正在下载原图,请稍候' }
|
||||||
|
}
|
||||||
|
|
||||||
|
setDownloadingOriginal(true)
|
||||||
|
setOriginalReadyNotice(false)
|
||||||
|
try {
|
||||||
|
const result = await window.api.downloadOriginalImage({
|
||||||
|
sessionId,
|
||||||
|
localId,
|
||||||
|
serverId,
|
||||||
|
createTime,
|
||||||
|
imageMd5,
|
||||||
|
imageDatName,
|
||||||
|
fileId,
|
||||||
|
aesKey,
|
||||||
|
rawXml
|
||||||
|
})
|
||||||
|
if (!result.success || !result.data) {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: result.error || '原图下载失败'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
setCachedLoadedImage(imageMd5, imageDatName, {
|
||||||
|
data: result.data,
|
||||||
|
isThumbnail: false
|
||||||
|
})
|
||||||
|
if (result.md5 && result.md5 !== imageMd5) {
|
||||||
|
setCachedLoadedImage(result.md5, imageDatName, {
|
||||||
|
data: result.data,
|
||||||
|
isThumbnail: false
|
||||||
|
})
|
||||||
|
}
|
||||||
|
if (mountedRef.current) {
|
||||||
|
setImageUrl(result.data)
|
||||||
|
setUsingFallback(false)
|
||||||
|
setError(null)
|
||||||
|
setOriginalReadyNotice(true)
|
||||||
|
window.setTimeout(() => {
|
||||||
|
if (mountedRef.current) setOriginalReadyNotice(false)
|
||||||
|
}, 2500)
|
||||||
|
}
|
||||||
|
return { success: true, data: result.data }
|
||||||
|
} catch (err) {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: err instanceof Error ? err.message : '原图下载失败'
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
if (mountedRef.current) setDownloadingOriginal(false)
|
||||||
|
}
|
||||||
|
}, [
|
||||||
|
aesKey,
|
||||||
|
createTime,
|
||||||
|
downloadingOriginal,
|
||||||
|
fileId,
|
||||||
|
imageDatName,
|
||||||
|
imageMd5,
|
||||||
|
localId,
|
||||||
|
rawXml,
|
||||||
|
serverId,
|
||||||
|
sessionId
|
||||||
|
])
|
||||||
|
|
||||||
|
const handleDownloadOriginalImage = async (event: MouseEvent): Promise<void> => {
|
||||||
|
event.preventDefault()
|
||||||
|
event.stopPropagation()
|
||||||
|
setContextMenuPos(null)
|
||||||
|
if (downloadingOriginal) return
|
||||||
|
|
||||||
|
const outcome = await downloadOriginalImageCore()
|
||||||
|
if (!mountedRef.current) return
|
||||||
|
if (!outcome.success) {
|
||||||
|
alert(outcome.error ? `原图下载失败:${outcome.error}` : '原图下载失败')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 复制消息原始 XML。 */
|
||||||
const handleCopyMessageXml = async (event: MouseEvent): Promise<void> => {
|
const handleCopyMessageXml = async (event: MouseEvent): Promise<void> => {
|
||||||
event.preventDefault()
|
event.preventDefault()
|
||||||
event.stopPropagation()
|
event.stopPropagation()
|
||||||
|
setContextMenuPos(null)
|
||||||
try {
|
try {
|
||||||
|
if ((!sessionId || !localId) && rawXml) {
|
||||||
|
await navigator.clipboard.writeText(rawXml)
|
||||||
|
alert('图片消息 XML 已复制')
|
||||||
|
return
|
||||||
|
}
|
||||||
const result = await window.api.getImageMessageXml({
|
const result = await window.api.getImageMessageXml({
|
||||||
sessionId,
|
sessionId,
|
||||||
localId,
|
localId,
|
||||||
@@ -143,6 +296,11 @@ export function ImageBubble({
|
|||||||
createTime
|
createTime
|
||||||
})
|
})
|
||||||
if (!result.success || !result.xml) {
|
if (!result.success || !result.xml) {
|
||||||
|
if (rawXml) {
|
||||||
|
await navigator.clipboard.writeText(rawXml)
|
||||||
|
alert('图片消息 XML 已复制')
|
||||||
|
return
|
||||||
|
}
|
||||||
alert(result.error ? `XML 获取失败:${result.error}` : 'XML 获取失败')
|
alert(result.error ? `XML 获取失败:${result.error}` : 'XML 获取失败')
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -153,15 +311,65 @@ export function ImageBubble({
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const renderContextMenu = (): JSX.Element | null => {
|
||||||
|
if (!contextMenuPos || typeof document === 'undefined') return null
|
||||||
|
return createPortal(
|
||||||
|
<div
|
||||||
|
ref={menuRef}
|
||||||
|
className="image-bubble-context-menu"
|
||||||
|
role="menu"
|
||||||
|
aria-label="图片右键菜单"
|
||||||
|
style={{ left: `${contextMenuPos.x}px`, top: `${contextMenuPos.y}px` }}
|
||||||
|
onClick={(event) => event.stopPropagation()}
|
||||||
|
onContextMenu={(event) => {
|
||||||
|
event.preventDefault()
|
||||||
|
event.stopPropagation()
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
role="menuitem"
|
||||||
|
className="image-bubble-context-item"
|
||||||
|
disabled={downloadingOriginal}
|
||||||
|
onClick={(event) => void handleDownloadOriginalImage(event)}
|
||||||
|
>
|
||||||
|
{downloadingOriginal ? '正在下载原图...' : '下载原图'}
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
role="menuitem"
|
||||||
|
className="image-bubble-context-item"
|
||||||
|
onClick={(event) => void handleCopyMessageXml(event)}
|
||||||
|
>
|
||||||
|
复制 XML
|
||||||
|
</button>
|
||||||
|
</div>,
|
||||||
|
document.body
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
const canDownloadOriginal =
|
||||||
|
typeof window !== 'undefined' &&
|
||||||
|
typeof window.api?.downloadOriginalImage === 'function' &&
|
||||||
|
Boolean((sessionId && (localId || serverId)) || (fileId && aesKey) || rawXml)
|
||||||
|
|
||||||
|
const openPreview = (url: string): void => {
|
||||||
|
if (canDownloadOriginal) {
|
||||||
|
onImageClick?.(url, { onDownloadOriginal: downloadOriginalImageCore })
|
||||||
|
} else {
|
||||||
|
onImageClick?.(url)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const handleClick = async (): Promise<void> => {
|
const handleClick = async (): Promise<void> => {
|
||||||
if (!imageUrl && !error) return
|
if (!imageUrl && !error) return
|
||||||
if (!imageMd5 && !imageDatName) {
|
if (!imageMd5 && !imageDatName) {
|
||||||
if (imageUrl) onImageClick?.(imageUrl)
|
if (imageUrl) openPreview(imageUrl)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if (upgrading) {
|
if (upgrading) {
|
||||||
if (imageUrl) onImageClick?.(imageUrl)
|
if (imageUrl) openPreview(imageUrl)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -172,7 +380,7 @@ export function ImageBubble({
|
|||||||
setImageUrl(result.data)
|
setImageUrl(result.data)
|
||||||
setUsingFallback(false)
|
setUsingFallback(false)
|
||||||
setError(null)
|
setError(null)
|
||||||
onImageClick?.(result.data)
|
openPreview(result.data)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
} catch {
|
} catch {
|
||||||
@@ -181,7 +389,7 @@ export function ImageBubble({
|
|||||||
setUpgrading(false)
|
setUpgrading(false)
|
||||||
}
|
}
|
||||||
|
|
||||||
if (imageUrl) onImageClick?.(imageUrl)
|
if (imageUrl) openPreview(imageUrl)
|
||||||
}
|
}
|
||||||
|
|
||||||
const handlePreviewKeyDown = (event: KeyboardEvent<HTMLDivElement>): void => {
|
const handlePreviewKeyDown = (event: KeyboardEvent<HTMLDivElement>): void => {
|
||||||
@@ -201,10 +409,19 @@ export function ImageBubble({
|
|||||||
|
|
||||||
if (error) {
|
if (error) {
|
||||||
return (
|
return (
|
||||||
<div className="image-bubble image-error" onClick={() => void loadImage(0)}>
|
<>
|
||||||
|
<div
|
||||||
|
className="image-bubble image-error"
|
||||||
|
onClick={() => void loadImage(0)}
|
||||||
|
onContextMenu={handleOpenContextMenu}
|
||||||
|
>
|
||||||
<div className="image-error-text">{error || '图片未缓存'}</div>
|
<div className="image-error-text">{error || '图片未缓存'}</div>
|
||||||
<div className="image-quality-badge">加载失败</div>
|
<div className="image-quality-badge">
|
||||||
|
{downloadingOriginal ? '正在下载原图...' : '加载失败'}
|
||||||
</div>
|
</div>
|
||||||
|
</div>
|
||||||
|
{renderContextMenu()}
|
||||||
|
</>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -218,13 +435,14 @@ export function ImageBubble({
|
|||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
<>
|
||||||
<div
|
<div
|
||||||
className="image-bubble image-loaded"
|
className="image-bubble image-loaded"
|
||||||
role="button"
|
role="button"
|
||||||
tabIndex={0}
|
tabIndex={0}
|
||||||
aria-label="查看图片"
|
aria-label="查看图片"
|
||||||
onClick={handleClick}
|
onClick={handleClick}
|
||||||
onContextMenu={handleCopyMessageXml}
|
onContextMenu={handleOpenContextMenu}
|
||||||
onKeyDown={handlePreviewKeyDown}
|
onKeyDown={handlePreviewKeyDown}
|
||||||
>
|
>
|
||||||
<img
|
<img
|
||||||
@@ -232,12 +450,20 @@ export function ImageBubble({
|
|||||||
alt="图片"
|
alt="图片"
|
||||||
className={`image-content ${usingFallback ? 'image-fallback' : ''}`}
|
className={`image-content ${usingFallback ? 'image-fallback' : ''}`}
|
||||||
/>
|
/>
|
||||||
{upgrading && <div className="image-quality-badge">正在查找原图</div>}
|
{downloadingOriginal ? (
|
||||||
|
<div className="image-quality-badge">正在下载原图...</div>
|
||||||
|
) : originalReadyNotice ? (
|
||||||
|
<div className="image-quality-badge">已加载原图</div>
|
||||||
|
) : (
|
||||||
|
upgrading && <div className="image-quality-badge">正在查找原图</div>
|
||||||
|
)}
|
||||||
<div className="image-actions">
|
<div className="image-actions">
|
||||||
<button className="image-action-btn" onClick={handleCopy} title="复制图片">
|
<button className="image-action-btn" onClick={handleCopy} title="复制图片">
|
||||||
复制
|
复制
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
{renderContextMenu()}
|
||||||
|
</>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -2,7 +2,7 @@ import { ParsedContent, type ForwardedMessageItem } from '../../../shared/types'
|
|||||||
import { useCallback, useEffect, useState } from 'react'
|
import { useCallback, useEffect, useState } from 'react'
|
||||||
import type { JSX, MouseEvent } from 'react'
|
import type { JSX, MouseEvent } from 'react'
|
||||||
import { renderWechatEmojiText } from '../utils/wechatEmojiText'
|
import { renderWechatEmojiText } from '../utils/wechatEmojiText'
|
||||||
import { ImageBubble } from './ImageBubble'
|
import { ImageBubble, type ImageClickHandler } from './ImageBubble'
|
||||||
import { ForwardBundleModalStack, type ForwardBundleWindowLayer } from './ForwardBundleModal'
|
import { ForwardBundleModalStack, type ForwardBundleWindowLayer } from './ForwardBundleModal'
|
||||||
|
|
||||||
const stickerDataUrlCache = new Map<string, string>()
|
const stickerDataUrlCache = new Map<string, string>()
|
||||||
@@ -10,12 +10,18 @@ const stickerDataUrlCache = new Map<string, string>()
|
|||||||
interface RichMessageBubbleProps {
|
interface RichMessageBubbleProps {
|
||||||
contentData: ParsedContent
|
contentData: ParsedContent
|
||||||
sessionId?: string
|
sessionId?: string
|
||||||
onImageClick?: (imageUrl: string) => void
|
localId?: number
|
||||||
|
serverId?: string
|
||||||
|
createTime?: number
|
||||||
|
onImageClick?: ImageClickHandler
|
||||||
}
|
}
|
||||||
|
|
||||||
export function RichMessageBubble({
|
export function RichMessageBubble({
|
||||||
contentData,
|
contentData,
|
||||||
sessionId,
|
sessionId,
|
||||||
|
localId,
|
||||||
|
serverId,
|
||||||
|
createTime,
|
||||||
onImageClick
|
onImageClick
|
||||||
}: RichMessageBubbleProps): JSX.Element {
|
}: RichMessageBubbleProps): JSX.Element {
|
||||||
switch (contentData.type) {
|
switch (contentData.type) {
|
||||||
@@ -44,7 +50,16 @@ export function RichMessageBubble({
|
|||||||
case 'sticker':
|
case 'sticker':
|
||||||
return <StickerBubble data={contentData} />
|
return <StickerBubble data={contentData} />
|
||||||
case 'quote':
|
case 'quote':
|
||||||
return <QuoteBubble data={contentData} sessionId={sessionId} onImageClick={onImageClick} />
|
return (
|
||||||
|
<QuoteBubble
|
||||||
|
data={contentData}
|
||||||
|
sessionId={sessionId}
|
||||||
|
localId={localId}
|
||||||
|
serverId={serverId}
|
||||||
|
createTime={createTime}
|
||||||
|
onImageClick={onImageClick}
|
||||||
|
/>
|
||||||
|
)
|
||||||
case 'system':
|
case 'system':
|
||||||
return <SystemBubble data={contentData} />
|
return <SystemBubble data={contentData} />
|
||||||
case 'unknown':
|
case 'unknown':
|
||||||
@@ -68,7 +83,7 @@ function ForwardBundleBubble({
|
|||||||
}: {
|
}: {
|
||||||
data: Extract<ParsedContent, { type: 'forwardBundle' }>
|
data: Extract<ParsedContent, { type: 'forwardBundle' }>
|
||||||
sessionId?: string
|
sessionId?: string
|
||||||
onImageClick?: (imageUrl: string) => void
|
onImageClick?: ImageClickHandler
|
||||||
}): JSX.Element {
|
}): JSX.Element {
|
||||||
const [modalLayers, setModalLayers] = useState<ForwardBundleWindowLayer[]>([])
|
const [modalLayers, setModalLayers] = useState<ForwardBundleWindowLayer[]>([])
|
||||||
const previewItems = data.items.slice(0, 4)
|
const previewItems = data.items.slice(0, 4)
|
||||||
@@ -261,7 +276,7 @@ function MiniProgramBubble({
|
|||||||
}: {
|
}: {
|
||||||
data: Extract<ParsedContent, { type: 'miniProgram' }>
|
data: Extract<ParsedContent, { type: 'miniProgram' }>
|
||||||
sessionId?: string
|
sessionId?: string
|
||||||
onImageClick?: (imageUrl: string) => void
|
onImageClick?: ImageClickHandler
|
||||||
}): JSX.Element {
|
}): JSX.Element {
|
||||||
return (
|
return (
|
||||||
<div className="mini-program-message">
|
<div className="mini-program-message">
|
||||||
@@ -426,11 +441,17 @@ function StickerBubble({
|
|||||||
function QuoteBubble({
|
function QuoteBubble({
|
||||||
data,
|
data,
|
||||||
sessionId,
|
sessionId,
|
||||||
|
localId,
|
||||||
|
serverId,
|
||||||
|
createTime,
|
||||||
onImageClick
|
onImageClick
|
||||||
}: {
|
}: {
|
||||||
data: Extract<ParsedContent, { type: 'quote' }>
|
data: Extract<ParsedContent, { type: 'quote' }>
|
||||||
sessionId?: string
|
sessionId?: string
|
||||||
onImageClick?: (imageUrl: string) => void
|
localId?: number
|
||||||
|
serverId?: string
|
||||||
|
createTime?: number
|
||||||
|
onImageClick?: ImageClickHandler
|
||||||
}): JSX.Element {
|
}): JSX.Element {
|
||||||
const quotedText = data.quotedContent || data.content || '[引用消息]'
|
const quotedText = data.quotedContent || data.content || '[引用消息]'
|
||||||
const replyText = data.content || data.title || ''
|
const replyText = data.content || data.title || ''
|
||||||
@@ -452,6 +473,9 @@ function QuoteBubble({
|
|||||||
imageMd5={data.quotedImageMd5}
|
imageMd5={data.quotedImageMd5}
|
||||||
imageDatName={data.quotedImageDatName}
|
imageDatName={data.quotedImageDatName}
|
||||||
sessionId={sessionId}
|
sessionId={sessionId}
|
||||||
|
localId={localId}
|
||||||
|
serverId={serverId}
|
||||||
|
createTime={createTime}
|
||||||
isThumb
|
isThumb
|
||||||
onImageClick={onImageClick}
|
onImageClick={onImageClick}
|
||||||
/>
|
/>
|
||||||
|
|||||||
@@ -1,9 +1,14 @@
|
|||||||
import { useEffect, useMemo, useState } from 'react'
|
import { useEffect, useMemo, useRef, useState } from 'react'
|
||||||
|
import { createPortal } from 'react-dom'
|
||||||
|
import type { JSX, MouseEvent } from 'react'
|
||||||
|
|
||||||
interface VideoBubbleProps {
|
interface VideoBubbleProps {
|
||||||
md5?: string
|
md5?: string
|
||||||
newMd5?: string
|
newMd5?: string
|
||||||
rawMd5?: string
|
rawMd5?: string
|
||||||
|
sessionId?: string
|
||||||
|
localId?: number
|
||||||
|
serverId?: string
|
||||||
createTime?: number
|
createTime?: number
|
||||||
byteLength?: number
|
byteLength?: number
|
||||||
duration?: number
|
duration?: number
|
||||||
@@ -15,6 +20,9 @@ export function VideoBubble({
|
|||||||
md5,
|
md5,
|
||||||
newMd5,
|
newMd5,
|
||||||
rawMd5,
|
rawMd5,
|
||||||
|
sessionId,
|
||||||
|
localId,
|
||||||
|
serverId,
|
||||||
createTime,
|
createTime,
|
||||||
byteLength,
|
byteLength,
|
||||||
duration,
|
duration,
|
||||||
@@ -26,13 +34,50 @@ export function VideoBubble({
|
|||||||
[md5, newMd5, rawMd5]
|
[md5, newMd5, rawMd5]
|
||||||
)
|
)
|
||||||
const [media, setMedia] = useState<{ url?: string; poster?: string; error?: string }>({})
|
const [media, setMedia] = useState<{ url?: string; poster?: string; error?: string }>({})
|
||||||
|
const [downloadingVideo, setDownloadingVideo] = useState(false)
|
||||||
|
const [contextMenuPos, setContextMenuPos] = useState<{ x: number; y: number } | null>(null)
|
||||||
|
const menuRef = useRef<HTMLDivElement>(null)
|
||||||
|
const mountedRef = useRef(true)
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
mountedRef.current = true
|
||||||
|
return () => {
|
||||||
|
mountedRef.current = false
|
||||||
|
}
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!contextMenuPos) return
|
||||||
|
const handlePointerDown = (event: globalThis.MouseEvent): void => {
|
||||||
|
if (menuRef.current && menuRef.current.contains(event.target as Node)) return
|
||||||
|
setContextMenuPos(null)
|
||||||
|
}
|
||||||
|
const handleKeyDown = (event: globalThis.KeyboardEvent): void => {
|
||||||
|
if (event.key === 'Escape') {
|
||||||
|
setContextMenuPos(null)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const handleScroll = (): void => {
|
||||||
|
setContextMenuPos(null)
|
||||||
|
}
|
||||||
|
window.addEventListener('mousedown', handlePointerDown, true)
|
||||||
|
window.addEventListener('keydown', handleKeyDown, true)
|
||||||
|
window.addEventListener('scroll', handleScroll, true)
|
||||||
|
return () => {
|
||||||
|
window.removeEventListener('mousedown', handlePointerDown, true)
|
||||||
|
window.removeEventListener('keydown', handleKeyDown, true)
|
||||||
|
window.removeEventListener('scroll', handleScroll, true)
|
||||||
|
}
|
||||||
|
}, [contextMenuPos])
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
let cancelled = false
|
let cancelled = false
|
||||||
window.api
|
window.api
|
||||||
.getVideo(hashes, { createTime, byteLength, duration, width, height })
|
.getVideo(hashes, { createTime, byteLength, duration, width, height })
|
||||||
.then((result) => {
|
.then((result) => {
|
||||||
if (!cancelled) setMedia(result.success ? result : { error: result.error })
|
if (!cancelled) {
|
||||||
|
setMedia(result.success ? result : { poster: result.poster, error: result.error })
|
||||||
|
}
|
||||||
})
|
})
|
||||||
.catch((error) => {
|
.catch((error) => {
|
||||||
if (!cancelled) setMedia({ error: error instanceof Error ? error.message : String(error) })
|
if (!cancelled) setMedia({ error: error instanceof Error ? error.message : String(error) })
|
||||||
@@ -42,12 +87,136 @@ export function VideoBubble({
|
|||||||
}
|
}
|
||||||
}, [byteLength, createTime, duration, hashes, height, width])
|
}, [byteLength, createTime, duration, hashes, height, width])
|
||||||
|
|
||||||
|
const handleOpenContextMenu = (event: MouseEvent): void => {
|
||||||
|
event.preventDefault()
|
||||||
|
event.stopPropagation()
|
||||||
|
const menuWidth = 152
|
||||||
|
const menuHeight = 88
|
||||||
|
const maxX =
|
||||||
|
typeof window !== 'undefined'
|
||||||
|
? Math.max(8, window.innerWidth - menuWidth - 8)
|
||||||
|
: event.clientX
|
||||||
|
const maxY =
|
||||||
|
typeof window !== 'undefined'
|
||||||
|
? Math.max(8, window.innerHeight - menuHeight - 8)
|
||||||
|
: event.clientY
|
||||||
|
setContextMenuPos({
|
||||||
|
x: Math.min(Math.max(8, event.clientX), maxX),
|
||||||
|
y: Math.min(Math.max(8, event.clientY), maxY)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleDownloadVideo = async (event?: MouseEvent): Promise<void> => {
|
||||||
|
event?.preventDefault()
|
||||||
|
event?.stopPropagation()
|
||||||
|
setContextMenuPos(null)
|
||||||
|
if (downloadingVideo) return
|
||||||
|
|
||||||
|
setDownloadingVideo(true)
|
||||||
|
try {
|
||||||
|
const result = await window.api.downloadVideo({
|
||||||
|
sessionId,
|
||||||
|
localId,
|
||||||
|
serverId,
|
||||||
|
createTime,
|
||||||
|
md5,
|
||||||
|
newMd5,
|
||||||
|
rawMd5
|
||||||
|
})
|
||||||
|
if (!mountedRef.current) return
|
||||||
|
if (!result.success || !result.url) {
|
||||||
|
alert(result.error ? `视频下载失败:${result.error}` : '视频下载失败')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
setMedia({
|
||||||
|
url: result.url,
|
||||||
|
poster: result.poster || media.poster
|
||||||
|
})
|
||||||
|
} catch (error) {
|
||||||
|
if (!mountedRef.current) return
|
||||||
|
alert(error instanceof Error ? `视频下载失败:${error.message}` : '视频下载失败')
|
||||||
|
} finally {
|
||||||
|
if (mountedRef.current) setDownloadingVideo(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleCopyMessageXml = async (event: MouseEvent): Promise<void> => {
|
||||||
|
event.preventDefault()
|
||||||
|
event.stopPropagation()
|
||||||
|
setContextMenuPos(null)
|
||||||
|
try {
|
||||||
|
const result = await window.api.getImageMessageXml({
|
||||||
|
sessionId,
|
||||||
|
localId,
|
||||||
|
serverId,
|
||||||
|
createTime
|
||||||
|
})
|
||||||
|
if (!result.success || !result.xml) {
|
||||||
|
alert(result.error ? `XML 获取失败:${result.error}` : 'XML 获取失败')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
await navigator.clipboard.writeText(result.xml)
|
||||||
|
alert('视频消息 XML 已复制')
|
||||||
|
} catch (error) {
|
||||||
|
alert(error instanceof Error ? `XML 复制失败:${error.message}` : 'XML 复制失败')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const renderContextMenu = (): JSX.Element | null => {
|
||||||
|
if (!contextMenuPos || typeof document === 'undefined') return null
|
||||||
|
return createPortal(
|
||||||
|
<div
|
||||||
|
ref={menuRef}
|
||||||
|
className="image-bubble-context-menu"
|
||||||
|
role="menu"
|
||||||
|
aria-label="视频右键菜单"
|
||||||
|
style={{ left: `${contextMenuPos.x}px`, top: `${contextMenuPos.y}px` }}
|
||||||
|
onClick={(event) => event.stopPropagation()}
|
||||||
|
onContextMenu={(event) => {
|
||||||
|
event.preventDefault()
|
||||||
|
event.stopPropagation()
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
role="menuitem"
|
||||||
|
className="image-bubble-context-item"
|
||||||
|
disabled={downloadingVideo}
|
||||||
|
onClick={(event) => void handleDownloadVideo(event)}
|
||||||
|
>
|
||||||
|
{downloadingVideo ? '正在下载视频...' : '下载视频'}
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
role="menuitem"
|
||||||
|
className="image-bubble-context-item"
|
||||||
|
onClick={(event) => void handleCopyMessageXml(event)}
|
||||||
|
>
|
||||||
|
复制 XML
|
||||||
|
</button>
|
||||||
|
</div>,
|
||||||
|
document.body
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
if (!media.url) {
|
if (!media.url) {
|
||||||
return <div className="video-placeholder">{media.error || '视频加载中…'}</div>
|
return (
|
||||||
|
<>
|
||||||
|
<div
|
||||||
|
className="video-placeholder"
|
||||||
|
onContextMenu={handleOpenContextMenu}
|
||||||
|
title="右键可下载视频或复制 XML"
|
||||||
|
>
|
||||||
|
{downloadingVideo ? '正在从微信下载视频…' : media.error || '视频加载中…'}
|
||||||
|
</div>
|
||||||
|
{renderContextMenu()}
|
||||||
|
</>
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="video-message">
|
<>
|
||||||
|
<div className="video-message" onContextMenu={handleOpenContextMenu}>
|
||||||
<video
|
<video
|
||||||
className="video-content"
|
className="video-content"
|
||||||
src={media.url}
|
src={media.url}
|
||||||
@@ -55,7 +224,13 @@ export function VideoBubble({
|
|||||||
controls
|
controls
|
||||||
preload="metadata"
|
preload="metadata"
|
||||||
/>
|
/>
|
||||||
{duration ? <span className="video-duration">{duration} 秒</span> : null}
|
{downloadingVideo ? (
|
||||||
|
<span className="video-duration">正在下载视频…</span>
|
||||||
|
) : duration ? (
|
||||||
|
<span className="video-duration">{duration} 秒</span>
|
||||||
|
) : null}
|
||||||
</div>
|
</div>
|
||||||
|
{renderContextMenu()}
|
||||||
|
</>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -2,7 +2,7 @@ import React, { useState } from 'react'
|
|||||||
import { Contact } from '../../../../shared/types'
|
import { Contact } from '../../../../shared/types'
|
||||||
import { Button, IconButton, Tooltip, TooltipContent, TooltipTrigger } from '../ui'
|
import { Button, IconButton, Tooltip, TooltipContent, TooltipTrigger } from '../ui'
|
||||||
import { ConversationContentSearch } from './ConversationContentSearch'
|
import { ConversationContentSearch } from './ConversationContentSearch'
|
||||||
import { AiIcon, ExportIcon, RefreshIcon, SearchIcon, SendIcon, StatsIcon } from './icons'
|
import { AiIcon, RefreshIcon, SearchIcon, SendIcon, StatsIcon } from './icons'
|
||||||
import { supportsPersonalWechatSend } from '../../utils/runtime-environment'
|
import { supportsPersonalWechatSend } from '../../utils/runtime-environment'
|
||||||
import { GroupMemberStatsDialog } from '../group-stats/GroupMemberStatsDialog'
|
import { GroupMemberStatsDialog } from '../group-stats/GroupMemberStatsDialog'
|
||||||
|
|
||||||
@@ -16,7 +16,6 @@ interface ChatHeaderProps {
|
|||||||
onContentFilterChange: (value: string) => void
|
onContentFilterChange: (value: string) => void
|
||||||
onRefresh?: () => void
|
onRefresh?: () => void
|
||||||
onTestSend: () => void
|
onTestSend: () => void
|
||||||
onSendFile?: () => void
|
|
||||||
onOpenAiSettings: () => void
|
onOpenAiSettings: () => void
|
||||||
/** 跳到「设置 · 本地索引」(群统计发现索引没追平时用)。 */
|
/** 跳到「设置 · 本地索引」(群统计发现索引没追平时用)。 */
|
||||||
onOpenLocalIndexSettings?: () => void
|
onOpenLocalIndexSettings?: () => void
|
||||||
@@ -32,7 +31,6 @@ export function ChatHeader({
|
|||||||
onContentFilterChange,
|
onContentFilterChange,
|
||||||
onRefresh,
|
onRefresh,
|
||||||
onTestSend,
|
onTestSend,
|
||||||
onSendFile,
|
|
||||||
onOpenAiSettings,
|
onOpenAiSettings,
|
||||||
onOpenLocalIndexSettings
|
onOpenLocalIndexSettings
|
||||||
}: ChatHeaderProps): React.ReactElement {
|
}: ChatHeaderProps): React.ReactElement {
|
||||||
@@ -133,19 +131,6 @@ export function ChatHeader({
|
|||||||
<TooltipContent>仅支持 macOS 和 Windows</TooltipContent>
|
<TooltipContent>仅支持 macOS 和 Windows</TooltipContent>
|
||||||
</Tooltip>
|
</Tooltip>
|
||||||
)}
|
)}
|
||||||
{supportsPersonalWechatSend && onSendFile ? (
|
|
||||||
<Button
|
|
||||||
variant="outline"
|
|
||||||
size="sm"
|
|
||||||
className="chat-header-text-action"
|
|
||||||
aria-label="发送文件"
|
|
||||||
title="发送文件"
|
|
||||||
onClick={onSendFile}
|
|
||||||
>
|
|
||||||
<ExportIcon />
|
|
||||||
<span>发送文件</span>
|
|
||||||
</Button>
|
|
||||||
) : null}
|
|
||||||
<Button
|
<Button
|
||||||
variant="default"
|
variant="default"
|
||||||
size="sm"
|
size="sm"
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import { useRef, useState } from 'react'
|
import { useEffect, useRef, useState } from 'react'
|
||||||
import {
|
import {
|
||||||
|
Button,
|
||||||
Dialog,
|
Dialog,
|
||||||
DialogContent,
|
DialogContent,
|
||||||
DialogDescription,
|
DialogDescription,
|
||||||
@@ -8,20 +9,68 @@ import {
|
|||||||
IconButton,
|
IconButton,
|
||||||
Separator
|
Separator
|
||||||
} from '../ui'
|
} from '../ui'
|
||||||
|
import type { ImageOriginalDownloadOutcome } from '../ImageBubble'
|
||||||
|
|
||||||
interface ChatImageViewerProps {
|
interface ChatImageViewerProps {
|
||||||
imageUrl: string
|
imageUrl: string
|
||||||
onClose: () => void
|
onClose: () => void
|
||||||
|
onDownloadOriginal?: () => Promise<ImageOriginalDownloadOutcome>
|
||||||
|
onImageChange?: (nextUrl: string) => void
|
||||||
}
|
}
|
||||||
|
|
||||||
export function ChatImageViewer({ imageUrl, onClose }: ChatImageViewerProps): React.ReactElement {
|
export function ChatImageViewer({
|
||||||
|
imageUrl,
|
||||||
|
onClose,
|
||||||
|
onDownloadOriginal,
|
||||||
|
onImageChange
|
||||||
|
}: ChatImageViewerProps): React.ReactElement {
|
||||||
|
const [displayUrl, setDisplayUrl] = useState(imageUrl)
|
||||||
const [scale, setScale] = useState(1)
|
const [scale, setScale] = useState(1)
|
||||||
const [rotation, setRotation] = useState(0)
|
const [rotation, setRotation] = useState(0)
|
||||||
const [offset, setOffset] = useState({ x: 0, y: 0 })
|
const [offset, setOffset] = useState({ x: 0, y: 0 })
|
||||||
|
const [downloadingOriginal, setDownloadingOriginal] = useState(false)
|
||||||
|
const [loadedOriginal, setLoadedOriginal] = useState(false)
|
||||||
|
const [downloadError, setDownloadError] = useState<string | null>(null)
|
||||||
const dragRef = useRef<{ x: number; y: number; offsetX: number; offsetY: number } | null>(null)
|
const dragRef = useRef<{ x: number; y: number; offsetX: number; offsetY: number } | null>(null)
|
||||||
const contentRef = useRef<HTMLDivElement | null>(null)
|
const contentRef = useRef<HTMLDivElement | null>(null)
|
||||||
const restoreFocusRef = useRef<HTMLElement | null>(null)
|
const restoreFocusRef = useRef<HTMLElement | null>(null)
|
||||||
const closingRef = useRef(false)
|
const closingRef = useRef(false)
|
||||||
|
const mountedRef = useRef(true)
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
mountedRef.current = true
|
||||||
|
return () => {
|
||||||
|
mountedRef.current = false
|
||||||
|
}
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
setDisplayUrl(imageUrl)
|
||||||
|
}, [imageUrl])
|
||||||
|
|
||||||
|
const handleDownloadOriginal = async (): Promise<void> => {
|
||||||
|
if (!onDownloadOriginal || downloadingOriginal) return
|
||||||
|
setDownloadingOriginal(true)
|
||||||
|
setDownloadError(null)
|
||||||
|
try {
|
||||||
|
const outcome = await onDownloadOriginal()
|
||||||
|
if (!mountedRef.current) return
|
||||||
|
if (!outcome.success || !outcome.data) {
|
||||||
|
setDownloadError(outcome.error || '原图加载失败')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
setDisplayUrl(outcome.data)
|
||||||
|
onImageChange?.(outcome.data)
|
||||||
|
setLoadedOriginal(true)
|
||||||
|
setScale(1)
|
||||||
|
setOffset({ x: 0, y: 0 })
|
||||||
|
} catch (error) {
|
||||||
|
if (!mountedRef.current) return
|
||||||
|
setDownloadError(error instanceof Error ? error.message : '原图加载失败')
|
||||||
|
} finally {
|
||||||
|
if (mountedRef.current) setDownloadingOriginal(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const closeViewer = (): void => {
|
const closeViewer = (): void => {
|
||||||
if (closingRef.current) return
|
if (closingRef.current) return
|
||||||
@@ -130,6 +179,34 @@ export function ChatImageViewer({ imageUrl, onClose }: ChatImageViewerProps): Re
|
|||||||
>
|
>
|
||||||
<span aria-hidden>⟲</span>
|
<span aria-hidden>⟲</span>
|
||||||
</IconButton>
|
</IconButton>
|
||||||
|
{onDownloadOriginal && (
|
||||||
|
<>
|
||||||
|
<Separator orientation="vertical" className="mx-1 h-5" />
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="ghost"
|
||||||
|
size="sm"
|
||||||
|
className="h-7 shrink-0 px-2.5 text-xs font-medium"
|
||||||
|
disabled={downloadingOriginal}
|
||||||
|
onClick={() => void handleDownloadOriginal()}
|
||||||
|
>
|
||||||
|
{downloadingOriginal
|
||||||
|
? '加载原图中...'
|
||||||
|
: loadedOriginal
|
||||||
|
? '已加载原图'
|
||||||
|
: '加载原图'}
|
||||||
|
</Button>
|
||||||
|
{downloadError && (
|
||||||
|
<span
|
||||||
|
className="truncate text-xs text-destructive"
|
||||||
|
title={downloadError}
|
||||||
|
role="alert"
|
||||||
|
>
|
||||||
|
{downloadError}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
</DialogHeader>
|
</DialogHeader>
|
||||||
<div
|
<div
|
||||||
@@ -146,7 +223,7 @@ export function ChatImageViewer({ imageUrl, onClose }: ChatImageViewerProps): Re
|
|||||||
>
|
>
|
||||||
<img
|
<img
|
||||||
className="pointer-events-none h-auto w-auto max-w-none select-none object-contain shadow-floating transition-transform duration-fast ease-out"
|
className="pointer-events-none h-auto w-auto max-w-none select-none object-contain shadow-floating transition-transform duration-fast ease-out"
|
||||||
src={imageUrl}
|
src={displayUrl}
|
||||||
alt="图片预览"
|
alt="图片预览"
|
||||||
draggable={false}
|
draggable={false}
|
||||||
style={{
|
style={{
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import React from 'react'
|
import React from 'react'
|
||||||
import { Contact, Message } from '../../../../shared/types'
|
import { Contact, Message } from '../../../../shared/types'
|
||||||
import { ImageBubble } from '../ImageBubble'
|
import { ImageBubble, type ImageClickHandler } from '../ImageBubble'
|
||||||
import { RichMessageBubble } from '../RichMessageBubble'
|
import { RichMessageBubble } from '../RichMessageBubble'
|
||||||
import { VoicePlayer } from '../VoicePlayer'
|
import { VoicePlayer } from '../VoicePlayer'
|
||||||
import { VideoBubble } from '../VideoBubble'
|
import { VideoBubble } from '../VideoBubble'
|
||||||
@@ -13,7 +13,7 @@ interface MessageBubbleProps {
|
|||||||
isGroupChat: boolean
|
isGroupChat: boolean
|
||||||
isMine: boolean
|
isMine: boolean
|
||||||
showAvatarSpace: boolean
|
showAvatarSpace: boolean
|
||||||
onImageClick: (imageUrl: string) => void
|
onImageClick: ImageClickHandler
|
||||||
isJumpTarget?: boolean
|
isJumpTarget?: boolean
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -84,6 +84,9 @@ export function MessageBubble({
|
|||||||
md5={message.contentData.md5}
|
md5={message.contentData.md5}
|
||||||
newMd5={message.contentData.newMd5}
|
newMd5={message.contentData.newMd5}
|
||||||
rawMd5={message.contentData.rawMd5}
|
rawMd5={message.contentData.rawMd5}
|
||||||
|
sessionId={message.sessionId}
|
||||||
|
localId={message.localId}
|
||||||
|
serverId={message.serverId}
|
||||||
createTime={message.createTime}
|
createTime={message.createTime}
|
||||||
byteLength={message.contentData.byteLength}
|
byteLength={message.contentData.byteLength}
|
||||||
duration={message.contentData.duration}
|
duration={message.contentData.duration}
|
||||||
@@ -94,6 +97,9 @@ export function MessageBubble({
|
|||||||
<RichMessageBubble
|
<RichMessageBubble
|
||||||
contentData={message.contentData}
|
contentData={message.contentData}
|
||||||
sessionId={message.sessionId}
|
sessionId={message.sessionId}
|
||||||
|
localId={message.localId}
|
||||||
|
serverId={message.serverId}
|
||||||
|
createTime={message.createTime}
|
||||||
onImageClick={onImageClick}
|
onImageClick={onImageClick}
|
||||||
/>
|
/>
|
||||||
) : (
|
) : (
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ import { Contact } from '../../../../shared/types'
|
|||||||
import { isGroupExitEventMessage } from '../../../../shared/group-exit-event-message'
|
import { isGroupExitEventMessage } from '../../../../shared/group-exit-event-message'
|
||||||
import { GroupExitEventBubble } from './GroupExitEventBubble'
|
import { GroupExitEventBubble } from './GroupExitEventBubble'
|
||||||
import { MessageBubble } from './MessageBubble'
|
import { MessageBubble } from './MessageBubble'
|
||||||
|
import type { ImageClickHandler } from '../ImageBubble'
|
||||||
import { MessageGroupModel } from './messageGrouping'
|
import { MessageGroupModel } from './messageGrouping'
|
||||||
|
|
||||||
interface MessageGroupProps {
|
interface MessageGroupProps {
|
||||||
@@ -10,7 +11,7 @@ interface MessageGroupProps {
|
|||||||
contact: Contact
|
contact: Contact
|
||||||
isGroupChat: boolean
|
isGroupChat: boolean
|
||||||
showAvatar: boolean
|
showAvatar: boolean
|
||||||
onImageClick: (imageUrl: string) => void
|
onImageClick: ImageClickHandler
|
||||||
jumpTargetMessageId?: string
|
jumpTargetMessageId?: string
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import React from 'react'
|
|||||||
import { useVirtualizer } from '@tanstack/react-virtual'
|
import { useVirtualizer } from '@tanstack/react-virtual'
|
||||||
import { Contact, Message } from '../../../../shared/types'
|
import { Contact, Message } from '../../../../shared/types'
|
||||||
import { MessageGroup } from './MessageGroup'
|
import { MessageGroup } from './MessageGroup'
|
||||||
|
import type { ImageClickHandler } from '../ImageBubble'
|
||||||
import { buildMessageGroups } from './messageGrouping'
|
import { buildMessageGroups } from './messageGrouping'
|
||||||
import { resolveMessageJumpTarget } from './messageJump'
|
import { resolveMessageJumpTarget } from './messageJump'
|
||||||
|
|
||||||
@@ -17,7 +18,7 @@ interface MessageListProps {
|
|||||||
bottomRef: React.RefObject<HTMLDivElement | null>
|
bottomRef: React.RefObject<HTMLDivElement | null>
|
||||||
onScroll: (event: React.UIEvent<HTMLDivElement>) => void
|
onScroll: (event: React.UIEvent<HTMLDivElement>) => void
|
||||||
onReachTop?: () => Promise<void>
|
onReachTop?: () => Promise<void>
|
||||||
onImageClick: (imageUrl: string) => void
|
onImageClick: ImageClickHandler
|
||||||
jumpToTime?: number | null
|
jumpToTime?: number | null
|
||||||
/**
|
/**
|
||||||
* 精确跳转目标(规范化消息 id,即去掉 `local:` 前缀后的 WCDB 本地 id)。
|
* 精确跳转目标(规范化消息 id,即去掉 `local:` 前缀后的 WCDB 本地 id)。
|
||||||
|
|||||||
@@ -37,6 +37,8 @@ interface ExportConfigurationPanelProps {
|
|||||||
includeVoiceTranscripts: boolean
|
includeVoiceTranscripts: boolean
|
||||||
includeAvatars: boolean
|
includeAvatars: boolean
|
||||||
preferOriginal: boolean
|
preferOriginal: boolean
|
||||||
|
hasMacHookMediaDownload?: boolean
|
||||||
|
onOpenSendSettings?: () => void
|
||||||
fallbackThumbnail: boolean
|
fallbackThumbnail: boolean
|
||||||
keepMissing: boolean
|
keepMissing: boolean
|
||||||
voiceModelStatus: VoiceModelStatus | null
|
voiceModelStatus: VoiceModelStatus | null
|
||||||
@@ -90,6 +92,8 @@ export function ExportConfigurationPanel({
|
|||||||
includeVoiceTranscripts,
|
includeVoiceTranscripts,
|
||||||
includeAvatars,
|
includeAvatars,
|
||||||
preferOriginal,
|
preferOriginal,
|
||||||
|
hasMacHookMediaDownload = false,
|
||||||
|
onOpenSendSettings,
|
||||||
fallbackThumbnail,
|
fallbackThumbnail,
|
||||||
keepMissing,
|
keepMissing,
|
||||||
voiceModelStatus,
|
voiceModelStatus,
|
||||||
@@ -335,7 +339,14 @@ export function ExportConfigurationPanel({
|
|||||||
>
|
>
|
||||||
{(
|
{(
|
||||||
[
|
[
|
||||||
['prefer-original', '优先导出原图', preferOriginal, onPreferOriginalChange],
|
[
|
||||||
|
'prefer-original',
|
||||||
|
hasMacHookMediaDownload
|
||||||
|
? '下载原图原视频替换(如视频或图片过期可导致下载失败)'
|
||||||
|
: '优先导出原图',
|
||||||
|
preferOriginal,
|
||||||
|
onPreferOriginalChange
|
||||||
|
],
|
||||||
[
|
[
|
||||||
'fallback-thumbnail',
|
'fallback-thumbnail',
|
||||||
'原图缺失时使用缩略图',
|
'原图缺失时使用缩略图',
|
||||||
@@ -366,6 +377,20 @@ export function ExportConfigurationPanel({
|
|||||||
<span>语音转文字,显示在语音条下方</span>
|
<span>语音转文字,显示在语音条下方</span>
|
||||||
</label>
|
</label>
|
||||||
</div>
|
</div>
|
||||||
|
{onOpenSendSettings && (
|
||||||
|
<div className="mt-2 flex items-center justify-between gap-2 rounded-md border border-border-subtle bg-primary/5 px-3 py-2 text-[11px] leading-[17px] text-muted-foreground">
|
||||||
|
<span>
|
||||||
|
如果有发送能力,可自动下载并导出高清原图、原视频等资源。
|
||||||
|
</span>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={onOpenSendSettings}
|
||||||
|
className="shrink-0 cursor-pointer border-0 bg-transparent p-0 text-[11px] font-medium text-primary hover:underline"
|
||||||
|
>
|
||||||
|
前往设置 · 发送能力 →
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
<p className={helperClassName}>
|
<p className={helperClassName}>
|
||||||
资源文件仅在 HTML 导出中生效,CSV、JSON 和 Markdown 只保留文本内容。
|
资源文件仅在 HTML 导出中生效,CSV、JSON 和 Markdown 只保留文本内容。
|
||||||
</p>
|
</p>
|
||||||
|
|||||||
@@ -40,6 +40,7 @@ export function ExportWorkspace({
|
|||||||
dbReady,
|
dbReady,
|
||||||
loadPreviewMessages,
|
loadPreviewMessages,
|
||||||
onOpenSettings,
|
onOpenSettings,
|
||||||
|
onOpenSendSettings,
|
||||||
exportTasks,
|
exportTasks,
|
||||||
onStartExport,
|
onStartExport,
|
||||||
onCancelExport
|
onCancelExport
|
||||||
@@ -79,6 +80,7 @@ export function ExportWorkspace({
|
|||||||
() => savedPreferences.includeVoiceTranscripts
|
() => savedPreferences.includeVoiceTranscripts
|
||||||
)
|
)
|
||||||
const [voiceModelStatus, setVoiceModelStatus] = useState<VoiceModelStatus | null>(null)
|
const [voiceModelStatus, setVoiceModelStatus] = useState<VoiceModelStatus | null>(null)
|
||||||
|
const [hasMacHookMediaDownload, setHasMacHookMediaDownload] = useState(false)
|
||||||
const [includeAvatars, setIncludeAvatars] = useState(() => savedPreferences.includeAvatars)
|
const [includeAvatars, setIncludeAvatars] = useState(() => savedPreferences.includeAvatars)
|
||||||
const [preferOriginal, setPreferOriginal] = useState(() => savedPreferences.preferOriginal)
|
const [preferOriginal, setPreferOriginal] = useState(() => savedPreferences.preferOriginal)
|
||||||
const [fallbackThumbnail, setFallbackThumbnail] = useState(
|
const [fallbackThumbnail, setFallbackThumbnail] = useState(
|
||||||
@@ -300,6 +302,22 @@ export function ExportWorkspace({
|
|||||||
.getVoiceModelStatus()
|
.getVoiceModelStatus()
|
||||||
.then((next) => active && setVoiceModelStatus(next))
|
.then((next) => active && setVoiceModelStatus(next))
|
||||||
.catch(() => undefined)
|
.catch(() => undefined)
|
||||||
|
void Promise.all([
|
||||||
|
window.api.getPersonalWechatSendCapability?.().catch(() => null),
|
||||||
|
window.api.getMacSendRuntimeAvailability?.().catch(() => null)
|
||||||
|
]).then(([capability, runtimeAvailability]) => {
|
||||||
|
if (!active) return
|
||||||
|
const isMacHookCapable =
|
||||||
|
runtimeAvailability?.state === 'available' ||
|
||||||
|
(capability?.senderStatus?.platform === 'darwin' &&
|
||||||
|
Boolean(
|
||||||
|
capability.ready ||
|
||||||
|
capability.senderStatus.runtimeReady ||
|
||||||
|
capability.senderStatus.attachReady ||
|
||||||
|
capability.senderStatus.canSend
|
||||||
|
))
|
||||||
|
setHasMacHookMediaDownload(Boolean(isMacHookCapable))
|
||||||
|
})
|
||||||
return () => {
|
return () => {
|
||||||
active = false
|
active = false
|
||||||
}
|
}
|
||||||
@@ -396,6 +414,7 @@ export function ExportWorkspace({
|
|||||||
includeMedia,
|
includeMedia,
|
||||||
includeVoiceTranscripts: shouldIncludeVoiceTranscripts,
|
includeVoiceTranscripts: shouldIncludeVoiceTranscripts,
|
||||||
preferOriginal,
|
preferOriginal,
|
||||||
|
...(preferOriginal && hasMacHookMediaDownload ? { downloadOriginalMedia: true } : {}),
|
||||||
fallbackThumbnail,
|
fallbackThumbnail,
|
||||||
keepMissing,
|
keepMissing,
|
||||||
includeAvatars,
|
includeAvatars,
|
||||||
@@ -547,6 +566,8 @@ export function ExportWorkspace({
|
|||||||
includeVoiceTranscripts={includeVoiceTranscripts}
|
includeVoiceTranscripts={includeVoiceTranscripts}
|
||||||
includeAvatars={includeAvatars}
|
includeAvatars={includeAvatars}
|
||||||
preferOriginal={preferOriginal}
|
preferOriginal={preferOriginal}
|
||||||
|
hasMacHookMediaDownload={hasMacHookMediaDownload}
|
||||||
|
onOpenSendSettings={onOpenSendSettings || onOpenSettings}
|
||||||
fallbackThumbnail={fallbackThumbnail}
|
fallbackThumbnail={fallbackThumbnail}
|
||||||
keepMissing={keepMissing}
|
keepMissing={keepMissing}
|
||||||
voiceModelStatus={voiceModelStatus}
|
voiceModelStatus={voiceModelStatus}
|
||||||
|
|||||||
@@ -35,6 +35,7 @@ export interface ExportWorkspaceProps {
|
|||||||
dbReady: boolean
|
dbReady: boolean
|
||||||
loadPreviewMessages: (contact: Contact) => Promise<Message[]>
|
loadPreviewMessages: (contact: Contact) => Promise<Message[]>
|
||||||
onOpenSettings: () => void
|
onOpenSettings: () => void
|
||||||
|
onOpenSendSettings?: () => void
|
||||||
exportTasks: ExportTaskRecord[]
|
exportTasks: ExportTaskRecord[]
|
||||||
onStartExport: (request: ExportRequest) => Promise<ExportResult>
|
onStartExport: (request: ExportRequest) => Promise<ExportResult>
|
||||||
onCancelExport: (jobId: string) => Promise<void>
|
onCancelExport: (jobId: string) => Promise<void>
|
||||||
|
|||||||
@@ -142,6 +142,17 @@ export function getCachedLoadedImage(
|
|||||||
return getCachedImage(imageMd5, imageDatName, options)
|
return getCachedImage(imageMd5, imageDatName, options)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 三种 mode 的缓存键互不相通;只写一种,另一条读取路径仍会回退到缩略图。 */
|
||||||
|
export function setCachedLoadedImage(
|
||||||
|
imageMd5: string | undefined,
|
||||||
|
imageDatName: string | undefined,
|
||||||
|
image: LoadedImage
|
||||||
|
): void {
|
||||||
|
cacheImage(imageMd5, imageDatName, { force: true }, image)
|
||||||
|
cacheImage(imageMd5, imageDatName, { preferThumbnail: true }, image)
|
||||||
|
cacheImage(imageMd5, imageDatName, {}, image)
|
||||||
|
}
|
||||||
|
|
||||||
export function requestImage(
|
export function requestImage(
|
||||||
imageMd5: string | undefined,
|
imageMd5: string | undefined,
|
||||||
imageDatName: string | undefined,
|
imageDatName: string | undefined,
|
||||||
|
|||||||
@@ -1628,6 +1628,44 @@
|
|||||||
padding: 4px 6px;
|
padding: 4px 6px;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.image-bubble-context-menu {
|
||||||
|
position: fixed;
|
||||||
|
z-index: 120;
|
||||||
|
min-width: 140px;
|
||||||
|
padding: 5px;
|
||||||
|
border: 1px solid var(--wxex-border, rgba(15, 23, 42, 0.12));
|
||||||
|
border-radius: 10px;
|
||||||
|
background: var(--wxex-bg-elevated, #ffffff);
|
||||||
|
box-shadow: 0 12px 28px rgba(15, 23, 42, 0.18);
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 2px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.image-bubble-context-item {
|
||||||
|
width: 100%;
|
||||||
|
padding: 7px 11px;
|
||||||
|
border: 0;
|
||||||
|
border-radius: 6px;
|
||||||
|
background: transparent;
|
||||||
|
color: var(--wxex-text-primary, #1e293b);
|
||||||
|
font-size: 13px;
|
||||||
|
line-height: 1.4;
|
||||||
|
text-align: left;
|
||||||
|
cursor: pointer;
|
||||||
|
transition: background-color 0.12s ease, color 0.12s ease;
|
||||||
|
|
||||||
|
&:hover:not(:disabled) {
|
||||||
|
background: var(--wxex-brand-soft, rgba(7, 193, 96, 0.12));
|
||||||
|
color: var(--wxex-brand, #07c160);
|
||||||
|
}
|
||||||
|
|
||||||
|
&:disabled {
|
||||||
|
opacity: 0.55;
|
||||||
|
cursor: wait;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
.voice-message {
|
.voice-message {
|
||||||
display: flex;
|
display: flex;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
|
|||||||
@@ -39,6 +39,8 @@ export interface ExportRequest {
|
|||||||
includeMedia: boolean
|
includeMedia: boolean
|
||||||
includeVoiceTranscripts?: boolean
|
includeVoiceTranscripts?: boolean
|
||||||
preferOriginal?: boolean
|
preferOriginal?: boolean
|
||||||
|
/** Mac 具备微信发送 能力时,在导出期间主动调用微信原生下载取回原图与原视频并替换。 */
|
||||||
|
downloadOriginalMedia?: boolean
|
||||||
fallbackThumbnail?: boolean
|
fallbackThumbnail?: boolean
|
||||||
keepMissing?: boolean
|
keepMissing?: boolean
|
||||||
includeAvatars?: boolean
|
includeAvatars?: boolean
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
/** 图片消息原始 XML 的查询契约。 */
|
/** 图片消息原始 XML 与原图下载的契约。 */
|
||||||
|
|
||||||
/** 渲染进程 → 主进程的查询入参。 */
|
/** 渲染进程 → 主进程的查询入参。 */
|
||||||
export interface ImageMessageXmlRequest {
|
export interface ImageMessageXmlRequest {
|
||||||
@@ -14,3 +14,57 @@ export interface ImageMessageXmlResult {
|
|||||||
xml?: string
|
xml?: string
|
||||||
error?: string
|
error?: string
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 渲染进程 → 主进程的原图下载入参。 */
|
||||||
|
export interface DownloadOriginalImageRequest {
|
||||||
|
sessionId?: string
|
||||||
|
localId?: number
|
||||||
|
serverId?: string
|
||||||
|
createTime?: number
|
||||||
|
imageMd5?: string
|
||||||
|
imageDatName?: string
|
||||||
|
fileId?: string
|
||||||
|
aesKey?: string
|
||||||
|
rawXml?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface DownloadOriginalImageResult {
|
||||||
|
success: boolean
|
||||||
|
data?: string
|
||||||
|
filePath?: string
|
||||||
|
fileType?: string
|
||||||
|
fileSize?: number
|
||||||
|
md5?: string
|
||||||
|
width?: number
|
||||||
|
height?: number
|
||||||
|
isOriginal?: boolean
|
||||||
|
byteIdentical?: boolean
|
||||||
|
verification?: string
|
||||||
|
rendition?: string
|
||||||
|
errorCode?: string
|
||||||
|
error?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 渲染进程 → 主进程的视频下载入参。 */
|
||||||
|
export interface DownloadVideoRequest {
|
||||||
|
sessionId?: string
|
||||||
|
localId?: number
|
||||||
|
serverId?: string
|
||||||
|
createTime?: number
|
||||||
|
md5?: string
|
||||||
|
newMd5?: string
|
||||||
|
rawMd5?: string
|
||||||
|
rawXml?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface DownloadVideoResult {
|
||||||
|
success: boolean
|
||||||
|
url?: string
|
||||||
|
poster?: string
|
||||||
|
filePath?: string
|
||||||
|
fileSize?: number
|
||||||
|
md5?: string
|
||||||
|
isRaw?: boolean
|
||||||
|
errorCode?: string
|
||||||
|
error?: string
|
||||||
|
}
|
||||||
@@ -67,7 +67,7 @@ export interface MacWechatRuntimeManifest {
|
|||||||
tmSendSourceSha256: string
|
tmSendSourceSha256: string
|
||||||
addressProfileSha256: string
|
addressProfileSha256: string
|
||||||
supportedWechatVersions: string[]
|
supportedWechatVersions: string[]
|
||||||
capabilities: Array<'text' | 'image' | 'voice' | 'file'>
|
capabilities: Array<'text' | 'image' | 'voice' | 'file' | 'download_image'>
|
||||||
capabilitiesByVersion?: Record<
|
capabilitiesByVersion?: Record<
|
||||||
string,
|
string,
|
||||||
{
|
{
|
||||||
@@ -103,6 +103,7 @@ export interface MacWechatBindingStatus {
|
|||||||
canSendText?: boolean
|
canSendText?: boolean
|
||||||
canSendImage?: boolean
|
canSendImage?: boolean
|
||||||
canSendVoice?: boolean
|
canSendVoice?: boolean
|
||||||
|
canDownloadImage?: boolean
|
||||||
attachCount: number
|
attachCount: number
|
||||||
lastAttachAt?: string
|
lastAttachAt?: string
|
||||||
lastDetachReason?: string
|
lastDetachReason?: string
|
||||||
|
|||||||
@@ -110,6 +110,9 @@ export type ForwardedMessageItem = {
|
|||||||
imageMd5?: string
|
imageMd5?: string
|
||||||
thumbMd5?: string
|
thumbMd5?: string
|
||||||
imageDatName?: string
|
imageDatName?: string
|
||||||
|
cdnFileId?: string
|
||||||
|
cdnAesKey?: string
|
||||||
|
rawXml?: string
|
||||||
exportMediaUrl?: string
|
exportMediaUrl?: string
|
||||||
dataSize?: number
|
dataSize?: number
|
||||||
thumbSize?: number
|
thumbSize?: number
|
||||||
|
|||||||
@@ -70,4 +70,62 @@ describe('ChatImageViewer', () => {
|
|||||||
await waitFor(() => expect(opener).toHaveFocus())
|
await waitFor(() => expect(opener).toHaveFocus())
|
||||||
expect(onClose).toHaveBeenCalledTimes(2)
|
expect(onClose).toHaveBeenCalledTimes(2)
|
||||||
})
|
})
|
||||||
|
|
||||||
|
it('loads the original image from the top toolbar and updates the displayed src', async () => {
|
||||||
|
const user = userEvent.setup()
|
||||||
|
const hdUrl = `${imageUrl}#hd`
|
||||||
|
const onDownloadOriginal = vi.fn().mockResolvedValue({ success: true, data: hdUrl })
|
||||||
|
const onImageChange = vi.fn()
|
||||||
|
|
||||||
|
render(
|
||||||
|
<TooltipProvider>
|
||||||
|
<ChatImageViewer
|
||||||
|
imageUrl={imageUrl}
|
||||||
|
onDownloadOriginal={onDownloadOriginal}
|
||||||
|
onImageChange={onImageChange}
|
||||||
|
onClose={vi.fn()}
|
||||||
|
/>
|
||||||
|
</TooltipProvider>
|
||||||
|
)
|
||||||
|
|
||||||
|
const loadButton = screen.getByRole('button', { name: '加载原图' })
|
||||||
|
await user.click(loadButton)
|
||||||
|
|
||||||
|
await waitFor(() => expect(onDownloadOriginal).toHaveBeenCalledTimes(1))
|
||||||
|
expect(screen.getByAltText('图片预览')).toHaveAttribute('src', hdUrl)
|
||||||
|
expect(onImageChange).toHaveBeenCalledWith(hdUrl)
|
||||||
|
expect(screen.getByRole('button', { name: '已加载原图' })).toBeVisible()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('surfaces an inline error when loading the original image fails', async () => {
|
||||||
|
const user = userEvent.setup()
|
||||||
|
const onDownloadOriginal = vi.fn().mockResolvedValue({
|
||||||
|
success: false,
|
||||||
|
error: '图片已在微信服务器过期'
|
||||||
|
})
|
||||||
|
|
||||||
|
render(
|
||||||
|
<TooltipProvider>
|
||||||
|
<ChatImageViewer
|
||||||
|
imageUrl={imageUrl}
|
||||||
|
onDownloadOriginal={onDownloadOriginal}
|
||||||
|
onClose={vi.fn()}
|
||||||
|
/>
|
||||||
|
</TooltipProvider>
|
||||||
|
)
|
||||||
|
|
||||||
|
await user.click(screen.getByRole('button', { name: '加载原图' }))
|
||||||
|
expect(await screen.findByRole('alert')).toHaveTextContent('图片已在微信服务器过期')
|
||||||
|
expect(screen.getByAltText('图片预览')).toHaveAttribute('src', imageUrl)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('hides the load-original button when send/runtime capability is unavailable', () => {
|
||||||
|
render(
|
||||||
|
<TooltipProvider>
|
||||||
|
<ChatImageViewer imageUrl={imageUrl} onClose={vi.fn()} />
|
||||||
|
</TooltipProvider>
|
||||||
|
)
|
||||||
|
|
||||||
|
expect(screen.queryByRole('button', { name: '加载原图' })).not.toBeInTheDocument()
|
||||||
|
})
|
||||||
})
|
})
|
||||||
@@ -226,6 +226,7 @@ describe('ExportWorkspace multi-chat selection', () => {
|
|||||||
it('restores export preferences after leaving and reopening the workspace', async () => {
|
it('restores export preferences after leaving and reopening the workspace', async () => {
|
||||||
const { unmount } = renderWorkspace()
|
const { unmount } = renderWorkspace()
|
||||||
|
|
||||||
|
await userEvent.click(screen.getByRole('button', { name: '前往设置 · 发送能力 →' }))
|
||||||
await userEvent.click(
|
await userEvent.click(
|
||||||
within(screen.getByRole('radiogroup', { name: '导出格式' })).getByRole('radio', {
|
within(screen.getByRole('radiogroup', { name: '导出格式' })).getByRole('radio', {
|
||||||
name: /HTML/
|
name: /HTML/
|
||||||
@@ -309,6 +310,43 @@ describe('ExportWorkspace multi-chat selection', () => {
|
|||||||
})
|
})
|
||||||
).toBeChecked()
|
).toBeChecked()
|
||||||
})
|
})
|
||||||
|
|
||||||
|
it('switches the original media option label and passes downloadOriginalMedia when Mac hook send capability is available', async () => {
|
||||||
|
const onStartExport = vi.fn(async () => ({ success: false }))
|
||||||
|
Object.defineProperty(window, 'api', {
|
||||||
|
configurable: true,
|
||||||
|
value: {
|
||||||
|
...window.api,
|
||||||
|
getMacSendRuntimeAvailability: vi
|
||||||
|
.fn()
|
||||||
|
.mockResolvedValue({ state: 'available', message: '微信发送组件可用' })
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
renderWorkspace(onStartExport)
|
||||||
|
|
||||||
|
expect(
|
||||||
|
await screen.findByRole('checkbox', {
|
||||||
|
name: '下载原图原视频替换(如视频或图片过期可导致下载失败)'
|
||||||
|
})
|
||||||
|
).toBeChecked()
|
||||||
|
|
||||||
|
await userEvent.click(screen.getByRole('button', { name: '前往设置 · 发送能力 →' }))
|
||||||
|
await userEvent.click(
|
||||||
|
within(screen.getByRole('radiogroup', { name: '导出格式' })).getByRole('radio', {
|
||||||
|
name: /HTML/
|
||||||
|
})
|
||||||
|
)
|
||||||
|
await userEvent.click(screen.getByRole('button', { name: '开始导出' }))
|
||||||
|
|
||||||
|
await waitFor(() => expect(onStartExport).toHaveBeenCalledOnce())
|
||||||
|
expect(onStartExport).toHaveBeenCalledWith(
|
||||||
|
expect.objectContaining({
|
||||||
|
preferOriginal: true,
|
||||||
|
downloadOriginalMedia: true
|
||||||
|
})
|
||||||
|
)
|
||||||
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
describe('ExportTaskCenter details', () => {
|
describe('ExportTaskCenter details', () => {
|
||||||
|
|||||||
@@ -3,9 +3,11 @@ import userEvent from '@testing-library/user-event'
|
|||||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||||
|
|
||||||
const requestImage = vi.fn()
|
const requestImage = vi.fn()
|
||||||
|
const setCachedLoadedImage = vi.fn()
|
||||||
vi.mock('../../src/renderer/src/components/image-loader', () => ({
|
vi.mock('../../src/renderer/src/components/image-loader', () => ({
|
||||||
getCachedLoadedImage: vi.fn(() => undefined),
|
getCachedLoadedImage: vi.fn(() => undefined),
|
||||||
requestImage: (...args: unknown[]) => requestImage(...args)
|
requestImage: (...args: unknown[]) => requestImage(...args),
|
||||||
|
setCachedLoadedImage: (...args: unknown[]) => setCachedLoadedImage(...args)
|
||||||
}))
|
}))
|
||||||
|
|
||||||
import { ImageBubble } from '../../src/renderer/src/components/ImageBubble'
|
import { ImageBubble } from '../../src/renderer/src/components/ImageBubble'
|
||||||
@@ -18,6 +20,7 @@ const original = `${thumbnail}original`
|
|||||||
describe('ImageBubble', () => {
|
describe('ImageBubble', () => {
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
requestImage.mockReset()
|
requestImage.mockReset()
|
||||||
|
setCachedLoadedImage.mockReset()
|
||||||
window.api = { copyImage: vi.fn().mockResolvedValue({ success: true }) } as typeof window.api
|
window.api = { copyImage: vi.fn().mockResolvedValue({ success: true }) } as typeof window.api
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -59,7 +62,7 @@ describe('ImageBubble', () => {
|
|||||||
expect(await screen.findByAltText('图片')).toBeVisible()
|
expect(await screen.findByAltText('图片')).toBeVisible()
|
||||||
})
|
})
|
||||||
|
|
||||||
it('copies the raw message xml when right clicked', async () => {
|
it('opens a context menu on right click and copies the raw message xml when selected', async () => {
|
||||||
const writeText = vi.fn().mockResolvedValue(undefined)
|
const writeText = vi.fn().mockResolvedValue(undefined)
|
||||||
Object.defineProperty(navigator, 'clipboard', {
|
Object.defineProperty(navigator, 'clipboard', {
|
||||||
value: { writeText },
|
value: { writeText },
|
||||||
@@ -87,6 +90,11 @@ describe('ImageBubble', () => {
|
|||||||
const image = await screen.findByAltText('图片')
|
const image = await screen.findByAltText('图片')
|
||||||
fireEvent.contextMenu(image)
|
fireEvent.contextMenu(image)
|
||||||
|
|
||||||
|
expect(screen.getByRole('menuitem', { name: '下载原图' })).toBeVisible()
|
||||||
|
const copyXmlButton = screen.getByRole('menuitem', { name: '复制 XML' })
|
||||||
|
expect(copyXmlButton).toBeVisible()
|
||||||
|
await userEvent.click(copyXmlButton)
|
||||||
|
|
||||||
await waitFor(() =>
|
await waitFor(() =>
|
||||||
expect(writeText).toHaveBeenCalledWith('<msg><img aeskey="fixture" /></msg>')
|
expect(writeText).toHaveBeenCalledWith('<msg><img aeskey="fixture" /></msg>')
|
||||||
)
|
)
|
||||||
@@ -100,6 +108,55 @@ describe('ImageBubble', () => {
|
|||||||
alertSpy.mockRestore()
|
alertSpy.mockRestore()
|
||||||
})
|
})
|
||||||
|
|
||||||
|
it('downloads the original image from the right-click context menu and updates the bubble', async () => {
|
||||||
|
const downloadOriginalImage = vi.fn().mockResolvedValue({
|
||||||
|
success: true,
|
||||||
|
data: original,
|
||||||
|
md5: 'fixture-image',
|
||||||
|
isOriginal: true
|
||||||
|
})
|
||||||
|
window.api = {
|
||||||
|
copyImage: vi.fn(),
|
||||||
|
downloadOriginalImage
|
||||||
|
} as unknown as typeof window.api
|
||||||
|
|
||||||
|
requestImage.mockResolvedValueOnce({ data: thumbnail, isThumbnail: true })
|
||||||
|
render(
|
||||||
|
<ImageBubble
|
||||||
|
imageMd5="fixture-image"
|
||||||
|
imageDatName="fixture.dat"
|
||||||
|
sessionId="fixture-session"
|
||||||
|
localId={99}
|
||||||
|
createTime={1700000100}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
|
||||||
|
const image = await screen.findByAltText('图片')
|
||||||
|
expect(image).toHaveAttribute('src', thumbnail)
|
||||||
|
fireEvent.contextMenu(image)
|
||||||
|
|
||||||
|
const downloadBtn = screen.getByRole('menuitem', { name: '下载原图' })
|
||||||
|
await userEvent.click(downloadBtn)
|
||||||
|
|
||||||
|
await waitFor(() => expect(downloadOriginalImage).toHaveBeenCalledTimes(1))
|
||||||
|
expect(downloadOriginalImage).toHaveBeenCalledWith({
|
||||||
|
sessionId: 'fixture-session',
|
||||||
|
localId: 99,
|
||||||
|
serverId: undefined,
|
||||||
|
createTime: 1700000100,
|
||||||
|
imageMd5: 'fixture-image',
|
||||||
|
imageDatName: 'fixture.dat',
|
||||||
|
fileId: undefined,
|
||||||
|
aesKey: undefined,
|
||||||
|
rawXml: undefined
|
||||||
|
})
|
||||||
|
await waitFor(() => expect(image).toHaveAttribute('src', original))
|
||||||
|
expect(setCachedLoadedImage).toHaveBeenCalledWith('fixture-image', 'fixture.dat', {
|
||||||
|
data: original,
|
||||||
|
isThumbnail: false
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
it('surfaces a failure instead of copying anything when the xml is unavailable', async () => {
|
it('surfaces a failure instead of copying anything when the xml is unavailable', async () => {
|
||||||
const writeText = vi.fn().mockResolvedValue(undefined)
|
const writeText = vi.fn().mockResolvedValue(undefined)
|
||||||
Object.defineProperty(navigator, 'clipboard', {
|
Object.defineProperty(navigator, 'clipboard', {
|
||||||
@@ -116,6 +173,7 @@ describe('ImageBubble', () => {
|
|||||||
render(<ImageBubble imageMd5="fixture-image" sessionId="fixture-session" localId={7} />)
|
render(<ImageBubble imageMd5="fixture-image" sessionId="fixture-session" localId={7} />)
|
||||||
|
|
||||||
fireEvent.contextMenu(await screen.findByAltText('图片'))
|
fireEvent.contextMenu(await screen.findByAltText('图片'))
|
||||||
|
await userEvent.click(screen.getByRole('menuitem', { name: '复制 XML' }))
|
||||||
|
|
||||||
await waitFor(() => expect(alertSpy).toHaveBeenCalledWith('XML 获取失败:数据库尚未连接'))
|
await waitFor(() => expect(alertSpy).toHaveBeenCalledWith('XML 获取失败:数据库尚未连接'))
|
||||||
expect(writeText).not.toHaveBeenCalled()
|
expect(writeText).not.toHaveBeenCalled()
|
||||||
|
|||||||
@@ -180,4 +180,28 @@ describe('VideoAssetService local fallback', () => {
|
|||||||
|
|
||||||
expect(result).toEqual({ success: false, error: '本地未找到该视频文件' })
|
expect(result).toEqual({ success: false, error: '本地未找到该视频文件' })
|
||||||
})
|
})
|
||||||
|
|
||||||
|
it('registers a newly downloaded video and pairs it with an existing thumbnail poster', async () => {
|
||||||
|
const { accountRoot, service } = createService()
|
||||||
|
const month = join(accountRoot, 'msg', 'video', '2026-11')
|
||||||
|
mkdirSync(month, { recursive: true })
|
||||||
|
const stem = '7f3c9a2e5b1d804fc6a7e93b2d10f854'
|
||||||
|
const posterPath = join(month, `${stem}_thumb.jpg`)
|
||||||
|
writeFileSync(posterPath, jpegFixture(219, 360))
|
||||||
|
|
||||||
|
const beforeDownload = await service.resolve([stem])
|
||||||
|
expect(beforeDownload.success).toBe(false)
|
||||||
|
expect(service.pathForUrl(beforeDownload.poster!)).toBe(posterPath)
|
||||||
|
|
||||||
|
const downloadedRawPath = join(month, `${stem}_raw.mp4`)
|
||||||
|
writeFileSync(downloadedRawPath, mp4Fixture(6, 'downloaded-raw-video'))
|
||||||
|
const registered = service.registerDownloadedVideo([stem], downloadedRawPath, true)
|
||||||
|
expect(service.pathForUrl(registered.url)).toBe(downloadedRawPath)
|
||||||
|
expect(service.pathForUrl(registered.poster!)).toBe(posterPath)
|
||||||
|
|
||||||
|
const afterDownload = await service.resolve([stem])
|
||||||
|
expect(afterDownload.success).toBe(true)
|
||||||
|
expect(service.pathForUrl(afterDownload.url!)).toBe(downloadedRawPath)
|
||||||
|
expect(service.pathForUrl(afterDownload.poster!)).toBe(posterPath)
|
||||||
|
})
|
||||||
})
|
})
|
||||||
Reference in new issue
Block a user