feat: 获取对应图片原图

This commit is contained in:
Wxw-Gu committed 2026-10-20 16:07:58 +08:00
1 parent 52c89bf0c7
commit 9ab71bf730
8 files changed
+177 -18

No files matched your search

+1
View File
@@ -28,3 +28,4 @@ progress.md
task_plan.md task_plan.md
*tm-wcdb-config-helper* *tm-wcdb-config-helper*
debug-originals
+36 -1
View File
@@ -99,6 +99,7 @@ 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 { import {
loadSettings, loadSettings,
saveSettings, saveSettings,
@@ -704,6 +705,16 @@ function toDebugQuality(quality: 'original' | 'medium' | 'thumbnail'): ImageDebu
return 'normal' return 'normal'
} }
/** 反转义以 HTML 实体形式存库的正文(& 必须最后处理)。 */
function unescapeXmlText(text: string): string {
return text
.replace(/&lt;/g, '<')
.replace(/&gt;/g, '>')
.replace(/&quot;/g, '"')
.replace(/&#39;/g, "'")
.replace(/&amp;/g, '&')
}
function buildImageResponse( function buildImageResponse(
image: DecodedImage, image: DecodedImage,
includeData = false includeData = false
@@ -1806,10 +1817,34 @@ app.whenReady().then(async () => {
} }
) )
/** 取回一条图片消息的原始 XML。需 sessionId + localId 定位。 */
ipcMain.handle(
'image:getMessageXml',
async (_, request: ImageMessageXmlRequest): Promise<ImageMessageXmlResult> => {
const sessionId = String(request?.sessionId || '').trim()
const localId = Math.trunc(Number(request?.localId) || 0)
const createTime = Math.trunc(Number(request?.createTime) || 0)
if (!sessionId) return { success: false, error: '缺少会话标识,无法定位消息' }
if (localId <= 0) return { success: false, error: '缺少消息序号,无法定位消息' }
try {
const db = chat.getChatDb()
const client = db ? db.getWcdb4Client() : null
if (!client) return { success: false, error: '数据库尚未连接' }
const raw = client.getRawMessageContent(sessionId, localId, createTime || undefined)
if (!raw) return { success: false, error: '这条消息没有可读取的正文' }
const xml = raw.trim().includes('<') ? raw.trim() : unescapeXmlText(raw.trim())
return { success: true, xml }
} catch (error) {
return { success: false, error: error instanceof Error ? error.message : String(error) }
}
}
)
ipcMain.handle('image:getStatus', async () => ipcMain.handle('image:getStatus', async () =>
inspectImageDecryptionStatus(imageKeyConfigService.getConfig()) inspectImageDecryptionStatus(imageKeyConfigService.getConfig())
) )
ipcMain.handle('image:saveConfig', (_, request: SaveImageKeyRequest) => { ipcMain.handle('image:saveConfig', (_, request: SaveImageKeyRequest) => {
const result = imageKeyConfigService.save(request) const result = imageKeyConfigService.save(request)
if (result.success) imageDecryptService = null if (result.success) imageDecryptService = null
+44
View File
@@ -3044,6 +3044,50 @@ export class Wcdb4Client {
return this.key return this.key
} }
/** 按 (localId, createTime) 取回一条消息的原始 content。 */
getRawMessageContent(username: string, localId: number, createTime?: number): string | null {
if (!this.wcdbExecQuery) return null
const targetId = Math.trunc(Number(localId) || 0)
if (!username || targetId <= 0) return null
const anchorTime = Math.trunc(Number(createTime) || 0)
let stores: Wcdb4MessageStore[] = []
try {
stores = this.listMessageStores(username)
} catch {
return null
}
const candidates: string[] = []
for (const store of stores) {
const conditions = [`"local_id" = ${targetId}`]
if (anchorTime > 0) {
conditions.push(`"create_time" = ${anchorTime}`)
}
const sql = `${this.messageTableSelect(store)} WHERE ${conditions.join(' AND ')} LIMIT 5`
let rows: Record<string, unknown>[] = []
try {
rows = this.executeMessageSql(store, sql)
} catch {
continue
}
for (const row of rows) {
try {
const message = this.normalizeMessage(row)
if (typeof message.msgContent === 'string' && message.msgContent.trim()) {
candidates.push(message.msgContent)
}
} catch {
// 单行解析失败不影响其它分片;定位信息不全时这里本来就可能拿不到。
}
}
}
if (candidates.length === 0) return null
candidates.sort((left, right) => right.length - left.length)
return candidates[0]
}
resolveImageHardlink(md5: string): Wcdb4ImageHardlink | null { resolveImageHardlink(md5: string): Wcdb4ImageHardlink | null {
if (!this.wcdbResolveImageHardlink) return null if (!this.wcdbResolveImageHardlink) return null
const normalizedMd5 = String(md5 || '') const normalizedMd5 = String(md5 || '')
+2
View File
@@ -40,6 +40,7 @@ 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 { import type {
AIChatRequestOptions, AIChatRequestOptions,
AiSearchExternalAuthorizationRequest, AiSearchExternalAuthorizationRequest,
@@ -460,6 +461,7 @@ declare global {
filePath?: string filePath?: string
}> }>
getImageDebugInfo: (request: ImageDebugInfoRequest) => Promise<ImageDebugInfoResult> getImageDebugInfo: (request: ImageDebugInfoRequest) => Promise<ImageDebugInfoResult>
getImageMessageXml: (request: ImageMessageXmlRequest) => Promise<ImageMessageXmlResult>
getVideo: ( getVideo: (
hashes: string[], hashes: string[],
options?: { options?: {
+4
View File
@@ -84,6 +84,7 @@ 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 { AccountDiscoveryResult } from '../shared/database-key' import type { AccountDiscoveryResult } from '../shared/database-key'
import type { import type {
VoiceBatchConversationSummary, VoiceBatchConversationSummary,
@@ -397,6 +398,9 @@ const api = {
) => ipcRenderer.invoke('db:getImage', imageMd5, imageDatNameOrThumb, sessionId, options), ) => ipcRenderer.invoke('db:getImage', imageMd5, imageDatNameOrThumb, sessionId, options),
getImageDebugInfo: (request: ImageDebugInfoRequest): Promise<ImageDebugInfoResult> => getImageDebugInfo: (request: ImageDebugInfoRequest): Promise<ImageDebugInfoResult> =>
ipcRenderer.invoke('image:getDebugInfo', request), ipcRenderer.invoke('image:getDebugInfo', request),
/** 图片消息原始 XML。 */
getImageMessageXml: (request: ImageMessageXmlRequest): Promise<ImageMessageXmlResult> =>
ipcRenderer.invoke('image:getMessageXml', request),
getVideo: ( getVideo: (
hashes: string[], hashes: string[],
options?: { options?: {
+10 -16
View File
@@ -131,31 +131,25 @@ export function ImageBubble({
alert('图片已复制') alert('图片已复制')
} }
/** /** 右键复制消息原始 XML。 */
* 复制的是「消息定位信息」而非图片内容: const handleCopyMessageXml = async (event: MouseEvent): Promise<void> => {
* 不带 aeskey / XML / fileid / 带票据的下载地址。
*/
const handleCopyDebugInfo = async (event: MouseEvent): Promise<void> => {
event.preventDefault() event.preventDefault()
event.stopPropagation() event.stopPropagation()
try { try {
const result = await window.api.getImageDebugInfo({ const result = await window.api.getImageMessageXml({
sessionId, sessionId,
localId, localId,
serverId, serverId,
createTime, createTime
imageMd5,
imageDatName
}) })
if (!result.success || !result.payload) { if (!result.success || !result.xml) {
alert(result.error ? `图片调试信息获取失败:${result.error}` : '图片调试信息获取失败') alert(result.error ? `XML 获取失败:${result.error}` : 'XML 获取失败')
return return
} }
const text = JSON.stringify(result.payload, null, 2) await navigator.clipboard.writeText(result.xml)
await navigator.clipboard.writeText(text) alert('图片消息 XML 已复制')
alert('图片调试信息已复制')
} catch (error) { } catch (error) {
alert(error instanceof Error ? `图片调试信息复制失败:${error.message}` : '图片调试信息复制失败') alert(error instanceof Error ? `XML 复制失败:${error.message}` : 'XML 复制失败')
} }
} }
@@ -230,7 +224,7 @@ export function ImageBubble({
tabIndex={0} tabIndex={0}
aria-label="查看图片" aria-label="查看图片"
onClick={handleClick} onClick={handleClick}
onContextMenu={handleCopyDebugInfo} onContextMenu={handleCopyMessageXml}
onKeyDown={handlePreviewKeyDown} onKeyDown={handlePreviewKeyDown}
> >
<img <img
+16
View File
@@ -0,0 +1,16 @@
/** 图片消息原始 XML 的查询契约。 */
/** 渲染进程 → 主进程的查询入参。 */
export interface ImageMessageXmlRequest {
sessionId?: string
localId?: number
serverId?: string
/** 消息创建时间(epoch 秒)。 */
createTime?: number
}
export interface ImageMessageXmlResult {
success: boolean
xml?: string
error?: string
}
+64 -1
View File
@@ -1,4 +1,4 @@
import { render, screen, waitFor } from '@testing-library/react' import { fireEvent, render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event' import userEvent from '@testing-library/user-event'
import { beforeEach, describe, expect, it, vi } from 'vitest' import { beforeEach, describe, expect, it, vi } from 'vitest'
@@ -59,6 +59,69 @@ describe('ImageBubble', () => {
expect(await screen.findByAltText('图片')).toBeVisible() expect(await screen.findByAltText('图片')).toBeVisible()
}) })
it('copies the raw message xml when right clicked', async () => {
const writeText = vi.fn().mockResolvedValue(undefined)
Object.defineProperty(navigator, 'clipboard', {
value: { writeText },
configurable: true
})
const alertSpy = vi.spyOn(window, 'alert').mockImplementation(() => undefined)
const getImageMessageXml = vi
.fn()
.mockResolvedValue({ success: true, xml: '<msg><img aeskey="fixture" /></msg>' })
window.api = {
copyImage: vi.fn(),
getImageMessageXml
} as unknown as typeof window.api
requestImage.mockResolvedValueOnce({ data: thumbnail, isThumbnail: true })
render(
<ImageBubble
imageMd5="fixture-image"
sessionId="fixture-session"
localId={42}
createTime={1700000000}
/>
)
const image = await screen.findByAltText('图片')
fireEvent.contextMenu(image)
await waitFor(() =>
expect(writeText).toHaveBeenCalledWith('<msg><img aeskey="fixture" /></msg>')
)
expect(getImageMessageXml).toHaveBeenCalledWith({
sessionId: 'fixture-session',
localId: 42,
serverId: undefined,
createTime: 1700000000
})
expect(alertSpy).toHaveBeenCalledWith('图片消息 XML 已复制')
alertSpy.mockRestore()
})
it('surfaces a failure instead of copying anything when the xml is unavailable', async () => {
const writeText = vi.fn().mockResolvedValue(undefined)
Object.defineProperty(navigator, 'clipboard', {
value: { writeText },
configurable: true
})
const alertSpy = vi.spyOn(window, 'alert').mockImplementation(() => undefined)
window.api = {
copyImage: vi.fn(),
getImageMessageXml: vi.fn().mockResolvedValue({ success: false, error: '数据库尚未连接' })
} as unknown as typeof window.api
requestImage.mockResolvedValueOnce({ data: thumbnail, isThumbnail: true })
render(<ImageBubble imageMd5="fixture-image" sessionId="fixture-session" localId={7} />)
fireEvent.contextMenu(await screen.findByAltText('图片'))
await waitFor(() => expect(alertSpy).toHaveBeenCalledWith('XML 获取失败:数据库尚未连接'))
expect(writeText).not.toHaveBeenCalled()
alertSpy.mockRestore()
})
it('places a quoted image on the line below the quoted sender', async () => { it('places a quoted image on the line below the quoted sender', async () => {
requestImage.mockResolvedValueOnce({ data: thumbnail, isThumbnail: true }) requestImage.mockResolvedValueOnce({ data: thumbnail, isThumbnail: true })
const { container } = render( const { container } = render(