mirror of
https://github.com/hicccc77/WeFlow.git
synced 2026-03-25 23:35:49 +00:00
Compare commits
17 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fabbada580 | ||
|
|
6e434d37dc | ||
|
|
904da80f81 | ||
|
|
2a4bd52f0a | ||
|
|
b4248d4a12 | ||
|
|
75b056d5ba | ||
|
|
e87e12c939 | ||
|
|
5cb7e3bc73 | ||
|
|
1930b91a5b | ||
|
|
ea0dad132c | ||
|
|
5b7b94f507 | ||
|
|
28e38f73f8 | ||
|
|
d43c0ef209 | ||
|
|
6394384be0 | ||
|
|
4f0af3d0cb | ||
|
|
2a6f833718 | ||
|
|
c8835f4d4c |
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.
@@ -11,6 +11,7 @@ interface WorkerConfig {
|
||||
resourcesPath?: string
|
||||
userDataPath?: string
|
||||
logEnabled?: boolean
|
||||
excludeWords?: string[]
|
||||
}
|
||||
|
||||
const config = workerData as WorkerConfig
|
||||
@@ -29,6 +30,7 @@ async function run() {
|
||||
dbPath: config.dbPath,
|
||||
decryptKey: config.decryptKey,
|
||||
wxid: config.myWxid,
|
||||
excludeWords: config.excludeWords,
|
||||
onProgress: (status: string, progress: number) => {
|
||||
parentPort?.postMessage({
|
||||
type: 'dualReport:progress',
|
||||
|
||||
@@ -18,7 +18,7 @@ import { exportService, ExportOptions, ExportProgress } from './services/exportS
|
||||
import { KeyService } from './services/keyService'
|
||||
import { voiceTranscribeService } from './services/voiceTranscribeService'
|
||||
import { videoService } from './services/videoService'
|
||||
import { snsService } from './services/snsService'
|
||||
import { snsService, isVideoUrl } from './services/snsService'
|
||||
import { contactExportService } from './services/contactExportService'
|
||||
import { windowsHelloService } from './services/windowsHelloService'
|
||||
import { llamaService } from './services/llamaService'
|
||||
@@ -104,7 +104,8 @@ function createWindow(options: { autoShow?: boolean } = {}) {
|
||||
webPreferences: {
|
||||
preload: join(__dirname, 'preload.js'),
|
||||
contextIsolation: true,
|
||||
nodeIntegration: false
|
||||
nodeIntegration: false,
|
||||
webSecurity: false // Allow loading local files (video playback)
|
||||
},
|
||||
titleBarStyle: 'hidden',
|
||||
titleBarOverlay: {
|
||||
@@ -903,6 +904,9 @@ function registerIpcHandlers() {
|
||||
ipcMain.handle('chat:getAllVoiceMessages', async (_, sessionId: string) => {
|
||||
return chatService.getAllVoiceMessages(sessionId)
|
||||
})
|
||||
ipcMain.handle('chat:getMessageDates', async (_, sessionId: string) => {
|
||||
return chatService.getMessageDates(sessionId)
|
||||
})
|
||||
ipcMain.handle('chat:resolveVoiceCache', async (_, sessionId: string, msgId: string) => {
|
||||
return chatService.resolveVoiceCache(sessionId, msgId)
|
||||
})
|
||||
@@ -929,8 +933,46 @@ function registerIpcHandlers() {
|
||||
return snsService.debugResource(url)
|
||||
})
|
||||
|
||||
ipcMain.handle('sns:proxyImage', async (_, url: string) => {
|
||||
return snsService.proxyImage(url)
|
||||
ipcMain.handle('sns:proxyImage', async (_, payload: string | { url: string; key?: string | number }) => {
|
||||
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) }
|
||||
}
|
||||
})
|
||||
|
||||
// 私聊克隆
|
||||
@@ -1192,6 +1234,7 @@ function registerIpcHandlers() {
|
||||
const logEnabled = cfg.get('logEnabled')
|
||||
const friendUsername = payload?.friendUsername
|
||||
const year = payload?.year ?? 0
|
||||
const excludeWords = cfg.get('wordCloudExcludeWords') || []
|
||||
|
||||
if (!friendUsername) {
|
||||
return { success: false, error: '缺少好友用户名' }
|
||||
@@ -1206,7 +1249,7 @@ function registerIpcHandlers() {
|
||||
|
||||
return await new Promise((resolve) => {
|
||||
const worker = new Worker(workerPath, {
|
||||
workerData: { year, friendUsername, dbPath, decryptKey, myWxid: wxid, resourcesPath, userDataPath, logEnabled }
|
||||
workerData: { year, friendUsername, dbPath, decryptKey, myWxid: wxid, resourcesPath, userDataPath, logEnabled, excludeWords }
|
||||
})
|
||||
|
||||
const cleanup = () => {
|
||||
|
||||
@@ -142,6 +142,7 @@ contextBridge.exposeInMainWorld('electronAPI', {
|
||||
getVoiceData: (sessionId: string, msgId: string, createTime?: number, serverId?: string | number) =>
|
||||
ipcRenderer.invoke('chat:getVoiceData', sessionId, msgId, createTime, serverId),
|
||||
getAllVoiceMessages: (sessionId: string) => ipcRenderer.invoke('chat:getAllVoiceMessages', sessionId),
|
||||
getMessageDates: (sessionId: string) => ipcRenderer.invoke('chat:getMessageDates', sessionId),
|
||||
resolveVoiceCache: (sessionId: string, msgId: string) => ipcRenderer.invoke('chat:resolveVoiceCache', sessionId, msgId),
|
||||
getVoiceTranscript: (sessionId: string, msgId: string, createTime?: number) => ipcRenderer.invoke('chat:getVoiceTranscript', sessionId, msgId, createTime),
|
||||
onVoiceTranscriptPartial: (callback: (payload: { msgId: string; text: string }) => void) => {
|
||||
@@ -270,7 +271,8 @@ contextBridge.exposeInMainWorld('electronAPI', {
|
||||
getTimeline: (limit: number, offset: number, usernames?: string[], keyword?: string, startTime?: number, endTime?: number) =>
|
||||
ipcRenderer.invoke('sns:getTimeline', limit, offset, usernames, keyword, startTime, endTime),
|
||||
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
|
||||
|
||||
@@ -116,7 +116,7 @@ class AnnualReportService {
|
||||
}
|
||||
const suffixMatch = trimmed.match(/^(.+)_([a-zA-Z0-9]{4})$/)
|
||||
const cleaned = suffixMatch ? suffixMatch[1] : trimmed
|
||||
|
||||
|
||||
return cleaned
|
||||
}
|
||||
|
||||
@@ -499,7 +499,7 @@ class AnnualReportService {
|
||||
}
|
||||
}
|
||||
|
||||
this.reportProgress('加载扩展统计... (初始化)', 30, onProgress)
|
||||
this.reportProgress('加载扩展统计...', 30, onProgress)
|
||||
const extras = await wcdbService.getAnnualReportExtras(sessionIds, actualStartTime, actualEndTime, peakDayBegin, peakDayEnd)
|
||||
if (extras.success && extras.data) {
|
||||
this.reportProgress('加载扩展统计... (解析热力图)', 32, onProgress)
|
||||
|
||||
@@ -72,6 +72,9 @@ export interface Message {
|
||||
// 名片消息
|
||||
cardUsername?: string // 名片的微信ID
|
||||
cardNickname?: string // 名片的昵称
|
||||
// 转账消息
|
||||
transferPayerUsername?: string // 转账付款人
|
||||
transferReceiverUsername?: string // 转账收款人
|
||||
// 聊天记录
|
||||
chatRecordTitle?: string // 聊天记录标题
|
||||
chatRecordList?: Array<{
|
||||
@@ -138,10 +141,10 @@ class ChatService {
|
||||
|
||||
constructor() {
|
||||
this.configService = new ConfigService()
|
||||
this.contactCacheService = new ContactCacheService(this.configService.get('cachePath'))
|
||||
this.contactCacheService = new ContactCacheService(this.configService.getCacheBasePath())
|
||||
const persisted = this.contactCacheService.getAllEntries()
|
||||
this.avatarCache = new Map(Object.entries(persisted))
|
||||
this.messageCacheService = new MessageCacheService(this.configService.get('cachePath'))
|
||||
this.messageCacheService = new MessageCacheService(this.configService.getCacheBasePath())
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -723,7 +726,7 @@ class ChatService {
|
||||
// 1. 没有游标状态
|
||||
// 2. offset 为 0 (重新加载会话)
|
||||
// 3. batchSize 改变
|
||||
// 4. startTime 改变
|
||||
// 4. startTime/endTime 改变(视为全新查询)
|
||||
// 5. ascending 改变
|
||||
const needNewCursor = !state ||
|
||||
offset === 0 ||
|
||||
@@ -756,27 +759,35 @@ class ChatService {
|
||||
this.messageCursors.set(sessionId, state)
|
||||
|
||||
// 如果需要跳过消息(offset > 0),逐批获取但不返回
|
||||
// 注意:仅在 offset === 0 时重建游标最安全;
|
||||
// 当 startTime/endTime 变化导致重建时,offset 应由前端重置为 0
|
||||
if (offset > 0) {
|
||||
|
||||
console.warn(`[ChatService] 新游标需跳过 ${offset} 条消息(startTime=${startTime}, endTime=${endTime})`)
|
||||
let skipped = 0
|
||||
while (skipped < offset) {
|
||||
const maxSkipAttempts = Math.ceil(offset / batchSize) + 5 // 防止无限循环
|
||||
let attempts = 0
|
||||
while (skipped < offset && attempts < maxSkipAttempts) {
|
||||
attempts++
|
||||
const skipBatch = await wcdbService.fetchMessageBatch(state.cursor)
|
||||
if (!skipBatch.success) {
|
||||
console.error('[ChatService] 跳过消息批次失败:', skipBatch.error)
|
||||
return { success: false, error: skipBatch.error || '跳过消息失败' }
|
||||
}
|
||||
if (!skipBatch.rows || skipBatch.rows.length === 0) {
|
||||
|
||||
console.warn(`[ChatService] 跳过时数据耗尽: skipped=${skipped}/${offset}`)
|
||||
return { success: true, messages: [], hasMore: false }
|
||||
}
|
||||
skipped += skipBatch.rows.length
|
||||
state.fetched += skipBatch.rows.length
|
||||
if (!skipBatch.hasMore) {
|
||||
|
||||
console.warn(`[ChatService] 跳过后无更多数据: skipped=${skipped}/${offset}`)
|
||||
return { success: true, messages: [], hasMore: false }
|
||||
}
|
||||
}
|
||||
|
||||
if (attempts >= maxSkipAttempts) {
|
||||
console.error(`[ChatService] 跳过消息超过最大尝试次数: attempts=${attempts}`)
|
||||
}
|
||||
console.log(`[ChatService] 跳过完成: skipped=${skipped}, fetched=${state.fetched}`)
|
||||
}
|
||||
} else if (state && offset !== state.fetched) {
|
||||
// offset 与 fetched 不匹配,说明状态不一致
|
||||
@@ -3776,6 +3787,32 @@ class ChatService {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取某会话中有消息的日期列表
|
||||
* 返回 YYYY-MM-DD 格式的日期字符串数组
|
||||
*/
|
||||
async getMessageDates(sessionId: string): Promise<{ success: boolean; dates?: string[]; error?: string }> {
|
||||
try {
|
||||
const connectResult = await this.ensureConnected()
|
||||
if (!connectResult.success) {
|
||||
return { success: false, error: connectResult.error || '数据库未连接' }
|
||||
}
|
||||
|
||||
const result = await wcdbService.getMessageDates(sessionId)
|
||||
if (!result.success) {
|
||||
throw new Error(result.error || '查询失败')
|
||||
}
|
||||
|
||||
const dates = result.dates || []
|
||||
|
||||
console.log(`[ChatService] 会话 ${sessionId} 共有 ${dates.length} 个有消息的日期`)
|
||||
return { success: true, dates }
|
||||
} catch (e) {
|
||||
console.error('[ChatService] 获取消息日期失败:', e)
|
||||
return { success: false, error: String(e) }
|
||||
}
|
||||
}
|
||||
|
||||
async getMessageById(sessionId: string, localId: number): Promise<{ success: boolean; message?: Message; error?: string }> {
|
||||
try {
|
||||
// 1. 尝试从缓存获取会话表信息
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { join } from 'path'
|
||||
import { app } from 'electron'
|
||||
import Store from 'electron-store'
|
||||
|
||||
interface ConfigSchema {
|
||||
@@ -12,6 +14,7 @@ interface ConfigSchema {
|
||||
|
||||
// 缓存相关
|
||||
cachePath: string
|
||||
weixinDllPath: string
|
||||
lastOpenedDb: string
|
||||
lastSession: string
|
||||
|
||||
@@ -42,6 +45,7 @@ interface ConfigSchema {
|
||||
notificationPosition: 'top-right' | 'top-left' | 'bottom-right' | 'bottom-left'
|
||||
notificationFilterMode: 'all' | 'whitelist' | 'blacklist'
|
||||
notificationFilterList: string[]
|
||||
wordCloudExcludeWords: string[]
|
||||
}
|
||||
|
||||
export class ConfigService {
|
||||
@@ -71,6 +75,7 @@ export class ConfigService {
|
||||
imageAesKey: '',
|
||||
wxidConfigs: {},
|
||||
cachePath: '',
|
||||
weixinDllPath: '',
|
||||
lastOpenedDb: '',
|
||||
lastSession: '',
|
||||
theme: 'system',
|
||||
@@ -94,7 +99,8 @@ export class ConfigService {
|
||||
notificationEnabled: true,
|
||||
notificationPosition: 'top-right',
|
||||
notificationFilterMode: 'all',
|
||||
notificationFilterList: []
|
||||
notificationFilterList: [],
|
||||
wordCloudExcludeWords: []
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -107,6 +113,14 @@ export class ConfigService {
|
||||
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 {
|
||||
return this.store.store
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { join, dirname } from 'path'
|
||||
import { existsSync, mkdirSync, readFileSync, writeFileSync, rmSync } from 'fs'
|
||||
import { app } from 'electron'
|
||||
import { ConfigService } from './config'
|
||||
|
||||
export interface ContactCacheEntry {
|
||||
displayName?: string
|
||||
@@ -15,7 +16,7 @@ export class ContactCacheService {
|
||||
constructor(cacheBasePath?: string) {
|
||||
const basePath = cacheBasePath && cacheBasePath.trim().length > 0
|
||||
? cacheBasePath
|
||||
: join(app.getPath('documents'), 'WeFlow')
|
||||
: ConfigService.getInstance().getCacheBasePath()
|
||||
this.cacheFilePath = join(basePath, 'contacts.json')
|
||||
this.ensureCacheDir()
|
||||
this.loadCache()
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { parentPort } from 'worker_threads'
|
||||
import { wcdbService } from './wcdbService'
|
||||
|
||||
|
||||
export interface DualReportMessage {
|
||||
content: string
|
||||
isSentByMe: boolean
|
||||
@@ -58,6 +59,8 @@ export interface DualReportData {
|
||||
} | null
|
||||
stats: DualReportStats
|
||||
topPhrases: Array<{ phrase: string; count: number }>
|
||||
myExclusivePhrases: Array<{ phrase: string; count: number }>
|
||||
friendExclusivePhrases: Array<{ phrase: string; count: number }>
|
||||
heatmap?: number[][]
|
||||
initiative?: { initiated: number; received: number }
|
||||
response?: { avg: number; fastest: number; count: number }
|
||||
@@ -499,10 +502,11 @@ class DualReportService {
|
||||
dbPath: string
|
||||
decryptKey: string
|
||||
wxid: string
|
||||
excludeWords?: string[]
|
||||
onProgress?: (status: string, progress: number) => void
|
||||
}): Promise<{ success: boolean; data?: DualReportData; error?: string }> {
|
||||
try {
|
||||
const { year, friendUsername, dbPath, decryptKey, wxid, onProgress } = params
|
||||
const { year, friendUsername, dbPath, decryptKey, wxid, excludeWords, onProgress } = params
|
||||
this.reportProgress('正在连接数据库...', 5, onProgress)
|
||||
const conn = await this.ensureConnectedWithConfig(dbPath, decryptKey, wxid)
|
||||
if (!conn.success || !conn.cleanedWxid || !conn.rawWxid) return { success: false, error: conn.error }
|
||||
@@ -714,11 +718,58 @@ class DualReportService {
|
||||
if (myTopCount >= 0) stats.myTopEmojiCount = myTopCount
|
||||
if (friendTopCount >= 0) stats.friendTopEmojiCount = friendTopCount
|
||||
|
||||
const topPhrases = (cppData.phrases || []).map((p: any) => ({
|
||||
if (friendTopCount >= 0) stats.friendTopEmojiCount = friendTopCount
|
||||
|
||||
const excludeSet = new Set(excludeWords || [])
|
||||
|
||||
const filterPhrases = (list: any[]) => {
|
||||
return (list || []).filter((p: any) => !excludeSet.has(p.phrase))
|
||||
}
|
||||
|
||||
const cleanPhrases = filterPhrases(cppData.phrases)
|
||||
const cleanMyPhrases = filterPhrases(cppData.myPhrases)
|
||||
const cleanFriendPhrases = filterPhrases(cppData.friendPhrases)
|
||||
|
||||
const topPhrases = cleanPhrases.map((p: any) => ({
|
||||
phrase: p.phrase,
|
||||
count: p.count
|
||||
}))
|
||||
|
||||
// 计算专属词汇:一方频繁使用而另一方很少使用的词
|
||||
const myPhraseMap = new Map<string, number>()
|
||||
const friendPhraseMap = new Map<string, number>()
|
||||
for (const p of cleanMyPhrases) {
|
||||
myPhraseMap.set(p.phrase, p.count)
|
||||
}
|
||||
for (const p of cleanFriendPhrases) {
|
||||
friendPhraseMap.set(p.phrase, p.count)
|
||||
}
|
||||
|
||||
// 专属词汇:该方使用占比 >= 75% 且至少出现 2 次
|
||||
const myExclusivePhrases: Array<{ phrase: string; count: number }> = []
|
||||
const friendExclusivePhrases: Array<{ phrase: string; count: number }> = []
|
||||
|
||||
for (const [phrase, myCount] of myPhraseMap) {
|
||||
const friendCount = friendPhraseMap.get(phrase) || 0
|
||||
const total = myCount + friendCount
|
||||
if (myCount >= 2 && total > 0 && myCount / total >= 0.75) {
|
||||
myExclusivePhrases.push({ phrase, count: myCount })
|
||||
}
|
||||
}
|
||||
for (const [phrase, friendCount] of friendPhraseMap) {
|
||||
const myCount = myPhraseMap.get(phrase) || 0
|
||||
const total = myCount + friendCount
|
||||
if (friendCount >= 2 && total > 0 && friendCount / total >= 0.75) {
|
||||
friendExclusivePhrases.push({ phrase, count: friendCount })
|
||||
}
|
||||
}
|
||||
|
||||
// 按频率排序,取前 20
|
||||
myExclusivePhrases.sort((a, b) => b.count - a.count)
|
||||
friendExclusivePhrases.sort((a, b) => b.count - a.count)
|
||||
if (myExclusivePhrases.length > 20) myExclusivePhrases.length = 20
|
||||
if (friendExclusivePhrases.length > 20) friendExclusivePhrases.length = 20
|
||||
|
||||
const reportData: DualReportData = {
|
||||
year: reportYear,
|
||||
selfName: myName,
|
||||
@@ -731,6 +782,8 @@ class DualReportService {
|
||||
yearFirstChat,
|
||||
stats,
|
||||
topPhrases,
|
||||
myExclusivePhrases,
|
||||
friendExclusivePhrases,
|
||||
heatmap: cppData.heatmap,
|
||||
initiative: cppData.initiative,
|
||||
response: cppData.response,
|
||||
|
||||
@@ -363,7 +363,7 @@ class ExportService {
|
||||
// 检查 XML 中的 type 标签(支持大 localType 的情况)
|
||||
const xmlTypeMatch = /<type>(\d+)<\/type>/i.exec(content)
|
||||
const xmlType = xmlTypeMatch ? parseInt(xmlTypeMatch[1]) : null
|
||||
|
||||
|
||||
// 特殊处理 type 49 或 XML type
|
||||
if (localType === 49 || xmlType) {
|
||||
const subType = xmlType || 0
|
||||
@@ -376,7 +376,7 @@ class ExportService {
|
||||
case 2000: return 99 // 转账 -> OTHER (ChatLab 没有转账类型)
|
||||
case 5:
|
||||
case 49: return 7 // 链接 -> LINK
|
||||
default:
|
||||
default:
|
||||
if (xmlType) return 7 // 有 XML type 但未知,默认为链接
|
||||
}
|
||||
}
|
||||
@@ -606,7 +606,7 @@ class ExportService {
|
||||
case 49: {
|
||||
const title = this.extractXmlValue(content, 'title')
|
||||
const type = this.extractXmlValue(content, 'type')
|
||||
|
||||
|
||||
// 转账消息特殊处理
|
||||
if (type === '2000') {
|
||||
const feedesc = this.extractXmlValue(content, 'feedesc')
|
||||
@@ -616,7 +616,7 @@ class ExportService {
|
||||
}
|
||||
return '[转账]'
|
||||
}
|
||||
|
||||
|
||||
if (type === '6') return title ? `[文件] ${title}` : '[文件]'
|
||||
if (type === '19') return title ? `[聊天记录] ${title}` : '[聊天记录]'
|
||||
if (type === '33' || type === '36') return title ? `[小程序] ${title}` : '[小程序]'
|
||||
@@ -636,7 +636,7 @@ class ExportService {
|
||||
// 对于未知的 localType,检查 XML type 来判断消息类型
|
||||
if (xmlType) {
|
||||
const title = this.extractXmlValue(content, 'title')
|
||||
|
||||
|
||||
// 群公告消息(type 87)
|
||||
if (xmlType === '87') {
|
||||
const textAnnouncement = this.extractXmlValue(content, 'textannouncement')
|
||||
@@ -645,7 +645,7 @@ class ExportService {
|
||||
}
|
||||
return '[群公告]'
|
||||
}
|
||||
|
||||
|
||||
// 转账消息
|
||||
if (xmlType === '2000') {
|
||||
const feedesc = this.extractXmlValue(content, 'feedesc')
|
||||
@@ -655,18 +655,18 @@ class ExportService {
|
||||
}
|
||||
return '[转账]'
|
||||
}
|
||||
|
||||
|
||||
// 其他类型
|
||||
if (xmlType === '6') return title ? `[文件] ${title}` : '[文件]'
|
||||
if (xmlType === '19') return title ? `[聊天记录] ${title}` : '[聊天记录]'
|
||||
if (xmlType === '33' || xmlType === '36') return title ? `[小程序] ${title}` : '[小程序]'
|
||||
if (xmlType === '57') return title || '[引用消息]'
|
||||
if (xmlType === '5' || xmlType === '49') return title ? `[链接] ${title}` : '[链接]'
|
||||
|
||||
|
||||
// 有 title 就返回 title
|
||||
if (title) return title
|
||||
}
|
||||
|
||||
|
||||
// 最后尝试提取文本内容
|
||||
return this.stripSenderPrefix(content) || null
|
||||
}
|
||||
@@ -728,7 +728,7 @@ class ExportService {
|
||||
const typeMatch = /<type>(\d+)<\/type>/i.exec(normalized)
|
||||
const subType = typeMatch ? parseInt(typeMatch[1], 10) : 0
|
||||
const title = this.extractXmlValue(normalized, 'title') || this.extractXmlValue(normalized, 'appname')
|
||||
|
||||
|
||||
// 群公告消息(type 87)
|
||||
if (subType === 87) {
|
||||
const textAnnouncement = this.extractXmlValue(normalized, 'textannouncement')
|
||||
@@ -737,7 +737,7 @@ class ExportService {
|
||||
}
|
||||
return '[群公告]'
|
||||
}
|
||||
|
||||
|
||||
// 转账消息特殊处理
|
||||
if (subType === 2000 || title.includes('转账') || normalized.includes('transfer')) {
|
||||
const feedesc = this.extractXmlValue(normalized, 'feedesc')
|
||||
@@ -758,7 +758,7 @@ class ExportService {
|
||||
)
|
||||
return amount ? `[转账]${amount}` : '[转账]'
|
||||
}
|
||||
|
||||
|
||||
if (subType === 3 || normalized.includes('<musicurl') || normalized.includes('<songname')) {
|
||||
const songName = this.extractXmlValue(normalized, 'songname') || title || '音乐'
|
||||
return `[音乐]${songName}`
|
||||
@@ -870,17 +870,17 @@ class ExportService {
|
||||
*/
|
||||
private extractRevokerInfo(content: string): { isRevoke: boolean; isSelfRevoke?: boolean; revokerWxid?: string } {
|
||||
if (!content) return { isRevoke: false }
|
||||
|
||||
|
||||
// 检查是否是撤回消息
|
||||
if (!content.includes('revokemsg') && !content.includes('撤回')) {
|
||||
return { isRevoke: false }
|
||||
}
|
||||
|
||||
|
||||
// 检查是否是 "你撤回了" - 自己撤回
|
||||
if (content.includes('你撤回')) {
|
||||
return { isRevoke: true, isSelfRevoke: true }
|
||||
}
|
||||
|
||||
|
||||
// 尝试从 <session> 标签提取(格式: wxid_xxx)
|
||||
const sessionMatch = /<session>([^<]+)<\/session>/i.exec(content)
|
||||
if (sessionMatch) {
|
||||
@@ -890,13 +890,13 @@ class ExportService {
|
||||
return { isRevoke: true, revokerWxid: session }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// 尝试从 <fromusername> 提取
|
||||
const fromUserMatch = /<fromusername>([^<]+)<\/fromusername>/i.exec(content)
|
||||
if (fromUserMatch) {
|
||||
return { isRevoke: true, revokerWxid: fromUserMatch[1].trim() }
|
||||
}
|
||||
|
||||
|
||||
// 是撤回消息但无法提取撤回者
|
||||
return { isRevoke: true }
|
||||
}
|
||||
@@ -1024,7 +1024,7 @@ class ExportService {
|
||||
if (content) {
|
||||
const xmlTypeMatch = /<type>(\d+)<\/type>/i.exec(content)
|
||||
const xmlType = xmlTypeMatch ? xmlTypeMatch[1] : null
|
||||
|
||||
|
||||
if (xmlType) {
|
||||
switch (xmlType) {
|
||||
case '87': return '群公告'
|
||||
@@ -2385,7 +2385,7 @@ class ExportService {
|
||||
// 如果有聊天记录,添加为嵌套字段
|
||||
if (msg.chatRecordList && msg.chatRecordList.length > 0) {
|
||||
const chatRecords: any[] = []
|
||||
|
||||
|
||||
for (const record of msg.chatRecordList) {
|
||||
// 解析时间戳 (格式: "YYYY-MM-DD HH:MM:SS")
|
||||
let recordTimestamp = msg.createTime
|
||||
@@ -2411,7 +2411,7 @@ class ExportService {
|
||||
// 转换消息类型
|
||||
let recordType = 0 // TEXT
|
||||
let recordContent = record.datadesc || record.datatitle || ''
|
||||
|
||||
|
||||
switch (record.datatype) {
|
||||
case 1:
|
||||
recordType = 0 // TEXT
|
||||
@@ -2449,14 +2449,14 @@ class ExportService {
|
||||
type: recordType,
|
||||
content: recordContent
|
||||
}
|
||||
|
||||
|
||||
// 添加头像(如果启用导出头像)
|
||||
if (options.exportAvatars && record.sourceheadurl) {
|
||||
chatRecord.avatar = record.sourceheadurl
|
||||
}
|
||||
|
||||
|
||||
chatRecords.push(chatRecord)
|
||||
|
||||
|
||||
// 添加成员信息到 memberSet
|
||||
if (record.sourcename && !collected.memberSet.has(record.sourcename)) {
|
||||
const newMember: ChatLabMember = {
|
||||
@@ -2472,7 +2472,7 @@ class ExportService {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
message.chatRecords = chatRecords
|
||||
}
|
||||
|
||||
@@ -4512,7 +4512,7 @@ class ExportService {
|
||||
phase: 'exporting'
|
||||
})
|
||||
|
||||
const safeName = sessionInfo.displayName.replace(/[<>:"/\\|?*]/g, '_')
|
||||
const safeName = sessionInfo.displayName.replace(/[<>:"\/\\|?*]/g, '_').replace(/\.+$/, '')
|
||||
const useSessionFolder = sessionLayout === 'per-session'
|
||||
const sessionDir = useSessionFolder ? path.join(outputDir, safeName) : outputDir
|
||||
|
||||
|
||||
121
electron/services/isaac64.ts
Normal file
121
electron/services/isaac64.ts
Normal file
@@ -0,0 +1,121 @@
|
||||
/**
|
||||
* 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[256 - (this.randcnt--)];
|
||||
}
|
||||
|
||||
/**
|
||||
* Generates a keystream of the specified size (in bytes).
|
||||
* @param size Size of the keystream in bytes (must be multiple of 8)
|
||||
* @returns Buffer containing the keystream
|
||||
*/
|
||||
public generateKeystream(size: number): Buffer {
|
||||
const stream = new BigUint64Array(size / 8);
|
||||
for (let i = 0; i < stream.length; i++) {
|
||||
stream[i] = this.getNext();
|
||||
}
|
||||
// WeChat's logic specifically reverses the entire byte array
|
||||
const buffer = Buffer.from(stream.buffer);
|
||||
// 注意:根据 worker.html 的逻辑,它是对 Uint8Array 执行 reverse()
|
||||
// Array.from(wasmArray).reverse()
|
||||
return buffer.reverse();
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import { join, dirname } from 'path'
|
||||
import { existsSync, mkdirSync, readFileSync, writeFileSync, rmSync } from 'fs'
|
||||
import { app } from 'electron'
|
||||
import { ConfigService } from './config'
|
||||
|
||||
export interface SessionMessageCacheEntry {
|
||||
updatedAt: number
|
||||
@@ -15,7 +16,7 @@ export class MessageCacheService {
|
||||
constructor(cacheBasePath?: string) {
|
||||
const basePath = cacheBasePath && cacheBasePath.trim().length > 0
|
||||
? cacheBasePath
|
||||
: join(app.getPath('documents'), 'WeFlow')
|
||||
: ConfigService.getInstance().getCacheBasePath()
|
||||
this.cacheFilePath = join(basePath, 'session-messages.json')
|
||||
this.ensureCacheDir()
|
||||
this.loadCache()
|
||||
|
||||
@@ -1,6 +1,11 @@
|
||||
import { wcdbService } from './wcdbService'
|
||||
import { ConfigService } from './config'
|
||||
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 {
|
||||
url: string
|
||||
@@ -32,82 +37,147 @@ export interface SnsPost {
|
||||
media: SnsMedia[]
|
||||
likes: 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('?') ? '&' : '?';
|
||||
return `${fixedUrl}${connector}token=${token}&idx=1`;
|
||||
};
|
||||
let fixedUrl = url.replace('http://', 'https://')
|
||||
|
||||
// 只有非视频(即图片)才需要处理 /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 {
|
||||
private configService: ConfigService
|
||||
private contactCache: ContactCacheService
|
||||
private imageCache = new Map<string, string>()
|
||||
|
||||
constructor() {
|
||||
const config = new ConfigService()
|
||||
this.contactCache = new ContactCacheService(config.get('cachePath') as string)
|
||||
this.configService = new ConfigService()
|
||||
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 }> {
|
||||
|
||||
|
||||
const result = await wcdbService.getSnsTimeline(limit, offset, usernames, keyword, startTime, endTime)
|
||||
|
||||
|
||||
|
||||
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 isVideoPost = post.type === 15
|
||||
|
||||
// 修复媒体 URL
|
||||
const fixedMedia = post.media.map((m: any, mIdx: number) => {
|
||||
const base = {
|
||||
url: fixSnsUrl(m.url, m.token),
|
||||
thumb: fixSnsUrl(m.thumb, m.token),
|
||||
md5: m.md5,
|
||||
token: m.token,
|
||||
key: m.key,
|
||||
encIdx: m.encIdx || m.enc_idx, // 兼容不同命名
|
||||
livePhoto: m.livePhoto ? {
|
||||
// 尝试从 rawXml 中提取视频解密密钥 (针对视频号视频)
|
||||
const videoKey = extractVideoKey(post.rawXml || '')
|
||||
|
||||
const fixedMedia = (post.media || []).map((m: any) => ({
|
||||
// 如果是视频动态,url 是视频,thumb 是缩略图
|
||||
url: fixSnsUrl(m.url, m.token, isVideoPost),
|
||||
thumb: fixSnsUrl(m.thumb, m.token, false),
|
||||
md5: m.md5,
|
||||
token: m.token,
|
||||
// 只有在视频动态 (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,
|
||||
url: fixSnsUrl(m.livePhoto.url, m.livePhoto.token),
|
||||
thumb: fixSnsUrl(m.livePhoto.thumb, m.livePhoto.token),
|
||||
url: fixSnsUrl(m.livePhoto.url, m.livePhoto.token, true),
|
||||
thumb: fixSnsUrl(m.livePhoto.thumb, m.livePhoto.token, false),
|
||||
token: m.livePhoto.token,
|
||||
key: m.livePhoto.key
|
||||
} : undefined
|
||||
}
|
||||
|
||||
// [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)
|
||||
// 实况照片的视频部分优先使用从 XML 提取的 Key
|
||||
key: videoKey || m.livePhoto.key || m.key,
|
||||
encIdx: m.livePhoto.encIdx || m.livePhoto.enc_idx
|
||||
}
|
||||
base.encIdx = '1'
|
||||
|
||||
// 强制给第一个帖子的第一张图加 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
|
||||
})
|
||||
: undefined
|
||||
}))
|
||||
|
||||
return {
|
||||
...post,
|
||||
@@ -116,20 +186,15 @@ class SnsService {
|
||||
media: fixedMedia
|
||||
}
|
||||
})
|
||||
|
||||
|
||||
return { ...result, timeline: enrichedTimeline }
|
||||
}
|
||||
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
async debugResource(url: string): Promise<{ success: boolean; status?: number; headers?: any; error?: string }> {
|
||||
return new Promise((resolve) => {
|
||||
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 urlObj = new URL(url)
|
||||
|
||||
@@ -138,13 +203,12 @@ class SnsService {
|
||||
path: urlObj.pathname + urlObj.search,
|
||||
method: 'GET',
|
||||
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",
|
||||
"Accept": "image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8",
|
||||
"Accept-Encoding": "gzip, deflate, br",
|
||||
"Accept-Language": "zh-CN,zh;q=0.9",
|
||||
"Referer": "https://servicewechat.com/",
|
||||
"Connection": "keep-alive",
|
||||
"Range": "bytes=0-10" // Keep our range check
|
||||
'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-Encoding': 'gzip, deflate, br',
|
||||
'Accept-Language': 'zh-CN,zh;q=0.9',
|
||||
'Connection': 'keep-alive',
|
||||
'Range': 'bytes=0-10'
|
||||
}
|
||||
}
|
||||
|
||||
@@ -154,17 +218,15 @@ class SnsService {
|
||||
status: res.statusCode,
|
||||
headers: {
|
||||
'x-enc': res.headers['x-enc'],
|
||||
'x-time': res.headers['x-time'],
|
||||
'content-length': res.headers['content-length'],
|
||||
'content-type': res.headers['content-type']
|
||||
}
|
||||
})
|
||||
req.destroy() // We only need headers
|
||||
})
|
||||
|
||||
req.on('error', (e: any) => {
|
||||
resolve({ success: false, error: e.message })
|
||||
req.destroy()
|
||||
})
|
||||
|
||||
req.on('error', (e: any) => resolve({ success: false, error: e.message }))
|
||||
req.end()
|
||||
} catch (e: any) {
|
||||
resolve({ success: false, error: e.message })
|
||||
@@ -172,14 +234,173 @@ class SnsService {
|
||||
})
|
||||
}
|
||||
|
||||
private imageCache = new Map<string, string>()
|
||||
|
||||
async proxyImage(url: string): Promise<{ success: boolean; dataUrl?: string; error?: string }> {
|
||||
// Check cache
|
||||
if (this.imageCache.has(url)) {
|
||||
return { success: true, dataUrl: this.imageCache.get(url) }
|
||||
|
||||
async proxyImage(url: string, key?: string | number): Promise<{ success: boolean; dataUrl?: string; videoPath?: string; error?: string }> {
|
||||
if (!url) return { success: false, error: '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`)
|
||||
console.log(`[SnsService] 开始下载视频到临时文件: ${tmpPath}`)
|
||||
|
||||
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()
|
||||
console.log(`[SnsService] 视频下载完成,开始解密... Key: ${key}`)
|
||||
|
||||
try {
|
||||
const encryptedBuffer = await readFile(tmpPath)
|
||||
const raw = encryptedBuffer // 引用,方便后续操作
|
||||
|
||||
|
||||
if (key && String(key).trim().length > 0) {
|
||||
try {
|
||||
console.log(`[SnsService] 使用 WASM Isaac64 解密视频... Key: ${key}`)
|
||||
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
|
||||
console.warn(`[SnsService] WASM 解密不可用,回退 Isaac64: ${wasmErr}`)
|
||||
const isaac = new Isaac64(keyText)
|
||||
keystream = isaac.generateKeystream(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') {
|
||||
console.log(`[SnsService] 视频解密成功: ${url}`)
|
||||
} else {
|
||||
console.warn(`[SnsService] 视频解密可能失败: ${url}, 未找到 ftyp 签名: ${ftyp}`)
|
||||
// 打印前 32 字节用于调试
|
||||
console.warn(`[SnsService] Decrypted Header (first 32 bytes): ${raw.subarray(0, 32).toString('hex')}`)
|
||||
}
|
||||
} catch (err) {
|
||||
console.error(`[SnsService] 视频解密出错: ${err}`)
|
||||
}
|
||||
} else {
|
||||
console.warn(`[SnsService] 未提供 Key,跳过解密,直接保存`)
|
||||
}
|
||||
|
||||
// 写入最终缓存 (覆盖)
|
||||
await writeFile(cachePath, raw)
|
||||
console.log(`[SnsService] 视频已保存到缓存: ${cachePath}`)
|
||||
|
||||
// 删除临时文件
|
||||
try { await import('fs/promises').then(fs => fs.unlink(tmpPath)) } catch (e) { }
|
||||
|
||||
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) => {
|
||||
try {
|
||||
const https = require('https')
|
||||
@@ -191,17 +412,16 @@ class SnsService {
|
||||
path: urlObj.pathname + urlObj.search,
|
||||
method: 'GET',
|
||||
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",
|
||||
"Accept": "image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8",
|
||||
"Accept-Encoding": "gzip, deflate, br",
|
||||
"Accept-Language": "zh-CN,zh;q=0.9",
|
||||
"Referer": "https://servicewechat.com/",
|
||||
"Connection": "keep-alive"
|
||||
'User-Agent': 'MicroMessenger Client',
|
||||
'Accept': '*/*',
|
||||
'Accept-Encoding': 'gzip, deflate, br',
|
||||
'Accept-Language': 'zh-CN,zh;q=0.9',
|
||||
'Connection': 'keep-alive'
|
||||
}
|
||||
}
|
||||
|
||||
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}` })
|
||||
return
|
||||
}
|
||||
@@ -209,37 +429,39 @@ class SnsService {
|
||||
const chunks: Buffer[] = []
|
||||
let stream = res
|
||||
|
||||
// Handle gzip compression
|
||||
const encoding = res.headers['content-encoding']
|
||||
if (encoding === 'gzip') {
|
||||
stream = res.pipe(zlib.createGunzip())
|
||||
} else if (encoding === 'deflate') {
|
||||
stream = res.pipe(zlib.createInflate())
|
||||
} else if (encoding === 'br') {
|
||||
stream = res.pipe(zlib.createBrotliDecompress())
|
||||
}
|
||||
if (encoding === 'gzip') stream = res.pipe(zlib.createGunzip())
|
||||
else if (encoding === 'deflate') stream = res.pipe(zlib.createInflate())
|
||||
else if (encoding === 'br') stream = res.pipe(zlib.createBrotliDecompress())
|
||||
|
||||
stream.on('data', (chunk: Buffer) => chunks.push(chunk))
|
||||
stream.on('end', () => {
|
||||
const buffer = Buffer.concat(chunks)
|
||||
const contentType = res.headers['content-type'] || 'image/jpeg'
|
||||
const base64 = buffer.toString('base64')
|
||||
const dataUrl = `data:${contentType};base64,${base64}`
|
||||
stream.on('end', async () => {
|
||||
const raw = Buffer.concat(chunks)
|
||||
const xEnc = String(res.headers['x-enc'] || '').trim()
|
||||
|
||||
// Cache
|
||||
this.imageCache.set(url, dataUrl)
|
||||
let decoded = raw
|
||||
|
||||
resolve({ success: true, dataUrl })
|
||||
})
|
||||
stream.on('error', (e: any) => {
|
||||
resolve({ success: false, error: e.message })
|
||||
// 图片逻辑
|
||||
const shouldDecrypt = (xEnc === '1' || !!key) && key !== undefined && key !== null && String(key).trim().length > 0
|
||||
if (shouldDecrypt) {
|
||||
const decrypted = await wcdbService.decryptSnsImage(raw, String(key))
|
||||
decoded = Buffer.from(decrypted)
|
||||
}
|
||||
|
||||
// 写入磁盘缓存
|
||||
try {
|
||||
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) => {
|
||||
resolve({ success: false, error: e.message })
|
||||
})
|
||||
|
||||
req.on('error', (e: any) => resolve({ success: false, error: e.message }))
|
||||
req.end()
|
||||
} catch (e: any) {
|
||||
resolve({ success: false, error: e.message })
|
||||
|
||||
@@ -36,7 +36,7 @@ class VideoService {
|
||||
* 获取缓存目录(解密后的数据库存放位置)
|
||||
*/
|
||||
private getCachePath(): string {
|
||||
return this.configService.get('cachePath') || ''
|
||||
return this.configService.getCacheBasePath()
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -110,7 +110,7 @@ class VideoService {
|
||||
const wxidLower = wxid.toLowerCase()
|
||||
const cleanedWxidLower = cleanedWxid.toLowerCase()
|
||||
const dbPathContainsWxid = dbPathLower.includes(wxidLower) || dbPathLower.includes(cleanedWxidLower)
|
||||
|
||||
|
||||
const encryptedDbPaths: string[] = []
|
||||
if (dbPathContainsWxid) {
|
||||
// dbPath 已包含 wxid,不需要再拼接
|
||||
@@ -120,15 +120,15 @@ class VideoService {
|
||||
encryptedDbPaths.push(join(dbPath, wxid, 'db_storage', 'hardlink', 'hardlink.db'))
|
||||
encryptedDbPaths.push(join(dbPath, cleanedWxid, 'db_storage', 'hardlink', 'hardlink.db'))
|
||||
}
|
||||
|
||||
|
||||
for (const p of encryptedDbPaths) {
|
||||
if (existsSync(p)) {
|
||||
try {
|
||||
const escapedMd5 = md5.replace(/'/g, "''")
|
||||
|
||||
|
||||
// 用 md5 字段查询,获取 file_name
|
||||
const sql = `SELECT file_name FROM video_hardlink_info_v4 WHERE md5 = '${escapedMd5}' LIMIT 1`
|
||||
|
||||
|
||||
const result = await wcdbService.execQuery('media', p, sql)
|
||||
|
||||
if (result.success && result.rows && result.rows.length > 0) {
|
||||
@@ -181,7 +181,7 @@ class VideoService {
|
||||
const dbPathLower = dbPath.toLowerCase()
|
||||
const wxidLower = wxid.toLowerCase()
|
||||
const cleanedWxid = this.cleanWxid(wxid)
|
||||
|
||||
|
||||
let videoBaseDir: string
|
||||
if (dbPathLower.includes(wxidLower) || dbPathLower.includes(cleanedWxid.toLowerCase())) {
|
||||
// dbPath 已经包含 wxid,直接使用
|
||||
@@ -235,7 +235,7 @@ class VideoService {
|
||||
* 根据消息内容解析视频MD5
|
||||
*/
|
||||
parseVideoMd5(content: string): string | undefined {
|
||||
|
||||
|
||||
// 打印前500字符看看 XML 结构
|
||||
|
||||
if (!content) return undefined
|
||||
@@ -252,7 +252,7 @@ class VideoService {
|
||||
// 提取 md5(用于查询 hardlink.db)
|
||||
// 注意:不是 rawmd5,rawmd5 是另一个值
|
||||
// 格式: md5="xxx" 或 <md5>xxx</md5>
|
||||
|
||||
|
||||
// 尝试从videomsg标签中提取md5
|
||||
const videoMsgMatch = /<videomsg[^>]*\smd5\s*=\s*['"]([a-fA-F0-9]+)['"]/i.exec(content)
|
||||
if (videoMsgMatch) {
|
||||
|
||||
175
electron/services/wasmService.ts
Normal file
175
electron/services/wasmService.ts
Normal file
@@ -0,0 +1,175 @@
|
||||
|
||||
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');
|
||||
|
||||
console.log('[WasmService] Loading WASM from:', wasmPath);
|
||||
|
||||
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: () => {
|
||||
console.log("[WasmService] WASM Runtime Initialized");
|
||||
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> {
|
||||
await this.init();
|
||||
|
||||
if (!this.module || !this.module.WxIsaac64) {
|
||||
// Fallback check for asm.WxIsaac64 logic if needed, but debug showed it on Module
|
||||
if (this.module.asm && this.module.asm.WxIsaac64) {
|
||||
this.module.WxIsaac64 = this.module.asm.WxIsaac64;
|
||||
}
|
||||
}
|
||||
|
||||
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); // This triggers the global.wasm_isaac_generate callback
|
||||
|
||||
// Cleanup if possible? isaac.delete()?
|
||||
// In worker code: p.decryptor.delete()
|
||||
if (isaac.delete) {
|
||||
isaac.delete();
|
||||
}
|
||||
|
||||
if (this.capturedKeystream) {
|
||||
// The worker_release.js logic does:
|
||||
// p.decryptor_array.set(r.reverse())
|
||||
// So the actual keystream is the REVERSE of what is passed to the callback.
|
||||
const reversed = new Uint8Array(this.capturedKeystream);
|
||||
reversed.reverse();
|
||||
return Buffer.from(reversed);
|
||||
} else {
|
||||
throw new Error('[WasmService] Failed to capture keystream (callback not called)');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('[WasmService] Error generating keystream:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -46,6 +46,7 @@ export class WcdbCore {
|
||||
private wcdbGetAnnualReportExtras: any = null
|
||||
private wcdbGetDualReportStats: any = null
|
||||
private wcdbGetGroupStats: any = null
|
||||
private wcdbGetMessageDates: any = null
|
||||
private wcdbOpenMessageCursor: any = null
|
||||
private wcdbOpenMessageCursorLite: any = null
|
||||
private wcdbFetchMessageBatch: any = null
|
||||
@@ -63,7 +64,9 @@ export class WcdbCore {
|
||||
private wcdbVerifyUser: any = null
|
||||
private wcdbStartMonitorPipe: any = null
|
||||
private wcdbStopMonitorPipe: any = null
|
||||
|
||||
private monitorPipeClient: any = null
|
||||
private wcdbDecryptSnsImage: any = null
|
||||
|
||||
private avatarUrlCache: Map<string, { url?: string; updatedAt: number }> = new Map()
|
||||
private readonly avatarCacheTtlMs = 10 * 60 * 1000
|
||||
@@ -136,11 +139,48 @@ export class WcdbCore {
|
||||
this.writeLog('Monitor started via named pipe IPC')
|
||||
return true
|
||||
} catch (e) {
|
||||
console.error('startMonitor failed:', e)
|
||||
console.error('打开数据库异常:', e)
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 解密朋友圈图片
|
||||
*/
|
||||
async decryptSnsImage(encryptedData: Buffer, key: string): Promise<Buffer> {
|
||||
if (!this.initialized) {
|
||||
const initOk = await this.initialize()
|
||||
if (!initOk) return encryptedData
|
||||
}
|
||||
|
||||
if (!this.wcdbDecryptSnsImage) return encryptedData
|
||||
|
||||
try {
|
||||
if (!this.wcdbDecryptSnsImage) {
|
||||
console.error('[WCDB] wcdbDecryptSnsImage func is null')
|
||||
return encryptedData
|
||||
}
|
||||
|
||||
const outPtr = [null as any]
|
||||
// Koffi pass Buffer as char* pointer
|
||||
const result = this.wcdbDecryptSnsImage(encryptedData, encryptedData.length, key, outPtr)
|
||||
|
||||
if (result === 0 && outPtr[0]) {
|
||||
const hex = this.decodeJsonPtr(outPtr[0])
|
||||
if (hex) {
|
||||
return Buffer.from(hex, 'hex')
|
||||
}
|
||||
} else {
|
||||
console.error(`[WCDB] Decrypt SNS image failed with code: ${result}`)
|
||||
// 主动获取 DLL 内部日志以诊断问题
|
||||
await this.printLogs(true)
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('解密图片失败:', e)
|
||||
}
|
||||
return encryptedData
|
||||
}
|
||||
|
||||
stopMonitor(): void {
|
||||
if (this.monitorPipeClient) {
|
||||
this.monitorPipeClient.destroy()
|
||||
@@ -299,9 +339,6 @@ export class WcdbCore {
|
||||
return false
|
||||
}
|
||||
|
||||
// 关键修复:显式预加载依赖库 WCDB.dll 和 SDL2.dll
|
||||
// Windows 加载器默认不会查找子目录中的依赖,必须先将其加载到内存
|
||||
// 这可以解决部分用户因为 VC++ 运行时或 DLL 依赖问题导致的闪退
|
||||
const dllDir = dirname(dllPath)
|
||||
const wcdbCorePath = join(dllDir, 'WCDB.dll')
|
||||
if (existsSync(wcdbCorePath)) {
|
||||
@@ -478,6 +515,13 @@ export class WcdbCore {
|
||||
this.wcdbGetGroupStats = null
|
||||
}
|
||||
|
||||
// wcdb_status wcdb_get_message_dates(wcdb_handle handle, const char* session_id, char** out_json)
|
||||
try {
|
||||
this.wcdbGetMessageDates = this.lib.func('int32 wcdb_get_message_dates(int64 handle, const char* sessionId, _Out_ void** outJson)')
|
||||
} catch {
|
||||
this.wcdbGetMessageDates = null
|
||||
}
|
||||
|
||||
// wcdb_status wcdb_open_message_cursor(wcdb_handle handle, const char* session_id, int32_t batch_size, int32_t ascending, int32_t begin_timestamp, int32_t end_timestamp, wcdb_cursor* out_cursor)
|
||||
this.wcdbOpenMessageCursor = this.lib.func('int32 wcdb_open_message_cursor(int64 handle, const char* sessionId, int32 batchSize, int32 ascending, int32 beginTimestamp, int32 endTimestamp, _Out_ int64* outCursor)')
|
||||
|
||||
@@ -558,6 +602,13 @@ export class WcdbCore {
|
||||
this.wcdbVerifyUser = null
|
||||
}
|
||||
|
||||
// wcdb_status wcdb_decrypt_sns_image(const char* encrypted_data, int32_t data_len, const char* key, char** out_hex)
|
||||
try {
|
||||
this.wcdbDecryptSnsImage = this.lib.func('int32 wcdb_decrypt_sns_image(const char* data, int32 len, const char* key, _Out_ void** outHex)')
|
||||
} catch {
|
||||
this.wcdbDecryptSnsImage = null
|
||||
}
|
||||
|
||||
// 初始化
|
||||
const initResult = this.wcdbInit()
|
||||
if (initResult !== 0) {
|
||||
@@ -1194,6 +1245,29 @@ export class WcdbCore {
|
||||
}
|
||||
}
|
||||
|
||||
async getMessageDates(sessionId: string): Promise<{ success: boolean; dates?: string[]; error?: string }> {
|
||||
if (!this.ensureReady()) {
|
||||
return { success: false, error: 'WCDB 未连接' }
|
||||
}
|
||||
try {
|
||||
if (!this.wcdbGetMessageDates) {
|
||||
return { success: false, error: 'DLL 不支持 getMessageDates' }
|
||||
}
|
||||
const outPtr = [null as any]
|
||||
const result = this.wcdbGetMessageDates(this.handle, sessionId, outPtr)
|
||||
if (result !== 0 || !outPtr[0]) {
|
||||
// 空结果也可能是正常的(无消息)
|
||||
return { success: true, dates: [] }
|
||||
}
|
||||
const jsonStr = this.decodeJsonPtr(outPtr[0])
|
||||
if (!jsonStr) return { success: false, error: '解析日期列表失败' }
|
||||
const dates = JSON.parse(jsonStr)
|
||||
return { success: true, dates }
|
||||
} catch (e) {
|
||||
return { success: false, error: String(e) }
|
||||
}
|
||||
}
|
||||
|
||||
async getMessageTableStats(sessionId: string): Promise<{ success: boolean; tables?: any[]; error?: string }> {
|
||||
if (!this.ensureReady()) {
|
||||
return { success: false, error: 'WCDB 未连接' }
|
||||
|
||||
@@ -273,6 +273,10 @@ export class WcdbService {
|
||||
return this.callWorker('getMessageTableStats', { sessionId })
|
||||
}
|
||||
|
||||
async getMessageDates(sessionId: string): Promise<{ success: boolean; dates?: string[]; error?: string }> {
|
||||
return this.callWorker('getMessageDates', { sessionId })
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取消息元数据
|
||||
*/
|
||||
@@ -427,6 +431,13 @@ export class WcdbService {
|
||||
return this.callWorker('verifyUser', { message, hwnd })
|
||||
}
|
||||
|
||||
/**
|
||||
* 解密朋友圈图片
|
||||
*/
|
||||
async decryptSnsImage(encryptedData: Buffer, key: string): Promise<Buffer> {
|
||||
return this.callWorker<Buffer>('decryptSnsImage', { encryptedData, key })
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
export const wcdbService = new WcdbService()
|
||||
|
||||
@@ -78,6 +78,9 @@ if (parentPort) {
|
||||
case 'getMessageTableStats':
|
||||
result = await core.getMessageTableStats(payload.sessionId)
|
||||
break
|
||||
case 'getMessageDates':
|
||||
result = await core.getMessageDates(payload.sessionId)
|
||||
break
|
||||
case 'getMessageMeta':
|
||||
result = await core.getMessageMeta(payload.dbPath, payload.tableName, payload.limit, payload.offset)
|
||||
break
|
||||
@@ -147,6 +150,9 @@ if (parentPort) {
|
||||
case 'verifyUser':
|
||||
result = await core.verifyUser(payload.message, payload.hwnd)
|
||||
break
|
||||
case 'decryptSnsImage':
|
||||
result = await core.decryptSnsImage(payload.encryptedData, payload.key)
|
||||
break
|
||||
default:
|
||||
result = { success: false, error: `Unknown method: ${type}` }
|
||||
}
|
||||
|
||||
@@ -76,12 +76,10 @@ export async function showNotification(data: any) {
|
||||
const isInList = filterList.includes(sessionId)
|
||||
if (filterMode === 'whitelist' && !isInList) {
|
||||
// 白名单模式:不在列表中则不显示
|
||||
console.log('[NotificationWindow] Filtered by whitelist:', sessionId)
|
||||
return
|
||||
}
|
||||
if (filterMode === 'blacklist' && isInList) {
|
||||
// 黑名单模式:在列表中则不显示
|
||||
console.log('[NotificationWindow] Filtered by blacklist:', sessionId)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
8
package-lock.json
generated
8
package-lock.json
generated
@@ -11428,12 +11428,6 @@
|
||||
"sherpa-onnx-win-x64": "^1.12.23"
|
||||
}
|
||||
},
|
||||
"node_modules/sherpa-onnx-node/node_modules/sherpa-onnx-darwin-x64": {
|
||||
"optional": true
|
||||
},
|
||||
"node_modules/sherpa-onnx-node/node_modules/sherpa-onnx-linux-arm64": {
|
||||
"optional": true
|
||||
},
|
||||
"node_modules/sherpa-onnx-win-ia32": {
|
||||
"version": "1.12.23",
|
||||
"resolved": "https://registry.npmmirror.com/sherpa-onnx-win-ia32/-/sherpa-onnx-win-ia32-1.12.23.tgz",
|
||||
@@ -13032,4 +13026,4 @@
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -10,7 +10,7 @@
|
||||
},
|
||||
"//": "二改不应改变此处的作者与应用信息",
|
||||
"scripts": {
|
||||
"postinstall": "echo 'No native modules to rebuild'",
|
||||
"postinstall": "electron-builder install-app-deps",
|
||||
"rebuild": "electron-rebuild",
|
||||
"dev": "vite",
|
||||
"build": "tsc && vite build && electron-builder",
|
||||
@@ -107,6 +107,10 @@
|
||||
{
|
||||
"from": "public/icon.ico",
|
||||
"to": "icon.ico"
|
||||
},
|
||||
{
|
||||
"from": "electron/assets/wasm/",
|
||||
"to": "assets/wasm/"
|
||||
}
|
||||
],
|
||||
"files": [
|
||||
|
||||
Binary file not shown.
@@ -70,6 +70,7 @@
|
||||
opacity: 0;
|
||||
transform: translateY(-8px);
|
||||
}
|
||||
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: translateY(0);
|
||||
@@ -144,6 +145,7 @@
|
||||
.calendar-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(7, 1fr);
|
||||
grid-template-rows: auto repeat(6, 32px);
|
||||
gap: 2px;
|
||||
}
|
||||
|
||||
@@ -156,7 +158,6 @@
|
||||
}
|
||||
|
||||
.calendar-day {
|
||||
aspect-ratio: 1;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
@@ -211,4 +212,4 @@
|
||||
padding-top: 12px;
|
||||
border-top: 1px solid var(--border-color);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -86,7 +86,7 @@ function DateRangePicker({ startDate, endDate, onStartDateChange, onEndDateChang
|
||||
|
||||
const handleDateClick = (day: number) => {
|
||||
const dateStr = `${currentMonth.getFullYear()}-${String(currentMonth.getMonth() + 1).padStart(2, '0')}-${String(day).padStart(2, '0')}`
|
||||
|
||||
|
||||
if (selectingStart) {
|
||||
onStartDateChange(dateStr)
|
||||
if (endDate && dateStr > endDate) {
|
||||
@@ -125,8 +125,8 @@ function DateRangePicker({ startDate, endDate, onStartDateChange, onEndDateChang
|
||||
const isToday = (day: number) => {
|
||||
const today = new Date()
|
||||
return currentMonth.getFullYear() === today.getFullYear() &&
|
||||
currentMonth.getMonth() === today.getMonth() &&
|
||||
day === today.getDate()
|
||||
currentMonth.getMonth() === today.getMonth() &&
|
||||
day === today.getDate()
|
||||
}
|
||||
|
||||
const renderCalendar = () => {
|
||||
|
||||
@@ -14,12 +14,21 @@
|
||||
max-height: 90vh;
|
||||
object-fit: contain;
|
||||
transition: transform 0.15s ease-out;
|
||||
|
||||
|
||||
&.dragging {
|
||||
transition: none;
|
||||
}
|
||||
}
|
||||
|
||||
.preview-content {
|
||||
position: relative;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: fit-content;
|
||||
height: fit-content;
|
||||
}
|
||||
|
||||
.image-preview-close {
|
||||
position: absolute;
|
||||
bottom: 40px;
|
||||
@@ -44,3 +53,38 @@
|
||||
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 { X } from 'lucide-react'
|
||||
import { LivePhotoIcon } from './LivePhotoIcon'
|
||||
import { createPortal } from 'react-dom'
|
||||
import './ImagePreview.scss'
|
||||
|
||||
interface ImagePreviewProps {
|
||||
src: string
|
||||
isVideo?: boolean
|
||||
liveVideoPath?: string
|
||||
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 [position, setPosition] = useState({ x: 0, y: 0 })
|
||||
const [isDragging, setIsDragging] = useState(false)
|
||||
const [showLive, setShowLive] = useState(false)
|
||||
const dragStart = useRef({ x: 0, y: 0 })
|
||||
const positionStart = useRef({ x: 0, y: 0 })
|
||||
const containerRef = useRef<HTMLDivElement>(null)
|
||||
|
||||
// 滚轮缩放
|
||||
const handleWheel = useCallback((e: React.WheelEvent) => {
|
||||
if (showLive) return // 播放实况时禁止缩放? 或者支持缩放? 暂定禁止以简化
|
||||
e.preventDefault()
|
||||
const delta = e.deltaY > 0 ? 0.9 : 1.1
|
||||
setScale(prev => Math.min(Math.max(prev * delta, 0.5), 5))
|
||||
}, [])
|
||||
}, [showLive])
|
||||
|
||||
// 开始拖动
|
||||
const handleMouseDown = useCallback((e: React.MouseEvent) => {
|
||||
if (scale <= 1) return
|
||||
if (showLive || scale <= 1) return
|
||||
e.preventDefault()
|
||||
setIsDragging(true)
|
||||
dragStart.current = { x: e.clientX, y: e.clientY }
|
||||
positionStart.current = { ...position }
|
||||
}, [scale, position])
|
||||
}, [scale, position, showLive])
|
||||
|
||||
// 拖动中
|
||||
const handleMouseMove = useCallback((e: React.MouseEvent) => {
|
||||
@@ -79,19 +84,62 @@ export const ImagePreview: React.FC<ImagePreviewProps> = ({ src, onClose }) => {
|
||||
onMouseUp={handleMouseUp}
|
||||
onMouseLeave={handleMouseUp}
|
||||
>
|
||||
<img
|
||||
src={src}
|
||||
alt="图片预览"
|
||||
className={`preview-image ${isDragging ? 'dragging' : ''}`}
|
||||
<div
|
||||
className="preview-content"
|
||||
style={{
|
||||
transform: `translate(${position.x}px, ${position.y}px) scale(${scale})`,
|
||||
cursor: scale > 1 ? (isDragging ? 'grabbing' : 'grab') : 'default'
|
||||
position: 'relative',
|
||||
transform: `translate(${position.x}px, ${position.y}px)`,
|
||||
width: 'fit-content',
|
||||
height: 'fit-content'
|
||||
}}
|
||||
onWheel={handleWheel}
|
||||
onMouseDown={handleMouseDown}
|
||||
onDoubleClick={handleDoubleClick}
|
||||
draggable={false}
|
||||
/>
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
{(isVideo || showLive) ? (
|
||||
<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}>
|
||||
<X size={20} />
|
||||
</button>
|
||||
|
||||
@@ -100,6 +100,33 @@
|
||||
}
|
||||
|
||||
.calendar-grid {
|
||||
position: relative;
|
||||
|
||||
&.loading {
|
||||
|
||||
.weekdays,
|
||||
.days {
|
||||
pointer-events: none;
|
||||
}
|
||||
}
|
||||
|
||||
.calendar-loading {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 8px;
|
||||
color: var(--text-secondary);
|
||||
font-size: 13px;
|
||||
|
||||
.spin {
|
||||
color: var(--primary);
|
||||
animation: spin 1s linear infinite;
|
||||
}
|
||||
}
|
||||
|
||||
.weekdays {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(7, 1fr);
|
||||
@@ -117,10 +144,10 @@
|
||||
.days {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(7, 1fr);
|
||||
grid-template-rows: repeat(6, 36px);
|
||||
gap: 4px;
|
||||
|
||||
.day-cell {
|
||||
aspect-ratio: 1;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
@@ -129,12 +156,13 @@
|
||||
border-radius: 8px;
|
||||
cursor: pointer;
|
||||
transition: all 0.2s;
|
||||
position: relative;
|
||||
|
||||
&.empty {
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
&:not(.empty):hover {
|
||||
&:not(.empty):not(.no-message):hover {
|
||||
background: var(--bg-hover);
|
||||
}
|
||||
|
||||
@@ -149,10 +177,43 @@
|
||||
font-weight: 600;
|
||||
background: var(--primary-light);
|
||||
}
|
||||
|
||||
// 无消息的日期 - 灰显且不可点击
|
||||
&.no-message {
|
||||
opacity: 0.3;
|
||||
cursor: default;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
// 有消息的日期指示器小圆点
|
||||
.message-dot {
|
||||
position: absolute;
|
||||
bottom: 3px;
|
||||
left: 50%;
|
||||
transform: translateX(-50%);
|
||||
width: 4px;
|
||||
height: 4px;
|
||||
border-radius: 50%;
|
||||
background: var(--primary);
|
||||
}
|
||||
|
||||
&.selected .message-dot {
|
||||
background: rgba(255, 255, 255, 0.7);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes spin {
|
||||
from {
|
||||
transform: rotate(0deg);
|
||||
}
|
||||
|
||||
to {
|
||||
transform: rotate(360deg);
|
||||
}
|
||||
}
|
||||
|
||||
.quick-options {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import React, { useState } from 'react'
|
||||
import { X, ChevronLeft, ChevronRight, Calendar as CalendarIcon } from 'lucide-react'
|
||||
import React, { useState, useMemo } from 'react'
|
||||
import { X, ChevronLeft, ChevronRight, Calendar as CalendarIcon, Loader2 } from 'lucide-react'
|
||||
import './JumpToDateDialog.scss'
|
||||
|
||||
interface JumpToDateDialogProps {
|
||||
@@ -7,15 +7,22 @@ interface JumpToDateDialogProps {
|
||||
onClose: () => void
|
||||
onSelect: (date: Date) => void
|
||||
currentDate?: Date
|
||||
/** 有消息的日期集合,格式为 YYYY-MM-DD */
|
||||
messageDates?: Set<string>
|
||||
/** 是否正在加载消息日期 */
|
||||
loadingDates?: boolean
|
||||
}
|
||||
|
||||
const JumpToDateDialog: React.FC<JumpToDateDialogProps> = ({
|
||||
isOpen,
|
||||
onClose,
|
||||
onSelect,
|
||||
currentDate = new Date()
|
||||
currentDate = new Date(),
|
||||
messageDates,
|
||||
loadingDates = false
|
||||
}) => {
|
||||
const [calendarDate, setCalendarDate] = useState(new Date(currentDate))
|
||||
const isValidDate = (d: any) => d instanceof Date && !isNaN(d.getTime())
|
||||
const [calendarDate, setCalendarDate] = useState(isValidDate(currentDate) ? new Date(currentDate) : new Date())
|
||||
const [selectedDate, setSelectedDate] = useState(new Date(currentDate))
|
||||
|
||||
if (!isOpen) return null
|
||||
@@ -48,7 +55,20 @@ const JumpToDateDialog: React.FC<JumpToDateDialogProps> = ({
|
||||
return days
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断某天是否有消息
|
||||
*/
|
||||
const hasMessage = (day: number): boolean => {
|
||||
if (!messageDates || messageDates.size === 0) return true // 未加载时默认全部可点击
|
||||
const year = calendarDate.getFullYear()
|
||||
const month = calendarDate.getMonth() + 1
|
||||
const dateStr = `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`
|
||||
return messageDates.has(dateStr)
|
||||
}
|
||||
|
||||
const handleDateClick = (day: number) => {
|
||||
// 如果已加载日期数据且该日期无消息,则不可点击
|
||||
if (messageDates && messageDates.size > 0 && !hasMessage(day)) return
|
||||
const newDate = new Date(calendarDate.getFullYear(), calendarDate.getMonth(), day)
|
||||
setSelectedDate(newDate)
|
||||
}
|
||||
@@ -71,6 +91,28 @@ const JumpToDateDialog: React.FC<JumpToDateDialogProps> = ({
|
||||
calendarDate.getFullYear() === selectedDate.getFullYear()
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取某天的 CSS 类名
|
||||
*/
|
||||
const getDayClassName = (day: number | null): string => {
|
||||
if (day === null) return 'day-cell empty'
|
||||
|
||||
const classes = ['day-cell']
|
||||
if (isSelected(day)) classes.push('selected')
|
||||
if (isToday(day)) classes.push('today')
|
||||
|
||||
// 仅在已加载消息日期数据时区分有/无消息
|
||||
if (messageDates && messageDates.size > 0) {
|
||||
if (hasMessage(day)) {
|
||||
classes.push('has-message')
|
||||
} else {
|
||||
classes.push('no-message')
|
||||
}
|
||||
}
|
||||
|
||||
return classes.join(' ')
|
||||
}
|
||||
|
||||
const weekdays = ['日', '一', '二', '三', '四', '五', '六']
|
||||
const days = generateCalendar()
|
||||
|
||||
@@ -106,18 +148,28 @@ const JumpToDateDialog: React.FC<JumpToDateDialogProps> = ({
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="calendar-grid">
|
||||
<div className="weekdays">
|
||||
<div className={`calendar-grid ${loadingDates ? 'loading' : ''}`}>
|
||||
{loadingDates && (
|
||||
<div className="calendar-loading">
|
||||
<Loader2 size={20} className="spin" />
|
||||
<span>正在加载...</span>
|
||||
</div>
|
||||
)}
|
||||
<div className="weekdays" style={{ visibility: loadingDates ? 'hidden' : 'visible' }}>
|
||||
{weekdays.map(d => <div key={d} className="weekday">{d}</div>)}
|
||||
</div>
|
||||
<div className="days">
|
||||
<div className="days" style={{ visibility: loadingDates ? 'hidden' : 'visible' }}>
|
||||
{days.map((day, i) => (
|
||||
<div
|
||||
key={i}
|
||||
className={`day-cell ${day === null ? 'empty' : ''} ${day !== null && isSelected(day) ? 'selected' : ''} ${day !== null && isToday(day) ? 'today' : ''}`}
|
||||
className={getDayClassName(day)}
|
||||
style={{ visibility: loadingDates ? 'hidden' : 'visible' }}
|
||||
onClick={() => day !== null && handleDateClick(day)}
|
||||
>
|
||||
{day}
|
||||
{day !== null && messageDates && messageDates.size > 0 && hasMessage(day) && (
|
||||
<span className="message-dot" />
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
@@ -87,8 +87,8 @@
|
||||
position: absolute;
|
||||
inset: -6%;
|
||||
background:
|
||||
radial-gradient(circle at 35% 45%, color-mix(in srgb, var(--primary, #07C160) 12%, transparent), transparent 55%),
|
||||
radial-gradient(circle at 65% 50%, color-mix(in srgb, var(--accent, #F2AA00) 10%, transparent), transparent 58%),
|
||||
radial-gradient(circle at 35% 45%, rgba(var(--ar-primary-rgb, 7, 193, 96), 0.12), transparent 55%),
|
||||
radial-gradient(circle at 65% 50%, rgba(var(--ar-accent-rgb, 242, 170, 0), 0.10), transparent 58%),
|
||||
radial-gradient(circle at 50% 65%, var(--bg-tertiary, rgba(0, 0, 0, 0.04)), transparent 60%);
|
||||
filter: blur(18px);
|
||||
border-radius: 50%;
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
.annual-report-window {
|
||||
// 使用全局主题变量,带回退值
|
||||
--ar-primary: var(--primary, #07C160);
|
||||
--ar-primary-rgb: var(--primary-rgb, 7, 193, 96);
|
||||
--ar-accent: var(--accent, #F2AA00);
|
||||
--ar-accent-rgb: 242, 170, 0;
|
||||
--ar-text-main: var(--text-primary, #222222);
|
||||
--ar-text-sub: var(--text-secondary, #555555);
|
||||
--ar-bg-color: var(--bg-primary, #F9F8F6);
|
||||
@@ -53,7 +55,7 @@
|
||||
.deco-circle {
|
||||
position: absolute;
|
||||
border-radius: 50%;
|
||||
background: color-mix(in srgb, var(--primary) 3%, transparent);
|
||||
background: rgba(var(--ar-primary-rgb), 0.03);
|
||||
backdrop-filter: blur(40px);
|
||||
-webkit-backdrop-filter: blur(40px);
|
||||
border: 1px solid var(--border-color);
|
||||
@@ -254,6 +256,11 @@
|
||||
background: transparent !important;
|
||||
box-shadow: none !important;
|
||||
}
|
||||
|
||||
.deco-circle {
|
||||
background: transparent !important;
|
||||
border: none !important;
|
||||
}
|
||||
}
|
||||
|
||||
.section {
|
||||
|
||||
@@ -164,6 +164,9 @@ function ChatPage(_props: ChatPageProps) {
|
||||
const [jumpStartTime, setJumpStartTime] = useState(0)
|
||||
const [jumpEndTime, setJumpEndTime] = useState(0)
|
||||
const [showJumpDialog, setShowJumpDialog] = useState(false)
|
||||
const [messageDates, setMessageDates] = useState<Set<string>>(new Set())
|
||||
const [loadingDates, setLoadingDates] = useState(false)
|
||||
const messageDatesCache = useRef<Map<string, Set<string>>>(new Map())
|
||||
const [myAvatarUrl, setMyAvatarUrl] = useState<string | undefined>(undefined)
|
||||
const [myWxid, setMyWxid] = useState<string | undefined>(undefined)
|
||||
const [showScrollToBottom, setShowScrollToBottom] = useState(false)
|
||||
@@ -680,12 +683,32 @@ function ChatPage(_props: ChatPageProps) {
|
||||
|
||||
|
||||
|
||||
// 动态游标批量大小控制
|
||||
const currentBatchSizeRef = useRef(50)
|
||||
|
||||
// 加载消息
|
||||
const loadMessages = async (sessionId: string, offset = 0, startTime = 0, endTime = 0) => {
|
||||
const listEl = messageListRef.current
|
||||
const session = sessionMapRef.current.get(sessionId)
|
||||
const unreadCount = session?.unreadCount ?? 0
|
||||
const messageLimit = offset === 0 && unreadCount > 99 ? 30 : 50
|
||||
|
||||
let messageLimit = 50
|
||||
|
||||
if (offset === 0) {
|
||||
// 初始加载:重置批量大小
|
||||
currentBatchSizeRef.current = 50
|
||||
// 首屏优化:消息过多时限制数量
|
||||
messageLimit = unreadCount > 99 ? 30 : 50
|
||||
} else {
|
||||
// 滚动加载:动态递增 (50 -> 100 -> 200)
|
||||
if (currentBatchSizeRef.current < 100) {
|
||||
currentBatchSizeRef.current = 100
|
||||
} else {
|
||||
currentBatchSizeRef.current = 200
|
||||
}
|
||||
messageLimit = currentBatchSizeRef.current
|
||||
}
|
||||
|
||||
|
||||
if (offset === 0) {
|
||||
setLoadingMessages(true)
|
||||
@@ -1523,7 +1546,31 @@ function ChatPage(_props: ChatPageProps) {
|
||||
</button>
|
||||
<button
|
||||
className="icon-btn jump-to-time-btn"
|
||||
onClick={() => setShowJumpDialog(true)}
|
||||
onClick={async () => {
|
||||
setShowJumpDialog(true)
|
||||
if (!currentSessionId) return
|
||||
// 检查缓存
|
||||
const cached = messageDatesCache.current.get(currentSessionId)
|
||||
if (cached) {
|
||||
setMessageDates(cached)
|
||||
return
|
||||
}
|
||||
// 获取消息日期
|
||||
setMessageDates(new Set()) // 清除旧数据
|
||||
setLoadingDates(true)
|
||||
try {
|
||||
const result = await (window as any).electronAPI.chat.getMessageDates(currentSessionId)
|
||||
if (result?.success && result.dates) {
|
||||
const dateSet = new Set<string>(result.dates)
|
||||
setMessageDates(dateSet)
|
||||
messageDatesCache.current.set(currentSessionId, dateSet)
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('获取消息日期失败:', e)
|
||||
} finally {
|
||||
setLoadingDates(false)
|
||||
}
|
||||
}}
|
||||
title="跳转到指定时间"
|
||||
>
|
||||
<Calendar size={18} />
|
||||
@@ -1539,6 +1586,8 @@ function ChatPage(_props: ChatPageProps) {
|
||||
setJumpEndTime(end)
|
||||
loadMessages(currentSessionId, 0, 0, end)
|
||||
}}
|
||||
messageDates={messageDates}
|
||||
loadingDates={loadingDates}
|
||||
/>
|
||||
<button
|
||||
className="icon-btn refresh-messages-btn"
|
||||
|
||||
@@ -906,4 +906,79 @@
|
||||
min-width: 56px;
|
||||
}
|
||||
}
|
||||
|
||||
// Word Cloud Tabs
|
||||
.word-cloud-section {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.word-cloud-tabs {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
background: rgba(255, 255, 255, 0.08);
|
||||
padding: 4px;
|
||||
border-radius: 12px;
|
||||
margin: 0 auto 32px;
|
||||
border: 1px solid rgba(255, 255, 255, 0.1);
|
||||
}
|
||||
|
||||
.tab-item {
|
||||
padding: 8px 16px;
|
||||
border-radius: 8px;
|
||||
border: none;
|
||||
background: transparent;
|
||||
color: var(--ar-text-sub);
|
||||
font-size: 14px;
|
||||
font-weight: 500;
|
||||
cursor: pointer;
|
||||
transition: all 0.2s ease;
|
||||
white-space: nowrap;
|
||||
|
||||
&:hover {
|
||||
color: var(--ar-text-main);
|
||||
background: rgba(255, 255, 255, 0.05);
|
||||
}
|
||||
|
||||
&.active {
|
||||
background: var(--ar-card-bg);
|
||||
color: var(--ar-primary);
|
||||
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
|
||||
font-weight: 600;
|
||||
}
|
||||
}
|
||||
|
||||
.word-cloud-container {
|
||||
width: 100%;
|
||||
|
||||
&.fade-in {
|
||||
animation: fadeIn 0.4s ease-out;
|
||||
}
|
||||
}
|
||||
|
||||
.empty-state {
|
||||
text-align: center;
|
||||
padding: 40px 0;
|
||||
color: var(--ar-text-sub);
|
||||
opacity: 0.6;
|
||||
font-size: 14px;
|
||||
background: rgba(255, 255, 255, 0.03);
|
||||
border-radius: 16px;
|
||||
border: 1px dashed rgba(255, 255, 255, 0.1);
|
||||
margin-top: 20px;
|
||||
}
|
||||
|
||||
@keyframes fadeIn {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translateY(10px);
|
||||
}
|
||||
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: translateY(0);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -57,6 +57,8 @@ interface DualReportData {
|
||||
friendTopEmojiCount?: number
|
||||
}
|
||||
topPhrases: Array<{ phrase: string; count: number }>
|
||||
myExclusivePhrases: Array<{ phrase: string; count: number }>
|
||||
friendExclusivePhrases: Array<{ phrase: string; count: number }>
|
||||
heatmap?: number[][]
|
||||
initiative?: { initiated: number; received: number }
|
||||
response?: { avg: number; fastest: number; slowest: number; count: number }
|
||||
@@ -72,6 +74,7 @@ function DualReportWindow() {
|
||||
const [loadingProgress, setLoadingProgress] = useState(0)
|
||||
const [myEmojiUrl, setMyEmojiUrl] = useState<string | null>(null)
|
||||
const [friendEmojiUrl, setFriendEmojiUrl] = useState<string | null>(null)
|
||||
const [activeWordCloudTab, setActiveWordCloudTab] = useState<'shared' | 'my' | 'friend'>('shared')
|
||||
|
||||
useEffect(() => {
|
||||
const params = new URLSearchParams(window.location.hash.split('?')[1] || '')
|
||||
@@ -584,10 +587,48 @@ function DualReportWindow() {
|
||||
</section>
|
||||
)}
|
||||
|
||||
<section className="section">
|
||||
<section className="section word-cloud-section">
|
||||
<div className="label-text">常用语</div>
|
||||
<h2 className="hero-title">{yearTitle}常用语</h2>
|
||||
<ReportWordCloud words={reportData.topPhrases} />
|
||||
|
||||
<div className="word-cloud-tabs">
|
||||
<button
|
||||
className={`tab-item ${activeWordCloudTab === 'shared' ? 'active' : ''}`}
|
||||
onClick={() => setActiveWordCloudTab('shared')}
|
||||
>
|
||||
共用词汇
|
||||
</button>
|
||||
<button
|
||||
className={`tab-item ${activeWordCloudTab === 'my' ? 'active' : ''}`}
|
||||
onClick={() => setActiveWordCloudTab('my')}
|
||||
>
|
||||
我的专属
|
||||
</button>
|
||||
<button
|
||||
className={`tab-item ${activeWordCloudTab === 'friend' ? 'active' : ''}`}
|
||||
onClick={() => setActiveWordCloudTab('friend')}
|
||||
>
|
||||
TA的专属
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className={`word-cloud-container fade-in ${activeWordCloudTab}`}>
|
||||
{activeWordCloudTab === 'shared' && <ReportWordCloud words={reportData.topPhrases} />}
|
||||
{activeWordCloudTab === 'my' && (
|
||||
reportData.myExclusivePhrases && reportData.myExclusivePhrases.length > 0 ? (
|
||||
<ReportWordCloud words={reportData.myExclusivePhrases} />
|
||||
) : (
|
||||
<div className="empty-state">暂无专属词汇</div>
|
||||
)
|
||||
)}
|
||||
{activeWordCloudTab === 'friend' && (
|
||||
reportData.friendExclusivePhrases && reportData.friendExclusivePhrases.length > 0 ? (
|
||||
<ReportWordCloud words={reportData.friendExclusivePhrases} />
|
||||
) : (
|
||||
<div className="empty-state">暂无专属词汇</div>
|
||||
)
|
||||
)}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="section">
|
||||
|
||||
@@ -830,8 +830,7 @@
|
||||
padding: 28px 32px;
|
||||
border-radius: 16px;
|
||||
box-shadow: 0 20px 60px rgba(0, 0, 0, 0.25);
|
||||
min-width: 420px;
|
||||
max-width: 500px;
|
||||
width: 420px;
|
||||
|
||||
h3 {
|
||||
font-size: 18px;
|
||||
@@ -977,10 +976,10 @@
|
||||
.calendar-days {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(7, 1fr);
|
||||
grid-template-rows: repeat(6, 40px);
|
||||
gap: 4px;
|
||||
|
||||
.calendar-day {
|
||||
aspect-ratio: 1;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
|
||||
@@ -1084,7 +1084,7 @@ function ExportPage() {
|
||||
>
|
||||
<span className="date-label">开始日期</span>
|
||||
<span className="date-value">
|
||||
{options.dateRange?.start.toLocaleDateString('zh-CN', {
|
||||
{options.dateRange?.start?.toLocaleDateString('zh-CN', {
|
||||
year: 'numeric',
|
||||
month: '2-digit',
|
||||
day: '2-digit'
|
||||
@@ -1098,7 +1098,7 @@ function ExportPage() {
|
||||
>
|
||||
<span className="date-label">结束日期</span>
|
||||
<span className="date-value">
|
||||
{options.dateRange?.end.toLocaleDateString('zh-CN', {
|
||||
{options.dateRange?.end?.toLocaleDateString('zh-CN', {
|
||||
year: 'numeric',
|
||||
month: '2-digit',
|
||||
day: '2-digit'
|
||||
@@ -1136,9 +1136,9 @@ function ExportPage() {
|
||||
}
|
||||
|
||||
const currentDate = new Date(calendarDate.getFullYear(), calendarDate.getMonth(), day)
|
||||
const isStart = options.dateRange?.start.toDateString() === currentDate.toDateString()
|
||||
const isEnd = options.dateRange?.end.toDateString() === currentDate.toDateString()
|
||||
const isInRange = options.dateRange && currentDate >= options.dateRange.start && currentDate <= options.dateRange.end
|
||||
const isStart = options.dateRange?.start?.toDateString() === currentDate.toDateString()
|
||||
const isEnd = options.dateRange?.end?.toDateString() === currentDate.toDateString()
|
||||
const isInRange = options.dateRange?.start && options.dateRange?.end && currentDate >= options.dateRange.start && currentDate <= options.dateRange.end
|
||||
const today = new Date()
|
||||
today.setHours(0, 0, 0, 0)
|
||||
const isFuture = currentDate > today
|
||||
|
||||
@@ -1279,6 +1279,7 @@
|
||||
from {
|
||||
opacity: 0;
|
||||
}
|
||||
|
||||
to {
|
||||
opacity: 1;
|
||||
}
|
||||
@@ -1289,6 +1290,7 @@
|
||||
opacity: 0;
|
||||
transform: translateY(10px);
|
||||
}
|
||||
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: translateY(0);
|
||||
@@ -2097,9 +2099,77 @@
|
||||
.btn-sm {
|
||||
padding: 4px 10px !important;
|
||||
font-size: 12px !important;
|
||||
|
||||
|
||||
|
||||
svg {
|
||||
width: 14px;
|
||||
height: 14px;
|
||||
}
|
||||
}
|
||||
|
||||
// Analysis Settings Styling
|
||||
.settings-section {
|
||||
h2 {
|
||||
font-size: 18px;
|
||||
font-weight: 600;
|
||||
color: var(--text-primary);
|
||||
margin: 0 0 16px;
|
||||
}
|
||||
}
|
||||
|
||||
.setting-item {
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
.setting-label {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
margin-bottom: 8px;
|
||||
|
||||
span:first-child {
|
||||
font-size: 14px;
|
||||
font-weight: 500;
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.setting-desc {
|
||||
font-size: 13px;
|
||||
color: var(--text-tertiary);
|
||||
margin-top: 2px;
|
||||
}
|
||||
}
|
||||
|
||||
.setting-control {
|
||||
display: flex;
|
||||
|
||||
// textarea specific
|
||||
textarea.form-input {
|
||||
width: 100%;
|
||||
padding: 12px;
|
||||
background: var(--bg-primary);
|
||||
border: 1px solid var(--border-color);
|
||||
border-radius: 12px;
|
||||
color: var(--text-primary);
|
||||
font-family: monospace;
|
||||
font-size: 13px;
|
||||
resize: vertical;
|
||||
transition: all 0.2s;
|
||||
outline: none;
|
||||
|
||||
&:focus {
|
||||
border-color: var(--primary);
|
||||
box-shadow: 0 0 0 3px color-mix(in srgb, var(--primary) 10%, transparent);
|
||||
}
|
||||
|
||||
&::placeholder {
|
||||
color: var(--text-tertiary);
|
||||
}
|
||||
}
|
||||
|
||||
.button-group {
|
||||
display: flex;
|
||||
gap: 12px;
|
||||
width: 100%;
|
||||
margin-top: 12px;
|
||||
}
|
||||
}
|
||||
@@ -9,12 +9,12 @@ import {
|
||||
Eye, EyeOff, FolderSearch, FolderOpen, Search, Copy,
|
||||
RotateCcw, Trash2, Plug, Check, Sun, Moon,
|
||||
Palette, Database, Download, HardDrive, Info, RefreshCw, ChevronDown, Mic,
|
||||
ShieldCheck, Fingerprint, Lock, KeyRound, Bell, Globe
|
||||
ShieldCheck, Fingerprint, Lock, KeyRound, Bell, Globe, BarChart2
|
||||
} from 'lucide-react'
|
||||
import { Avatar } from '../components/Avatar'
|
||||
import './SettingsPage.scss'
|
||||
|
||||
type SettingsTab = 'appearance' | 'notification' | 'database' | 'models' | 'export' | 'cache' | 'api' | 'security' | 'about'
|
||||
type SettingsTab = 'appearance' | 'notification' | 'database' | 'models' | 'export' | 'cache' | 'api' | 'security' | 'about' | 'analytics'
|
||||
|
||||
const tabs: { id: SettingsTab; label: string; icon: React.ElementType }[] = [
|
||||
{ id: 'appearance', label: '外观', icon: Palette },
|
||||
@@ -24,6 +24,8 @@ const tabs: { id: SettingsTab; label: string; icon: React.ElementType }[] = [
|
||||
{ id: 'export', label: '导出', icon: Download },
|
||||
{ id: 'cache', label: '缓存', icon: HardDrive },
|
||||
{ id: 'api', label: 'API 服务', icon: Globe },
|
||||
|
||||
{ id: 'analytics', label: '分析', icon: BarChart2 },
|
||||
{ id: 'security', label: '安全', icon: ShieldCheck },
|
||||
{ id: 'about', label: '关于', icon: Info }
|
||||
]
|
||||
@@ -72,6 +74,7 @@ function SettingsPage() {
|
||||
const exportExcelColumnsDropdownRef = useRef<HTMLDivElement>(null)
|
||||
const exportConcurrencyDropdownRef = useRef<HTMLDivElement>(null)
|
||||
const [cachePath, setCachePath] = useState('')
|
||||
const [weixinDllPath, setWeixinDllPath] = useState('')
|
||||
const [logEnabled, setLogEnabled] = useState(false)
|
||||
const [whisperModelName, setWhisperModelName] = useState('base')
|
||||
const [whisperModelDir, setWhisperModelDir] = useState('')
|
||||
@@ -109,6 +112,9 @@ function SettingsPage() {
|
||||
const [filterModeDropdownOpen, setFilterModeDropdownOpen] = useState(false)
|
||||
const [positionDropdownOpen, setPositionDropdownOpen] = useState(false)
|
||||
|
||||
const [wordCloudExcludeWords, setWordCloudExcludeWords] = useState<string[]>([])
|
||||
const [excludeWordsInput, setExcludeWordsInput] = useState('')
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -244,6 +250,7 @@ function SettingsPage() {
|
||||
const savedPath = await configService.getDbPath()
|
||||
const savedWxid = await configService.getMyWxid()
|
||||
const savedCachePath = await configService.getCachePath()
|
||||
const savedWeixinDllPath = await configService.getWeixinDllPath()
|
||||
const savedExportPath = await configService.getExportPath()
|
||||
const savedLogEnabled = await configService.getLogEnabled()
|
||||
const savedImageXorKey = await configService.getImageXorKey()
|
||||
@@ -272,6 +279,7 @@ function SettingsPage() {
|
||||
if (savedPath) setDbPath(savedPath)
|
||||
if (savedWxid) setWxid(savedWxid)
|
||||
if (savedCachePath) setCachePath(savedCachePath)
|
||||
if (savedWeixinDllPath) setWeixinDllPath(savedWeixinDllPath)
|
||||
|
||||
const wxidConfig = savedWxid ? await configService.getWxidConfig(savedWxid) : null
|
||||
const decryptKeyToUse = wxidConfig?.decryptKey ?? savedKey ?? ''
|
||||
@@ -302,6 +310,10 @@ function SettingsPage() {
|
||||
setNotificationFilterMode(savedNotificationFilterMode)
|
||||
setNotificationFilterList(savedNotificationFilterList)
|
||||
|
||||
const savedExcludeWords = await configService.getWordCloudExcludeWords()
|
||||
setWordCloudExcludeWords(savedExcludeWords)
|
||||
setExcludeWordsInput(savedExcludeWords.join('\n'))
|
||||
|
||||
// 如果语言列表为空,保存默认值
|
||||
if (!savedTranscribeLanguages || savedTranscribeLanguages.length === 0) {
|
||||
const defaultLanguages = ['zh']
|
||||
@@ -604,6 +616,29 @@ function SettingsPage() {
|
||||
await applyWxidSelection(selectedWxid)
|
||||
}
|
||||
|
||||
const handleSelectWeixinDllPath = async () => {
|
||||
try {
|
||||
const result = await dialog.openFile({
|
||||
title: '选择 Weixin.dll 文件',
|
||||
properties: ['openFile'],
|
||||
filters: [{ name: 'DLL', extensions: ['dll'] }]
|
||||
})
|
||||
if (!result.canceled && result.filePaths.length > 0) {
|
||||
const selectedPath = result.filePaths[0]
|
||||
setWeixinDllPath(selectedPath)
|
||||
await configService.setWeixinDllPath(selectedPath)
|
||||
showMessage('已选择 Weixin.dll 路径', true)
|
||||
}
|
||||
} catch {
|
||||
showMessage('选择 Weixin.dll 失败', false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleResetWeixinDllPath = async () => {
|
||||
setWeixinDllPath('')
|
||||
await configService.setWeixinDllPath('')
|
||||
showMessage('已清空 Weixin.dll 路径', true)
|
||||
}
|
||||
const handleSelectCachePath = async () => {
|
||||
try {
|
||||
const result = await dialog.openFile({ title: '选择缓存目录', properties: ['openDirectory'] })
|
||||
@@ -1297,6 +1332,29 @@ function SettingsPage() {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="form-group">
|
||||
<label>Weixin.dll 路径 <span className="optional">(可选)</span></label>
|
||||
<span className="form-hint">用于朋友圈在线图片原生解密,优先使用这里配置的 DLL</span>
|
||||
<input
|
||||
type="text"
|
||||
placeholder="例如: D:\weixindata\Weixin\Weixin.dll"
|
||||
value={weixinDllPath}
|
||||
onChange={(e) => {
|
||||
const value = e.target.value
|
||||
setWeixinDllPath(value)
|
||||
scheduleConfigSave('weixinDllPath', () => configService.setWeixinDllPath(value))
|
||||
}}
|
||||
/>
|
||||
<div className="btn-row">
|
||||
<button className="btn btn-secondary" onClick={handleSelectWeixinDllPath}>
|
||||
<FolderOpen size={16} /> 浏览选择
|
||||
</button>
|
||||
<button className="btn btn-secondary" onClick={handleResetWeixinDllPath}>
|
||||
清空
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="form-group">
|
||||
<label>账号 wxid</label>
|
||||
<span className="form-hint">微信账号标识</span>
|
||||
@@ -1863,13 +1921,13 @@ function SettingsPage() {
|
||||
// HTTP API 服务控制
|
||||
const handleToggleApi = async () => {
|
||||
if (isTogglingApi) return
|
||||
|
||||
|
||||
// 启动时显示警告弹窗
|
||||
if (!httpApiRunning) {
|
||||
setShowApiWarning(true)
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
setIsTogglingApi(true)
|
||||
try {
|
||||
await window.electronAPI.http.stop()
|
||||
@@ -2053,6 +2111,56 @@ function SettingsPage() {
|
||||
}
|
||||
}
|
||||
|
||||
const renderAnalyticsTab = () => (
|
||||
<div className="tab-content">
|
||||
<div className="settings-section">
|
||||
<h2>分析设置</h2>
|
||||
<div className="setting-item">
|
||||
<div className="setting-label">
|
||||
<span>词云排除词</span>
|
||||
<span className="setting-desc">输入不需要在词云和常用语中显示的词语,用换行分隔</span>
|
||||
</div>
|
||||
<div className="setting-control" style={{ flexDirection: 'column', alignItems: 'flex-start', gap: '8px' }}>
|
||||
<textarea
|
||||
className="form-input"
|
||||
style={{ width: '100%', height: '200px', fontFamily: 'monospace' }}
|
||||
value={excludeWordsInput}
|
||||
onChange={(e) => setExcludeWordsInput(e.target.value)}
|
||||
placeholder="例如:
|
||||
第一个词
|
||||
第二个词
|
||||
第三个词"
|
||||
/>
|
||||
<div className="button-group">
|
||||
<button
|
||||
className="btn btn-primary"
|
||||
onClick={async () => {
|
||||
const words = excludeWordsInput.split('\n').map(w => w.trim()).filter(w => w.length > 0)
|
||||
// 去重
|
||||
const uniqueWords = Array.from(new Set(words))
|
||||
await configService.setWordCloudExcludeWords(uniqueWords)
|
||||
setWordCloudExcludeWords(uniqueWords)
|
||||
setExcludeWordsInput(uniqueWords.join('\n'))
|
||||
// Show success toast or feedback if needed (optional)
|
||||
}}
|
||||
>
|
||||
保存排除列表
|
||||
</button>
|
||||
<button
|
||||
className="btn btn-secondary"
|
||||
onClick={() => {
|
||||
setExcludeWordsInput(wordCloudExcludeWords.join('\n'))
|
||||
}}
|
||||
>
|
||||
重置
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
|
||||
const renderSecurityTab = () => (
|
||||
<div className="tab-content">
|
||||
<div className="form-group">
|
||||
@@ -2242,6 +2350,7 @@ function SettingsPage() {
|
||||
{activeTab === 'export' && renderExportTab()}
|
||||
{activeTab === 'cache' && renderCacheTab()}
|
||||
{activeTab === 'api' && renderApiTab()}
|
||||
{activeTab === 'analytics' && renderAnalyticsTab()}
|
||||
{activeTab === 'security' && renderSecurityTab()}
|
||||
{activeTab === 'about' && renderAboutTab()}
|
||||
</div>
|
||||
|
||||
@@ -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 {
|
||||
.download-btn-overlay {
|
||||
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 数据
|
||||
}
|
||||
|
||||
const MediaItem = ({ media, onPreview }: { media: any, onPreview: () => void }) => {
|
||||
const [error, setError] = useState(false);
|
||||
const { url, thumb, livePhoto } = media;
|
||||
const isLive = !!livePhoto;
|
||||
const targetUrl = thumb || url;
|
||||
const MediaItem = ({ media, onPreview }: { media: any; onPreview: (src: string, isVideo?: boolean, liveVideoPath?: string) => void }) => {
|
||||
const [error, setError] = useState(false)
|
||||
const [thumbSrc, setThumbSrc] = useState<string>('') // 缩略图
|
||||
const [videoPath, setVideoPath] = useState<string>('') // 视频本地路径
|
||||
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;
|
||||
let downloadKey = media.key || '';
|
||||
useEffect(() => {
|
||||
let cancelled = false
|
||||
setError(false)
|
||||
setThumbSrc('')
|
||||
setVideoPath('')
|
||||
setLiveVideoPath('')
|
||||
setIsDecrypting(false)
|
||||
|
||||
if (isLive && media.livePhoto) {
|
||||
downloadUrl = media.livePhoto.url;
|
||||
downloadKey = media.livePhoto.key || '';
|
||||
const extractFirstFrame = (videoUrl: string) => {
|
||||
const video = document.createElement('video')
|
||||
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: 调用后端下载服务
|
||||
// window.electronAPI.sns.download(downloadUrl, downloadKey);
|
||||
};
|
||||
const run = async () => {
|
||||
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 (
|
||||
<div className={`media-item ${error ? 'error' : ''}`} onClick={onPreview}>
|
||||
<img
|
||||
src={targetUrl}
|
||||
alt=""
|
||||
referrerPolicy="no-referrer"
|
||||
loading="lazy"
|
||||
onError={() => setError(true)}
|
||||
/>
|
||||
{isLive && (
|
||||
<div className={`media-item ${error ? 'error' : ''} ${isVideo && isDecrypting ? 'decrypting' : ''}`} onClick={handleClick}>
|
||||
{isVideo && isDecrypting ? (
|
||||
<div className="video-loading-overlay" style={{
|
||||
position: 'absolute', inset: 0, display: 'flex', flexDirection: 'column',
|
||||
alignItems: 'center', justifyContent: 'center', background: 'rgba(0,0,0,0.5)', color: '#fff',
|
||||
zIndex: 2, backdropFilter: 'blur(4px)'
|
||||
}}>
|
||||
<RefreshCw size={24} className="spin-icon" style={{ marginBottom: 8 }} />
|
||||
<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">
|
||||
<LivePhotoIcon size={16} className="live-icon" />
|
||||
</div>
|
||||
)}
|
||||
<button className="download-btn-overlay" onClick={handleDownload} title="下载原图">
|
||||
<button className="download-btn-overlay" onClick={handleDownload} title="Download original">
|
||||
<Download size={14} />
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
)
|
||||
}
|
||||
|
||||
interface Contact {
|
||||
username: string
|
||||
@@ -100,7 +281,7 @@ export default function SnsPage() {
|
||||
const [contactsLoading, setContactsLoading] = useState(false)
|
||||
const [showJumpDialog, setShowJumpDialog] = useState(false)
|
||||
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 postsContainerRef = useRef<HTMLDivElement>(null)
|
||||
@@ -149,7 +330,7 @@ export default function SnsPage() {
|
||||
const currentPosts = postsRef.current
|
||||
if (currentPosts.length > 0) {
|
||||
const topTs = currentPosts[0].createTime
|
||||
|
||||
|
||||
|
||||
const result = await window.electronAPI.sns.getTimeline(
|
||||
limit,
|
||||
@@ -281,10 +462,10 @@ export default function SnsPage() {
|
||||
const checkSchema = async () => {
|
||||
try {
|
||||
const schema = await window.electronAPI.chat.execQuery('sns', null, "PRAGMA table_info(SnsTimeLine)");
|
||||
|
||||
|
||||
if (schema.success && schema.rows) {
|
||||
const columns = schema.rows.map((r: any) => r.name);
|
||||
|
||||
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('[SnsPage] Failed to check schema:', e);
|
||||
@@ -335,7 +516,7 @@ export default function SnsPage() {
|
||||
|
||||
// deltaY < 0 表示向上滚,scrollTop === 0 表示已经在最顶端
|
||||
if (e.deltaY < -20 && container.scrollTop <= 0 && hasNewer && !loading && !loadingNewer) {
|
||||
|
||||
|
||||
loadPosts({ direction: 'newer' })
|
||||
}
|
||||
}
|
||||
@@ -412,10 +593,6 @@ export default function SnsPage() {
|
||||
</div>
|
||||
|
||||
<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="posts-list">
|
||||
{loadingNewer && (
|
||||
@@ -463,15 +640,10 @@ export default function SnsPage() {
|
||||
<div className="post-body">
|
||||
{post.contentDesc && <div className="post-text">{post.contentDesc}</div>}
|
||||
|
||||
{post.type === 15 ? (
|
||||
<div className="post-video-placeholder">
|
||||
<Play size={20} />
|
||||
<span>视频动态</span>
|
||||
</div>
|
||||
) : post.media.length > 0 && (
|
||||
{post.media.length > 0 && (
|
||||
<div className={`post-media-grid media-count-${Math.min(post.media.length, 9)}`}>
|
||||
{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>
|
||||
)}
|
||||
@@ -644,7 +816,12 @@ export default function SnsPage() {
|
||||
</aside>
|
||||
</div>
|
||||
{previewImage && (
|
||||
<ImagePreview src={previewImage} onClose={() => setPreviewImage(null)} />
|
||||
<ImagePreview
|
||||
src={previewImage.src}
|
||||
isVideo={previewImage.isVideo}
|
||||
liveVideoPath={previewImage.liveVideoPath}
|
||||
onClose={() => setPreviewImage(null)}
|
||||
/>
|
||||
)}
|
||||
<JumpToDateDialog
|
||||
isOpen={showJumpDialog}
|
||||
|
||||
@@ -12,6 +12,7 @@ export const CONFIG_KEYS = {
|
||||
LAST_SESSION: 'lastSession',
|
||||
WINDOW_BOUNDS: 'windowBounds',
|
||||
CACHE_PATH: 'cachePath',
|
||||
WEIXIN_DLL_PATH: 'weixinDllPath',
|
||||
EXPORT_PATH: 'exportPath',
|
||||
AGREEMENT_ACCEPTED: 'agreementAccepted',
|
||||
LOG_ENABLED: 'logEnabled',
|
||||
@@ -44,7 +45,10 @@ export const CONFIG_KEYS = {
|
||||
NOTIFICATION_ENABLED: 'notificationEnabled',
|
||||
NOTIFICATION_POSITION: 'notificationPosition',
|
||||
NOTIFICATION_FILTER_MODE: 'notificationFilterMode',
|
||||
NOTIFICATION_FILTER_LIST: 'notificationFilterList'
|
||||
NOTIFICATION_FILTER_LIST: 'notificationFilterList',
|
||||
|
||||
// 词云
|
||||
WORD_CLOUD_EXCLUDE_WORDS: 'wordCloudExcludeWords'
|
||||
} as const
|
||||
|
||||
export interface WxidConfig {
|
||||
@@ -159,6 +163,17 @@ export async function setCachePath(path: string): Promise<void> {
|
||||
}
|
||||
|
||||
|
||||
// 获取 Weixin.dll 路径
|
||||
export async function getWeixinDllPath(): Promise<string | null> {
|
||||
const value = await config.get(CONFIG_KEYS.WEIXIN_DLL_PATH)
|
||||
return value as string | null
|
||||
}
|
||||
|
||||
// 设置 Weixin.dll 路径
|
||||
export async function setWeixinDllPath(path: string): Promise<void> {
|
||||
await config.set(CONFIG_KEYS.WEIXIN_DLL_PATH, path)
|
||||
}
|
||||
|
||||
// 获取导出路径
|
||||
export async function getExportPath(): Promise<string | null> {
|
||||
const value = await config.get(CONFIG_KEYS.EXPORT_PATH)
|
||||
@@ -465,3 +480,14 @@ export async function getNotificationFilterList(): Promise<string[]> {
|
||||
export async function setNotificationFilterList(list: string[]): Promise<void> {
|
||||
await config.set(CONFIG_KEYS.NOTIFICATION_FILTER_LIST, list)
|
||||
}
|
||||
|
||||
// 获取词云排除词列表
|
||||
export async function getWordCloudExcludeWords(): Promise<string[]> {
|
||||
const value = await config.get(CONFIG_KEYS.WORD_CLOUD_EXCLUDE_WORDS)
|
||||
return Array.isArray(value) ? value : []
|
||||
}
|
||||
|
||||
// 设置词云排除词列表
|
||||
export async function setWordCloudExcludeWords(words: string[]): Promise<void> {
|
||||
await config.set(CONFIG_KEYS.WORD_CLOUD_EXCLUDE_WORDS, words)
|
||||
}
|
||||
|
||||
@@ -45,6 +45,7 @@
|
||||
[data-theme="cloud-dancer"][data-mode="light"],
|
||||
[data-theme="cloud-dancer"]:not([data-mode]) {
|
||||
--primary: #8B7355;
|
||||
--primary-rgb: 139, 115, 85;
|
||||
--primary-hover: #7A6548;
|
||||
--primary-light: rgba(139, 115, 85, 0.1);
|
||||
--bg-primary: #F0EEE9;
|
||||
@@ -64,6 +65,7 @@
|
||||
[data-theme="corundum-blue"][data-mode="light"],
|
||||
[data-theme="corundum-blue"]:not([data-mode]) {
|
||||
--primary: #4A6670;
|
||||
--primary-rgb: 74, 102, 112;
|
||||
--primary-hover: #3D565E;
|
||||
--primary-light: rgba(74, 102, 112, 0.1);
|
||||
--bg-primary: #E8EEF0;
|
||||
@@ -83,6 +85,7 @@
|
||||
[data-theme="kiwi-green"][data-mode="light"],
|
||||
[data-theme="kiwi-green"]:not([data-mode]) {
|
||||
--primary: #7A9A5C;
|
||||
--primary-rgb: 122, 154, 92;
|
||||
--primary-hover: #6A8A4C;
|
||||
--primary-light: rgba(122, 154, 92, 0.1);
|
||||
--bg-primary: #E8F0E4;
|
||||
@@ -102,6 +105,7 @@
|
||||
[data-theme="spicy-red"][data-mode="light"],
|
||||
[data-theme="spicy-red"]:not([data-mode]) {
|
||||
--primary: #8B4049;
|
||||
--primary-rgb: 139, 64, 73;
|
||||
--primary-hover: #7A3540;
|
||||
--primary-light: rgba(139, 64, 73, 0.1);
|
||||
--bg-primary: #F0E8E8;
|
||||
@@ -121,6 +125,7 @@
|
||||
[data-theme="teal-water"][data-mode="light"],
|
||||
[data-theme="teal-water"]:not([data-mode]) {
|
||||
--primary: #5A8A8A;
|
||||
--primary-rgb: 90, 138, 138;
|
||||
--primary-hover: #4A7A7A;
|
||||
--primary-light: rgba(90, 138, 138, 0.1);
|
||||
--bg-primary: #E4F0F0;
|
||||
@@ -141,6 +146,7 @@
|
||||
// 云上舞白 - 深色
|
||||
[data-theme="cloud-dancer"][data-mode="dark"] {
|
||||
--primary: #C9A86C;
|
||||
--primary-rgb: 201, 168, 108;
|
||||
--primary-hover: #D9B87C;
|
||||
--primary-light: rgba(201, 168, 108, 0.15);
|
||||
--bg-primary: #1a1816;
|
||||
@@ -159,6 +165,7 @@
|
||||
// 刚玉蓝 - 深色
|
||||
[data-theme="corundum-blue"][data-mode="dark"] {
|
||||
--primary: #6A9AAA;
|
||||
--primary-rgb: 106, 154, 170;
|
||||
--primary-hover: #7AAABA;
|
||||
--primary-light: rgba(106, 154, 170, 0.15);
|
||||
--bg-primary: #141a1c;
|
||||
@@ -177,6 +184,7 @@
|
||||
// 冰猕猴桃汁绿 - 深色
|
||||
[data-theme="kiwi-green"][data-mode="dark"] {
|
||||
--primary: #9ABA7C;
|
||||
--primary-rgb: 154, 186, 124;
|
||||
--primary-hover: #AACA8C;
|
||||
--primary-light: rgba(154, 186, 124, 0.15);
|
||||
--bg-primary: #161a14;
|
||||
@@ -195,6 +203,7 @@
|
||||
// 辛辣红 - 深色
|
||||
[data-theme="spicy-red"][data-mode="dark"] {
|
||||
--primary: #C06068;
|
||||
--primary-rgb: 192, 96, 104;
|
||||
--primary-hover: #D07078;
|
||||
--primary-light: rgba(192, 96, 104, 0.15);
|
||||
--bg-primary: #1a1416;
|
||||
@@ -213,6 +222,7 @@
|
||||
// 明水鸭色 - 深色
|
||||
[data-theme="teal-water"][data-mode="dark"] {
|
||||
--primary: #7ABAAA;
|
||||
--primary-rgb: 122, 186, 170;
|
||||
--primary-hover: #8ACABA;
|
||||
--primary-light: rgba(122, 186, 170, 0.15);
|
||||
--bg-primary: #121a1a;
|
||||
|
||||
19
src/types/electron.d.ts
vendored
19
src/types/electron.d.ts
vendored
@@ -397,16 +397,15 @@ export interface ElectronAPI {
|
||||
myTopEmojiMd5?: string
|
||||
friendTopEmojiMd5?: string
|
||||
myTopEmojiUrl?: string
|
||||
friendTopEmojiUrl?: string
|
||||
myTopEmojiCount?: number
|
||||
friendTopEmojiCount?: number
|
||||
topPhrases: Array<{ phrase: string; count: number }>
|
||||
myExclusivePhrases: Array<{ phrase: string; count: number }>
|
||||
friendExclusivePhrases: Array<{ phrase: string; count: number }>
|
||||
heatmap?: number[][]
|
||||
initiative?: { initiated: number; received: number }
|
||||
response?: { avg: number; fastest: number; count: number }
|
||||
monthly?: Record<string, number>
|
||||
streak?: { days: number; startDate: string; endDate: string }
|
||||
}
|
||||
topPhrases: Array<{ phrase: string; count: number }>
|
||||
heatmap?: number[][]
|
||||
initiative?: { initiated: number; received: number }
|
||||
response?: { avg: number; fastest: number; count: number }
|
||||
monthly?: Record<string, number>
|
||||
streak?: { days: number; startDate: string; endDate: string }
|
||||
}
|
||||
error?: string
|
||||
}>
|
||||
@@ -478,7 +477,7 @@ export interface ElectronAPI {
|
||||
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: {
|
||||
loadModel: (modelPath: string) => Promise<boolean>
|
||||
|
||||
Reference in New Issue
Block a user