mirror of
https://github.com/hicccc77/WeFlow.git
synced 2026-03-26 15:45:51 +00:00
Compare commits
14 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b4f37451be | ||
|
|
84ea378815 | ||
|
|
72d4db1f27 | ||
|
|
21ea879d97 | ||
|
|
a5baef2240 | ||
|
|
bbecf54aba | ||
|
|
5f868d193c | ||
|
|
62b035ab39 | ||
|
|
ff5ee33e08 | ||
|
|
8e28016e5e | ||
|
|
f17a18cb6d | ||
|
|
999f45e5f5 | ||
|
|
3e303fadd7 | ||
|
|
3b7590d8ce |
@@ -35,6 +35,7 @@ WeFlow 是一个**完全本地**的微信**实时**聊天记录查看、分析
|
||||
## 主要功能
|
||||
|
||||
- 本地实时查看聊天记录
|
||||
- 朋友圈图片、视频、**实况**的预览和解密
|
||||
- 统计分析与群聊画像
|
||||
- 年度报告与可视化概览
|
||||
- 导出聊天记录为 HTML 等格式
|
||||
@@ -86,6 +87,7 @@ npm run build
|
||||
## 致谢
|
||||
|
||||
- [密语 CipherTalk](https://github.com/ILoveBingLu/miyu) 为本项目提供了基础框架
|
||||
- [WeChat-Channels-Video-File-Decryption](https://github.com/Evil0ctal/WeChat-Channels-Video-File-Decryption) 提供了视频解密相关的技术参考
|
||||
|
||||
## 支持我们
|
||||
|
||||
|
||||
@@ -799,6 +799,14 @@ function registerIpcHandlers() {
|
||||
return chatService.getNewMessages(sessionId, minTime, limit)
|
||||
})
|
||||
|
||||
ipcMain.handle('chat:updateMessage', async (_, sessionId: string, localId: number, createTime: number, newContent: string) => {
|
||||
return chatService.updateMessage(sessionId, localId, createTime, newContent)
|
||||
})
|
||||
|
||||
ipcMain.handle('chat:deleteMessage', async (_, sessionId: string, localId: number, createTime: number, dbPathHint?: string) => {
|
||||
return chatService.deleteMessage(sessionId, localId, createTime, dbPathHint)
|
||||
})
|
||||
|
||||
ipcMain.handle('chat:getContact', async (_, username: string) => {
|
||||
return await chatService.getContact(username)
|
||||
})
|
||||
|
||||
@@ -131,6 +131,10 @@ contextBridge.exposeInMainWorld('electronAPI', {
|
||||
ipcRenderer.invoke('chat:getNewMessages', sessionId, minTime, limit),
|
||||
getContact: (username: string) => ipcRenderer.invoke('chat:getContact', username),
|
||||
getContactAvatar: (username: string) => ipcRenderer.invoke('chat:getContactAvatar', username),
|
||||
updateMessage: (sessionId: string, localId: number, createTime: number, newContent: string) =>
|
||||
ipcRenderer.invoke('chat:updateMessage', sessionId, localId, createTime, newContent),
|
||||
deleteMessage: (sessionId: string, localId: number, createTime: number, dbPathHint?: string) =>
|
||||
ipcRenderer.invoke('chat:deleteMessage', sessionId, localId, createTime, dbPathHint),
|
||||
resolveTransferDisplayNames: (chatroomId: string, payerUsername: string, receiverUsername: string) =>
|
||||
ipcRenderer.invoke('chat:resolveTransferDisplayNames', chatroomId, payerUsername, receiverUsername),
|
||||
getMyAvatarUrl: () => ipcRenderer.invoke('chat:getMyAvatarUrl'),
|
||||
|
||||
@@ -50,6 +50,9 @@ export interface Message {
|
||||
emojiCdnUrl?: string
|
||||
emojiMd5?: string
|
||||
emojiLocalPath?: string // 本地缓存 castle 路径
|
||||
emojiThumbUrl?: string
|
||||
emojiEncryptUrl?: string
|
||||
emojiAesKey?: string
|
||||
// 引用消息相关
|
||||
quotedContent?: string
|
||||
quotedSender?: string
|
||||
@@ -84,6 +87,7 @@ export interface Message {
|
||||
datadesc: string
|
||||
datatitle?: string
|
||||
}>
|
||||
_db_path?: string // 内部字段:记录消息所属数据库路径
|
||||
}
|
||||
|
||||
export interface Contact {
|
||||
@@ -109,7 +113,7 @@ const emojiDownloading: Map<string, Promise<string | null>> = new Map()
|
||||
class ChatService {
|
||||
private configService: ConfigService
|
||||
private connected = false
|
||||
private messageCursors: Map<string, { cursor: number; fetched: number; batchSize: number; startTime?: number; endTime?: number; ascending?: boolean }> = new Map()
|
||||
private messageCursors: Map<string, { cursor: number; fetched: number; batchSize: number; startTime?: number; endTime?: number; ascending?: boolean; bufferedMessages?: any[] }> = new Map()
|
||||
private readonly messageBatchDefault = 50
|
||||
private avatarCache: Map<string, ContactCacheEntry>
|
||||
private readonly avatarCacheTtlMs = 10 * 60 * 1000
|
||||
@@ -269,6 +273,32 @@ class ChatService {
|
||||
this.connected = false
|
||||
}
|
||||
|
||||
/**
|
||||
* 修改消息内容
|
||||
*/
|
||||
async updateMessage(sessionId: string, localId: number, createTime: number, newContent: string): Promise<{ success: boolean; error?: string }> {
|
||||
try {
|
||||
const connectResult = await this.ensureConnected()
|
||||
if (!connectResult.success) return { success: false, error: connectResult.error }
|
||||
return await wcdbService.updateMessage(sessionId, localId, createTime, newContent)
|
||||
} catch (e) {
|
||||
return { success: false, error: String(e) }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除消息
|
||||
*/
|
||||
async deleteMessage(sessionId: string, localId: number, createTime: number, dbPathHint?: string): Promise<{ success: boolean; error?: string }> {
|
||||
try {
|
||||
const connectResult = await this.ensureConnected()
|
||||
if (!connectResult.success) return { success: false, error: connectResult.error }
|
||||
return await wcdbService.deleteMessage(sessionId, localId, createTime, dbPathHint)
|
||||
} catch (e) {
|
||||
return { success: false, error: String(e) }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取会话列表(优化:先返回基础数据,不等待联系人信息加载)
|
||||
*/
|
||||
@@ -729,7 +759,7 @@ class ChatService {
|
||||
// 4. startTime/endTime 改变(视为全新查询)
|
||||
// 5. ascending 改变
|
||||
const needNewCursor = !state ||
|
||||
offset === 0 ||
|
||||
offset !== state.fetched || // Offset mismatch -> must reset cursor
|
||||
state.batchSize !== batchSize ||
|
||||
state.startTime !== startTime ||
|
||||
state.endTime !== endTime ||
|
||||
@@ -761,6 +791,7 @@ class ChatService {
|
||||
// 如果需要跳过消息(offset > 0),逐批获取但不返回
|
||||
// 注意:仅在 offset === 0 时重建游标最安全;
|
||||
// 当 startTime/endTime 变化导致重建时,offset 应由前端重置为 0
|
||||
state.bufferedMessages = []
|
||||
if (offset > 0) {
|
||||
console.warn(`[ChatService] 新游标需跳过 ${offset} 条消息(startTime=${startTime}, endTime=${endTime})`)
|
||||
let skipped = 0
|
||||
@@ -777,8 +808,22 @@ class ChatService {
|
||||
console.warn(`[ChatService] 跳过时数据耗尽: skipped=${skipped}/${offset}`)
|
||||
return { success: true, messages: [], hasMore: false }
|
||||
}
|
||||
skipped += skipBatch.rows.length
|
||||
state.fetched += skipBatch.rows.length
|
||||
|
||||
const count = skipBatch.rows.length
|
||||
// Check if we overshot the offset
|
||||
if (skipped + count > offset) {
|
||||
const keepIndex = offset - skipped
|
||||
if (keepIndex < count) {
|
||||
state.bufferedMessages = skipBatch.rows.slice(keepIndex)
|
||||
}
|
||||
}
|
||||
|
||||
skipped += count
|
||||
state.fetched += count
|
||||
|
||||
// If satisfied offset, break
|
||||
if (skipped >= offset) break;
|
||||
|
||||
if (!skipBatch.hasMore) {
|
||||
console.warn(`[ChatService] 跳过后无更多数据: skipped=${skipped}/${offset}`)
|
||||
return { success: true, messages: [], hasMore: false }
|
||||
@@ -787,13 +832,8 @@ class ChatService {
|
||||
if (attempts >= maxSkipAttempts) {
|
||||
console.error(`[ChatService] 跳过消息超过最大尝试次数: attempts=${attempts}`)
|
||||
}
|
||||
console.log(`[ChatService] 跳过完成: skipped=${skipped}, fetched=${state.fetched}`)
|
||||
console.log(`[ChatService] 跳过完成: skipped=${skipped}, fetched=${state.fetched}, buffered=${state.bufferedMessages?.length || 0}`)
|
||||
}
|
||||
} else if (state && offset !== state.fetched) {
|
||||
// offset 与 fetched 不匹配,说明状态不一致
|
||||
console.warn(`[ChatService] 游标状态不一致: offset=${offset}, fetched=${state.fetched}, 继续使用现有游标`)
|
||||
// 不重新创建游标,而是继续使用现有游标
|
||||
// 这样可以避免频繁重建导致的问题
|
||||
}
|
||||
|
||||
// 确保 state 已初始化
|
||||
@@ -803,19 +843,35 @@ class ChatService {
|
||||
}
|
||||
|
||||
// 获取当前批次的消息
|
||||
const batch = await wcdbService.fetchMessageBatch(state.cursor)
|
||||
if (!batch.success) {
|
||||
console.error('[ChatService] 获取消息批次失败:', batch.error)
|
||||
return { success: false, error: batch.error || '获取消息失败' }
|
||||
// Use buffered rows from skip logic if available
|
||||
let rows: any[] = state.bufferedMessages || []
|
||||
state.bufferedMessages = undefined // Clear buffer after use
|
||||
|
||||
// If buffer is not enough to fill a batch, try to fetch more
|
||||
// Or if buffer is empty, fetch a batch
|
||||
if (rows.length < batchSize) {
|
||||
const nextBatch = await wcdbService.fetchMessageBatch(state.cursor)
|
||||
if (nextBatch.success && nextBatch.rows) {
|
||||
rows = rows.concat(nextBatch.rows)
|
||||
state.fetched += nextBatch.rows.length
|
||||
} else if (!nextBatch.success) {
|
||||
console.error('[ChatService] 获取消息批次失败:', nextBatch.error)
|
||||
// If we have some buffered rows, we can still return them?
|
||||
// Or fail? Let's return what we have if any, otherwise fail.
|
||||
if (rows.length === 0) {
|
||||
return { success: false, error: nextBatch.error || '获取消息失败' }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!batch.rows) {
|
||||
console.error('[ChatService] 获取消息失败: 返回数据为空')
|
||||
return { success: false, error: '获取消息失败: 返回数据为空' }
|
||||
// If we have more than limit (due to buffer + full batch), slice it
|
||||
if (rows.length > limit) {
|
||||
rows = rows.slice(0, limit)
|
||||
// Note: We don't adjust state.fetched here because it tracks cursor position.
|
||||
// Next time offset will catch up or mismatch trigger reset.
|
||||
}
|
||||
|
||||
const rows = batch.rows as Record<string, any>[]
|
||||
const hasMore = batch.hasMore === true
|
||||
const hasMore = rows.length > 0 // Simplified hasMore check for now, can be improved
|
||||
|
||||
const normalized = this.normalizeMessageOrder(this.mapRowsToMessages(rows))
|
||||
|
||||
@@ -1151,6 +1207,9 @@ class ChatService {
|
||||
const emojiInfo = this.parseEmojiInfo(content)
|
||||
emojiCdnUrl = emojiInfo.cdnUrl
|
||||
emojiMd5 = emojiInfo.md5
|
||||
cdnThumbUrl = emojiInfo.thumbUrl // 复用 cdnThumbUrl 字段或使用 emojiThumbUrl
|
||||
// 注意:Message 接口定义的 emojiThumbUrl,这里我们统一一下
|
||||
// 如果 Message 接口有 emojiThumbUrl,则使用它
|
||||
} else if (localType === 3 && content) {
|
||||
const imageInfo = this.parseImageInfo(content)
|
||||
imageMd5 = imageInfo.md5
|
||||
@@ -1373,7 +1432,7 @@ class ChatService {
|
||||
/**
|
||||
* 解析表情包信息
|
||||
*/
|
||||
private parseEmojiInfo(content: string): { cdnUrl?: string; md5?: string } {
|
||||
private parseEmojiInfo(content: string): { cdnUrl?: string; md5?: string; thumbUrl?: string; encryptUrl?: string; aesKey?: string } {
|
||||
try {
|
||||
// 提取 cdnurl
|
||||
let cdnUrl: string | undefined
|
||||
@@ -1387,26 +1446,39 @@ class ChatService {
|
||||
}
|
||||
}
|
||||
|
||||
// 如果没有 cdnurl,尝试 thumburl
|
||||
if (!cdnUrl) {
|
||||
// 提取 thumburl
|
||||
let thumbUrl: string | undefined
|
||||
const thumbUrlMatch = /thumburl\s*=\s*['"]([^'"]+)['"]/i.exec(content) || /thumburl\s*=\s*([^'"]+?)(?=\s|\/|>)/i.exec(content)
|
||||
if (thumbUrlMatch) {
|
||||
cdnUrl = thumbUrlMatch[1].replace(/&/g, '&')
|
||||
if (cdnUrl.includes('%')) {
|
||||
thumbUrl = thumbUrlMatch[1].replace(/&/g, '&')
|
||||
if (thumbUrl.includes('%')) {
|
||||
try {
|
||||
cdnUrl = decodeURIComponent(cdnUrl)
|
||||
thumbUrl = decodeURIComponent(thumbUrl)
|
||||
} catch { }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 提取 md5
|
||||
const md5Match = /md5\s*=\s*['"]([a-fA-F0-9]+)['"]/i.exec(content) || /md5\s*=\s*([a-fA-F0-9]+)/i.exec(content)
|
||||
const md5 = md5Match ? md5Match[1] : undefined
|
||||
|
||||
// 不构造假 URL,只返回真正的 cdnurl
|
||||
// 没有 cdnUrl 时保持静默,交由后续回退逻辑处理
|
||||
return { cdnUrl, md5 }
|
||||
// 提取 encrypturl
|
||||
let encryptUrl: string | undefined
|
||||
const encryptUrlMatch = /encrypturl\s*=\s*['"]([^'"]+)['"]/i.exec(content) || /encrypturl\s*=\s*([^'"]+?)(?=\s|\/|>)/i.exec(content)
|
||||
if (encryptUrlMatch) {
|
||||
encryptUrl = encryptUrlMatch[1].replace(/&/g, '&')
|
||||
if (encryptUrl.includes('%')) {
|
||||
try {
|
||||
encryptUrl = decodeURIComponent(encryptUrl)
|
||||
} catch { }
|
||||
}
|
||||
}
|
||||
|
||||
// 提取 aeskey
|
||||
const aesKeyMatch = /aeskey\s*=\s*['"]([a-zA-Z0-9]+)['"]/i.exec(content) || /aeskey\s*=\s*([a-zA-Z0-9]+)/i.exec(content)
|
||||
const aesKey = aesKeyMatch ? aesKeyMatch[1] : undefined
|
||||
|
||||
return { cdnUrl, md5, thumbUrl, encryptUrl, aesKey }
|
||||
} catch (e) {
|
||||
console.error('[ChatService] 表情包解析失败:', e, { xml: content })
|
||||
return {}
|
||||
@@ -2622,11 +2694,7 @@ class ChatService {
|
||||
// 检查内存缓存
|
||||
const cached = emojiCache.get(cacheKey)
|
||||
if (cached && existsSync(cached)) {
|
||||
// 读取文件并转为 data URL
|
||||
const dataUrl = this.fileToDataUrl(cached)
|
||||
if (dataUrl) {
|
||||
return { success: true, localPath: dataUrl }
|
||||
}
|
||||
return { success: true, localPath: cached }
|
||||
}
|
||||
|
||||
// 检查是否正在下载
|
||||
@@ -2634,10 +2702,7 @@ class ChatService {
|
||||
if (downloading) {
|
||||
const result = await downloading
|
||||
if (result) {
|
||||
const dataUrl = this.fileToDataUrl(result)
|
||||
if (dataUrl) {
|
||||
return { success: true, localPath: dataUrl }
|
||||
}
|
||||
return { success: true, localPath: result }
|
||||
}
|
||||
return { success: false, error: '下载失败' }
|
||||
}
|
||||
@@ -2654,10 +2719,7 @@ class ChatService {
|
||||
const filePath = join(cacheDir, `${cacheKey}${ext}`)
|
||||
if (existsSync(filePath)) {
|
||||
emojiCache.set(cacheKey, filePath)
|
||||
const dataUrl = this.fileToDataUrl(filePath)
|
||||
if (dataUrl) {
|
||||
return { success: true, localPath: dataUrl }
|
||||
}
|
||||
return { success: true, localPath: filePath }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2671,10 +2733,7 @@ class ChatService {
|
||||
|
||||
if (localPath) {
|
||||
emojiCache.set(cacheKey, localPath)
|
||||
const dataUrl = this.fileToDataUrl(localPath)
|
||||
if (dataUrl) {
|
||||
return { success: true, localPath: dataUrl }
|
||||
}
|
||||
return { success: true, localPath }
|
||||
}
|
||||
return { success: false, error: '下载失败' }
|
||||
} catch (e) {
|
||||
@@ -3917,6 +3976,13 @@ class ChatService {
|
||||
const imgInfo = this.parseImageInfo(rawContent)
|
||||
Object.assign(msg, imgInfo)
|
||||
msg.imageDatName = this.parseImageDatNameFromRow(row)
|
||||
} else if (msg.localType === 47) { // Emoji
|
||||
const emojiInfo = this.parseEmojiInfo(rawContent)
|
||||
msg.emojiCdnUrl = emojiInfo.cdnUrl
|
||||
msg.emojiMd5 = emojiInfo.md5
|
||||
msg.emojiThumbUrl = emojiInfo.thumbUrl
|
||||
msg.emojiEncryptUrl = emojiInfo.encryptUrl
|
||||
msg.emojiAesKey = emojiInfo.aesKey
|
||||
}
|
||||
|
||||
return msg
|
||||
@@ -4227,6 +4293,34 @@ class ChatService {
|
||||
return { success: false, error: String(e) }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 下载表情包文件(用于导出,返回文件路径)
|
||||
*/
|
||||
async downloadEmojiFile(msg: Message): Promise<string | null> {
|
||||
if (!msg.emojiMd5) return null
|
||||
let url = msg.emojiCdnUrl
|
||||
|
||||
// 尝试获取 URL
|
||||
if (!url && msg.emojiEncryptUrl) {
|
||||
console.warn('[ChatService] Emoji has only encryptUrl:', msg.emojiMd5)
|
||||
}
|
||||
|
||||
if (!url) {
|
||||
await this.fallbackEmoticon(msg)
|
||||
url = msg.emojiCdnUrl
|
||||
}
|
||||
|
||||
if (!url) return null
|
||||
|
||||
// Reuse existing downloadEmoji method
|
||||
const result = await this.downloadEmoji(url, msg.emojiMd5)
|
||||
if (result.success && result.localPath) {
|
||||
return result.localPath
|
||||
}
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
export const chatService = new ChatService()
|
||||
|
||||
@@ -14,7 +14,7 @@ interface ConfigSchema {
|
||||
|
||||
// 缓存相关
|
||||
cachePath: string
|
||||
weixinDllPath: string
|
||||
|
||||
lastOpenedDb: string
|
||||
lastSession: string
|
||||
|
||||
@@ -75,7 +75,7 @@ export class ConfigService {
|
||||
imageAesKey: '',
|
||||
wxidConfigs: {},
|
||||
cachePath: '',
|
||||
weixinDllPath: '',
|
||||
|
||||
lastOpenedDb: '',
|
||||
lastSession: '',
|
||||
theme: 'system',
|
||||
|
||||
@@ -1479,49 +1479,30 @@ class ExportService {
|
||||
fs.mkdirSync(emojisDir, { recursive: true })
|
||||
}
|
||||
|
||||
// 使用消息对象中已提取的字段
|
||||
const emojiUrl = msg.emojiCdnUrl
|
||||
const emojiMd5 = msg.emojiMd5
|
||||
|
||||
if (!emojiUrl && !emojiMd5) {
|
||||
// 使用 chatService 下载表情包 (利用其重试和 fallback 逻辑)
|
||||
const localPath = await chatService.downloadEmojiFile(msg)
|
||||
|
||||
if (!localPath || !fs.existsSync(localPath)) {
|
||||
return null
|
||||
}
|
||||
|
||||
|
||||
|
||||
const key = emojiMd5 || String(msg.localId)
|
||||
// 根据 URL 判断扩展名
|
||||
let ext = '.gif'
|
||||
if (emojiUrl) {
|
||||
if (emojiUrl.includes('.png')) ext = '.png'
|
||||
else if (emojiUrl.includes('.jpg') || emojiUrl.includes('.jpeg')) ext = '.jpg'
|
||||
}
|
||||
// 确定目标文件名
|
||||
const ext = path.extname(localPath) || '.gif'
|
||||
const key = msg.emojiMd5 || String(msg.localId)
|
||||
const fileName = `${key}${ext}`
|
||||
const destPath = path.join(emojisDir, fileName)
|
||||
|
||||
// 如果已存在则跳过
|
||||
if (fs.existsSync(destPath)) {
|
||||
// 复制文件到导出目录 (如果不存在)
|
||||
if (!fs.existsSync(destPath)) {
|
||||
fs.copyFileSync(localPath, destPath)
|
||||
}
|
||||
|
||||
return {
|
||||
relativePath: path.posix.join(mediaRelativePrefix, 'emojis', fileName),
|
||||
kind: 'emoji'
|
||||
}
|
||||
}
|
||||
|
||||
// 下载表情
|
||||
if (emojiUrl) {
|
||||
const downloaded = await this.downloadFile(emojiUrl, destPath)
|
||||
if (downloaded) {
|
||||
return {
|
||||
relativePath: path.posix.join(mediaRelativePrefix, 'emojis', fileName),
|
||||
kind: 'emoji'
|
||||
}
|
||||
} else {
|
||||
}
|
||||
}
|
||||
|
||||
return null
|
||||
} catch (e) {
|
||||
console.error('ExportService: exportEmoji failed', e)
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
@@ -99,23 +99,29 @@ export class Isaac64 {
|
||||
this.isaac64();
|
||||
this.randcnt = 256;
|
||||
}
|
||||
return this.randrsl[256 - (this.randcnt--)];
|
||||
return this.randrsl[--this.randcnt];
|
||||
}
|
||||
|
||||
/**
|
||||
* Generates a keystream of the specified size (in bytes).
|
||||
* @param size Size of the keystream in bytes (must be multiple of 8)
|
||||
* @returns Buffer containing the keystream
|
||||
* Generates a keystream where each 64-bit block is Big-Endian.
|
||||
* This matches WeChat's behavior (Reverse index order + byte reversal).
|
||||
*/
|
||||
public generateKeystream(size: number): Buffer {
|
||||
const stream = new BigUint64Array(size / 8);
|
||||
for (let i = 0; i < stream.length; i++) {
|
||||
stream[i] = this.getNext();
|
||||
public generateKeystreamBE(size: number): Buffer {
|
||||
const buffer = Buffer.allocUnsafe(size);
|
||||
const fullBlocks = Math.floor(size / 8);
|
||||
|
||||
for (let i = 0; i < fullBlocks; i++) {
|
||||
buffer.writeBigUInt64BE(this.getNext(), i * 8);
|
||||
}
|
||||
// WeChat's logic specifically reverses the entire byte array
|
||||
const buffer = Buffer.from(stream.buffer);
|
||||
// 注意:根据 worker.html 的逻辑,它是对 Uint8Array 执行 reverse()
|
||||
// Array.from(wasmArray).reverse()
|
||||
return buffer.reverse();
|
||||
|
||||
const remaining = size % 8;
|
||||
if (remaining > 0) {
|
||||
const lastK = this.getNext();
|
||||
const temp = Buffer.allocUnsafe(8);
|
||||
temp.writeBigUInt64BE(lastK, 0);
|
||||
temp.copy(buffer, fullBlocks * 8, 0, remaining);
|
||||
}
|
||||
|
||||
return buffer;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -292,7 +292,6 @@ class SnsService {
|
||||
// 视频专用下载逻辑 (下载 -> 解密 -> 缓存)
|
||||
return new Promise(async (resolve) => {
|
||||
const tmpPath = join(require('os').tmpdir(), `sns_video_${Date.now()}_${Math.random().toString(36).slice(2)}.enc`)
|
||||
console.log(`[SnsService] 开始下载视频到临时文件: ${tmpPath}`)
|
||||
|
||||
try {
|
||||
const https = require('https')
|
||||
@@ -325,7 +324,6 @@ class SnsService {
|
||||
|
||||
fileStream.on('finish', async () => {
|
||||
fileStream.close()
|
||||
console.log(`[SnsService] 视频下载完成,开始解密... Key: ${key}`)
|
||||
|
||||
try {
|
||||
const encryptedBuffer = await readFile(tmpPath)
|
||||
@@ -334,7 +332,6 @@ class SnsService {
|
||||
|
||||
if (key && String(key).trim().length > 0) {
|
||||
try {
|
||||
console.log(`[SnsService] 使用 WASM Isaac64 解密视频... Key: ${key}`)
|
||||
const keyText = String(key).trim()
|
||||
let keystream: Buffer
|
||||
|
||||
@@ -344,9 +341,8 @@ class SnsService {
|
||||
keystream = await wasmService.getKeystream(keyText, 131072)
|
||||
} catch (wasmErr) {
|
||||
// 打包漏带 wasm 或 wasm 初始化异常时,回退到纯 TS ISAAC64
|
||||
console.warn(`[SnsService] WASM 解密不可用,回退 Isaac64: ${wasmErr}`)
|
||||
const isaac = new Isaac64(keyText)
|
||||
keystream = isaac.generateKeystream(131072)
|
||||
keystream = isaac.generateKeystreamBE(131072)
|
||||
}
|
||||
|
||||
const decryptLen = Math.min(keystream.length, raw.length)
|
||||
@@ -358,23 +354,16 @@ class SnsService {
|
||||
|
||||
// 验证 MP4 签名 ('ftyp' at offset 4)
|
||||
const ftyp = raw.subarray(4, 8).toString('ascii')
|
||||
if (ftyp === 'ftyp') {
|
||||
console.log(`[SnsService] 视频解密成功: ${url}`)
|
||||
} else {
|
||||
console.warn(`[SnsService] 视频解密可能失败: ${url}, 未找到 ftyp 签名: ${ftyp}`)
|
||||
// 打印前 32 字节用于调试
|
||||
console.warn(`[SnsService] Decrypted Header (first 32 bytes): ${raw.subarray(0, 32).toString('hex')}`)
|
||||
if (ftyp !== 'ftyp') {
|
||||
// 可以在此处记录解密可能失败的标记,但不打印详细 hex
|
||||
}
|
||||
} catch (err) {
|
||||
console.error(`[SnsService] 视频解密出错: ${err}`)
|
||||
}
|
||||
} else {
|
||||
console.warn(`[SnsService] 未提供 Key,跳过解密,直接保存`)
|
||||
}
|
||||
|
||||
// 写入最终缓存 (覆盖)
|
||||
await writeFile(cachePath, raw)
|
||||
console.log(`[SnsService] 视频已保存到缓存: ${cachePath}`)
|
||||
|
||||
// 删除临时文件
|
||||
try { await import('fs/promises').then(fs => fs.unlink(tmpPath)) } catch (e) { }
|
||||
@@ -444,8 +433,24 @@ class SnsService {
|
||||
// 图片逻辑
|
||||
const shouldDecrypt = (xEnc === '1' || !!key) && key !== undefined && key !== null && String(key).trim().length > 0
|
||||
if (shouldDecrypt) {
|
||||
const decrypted = await wcdbService.decryptSnsImage(raw, String(key))
|
||||
decoded = Buffer.from(decrypted)
|
||||
try {
|
||||
const keyStr = String(key).trim()
|
||||
if (/^\d+$/.test(keyStr)) {
|
||||
// 使用 WASM 版本的 Isaac64 解密图片
|
||||
// 修正逻辑:使用带 reverse 且修正了 8字节对齐偏移的 getKeystream
|
||||
const wasmService = WasmService.getInstance()
|
||||
const keystream = await wasmService.getKeystream(keyStr, raw.length)
|
||||
|
||||
const decrypted = Buffer.allocUnsafe(raw.length)
|
||||
for (let i = 0; i < raw.length; i++) {
|
||||
decrypted[i] = raw[i] ^ keystream[i]
|
||||
}
|
||||
|
||||
decoded = decrypted
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('[SnsService] TS Decrypt Error:', e)
|
||||
}
|
||||
}
|
||||
|
||||
// 写入磁盘缓存
|
||||
|
||||
@@ -46,7 +46,6 @@ export class WasmService {
|
||||
const wasmPath = path.join(basePath, 'wasm_video_decode.wasm');
|
||||
const jsPath = path.join(basePath, 'wasm_video_decode.js');
|
||||
|
||||
console.log('[WasmService] Loading WASM from:', wasmPath);
|
||||
|
||||
if (!fs.existsSync(wasmPath) || !fs.existsSync(jsPath)) {
|
||||
throw new Error(`WASM files not found at ${basePath}`);
|
||||
@@ -88,7 +87,6 @@ export class WasmService {
|
||||
// Define Module
|
||||
mockGlobal.Module = {
|
||||
onRuntimeInitialized: () => {
|
||||
console.log("[WasmService] WASM Runtime Initialized");
|
||||
this.wasmLoaded = true;
|
||||
resolve();
|
||||
},
|
||||
@@ -133,10 +131,24 @@ export class WasmService {
|
||||
}
|
||||
|
||||
public async getKeystream(key: string, size: number = 131072): Promise<Buffer> {
|
||||
// ISAAC-64 uses 8-byte blocks. If size is not a multiple of 8,
|
||||
// the global reverse() will cause a shift in alignment.
|
||||
const alignSize = Math.ceil(size / 8) * 8;
|
||||
const buffer = await this.getRawKeystream(key, alignSize);
|
||||
|
||||
// Reverse the entire aligned buffer
|
||||
const reversed = new Uint8Array(buffer);
|
||||
reversed.reverse();
|
||||
|
||||
// Return exactly the requested size from the beginning of the reversed stream.
|
||||
// Since we reversed the 'aligned' buffer, index 0 is the last byte of the last block.
|
||||
return Buffer.from(reversed).subarray(0, size);
|
||||
}
|
||||
|
||||
public async getRawKeystream(key: string, size: number = 131072): Promise<Buffer> {
|
||||
await this.init();
|
||||
|
||||
if (!this.module || !this.module.WxIsaac64) {
|
||||
// Fallback check for asm.WxIsaac64 logic if needed, but debug showed it on Module
|
||||
if (this.module.asm && this.module.asm.WxIsaac64) {
|
||||
this.module.WxIsaac64 = this.module.asm.WxIsaac64;
|
||||
}
|
||||
@@ -149,26 +161,19 @@ export class WasmService {
|
||||
try {
|
||||
this.capturedKeystream = null;
|
||||
const isaac = new this.module.WxIsaac64(key);
|
||||
isaac.generate(size); // This triggers the global.wasm_isaac_generate callback
|
||||
isaac.generate(size);
|
||||
|
||||
// Cleanup if possible? isaac.delete()?
|
||||
// In worker code: p.decryptor.delete()
|
||||
if (isaac.delete) {
|
||||
isaac.delete();
|
||||
}
|
||||
|
||||
if (this.capturedKeystream) {
|
||||
// The worker_release.js logic does:
|
||||
// p.decryptor_array.set(r.reverse())
|
||||
// So the actual keystream is the REVERSE of what is passed to the callback.
|
||||
const reversed = new Uint8Array(this.capturedKeystream);
|
||||
reversed.reverse();
|
||||
return Buffer.from(reversed);
|
||||
return Buffer.from(this.capturedKeystream);
|
||||
} else {
|
||||
throw new Error('[WasmService] Failed to capture keystream (callback not called)');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('[WasmService] Error generating keystream:', error);
|
||||
console.error('[WasmService] Error generating raw keystream:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -27,6 +27,8 @@ export class WcdbCore {
|
||||
private wcdbCloseAccount: any = null
|
||||
private wcdbSetMyWxid: any = null
|
||||
private wcdbFreeString: any = null
|
||||
private wcdbUpdateMessage: any = null
|
||||
private wcdbDeleteMessage: any = null
|
||||
private wcdbGetSessions: any = null
|
||||
private wcdbGetMessages: any = null
|
||||
private wcdbGetMessageCount: any = null
|
||||
@@ -66,7 +68,7 @@ export class WcdbCore {
|
||||
private wcdbStopMonitorPipe: any = null
|
||||
|
||||
private monitorPipeClient: any = null
|
||||
private wcdbDecryptSnsImage: any = null
|
||||
|
||||
|
||||
private avatarUrlCache: Map<string, { url?: string; updatedAt: number }> = new Map()
|
||||
private readonly avatarCacheTtlMs = 10 * 60 * 1000
|
||||
@@ -144,42 +146,7 @@ export class WcdbCore {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 解密朋友圈图片
|
||||
*/
|
||||
async decryptSnsImage(encryptedData: Buffer, key: string): Promise<Buffer> {
|
||||
if (!this.initialized) {
|
||||
const initOk = await this.initialize()
|
||||
if (!initOk) return encryptedData
|
||||
}
|
||||
|
||||
if (!this.wcdbDecryptSnsImage) return encryptedData
|
||||
|
||||
try {
|
||||
if (!this.wcdbDecryptSnsImage) {
|
||||
console.error('[WCDB] wcdbDecryptSnsImage func is null')
|
||||
return encryptedData
|
||||
}
|
||||
|
||||
const outPtr = [null as any]
|
||||
// Koffi pass Buffer as char* pointer
|
||||
const result = this.wcdbDecryptSnsImage(encryptedData, encryptedData.length, key, outPtr)
|
||||
|
||||
if (result === 0 && outPtr[0]) {
|
||||
const hex = this.decodeJsonPtr(outPtr[0])
|
||||
if (hex) {
|
||||
return Buffer.from(hex, 'hex')
|
||||
}
|
||||
} else {
|
||||
console.error(`[WCDB] Decrypt SNS image failed with code: ${result}`)
|
||||
// 主动获取 DLL 内部日志以诊断问题
|
||||
await this.printLogs(true)
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('解密图片失败:', e)
|
||||
}
|
||||
return encryptedData
|
||||
}
|
||||
|
||||
stopMonitor(): void {
|
||||
if (this.monitorPipeClient) {
|
||||
@@ -420,6 +387,20 @@ export class WcdbCore {
|
||||
this.wcdbSetMyWxid = null
|
||||
}
|
||||
|
||||
// wcdb_status wcdb_update_message(wcdb_handle handle, const char* session_id, int64_t local_id, int32_t create_time, const char* new_content, char** out_error)
|
||||
try {
|
||||
this.wcdbUpdateMessage = this.lib.func('int32 wcdb_update_message(int64 handle, const char* sessionId, int64 localId, int32 createTime, const char* newContent, _Out_ void** outError)')
|
||||
} catch {
|
||||
this.wcdbUpdateMessage = null
|
||||
}
|
||||
|
||||
// wcdb_status wcdb_delete_message(wcdb_handle handle, const char* session_id, int64_t local_id, char** out_error)
|
||||
try {
|
||||
this.wcdbDeleteMessage = this.lib.func('int32 wcdb_delete_message(int64 handle, const char* sessionId, int64 localId, int32 createTime, const char* dbPathHint, _Out_ void** outError)')
|
||||
} catch {
|
||||
this.wcdbDeleteMessage = null
|
||||
}
|
||||
|
||||
// void wcdb_free_string(char* ptr)
|
||||
this.wcdbFreeString = this.lib.func('void wcdb_free_string(void* ptr)')
|
||||
|
||||
@@ -602,12 +583,7 @@ export class WcdbCore {
|
||||
this.wcdbVerifyUser = null
|
||||
}
|
||||
|
||||
// wcdb_status wcdb_decrypt_sns_image(const char* encrypted_data, int32_t data_len, const char* key, char** out_hex)
|
||||
try {
|
||||
this.wcdbDecryptSnsImage = this.lib.func('int32 wcdb_decrypt_sns_image(const char* data, int32 len, const char* key, _Out_ void** outHex)')
|
||||
} catch {
|
||||
this.wcdbDecryptSnsImage = null
|
||||
}
|
||||
|
||||
|
||||
// 初始化
|
||||
const initResult = this.wcdbInit()
|
||||
@@ -1814,4 +1790,62 @@ export class WcdbCore {
|
||||
return { success: false, error: String(e) }
|
||||
}
|
||||
}
|
||||
/**
|
||||
* 修改消息内容
|
||||
*/
|
||||
async updateMessage(sessionId: string, localId: number, createTime: number, newContent: string): Promise<{ success: boolean; error?: string }> {
|
||||
if (!this.initialized || !this.wcdbUpdateMessage) return { success: false, error: 'WCDB Not Initialized or Method Missing' }
|
||||
if (!this.handle) return { success: false, error: 'Not Connected' }
|
||||
|
||||
return new Promise((resolve) => {
|
||||
try {
|
||||
const outError = [null as any]
|
||||
const result = this.wcdbUpdateMessage(this.handle, sessionId, localId, createTime, newContent, outError)
|
||||
|
||||
if (result !== 0) {
|
||||
let errorMsg = 'Unknown Error'
|
||||
if (outError[0]) {
|
||||
errorMsg = this.decodeJsonPtr(outError[0]) || 'Unknown Error (Decode Failed)'
|
||||
}
|
||||
resolve({ success: false, error: errorMsg })
|
||||
return
|
||||
}
|
||||
|
||||
resolve({ success: true })
|
||||
} catch (e) {
|
||||
resolve({ success: false, error: String(e) })
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除消息
|
||||
*/
|
||||
async deleteMessage(sessionId: string, localId: number, createTime: number, dbPathHint?: string): Promise<{ success: boolean; error?: string }> {
|
||||
if (!this.initialized || !this.wcdbDeleteMessage) return { success: false, error: 'WCDB Not Initialized or Method Missing' }
|
||||
if (!this.handle) return { success: false, error: 'Not Connected' }
|
||||
|
||||
return new Promise((resolve) => {
|
||||
try {
|
||||
const outError = [null as any]
|
||||
const result = this.wcdbDeleteMessage(this.handle, sessionId, localId, createTime || 0, dbPathHint || '', outError)
|
||||
|
||||
if (result !== 0) {
|
||||
let errorMsg = 'Unknown Error'
|
||||
if (outError[0]) {
|
||||
errorMsg = this.decodeJsonPtr(outError[0]) || 'Unknown Error (Decode Failed)'
|
||||
}
|
||||
console.error(`[WcdbCore] deleteMessage fail: code=${result}, error=${errorMsg}`)
|
||||
resolve({ success: false, error: errorMsg })
|
||||
return
|
||||
}
|
||||
|
||||
resolve({ success: true })
|
||||
} catch (e) {
|
||||
console.error(`[WcdbCore] deleteMessage exception:`, e)
|
||||
resolve({ success: false, error: String(e) })
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -432,12 +432,21 @@ export class WcdbService {
|
||||
}
|
||||
|
||||
/**
|
||||
* 解密朋友圈图片
|
||||
* 修改消息内容
|
||||
*/
|
||||
async decryptSnsImage(encryptedData: Buffer, key: string): Promise<Buffer> {
|
||||
return this.callWorker<Buffer>('decryptSnsImage', { encryptedData, key })
|
||||
async updateMessage(sessionId: string, localId: number, createTime: number, newContent: string): Promise<{ success: boolean; error?: string }> {
|
||||
return this.callWorker('updateMessage', { sessionId, localId, createTime, newContent })
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除消息
|
||||
*/
|
||||
async deleteMessage(sessionId: string, localId: number, createTime: number, dbPathHint?: string): Promise<{ success: boolean; error?: string }> {
|
||||
return this.callWorker('deleteMessage', { sessionId, localId, createTime, dbPathHint })
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
export const wcdbService = new WcdbService()
|
||||
|
||||
@@ -150,9 +150,13 @@ if (parentPort) {
|
||||
case 'verifyUser':
|
||||
result = await core.verifyUser(payload.message, payload.hwnd)
|
||||
break
|
||||
case 'decryptSnsImage':
|
||||
result = await core.decryptSnsImage(payload.encryptedData, payload.key)
|
||||
case 'updateMessage':
|
||||
result = await core.updateMessage(payload.sessionId, payload.localId, payload.createTime, payload.newContent)
|
||||
break
|
||||
case 'deleteMessage':
|
||||
result = await core.deleteMessage(payload.sessionId, payload.localId, payload.createTime, payload.dbPathHint)
|
||||
break
|
||||
|
||||
default:
|
||||
result = { success: false, error: `Unknown method: ${type}` }
|
||||
}
|
||||
|
||||
4
package-lock.json
generated
4
package-lock.json
generated
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "weflow",
|
||||
"version": "1.5.4",
|
||||
"version": "2.0.1",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "weflow",
|
||||
"version": "1.5.4",
|
||||
"version": "2.0.1",
|
||||
"hasInstallScript": true,
|
||||
"dependencies": {
|
||||
"better-sqlite3": "^12.5.0",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "weflow",
|
||||
"version": "1.5.4",
|
||||
"version": "2.0.1",
|
||||
"description": "WeFlow",
|
||||
"main": "dist-electron/main.js",
|
||||
"author": "cc",
|
||||
|
||||
Binary file not shown.
@@ -482,11 +482,41 @@
|
||||
margin-top: 16px;
|
||||
}
|
||||
|
||||
.exclude-footer-left {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.exclude-count {
|
||||
font-size: 12px;
|
||||
color: var(--text-tertiary);
|
||||
}
|
||||
|
||||
.btn-text {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
background: none;
|
||||
border: none;
|
||||
cursor: pointer;
|
||||
font-size: 12px;
|
||||
color: var(--text-secondary);
|
||||
padding: 4px 8px;
|
||||
border-radius: 6px;
|
||||
transition: all 0.15s;
|
||||
|
||||
&:hover {
|
||||
color: var(--primary);
|
||||
background: var(--primary-light);
|
||||
}
|
||||
|
||||
&:disabled {
|
||||
opacity: 0.5;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
}
|
||||
|
||||
.exclude-actions {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
|
||||
@@ -146,6 +146,17 @@ function AnalyticsPage() {
|
||||
})
|
||||
}
|
||||
|
||||
const toggleInvertSelection = () => {
|
||||
setDraftExcluded((prev) => {
|
||||
const allUsernames = new Set(excludeCandidates.map(c => normalizeUsername(c.username)))
|
||||
const inverted = new Set<string>()
|
||||
for (const u of allUsernames) {
|
||||
if (!prev.has(u)) inverted.add(u)
|
||||
}
|
||||
return inverted
|
||||
})
|
||||
}
|
||||
|
||||
const handleApplyExcluded = async () => {
|
||||
const payload = Array.from(draftExcluded)
|
||||
setIsExcludeDialogOpen(false)
|
||||
@@ -493,7 +504,12 @@ function AnalyticsPage() {
|
||||
)}
|
||||
</div>
|
||||
<div className="exclude-modal-footer">
|
||||
<div className="exclude-footer-left">
|
||||
<span className="exclude-count">已排除 {draftExcluded.size} 人</span>
|
||||
<button className="btn btn-text" onClick={toggleInvertSelection} disabled={excludeLoading}>
|
||||
反选
|
||||
</button>
|
||||
</div>
|
||||
<div className="exclude-actions">
|
||||
<button className="btn btn-secondary" onClick={() => setIsExcludeDialogOpen(false)}>
|
||||
取消
|
||||
|
||||
@@ -1,8 +1,214 @@
|
||||
.chat-page {
|
||||
position: relative;
|
||||
display: flex;
|
||||
height: 100%;
|
||||
gap: 16px;
|
||||
|
||||
// 批量删除进度遮罩
|
||||
.delete-progress-overlay {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
z-index: 9999;
|
||||
background: rgba(0, 0, 0, 0.4);
|
||||
backdrop-filter: blur(8px);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
animation: fadeIn 0.3s ease;
|
||||
|
||||
.delete-progress-card {
|
||||
width: 400px;
|
||||
padding: 24px;
|
||||
background: var(--card-bg);
|
||||
border: 1px solid var(--border-color);
|
||||
border-radius: 16px;
|
||||
box-shadow: 0 10px 40px rgba(0, 0, 0, 0.3);
|
||||
text-align: center;
|
||||
|
||||
.progress-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
margin-bottom: 20px;
|
||||
|
||||
h3 {
|
||||
margin: 0;
|
||||
font-size: 18px;
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.count {
|
||||
font-variant-numeric: tabular-nums;
|
||||
font-weight: 600;
|
||||
background: var(--bg-tertiary);
|
||||
padding: 2px 8px;
|
||||
border-radius: 4px;
|
||||
color: var(--primary);
|
||||
}
|
||||
}
|
||||
|
||||
.progress-bar-container {
|
||||
height: 10px;
|
||||
background: var(--bg-tertiary);
|
||||
border-radius: 5px;
|
||||
overflow: hidden;
|
||||
margin-bottom: 20px;
|
||||
|
||||
.progress-bar-fill {
|
||||
height: 100%;
|
||||
background: linear-gradient(90deg, var(--primary), var(--primary-light));
|
||||
transition: width 0.3s cubic-bezier(0.4, 0, 0.2, 1);
|
||||
}
|
||||
}
|
||||
|
||||
.progress-footer {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 16px;
|
||||
|
||||
p {
|
||||
font-size: 13px;
|
||||
color: var(--text-tertiary);
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.cancel-delete-btn {
|
||||
padding: 10px;
|
||||
border-radius: 8px;
|
||||
border: 1px solid var(--border-color);
|
||||
background: var(--bg-secondary);
|
||||
color: var(--text-secondary);
|
||||
font-size: 14px;
|
||||
cursor: pointer;
|
||||
transition: all 0.2s;
|
||||
|
||||
&:hover:not(:disabled) {
|
||||
background: var(--danger-light);
|
||||
color: var(--danger);
|
||||
border-color: var(--danger);
|
||||
}
|
||||
|
||||
&:disabled {
|
||||
opacity: 0.6;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 自定义删除确认对话框
|
||||
.delete-confirm-overlay {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
z-index: 10000;
|
||||
background: rgba(0, 0, 0, 0.3);
|
||||
backdrop-filter: blur(4px);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
animation: fadeIn 0.2s ease;
|
||||
|
||||
.delete-confirm-card {
|
||||
width: 360px;
|
||||
padding: 32px 24px 24px;
|
||||
background: var(--card-bg);
|
||||
border: 1px solid var(--border-color);
|
||||
border-radius: 20px;
|
||||
box-shadow: 0 20px 60px rgba(0, 0, 0, 0.4);
|
||||
text-align: center;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
|
||||
.confirm-icon {
|
||||
margin-bottom: 20px;
|
||||
padding: 16px;
|
||||
background: var(--danger-light);
|
||||
border-radius: 50%;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.confirm-content {
|
||||
margin-bottom: 32px;
|
||||
|
||||
h3 {
|
||||
margin: 0 0 12px;
|
||||
font-size: 20px;
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
p {
|
||||
margin: 0;
|
||||
font-size: 14px;
|
||||
color: var(--text-secondary);
|
||||
line-height: 1.6;
|
||||
}
|
||||
}
|
||||
|
||||
.confirm-actions {
|
||||
display: flex;
|
||||
gap: 12px;
|
||||
width: 100%;
|
||||
|
||||
button {
|
||||
flex: 1;
|
||||
padding: 12px;
|
||||
border-radius: 12px;
|
||||
font-size: 14px;
|
||||
font-weight: 500;
|
||||
cursor: pointer;
|
||||
transition: all 0.2s;
|
||||
}
|
||||
|
||||
.btn-secondary {
|
||||
background: var(--bg-secondary);
|
||||
border: 1px solid var(--border-color);
|
||||
color: var(--text-secondary);
|
||||
|
||||
&:hover {
|
||||
background: var(--bg-hover);
|
||||
color: var(--text-primary);
|
||||
}
|
||||
}
|
||||
|
||||
.btn-danger-filled {
|
||||
background: var(--danger);
|
||||
border: none;
|
||||
color: white;
|
||||
|
||||
&:hover {
|
||||
background: #e54d45; // Darker red
|
||||
transform: translateY(-1px);
|
||||
box-shadow: 0 4px 12px rgba(229, 77, 69, 0.3);
|
||||
}
|
||||
|
||||
&:active {
|
||||
transform: translateY(0);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes fadeIn {
|
||||
from {
|
||||
opacity: 0;
|
||||
}
|
||||
|
||||
to {
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
|
||||
// 独立窗口模式 - EchoTrace 特色风格(使用主题变量)
|
||||
&.standalone {
|
||||
height: 100vh;
|
||||
@@ -2511,6 +2717,7 @@
|
||||
|
||||
// 发送消息中的特殊消息类型适配(除了文件和转账)
|
||||
.message-bubble.sent {
|
||||
|
||||
.card-message,
|
||||
.chat-record-message,
|
||||
.miniapp-message {
|
||||
@@ -2616,6 +2823,7 @@
|
||||
&:hover:not(:disabled) {
|
||||
color: var(--primary-color);
|
||||
}
|
||||
|
||||
&.transcribing {
|
||||
color: var(--primary-color);
|
||||
cursor: pointer;
|
||||
@@ -2637,7 +2845,9 @@
|
||||
padding: 1.5rem;
|
||||
border-bottom: 1px solid var(--border-color);
|
||||
|
||||
svg { color: var(--primary-color); }
|
||||
svg {
|
||||
color: var(--primary-color);
|
||||
}
|
||||
|
||||
h3 {
|
||||
margin: 0;
|
||||
@@ -2697,7 +2907,10 @@
|
||||
|
||||
li {
|
||||
border-bottom: 1px solid var(--border-color);
|
||||
&:last-child { border-bottom: none; }
|
||||
|
||||
&:last-child {
|
||||
border-bottom: none;
|
||||
}
|
||||
}
|
||||
|
||||
.batch-date-row {
|
||||
@@ -2708,7 +2921,9 @@
|
||||
cursor: pointer;
|
||||
transition: background 0.15s;
|
||||
|
||||
&:hover { background: var(--bg-hover); }
|
||||
&:hover {
|
||||
background: var(--bg-hover);
|
||||
}
|
||||
|
||||
input[type="checkbox"] {
|
||||
accent-color: var(--primary-color);
|
||||
@@ -2806,13 +3021,185 @@
|
||||
&.btn-secondary {
|
||||
background: var(--bg-tertiary);
|
||||
color: var(--text-primary);
|
||||
&:hover { background: var(--border-color); }
|
||||
|
||||
&:hover {
|
||||
background: var(--border-color);
|
||||
}
|
||||
}
|
||||
|
||||
&.btn-primary, &.batch-transcribe-start-btn {
|
||||
&.btn-primary,
|
||||
&.batch-transcribe-start-btn {
|
||||
background: var(--primary-color);
|
||||
color: white;
|
||||
&:hover { opacity: 0.9; }
|
||||
|
||||
&:hover {
|
||||
opacity: 0.9;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Context Menu
|
||||
.context-menu-overlay {
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
.context-menu {
|
||||
background: var(--card-bg);
|
||||
border: 1px solid var(--border-color);
|
||||
border-radius: 8px;
|
||||
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
|
||||
padding: 4px;
|
||||
min-width: 140px;
|
||||
backdrop-filter: blur(10px);
|
||||
animation: fadeIn 0.1s ease-out;
|
||||
|
||||
.menu-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 8px 12px;
|
||||
cursor: pointer;
|
||||
border-radius: 4px;
|
||||
color: var(--text-primary);
|
||||
font-size: 13px;
|
||||
transition: all 0.2s;
|
||||
|
||||
&:hover {
|
||||
background: var(--bg-hover);
|
||||
}
|
||||
|
||||
&.delete {
|
||||
color: var(--danger);
|
||||
|
||||
&:hover {
|
||||
background: rgba(220, 53, 69, 0.1);
|
||||
}
|
||||
}
|
||||
|
||||
svg {
|
||||
opacity: 0.7;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Modal Overlay
|
||||
.modal-overlay {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
background: rgba(0, 0, 0, 0.6);
|
||||
backdrop-filter: blur(4px);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
z-index: 2000;
|
||||
padding: 20px;
|
||||
}
|
||||
|
||||
// Edit Message Modal
|
||||
.edit-message-modal {
|
||||
width: 500px;
|
||||
max-width: 90vw;
|
||||
max-height: 85vh;
|
||||
background: var(--card-bg);
|
||||
border-radius: 12px;
|
||||
box-shadow: 0 8px 30px rgba(0, 0, 0, 0.2);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
overflow: hidden;
|
||||
|
||||
.modal-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding: 16px 20px;
|
||||
border-bottom: 1px solid var(--border-color);
|
||||
|
||||
h3 {
|
||||
font-size: 16px;
|
||||
font-weight: 600;
|
||||
color: var(--text-primary);
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.close-btn {
|
||||
width: 28px;
|
||||
height: 28px;
|
||||
border: none;
|
||||
background: transparent;
|
||||
border-radius: 6px;
|
||||
cursor: pointer;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
color: var(--text-tertiary);
|
||||
transition: all 0.2s;
|
||||
|
||||
&:hover {
|
||||
background: var(--bg-hover);
|
||||
color: var(--text-primary);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.edit-message-textarea {
|
||||
flex: 1;
|
||||
border: none;
|
||||
padding: 16px 20px;
|
||||
background: var(--bg-secondary);
|
||||
color: var(--text-primary);
|
||||
font-size: 14px;
|
||||
line-height: 1.6;
|
||||
resize: none;
|
||||
outline: none;
|
||||
min-height: 120px;
|
||||
|
||||
&:focus {
|
||||
background: var(--bg-primary);
|
||||
}
|
||||
}
|
||||
|
||||
.modal-actions {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
gap: 12px;
|
||||
padding: 16px 20px;
|
||||
border-top: 1px solid var(--border-color);
|
||||
background: var(--card-bg);
|
||||
|
||||
button {
|
||||
padding: 8px 16px;
|
||||
border-radius: 6px;
|
||||
font-size: 13px;
|
||||
font-weight: 500;
|
||||
cursor: pointer;
|
||||
transition: all 0.2s;
|
||||
}
|
||||
|
||||
.btn-secondary {
|
||||
background: var(--bg-tertiary);
|
||||
border: 1px solid transparent;
|
||||
color: var(--text-secondary);
|
||||
|
||||
&:hover {
|
||||
background: var(--bg-hover);
|
||||
color: var(--text-primary);
|
||||
}
|
||||
}
|
||||
|
||||
.btn-primary {
|
||||
background: var(--primary);
|
||||
border: 1px solid transparent;
|
||||
color: #fff;
|
||||
box-shadow: 0 2px 8px var(--primary-light);
|
||||
|
||||
&:hover {
|
||||
background: var(--primary-hover);
|
||||
box-shadow: 0 4px 12px var(--primary-light);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import React, { useState, useEffect, useRef, useCallback, useMemo } from 'react'
|
||||
import { Search, MessageSquare, AlertCircle, Loader2, RefreshCw, X, ChevronDown, Info, Calendar, Database, Hash, Play, Pause, Image as ImageIcon, Link, Mic, CheckCircle, Copy, Check, Download, BarChart3 } from 'lucide-react'
|
||||
import { Search, MessageSquare, AlertCircle, Loader2, RefreshCw, X, ChevronDown, Info, Calendar, Database, Hash, Play, Pause, Image as ImageIcon, Link, Mic, CheckCircle, Copy, Check, CheckSquare, Download, BarChart3, Edit2, Trash2 } from 'lucide-react'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import { createPortal } from 'react-dom'
|
||||
import { useChatStore } from '../stores/chatStore'
|
||||
@@ -18,6 +18,102 @@ const SYSTEM_MESSAGE_TYPES = [
|
||||
266287972401, // 拍一拍
|
||||
]
|
||||
|
||||
interface XmlField {
|
||||
key: string;
|
||||
value: string;
|
||||
type: 'attr' | 'node';
|
||||
tagName?: string;
|
||||
path: string;
|
||||
}
|
||||
|
||||
// 尝试解析 XML 为可编辑字段
|
||||
function parseXmlToFields(xml: string): XmlField[] {
|
||||
const fields: XmlField[] = []
|
||||
if (!xml || !xml.includes('<')) return []
|
||||
try {
|
||||
const parser = new DOMParser()
|
||||
// 包装一下确保是单一根节点
|
||||
const wrappedXml = xml.trim().startsWith('<?xml') ? xml : `<root>${xml}</root>`
|
||||
const doc = parser.parseFromString(wrappedXml, 'text/xml')
|
||||
const errorNode = doc.querySelector('parsererror')
|
||||
if (errorNode) return []
|
||||
|
||||
const walk = (node: Node, path: string = '') => {
|
||||
if (node.nodeType === Node.ELEMENT_NODE) {
|
||||
const element = node as Element
|
||||
if (element.tagName === 'root') {
|
||||
node.childNodes.forEach((child, index) => walk(child, path))
|
||||
return
|
||||
}
|
||||
|
||||
const currentPath = path ? `${path} > ${element.tagName}` : element.tagName
|
||||
|
||||
for (let i = 0; i < element.attributes.length; i++) {
|
||||
const attr = element.attributes[i]
|
||||
fields.push({
|
||||
key: attr.name,
|
||||
value: attr.value,
|
||||
type: 'attr',
|
||||
tagName: element.tagName,
|
||||
path: `${currentPath}[@${attr.name}]`
|
||||
})
|
||||
}
|
||||
|
||||
if (element.childNodes.length === 1 && element.childNodes[0].nodeType === Node.TEXT_NODE) {
|
||||
const text = element.textContent?.trim() || ''
|
||||
if (text) {
|
||||
fields.push({
|
||||
key: element.tagName,
|
||||
value: text,
|
||||
type: 'node',
|
||||
path: currentPath
|
||||
})
|
||||
}
|
||||
} else {
|
||||
node.childNodes.forEach((child, index) => walk(child, `${currentPath}[${index}]`))
|
||||
}
|
||||
}
|
||||
}
|
||||
doc.childNodes.forEach((node, index) => walk(node, ''))
|
||||
} catch (e) {
|
||||
console.warn('[XML Parse] Failed:', e)
|
||||
}
|
||||
return fields
|
||||
}
|
||||
|
||||
// 将编辑后的字段同步回 XML
|
||||
function updateXmlWithFields(xml: string, fields: XmlField[]): string {
|
||||
try {
|
||||
const parser = new DOMParser()
|
||||
const wrappedXml = xml.trim().startsWith('<?xml') ? xml : `<root>${xml}</root>`
|
||||
const doc = parser.parseFromString(wrappedXml, 'text/xml')
|
||||
const errorNode = doc.querySelector('parsererror')
|
||||
if (errorNode) return xml
|
||||
|
||||
fields.forEach(f => {
|
||||
if (f.type === 'attr') {
|
||||
const elements = doc.getElementsByTagName(f.tagName!)
|
||||
if (elements.length > 0) {
|
||||
elements[0].setAttribute(f.key, f.value)
|
||||
}
|
||||
} else {
|
||||
const elements = doc.getElementsByTagName(f.key)
|
||||
if (elements.length > 0 && (elements[0].childNodes.length <= 1)) {
|
||||
elements[0].textContent = f.value
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
let result = new XMLSerializer().serializeToString(doc)
|
||||
if (!xml.trim().startsWith('<?xml')) {
|
||||
result = result.replace('<root>', '').replace('</root>', '').replace('<root/>', '')
|
||||
}
|
||||
return result
|
||||
} catch (e) {
|
||||
return xml
|
||||
}
|
||||
}
|
||||
|
||||
// 判断是否为系统消息
|
||||
function isSystemMessage(localType: number): boolean {
|
||||
return SYSTEM_MESSAGE_TYPES.includes(localType)
|
||||
@@ -32,6 +128,12 @@ function formatFileSize(bytes: number): string {
|
||||
return Math.round(bytes / Math.pow(k, i) * 100) / 100 + ' ' + sizes[i]
|
||||
}
|
||||
|
||||
// 清理消息内容的辅助函数
|
||||
function cleanMessageContent(content: string): string {
|
||||
if (!content) return ''
|
||||
return content.trim()
|
||||
}
|
||||
|
||||
interface ChatPageProps {
|
||||
// 保留接口以备将来扩展
|
||||
}
|
||||
@@ -182,6 +284,18 @@ function ChatPage(_props: ChatPageProps) {
|
||||
const [showVoiceTranscribeDialog, setShowVoiceTranscribeDialog] = useState(false)
|
||||
const [pendingVoiceTranscriptRequest, setPendingVoiceTranscriptRequest] = useState<{ sessionId: string; messageId: string } | null>(null)
|
||||
|
||||
// 消息右键菜单
|
||||
const [contextMenu, setContextMenu] = useState<{ x: number, y: number, message: Message } | null>(null)
|
||||
const [editingMessage, setEditingMessage] = useState<{ message: Message, content: string } | null>(null)
|
||||
|
||||
// 多选模式
|
||||
const [isSelectionMode, setIsSelectionMode] = useState(false)
|
||||
const [selectedMessages, setSelectedMessages] = useState<Set<number>>(new Set())
|
||||
|
||||
// 编辑消息额外状态
|
||||
const [editMode, setEditMode] = useState<'raw' | 'fields'>('raw')
|
||||
const [tempFields, setTempFields] = useState<XmlField[]>([])
|
||||
|
||||
// 批量语音转文字相关状态(进度/结果 由全局 store 管理)
|
||||
const { isBatchTranscribing, progress: batchTranscribeProgress, showToast: showBatchProgress, startTranscribe, updateProgress, finishTranscribe, setShowToast: setShowBatchProgress } = useBatchTranscribeStore()
|
||||
const [showBatchConfirm, setShowBatchConfirm] = useState(false)
|
||||
@@ -190,6 +304,19 @@ function ChatPage(_props: ChatPageProps) {
|
||||
const [batchVoiceDates, setBatchVoiceDates] = useState<string[]>([])
|
||||
const [batchSelectedDates, setBatchSelectedDates] = useState<Set<string>>(new Set())
|
||||
|
||||
// 批量删除相关状态
|
||||
const [isDeleting, setIsDeleting] = useState(false)
|
||||
const [deleteProgress, setDeleteProgress] = useState({ current: 0, total: 0 })
|
||||
const [cancelDeleteRequested, setCancelDeleteRequested] = useState(false)
|
||||
|
||||
// 自定义删除确认对话框
|
||||
const [deleteConfirm, setDeleteConfirm] = useState<{
|
||||
show: boolean;
|
||||
mode: 'single' | 'batch';
|
||||
message?: Message;
|
||||
count?: number;
|
||||
}>({ show: false, mode: 'single' })
|
||||
|
||||
// 联系人信息加载控制
|
||||
const isEnrichingRef = useRef(false)
|
||||
const enrichCancelledRef = useRef(false)
|
||||
@@ -1394,13 +1521,302 @@ function ChatPage(_props: ChatPageProps) {
|
||||
const selectAllBatchDates = useCallback(() => setBatchSelectedDates(new Set(batchVoiceDates)), [batchVoiceDates])
|
||||
const clearAllBatchDates = useCallback(() => setBatchSelectedDates(new Set()), [])
|
||||
|
||||
const lastSelectedIdRef = useRef<number | null>(null)
|
||||
|
||||
const handleToggleSelection = useCallback((localId: number, isShiftKey: boolean = false) => {
|
||||
setSelectedMessages(prev => {
|
||||
const next = new Set(prev)
|
||||
|
||||
// Range selection with Shift key
|
||||
if (isShiftKey && lastSelectedIdRef.current !== null && lastSelectedIdRef.current !== localId) {
|
||||
const currentMsgs = useChatStore.getState().messages
|
||||
const idx1 = currentMsgs.findIndex(m => m.localId === lastSelectedIdRef.current)
|
||||
const idx2 = currentMsgs.findIndex(m => m.localId === localId)
|
||||
|
||||
if (idx1 !== -1 && idx2 !== -1) {
|
||||
const start = Math.min(idx1, idx2)
|
||||
const end = Math.max(idx1, idx2)
|
||||
for (let i = start; i <= end; i++) {
|
||||
next.add(currentMsgs[i].localId)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Normal toggle
|
||||
if (next.has(localId)) {
|
||||
next.delete(localId)
|
||||
lastSelectedIdRef.current = null // Reset last selection on uncheck? Or keep? Usually keep last interaction.
|
||||
} else {
|
||||
next.add(localId)
|
||||
lastSelectedIdRef.current = localId
|
||||
}
|
||||
}
|
||||
return next
|
||||
})
|
||||
}, [])
|
||||
|
||||
const formatBatchDateLabel = useCallback((dateStr: string) => {
|
||||
const [y, m, d] = dateStr.split('-').map(Number)
|
||||
return `${y}年${m}月${d}日`
|
||||
}, [])
|
||||
|
||||
// 消息右键菜单处理
|
||||
const handleContextMenu = useCallback((e: React.MouseEvent, message: Message) => {
|
||||
e.preventDefault()
|
||||
setContextMenu({
|
||||
x: e.clientX,
|
||||
y: e.clientY,
|
||||
message
|
||||
})
|
||||
}, [])
|
||||
|
||||
// 关闭右键菜单
|
||||
useEffect(() => {
|
||||
const handleClick = () => {
|
||||
setContextMenu(null)
|
||||
}
|
||||
window.addEventListener('click', handleClick)
|
||||
return () => {
|
||||
window.removeEventListener('click', handleClick)
|
||||
}
|
||||
}, [])
|
||||
|
||||
// 删除消息 - 触发确认弹窗
|
||||
const handleDelete = useCallback((target: { message: Message } | null = null) => {
|
||||
const msg = target?.message || contextMenu?.message
|
||||
if (!currentSessionId || !msg) return
|
||||
|
||||
setDeleteConfirm({
|
||||
show: true,
|
||||
mode: 'single',
|
||||
message: msg
|
||||
})
|
||||
setContextMenu(null)
|
||||
}, [contextMenu, currentSessionId])
|
||||
|
||||
// 执行单条删除动作
|
||||
const performSingleDelete = async (msg: Message) => {
|
||||
try {
|
||||
const dbPathHint = (msg as any)._db_path
|
||||
const result = await (window as any).electronAPI.chat.deleteMessage(currentSessionId, msg.localId, msg.createTime, dbPathHint)
|
||||
if (result.success) {
|
||||
const currentMessages = useChatStore.getState().messages
|
||||
const newMessages = currentMessages.filter(m => m.localId !== msg.localId)
|
||||
useChatStore.getState().setMessages(newMessages)
|
||||
} else {
|
||||
alert('删除失败: ' + (result.error || '原因未知'))
|
||||
}
|
||||
} catch (e) {
|
||||
console.error(e)
|
||||
alert('删除异常: ' + String(e))
|
||||
}
|
||||
}
|
||||
|
||||
// 修改消息
|
||||
const handleEditMessage = useCallback(() => {
|
||||
if (contextMenu) {
|
||||
// 允许编辑所有类型的消息
|
||||
// 如果是文本消息(1),使用 parsedContent
|
||||
// 如果是其他类型(如系统消息 10000),使用 rawContent 或 content 作为 XML 源码编辑
|
||||
const isText = contextMenu.message.localType === 1
|
||||
const rawXml = contextMenu.message.content || (contextMenu.message as any).rawContent || contextMenu.message.parsedContent || ''
|
||||
|
||||
const contentToEdit = isText
|
||||
? cleanMessageContent(contextMenu.message.parsedContent)
|
||||
: rawXml
|
||||
|
||||
if (!isText) {
|
||||
const fields = parseXmlToFields(rawXml)
|
||||
setTempFields(fields)
|
||||
setEditMode(fields.length > 0 ? 'fields' : 'raw')
|
||||
} else {
|
||||
setEditMode('raw')
|
||||
setTempFields([])
|
||||
}
|
||||
|
||||
setEditingMessage({
|
||||
message: contextMenu.message,
|
||||
content: contentToEdit
|
||||
})
|
||||
setContextMenu(null)
|
||||
}
|
||||
}, [contextMenu])
|
||||
|
||||
// 确认修改消息
|
||||
const handleSaveEdit = useCallback(async () => {
|
||||
if (editingMessage && currentSessionId) {
|
||||
let finalContent = editingMessage.content
|
||||
|
||||
// 如果是字段编辑模式,先同步回 XML
|
||||
if (editMode === 'fields' && tempFields.length > 0) {
|
||||
finalContent = updateXmlWithFields(editingMessage.content, tempFields)
|
||||
}
|
||||
|
||||
if (!finalContent.trim()) {
|
||||
handleDelete({ message: editingMessage.message })
|
||||
setEditingMessage(null)
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await (window as any).electronAPI.chat.updateMessage(currentSessionId, editingMessage.message.localId, editingMessage.message.createTime, finalContent)
|
||||
if (result.success) {
|
||||
const currentMessages = useChatStore.getState().messages
|
||||
const newMessages = currentMessages.map(m => {
|
||||
if (m.localId === editingMessage.message.localId) {
|
||||
return { ...m, parsedContent: finalContent, content: finalContent, rawContent: finalContent }
|
||||
}
|
||||
return m
|
||||
})
|
||||
useChatStore.getState().setMessages(newMessages)
|
||||
setEditingMessage(null)
|
||||
} else {
|
||||
alert('修改失败: ' + result.error)
|
||||
}
|
||||
} catch (e) {
|
||||
alert('修改异常: ' + String(e))
|
||||
}
|
||||
}
|
||||
}, [editingMessage, currentSessionId, editMode, tempFields, handleDelete])
|
||||
|
||||
// 用于在异步循环中获取最新的取消状态
|
||||
const cancelDeleteRef = useRef(false)
|
||||
|
||||
const handleBatchDelete = () => {
|
||||
if (selectedMessages.size === 0) {
|
||||
alert('请先选择要删除的消息')
|
||||
return
|
||||
}
|
||||
if (!currentSessionId) return
|
||||
|
||||
setDeleteConfirm({
|
||||
show: true,
|
||||
mode: 'batch',
|
||||
count: selectedMessages.size
|
||||
})
|
||||
}
|
||||
|
||||
const performBatchDelete = async () => {
|
||||
setIsDeleting(true)
|
||||
setDeleteProgress({ current: 0, total: selectedMessages.size })
|
||||
setCancelDeleteRequested(false)
|
||||
cancelDeleteRef.current = false
|
||||
|
||||
try {
|
||||
const currentMessages = useChatStore.getState().messages
|
||||
const selectedIds = Array.from(selectedMessages)
|
||||
const deletedIds = new Set<number>()
|
||||
|
||||
for (let i = 0; i < selectedIds.length; i++) {
|
||||
if (cancelDeleteRef.current) break
|
||||
|
||||
const id = selectedIds[i]
|
||||
const msgObj = currentMessages.find(m => m.localId === id)
|
||||
const dbPathHint = (msgObj as any)?._db_path
|
||||
const createTime = msgObj?.createTime || 0
|
||||
|
||||
try {
|
||||
const result = await (window as any).electronAPI.chat.deleteMessage(currentSessionId, id, createTime, dbPathHint)
|
||||
if (result.success) {
|
||||
deletedIds.add(id)
|
||||
}
|
||||
} catch (err) {
|
||||
console.error(`删除消息 ${id} 失败:`, err)
|
||||
}
|
||||
|
||||
setDeleteProgress({ current: i + 1, total: selectedIds.length })
|
||||
}
|
||||
|
||||
const finalMessages = useChatStore.getState().messages.filter(m => !deletedIds.has(m.localId))
|
||||
useChatStore.getState().setMessages(finalMessages)
|
||||
|
||||
setIsSelectionMode(false)
|
||||
setSelectedMessages(new Set())
|
||||
|
||||
if (cancelDeleteRef.current) {
|
||||
alert(`操作已中止。已删除 ${deletedIds.size} 条,剩余记录保留。`)
|
||||
}
|
||||
} catch (e) {
|
||||
alert('批量删除出现错误: ' + String(e))
|
||||
console.error(e)
|
||||
} finally {
|
||||
setIsDeleting(false)
|
||||
setCancelDeleteRequested(false)
|
||||
cancelDeleteRef.current = false
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={`chat-page ${isResizing ? 'resizing' : ''}`}>
|
||||
{/* 自定义删除确认对话框 */}
|
||||
{deleteConfirm.show && (
|
||||
<div className="delete-confirm-overlay">
|
||||
<div className="delete-confirm-card">
|
||||
<div className="confirm-icon">
|
||||
<Trash2 size={32} color="var(--danger)" />
|
||||
</div>
|
||||
<div className="confirm-content">
|
||||
<h3>确认删除</h3>
|
||||
<p>
|
||||
{deleteConfirm.mode === 'single'
|
||||
? '确定要删除这条消息吗?此操作不可恢复。'
|
||||
: `确定要删除选中的 ${deleteConfirm.count} 条消息吗?`}
|
||||
</p>
|
||||
</div>
|
||||
<div className="confirm-actions">
|
||||
<button
|
||||
className="btn-secondary"
|
||||
onClick={() => setDeleteConfirm({ ...deleteConfirm, show: false })}
|
||||
>
|
||||
取消
|
||||
</button>
|
||||
<button
|
||||
className="btn-danger-filled"
|
||||
onClick={() => {
|
||||
setDeleteConfirm({ ...deleteConfirm, show: false });
|
||||
if (deleteConfirm.mode === 'single' && deleteConfirm.message) {
|
||||
performSingleDelete(deleteConfirm.message);
|
||||
} else if (deleteConfirm.mode === 'batch') {
|
||||
performBatchDelete();
|
||||
}
|
||||
}}
|
||||
>
|
||||
确定删除
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 批量删除进度遮罩 */}
|
||||
{isDeleting && (
|
||||
<div className="delete-progress-overlay">
|
||||
<div className="delete-progress-card">
|
||||
<div className="progress-header">
|
||||
<h3>正在彻底删除消息...</h3>
|
||||
<span className="count">{deleteProgress.current} / {deleteProgress.total}</span>
|
||||
</div>
|
||||
<div className="progress-bar-container">
|
||||
<div
|
||||
className="progress-bar-fill"
|
||||
style={{ width: `${(deleteProgress.current / deleteProgress.total) * 100}%` }}
|
||||
/>
|
||||
</div>
|
||||
<div className="progress-footer">
|
||||
<p>请勿关闭应用或切换会话,确保所有副本都被清理。</p>
|
||||
<button
|
||||
className="cancel-delete-btn"
|
||||
onClick={() => {
|
||||
setCancelDeleteRequested(true)
|
||||
cancelDeleteRef.current = true
|
||||
}}
|
||||
disabled={cancelDeleteRequested}
|
||||
>
|
||||
{cancelDeleteRequested ? '正在停止...' : '中止删除'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{/* 左侧会话列表 */}
|
||||
<div
|
||||
className="session-sidebar"
|
||||
@@ -1659,6 +2075,10 @@ function ChatPage(_props: ChatPageProps) {
|
||||
myAvatarUrl={myAvatarUrl}
|
||||
isGroupChat={isGroupChat(currentSession.username)}
|
||||
onRequireModelDownload={handleRequireModelDownload}
|
||||
onContextMenu={handleContextMenu}
|
||||
isSelectionMode={isSelectionMode}
|
||||
isSelected={selectedMessages.has(msg.localId)}
|
||||
onToggleSelection={handleToggleSelection}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
@@ -1897,6 +2317,187 @@ function ChatPage(_props: ChatPageProps) {
|
||||
</div>,
|
||||
document.body
|
||||
)}
|
||||
{/* 消息右键菜单 */}
|
||||
{contextMenu && createPortal(
|
||||
<>
|
||||
<div className="context-menu-overlay" onClick={() => setContextMenu(null)}
|
||||
style={{ position: 'fixed', top: 0, left: 0, right: 0, bottom: 0, zIndex: 9998 }} />
|
||||
<div
|
||||
className="context-menu"
|
||||
style={{
|
||||
position: 'fixed',
|
||||
top: contextMenu.y,
|
||||
left: contextMenu.x,
|
||||
zIndex: 9999
|
||||
}}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<div className="menu-item" onClick={handleEditMessage}>
|
||||
<Edit2 size={16} />
|
||||
<span>{contextMenu.message.localType === 1 ? '修改消息' : '编辑源码'}</span>
|
||||
</div>
|
||||
<div className="menu-item" onClick={() => {
|
||||
setIsSelectionMode(true)
|
||||
setSelectedMessages(new Set([contextMenu.message.localId]))
|
||||
setContextMenu(null)
|
||||
}}>
|
||||
<CheckSquare size={16} />
|
||||
<span>多选</span>
|
||||
</div>
|
||||
<div className="menu-item delete" onClick={(e) => { e.stopPropagation(); handleDelete() }}>
|
||||
<Trash2 size={16} />
|
||||
<span>删除消息</span>
|
||||
</div>
|
||||
</div>
|
||||
</>,
|
||||
document.body
|
||||
)}
|
||||
|
||||
{/* 修改消息弹窗 */}
|
||||
{editingMessage && createPortal(
|
||||
<div className="modal-overlay">
|
||||
<div className="modal-content edit-message-modal">
|
||||
<div className="modal-header">
|
||||
<h3 style={{ margin: 0 }}>{editingMessage.message.localType === 1 ? '修改消息' : '编辑消息'}</h3>
|
||||
<button className="close-btn" onClick={() => setEditingMessage(null)}>
|
||||
<X size={16} />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div style={{ flex: 1, overflowY: 'auto', display: 'flex', flexDirection: 'column' }}>
|
||||
{editMode === 'raw' ? (
|
||||
<textarea
|
||||
className="edit-message-textarea"
|
||||
style={{ fontFamily: 'inherit', width: '100%', boxSizing: 'border-box' }}
|
||||
value={editingMessage.content}
|
||||
onChange={(e) => setEditingMessage({ ...editingMessage, content: e.target.value })}
|
||||
rows={editingMessage.message.localType === 1 ? 8 : 15}
|
||||
/>
|
||||
) : (
|
||||
<div style={{ padding: '16px 20px', display: 'flex', flexDirection: 'column', gap: '14px' }}>
|
||||
{tempFields.map((field, idx) => (
|
||||
<div key={idx} style={{ display: 'flex', flexDirection: 'column', gap: '6px' }}>
|
||||
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
|
||||
<span style={{ fontSize: '12px', color: 'var(--text-secondary)', fontWeight: 500 }}>
|
||||
{field.tagName ? field.tagName : '节点'}: <span style={{ color: 'var(--primary)' }}>{field.key}</span>
|
||||
</span>
|
||||
<span style={{ fontSize: '10px', color: 'var(--text-tertiary)', opacity: 0.6 }}>
|
||||
{field.type === 'attr' ? '属性' : '文本内容'}
|
||||
</span>
|
||||
</div>
|
||||
<input
|
||||
type="text"
|
||||
value={field.value}
|
||||
onChange={(e) => {
|
||||
const newFields = [...tempFields]
|
||||
newFields[idx].value = e.target.value
|
||||
setTempFields(newFields)
|
||||
}}
|
||||
style={{
|
||||
background: 'var(--bg-tertiary)',
|
||||
border: '1px solid var(--border-color)',
|
||||
borderRadius: '6px',
|
||||
padding: '10px 12px',
|
||||
color: 'var(--text-primary)',
|
||||
fontSize: '13px',
|
||||
outline: 'none',
|
||||
width: '100%',
|
||||
boxSizing: 'border-box'
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="modal-actions" style={{ justifyContent: 'space-between' }}>
|
||||
<div>
|
||||
{editingMessage.message.localType !== 1 && tempFields.length > 0 && (
|
||||
<button
|
||||
onClick={() => setEditMode(editMode === 'raw' ? 'fields' : 'raw')}
|
||||
style={{
|
||||
padding: '6px 12px',
|
||||
fontSize: '12px',
|
||||
borderRadius: '6px',
|
||||
border: '1px solid var(--border-color)',
|
||||
background: editMode === 'fields' ? 'var(--primary)' : 'transparent',
|
||||
color: editMode === 'fields' ? '#fff' : 'var(--text-secondary)',
|
||||
cursor: 'pointer',
|
||||
transition: 'all 0.2s',
|
||||
}}
|
||||
>
|
||||
{editMode === 'raw' ? '可视化编辑' : '源码编辑'}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
<div style={{ display: 'flex', gap: '12px' }}>
|
||||
<button className="btn-secondary" onClick={() => setEditingMessage(null)}>取消</button>
|
||||
<button className="btn-primary" onClick={handleSaveEdit}>保存</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>,
|
||||
document.body
|
||||
)}
|
||||
|
||||
{/* 底部多选操作栏 */}
|
||||
{isSelectionMode && (
|
||||
<div style={{
|
||||
position: 'absolute',
|
||||
bottom: 24,
|
||||
left: '50%',
|
||||
transform: 'translateX(-50%)',
|
||||
backgroundColor: 'var(--bg-secondary)', // Use system background
|
||||
color: 'var(--text-primary)',
|
||||
boxShadow: '0 8px 24px rgba(0,0,0,0.2)',
|
||||
borderRadius: '12px',
|
||||
padding: '12px 24px',
|
||||
display: 'flex',
|
||||
gap: '20px',
|
||||
zIndex: 1000,
|
||||
alignItems: 'center',
|
||||
border: '1px solid var(--border-color)', // Subtle border
|
||||
backdropFilter: 'blur(10px)'
|
||||
}}>
|
||||
<span style={{ fontSize: '14px', fontWeight: 500 }}>已选 {selectedMessages.size} 条</span>
|
||||
<div style={{ width: '1px', height: '16px', background: 'var(--border-color)' }}></div>
|
||||
<button
|
||||
className="btn-danger"
|
||||
onClick={handleBatchDelete}
|
||||
style={{
|
||||
padding: '6px 16px',
|
||||
borderRadius: '6px',
|
||||
border: 'none',
|
||||
backgroundColor: '#fa5151',
|
||||
color: 'white',
|
||||
cursor: 'pointer',
|
||||
fontSize: '13px',
|
||||
fontWeight: 500
|
||||
}}
|
||||
>
|
||||
删除
|
||||
</button>
|
||||
<button
|
||||
className="btn-secondary"
|
||||
onClick={() => {
|
||||
setIsSelectionMode(false)
|
||||
setSelectedMessages(new Set())
|
||||
}}
|
||||
style={{
|
||||
padding: '6px 16px',
|
||||
borderRadius: '6px',
|
||||
border: '1px solid var(--border-color)',
|
||||
backgroundColor: 'transparent',
|
||||
color: 'var(--text-primary)',
|
||||
cursor: 'pointer',
|
||||
fontSize: '13px'
|
||||
}}
|
||||
>
|
||||
取消
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1932,13 +2533,28 @@ const senderAvatarCache = new Map<string, { avatarUrl?: string; displayName?: st
|
||||
const senderAvatarLoading = new Map<string, Promise<{ avatarUrl?: string; displayName?: string } | null>>()
|
||||
|
||||
// 消息气泡组件
|
||||
function MessageBubble({ message, session, showTime, myAvatarUrl, isGroupChat, onRequireModelDownload }: {
|
||||
function MessageBubble({
|
||||
message,
|
||||
session,
|
||||
showTime,
|
||||
myAvatarUrl,
|
||||
isGroupChat,
|
||||
onRequireModelDownload,
|
||||
onContextMenu,
|
||||
isSelectionMode,
|
||||
isSelected,
|
||||
onToggleSelection
|
||||
}: {
|
||||
message: Message;
|
||||
session: ChatSession;
|
||||
showTime?: boolean;
|
||||
myAvatarUrl?: string;
|
||||
isGroupChat?: boolean;
|
||||
onRequireModelDownload?: (sessionId: string, messageId: string) => void;
|
||||
onContextMenu?: (e: React.MouseEvent, message: Message) => void;
|
||||
isSelectionMode?: boolean;
|
||||
isSelected?: boolean;
|
||||
onToggleSelection?: (localId: number, isShiftKey?: boolean) => void;
|
||||
}) {
|
||||
const isSystem = isSystemMessage(message.localType)
|
||||
const isEmoji = message.localType === 47
|
||||
@@ -1953,6 +2569,8 @@ function MessageBubble({ message, session, showTime, myAvatarUrl, isGroupChat, o
|
||||
const [senderName, setSenderName] = useState<string | undefined>(undefined)
|
||||
const [emojiError, setEmojiError] = useState(false)
|
||||
const [emojiLoading, setEmojiLoading] = useState(false)
|
||||
|
||||
// State variables...
|
||||
const [imageError, setImageError] = useState(false)
|
||||
const [imageLoading, setImageLoading] = useState(false)
|
||||
const [imageHasUpdate, setImageHasUpdate] = useState(false)
|
||||
@@ -2643,9 +3261,39 @@ function MessageBubble({ message, session, showTime, myAvatarUrl, isGroupChat, o
|
||||
void requestVoiceTranscript()
|
||||
}, [autoTranscribeEnabled, isVoice, voiceDataUrl, voiceTranscript, voiceTranscriptError, voiceTranscriptLoading, requestVoiceTranscript])
|
||||
|
||||
// Selection mode handling removed from here to allow normal rendering
|
||||
// We will wrap the output instead
|
||||
|
||||
// Regular rendering logic...
|
||||
if (isSystem) {
|
||||
return (
|
||||
<div className="message-bubble system">
|
||||
<div
|
||||
className={`message-bubble system ${isSelectionMode ? 'selectable' : ''}`}
|
||||
onContextMenu={(e) => onContextMenu?.(e, message)}
|
||||
style={{ cursor: isSelectionMode ? 'pointer' : 'default', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: '8px' }}
|
||||
onClick={(e) => {
|
||||
if (isSelectionMode) {
|
||||
e.stopPropagation()
|
||||
onToggleSelection?.(message.localId, e.shiftKey)
|
||||
}
|
||||
}}
|
||||
>
|
||||
{isSelectionMode && (
|
||||
<div className={`checkbox ${isSelected ? 'checked' : ''}`} style={{
|
||||
width: '20px',
|
||||
height: '20px',
|
||||
borderRadius: '4px',
|
||||
border: isSelected ? 'none' : '2px solid rgba(128,128,128,0.5)',
|
||||
backgroundColor: isSelected ? 'var(--primary)' : 'transparent',
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
color: 'white',
|
||||
flexShrink: 0
|
||||
}}>
|
||||
{isSelected && <Check size={14} strokeWidth={3} />}
|
||||
</div>
|
||||
)}
|
||||
<div className="bubble-content">{message.parsedContent}</div>
|
||||
</div>
|
||||
)
|
||||
@@ -3344,16 +3992,50 @@ function MessageBubble({ message, session, showTime, myAvatarUrl, isGroupChat, o
|
||||
<span>{formatTime(message.createTime)}</span>
|
||||
</div>
|
||||
)}
|
||||
<div className={`message-bubble ${bubbleClass} ${isEmoji && message.emojiCdnUrl && !emojiError ? 'emoji' : ''} ${isImage ? 'image' : ''} ${isVoice ? 'voice' : ''}`}>
|
||||
<div
|
||||
className={`message-wrapper-with-selection ${isSelectionMode ? 'selectable' : ''}`}
|
||||
style={{
|
||||
display: 'flex',
|
||||
alignItems: 'flex-start',
|
||||
width: '100%',
|
||||
justifyContent: isSent ? 'flex-end' : 'flex-start',
|
||||
cursor: isSelectionMode ? 'pointer' : 'default'
|
||||
}}
|
||||
onClick={(e) => {
|
||||
if (isSelectionMode) {
|
||||
e.stopPropagation()
|
||||
onToggleSelection?.(message.localId, e.shiftKey)
|
||||
}
|
||||
}}
|
||||
>
|
||||
{isSelectionMode && !isSent && (
|
||||
<div className={`checkbox ${isSelected ? 'checked' : ''}`} style={{
|
||||
width: '20px',
|
||||
height: '20px',
|
||||
borderRadius: '4px',
|
||||
border: isSelected ? 'none' : '2px solid rgba(128,128,128,0.5)',
|
||||
backgroundColor: isSelected ? 'var(--primary)' : 'transparent',
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
color: 'white',
|
||||
marginRight: '12px',
|
||||
marginTop: '10px', // Align with avatar top
|
||||
flexShrink: 0
|
||||
}}>
|
||||
{isSelected && <Check size={14} strokeWidth={3} />}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className={`message-bubble ${bubbleClass} ${isEmoji && message.emojiCdnUrl && !emojiError ? 'emoji' : ''} ${isImage ? 'image' : ''} ${isVoice ? 'voice' : ''}`}
|
||||
onContextMenu={(e) => onContextMenu?.(e, message)}
|
||||
>
|
||||
<div className="bubble-avatar">
|
||||
<Avatar
|
||||
src={avatarUrl}
|
||||
name={!isSent ? (isGroupChat ? (senderName || message.senderUsername || '?') : (session.displayName || session.username)) : '我'}
|
||||
size={36}
|
||||
className="bubble-avatar"
|
||||
// If it's sent by me (isSent), we might not want 'group' class even if it's a group chat.
|
||||
// But 'group' class mainly handles default avatar icon.
|
||||
// Let's rely on standard Avatar behavior.
|
||||
/>
|
||||
</div>
|
||||
<div className="bubble-body">
|
||||
@@ -3366,6 +4048,26 @@ function MessageBubble({ message, session, showTime, myAvatarUrl, isGroupChat, o
|
||||
{renderContent()}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{isSelectionMode && isSent && (
|
||||
<div className={`checkbox ${isSelected ? 'checked' : ''}`} style={{
|
||||
width: '20px',
|
||||
height: '20px',
|
||||
borderRadius: '4px',
|
||||
border: isSelected ? 'none' : '2px solid rgba(128,128,128,0.5)',
|
||||
backgroundColor: isSelected ? 'var(--primary)' : 'transparent',
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
color: 'white',
|
||||
marginLeft: '12px',
|
||||
marginTop: '10px',
|
||||
flexShrink: 0
|
||||
}}>
|
||||
{isSelected && <Check size={14} strokeWidth={3} />}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -74,7 +74,7 @@ function SettingsPage() {
|
||||
const exportExcelColumnsDropdownRef = useRef<HTMLDivElement>(null)
|
||||
const exportConcurrencyDropdownRef = useRef<HTMLDivElement>(null)
|
||||
const [cachePath, setCachePath] = useState('')
|
||||
const [weixinDllPath, setWeixinDllPath] = useState('')
|
||||
|
||||
const [logEnabled, setLogEnabled] = useState(false)
|
||||
const [whisperModelName, setWhisperModelName] = useState('base')
|
||||
const [whisperModelDir, setWhisperModelDir] = useState('')
|
||||
@@ -250,7 +250,7 @@ function SettingsPage() {
|
||||
const savedPath = await configService.getDbPath()
|
||||
const savedWxid = await configService.getMyWxid()
|
||||
const savedCachePath = await configService.getCachePath()
|
||||
const savedWeixinDllPath = await configService.getWeixinDllPath()
|
||||
|
||||
const savedExportPath = await configService.getExportPath()
|
||||
const savedLogEnabled = await configService.getLogEnabled()
|
||||
const savedImageXorKey = await configService.getImageXorKey()
|
||||
@@ -279,7 +279,7 @@ function SettingsPage() {
|
||||
if (savedPath) setDbPath(savedPath)
|
||||
if (savedWxid) setWxid(savedWxid)
|
||||
if (savedCachePath) setCachePath(savedCachePath)
|
||||
if (savedWeixinDllPath) setWeixinDllPath(savedWeixinDllPath)
|
||||
|
||||
|
||||
const wxidConfig = savedWxid ? await configService.getWxidConfig(savedWxid) : null
|
||||
const decryptKeyToUse = wxidConfig?.decryptKey ?? savedKey ?? ''
|
||||
@@ -616,29 +616,7 @@ function SettingsPage() {
|
||||
await applyWxidSelection(selectedWxid)
|
||||
}
|
||||
|
||||
const handleSelectWeixinDllPath = async () => {
|
||||
try {
|
||||
const result = await dialog.openFile({
|
||||
title: '选择 Weixin.dll 文件',
|
||||
properties: ['openFile'],
|
||||
filters: [{ name: 'DLL', extensions: ['dll'] }]
|
||||
})
|
||||
if (!result.canceled && result.filePaths.length > 0) {
|
||||
const selectedPath = result.filePaths[0]
|
||||
setWeixinDllPath(selectedPath)
|
||||
await configService.setWeixinDllPath(selectedPath)
|
||||
showMessage('已选择 Weixin.dll 路径', true)
|
||||
}
|
||||
} catch {
|
||||
showMessage('选择 Weixin.dll 失败', false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleResetWeixinDllPath = async () => {
|
||||
setWeixinDllPath('')
|
||||
await configService.setWeixinDllPath('')
|
||||
showMessage('已清空 Weixin.dll 路径', true)
|
||||
}
|
||||
const handleSelectCachePath = async () => {
|
||||
try {
|
||||
const result = await dialog.openFile({ title: '选择缓存目录', properties: ['openDirectory'] })
|
||||
@@ -1332,28 +1310,7 @@ function SettingsPage() {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="form-group">
|
||||
<label>Weixin.dll 路径 <span className="optional">(可选)</span></label>
|
||||
<span className="form-hint">用于朋友圈在线图片原生解密,优先使用这里配置的 DLL</span>
|
||||
<input
|
||||
type="text"
|
||||
placeholder="例如: D:\weixindata\Weixin\Weixin.dll"
|
||||
value={weixinDllPath}
|
||||
onChange={(e) => {
|
||||
const value = e.target.value
|
||||
setWeixinDllPath(value)
|
||||
scheduleConfigSave('weixinDllPath', () => configService.setWeixinDllPath(value))
|
||||
}}
|
||||
/>
|
||||
<div className="btn-row">
|
||||
<button className="btn btn-secondary" onClick={handleSelectWeixinDllPath}>
|
||||
<FolderOpen size={16} /> 浏览选择
|
||||
</button>
|
||||
<button className="btn btn-secondary" onClick={handleResetWeixinDllPath}>
|
||||
清空
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
<div className="form-group">
|
||||
<label>账号 wxid</label>
|
||||
|
||||
@@ -12,7 +12,7 @@ export const CONFIG_KEYS = {
|
||||
LAST_SESSION: 'lastSession',
|
||||
WINDOW_BOUNDS: 'windowBounds',
|
||||
CACHE_PATH: 'cachePath',
|
||||
WEIXIN_DLL_PATH: 'weixinDllPath',
|
||||
|
||||
EXPORT_PATH: 'exportPath',
|
||||
AGREEMENT_ACCEPTED: 'agreementAccepted',
|
||||
LOG_ENABLED: 'logEnabled',
|
||||
@@ -163,16 +163,7 @@ export async function setCachePath(path: string): Promise<void> {
|
||||
}
|
||||
|
||||
|
||||
// 获取 Weixin.dll 路径
|
||||
export async function getWeixinDllPath(): Promise<string | null> {
|
||||
const value = await config.get(CONFIG_KEYS.WEIXIN_DLL_PATH)
|
||||
return value as string | null
|
||||
}
|
||||
|
||||
// 设置 Weixin.dll 路径
|
||||
export async function setWeixinDllPath(path: string): Promise<void> {
|
||||
await config.set(CONFIG_KEYS.WEIXIN_DLL_PATH, path)
|
||||
}
|
||||
|
||||
// 获取导出路径
|
||||
export async function getExportPath(): Promise<string | null> {
|
||||
|
||||
2
src/types/electron.d.ts
vendored
2
src/types/electron.d.ts
vendored
@@ -85,6 +85,8 @@ export interface ElectronAPI {
|
||||
}>
|
||||
getContact: (username: string) => Promise<Contact | null>
|
||||
getContactAvatar: (username: string) => Promise<{ avatarUrl?: string; displayName?: string } | null>
|
||||
updateMessage: (sessionId: string, localId: number, createTime: number, newContent: string) => Promise<{ success: boolean; error?: string }>
|
||||
deleteMessage: (sessionId: string, localId: number, createTime: number, dbPathHint?: string) => Promise<{ success: boolean; error?: string }>
|
||||
resolveTransferDisplayNames: (chatroomId: string, payerUsername: string, receiverUsername: string) => Promise<{ payerName: string; receiverName: string }>
|
||||
getContacts: () => Promise<{
|
||||
success: boolean
|
||||
|
||||
Reference in New Issue
Block a user