mirror of
https://github.com/hicccc77/WeFlow.git
synced 2026-03-25 15:25:50 +00:00
Compare commits
22 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
72d4db1f27 | ||
|
|
21ea879d97 | ||
|
|
a5baef2240 | ||
|
|
bbecf54aba | ||
|
|
5f868d193c | ||
|
|
62b035ab39 | ||
|
|
ff5ee33e08 | ||
|
|
8e28016e5e | ||
|
|
f17a18cb6d | ||
|
|
999f45e5f5 | ||
|
|
3e303fadd7 | ||
|
|
3b7590d8ce | ||
|
|
fabbada580 | ||
|
|
6e434d37dc | ||
|
|
904da80f81 | ||
|
|
2a4bd52f0a | ||
|
|
b4248d4a12 | ||
|
|
75b056d5ba | ||
|
|
e87e12c939 | ||
|
|
5cb7e3bc73 | ||
|
|
1930b91a5b | ||
|
|
ea0dad132c |
@@ -35,6 +35,7 @@ WeFlow 是一个**完全本地**的微信**实时**聊天记录查看、分析
|
|||||||
## 主要功能
|
## 主要功能
|
||||||
|
|
||||||
- 本地实时查看聊天记录
|
- 本地实时查看聊天记录
|
||||||
|
- 朋友圈图片、视频、**实况**的预览和解密
|
||||||
- 统计分析与群聊画像
|
- 统计分析与群聊画像
|
||||||
- 年度报告与可视化概览
|
- 年度报告与可视化概览
|
||||||
- 导出聊天记录为 HTML 等格式
|
- 导出聊天记录为 HTML 等格式
|
||||||
@@ -86,6 +87,7 @@ npm run build
|
|||||||
## 致谢
|
## 致谢
|
||||||
|
|
||||||
- [密语 CipherTalk](https://github.com/ILoveBingLu/miyu) 为本项目提供了基础框架
|
- [密语 CipherTalk](https://github.com/ILoveBingLu/miyu) 为本项目提供了基础框架
|
||||||
|
- [WeChat-Channels-Video-File-Decryption](https://github.com/Evil0ctal/WeChat-Channels-Video-File-Decryption) 提供了视频解密相关的技术参考
|
||||||
|
|
||||||
## 支持我们
|
## 支持我们
|
||||||
|
|
||||||
|
|||||||
4707
electron/assets/wasm/wasm_video_decode.js
Normal file
4707
electron/assets/wasm/wasm_video_decode.js
Normal file
File diff suppressed because it is too large
Load Diff
BIN
electron/assets/wasm/wasm_video_decode.wasm
Normal file
BIN
electron/assets/wasm/wasm_video_decode.wasm
Normal file
Binary file not shown.
@@ -18,7 +18,7 @@ import { exportService, ExportOptions, ExportProgress } from './services/exportS
|
|||||||
import { KeyService } from './services/keyService'
|
import { KeyService } from './services/keyService'
|
||||||
import { voiceTranscribeService } from './services/voiceTranscribeService'
|
import { voiceTranscribeService } from './services/voiceTranscribeService'
|
||||||
import { videoService } from './services/videoService'
|
import { videoService } from './services/videoService'
|
||||||
import { snsService } from './services/snsService'
|
import { snsService, isVideoUrl } from './services/snsService'
|
||||||
import { contactExportService } from './services/contactExportService'
|
import { contactExportService } from './services/contactExportService'
|
||||||
import { windowsHelloService } from './services/windowsHelloService'
|
import { windowsHelloService } from './services/windowsHelloService'
|
||||||
import { llamaService } from './services/llamaService'
|
import { llamaService } from './services/llamaService'
|
||||||
@@ -104,7 +104,8 @@ function createWindow(options: { autoShow?: boolean } = {}) {
|
|||||||
webPreferences: {
|
webPreferences: {
|
||||||
preload: join(__dirname, 'preload.js'),
|
preload: join(__dirname, 'preload.js'),
|
||||||
contextIsolation: true,
|
contextIsolation: true,
|
||||||
nodeIntegration: false
|
nodeIntegration: false,
|
||||||
|
webSecurity: false // Allow loading local files (video playback)
|
||||||
},
|
},
|
||||||
titleBarStyle: 'hidden',
|
titleBarStyle: 'hidden',
|
||||||
titleBarOverlay: {
|
titleBarOverlay: {
|
||||||
@@ -798,6 +799,14 @@ function registerIpcHandlers() {
|
|||||||
return chatService.getNewMessages(sessionId, minTime, limit)
|
return chatService.getNewMessages(sessionId, minTime, limit)
|
||||||
})
|
})
|
||||||
|
|
||||||
|
ipcMain.handle('chat:updateMessage', async (_, sessionId: string, localId: number, newContent: string) => {
|
||||||
|
return chatService.updateMessage(sessionId, localId, 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) => {
|
ipcMain.handle('chat:getContact', async (_, username: string) => {
|
||||||
return await chatService.getContact(username)
|
return await chatService.getContact(username)
|
||||||
})
|
})
|
||||||
@@ -932,8 +941,46 @@ function registerIpcHandlers() {
|
|||||||
return snsService.debugResource(url)
|
return snsService.debugResource(url)
|
||||||
})
|
})
|
||||||
|
|
||||||
ipcMain.handle('sns:proxyImage', async (_, url: string) => {
|
ipcMain.handle('sns:proxyImage', async (_, payload: string | { url: string; key?: string | number }) => {
|
||||||
return snsService.proxyImage(url)
|
const url = typeof payload === 'string' ? payload : payload?.url
|
||||||
|
const key = typeof payload === 'string' ? undefined : payload?.key
|
||||||
|
return snsService.proxyImage(url, key)
|
||||||
|
})
|
||||||
|
|
||||||
|
ipcMain.handle('sns:downloadImage', async (_, payload: { url: string; key?: string | number }) => {
|
||||||
|
try {
|
||||||
|
const { url, key } = payload
|
||||||
|
const result = await snsService.downloadImage(url, key)
|
||||||
|
|
||||||
|
if (!result.success || !result.data) {
|
||||||
|
return { success: false, error: result.error || '下载图片失败' }
|
||||||
|
}
|
||||||
|
|
||||||
|
const { dialog } = await import('electron')
|
||||||
|
const ext = (result.contentType || '').split('/')[1] || 'jpg'
|
||||||
|
const defaultPath = `SNS_${Date.now()}.${ext}`
|
||||||
|
|
||||||
|
|
||||||
|
const filters = isVideoUrl(url)
|
||||||
|
? [{ name: 'Videos', extensions: ['mp4', 'mov', 'avi', 'mkv'] }]
|
||||||
|
: [{ name: 'Images', extensions: [ext, 'jpg', 'jpeg', 'png', 'webp', 'gif'] }]
|
||||||
|
|
||||||
|
const { filePath, canceled } = await dialog.showSaveDialog({
|
||||||
|
defaultPath,
|
||||||
|
filters
|
||||||
|
})
|
||||||
|
|
||||||
|
if (canceled || !filePath) {
|
||||||
|
return { success: false, error: '用户已取消' }
|
||||||
|
}
|
||||||
|
|
||||||
|
const fs = await import('fs/promises')
|
||||||
|
await fs.writeFile(filePath, result.data)
|
||||||
|
|
||||||
|
return { success: true, filePath }
|
||||||
|
} catch (e) {
|
||||||
|
return { success: false, error: String(e) }
|
||||||
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
// 私聊克隆
|
// 私聊克隆
|
||||||
|
|||||||
@@ -131,6 +131,10 @@ contextBridge.exposeInMainWorld('electronAPI', {
|
|||||||
ipcRenderer.invoke('chat:getNewMessages', sessionId, minTime, limit),
|
ipcRenderer.invoke('chat:getNewMessages', sessionId, minTime, limit),
|
||||||
getContact: (username: string) => ipcRenderer.invoke('chat:getContact', username),
|
getContact: (username: string) => ipcRenderer.invoke('chat:getContact', username),
|
||||||
getContactAvatar: (username: string) => ipcRenderer.invoke('chat:getContactAvatar', username),
|
getContactAvatar: (username: string) => ipcRenderer.invoke('chat:getContactAvatar', username),
|
||||||
|
updateMessage: (sessionId: string, localId: number, newContent: string) =>
|
||||||
|
ipcRenderer.invoke('chat:updateMessage', sessionId, localId, 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) =>
|
resolveTransferDisplayNames: (chatroomId: string, payerUsername: string, receiverUsername: string) =>
|
||||||
ipcRenderer.invoke('chat:resolveTransferDisplayNames', chatroomId, payerUsername, receiverUsername),
|
ipcRenderer.invoke('chat:resolveTransferDisplayNames', chatroomId, payerUsername, receiverUsername),
|
||||||
getMyAvatarUrl: () => ipcRenderer.invoke('chat:getMyAvatarUrl'),
|
getMyAvatarUrl: () => ipcRenderer.invoke('chat:getMyAvatarUrl'),
|
||||||
@@ -271,7 +275,8 @@ contextBridge.exposeInMainWorld('electronAPI', {
|
|||||||
getTimeline: (limit: number, offset: number, usernames?: string[], keyword?: string, startTime?: number, endTime?: number) =>
|
getTimeline: (limit: number, offset: number, usernames?: string[], keyword?: string, startTime?: number, endTime?: number) =>
|
||||||
ipcRenderer.invoke('sns:getTimeline', limit, offset, usernames, keyword, startTime, endTime),
|
ipcRenderer.invoke('sns:getTimeline', limit, offset, usernames, keyword, startTime, endTime),
|
||||||
debugResource: (url: string) => ipcRenderer.invoke('sns:debugResource', url),
|
debugResource: (url: string) => ipcRenderer.invoke('sns:debugResource', url),
|
||||||
proxyImage: (url: string) => ipcRenderer.invoke('sns:proxyImage', url)
|
proxyImage: (payload: { url: string; key?: string | number }) => ipcRenderer.invoke('sns:proxyImage', payload),
|
||||||
|
downloadImage: (payload: { url: string; key?: string | number }) => ipcRenderer.invoke('sns:downloadImage', payload)
|
||||||
},
|
},
|
||||||
|
|
||||||
// Llama AI
|
// Llama AI
|
||||||
|
|||||||
@@ -50,6 +50,9 @@ export interface Message {
|
|||||||
emojiCdnUrl?: string
|
emojiCdnUrl?: string
|
||||||
emojiMd5?: string
|
emojiMd5?: string
|
||||||
emojiLocalPath?: string // 本地缓存 castle 路径
|
emojiLocalPath?: string // 本地缓存 castle 路径
|
||||||
|
emojiThumbUrl?: string
|
||||||
|
emojiEncryptUrl?: string
|
||||||
|
emojiAesKey?: string
|
||||||
// 引用消息相关
|
// 引用消息相关
|
||||||
quotedContent?: string
|
quotedContent?: string
|
||||||
quotedSender?: string
|
quotedSender?: string
|
||||||
@@ -84,6 +87,7 @@ export interface Message {
|
|||||||
datadesc: string
|
datadesc: string
|
||||||
datatitle?: string
|
datatitle?: string
|
||||||
}>
|
}>
|
||||||
|
_db_path?: string // 内部字段:记录消息所属数据库路径
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface Contact {
|
export interface Contact {
|
||||||
@@ -109,7 +113,7 @@ const emojiDownloading: Map<string, Promise<string | null>> = new Map()
|
|||||||
class ChatService {
|
class ChatService {
|
||||||
private configService: ConfigService
|
private configService: ConfigService
|
||||||
private connected = false
|
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 readonly messageBatchDefault = 50
|
||||||
private avatarCache: Map<string, ContactCacheEntry>
|
private avatarCache: Map<string, ContactCacheEntry>
|
||||||
private readonly avatarCacheTtlMs = 10 * 60 * 1000
|
private readonly avatarCacheTtlMs = 10 * 60 * 1000
|
||||||
@@ -141,10 +145,10 @@ class ChatService {
|
|||||||
|
|
||||||
constructor() {
|
constructor() {
|
||||||
this.configService = new ConfigService()
|
this.configService = new ConfigService()
|
||||||
this.contactCacheService = new ContactCacheService(this.configService.get('cachePath'))
|
this.contactCacheService = new ContactCacheService(this.configService.getCacheBasePath())
|
||||||
const persisted = this.contactCacheService.getAllEntries()
|
const persisted = this.contactCacheService.getAllEntries()
|
||||||
this.avatarCache = new Map(Object.entries(persisted))
|
this.avatarCache = new Map(Object.entries(persisted))
|
||||||
this.messageCacheService = new MessageCacheService(this.configService.get('cachePath'))
|
this.messageCacheService = new MessageCacheService(this.configService.getCacheBasePath())
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -269,6 +273,32 @@ class ChatService {
|
|||||||
this.connected = false
|
this.connected = false
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 修改消息内容
|
||||||
|
*/
|
||||||
|
async updateMessage(sessionId: string, localId: 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, 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 改变(视为全新查询)
|
// 4. startTime/endTime 改变(视为全新查询)
|
||||||
// 5. ascending 改变
|
// 5. ascending 改变
|
||||||
const needNewCursor = !state ||
|
const needNewCursor = !state ||
|
||||||
offset === 0 ||
|
offset !== state.fetched || // Offset mismatch -> must reset cursor
|
||||||
state.batchSize !== batchSize ||
|
state.batchSize !== batchSize ||
|
||||||
state.startTime !== startTime ||
|
state.startTime !== startTime ||
|
||||||
state.endTime !== endTime ||
|
state.endTime !== endTime ||
|
||||||
@@ -761,6 +791,7 @@ class ChatService {
|
|||||||
// 如果需要跳过消息(offset > 0),逐批获取但不返回
|
// 如果需要跳过消息(offset > 0),逐批获取但不返回
|
||||||
// 注意:仅在 offset === 0 时重建游标最安全;
|
// 注意:仅在 offset === 0 时重建游标最安全;
|
||||||
// 当 startTime/endTime 变化导致重建时,offset 应由前端重置为 0
|
// 当 startTime/endTime 变化导致重建时,offset 应由前端重置为 0
|
||||||
|
state.bufferedMessages = []
|
||||||
if (offset > 0) {
|
if (offset > 0) {
|
||||||
console.warn(`[ChatService] 新游标需跳过 ${offset} 条消息(startTime=${startTime}, endTime=${endTime})`)
|
console.warn(`[ChatService] 新游标需跳过 ${offset} 条消息(startTime=${startTime}, endTime=${endTime})`)
|
||||||
let skipped = 0
|
let skipped = 0
|
||||||
@@ -777,8 +808,22 @@ class ChatService {
|
|||||||
console.warn(`[ChatService] 跳过时数据耗尽: skipped=${skipped}/${offset}`)
|
console.warn(`[ChatService] 跳过时数据耗尽: skipped=${skipped}/${offset}`)
|
||||||
return { success: true, messages: [], hasMore: false }
|
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) {
|
if (!skipBatch.hasMore) {
|
||||||
console.warn(`[ChatService] 跳过后无更多数据: skipped=${skipped}/${offset}`)
|
console.warn(`[ChatService] 跳过后无更多数据: skipped=${skipped}/${offset}`)
|
||||||
return { success: true, messages: [], hasMore: false }
|
return { success: true, messages: [], hasMore: false }
|
||||||
@@ -787,13 +832,8 @@ class ChatService {
|
|||||||
if (attempts >= maxSkipAttempts) {
|
if (attempts >= maxSkipAttempts) {
|
||||||
console.error(`[ChatService] 跳过消息超过最大尝试次数: attempts=${attempts}`)
|
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 已初始化
|
// 确保 state 已初始化
|
||||||
@@ -803,19 +843,35 @@ class ChatService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 获取当前批次的消息
|
// 获取当前批次的消息
|
||||||
const batch = await wcdbService.fetchMessageBatch(state.cursor)
|
// Use buffered rows from skip logic if available
|
||||||
if (!batch.success) {
|
let rows: any[] = state.bufferedMessages || []
|
||||||
console.error('[ChatService] 获取消息批次失败:', batch.error)
|
state.bufferedMessages = undefined // Clear buffer after use
|
||||||
return { success: false, error: batch.error || '获取消息失败' }
|
|
||||||
|
// 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) {
|
// If we have more than limit (due to buffer + full batch), slice it
|
||||||
console.error('[ChatService] 获取消息失败: 返回数据为空')
|
if (rows.length > limit) {
|
||||||
return { success: false, error: '获取消息失败: 返回数据为空' }
|
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 = rows.length > 0 // Simplified hasMore check for now, can be improved
|
||||||
const hasMore = batch.hasMore === true
|
|
||||||
|
|
||||||
const normalized = this.normalizeMessageOrder(this.mapRowsToMessages(rows))
|
const normalized = this.normalizeMessageOrder(this.mapRowsToMessages(rows))
|
||||||
|
|
||||||
@@ -1151,6 +1207,9 @@ class ChatService {
|
|||||||
const emojiInfo = this.parseEmojiInfo(content)
|
const emojiInfo = this.parseEmojiInfo(content)
|
||||||
emojiCdnUrl = emojiInfo.cdnUrl
|
emojiCdnUrl = emojiInfo.cdnUrl
|
||||||
emojiMd5 = emojiInfo.md5
|
emojiMd5 = emojiInfo.md5
|
||||||
|
cdnThumbUrl = emojiInfo.thumbUrl // 复用 cdnThumbUrl 字段或使用 emojiThumbUrl
|
||||||
|
// 注意:Message 接口定义的 emojiThumbUrl,这里我们统一一下
|
||||||
|
// 如果 Message 接口有 emojiThumbUrl,则使用它
|
||||||
} else if (localType === 3 && content) {
|
} else if (localType === 3 && content) {
|
||||||
const imageInfo = this.parseImageInfo(content)
|
const imageInfo = this.parseImageInfo(content)
|
||||||
imageMd5 = imageInfo.md5
|
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 {
|
try {
|
||||||
// 提取 cdnurl
|
// 提取 cdnurl
|
||||||
let cdnUrl: string | undefined
|
let cdnUrl: string | undefined
|
||||||
@@ -1387,16 +1446,15 @@ class ChatService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 如果没有 cdnurl,尝试 thumburl
|
// 提取 thumburl
|
||||||
if (!cdnUrl) {
|
let thumbUrl: string | undefined
|
||||||
const thumbUrlMatch = /thumburl\s*=\s*['"]([^'"]+)['"]/i.exec(content) || /thumburl\s*=\s*([^'"]+?)(?=\s|\/|>)/i.exec(content)
|
const thumbUrlMatch = /thumburl\s*=\s*['"]([^'"]+)['"]/i.exec(content) || /thumburl\s*=\s*([^'"]+?)(?=\s|\/|>)/i.exec(content)
|
||||||
if (thumbUrlMatch) {
|
if (thumbUrlMatch) {
|
||||||
cdnUrl = thumbUrlMatch[1].replace(/&/g, '&')
|
thumbUrl = thumbUrlMatch[1].replace(/&/g, '&')
|
||||||
if (cdnUrl.includes('%')) {
|
if (thumbUrl.includes('%')) {
|
||||||
try {
|
try {
|
||||||
cdnUrl = decodeURIComponent(cdnUrl)
|
thumbUrl = decodeURIComponent(thumbUrl)
|
||||||
} catch { }
|
} catch { }
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1404,9 +1462,23 @@ class ChatService {
|
|||||||
const md5Match = /md5\s*=\s*['"]([a-fA-F0-9]+)['"]/i.exec(content) || /md5\s*=\s*([a-fA-F0-9]+)/i.exec(content)
|
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
|
const md5 = md5Match ? md5Match[1] : undefined
|
||||||
|
|
||||||
// 不构造假 URL,只返回真正的 cdnurl
|
// 提取 encrypturl
|
||||||
// 没有 cdnUrl 时保持静默,交由后续回退逻辑处理
|
let encryptUrl: string | undefined
|
||||||
return { cdnUrl, md5 }
|
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) {
|
} catch (e) {
|
||||||
console.error('[ChatService] 表情包解析失败:', e, { xml: content })
|
console.error('[ChatService] 表情包解析失败:', e, { xml: content })
|
||||||
return {}
|
return {}
|
||||||
@@ -2622,11 +2694,7 @@ class ChatService {
|
|||||||
// 检查内存缓存
|
// 检查内存缓存
|
||||||
const cached = emojiCache.get(cacheKey)
|
const cached = emojiCache.get(cacheKey)
|
||||||
if (cached && existsSync(cached)) {
|
if (cached && existsSync(cached)) {
|
||||||
// 读取文件并转为 data URL
|
return { success: true, localPath: cached }
|
||||||
const dataUrl = this.fileToDataUrl(cached)
|
|
||||||
if (dataUrl) {
|
|
||||||
return { success: true, localPath: dataUrl }
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// 检查是否正在下载
|
// 检查是否正在下载
|
||||||
@@ -2634,10 +2702,7 @@ class ChatService {
|
|||||||
if (downloading) {
|
if (downloading) {
|
||||||
const result = await downloading
|
const result = await downloading
|
||||||
if (result) {
|
if (result) {
|
||||||
const dataUrl = this.fileToDataUrl(result)
|
return { success: true, localPath: result }
|
||||||
if (dataUrl) {
|
|
||||||
return { success: true, localPath: dataUrl }
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
return { success: false, error: '下载失败' }
|
return { success: false, error: '下载失败' }
|
||||||
}
|
}
|
||||||
@@ -2654,10 +2719,7 @@ class ChatService {
|
|||||||
const filePath = join(cacheDir, `${cacheKey}${ext}`)
|
const filePath = join(cacheDir, `${cacheKey}${ext}`)
|
||||||
if (existsSync(filePath)) {
|
if (existsSync(filePath)) {
|
||||||
emojiCache.set(cacheKey, filePath)
|
emojiCache.set(cacheKey, filePath)
|
||||||
const dataUrl = this.fileToDataUrl(filePath)
|
return { success: true, localPath: filePath }
|
||||||
if (dataUrl) {
|
|
||||||
return { success: true, localPath: dataUrl }
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -2671,10 +2733,7 @@ class ChatService {
|
|||||||
|
|
||||||
if (localPath) {
|
if (localPath) {
|
||||||
emojiCache.set(cacheKey, localPath)
|
emojiCache.set(cacheKey, localPath)
|
||||||
const dataUrl = this.fileToDataUrl(localPath)
|
return { success: true, localPath }
|
||||||
if (dataUrl) {
|
|
||||||
return { success: true, localPath: dataUrl }
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
return { success: false, error: '下载失败' }
|
return { success: false, error: '下载失败' }
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
@@ -3917,6 +3976,13 @@ class ChatService {
|
|||||||
const imgInfo = this.parseImageInfo(rawContent)
|
const imgInfo = this.parseImageInfo(rawContent)
|
||||||
Object.assign(msg, imgInfo)
|
Object.assign(msg, imgInfo)
|
||||||
msg.imageDatName = this.parseImageDatNameFromRow(row)
|
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
|
return msg
|
||||||
@@ -4227,6 +4293,34 @@ class ChatService {
|
|||||||
return { success: false, error: String(e) }
|
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()
|
export const chatService = new ChatService()
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
|
import { join } from 'path'
|
||||||
|
import { app } from 'electron'
|
||||||
import Store from 'electron-store'
|
import Store from 'electron-store'
|
||||||
|
|
||||||
interface ConfigSchema {
|
interface ConfigSchema {
|
||||||
@@ -12,6 +14,7 @@ interface ConfigSchema {
|
|||||||
|
|
||||||
// 缓存相关
|
// 缓存相关
|
||||||
cachePath: string
|
cachePath: string
|
||||||
|
|
||||||
lastOpenedDb: string
|
lastOpenedDb: string
|
||||||
lastSession: string
|
lastSession: string
|
||||||
|
|
||||||
@@ -72,6 +75,7 @@ export class ConfigService {
|
|||||||
imageAesKey: '',
|
imageAesKey: '',
|
||||||
wxidConfigs: {},
|
wxidConfigs: {},
|
||||||
cachePath: '',
|
cachePath: '',
|
||||||
|
|
||||||
lastOpenedDb: '',
|
lastOpenedDb: '',
|
||||||
lastSession: '',
|
lastSession: '',
|
||||||
theme: 'system',
|
theme: 'system',
|
||||||
@@ -109,6 +113,14 @@ export class ConfigService {
|
|||||||
this.store.set(key, value)
|
this.store.set(key, value)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
getCacheBasePath(): string {
|
||||||
|
const configured = this.get('cachePath')
|
||||||
|
if (configured && configured.trim().length > 0) {
|
||||||
|
return configured
|
||||||
|
}
|
||||||
|
return join(app.getPath('documents'), 'WeFlow')
|
||||||
|
}
|
||||||
|
|
||||||
getAll(): ConfigSchema {
|
getAll(): ConfigSchema {
|
||||||
return this.store.store
|
return this.store.store
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import { join, dirname } from 'path'
|
import { join, dirname } from 'path'
|
||||||
import { existsSync, mkdirSync, readFileSync, writeFileSync, rmSync } from 'fs'
|
import { existsSync, mkdirSync, readFileSync, writeFileSync, rmSync } from 'fs'
|
||||||
import { app } from 'electron'
|
import { app } from 'electron'
|
||||||
|
import { ConfigService } from './config'
|
||||||
|
|
||||||
export interface ContactCacheEntry {
|
export interface ContactCacheEntry {
|
||||||
displayName?: string
|
displayName?: string
|
||||||
@@ -15,7 +16,7 @@ export class ContactCacheService {
|
|||||||
constructor(cacheBasePath?: string) {
|
constructor(cacheBasePath?: string) {
|
||||||
const basePath = cacheBasePath && cacheBasePath.trim().length > 0
|
const basePath = cacheBasePath && cacheBasePath.trim().length > 0
|
||||||
? cacheBasePath
|
? cacheBasePath
|
||||||
: join(app.getPath('documents'), 'WeFlow')
|
: ConfigService.getInstance().getCacheBasePath()
|
||||||
this.cacheFilePath = join(basePath, 'contacts.json')
|
this.cacheFilePath = join(basePath, 'contacts.json')
|
||||||
this.ensureCacheDir()
|
this.ensureCacheDir()
|
||||||
this.loadCache()
|
this.loadCache()
|
||||||
|
|||||||
@@ -1479,49 +1479,30 @@ class ExportService {
|
|||||||
fs.mkdirSync(emojisDir, { recursive: true })
|
fs.mkdirSync(emojisDir, { recursive: true })
|
||||||
}
|
}
|
||||||
|
|
||||||
// 使用消息对象中已提取的字段
|
// 使用 chatService 下载表情包 (利用其重试和 fallback 逻辑)
|
||||||
const emojiUrl = msg.emojiCdnUrl
|
const localPath = await chatService.downloadEmojiFile(msg)
|
||||||
const emojiMd5 = msg.emojiMd5
|
|
||||||
|
|
||||||
if (!emojiUrl && !emojiMd5) {
|
|
||||||
|
|
||||||
|
if (!localPath || !fs.existsSync(localPath)) {
|
||||||
return null
|
return null
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 确定目标文件名
|
||||||
|
const ext = path.extname(localPath) || '.gif'
|
||||||
const key = emojiMd5 || String(msg.localId)
|
const key = msg.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 fileName = `${key}${ext}`
|
const fileName = `${key}${ext}`
|
||||||
const destPath = path.join(emojisDir, fileName)
|
const destPath = path.join(emojisDir, fileName)
|
||||||
|
|
||||||
// 如果已存在则跳过
|
// 复制文件到导出目录 (如果不存在)
|
||||||
if (fs.existsSync(destPath)) {
|
if (!fs.existsSync(destPath)) {
|
||||||
return {
|
fs.copyFileSync(localPath, destPath)
|
||||||
relativePath: path.posix.join(mediaRelativePrefix, 'emojis', fileName),
|
|
||||||
kind: 'emoji'
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// 下载表情
|
return {
|
||||||
if (emojiUrl) {
|
relativePath: path.posix.join(mediaRelativePrefix, 'emojis', fileName),
|
||||||
const downloaded = await this.downloadFile(emojiUrl, destPath)
|
kind: 'emoji'
|
||||||
if (downloaded) {
|
|
||||||
return {
|
|
||||||
relativePath: path.posix.join(mediaRelativePrefix, 'emojis', fileName),
|
|
||||||
kind: 'emoji'
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return null
|
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
console.error('ExportService: exportEmoji failed', e)
|
||||||
return null
|
return null
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -4512,7 +4493,7 @@ class ExportService {
|
|||||||
phase: 'exporting'
|
phase: 'exporting'
|
||||||
})
|
})
|
||||||
|
|
||||||
const safeName = sessionInfo.displayName.replace(/[<>:"/\\|?*]/g, '_')
|
const safeName = sessionInfo.displayName.replace(/[<>:"\/\\|?*]/g, '_').replace(/\.+$/, '')
|
||||||
const useSessionFolder = sessionLayout === 'per-session'
|
const useSessionFolder = sessionLayout === 'per-session'
|
||||||
const sessionDir = useSessionFolder ? path.join(outputDir, safeName) : outputDir
|
const sessionDir = useSessionFolder ? path.join(outputDir, safeName) : outputDir
|
||||||
|
|
||||||
|
|||||||
127
electron/services/isaac64.ts
Normal file
127
electron/services/isaac64.ts
Normal file
@@ -0,0 +1,127 @@
|
|||||||
|
/**
|
||||||
|
* ISAAC-64: A fast cryptographic PRNG
|
||||||
|
* Re-implemented in TypeScript using BigInt for 64-bit support.
|
||||||
|
* Used for WeChat Channels/SNS video decryption.
|
||||||
|
*/
|
||||||
|
|
||||||
|
export class Isaac64 {
|
||||||
|
private mm = new BigUint64Array(256);
|
||||||
|
private aa = 0n;
|
||||||
|
private bb = 0n;
|
||||||
|
private cc = 0n;
|
||||||
|
private randrsl = new BigUint64Array(256);
|
||||||
|
private randcnt = 0;
|
||||||
|
private static readonly MASK = 0xFFFFFFFFFFFFFFFFn;
|
||||||
|
|
||||||
|
constructor(seed: number | string | bigint) {
|
||||||
|
const seedBig = BigInt(seed);
|
||||||
|
// 通常单密钥初始化是将密钥放在第一个槽位,其余清零(或者按某种规律填充)
|
||||||
|
// 这里我们尝试仅设置第一个槽位,这在很多 WASM 移植版本中更为常见
|
||||||
|
this.randrsl.fill(0n);
|
||||||
|
this.randrsl[0] = seedBig;
|
||||||
|
this.init(true);
|
||||||
|
}
|
||||||
|
|
||||||
|
private init(flag: boolean) {
|
||||||
|
let a: bigint, b: bigint, c: bigint, d: bigint, e: bigint, f: bigint, g: bigint, h: bigint;
|
||||||
|
a = b = c = d = e = f = g = h = 0x9e3779b97f4a7c15n;
|
||||||
|
|
||||||
|
const mix = () => {
|
||||||
|
a = (a - e) & Isaac64.MASK; f ^= (h >> 9n); h = (h + a) & Isaac64.MASK;
|
||||||
|
b = (b - f) & Isaac64.MASK; g ^= (a << 9n) & Isaac64.MASK; a = (a + b) & Isaac64.MASK;
|
||||||
|
c = (c - g) & Isaac64.MASK; h ^= (b >> 23n); b = (b + c) & Isaac64.MASK;
|
||||||
|
d = (d - h) & Isaac64.MASK; a ^= (c << 15n) & Isaac64.MASK; c = (c + d) & Isaac64.MASK;
|
||||||
|
e = (e - a) & Isaac64.MASK; b ^= (d >> 14n); d = (d + e) & Isaac64.MASK;
|
||||||
|
f = (f - b) & Isaac64.MASK; c ^= (e << 20n) & Isaac64.MASK; e = (e + f) & Isaac64.MASK;
|
||||||
|
g = (g - c) & Isaac64.MASK; d ^= (f >> 17n); f = (f + g) & Isaac64.MASK;
|
||||||
|
h = (h - d) & Isaac64.MASK; e ^= (g << 14n) & Isaac64.MASK; g = (g + h) & Isaac64.MASK;
|
||||||
|
};
|
||||||
|
|
||||||
|
for (let i = 0; i < 4; i++) mix();
|
||||||
|
|
||||||
|
for (let i = 0; i < 256; i += 8) {
|
||||||
|
if (flag) {
|
||||||
|
a = (a + this.randrsl[i]) & Isaac64.MASK;
|
||||||
|
b = (b + this.randrsl[i + 1]) & Isaac64.MASK;
|
||||||
|
c = (c + this.randrsl[i + 2]) & Isaac64.MASK;
|
||||||
|
d = (d + this.randrsl[i + 3]) & Isaac64.MASK;
|
||||||
|
e = (e + this.randrsl[i + 4]) & Isaac64.MASK;
|
||||||
|
f = (f + this.randrsl[i + 5]) & Isaac64.MASK;
|
||||||
|
g = (g + this.randrsl[i + 6]) & Isaac64.MASK;
|
||||||
|
h = (h + this.randrsl[i + 7]) & Isaac64.MASK;
|
||||||
|
}
|
||||||
|
mix();
|
||||||
|
this.mm[i] = a; this.mm[i + 1] = b; this.mm[i + 2] = c; this.mm[i + 3] = d;
|
||||||
|
this.mm[i + 4] = e; this.mm[i + 5] = f; this.mm[i + 6] = g; this.mm[i + 7] = h;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (flag) {
|
||||||
|
for (let i = 0; i < 256; i += 8) {
|
||||||
|
a = (a + this.mm[i]) & Isaac64.MASK;
|
||||||
|
b = (b + this.mm[i + 1]) & Isaac64.MASK;
|
||||||
|
c = (c + this.mm[i + 2]) & Isaac64.MASK;
|
||||||
|
d = (d + this.mm[i + 3]) & Isaac64.MASK;
|
||||||
|
e = (e + this.mm[i + 4]) & Isaac64.MASK;
|
||||||
|
f = (f + this.mm[i + 5]) & Isaac64.MASK;
|
||||||
|
g = (g + this.mm[i + 6]) & Isaac64.MASK;
|
||||||
|
h = (h + this.mm[i + 7]) & Isaac64.MASK;
|
||||||
|
mix();
|
||||||
|
this.mm[i] = a; this.mm[i + 1] = b; this.mm[i + 2] = c; this.mm[i + 3] = d;
|
||||||
|
this.mm[i + 4] = e; this.mm[i + 5] = f; this.mm[i + 6] = g; this.mm[i + 7] = h;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
this.isaac64();
|
||||||
|
this.randcnt = 256;
|
||||||
|
}
|
||||||
|
|
||||||
|
private isaac64() {
|
||||||
|
this.cc = (this.cc + 1n) & Isaac64.MASK;
|
||||||
|
this.bb = (this.bb + this.cc) & Isaac64.MASK;
|
||||||
|
for (let i = 0; i < 256; i++) {
|
||||||
|
let x = this.mm[i];
|
||||||
|
switch (i & 3) {
|
||||||
|
case 0: this.aa = (this.aa ^ (((this.aa << 21n) & Isaac64.MASK) ^ Isaac64.MASK)) & Isaac64.MASK; break;
|
||||||
|
case 1: this.aa = (this.aa ^ (this.aa >> 5n)) & Isaac64.MASK; break;
|
||||||
|
case 2: this.aa = (this.aa ^ ((this.aa << 12n) & Isaac64.MASK)) & Isaac64.MASK; break;
|
||||||
|
case 3: this.aa = (this.aa ^ (this.aa >> 33n)) & Isaac64.MASK; break;
|
||||||
|
}
|
||||||
|
this.aa = (this.mm[(i + 128) & 255] + this.aa) & Isaac64.MASK;
|
||||||
|
const y = (this.mm[Number(x >> 3n) & 255] + this.aa + this.bb) & Isaac64.MASK;
|
||||||
|
this.mm[i] = y;
|
||||||
|
this.bb = (this.mm[Number(y >> 11n) & 255] + x) & Isaac64.MASK;
|
||||||
|
this.randrsl[i] = this.bb;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public getNext(): bigint {
|
||||||
|
if (this.randcnt === 0) {
|
||||||
|
this.isaac64();
|
||||||
|
this.randcnt = 256;
|
||||||
|
}
|
||||||
|
return this.randrsl[--this.randcnt];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Generates a keystream where each 64-bit block is Big-Endian.
|
||||||
|
* This matches WeChat's behavior (Reverse index order + byte reversal).
|
||||||
|
*/
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
import { join, dirname } from 'path'
|
import { join, dirname } from 'path'
|
||||||
import { existsSync, mkdirSync, readFileSync, writeFileSync, rmSync } from 'fs'
|
import { existsSync, mkdirSync, readFileSync, writeFileSync, rmSync } from 'fs'
|
||||||
import { app } from 'electron'
|
import { app } from 'electron'
|
||||||
|
import { ConfigService } from './config'
|
||||||
|
|
||||||
export interface SessionMessageCacheEntry {
|
export interface SessionMessageCacheEntry {
|
||||||
updatedAt: number
|
updatedAt: number
|
||||||
@@ -15,7 +16,7 @@ export class MessageCacheService {
|
|||||||
constructor(cacheBasePath?: string) {
|
constructor(cacheBasePath?: string) {
|
||||||
const basePath = cacheBasePath && cacheBasePath.trim().length > 0
|
const basePath = cacheBasePath && cacheBasePath.trim().length > 0
|
||||||
? cacheBasePath
|
? cacheBasePath
|
||||||
: join(app.getPath('documents'), 'WeFlow')
|
: ConfigService.getInstance().getCacheBasePath()
|
||||||
this.cacheFilePath = join(basePath, 'session-messages.json')
|
this.cacheFilePath = join(basePath, 'session-messages.json')
|
||||||
this.ensureCacheDir()
|
this.ensureCacheDir()
|
||||||
this.loadCache()
|
this.loadCache()
|
||||||
|
|||||||
@@ -1,6 +1,11 @@
|
|||||||
import { wcdbService } from './wcdbService'
|
import { wcdbService } from './wcdbService'
|
||||||
import { ConfigService } from './config'
|
import { ConfigService } from './config'
|
||||||
import { ContactCacheService } from './contactCacheService'
|
import { ContactCacheService } from './contactCacheService'
|
||||||
|
import { existsSync, mkdirSync } from 'fs'
|
||||||
|
import { readFile, writeFile, mkdir } from 'fs/promises'
|
||||||
|
import { basename, join } from 'path'
|
||||||
|
import crypto from 'crypto'
|
||||||
|
import { WasmService } from './wasmService'
|
||||||
|
|
||||||
export interface SnsLivePhoto {
|
export interface SnsLivePhoto {
|
||||||
url: string
|
url: string
|
||||||
@@ -32,82 +37,147 @@ export interface SnsPost {
|
|||||||
media: SnsMedia[]
|
media: SnsMedia[]
|
||||||
likes: string[]
|
likes: string[]
|
||||||
comments: { id: string; nickname: string; content: string; refCommentId: string; refNickname?: string }[]
|
comments: { id: string; nickname: string; content: string; refCommentId: string; refNickname?: string }[]
|
||||||
rawXml?: string // 原始 XML 数据
|
rawXml?: string
|
||||||
}
|
}
|
||||||
|
|
||||||
const fixSnsUrl = (url: string, token?: string) => {
|
|
||||||
if (!url) return url;
|
|
||||||
|
|
||||||
// 1. 统一使用 https
|
|
||||||
// 2. 将 /150 (缩略图) 强制改为 /0 (原图)
|
|
||||||
let fixedUrl = url.replace('http://', 'https://').replace(/\/150($|\?)/, '/0$1');
|
|
||||||
|
|
||||||
if (!token || fixedUrl.includes('token=')) return fixedUrl;
|
const fixSnsUrl = (url: string, token?: string, isVideo: boolean = false) => {
|
||||||
|
if (!url) return url
|
||||||
|
|
||||||
const connector = fixedUrl.includes('?') ? '&' : '?';
|
let fixedUrl = url.replace('http://', 'https://')
|
||||||
return `${fixedUrl}${connector}token=${token}&idx=1`;
|
|
||||||
};
|
// 只有非视频(即图片)才需要处理 /150 变 /0
|
||||||
|
if (!isVideo) {
|
||||||
|
fixedUrl = fixedUrl.replace(/\/150($|\?)/, '/0$1')
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!token || fixedUrl.includes('token=')) return fixedUrl
|
||||||
|
|
||||||
|
// 根据用户要求,视频链接组合方式为: BASE_URL + "?" + "token=" + token + "&idx=1" + 原有参数
|
||||||
|
if (isVideo) {
|
||||||
|
const urlParts = fixedUrl.split('?')
|
||||||
|
const baseUrl = urlParts[0]
|
||||||
|
const existingParams = urlParts[1] ? `&${urlParts[1]}` : ''
|
||||||
|
return `${baseUrl}?token=${token}&idx=1${existingParams}`
|
||||||
|
}
|
||||||
|
|
||||||
|
const connector = fixedUrl.includes('?') ? '&' : '?'
|
||||||
|
return `${fixedUrl}${connector}token=${token}&idx=1`
|
||||||
|
}
|
||||||
|
|
||||||
|
const detectImageMime = (buf: Buffer, fallback: string = 'image/jpeg') => {
|
||||||
|
if (!buf || buf.length < 4) return fallback
|
||||||
|
|
||||||
|
// JPEG
|
||||||
|
if (buf[0] === 0xff && buf[1] === 0xd8 && buf[2] === 0xff) return 'image/jpeg'
|
||||||
|
|
||||||
|
// PNG
|
||||||
|
if (
|
||||||
|
buf.length >= 8 &&
|
||||||
|
buf[0] === 0x89 && buf[1] === 0x50 && buf[2] === 0x4e && buf[3] === 0x47 &&
|
||||||
|
buf[4] === 0x0d && buf[5] === 0x0a && buf[6] === 0x1a && buf[7] === 0x0a
|
||||||
|
) return 'image/png'
|
||||||
|
|
||||||
|
// GIF
|
||||||
|
if (buf.length >= 6) {
|
||||||
|
const sig = buf.subarray(0, 6).toString('ascii')
|
||||||
|
if (sig === 'GIF87a' || sig === 'GIF89a') return 'image/gif'
|
||||||
|
}
|
||||||
|
|
||||||
|
// WebP
|
||||||
|
if (
|
||||||
|
buf.length >= 12 &&
|
||||||
|
buf[0] === 0x52 && buf[1] === 0x49 && buf[2] === 0x46 && buf[3] === 0x46 &&
|
||||||
|
buf[8] === 0x57 && buf[9] === 0x45 && buf[10] === 0x42 && buf[11] === 0x50
|
||||||
|
) return 'image/webp'
|
||||||
|
|
||||||
|
// BMP
|
||||||
|
if (buf[0] === 0x42 && buf[1] === 0x4d) return 'image/bmp'
|
||||||
|
|
||||||
|
// MP4: 00 00 00 18 / 20 / ... + 'ftyp'
|
||||||
|
if (buf.length > 8 && buf[4] === 0x66 && buf[5] === 0x74 && buf[6] === 0x79 && buf[7] === 0x70) return 'video/mp4'
|
||||||
|
|
||||||
|
// Fallback logic for video
|
||||||
|
if (fallback.includes('video') || fallback.includes('mp4')) return 'video/mp4'
|
||||||
|
|
||||||
|
return fallback
|
||||||
|
}
|
||||||
|
|
||||||
|
export const isVideoUrl = (url: string) => {
|
||||||
|
if (!url) return false
|
||||||
|
// 排除 vweixinthumb 域名 (缩略图)
|
||||||
|
if (url.includes('vweixinthumb')) return false
|
||||||
|
return url.includes('snsvideodownload') || url.includes('video') || url.includes('.mp4')
|
||||||
|
}
|
||||||
|
|
||||||
|
import { Isaac64 } from './isaac64'
|
||||||
|
|
||||||
|
const extractVideoKey = (xml: string): string | undefined => {
|
||||||
|
if (!xml) return undefined
|
||||||
|
// 匹配 <enc key="2105122989" ... /> 或 <enc key="2105122989">
|
||||||
|
const match = xml.match(/<enc\s+key="(\d+)"/i)
|
||||||
|
return match ? match[1] : undefined
|
||||||
|
}
|
||||||
|
|
||||||
class SnsService {
|
class SnsService {
|
||||||
|
private configService: ConfigService
|
||||||
private contactCache: ContactCacheService
|
private contactCache: ContactCacheService
|
||||||
|
private imageCache = new Map<string, string>()
|
||||||
|
|
||||||
constructor() {
|
constructor() {
|
||||||
const config = new ConfigService()
|
this.configService = new ConfigService()
|
||||||
this.contactCache = new ContactCacheService(config.get('cachePath') as string)
|
this.contactCache = new ContactCacheService(this.configService.get('cachePath') as string)
|
||||||
|
}
|
||||||
|
|
||||||
|
private getSnsCacheDir(): string {
|
||||||
|
const cachePath = this.configService.getCacheBasePath()
|
||||||
|
const snsCacheDir = join(cachePath, 'sns_cache')
|
||||||
|
if (!existsSync(snsCacheDir)) {
|
||||||
|
mkdirSync(snsCacheDir, { recursive: true })
|
||||||
|
}
|
||||||
|
return snsCacheDir
|
||||||
|
}
|
||||||
|
|
||||||
|
private getCacheFilePath(url: string): string {
|
||||||
|
const hash = crypto.createHash('md5').update(url).digest('hex')
|
||||||
|
const ext = isVideoUrl(url) ? '.mp4' : '.jpg'
|
||||||
|
return join(this.getSnsCacheDir(), `${hash}${ext}`)
|
||||||
}
|
}
|
||||||
|
|
||||||
async getTimeline(limit: number = 20, offset: number = 0, usernames?: string[], keyword?: string, startTime?: number, endTime?: number): Promise<{ success: boolean; timeline?: SnsPost[]; error?: string }> {
|
async getTimeline(limit: number = 20, offset: number = 0, usernames?: string[], keyword?: string, startTime?: number, endTime?: number): Promise<{ success: boolean; timeline?: SnsPost[]; error?: string }> {
|
||||||
|
|
||||||
|
|
||||||
const result = await wcdbService.getSnsTimeline(limit, offset, usernames, keyword, startTime, endTime)
|
const result = await wcdbService.getSnsTimeline(limit, offset, usernames, keyword, startTime, endTime)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
if (result.success && result.timeline) {
|
if (result.success && result.timeline) {
|
||||||
const enrichedTimeline = result.timeline.map((post: any, index: number) => {
|
const enrichedTimeline = result.timeline.map((post: any) => {
|
||||||
const contact = this.contactCache.get(post.username)
|
const contact = this.contactCache.get(post.username)
|
||||||
|
const isVideoPost = post.type === 15
|
||||||
|
|
||||||
// 修复媒体 URL
|
// 尝试从 rawXml 中提取视频解密密钥 (针对视频号视频)
|
||||||
const fixedMedia = post.media.map((m: any, mIdx: number) => {
|
const videoKey = extractVideoKey(post.rawXml || '')
|
||||||
const base = {
|
|
||||||
url: fixSnsUrl(m.url, m.token),
|
const fixedMedia = (post.media || []).map((m: any) => ({
|
||||||
thumb: fixSnsUrl(m.thumb, m.token),
|
// 如果是视频动态,url 是视频,thumb 是缩略图
|
||||||
md5: m.md5,
|
url: fixSnsUrl(m.url, m.token, isVideoPost),
|
||||||
token: m.token,
|
thumb: fixSnsUrl(m.thumb, m.token, false),
|
||||||
key: m.key,
|
md5: m.md5,
|
||||||
encIdx: m.encIdx || m.enc_idx, // 兼容不同命名
|
token: m.token,
|
||||||
livePhoto: m.livePhoto ? {
|
// 只有在视频动态 (Type 15) 下才尝试将 XML 提取的 videoKey 赋予主媒体
|
||||||
|
// 对于图片或实况照片的静态部分,应保留原始 m.key (由 DLL/DB 提供),避免由于错误的 Isaac64 密钥导致图片解密损坏
|
||||||
|
key: isVideoPost ? (videoKey || m.key) : m.key,
|
||||||
|
encIdx: m.encIdx || m.enc_idx,
|
||||||
|
livePhoto: m.livePhoto
|
||||||
|
? {
|
||||||
...m.livePhoto,
|
...m.livePhoto,
|
||||||
url: fixSnsUrl(m.livePhoto.url, m.livePhoto.token),
|
url: fixSnsUrl(m.livePhoto.url, m.livePhoto.token, true),
|
||||||
thumb: fixSnsUrl(m.livePhoto.thumb, m.livePhoto.token),
|
thumb: fixSnsUrl(m.livePhoto.thumb, m.livePhoto.token, false),
|
||||||
token: m.livePhoto.token,
|
token: m.livePhoto.token,
|
||||||
key: m.livePhoto.key
|
// 实况照片的视频部分优先使用从 XML 提取的 Key
|
||||||
} : undefined
|
key: videoKey || m.livePhoto.key || m.key,
|
||||||
}
|
encIdx: m.livePhoto.encIdx || m.livePhoto.enc_idx
|
||||||
|
|
||||||
// [MOCK] 模拟数据:如果后端没返回 key (说明 DLL 未更新),注入一些 Mock 数据以便前端开发
|
|
||||||
if (!base.key) {
|
|
||||||
base.key = 'mock_key_for_dev'
|
|
||||||
if (!base.token) {
|
|
||||||
base.token = 'mock_token_for_dev'
|
|
||||||
base.url = fixSnsUrl(base.url, base.token)
|
|
||||||
base.thumb = fixSnsUrl(base.thumb, base.token)
|
|
||||||
}
|
}
|
||||||
base.encIdx = '1'
|
: undefined
|
||||||
|
}))
|
||||||
// 强制给第一个帖子的第一张图加 LivePhoto 模拟
|
|
||||||
if (index === 0 && mIdx === 0 && !base.livePhoto) {
|
|
||||||
base.livePhoto = {
|
|
||||||
url: fixSnsUrl('https://tm.sh/d4cb0.mp4', 'mock_live_token'),
|
|
||||||
thumb: base.thumb,
|
|
||||||
token: 'mock_live_token',
|
|
||||||
key: 'mock_live_key'
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return base
|
|
||||||
})
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
...post,
|
...post,
|
||||||
@@ -116,20 +186,15 @@ class SnsService {
|
|||||||
media: fixedMedia
|
media: fixedMedia
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|
||||||
return { ...result, timeline: enrichedTimeline }
|
return { ...result, timeline: enrichedTimeline }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
return result
|
return result
|
||||||
}
|
}
|
||||||
|
|
||||||
async debugResource(url: string): Promise<{ success: boolean; status?: number; headers?: any; error?: string }> {
|
async debugResource(url: string): Promise<{ success: boolean; status?: number; headers?: any; error?: string }> {
|
||||||
return new Promise((resolve) => {
|
return new Promise((resolve) => {
|
||||||
try {
|
try {
|
||||||
const { app, net } = require('electron')
|
|
||||||
// Remove mocking 'require' if it causes issues, but here we need 'net' or 'https'
|
|
||||||
// implementing with 'https' for reliability if 'net' is main-process only special
|
|
||||||
const https = require('https')
|
const https = require('https')
|
||||||
const urlObj = new URL(url)
|
const urlObj = new URL(url)
|
||||||
|
|
||||||
@@ -138,13 +203,12 @@ class SnsService {
|
|||||||
path: urlObj.pathname + urlObj.search,
|
path: urlObj.pathname + urlObj.search,
|
||||||
method: 'GET',
|
method: 'GET',
|
||||||
headers: {
|
headers: {
|
||||||
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36 MicroMessenger/7.0.20.1781(0x6700143B) WindowsWechat(0x63090719) XWEB/8351",
|
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36 MicroMessenger/7.0.20.1781(0x6700143B) WindowsWechat(0x63090719) XWEB/8351',
|
||||||
"Accept": "image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8",
|
'Accept': 'image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8',
|
||||||
"Accept-Encoding": "gzip, deflate, br",
|
'Accept-Encoding': 'gzip, deflate, br',
|
||||||
"Accept-Language": "zh-CN,zh;q=0.9",
|
'Accept-Language': 'zh-CN,zh;q=0.9',
|
||||||
"Referer": "https://servicewechat.com/",
|
'Connection': 'keep-alive',
|
||||||
"Connection": "keep-alive",
|
'Range': 'bytes=0-10'
|
||||||
"Range": "bytes=0-10" // Keep our range check
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -154,17 +218,15 @@ class SnsService {
|
|||||||
status: res.statusCode,
|
status: res.statusCode,
|
||||||
headers: {
|
headers: {
|
||||||
'x-enc': res.headers['x-enc'],
|
'x-enc': res.headers['x-enc'],
|
||||||
|
'x-time': res.headers['x-time'],
|
||||||
'content-length': res.headers['content-length'],
|
'content-length': res.headers['content-length'],
|
||||||
'content-type': res.headers['content-type']
|
'content-type': res.headers['content-type']
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
req.destroy() // We only need headers
|
req.destroy()
|
||||||
})
|
|
||||||
|
|
||||||
req.on('error', (e: any) => {
|
|
||||||
resolve({ success: false, error: e.message })
|
|
||||||
})
|
})
|
||||||
|
|
||||||
|
req.on('error', (e: any) => resolve({ success: false, error: e.message }))
|
||||||
req.end()
|
req.end()
|
||||||
} catch (e: any) {
|
} catch (e: any) {
|
||||||
resolve({ success: false, error: e.message })
|
resolve({ success: false, error: e.message })
|
||||||
@@ -172,14 +234,162 @@ class SnsService {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
private imageCache = new Map<string, string>()
|
|
||||||
|
|
||||||
async proxyImage(url: string): Promise<{ success: boolean; dataUrl?: string; error?: string }> {
|
|
||||||
// Check cache
|
async proxyImage(url: string, key?: string | number): Promise<{ success: boolean; dataUrl?: string; videoPath?: string; error?: string }> {
|
||||||
if (this.imageCache.has(url)) {
|
if (!url) return { success: false, error: 'url 不能为空' }
|
||||||
return { success: true, dataUrl: this.imageCache.get(url) }
|
const cacheKey = `${url}|${key ?? ''}`
|
||||||
|
|
||||||
|
if (this.imageCache.has(cacheKey)) {
|
||||||
|
return { success: true, dataUrl: this.imageCache.get(cacheKey) }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const result = await this.fetchAndDecryptImage(url, key)
|
||||||
|
if (result.success) {
|
||||||
|
// 如果是视频,返回本地文件路径 (需配合 webSecurity: false 或自定义协议)
|
||||||
|
if (result.contentType?.startsWith('video/')) {
|
||||||
|
// Return cachePath directly for video
|
||||||
|
// 注意:fetchAndDecryptImage 需要修改以返回 cachePath
|
||||||
|
return { success: true, videoPath: result.cachePath }
|
||||||
|
}
|
||||||
|
|
||||||
|
if (result.data && result.contentType) {
|
||||||
|
const dataUrl = `data:${result.contentType};base64,${result.data.toString('base64')}`
|
||||||
|
this.imageCache.set(cacheKey, dataUrl)
|
||||||
|
return { success: true, dataUrl }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return { success: false, error: result.error }
|
||||||
|
}
|
||||||
|
|
||||||
|
async downloadImage(url: string, key?: string | number): Promise<{ success: boolean; data?: Buffer; contentType?: string; error?: string }> {
|
||||||
|
return this.fetchAndDecryptImage(url, key)
|
||||||
|
}
|
||||||
|
|
||||||
|
private async fetchAndDecryptImage(url: string, key?: string | number): Promise<{ success: boolean; data?: Buffer; contentType?: string; cachePath?: string; error?: string }> {
|
||||||
|
if (!url) return { success: false, error: 'url 不能为空' }
|
||||||
|
|
||||||
|
const isVideo = isVideoUrl(url)
|
||||||
|
const cachePath = this.getCacheFilePath(url)
|
||||||
|
|
||||||
|
// 1. 尝试从磁盘缓存读取
|
||||||
|
if (existsSync(cachePath)) {
|
||||||
|
try {
|
||||||
|
// 对于视频,不读取整个文件到内存,只确认存在即可
|
||||||
|
if (isVideo) {
|
||||||
|
return { success: true, cachePath, contentType: 'video/mp4' }
|
||||||
|
}
|
||||||
|
|
||||||
|
const data = await readFile(cachePath)
|
||||||
|
const contentType = detectImageMime(data)
|
||||||
|
return { success: true, data, contentType, cachePath }
|
||||||
|
} catch (e) {
|
||||||
|
console.warn(`[SnsService] 读取缓存失败: ${cachePath}`, e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isVideo) {
|
||||||
|
// 视频专用下载逻辑 (下载 -> 解密 -> 缓存)
|
||||||
|
return new Promise(async (resolve) => {
|
||||||
|
const tmpPath = join(require('os').tmpdir(), `sns_video_${Date.now()}_${Math.random().toString(36).slice(2)}.enc`)
|
||||||
|
|
||||||
|
try {
|
||||||
|
const https = require('https')
|
||||||
|
const urlObj = new URL(url)
|
||||||
|
const fs = require('fs')
|
||||||
|
|
||||||
|
const fileStream = fs.createWriteStream(tmpPath)
|
||||||
|
|
||||||
|
const options = {
|
||||||
|
hostname: urlObj.hostname,
|
||||||
|
path: urlObj.pathname + urlObj.search,
|
||||||
|
method: 'GET',
|
||||||
|
headers: {
|
||||||
|
'User-Agent': 'MicroMessenger Client',
|
||||||
|
'Accept': '*/*',
|
||||||
|
// 'Accept-Encoding': 'gzip, deflate, br', // 视频流通常不压缩,去掉以免 stream 处理复杂
|
||||||
|
'Connection': 'keep-alive'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const req = https.request(options, (res: any) => {
|
||||||
|
if (res.statusCode !== 200 && res.statusCode !== 206) {
|
||||||
|
fileStream.close()
|
||||||
|
fs.unlink(tmpPath, () => { }) // 删除临时文件
|
||||||
|
resolve({ success: false, error: `HTTP ${res.statusCode}` })
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
res.pipe(fileStream)
|
||||||
|
|
||||||
|
fileStream.on('finish', async () => {
|
||||||
|
fileStream.close()
|
||||||
|
|
||||||
|
try {
|
||||||
|
const encryptedBuffer = await readFile(tmpPath)
|
||||||
|
const raw = encryptedBuffer // 引用,方便后续操作
|
||||||
|
|
||||||
|
|
||||||
|
if (key && String(key).trim().length > 0) {
|
||||||
|
try {
|
||||||
|
const keyText = String(key).trim()
|
||||||
|
let keystream: Buffer
|
||||||
|
|
||||||
|
try {
|
||||||
|
const wasmService = WasmService.getInstance()
|
||||||
|
// 只需要前 128KB (131072 bytes) 用于解密头部
|
||||||
|
keystream = await wasmService.getKeystream(keyText, 131072)
|
||||||
|
} catch (wasmErr) {
|
||||||
|
// 打包漏带 wasm 或 wasm 初始化异常时,回退到纯 TS ISAAC64
|
||||||
|
const isaac = new Isaac64(keyText)
|
||||||
|
keystream = isaac.generateKeystreamBE(131072)
|
||||||
|
}
|
||||||
|
|
||||||
|
const decryptLen = Math.min(keystream.length, raw.length)
|
||||||
|
|
||||||
|
// XOR 解密
|
||||||
|
for (let i = 0; i < decryptLen; i++) {
|
||||||
|
raw[i] ^= keystream[i]
|
||||||
|
}
|
||||||
|
|
||||||
|
// 验证 MP4 签名 ('ftyp' at offset 4)
|
||||||
|
const ftyp = raw.subarray(4, 8).toString('ascii')
|
||||||
|
if (ftyp !== 'ftyp') {
|
||||||
|
// 可以在此处记录解密可能失败的标记,但不打印详细 hex
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
console.error(`[SnsService] 视频解密出错: ${err}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 写入最终缓存 (覆盖)
|
||||||
|
await writeFile(cachePath, raw)
|
||||||
|
|
||||||
|
// 删除临时文件
|
||||||
|
try { await import('fs/promises').then(fs => fs.unlink(tmpPath)) } catch (e) { }
|
||||||
|
|
||||||
|
resolve({ success: true, data: raw, contentType: 'video/mp4', cachePath })
|
||||||
|
} catch (e: any) {
|
||||||
|
console.error(`[SnsService] 视频处理失败:`, e)
|
||||||
|
resolve({ success: false, error: e.message })
|
||||||
|
}
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
req.on('error', (e: any) => {
|
||||||
|
fs.unlink(tmpPath, () => { })
|
||||||
|
resolve({ success: false, error: e.message })
|
||||||
|
})
|
||||||
|
|
||||||
|
req.end()
|
||||||
|
|
||||||
|
} catch (e: any) {
|
||||||
|
resolve({ success: false, error: e.message })
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// 图片逻辑 (保持流式处理)
|
||||||
return new Promise((resolve) => {
|
return new Promise((resolve) => {
|
||||||
try {
|
try {
|
||||||
const https = require('https')
|
const https = require('https')
|
||||||
@@ -191,17 +401,16 @@ class SnsService {
|
|||||||
path: urlObj.pathname + urlObj.search,
|
path: urlObj.pathname + urlObj.search,
|
||||||
method: 'GET',
|
method: 'GET',
|
||||||
headers: {
|
headers: {
|
||||||
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36 MicroMessenger/7.0.20.1781(0x6700143B) WindowsWechat(0x63090719) XWEB/8351",
|
'User-Agent': 'MicroMessenger Client',
|
||||||
"Accept": "image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8",
|
'Accept': '*/*',
|
||||||
"Accept-Encoding": "gzip, deflate, br",
|
'Accept-Encoding': 'gzip, deflate, br',
|
||||||
"Accept-Language": "zh-CN,zh;q=0.9",
|
'Accept-Language': 'zh-CN,zh;q=0.9',
|
||||||
"Referer": "https://servicewechat.com/",
|
'Connection': 'keep-alive'
|
||||||
"Connection": "keep-alive"
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const req = https.request(options, (res: any) => {
|
const req = https.request(options, (res: any) => {
|
||||||
if (res.statusCode !== 200) {
|
if (res.statusCode !== 200 && res.statusCode !== 206) {
|
||||||
resolve({ success: false, error: `HTTP ${res.statusCode}` })
|
resolve({ success: false, error: `HTTP ${res.statusCode}` })
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -209,37 +418,55 @@ class SnsService {
|
|||||||
const chunks: Buffer[] = []
|
const chunks: Buffer[] = []
|
||||||
let stream = res
|
let stream = res
|
||||||
|
|
||||||
// Handle gzip compression
|
|
||||||
const encoding = res.headers['content-encoding']
|
const encoding = res.headers['content-encoding']
|
||||||
if (encoding === 'gzip') {
|
if (encoding === 'gzip') stream = res.pipe(zlib.createGunzip())
|
||||||
stream = res.pipe(zlib.createGunzip())
|
else if (encoding === 'deflate') stream = res.pipe(zlib.createInflate())
|
||||||
} else if (encoding === 'deflate') {
|
else if (encoding === 'br') stream = res.pipe(zlib.createBrotliDecompress())
|
||||||
stream = res.pipe(zlib.createInflate())
|
|
||||||
} else if (encoding === 'br') {
|
|
||||||
stream = res.pipe(zlib.createBrotliDecompress())
|
|
||||||
}
|
|
||||||
|
|
||||||
stream.on('data', (chunk: Buffer) => chunks.push(chunk))
|
stream.on('data', (chunk: Buffer) => chunks.push(chunk))
|
||||||
stream.on('end', () => {
|
stream.on('end', async () => {
|
||||||
const buffer = Buffer.concat(chunks)
|
const raw = Buffer.concat(chunks)
|
||||||
const contentType = res.headers['content-type'] || 'image/jpeg'
|
const xEnc = String(res.headers['x-enc'] || '').trim()
|
||||||
const base64 = buffer.toString('base64')
|
|
||||||
const dataUrl = `data:${contentType};base64,${base64}`
|
|
||||||
|
|
||||||
// Cache
|
let decoded = raw
|
||||||
this.imageCache.set(url, dataUrl)
|
|
||||||
|
|
||||||
resolve({ success: true, dataUrl })
|
// 图片逻辑
|
||||||
})
|
const shouldDecrypt = (xEnc === '1' || !!key) && key !== undefined && key !== null && String(key).trim().length > 0
|
||||||
stream.on('error', (e: any) => {
|
if (shouldDecrypt) {
|
||||||
resolve({ success: false, error: e.message })
|
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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 写入磁盘缓存
|
||||||
|
try {
|
||||||
|
await writeFile(cachePath, decoded)
|
||||||
|
} catch (e) {
|
||||||
|
console.warn(`[SnsService] 写入缓存失败: ${cachePath}`, e)
|
||||||
|
}
|
||||||
|
|
||||||
|
const contentType = detectImageMime(decoded, (res.headers['content-type'] || 'image/jpeg') as string)
|
||||||
|
resolve({ success: true, data: decoded, contentType, cachePath })
|
||||||
})
|
})
|
||||||
|
stream.on('error', (e: any) => resolve({ success: false, error: e.message }))
|
||||||
})
|
})
|
||||||
|
|
||||||
req.on('error', (e: any) => {
|
req.on('error', (e: any) => resolve({ success: false, error: e.message }))
|
||||||
resolve({ success: false, error: e.message })
|
|
||||||
})
|
|
||||||
|
|
||||||
req.end()
|
req.end()
|
||||||
} catch (e: any) {
|
} catch (e: any) {
|
||||||
resolve({ success: false, error: e.message })
|
resolve({ success: false, error: e.message })
|
||||||
|
|||||||
@@ -36,7 +36,7 @@ class VideoService {
|
|||||||
* 获取缓存目录(解密后的数据库存放位置)
|
* 获取缓存目录(解密后的数据库存放位置)
|
||||||
*/
|
*/
|
||||||
private getCachePath(): string {
|
private getCachePath(): string {
|
||||||
return this.configService.get('cachePath') || ''
|
return this.configService.getCacheBasePath()
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
180
electron/services/wasmService.ts
Normal file
180
electron/services/wasmService.ts
Normal file
@@ -0,0 +1,180 @@
|
|||||||
|
|
||||||
|
import path from 'path';
|
||||||
|
import fs from 'fs';
|
||||||
|
import vm from 'vm';
|
||||||
|
|
||||||
|
let app: any;
|
||||||
|
try {
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
||||||
|
app = require('electron').app;
|
||||||
|
} catch (e) {
|
||||||
|
app = { isPackaged: false };
|
||||||
|
}
|
||||||
|
|
||||||
|
// This service handles the loading and execution of the WeChat WASM module
|
||||||
|
// to generate the correct Isaac64 keystream for video decryption.
|
||||||
|
export class WasmService {
|
||||||
|
private static instance: WasmService;
|
||||||
|
private module: any = null;
|
||||||
|
private wasmLoaded = false;
|
||||||
|
private initPromise: Promise<void> | null = null;
|
||||||
|
private capturedKeystream: Uint8Array | null = null;
|
||||||
|
|
||||||
|
private constructor() { }
|
||||||
|
|
||||||
|
public static getInstance(): WasmService {
|
||||||
|
if (!WasmService.instance) {
|
||||||
|
WasmService.instance = new WasmService();
|
||||||
|
}
|
||||||
|
return WasmService.instance;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async init(): Promise<void> {
|
||||||
|
if (this.wasmLoaded) return;
|
||||||
|
if (this.initPromise) return this.initPromise;
|
||||||
|
|
||||||
|
this.initPromise = new Promise((resolve, reject) => {
|
||||||
|
try {
|
||||||
|
// For dev, files are in electron/assets/wasm
|
||||||
|
// __dirname in dev (from dist-electron) is .../dist-electron
|
||||||
|
// So we need to go up one level and then into electron/assets/wasm
|
||||||
|
const isDev = !app.isPackaged;
|
||||||
|
const basePath = isDev
|
||||||
|
? path.join(__dirname, '../electron/assets/wasm')
|
||||||
|
: path.join(process.resourcesPath, 'assets/wasm'); // Adjust as needed for production build
|
||||||
|
|
||||||
|
const wasmPath = path.join(basePath, 'wasm_video_decode.wasm');
|
||||||
|
const jsPath = path.join(basePath, 'wasm_video_decode.js');
|
||||||
|
|
||||||
|
|
||||||
|
if (!fs.existsSync(wasmPath) || !fs.existsSync(jsPath)) {
|
||||||
|
throw new Error(`WASM files not found at ${basePath}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const wasmBinary = fs.readFileSync(wasmPath);
|
||||||
|
|
||||||
|
// Emulate Emscripten environment
|
||||||
|
// We must use 'any' for global mocking
|
||||||
|
const mockGlobal: any = {
|
||||||
|
console: console,
|
||||||
|
Buffer: Buffer,
|
||||||
|
Uint8Array: Uint8Array,
|
||||||
|
Int8Array: Int8Array,
|
||||||
|
Uint16Array: Uint16Array,
|
||||||
|
Int16Array: Int16Array,
|
||||||
|
Uint32Array: Uint32Array,
|
||||||
|
Int32Array: Int32Array,
|
||||||
|
Float32Array: Float32Array,
|
||||||
|
Float64Array: Float64Array,
|
||||||
|
BigInt64Array: BigInt64Array,
|
||||||
|
BigUint64Array: BigUint64Array,
|
||||||
|
Array: Array,
|
||||||
|
Object: Object,
|
||||||
|
Function: Function,
|
||||||
|
String: String,
|
||||||
|
Number: Number,
|
||||||
|
Boolean: Boolean,
|
||||||
|
Error: Error,
|
||||||
|
Promise: Promise,
|
||||||
|
require: require,
|
||||||
|
process: process,
|
||||||
|
setTimeout: setTimeout,
|
||||||
|
clearTimeout: clearTimeout,
|
||||||
|
setInterval: setInterval,
|
||||||
|
clearInterval: clearInterval,
|
||||||
|
};
|
||||||
|
|
||||||
|
// Define Module
|
||||||
|
mockGlobal.Module = {
|
||||||
|
onRuntimeInitialized: () => {
|
||||||
|
this.wasmLoaded = true;
|
||||||
|
resolve();
|
||||||
|
},
|
||||||
|
wasmBinary: wasmBinary,
|
||||||
|
print: (text: string) => console.log('[WASM stdout]', text),
|
||||||
|
printErr: (text: string) => console.error('[WASM stderr]', text)
|
||||||
|
};
|
||||||
|
|
||||||
|
// Define necessary globals for Emscripten loader
|
||||||
|
mockGlobal.self = mockGlobal;
|
||||||
|
mockGlobal.self.location = { href: jsPath };
|
||||||
|
mockGlobal.WorkerGlobalScope = function () { };
|
||||||
|
mockGlobal.VTS_WASM_URL = `file://${wasmPath}`; // Needs a URL, file protocol works in Node context for our mock?
|
||||||
|
|
||||||
|
// Define the callback function that WASM calls to return data
|
||||||
|
// The WASM module calls `wasm_isaac_generate(ptr, size)`
|
||||||
|
mockGlobal.wasm_isaac_generate = (ptr: number, size: number) => {
|
||||||
|
// console.log(`[WasmService] wasm_isaac_generate called: ptr=${ptr}, size=${size}`);
|
||||||
|
const buffer = new Uint8Array(mockGlobal.Module.HEAPU8.buffer, ptr, size);
|
||||||
|
// Copy the data because WASM memory might change or be invalidated
|
||||||
|
this.capturedKeystream = new Uint8Array(buffer);
|
||||||
|
};
|
||||||
|
|
||||||
|
// Execute the loader script in the context
|
||||||
|
const jsContent = fs.readFileSync(jsPath, 'utf8');
|
||||||
|
const script = new vm.Script(jsContent, { filename: jsPath });
|
||||||
|
|
||||||
|
// create context
|
||||||
|
const context = vm.createContext(mockGlobal);
|
||||||
|
script.runInContext(context);
|
||||||
|
|
||||||
|
// Store reference to module
|
||||||
|
this.module = mockGlobal.Module;
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
console.error('[WasmService] Failed to initialize WASM:', error);
|
||||||
|
reject(error);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
return this.initPromise;
|
||||||
|
}
|
||||||
|
|
||||||
|
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) {
|
||||||
|
if (this.module.asm && this.module.asm.WxIsaac64) {
|
||||||
|
this.module.WxIsaac64 = this.module.asm.WxIsaac64;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!this.module.WxIsaac64) {
|
||||||
|
throw new Error('[WasmService] WxIsaac64 not found in WASM module');
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
this.capturedKeystream = null;
|
||||||
|
const isaac = new this.module.WxIsaac64(key);
|
||||||
|
isaac.generate(size);
|
||||||
|
|
||||||
|
if (isaac.delete) {
|
||||||
|
isaac.delete();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (this.capturedKeystream) {
|
||||||
|
return Buffer.from(this.capturedKeystream);
|
||||||
|
} else {
|
||||||
|
throw new Error('[WasmService] Failed to capture keystream (callback not called)');
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('[WasmService] Error generating raw keystream:', error);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -27,6 +27,8 @@ export class WcdbCore {
|
|||||||
private wcdbCloseAccount: any = null
|
private wcdbCloseAccount: any = null
|
||||||
private wcdbSetMyWxid: any = null
|
private wcdbSetMyWxid: any = null
|
||||||
private wcdbFreeString: any = null
|
private wcdbFreeString: any = null
|
||||||
|
private wcdbUpdateMessage: any = null
|
||||||
|
private wcdbDeleteMessage: any = null
|
||||||
private wcdbGetSessions: any = null
|
private wcdbGetSessions: any = null
|
||||||
private wcdbGetMessages: any = null
|
private wcdbGetMessages: any = null
|
||||||
private wcdbGetMessageCount: any = null
|
private wcdbGetMessageCount: any = null
|
||||||
@@ -64,8 +66,10 @@ export class WcdbCore {
|
|||||||
private wcdbVerifyUser: any = null
|
private wcdbVerifyUser: any = null
|
||||||
private wcdbStartMonitorPipe: any = null
|
private wcdbStartMonitorPipe: any = null
|
||||||
private wcdbStopMonitorPipe: any = null
|
private wcdbStopMonitorPipe: any = null
|
||||||
|
|
||||||
private monitorPipeClient: any = null
|
private monitorPipeClient: any = null
|
||||||
|
|
||||||
|
|
||||||
private avatarUrlCache: Map<string, { url?: string; updatedAt: number }> = new Map()
|
private avatarUrlCache: Map<string, { url?: string; updatedAt: number }> = new Map()
|
||||||
private readonly avatarCacheTtlMs = 10 * 60 * 1000
|
private readonly avatarCacheTtlMs = 10 * 60 * 1000
|
||||||
private logTimer: NodeJS.Timeout | null = null
|
private logTimer: NodeJS.Timeout | null = null
|
||||||
@@ -137,11 +141,13 @@ export class WcdbCore {
|
|||||||
this.writeLog('Monitor started via named pipe IPC')
|
this.writeLog('Monitor started via named pipe IPC')
|
||||||
return true
|
return true
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error('startMonitor failed:', e)
|
console.error('打开数据库异常:', e)
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
stopMonitor(): void {
|
stopMonitor(): void {
|
||||||
if (this.monitorPipeClient) {
|
if (this.monitorPipeClient) {
|
||||||
this.monitorPipeClient.destroy()
|
this.monitorPipeClient.destroy()
|
||||||
@@ -381,6 +387,20 @@ export class WcdbCore {
|
|||||||
this.wcdbSetMyWxid = null
|
this.wcdbSetMyWxid = null
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// wcdb_status wcdb_update_message(wcdb_handle handle, const char* session_id, int64_t local_id, const char* new_content, char** out_error)
|
||||||
|
try {
|
||||||
|
this.wcdbUpdateMessage = this.lib.func('int32 wcdb_update_message(int64 handle, const char* sessionId, int64 localId, 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)
|
// void wcdb_free_string(char* ptr)
|
||||||
this.wcdbFreeString = this.lib.func('void wcdb_free_string(void* ptr)')
|
this.wcdbFreeString = this.lib.func('void wcdb_free_string(void* ptr)')
|
||||||
|
|
||||||
@@ -563,6 +583,8 @@ export class WcdbCore {
|
|||||||
this.wcdbVerifyUser = null
|
this.wcdbVerifyUser = null
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
// 初始化
|
// 初始化
|
||||||
const initResult = this.wcdbInit()
|
const initResult = this.wcdbInit()
|
||||||
if (initResult !== 0) {
|
if (initResult !== 0) {
|
||||||
@@ -1768,4 +1790,62 @@ export class WcdbCore {
|
|||||||
return { success: false, error: String(e) }
|
return { success: false, error: String(e) }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
/**
|
||||||
|
* 修改消息内容
|
||||||
|
*/
|
||||||
|
async updateMessage(sessionId: string, localId: 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, 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) })
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -431,6 +431,22 @@ export class WcdbService {
|
|||||||
return this.callWorker('verifyUser', { message, hwnd })
|
return this.callWorker('verifyUser', { message, hwnd })
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 修改消息内容
|
||||||
|
*/
|
||||||
|
async updateMessage(sessionId: string, localId: number, newContent: string): Promise<{ success: boolean; error?: string }> {
|
||||||
|
return this.callWorker('updateMessage', { sessionId, localId, 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()
|
export const wcdbService = new WcdbService()
|
||||||
|
|||||||
@@ -150,6 +150,13 @@ if (parentPort) {
|
|||||||
case 'verifyUser':
|
case 'verifyUser':
|
||||||
result = await core.verifyUser(payload.message, payload.hwnd)
|
result = await core.verifyUser(payload.message, payload.hwnd)
|
||||||
break
|
break
|
||||||
|
case 'updateMessage':
|
||||||
|
result = await core.updateMessage(payload.sessionId, payload.localId, payload.newContent)
|
||||||
|
break
|
||||||
|
case 'deleteMessage':
|
||||||
|
result = await core.deleteMessage(payload.sessionId, payload.localId, payload.createTime, payload.dbPathHint)
|
||||||
|
break
|
||||||
|
|
||||||
default:
|
default:
|
||||||
result = { success: false, error: `Unknown method: ${type}` }
|
result = { success: false, error: `Unknown method: ${type}` }
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -76,12 +76,10 @@ export async function showNotification(data: any) {
|
|||||||
const isInList = filterList.includes(sessionId)
|
const isInList = filterList.includes(sessionId)
|
||||||
if (filterMode === 'whitelist' && !isInList) {
|
if (filterMode === 'whitelist' && !isInList) {
|
||||||
// 白名单模式:不在列表中则不显示
|
// 白名单模式:不在列表中则不显示
|
||||||
console.log('[NotificationWindow] Filtered by whitelist:', sessionId)
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if (filterMode === 'blacklist' && isInList) {
|
if (filterMode === 'blacklist' && isInList) {
|
||||||
// 黑名单模式:在列表中则不显示
|
// 黑名单模式:在列表中则不显示
|
||||||
console.log('[NotificationWindow] Filtered by blacklist:', sessionId)
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
4
package-lock.json
generated
4
package-lock.json
generated
@@ -1,12 +1,12 @@
|
|||||||
{
|
{
|
||||||
"name": "weflow",
|
"name": "weflow",
|
||||||
"version": "1.5.4",
|
"version": "2.0.1",
|
||||||
"lockfileVersion": 3,
|
"lockfileVersion": 3,
|
||||||
"requires": true,
|
"requires": true,
|
||||||
"packages": {
|
"packages": {
|
||||||
"": {
|
"": {
|
||||||
"name": "weflow",
|
"name": "weflow",
|
||||||
"version": "1.5.4",
|
"version": "2.0.1",
|
||||||
"hasInstallScript": true,
|
"hasInstallScript": true,
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"better-sqlite3": "^12.5.0",
|
"better-sqlite3": "^12.5.0",
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "weflow",
|
"name": "weflow",
|
||||||
"version": "1.5.4",
|
"version": "2.0.1",
|
||||||
"description": "WeFlow",
|
"description": "WeFlow",
|
||||||
"main": "dist-electron/main.js",
|
"main": "dist-electron/main.js",
|
||||||
"author": "cc",
|
"author": "cc",
|
||||||
@@ -10,7 +10,7 @@
|
|||||||
},
|
},
|
||||||
"//": "二改不应改变此处的作者与应用信息",
|
"//": "二改不应改变此处的作者与应用信息",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"postinstall": "echo 'No native modules to rebuild'",
|
"postinstall": "electron-builder install-app-deps",
|
||||||
"rebuild": "electron-rebuild",
|
"rebuild": "electron-rebuild",
|
||||||
"dev": "vite",
|
"dev": "vite",
|
||||||
"build": "tsc && vite build && electron-builder",
|
"build": "tsc && vite build && electron-builder",
|
||||||
@@ -107,6 +107,10 @@
|
|||||||
{
|
{
|
||||||
"from": "public/icon.ico",
|
"from": "public/icon.ico",
|
||||||
"to": "icon.ico"
|
"to": "icon.ico"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"from": "electron/assets/wasm/",
|
||||||
|
"to": "assets/wasm/"
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"files": [
|
"files": [
|
||||||
|
|||||||
Binary file not shown.
@@ -20,6 +20,15 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.preview-content {
|
||||||
|
position: relative;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
width: fit-content;
|
||||||
|
height: fit-content;
|
||||||
|
}
|
||||||
|
|
||||||
.image-preview-close {
|
.image-preview-close {
|
||||||
position: absolute;
|
position: absolute;
|
||||||
bottom: 40px;
|
bottom: 40px;
|
||||||
@@ -44,3 +53,38 @@
|
|||||||
transform: translateX(-50%) scale(1.1);
|
transform: translateX(-50%) scale(1.1);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.live-photo-btn {
|
||||||
|
position: absolute;
|
||||||
|
top: 15px;
|
||||||
|
right: 15px;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 8px;
|
||||||
|
padding: 6px 12px;
|
||||||
|
border-radius: 16px;
|
||||||
|
background: rgba(0, 0, 0, 0.5);
|
||||||
|
color: #fff;
|
||||||
|
border: 1px solid rgba(255, 255, 255, 0.2);
|
||||||
|
cursor: pointer;
|
||||||
|
backdrop-filter: blur(10px);
|
||||||
|
transition: all 0.2s;
|
||||||
|
z-index: 10000;
|
||||||
|
|
||||||
|
&:hover {
|
||||||
|
background: rgba(255, 255, 255, 0.1);
|
||||||
|
border-color: rgba(255, 255, 255, 0.4);
|
||||||
|
transform: translateY(-2px);
|
||||||
|
}
|
||||||
|
|
||||||
|
&.active {
|
||||||
|
background: var(--accent-color, #007aff);
|
||||||
|
border-color: transparent;
|
||||||
|
box-shadow: 0 4px 12px rgba(0, 122, 255, 0.3);
|
||||||
|
}
|
||||||
|
|
||||||
|
span {
|
||||||
|
font-size: 14px;
|
||||||
|
font-weight: 500;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,36 +1,41 @@
|
|||||||
import React, { useState, useRef, useCallback, useEffect } from 'react'
|
import React, { useState, useRef, useCallback, useEffect } from 'react'
|
||||||
import { X } from 'lucide-react'
|
import { X } from 'lucide-react'
|
||||||
|
import { LivePhotoIcon } from './LivePhotoIcon'
|
||||||
import { createPortal } from 'react-dom'
|
import { createPortal } from 'react-dom'
|
||||||
import './ImagePreview.scss'
|
import './ImagePreview.scss'
|
||||||
|
|
||||||
interface ImagePreviewProps {
|
interface ImagePreviewProps {
|
||||||
src: string
|
src: string
|
||||||
|
isVideo?: boolean
|
||||||
|
liveVideoPath?: string
|
||||||
onClose: () => void
|
onClose: () => void
|
||||||
}
|
}
|
||||||
|
|
||||||
export const ImagePreview: React.FC<ImagePreviewProps> = ({ src, onClose }) => {
|
export const ImagePreview: React.FC<ImagePreviewProps> = ({ src, isVideo, liveVideoPath, onClose }) => {
|
||||||
const [scale, setScale] = useState(1)
|
const [scale, setScale] = useState(1)
|
||||||
const [position, setPosition] = useState({ x: 0, y: 0 })
|
const [position, setPosition] = useState({ x: 0, y: 0 })
|
||||||
const [isDragging, setIsDragging] = useState(false)
|
const [isDragging, setIsDragging] = useState(false)
|
||||||
|
const [showLive, setShowLive] = useState(false)
|
||||||
const dragStart = useRef({ x: 0, y: 0 })
|
const dragStart = useRef({ x: 0, y: 0 })
|
||||||
const positionStart = useRef({ x: 0, y: 0 })
|
const positionStart = useRef({ x: 0, y: 0 })
|
||||||
const containerRef = useRef<HTMLDivElement>(null)
|
const containerRef = useRef<HTMLDivElement>(null)
|
||||||
|
|
||||||
// 滚轮缩放
|
// 滚轮缩放
|
||||||
const handleWheel = useCallback((e: React.WheelEvent) => {
|
const handleWheel = useCallback((e: React.WheelEvent) => {
|
||||||
|
if (showLive) return // 播放实况时禁止缩放? 或者支持缩放? 暂定禁止以简化
|
||||||
e.preventDefault()
|
e.preventDefault()
|
||||||
const delta = e.deltaY > 0 ? 0.9 : 1.1
|
const delta = e.deltaY > 0 ? 0.9 : 1.1
|
||||||
setScale(prev => Math.min(Math.max(prev * delta, 0.5), 5))
|
setScale(prev => Math.min(Math.max(prev * delta, 0.5), 5))
|
||||||
}, [])
|
}, [showLive])
|
||||||
|
|
||||||
// 开始拖动
|
// 开始拖动
|
||||||
const handleMouseDown = useCallback((e: React.MouseEvent) => {
|
const handleMouseDown = useCallback((e: React.MouseEvent) => {
|
||||||
if (scale <= 1) return
|
if (showLive || scale <= 1) return
|
||||||
e.preventDefault()
|
e.preventDefault()
|
||||||
setIsDragging(true)
|
setIsDragging(true)
|
||||||
dragStart.current = { x: e.clientX, y: e.clientY }
|
dragStart.current = { x: e.clientX, y: e.clientY }
|
||||||
positionStart.current = { ...position }
|
positionStart.current = { ...position }
|
||||||
}, [scale, position])
|
}, [scale, position, showLive])
|
||||||
|
|
||||||
// 拖动中
|
// 拖动中
|
||||||
const handleMouseMove = useCallback((e: React.MouseEvent) => {
|
const handleMouseMove = useCallback((e: React.MouseEvent) => {
|
||||||
@@ -79,19 +84,62 @@ export const ImagePreview: React.FC<ImagePreviewProps> = ({ src, onClose }) => {
|
|||||||
onMouseUp={handleMouseUp}
|
onMouseUp={handleMouseUp}
|
||||||
onMouseLeave={handleMouseUp}
|
onMouseLeave={handleMouseUp}
|
||||||
>
|
>
|
||||||
<img
|
<div
|
||||||
src={src}
|
className="preview-content"
|
||||||
alt="图片预览"
|
|
||||||
className={`preview-image ${isDragging ? 'dragging' : ''}`}
|
|
||||||
style={{
|
style={{
|
||||||
transform: `translate(${position.x}px, ${position.y}px) scale(${scale})`,
|
position: 'relative',
|
||||||
cursor: scale > 1 ? (isDragging ? 'grabbing' : 'grab') : 'default'
|
transform: `translate(${position.x}px, ${position.y}px)`,
|
||||||
|
width: 'fit-content',
|
||||||
|
height: 'fit-content'
|
||||||
}}
|
}}
|
||||||
onWheel={handleWheel}
|
onClick={(e) => e.stopPropagation()}
|
||||||
onMouseDown={handleMouseDown}
|
>
|
||||||
onDoubleClick={handleDoubleClick}
|
{(isVideo || showLive) ? (
|
||||||
draggable={false}
|
<video
|
||||||
/>
|
src={showLive ? liveVideoPath : src}
|
||||||
|
controls={!showLive}
|
||||||
|
autoPlay
|
||||||
|
loop={showLive}
|
||||||
|
className="preview-image"
|
||||||
|
style={{
|
||||||
|
transform: `scale(${scale})`,
|
||||||
|
maxHeight: '90vh',
|
||||||
|
maxWidth: '90vw'
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
|
<img
|
||||||
|
src={src}
|
||||||
|
alt="图片预览"
|
||||||
|
className={`preview-image ${isDragging ? 'dragging' : ''}`}
|
||||||
|
style={{
|
||||||
|
transform: `scale(${scale})`,
|
||||||
|
maxHeight: '90vh',
|
||||||
|
maxWidth: '90vw',
|
||||||
|
cursor: scale > 1 ? (isDragging ? 'grabbing' : 'grab') : 'default'
|
||||||
|
}}
|
||||||
|
onWheel={handleWheel}
|
||||||
|
onMouseDown={handleMouseDown}
|
||||||
|
onDoubleClick={handleDoubleClick}
|
||||||
|
draggable={false}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{liveVideoPath && !isVideo && (
|
||||||
|
<button
|
||||||
|
className={`live-photo-btn ${showLive ? 'active' : ''}`}
|
||||||
|
onClick={(e) => {
|
||||||
|
e.stopPropagation()
|
||||||
|
setShowLive(!showLive)
|
||||||
|
}}
|
||||||
|
title={showLive ? "显示照片" : "播放实况"}
|
||||||
|
>
|
||||||
|
<LivePhotoIcon size={20} />
|
||||||
|
<span>实况</span>
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
<button className="image-preview-close" onClick={onClose}>
|
<button className="image-preview-close" onClick={onClose}>
|
||||||
<X size={20} />
|
<X size={20} />
|
||||||
</button>
|
</button>
|
||||||
|
|||||||
@@ -482,11 +482,41 @@
|
|||||||
margin-top: 16px;
|
margin-top: 16px;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.exclude-footer-left {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
.exclude-count {
|
.exclude-count {
|
||||||
font-size: 12px;
|
font-size: 12px;
|
||||||
color: var(--text-tertiary);
|
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 {
|
.exclude-actions {
|
||||||
display: flex;
|
display: flex;
|
||||||
gap: 8px;
|
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 handleApplyExcluded = async () => {
|
||||||
const payload = Array.from(draftExcluded)
|
const payload = Array.from(draftExcluded)
|
||||||
setIsExcludeDialogOpen(false)
|
setIsExcludeDialogOpen(false)
|
||||||
@@ -493,7 +504,12 @@ function AnalyticsPage() {
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
<div className="exclude-modal-footer">
|
<div className="exclude-modal-footer">
|
||||||
<span className="exclude-count">已排除 {draftExcluded.size} 人</span>
|
<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">
|
<div className="exclude-actions">
|
||||||
<button className="btn btn-secondary" onClick={() => setIsExcludeDialogOpen(false)}>
|
<button className="btn btn-secondary" onClick={() => setIsExcludeDialogOpen(false)}>
|
||||||
取消
|
取消
|
||||||
|
|||||||
@@ -1,8 +1,214 @@
|
|||||||
.chat-page {
|
.chat-page {
|
||||||
|
position: relative;
|
||||||
display: flex;
|
display: flex;
|
||||||
height: 100%;
|
height: 100%;
|
||||||
gap: 16px;
|
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 特色风格(使用主题变量)
|
// 独立窗口模式 - EchoTrace 特色风格(使用主题变量)
|
||||||
&.standalone {
|
&.standalone {
|
||||||
height: 100vh;
|
height: 100vh;
|
||||||
@@ -2511,6 +2717,7 @@
|
|||||||
|
|
||||||
// 发送消息中的特殊消息类型适配(除了文件和转账)
|
// 发送消息中的特殊消息类型适配(除了文件和转账)
|
||||||
.message-bubble.sent {
|
.message-bubble.sent {
|
||||||
|
|
||||||
.card-message,
|
.card-message,
|
||||||
.chat-record-message,
|
.chat-record-message,
|
||||||
.miniapp-message {
|
.miniapp-message {
|
||||||
@@ -2616,6 +2823,7 @@
|
|||||||
&:hover:not(:disabled) {
|
&:hover:not(:disabled) {
|
||||||
color: var(--primary-color);
|
color: var(--primary-color);
|
||||||
}
|
}
|
||||||
|
|
||||||
&.transcribing {
|
&.transcribing {
|
||||||
color: var(--primary-color);
|
color: var(--primary-color);
|
||||||
cursor: pointer;
|
cursor: pointer;
|
||||||
@@ -2637,7 +2845,9 @@
|
|||||||
padding: 1.5rem;
|
padding: 1.5rem;
|
||||||
border-bottom: 1px solid var(--border-color);
|
border-bottom: 1px solid var(--border-color);
|
||||||
|
|
||||||
svg { color: var(--primary-color); }
|
svg {
|
||||||
|
color: var(--primary-color);
|
||||||
|
}
|
||||||
|
|
||||||
h3 {
|
h3 {
|
||||||
margin: 0;
|
margin: 0;
|
||||||
@@ -2697,7 +2907,10 @@
|
|||||||
|
|
||||||
li {
|
li {
|
||||||
border-bottom: 1px solid var(--border-color);
|
border-bottom: 1px solid var(--border-color);
|
||||||
&:last-child { border-bottom: none; }
|
|
||||||
|
&:last-child {
|
||||||
|
border-bottom: none;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
.batch-date-row {
|
.batch-date-row {
|
||||||
@@ -2708,7 +2921,9 @@
|
|||||||
cursor: pointer;
|
cursor: pointer;
|
||||||
transition: background 0.15s;
|
transition: background 0.15s;
|
||||||
|
|
||||||
&:hover { background: var(--bg-hover); }
|
&:hover {
|
||||||
|
background: var(--bg-hover);
|
||||||
|
}
|
||||||
|
|
||||||
input[type="checkbox"] {
|
input[type="checkbox"] {
|
||||||
accent-color: var(--primary-color);
|
accent-color: var(--primary-color);
|
||||||
@@ -2806,13 +3021,185 @@
|
|||||||
&.btn-secondary {
|
&.btn-secondary {
|
||||||
background: var(--bg-tertiary);
|
background: var(--bg-tertiary);
|
||||||
color: var(--text-primary);
|
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);
|
background: var(--primary-color);
|
||||||
color: white;
|
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 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 { useNavigate } from 'react-router-dom'
|
||||||
import { createPortal } from 'react-dom'
|
import { createPortal } from 'react-dom'
|
||||||
import { useChatStore } from '../stores/chatStore'
|
import { useChatStore } from '../stores/chatStore'
|
||||||
@@ -18,6 +18,102 @@ const SYSTEM_MESSAGE_TYPES = [
|
|||||||
266287972401, // 拍一拍
|
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 {
|
function isSystemMessage(localType: number): boolean {
|
||||||
return SYSTEM_MESSAGE_TYPES.includes(localType)
|
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]
|
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 {
|
interface ChatPageProps {
|
||||||
// 保留接口以备将来扩展
|
// 保留接口以备将来扩展
|
||||||
}
|
}
|
||||||
@@ -182,6 +284,18 @@ function ChatPage(_props: ChatPageProps) {
|
|||||||
const [showVoiceTranscribeDialog, setShowVoiceTranscribeDialog] = useState(false)
|
const [showVoiceTranscribeDialog, setShowVoiceTranscribeDialog] = useState(false)
|
||||||
const [pendingVoiceTranscriptRequest, setPendingVoiceTranscriptRequest] = useState<{ sessionId: string; messageId: string } | null>(null)
|
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 管理)
|
// 批量语音转文字相关状态(进度/结果 由全局 store 管理)
|
||||||
const { isBatchTranscribing, progress: batchTranscribeProgress, showToast: showBatchProgress, startTranscribe, updateProgress, finishTranscribe, setShowToast: setShowBatchProgress } = useBatchTranscribeStore()
|
const { isBatchTranscribing, progress: batchTranscribeProgress, showToast: showBatchProgress, startTranscribe, updateProgress, finishTranscribe, setShowToast: setShowBatchProgress } = useBatchTranscribeStore()
|
||||||
const [showBatchConfirm, setShowBatchConfirm] = useState(false)
|
const [showBatchConfirm, setShowBatchConfirm] = useState(false)
|
||||||
@@ -190,6 +304,19 @@ function ChatPage(_props: ChatPageProps) {
|
|||||||
const [batchVoiceDates, setBatchVoiceDates] = useState<string[]>([])
|
const [batchVoiceDates, setBatchVoiceDates] = useState<string[]>([])
|
||||||
const [batchSelectedDates, setBatchSelectedDates] = useState<Set<string>>(new Set())
|
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 isEnrichingRef = useRef(false)
|
||||||
const enrichCancelledRef = useRef(false)
|
const enrichCancelledRef = useRef(false)
|
||||||
@@ -1394,13 +1521,302 @@ function ChatPage(_props: ChatPageProps) {
|
|||||||
const selectAllBatchDates = useCallback(() => setBatchSelectedDates(new Set(batchVoiceDates)), [batchVoiceDates])
|
const selectAllBatchDates = useCallback(() => setBatchSelectedDates(new Set(batchVoiceDates)), [batchVoiceDates])
|
||||||
const clearAllBatchDates = useCallback(() => setBatchSelectedDates(new Set()), [])
|
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 formatBatchDateLabel = useCallback((dateStr: string) => {
|
||||||
const [y, m, d] = dateStr.split('-').map(Number)
|
const [y, m, d] = dateStr.split('-').map(Number)
|
||||||
return `${y}年${m}月${d}日`
|
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, 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 (
|
return (
|
||||||
<div className={`chat-page ${isResizing ? 'resizing' : ''}`}>
|
<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
|
<div
|
||||||
className="session-sidebar"
|
className="session-sidebar"
|
||||||
@@ -1659,6 +2075,10 @@ function ChatPage(_props: ChatPageProps) {
|
|||||||
myAvatarUrl={myAvatarUrl}
|
myAvatarUrl={myAvatarUrl}
|
||||||
isGroupChat={isGroupChat(currentSession.username)}
|
isGroupChat={isGroupChat(currentSession.username)}
|
||||||
onRequireModelDownload={handleRequireModelDownload}
|
onRequireModelDownload={handleRequireModelDownload}
|
||||||
|
onContextMenu={handleContextMenu}
|
||||||
|
isSelectionMode={isSelectionMode}
|
||||||
|
isSelected={selectedMessages.has(msg.localId)}
|
||||||
|
onToggleSelection={handleToggleSelection}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
@@ -1897,6 +2317,187 @@ function ChatPage(_props: ChatPageProps) {
|
|||||||
</div>,
|
</div>,
|
||||||
document.body
|
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>
|
</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>>()
|
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;
|
message: Message;
|
||||||
session: ChatSession;
|
session: ChatSession;
|
||||||
showTime?: boolean;
|
showTime?: boolean;
|
||||||
myAvatarUrl?: string;
|
myAvatarUrl?: string;
|
||||||
isGroupChat?: boolean;
|
isGroupChat?: boolean;
|
||||||
onRequireModelDownload?: (sessionId: string, messageId: string) => void;
|
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 isSystem = isSystemMessage(message.localType)
|
||||||
const isEmoji = message.localType === 47
|
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 [senderName, setSenderName] = useState<string | undefined>(undefined)
|
||||||
const [emojiError, setEmojiError] = useState(false)
|
const [emojiError, setEmojiError] = useState(false)
|
||||||
const [emojiLoading, setEmojiLoading] = useState(false)
|
const [emojiLoading, setEmojiLoading] = useState(false)
|
||||||
|
|
||||||
|
// State variables...
|
||||||
const [imageError, setImageError] = useState(false)
|
const [imageError, setImageError] = useState(false)
|
||||||
const [imageLoading, setImageLoading] = useState(false)
|
const [imageLoading, setImageLoading] = useState(false)
|
||||||
const [imageHasUpdate, setImageHasUpdate] = useState(false)
|
const [imageHasUpdate, setImageHasUpdate] = useState(false)
|
||||||
@@ -2643,9 +3261,39 @@ function MessageBubble({ message, session, showTime, myAvatarUrl, isGroupChat, o
|
|||||||
void requestVoiceTranscript()
|
void requestVoiceTranscript()
|
||||||
}, [autoTranscribeEnabled, isVoice, voiceDataUrl, voiceTranscript, voiceTranscriptError, voiceTranscriptLoading, 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) {
|
if (isSystem) {
|
||||||
return (
|
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 className="bubble-content">{message.parsedContent}</div>
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
@@ -3344,27 +3992,81 @@ function MessageBubble({ message, session, showTime, myAvatarUrl, isGroupChat, o
|
|||||||
<span>{formatTime(message.createTime)}</span>
|
<span>{formatTime(message.createTime)}</span>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
<div className={`message-bubble ${bubbleClass} ${isEmoji && message.emojiCdnUrl && !emojiError ? 'emoji' : ''} ${isImage ? 'image' : ''} ${isVoice ? 'voice' : ''}`}>
|
<div
|
||||||
<div className="bubble-avatar">
|
className={`message-wrapper-with-selection ${isSelectionMode ? 'selectable' : ''}`}
|
||||||
<Avatar
|
style={{
|
||||||
src={avatarUrl}
|
display: 'flex',
|
||||||
name={!isSent ? (isGroupChat ? (senderName || message.senderUsername || '?') : (session.displayName || session.username)) : '我'}
|
alignItems: 'flex-start',
|
||||||
size={36}
|
width: '100%',
|
||||||
className="bubble-avatar"
|
justifyContent: isSent ? 'flex-end' : 'flex-start',
|
||||||
// If it's sent by me (isSent), we might not want 'group' class even if it's a group chat.
|
cursor: isSelectionMode ? 'pointer' : 'default'
|
||||||
// But 'group' class mainly handles default avatar icon.
|
}}
|
||||||
// Let's rely on standard Avatar behavior.
|
onClick={(e) => {
|
||||||
/>
|
if (isSelectionMode) {
|
||||||
</div>
|
e.stopPropagation()
|
||||||
<div className="bubble-body">
|
onToggleSelection?.(message.localId, e.shiftKey)
|
||||||
{/* 群聊中显示发送者名称 */}
|
}
|
||||||
{isGroupChat && !isSent && (
|
}}
|
||||||
<div className="sender-name">
|
>
|
||||||
{senderName || message.senderUsername || '群成员'}
|
{isSelectionMode && !isSent && (
|
||||||
</div>
|
<div className={`checkbox ${isSelected ? 'checked' : ''}`} style={{
|
||||||
)}
|
width: '20px',
|
||||||
{renderContent()}
|
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"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="bubble-body">
|
||||||
|
{/* 群聊中显示发送者名称 */}
|
||||||
|
{isGroupChat && !isSent && (
|
||||||
|
<div className="sender-name">
|
||||||
|
{senderName || message.senderUsername || '群成员'}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{renderContent()}
|
||||||
|
</div>
|
||||||
</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>
|
</div>
|
||||||
</>
|
</>
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -74,6 +74,7 @@ function SettingsPage() {
|
|||||||
const exportExcelColumnsDropdownRef = useRef<HTMLDivElement>(null)
|
const exportExcelColumnsDropdownRef = useRef<HTMLDivElement>(null)
|
||||||
const exportConcurrencyDropdownRef = useRef<HTMLDivElement>(null)
|
const exportConcurrencyDropdownRef = useRef<HTMLDivElement>(null)
|
||||||
const [cachePath, setCachePath] = useState('')
|
const [cachePath, setCachePath] = useState('')
|
||||||
|
|
||||||
const [logEnabled, setLogEnabled] = useState(false)
|
const [logEnabled, setLogEnabled] = useState(false)
|
||||||
const [whisperModelName, setWhisperModelName] = useState('base')
|
const [whisperModelName, setWhisperModelName] = useState('base')
|
||||||
const [whisperModelDir, setWhisperModelDir] = useState('')
|
const [whisperModelDir, setWhisperModelDir] = useState('')
|
||||||
@@ -249,6 +250,7 @@ function SettingsPage() {
|
|||||||
const savedPath = await configService.getDbPath()
|
const savedPath = await configService.getDbPath()
|
||||||
const savedWxid = await configService.getMyWxid()
|
const savedWxid = await configService.getMyWxid()
|
||||||
const savedCachePath = await configService.getCachePath()
|
const savedCachePath = await configService.getCachePath()
|
||||||
|
|
||||||
const savedExportPath = await configService.getExportPath()
|
const savedExportPath = await configService.getExportPath()
|
||||||
const savedLogEnabled = await configService.getLogEnabled()
|
const savedLogEnabled = await configService.getLogEnabled()
|
||||||
const savedImageXorKey = await configService.getImageXorKey()
|
const savedImageXorKey = await configService.getImageXorKey()
|
||||||
@@ -278,6 +280,7 @@ function SettingsPage() {
|
|||||||
if (savedWxid) setWxid(savedWxid)
|
if (savedWxid) setWxid(savedWxid)
|
||||||
if (savedCachePath) setCachePath(savedCachePath)
|
if (savedCachePath) setCachePath(savedCachePath)
|
||||||
|
|
||||||
|
|
||||||
const wxidConfig = savedWxid ? await configService.getWxidConfig(savedWxid) : null
|
const wxidConfig = savedWxid ? await configService.getWxidConfig(savedWxid) : null
|
||||||
const decryptKeyToUse = wxidConfig?.decryptKey ?? savedKey ?? ''
|
const decryptKeyToUse = wxidConfig?.decryptKey ?? savedKey ?? ''
|
||||||
const imageXorKeyToUse = typeof wxidConfig?.imageXorKey === 'number'
|
const imageXorKeyToUse = typeof wxidConfig?.imageXorKey === 'number'
|
||||||
@@ -613,6 +616,7 @@ function SettingsPage() {
|
|||||||
await applyWxidSelection(selectedWxid)
|
await applyWxidSelection(selectedWxid)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
const handleSelectCachePath = async () => {
|
const handleSelectCachePath = async () => {
|
||||||
try {
|
try {
|
||||||
const result = await dialog.openFile({ title: '选择缓存目录', properties: ['openDirectory'] })
|
const result = await dialog.openFile({ title: '选择缓存目录', properties: ['openDirectory'] })
|
||||||
@@ -1306,6 +1310,8 @@ function SettingsPage() {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
<div className="form-group">
|
<div className="form-group">
|
||||||
<label>账号 wxid</label>
|
<label>账号 wxid</label>
|
||||||
<span className="form-hint">微信账号标识</span>
|
<span className="form-hint">微信账号标识</span>
|
||||||
|
|||||||
@@ -809,6 +809,60 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
.video-badge-container {
|
||||||
|
position: absolute;
|
||||||
|
top: 50%;
|
||||||
|
left: 50%;
|
||||||
|
transform: translate(-50%, -50%);
|
||||||
|
z-index: 2;
|
||||||
|
pointer-events: none;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
|
||||||
|
.video-badge {
|
||||||
|
width: 44px;
|
||||||
|
height: 44px;
|
||||||
|
background: rgba(0, 0, 0, 0.3);
|
||||||
|
backdrop-filter: blur(4px);
|
||||||
|
border-radius: 50%;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
color: white;
|
||||||
|
border: 1px solid rgba(255, 255, 255, 0.3);
|
||||||
|
transition: all 0.2s;
|
||||||
|
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
|
||||||
|
|
||||||
|
svg {
|
||||||
|
fill: white;
|
||||||
|
opacity: 0.9;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.decrypting-badge {
|
||||||
|
background: rgba(0, 0, 0, 0.6);
|
||||||
|
backdrop-filter: blur(8px);
|
||||||
|
padding: 8px 16px;
|
||||||
|
border-radius: 20px;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 8px;
|
||||||
|
color: white;
|
||||||
|
font-size: 13px;
|
||||||
|
font-weight: 500;
|
||||||
|
border: 1px solid rgba(255, 255, 255, 0.2);
|
||||||
|
white-space: nowrap;
|
||||||
|
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
|
||||||
|
|
||||||
|
.spin-icon {
|
||||||
|
animation: spin 1s linear infinite;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
&:hover {
|
&:hover {
|
||||||
.download-btn-overlay {
|
.download-btn-overlay {
|
||||||
opacity: 1;
|
opacity: 1;
|
||||||
@@ -1207,4 +1261,14 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@keyframes spin {
|
||||||
|
from {
|
||||||
|
transform: rotate(0deg);
|
||||||
|
}
|
||||||
|
|
||||||
|
to {
|
||||||
|
transform: rotate(360deg);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -34,47 +34,228 @@ interface SnsPost {
|
|||||||
rawXml?: string // 原始 XML 数据
|
rawXml?: string // 原始 XML 数据
|
||||||
}
|
}
|
||||||
|
|
||||||
const MediaItem = ({ media, onPreview }: { media: any, onPreview: () => void }) => {
|
const MediaItem = ({ media, onPreview }: { media: any; onPreview: (src: string, isVideo?: boolean, liveVideoPath?: string) => void }) => {
|
||||||
const [error, setError] = useState(false);
|
const [error, setError] = useState(false)
|
||||||
const { url, thumb, livePhoto } = media;
|
const [thumbSrc, setThumbSrc] = useState<string>('') // 缩略图
|
||||||
const isLive = !!livePhoto;
|
const [videoPath, setVideoPath] = useState<string>('') // 视频本地路径
|
||||||
const targetUrl = thumb || url;
|
const [liveVideoPath, setLiveVideoPath] = useState<string>('') // Live Photo 视频路径
|
||||||
|
const [isDecrypting, setIsDecrypting] = useState(false) // 解密状态
|
||||||
|
const { url, thumb, livePhoto } = media
|
||||||
|
const isLive = !!livePhoto
|
||||||
|
const targetUrl = thumb || url // 默认显示缩略图
|
||||||
|
|
||||||
const handleDownload = (e: React.MouseEvent) => {
|
// 判断是否为视频
|
||||||
e.stopPropagation();
|
const isVideo = url && (url.includes('snsvideodownload') || url.includes('.mp4') || url.includes('video')) && !url.includes('vweixinthumb')
|
||||||
|
|
||||||
let downloadUrl = url;
|
useEffect(() => {
|
||||||
let downloadKey = media.key || '';
|
let cancelled = false
|
||||||
|
setError(false)
|
||||||
|
setThumbSrc('')
|
||||||
|
setVideoPath('')
|
||||||
|
setLiveVideoPath('')
|
||||||
|
setIsDecrypting(false)
|
||||||
|
|
||||||
if (isLive && media.livePhoto) {
|
const extractFirstFrame = (videoUrl: string) => {
|
||||||
downloadUrl = media.livePhoto.url;
|
const video = document.createElement('video')
|
||||||
downloadKey = media.livePhoto.key || '';
|
video.crossOrigin = 'anonymous'
|
||||||
|
video.style.display = 'none'
|
||||||
|
video.muted = true
|
||||||
|
video.src = videoUrl
|
||||||
|
video.currentTime = 0.1
|
||||||
|
|
||||||
|
const onLoadedData = () => {
|
||||||
|
if (cancelled) return cleanup()
|
||||||
|
try {
|
||||||
|
const canvas = document.createElement('canvas')
|
||||||
|
canvas.width = video.videoWidth
|
||||||
|
canvas.height = video.videoHeight
|
||||||
|
const ctx = canvas.getContext('2d')
|
||||||
|
if (ctx) {
|
||||||
|
ctx.drawImage(video, 0, 0, canvas.width, canvas.height)
|
||||||
|
const dataUrl = canvas.toDataURL('image/jpeg', 0.8)
|
||||||
|
if (!cancelled) {
|
||||||
|
setThumbSrc(dataUrl)
|
||||||
|
setIsDecrypting(false)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if (!cancelled) setIsDecrypting(false)
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
console.warn('Frame extraction error', e)
|
||||||
|
if (!cancelled) setIsDecrypting(false)
|
||||||
|
} finally {
|
||||||
|
cleanup()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const onError = () => {
|
||||||
|
if (!cancelled) {
|
||||||
|
setIsDecrypting(false)
|
||||||
|
setThumbSrc(targetUrl) // Fallback
|
||||||
|
}
|
||||||
|
cleanup()
|
||||||
|
}
|
||||||
|
|
||||||
|
const cleanup = () => {
|
||||||
|
video.removeEventListener('seeked', onLoadedData)
|
||||||
|
video.removeEventListener('error', onError)
|
||||||
|
video.remove()
|
||||||
|
}
|
||||||
|
|
||||||
|
video.addEventListener('seeked', onLoadedData)
|
||||||
|
video.addEventListener('error', onError)
|
||||||
|
video.load()
|
||||||
}
|
}
|
||||||
|
|
||||||
// TODO: 调用后端下载服务
|
const run = async () => {
|
||||||
// window.electronAPI.sns.download(downloadUrl, downloadKey);
|
try {
|
||||||
};
|
if (isVideo) {
|
||||||
|
setIsDecrypting(true)
|
||||||
|
|
||||||
|
const videoResult = await window.electronAPI.sns.proxyImage({
|
||||||
|
url: url,
|
||||||
|
key: media.key
|
||||||
|
})
|
||||||
|
|
||||||
|
if (cancelled) return
|
||||||
|
|
||||||
|
if (videoResult.success && videoResult.videoPath) {
|
||||||
|
const localUrl = videoResult.videoPath.startsWith('file:')
|
||||||
|
? videoResult.videoPath
|
||||||
|
: `file://${videoResult.videoPath.replace(/\\/g, '/')}`
|
||||||
|
setVideoPath(localUrl)
|
||||||
|
extractFirstFrame(localUrl)
|
||||||
|
} else {
|
||||||
|
console.warn('[MediaItem] Video decryption failed:', url, videoResult.error)
|
||||||
|
setIsDecrypting(false)
|
||||||
|
setError(true)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
const result = await window.electronAPI.sns.proxyImage({
|
||||||
|
url: targetUrl,
|
||||||
|
key: media.key
|
||||||
|
})
|
||||||
|
|
||||||
|
if (cancelled) return
|
||||||
|
if (result.success) {
|
||||||
|
if (result.dataUrl) {
|
||||||
|
setThumbSrc(result.dataUrl)
|
||||||
|
} else if (result.videoPath) {
|
||||||
|
const localUrl = result.videoPath.startsWith('file:')
|
||||||
|
? result.videoPath
|
||||||
|
: `file://${result.videoPath.replace(/\\/g, '/')}`
|
||||||
|
setThumbSrc(localUrl)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
console.warn('[MediaItem] Image proxy failed:', targetUrl, result.error)
|
||||||
|
setThumbSrc(targetUrl)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isLive && livePhoto && livePhoto.url) {
|
||||||
|
window.electronAPI.sns.proxyImage({
|
||||||
|
url: livePhoto.url,
|
||||||
|
key: livePhoto.key || media.key
|
||||||
|
}).then((res: any) => {
|
||||||
|
if (cancelled) return
|
||||||
|
if (res.success && res.videoPath) {
|
||||||
|
const localUrl = res.videoPath.startsWith('file:')
|
||||||
|
? res.videoPath
|
||||||
|
: `file://${res.videoPath.replace(/\\/g, '/')}`
|
||||||
|
setLiveVideoPath(localUrl)
|
||||||
|
console.log('[MediaItem] Live video ready:', localUrl)
|
||||||
|
} else {
|
||||||
|
console.warn('[MediaItem] Live video failed:', res.error)
|
||||||
|
}
|
||||||
|
}).catch((e: any) => console.error('[MediaItem] Live video err:', e))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
if (!cancelled) {
|
||||||
|
console.error('[MediaItem] run error:', err)
|
||||||
|
setError(true)
|
||||||
|
setIsDecrypting(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
run()
|
||||||
|
return () => { cancelled = true }
|
||||||
|
}, [targetUrl, url, media.key, isVideo, isLive, livePhoto])
|
||||||
|
|
||||||
|
const handleDownload = async (e: React.MouseEvent) => {
|
||||||
|
e.stopPropagation()
|
||||||
|
try {
|
||||||
|
const result = await window.electronAPI.sns.downloadImage({
|
||||||
|
url: url || targetUrl, // Use original url if available
|
||||||
|
key: media.key
|
||||||
|
})
|
||||||
|
if (!result.success && result.error !== '用户已取消') {
|
||||||
|
alert(`下载失败: ${result.error}`)
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Download failed:', error)
|
||||||
|
alert('下载过程中发生错误')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 点击时:如果是视频,应该传视频地址给 Preview?
|
||||||
|
// ImagePreview 目前可能只支持图片。需要检查 ImagePreview 是否支持视频。
|
||||||
|
// 假设 ImagePreview 暂不支持视频播放,我们可以在这里直接点开播放?
|
||||||
|
// 或者,传视频 URL 给 onPreview,让父组件决定/ImagePreview 决定。
|
||||||
|
// 通常做法:传给 ImagePreview,ImagePreview 识别 mp4 后播放。
|
||||||
|
|
||||||
|
// 显示用的图片:始终显示缩略图
|
||||||
|
const displaySrc = thumbSrc || targetUrl
|
||||||
|
|
||||||
|
// 预览用的地址:如果是视频,优先使用本地路径
|
||||||
|
const previewSrc = isVideo ? (videoPath || url) : (thumbSrc || url || targetUrl)
|
||||||
|
|
||||||
|
// 点击处理:解密中禁止点击
|
||||||
|
const handleClick = () => {
|
||||||
|
if (isVideo && isDecrypting) return
|
||||||
|
onPreview(previewSrc, isVideo, liveVideoPath)
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className={`media-item ${error ? 'error' : ''}`} onClick={onPreview}>
|
<div className={`media-item ${error ? 'error' : ''} ${isVideo && isDecrypting ? 'decrypting' : ''}`} onClick={handleClick}>
|
||||||
<img
|
{isVideo && isDecrypting ? (
|
||||||
src={targetUrl}
|
<div className="video-loading-overlay" style={{
|
||||||
alt=""
|
position: 'absolute', inset: 0, display: 'flex', flexDirection: 'column',
|
||||||
referrerPolicy="no-referrer"
|
alignItems: 'center', justifyContent: 'center', background: 'rgba(0,0,0,0.5)', color: '#fff',
|
||||||
loading="lazy"
|
zIndex: 2, backdropFilter: 'blur(4px)'
|
||||||
onError={() => setError(true)}
|
}}>
|
||||||
/>
|
<RefreshCw size={24} className="spin-icon" style={{ marginBottom: 8 }} />
|
||||||
{isLive && (
|
<span style={{ fontSize: 12 }}>解密中...</span>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<img
|
||||||
|
src={displaySrc}
|
||||||
|
alt=""
|
||||||
|
referrerPolicy="no-referrer"
|
||||||
|
loading="lazy"
|
||||||
|
onError={() => setError(true)}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{isVideo && !isDecrypting && (
|
||||||
|
<div className="video-badge-container">
|
||||||
|
<div className="video-badge">
|
||||||
|
<Play size={16} className="play-icon" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{isLive && !isVideo && (
|
||||||
<div className="live-badge">
|
<div className="live-badge">
|
||||||
<LivePhotoIcon size={16} className="live-icon" />
|
<LivePhotoIcon size={16} className="live-icon" />
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
<button className="download-btn-overlay" onClick={handleDownload} title="下载原图">
|
<button className="download-btn-overlay" onClick={handleDownload} title="Download original">
|
||||||
<Download size={14} />
|
<Download size={14} />
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
);
|
)
|
||||||
};
|
}
|
||||||
|
|
||||||
interface Contact {
|
interface Contact {
|
||||||
username: string
|
username: string
|
||||||
@@ -100,7 +281,7 @@ export default function SnsPage() {
|
|||||||
const [contactsLoading, setContactsLoading] = useState(false)
|
const [contactsLoading, setContactsLoading] = useState(false)
|
||||||
const [showJumpDialog, setShowJumpDialog] = useState(false)
|
const [showJumpDialog, setShowJumpDialog] = useState(false)
|
||||||
const [jumpTargetDate, setJumpTargetDate] = useState<Date | undefined>(undefined)
|
const [jumpTargetDate, setJumpTargetDate] = useState<Date | undefined>(undefined)
|
||||||
const [previewImage, setPreviewImage] = useState<string | null>(null)
|
const [previewImage, setPreviewImage] = useState<{ src: string, isVideo?: boolean, liveVideoPath?: string } | null>(null)
|
||||||
const [debugPost, setDebugPost] = useState<SnsPost | null>(null)
|
const [debugPost, setDebugPost] = useState<SnsPost | null>(null)
|
||||||
|
|
||||||
const postsContainerRef = useRef<HTMLDivElement>(null)
|
const postsContainerRef = useRef<HTMLDivElement>(null)
|
||||||
@@ -412,10 +593,6 @@ export default function SnsPage() {
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="sns-content-wrapper">
|
<div className="sns-content-wrapper">
|
||||||
<div className="sns-notice-banner">
|
|
||||||
<AlertTriangle size={16} />
|
|
||||||
<span>由于技术限制,当前无法解密显示部分图片与视频等加密资源文件</span>
|
|
||||||
</div>
|
|
||||||
<div className="sns-content custom-scrollbar" onScroll={handleScroll} onWheel={handleWheel} ref={postsContainerRef}>
|
<div className="sns-content custom-scrollbar" onScroll={handleScroll} onWheel={handleWheel} ref={postsContainerRef}>
|
||||||
<div className="posts-list">
|
<div className="posts-list">
|
||||||
{loadingNewer && (
|
{loadingNewer && (
|
||||||
@@ -463,15 +640,10 @@ export default function SnsPage() {
|
|||||||
<div className="post-body">
|
<div className="post-body">
|
||||||
{post.contentDesc && <div className="post-text">{post.contentDesc}</div>}
|
{post.contentDesc && <div className="post-text">{post.contentDesc}</div>}
|
||||||
|
|
||||||
{post.type === 15 ? (
|
{post.media.length > 0 && (
|
||||||
<div className="post-video-placeholder">
|
|
||||||
<Play size={20} />
|
|
||||||
<span>视频动态</span>
|
|
||||||
</div>
|
|
||||||
) : post.media.length > 0 && (
|
|
||||||
<div className={`post-media-grid media-count-${Math.min(post.media.length, 9)}`}>
|
<div className={`post-media-grid media-count-${Math.min(post.media.length, 9)}`}>
|
||||||
{post.media.map((m, idx) => (
|
{post.media.map((m, idx) => (
|
||||||
<MediaItem key={idx} media={m} onPreview={() => setPreviewImage(m.url)} />
|
<MediaItem key={idx} media={m} onPreview={(src, isVideo, liveVideoPath) => setPreviewImage({ src, isVideo, liveVideoPath })} />
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
@@ -644,7 +816,12 @@ export default function SnsPage() {
|
|||||||
</aside>
|
</aside>
|
||||||
</div>
|
</div>
|
||||||
{previewImage && (
|
{previewImage && (
|
||||||
<ImagePreview src={previewImage} onClose={() => setPreviewImage(null)} />
|
<ImagePreview
|
||||||
|
src={previewImage.src}
|
||||||
|
isVideo={previewImage.isVideo}
|
||||||
|
liveVideoPath={previewImage.liveVideoPath}
|
||||||
|
onClose={() => setPreviewImage(null)}
|
||||||
|
/>
|
||||||
)}
|
)}
|
||||||
<JumpToDateDialog
|
<JumpToDateDialog
|
||||||
isOpen={showJumpDialog}
|
isOpen={showJumpDialog}
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ export const CONFIG_KEYS = {
|
|||||||
LAST_SESSION: 'lastSession',
|
LAST_SESSION: 'lastSession',
|
||||||
WINDOW_BOUNDS: 'windowBounds',
|
WINDOW_BOUNDS: 'windowBounds',
|
||||||
CACHE_PATH: 'cachePath',
|
CACHE_PATH: 'cachePath',
|
||||||
|
|
||||||
EXPORT_PATH: 'exportPath',
|
EXPORT_PATH: 'exportPath',
|
||||||
AGREEMENT_ACCEPTED: 'agreementAccepted',
|
AGREEMENT_ACCEPTED: 'agreementAccepted',
|
||||||
LOG_ENABLED: 'logEnabled',
|
LOG_ENABLED: 'logEnabled',
|
||||||
@@ -162,6 +163,8 @@ export async function setCachePath(path: string): Promise<void> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
// 获取导出路径
|
// 获取导出路径
|
||||||
export async function getExportPath(): Promise<string | null> {
|
export async function getExportPath(): Promise<string | null> {
|
||||||
const value = await config.get(CONFIG_KEYS.EXPORT_PATH)
|
const value = await config.get(CONFIG_KEYS.EXPORT_PATH)
|
||||||
|
|||||||
4
src/types/electron.d.ts
vendored
4
src/types/electron.d.ts
vendored
@@ -85,6 +85,8 @@ export interface ElectronAPI {
|
|||||||
}>
|
}>
|
||||||
getContact: (username: string) => Promise<Contact | null>
|
getContact: (username: string) => Promise<Contact | null>
|
||||||
getContactAvatar: (username: string) => Promise<{ avatarUrl?: string; displayName?: string } | null>
|
getContactAvatar: (username: string) => Promise<{ avatarUrl?: string; displayName?: string } | null>
|
||||||
|
updateMessage: (sessionId: string, localId: 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 }>
|
resolveTransferDisplayNames: (chatroomId: string, payerUsername: string, receiverUsername: string) => Promise<{ payerName: string; receiverName: string }>
|
||||||
getContacts: () => Promise<{
|
getContacts: () => Promise<{
|
||||||
success: boolean
|
success: boolean
|
||||||
@@ -477,7 +479,7 @@ export interface ElectronAPI {
|
|||||||
error?: string
|
error?: string
|
||||||
}>
|
}>
|
||||||
debugResource: (url: string) => Promise<{ success: boolean; status?: number; headers?: any; error?: string }>
|
debugResource: (url: string) => Promise<{ success: boolean; status?: number; headers?: any; error?: string }>
|
||||||
proxyImage: (url: string) => Promise<{ success: boolean; dataUrl?: string; error?: string }>
|
proxyImage: (payload: { url: string; key?: string | number }) => Promise<{ success: boolean; dataUrl?: string; error?: string }>
|
||||||
}
|
}
|
||||||
llama: {
|
llama: {
|
||||||
loadModel: (modelPath: string) => Promise<boolean>
|
loadModel: (modelPath: string) => Promise<boolean>
|
||||||
|
|||||||
Reference in New Issue
Block a user