diff --git a/.gitignore b/.gitignore index 8b7210e..c424a77 100644 --- a/.gitignore +++ b/.gitignore @@ -59,4 +59,5 @@ wcdb/ *info 概述.md chatlab-format.md -*.bak \ No newline at end of file +*.bak +AGENTS.md \ No newline at end of file diff --git a/electron/main.ts b/electron/main.ts index ebfd428..1e0de48 100644 --- a/electron/main.ts +++ b/electron/main.ts @@ -985,8 +985,8 @@ function registerIpcHandlers() { return analyticsService.getOverallStatistics(force) }) - ipcMain.handle('analytics:getContactRankings', async (_, limit?: number) => { - return analyticsService.getContactRankings(limit) + ipcMain.handle('analytics:getContactRankings', async (_, limit?: number, beginTimestamp?: number, endTimestamp?: number) => { + return analyticsService.getContactRankings(limit, beginTimestamp, endTimestamp) }) ipcMain.handle('analytics:getTimeDistribution', async () => { diff --git a/electron/preload.ts b/electron/preload.ts index b6a8559..29d3829 100644 --- a/electron/preload.ts +++ b/electron/preload.ts @@ -189,7 +189,8 @@ contextBridge.exposeInMainWorld('electronAPI', { // 数据分析 analytics: { getOverallStatistics: (force?: boolean) => ipcRenderer.invoke('analytics:getOverallStatistics', force), - getContactRankings: (limit?: number) => ipcRenderer.invoke('analytics:getContactRankings', limit), + getContactRankings: (limit?: number, beginTimestamp?: number, endTimestamp?: number) => + ipcRenderer.invoke('analytics:getContactRankings', limit, beginTimestamp, endTimestamp), getTimeDistribution: () => ipcRenderer.invoke('analytics:getTimeDistribution'), getExcludedUsernames: () => ipcRenderer.invoke('analytics:getExcludedUsernames'), setExcludedUsernames: (usernames: string[]) => ipcRenderer.invoke('analytics:setExcludedUsernames', usernames), diff --git a/electron/services/analyticsService.ts b/electron/services/analyticsService.ts index 8c04476..80a7169 100644 --- a/electron/services/analyticsService.ts +++ b/electron/services/analyticsService.ts @@ -31,6 +31,7 @@ export interface ContactRanking { username: string displayName: string avatarUrl?: string + wechatId?: string messageCount: number sentCount: number receivedCount: number @@ -576,7 +577,11 @@ class AnalyticsService { } } - async getContactRankings(limit: number = 20): Promise<{ success: boolean; data?: ContactRanking[]; error?: string }> { + async getContactRankings( + limit: number = 20, + beginTimestamp: number = 0, + endTimestamp: number = 0 + ): Promise<{ success: boolean; data?: ContactRanking[]; error?: string }> { try { const conn = await this.ensureConnected() if (!conn.success || !conn.cleanedWxid) return { success: false, error: conn.error } @@ -586,7 +591,7 @@ class AnalyticsService { return { success: false, error: '未找到消息会话' } } - const result = await this.getAggregateWithFallback(sessionInfo.usernames, 0, 0) + const result = await this.getAggregateWithFallback(sessionInfo.usernames, beginTimestamp, endTimestamp) if (!result.success || !result.data) { return { success: false, error: result.error || '聚合统计失败' } } @@ -594,9 +599,10 @@ class AnalyticsService { const d = result.data const sessions = this.normalizeAggregateSessions(d.sessions, d.idMap) const usernames = Object.keys(sessions) - const [displayNames, avatarUrls] = await Promise.all([ + const [displayNames, avatarUrls, aliasMap] = await Promise.all([ wcdbService.getDisplayNames(usernames), - wcdbService.getAvatarUrls(usernames) + wcdbService.getAvatarUrls(usernames), + this.getAliasMap(usernames) ]) const rankings: ContactRanking[] = usernames @@ -608,10 +614,13 @@ class AnalyticsService { const avatarUrl = avatarUrls.success && avatarUrls.map ? avatarUrls.map[username] : undefined + const alias = aliasMap[username] || '' + const wechatId = alias || (!username.startsWith('wxid_') ? username : '') return { username, displayName, avatarUrl, + wechatId, messageCount: stat.total, sentCount: stat.sent, receivedCount: stat.received, diff --git a/electron/services/dualReportService.ts b/electron/services/dualReportService.ts index e395412..5e3b21a 100644 --- a/electron/services/dualReportService.ts +++ b/electron/services/dualReportService.ts @@ -26,13 +26,17 @@ export interface DualReportStats { friendTopEmojiMd5?: string myTopEmojiUrl?: string friendTopEmojiUrl?: string + myTopEmojiCount?: number + friendTopEmojiCount?: number } export interface DualReportData { year: number selfName: string + selfAvatarUrl?: string friendUsername: string friendName: string + friendAvatarUrl?: string firstChat: DualReportFirstChat | null firstChatMessages?: DualReportMessage[] yearFirstChat?: { @@ -173,26 +177,258 @@ class DualReportService { return `${month}/${day} ${hour}:${minute}` } - private extractEmojiUrl(content: string): string | undefined { - if (!content) return undefined - const attrMatch = /cdnurl\s*=\s*['"]([^'"]+)['"]/i.exec(content) - if (attrMatch) { - let url = attrMatch[1].replace(/&/g, '&') - try { - if (url.includes('%')) { - url = decodeURIComponent(url) - } - } catch { } - return url + private getRecordField(record: Record | undefined | null, keys: string[]): any { + if (!record) return undefined + for (const key of keys) { + if (Object.prototype.hasOwnProperty.call(record, key) && record[key] !== undefined && record[key] !== null) { + return record[key] + } } - const tagMatch = /cdnurl[^>]*>([^<]+)/i.exec(content) - return tagMatch?.[1] + return undefined } - private extractEmojiMd5(content: string): string | undefined { + private coerceNumber(raw: any): number { + if (raw === undefined || raw === null || raw === '') return NaN + if (typeof raw === 'number') return raw + if (typeof raw === 'bigint') return Number(raw) + if (Buffer.isBuffer(raw)) return parseInt(raw.toString('utf-8'), 10) + if (raw instanceof Uint8Array) return parseInt(Buffer.from(raw).toString('utf-8'), 10) + const parsed = parseInt(String(raw), 10) + return Number.isFinite(parsed) ? parsed : NaN + } + + private coerceString(raw: any): string { + if (raw === undefined || raw === null) return '' + if (typeof raw === 'string') return raw + if (Buffer.isBuffer(raw)) return this.decodeBinaryContent(raw) + if (raw instanceof Uint8Array) return this.decodeBinaryContent(Buffer.from(raw)) + return String(raw) + } + + private coerceBoolean(raw: any): boolean | undefined { + if (raw === undefined || raw === null || raw === '') return undefined + if (typeof raw === 'boolean') return raw + if (typeof raw === 'number') return raw !== 0 + + const normalized = String(raw).trim().toLowerCase() + if (!normalized) return undefined + + if (['1', 'true', 'yes', 'me', 'self', 'mine', 'sent', 'out', 'outgoing'].includes(normalized)) return true + if (['0', 'false', 'no', 'friend', 'peer', 'other', 'recv', 'received', 'in', 'incoming'].includes(normalized)) return false + return undefined + } + + private normalizeEmojiMd5(raw: string): string | undefined { + if (!raw) return undefined + const trimmed = raw.trim() + if (!trimmed) return undefined + const match = /([a-fA-F0-9]{16,64})/.exec(trimmed) + return match ? match[1].toLowerCase() : undefined + } + + private normalizeEmojiUrl(raw: string): string | undefined { + if (!raw) return undefined + let url = raw.trim().replace(/&/g, '&') + if (!url) return undefined + try { + if (url.includes('%')) { + url = decodeURIComponent(url) + } + } catch { } + return url || undefined + } + + private extractEmojiUrl(content: string | undefined): string | undefined { if (!content) return undefined - const match = /md5="([^"]+)"/i.exec(content) || /([^<]+)<\/md5>/i.exec(content) - return match?.[1] + const direct = this.normalizeEmojiUrl(content) + if (direct && /^https?:\/\//i.test(direct)) return direct + + const attrMatch = /(?:cdnurl|thumburl)\s*=\s*['"]([^'"]+)['"]/i.exec(content) + || /(?:cdnurl|thumburl)\s*=\s*([^'"\s>]+)/i.exec(content) + if (attrMatch) return this.normalizeEmojiUrl(attrMatch[1]) + + const tagMatch = /<(?:cdnurl|thumburl)>([^<]+)<\/(?:cdnurl|thumburl)>/i.exec(content) + || /(?:cdnurl|thumburl)[^>]*>([^<]+)/i.exec(content) + return this.normalizeEmojiUrl(tagMatch?.[1] || '') + } + + private extractEmojiMd5(content: string | undefined): string | undefined { + if (!content) return undefined + const direct = this.normalizeEmojiMd5(content) + if (direct && direct.length >= 24) return direct + + const match = /md5\s*=\s*['"]([a-fA-F0-9]{16,64})['"]/i.exec(content) + || /md5\s*=\s*([a-fA-F0-9]{16,64})/i.exec(content) + || /([a-fA-F0-9]{16,64})<\/md5>/i.exec(content) + return this.normalizeEmojiMd5(match?.[1] || '') + } + + private resolveEmojiOwner(item: any, content: string): boolean | undefined { + const sentFlag = this.coerceBoolean(this.getRecordField(item, [ + 'isMe', + 'is_me', + 'isSent', + 'is_sent', + 'isSend', + 'is_send', + 'fromMe', + 'from_me' + ])) + if (sentFlag !== undefined) return sentFlag + + const sideRaw = this.coerceString(this.getRecordField(item, ['side', 'sender', 'from', 'owner', 'role', 'direction'])).trim().toLowerCase() + if (sideRaw) { + if (['me', 'self', 'mine', 'out', 'outgoing', 'sent'].includes(sideRaw)) return true + if (['friend', 'peer', 'other', 'in', 'incoming', 'received', 'recv'].includes(sideRaw)) return false + } + + const prefixMatch = /^\s*([01])\s*:\s*/.exec(content) + if (prefixMatch) return prefixMatch[1] === '1' + return undefined + } + + private stripEmojiOwnerPrefix(content: string): string { + if (!content) return '' + return content.replace(/^\s*[01]\s*:\s*/, '') + } + + private parseEmojiCandidate(item: any): { isMe?: boolean; md5?: string; url?: string; count: number } { + const rawContent = this.coerceString(this.getRecordField(item, [ + 'content', + 'xml', + 'message_content', + 'messageContent', + 'msg', + 'payload', + 'raw' + ])) + const content = this.stripEmojiOwnerPrefix(rawContent) + + const countRaw = this.getRecordField(item, ['count', 'cnt', 'times', 'total', 'num']) + const parsedCount = this.coerceNumber(countRaw) + const count = Number.isFinite(parsedCount) && parsedCount > 0 ? parsedCount : 0 + + const directMd5 = this.normalizeEmojiMd5(this.coerceString(this.getRecordField(item, [ + 'md5', + 'emojiMd5', + 'emoji_md5', + 'emd5' + ]))) + const md5 = directMd5 || this.extractEmojiMd5(content) + + const directUrl = this.normalizeEmojiUrl(this.coerceString(this.getRecordField(item, [ + 'cdnUrl', + 'cdnurl', + 'emojiUrl', + 'emoji_url', + 'url', + 'thumbUrl', + 'thumburl' + ]))) + const url = directUrl || this.extractEmojiUrl(content) + + return { + isMe: this.resolveEmojiOwner(item, rawContent), + md5, + url, + count + } + } + + private getRowInt(row: Record, keys: string[], fallback = 0): number { + const raw = this.getRecordField(row, keys) + const parsed = this.coerceNumber(raw) + return Number.isFinite(parsed) ? parsed : fallback + } + + private decodeRowMessageContent(row: Record): string { + const messageContent = this.getRecordField(row, [ + 'message_content', + 'messageContent', + 'content', + 'msg_content', + 'msgContent', + 'WCDB_CT_message_content', + 'WCDB_CT_messageContent' + ]) + const compressContent = this.getRecordField(row, [ + 'compress_content', + 'compressContent', + 'compressed_content', + 'WCDB_CT_compress_content', + 'WCDB_CT_compressContent' + ]) + return this.decodeMessageContent(messageContent, compressContent) + } + + private async scanEmojiTopFallback( + sessionId: string, + beginTimestamp: number, + endTimestamp: number, + rawWxid: string, + cleanedWxid: string + ): Promise<{ my?: { md5: string; url?: string; count: number }; friend?: { md5: string; url?: string; count: number } }> { + const cursorResult = await wcdbService.openMessageCursor(sessionId, 500, true, beginTimestamp, endTimestamp) + if (!cursorResult.success || !cursorResult.cursor) return {} + + const tallyMap = new Map() + try { + let hasMore = true + while (hasMore) { + const batch = await wcdbService.fetchMessageBatch(cursorResult.cursor) + if (!batch.success || !Array.isArray(batch.rows)) break + + for (const row of batch.rows) { + const localType = this.getRowInt(row, ['local_type', 'localType', 'type', 'msg_type', 'msgType', 'WCDB_CT_local_type'], 0) + if (localType !== 47) continue + + const rawContent = this.decodeRowMessageContent(row) + const content = this.stripEmojiOwnerPrefix(rawContent) + const directMd5 = this.normalizeEmojiMd5(this.coerceString(this.getRecordField(row, ['emoji_md5', 'emojiMd5', 'md5']))) + const md5 = directMd5 || this.extractEmojiMd5(content) + if (!md5) continue + + const directUrl = this.normalizeEmojiUrl(this.coerceString(this.getRecordField(row, [ + 'emoji_cdn_url', + 'emojiCdnUrl', + 'cdnurl', + 'cdn_url', + 'emoji_url', + 'emojiUrl', + 'url', + 'thumburl', + 'thumb_url' + ]))) + const url = directUrl || this.extractEmojiUrl(content) + const isMe = this.resolveIsSent(row, rawWxid, cleanedWxid) + const mapKey = `${isMe ? '1' : '0'}:${md5}` + const existing = tallyMap.get(mapKey) + if (existing) { + existing.count += 1 + if (!existing.url && url) existing.url = url + } else { + tallyMap.set(mapKey, { isMe, md5, url, count: 1 }) + } + } + hasMore = batch.hasMore === true + } + } finally { + await wcdbService.closeMessageCursor(cursorResult.cursor) + } + + let myTop: { md5: string; url?: string; count: number } | undefined + let friendTop: { md5: string; url?: string; count: number } | undefined + for (const entry of tallyMap.values()) { + if (entry.isMe) { + if (!myTop || entry.count > myTop.count) { + myTop = { md5: entry.md5, url: entry.url, count: entry.count } + } + } else if (!friendTop || entry.count > friendTop.count) { + friendTop = { md5: entry.md5, url: entry.url, count: entry.count } + } + } + + return { my: myTop, friend: friendTop } } private async getDisplayName(username: string, fallback: string): Promise { @@ -276,6 +512,18 @@ class DualReportService { if (myName === rawWxid && cleanedWxid && cleanedWxid !== rawWxid) { myName = await this.getDisplayName(cleanedWxid, rawWxid) } + const avatarCandidates = Array.from(new Set([ + friendUsername, + rawWxid, + cleanedWxid + ].filter(Boolean) as string[])) + let selfAvatarUrl: string | undefined + let friendAvatarUrl: string | undefined + const avatarResult = await wcdbService.getAvatarUrls(avatarCandidates) + if (avatarResult.success && avatarResult.map) { + selfAvatarUrl = avatarResult.map[rawWxid] || avatarResult.map[cleanedWxid] + friendAvatarUrl = avatarResult.map[friendUsername] + } this.reportProgress('获取首条聊天记录...', 15, onProgress) const firstRows = await this.getFirstMessages(friendUsername, 3, 0, 0) @@ -360,37 +608,52 @@ class DualReportService { if (cppData.emojis && Array.isArray(cppData.emojis)) { for (const item of cppData.emojis) { - const rawContent = item.content || '' - const isMe = rawContent.startsWith('1:') - const content = rawContent.substring(2) // Remove "1:" or "0:" prefix - const count = item.count || 0 + const candidate = this.parseEmojiCandidate(item) + if (!candidate.md5 || candidate.isMe === undefined || candidate.count <= 0) continue - if (isMe) { - if (count > myTopCount) { - const md5 = this.extractEmojiMd5(content) - if (md5) { - myTopCount = count - myTopEmojiMd5 = md5 - myTopEmojiUrl = this.extractEmojiUrl(content) - } - } - } else { - if (count > friendTopCount) { - const md5 = this.extractEmojiMd5(content) - if (md5) { - friendTopCount = count - friendTopEmojiMd5 = md5 - friendTopEmojiUrl = this.extractEmojiUrl(content) - } + if (candidate.isMe) { + if (candidate.count > myTopCount) { + myTopCount = candidate.count + myTopEmojiMd5 = candidate.md5 + myTopEmojiUrl = candidate.url } + } else if (candidate.count > friendTopCount) { + friendTopCount = candidate.count + friendTopEmojiMd5 = candidate.md5 + friendTopEmojiUrl = candidate.url } } } + const needsEmojiFallback = stats.emojiCount > 0 && (!myTopEmojiMd5 || !friendTopEmojiMd5) + if (needsEmojiFallback) { + const fallback = await this.scanEmojiTopFallback(friendUsername, startTime, endTime, rawWxid, cleanedWxid) + + if (!myTopEmojiMd5 && fallback.my?.md5) { + myTopEmojiMd5 = fallback.my.md5 + myTopEmojiUrl = myTopEmojiUrl || fallback.my.url + myTopCount = fallback.my.count + } + if (!friendTopEmojiMd5 && fallback.friend?.md5) { + friendTopEmojiMd5 = fallback.friend.md5 + friendTopEmojiUrl = friendTopEmojiUrl || fallback.friend.url + friendTopCount = fallback.friend.count + } + } + + const [myEmojiUrlResult, friendEmojiUrlResult] = await Promise.all([ + myTopEmojiMd5 && !myTopEmojiUrl ? wcdbService.getEmoticonCdnUrl(dbPath, myTopEmojiMd5) : Promise.resolve(null), + friendTopEmojiMd5 && !friendTopEmojiUrl ? wcdbService.getEmoticonCdnUrl(dbPath, friendTopEmojiMd5) : Promise.resolve(null) + ]) + if (myEmojiUrlResult?.success && myEmojiUrlResult.url) myTopEmojiUrl = myEmojiUrlResult.url + if (friendEmojiUrlResult?.success && friendEmojiUrlResult.url) friendTopEmojiUrl = friendEmojiUrlResult.url + stats.myTopEmojiMd5 = myTopEmojiMd5 stats.myTopEmojiUrl = myTopEmojiUrl stats.friendTopEmojiMd5 = friendTopEmojiMd5 stats.friendTopEmojiUrl = friendTopEmojiUrl + if (myTopCount >= 0) stats.myTopEmojiCount = myTopCount + if (friendTopCount >= 0) stats.friendTopEmojiCount = friendTopCount const topPhrases = (cppData.phrases || []).map((p: any) => ({ phrase: p.phrase, @@ -401,8 +664,10 @@ class DualReportService { const reportData: DualReportData = { year: reportYear, selfName: myName, + selfAvatarUrl, friendUsername, friendName, + friendAvatarUrl, firstChat, firstChatMessages, yearFirstChat, diff --git a/electron/services/exportService.ts b/electron/services/exportService.ts index 383aede..9679cce 100644 --- a/electron/services/exportService.ts +++ b/electron/services/exportService.ts @@ -68,7 +68,7 @@ const MESSAGE_TYPE_MAP: Record = { } export interface ExportOptions { - format: 'chatlab' | 'chatlab-jsonl' | 'json' | 'html' | 'txt' | 'excel' | 'sql' + format: 'chatlab' | 'chatlab-jsonl' | 'json' | 'html' | 'txt' | 'excel' | 'weclone' | 'sql' dateRange?: { start: number; end: number } | null exportMedia?: boolean exportAvatars?: boolean @@ -811,6 +811,55 @@ class ExportService { return content.replace(/^[\s]*([a-zA-Z0-9_-]+):(?!\/\/)/, '') } + private getWeCloneTypeName(localType: number, content: string): string { + if (localType === 1) return 'text' + if (localType === 3) return 'image' + if (localType === 47) return 'sticker' + if (localType === 43) return 'video' + if (localType === 34) return 'voice' + if (localType === 48) return 'location' + if (localType === 49) { + const xmlType = this.extractXmlValue(content || '', 'type') + if (xmlType === '6') return 'file' + return 'text' + } + return 'text' + } + + private getWeCloneSource(msg: any, typeName: string, mediaItem: MediaExportItem | null): string { + if (mediaItem?.relativePath) { + return mediaItem.relativePath + } + + if (typeName === 'image') { + return msg.imageDatName || '' + } + if (typeName === 'sticker') { + return msg.emojiCdnUrl || '' + } + if (typeName === 'video') { + return '' + } + if (typeName === 'file') { + const xml = msg.content || '' + return this.extractXmlValue(xml, 'filename') || this.extractXmlValue(xml, 'title') || '' + } + return '' + } + + private escapeCsvCell(value: unknown): string { + if (value === null || value === undefined) return '' + const text = String(value) + if (/[",\r\n]/.test(text)) { + return `"${text.replace(/"/g, '""')}"` + } + return text + } + + private formatIsoTimestamp(timestamp: number): string { + return new Date(timestamp * 1000).toISOString() + } + /** * 从撤回消息内容中提取撤回者的 wxid * 撤回消息 XML 格式通常包含 等字段 @@ -3577,6 +3626,253 @@ class ExportService { } } + /** + * 导出单个会话为 WeClone CSV 格式 + */ + async exportSessionToWeCloneCsv( + sessionId: string, + outputPath: string, + options: ExportOptions, + onProgress?: (progress: ExportProgress) => void + ): Promise<{ success: boolean; error?: string }> { + try { + const conn = await this.ensureConnected() + if (!conn.success || !conn.cleanedWxid) return { success: false, error: conn.error } + + const cleanedMyWxid = conn.cleanedWxid + const isGroup = sessionId.includes('@chatroom') + const sessionInfo = await this.getContactInfo(sessionId) + const myInfo = await this.getContactInfo(cleanedMyWxid) + + const contactCache = new Map() + const getContactCached = async (username: string) => { + if (contactCache.has(username)) { + return contactCache.get(username)! + } + const result = await wcdbService.getContact(username) + contactCache.set(username, result) + return result + } + + onProgress?.({ + current: 0, + total: 100, + currentSession: sessionInfo.displayName, + phase: 'preparing' + }) + + const collected = await this.collectMessages(sessionId, cleanedMyWxid, options.dateRange) + if (collected.rows.length === 0) { + return { success: false, error: '该会话在指定时间范围内没有消息' } + } + + const senderUsernames = new Set() + for (const msg of collected.rows) { + if (msg.senderUsername) senderUsernames.add(msg.senderUsername) + } + senderUsernames.add(sessionId) + await this.preloadContacts(senderUsernames, contactCache) + + const groupNicknameCandidates = isGroup + ? this.buildGroupNicknameIdCandidates([ + ...Array.from(senderUsernames.values()), + ...collected.rows.map(msg => msg.senderUsername), + cleanedMyWxid + ]) + : [] + const groupNicknamesMap = isGroup + ? await this.getGroupNicknamesForRoom(sessionId, groupNicknameCandidates) + : new Map() + + const sortedMessages = collected.rows.sort((a, b) => a.createTime - b.createTime) + + const voiceMessages = options.exportVoiceAsText + ? sortedMessages.filter(msg => msg.localType === 34) + : [] + + if (options.exportVoiceAsText && voiceMessages.length > 0) { + await this.ensureVoiceModel(onProgress) + } + + const { exportMediaEnabled, mediaRootDir, mediaRelativePrefix } = this.getMediaLayout(outputPath, options) + const mediaMessages = exportMediaEnabled + ? sortedMessages.filter(msg => { + const t = msg.localType + return (t === 3 && options.exportImages) || + (t === 47 && options.exportEmojis) || + (t === 43 && options.exportVideos) || + (t === 34 && options.exportVoices) + }) + : [] + + const mediaCache = new Map() + + if (mediaMessages.length > 0) { + onProgress?.({ + current: 25, + total: 100, + currentSession: sessionInfo.displayName, + phase: 'exporting-media', + phaseProgress: 0, + phaseTotal: mediaMessages.length, + phaseLabel: `导出媒体 0/${mediaMessages.length}` + }) + + const mediaConcurrency = this.getClampedConcurrency(options.exportConcurrency) + let mediaExported = 0 + await parallelLimit(mediaMessages, mediaConcurrency, async (msg) => { + const mediaKey = `${msg.localType}_${msg.localId}` + if (!mediaCache.has(mediaKey)) { + const mediaItem = await this.exportMediaForMessage(msg, sessionId, mediaRootDir, mediaRelativePrefix, { + exportImages: options.exportImages, + exportVoices: options.exportVoices, + exportVideos: options.exportVideos, + exportEmojis: options.exportEmojis, + exportVoiceAsText: options.exportVoiceAsText + }) + mediaCache.set(mediaKey, mediaItem) + } + mediaExported++ + if (mediaExported % 5 === 0 || mediaExported === mediaMessages.length) { + onProgress?.({ + current: 25, + total: 100, + currentSession: sessionInfo.displayName, + phase: 'exporting-media', + phaseProgress: mediaExported, + phaseTotal: mediaMessages.length, + phaseLabel: `导出媒体 ${mediaExported}/${mediaMessages.length}` + }) + } + }) + } + + const voiceTranscriptMap = new Map() + + if (voiceMessages.length > 0) { + onProgress?.({ + current: 45, + total: 100, + currentSession: sessionInfo.displayName, + phase: 'exporting-voice', + phaseProgress: 0, + phaseTotal: voiceMessages.length, + phaseLabel: `语音转文字 0/${voiceMessages.length}` + }) + + const VOICE_CONCURRENCY = 4 + let voiceTranscribed = 0 + await parallelLimit(voiceMessages, VOICE_CONCURRENCY, async (msg) => { + const transcript = await this.transcribeVoice(sessionId, String(msg.localId), msg.createTime, msg.senderUsername) + voiceTranscriptMap.set(msg.localId, transcript) + voiceTranscribed++ + onProgress?.({ + current: 45, + total: 100, + currentSession: sessionInfo.displayName, + phase: 'exporting-voice', + phaseProgress: voiceTranscribed, + phaseTotal: voiceMessages.length, + phaseLabel: `语音转文字 ${voiceTranscribed}/${voiceMessages.length}` + }) + }) + } + + onProgress?.({ + current: 60, + total: 100, + currentSession: sessionInfo.displayName, + phase: 'exporting' + }) + + const lines: string[] = [] + lines.push('id,MsgSvrID,type_name,is_sender,talker,msg,src,CreateTime') + + for (let i = 0; i < sortedMessages.length; i++) { + const msg = sortedMessages[i] + const mediaKey = `${msg.localType}_${msg.localId}` + const mediaItem = mediaCache.get(mediaKey) || null + + const typeName = this.getWeCloneTypeName(msg.localType, msg.content || '') + let senderWxid = cleanedMyWxid + if (!msg.isSend) { + senderWxid = isGroup && msg.senderUsername + ? msg.senderUsername + : sessionId + } + + let talker = myInfo.displayName || '我' + if (!msg.isSend) { + const contactDetail = await getContactCached(senderWxid) + const senderNickname = contactDetail.success && contactDetail.contact + ? (contactDetail.contact.nickName || senderWxid) + : senderWxid + const senderRemark = contactDetail.success && contactDetail.contact + ? (contactDetail.contact.remark || '') + : '' + const senderGroupNickname = isGroup + ? this.resolveGroupNicknameByCandidates(groupNicknamesMap, [senderWxid]) + : '' + talker = this.getPreferredDisplayName( + senderWxid, + senderNickname, + senderRemark, + senderGroupNickname, + options.displayNamePreference || 'remark' + ) + } + + const msgText = msg.localType === 34 && options.exportVoiceAsText + ? (voiceTranscriptMap.get(msg.localId) || '[语音消息 - 转文字失败]') + : (this.parseMessageContent(msg.content, msg.localType, sessionId, msg.createTime) || '') + const src = this.getWeCloneSource(msg, typeName, mediaItem) + + const row = [ + i + 1, + i + 1, + typeName, + msg.isSend ? 1 : 0, + talker, + msgText, + src, + this.formatIsoTimestamp(msg.createTime) + ] + + lines.push(row.map((value) => this.escapeCsvCell(value)).join(',')) + + if ((i + 1) % 200 === 0) { + const progress = 60 + Math.floor((i + 1) / sortedMessages.length * 30) + onProgress?.({ + current: progress, + total: 100, + currentSession: sessionInfo.displayName, + phase: 'exporting' + }) + } + } + + onProgress?.({ + current: 92, + total: 100, + currentSession: sessionInfo.displayName, + phase: 'writing' + }) + + fs.writeFileSync(outputPath, `\uFEFF${lines.join('\r\n')}`, 'utf-8') + + onProgress?.({ + current: 100, + total: 100, + currentSession: sessionInfo.displayName, + phase: 'complete' + }) + + return { success: true } + } catch (e) { + return { success: false, error: String(e) } + } + } + private getVirtualScrollScript(): string { return ` class ChunkedRenderer { @@ -4228,6 +4524,7 @@ class ExportService { if (options.format === 'chatlab-jsonl') ext = '.jsonl' else if (options.format === 'excel') ext = '.xlsx' else if (options.format === 'txt') ext = '.txt' + else if (options.format === 'weclone') ext = '.csv' else if (options.format === 'html') ext = '.html' const outputPath = path.join(sessionDir, `${safeName}${ext}`) @@ -4240,6 +4537,8 @@ class ExportService { result = await this.exportSessionToExcel(sessionId, outputPath, options, sessionProgress) } else if (options.format === 'txt') { result = await this.exportSessionToTxt(sessionId, outputPath, options, sessionProgress) + } else if (options.format === 'weclone') { + result = await this.exportSessionToWeCloneCsv(sessionId, outputPath, options, sessionProgress) } else if (options.format === 'html') { result = await this.exportSessionToHtml(sessionId, outputPath, options, sessionProgress) } else { diff --git a/src/pages/DualReportPage.tsx b/src/pages/DualReportPage.tsx index 3516589..a8398fc 100644 --- a/src/pages/DualReportPage.tsx +++ b/src/pages/DualReportPage.tsx @@ -7,6 +7,7 @@ interface ContactRanking { username: string displayName: string avatarUrl?: string + wechatId?: string messageCount: number sentCount: number receivedCount: number @@ -15,28 +16,29 @@ interface ContactRanking { function DualReportPage() { const navigate = useNavigate() - const [year, setYear] = useState(0) + const [year] = useState(() => { + const params = new URLSearchParams(window.location.hash.split('?')[1] || '') + const yearParam = params.get('year') + const parsedYear = yearParam ? parseInt(yearParam, 10) : 0 + return Number.isNaN(parsedYear) ? 0 : parsedYear + }) const [rankings, setRankings] = useState([]) const [isLoading, setIsLoading] = useState(true) const [loadError, setLoadError] = useState(null) const [keyword, setKeyword] = useState('') useEffect(() => { - const params = new URLSearchParams(window.location.hash.split('?')[1] || '') - const yearParam = params.get('year') - const parsedYear = yearParam ? parseInt(yearParam, 10) : 0 - setYear(Number.isNaN(parsedYear) ? 0 : parsedYear) - }, []) + void loadRankings(year) + }, [year]) - useEffect(() => { - loadRankings() - }, []) - - const loadRankings = async () => { + const loadRankings = async (reportYear: number) => { setIsLoading(true) setLoadError(null) try { - const result = await window.electronAPI.analytics.getContactRankings(200) + const isAllTime = reportYear <= 0 + const beginTimestamp = isAllTime ? 0 : Math.floor(new Date(reportYear, 0, 1).getTime() / 1000) + const endTimestamp = isAllTime ? 0 : Math.floor(new Date(reportYear, 11, 31, 23, 59, 59).getTime() / 1000) + const result = await window.electronAPI.analytics.getContactRankings(200, beginTimestamp, endTimestamp) if (result.success && result.data) { setRankings(result.data) } else { @@ -55,7 +57,8 @@ function DualReportPage() { if (!keyword.trim()) return rankings const q = keyword.trim().toLowerCase() return rankings.filter((item) => { - return item.displayName.toLowerCase().includes(q) || item.username.toLowerCase().includes(q) + const wechatId = (item.wechatId || '').toLowerCase() + return item.displayName.toLowerCase().includes(q) || wechatId.includes(q) }) }, [rankings, keyword]) @@ -99,7 +102,7 @@ function DualReportPage() { setKeyword(e.target.value)} - placeholder="搜索好友(昵称/备注/wxid)" + placeholder="搜索好友(昵称/微信号)" /> @@ -119,7 +122,7 @@ function DualReportPage() {
{item.displayName}
-
{item.username}
+
{item.wechatId || '\u672A\u8bbe\u7f6e\u5fae\u4fe1\u53f7'}
{item.messageCount.toLocaleString()} 条
diff --git a/src/pages/DualReportWindow.scss b/src/pages/DualReportWindow.scss index 574068e..221604e 100644 --- a/src/pages/DualReportWindow.scss +++ b/src/pages/DualReportWindow.scss @@ -82,29 +82,18 @@ } .first-chat-scene { - background: linear-gradient(180deg, - color-mix(in srgb, var(--primary) 60%, #000) 0%, - color-mix(in srgb, var(--primary) 40%, #fff) 50%, - var(--ar-bg-color) 100%); - border-radius: 20px; - padding: 28px 24px 24px; - color: var(--text-primary); + background: color-mix(in srgb, var(--ar-card-bg) 92%, #fff 8%); + border-radius: 16px; + padding: 18px 16px 16px; + color: var(--ar-text-main); position: relative; overflow: hidden; margin-top: 16px; - border: 1px solid var(--border-color); + border: 1px solid var(--bg-tertiary, rgba(0, 0, 0, 0.06)); } .first-chat-scene::before { - content: ""; - position: absolute; - inset: 0; - background-image: - radial-gradient(circle at 20% 20%, color-mix(in srgb, var(--primary) 20%, transparent), transparent 40%), - radial-gradient(circle at 80% 10%, color-mix(in srgb, var(--accent) 15%, transparent), transparent 35%), - radial-gradient(circle at 50% 80%, color-mix(in srgb, var(--primary) 12%, transparent), transparent 45%); - opacity: 0.6; - pointer-events: none; + display: none; } .scene-title { @@ -112,7 +101,7 @@ font-weight: 700; text-align: center; margin-bottom: 8px; - color: var(--text-primary); + color: var(--ar-text-main); } .scene-subtitle { @@ -121,13 +110,13 @@ text-align: center; margin-bottom: 20px; opacity: 0.9; - color: var(--text-secondary); + color: var(--ar-text-sub); } .scene-messages { display: flex; flex-direction: column; - gap: 14px; + gap: 16px; } .scene-message { @@ -141,30 +130,53 @@ } .scene-avatar { - width: 40px; - height: 40px; - border-radius: 12px; - background: var(--primary-light); + width: 42px; + height: 42px; + border-radius: 50%; + background: var(--ar-card-bg); display: flex; align-items: center; justify-content: center; font-weight: 700; - color: var(--primary); + color: var(--ar-text-sub); + border: 1px solid var(--bg-tertiary, rgba(0, 0, 0, 0.08)); + overflow: hidden; + flex-shrink: 0; + + img { + width: 100%; + height: 100%; + object-fit: cover; + display: block; + } + } + + .scene-content-wrapper { + display: flex; + flex-direction: column; + width: 100%; + max-width: min(78%, 720px); + } + + .scene-message.sent .scene-content-wrapper { + align-items: flex-end; } .scene-bubble { - background: var(--bg-secondary); - color: var(--text-primary); + background: color-mix(in srgb, var(--ar-card-bg-hover) 90%, #fff 10%); + color: var(--ar-text-main); padding: 10px 14px; - border-radius: 14px; - max-width: 60%; - box-shadow: var(--shadow-md); - border: 1px solid var(--border-color); + border-radius: 12px; + width: fit-content; + min-width: 68px; + max-width: 100%; + box-shadow: 0 1px 4px rgba(0, 0, 0, 0.04); + border: 1px solid var(--bg-tertiary, rgba(0, 0, 0, 0.06)); } .scene-message.sent .scene-bubble { - background: color-mix(in srgb, var(--primary) 15%, var(--bg-secondary)); - border-color: color-mix(in srgb, var(--primary) 30%, var(--border-color)); + background: color-mix(in srgb, var(--primary) 12%, var(--ar-card-bg-hover)); + border-color: color-mix(in srgb, var(--primary) 26%, var(--bg-tertiary, rgba(0, 0, 0, 0.06))); } .scene-meta { @@ -176,13 +188,24 @@ .scene-content { font-size: 14px; - line-height: 1.4; + line-height: 1.65; + white-space: pre-wrap; word-break: break-word; + overflow-wrap: break-word; + line-break: auto; + } + + .scene-avatar.fallback { + font-size: 14px; + } + + .scene-avatar.with-image { + background: transparent; + color: transparent; } .scene-message.sent .scene-avatar { - background: var(--primary); - color: #fff; + border-color: color-mix(in srgb, var(--primary) 30%, var(--bg-tertiary, rgba(0, 0, 0, 0.08))); } .dual-stat-grid { @@ -296,6 +319,13 @@ font-size: 14px; border: 2px solid var(--ar-card-bg); box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1); + + img { + width: 100%; + height: 100%; + object-fit: cover; + border-radius: 50%; + } } .count { @@ -303,6 +333,13 @@ font-weight: 600; color: var(--ar-text-sub); } + + .percent { + font-size: 12px; + color: var(--ar-text-main); + opacity: 0.85; + font-weight: 600; + } } .initiative-progress { @@ -347,7 +384,7 @@ // --- New Response Speed Section (Grid + Icons) --- .response-grid { display: grid; - grid-template-columns: 1fr 1fr; + grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 16px; margin-top: 24px; padding: 0 10px; @@ -391,6 +428,11 @@ color: var(--ar-accent); } + &.sample .icon-box { + background: rgba(16, 174, 255, 0.08); + color: #10AEFF; + } + .label { font-size: 13px; color: var(--ar-text-sub); @@ -412,6 +454,14 @@ } } + .response-note { + margin-top: 14px; + max-width: none; + text-align: center; + font-size: 14px; + color: var(--ar-text-sub); + } + // --- New Streak Section (Flame) --- .streak-container { @@ -473,4 +523,32 @@ border: 1px solid var(--bg-tertiary, rgba(0, 0, 0, 0.05)); box-shadow: 0 2px 8px rgba(0, 0, 0, 0.03); } -} \ No newline at end of file + + .emoji-count { + font-size: 12px; + color: var(--ar-text-sub); + opacity: 0.85; + } + + @media (max-width: 960px) { + .response-grid { + grid-template-columns: 1fr; + padding: 0; + } + + .scene-avatar { + width: 36px; + height: 36px; + font-size: 13px; + } + + .scene-content-wrapper { + max-width: min(86%, 500px); + } + + .scene-bubble { + max-width: 100%; + min-width: 56px; + } + } +} diff --git a/src/pages/DualReportWindow.tsx b/src/pages/DualReportWindow.tsx index 087be97..cf9f005 100644 --- a/src/pages/DualReportWindow.tsx +++ b/src/pages/DualReportWindow.tsx @@ -1,5 +1,5 @@ -import { useEffect, useState, type CSSProperties } from 'react' -import { Clock, Zap, MessageSquare, Type, Image as ImageIcon, Mic, Smile } from 'lucide-react' +import { useEffect, useState } from 'react' +import { Clock, Zap, MessageCircle, MessageSquare, Type, Image as ImageIcon, Mic, Smile } from 'lucide-react' import ReportHeatmap from '../components/ReportHeatmap' import ReportWordCloud from '../components/ReportWordCloud' import './AnnualReportWindow.scss' @@ -15,8 +15,10 @@ interface DualReportMessage { interface DualReportData { year: number selfName: string + selfAvatarUrl?: string friendUsername: string friendName: string + friendAvatarUrl?: string firstChat: { createTime: number createTimeStr: string @@ -43,6 +45,8 @@ interface DualReportData { friendTopEmojiMd5?: string myTopEmojiUrl?: string friendTopEmojiUrl?: string + myTopEmojiCount?: number + friendTopEmojiCount?: number } topPhrases: Array<{ phrase: string; count: number }> heatmap?: number[][] @@ -108,6 +112,8 @@ function DualReportWindow() { useEffect(() => { const loadEmojis = async () => { if (!reportData) return + setMyEmojiUrl(null) + setFriendEmojiUrl(null) const stats = reportData.stats if (stats.myTopEmojiUrl) { const res = await window.electronAPI.chat.downloadEmoji(stats.myTopEmojiUrl, stats.myTopEmojiMd5) @@ -178,6 +184,9 @@ function DualReportWindow() { : null const yearFirstChat = reportData.yearFirstChat const stats = reportData.stats + const initiativeTotal = (reportData.initiative?.initiated || 0) + (reportData.initiative?.received || 0) + const initiatedPercent = initiativeTotal > 0 ? (reportData.initiative!.initiated / initiativeTotal) * 100 : 0 + const receivedPercent = initiativeTotal > 0 ? (reportData.initiative!.received / initiativeTotal) * 100 : 0 const statItems = [ { label: '总消息数', value: stats.totalMessages, icon: MessageSquare, color: '#07C160' }, { label: '总字数', value: stats.totalWords, icon: Type, color: '#10AEFF' }, @@ -196,6 +205,13 @@ function DualReportWindow() { ) const stripCdata = (text: string) => text.replace(//g, '$1') + const compactMessageText = (text: string) => ( + text + .replace(/\r\n/g, '\n') + .replace(/\s*\n+\s*/g, ' ') + .replace(/\s{2,}/g, ' ') + .trim() + ) const extractXmlText = (content: string) => { const titleMatch = content.match(/([\s\S]*?)<\/title>/i) @@ -210,18 +226,18 @@ function DualReportWindow() { } const formatMessageContent = (content?: string) => { - const raw = String(content || '').trim() + const raw = compactMessageText(String(content || '').trim()) if (!raw) return '(空)' // 1. 尝试提取 XML 关键字段 const titleMatch = raw.match(/<title>([\s\S]*?)<\/title>/i) - if (titleMatch?.[1]) return decodeEntities(stripCdata(titleMatch[1]).trim()) + if (titleMatch?.[1]) return compactMessageText(decodeEntities(stripCdata(titleMatch[1]).trim())) const descMatch = raw.match(/<des>([\s\S]*?)<\/des>/i) - if (descMatch?.[1]) return decodeEntities(stripCdata(descMatch[1]).trim()) + if (descMatch?.[1]) return compactMessageText(decodeEntities(stripCdata(descMatch[1]).trim())) const summaryMatch = raw.match(/<summary>([\s\S]*?)<\/summary>/i) - if (summaryMatch?.[1]) return decodeEntities(stripCdata(summaryMatch[1]).trim()) + if (summaryMatch?.[1]) return compactMessageText(decodeEntities(stripCdata(summaryMatch[1]).trim())) // 2. 检查是否是 XML 结构 const hasXmlTag = /<\s*[a-zA-Z]+[^>]*>/.test(raw) @@ -232,7 +248,7 @@ function DualReportWindow() { // 3. 最后的尝试:移除所有 XML 标签,看是否还有有意义的文本 const stripped = raw.replace(/<[^>]+>/g, '').trim() if (stripped && stripped.length > 0 && stripped.length < 50) { - return decodeEntities(stripped) + return compactMessageText(decodeEntities(stripped)) } return '(多媒体/卡片消息)' @@ -247,6 +263,43 @@ function DualReportWindow() { return `${year}/${month}/${day} ${hour}:${minute}` } + const getMostActiveTime = (data: number[][]) => { + let maxHour = 0 + let maxWeekday = 0 + let maxVal = -1 + data.forEach((row, weekday) => { + row.forEach((value, hour) => { + if (value > maxVal) { + maxVal = value + maxHour = hour + maxWeekday = weekday + } + }) + }) + const weekdayNames = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'] + return { + weekday: weekdayNames[maxWeekday] || '周一', + hour: maxHour, + value: Math.max(0, maxVal) + } + } + + const mostActive = reportData.heatmap ? getMostActiveTime(reportData.heatmap) : null + const responseAvgMinutes = reportData.response ? Math.max(0, Math.round(reportData.response.avg / 60)) : 0 + const getSceneAvatarUrl = (isSentByMe: boolean) => (isSentByMe ? reportData.selfAvatarUrl : reportData.friendAvatarUrl) + const getSceneAvatarFallback = (isSentByMe: boolean) => (isSentByMe ? '我' : reportData.friendName.substring(0, 1)) + const renderSceneAvatar = (isSentByMe: boolean) => { + const avatarUrl = getSceneAvatarUrl(isSentByMe) + if (avatarUrl) { + return ( + <div className="scene-avatar with-image"> + <img src={avatarUrl} alt={isSentByMe ? 'me-avatar' : 'friend-avatar'} /> + </div> + ) + } + return <div className="scene-avatar fallback">{getSceneAvatarFallback(isSentByMe)}</div> + } + return ( <div className="annual-report-window dual-report-window"> <div className="drag-region" /> @@ -284,9 +337,7 @@ function DualReportWindow() { <div className="scene-messages"> {firstChatMessages.map((msg, idx) => ( <div key={idx} className={`scene-message ${msg.isSentByMe ? 'sent' : 'received'}`}> - <div className="scene-avatar"> - {msg.isSentByMe ? '我' : reportData.friendName.substring(0, 1)} - </div> + {renderSceneAvatar(msg.isSentByMe)} <div className="scene-content-wrapper"> <div className="scene-meta"> {formatFullDate(msg.createTime).split(' ')[1]} @@ -322,9 +373,7 @@ function DualReportWindow() { <div className="scene-messages"> {yearFirstChat.firstThreeMessages.map((msg, idx) => ( <div key={idx} className={`scene-message ${msg.isSentByMe ? 'sent' : 'received'}`}> - <div className="scene-avatar"> - {msg.isSentByMe ? '我' : reportData.friendName.substring(0, 1)} - </div> + {renderSceneAvatar(msg.isSentByMe)} <div className="scene-content-wrapper"> <div className="scene-meta"> {formatFullDate(msg.createTime).split(' ')[1]} @@ -344,6 +393,11 @@ function DualReportWindow() { <section className="section"> <div className="label-text">聊天习惯</div> <h2 className="hero-title">作息规律</h2> + {mostActive && ( + <p className="hero-desc active-time dual-active-time"> + {'\u5728'} <span className="hl">{mostActive.weekday} {String(mostActive.hour).padStart(2, '0')}:00</span> {'\u6700\u6d3b\u8dc3\uff08'}{mostActive.value}{'\u6761\uff09'} + </p> + )} <ReportHeatmap data={reportData.heatmap} /> </section> )} @@ -358,22 +412,28 @@ function DualReportWindow() { </div> <div className="initiative-bar-wrapper"> <div className="initiative-side"> - <div className="avatar-placeholder">我</div> - <div className="count">{reportData.initiative.initiated}次</div> + <div className="avatar-placeholder"> + {reportData.selfAvatarUrl ? <img src={reportData.selfAvatarUrl} alt="me-avatar" /> : '\u6211'} + </div> + <div className="count">{reportData.initiative.initiated}{'\u6b21'}</div> + <div className="percent">{initiatedPercent.toFixed(1)}%</div> </div> <div className="initiative-progress"> <div className="bar-segment left" - style={{ width: `${reportData.initiative.initiated / (reportData.initiative.initiated + reportData.initiative.received) * 100}%` }} + style={{ width: `${initiatedPercent}%` }} /> <div className="bar-segment right" - style={{ width: `${reportData.initiative.received / (reportData.initiative.initiated + reportData.initiative.received) * 100}%` }} + style={{ width: `${receivedPercent}%` }} /> </div> <div className="initiative-side"> - <div className="avatar-placeholder">{reportData.friendName.substring(0, 1)}</div> - <div className="count">{reportData.initiative.received}次</div> + <div className="avatar-placeholder"> + {reportData.friendAvatarUrl ? <img src={reportData.friendAvatarUrl} alt="friend-avatar" /> : reportData.friendName.substring(0, 1)} + </div> + <div className="count">{reportData.initiative.received}{'\u6b21'}</div> + <div className="percent">{receivedPercent.toFixed(1)}%</div> </div> </div> </div> @@ -383,33 +443,43 @@ function DualReportWindow() { {reportData.response && ( <section className="section"> <div className="label-text">回复速度</div> - <h2 className="hero-title">秒回是并在乎</h2> + <h2 className="hero-title">{'\u79d2\u56de\uff0c\u662f\u56e0\u4e3a\u5728\u4e4e'}</h2> <div className="response-grid"> <div className="response-card"> <div className="icon-box"> <Clock size={24} /> </div> - <div className="label">平均回复</div> - <div className="value">{Math.round(reportData.response.avg / 60)}<span>分</span></div> + <div className="label">{'\u5e73\u5747\u56de\u590d'}</div> + <div className="value">{Math.round(reportData.response.avg / 60)}<span>{'\u5206'}</span></div> </div> <div className="response-card fastest"> <div className="icon-box"> <Zap size={24} /> </div> - <div className="label">最快回复</div> - <div className="value">{reportData.response.fastest}<span>秒</span></div> + <div className="label">{'\u6700\u5feb\u56de\u590d'}</div> + <div className="value">{reportData.response.fastest}<span>{'\u79d2'}</span></div> + </div> + <div className="response-card sample"> + <div className="icon-box"> + <MessageCircle size={24} /> + </div> + <div className="label">{'\u7edf\u8ba1\u6837\u672c'}</div> + <div className="value">{reportData.response.count}<span>{'\u6b21'}</span></div> </div> </div> + <p className="hero-desc response-note"> + {`\u5171\u7edf\u8ba1 ${reportData.response.count} \u6b21\u6709\u6548\u56de\u590d\uff0c\u5e73\u5747\u7ea6 ${responseAvgMinutes} \u5206\u949f\uff0c\u6700\u5feb ${reportData.response.fastest} \u79d2\u3002`} + </p> </section> )} {reportData.streak && ( <section className="section"> - <div className="label-text">聊天火花</div> - <h2 className="hero-title">最长连续聊天</h2> + <div className="label-text">{'\u804a\u5929\u706b\u82b1'}</div> + <h2 className="hero-title">{'\u6700\u957f\u8fde\u7eed\u804a\u5929'}</h2> <div className="streak-container"> - <div className="streak-flame">🔥</div> - <div className="streak-days">{reportData.streak.days}<span>天</span></div> + <div className="streak-flame">{'\uD83D\uDD25'}</div> + <div className="streak-days">{reportData.streak.days}<span>{'\u5929'}</span></div> <div className="streak-range"> {reportData.streak.startDate} ~ {reportData.streak.endDate} </div> @@ -461,6 +531,7 @@ function DualReportWindow() { ) : ( <div className="emoji-placeholder">{stats.myTopEmojiMd5 || '暂无'}</div> )} + <div className="emoji-count">{stats.myTopEmojiCount ? `${stats.myTopEmojiCount}\u6b21` : '\u6682\u65e0\u7edf\u8ba1'}</div> </div> <div className="emoji-card"> <div className="emoji-title">{reportData.friendName}常用的表情</div> @@ -469,6 +540,7 @@ function DualReportWindow() { ) : ( <div className="emoji-placeholder">{stats.friendTopEmojiMd5 || '暂无'}</div> )} + <div className="emoji-count">{stats.friendTopEmojiCount ? `${stats.friendTopEmojiCount}\u6b21` : '\u6682\u65e0\u7edf\u8ba1'}</div> </div> </div> </section> diff --git a/src/pages/ExportPage.tsx b/src/pages/ExportPage.tsx index 7ffc1cc..92b9d81 100644 --- a/src/pages/ExportPage.tsx +++ b/src/pages/ExportPage.tsx @@ -13,7 +13,7 @@ interface ChatSession { } interface ExportOptions { - format: 'chatlab' | 'chatlab-jsonl' | 'json' | 'html' | 'txt' | 'excel' | 'sql' + format: 'chatlab' | 'chatlab-jsonl' | 'json' | 'html' | 'txt' | 'excel' | 'weclone' | 'sql' dateRange: { start: Date; end: Date } | null useAllTime: boolean exportAvatars: boolean @@ -360,7 +360,7 @@ function ExportPage() { } : null } - if (options.format === 'chatlab' || options.format === 'chatlab-jsonl' || options.format === 'json' || options.format === 'excel' || options.format === 'txt' || options.format === 'html') { + if (options.format === 'chatlab' || options.format === 'chatlab-jsonl' || options.format === 'json' || options.format === 'excel' || options.format === 'txt' || options.format === 'html' || options.format === 'weclone') { const result = await window.electronAPI.export.exportSessions( sessionList, exportFolder, @@ -513,6 +513,7 @@ function ExportPage() { { value: 'html', label: 'HTML', icon: FileText, desc: '网页格式,可直接浏览' }, { value: 'txt', label: 'TXT', icon: Table, desc: '纯文本,通用格式' }, { value: 'excel', label: 'Excel', icon: FileSpreadsheet, desc: '电子表格,适合统计分析' }, + { value: 'weclone', label: 'WeClone CSV', icon: Table, desc: 'WeClone 兼容字段格式(CSV)' }, { value: 'sql', label: 'PostgreSQL', icon: Database, desc: '数据库脚本,便于导入到数据库' } ] const displayNameOptions = [ diff --git a/src/pages/SettingsPage.tsx b/src/pages/SettingsPage.tsx index b3187c9..b6a01d6 100644 --- a/src/pages/SettingsPage.tsx +++ b/src/pages/SettingsPage.tsx @@ -1565,6 +1565,7 @@ function SettingsPage() { { value: 'json', label: 'JSON', desc: '详细格式,包含完整消息信息' }, { value: 'html', label: 'HTML', desc: '网页格式,可直接浏览' }, { value: 'txt', label: 'TXT', desc: '纯文本,通用格式' }, + { value: 'weclone', label: 'WeClone CSV', desc: 'WeClone 兼容字段格式(CSV)' }, { value: 'sql', label: 'PostgreSQL', desc: '数据库脚本,便于导入到数据库' } ] const exportDateRangeOptions = [ diff --git a/src/types/electron.d.ts b/src/types/electron.d.ts index e66004c..ad0daf3 100644 --- a/src/types/electron.d.ts +++ b/src/types/electron.d.ts @@ -163,12 +163,13 @@ export interface ElectronAPI { } error?: string }> - getContactRankings: (limit?: number) => Promise<{ + getContactRankings: (limit?: number, beginTimestamp?: number, endTimestamp?: number) => Promise<{ success: boolean data?: Array<{ username: string displayName: string avatarUrl?: string + wechatId?: string messageCount: number sentCount: number receivedCount: number @@ -357,8 +358,10 @@ export interface ElectronAPI { data?: { year: number selfName: string + selfAvatarUrl?: string friendUsername: string friendName: string + friendAvatarUrl?: string firstChat: { createTime: number createTimeStr: string @@ -395,8 +398,15 @@ export interface ElectronAPI { friendTopEmojiMd5?: string myTopEmojiUrl?: string friendTopEmojiUrl?: string + myTopEmojiCount?: number + friendTopEmojiCount?: number } 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 }>