Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
597667e005 | ||
|
|
515348b6d8 | ||
|
|
e150605c91 | ||
|
|
556d70eab3 | ||
|
|
9bd2c4bb94 | ||
|
|
19128fccca | ||
|
|
eaf8e9b07d | ||
|
|
aebf56b3f7 | ||
|
|
ce4b00bcd9 | ||
|
|
31df97237d | ||
|
|
7b54b611d3 | ||
|
|
f1ceef0e5e | ||
|
|
ab24185670 | ||
|
|
842144eba0 | ||
|
|
d37341ab52 | ||
|
|
5d041aa137 | ||
|
|
519c10223d | ||
|
|
d28b579cb4 | ||
|
|
c291c94bd8 | ||
|
|
16a9aed6bb | ||
|
|
7880e874b2 | ||
|
|
7e217f7034 | ||
|
|
4f0b4884b6 | ||
|
|
d4f6b755e5 | ||
|
|
995a95e8dc | ||
|
|
8bb9576f10 | ||
|
|
a776830144 | ||
|
|
ad50939005 | ||
|
|
71e970c55c | ||
|
|
8d82fabf57 | ||
|
|
e8c12696b2 | ||
|
|
267730d59e | ||
|
|
3dbc11c19d | ||
|
|
d079d45279 | ||
|
|
b39cb362f7 | ||
|
|
a0b163823d |
@@ -1,16 +1,20 @@
|
||||
# WeChat Database Key (Optional, can be entered in UI)
|
||||
VITE_DB_KEY=
|
||||
|
||||
# Auto login on startup with VITE_DB_KEY or saved key.
|
||||
# Set to true/1/yes/on for local development. Default is disabled.
|
||||
VITE_AUTO_LOGIN=false
|
||||
|
||||
# AI API Configuration (Optional, can be entered in UI)
|
||||
VITE_DEEPSEEK_API_KEY=
|
||||
VITE_AI_BASE_URL=https://api.deepseek.com
|
||||
VITE_AI_MODEL=deepseek-chat
|
||||
VITE_AI_MODEL=deepseek-v4-flash
|
||||
|
||||
# Message types to filter out (comma separated). Empty means show all message types.
|
||||
VITE_FILTER_MSG_TYPES=
|
||||
|
||||
# Image Decryption Keys (Optional, for WeChat 4.0+ image decryption)
|
||||
# These are used to decrypt image .dat files in WeChat 4.0+
|
||||
# These are dev fallbacks. End users can fill or auto-fetch them in Settings.
|
||||
# XOR Key: hex format like 0x40, 0x53 etc.
|
||||
# AES Key: 16-character string, derived from wxid and code
|
||||
VITE_IMAGE_XOR_KEY=
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
node_modules
|
||||
*.tsbuildinfo
|
||||
dist
|
||||
out
|
||||
.env
|
||||
@@ -6,3 +7,8 @@ out
|
||||
.eslintcache
|
||||
*.log*
|
||||
.omc
|
||||
.codex/
|
||||
docs/design/
|
||||
docs/ui-redesign-plan.md
|
||||
docs/ui-redesign-spec.md
|
||||
AGENTS.md
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# WechatExplorer
|
||||
|
||||
MAC系统 获取微信聊天记录 AI一键生成群聊总结
|
||||
macOS / Windows 微信聊天记录查看,AI 一键生成群聊总结。
|
||||
是一个基于 Electron + React + TypeScript 开发的微信聊天记录查看与分析工具。它支持查看解密后的微信数据库内容,提供聊天记录搜索、导出以及 AI 智能总结功能。
|
||||
|
||||
## 项目说明
|
||||
@@ -9,6 +9,8 @@ MAC系统 获取微信聊天记录 AI一键生成群聊总结
|
||||
|
||||
在微信 4.0 数据库解析、解密思路上,项目参考了 [WeFlow](https://github.com/hicccc77/WeFlow) 等开源项目的实现方式;此项目围绕我自己的使用场景做的定制化工具,重点放在本地聊天记录查看、群聊总结和个人工作流集成上。
|
||||
|
||||
> 当前版本:`v2.1.0`。macOS 支持相对稳定;Windows 已初步支持微信 4.0 数据库连接、自动获取密钥和聊天记录查看,仍在持续兼容不同微信版本与本地目录结构。
|
||||
|
||||
## ✨ 功能特性
|
||||
|
||||
- **聊天记录查看**: 浏览微信好友和群聊的聊天记录,支持头像显示。
|
||||
@@ -16,10 +18,13 @@ MAC系统 获取微信聊天记录 AI一键生成群聊总结
|
||||
- **AI 智能总结**: 支持多模型服务配置(DeepSeek/GPT-4o/Claude/Moonshot),一键总结群聊精华内容,生成话题报告。
|
||||
- **群聊日报生成**: 支持围绕群聊内容生成日报,通常会覆盖以下模块中的部分或全部内容:
|
||||
- **今日讨论热点**: 梳理群内主要话题,支持热度标签。
|
||||
- **一句话速览**: 首屏突出今日核心结论与待跟进事项。
|
||||
- **实用信息与资源**: 提取分享的链接、资源等信息。
|
||||
- **重要消息汇总**: 标记并展示重要消息,带发送者头像。
|
||||
- **有趣对话或金句**: 收录群内的精彩对话。
|
||||
- **问题与解答**: 整理群内的问答内容。
|
||||
- **尚未解决 / 今日剧情线**: 更适合工作群和项目群的回顾与跟进。
|
||||
- **今日群相册 / 语音时长榜 / 临时群友称号**: 让图片、语音和氛围型内容也能参与日报。
|
||||
- **群内数据可视化**: 消息热度条形图、话唠榜 TOP5、活跃时间线。
|
||||
- **词云/关键词**: 可视化展示群聊关键词。
|
||||
- **图片生成**: 将 AI 总结的内容生成精美图片,方便分享。
|
||||
@@ -28,29 +33,53 @@ MAC系统 获取微信聊天记录 AI一键生成群聊总结
|
||||
|
||||
## 📸 预览
|
||||
|
||||
### 群聊总结长图
|
||||
### 日报模板
|
||||
|
||||
<img src="./public/example1.png" alt="总结图片" />
|
||||
<details>
|
||||
<summary>点击查看完整日报模板</summary>
|
||||
<br />
|
||||
<img src="./public/report-template-1.png" alt="完整日报模板" />
|
||||
</details>
|
||||
|
||||
### 软件主页面
|
||||
### AI 群聊日报界面
|
||||
|
||||
<img src="./public/example2.png" alt="软件主页面" />
|
||||
<img src="./public/software-1.png" alt="AI 群聊日报页面" />
|
||||
|
||||
### 本地 API 与 Reader Skill
|
||||
|
||||
<img src="./public/software-2.png" alt="本地 API 与 Reader Skill 页面" />
|
||||
|
||||
## [点击这里下载](https://github.com/Wxw-Gu/WechatExplorer/releases)
|
||||
|
||||
## 📦 安装说明
|
||||
|
||||
1. 下载下方的 `xxx.dmg` 文件。
|
||||
### macOS 版本已测 4.1.8
|
||||
|
||||
> 微信 macOS `4.1.8.100` 下载地址:[wechat-versions v4.1.8.100](https://github.com/zsbai/wechat-versions/releases/tag/4.1.8.100)
|
||||
|
||||
1. 下载 Releases 中的 `xxx.dmg` 文件。
|
||||
2. 打开 DMG 并将应用拖动到 **Applications** (应用程序) 文件夹。
|
||||
3. 如果遇到“无法打开,因为开发者无法验证”的提示,请前往:
|
||||
`系统设置 -> 隐私与安全性 -> 仍要打开`。
|
||||
4. 打开微信登录界面不要登录,然后点击获取密钥,提示登录 然后点击登录 自动获取密钥
|
||||
|
||||
### Windows 版本已测 4.1.9
|
||||
|
||||
> 微信 Windows `4.1.9.57` 下载地址:[wechat-win-archive v4.1.9.57](https://github.com/iibob/wechat-win-archive/releases#release-v4.1.9.57)
|
||||
|
||||
1. 下载 Releases 中的 `xxx-setup.exe` 安装包。
|
||||
2. 双击安装,可按安装向导选择安装目录。
|
||||
3. 打开微信登录界面不要登录,然后点击获取密钥,提示登录 然后点击登录 自动获取密钥。
|
||||
|
||||
> Windows 支持仍处于初步阶段。软件会有些卡顿, 如果自动获取密钥失败,请先确认微信客户端已登录并保持运行;不同微信安装路径、数据目录和权限环境可能仍需要继续适配。
|
||||
|
||||
## 🚀 快速开始
|
||||
|
||||
### 使用前置要求
|
||||
|
||||
- **微信版本**:
|
||||
- 微信 4.0+: 已支持部分能力,仍在持续迭代与兼容性验证中;如需更成熟的完整方案,推荐使用 [WeFlow](https://github.com/hicccc77/WeFlow) [Chatlog](https://github.com/sjzar/chatlog)
|
||||
- 微信 4.0+: macOS / Windows 已支持部分能力,仍在持续迭代与兼容性验证中;如需更成熟的完整方案,推荐使用 [WeFlow](https://github.com/hicccc77/WeFlow) [Chatlog](https://github.com/sjzar/chatlog)
|
||||
- **macOS 自动获取密钥**: 需要先关闭 SIP,操作方式见 [macOS 关闭 SIP 教程](./docs/mac-disable-sip.md);关闭 SIP 会降低系统安全性,使用完成后建议重新开启。
|
||||
- 如无法获取本地数据库密码,则无法使用当前项目
|
||||
- Node.js (推荐 v16+)
|
||||
- pnpm@7
|
||||
@@ -59,7 +88,7 @@ MAC系统 获取微信聊天记录 AI一键生成群聊总结
|
||||
|
||||
### 环境变量配置 (.env)
|
||||
|
||||
可选配置项,可在 `.env` 文件中设置:
|
||||
可选配置项,可在 `.env` 文件中设置;本地开发时运行 `pnpm dev` 会在 `.env` 不存在时自动从 `.env.example` 复制一份。成品用户也可以直接在软件“设置”里填写或自动获取图片解密密钥。
|
||||
|
||||
| 变量名 | 说明 | 示例 |
|
||||
| ----------------------- | --------------------------- | --------------------------- |
|
||||
@@ -80,8 +109,10 @@ MAC系统 获取微信聊天记录 AI一键生成群聊总结
|
||||
|
||||
这两个密钥可以通过以下方式获取:
|
||||
|
||||
1. 从 WeFlow/Chatlog 设置中导出
|
||||
2. 使用内存扫描工具从微信进程中自动提取(待实现)
|
||||
1. 在应用登录界面点击“自动获取密钥”
|
||||
2. 从 WeFlow/Chatlog 设置中导出
|
||||
3. 在软件“设置 -> 图片解密密钥”中自动获取或手动填写
|
||||
4. 如自动获取失败,可手动粘贴已获取的密钥
|
||||
|
||||
## 🤖 AI 集成(本地 HTTP API)
|
||||
|
||||
@@ -90,6 +121,7 @@ WechatExplorer 内置了一个本地 HTTP API 服务,默认监听 `127.0.0.1:6
|
||||
### 启用本地 API
|
||||
|
||||
API 服务在 WechatExplorer 启动时自动启用,**不需要任何配置**。只需要:
|
||||
|
||||
1. 安装并启动 WechatExplorer
|
||||
2. 完成首次密钥配置(主窗口第一步),解锁 WCDB 数据库
|
||||
3. API 即在 `http://127.0.0.1:6131` 可用
|
||||
@@ -105,37 +137,42 @@ WXE_TRAY=1 open /Applications/WechatExplorer.app
|
||||
```
|
||||
|
||||
启用后:
|
||||
|
||||
- macOS dock 图标自动隐藏
|
||||
- 菜单栏出现 WechatExplorer 图标(可点击重新打开主窗口、查看 API 状态)
|
||||
- 主窗口关闭后 API 服务继续运行
|
||||
|
||||
### API 端点一览
|
||||
|
||||
| 端点 | 说明 |
|
||||
|------|------|
|
||||
| `GET /api/v1/health` | 健康检查 |
|
||||
| `GET /api/v1/current_time` | 获取当前本地时间(用于"今天/昨天"换算) |
|
||||
| `GET /api/v1/contact?filter=xxx` | 联系人 / 群聊列表 |
|
||||
| `GET /api/v1/chatroom?keyword=xxx` | 搜索群聊 |
|
||||
| `GET /api/v1/chatlog?talker=xxx&time=2026-07-03` | 聊天记录 |
|
||||
| `GET /api/v1/group_snapshot?md5=xxx` | 群成员快照 |
|
||||
| `GET /api/v1/resolve?q=群昵称` | 把昵称/wxid/md5 解析成 md5 |
|
||||
| 端点 | 说明 |
|
||||
| ------------------------------------------------ | --------------------------------------- |
|
||||
| `GET /api/v1/health` | 健康检查 |
|
||||
| `GET /api/v1/current_time` | 获取当前本地时间(用于"今天/昨天"换算) |
|
||||
| `GET /api/v1/contact?filter=xxx` | 联系人 / 群聊列表 |
|
||||
| `GET /api/v1/chatroom?keyword=xxx` | 搜索群聊 |
|
||||
| `GET /api/v1/chatlog?talker=xxx&time=2026-07-03` | 聊天记录 |
|
||||
| `GET /api/v1/group_snapshot?md5=xxx` | 群成员快照 |
|
||||
| `GET /api/v1/resolve?q=群昵称` | 把昵称/wxid/md5 解析成 md5 |
|
||||
|
||||
详细参数、返回结构、时间格式见 [`docs/skill/wechatexplorer-reader/SKILL.md`](./docs/skill/wechatexplorer-reader/SKILL.md)。
|
||||
|
||||
### 让 Claude 自动总结你的群聊
|
||||
### 安装 Reader Skill,让 Agent 读取和总结群聊
|
||||
|
||||
复制 [`docs/skill/wechatexplorer-reader/SKILL.md`](./docs/skill/wechatexplorer-reader/SKILL.md) 到 `~/.claude/skills/`,然后在 Claude Desktop 里说:
|
||||
WechatExplorer 已内置 **Reader Skill**,无需手动复制仓库中的 `SKILL.md`:
|
||||
|
||||
> "今天 技术交流群 聊了啥?"
|
||||
1. 启动 WechatExplorer,并确认数据库已连接、本地 API 已运行。
|
||||
2. 打开应用内的 **API** 页面。
|
||||
3. 在“快速接入”中选择 **Codex** 或 **Claude Code**。
|
||||
4. 点击复制安装指令,将指令粘贴给对应的 Agent 执行。
|
||||
5. 安装完成后,可以直接向 Agent 提问:
|
||||
|
||||
Claude 会自动:
|
||||
1. 调 `current_time` 拿到今天日期
|
||||
2. 调 `chatroom` 找到目标群
|
||||
3. 调 `chatlog` 拿 JSON 聊天记录
|
||||
4. 自己用 LLM 生成总结报告
|
||||
> “今天技术交流群聊了什么?”
|
||||
|
||||
### curl 示例
|
||||
Reader Skill 会自动获取本机时间、定位目标群聊、读取所需聊天记录,并结合上下文生成总结。详细接口说明仍可查看 [`docs/skill/wechatexplorer-reader/SKILL.md`](./docs/skill/wechatexplorer-reader/SKILL.md)。
|
||||
|
||||
### curl 调试示例(可选)
|
||||
|
||||
不使用 Agent 时,也可以通过 `curl` 直接调试本地 HTTP API:
|
||||
|
||||
```bash
|
||||
# 健康检查
|
||||
@@ -155,7 +192,7 @@ curl -G "http://127.0.0.1:6131/api/v1/resolve" \
|
||||
|
||||
本项目仅供学习和研究使用。请勿用于非法用途。开发者不对使用本项目造成的任何后果负责。请遵守相关法律法规和微信使用协议。
|
||||
|
||||
## 🔗 参考
|
||||
## 🔗 参考致谢
|
||||
|
||||
- [WechatMessageExplorer](https://github.com/svcvit/WechatMessageExplorer)
|
||||
- [WeFlow](https://github.com/hicccc77/WeFlow)
|
||||
|
||||
|
Before Width: | Height: | Size: 121 KiB After Width: | Height: | Size: 21 KiB |
|
Before Width: | Height: | Size: 35 KiB After Width: | Height: | Size: 27 KiB |
@@ -0,0 +1,47 @@
|
||||
# macOS 关闭 SIP 教程
|
||||
|
||||
SIP(System Integrity Protection,系统完整性保护)是 macOS 的系统安全机制。关闭 SIP 会降低系统安全性,只建议在确实需要读取或调试本地微信数据时临时关闭;操作完成后,建议重新开启。
|
||||
|
||||
## 准备
|
||||
|
||||
- 一台 Mac 电脑,Intel 芯片和 Apple Silicon 芯片均可。
|
||||
- 需要进入 macOS 恢复模式。
|
||||
- 请先保存正在编辑的文件,并预留一次重启时间。
|
||||
|
||||
## 关闭 SIP
|
||||
|
||||
### Intel Mac
|
||||
|
||||
1. 关机。
|
||||
2. 按下开机键后,立刻按住 `Command + R`。
|
||||
3. 保持按住,直到进入 macOS 恢复模式。
|
||||
|
||||
### Apple Silicon Mac(M1/M2/M3/M4)
|
||||
|
||||
1. 关机。
|
||||
2. 长按开机键不放。
|
||||
3. 直到出现启动选项界面后松开。
|
||||
4. 选择“选项”,进入 macOS 恢复模式。
|
||||
|
||||
### 在恢复模式中执行命令
|
||||
|
||||
1. 进入恢复模式后,点击顶部菜单栏的 **Utilities(实用工具)**。
|
||||
2. 选择 **Terminal(终端)**。
|
||||
3. 在终端中输入:
|
||||
|
||||
```bash
|
||||
csrutil disable
|
||||
```
|
||||
|
||||
4. 按回车执行。
|
||||
5. 看到关闭成功提示后,重启电脑。
|
||||
|
||||
## 重新开启 SIP
|
||||
|
||||
如果后续不再需要关闭 SIP,建议重新进入恢复模式,在终端中执行:
|
||||
|
||||
```bash
|
||||
csrutil enable
|
||||
```
|
||||
|
||||
然后重启电脑。
|
||||
@@ -1,6 +1,6 @@
|
||||
---
|
||||
name: wechatexplorer-reader
|
||||
description: 通过本地 HTTP API 读取 WechatExplorer 解锁后的微信聊天数据(本地服务由 WechatExplorer.app 提供)。当用户提到微信聊天记录、群消息、看看群里说了什么、查一下微信、分析微信对话、总结群聊等场景时,使用此技能。注意:此技能的数据源是用户本机 WechatExplorer app,而非 chatlog/WeFlow。
|
||||
description: 通过本地 HTTP API 读取 WechatExplorer 解锁后的微信聊天数据(本地服务由 WechatExplorer.app 提供)。当用户提到微信聊天记录、群消息、看看群里说了什么、查一下微信、分析微信对话、总结群聊等场景时,使用此技能。注意:此技能的数据源是用户本机 WechatExplorer app。
|
||||
---
|
||||
|
||||
# WechatExplorer Reader
|
||||
@@ -141,12 +141,31 @@ GET 用于读取数据,`POST /api/v1/report` 用于生成群日报(HTML + 长图
|
||||
"qa": [
|
||||
{ "question": "Q", "answer": "A", "answerer": "解答人(可选)" }
|
||||
],
|
||||
"unresolved": [
|
||||
{ "question": "待跟进问题", "owner": "相关人(可选)", "status": "待跟进", "note": "为什么还没结束" }
|
||||
],
|
||||
"storylines": [
|
||||
{ "title": "剧情线", "stages": [{ "time": "10:12", "event": "提出问题" }], "result": "可选结果" }
|
||||
],
|
||||
"reversals": [
|
||||
{ "topic": "某话题", "initialView": "最初判断", "finalView": "最终判断", "note": "可选说明" }
|
||||
],
|
||||
"participantChains": [
|
||||
{ "topic": "某话题", "chain": ["A 提出", "B 补充", "C 收尾"], "note": "可选说明" }
|
||||
],
|
||||
"analytics": {
|
||||
"topicHeat": [{ "topic": "话题1", "score": 9.5 }],
|
||||
"activeTimeline": "10:00-12:00 为最活跃时段",
|
||||
"topSpeakers": [{ "name": "张三", "count": 58 }]
|
||||
"topSpeakers": [{ "name": "张三", "count": 58 }],
|
||||
"voiceLeaderboard": [{ "sender": "张三", "count": 3, "durationSec": 97 }]
|
||||
},
|
||||
"keywords": ["高频词1", "高频词2"]
|
||||
"keywords": ["高频词1", "高频词2"],
|
||||
"hero": {
|
||||
"headline": "一句抓重点的日报标题",
|
||||
"summary": "一句概览",
|
||||
"keyTakeaway": "最重要结论",
|
||||
"pendingNote": "待跟进事项"
|
||||
}
|
||||
},
|
||||
"metadata": {
|
||||
"groupName": "技术交流",
|
||||
|
||||
@@ -20,14 +20,25 @@ extraResources:
|
||||
to: resources
|
||||
filter:
|
||||
- '**/*'
|
||||
- from: docs/skill/wechatexplorer-reader
|
||||
to: skill/wechatexplorer-reader
|
||||
filter:
|
||||
- '**/*'
|
||||
win:
|
||||
executableName: wechatexplorer
|
||||
icon: icon.ico
|
||||
# WCDB's Windows runtime checks the host executable name. The dev runtime is
|
||||
# electron.exe, so keep the packaged executable compatible while preserving
|
||||
# WechatExplorer as the product/shortcut name.
|
||||
executableName: electron
|
||||
nsis:
|
||||
oneClick: false
|
||||
allowToChangeInstallationDirectory: true
|
||||
artifactName: ${name}-${version}-setup.${ext}
|
||||
shortcutName: ${productName}
|
||||
uninstallDisplayName: ${productName}
|
||||
createDesktopShortcut: always
|
||||
mac:
|
||||
icon: icon.icns
|
||||
entitlementsInherit: build/entitlements.mac.plist
|
||||
extendInfo:
|
||||
# The bundled WCDB bridge accepts Electron as its internal host name. The
|
||||
@@ -42,6 +53,7 @@ mac:
|
||||
dmg:
|
||||
artifactName: ${name}-${version}-${arch}.${ext}
|
||||
linux:
|
||||
icon: icon.png
|
||||
target:
|
||||
- AppImage
|
||||
- snap
|
||||
@@ -53,4 +65,6 @@ appImage:
|
||||
npmRebuild: false
|
||||
publish:
|
||||
provider: github
|
||||
owner: Wxw-Gu
|
||||
repo: WechatExplorer
|
||||
releaseType: draft
|
||||
|
||||
@@ -3,7 +3,19 @@ import { defineConfig } from 'electron-vite'
|
||||
import react from '@vitejs/plugin-react'
|
||||
|
||||
export default defineConfig({
|
||||
main: {},
|
||||
main: {
|
||||
build: {
|
||||
rollupOptions: {
|
||||
input: {
|
||||
index: resolve('src/main/index.ts')
|
||||
},
|
||||
output: {
|
||||
entryFileNames: '[name].js'
|
||||
},
|
||||
external: ['koffi']
|
||||
}
|
||||
}
|
||||
},
|
||||
preload: {},
|
||||
renderer: {
|
||||
resolve: {
|
||||
|
||||
@@ -1,15 +1,20 @@
|
||||
{
|
||||
"name": "wechatexplorer",
|
||||
"version": "2.0.1",
|
||||
"description": "mac 版本获取微信聊天记录, AI群聊总结助手",
|
||||
"version": "2.1.1",
|
||||
"description": "macOS / Windows 微信聊天记录查看与 AI 群聊总结助手",
|
||||
"keywords": [
|
||||
"wechat",
|
||||
"chat",
|
||||
"mac微信",
|
||||
"windows微信",
|
||||
"微信聊天记录",
|
||||
"AI群聊总结助手"
|
||||
],
|
||||
"author": "Qingmao",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/Wxw-Gu/WechatExplorer.git"
|
||||
},
|
||||
"main": "./out/main/index.js",
|
||||
"scripts": {
|
||||
"format": "prettier --write .",
|
||||
@@ -17,10 +22,14 @@
|
||||
"typecheck:node": "tsc --noEmit -p tsconfig.node.json --composite false",
|
||||
"typecheck:web": "tsc --noEmit -p tsconfig.web.json --composite false",
|
||||
"typecheck": "npm run typecheck:node && npm run typecheck:web",
|
||||
"test:skill-install": "node scripts/test-skill-install-instruction.cjs",
|
||||
"cp:env": "node scripts/ensure-env.cjs",
|
||||
"prepare:env": "node scripts/ensure-env.cjs",
|
||||
"predev": "node scripts/ensure-env.cjs",
|
||||
"start": "electron-vite preview",
|
||||
"dev": "electron-vite dev",
|
||||
"build": "npm run typecheck && electron-vite build",
|
||||
"postinstall": "electron-builder install-app-deps",
|
||||
"postinstall": "electron-builder install-app-deps && node scripts/prepare-electron-runtime.cjs",
|
||||
"build:unpack": "npm run build && electron-builder --config electron-builder.yml --dir",
|
||||
"build:win": "npm run build && electron-builder --config electron-builder.yml --win",
|
||||
"build:mac:x64": "electron-vite build && electron-builder --config electron-builder.yml --mac --x64",
|
||||
@@ -33,9 +42,10 @@
|
||||
"@electron-toolkit/utils": "^4.0.0",
|
||||
"fs-extra": "^11.3.2",
|
||||
"fzstd": "^0.1.1",
|
||||
"koffi": "^2.9.0",
|
||||
"koffi": "^3.1.0",
|
||||
"openai": "^6.10.0",
|
||||
"silk-wasm": "^3.7.1"
|
||||
"silk-wasm": "^3.7.1",
|
||||
"wechat-emojis": "^1.0.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@electron-toolkit/eslint-config-prettier": "^3.0.0",
|
||||
@@ -47,7 +57,7 @@
|
||||
"@types/react": "^19.2.7",
|
||||
"@types/react-dom": "^19.2.3",
|
||||
"@vitejs/plugin-react": "^5.1.1",
|
||||
"electron": "^39.2.6",
|
||||
"electron": "^43.0.0",
|
||||
"electron-builder": "^26.0.12",
|
||||
"electron-vite": "^5.0.0",
|
||||
"eslint": "^9.39.1",
|
||||
|
||||
@@ -16,7 +16,7 @@ specifiers:
|
||||
'@types/react': ^19.2.7
|
||||
'@types/react-dom': ^19.2.3
|
||||
'@vitejs/plugin-react': ^5.1.1
|
||||
electron: ^39.2.6
|
||||
electron: ^43.0.0
|
||||
electron-builder: ^26.0.12
|
||||
electron-vite: ^5.0.0
|
||||
eslint: ^9.39.1
|
||||
@@ -25,7 +25,7 @@ specifiers:
|
||||
eslint-plugin-react-refresh: ^0.4.24
|
||||
fs-extra: ^11.3.2
|
||||
fzstd: ^0.1.1
|
||||
koffi: ^2.9.0
|
||||
koffi: ^3.1.0
|
||||
openai: ^6.10.0
|
||||
prettier: ^3.7.4
|
||||
react: ^19.2.1
|
||||
@@ -33,15 +33,17 @@ specifiers:
|
||||
silk-wasm: ^3.7.1
|
||||
typescript: ^5.9.3
|
||||
vite: ^7.2.6
|
||||
wechat-emojis: ^1.0.2
|
||||
|
||||
dependencies:
|
||||
'@electron-toolkit/preload': 3.0.2_electron@39.2.6
|
||||
'@electron-toolkit/utils': 4.0.0_electron@39.2.6
|
||||
'@electron-toolkit/preload': 3.0.2_electron@43.1.0
|
||||
'@electron-toolkit/utils': 4.0.0_electron@43.1.0
|
||||
fs-extra: 11.3.2
|
||||
fzstd: 0.1.1
|
||||
koffi: 2.16.2
|
||||
koffi: 3.1.0
|
||||
openai: 6.10.0
|
||||
silk-wasm: 3.7.1
|
||||
wechat-emojis: 1.0.2
|
||||
|
||||
devDependencies:
|
||||
'@electron-toolkit/eslint-config-prettier': 3.0.0_fiitszekoa4sqtbwyewxi6kyy4
|
||||
@@ -53,7 +55,7 @@ devDependencies:
|
||||
'@types/react': 19.2.7
|
||||
'@types/react-dom': 19.2.3_@types+react@19.2.7
|
||||
'@vitejs/plugin-react': 5.1.2_vite@7.2.7
|
||||
electron: 39.2.6
|
||||
electron: 43.1.0
|
||||
electron-builder: 26.0.12
|
||||
electron-vite: 5.0.0_vite@7.2.7
|
||||
eslint: 9.39.1
|
||||
@@ -266,6 +268,10 @@ packages:
|
||||
ajv-keywords: 3.5.2_ajv@6.12.6
|
||||
dev: true
|
||||
|
||||
/@electron-internal/extract-zip/1.0.4:
|
||||
resolution: {integrity: sha512-Zr1Vs7E9tpCNhZHDAbFVXc2gEVCG9RqPDjrno5+bdgB6LRAuvgyMHJut4NCVyYwtAieapMzc3fiQ3CSTi75ARg==}
|
||||
engines: {node: '>=22.12.0'}
|
||||
|
||||
/@electron-toolkit/eslint-config-prettier/3.0.0_fiitszekoa4sqtbwyewxi6kyy4:
|
||||
resolution: {integrity: sha512-YapmIOVkbYdHLuTa+ad1SAVtcqYL9A/SJsc7cxQokmhcwAwonGevNom37jBf9slXegcZ/Slh01I/JARG1yhNFw==}
|
||||
peerDependencies:
|
||||
@@ -298,12 +304,12 @@ packages:
|
||||
- supports-color
|
||||
dev: true
|
||||
|
||||
/@electron-toolkit/preload/3.0.2_electron@39.2.6:
|
||||
/@electron-toolkit/preload/3.0.2_electron@43.1.0:
|
||||
resolution: {integrity: sha512-TWWPToXd8qPRfSXwzf5KVhpXMfONaUuRAZJHsKthKgZR/+LqX1dZVSSClQ8OTAEduvLGdecljCsoT2jSshfoUg==}
|
||||
peerDependencies:
|
||||
electron: '>=13.0.0'
|
||||
dependencies:
|
||||
electron: 39.2.6
|
||||
electron: 43.1.0
|
||||
dev: false
|
||||
|
||||
/@electron-toolkit/tsconfig/2.0.0_@types+node@22.19.2:
|
||||
@@ -314,12 +320,12 @@ packages:
|
||||
'@types/node': 22.19.2
|
||||
dev: true
|
||||
|
||||
/@electron-toolkit/utils/4.0.0_electron@39.2.6:
|
||||
/@electron-toolkit/utils/4.0.0_electron@43.1.0:
|
||||
resolution: {integrity: sha512-qXSntwEzluSzKl4z5yFNBknmPGjPa3zFhE4mp9+h0cgokY5ornAeP+CJQDBhKsL1S58aOQfcwkD3NwLZCl+64g==}
|
||||
peerDependencies:
|
||||
electron: '>=13.0.0'
|
||||
dependencies:
|
||||
electron: 39.2.6
|
||||
electron: 43.1.0
|
||||
dev: false
|
||||
|
||||
/@electron/asar/3.2.18:
|
||||
@@ -341,19 +347,18 @@ packages:
|
||||
minimist: 1.2.8
|
||||
dev: true
|
||||
|
||||
/@electron/get/2.0.3:
|
||||
resolution: {integrity: sha512-Qkzpg2s9GnVV2I2BjRksUi43U5e6+zaQMcjoJy0C+C5oxaKl+fmckGDQFtRpZpZV0NQekuZZ+tGz7EA9TVnQtQ==}
|
||||
engines: {node: '>=12'}
|
||||
/@electron/get/5.0.0:
|
||||
resolution: {integrity: sha512-pjoBpru1KdEtcExBnuHAP1cAc/5faoedw0hzJkL3o4/IJp7HNF1+fbrdxT3gMYRX2oJfvnA/WXeCTVQpYYxyJA==}
|
||||
engines: {node: '>=22.12.0'}
|
||||
dependencies:
|
||||
debug: 4.4.3
|
||||
env-paths: 2.2.1
|
||||
fs-extra: 8.1.0
|
||||
got: 11.8.6
|
||||
env-paths: 3.0.0
|
||||
graceful-fs: 4.2.11
|
||||
progress: 2.0.3
|
||||
semver: 6.3.1
|
||||
semver: 7.7.3
|
||||
sumchecker: 3.0.1
|
||||
optionalDependencies:
|
||||
global-agent: 3.0.0
|
||||
undici: 7.28.0
|
||||
transitivePeerDependencies:
|
||||
- supports-color
|
||||
|
||||
@@ -786,6 +791,104 @@ packages:
|
||||
'@jridgewell/sourcemap-codec': 1.5.5
|
||||
dev: true
|
||||
|
||||
/@koromix/koffi-darwin-arm64/3.1.0:
|
||||
resolution: {integrity: sha512-VEt5r3fXTfbejr83PnuOP0H7s9Zmazcs+lofu96DOcRkistlMsn59wYyWiKpyAjs9PCgm0Ykh62ChZ3CGMmIOg==}
|
||||
cpu: [arm64]
|
||||
os: [darwin]
|
||||
dev: false
|
||||
optional: true
|
||||
|
||||
/@koromix/koffi-darwin-x64/3.1.0:
|
||||
resolution: {integrity: sha512-n/tVRB9xIzdXT5H3zZt8ueThgWTSDL+yU7PWnU8wbZPBSawP/otx3swQyd6nMOqj1bmHgSHopiKSBXRS9pllmg==}
|
||||
cpu: [x64]
|
||||
os: [darwin]
|
||||
dev: false
|
||||
optional: true
|
||||
|
||||
/@koromix/koffi-freebsd-arm64/3.1.0:
|
||||
resolution: {integrity: sha512-vazoPYIhOAlXZksVIqDRMIID4VeUZKx8F3dR90hOobT2ATyOkqNS5dv5UCV7Q7DSq22lQTrdbvENBAhROzCp0w==}
|
||||
cpu: [arm64]
|
||||
os: [freebsd]
|
||||
dev: false
|
||||
optional: true
|
||||
|
||||
/@koromix/koffi-freebsd-ia32/3.1.0:
|
||||
resolution: {integrity: sha512-Vm7Uc97ru6RTSVmae2zCZZQeaizqVZ8WoU4+gG4H03Qe+WOj7kbKt/MxT7VBzdbPYIU5ZJeG/ZED1YlZyab6eQ==}
|
||||
cpu: [ia32]
|
||||
os: [freebsd]
|
||||
dev: false
|
||||
optional: true
|
||||
|
||||
/@koromix/koffi-freebsd-x64/3.1.0:
|
||||
resolution: {integrity: sha512-N+VuVWjoiYPy1Go5mRadZ3B6RM5Qz+eCLhj2LXrMlefbUJ+O4gg7teCUGvPGfBEHDgmSN4yYUrfQmdJC10vOYw==}
|
||||
cpu: [x64]
|
||||
os: [freebsd]
|
||||
dev: false
|
||||
optional: true
|
||||
|
||||
/@koromix/koffi-linux-arm64/3.1.0:
|
||||
resolution: {integrity: sha512-Wx5iOkeALe2ympLdiYwRpIg5qUkyQIv8N2foZ9rRker0uE7ZtXew2RRkbEgMir4b0yDYR1zyXd6B62GUzLtZ/g==}
|
||||
cpu: [arm64]
|
||||
os: [linux]
|
||||
dev: false
|
||||
optional: true
|
||||
|
||||
/@koromix/koffi-linux-ia32/3.1.0:
|
||||
resolution: {integrity: sha512-1DjYm1QehXU0dgn0uE+FGYOb3Of7GiTMqLS+ZI2gbl1b+h76sz4LRBvDVrQyAmSMVVU8/7696S21YgE/iBhBVg==}
|
||||
cpu: [ia32]
|
||||
os: [linux]
|
||||
dev: false
|
||||
optional: true
|
||||
|
||||
/@koromix/koffi-linux-loong64/3.1.0:
|
||||
resolution: {integrity: sha512-NOa0LdyltdESz3oeTqUH6MErHVoJOHoeXIsEp6xIMTUh4eKXEtlDQeoK6EYqo0DnBt83Xud95qLvi4Aw12pG4Q==}
|
||||
cpu: [loong64]
|
||||
os: [linux]
|
||||
dev: false
|
||||
optional: true
|
||||
|
||||
/@koromix/koffi-linux-riscv64/3.1.0:
|
||||
resolution: {integrity: sha512-Ye6kiXZCGxGtAIXSly6XuOP5tJZNYOZ2eVg33k1MilKrzimAy9Mpw4d6e9+Sfsc1jesgeNYs1sb5iaI8HS3ncA==}
|
||||
cpu: [riscv64]
|
||||
os: [linux]
|
||||
dev: false
|
||||
optional: true
|
||||
|
||||
/@koromix/koffi-linux-x64/3.1.0:
|
||||
resolution: {integrity: sha512-3yQTOkQrMna4VX+yeyfYImBjLlGrItMpsWyfaW1uSiz/A6GRydqdwYH7DWnp4Z+RSGYZpsewkf7byMc8pOOQKA==}
|
||||
cpu: [x64]
|
||||
os: [linux]
|
||||
dev: false
|
||||
optional: true
|
||||
|
||||
/@koromix/koffi-openbsd-ia32/3.1.0:
|
||||
resolution: {integrity: sha512-/cDoFHb9yx4+yoT3GUpnKnfi3W2drG+/Ewo0TTZaQHb4PsxnYYyT6V8+t4cL5XXbQcTTcOsZxpmBRrn0NBa3dA==}
|
||||
cpu: [ia32]
|
||||
os: [openbsd]
|
||||
dev: false
|
||||
optional: true
|
||||
|
||||
/@koromix/koffi-openbsd-x64/3.1.0:
|
||||
resolution: {integrity: sha512-CoQdqgnKvWgTXXZlUst8cBRQEov7QsxlTN2WAsu9wez01Xe6gEcH/zYePANualzzCbnaELfe5P0rA80QkoDuPA==}
|
||||
cpu: [x64]
|
||||
os: [openbsd]
|
||||
dev: false
|
||||
optional: true
|
||||
|
||||
/@koromix/koffi-win32-ia32/3.1.0:
|
||||
resolution: {integrity: sha512-WjrA+DEkpy0xEHu48+NSOboHhTnzkIfsFuq3d/WrSs+T9WflWRng3jC7mdJxmR4eHb6i6BqjW3k/U0mNUTjFPA==}
|
||||
cpu: [ia32]
|
||||
os: [win32]
|
||||
dev: false
|
||||
optional: true
|
||||
|
||||
/@koromix/koffi-win32-x64/3.1.0:
|
||||
resolution: {integrity: sha512-tnK5+IkzQBauQAQSzuyjso8OOIQRlaTZS39xIWpfqVYDLVDIuLDQk/WwHcOrR5yxlDrZq9ygiebBTOfcJFia7w==}
|
||||
cpu: [x64]
|
||||
os: [win32]
|
||||
dev: false
|
||||
optional: true
|
||||
|
||||
/@malept/cross-spawn-promise/2.0.0:
|
||||
resolution: {integrity: sha512-1DpKU0Z5ThltBwjNySMC14g0CkbyhCaz9FkhxqNsZI6uAPJXFS8cMXlBKo26FJ8ZuW6S9GCMcR9IO5k2X5/9Fg==}
|
||||
engines: {node: '>= 12.13.0'}
|
||||
@@ -1011,12 +1114,14 @@ packages:
|
||||
/@sindresorhus/is/4.6.0:
|
||||
resolution: {integrity: sha512-t09vSN3MdfsyCHoFcTRCH/iUtG7OJ0CsjzB8cjAmKc/va/kIgeDI/TxsigdncE/4be734m0cvIYwNaV4i2XqAw==}
|
||||
engines: {node: '>=10'}
|
||||
dev: true
|
||||
|
||||
/@szmarczak/http-timer/4.0.6:
|
||||
resolution: {integrity: sha512-4BAffykYOgO+5nzBWYwE3W90sBgLJoUPRWWcL8wlyiM8IB8ipJz3UMJ9KXQd1RKQXpKp8Tutn80HZtWsu2u76w==}
|
||||
engines: {node: '>=10'}
|
||||
dependencies:
|
||||
defer-to-connect: 2.0.1
|
||||
dev: true
|
||||
|
||||
/@tootallnate/once/2.0.0:
|
||||
resolution: {integrity: sha512-XCuKFP5PS55gnMVu3dty8KPatLqUoy/ZYzDzAGCQ8JNFCkLXzmI7vNHCR+XpbZaMWQK/vQubr7PkYq8g470J/A==}
|
||||
@@ -1059,6 +1164,7 @@ packages:
|
||||
'@types/keyv': 3.1.4
|
||||
'@types/node': 22.19.2
|
||||
'@types/responselike': 1.0.3
|
||||
dev: true
|
||||
|
||||
/@types/debug/4.1.12:
|
||||
resolution: {integrity: sha512-vIChWdVG3LG1SMxEvI/AK+FWJthlrqlTu7fbrlywTkkaONwk/UAGaULXRlf8vkzFBLVm0zkMdCquhL5aOjhXPQ==}
|
||||
@@ -1085,6 +1191,7 @@ packages:
|
||||
|
||||
/@types/http-cache-semantics/4.0.4:
|
||||
resolution: {integrity: sha512-1m0bIFVc7eJWyve9S0RnuRgcQqF/Xd5QsUZAZeQFr1Q3/p9JWoQQEqmVy+DPTNpGXwhgIetAoYF8JSc33q29QA==}
|
||||
dev: true
|
||||
|
||||
/@types/json-schema/7.0.15:
|
||||
resolution: {integrity: sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA==}
|
||||
@@ -1100,6 +1207,7 @@ packages:
|
||||
resolution: {integrity: sha512-BQ5aZNSCpj7D6K2ksrRCTmKRLEpnPvWDiLPfoGyhZ++8YtiK9d/3DBKPJgry359X/P1PfruyYwvnvwFjuEiEIg==}
|
||||
dependencies:
|
||||
'@types/node': 22.19.2
|
||||
dev: true
|
||||
|
||||
/@types/ms/2.1.0:
|
||||
resolution: {integrity: sha512-GsCCIZDE/p3i96vtEqx+7dBUGXrc7zeSK3wwPHIaRThS+9OhWIXRqzs4d6k1SVU8g91DrNRWxWUGhp5KXQb2VA==}
|
||||
@@ -1109,6 +1217,12 @@ packages:
|
||||
resolution: {integrity: sha512-LPM2G3Syo1GLzXLGJAKdqoU35XvrWzGJ21/7sgZTUpbkBaOasTj8tjwn6w+hCkqaa1TfJ/w67rJSwYItlJ2mYw==}
|
||||
dependencies:
|
||||
undici-types: 6.21.0
|
||||
dev: true
|
||||
|
||||
/@types/node/24.13.3:
|
||||
resolution: {integrity: sha512-Dh8vAsV36ig5wa9OX4pXvMc9D3Veibfw2wix0CUwYODLD8nkj9UsLjASr49nPg+2eKzxhBV+v7L8pXvT4e639Q==}
|
||||
dependencies:
|
||||
undici-types: 7.18.2
|
||||
|
||||
/@types/plist/3.0.5:
|
||||
resolution: {integrity: sha512-E6OCaRmAe4WDmWNsL/9RMqdkkzDCY1etutkflWk4c+AcjDU07Pcz1fQwTX0TQz+Pxqn9i4L1TU3UFpjnrcDgxA==}
|
||||
@@ -1136,18 +1250,13 @@ packages:
|
||||
resolution: {integrity: sha512-H/+L+UkTV33uf49PH5pCAUBVPNj2nDBXTN+qS1dOwyyg24l3CcicicCA7ca+HMvJBZcFgl5r8e+RR6elsb4Lyw==}
|
||||
dependencies:
|
||||
'@types/node': 22.19.2
|
||||
dev: true
|
||||
|
||||
/@types/verror/1.10.11:
|
||||
resolution: {integrity: sha512-RlDm9K7+o5stv0Co8i8ZRGxDbrTxhJtgjqjFyVh/tXQyl/rYtTKlnTvZ88oSTeYREWurwx20Js4kTuKCsFkUtg==}
|
||||
dev: true
|
||||
optional: true
|
||||
|
||||
/@types/yauzl/2.10.3:
|
||||
resolution: {integrity: sha512-oJoftv0LSuaDZE3Le4DbKX+KS9G36NzOeSap90UIK0yMA/NhKJhqlSGtNDORNRaIbQfzjXDrQa0ytJ6mNRGz/Q==}
|
||||
dependencies:
|
||||
'@types/node': 22.19.2
|
||||
optional: true
|
||||
|
||||
/@typescript-eslint/eslint-plugin/8.49.0_nj5tjtfh637kziiwuhl3v5a4iq:
|
||||
resolution: {integrity: sha512-JXij0vzIaTtCwu6SxTh8qBc66kmf1xs7pI4UOiMDFVct6q86G0Zs7KRcEoJgY3Cav3x5Tq0MF5jwgpgLqgKG3A==}
|
||||
engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}
|
||||
@@ -1591,11 +1700,6 @@ packages:
|
||||
readable-stream: 3.6.2
|
||||
dev: true
|
||||
|
||||
/boolean/3.2.0:
|
||||
resolution: {integrity: sha512-d0II/GO9uf9lfUHH2BQsjxzRJZBdsjgsBiW4BvhWk/3qoKwQFjIDVN19PfX8F2D/r9PCMTtLWjYVCFrpeYUzsw==}
|
||||
deprecated: Package no longer supported. Contact Support at https://www.npmjs.com/support for more info.
|
||||
optional: true
|
||||
|
||||
/brace-expansion/1.1.12:
|
||||
resolution: {integrity: sha512-9T9UjW3r0UW5c1Q7GTwllptXwhvYmEzFhzMfZ9H7FQWt+uZePjZPjBP/W1ZEyZ1twGWom5/56TF4lPcqjnDHcg==}
|
||||
dependencies:
|
||||
@@ -1621,9 +1725,6 @@ packages:
|
||||
update-browserslist-db: 1.2.2_browserslist@4.28.1
|
||||
dev: true
|
||||
|
||||
/buffer-crc32/0.2.13:
|
||||
resolution: {integrity: sha512-VO9Ht/+p3SN7SKWqcrgEzjGbRSJYTx+Q1pTQC0wrWqHx0vpJraQ6GtHx8tvcg1rlK1byhU5gccxgOgj7B0TDkQ==}
|
||||
|
||||
/buffer-from/1.1.2:
|
||||
resolution: {integrity: sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==}
|
||||
dev: true
|
||||
@@ -1703,6 +1804,7 @@ packages:
|
||||
/cacheable-lookup/5.0.4:
|
||||
resolution: {integrity: sha512-2/kNscPhpcxrOigMZzbiWF7dz8ilhb/nIHU3EyZiXWXpeq/au8qJ8VhdftMkty3n7Gj6HIGalQG8oiBNB3AJgA==}
|
||||
engines: {node: '>=10.6.0'}
|
||||
dev: true
|
||||
|
||||
/cacheable-request/7.0.4:
|
||||
resolution: {integrity: sha512-v+p6ongsrp0yTGbJXjgxPow2+DL93DASP4kXCDKb8/bwRtt9OEF3whggkkDkGNzgcWy2XaF4a8nZglC7uElscg==}
|
||||
@@ -1715,6 +1817,7 @@ packages:
|
||||
lowercase-keys: 2.0.0
|
||||
normalize-url: 6.1.0
|
||||
responselike: 2.0.1
|
||||
dev: true
|
||||
|
||||
/call-bind-apply-helpers/1.0.2:
|
||||
resolution: {integrity: sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==}
|
||||
@@ -1812,6 +1915,7 @@ packages:
|
||||
resolution: {integrity: sha512-ROoL94jJH2dUVML2Y/5PEDNaSHgeOdSDicUyS7izcF63G6sTc/FTjLub4b8Il9S8S0beOfYt0TaA5qvFK+w0wA==}
|
||||
dependencies:
|
||||
mimic-response: 1.0.1
|
||||
dev: true
|
||||
|
||||
/clone/1.0.4:
|
||||
resolution: {integrity: sha512-JQHZ2QMW6l3aH/j6xCqQThY/9OH4D/9ls34cgkUBiEeocRTU04tHfKPBsUK1PqZCUQM7GiA0IIXJSuXHI64Kbg==}
|
||||
@@ -1929,6 +2033,7 @@ packages:
|
||||
engines: {node: '>=10'}
|
||||
dependencies:
|
||||
mimic-response: 3.1.0
|
||||
dev: true
|
||||
|
||||
/deep-is/0.1.4:
|
||||
resolution: {integrity: sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ==}
|
||||
@@ -1943,6 +2048,7 @@ packages:
|
||||
/defer-to-connect/2.0.1:
|
||||
resolution: {integrity: sha512-4tvttepXG1VaYGrRibk5EwJd1t4udunSOVMdLSAL6mId1ix438oPwPZMALY41FCijukO1L0twNcGsdzS7dHgDg==}
|
||||
engines: {node: '>=10'}
|
||||
dev: true
|
||||
|
||||
/define-data-property/1.1.4:
|
||||
resolution: {integrity: sha512-rBMvIzlpA8v6E+SJZoo++HAYqsLrkg7MSfIinMPFhmkorw7X+dOXVJQs+QT69zGkzMyfDnIMN2Wid1+NbL3T+A==}
|
||||
@@ -1951,6 +2057,7 @@ packages:
|
||||
es-define-property: 1.0.1
|
||||
es-errors: 1.3.0
|
||||
gopd: 1.2.0
|
||||
dev: true
|
||||
|
||||
/define-properties/1.2.1:
|
||||
resolution: {integrity: sha512-8QmQKqEASLd5nx0U1B1okLElbUuuttJ/AnYmRXbbbGDWh6uS208EjD4Xqq/I9wK7u0v6O08XhTWnt5XtEbR6Dg==}
|
||||
@@ -1959,6 +2066,7 @@ packages:
|
||||
define-data-property: 1.1.4
|
||||
has-property-descriptors: 1.0.2
|
||||
object-keys: 1.1.1
|
||||
dev: true
|
||||
|
||||
/delayed-stream/1.0.0:
|
||||
resolution: {integrity: sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==}
|
||||
@@ -1970,10 +2078,6 @@ packages:
|
||||
engines: {node: '>=8'}
|
||||
dev: true
|
||||
|
||||
/detect-node/2.1.0:
|
||||
resolution: {integrity: sha512-T0NIuQpnTvFDATNuHN5roPwSBG83rFsuO+MXXH9/3N1eFbn4wcPjttvjMLEPWJ0RGUYgQE7cGgS3tNxbqCGM7g==}
|
||||
optional: true
|
||||
|
||||
/dir-compare/4.2.0:
|
||||
resolution: {integrity: sha512-2xMCmOoMrdQIPHdsTawECdNPwlVFB9zGcz3kuhmBO6U3oU+UQjsue0i8ayLKpgBcm+hcXPMVSGUN9d+pvJ6+VQ==}
|
||||
dependencies:
|
||||
@@ -2117,15 +2221,14 @@ packages:
|
||||
- supports-color
|
||||
dev: true
|
||||
|
||||
/electron/39.2.6:
|
||||
resolution: {integrity: sha512-dHBgTodWBZd+tL1Dt0PSh/CFLHeDkFCTKCTXu1dgPhlE9Z3k2zzlBQ9B2oW55CFsKanBDHiUomHJNw0XaSdQpA==}
|
||||
engines: {node: '>= 12.20.55'}
|
||||
/electron/43.1.0:
|
||||
resolution: {integrity: sha512-DPfxpQLd4NL3BJ8DBxYAfmLUKKesF5Rx9dQx5FyczAP8bhOPScjHE48GArVeXu68LlAainuwkmQTQvdZwpIIAQ==}
|
||||
engines: {node: '>= 22.12.0'}
|
||||
hasBin: true
|
||||
requiresBuild: true
|
||||
dependencies:
|
||||
'@electron/get': 2.0.3
|
||||
'@types/node': 22.19.2
|
||||
extract-zip: 2.0.1
|
||||
'@electron-internal/extract-zip': 1.0.4
|
||||
'@electron/get': 5.0.0
|
||||
'@types/node': 24.13.3
|
||||
transitivePeerDependencies:
|
||||
- supports-color
|
||||
|
||||
@@ -2148,10 +2251,16 @@ packages:
|
||||
resolution: {integrity: sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg==}
|
||||
dependencies:
|
||||
once: 1.4.0
|
||||
dev: true
|
||||
|
||||
/env-paths/2.2.1:
|
||||
resolution: {integrity: sha512-+h1lkLKhZMTYjog1VEpJNG7NZJWcuc2DDk/qsqSTRRCOXiLjeQ1d1/udrUGhqMxUgAlwKNZ0cf2uqan5GLuS2A==}
|
||||
engines: {node: '>=6'}
|
||||
dev: true
|
||||
|
||||
/env-paths/3.0.0:
|
||||
resolution: {integrity: sha512-dtJUTepzMW3Lm/NPxRf3wP4642UWhjL2sQxc+ym2YMj1m/H2zDNQOlezafzkHwn6sMstjHTwG6iQQsctDW/b1A==}
|
||||
engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0}
|
||||
|
||||
/err-code/2.0.3:
|
||||
resolution: {integrity: sha512-2bmlRpNKBxT/CRmPOlyISQpNj+qSeYvcym/uT0Jx2bMOlKLtSy1ZmLuVxSEKKyor/N5yhvp/ZiG1oE3DEYMSFA==}
|
||||
@@ -2220,10 +2329,12 @@ packages:
|
||||
/es-define-property/1.0.1:
|
||||
resolution: {integrity: sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==}
|
||||
engines: {node: '>= 0.4'}
|
||||
dev: true
|
||||
|
||||
/es-errors/1.3.0:
|
||||
resolution: {integrity: sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==}
|
||||
engines: {node: '>= 0.4'}
|
||||
dev: true
|
||||
|
||||
/es-iterator-helpers/1.2.1:
|
||||
resolution: {integrity: sha512-uDn+FE1yrDzyC0pCo961B2IHbdM8y/ACZsKD4dG6WqrjV53BADjwa7D+1aom2rsNVfLyDgU/eigvlJGJ08OQ4w==}
|
||||
@@ -2280,10 +2391,6 @@ packages:
|
||||
is-symbol: 1.1.1
|
||||
dev: true
|
||||
|
||||
/es6-error/4.1.1:
|
||||
resolution: {integrity: sha512-Um/+FxMr9CISWh0bi5Zv0iOD+4cFh5qLeks1qhAopKVAJw3drgKbKySikp7wGhDL0HPeaja0P5ULZrxLkniUVg==}
|
||||
optional: true
|
||||
|
||||
/esbuild/0.25.12:
|
||||
resolution: {integrity: sha512-bbPBYYrtZbkt6Os6FiTLCTFxvq4tt3JKall1vRwshA3fdVztsLAatFaZobhkBC8/BrPetoa0oksYoKXoG4ryJg==}
|
||||
engines: {node: '>=18'}
|
||||
@@ -2326,6 +2433,7 @@ packages:
|
||||
/escape-string-regexp/4.0.0:
|
||||
resolution: {integrity: sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==}
|
||||
engines: {node: '>=10'}
|
||||
dev: true
|
||||
|
||||
/eslint-config-prettier/10.1.8_eslint@9.39.1:
|
||||
resolution: {integrity: sha512-82GZUjRS0p/jganf6q1rEO25VSoHH0hKPCTrgillPjdI/3bgBhAE1QzHrHTizjpRvy6pGAvKjDJtk2pF9NDq8w==}
|
||||
@@ -2511,19 +2619,6 @@ packages:
|
||||
resolution: {integrity: sha512-ZgEeZXj30q+I0EN+CbSSpIyPaJ5HVQD18Z1m+u1FXbAeT94mr1zw50q4q6jiiC447Nl/YTcIYSAftiGqetwXCA==}
|
||||
dev: true
|
||||
|
||||
/extract-zip/2.0.1:
|
||||
resolution: {integrity: sha512-GDhU9ntwuKyGXdZBUgTIe+vXnWj0fppUEtMDL0+idd5Sta8TGpHssn/eusA9mrPr9qNDym6SxAYZjNvCn/9RBg==}
|
||||
engines: {node: '>= 10.17.0'}
|
||||
hasBin: true
|
||||
dependencies:
|
||||
debug: 4.4.3
|
||||
get-stream: 5.2.0
|
||||
yauzl: 2.10.0
|
||||
optionalDependencies:
|
||||
'@types/yauzl': 2.10.3
|
||||
transitivePeerDependencies:
|
||||
- supports-color
|
||||
|
||||
/extsprintf/1.4.1:
|
||||
resolution: {integrity: sha512-Wrk35e8ydCKDj/ArClo1VrPVmN8zph5V4AtHwIuHhvMXsKf73UT3BOD+azBIW+3wOJ4FhEH7zyaJCFvChjYvMA==}
|
||||
engines: {'0': node >=0.6.0}
|
||||
@@ -2546,11 +2641,6 @@ packages:
|
||||
resolution: {integrity: sha512-DCXu6Ifhqcks7TZKY3Hxp3y6qphY5SJZmrWMDrKcERSOXWQdMhU9Ig/PYrzyw/ul9jOIyh0N4M0tbC5hodg8dw==}
|
||||
dev: true
|
||||
|
||||
/fd-slicer/1.1.0:
|
||||
resolution: {integrity: sha512-cE1qsB/VwyQozZ+q1dGxR8LBYNZeofhEdUNGSMbQD3Gw2lAzX9Zb3uIU6Ebc/Fmyjo9AWWfnn0AUCHqtevs/8g==}
|
||||
dependencies:
|
||||
pend: 1.2.0
|
||||
|
||||
/fdir/6.5.0_picomatch@4.0.3:
|
||||
resolution: {integrity: sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==}
|
||||
engines: {node: '>=12.0.0'}
|
||||
@@ -2639,14 +2729,6 @@ packages:
|
||||
jsonfile: 6.2.0
|
||||
universalify: 2.0.1
|
||||
|
||||
/fs-extra/8.1.0:
|
||||
resolution: {integrity: sha512-yhlQgA6mnOJUKOsRUFsgJdQCvkKhcz8tlZG5HBQfReYZy46OwLcY+Zia0mtdHsOo9y/hP+CxMN0TU9QxoOtG4g==}
|
||||
engines: {node: '>=6 <7 || >=8'}
|
||||
dependencies:
|
||||
graceful-fs: 4.2.11
|
||||
jsonfile: 4.0.0
|
||||
universalify: 0.1.2
|
||||
|
||||
/fs-extra/9.1.0:
|
||||
resolution: {integrity: sha512-hcg3ZmepS30/7BSFqRvoo3DOMQu7IjqxO5nCDt+zM9XWjb33Wg7ziNT+Qvqbuc3+gWpzO02JubVyk2G4Zvo1OQ==}
|
||||
engines: {node: '>=10'}
|
||||
@@ -2743,6 +2825,7 @@ packages:
|
||||
engines: {node: '>=8'}
|
||||
dependencies:
|
||||
pump: 3.0.3
|
||||
dev: true
|
||||
|
||||
/get-symbol-description/1.1.0:
|
||||
resolution: {integrity: sha512-w9UMqWwJxHNOvoNzSJ2oPF5wvYcvP7jUvYzhp67yEhTi17ZDBBC1z9pTdGuzjD+EFIqLSYRweZjqfiPzQ06Ebg==}
|
||||
@@ -2796,18 +2879,6 @@ packages:
|
||||
once: 1.4.0
|
||||
dev: true
|
||||
|
||||
/global-agent/3.0.0:
|
||||
resolution: {integrity: sha512-PT6XReJ+D07JvGoxQMkT6qji/jVNfX/h364XHZOWeRzy64sSFr+xJ5OX7LI3b4MPQzdL4H8Y8M0xzPpsVMwA8Q==}
|
||||
engines: {node: '>=10.0'}
|
||||
dependencies:
|
||||
boolean: 3.2.0
|
||||
es6-error: 4.1.1
|
||||
matcher: 3.0.0
|
||||
roarr: 2.15.4
|
||||
semver: 7.7.3
|
||||
serialize-error: 7.0.1
|
||||
optional: true
|
||||
|
||||
/globals/14.0.0:
|
||||
resolution: {integrity: sha512-oahGvuMGQlPw/ivIYBjVSrWAfWLBeku5tpPE2fOPLi+WHffIWbuh2tCjhyQhTBPMf5E9jDEH4FOmTYgYwbKwtQ==}
|
||||
engines: {node: '>=18'}
|
||||
@@ -2824,10 +2895,12 @@ packages:
|
||||
dependencies:
|
||||
define-properties: 1.2.1
|
||||
gopd: 1.2.0
|
||||
dev: true
|
||||
|
||||
/gopd/1.2.0:
|
||||
resolution: {integrity: sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==}
|
||||
engines: {node: '>= 0.4'}
|
||||
dev: true
|
||||
|
||||
/got/11.8.6:
|
||||
resolution: {integrity: sha512-6tfZ91bOr7bOXnK7PRDCGBLa1H4U080YHNaAQ2KsMGlLEzRbk44nsZF2E1IeRc3vtJHPVbKCYgdFbaGO2ljd8g==}
|
||||
@@ -2844,6 +2917,7 @@ packages:
|
||||
lowercase-keys: 2.0.0
|
||||
p-cancelable: 2.1.1
|
||||
responselike: 2.0.1
|
||||
dev: true
|
||||
|
||||
/graceful-fs/4.2.11:
|
||||
resolution: {integrity: sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==}
|
||||
@@ -2862,6 +2936,7 @@ packages:
|
||||
resolution: {integrity: sha512-55JNKuIW+vq4Ke1BjOTjM2YctQIvCT7GFzHwmfZPGo5wnrgkid0YQtnAleFSqumZm4az3n2BS+erby5ipJdgrg==}
|
||||
dependencies:
|
||||
es-define-property: 1.0.1
|
||||
dev: true
|
||||
|
||||
/has-proto/1.2.0:
|
||||
resolution: {integrity: sha512-KIL7eQPfHQRC8+XluaIw7BHUwwqL19bQn4hzNgdr+1wXoU0KKj6rufu47lhY7KbJR2C6T6+PfyN0Ea7wkSS+qQ==}
|
||||
@@ -2908,6 +2983,7 @@ packages:
|
||||
|
||||
/http-cache-semantics/4.2.0:
|
||||
resolution: {integrity: sha512-dTxcvPXqPvXBQpq5dUr6mEMJX4oIEFv6bwom3FDwKRDsuIjjJGANqhBuoAn9c1RQJIdAKav33ED65E2ys+87QQ==}
|
||||
dev: true
|
||||
|
||||
/http-proxy-agent/5.0.0:
|
||||
resolution: {integrity: sha512-n2hY8YdoRE1i7r6M0w9DIw5GgZN0G25P8zLCRQ8rjXtTU3vsNFBI/vWK/UIeE6g5MUUz6avwAPXmL6Fy9D/90w==}
|
||||
@@ -2936,6 +3012,7 @@ packages:
|
||||
dependencies:
|
||||
quick-lru: 5.1.1
|
||||
resolve-alpn: 1.2.1
|
||||
dev: true
|
||||
|
||||
/https-proxy-agent/5.0.1:
|
||||
resolution: {integrity: sha512-dFcAjpTQFgoLMzC2VwU+C/CbS7uRL0lWmxDITmqm7C+7F0Odmj6s9l6alZc6AELXhrnggM2CeWSXHGOdX2YtwA==}
|
||||
@@ -3313,6 +3390,7 @@ packages:
|
||||
|
||||
/json-buffer/3.0.1:
|
||||
resolution: {integrity: sha512-4bV5BfR2mqfQTJm+V5tPPdf+ZpuhiIvTuAB5g8kcrXOZpTT/QwwVRWBywX1ozr6lEuPdbHxwaJlm9G6mI2sfSQ==}
|
||||
dev: true
|
||||
|
||||
/json-schema-traverse/0.4.1:
|
||||
resolution: {integrity: sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==}
|
||||
@@ -3322,21 +3400,12 @@ packages:
|
||||
resolution: {integrity: sha512-Bdboy+l7tA3OGW6FjyFHWkP5LuByj1Tk33Ljyq0axyzdk9//JSi2u3fP1QSmd1KNwq6VOKYGlAu87CisVir6Pw==}
|
||||
dev: true
|
||||
|
||||
/json-stringify-safe/5.0.1:
|
||||
resolution: {integrity: sha512-ZClg6AaYvamvYEE82d3Iyd3vSSIjQ+odgjaTzRuO3s7toCdFKczob2i0zCh7JE8kWn17yvAWhUVxvqGwUalsRA==}
|
||||
optional: true
|
||||
|
||||
/json5/2.2.3:
|
||||
resolution: {integrity: sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==}
|
||||
engines: {node: '>=6'}
|
||||
hasBin: true
|
||||
dev: true
|
||||
|
||||
/jsonfile/4.0.0:
|
||||
resolution: {integrity: sha512-m6F1R3z8jjlf2imQHS2Qez5sjKWQzbuuhuJ/FKYFRZvPE3PuHcSMVZzfsLhGVOkfd20obL5SWEBew5ShlquNxg==}
|
||||
optionalDependencies:
|
||||
graceful-fs: 4.2.11
|
||||
|
||||
/jsonfile/6.2.0:
|
||||
resolution: {integrity: sha512-FGuPw30AdOIUTRMC2OMRtQV+jkVj2cfPqSeWXv1NEAJ1qZ5zb1X6z1mFhbfOB/iy3ssJCD+3KuZ8r8C3uVFlAg==}
|
||||
dependencies:
|
||||
@@ -3358,9 +3427,25 @@ packages:
|
||||
resolution: {integrity: sha512-oxVHkHR/EJf2CNXnWxRLW6mg7JyCCUcG0DtEGmL2ctUo1PNTin1PUil+r/+4r5MpVgC/fn1kjsx7mjSujKqIpw==}
|
||||
dependencies:
|
||||
json-buffer: 3.0.1
|
||||
dev: true
|
||||
|
||||
/koffi/2.16.2:
|
||||
resolution: {integrity: sha512-owU0MRwv6xkrVqCd+33uw6BaYppkTRXbO/rVdJNI2dvZG0gzyRhYwW25eWtc5pauwK8TGh3AbkFONSezdykfSA==}
|
||||
/koffi/3.1.0:
|
||||
resolution: {integrity: sha512-0mCvdjTJBXioiaKNz0vajAEdWtfM5qyhVXSq+wQrrU3odzNvl/J7Cqna79QpNo9mfoKpQgGsyFFDRtDACCwGrQ==}
|
||||
optionalDependencies:
|
||||
'@koromix/koffi-darwin-arm64': 3.1.0
|
||||
'@koromix/koffi-darwin-x64': 3.1.0
|
||||
'@koromix/koffi-freebsd-arm64': 3.1.0
|
||||
'@koromix/koffi-freebsd-ia32': 3.1.0
|
||||
'@koromix/koffi-freebsd-x64': 3.1.0
|
||||
'@koromix/koffi-linux-arm64': 3.1.0
|
||||
'@koromix/koffi-linux-ia32': 3.1.0
|
||||
'@koromix/koffi-linux-loong64': 3.1.0
|
||||
'@koromix/koffi-linux-riscv64': 3.1.0
|
||||
'@koromix/koffi-linux-x64': 3.1.0
|
||||
'@koromix/koffi-openbsd-ia32': 3.1.0
|
||||
'@koromix/koffi-openbsd-x64': 3.1.0
|
||||
'@koromix/koffi-win32-ia32': 3.1.0
|
||||
'@koromix/koffi-win32-x64': 3.1.0
|
||||
dev: false
|
||||
|
||||
/lazy-val/1.0.5:
|
||||
@@ -3408,6 +3493,7 @@ packages:
|
||||
/lowercase-keys/2.0.0:
|
||||
resolution: {integrity: sha512-tqNXrS78oMOE73NMxK4EMLQsQowWf8jKooH9g7xPavRT706R6bkQJ6DY2Te7QukaZsulxa30wQ7bk0pm4XiHmA==}
|
||||
engines: {node: '>=8'}
|
||||
dev: true
|
||||
|
||||
/lru-cache/10.4.3:
|
||||
resolution: {integrity: sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ==}
|
||||
@@ -3462,13 +3548,6 @@ packages:
|
||||
- supports-color
|
||||
dev: true
|
||||
|
||||
/matcher/3.0.0:
|
||||
resolution: {integrity: sha512-OkeDaAZ/bQCxeFAozM55PKcKU0yJMPGifLwV4Qgjitu+5MoAfSQN4lsLJeXZ1b8w0x+/Emda6MZgXS1jvsapng==}
|
||||
engines: {node: '>=10'}
|
||||
dependencies:
|
||||
escape-string-regexp: 4.0.0
|
||||
optional: true
|
||||
|
||||
/math-intrinsics/1.1.0:
|
||||
resolution: {integrity: sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==}
|
||||
engines: {node: '>= 0.4'}
|
||||
@@ -3500,10 +3579,12 @@ packages:
|
||||
/mimic-response/1.0.1:
|
||||
resolution: {integrity: sha512-j5EctnkH7amfV/q5Hgmoal1g2QHFJRraOtmx0JpIqkxhBhI/lJSl1nMpQ45hVarwNETOoWEimndZ4QK0RHxuxQ==}
|
||||
engines: {node: '>=4'}
|
||||
dev: true
|
||||
|
||||
/mimic-response/3.1.0:
|
||||
resolution: {integrity: sha512-z0yWI+4FDrrweS8Zmt4Ej5HdJmky15+L2e6Wgn3+iK5fWzb6T3fhNFq2+MeTRb064c6Wr4N/wv0DzQTjNzHNGQ==}
|
||||
engines: {node: '>=10'}
|
||||
dev: true
|
||||
|
||||
/minimatch/10.1.1:
|
||||
resolution: {integrity: sha512-enIvLvRAFZYXJzkCYG5RKmPfrFArdLv+R+lbQ53BmIMLIry74bjKzX6iHAm8WYamJkhSSEabrWN5D97XnKObjQ==}
|
||||
@@ -3657,6 +3738,7 @@ packages:
|
||||
/normalize-url/6.1.0:
|
||||
resolution: {integrity: sha512-DlL+XwOy3NxAQ8xuC0okPgK46iuVNAK01YN7RueYBqqFeGsBjV9XmCAzAdgt+667bCl5kPh9EqKKDwnaPG1I7A==}
|
||||
engines: {node: '>=10'}
|
||||
dev: true
|
||||
|
||||
/object-assign/4.1.1:
|
||||
resolution: {integrity: sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==}
|
||||
@@ -3671,6 +3753,7 @@ packages:
|
||||
/object-keys/1.1.1:
|
||||
resolution: {integrity: sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA==}
|
||||
engines: {node: '>= 0.4'}
|
||||
dev: true
|
||||
|
||||
/object.assign/4.1.7:
|
||||
resolution: {integrity: sha512-nK28WOo+QIjBkDduTINE4JkF/UJJKyf2EJxvJKfblDpyg0Q+pkOHNTL0Qwy6NP6FhE/EnzV73BxxqcJaXY9anw==}
|
||||
@@ -3718,6 +3801,7 @@ packages:
|
||||
resolution: {integrity: sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==}
|
||||
dependencies:
|
||||
wrappy: 1.0.2
|
||||
dev: true
|
||||
|
||||
/onetime/5.1.2:
|
||||
resolution: {integrity: sha512-kbpaSSGJTWdAY5KPVeMOKXSrPtr8C8C7wodJbcsd51jRnmD+GZu8Y0VoU6Dm5Z4vWr0Ig/1NKuWRKf7j5aaYSg==}
|
||||
@@ -3778,6 +3862,7 @@ packages:
|
||||
/p-cancelable/2.1.1:
|
||||
resolution: {integrity: sha512-BZOr3nRQHOntUjTrH8+Lh54smKHoHyur8We1V8DSMVrl5A2malOOwuJRnKRDjSnkoeBh4at6BwEnb5I7Jl31wg==}
|
||||
engines: {node: '>=8'}
|
||||
dev: true
|
||||
|
||||
/p-limit/3.1.0:
|
||||
resolution: {integrity: sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==}
|
||||
@@ -3843,9 +3928,6 @@ packages:
|
||||
engines: {node: '>=12', npm: '>=6'}
|
||||
dev: true
|
||||
|
||||
/pend/1.2.0:
|
||||
resolution: {integrity: sha512-F3asv42UuXchdzt+xXqfW1OGlVBe+mxa2mqI0pg5yAHZPvFmY3Y6drSf/GQ1A86WgWEN9Kzh/WrgKa6iGcHXLg==}
|
||||
|
||||
/picocolors/1.1.1:
|
||||
resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==}
|
||||
dev: true
|
||||
@@ -3935,6 +4017,7 @@ packages:
|
||||
dependencies:
|
||||
end-of-stream: 1.4.5
|
||||
once: 1.4.0
|
||||
dev: true
|
||||
|
||||
/punycode/2.3.1:
|
||||
resolution: {integrity: sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==}
|
||||
@@ -3944,6 +4027,7 @@ packages:
|
||||
/quick-lru/5.1.1:
|
||||
resolution: {integrity: sha512-WuyALRjWPDGtt/wzJiadO5AXY+8hZ80hVpe6MyivgraREW751X3SbhRvG3eLKOYN+8VEvqLcf3wdnt44Z4S4SA==}
|
||||
engines: {node: '>=10'}
|
||||
dev: true
|
||||
|
||||
/react-dom/19.2.1_react@19.2.1:
|
||||
resolution: {integrity: sha512-ibrK8llX2a4eOskq1mXKu/TGZj9qzomO+sNfO98M6d9zIPOEhlBkMkBUBLd1vgS0gQsLDBzA+8jJBVXDnfHmJg==}
|
||||
@@ -4026,6 +4110,7 @@ packages:
|
||||
|
||||
/resolve-alpn/1.2.1:
|
||||
resolution: {integrity: sha512-0a1F4l73/ZFZOakJnQ3FvkJ2+gSTQWz/r2KE5OdDY0TxPm5h4GkqkWWfM47T7HsbnOtcJVEF4epCVy6u7Q3K+g==}
|
||||
dev: true
|
||||
|
||||
/resolve-from/4.0.0:
|
||||
resolution: {integrity: sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g==}
|
||||
@@ -4045,6 +4130,7 @@ packages:
|
||||
resolution: {integrity: sha512-4gl03wn3hj1HP3yzgdI7d3lCkF95F21Pz4BPGvKHinyQzALR5CapwC8yIi0Rh58DEMQ/SguC03wFj2k0M/mHhw==}
|
||||
dependencies:
|
||||
lowercase-keys: 2.0.0
|
||||
dev: true
|
||||
|
||||
/restore-cursor/3.1.0:
|
||||
resolution: {integrity: sha512-l+sSefzHpj5qimhFSE5a8nufZYAM3sBSVMAPtYkmC+4EH2anSGaEMXSD0izRQbu9nfyQ9y5JrVmp7E8oZrUjvA==}
|
||||
@@ -4067,18 +4153,6 @@ packages:
|
||||
glob: 7.2.3
|
||||
dev: true
|
||||
|
||||
/roarr/2.15.4:
|
||||
resolution: {integrity: sha512-CHhPh+UNHD2GTXNYhPWLnU8ONHdI+5DI+4EYIAOaiD63rHeYlZvyh8P+in5999TTSFgUYuKUAjzRI4mdh/p+2A==}
|
||||
engines: {node: '>=8.0'}
|
||||
dependencies:
|
||||
boolean: 3.2.0
|
||||
detect-node: 2.1.0
|
||||
globalthis: 1.0.4
|
||||
json-stringify-safe: 5.0.1
|
||||
semver-compare: 1.0.0
|
||||
sprintf-js: 1.1.3
|
||||
optional: true
|
||||
|
||||
/rollup/4.53.3:
|
||||
resolution: {integrity: sha512-w8GmOxZfBmKknvdXU1sdM9NHcoQejwF/4mNgj2JuEEdRaHwwF12K7e9eXn1nLZ07ad+du76mkVsyeb2rKGllsA==}
|
||||
engines: {node: '>=18.0.0', npm: '>=8.0.0'}
|
||||
@@ -4161,10 +4235,6 @@ packages:
|
||||
resolution: {integrity: sha512-eNv+WrVbKu1f3vbYJT/xtiF5syA5HPIMtf9IgY/nKg0sWqzAUEvqY/xm7OcZc/qafLx/iO9FgOmeSAp4v5ti/Q==}
|
||||
dev: true
|
||||
|
||||
/semver-compare/1.0.0:
|
||||
resolution: {integrity: sha512-YM3/ITh2MJ5MtzaM429anh+x2jiLVjqILF4m4oyQB18W7Ggea7BfqdH/wGMK7dDiMghv/6WG7znWMwUDzJiXow==}
|
||||
optional: true
|
||||
|
||||
/semver/5.7.2:
|
||||
resolution: {integrity: sha512-cBznnQ9KjJqU67B52RMC65CMarK2600WFnbkcaiwWq3xy/5haFJlshgnpjovMVJ+Hff49d8GEn0b87C5pDQ10g==}
|
||||
hasBin: true
|
||||
@@ -4173,19 +4243,13 @@ packages:
|
||||
/semver/6.3.1:
|
||||
resolution: {integrity: sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==}
|
||||
hasBin: true
|
||||
dev: true
|
||||
|
||||
/semver/7.7.3:
|
||||
resolution: {integrity: sha512-SdsKMrI9TdgjdweUSR9MweHA4EJ8YxHn8DFaDisvhVlUOe4BF1tLD7GAj0lIqWVl+dPb/rExr0Btby5loQm20Q==}
|
||||
engines: {node: '>=10'}
|
||||
hasBin: true
|
||||
|
||||
/serialize-error/7.0.1:
|
||||
resolution: {integrity: sha512-8I8TjW5KMOKsZQTvoxjuSIa7foAwPWGOts+6o7sgjz41/qMD9VQHEDxi6PBvK2l0MXUmqZyNpUK+T2tQaaElvw==}
|
||||
engines: {node: '>=10'}
|
||||
dependencies:
|
||||
type-fest: 0.13.1
|
||||
optional: true
|
||||
|
||||
/set-function-length/1.2.2:
|
||||
resolution: {integrity: sha512-pgRc4hJ4/sNjWCSS9AmnS40x3bNMDTknHgL5UaMBTMyJnU90EgWh1Rz+MC9eFu4BuN/UwZjKQuY/1v3rM7HMfg==}
|
||||
engines: {node: '>= 0.4'}
|
||||
@@ -4341,10 +4405,6 @@ packages:
|
||||
engines: {node: '>=0.10.0'}
|
||||
dev: true
|
||||
|
||||
/sprintf-js/1.1.3:
|
||||
resolution: {integrity: sha512-Oo+0REFV59/rz3gfJNKQiBlwfHaSESl1pcGyABQsnnIfWOFt6JNj5gCog2U6MLZ//IGYD+nA8nI+mTShREReaA==}
|
||||
optional: true
|
||||
|
||||
/ssri/9.0.1:
|
||||
resolution: {integrity: sha512-o57Wcn66jMQvfHG1FlYbWeZWW/dHZhJXjpIcTfXldXEk5nz5lStPo3mK0OJQfGR3RbZUlbISexbljkJzuEj/8Q==}
|
||||
engines: {node: ^12.13.0 || ^14.15.0 || >=16.0.0}
|
||||
@@ -4559,11 +4619,6 @@ packages:
|
||||
prelude-ls: 1.2.1
|
||||
dev: true
|
||||
|
||||
/type-fest/0.13.1:
|
||||
resolution: {integrity: sha512-34R7HTnG0XIJcBSn5XhDd7nNFPRcXYRZrBB2O2jdKqYODldSzBAqzsWoZYYvduky73toYS/ESqxPvkDf/F0XMg==}
|
||||
engines: {node: '>=10'}
|
||||
optional: true
|
||||
|
||||
/typed-array-buffer/1.0.3:
|
||||
resolution: {integrity: sha512-nAYYwfY3qnzX30IkA6AQZjVbtK6duGontcQm1WSG1MD94YLqK0515GNApXkoxKOWMusVssAHWLh9SeaoefYFGw==}
|
||||
engines: {node: '>= 0.4'}
|
||||
@@ -4644,6 +4699,15 @@ packages:
|
||||
|
||||
/undici-types/6.21.0:
|
||||
resolution: {integrity: sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==}
|
||||
dev: true
|
||||
|
||||
/undici-types/7.18.2:
|
||||
resolution: {integrity: sha512-AsuCzffGHJybSaRrmr5eHr81mwJU3kjw6M+uprWvCXiNeN9SOGwQ3Jn8jb8m3Z6izVgknn1R0FTCEAP2QrLY/w==}
|
||||
|
||||
/undici/7.28.0:
|
||||
resolution: {integrity: sha512-cRZYrTDwWznlnRiPjggAGxZXanty6M8RV1ff8Wm4LWXBp7/IG8v5DnOm74DtUBp9OONpK75YlPnIjQqX0dBDtA==}
|
||||
engines: {node: '>=20.18.1'}
|
||||
optional: true
|
||||
|
||||
/unique-filename/2.0.1:
|
||||
resolution: {integrity: sha512-ODWHtkkdx3IAR+veKxFV+VBkUMcN+FaqzUUd7IZzt+0zhDZFPFxhlqwPF3YQvMHx1TD0tdgYl+kuPnJ8E6ql7A==}
|
||||
@@ -4659,10 +4723,6 @@ packages:
|
||||
imurmurhash: 0.1.4
|
||||
dev: true
|
||||
|
||||
/universalify/0.1.2:
|
||||
resolution: {integrity: sha512-rBJeI5CXAlmy1pV+617WB9J63U6XcazHHF2f2dbJix4XzpUF0RS3Zbj0FGIOCAva5P/d/GBOYaACQ1w+0azUkg==}
|
||||
engines: {node: '>= 4.0.0'}
|
||||
|
||||
/universalify/2.0.1:
|
||||
resolution: {integrity: sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw==}
|
||||
engines: {node: '>= 10.0.0'}
|
||||
@@ -4759,6 +4819,11 @@ packages:
|
||||
defaults: 1.0.4
|
||||
dev: true
|
||||
|
||||
/wechat-emojis/1.0.2:
|
||||
resolution: {integrity: sha512-T1drHGy92rKm/Vo7LRkU4D4wdREpVTjAMEa4gR1NB9IAyck3qmmewFSrnEEIyZfsv3SXTA7X1kt6Smt0UKVCyw==}
|
||||
engines: {node: '>=14.0.0'}
|
||||
dev: false
|
||||
|
||||
/which-boxed-primitive/1.1.1:
|
||||
resolution: {integrity: sha512-TbX3mj8n0odCBFVlY8AxkqcHASw3L60jIuF8jFP78az3C2YhmGvqbHBpAjTRH2/xqYunrJ9g1jSyjCjpoWzIAA==}
|
||||
engines: {node: '>= 0.4'}
|
||||
@@ -4845,6 +4910,7 @@ packages:
|
||||
|
||||
/wrappy/1.0.2:
|
||||
resolution: {integrity: sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==}
|
||||
dev: true
|
||||
|
||||
/xmlbuilder/15.1.1:
|
||||
resolution: {integrity: sha512-yMqGBqtXyeN1e3TGYvgNgDVZ3j84W4cwkOXQswghol6APgZWaff9lnbvN7MHYJOiXsvGPXtjTYJEiC9J2wv9Eg==}
|
||||
@@ -4882,12 +4948,6 @@ packages:
|
||||
yargs-parser: 21.1.1
|
||||
dev: true
|
||||
|
||||
/yauzl/2.10.0:
|
||||
resolution: {integrity: sha512-p4a9I6X6nu6IhoGmBqAcbJy1mlC4j27vEPZX9F4L4/vZT3Lyq1VkFHw/V/PUcB9Buo+DG3iHkT0x3Qya58zc3g==}
|
||||
dependencies:
|
||||
buffer-crc32: 0.2.13
|
||||
fd-slicer: 1.1.0
|
||||
|
||||
/yocto-queue/0.1.0:
|
||||
resolution: {integrity: sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==}
|
||||
engines: {node: '>=10'}
|
||||
|
||||
|
After Width: | Height: | Size: 767 KiB |
|
After Width: | Height: | Size: 680 KiB |
|
After Width: | Height: | Size: 204 KiB |
|
Before Width: | Height: | Size: 35 KiB After Width: | Height: | Size: 27 KiB |
@@ -27,13 +27,13 @@
|
||||
.report {
|
||||
width: 430px;
|
||||
margin: 0 auto;
|
||||
padding: 22px 14px 34px;
|
||||
padding: 20px 14px 34px;
|
||||
}
|
||||
.hero,
|
||||
.card,
|
||||
.section {
|
||||
.section,
|
||||
.card {
|
||||
background: #fff;
|
||||
border-radius: 16px;
|
||||
border-radius: 18px;
|
||||
box-shadow: 0 8px 24px rgba(15, 23, 42, 0.06);
|
||||
}
|
||||
.hero {
|
||||
@@ -41,25 +41,35 @@
|
||||
}
|
||||
.hero-top {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
gap: 14px;
|
||||
min-width: 0;
|
||||
}
|
||||
.hero-top > div:first-child {
|
||||
min-width: 0;
|
||||
flex: 1 1 auto;
|
||||
}
|
||||
.hero h1 {
|
||||
margin: 0;
|
||||
font-size: 23px;
|
||||
line-height: 1.2;
|
||||
margin: 0 0 8px;
|
||||
font-weight: 900;
|
||||
}
|
||||
.sub {
|
||||
margin-top: 8px;
|
||||
color: #667085;
|
||||
font-size: 13px;
|
||||
line-height: 1.5;
|
||||
line-height: 1.55;
|
||||
}
|
||||
.mode-tag {
|
||||
display: inline-flex;
|
||||
margin-top: 10px;
|
||||
padding: 4px 10px;
|
||||
border-radius: 999px;
|
||||
background: #eef8f2;
|
||||
color: #07a352;
|
||||
font-size: 11px;
|
||||
font-weight: 800;
|
||||
}
|
||||
.avatar-grid {
|
||||
width: 58px;
|
||||
@@ -76,6 +86,49 @@
|
||||
border-radius: 50%;
|
||||
object-fit: cover;
|
||||
}
|
||||
.hero-headline {
|
||||
margin-top: 14px;
|
||||
padding: 14px;
|
||||
border-radius: 16px;
|
||||
background: linear-gradient(135deg, #edf9f1 0%, #f7fbf8 100%);
|
||||
}
|
||||
.hero-headline b {
|
||||
display: block;
|
||||
font-size: 17px;
|
||||
color: #076c39;
|
||||
}
|
||||
.hero-headline p {
|
||||
margin: 8px 0 0;
|
||||
font-size: 13px;
|
||||
line-height: 1.65;
|
||||
color: #1f2933;
|
||||
}
|
||||
.hero-inline-notes {
|
||||
display: grid;
|
||||
gap: 8px;
|
||||
margin-top: 10px;
|
||||
}
|
||||
.hero-note,
|
||||
.hero-status {
|
||||
padding: 10px 12px;
|
||||
border-radius: 12px;
|
||||
font-size: 12px;
|
||||
line-height: 1.5;
|
||||
}
|
||||
.hero-status {
|
||||
margin-top: 10px;
|
||||
background: #f7faf9;
|
||||
color: #076c39;
|
||||
font-weight: 700;
|
||||
}
|
||||
.hero-note.takeaway {
|
||||
background: #eef8f2;
|
||||
color: #076c39;
|
||||
}
|
||||
.hero-note.pending {
|
||||
background: #fff8e8;
|
||||
color: #8a5a00;
|
||||
}
|
||||
.stats {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(4, 1fr);
|
||||
@@ -87,14 +140,11 @@
|
||||
border-radius: 12px;
|
||||
padding: 10px 6px;
|
||||
text-align: center;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
}
|
||||
.stat b {
|
||||
display: block;
|
||||
font-size: 18px;
|
||||
color: #07a352;
|
||||
white-space: nowrap;
|
||||
line-height: 1.25;
|
||||
}
|
||||
.stat span {
|
||||
@@ -102,16 +152,16 @@
|
||||
color: #667085;
|
||||
}
|
||||
.section {
|
||||
margin-top: 14px;
|
||||
margin-top: 18px;
|
||||
padding: 18px;
|
||||
}
|
||||
.section-title {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
font-size: 18px;
|
||||
margin-bottom: 14px;
|
||||
font-size: 19px;
|
||||
font-weight: 900;
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
.section-title::before {
|
||||
content: '';
|
||||
@@ -120,11 +170,23 @@
|
||||
border-radius: 99px;
|
||||
background: #07c160;
|
||||
}
|
||||
.section-subtitle {
|
||||
margin: 10px 0 6px;
|
||||
color: #667085;
|
||||
font-size: 12px;
|
||||
font-weight: 700;
|
||||
}
|
||||
.section-more {
|
||||
margin-top: 10px;
|
||||
color: #98a2b3;
|
||||
font-size: 11px;
|
||||
text-align: right;
|
||||
}
|
||||
.card {
|
||||
padding: 14px;
|
||||
margin-top: 10px;
|
||||
box-shadow: none;
|
||||
border: 1px solid #edf0f2;
|
||||
box-shadow: none;
|
||||
}
|
||||
.topic-title-row {
|
||||
display: flex;
|
||||
@@ -133,17 +195,17 @@
|
||||
gap: 8px;
|
||||
}
|
||||
.topic-title-row h3 {
|
||||
margin: 0;
|
||||
font-size: 16px;
|
||||
line-height: 1.35;
|
||||
margin: 0;
|
||||
font-weight: 850;
|
||||
}
|
||||
.heat,
|
||||
.tag {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
border-radius: 999px;
|
||||
padding: 4px 8px;
|
||||
border-radius: 999px;
|
||||
background: #eef8f2;
|
||||
color: #07a352;
|
||||
font-size: 11px;
|
||||
@@ -158,19 +220,44 @@
|
||||
background: #eef5ff;
|
||||
color: #1677ff;
|
||||
}
|
||||
.red {
|
||||
background: #fff1f0;
|
||||
color: #ff4d4f;
|
||||
}
|
||||
.topic-meta {
|
||||
margin-top: 6px;
|
||||
color: #8a94a6;
|
||||
font-size: 12px;
|
||||
}
|
||||
.card p {
|
||||
margin: 10px 0 0;
|
||||
font-size: 13px;
|
||||
line-height: 1.65;
|
||||
margin: 10px 0 0;
|
||||
}
|
||||
.topic-conclusions {
|
||||
display: grid;
|
||||
gap: 8px;
|
||||
margin-top: 10px;
|
||||
}
|
||||
.topic-conclusion {
|
||||
padding: 8px 10px;
|
||||
border-radius: 10px;
|
||||
background: #edf9f1;
|
||||
color: #076c39;
|
||||
font-size: 12px;
|
||||
line-height: 1.5;
|
||||
font-weight: 700;
|
||||
}
|
||||
.topic-inline-image {
|
||||
display: grid;
|
||||
grid-template-columns: 76px 1fr;
|
||||
gap: 10px;
|
||||
margin-top: 10px;
|
||||
padding: 10px;
|
||||
border-radius: 12px;
|
||||
background: #f7faf9;
|
||||
}
|
||||
.topic-inline-image img {
|
||||
width: 76px;
|
||||
height: 76px;
|
||||
border-radius: 10px;
|
||||
object-fit: cover;
|
||||
}
|
||||
.participants {
|
||||
display: flex;
|
||||
@@ -182,7 +269,6 @@
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 5px;
|
||||
min-width: 0;
|
||||
background: #f6f8fa;
|
||||
border-radius: 999px;
|
||||
padding: 3px 8px 3px 3px;
|
||||
@@ -191,7 +277,6 @@
|
||||
width: 24px;
|
||||
height: 24px;
|
||||
border-radius: 50%;
|
||||
object-fit: cover;
|
||||
}
|
||||
.person-chip b {
|
||||
max-width: 58px;
|
||||
@@ -213,17 +298,6 @@
|
||||
background: #f2f4f7;
|
||||
color: #667085;
|
||||
}
|
||||
.resource {
|
||||
padding: 11px 12px;
|
||||
background: #f7f8fa;
|
||||
border-radius: 12px;
|
||||
margin-top: 8px;
|
||||
font-size: 13px;
|
||||
line-height: 1.55;
|
||||
}
|
||||
.resource b {
|
||||
color: #1677ff;
|
||||
}
|
||||
.important-card {
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
@@ -248,9 +322,9 @@
|
||||
color: #1f2933;
|
||||
}
|
||||
.important-text {
|
||||
margin-top: 5px;
|
||||
font-size: 13px;
|
||||
line-height: 1.55;
|
||||
margin-top: 5px;
|
||||
}
|
||||
.important-note {
|
||||
margin-top: 8px;
|
||||
@@ -262,6 +336,34 @@
|
||||
font-size: 12px;
|
||||
line-height: 1.45;
|
||||
}
|
||||
.action-grid {
|
||||
display: grid;
|
||||
gap: 10px;
|
||||
}
|
||||
.action-card {
|
||||
border-radius: 14px;
|
||||
padding: 12px;
|
||||
}
|
||||
.todo-card {
|
||||
background: #eef5ff;
|
||||
}
|
||||
.unresolved-card {
|
||||
background: #fff8e8;
|
||||
}
|
||||
.action-card b {
|
||||
display: block;
|
||||
color: #1f2933;
|
||||
font-size: 14px;
|
||||
}
|
||||
.action-card div {
|
||||
margin-top: 6px;
|
||||
font-size: 12px;
|
||||
line-height: 1.55;
|
||||
color: #485465;
|
||||
}
|
||||
.action-note {
|
||||
color: #667085;
|
||||
}
|
||||
.chat-block {
|
||||
background: #f0f2f5;
|
||||
border-radius: 14px;
|
||||
@@ -292,49 +394,180 @@
|
||||
line-height: 1.5;
|
||||
}
|
||||
.quote-note {
|
||||
background: #fff8e1;
|
||||
border-radius: 10px;
|
||||
padding: 9px 10px;
|
||||
margin-top: 10px;
|
||||
padding: 9px 10px;
|
||||
border-radius: 10px;
|
||||
background: #fff8e1;
|
||||
color: #8a5a00;
|
||||
font-size: 12px;
|
||||
line-height: 1.5;
|
||||
}
|
||||
.qa-card {
|
||||
background: #f8fafc;
|
||||
border-radius: 14px;
|
||||
padding: 12px;
|
||||
.qa-card,
|
||||
.resource {
|
||||
margin-top: 10px;
|
||||
padding: 12px;
|
||||
border-radius: 14px;
|
||||
background: #f8fafc;
|
||||
}
|
||||
.qa-card b {
|
||||
.qa-card b,
|
||||
.resource b {
|
||||
display: block;
|
||||
color: #1f2933;
|
||||
margin-bottom: 5px;
|
||||
}
|
||||
.qa-card div {
|
||||
.qa-card div,
|
||||
.resource {
|
||||
font-size: 13px;
|
||||
line-height: 1.55;
|
||||
color: #485465;
|
||||
}
|
||||
.bar-row {
|
||||
.storyline-card,
|
||||
.chain-card {
|
||||
background: #f8fafc;
|
||||
}
|
||||
.storyline-steps {
|
||||
display: grid;
|
||||
grid-template-columns: 82px 1fr;
|
||||
gap: 8px;
|
||||
align-items: center;
|
||||
margin-top: 9px;
|
||||
margin-top: 10px;
|
||||
}
|
||||
.storyline-step {
|
||||
display: grid;
|
||||
grid-template-columns: 50px 1fr;
|
||||
gap: 10px;
|
||||
}
|
||||
.storyline-step span {
|
||||
color: #8a94a6;
|
||||
font-size: 12px;
|
||||
}
|
||||
.bar {
|
||||
height: 10px;
|
||||
background: #edf1f5;
|
||||
border-radius: 999px;
|
||||
overflow: hidden;
|
||||
.storyline-step b {
|
||||
font-size: 13px;
|
||||
line-height: 1.5;
|
||||
}
|
||||
.bar i {
|
||||
display: block;
|
||||
height: 100%;
|
||||
background: #07c160;
|
||||
.chain-flow {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 6px;
|
||||
align-items: center;
|
||||
margin-top: 10px;
|
||||
}
|
||||
.chain-flow span {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
padding: 6px 9px;
|
||||
border-radius: 999px;
|
||||
background: #eef8f2;
|
||||
color: #076c39;
|
||||
font-size: 12px;
|
||||
font-weight: 700;
|
||||
}
|
||||
.chain-flow i {
|
||||
font-style: normal;
|
||||
color: #98a2b3;
|
||||
}
|
||||
.gallery-card {
|
||||
display: grid;
|
||||
grid-template-columns: 112px 1fr;
|
||||
gap: 12px;
|
||||
margin-top: 10px;
|
||||
padding: 12px;
|
||||
background: #f7faf9;
|
||||
border-radius: 14px;
|
||||
}
|
||||
.gallery-image {
|
||||
width: 112px;
|
||||
height: 112px;
|
||||
border-radius: 12px;
|
||||
object-fit: cover;
|
||||
background: #e5e7eb;
|
||||
}
|
||||
.gallery-stats {
|
||||
display: inline-flex;
|
||||
margin-top: 7px;
|
||||
padding: 4px 8px;
|
||||
border-radius: 999px;
|
||||
background: #eef5ff;
|
||||
color: #1677ff;
|
||||
font-size: 11px;
|
||||
font-weight: 700;
|
||||
}
|
||||
.badge-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
gap: 10px;
|
||||
}
|
||||
/* AI 图片识别板块 */
|
||||
.vision-card {
|
||||
display: grid;
|
||||
grid-template-columns: 132px 1fr;
|
||||
gap: 14px;
|
||||
margin-top: 10px;
|
||||
padding: 12px;
|
||||
background: linear-gradient(135deg, #edf9f1 0%, #f7fbf8 100%);
|
||||
border: 1px solid #d6efde;
|
||||
border-radius: 14px;
|
||||
}
|
||||
.vision-image {
|
||||
width: 132px;
|
||||
height: 132px;
|
||||
border-radius: 12px;
|
||||
object-fit: cover;
|
||||
background: #e5e7eb;
|
||||
}
|
||||
.vision-description {
|
||||
margin-top: 6px;
|
||||
font-size: 13px;
|
||||
line-height: 1.5;
|
||||
color: #1f2933;
|
||||
}
|
||||
.vision-ocr {
|
||||
margin-top: 6px;
|
||||
padding: 6px 10px;
|
||||
background: #eef5ff;
|
||||
color: #1677ff;
|
||||
font-size: 11px;
|
||||
border-radius: 8px;
|
||||
word-break: break-all;
|
||||
}
|
||||
.vision-tags {
|
||||
margin-top: 8px;
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 4px;
|
||||
}
|
||||
.vision-tag {
|
||||
display: inline-block;
|
||||
padding: 3px 8px;
|
||||
background: #07c160;
|
||||
color: #fff;
|
||||
font-size: 10px;
|
||||
font-weight: 700;
|
||||
border-radius: 999px;
|
||||
}
|
||||
.vision-label {
|
||||
margin-top: 6px;
|
||||
font-size: 10px;
|
||||
color: #07a352;
|
||||
font-weight: 600;
|
||||
}
|
||||
.badge-card {
|
||||
background: linear-gradient(180deg, #fdfdfd 0%, #f6fbf8 100%);
|
||||
border: 1px solid #edf0f2;
|
||||
border-radius: 14px;
|
||||
padding: 12px;
|
||||
}
|
||||
.badge-card b {
|
||||
display: block;
|
||||
margin-top: 8px;
|
||||
font-size: 15px;
|
||||
}
|
||||
.badge-card p {
|
||||
margin: 8px 0 0;
|
||||
font-size: 12px;
|
||||
line-height: 1.55;
|
||||
}
|
||||
.data-grid {
|
||||
display: grid;
|
||||
gap: 12px;
|
||||
}
|
||||
.rank {
|
||||
display: flex;
|
||||
@@ -343,6 +576,9 @@
|
||||
padding: 9px 0;
|
||||
border-bottom: 1px solid #eef0f2;
|
||||
}
|
||||
.rank:last-child {
|
||||
border-bottom: none;
|
||||
}
|
||||
.rank img {
|
||||
width: 30px;
|
||||
height: 30px;
|
||||
@@ -395,7 +631,58 @@
|
||||
color: #8a94a6;
|
||||
}
|
||||
.empty-section {
|
||||
display: none;
|
||||
display: none !important;
|
||||
}
|
||||
.compact .report {
|
||||
padding-top: 18px;
|
||||
}
|
||||
.compact .section {
|
||||
margin-top: 12px;
|
||||
padding: 14px;
|
||||
}
|
||||
.compact .card {
|
||||
padding: 11px;
|
||||
}
|
||||
.compact .important-card,
|
||||
.compact .gallery-card,
|
||||
.compact .chat-block {
|
||||
padding: 10px;
|
||||
}
|
||||
.compact .section-title {
|
||||
margin-bottom: 9px;
|
||||
font-size: 17px;
|
||||
}
|
||||
.compact .hero-headline p,
|
||||
.compact .card p,
|
||||
.compact .important-text,
|
||||
.compact .chat-bubble {
|
||||
line-height: 1.5;
|
||||
}
|
||||
.compact .participants,
|
||||
.compact .keywords,
|
||||
.compact .hero-inline-notes {
|
||||
gap: 6px;
|
||||
}
|
||||
.compact .topic-conclusions {
|
||||
gap: 6px;
|
||||
}
|
||||
.compact .topic-inline-image {
|
||||
grid-template-columns: 64px 1fr;
|
||||
padding: 8px;
|
||||
}
|
||||
.compact .topic-inline-image img {
|
||||
width: 64px;
|
||||
height: 64px;
|
||||
}
|
||||
.compact .stats {
|
||||
gap: 6px;
|
||||
margin-top: 14px;
|
||||
}
|
||||
.compact .stat {
|
||||
padding: 8px 6px;
|
||||
}
|
||||
.compact .stat b {
|
||||
font-size: 17px;
|
||||
}
|
||||
@media (max-width: 430px) {
|
||||
html,
|
||||
@@ -407,75 +694,140 @@
|
||||
padding-left: 12px;
|
||||
padding-right: 12px;
|
||||
}
|
||||
.stats {
|
||||
gap: 6px;
|
||||
}
|
||||
.stat b {
|
||||
font-size: 16px;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<body class="{{REPORT_MODE_CLASS}}">
|
||||
<main class="report">
|
||||
<header class="hero">
|
||||
<div class="hero-top">
|
||||
<div>
|
||||
<h1>{{GROUP_NAME}}日报</h1>
|
||||
<div class="sub">{{DATE_RANGE}}<br />{{RECORD_NOTE}}</div>
|
||||
<div class="mode-tag">{{REPORT_MODE_LABEL}}</div>
|
||||
</div>
|
||||
<div class="avatar-grid">{{HERO_AVATARS}}</div>
|
||||
</div>
|
||||
<div class="hero-headline">
|
||||
<b>{{HERO_HEADLINE}}</b>
|
||||
<p>{{HERO_SUMMARY}}</p>
|
||||
</div>
|
||||
<div class="hero-status {{HERO_STATUS_EMPTY_CLASS}}">{{HERO_STATUS_LINE}}</div>
|
||||
<div class="hero-inline-notes">
|
||||
<div class="hero-note takeaway {{HERO_TAKEAWAY_EMPTY_CLASS}}">{{HERO_TAKEAWAY}}</div>
|
||||
<div class="hero-note pending {{HERO_PENDING_EMPTY_CLASS}}">{{HERO_PENDING}}</div>
|
||||
</div>
|
||||
<div class="stats">
|
||||
<div class="stat"><b>{{MESSAGE_COUNT}}</b><span>消息数</span></div>
|
||||
<div class="stat"><b>{{ACTIVE_USERS}}</b><span>活跃人数</span></div>
|
||||
<div class="stat"><b>{{TIME_SPAN}}</b><span>持续时长</span></div>
|
||||
<div class="stat"><b>{{TOPIC_COUNT}}</b><span>主要话题</span></div>
|
||||
<div class="stat"><b>{{TOPIC_COUNT}}</b><span>话题数</span></div>
|
||||
<div class="stat"><b>{{MEDIA_COUNT}}</b><span>媒体消息</span></div>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<section class="section topics">
|
||||
<section class="section {{TOPICS_EMPTY_CLASS}}">
|
||||
<div class="section-title">今日讨论热点</div>
|
||||
{{TOPIC_CARDS}}
|
||||
{{TOPICS_MORE_NOTE}}
|
||||
</section>
|
||||
|
||||
<section class="section resources {{RESOURCES_EMPTY_CLASS}}">
|
||||
<section class="section {{MESSAGES_EMPTY_CLASS}}">
|
||||
<div class="section-title">重要消息</div>
|
||||
{{IMPORTANT_MESSAGES}}
|
||||
{{MESSAGES_MORE_NOTE}}
|
||||
</section>
|
||||
|
||||
<section class="section {{ACTIONS_EMPTY_CLASS}}">
|
||||
<div class="section-title">待办事项和未解决问题</div>
|
||||
<div class="section-subtitle {{TODO_EMPTY_CLASS}}">待办事项</div>
|
||||
<div class="action-grid {{TODO_EMPTY_CLASS}}">{{TODO_CARDS}}</div>
|
||||
<div class="section-subtitle {{UNRESOLVED_EMPTY_CLASS}}">尚未解决</div>
|
||||
<div class="action-grid {{UNRESOLVED_EMPTY_CLASS}}">{{UNRESOLVED_CARDS}}</div>
|
||||
{{ACTIONS_MORE_NOTE}}
|
||||
</section>
|
||||
|
||||
<section class="section {{QUOTES_EMPTY_CLASS}}">
|
||||
<div class="section-title">今日名场面</div>
|
||||
{{QUOTE_BLOCKS}}
|
||||
{{QUOTES_MORE_NOTE}}
|
||||
</section>
|
||||
|
||||
<section class="section {{ANALYTICS_EMPTY_CLASS}}">
|
||||
<div class="section-title">今日群数据</div>
|
||||
<div class="data-grid">
|
||||
<div class="card">
|
||||
<div class="muted" style="font-size: 12px; margin-bottom: 6px">话唠榜 TOP5</div>
|
||||
{{RANK_ITEMS}}
|
||||
</div>
|
||||
<div class="card">
|
||||
<p><b>最活跃时段:</b>{{ACTIVITY_TIMELINE}}</p>
|
||||
<p><b>今日状态:</b>形成 {{CONCLUSION_COUNT}} 个结论,待办 {{TODO_COUNT}} 项,未解决 {{UNRESOLVED_COUNT}} 项。</p>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="section {{KEYWORDS_EMPTY_CLASS}}">
|
||||
<div class="section-title">关键词</div>
|
||||
<div class="cloud-tags">{{CLOUD_TAGS}}</div>
|
||||
{{KEYWORDS_MORE_NOTE}}
|
||||
</section>
|
||||
|
||||
<section class="section {{RESOURCES_EMPTY_CLASS}}">
|
||||
<div class="section-title">实用信息与资源</div>
|
||||
{{RESOURCE_ITEMS}}
|
||||
{{RESOURCES_MORE_NOTE}}
|
||||
</section>
|
||||
|
||||
<section class="section messages {{MESSAGES_EMPTY_CLASS}}">
|
||||
<div class="section-title">重要消息汇总</div>
|
||||
{{IMPORTANT_MESSAGES}}
|
||||
</section>
|
||||
|
||||
<section class="section quotes {{QUOTES_EMPTY_CLASS}}">
|
||||
<div class="section-title">有趣对话或金句</div>
|
||||
{{QUOTE_BLOCKS}}
|
||||
</section>
|
||||
|
||||
<section class="section qa {{QA_EMPTY_CLASS}}">
|
||||
<section class="section {{QA_EMPTY_CLASS}}">
|
||||
<div class="section-title">问题与解答</div>
|
||||
{{QA_CARDS}}
|
||||
{{QA_MORE_NOTE}}
|
||||
</section>
|
||||
|
||||
<section class="section analytics">
|
||||
<div class="section-title">群内数据可视化</div>
|
||||
{{HEAT_BARS}}
|
||||
<div class="card">
|
||||
<div class="muted" style="font-size: 12px; margin-bottom: 6px">
|
||||
话唠榜 TOP5(基于已读取记录估算)
|
||||
</div>
|
||||
{{RANK_ITEMS}}
|
||||
</div>
|
||||
<div class="card">
|
||||
<p><b>活跃时间线:</b>{{ACTIVITY_TIMELINE}}</p>
|
||||
</div>
|
||||
<section class="section {{STORYLINES_EMPTY_CLASS}}">
|
||||
<div class="section-title">今日剧情时间线</div>
|
||||
{{STORYLINE_CARDS}}
|
||||
{{STORYLINES_MORE_NOTE}}
|
||||
</section>
|
||||
|
||||
<section class="section cloud">
|
||||
<div class="section-title">词云/关键词</div>
|
||||
<div class="cloud-tags">{{CLOUD_TAGS}}</div>
|
||||
<section class="section {{REVERSALS_EMPTY_CLASS}}">
|
||||
<div class="section-title">群聊反转现场</div>
|
||||
{{REVERSAL_CARDS}}
|
||||
{{REVERSALS_MORE_NOTE}}
|
||||
</section>
|
||||
|
||||
<section class="section {{VISION_EMPTY_CLASS}}">
|
||||
<div class="section-title">{{VISION_TITLE}}</div>
|
||||
{{VISION_CARDS}}
|
||||
</section>
|
||||
|
||||
<section class="section {{GALLERY_EMPTY_CLASS}}">
|
||||
<div class="section-title">今日群相册</div>
|
||||
{{GALLERY_CARDS}}
|
||||
{{GALLERY_MORE_NOTE}}
|
||||
</section>
|
||||
|
||||
<section class="section {{VOICE_EMPTY_CLASS}}">
|
||||
<div class="section-title">语音之最</div>
|
||||
{{VOICE_CARDS}}
|
||||
{{VOICE_MORE_NOTE}}
|
||||
</section>
|
||||
|
||||
<section class="section {{VOICE_RANK_EMPTY_CLASS}}">
|
||||
<div class="section-title">语音时长榜</div>
|
||||
<div class="card">{{VOICE_RANK_CARDS}}</div>
|
||||
</section>
|
||||
|
||||
<section class="section {{BADGES_EMPTY_CLASS}}">
|
||||
<div class="section-title">今日临时人设</div>
|
||||
<div class="badge-grid">{{BADGE_CARDS}}</div>
|
||||
{{BADGES_MORE_NOTE}}
|
||||
</section>
|
||||
|
||||
<section class="section {{CHAINS_EMPTY_CLASS}}">
|
||||
<div class="section-title">话题参与链路</div>
|
||||
{{CHAIN_CARDS}}
|
||||
{{CHAINS_MORE_NOTE}}
|
||||
</section>
|
||||
|
||||
<footer class="footer">
|
||||
|
||||
@@ -0,0 +1,592 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1" />
|
||||
<title>{{REPORT_TITLE}}</title>
|
||||
<style>
|
||||
* {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
::-webkit-scrollbar {
|
||||
width: 0;
|
||||
height: 0;
|
||||
}
|
||||
html {
|
||||
width: 430px;
|
||||
scrollbar-width: none;
|
||||
}
|
||||
body {
|
||||
margin: 0;
|
||||
width: 430px;
|
||||
background: #f3f5f7;
|
||||
color: #1f2933;
|
||||
font-family:
|
||||
-apple-system, BlinkMacSystemFont, 'PingFang SC', 'Microsoft YaHei', sans-serif;
|
||||
}
|
||||
.report {
|
||||
width: 430px;
|
||||
margin: 0 auto;
|
||||
padding: 22px 14px 34px;
|
||||
}
|
||||
.hero,
|
||||
.card,
|
||||
.section {
|
||||
background: #fff;
|
||||
border-radius: 16px;
|
||||
box-shadow: 0 8px 24px rgba(15, 23, 42, 0.06);
|
||||
}
|
||||
.hero {
|
||||
padding: 20px;
|
||||
}
|
||||
.hero-top {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 14px;
|
||||
min-width: 0;
|
||||
}
|
||||
.hero-top > div:first-child {
|
||||
min-width: 0;
|
||||
flex: 1 1 auto;
|
||||
}
|
||||
.hero h1 {
|
||||
font-size: 23px;
|
||||
line-height: 1.2;
|
||||
margin: 0 0 8px;
|
||||
font-weight: 900;
|
||||
}
|
||||
.sub {
|
||||
color: #667085;
|
||||
font-size: 13px;
|
||||
line-height: 1.5;
|
||||
}
|
||||
.record-note {
|
||||
color: #485465;
|
||||
font-weight: 650;
|
||||
}
|
||||
.overview {
|
||||
margin-top: 2px;
|
||||
}
|
||||
.avatar-grid {
|
||||
width: 58px;
|
||||
height: 58px;
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: 3px;
|
||||
flex: 0 0 auto;
|
||||
}
|
||||
.avatar-grid img,
|
||||
.avatar {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
border-radius: 50%;
|
||||
object-fit: cover;
|
||||
}
|
||||
.stats {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(4, 1fr);
|
||||
gap: 8px;
|
||||
margin-top: 16px;
|
||||
}
|
||||
.stat {
|
||||
background: #f7faf9;
|
||||
border-radius: 12px;
|
||||
padding: 10px 6px;
|
||||
text-align: center;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
}
|
||||
.stat b {
|
||||
display: block;
|
||||
font-size: 18px;
|
||||
color: #07a352;
|
||||
white-space: nowrap;
|
||||
line-height: 1.25;
|
||||
}
|
||||
.stat span {
|
||||
font-size: 11px;
|
||||
color: #667085;
|
||||
}
|
||||
.section {
|
||||
margin-top: 14px;
|
||||
padding: 18px;
|
||||
}
|
||||
.section-title {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
font-size: 18px;
|
||||
font-weight: 900;
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
.section-title::before {
|
||||
content: '';
|
||||
width: 5px;
|
||||
height: 20px;
|
||||
border-radius: 99px;
|
||||
background: #07c160;
|
||||
}
|
||||
.card {
|
||||
padding: 14px;
|
||||
margin-top: 10px;
|
||||
box-shadow: none;
|
||||
border: 1px solid #edf0f2;
|
||||
}
|
||||
.topic-title-row {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
gap: 8px;
|
||||
}
|
||||
.topic-title-row h3 {
|
||||
font-size: 16px;
|
||||
line-height: 1.35;
|
||||
margin: 0;
|
||||
font-weight: 850;
|
||||
}
|
||||
.heat,
|
||||
.tag {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
border-radius: 999px;
|
||||
padding: 4px 8px;
|
||||
background: #eef8f2;
|
||||
color: #07a352;
|
||||
font-size: 11px;
|
||||
font-weight: 800;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.hot {
|
||||
background: #fff4e5;
|
||||
color: #d46b08;
|
||||
}
|
||||
.blue {
|
||||
background: #eef5ff;
|
||||
color: #1677ff;
|
||||
}
|
||||
.red {
|
||||
background: #fff1f0;
|
||||
color: #ff4d4f;
|
||||
}
|
||||
.topic-meta {
|
||||
margin-top: 6px;
|
||||
color: #8a94a6;
|
||||
font-size: 12px;
|
||||
}
|
||||
.card p {
|
||||
font-size: 13px;
|
||||
line-height: 1.65;
|
||||
margin: 10px 0 0;
|
||||
}
|
||||
.participants {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
margin-top: 10px;
|
||||
}
|
||||
.person-chip {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 5px;
|
||||
min-width: 0;
|
||||
background: #f6f8fa;
|
||||
border-radius: 999px;
|
||||
padding: 3px 8px 3px 3px;
|
||||
}
|
||||
.person-chip img {
|
||||
width: 24px;
|
||||
height: 24px;
|
||||
border-radius: 50%;
|
||||
object-fit: cover;
|
||||
}
|
||||
.person-chip b {
|
||||
max-width: 58px;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
font-size: 11px;
|
||||
}
|
||||
.keywords {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 6px;
|
||||
margin-top: 10px;
|
||||
}
|
||||
.keywords span {
|
||||
font-size: 11px;
|
||||
padding: 4px 8px;
|
||||
border-radius: 999px;
|
||||
background: #f2f4f7;
|
||||
color: #667085;
|
||||
}
|
||||
.resource {
|
||||
padding: 11px 12px;
|
||||
background: #f7f8fa;
|
||||
border-radius: 12px;
|
||||
margin-top: 8px;
|
||||
font-size: 13px;
|
||||
line-height: 1.55;
|
||||
}
|
||||
.resource b {
|
||||
color: #1677ff;
|
||||
}
|
||||
.important-card {
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
background: #f7faf9;
|
||||
border-radius: 14px;
|
||||
padding: 12px;
|
||||
margin-top: 10px;
|
||||
}
|
||||
.important-card > .avatar {
|
||||
width: 36px;
|
||||
height: 36px;
|
||||
flex: 0 0 auto;
|
||||
}
|
||||
.important-meta {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
gap: 8px;
|
||||
font-size: 12px;
|
||||
color: #667085;
|
||||
}
|
||||
.important-meta b {
|
||||
color: #1f2933;
|
||||
}
|
||||
.important-text {
|
||||
font-size: 13px;
|
||||
line-height: 1.55;
|
||||
margin-top: 5px;
|
||||
}
|
||||
.important-note {
|
||||
margin-top: 8px;
|
||||
padding: 7px 9px;
|
||||
border-left: 3px solid #07c160;
|
||||
background: #fff;
|
||||
border-radius: 8px;
|
||||
color: #07a352;
|
||||
font-size: 12px;
|
||||
line-height: 1.45;
|
||||
}
|
||||
.chat-block {
|
||||
background: #f0f2f5;
|
||||
border-radius: 14px;
|
||||
padding: 12px;
|
||||
margin-top: 10px;
|
||||
}
|
||||
.chat-msg {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
margin-top: 8px;
|
||||
}
|
||||
.chat-avatar {
|
||||
width: 32px;
|
||||
height: 32px;
|
||||
border-radius: 50%;
|
||||
object-fit: cover;
|
||||
}
|
||||
.chat-name {
|
||||
font-size: 11px;
|
||||
color: #667085;
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
.chat-bubble {
|
||||
background: #fff;
|
||||
border-radius: 4px 12px 12px 12px;
|
||||
padding: 9px 10px;
|
||||
font-size: 13px;
|
||||
line-height: 1.5;
|
||||
}
|
||||
.quote-note {
|
||||
background: #fff8e1;
|
||||
border-radius: 10px;
|
||||
padding: 9px 10px;
|
||||
margin-top: 10px;
|
||||
color: #8a5a00;
|
||||
font-size: 12px;
|
||||
line-height: 1.5;
|
||||
}
|
||||
.qa-card {
|
||||
background: #f8fafc;
|
||||
border-radius: 14px;
|
||||
padding: 12px;
|
||||
margin-top: 10px;
|
||||
}
|
||||
.qa-card b {
|
||||
display: block;
|
||||
color: #1f2933;
|
||||
margin-bottom: 5px;
|
||||
}
|
||||
.qa-card div {
|
||||
font-size: 13px;
|
||||
line-height: 1.55;
|
||||
color: #485465;
|
||||
}
|
||||
.bar-row {
|
||||
display: grid;
|
||||
grid-template-columns: 82px 1fr;
|
||||
gap: 8px;
|
||||
align-items: center;
|
||||
margin-top: 9px;
|
||||
font-size: 12px;
|
||||
}
|
||||
.bar {
|
||||
height: 10px;
|
||||
background: #edf1f5;
|
||||
border-radius: 999px;
|
||||
overflow: hidden;
|
||||
}
|
||||
.bar i {
|
||||
display: block;
|
||||
height: 100%;
|
||||
background: #07c160;
|
||||
border-radius: 999px;
|
||||
}
|
||||
.rank {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 9px;
|
||||
padding: 9px 0;
|
||||
border-bottom: 1px solid #eef0f2;
|
||||
}
|
||||
.rank img {
|
||||
width: 30px;
|
||||
height: 30px;
|
||||
border-radius: 50%;
|
||||
object-fit: cover;
|
||||
}
|
||||
.rank b {
|
||||
font-size: 13px;
|
||||
}
|
||||
.rank span {
|
||||
margin-left: auto;
|
||||
color: #8a94a6;
|
||||
font-size: 12px;
|
||||
}
|
||||
.cloud-tags {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
}
|
||||
.cloud-tags span {
|
||||
padding: 6px 10px;
|
||||
border-radius: 999px;
|
||||
background: #f2f4f7;
|
||||
color: #485465;
|
||||
font-weight: 800;
|
||||
}
|
||||
.cloud-tags .xl {
|
||||
font-size: 20px;
|
||||
color: #07a352;
|
||||
background: #e9f8ef;
|
||||
}
|
||||
.cloud-tags .lg {
|
||||
font-size: 17px;
|
||||
color: #1677ff;
|
||||
background: #eef5ff;
|
||||
}
|
||||
.cloud-tags .md {
|
||||
font-size: 15px;
|
||||
color: #d46b08;
|
||||
background: #fff4e5;
|
||||
}
|
||||
.footer {
|
||||
padding: 16px 4px 0;
|
||||
color: #98a2b3;
|
||||
text-align: center;
|
||||
font-size: 11px;
|
||||
line-height: 1.8;
|
||||
}
|
||||
.muted {
|
||||
color: #8a94a6;
|
||||
}
|
||||
.empty-section {
|
||||
display: none;
|
||||
}
|
||||
@media (max-width: 430px) {
|
||||
html,
|
||||
body {
|
||||
width: 100%;
|
||||
}
|
||||
.report {
|
||||
width: 100%;
|
||||
padding-left: 12px;
|
||||
padding-right: 12px;
|
||||
}
|
||||
.stats {
|
||||
gap: 6px;
|
||||
}
|
||||
.stat b {
|
||||
font-size: 16px;
|
||||
}
|
||||
}
|
||||
/* AI 图片识别板块(v1 模板) */
|
||||
.vision-card {
|
||||
display: grid;
|
||||
grid-template-columns: 132px 1fr;
|
||||
gap: 14px;
|
||||
margin-top: 10px;
|
||||
padding: 12px;
|
||||
background: linear-gradient(135deg, #edf9f1 0%, #f7fbf8 100%);
|
||||
border: 1px solid #d6efde;
|
||||
border-radius: 14px;
|
||||
}
|
||||
.vision-image {
|
||||
width: 132px;
|
||||
height: 132px;
|
||||
border-radius: 12px;
|
||||
object-fit: cover;
|
||||
background: #e5e7eb;
|
||||
}
|
||||
.vision-description {
|
||||
margin-top: 6px;
|
||||
font-size: 13px;
|
||||
line-height: 1.5;
|
||||
color: #1f2933;
|
||||
}
|
||||
.vision-ocr {
|
||||
margin-top: 6px;
|
||||
padding: 6px 10px;
|
||||
background: #eef5ff;
|
||||
color: #1677ff;
|
||||
font-size: 11px;
|
||||
border-radius: 8px;
|
||||
word-break: break-all;
|
||||
}
|
||||
.vision-tags {
|
||||
margin-top: 8px;
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 4px;
|
||||
}
|
||||
.vision-tag {
|
||||
display: inline-block;
|
||||
padding: 3px 8px;
|
||||
background: #07c160;
|
||||
color: #fff;
|
||||
font-size: 10px;
|
||||
font-weight: 700;
|
||||
border-radius: 999px;
|
||||
}
|
||||
.vision-label {
|
||||
margin-top: 6px;
|
||||
font-size: 10px;
|
||||
color: #07a352;
|
||||
font-weight: 600;
|
||||
}
|
||||
/* 热度条形图(v1 模板) */
|
||||
.heat-row {
|
||||
display: grid;
|
||||
grid-template-columns: 80px 1fr 40px;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
margin-top: 8px;
|
||||
font-size: 12px;
|
||||
}
|
||||
.heat-name {
|
||||
color: #1f2933;
|
||||
font-weight: 600;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
.heat-bar {
|
||||
background: #f3f5f7;
|
||||
border-radius: 999px;
|
||||
height: 10px;
|
||||
overflow: hidden;
|
||||
}
|
||||
.heat-bar i {
|
||||
display: block;
|
||||
height: 100%;
|
||||
background: linear-gradient(90deg, #07c160 0%, #34d399 100%);
|
||||
border-radius: 999px;
|
||||
}
|
||||
.heat-val {
|
||||
color: #485465;
|
||||
font-weight: 700;
|
||||
font-size: 11px;
|
||||
text-align: right;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<main class="report">
|
||||
<header class="hero">
|
||||
<div class="hero-top">
|
||||
<div>
|
||||
<h1>{{GROUP_NAME}}日报</h1>
|
||||
<div class="sub">
|
||||
<div>{{DATE_RANGE}}</div>
|
||||
<div class="record-note">{{RECORD_NOTE}}</div>
|
||||
<div class="overview">{{OVERVIEW}}</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="avatar-grid">{{HERO_AVATARS}}</div>
|
||||
</div>
|
||||
<div class="stats">
|
||||
<div class="stat"><b>{{MESSAGE_COUNT}}</b><span>消息数</span></div>
|
||||
<div class="stat"><b>{{ACTIVE_USERS}}</b><span>活跃人数</span></div>
|
||||
<div class="stat"><b>{{TIME_SPAN}}</b><span>持续时长</span></div>
|
||||
<div class="stat"><b>{{TOPIC_COUNT}}</b><span>主要话题</span></div>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<section class="section topics">
|
||||
<div class="section-title">今日讨论热点</div>
|
||||
{{TOPIC_CARDS}}
|
||||
</section>
|
||||
|
||||
<section class="section vision {{VISION_EMPTY_CLASS}}">
|
||||
<div class="section-title">{{VISION_TITLE}}</div>
|
||||
{{VISION_CARDS}}
|
||||
</section>
|
||||
|
||||
<section class="section resources {{RESOURCES_EMPTY_CLASS}}">
|
||||
<div class="section-title">实用信息与资源</div>
|
||||
{{RESOURCE_ITEMS}}
|
||||
</section>
|
||||
|
||||
<section class="section messages {{MESSAGES_EMPTY_CLASS}}">
|
||||
<div class="section-title">重要消息汇总</div>
|
||||
{{IMPORTANT_MESSAGES}}
|
||||
</section>
|
||||
|
||||
<section class="section quotes {{QUOTES_EMPTY_CLASS}}">
|
||||
<div class="section-title">有趣对话或金句</div>
|
||||
{{QUOTE_BLOCKS}}
|
||||
</section>
|
||||
|
||||
<section class="section qa {{QA_EMPTY_CLASS}}">
|
||||
<div class="section-title">问题与解答</div>
|
||||
{{QA_CARDS}}
|
||||
</section>
|
||||
|
||||
<section class="section analytics">
|
||||
<div class="section-title">群内数据可视化</div>
|
||||
{{HEAT_BARS}}
|
||||
<div class="card">
|
||||
<div class="muted" style="font-size: 12px; margin-bottom: 6px">
|
||||
话唠榜 TOP5(基于已读取记录估算)
|
||||
</div>
|
||||
{{RANK_ITEMS}}
|
||||
</div>
|
||||
<div class="card">
|
||||
<p><b>活跃时间线:</b>{{ACTIVITY_TIMELINE}}</p>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="section cloud">
|
||||
<div class="section-title">词云/关键词</div>
|
||||
<div class="cloud-tags">{{CLOUD_TAGS}}</div>
|
||||
</section>
|
||||
|
||||
<footer class="footer">
|
||||
数据来源:WechatExplorer · 微信群聊记录<br />
|
||||
生成时间:{{GENERATED_AT}}<br />
|
||||
{{FOOTER_NOTE}}
|
||||
</footer>
|
||||
</main>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,829 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1" />
|
||||
<title>{{REPORT_TITLE}}</title>
|
||||
<style>
|
||||
* {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
::-webkit-scrollbar {
|
||||
width: 0;
|
||||
height: 0;
|
||||
}
|
||||
html {
|
||||
width: 430px;
|
||||
scrollbar-width: none;
|
||||
}
|
||||
body {
|
||||
margin: 0;
|
||||
width: 430px;
|
||||
background: #f3f5f7;
|
||||
color: #1f2933;
|
||||
font-family:
|
||||
-apple-system, BlinkMacSystemFont, 'PingFang SC', 'Microsoft YaHei', sans-serif;
|
||||
}
|
||||
.report {
|
||||
width: 430px;
|
||||
margin: 0 auto;
|
||||
padding: 20px 14px 34px;
|
||||
}
|
||||
.hero,
|
||||
.section,
|
||||
.card {
|
||||
background: #fff;
|
||||
border-radius: 18px;
|
||||
box-shadow: 0 8px 24px rgba(15, 23, 42, 0.06);
|
||||
}
|
||||
.hero {
|
||||
padding: 20px;
|
||||
}
|
||||
.hero-top {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
gap: 14px;
|
||||
}
|
||||
.hero-top > div:first-child {
|
||||
min-width: 0;
|
||||
flex: 1 1 auto;
|
||||
}
|
||||
.hero h1 {
|
||||
margin: 0;
|
||||
font-size: 23px;
|
||||
line-height: 1.2;
|
||||
font-weight: 900;
|
||||
}
|
||||
.sub {
|
||||
margin-top: 8px;
|
||||
color: #667085;
|
||||
font-size: 13px;
|
||||
line-height: 1.55;
|
||||
}
|
||||
.avatar-grid {
|
||||
width: 58px;
|
||||
height: 58px;
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: 3px;
|
||||
flex: 0 0 auto;
|
||||
}
|
||||
.avatar-grid img,
|
||||
.avatar {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
border-radius: 50%;
|
||||
object-fit: cover;
|
||||
}
|
||||
.hero-headline {
|
||||
margin-top: 14px;
|
||||
padding: 14px;
|
||||
border-radius: 16px;
|
||||
background: linear-gradient(135deg, #edf9f1 0%, #f7fbf8 100%);
|
||||
}
|
||||
.hero-headline b {
|
||||
display: block;
|
||||
font-size: 17px;
|
||||
color: #076c39;
|
||||
}
|
||||
.hero-headline p {
|
||||
margin: 8px 0 0;
|
||||
font-size: 13px;
|
||||
line-height: 1.65;
|
||||
color: #1f2933;
|
||||
}
|
||||
.hero-inline-notes {
|
||||
display: grid;
|
||||
gap: 8px;
|
||||
margin-top: 10px;
|
||||
}
|
||||
.hero-note,
|
||||
.hero-status {
|
||||
padding: 10px 12px;
|
||||
border-radius: 12px;
|
||||
font-size: 12px;
|
||||
line-height: 1.5;
|
||||
}
|
||||
.hero-status {
|
||||
margin-top: 10px;
|
||||
background: #f7faf9;
|
||||
color: #076c39;
|
||||
font-weight: 700;
|
||||
}
|
||||
.hero-note.takeaway {
|
||||
background: #eef8f2;
|
||||
color: #076c39;
|
||||
}
|
||||
.hero-note.pending {
|
||||
background: #fff8e8;
|
||||
color: #8a5a00;
|
||||
}
|
||||
.stats {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(4, 1fr);
|
||||
gap: 8px;
|
||||
margin-top: 16px;
|
||||
}
|
||||
.stat {
|
||||
background: #f7faf9;
|
||||
border-radius: 12px;
|
||||
padding: 10px 6px;
|
||||
text-align: center;
|
||||
}
|
||||
.stat b {
|
||||
display: block;
|
||||
font-size: 18px;
|
||||
color: #07a352;
|
||||
line-height: 1.25;
|
||||
}
|
||||
.stat span {
|
||||
font-size: 11px;
|
||||
color: #667085;
|
||||
}
|
||||
.section {
|
||||
margin-top: 18px;
|
||||
padding: 18px;
|
||||
}
|
||||
.section-title {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
margin-bottom: 14px;
|
||||
font-size: 19px;
|
||||
font-weight: 900;
|
||||
}
|
||||
.section-title::before {
|
||||
content: '';
|
||||
width: 5px;
|
||||
height: 20px;
|
||||
border-radius: 99px;
|
||||
background: #07c160;
|
||||
}
|
||||
.section-subtitle {
|
||||
margin: 10px 0 6px;
|
||||
color: #667085;
|
||||
font-size: 12px;
|
||||
font-weight: 700;
|
||||
}
|
||||
.section-more {
|
||||
margin-top: 10px;
|
||||
color: #98a2b3;
|
||||
font-size: 11px;
|
||||
text-align: right;
|
||||
}
|
||||
.card {
|
||||
padding: 14px;
|
||||
margin-top: 10px;
|
||||
border: 1px solid #edf0f2;
|
||||
box-shadow: none;
|
||||
}
|
||||
.topic-title-row {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
gap: 8px;
|
||||
}
|
||||
.topic-title-row h3 {
|
||||
margin: 0;
|
||||
font-size: 16px;
|
||||
line-height: 1.35;
|
||||
font-weight: 850;
|
||||
}
|
||||
.heat,
|
||||
.tag {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
padding: 4px 8px;
|
||||
border-radius: 999px;
|
||||
background: #eef8f2;
|
||||
color: #07a352;
|
||||
font-size: 11px;
|
||||
font-weight: 800;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.hot {
|
||||
background: #fff4e5;
|
||||
color: #d46b08;
|
||||
}
|
||||
.blue {
|
||||
background: #eef5ff;
|
||||
color: #1677ff;
|
||||
}
|
||||
.topic-meta {
|
||||
margin-top: 6px;
|
||||
color: #8a94a6;
|
||||
font-size: 12px;
|
||||
}
|
||||
.card p {
|
||||
margin: 10px 0 0;
|
||||
font-size: 13px;
|
||||
line-height: 1.65;
|
||||
}
|
||||
.topic-conclusions {
|
||||
display: grid;
|
||||
gap: 8px;
|
||||
margin-top: 10px;
|
||||
}
|
||||
.topic-conclusion {
|
||||
padding: 8px 10px;
|
||||
border-radius: 10px;
|
||||
background: #edf9f1;
|
||||
color: #076c39;
|
||||
font-size: 12px;
|
||||
line-height: 1.5;
|
||||
font-weight: 700;
|
||||
}
|
||||
.topic-inline-image {
|
||||
display: grid;
|
||||
grid-template-columns: 76px 1fr;
|
||||
gap: 10px;
|
||||
margin-top: 10px;
|
||||
padding: 10px;
|
||||
border-radius: 12px;
|
||||
background: #f7faf9;
|
||||
}
|
||||
.topic-inline-image img {
|
||||
width: 76px;
|
||||
height: 76px;
|
||||
border-radius: 10px;
|
||||
object-fit: cover;
|
||||
}
|
||||
.participants {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
margin-top: 10px;
|
||||
}
|
||||
.person-chip {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 5px;
|
||||
background: #f6f8fa;
|
||||
border-radius: 999px;
|
||||
padding: 3px 8px 3px 3px;
|
||||
}
|
||||
.person-chip img {
|
||||
width: 24px;
|
||||
height: 24px;
|
||||
border-radius: 50%;
|
||||
}
|
||||
.person-chip b {
|
||||
max-width: 58px;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
font-size: 11px;
|
||||
}
|
||||
.keywords {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 6px;
|
||||
margin-top: 10px;
|
||||
}
|
||||
.keywords span {
|
||||
font-size: 11px;
|
||||
padding: 4px 8px;
|
||||
border-radius: 999px;
|
||||
background: #f2f4f7;
|
||||
color: #667085;
|
||||
}
|
||||
.important-card {
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
background: #f7faf9;
|
||||
border-radius: 14px;
|
||||
padding: 12px;
|
||||
margin-top: 10px;
|
||||
}
|
||||
.important-card > .avatar {
|
||||
width: 36px;
|
||||
height: 36px;
|
||||
flex: 0 0 auto;
|
||||
}
|
||||
.important-meta {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
gap: 8px;
|
||||
font-size: 12px;
|
||||
color: #667085;
|
||||
}
|
||||
.important-meta b {
|
||||
color: #1f2933;
|
||||
}
|
||||
.important-text {
|
||||
margin-top: 5px;
|
||||
font-size: 13px;
|
||||
line-height: 1.55;
|
||||
}
|
||||
.important-note {
|
||||
margin-top: 8px;
|
||||
padding: 7px 9px;
|
||||
border-left: 3px solid #07c160;
|
||||
background: #fff;
|
||||
border-radius: 8px;
|
||||
color: #07a352;
|
||||
font-size: 12px;
|
||||
line-height: 1.45;
|
||||
}
|
||||
.action-grid {
|
||||
display: grid;
|
||||
gap: 10px;
|
||||
}
|
||||
.action-card {
|
||||
border-radius: 14px;
|
||||
padding: 12px;
|
||||
}
|
||||
.todo-card {
|
||||
background: #eef5ff;
|
||||
}
|
||||
.unresolved-card {
|
||||
background: #fff8e8;
|
||||
}
|
||||
.action-card b {
|
||||
display: block;
|
||||
color: #1f2933;
|
||||
font-size: 14px;
|
||||
}
|
||||
.action-card div {
|
||||
margin-top: 6px;
|
||||
font-size: 12px;
|
||||
line-height: 1.55;
|
||||
color: #485465;
|
||||
}
|
||||
.action-note {
|
||||
color: #667085;
|
||||
}
|
||||
.chat-block {
|
||||
background: #f0f2f5;
|
||||
border-radius: 14px;
|
||||
padding: 12px;
|
||||
margin-top: 10px;
|
||||
}
|
||||
.chat-msg {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
margin-top: 8px;
|
||||
}
|
||||
.chat-avatar {
|
||||
width: 32px;
|
||||
height: 32px;
|
||||
border-radius: 50%;
|
||||
object-fit: cover;
|
||||
}
|
||||
.chat-name {
|
||||
font-size: 11px;
|
||||
color: #667085;
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
.chat-bubble {
|
||||
background: #fff;
|
||||
border-radius: 4px 12px 12px 12px;
|
||||
padding: 9px 10px;
|
||||
font-size: 13px;
|
||||
line-height: 1.5;
|
||||
}
|
||||
.quote-note {
|
||||
margin-top: 10px;
|
||||
padding: 9px 10px;
|
||||
border-radius: 10px;
|
||||
background: #fff8e1;
|
||||
color: #8a5a00;
|
||||
font-size: 12px;
|
||||
line-height: 1.5;
|
||||
}
|
||||
.qa-card,
|
||||
.resource {
|
||||
margin-top: 10px;
|
||||
padding: 12px;
|
||||
border-radius: 14px;
|
||||
background: #f8fafc;
|
||||
}
|
||||
.qa-card b,
|
||||
.resource b {
|
||||
display: block;
|
||||
color: #1f2933;
|
||||
margin-bottom: 5px;
|
||||
}
|
||||
.qa-card div,
|
||||
.resource {
|
||||
font-size: 13px;
|
||||
line-height: 1.55;
|
||||
color: #485465;
|
||||
}
|
||||
.storyline-card,
|
||||
.chain-card {
|
||||
background: #f8fafc;
|
||||
}
|
||||
.storyline-steps {
|
||||
display: grid;
|
||||
gap: 8px;
|
||||
margin-top: 10px;
|
||||
}
|
||||
.storyline-step {
|
||||
display: grid;
|
||||
grid-template-columns: 50px 1fr;
|
||||
gap: 10px;
|
||||
}
|
||||
.storyline-step span {
|
||||
color: #8a94a6;
|
||||
font-size: 12px;
|
||||
}
|
||||
.storyline-step b {
|
||||
font-size: 13px;
|
||||
line-height: 1.5;
|
||||
}
|
||||
.chain-flow {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 6px;
|
||||
align-items: center;
|
||||
margin-top: 10px;
|
||||
}
|
||||
.chain-flow span {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
padding: 6px 9px;
|
||||
border-radius: 999px;
|
||||
background: #eef8f2;
|
||||
color: #076c39;
|
||||
font-size: 12px;
|
||||
font-weight: 700;
|
||||
}
|
||||
.chain-flow i {
|
||||
font-style: normal;
|
||||
color: #98a2b3;
|
||||
}
|
||||
.gallery-card {
|
||||
display: grid;
|
||||
grid-template-columns: 112px 1fr;
|
||||
gap: 12px;
|
||||
margin-top: 10px;
|
||||
padding: 12px;
|
||||
background: #f7faf9;
|
||||
border-radius: 14px;
|
||||
}
|
||||
.gallery-image {
|
||||
width: 112px;
|
||||
height: 112px;
|
||||
border-radius: 12px;
|
||||
object-fit: cover;
|
||||
background: #e5e7eb;
|
||||
}
|
||||
.gallery-stats {
|
||||
display: inline-flex;
|
||||
margin-top: 7px;
|
||||
padding: 4px 8px;
|
||||
border-radius: 999px;
|
||||
background: #eef5ff;
|
||||
color: #1677ff;
|
||||
font-size: 11px;
|
||||
font-weight: 700;
|
||||
}
|
||||
.badge-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
gap: 10px;
|
||||
}
|
||||
/* AI 图片识别板块 */
|
||||
.vision-card {
|
||||
display: grid;
|
||||
grid-template-columns: 132px 1fr;
|
||||
gap: 14px;
|
||||
margin-top: 10px;
|
||||
padding: 12px;
|
||||
background: linear-gradient(135deg, #edf9f1 0%, #f7fbf8 100%);
|
||||
border: 1px solid #d6efde;
|
||||
border-radius: 14px;
|
||||
}
|
||||
.vision-image {
|
||||
width: 132px;
|
||||
height: 132px;
|
||||
border-radius: 12px;
|
||||
object-fit: cover;
|
||||
background: #e5e7eb;
|
||||
}
|
||||
.vision-description {
|
||||
margin-top: 6px;
|
||||
font-size: 13px;
|
||||
line-height: 1.5;
|
||||
color: #1f2933;
|
||||
}
|
||||
.vision-ocr {
|
||||
margin-top: 6px;
|
||||
padding: 6px 10px;
|
||||
background: #eef5ff;
|
||||
color: #1677ff;
|
||||
font-size: 11px;
|
||||
border-radius: 8px;
|
||||
word-break: break-all;
|
||||
}
|
||||
.vision-tags {
|
||||
margin-top: 8px;
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 4px;
|
||||
}
|
||||
.vision-tag {
|
||||
display: inline-block;
|
||||
padding: 3px 8px;
|
||||
background: #07c160;
|
||||
color: #fff;
|
||||
font-size: 10px;
|
||||
font-weight: 700;
|
||||
border-radius: 999px;
|
||||
}
|
||||
.vision-label {
|
||||
margin-top: 6px;
|
||||
font-size: 10px;
|
||||
color: #07a352;
|
||||
font-weight: 600;
|
||||
}
|
||||
.badge-card {
|
||||
background: linear-gradient(180deg, #fdfdfd 0%, #f6fbf8 100%);
|
||||
border: 1px solid #edf0f2;
|
||||
border-radius: 14px;
|
||||
padding: 12px;
|
||||
}
|
||||
.badge-card b {
|
||||
display: block;
|
||||
margin-top: 8px;
|
||||
font-size: 15px;
|
||||
}
|
||||
.badge-card p {
|
||||
margin: 8px 0 0;
|
||||
font-size: 12px;
|
||||
line-height: 1.55;
|
||||
}
|
||||
.data-grid {
|
||||
display: grid;
|
||||
gap: 12px;
|
||||
}
|
||||
.rank {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 9px;
|
||||
padding: 9px 0;
|
||||
border-bottom: 1px solid #eef0f2;
|
||||
}
|
||||
.rank:last-child {
|
||||
border-bottom: none;
|
||||
}
|
||||
.rank img {
|
||||
width: 30px;
|
||||
height: 30px;
|
||||
border-radius: 50%;
|
||||
object-fit: cover;
|
||||
}
|
||||
.rank b {
|
||||
font-size: 13px;
|
||||
}
|
||||
.rank span {
|
||||
margin-left: auto;
|
||||
color: #8a94a6;
|
||||
font-size: 12px;
|
||||
}
|
||||
.cloud-tags {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
}
|
||||
.cloud-tags span {
|
||||
padding: 6px 10px;
|
||||
border-radius: 999px;
|
||||
background: #f2f4f7;
|
||||
color: #485465;
|
||||
font-weight: 800;
|
||||
}
|
||||
.cloud-tags .xl {
|
||||
font-size: 20px;
|
||||
color: #07a352;
|
||||
background: #e9f8ef;
|
||||
}
|
||||
.cloud-tags .lg {
|
||||
font-size: 17px;
|
||||
color: #1677ff;
|
||||
background: #eef5ff;
|
||||
}
|
||||
.cloud-tags .md {
|
||||
font-size: 15px;
|
||||
color: #d46b08;
|
||||
background: #fff4e5;
|
||||
}
|
||||
.footer {
|
||||
padding: 16px 4px 0;
|
||||
color: #98a2b3;
|
||||
text-align: center;
|
||||
font-size: 11px;
|
||||
line-height: 1.8;
|
||||
}
|
||||
.muted {
|
||||
color: #8a94a6;
|
||||
}
|
||||
.empty-section {
|
||||
display: none !important;
|
||||
}
|
||||
.compact .report {
|
||||
padding-top: 18px;
|
||||
}
|
||||
.compact .section {
|
||||
margin-top: 12px;
|
||||
padding: 14px;
|
||||
}
|
||||
.compact .card {
|
||||
padding: 11px;
|
||||
}
|
||||
.compact .important-card,
|
||||
.compact .gallery-card,
|
||||
.compact .chat-block {
|
||||
padding: 10px;
|
||||
}
|
||||
.compact .section-title {
|
||||
margin-bottom: 9px;
|
||||
font-size: 17px;
|
||||
}
|
||||
.compact .hero-headline p,
|
||||
.compact .card p,
|
||||
.compact .important-text,
|
||||
.compact .chat-bubble {
|
||||
line-height: 1.5;
|
||||
}
|
||||
.compact .participants,
|
||||
.compact .keywords,
|
||||
.compact .hero-inline-notes {
|
||||
gap: 6px;
|
||||
}
|
||||
.compact .topic-conclusions {
|
||||
gap: 6px;
|
||||
}
|
||||
.compact .topic-inline-image {
|
||||
grid-template-columns: 64px 1fr;
|
||||
padding: 8px;
|
||||
}
|
||||
.compact .topic-inline-image img {
|
||||
width: 64px;
|
||||
height: 64px;
|
||||
}
|
||||
.compact .stats {
|
||||
gap: 6px;
|
||||
margin-top: 14px;
|
||||
}
|
||||
.compact .stat {
|
||||
padding: 8px 6px;
|
||||
}
|
||||
.compact .stat b {
|
||||
font-size: 17px;
|
||||
}
|
||||
@media (max-width: 430px) {
|
||||
html,
|
||||
body {
|
||||
width: 100%;
|
||||
}
|
||||
.report {
|
||||
width: 100%;
|
||||
padding-left: 12px;
|
||||
padding-right: 12px;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body class="{{REPORT_MODE_CLASS}}">
|
||||
<main class="report">
|
||||
<header class="hero">
|
||||
<div class="hero-top">
|
||||
<div>
|
||||
<h1>{{GROUP_NAME}}日报</h1>
|
||||
<div class="sub">{{DATE_RANGE}}<br />{{RECORD_NOTE}}</div>
|
||||
</div>
|
||||
<div class="avatar-grid">{{HERO_AVATARS}}</div>
|
||||
</div>
|
||||
<div class="hero-headline">
|
||||
<b>{{HERO_HEADLINE}}</b>
|
||||
<p>{{HERO_SUMMARY}}</p>
|
||||
</div>
|
||||
<div class="hero-status {{HERO_STATUS_EMPTY_CLASS}}">{{HERO_STATUS_LINE}}</div>
|
||||
<div class="hero-inline-notes">
|
||||
<div class="hero-note takeaway {{HERO_TAKEAWAY_EMPTY_CLASS}}">{{HERO_TAKEAWAY}}</div>
|
||||
<div class="hero-note pending {{HERO_PENDING_EMPTY_CLASS}}">{{HERO_PENDING}}</div>
|
||||
</div>
|
||||
<div class="stats">
|
||||
<div class="stat"><b>{{MESSAGE_COUNT}}</b><span>消息数</span></div>
|
||||
<div class="stat"><b>{{ACTIVE_USERS}}</b><span>活跃人数</span></div>
|
||||
<div class="stat"><b>{{TOPIC_COUNT}}</b><span>话题数</span></div>
|
||||
<div class="stat"><b>{{MEDIA_COUNT}}</b><span>媒体消息</span></div>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<section class="section {{TOPICS_EMPTY_CLASS}}">
|
||||
<div class="section-title">今日讨论热点</div>
|
||||
{{TOPIC_CARDS}}
|
||||
{{TOPICS_MORE_NOTE}}
|
||||
</section>
|
||||
|
||||
<section class="section {{MESSAGES_EMPTY_CLASS}}">
|
||||
<div class="section-title">重要消息</div>
|
||||
{{IMPORTANT_MESSAGES}}
|
||||
{{MESSAGES_MORE_NOTE}}
|
||||
</section>
|
||||
|
||||
<section class="section {{ACTIONS_EMPTY_CLASS}}">
|
||||
<div class="section-title">待办事项和未解决问题</div>
|
||||
<div class="section-subtitle {{TODO_EMPTY_CLASS}}">待办事项</div>
|
||||
<div class="action-grid {{TODO_EMPTY_CLASS}}">{{TODO_CARDS}}</div>
|
||||
<div class="section-subtitle {{UNRESOLVED_EMPTY_CLASS}}">尚未解决</div>
|
||||
<div class="action-grid {{UNRESOLVED_EMPTY_CLASS}}">{{UNRESOLVED_CARDS}}</div>
|
||||
{{ACTIONS_MORE_NOTE}}
|
||||
</section>
|
||||
|
||||
<section class="section {{QUOTES_EMPTY_CLASS}}">
|
||||
<div class="section-title">今日名场面</div>
|
||||
{{QUOTE_BLOCKS}}
|
||||
{{QUOTES_MORE_NOTE}}
|
||||
</section>
|
||||
|
||||
<section class="section {{ANALYTICS_EMPTY_CLASS}}">
|
||||
<div class="section-title">今日群数据</div>
|
||||
<div class="data-grid">
|
||||
<div class="card">
|
||||
<div class="muted" style="font-size: 12px; margin-bottom: 6px">话唠榜 TOP5</div>
|
||||
{{RANK_ITEMS}}
|
||||
</div>
|
||||
<div class="card">
|
||||
<p><b>最活跃时段:</b>{{ACTIVITY_TIMELINE}}</p>
|
||||
<p><b>今日状态:</b>形成 {{CONCLUSION_COUNT}} 个结论,待办 {{TODO_COUNT}} 项,未解决 {{UNRESOLVED_COUNT}} 项。</p>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="section {{KEYWORDS_EMPTY_CLASS}}">
|
||||
<div class="section-title">关键词</div>
|
||||
<div class="cloud-tags">{{CLOUD_TAGS}}</div>
|
||||
{{KEYWORDS_MORE_NOTE}}
|
||||
</section>
|
||||
|
||||
<section class="section {{RESOURCES_EMPTY_CLASS}}">
|
||||
<div class="section-title">实用信息与资源</div>
|
||||
{{RESOURCE_ITEMS}}
|
||||
{{RESOURCES_MORE_NOTE}}
|
||||
</section>
|
||||
|
||||
<section class="section {{QA_EMPTY_CLASS}}">
|
||||
<div class="section-title">问题与解答</div>
|
||||
{{QA_CARDS}}
|
||||
{{QA_MORE_NOTE}}
|
||||
</section>
|
||||
|
||||
<section class="section {{STORYLINES_EMPTY_CLASS}}">
|
||||
<div class="section-title">今日剧情时间线</div>
|
||||
{{STORYLINE_CARDS}}
|
||||
{{STORYLINES_MORE_NOTE}}
|
||||
</section>
|
||||
|
||||
<section class="section {{REVERSALS_EMPTY_CLASS}}">
|
||||
<div class="section-title">群聊反转现场</div>
|
||||
{{REVERSAL_CARDS}}
|
||||
{{REVERSALS_MORE_NOTE}}
|
||||
</section>
|
||||
|
||||
<section class="section {{VISION_EMPTY_CLASS}}">
|
||||
<div class="section-title">{{VISION_TITLE}}</div>
|
||||
{{VISION_CARDS}}
|
||||
</section>
|
||||
|
||||
<section class="section {{GALLERY_EMPTY_CLASS}}">
|
||||
<div class="section-title">今日群相册</div>
|
||||
{{GALLERY_CARDS}}
|
||||
{{GALLERY_MORE_NOTE}}
|
||||
</section>
|
||||
|
||||
<section class="section {{VOICE_EMPTY_CLASS}}">
|
||||
<div class="section-title">语音之最</div>
|
||||
{{VOICE_CARDS}}
|
||||
{{VOICE_MORE_NOTE}}
|
||||
</section>
|
||||
|
||||
<section class="section {{VOICE_RANK_EMPTY_CLASS}}">
|
||||
<div class="section-title">语音时长榜</div>
|
||||
<div class="card">{{VOICE_RANK_CARDS}}</div>
|
||||
</section>
|
||||
|
||||
<section class="section {{BADGES_EMPTY_CLASS}}">
|
||||
<div class="section-title">今日临时人设</div>
|
||||
<div class="badge-grid">{{BADGE_CARDS}}</div>
|
||||
{{BADGES_MORE_NOTE}}
|
||||
</section>
|
||||
|
||||
<section class="section {{CHAINS_EMPTY_CLASS}}">
|
||||
<div class="section-title">话题参与链路</div>
|
||||
{{CHAIN_CARDS}}
|
||||
{{CHAINS_MORE_NOTE}}
|
||||
</section>
|
||||
|
||||
<footer class="footer">
|
||||
数据来源:WechatExplorer · 微信群聊记录<br />
|
||||
生成时间:{{GENERATED_AT}}<br />
|
||||
{{FOOTER_NOTE}}
|
||||
</footer>
|
||||
</main>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,13 @@
|
||||
const fs = require('node:fs')
|
||||
const path = require('node:path')
|
||||
|
||||
const root = path.resolve(__dirname, '..')
|
||||
const source = path.join(root, '.env.example')
|
||||
const target = path.join(root, '.env')
|
||||
|
||||
if (!fs.existsSync(source) || fs.existsSync(target)) {
|
||||
process.exit(0)
|
||||
}
|
||||
|
||||
fs.copyFileSync(source, target)
|
||||
console.log('[ensure-env] created .env from .env.example')
|
||||
@@ -0,0 +1,48 @@
|
||||
const fs = require('node:fs')
|
||||
const path = require('node:path')
|
||||
|
||||
const runtimeNames = [
|
||||
'msvcp140.dll',
|
||||
'msvcp140_1.dll',
|
||||
'vcruntime140.dll',
|
||||
'vcruntime140_1.dll'
|
||||
]
|
||||
|
||||
function copyIfDifferent(sourcePath, targetPath) {
|
||||
const source = fs.statSync(sourcePath)
|
||||
const targetExists = fs.existsSync(targetPath)
|
||||
|
||||
if (targetExists) {
|
||||
const target = fs.statSync(targetPath)
|
||||
if (target.size === source.size && target.mtimeMs >= source.mtimeMs) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
fs.copyFileSync(sourcePath, targetPath)
|
||||
return true
|
||||
}
|
||||
|
||||
function main() {
|
||||
if (process.platform !== 'win32') return
|
||||
|
||||
const projectRoot = path.resolve(__dirname, '..')
|
||||
const sourceDir = path.join(projectRoot, 'resources', 'runtime', 'win32')
|
||||
const targetDir = path.join(projectRoot, 'node_modules', 'electron', 'dist')
|
||||
|
||||
if (!fs.existsSync(sourceDir) || !fs.existsSync(targetDir)) return
|
||||
|
||||
let copiedCount = 0
|
||||
for (const name of runtimeNames) {
|
||||
const sourcePath = path.join(sourceDir, name)
|
||||
const targetPath = path.join(targetDir, name)
|
||||
if (!fs.existsSync(sourcePath)) continue
|
||||
if (copyIfDifferent(sourcePath, targetPath)) copiedCount += 1
|
||||
}
|
||||
|
||||
if (copiedCount > 0) {
|
||||
console.log(`[prepare-electron-runtime] synced ${copiedCount} runtime DLL(s) to ${targetDir}`)
|
||||
}
|
||||
}
|
||||
|
||||
main()
|
||||
@@ -0,0 +1,409 @@
|
||||
import { app, BrowserWindow } from 'electron'
|
||||
import fs from 'fs-extra'
|
||||
import path from 'path'
|
||||
import os from 'os'
|
||||
import { fileURLToPath } from 'url'
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url))
|
||||
const root = path.resolve(__dirname, '..')
|
||||
const templatePath = path.join(root, 'resources', 'mobile_daily_report.html')
|
||||
const outputDir = path.join(os.tmpdir(), 'wechatexplorer-report-fixtures')
|
||||
|
||||
const escapeHtml = (value) =>
|
||||
String(value ?? '')
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, ''')
|
||||
|
||||
const replacePlaceholder = (html, key, value) => html.replaceAll(`{{${key}}}`, value)
|
||||
|
||||
const avatarSvg = (label, color) =>
|
||||
`data:image/svg+xml;base64,${Buffer.from(
|
||||
`<svg xmlns="http://www.w3.org/2000/svg" width="96" height="96"><rect width="96" height="96" rx="18" fill="${color}"/><text x="48" y="58" text-anchor="middle" font-family="PingFang SC, sans-serif" font-size="36" fill="#0f172a">${label}</text></svg>`
|
||||
).toString('base64')}`
|
||||
|
||||
const localImagePath = '/Users/Wxw_/Library/Containers/com.tencent.xinWeChat/Data/Documents/xwechat_files/a969409112_d784/temp/RWTemp/2026-07/94ce24699a5a1d539c00a37ec8ace755.png'
|
||||
const sampleImage = fs.existsSync(localImagePath)
|
||||
? `data:image/png;base64,${fs.readFileSync(localImagePath).toString('base64')}`
|
||||
: avatarSvg('图', '#dbeafe')
|
||||
|
||||
const avatars = {
|
||||
阿宇: avatarSvg('宇', '#dcfce7'),
|
||||
老周: avatarSvg('周', '#e0f2fe'),
|
||||
小李: avatarSvg('李', '#fef3c7'),
|
||||
'we water': avatarSvg('W', '#ede9fe'),
|
||||
佩佩: avatarSvg('佩', '#fee2e2')
|
||||
}
|
||||
|
||||
const heroNames = ['阿宇', '老周', '小李', 'we water']
|
||||
const heroAvatars = heroNames
|
||||
.map((name) => `<img src="${avatars[name]}" alt="${name}">`)
|
||||
.join('')
|
||||
|
||||
const compactRequest = {
|
||||
metadata: {
|
||||
groupName: '技术交流',
|
||||
reportDate: '2026-07-10',
|
||||
dateRange: '2026-07-10 09:12-19:48',
|
||||
messageCount: 382,
|
||||
activeUsers: 47,
|
||||
imageCount: 9,
|
||||
voiceCount: 5,
|
||||
stickerCount: 14,
|
||||
mediaMessageCount: 28,
|
||||
timeSpan: '11 h',
|
||||
generatedAt: '2026-07-10 22:18',
|
||||
recordNote: '基于示例数据生成的精简版日报',
|
||||
footerNote: '精简版默认面向长图转发;无内容模块自动隐藏。',
|
||||
heroParticipants: heroNames,
|
||||
avatars,
|
||||
reportMode: 'compact'
|
||||
},
|
||||
report: {
|
||||
hero: {
|
||||
headline: '接口排查和版本升级是今天主线',
|
||||
summary: '白天主要围绕接口异常、升级节奏和上线安排展开,结论比争论更多,待跟进事项也比较集中。',
|
||||
keyTakeaway: '大家确认本次异常更像缓存与配置问题,而不是服务端挂掉。',
|
||||
pendingNote: '测试环境接口文档和回滚方案仍需补齐。',
|
||||
statusLine: '今日形成 3 个结论 · 2 个待办 · 1 个问题尚未解决'
|
||||
},
|
||||
summaryStats: {
|
||||
messageCount: 382,
|
||||
activeUsers: 47,
|
||||
topicCount: 4,
|
||||
mediaCount: 28,
|
||||
imageCount: 9,
|
||||
voiceCount: 5,
|
||||
stickerCount: 14,
|
||||
conclusionCount: 3,
|
||||
todoCount: 2,
|
||||
unresolvedCount: 1
|
||||
},
|
||||
sectionMeta: {
|
||||
hero: { enabled: true, importance: 1, confidence: 0.95, totalCount: 1, displayedCount: 1 },
|
||||
topics: { enabled: true, importance: 0.98, confidence: 0.86, totalCount: 6, displayedCount: 3, hiddenCount: 3 },
|
||||
importantMessages: { enabled: true, importance: 0.95, confidence: 0.84, totalCount: 6, displayedCount: 3, hiddenCount: 3 },
|
||||
actions: { enabled: true, importance: 0.97, confidence: 0.81, totalCount: 5, displayedCount: 3, hiddenCount: 2 },
|
||||
moments: { enabled: true, importance: 0.75, confidence: 0.75, totalCount: 3, displayedCount: 1, hiddenCount: 2 },
|
||||
analytics: { enabled: true, importance: 0.8, confidence: 0.95, totalCount: 1, displayedCount: 1 },
|
||||
keywords: { enabled: true, importance: 0.68, confidence: 0.92, totalCount: 16, displayedCount: 12, hiddenCount: 4 }
|
||||
},
|
||||
topics: [
|
||||
{
|
||||
title: 'GPT 接口异常排查',
|
||||
timeRange: '09:20-11:05',
|
||||
heat: '高',
|
||||
summary: '上午先从接口超时和返回结构异常入手,几轮排查后,大家逐步把问题收敛到缓存与环境配置,而不是后端服务不可用。',
|
||||
conclusions: [
|
||||
{ text: '接口本身可用,异常更像本地缓存与环境变量冲突。' },
|
||||
{ text: '先清缓存再复测,避免把旧响应误判成线上事故。' }
|
||||
],
|
||||
participants: ['阿宇', '老周', '小李'],
|
||||
keywords: ['接口', '缓存', '环境变量'],
|
||||
image: {
|
||||
imageUrl: sampleImage,
|
||||
note: '该图片引发 12 条回复。根据图片前后对话推断,这是一张帮助定位问题的截图。'
|
||||
}
|
||||
},
|
||||
{
|
||||
title: '版本升级节奏',
|
||||
timeRange: '11:40-12:20',
|
||||
heat: '中',
|
||||
summary: '关于 React 版本是否立刻升级,讨论从“能不能升”转成“这周值不值得升”,最终倾向先补兼容性清单再动。',
|
||||
conclusions: [{ text: '先列旧组件兼容清单,再决定升级窗口。' }],
|
||||
participants: ['阿宇', 'we water', '佩佩'],
|
||||
keywords: ['React', '升级', '兼容性']
|
||||
},
|
||||
{
|
||||
title: '上线节奏与回滚准备',
|
||||
timeRange: '15:10-16:05',
|
||||
heat: '中',
|
||||
summary: '下午讨论上线方案时,大家更关注回滚准备是否充分,最后把重点放在文档、监控和回滚路径补齐上。',
|
||||
conclusions: [{ text: '上线前需要补一版简短回滚说明。' }],
|
||||
participants: ['老周', '小李'],
|
||||
keywords: ['上线', '回滚', '监控']
|
||||
},
|
||||
],
|
||||
importantMessages: [
|
||||
{ sender: '阿宇', time: '10:41', content: '先别回滚,接口能通。', note: '稳定了排查方向。' },
|
||||
{ sender: '老周', time: '11:02', content: '像是缓存没清掉。', note: '把问题从服务端收敛到本地环境。' },
|
||||
{ sender: '小李', time: '15:36', content: '上线前把回滚文档补一下。', note: '明确形成待办。' }
|
||||
],
|
||||
todos: [
|
||||
{ task: '补测试环境接口文档', owner: '小李', topic: 'GPT 接口异常排查', note: '方便明天复测。' },
|
||||
{ task: '整理回滚说明', owner: '老周', deadline: '今晚', topic: '上线节奏与回滚准备' }
|
||||
],
|
||||
unresolved: [
|
||||
{ question: '缓存问题的根因是不是插件残留?', owner: '阿宇', status: '待跟进', lastDiscussedAt: '18:26', note: '目前只有推断,还没有最终证据。' }
|
||||
],
|
||||
quotes: [
|
||||
{
|
||||
messages: [
|
||||
{ sender: '阿宇', content: '我以为接口炸了。' },
|
||||
{ sender: '老周', content: '先别慌,先清缓存。' },
|
||||
{ sender: '小李', content: '清完它居然真好了。' }
|
||||
],
|
||||
note: '从“要不要回滚”迅速切到“先做最小验证”,很像今天的群聊节奏。'
|
||||
}
|
||||
],
|
||||
analytics: {
|
||||
topSpeakers: [
|
||||
{ name: '阿宇', count: 112 },
|
||||
{ name: '老周', count: 78 },
|
||||
{ name: '小李', count: 61 },
|
||||
{ name: 'we water', count: 49 },
|
||||
{ name: '佩佩', count: 33 }
|
||||
],
|
||||
activeTimeline: '09:00-09:59、10:00-10:59、15:00-15:59',
|
||||
voiceLeaderboard: []
|
||||
},
|
||||
keywords: ['GPT', '接口', '缓存', '升级', '上线', '回滚', '监控', '兼容性', '截图', '文档', '测试环境', '复测'],
|
||||
media: {
|
||||
gallery: [],
|
||||
voiceHighlights: [],
|
||||
funBadges: []
|
||||
},
|
||||
resources: [],
|
||||
qa: [],
|
||||
storylines: [],
|
||||
reversals: [],
|
||||
participantChains: []
|
||||
}
|
||||
}
|
||||
|
||||
const fullRequest = JSON.parse(JSON.stringify(compactRequest))
|
||||
fullRequest.metadata.recordNote = '基于示例数据生成的完整版日报'
|
||||
fullRequest.metadata.reportMode = 'full'
|
||||
fullRequest.report.sectionMeta = {
|
||||
...fullRequest.report.sectionMeta,
|
||||
resources: { enabled: true, importance: 0.58, confidence: 0.76, totalCount: 2, displayedCount: 2 },
|
||||
qa: { enabled: true, importance: 0.62, confidence: 0.8, totalCount: 2, displayedCount: 2 },
|
||||
storylines: { enabled: true, importance: 0.68, confidence: 0.74, totalCount: 2, displayedCount: 2 },
|
||||
reversals: { enabled: true, importance: 0.55, confidence: 0.72, totalCount: 1, displayedCount: 1 },
|
||||
gallery: { enabled: true, importance: 0.64, confidence: 0.82, totalCount: 2, displayedCount: 2 },
|
||||
voices: { enabled: true, importance: 0.6, confidence: 0.83, totalCount: 2, displayedCount: 2 },
|
||||
badges: { enabled: true, importance: 0.45, confidence: 0.68, totalCount: 2, displayedCount: 2 },
|
||||
chains: { enabled: true, importance: 0.58, confidence: 0.72, totalCount: 1, displayedCount: 1 }
|
||||
}
|
||||
fullRequest.report.resources = [
|
||||
{ title: '测试环境接口文档', description: '明天复测会直接用到的说明。', sender: '小李' },
|
||||
{ title: '回滚说明草稿', description: '上线前确认回滚路径与负责人。', sender: '老周' }
|
||||
]
|
||||
fullRequest.report.qa = [
|
||||
{ question: '今晚要不要升级 React?', answer: '先不升级,先补兼容清单。', answerer: 'we water' },
|
||||
{ question: '接口是不是服务端挂了?', answer: '不是,当前更像缓存与环境问题。', answerer: '老周' }
|
||||
]
|
||||
fullRequest.report.storylines = [
|
||||
{
|
||||
title: '接口异常排查线',
|
||||
stages: [
|
||||
{ time: '09:20', event: '阿宇提出接口异常。' },
|
||||
{ time: '09:46', event: '老周建议先清缓存。' },
|
||||
{ time: '10:41', event: '确认接口本身可通。' }
|
||||
],
|
||||
result: '初步定位为缓存与配置冲突。'
|
||||
},
|
||||
{
|
||||
title: '版本升级讨论线',
|
||||
stages: [
|
||||
{ time: '11:40', event: '开始讨论是否本周升级。' },
|
||||
{ time: '12:05', event: '补充兼容性与工期顾虑。' }
|
||||
],
|
||||
result: '今晚不升,先补兼容清单。'
|
||||
}
|
||||
]
|
||||
fullRequest.report.reversals = [
|
||||
{ topic: '接口异常', initialView: '最初以为后端服务不稳定。', finalView: '最终判断更像缓存与配置问题。', note: '多轮验证后,排查方向明显收敛。' }
|
||||
]
|
||||
fullRequest.report.media = {
|
||||
gallery: [
|
||||
{
|
||||
sender: '阿宇',
|
||||
time: '09:52',
|
||||
imageUrl: sampleImage,
|
||||
note: '图片发出后,群里立刻围绕异常现象、返回结构和复现环境展开讨论。',
|
||||
stats: '12 条后续消息 · 6 人接话',
|
||||
inferenceLabel: '基于图片后的聊天上下文推断'
|
||||
},
|
||||
{
|
||||
sender: '佩佩',
|
||||
time: '17:14',
|
||||
imageUrl: sampleImage,
|
||||
note: '第二张图带起一轮轻松但有效的快速确认。',
|
||||
stats: '5 条后续消息 · 3 人接话',
|
||||
inferenceLabel: '基于图片后的聊天上下文推断'
|
||||
}
|
||||
],
|
||||
voiceHighlights: [
|
||||
{ title: '语音输出王', sender: '老周', note: '共发送 3 条语音,累计 97 秒。' },
|
||||
{ title: '连续发言时刻', sender: '阿宇', note: '16:32 连发 2 条语音,共 54 秒。' }
|
||||
],
|
||||
funBadges: [
|
||||
{ title: '高能输出王', owner: '阿宇', note: '今天一共发了 112 条消息。' },
|
||||
{ title: '语音麦霸', owner: '老周', note: '语音总时长位列第一。' }
|
||||
]
|
||||
}
|
||||
fullRequest.report.participantChains = [
|
||||
{ topic: '接口异常排查', chain: ['阿宇 提出', '老周 收敛方向', '小李 验证', 'we water 定结论'], note: '比较典型的一条技术讨论链路。' }
|
||||
]
|
||||
fullRequest.report.analytics.voiceLeaderboard = [
|
||||
{ sender: '老周', count: 3, durationSec: 97 },
|
||||
{ sender: '阿宇', count: 2, durationSec: 54 }
|
||||
]
|
||||
|
||||
async function renderRequest(request, targetBase) {
|
||||
let html = await fs.readFile(templatePath, 'utf8')
|
||||
const report = request.report
|
||||
const metadata = request.metadata
|
||||
const topicCards = report.topics
|
||||
.map((topic) => {
|
||||
const conclusions = (topic.conclusions || [])
|
||||
.slice(0, 2)
|
||||
.map((entry) => `<div class="topic-conclusion">${escapeHtml(entry.text)}</div>`)
|
||||
.join('')
|
||||
const image = topic.image?.imageUrl
|
||||
? `<div class="topic-inline-image"><img src="${topic.image.imageUrl}" alt="热点图片"><div>${escapeHtml(topic.image.note)}</div></div>`
|
||||
: ''
|
||||
return `<div class="card topic-card"><div class="topic-title-row"><h3>${escapeHtml(topic.title)}</h3><span class="heat ${topic.heat === '高' ? 'hot' : topic.heat === '低' ? 'blue' : ''}">${escapeHtml(topic.heat)}热</span></div><div class="topic-meta">${escapeHtml(topic.timeRange)}</div><p>${escapeHtml(topic.summary)}</p>${conclusions ? `<div class="topic-conclusions">${conclusions}</div>` : ''}${image}<div class="participants">${topic.participants.map((name) => `<span class="person-chip"><img src="${avatars[name] || avatarSvg(name[0], '#e5e7eb')}" alt=""><b>${escapeHtml(name)}</b></span>`).join('')}</div><div class="keywords">${topic.keywords.map((word) => `<span>${escapeHtml(word)}</span>`).join('')}</div></div>`
|
||||
})
|
||||
.join('')
|
||||
const importantMessages = report.importantMessages
|
||||
.map((message) => `<div class="important-card"><img class="avatar" src="${avatars[message.sender] || avatarSvg(message.sender[0], '#e5e7eb')}" alt=""><div class="important-body"><div class="important-meta"><b>${escapeHtml(message.sender)}</b><span>${escapeHtml(message.time)}</span></div><div class="important-text">${escapeHtml(message.content)}</div><div class="important-note">${escapeHtml(message.note)}</div></div></div>`)
|
||||
.join('')
|
||||
const todoCards = (report.todos || []).map((item) => `<div class="action-card todo-card"><b>${escapeHtml(item.task)}</b><div>${[item.owner || '', item.deadline || '', item.topic || ''].filter(Boolean).map(escapeHtml).join(' · ')}</div>${item.note ? `<div class="action-note">${escapeHtml(item.note)}</div>` : ''}</div>`).join('')
|
||||
const unresolvedCards = (report.unresolved || []).map((item) => `<div class="action-card unresolved-card"><b>${escapeHtml(item.question)}</b><div>${[item.owner || '', item.lastDiscussedAt || '', item.status].filter(Boolean).map(escapeHtml).join(' · ')}</div><div class="action-note">${escapeHtml(item.note)}</div></div>`).join('')
|
||||
const quoteBlocks = report.quotes.map((quote) => `<div class="chat-block">${quote.messages.map((message) => `<div class="chat-msg"><img class="chat-avatar" src="${avatars[message.sender] || avatarSvg(message.sender[0], '#e5e7eb')}" alt=""><div><div class="chat-name">${escapeHtml(message.sender)}</div><div class="chat-bubble">${escapeHtml(message.content)}</div></div></div>`).join('')}<div class="quote-note">${escapeHtml(quote.note)}</div></div>`).join('')
|
||||
const rankItems = report.analytics.topSpeakers.map((speaker, index) => `<div class="rank"><img src="${avatars[speaker.name] || avatarSvg(speaker.name[0], '#e5e7eb')}" alt=""><b>${index + 1}. ${escapeHtml(speaker.name)}</b><span>${speaker.count} 条</span></div>`).join('')
|
||||
const cloudTags = report.keywords.map((word, index) => `<span class="${index < 2 ? 'xl' : index < 5 ? 'lg' : index < 9 ? 'md' : ''}">${escapeHtml(word)}</span>`).join('')
|
||||
const resourceItems = (report.resources || []).map((resource) => `<div class="resource"><b>${escapeHtml(resource.title)}</b>${resource.sender ? ` · ${escapeHtml(resource.sender)}` : ''}<br>${escapeHtml(resource.description)}</div>`).join('')
|
||||
const qaCards = (report.qa || []).map((item) => `<div class="qa-card"><b>Q:${escapeHtml(item.question)}</b><div>A:${escapeHtml(item.answer)}${item.answerer ? ` — ${escapeHtml(item.answerer)}` : ''}</div></div>`).join('')
|
||||
const storylineCards = (report.storylines || []).map((item) => `<div class="card storyline-card"><div class="topic-title-row"><h3>${escapeHtml(item.title)}</h3></div><div class="storyline-steps">${item.stages.map((stage) => `<div class="storyline-step"><span>${escapeHtml(stage.time)}</span><b>${escapeHtml(stage.event)}</b></div>`).join('')}</div>${item.result ? `<p class="muted">${escapeHtml(item.result)}</p>` : ''}</div>`).join('')
|
||||
const reversalCards = (report.reversals || []).map((item) => `<div class="qa-card"><b>${escapeHtml(item.topic)}</b><div>最初:${escapeHtml(item.initialView)}</div><div>后来:${escapeHtml(item.finalView)}</div>${item.note ? `<div>${escapeHtml(item.note)}</div>` : ''}</div>`).join('')
|
||||
const galleryCards = (report.media.gallery || []).map((item) => `<div class="gallery-card"><img class="gallery-image" src="${item.imageUrl}" alt=""><div class="gallery-body"><div class="important-meta"><b>${escapeHtml(item.sender)}</b><span>${escapeHtml(item.time)}</span></div>${item.stats ? `<div class="gallery-stats">${escapeHtml(item.stats)}</div>` : ''}<div class="important-text">${escapeHtml(item.note)}</div>${item.inferenceLabel ? `<div class="topic-meta">${escapeHtml(item.inferenceLabel)}</div>` : ''}</div></div>`).join('')
|
||||
const voiceCards = (report.media.voiceHighlights || []).map((item) => `<div class="qa-card"><b>${escapeHtml(item.title)} · ${escapeHtml(item.sender)}</b><div>${escapeHtml(item.note)}</div></div>`).join('')
|
||||
const voiceRankCards = (report.analytics.voiceLeaderboard || []).map((item, index) => `<div class="rank"><img src="${avatars[item.sender] || avatarSvg(item.sender[0], '#e5e7eb')}" alt=""><b>${index + 1}. ${escapeHtml(item.sender)}</b><span>${item.count} 条 · ${item.durationSec} 秒</span></div>`).join('')
|
||||
const badgeCards = (report.media.funBadges || []).map((item) => `<div class="badge-card"><span class="tag">${escapeHtml(item.title)}</span><b>${escapeHtml(item.owner)}</b><p>${escapeHtml(item.note)}</p></div>`).join('')
|
||||
const chainCards = (report.participantChains || []).map((item) => `<div class="card chain-card"><div class="topic-title-row"><h3>${escapeHtml(item.topic)}</h3></div><div class="chain-flow">${item.chain.map((node) => `<span>${escapeHtml(node)}</span>`).join('<i>→</i>')}</div>${item.note ? `<p class="muted">${escapeHtml(item.note)}</p>` : ''}</div>`).join('')
|
||||
|
||||
const replaceMap = {
|
||||
REPORT_TITLE: `${metadata.groupName}日报`,
|
||||
REPORT_MODE_CLASS: metadata.reportMode === 'full' ? 'full' : 'compact',
|
||||
GROUP_NAME: metadata.groupName,
|
||||
DATE_RANGE: metadata.dateRange,
|
||||
RECORD_NOTE: metadata.recordNote,
|
||||
REPORT_MODE_LABEL: metadata.reportMode === 'full' ? '完整版' : '精简版',
|
||||
HERO_HEADLINE: report.hero.headline,
|
||||
HERO_SUMMARY: report.hero.summary,
|
||||
HERO_STATUS_LINE: report.hero.statusLine || '',
|
||||
HERO_STATUS_EMPTY_CLASS: report.hero.statusLine ? '' : 'empty-section',
|
||||
HERO_TAKEAWAY: report.hero.keyTakeaway || '',
|
||||
HERO_TAKEAWAY_EMPTY_CLASS: report.hero.keyTakeaway ? '' : 'empty-section',
|
||||
HERO_PENDING: report.hero.pendingNote || '',
|
||||
HERO_PENDING_EMPTY_CLASS: report.hero.pendingNote ? '' : 'empty-section',
|
||||
HERO_AVATARS: heroAvatars,
|
||||
MESSAGE_COUNT: String(report.summaryStats.messageCount),
|
||||
ACTIVE_USERS: String(report.summaryStats.activeUsers),
|
||||
TOPIC_COUNT: String(report.summaryStats.topicCount),
|
||||
MEDIA_COUNT: String(report.summaryStats.mediaCount),
|
||||
TOPICS_EMPTY_CLASS: report.sectionMeta.topics?.enabled ? '' : 'empty-section',
|
||||
TOPIC_CARDS: topicCards,
|
||||
TOPICS_MORE_NOTE: report.sectionMeta.topics?.hiddenCount ? `<div class="section-more">另有 ${report.sectionMeta.topics.hiddenCount} 条内容,请在完整版中查看</div>` : '',
|
||||
MESSAGES_EMPTY_CLASS: report.sectionMeta.importantMessages?.enabled ? '' : 'empty-section',
|
||||
IMPORTANT_MESSAGES: importantMessages,
|
||||
MESSAGES_MORE_NOTE: report.sectionMeta.importantMessages?.hiddenCount ? `<div class="section-more">另有 ${report.sectionMeta.importantMessages.hiddenCount} 条内容,请在完整版中查看</div>` : '',
|
||||
ACTIONS_EMPTY_CLASS: report.sectionMeta.actions?.enabled ? '' : 'empty-section',
|
||||
TODO_EMPTY_CLASS: report.todos.length ? '' : 'empty-section',
|
||||
TODO_CARDS: todoCards,
|
||||
UNRESOLVED_EMPTY_CLASS: report.unresolved.length ? '' : 'empty-section',
|
||||
UNRESOLVED_CARDS: unresolvedCards,
|
||||
ACTIONS_MORE_NOTE: report.sectionMeta.actions?.hiddenCount ? `<div class="section-more">另有 ${report.sectionMeta.actions.hiddenCount} 条内容,请在完整版中查看</div>` : '',
|
||||
QUOTES_EMPTY_CLASS: report.sectionMeta.moments?.enabled ? '' : 'empty-section',
|
||||
QUOTE_BLOCKS: quoteBlocks,
|
||||
QUOTES_MORE_NOTE: report.sectionMeta.moments?.hiddenCount ? `<div class="section-more">另有 ${report.sectionMeta.moments.hiddenCount} 条内容,请在完整版中查看</div>` : '',
|
||||
ANALYTICS_EMPTY_CLASS: '',
|
||||
RANK_ITEMS: rankItems,
|
||||
ACTIVITY_TIMELINE: report.analytics.activeTimeline,
|
||||
CONCLUSION_COUNT: String(report.summaryStats.conclusionCount),
|
||||
TODO_COUNT: String(report.summaryStats.todoCount),
|
||||
UNRESOLVED_COUNT: String(report.summaryStats.unresolvedCount),
|
||||
KEYWORDS_EMPTY_CLASS: report.sectionMeta.keywords?.enabled ? '' : 'empty-section',
|
||||
CLOUD_TAGS: cloudTags,
|
||||
KEYWORDS_MORE_NOTE: report.sectionMeta.keywords?.hiddenCount ? `<div class="section-more">另有 ${report.sectionMeta.keywords.hiddenCount} 个关键词,请在完整版中查看</div>` : '',
|
||||
RESOURCES_EMPTY_CLASS: report.sectionMeta.resources?.enabled ? '' : 'empty-section',
|
||||
RESOURCE_ITEMS: resourceItems,
|
||||
RESOURCES_MORE_NOTE: '',
|
||||
QA_EMPTY_CLASS: report.sectionMeta.qa?.enabled ? '' : 'empty-section',
|
||||
QA_CARDS: qaCards,
|
||||
QA_MORE_NOTE: '',
|
||||
STORYLINES_EMPTY_CLASS: report.sectionMeta.storylines?.enabled ? '' : 'empty-section',
|
||||
STORYLINE_CARDS: storylineCards,
|
||||
STORYLINES_MORE_NOTE: '',
|
||||
REVERSALS_EMPTY_CLASS: report.sectionMeta.reversals?.enabled ? '' : 'empty-section',
|
||||
REVERSAL_CARDS: reversalCards,
|
||||
REVERSALS_MORE_NOTE: '',
|
||||
GALLERY_EMPTY_CLASS: report.sectionMeta.gallery?.enabled ? '' : 'empty-section',
|
||||
GALLERY_CARDS: galleryCards,
|
||||
GALLERY_MORE_NOTE: '',
|
||||
VOICE_EMPTY_CLASS: report.sectionMeta.voices?.enabled ? '' : 'empty-section',
|
||||
VOICE_CARDS: voiceCards,
|
||||
VOICE_MORE_NOTE: '',
|
||||
VOICE_RANK_EMPTY_CLASS: report.sectionMeta.voices?.enabled ? '' : 'empty-section',
|
||||
VOICE_RANK_CARDS: voiceRankCards,
|
||||
BADGES_EMPTY_CLASS: report.sectionMeta.badges?.enabled ? '' : 'empty-section',
|
||||
BADGE_CARDS: badgeCards,
|
||||
BADGES_MORE_NOTE: '',
|
||||
CHAINS_EMPTY_CLASS: report.sectionMeta.chains?.enabled ? '' : 'empty-section',
|
||||
CHAIN_CARDS: chainCards,
|
||||
CHAINS_MORE_NOTE: '',
|
||||
GENERATED_AT: metadata.generatedAt,
|
||||
FOOTER_NOTE: metadata.footerNote
|
||||
}
|
||||
for (const [key, value] of Object.entries(replaceMap)) html = replacePlaceholder(html, key, value)
|
||||
const htmlPath = path.join(outputDir, `${targetBase}.html`)
|
||||
const pngPath = path.join(outputDir, `${targetBase}.png`)
|
||||
await fs.ensureDir(outputDir)
|
||||
await fs.writeFile(htmlPath, html, 'utf8')
|
||||
|
||||
const win = new BrowserWindow({
|
||||
show: false,
|
||||
width: 430,
|
||||
height: 800,
|
||||
frame: false,
|
||||
backgroundColor: '#f3f5f7',
|
||||
webPreferences: { sandbox: true }
|
||||
})
|
||||
await win.loadFile(htmlPath)
|
||||
await win.webContents.executeJavaScript(`Promise.all([
|
||||
document.fonts.ready,
|
||||
...Array.from(document.images).map((img) => img.complete ? Promise.resolve() : new Promise((resolve) => {
|
||||
img.addEventListener('load', resolve, { once: true });
|
||||
img.addEventListener('error', resolve, { once: true });
|
||||
}))
|
||||
])`)
|
||||
win.webContents.debugger.attach('1.3')
|
||||
const metrics = await win.webContents.debugger.sendCommand('Page.getLayoutMetrics')
|
||||
const width = Math.max(430, Math.ceil(metrics.cssContentSize.width))
|
||||
const height = Math.ceil(metrics.cssContentSize.height)
|
||||
const screenshot = await win.webContents.debugger.sendCommand('Page.captureScreenshot', {
|
||||
format: 'png',
|
||||
captureBeyondViewport: true,
|
||||
fromSurface: true,
|
||||
clip: { x: 0, y: 0, width, height, scale: 1 }
|
||||
})
|
||||
await fs.writeFile(pngPath, Buffer.from(screenshot.data, 'base64'))
|
||||
if (win.webContents.debugger.isAttached()) win.webContents.debugger.detach()
|
||||
win.destroy()
|
||||
return { htmlPath, pngPath, height }
|
||||
}
|
||||
|
||||
app.whenReady().then(async () => {
|
||||
const mode = process.argv.includes('--full') ? 'full' : 'compact'
|
||||
const result =
|
||||
mode === 'full'
|
||||
? await renderRequest(fullRequest, 'full-fixture')
|
||||
: await renderRequest(compactRequest, 'compact-fixture')
|
||||
console.log(JSON.stringify({ mode, result, outputDir }, null, 2))
|
||||
app.quit()
|
||||
})
|
||||
@@ -0,0 +1,45 @@
|
||||
const assert = require('node:assert/strict')
|
||||
const fs = require('node:fs')
|
||||
const path = require('node:path')
|
||||
const ts = require('typescript')
|
||||
|
||||
const filePath = path.join(
|
||||
__dirname,
|
||||
'..',
|
||||
'src',
|
||||
'renderer',
|
||||
'src',
|
||||
'features',
|
||||
'api-center',
|
||||
'utils',
|
||||
'buildSkillInstallInstruction.ts'
|
||||
)
|
||||
const source = fs.readFileSync(filePath, 'utf8')
|
||||
const output = ts.transpileModule(source, { compilerOptions: { module: ts.ModuleKind.CommonJS } }).outputText
|
||||
const moduleExports = {}
|
||||
new Function('exports', 'require', 'module', output)(moduleExports, require, { exports: moduleExports })
|
||||
|
||||
const { buildSkillInstallInstruction } = moduleExports
|
||||
const local = { type: 'local', directoryPath: 'C:/skill/wechatexplorer-reader', skillPath: 'C:/skill/wechatexplorer-reader/SKILL.md', version: 'v1.0' }
|
||||
|
||||
for (const [target, expected] of [
|
||||
['codex', 'Codex 项目或用户 Skill 目录'],
|
||||
['claude-code', '按照 SKILL\.md 调用本地 HTTP API'],
|
||||
['openclaw', '作为 WechatExplorer Reader Skill 安装'],
|
||||
['generic', '读取并安装']
|
||||
]) {
|
||||
const text = buildSkillInstallInstruction({ target, source: local, apiBaseUrl: { host: '127.0.0.1', port: 6131 } })
|
||||
assert.match(text, new RegExp(expected))
|
||||
assert.match(text, /http:\/\/127\.0\.0\.1:6131\/api\/v1\/health/)
|
||||
}
|
||||
|
||||
assert.match(
|
||||
buildSkillInstallInstruction({ target: 'codex', source: local, apiBaseUrl: { host: '0.0.0.0', port: 7000 } }),
|
||||
/http:\/\/127\.0\.0\.1:7000\/api\/v1\/health/
|
||||
)
|
||||
assert.match(
|
||||
buildSkillInstallInstruction({ target: 'generic', source: { type: 'remote', installUrl: 'https://example.com/skill', version: 'v1.0' }, apiBaseUrl: { host: 'localhost', port: 6131 } }),
|
||||
/https:\/\/example\.com\/skill/
|
||||
)
|
||||
|
||||
console.log('skill install instruction tests passed')
|
||||
@@ -0,0 +1,79 @@
|
||||
import { app, safeStorage } from 'electron'
|
||||
import fs from 'fs-extra'
|
||||
import path from 'path'
|
||||
|
||||
interface StoredKeys {
|
||||
version: 1
|
||||
keys: Record<string, string>
|
||||
}
|
||||
|
||||
export class AIProviderKeyStore {
|
||||
private get filePath(): string {
|
||||
return path.join(app.getPath('userData'), 'ai-provider-keys.bin')
|
||||
}
|
||||
|
||||
get(providerId: string): { success: boolean; key?: string; error?: string; available: boolean } {
|
||||
const result = this.read()
|
||||
return { ...result, key: result.data?.keys[providerId] }
|
||||
}
|
||||
|
||||
save(providerId: string, key: string): { success: boolean; error?: string } {
|
||||
if (!safeStorage.isEncryptionAvailable()) {
|
||||
return { success: false, error: '系统安全存储不可用' }
|
||||
}
|
||||
const current = this.read()
|
||||
if (!current.success) return { success: false, error: current.error }
|
||||
const data = current.data || { version: 1 as const, keys: {} }
|
||||
data.keys[providerId] = key
|
||||
return this.write(data)
|
||||
}
|
||||
|
||||
clear(providerId: string): { success: boolean; error?: string } {
|
||||
const current = this.read()
|
||||
if (!current.success) return { success: false, error: current.error }
|
||||
if (!current.data?.keys[providerId]) return { success: true }
|
||||
delete current.data.keys[providerId]
|
||||
try {
|
||||
if (Object.keys(current.data.keys).length === 0) fs.removeSync(this.filePath)
|
||||
else return this.write(current.data)
|
||||
return { success: true }
|
||||
} catch {
|
||||
return { success: false, error: '无法清除 AI Provider 密钥' }
|
||||
}
|
||||
}
|
||||
|
||||
private read(): {
|
||||
success: boolean
|
||||
data?: StoredKeys
|
||||
error?: string
|
||||
available: boolean
|
||||
} {
|
||||
const available = safeStorage.isEncryptionAvailable()
|
||||
if (!fs.existsSync(this.filePath)) {
|
||||
return { success: true, data: { version: 1, keys: {} }, available }
|
||||
}
|
||||
if (!available) return { success: false, error: '系统安全存储不可用', available }
|
||||
try {
|
||||
const data = JSON.parse(
|
||||
safeStorage.decryptString(fs.readFileSync(this.filePath))
|
||||
) as StoredKeys
|
||||
if (data.version !== 1 || !data.keys) throw new Error('invalid AI key store')
|
||||
return { success: true, data, available }
|
||||
} catch {
|
||||
return { success: false, error: 'AI Provider 安全存储不可读取', available }
|
||||
}
|
||||
}
|
||||
|
||||
private write(data: StoredKeys): { success: boolean; error?: string } {
|
||||
try {
|
||||
fs.ensureDirSync(path.dirname(this.filePath))
|
||||
fs.writeFileSync(this.filePath, safeStorage.encryptString(JSON.stringify(data)), {
|
||||
mode: 0o600
|
||||
})
|
||||
fs.chmodSync(this.filePath, 0o600)
|
||||
return { success: true }
|
||||
} catch {
|
||||
return { success: false, error: 'AI Provider 密钥保存失败' }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,12 +1,7 @@
|
||||
import { app, safeStorage } from 'electron'
|
||||
import fs from 'fs-extra'
|
||||
import path from 'path'
|
||||
|
||||
export interface StoredKeyResult {
|
||||
success: boolean
|
||||
key?: string
|
||||
error?: string
|
||||
}
|
||||
import type { DatabaseKeyStorageResult } from '../shared/database-key'
|
||||
|
||||
const normalizeDatabaseKey = (value: string): string => value.trim().replace(/^0x/i, '')
|
||||
|
||||
@@ -18,37 +13,67 @@ export class DatabaseKeyStore {
|
||||
return path.join(app.getPath('userData'), 'wechat-db-key.bin')
|
||||
}
|
||||
|
||||
async load(): Promise<StoredKeyResult> {
|
||||
try {
|
||||
if (!(await fs.pathExists(this.filePath))) return { success: true }
|
||||
if (!safeStorage.isEncryptionAvailable()) {
|
||||
return { success: false, error: '系统安全存储不可用' }
|
||||
}
|
||||
const encrypted = await fs.readFile(this.filePath)
|
||||
const key = normalizeDatabaseKey(safeStorage.decryptString(encrypted))
|
||||
if (!isValidDatabaseKey(key)) return { success: false, error: '已保存的密钥格式无效' }
|
||||
return { success: true, key }
|
||||
} catch (error) {
|
||||
return { success: false, error: error instanceof Error ? error.message : String(error) }
|
||||
async getStatus(): Promise<{ saved: boolean; encryptionAvailable: boolean }> {
|
||||
return {
|
||||
saved: await fs.pathExists(this.filePath),
|
||||
encryptionAvailable: safeStorage.isEncryptionAvailable()
|
||||
}
|
||||
}
|
||||
|
||||
async save(rawKey: string): Promise<StoredKeyResult> {
|
||||
async load(): Promise<DatabaseKeyStorageResult> {
|
||||
try {
|
||||
const status = await this.getStatus()
|
||||
if (!status.saved) return { success: true, ...status }
|
||||
if (!status.encryptionAvailable) {
|
||||
return { success: false, error: '系统安全存储不可用', ...status }
|
||||
}
|
||||
const encrypted = await fs.readFile(this.filePath)
|
||||
const key = normalizeDatabaseKey(safeStorage.decryptString(encrypted))
|
||||
if (!isValidDatabaseKey(key)) {
|
||||
return { success: false, error: '已保存的密钥格式无效', ...status }
|
||||
}
|
||||
return { success: true, key, ...status }
|
||||
} catch (error) {
|
||||
const status = await this.getStatus()
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
...status
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async save(rawKey: string): Promise<DatabaseKeyStorageResult> {
|
||||
const key = normalizeDatabaseKey(rawKey)
|
||||
if (!isValidDatabaseKey(key)) {
|
||||
return { success: false, error: '密钥必须是 64 位十六进制字符' }
|
||||
return {
|
||||
success: false,
|
||||
error: '密钥必须是 64 位十六进制字符',
|
||||
saved: await fs.pathExists(this.filePath),
|
||||
encryptionAvailable: safeStorage.isEncryptionAvailable()
|
||||
}
|
||||
}
|
||||
if (!safeStorage.isEncryptionAvailable()) {
|
||||
return { success: false, error: '系统安全存储不可用' }
|
||||
return {
|
||||
success: false,
|
||||
error: '系统安全存储不可用',
|
||||
saved: await fs.pathExists(this.filePath),
|
||||
encryptionAvailable: false
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
await fs.ensureDir(path.dirname(this.filePath))
|
||||
await fs.writeFile(this.filePath, safeStorage.encryptString(key), { mode: 0o600 })
|
||||
await fs.chmod(this.filePath, 0o600)
|
||||
return { success: true, key }
|
||||
return { success: true, key, saved: true, encryptionAvailable: true }
|
||||
} catch (error) {
|
||||
return { success: false, error: error instanceof Error ? error.message : String(error) }
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
saved: await fs.pathExists(this.filePath),
|
||||
encryptionAvailable: true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
// src/main/db/image-insights-store.ts
|
||||
// 持久化 ImageInsight 到 JSON 文件(userData/image-insights.json)
|
||||
// 跟项目现有风格一致(ai-provider-service 用 ai-providers.json)
|
||||
|
||||
import { app } from 'electron'
|
||||
import fs from 'fs-extra'
|
||||
import path from 'path'
|
||||
import type { ImageInsight } from '../../shared/image-insight'
|
||||
|
||||
interface ImageInsightsFile {
|
||||
version: 1
|
||||
/** imageHash -> ImageInsight 索引(缓存查询 O(1)) */
|
||||
byHash: Record<string, ImageInsight>
|
||||
/** messageId -> imageHash 反向索引(防止同一 message 重复入库) */
|
||||
byMessageId: Record<string, string>
|
||||
}
|
||||
|
||||
const EMPTY_FILE: ImageInsightsFile = {
|
||||
version: 1,
|
||||
byHash: {},
|
||||
byMessageId: {}
|
||||
}
|
||||
|
||||
class ImageInsightsStore {
|
||||
private cache: ImageInsightsFile | null = null
|
||||
|
||||
private get filePath(): string {
|
||||
return path.join(app.getPath('userData'), 'image-insights.json')
|
||||
}
|
||||
|
||||
private ensureLoaded(): ImageInsightsFile {
|
||||
if (this.cache) return this.cache
|
||||
try {
|
||||
if (fs.existsSync(this.filePath)) {
|
||||
const raw = fs.readJsonSync(this.filePath) as Partial<ImageInsightsFile>
|
||||
this.cache = {
|
||||
version: 1,
|
||||
byHash: raw.byHash || {},
|
||||
byMessageId: raw.byMessageId || {}
|
||||
}
|
||||
return this.cache
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('[ImageInsightsStore] failed to load, fallback to empty:', error)
|
||||
}
|
||||
this.cache = { ...EMPTY_FILE }
|
||||
return this.cache
|
||||
}
|
||||
|
||||
private persist(): void {
|
||||
if (!this.cache) return
|
||||
try {
|
||||
fs.ensureDirSync(path.dirname(this.filePath))
|
||||
fs.writeJsonSync(this.filePath, this.cache, { spaces: 2 })
|
||||
} catch (error) {
|
||||
console.error('[ImageInsightsStore] failed to persist:', error)
|
||||
}
|
||||
}
|
||||
|
||||
/** 通过 imageHash 查询缓存 */
|
||||
getByHash(imageHash: string): ImageInsight | null {
|
||||
return this.ensureLoaded().byHash[imageHash] || null
|
||||
}
|
||||
|
||||
/** 列出某会话的所有 insights(按时间倒序) */
|
||||
listBySession(sessionId: string, limit?: number): ImageInsight[] {
|
||||
const data = this.ensureLoaded()
|
||||
const items = Object.values(data.byHash)
|
||||
.filter((it) => it.sessionId === sessionId)
|
||||
.sort((a, b) => b.sentAt - a.sentAt)
|
||||
return typeof limit === 'number' ? items.slice(0, limit) : items
|
||||
}
|
||||
|
||||
/**
|
||||
* 写入或更新 Insight。
|
||||
* - 同 imageHash 已存在:更新 description/ocrText/tags/category/importance/provider/model/updatedAt(保留 createdAt)
|
||||
* - 新 hash:插入
|
||||
* 同步维护 byMessageId 反向索引。
|
||||
*/
|
||||
upsert(insight: ImageInsight): void {
|
||||
const data = this.ensureLoaded()
|
||||
const existing = data.byHash[insight.imageHash]
|
||||
const now = Date.now()
|
||||
if (existing) {
|
||||
data.byHash[insight.imageHash] = {
|
||||
...existing,
|
||||
...insight,
|
||||
id: existing.id, // 保留 id
|
||||
createdAt: existing.createdAt, // 保留首次分析时间
|
||||
updatedAt: now
|
||||
}
|
||||
} else {
|
||||
data.byHash[insight.imageHash] = { ...insight, createdAt: now, updatedAt: now }
|
||||
data.byMessageId[insight.messageId] = insight.imageHash
|
||||
}
|
||||
this.persist()
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
export const imageInsightsStore = new ImageInsightsStore()
|
||||
@@ -6,11 +6,29 @@ import {
|
||||
GroupReportExportRequest,
|
||||
GroupReportExportResult,
|
||||
GroupReportMetadata,
|
||||
ReportHeat
|
||||
ReportHeat,
|
||||
ReportSectionMeta
|
||||
} from '../shared/group-report'
|
||||
import { resolveMd5, getGroupSnapshot } from './services/chat-service'
|
||||
import { imageInsightService } from './services/image-insight-service'
|
||||
|
||||
const TEMPLATE_NAME = 'mobile_daily_report.html'
|
||||
const TEMPLATE_FILES: Record<string, string> = {
|
||||
v1: 'mobile_daily_report_v1.html',
|
||||
v2: 'mobile_daily_report_v2.html'
|
||||
}
|
||||
const DEFAULT_TEMPLATE = TEMPLATE_FILES.v1
|
||||
|
||||
const templatePath = (templateId?: string): string => {
|
||||
const name = TEMPLATE_FILES[templateId || ''] || DEFAULT_TEMPLATE
|
||||
const candidates = [
|
||||
path.join(process.resourcesPath, 'resources', name),
|
||||
path.join(app.getAppPath(), 'resources', name),
|
||||
path.join(process.cwd(), 'resources', name)
|
||||
]
|
||||
const found = candidates.find((candidate) => fs.existsSync(candidate))
|
||||
if (!found) throw new Error(`日报模板不存在: ${candidates.join(' | ')}`)
|
||||
return found
|
||||
}
|
||||
|
||||
const escapeHtml = (value: unknown): string =>
|
||||
String(value ?? '')
|
||||
@@ -75,17 +93,6 @@ const embedAvatar = async (source: string | undefined, name: string): Promise<st
|
||||
}
|
||||
}
|
||||
|
||||
const templatePath = (): string => {
|
||||
const candidates = [
|
||||
path.join(process.resourcesPath, 'resources', TEMPLATE_NAME),
|
||||
path.join(app.getAppPath(), 'resources', TEMPLATE_NAME),
|
||||
path.join(process.cwd(), 'resources', TEMPLATE_NAME)
|
||||
]
|
||||
const found = candidates.find((candidate) => fs.existsSync(candidate))
|
||||
if (!found) throw new Error(`日报模板不存在: ${candidates.join(' | ')}`)
|
||||
return found
|
||||
}
|
||||
|
||||
/**
|
||||
* 从群成员快照反推真头像,填进 metadata.avatars。
|
||||
* - 没传 talker → 跳过(向后兼容)
|
||||
@@ -106,9 +113,7 @@ const enrichAvatarsFromGroup = async (metadata: GroupReportMetadata): Promise<vo
|
||||
const snapshot = getGroupSnapshot(resolved.md5)
|
||||
if (!snapshot) {
|
||||
metadata.warnings = metadata.warnings ?? []
|
||||
metadata.warnings.push(
|
||||
`enrich skipped: group snapshot not available for "${metadata.talker}"`
|
||||
)
|
||||
metadata.warnings.push(`enrich skipped: group snapshot not available for "${metadata.talker}"`)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -140,6 +145,26 @@ const heatClass = (heat: ReportHeat): string => {
|
||||
const replacePlaceholder = (html: string, key: string, value: string): string =>
|
||||
html.replaceAll(`{{${key}}}`, value)
|
||||
|
||||
const sectionMeta = (
|
||||
request: GroupReportExportRequest,
|
||||
key: keyof NonNullable<typeof request.report.sectionMeta>
|
||||
): ReportSectionMeta | undefined => request.report.sectionMeta?.[key]
|
||||
|
||||
const sectionClass = (
|
||||
request: GroupReportExportRequest,
|
||||
key: keyof NonNullable<typeof request.report.sectionMeta>,
|
||||
hasContent: boolean
|
||||
): string => (sectionMeta(request, key)?.enabled && hasContent ? '' : 'empty-section')
|
||||
|
||||
const overflowNote = (
|
||||
request: GroupReportExportRequest,
|
||||
key: keyof NonNullable<typeof request.report.sectionMeta>
|
||||
): string => {
|
||||
const meta = sectionMeta(request, key)
|
||||
if (request.metadata.reportMode !== 'compact' || !meta?.hiddenCount) return ''
|
||||
return `<div class="section-more">另有 ${meta.hiddenCount} 条内容,请在完整版中查看</div>`
|
||||
}
|
||||
|
||||
const renderReportHtml = async (request: GroupReportExportRequest): Promise<string> => {
|
||||
const { report, metadata } = request
|
||||
const avatarNames = new Set<string>(metadata.heroParticipants)
|
||||
@@ -149,6 +174,9 @@ const renderReportHtml = async (request: GroupReportExportRequest): Promise<stri
|
||||
quote.messages.forEach((message) => avatarNames.add(message.sender))
|
||||
)
|
||||
report.analytics.topSpeakers.forEach((speaker) => avatarNames.add(speaker.name))
|
||||
report.media?.gallery?.forEach((item) => avatarNames.add(item.sender))
|
||||
report.media?.voiceHighlights?.forEach((item) => avatarNames.add(item.sender))
|
||||
report.media?.funBadges?.forEach((item) => avatarNames.add(item.owner))
|
||||
|
||||
const avatars = new Map<string, string>()
|
||||
await Promise.all(
|
||||
@@ -170,7 +198,38 @@ const renderReportHtml = async (request: GroupReportExportRequest): Promise<stri
|
||||
<div class="topic-title-row"><h3>${escapeHtml(topic.title)}</h3><span class="heat ${heatClass(topic.heat)}">${escapeHtml(topic.heat)}热</span></div>
|
||||
<div class="topic-meta">${escapeHtml(topic.timeRange)}</div>
|
||||
<p>${escapeHtml(topic.summary)}</p>
|
||||
${topic.conclusion ? `<p class="muted">${escapeHtml(topic.conclusion)}</p>` : ''}
|
||||
${
|
||||
topic.conclusions?.length
|
||||
? `<div class="topic-conclusions">${topic.conclusions
|
||||
.slice(0, 2)
|
||||
.map((entry) => `<div class="topic-conclusion">${escapeHtml(entry.text)}</div>`)
|
||||
.join('')}</div>`
|
||||
: topic.conclusion
|
||||
? `<div class="topic-conclusions"><div class="topic-conclusion">${escapeHtml(topic.conclusion)}</div></div>`
|
||||
: ''
|
||||
}
|
||||
${
|
||||
topic.image
|
||||
? (() => {
|
||||
// 优先用已有 imageUrl;若有 imageHash(来自 visionGallery),按 hash 取原图
|
||||
let imageUrl = topic.image.imageUrl
|
||||
if (!imageUrl && topic.image.imageHash) {
|
||||
const insight = imageInsightService.getInsight(topic.image.imageHash)
|
||||
if (insight) {
|
||||
// insight 不含 imageUrl,需要按 md5/datName 重新拿;这里通过 ImageDecryptService 间接获取
|
||||
// 走 ImageDecryptService.findImageFile + decryptImageToBase64
|
||||
const decryptService = (globalThis as { __imageDecrypt?: { findImageFile: (md5?: string, dat?: string) => string | null; decryptImageToBase64: (p: string) => string | null } }).__imageDecrypt
|
||||
if (decryptService) {
|
||||
const filePath = decryptService.findImageFile(insight.md5, insight.datName)
|
||||
if (filePath) imageUrl = decryptService.decryptImageToBase64(filePath) || undefined
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!imageUrl) return ''
|
||||
return `<div class="topic-inline-image"><img src="${imageUrl}" alt="热点图片"><div>${escapeHtml(topic.image.note)}</div></div>`
|
||||
})()
|
||||
: ''
|
||||
}
|
||||
<div class="participants">${topic.participants
|
||||
.slice(0, 5)
|
||||
.map(
|
||||
@@ -215,18 +274,122 @@ const renderReportHtml = async (request: GroupReportExportRequest): Promise<stri
|
||||
)
|
||||
.join('')
|
||||
|
||||
const qaCards = report.qa
|
||||
const todoCards = (report.todos || [])
|
||||
.map(
|
||||
(item) =>
|
||||
`<div class="qa-card"><b>Q:${escapeHtml(item.question)}</b><div>A:${escapeHtml(item.answer)}${item.answerer ? ` — ${escapeHtml(item.answerer)}` : ''}</div></div>`
|
||||
(item) => `<div class="action-card todo-card">
|
||||
<b>${escapeHtml(item.task)}</b>
|
||||
<div>${[item.owner || '', item.deadline || '', item.topic || ''].filter(Boolean).map(escapeHtml).join(' · ')}</div>
|
||||
${item.note ? `<div class="action-note">${escapeHtml(item.note)}</div>` : ''}
|
||||
</div>`
|
||||
)
|
||||
.join('')
|
||||
|
||||
const maxHeat = Math.max(1, ...report.analytics.topicHeat.map((item) => item.score))
|
||||
const heatBars = report.analytics.topicHeat
|
||||
const unresolvedCards = (report.unresolved || [])
|
||||
.map(
|
||||
(item) =>
|
||||
`<div class="bar-row"><span>${escapeHtml(item.topic)}</span><div class="bar"><i style="width:${Math.max(8, Math.round((item.score / maxHeat) * 100))}%"></i></div></div>`
|
||||
(item) => `<div class="action-card unresolved-card">
|
||||
<b>${escapeHtml(item.question)}</b>
|
||||
<div>${[item.owner || '', item.lastDiscussedAt || '', item.status].filter(Boolean).map(escapeHtml).join(' · ')}</div>
|
||||
<div class="action-note">${escapeHtml(item.note)}</div>
|
||||
</div>`
|
||||
)
|
||||
.join('')
|
||||
|
||||
const storylineCards = (report.storylines || [])
|
||||
.map(
|
||||
(item) => `<div class="card storyline-card">
|
||||
<div class="topic-title-row"><h3>${escapeHtml(item.title)}</h3></div>
|
||||
<div class="storyline-steps">${item.stages
|
||||
.map(
|
||||
(stage) => `<div class="storyline-step">
|
||||
<span>${escapeHtml(stage.time || '--:--')}</span>
|
||||
<b>${escapeHtml(stage.event)}</b>
|
||||
</div>`
|
||||
)
|
||||
.join('')}</div>
|
||||
${item.result ? `<p class="muted">${escapeHtml(item.result)}</p>` : ''}
|
||||
</div>`
|
||||
)
|
||||
.join('')
|
||||
|
||||
const reversalCards = (report.reversals || [])
|
||||
.map(
|
||||
(item) => `<div class="qa-card">
|
||||
<b>${escapeHtml(item.topic)}</b>
|
||||
<div>最初:${escapeHtml(item.initialView)}</div>
|
||||
<div>后来:${escapeHtml(item.finalView)}</div>
|
||||
${item.note ? `<div>${escapeHtml(item.note)}</div>` : ''}
|
||||
</div>`
|
||||
)
|
||||
.join('')
|
||||
|
||||
const chainCards = (report.participantChains || [])
|
||||
.map(
|
||||
(item) => `<div class="card chain-card">
|
||||
<div class="topic-title-row"><h3>${escapeHtml(item.topic)}</h3></div>
|
||||
<div class="chain-flow">${item.chain.map((node) => `<span>${escapeHtml(node)}</span>`).join('<i>→</i>')}</div>
|
||||
${item.note ? `<p class="muted">${escapeHtml(item.note)}</p>` : ''}
|
||||
</div>`
|
||||
)
|
||||
.join('')
|
||||
|
||||
const galleryCards = (report.media?.gallery || [])
|
||||
.map(
|
||||
(item) => `<div class="gallery-card">
|
||||
<img class="gallery-image" src="${item.imageUrl}" alt="群聊图片">
|
||||
<div class="gallery-body">
|
||||
<div class="important-meta"><b>${escapeHtml(item.sender)}</b><span>${escapeHtml(item.time)}</span></div>
|
||||
${item.stats ? `<div class="gallery-stats">${escapeHtml(item.stats)}</div>` : ''}
|
||||
<div class="important-text">${escapeHtml(item.note)}</div>
|
||||
${item.inferenceLabel ? `<div class="topic-meta">${escapeHtml(item.inferenceLabel)}</div>` : ''}
|
||||
</div>
|
||||
</div>`
|
||||
)
|
||||
.join('')
|
||||
|
||||
// AI 图片理解结果板块(ImageInsight)
|
||||
// 内容由 ImageInsightService.analyze 生成,真实看图 + 看上下文
|
||||
const visionCards = (report.media?.visionGallery || [])
|
||||
.filter((item) => item.imageUrl) // 只显示加载成功的图
|
||||
.map(
|
||||
(item) => `<div class="vision-card">
|
||||
<img class="vision-image" src="${item.imageUrl}" alt="AI 识别的图片">
|
||||
<div class="vision-body">
|
||||
<div class="important-meta"><b>${escapeHtml(item.sender)}</b><span>${escapeHtml(item.time)}</span></div>
|
||||
<div class="vision-description">${escapeHtml(item.description)}</div>
|
||||
${item.ocrText ? `<div class="vision-ocr">📝 ${escapeHtml(item.ocrText)}</div>` : ''}
|
||||
${item.tags.length ? `<div class="vision-tags">${item.tags.map((t) => `<span class="vision-tag">${escapeHtml(t)}</span>`).join('')}</div>` : ''}
|
||||
<div class="vision-label">AI 图片识别</div>
|
||||
</div>
|
||||
</div>`
|
||||
)
|
||||
.join('')
|
||||
|
||||
const voiceCards = (report.media?.voiceHighlights || [])
|
||||
.map(
|
||||
(item) => `<div class="qa-card">
|
||||
<b>${escapeHtml(item.title)} · ${escapeHtml(item.sender)}</b>
|
||||
<div>${escapeHtml(item.note)}</div>
|
||||
</div>`
|
||||
)
|
||||
.join('')
|
||||
|
||||
const voiceRankCards = (report.analytics.voiceLeaderboard || [])
|
||||
.map(
|
||||
(item, index) => `<div class="rank">
|
||||
<img src="${avatar(item.sender)}" alt="">
|
||||
<b>${index + 1}. ${escapeHtml(item.sender)}</b>
|
||||
<span>${item.count} 条 · ${item.durationSec} 秒</span>
|
||||
</div>`
|
||||
)
|
||||
.join('')
|
||||
|
||||
const badgeCards = (report.media?.funBadges || [])
|
||||
.map(
|
||||
(item) => `<div class="badge-card">
|
||||
<span class="tag">${escapeHtml(item.title)}</span>
|
||||
<b>${escapeHtml(item.owner)}</b>
|
||||
<p>${escapeHtml(item.note)}</p>
|
||||
</div>`
|
||||
)
|
||||
.join('')
|
||||
|
||||
@@ -238,6 +401,20 @@ const renderReportHtml = async (request: GroupReportExportRequest): Promise<stri
|
||||
)
|
||||
.join('')
|
||||
|
||||
// v1 模板使用的水平条形热度图,渲染 top speakers 排行
|
||||
const heatBarsHtml = report.analytics.topSpeakers
|
||||
.slice(0, 8)
|
||||
.map((speaker) => {
|
||||
const count = Math.max(0, speaker.count)
|
||||
const width = Math.min(100, count * 12)
|
||||
return `<div class="heat-row">
|
||||
<span class="heat-name">${escapeHtml(speaker.name)}</span>
|
||||
<span class="heat-bar"><i style="width:${width}%"></i></span>
|
||||
<span class="heat-val">${count}</span>
|
||||
</div>`
|
||||
})
|
||||
.join('')
|
||||
|
||||
const cloudTags = report.keywords
|
||||
.slice(0, 15)
|
||||
.map(
|
||||
@@ -246,38 +423,121 @@ const renderReportHtml = async (request: GroupReportExportRequest): Promise<stri
|
||||
)
|
||||
.join('')
|
||||
|
||||
let html = await fs.readFile(templatePath(), 'utf8')
|
||||
const qaCards = report.qa
|
||||
.map(
|
||||
(item) =>
|
||||
`<div class="qa-card"><b>Q:${escapeHtml(item.question)}</b><div>A:${escapeHtml(item.answer)}${item.answerer ? ` — ${escapeHtml(item.answerer)}` : ''}</div></div>`
|
||||
)
|
||||
.join('')
|
||||
|
||||
const summaryStats = report.summaryStats || {
|
||||
messageCount: metadata.messageCount,
|
||||
activeUsers: metadata.activeUsers,
|
||||
topicCount: report.topics.length,
|
||||
mediaCount: metadata.mediaMessageCount || 0,
|
||||
imageCount: metadata.imageCount || 0,
|
||||
voiceCount: metadata.voiceCount || 0,
|
||||
stickerCount: metadata.stickerCount || 0,
|
||||
conclusionCount: 0,
|
||||
todoCount: report.todos.length,
|
||||
unresolvedCount: report.unresolved.length
|
||||
}
|
||||
|
||||
let html = await fs.readFile(templatePath(request.templateId), 'utf8')
|
||||
const values: Record<string, string> = {
|
||||
REPORT_TITLE: escapeHtml(`${metadata.groupName}日报`),
|
||||
REPORT_MODE_CLASS: metadata.reportMode === 'full' ? 'full' : 'compact',
|
||||
GROUP_NAME: escapeHtml(metadata.groupName),
|
||||
DATE_RANGE: escapeHtml(metadata.dateRange),
|
||||
RECORD_NOTE: escapeHtml(`${metadata.recordNote} ${report.overview}`.trim()),
|
||||
RECORD_NOTE: escapeHtml(metadata.recordNote),
|
||||
// v1 模板使用的 OVERVIEW(经典版以概览段落呈现)
|
||||
OVERVIEW: escapeHtml(report.overview || report.hero?.summary || '基于已读取聊天记录生成的群聊日报'),
|
||||
// v2 模板使用的 hero-*
|
||||
HERO_HEADLINE: escapeHtml(report.hero?.headline || '今日群聊速览'),
|
||||
HERO_SUMMARY: escapeHtml(report.hero?.summary || report.overview),
|
||||
HERO_TAKEAWAY: escapeHtml(report.hero?.keyTakeaway || ''),
|
||||
HERO_PENDING: escapeHtml(report.hero?.pendingNote || ''),
|
||||
HERO_STATUS_LINE: escapeHtml(report.hero?.statusLine || ''),
|
||||
HERO_STATUS_EMPTY_CLASS: report.hero?.statusLine ? '' : 'empty-section',
|
||||
HERO_TAKEAWAY_EMPTY_CLASS: report.hero?.keyTakeaway ? '' : 'empty-section',
|
||||
HERO_PENDING_EMPTY_CLASS: report.hero?.pendingNote ? '' : 'empty-section',
|
||||
HERO_AVATARS: heroAvatars,
|
||||
MESSAGE_COUNT: String(metadata.messageCount),
|
||||
ACTIVE_USERS: String(metadata.activeUsers),
|
||||
MESSAGE_COUNT: String(summaryStats.messageCount),
|
||||
ACTIVE_USERS: String(summaryStats.activeUsers),
|
||||
TIME_SPAN: escapeHtml(metadata.timeSpan || ''),
|
||||
TOPIC_COUNT: String(report.topics.length),
|
||||
TOPIC_COUNT: String(summaryStats.topicCount),
|
||||
MEDIA_COUNT: String(summaryStats.mediaCount),
|
||||
TOPIC_CARDS: topicCards,
|
||||
RESOURCES_EMPTY_CLASS: report.resources.length ? '' : 'empty-section',
|
||||
TOPICS_EMPTY_CLASS: sectionClass(request, 'topics', report.topics.length > 0),
|
||||
TOPICS_MORE_NOTE: overflowNote(request, 'topics'),
|
||||
RESOURCES_EMPTY_CLASS: sectionClass(request, 'resources', report.resources.length > 0),
|
||||
RESOURCE_ITEMS: resourceItems,
|
||||
MESSAGES_EMPTY_CLASS: report.importantMessages.length ? '' : 'empty-section',
|
||||
RESOURCES_MORE_NOTE: overflowNote(request, 'resources'),
|
||||
MESSAGES_EMPTY_CLASS: sectionClass(request, 'importantMessages', report.importantMessages.length > 0),
|
||||
IMPORTANT_MESSAGES: importantMessages,
|
||||
QUOTES_EMPTY_CLASS: report.quotes.length ? '' : 'empty-section',
|
||||
MESSAGES_MORE_NOTE: overflowNote(request, 'importantMessages'),
|
||||
QUOTES_EMPTY_CLASS: sectionClass(request, 'moments', report.quotes.length > 0),
|
||||
QUOTE_BLOCKS: quoteBlocks,
|
||||
QA_EMPTY_CLASS: report.qa.length ? '' : 'empty-section',
|
||||
QUOTES_MORE_NOTE: overflowNote(request, 'moments'),
|
||||
ACTIONS_EMPTY_CLASS: sectionClass(request, 'actions', report.todos.length + report.unresolved.length > 0),
|
||||
TODO_EMPTY_CLASS: report.todos.length ? '' : 'empty-section',
|
||||
TODO_CARDS: todoCards,
|
||||
UNRESOLVED_EMPTY_CLASS: report.unresolved?.length ? '' : 'empty-section',
|
||||
UNRESOLVED_CARDS: unresolvedCards,
|
||||
ACTIONS_MORE_NOTE: overflowNote(request, 'actions'),
|
||||
QA_EMPTY_CLASS: sectionClass(request, 'qa', report.qa.length > 0),
|
||||
QA_CARDS: qaCards,
|
||||
HEAT_BARS: heatBars,
|
||||
QA_MORE_NOTE: overflowNote(request, 'qa'),
|
||||
STORYLINES_EMPTY_CLASS: sectionClass(request, 'storylines', report.storylines?.length > 0),
|
||||
STORYLINE_CARDS: storylineCards,
|
||||
STORYLINES_MORE_NOTE: overflowNote(request, 'storylines'),
|
||||
REVERSALS_EMPTY_CLASS: sectionClass(request, 'reversals', report.reversals?.length > 0),
|
||||
REVERSAL_CARDS: reversalCards,
|
||||
REVERSALS_MORE_NOTE: overflowNote(request, 'reversals'),
|
||||
CHAINS_EMPTY_CLASS: sectionClass(request, 'chains', report.participantChains?.length > 0),
|
||||
CHAIN_CARDS: chainCards,
|
||||
CHAINS_MORE_NOTE: overflowNote(request, 'chains'),
|
||||
// AI 图片识别板块
|
||||
VISION_EMPTY_CLASS: sectionClass(
|
||||
request,
|
||||
'vision',
|
||||
(report.media?.visionGallery?.length ?? 0) > 0
|
||||
),
|
||||
VISION_CARDS: visionCards,
|
||||
VISION_TITLE: '📸 AI 识别的图片精选',
|
||||
GALLERY_EMPTY_CLASS: sectionClass(request, 'gallery', report.media?.gallery?.length > 0),
|
||||
GALLERY_CARDS: galleryCards,
|
||||
GALLERY_MORE_NOTE: overflowNote(request, 'gallery'),
|
||||
VOICE_EMPTY_CLASS: sectionClass(request, 'voices', report.media?.voiceHighlights?.length > 0),
|
||||
VOICE_CARDS: voiceCards,
|
||||
VOICE_MORE_NOTE: overflowNote(request, 'voices'),
|
||||
VOICE_RANK_EMPTY_CLASS: sectionClass(request, 'voices', report.analytics.voiceLeaderboard?.length > 0),
|
||||
VOICE_RANK_CARDS: voiceRankCards,
|
||||
BADGES_EMPTY_CLASS: sectionClass(request, 'badges', report.media?.funBadges?.length > 0),
|
||||
BADGE_CARDS: badgeCards,
|
||||
BADGES_MORE_NOTE: overflowNote(request, 'badges'),
|
||||
RANK_ITEMS: rankItems,
|
||||
ACTIVITY_TIMELINE: escapeHtml(report.analytics.activeTimeline),
|
||||
CONCLUSION_COUNT: String(summaryStats.conclusionCount),
|
||||
TODO_COUNT: String(summaryStats.todoCount),
|
||||
UNRESOLVED_COUNT: String(summaryStats.unresolvedCount),
|
||||
CLOUD_TAGS: cloudTags,
|
||||
KEYWORDS_EMPTY_CLASS: sectionClass(request, 'keywords', report.keywords.length > 0),
|
||||
KEYWORDS_MORE_NOTE: overflowNote(request, 'keywords'),
|
||||
ANALYTICS_EMPTY_CLASS: sectionClass(request, 'analytics', true),
|
||||
GENERATED_AT: escapeHtml(metadata.generatedAt),
|
||||
FOOTER_NOTE: escapeHtml(metadata.footerNote)
|
||||
FOOTER_NOTE: escapeHtml(metadata.footerNote),
|
||||
// v1 模板独有:从 analytics.topSpeakers 渲染水平条形热度图
|
||||
HEAT_BARS: heatBarsHtml
|
||||
}
|
||||
for (const [key, value] of Object.entries(values)) html = replacePlaceholder(html, key, value)
|
||||
// 清空模板中残留的未使用占位符(模板独有但 values 没提供的键)
|
||||
html = html.replace(/\{\{[A-Z_]+\}\}/g, '')
|
||||
return html
|
||||
}
|
||||
|
||||
const captureFullPage = async (htmlPath: string, pngPath: string): Promise<string> => {
|
||||
console.log(`[GroupReport] capture begin html=${htmlPath}`)
|
||||
const reportWindow = new BrowserWindow({
|
||||
show: false,
|
||||
width: 430,
|
||||
@@ -289,6 +549,7 @@ const captureFullPage = async (htmlPath: string, pngPath: string): Promise<strin
|
||||
|
||||
try {
|
||||
await reportWindow.loadFile(htmlPath)
|
||||
console.log('[GroupReport] capture loaded html')
|
||||
await reportWindow.webContents.executeJavaScript(`Promise.all([
|
||||
document.fonts.ready,
|
||||
...Array.from(document.images).map((img) => img.complete ? Promise.resolve() : new Promise((resolve) => {
|
||||
@@ -296,29 +557,23 @@ const captureFullPage = async (htmlPath: string, pngPath: string): Promise<strin
|
||||
img.addEventListener('error', resolve, { once: true });
|
||||
}))
|
||||
])`)
|
||||
reportWindow.webContents.debugger.attach('1.3')
|
||||
const metrics = (await reportWindow.webContents.debugger.sendCommand(
|
||||
'Page.getLayoutMetrics'
|
||||
)) as { cssContentSize: { width: number; height: number } }
|
||||
const width = Math.max(430, Math.ceil(metrics.cssContentSize.width))
|
||||
const height = Math.ceil(metrics.cssContentSize.height)
|
||||
const screenshot = (await reportWindow.webContents.debugger.sendCommand(
|
||||
'Page.captureScreenshot',
|
||||
{
|
||||
format: 'png',
|
||||
captureBeyondViewport: true,
|
||||
fromSurface: true,
|
||||
clip: { x: 0, y: 0, width, height, scale: 1 }
|
||||
}
|
||||
)) as { data: string }
|
||||
const png = Buffer.from(screenshot.data, 'base64')
|
||||
console.log('[GroupReport] capture assets ready')
|
||||
const metrics = (await reportWindow.webContents.executeJavaScript(`({
|
||||
width: Math.ceil(Math.max(document.documentElement.scrollWidth, document.body.scrollWidth, 430)),
|
||||
height: Math.ceil(Math.max(document.documentElement.scrollHeight, document.body.scrollHeight, 800))
|
||||
})`)) as { width: number; height: number }
|
||||
const width = Math.max(430, Math.min(1200, Math.ceil(metrics.width)))
|
||||
const height = Math.max(800, Math.min(20000, Math.ceil(metrics.height)))
|
||||
reportWindow.setContentSize(width, height)
|
||||
await new Promise((resolve) => setTimeout(resolve, 100))
|
||||
console.log(`[GroupReport] capture native page width=${width} height=${height}`)
|
||||
const image = await reportWindow.webContents.capturePage({ x: 0, y: 0, width, height })
|
||||
const png = image.toPNG()
|
||||
if (png.length < 1000) throw new Error('生成的日报图片为空')
|
||||
await fs.writeFile(pngPath, png)
|
||||
return `data:image/png;base64,${screenshot.data}`
|
||||
console.log(`[GroupReport] capture ok bytes=${png.length} png=${pngPath}`)
|
||||
return `data:image/png;base64,${png.toString('base64')}`
|
||||
} finally {
|
||||
if (reportWindow.webContents.debugger.isAttached()) {
|
||||
reportWindow.webContents.debugger.detach()
|
||||
}
|
||||
reportWindow.destroy()
|
||||
}
|
||||
}
|
||||
@@ -332,17 +587,34 @@ export const exportGroupReport = async (
|
||||
|
||||
const outputDir = path.join(os.homedir(), 'Documents', '微信聊天记录')
|
||||
await fs.ensureDir(outputDir)
|
||||
const baseName = `${sanitizeFileName(request.metadata.groupName)}日报_${request.metadata.reportDate}_可视化长图`
|
||||
const templateLabel = request.templateId === 'v1' ? '经典版' : '模板2'
|
||||
const baseName = `${sanitizeFileName(request.metadata.groupName)}日报_${request.metadata.reportDate}_${templateLabel}`
|
||||
const htmlPath = path.join(outputDir, `${baseName}.html`)
|
||||
const pngPath = path.join(outputDir, `${baseName}.png`)
|
||||
const htmlStartedAt = new Date()
|
||||
const html = await renderReportHtml(request)
|
||||
await fs.writeFile(htmlPath, html, 'utf8')
|
||||
const htmlEndedAt = new Date()
|
||||
const pngStartedAt = new Date()
|
||||
const imageDataUrl = await captureFullPage(htmlPath, pngPath)
|
||||
const pngEndedAt = new Date()
|
||||
return {
|
||||
success: true,
|
||||
htmlPath,
|
||||
pngPath,
|
||||
imageDataUrl,
|
||||
exportTimings: {
|
||||
html: {
|
||||
startedAt: htmlStartedAt.toISOString(),
|
||||
endedAt: htmlEndedAt.toISOString(),
|
||||
duration: htmlEndedAt.getTime() - htmlStartedAt.getTime()
|
||||
},
|
||||
png: {
|
||||
startedAt: pngStartedAt.toISOString(),
|
||||
endedAt: pngEndedAt.toISOString(),
|
||||
duration: pngEndedAt.getTime() - pngStartedAt.getTime()
|
||||
}
|
||||
},
|
||||
warnings: request.metadata.warnings?.length ? request.metadata.warnings : undefined
|
||||
}
|
||||
} catch (error) {
|
||||
|
||||
@@ -72,24 +72,33 @@ export class ImageDecryptService {
|
||||
/**
|
||||
* 根据 md5 查找图片文件 (WechatExplorer 风格)
|
||||
*/
|
||||
findImageFile(md5?: string, imageDatName?: string): string | null {
|
||||
findImageFile(
|
||||
md5?: string,
|
||||
imageDatName?: string,
|
||||
options?: { allowThumbnail?: boolean }
|
||||
): string | null {
|
||||
const accountDir = this.getAccountDir()
|
||||
if (!accountDir) return null
|
||||
const allowThumbnail = options?.allowThumbnail !== false
|
||||
|
||||
const normalizedMd5 = this.normalizeDatBase(md5 || '')
|
||||
const normalizedDatName = this.normalizeDatBase(imageDatName || '')
|
||||
console.log('[ImageDecrypt] findImageFile:', {
|
||||
md5: normalizedMd5,
|
||||
imageDatName: normalizedDatName,
|
||||
accountDir
|
||||
accountDir,
|
||||
allowThumbnail
|
||||
})
|
||||
|
||||
for (const key of this.uniq([normalizedMd5, normalizedDatName])) {
|
||||
const hardlink = this.wcdb4Client?.resolveImageHardlink(key)
|
||||
const fullPath = typeof hardlink?.full_path === 'string' ? hardlink.full_path : ''
|
||||
if (fullPath && existsSync(fullPath)) {
|
||||
console.log('[ImageDecrypt] hardlink hit:', fullPath)
|
||||
return this.getPreferredDatVariantPath(fullPath, true)
|
||||
const selected = this.getPreferredDatVariantPath(fullPath, allowThumbnail)
|
||||
if (allowThumbnail || !this.isThumbnailName(basename(selected))) {
|
||||
console.log('[ImageDecrypt] hardlink hit:', selected)
|
||||
return selected
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -104,18 +113,22 @@ export class ImageDecryptService {
|
||||
if (searchKeys.length === 0) return null
|
||||
|
||||
for (const key of searchKeys) {
|
||||
const directHit = this.fastProbabilisticSearch(attachDir, key)
|
||||
const directHit = this.fastProbabilisticSearch(attachDir, key, allowThumbnail)
|
||||
if (directHit) return directHit
|
||||
}
|
||||
|
||||
const legacyHit = this.findImageFileInLegacyDirs(accountDir, searchKeys[0])
|
||||
const legacyHit = this.findImageFileInLegacyDirs(accountDir, searchKeys[0], allowThumbnail)
|
||||
if (legacyHit) return legacyHit
|
||||
|
||||
console.log('[ImageDecrypt] findImageFile miss for:', searchKeys)
|
||||
return null
|
||||
}
|
||||
|
||||
private fastProbabilisticSearch(attachDir: string, datName: string): string | null {
|
||||
private fastProbabilisticSearch(
|
||||
attachDir: string,
|
||||
datName: string,
|
||||
allowThumbnail = true
|
||||
): string | null {
|
||||
const normalized = this.normalizeDatBase(datName)
|
||||
if (!normalized) return null
|
||||
|
||||
@@ -131,7 +144,7 @@ export class ImageDecryptService {
|
||||
join(attachDir, dir1, dir2, 'Image', variant),
|
||||
join(attachDir, dir1, dir2, 'image', variant)
|
||||
]
|
||||
const found = candidates.find((candidate) => existsSync(candidate))
|
||||
const found = this.getLargestExistingPath(candidates, allowThumbnail)
|
||||
if (found) {
|
||||
console.log('[ImageDecrypt] prefix path hit:', found)
|
||||
return found
|
||||
@@ -157,9 +170,10 @@ export class ImageDecryptService {
|
||||
const imgDir = join(attachDir, sessDir, month, sub)
|
||||
if (!existsSync(imgDir)) continue
|
||||
|
||||
const found = variants
|
||||
.map((variant) => join(imgDir, variant))
|
||||
.find((candidate) => existsSync(candidate))
|
||||
const found = this.getLargestExistingPath(
|
||||
variants.map((variant) => join(imgDir, variant)),
|
||||
allowThumbnail
|
||||
)
|
||||
if (found) {
|
||||
console.log('[ImageDecrypt] found at:', found)
|
||||
return found
|
||||
@@ -174,7 +188,11 @@ export class ImageDecryptService {
|
||||
return null
|
||||
}
|
||||
|
||||
private findImageFileInLegacyDirs(accountDir: string, datName: string): string | null {
|
||||
private findImageFileInLegacyDirs(
|
||||
accountDir: string,
|
||||
datName: string,
|
||||
allowThumbnail = true
|
||||
): string | null {
|
||||
const normalized = this.normalizeDatBase(datName)
|
||||
if (!normalized) return null
|
||||
|
||||
@@ -185,18 +203,27 @@ export class ImageDecryptService {
|
||||
].filter((root) => existsSync(root))
|
||||
|
||||
for (const root of roots) {
|
||||
const found = this.recursiveFindDat(root, normalized, 5)
|
||||
const found = this.recursiveFindDat(root, normalized, 5, allowThumbnail)
|
||||
if (found) return found
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
private recursiveFindDat(dir: string, datName: string, depth: number): string | null {
|
||||
private recursiveFindDat(
|
||||
dir: string,
|
||||
datName: string,
|
||||
depth: number,
|
||||
allowThumbnail = true
|
||||
): string | null {
|
||||
if (depth < 0) return null
|
||||
|
||||
try {
|
||||
const variants = new Set(this.buildPreferredDatNames(datName))
|
||||
const variants = new Set(
|
||||
this.buildPreferredDatNames(datName).filter(
|
||||
(name) => allowThumbnail || !this.isThumbnailName(name)
|
||||
)
|
||||
)
|
||||
const entries = readdirSync(dir)
|
||||
for (const entry of entries) {
|
||||
const fullPath = join(dir, entry)
|
||||
@@ -210,7 +237,7 @@ export class ImageDecryptService {
|
||||
for (const entry of entries) {
|
||||
const fullPath = join(dir, entry)
|
||||
if (!statSync(fullPath).isDirectory()) continue
|
||||
const found = this.recursiveFindDat(fullPath, datName, depth - 1)
|
||||
const found = this.recursiveFindDat(fullPath, datName, depth - 1, allowThumbnail)
|
||||
if (found) return found
|
||||
}
|
||||
} catch {
|
||||
@@ -290,6 +317,39 @@ export class ImageDecryptService {
|
||||
return `data:${mimeType};base64,${unwrapped.toString('base64')}`
|
||||
}
|
||||
|
||||
/**
|
||||
* 首选 DAT 无法解密时,继续尝试同目录下属于同一图片的其他清晰度变体。
|
||||
* 微信可能只保留 base/_h/_hd/_t 中的一部分,不能把首个文件失败等同于整张图失败。
|
||||
*/
|
||||
decryptImageToBase64WithFallback(
|
||||
datPath: string,
|
||||
allowThumbnail = true
|
||||
): { data: string; filePath: string } | null {
|
||||
const candidates = [datPath]
|
||||
if (extname(datPath).toLowerCase().includes('dat')) {
|
||||
const dir = dirname(datPath)
|
||||
const base = this.normalizeDatBase(basename(datPath))
|
||||
const siblings = this.buildPreferredDatNames(base)
|
||||
.filter((name) => allowThumbnail || !this.isThumbnailName(name))
|
||||
.map((name) => join(dir, name))
|
||||
.filter((candidate) => existsSync(candidate))
|
||||
.sort((left, right) => {
|
||||
const leftThumb = this.isThumbnailName(basename(left)) ? 1 : 0
|
||||
const rightThumb = this.isThumbnailName(basename(right)) ? 1 : 0
|
||||
if (leftThumb !== rightThumb) return leftThumb - rightThumb
|
||||
return statSync(right).size - statSync(left).size
|
||||
})
|
||||
candidates.push(...siblings)
|
||||
}
|
||||
|
||||
for (const candidate of this.uniq(candidates)) {
|
||||
const data = this.decryptImageToBase64(candidate)
|
||||
if (data) return { data, filePath: candidate }
|
||||
}
|
||||
console.warn('[ImageDecrypt] all variants failed:', this.uniq(candidates))
|
||||
return null
|
||||
}
|
||||
|
||||
/**
|
||||
* 检测 DAT 文件版本
|
||||
*/
|
||||
@@ -418,9 +478,11 @@ export class ImageDecryptService {
|
||||
const base = this.normalizeDatBase(baseName)
|
||||
if (!base) return []
|
||||
return [
|
||||
`${base}_h.dat`,
|
||||
`${base}.dat`,
|
||||
`${base}_hd.dat`,
|
||||
`${base}_h.dat`,
|
||||
`${base}_b.dat`,
|
||||
`${base}_w.dat`,
|
||||
`${base}_c.dat`,
|
||||
`${base}_t.dat`,
|
||||
`${base}.thumb.dat`,
|
||||
@@ -435,18 +497,46 @@ export class ImageDecryptService {
|
||||
const ordered = allowThumbnail
|
||||
? variants
|
||||
: variants.filter((name) => !this.isThumbnailName(name))
|
||||
for (const variant of ordered) {
|
||||
const candidate = join(actualDir, variant)
|
||||
if (existsSync(candidate)) return candidate
|
||||
}
|
||||
const largest = this.getLargestExistingPath(
|
||||
ordered.map((variant) => join(actualDir, variant)),
|
||||
allowThumbnail
|
||||
)
|
||||
if (largest) return largest
|
||||
return inputPath
|
||||
}
|
||||
|
||||
private getLargestExistingPath(paths: string[], allowThumbnail: boolean): string | null {
|
||||
const toSized = (candidates: string[]): { candidate: string; size: number }[] =>
|
||||
candidates
|
||||
.filter((candidate) => existsSync(candidate))
|
||||
.map((candidate) => {
|
||||
try {
|
||||
return { candidate, size: statSync(candidate).size }
|
||||
} catch {
|
||||
return { candidate, size: 0 }
|
||||
}
|
||||
})
|
||||
.sort((left, right) => right.size - left.size)
|
||||
|
||||
const nonThumb = toSized(
|
||||
paths.filter((candidate) => !this.isThumbnailName(basename(candidate)))
|
||||
)
|
||||
if (nonThumb[0]) return nonThumb[0].candidate
|
||||
if (!allowThumbnail) return null
|
||||
|
||||
const existing = toSized(paths)
|
||||
return existing[0]?.candidate || null
|
||||
}
|
||||
|
||||
private isThumbnailName(fileName: string): boolean {
|
||||
const lower = fileName.toLowerCase()
|
||||
return lower.includes('_t.dat') || lower.includes('_thumb.dat') || lower.includes('.thumb.dat')
|
||||
}
|
||||
|
||||
isThumbnailFile(filePath: string): boolean {
|
||||
return this.isThumbnailName(basename(filePath))
|
||||
}
|
||||
|
||||
private unwrapWxgf(buffer: Buffer): Buffer {
|
||||
if (
|
||||
buffer.length < 20 ||
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
import { app, safeStorage } from 'electron'
|
||||
import fs from 'fs-extra'
|
||||
import path from 'path'
|
||||
|
||||
export interface StoredImageKeyEntry {
|
||||
xorKey: string
|
||||
aesKey: string
|
||||
updatedAt: number
|
||||
}
|
||||
|
||||
interface StoredImageKeyFile {
|
||||
version: 1
|
||||
accounts: Record<string, StoredImageKeyEntry>
|
||||
}
|
||||
|
||||
interface StoreReadResult {
|
||||
success: boolean
|
||||
data?: StoredImageKeyFile
|
||||
error?: string
|
||||
encryptionAvailable: boolean
|
||||
}
|
||||
|
||||
export class ImageKeyStore {
|
||||
private get filePath(): string {
|
||||
return path.join(app.getPath('userData'), 'wechat-image-keys.bin')
|
||||
}
|
||||
|
||||
get(accountId: string): StoreReadResult & { entry?: StoredImageKeyEntry } {
|
||||
const result = this.read()
|
||||
return { ...result, entry: result.data?.accounts[accountId] }
|
||||
}
|
||||
|
||||
save(
|
||||
accountId: string,
|
||||
entry: Omit<StoredImageKeyEntry, 'updatedAt'>
|
||||
): { success: boolean; entry?: StoredImageKeyEntry; error?: string } {
|
||||
if (!safeStorage.isEncryptionAvailable()) {
|
||||
return { success: false, error: '系统安全存储不可用' }
|
||||
}
|
||||
const current = this.read()
|
||||
if (!current.success && fs.existsSync(this.filePath)) {
|
||||
return { success: false, error: '无法读取现有图片密钥配置' }
|
||||
}
|
||||
const nextEntry = { ...entry, updatedAt: Date.now() }
|
||||
const data: StoredImageKeyFile = current.data || { version: 1, accounts: {} }
|
||||
data.accounts[accountId] = nextEntry
|
||||
const saved = this.write(data)
|
||||
return saved.success ? { success: true, entry: nextEntry } : saved
|
||||
}
|
||||
|
||||
clear(accountId: string): { success: boolean; error?: string } {
|
||||
const current = this.read()
|
||||
if (!current.success) return { success: false, error: current.error }
|
||||
if (!current.data?.accounts[accountId]) return { success: true }
|
||||
delete current.data.accounts[accountId]
|
||||
try {
|
||||
if (Object.keys(current.data.accounts).length === 0) fs.removeSync(this.filePath)
|
||||
else return this.write(current.data)
|
||||
return { success: true }
|
||||
} catch {
|
||||
return { success: false, error: '无法清除图片密钥配置' }
|
||||
}
|
||||
}
|
||||
|
||||
private read(): StoreReadResult {
|
||||
const encryptionAvailable = safeStorage.isEncryptionAvailable()
|
||||
if (!fs.existsSync(this.filePath)) {
|
||||
return {
|
||||
success: true,
|
||||
data: { version: 1, accounts: {} },
|
||||
encryptionAvailable
|
||||
}
|
||||
}
|
||||
if (!encryptionAvailable) {
|
||||
return { success: false, error: '系统安全存储不可用', encryptionAvailable }
|
||||
}
|
||||
try {
|
||||
const decrypted = safeStorage.decryptString(fs.readFileSync(this.filePath))
|
||||
const data = JSON.parse(decrypted) as StoredImageKeyFile
|
||||
if (data.version !== 1 || !data.accounts) throw new Error('invalid image key store')
|
||||
return { success: true, data, encryptionAvailable }
|
||||
} catch {
|
||||
return { success: false, error: '图片密钥安全存储不可读取', encryptionAvailable }
|
||||
}
|
||||
}
|
||||
|
||||
private write(data: StoredImageKeyFile): { success: boolean; error?: string } {
|
||||
try {
|
||||
fs.ensureDirSync(path.dirname(this.filePath))
|
||||
fs.writeFileSync(this.filePath, safeStorage.encryptString(JSON.stringify(data)), {
|
||||
mode: 0o600
|
||||
})
|
||||
fs.chmodSync(this.filePath, 0o600)
|
||||
return { success: true }
|
||||
} catch {
|
||||
return { success: false, error: '图片密钥保存失败' }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,26 +1,72 @@
|
||||
import { app, shell, BrowserWindow, ipcMain, nativeImage, clipboard, Menu, Tray } from 'electron'
|
||||
import './preload-env'
|
||||
import {
|
||||
app,
|
||||
shell,
|
||||
BrowserWindow,
|
||||
ipcMain,
|
||||
nativeImage,
|
||||
clipboard,
|
||||
Menu,
|
||||
Tray,
|
||||
dialog
|
||||
} from 'electron'
|
||||
import { join } from 'path'
|
||||
import { existsSync } from 'fs'
|
||||
import { electronApp, optimizer, is } from '@electron-toolkit/utils'
|
||||
import icon from '../../resources/icon.png?asset'
|
||||
import { WechatDb } from './wechat-db'
|
||||
import { bootstrapWcdbNative } from './wcdb4-client'
|
||||
import { VoiceService } from './voice-service'
|
||||
import { StickerService } from './sticker-service'
|
||||
import { parseMessageContent } from './message-parser'
|
||||
import { ImageDecryptService } from './image-decrypt-service'
|
||||
import { exportGroupReport } from './group-report-service'
|
||||
import { GroupReportExportRequest } from '../shared/group-report'
|
||||
import {
|
||||
deleteGeneratedReport,
|
||||
listGeneratedReports,
|
||||
saveGeneratedReport
|
||||
} from './report-history-service'
|
||||
import type { GroupReportExportRequest } from '../shared/group-report'
|
||||
import type { SaveGeneratedReportRequest } from '../shared/report-history'
|
||||
import type {
|
||||
AIChatRequestOptions,
|
||||
AIProviderConfig,
|
||||
AIVisionTestRequest,
|
||||
LegacyAIConfig
|
||||
} from '../shared/ai-provider'
|
||||
import { DatabaseKeyStore } from './database-key-store'
|
||||
import { ImageKeyConfigService } from './services/image-key-config-service'
|
||||
import { AIProviderService } from './services/ai-provider-service'
|
||||
import { imageInsightService } from './services/image-insight-service'
|
||||
import type {
|
||||
ImageAnalysisRequest,
|
||||
ImageAnalysisResponse,
|
||||
ImageCandidate,
|
||||
ImageCandidateQuery,
|
||||
ImageInsight
|
||||
} from '../shared/image-insight'
|
||||
import { KeyServiceMac } from './key-service-mac'
|
||||
import { KeyService as KeyServiceWin } from './key-service-win'
|
||||
import * as chat from './services/chat-service'
|
||||
import { apiServer } from './http-server'
|
||||
import { skillResourceService } from './services/skill-resource-service'
|
||||
import { testLocalApiRequest } from './services/local-api-test-service'
|
||||
import { isWindowsWechatRunning } from './services/wechat-process-status'
|
||||
import {
|
||||
apiServer
|
||||
} from './http-server'
|
||||
inspectImageDecryptionStatus,
|
||||
testImageDecryption
|
||||
} from './services/image-decryption-status-service'
|
||||
import type { SaveImageKeyRequest, TestImageDecryptionRequest } from '../shared/image-decryption'
|
||||
import { loadSettings, saveSettings, getSettingsPath, AppSettings } from './services/settings-store'
|
||||
import {
|
||||
loadSettings,
|
||||
saveSettings,
|
||||
getSettingsPath,
|
||||
AppSettings
|
||||
} from './services/settings-store'
|
||||
getBootstrapCache,
|
||||
getCachedMessages,
|
||||
mergeBootstrapAvatars,
|
||||
mergeCachedContactAvatars,
|
||||
saveBootstrapContacts,
|
||||
saveBootstrapSelf,
|
||||
saveCachedMessages
|
||||
} from './services/bootstrap-cache'
|
||||
import { installSafeConsole } from './safe-log'
|
||||
|
||||
// electron-vite can close the child's stdout/stderr after spawning Electron.
|
||||
@@ -32,24 +78,40 @@ let voiceService: VoiceService | null = null
|
||||
let imageDecryptService: ImageDecryptService | null = null
|
||||
let stickerService: StickerService | null = null
|
||||
const databaseKeyStore = new DatabaseKeyStore()
|
||||
const imageKeyConfigService = new ImageKeyConfigService()
|
||||
const aiProviderService = new AIProviderService()
|
||||
const keyServiceMac = new KeyServiceMac()
|
||||
const keyServiceWin = new KeyServiceWin()
|
||||
let tray: Tray | null = null
|
||||
|
||||
const packagedIconPath = join(process.resourcesPath, 'resources', 'icon.png')
|
||||
const appIconPath = existsSync(packagedIconPath) ? packagedIconPath : icon
|
||||
|
||||
// WCDB's Windows runtime checks the host application name during wcdb_init.
|
||||
// Mirroring WeFlow's name unblocks the -1006 init failure on Windows.
|
||||
app.setName(process.platform === 'win32' ? 'WeFlow' : 'WechatExplorer')
|
||||
let dbInitInFlight: Promise<{ success: boolean; monitoring?: boolean; error?: string }> | null =
|
||||
null
|
||||
const BUILD_MARK = 'wechat4-local-http-api-2026-07-03'
|
||||
const TRAY_MODE =
|
||||
process.argv.includes('--tray') || (process.env['WXE_TRAY'] || '').toString() === '1'
|
||||
|
||||
// WechatExplorer's WCDB native library runs InitProtection before wcdb_init.
|
||||
// In dev, matching the host app name avoids failing the native protection gate.
|
||||
app.setName('WechatExplorer')
|
||||
function getConfiguredImageKeys(): { xorKey: string; aesKey: string } {
|
||||
const config = imageKeyConfigService.getConfig()
|
||||
return {
|
||||
xorKey: config.xorKey || '0x40',
|
||||
aesKey: config.aesKey || ''
|
||||
}
|
||||
}
|
||||
|
||||
function createWindow(): void {
|
||||
// 创建浏览器窗口
|
||||
// 鍒涘缓娴忚鍣ㄧ獥鍙?
|
||||
const mainWindow = new BrowserWindow({
|
||||
width: 1400,
|
||||
height: 800,
|
||||
show: false,
|
||||
autoHideMenuBar: true,
|
||||
...(process.platform === 'linux' ? { icon } : {}),
|
||||
icon: appIconPath,
|
||||
webPreferences: {
|
||||
preload: join(__dirname, '../preload/index.js'),
|
||||
sandbox: false
|
||||
@@ -65,8 +127,8 @@ function createWindow(): void {
|
||||
return { action: 'deny' }
|
||||
})
|
||||
|
||||
// 基于 electron-vite cli 的渲染器 HMR
|
||||
// 加载开发环境的远程 URL 或生产环境的本地 html 文件
|
||||
// 鍩轰簬 electron-vite cli 鐨勬覆鏌撳櫒 HMR
|
||||
// 鍔犺浇寮€鍙戠幆澧冪殑杩滅▼ URL 鎴栫敓浜х幆澧冪殑鏈湴 html 鏂囦欢
|
||||
if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
|
||||
mainWindow.loadURL(process.env['ELECTRON_RENDERER_URL'])
|
||||
} else {
|
||||
@@ -74,16 +136,29 @@ function createWindow(): void {
|
||||
}
|
||||
}
|
||||
|
||||
// 当 Electron 完成初始化并准备好创建浏览器窗口时,将调用此方法
|
||||
// 某些 API 只能在此事件发生后使用
|
||||
// 褰?Electron 瀹屾垚鍒濆鍖栧苟鍑嗗濂藉垱寤烘祻瑙堝櫒绐楀彛鏃讹紝灏嗚皟鐢ㄦ鏂规硶
|
||||
// 鏌愪簺 API 鍙兘鍦ㄦ浜嬩欢鍙戠敓鍚庝娇鐢?
|
||||
app.whenReady().then(async () => {
|
||||
console.log(`WechatExplorer main build: ${BUILD_MARK}`)
|
||||
// 为窗口设置应用程序用户模型 ID
|
||||
electronApp.setAppUserModelId('com.electron')
|
||||
|
||||
// 在开发环境中默认按 F12 打开或关闭 DevTools
|
||||
// 在生产环境中忽略 CommandOrControl + R
|
||||
// 参见 https://github.com/alex8088/electron-toolkit/tree/master/packages/utils
|
||||
// WCDB's Windows runtime returns -1006 if wcdb_init is called more than once
|
||||
// per process. Bootstrap native once here so any later Wcdb4Client instance
|
||||
// reuses the already-initialized library and skips wcdb_init.
|
||||
try {
|
||||
bootstrapWcdbNative()
|
||||
console.log('[WCDB4] bootstrap complete at whenReady top')
|
||||
} catch (bootstrapError) {
|
||||
console.error('[WCDB4] bootstrap failed at whenReady top:', bootstrapError)
|
||||
}
|
||||
|
||||
// 涓虹獥鍙h缃簲鐢ㄧ▼搴忕敤鎴锋ā鍨?ID
|
||||
electronApp.setAppUserModelId('com.wechatexplorer.app')
|
||||
|
||||
if (process.platform === 'darwin') app.dock?.setIcon(appIconPath)
|
||||
|
||||
// 鍦ㄥ紑鍙戠幆澧冧腑榛樿鎸?F12 鎵撳紑鎴栧叧闂?DevTools
|
||||
// 鍦ㄧ敓浜х幆澧冧腑蹇界暐 CommandOrControl + R
|
||||
// 鍙傝 https://github.com/alex8088/electron-toolkit/tree/master/packages/utils
|
||||
app.on('browser-window-created', (_, window) => {
|
||||
optimizer.watchWindowShortcuts(window)
|
||||
})
|
||||
@@ -91,45 +166,95 @@ app.whenReady().then(async () => {
|
||||
// IPC test
|
||||
ipcMain.on('ping', () => console.log('pong'))
|
||||
|
||||
ipcMain.handle('db:init', (_, key: string) => {
|
||||
try {
|
||||
const trimmedKey = String(key || '').trim()
|
||||
console.log(`db:init build=${BUILD_MARK} keyLength=${trimmedKey.length}`)
|
||||
const nextWechatDb = new WechatDb(key)
|
||||
chat.setChatDb(nextWechatDb)
|
||||
const wcdb4Client = nextWechatDb.getWcdb4Client()
|
||||
voiceService = new VoiceService(wcdb4Client)
|
||||
stickerService = new StickerService(wcdb4Client)
|
||||
const monitoring = wcdb4Client.startMonitor((type, json) => {
|
||||
for (const window of BrowserWindow.getAllWindows()) {
|
||||
if (!window.isDestroyed()) window.webContents.send('wcdb-change', { type, json })
|
||||
ipcMain.handle('db:init', async (_, key: string) => {
|
||||
if (dbInitInFlight) return dbInitInFlight
|
||||
|
||||
dbInitInFlight = (async () => {
|
||||
try {
|
||||
const trimmedKey = String(key || '').trim()
|
||||
console.log(`db:init build=${BUILD_MARK} keyLength=${trimmedKey.length}`)
|
||||
const settings = loadSettings()
|
||||
if (
|
||||
chat.isReady() &&
|
||||
chat.getCurrentKey().replace(/^0x/i, '').trim() === trimmedKey.replace(/^0x/i, '') &&
|
||||
(!settings.dbRoot || chat.getCurrentAccountRoot() === settings.dbRoot)
|
||||
) {
|
||||
console.log('[WCDB4] db:init reuse current connection')
|
||||
return { success: true, monitoring: true }
|
||||
}
|
||||
})
|
||||
imageDecryptService = null
|
||||
return { success: true, monitoring }
|
||||
} catch (error) {
|
||||
console.error('Failed to init DB:', error)
|
||||
return { success: false, error: error instanceof Error ? error.message : String(error) }
|
||||
}
|
||||
const nextWechatDb = await WechatDb.create(key, settings.dbRoot)
|
||||
const resolvedRoot = nextWechatDb.getWcdb4Client().getAccountRoot()
|
||||
if (resolvedRoot && resolvedRoot !== settings.dbRoot) {
|
||||
saveSettings({ ...settings, dbRoot: resolvedRoot })
|
||||
}
|
||||
chat.setChatDb(nextWechatDb)
|
||||
const wcdb4Client = nextWechatDb.getWcdb4Client()
|
||||
voiceService = new VoiceService(wcdb4Client)
|
||||
stickerService = new StickerService(wcdb4Client)
|
||||
const monitoring = wcdb4Client.startMonitor((type, json) => {
|
||||
for (const window of BrowserWindow.getAllWindows()) {
|
||||
if (!window.isDestroyed()) window.webContents.send('wcdb-change', { type, json })
|
||||
}
|
||||
})
|
||||
imageDecryptService = null
|
||||
return { success: true, monitoring }
|
||||
} catch (error) {
|
||||
console.error('Failed to init DB:', error)
|
||||
return { success: false, error: error instanceof Error ? error.message : String(error) }
|
||||
} finally {
|
||||
dbInitInFlight = null
|
||||
}
|
||||
})()
|
||||
|
||||
return dbInitInFlight
|
||||
})
|
||||
|
||||
ipcMain.handle('key:getSavedDbKey', async () => databaseKeyStore.load())
|
||||
|
||||
ipcMain.handle('key:getEnvironment', async () => {
|
||||
const storage = await databaseKeyStore.getStatus()
|
||||
const self = chat.getSelfAccountInfo()
|
||||
return {
|
||||
platform: process.platform,
|
||||
autoDetectSupported: process.platform === 'win32',
|
||||
wechatRunning: await isWindowsWechatRunning(),
|
||||
accountIdentified: Boolean(self?.wxid),
|
||||
dbConnected: chat.isReady(),
|
||||
encryptionAvailable: storage.encryptionAvailable
|
||||
}
|
||||
})
|
||||
|
||||
ipcMain.handle('key:readClipboardDbKey', () => {
|
||||
try {
|
||||
return { success: true, value: clipboard.readText().trim() }
|
||||
} catch {
|
||||
return { success: false, error: '无法读取剪贴板' }
|
||||
}
|
||||
})
|
||||
|
||||
ipcMain.handle('key:pasteAndSaveDbKey', async () => {
|
||||
const clipboardKey = clipboard.readText().trim()
|
||||
return databaseKeyStore.save(clipboardKey)
|
||||
})
|
||||
|
||||
ipcMain.handle('key:saveDbKey', async (_, key: string) => databaseKeyStore.save(String(key || '')))
|
||||
ipcMain.handle('key:saveDbKey', async (_, key: string) =>
|
||||
databaseKeyStore.save(String(key || ''))
|
||||
)
|
||||
|
||||
ipcMain.handle('key:clearSavedDbKey', async () => databaseKeyStore.clear())
|
||||
|
||||
ipcMain.handle('key:autoGetDbKey', async (event) => {
|
||||
const result = await keyServiceMac.autoGetDbKey((message) => {
|
||||
ipcMain.handle('key:autoGetDbKey', async (event, options?: { save?: boolean }) => {
|
||||
const onStatus = (message: string): void => {
|
||||
if (!event.sender.isDestroyed()) event.sender.send('key:dbKeyStatus', { message })
|
||||
})
|
||||
}
|
||||
const result =
|
||||
process.platform === 'win32'
|
||||
? await keyServiceWin.autoGetDbKey(60_000, onStatus)
|
||||
: await keyServiceMac.autoGetDbKey(onStatus)
|
||||
if (!result.success || !result.key) return result
|
||||
|
||||
if (options?.save === false) return result
|
||||
|
||||
const saved = await databaseKeyStore.save(result.key)
|
||||
return {
|
||||
...result,
|
||||
@@ -138,10 +263,110 @@ app.whenReady().then(async () => {
|
||||
}
|
||||
})
|
||||
|
||||
ipcMain.handle('db:getContacts', (_, filter?: string) => chat.listContacts(filter))
|
||||
ipcMain.handle('key:autoGetImageKey', async (event, options?: { save?: boolean }) => {
|
||||
const settings = loadSettings()
|
||||
const self = chat.getSelfAccountInfo()
|
||||
const accountRoot = settings.imageKeyRoot || self?.accountRoot || settings.dbRoot
|
||||
const wxid = self?.wxid
|
||||
const onStatus = (message: string): void => {
|
||||
if (!event.sender.isDestroyed()) event.sender.send('key:imageKeyStatus', { message })
|
||||
}
|
||||
const result =
|
||||
process.platform === 'win32'
|
||||
? await keyServiceWin.autoGetImageKeyByMemoryScan(accountRoot, onStatus)
|
||||
: await keyServiceMac.autoGetImageKey(accountRoot, onStatus, wxid)
|
||||
|
||||
ipcMain.handle('db:getMessages', (_, userMd5: string, startTime?: number, endTime?: number) =>
|
||||
chat.listMessages(userMd5, startTime, endTime)
|
||||
if (!result.success || !result.aesKey) return result
|
||||
if (process.platform === 'win32') {
|
||||
onStatus('发现候选密钥,图片模板验证通过')
|
||||
}
|
||||
|
||||
const imageXorKey = `0x${Number(result.xorKey ?? 0x40)
|
||||
.toString(16)
|
||||
.toUpperCase()
|
||||
.padStart(2, '0')}`
|
||||
const verified = result.verified ?? process.platform === 'win32'
|
||||
if (options?.save === false) {
|
||||
return { ...result, verified, imageXorKey, imageAesKey: result.aesKey }
|
||||
}
|
||||
const saved = imageKeyConfigService.save({
|
||||
resourceRoot: accountRoot,
|
||||
xorKey: imageXorKey,
|
||||
aesKey: result.aesKey
|
||||
})
|
||||
if (saved.success) imageDecryptService = null
|
||||
return {
|
||||
...result,
|
||||
success: saved.success,
|
||||
error: saved.success ? undefined : saved.error,
|
||||
verified,
|
||||
imageXorKey,
|
||||
imageAesKey: result.aesKey,
|
||||
settings: imageKeyConfigService.getLegacySettingsView()
|
||||
}
|
||||
})
|
||||
|
||||
ipcMain.handle('image:getConfig', () => imageKeyConfigService.getConfig())
|
||||
|
||||
ipcMain.handle('image:getStatus', async () =>
|
||||
inspectImageDecryptionStatus(imageKeyConfigService.getConfig())
|
||||
)
|
||||
|
||||
ipcMain.handle('image:saveConfig', (_, request: SaveImageKeyRequest) => {
|
||||
const result = imageKeyConfigService.save(request)
|
||||
if (result.success) imageDecryptService = null
|
||||
return result
|
||||
})
|
||||
|
||||
ipcMain.handle('image:testConfig', (_, request: TestImageDecryptionRequest) =>
|
||||
testImageDecryption(request)
|
||||
)
|
||||
|
||||
ipcMain.handle('image:clearConfig', () => {
|
||||
const result = imageKeyConfigService.clear()
|
||||
if (result.success) imageDecryptService = null
|
||||
return result
|
||||
})
|
||||
|
||||
ipcMain.handle('db:getBootstrapCache', () => {
|
||||
if (!chat.isReady()) return null
|
||||
return getBootstrapCache(chat.getCurrentAccountRoot())
|
||||
})
|
||||
|
||||
ipcMain.handle(
|
||||
'db:getCachedMessages',
|
||||
(_, userMd5: string, startTime?: number, endTime?: number) => {
|
||||
if (!chat.isReady()) return []
|
||||
return getCachedMessages(chat.getCurrentAccountRoot(), userMd5, startTime, endTime)
|
||||
}
|
||||
)
|
||||
|
||||
ipcMain.handle('db:getContacts', (_, filter?: string) => {
|
||||
const accountRoot = chat.getCurrentAccountRoot()
|
||||
const contacts = accountRoot
|
||||
? mergeCachedContactAvatars(accountRoot, chat.listContacts(filter))
|
||||
: chat.listContacts(filter)
|
||||
if (!filter && chat.isReady() && accountRoot) {
|
||||
saveBootstrapContacts(accountRoot, contacts)
|
||||
}
|
||||
return contacts
|
||||
})
|
||||
|
||||
ipcMain.handle('db:getContactAvatars', (_, usernames: string[]) => {
|
||||
const avatars = chat.getContactAvatars(usernames)
|
||||
if (chat.isReady()) mergeBootstrapAvatars(chat.getCurrentAccountRoot(), avatars)
|
||||
return avatars
|
||||
})
|
||||
|
||||
ipcMain.handle(
|
||||
'db:getMessages',
|
||||
(_, userMd5: string, startTime?: number, endTime?: number, options?: { limit?: number }) => {
|
||||
const messages = chat.listMessages(userMd5, startTime, endTime, options)
|
||||
if (chat.isReady()) {
|
||||
saveCachedMessages(chat.getCurrentAccountRoot(), userMd5, startTime, endTime, messages)
|
||||
}
|
||||
return messages
|
||||
}
|
||||
)
|
||||
|
||||
ipcMain.handle('db:getGroupSnapshot', (_, userMd5: string) => chat.getGroupSnapshot(userMd5))
|
||||
@@ -150,41 +375,27 @@ app.whenReady().then(async () => {
|
||||
|
||||
ipcMain.handle(
|
||||
'ai:chat',
|
||||
async (
|
||||
_,
|
||||
messages: { role: string; content: string }[],
|
||||
options?: { apiKey?: string; model?: string; baseURL?: string }
|
||||
) => {
|
||||
// @ts-ignore: vite env
|
||||
const apiKey = options?.apiKey || import.meta.env.VITE_DEEPSEEK_API_KEY
|
||||
const model = options?.model || import.meta.env.VITE_AI_MODEL || 'deepseek-chat'
|
||||
const baseURL =
|
||||
options?.baseURL || import.meta.env.VITE_AI_BASE_URL || 'https://api.deepseek.com'
|
||||
async (_, messages: { role: string; content: string }[], options?: AIChatRequestOptions) =>
|
||||
aiProviderService.chat(messages, options)
|
||||
)
|
||||
|
||||
if (!apiKey) {
|
||||
return { success: false, error: '未配置 API Key' }
|
||||
}
|
||||
|
||||
// 动态导入以避免如果未安装或初始类型缺失的问题
|
||||
const { OpenAI } = await import('openai')
|
||||
|
||||
const openai = new OpenAI({
|
||||
baseURL,
|
||||
apiKey
|
||||
})
|
||||
try {
|
||||
const completion = await openai.chat.completions.create({
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
messages: messages as any,
|
||||
model: model
|
||||
})
|
||||
return { success: true, data: completion.choices[0].message.content }
|
||||
} catch (error: unknown) {
|
||||
console.error('AI API Error:', error)
|
||||
const errorMessage = error instanceof Error ? error.message : 'Unknown error'
|
||||
return { success: false, error: errorMessage }
|
||||
}
|
||||
}
|
||||
ipcMain.handle('ai:listProviders', () => aiProviderService.list())
|
||||
ipcMain.handle('ai:getRuntimeConfig', () => aiProviderService.getRuntimeConfig())
|
||||
ipcMain.handle('ai:saveProvider', (_, provider: AIProviderConfig) =>
|
||||
aiProviderService.save(provider)
|
||||
)
|
||||
ipcMain.handle('ai:deleteProvider', (_, providerId: string) =>
|
||||
aiProviderService.delete(providerId)
|
||||
)
|
||||
ipcMain.handle('ai:setDefaultProvider', (_, providerId: string) =>
|
||||
aiProviderService.setDefault(providerId)
|
||||
)
|
||||
ipcMain.handle('ai:testProvider', (_, providerId: string) => aiProviderService.test(providerId))
|
||||
ipcMain.handle('ai:testVision', (_, request: AIVisionTestRequest) =>
|
||||
aiProviderService.testVision(request)
|
||||
)
|
||||
ipcMain.handle('ai:migrateLegacy', (_, config: LegacyAIConfig) =>
|
||||
aiProviderService.migrateLegacy(config)
|
||||
)
|
||||
|
||||
ipcMain.handle('copy-image', async (_, base64String) => {
|
||||
@@ -201,6 +412,18 @@ app.whenReady().then(async () => {
|
||||
return exportGroupReport(request)
|
||||
})
|
||||
|
||||
ipcMain.handle('report:listGenerated', async () => {
|
||||
return listGeneratedReports()
|
||||
})
|
||||
|
||||
ipcMain.handle('report:saveGenerated', async (_, request: SaveGeneratedReportRequest) => {
|
||||
return saveGeneratedReport(request)
|
||||
})
|
||||
|
||||
ipcMain.handle('report:deleteGenerated', async (_, reportId: string) => {
|
||||
return deleteGeneratedReport(reportId)
|
||||
})
|
||||
|
||||
ipcMain.handle('report:reveal', async (_, filePath: string) => {
|
||||
try {
|
||||
shell.showItemInFolder(filePath)
|
||||
@@ -226,30 +449,139 @@ app.whenReady().then(async () => {
|
||||
|
||||
ipcMain.handle(
|
||||
'db:getImage',
|
||||
async (_, imageMd5?: string, imageDatNameOrThumb?: string | boolean, _sessionId?: string) => {
|
||||
async (
|
||||
_,
|
||||
imageMd5?: string,
|
||||
imageDatNameOrThumb?: string | boolean,
|
||||
_sessionId?: string,
|
||||
options?: { force?: boolean }
|
||||
) => {
|
||||
void _sessionId
|
||||
if (!imageDecryptService) {
|
||||
// 从环境变量获取密钥
|
||||
const xorKey = import.meta.env.VITE_IMAGE_XOR_KEY || '0x40'
|
||||
const aesKey = import.meta.env.VITE_IMAGE_AES_KEY || ''
|
||||
const { xorKey, aesKey } = getConfiguredImageKeys()
|
||||
if (!aesKey) {
|
||||
return { success: false, error: '未配置图片解密密钥' }
|
||||
}
|
||||
imageDecryptService = new ImageDecryptService(xorKey, aesKey, chat.getChatDb()?.getWcdb4Client())
|
||||
imageDecryptService = new ImageDecryptService(
|
||||
xorKey,
|
||||
aesKey,
|
||||
chat.getChatDb()?.getWcdb4Client()
|
||||
)
|
||||
}
|
||||
|
||||
const imageDatName = typeof imageDatNameOrThumb === 'string' ? imageDatNameOrThumb : undefined
|
||||
const filePath = imageDecryptService.findImageFile(imageMd5, imageDatName)
|
||||
const force = options?.force === true
|
||||
let filePath = force
|
||||
? imageDecryptService.findImageFile(imageMd5, imageDatName, { allowThumbnail: false })
|
||||
: null
|
||||
if (!filePath) {
|
||||
return { success: false, error: '未找到图片文件' }
|
||||
filePath = imageDecryptService.findImageFile(imageMd5, imageDatName, {
|
||||
allowThumbnail: true
|
||||
})
|
||||
}
|
||||
if (!filePath) {
|
||||
return { success: false, error: force ? '未找到原图或缩略图文件' : '未找到图片文件' }
|
||||
}
|
||||
|
||||
const base64 = imageDecryptService.decryptImageToBase64(filePath)
|
||||
if (!base64) {
|
||||
const decrypted = imageDecryptService.decryptImageToBase64WithFallback(filePath, true)
|
||||
if (!decrypted) {
|
||||
return { success: false, error: '图片解密失败' }
|
||||
}
|
||||
|
||||
return { success: true, data: base64 }
|
||||
return {
|
||||
success: true,
|
||||
data: decrypted.data,
|
||||
isThumb: imageDecryptService.isThumbnailFile(decrypted.filePath),
|
||||
filePath: decrypted.filePath
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
// ============================================================
|
||||
// AI 图片理解基础设施(ImageInsightService)
|
||||
// ============================================================
|
||||
// 注入依赖(用闭包捕获当前 db:getImage 已经初始化过的 imageDecryptService)
|
||||
// 同时把 imageDecryptService 暴露到 globalThis,供 group-report-service 渲染时按 imageHash 取图
|
||||
;(globalThis as { __imageDecrypt?: typeof imageDecryptService }).__imageDecrypt =
|
||||
imageDecryptService
|
||||
imageInsightService.bind({
|
||||
providerService: aiProviderService,
|
||||
decryptService: {
|
||||
findImageFile: (md5, datName, opts) =>
|
||||
imageDecryptService?.findImageFile(md5, datName, opts) ?? null,
|
||||
decryptImageToBase64: (filePath) =>
|
||||
imageDecryptService?.decryptImageToBase64(filePath) ?? null
|
||||
}
|
||||
})
|
||||
|
||||
/** 日报入口:取会话 Top N 热点图片 + 已缓存的 Insight */
|
||||
ipcMain.handle(
|
||||
'image:listCandidates',
|
||||
async (
|
||||
_,
|
||||
query: ImageCandidateQuery
|
||||
): Promise<{ success: boolean; candidates: ImageCandidate[]; error?: string }> => {
|
||||
console.log('[IPC] image:listCandidates query=%j', query)
|
||||
try {
|
||||
const inputs = (query as ImageCandidateQuery & { inputs?: unknown[] }).inputs || []
|
||||
console.log('[IPC] image:listCandidates received %d inputs', inputs.length)
|
||||
const candidates = await imageInsightService.listTopHotImages(query, inputs as never)
|
||||
console.log('[IPC] image:listCandidates returned %d candidates', candidates.length)
|
||||
return { success: true, candidates }
|
||||
} catch (error) {
|
||||
console.warn('[IPC] image:listCandidates failed:', error)
|
||||
return {
|
||||
success: false,
|
||||
candidates: [],
|
||||
error: error instanceof Error ? error.message : String(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
/** 单图分析:缓存命中即返回,未命中调 AI;失败不抛 */
|
||||
ipcMain.handle(
|
||||
'image:analyze',
|
||||
async (_, request: ImageAnalysisRequest): Promise<ImageAnalysisResponse> => {
|
||||
console.log('[IPC] image:analyze hash=%s messageId=%s', request.imageHash, request.messageId)
|
||||
// 校验 provider 是否支持 vision
|
||||
const runtime = aiProviderService.getRuntimeConfig()
|
||||
if (!runtime.configured) {
|
||||
return { success: false, error: '尚未配置 AI Provider' }
|
||||
}
|
||||
const list = aiProviderService.list()
|
||||
const provider = list.providers.find((p) => p.id === runtime.providerId)
|
||||
const model = provider?.models.find((m) => m.id === runtime.model)
|
||||
if (!provider || !model) {
|
||||
return { success: false, error: '当前 AI 模型不存在' }
|
||||
}
|
||||
if (!model.capabilities.vision) {
|
||||
return { success: false, error: '当前模型不支持图片理解' }
|
||||
}
|
||||
// request 来自 renderer,imageHash 是 md5(优先)或 sha256(...),dataUrl 在内部算出
|
||||
// 这里直接调 service,dataUrl 由 renderer 通过 window.api.getImage 拿到再传进来
|
||||
return imageInsightService.analyze(request)
|
||||
}
|
||||
)
|
||||
|
||||
/** 单图查询缓存 */
|
||||
ipcMain.handle(
|
||||
'image:getInsight',
|
||||
async (_, imageHash: string): Promise<{ success: boolean; insight?: ImageInsight }> => {
|
||||
const insight = imageInsightService.getInsight(imageHash)
|
||||
return { success: true, insight: insight || undefined }
|
||||
}
|
||||
)
|
||||
|
||||
/** 列出某会话所有已分析的 insights */
|
||||
ipcMain.handle(
|
||||
'image:listInsights',
|
||||
async (
|
||||
_,
|
||||
sessionId: string,
|
||||
limit?: number
|
||||
): Promise<{ success: boolean; insights: ImageInsight[] }> => {
|
||||
return { success: true, insights: imageInsightService.listBySession(sessionId, limit) }
|
||||
}
|
||||
)
|
||||
|
||||
@@ -263,18 +595,35 @@ app.whenReady().then(async () => {
|
||||
// -------- Settings & API service --------
|
||||
|
||||
ipcMain.handle('settings:get', () => ({
|
||||
settings: loadSettings(),
|
||||
settings: imageKeyConfigService.getLegacySettingsView(),
|
||||
settingsPath: getSettingsPath()
|
||||
}))
|
||||
|
||||
ipcMain.handle('settings:set', (_, patch: Partial<AppSettings>) => {
|
||||
const merged = saveSettings({ ...loadSettings(), ...patch })
|
||||
return { settings: merged, settingsPath: getSettingsPath() }
|
||||
const before = loadSettings()
|
||||
const current = imageKeyConfigService.getConfig()
|
||||
const resourceRoot = patch.imageKeyRoot ?? before.imageKeyRoot
|
||||
const xorKey = patch.imageXorKey ?? current.xorKey ?? '0x40'
|
||||
const aesKey = patch.imageAesKey ?? current.aesKey ?? ''
|
||||
const includesImageKey = 'imageXorKey' in patch || 'imageAesKey' in patch
|
||||
if (includesImageKey) {
|
||||
saveSettings({ ...before, ...patch, imageXorKey: '', imageAesKey: '' })
|
||||
if (aesKey) imageKeyConfigService.save({ resourceRoot, xorKey, aesKey })
|
||||
else imageKeyConfigService.clear()
|
||||
imageDecryptService = null
|
||||
} else {
|
||||
saveSettings({ ...before, ...patch, imageXorKey: '', imageAesKey: '' })
|
||||
}
|
||||
return {
|
||||
settings: imageKeyConfigService.getLegacySettingsView(),
|
||||
settingsPath: getSettingsPath()
|
||||
}
|
||||
})
|
||||
|
||||
ipcMain.handle('settings:getSelf', () => {
|
||||
const info = chat.getSelfAccountInfo()
|
||||
if (!info) return { ready: false }
|
||||
if (chat.isReady()) saveBootstrapSelf(chat.getCurrentAccountRoot(), info)
|
||||
return { ready: true, info }
|
||||
})
|
||||
|
||||
@@ -289,6 +638,28 @@ app.whenReady().then(async () => {
|
||||
return { success: true, info }
|
||||
})
|
||||
|
||||
ipcMain.handle('settings:selectDbRoot', async (event) => {
|
||||
const result = await dialog.showOpenDialog(BrowserWindow.fromWebContents(event.sender)!, {
|
||||
title: '选择微信数据库目录',
|
||||
defaultPath: loadSettings().dbRoot || undefined,
|
||||
properties: ['openDirectory']
|
||||
})
|
||||
return result.canceled ? { canceled: true } : { canceled: false, path: result.filePaths[0] }
|
||||
})
|
||||
|
||||
ipcMain.handle('settings:openAccountRoot', async () => {
|
||||
const accountRoot = chat.getCurrentAccountRoot()
|
||||
if (!accountRoot) return { success: false, error: '当前没有可打开的账号目录' }
|
||||
const error = await shell.openPath(accountRoot)
|
||||
return error ? { success: false, error } : { success: true }
|
||||
})
|
||||
|
||||
ipcMain.handle('db:disconnect', () => {
|
||||
if (!chat.isReady()) return { success: false, error: '数据库当前未连接' }
|
||||
chat.setChatDb(null)
|
||||
return { success: true }
|
||||
})
|
||||
|
||||
ipcMain.handle('api:getStatus', () => apiServer.getState())
|
||||
|
||||
ipcMain.handle('api:start', async (_, host?: string, port?: number) => {
|
||||
@@ -311,9 +682,26 @@ app.whenReady().then(async () => {
|
||||
return apiServer.stop()
|
||||
})
|
||||
|
||||
ipcMain.handle('api:skillStatus', () => skillResourceService.getStatus())
|
||||
ipcMain.handle('api:readSkill', () => skillResourceService.read())
|
||||
ipcMain.handle('api:revealSkill', () => skillResourceService.reveal())
|
||||
ipcMain.handle('api:openSkillGithub', () => skillResourceService.openGithub())
|
||||
ipcMain.handle('api:testLocalRequest', (_, request) => testLocalApiRequest(request))
|
||||
ipcMain.handle('api:copyText', (_, text: unknown) => {
|
||||
if (typeof text !== 'string' || text.length > 1024 * 1024) {
|
||||
return { success: false, error: '复制内容无效或过大' }
|
||||
}
|
||||
try {
|
||||
clipboard.writeText(text)
|
||||
return { success: true }
|
||||
} catch (error) {
|
||||
return { success: false, error: error instanceof Error ? error.message : String(error) }
|
||||
}
|
||||
})
|
||||
|
||||
createWindow()
|
||||
|
||||
// 启动本地 HTTP API(根据 settings.apiEnabled 控制)
|
||||
// 鍚姩鏈湴 HTTP API(鏍规嵁 settings.apiEnabled 鎺у埗)
|
||||
const settings = loadSettings()
|
||||
if (settings.apiEnabled) {
|
||||
await apiServer.start(settings.apiHost, settings.apiPort)
|
||||
@@ -325,15 +713,15 @@ app.whenReady().then(async () => {
|
||||
}
|
||||
|
||||
app.on('activate', function () {
|
||||
// 在 macOS 上,当点击 dock 图标且没有其他窗口打开时,
|
||||
// 通常会在应用程序中重新创建一个窗口。
|
||||
// 鍦?macOS 涓婏紝褰撶偣鍑?dock 鍥炬爣涓旀病鏈夊叾浠栫獥鍙f墦寮€鏃讹紝
|
||||
// 閫氬父浼氬湪搴旂敤绋嬪簭涓噸鏂板垱寤轰竴涓獥鍙c€?
|
||||
if (BrowserWindow.getAllWindows().length === 0) createWindow()
|
||||
})
|
||||
})
|
||||
|
||||
// 当所有窗口关闭时退出,除了 macOS。在那里,
|
||||
// 应用程序及其菜单栏通常会保持活动状态,直到用户
|
||||
// 显式使用 Cmd + Q 退出。
|
||||
// 褰撴墍鏈夌獥鍙e叧闂椂閫€鍑猴紝闄や簡 macOS銆傚湪閭i噷锛?
|
||||
// 搴旂敤绋嬪簭鍙婂叾鑿滃崟鏍忛€氬父浼氫繚鎸佹椿鍔ㄧ姸鎬侊紝鐩村埌鐢ㄦ埛
|
||||
// 鏄惧紡浣跨敤 Cmd + Q 閫€鍑恒€?
|
||||
app.on('window-all-closed', () => {
|
||||
if (TRAY_MODE) return
|
||||
if (process.platform !== 'darwin') {
|
||||
@@ -388,8 +776,12 @@ function buildTrayMenu(): Menu {
|
||||
function setupTray(): void {
|
||||
if (tray) return
|
||||
try {
|
||||
const image = nativeImage.createFromPath(join(__dirname, '../../resources/icon.png'))
|
||||
tray = new Tray(image.isEmpty() ? nativeImage.createEmpty() : image)
|
||||
const image = nativeImage.createFromPath(appIconPath)
|
||||
const traySize = process.platform === 'darwin' ? 20 : 24
|
||||
const trayImage = image.isEmpty()
|
||||
? nativeImage.createEmpty()
|
||||
: image.resize({ width: traySize, height: traySize, quality: 'best' })
|
||||
tray = new Tray(trayImage)
|
||||
tray.setToolTip('WechatExplorer')
|
||||
tray.setContextMenu(buildTrayMenu())
|
||||
tray.on('click', () => showMainWindow())
|
||||
|
||||
@@ -4,6 +4,8 @@ import fs from 'fs-extra'
|
||||
import path from 'path'
|
||||
import { promisify } from 'util'
|
||||
import { isValidDatabaseKey } from './database-key-store'
|
||||
import crypto from 'crypto'
|
||||
import { findResource, getResourceCandidates } from './resource-paths'
|
||||
|
||||
const execFileAsync = promisify(execFile)
|
||||
|
||||
@@ -14,19 +16,22 @@ export interface DatabaseKeyResult {
|
||||
code?: string
|
||||
}
|
||||
|
||||
export interface ImageKeyResult {
|
||||
success: boolean
|
||||
xorKey?: number
|
||||
aesKey?: string
|
||||
verified?: boolean
|
||||
error?: string
|
||||
}
|
||||
|
||||
export class KeyServiceMac {
|
||||
private getHelperPath(): string {
|
||||
const candidates = app.isPackaged
|
||||
? [
|
||||
path.join(process.resourcesPath, 'resources', 'xkey_helper'),
|
||||
path.join(process.resourcesPath, 'xkey_helper')
|
||||
]
|
||||
: [
|
||||
path.join(process.cwd(), 'resources', 'xkey_helper'),
|
||||
path.join(app.getAppPath(), 'resources', 'xkey_helper')
|
||||
]
|
||||
const helperPath = candidates.find((candidate) => fs.existsSync(candidate))
|
||||
if (!helperPath) throw new Error('找不到 xkey_helper')
|
||||
const helperPath = findResource('xkey_helper')
|
||||
if (!helperPath) {
|
||||
throw new Error(
|
||||
`找不到 xkey_helper(已检查:${getResourceCandidates('xkey_helper').join(';')})`
|
||||
)
|
||||
}
|
||||
return helperPath
|
||||
}
|
||||
|
||||
@@ -136,7 +141,7 @@ export class KeyServiceMac {
|
||||
'return "ERR::" & errNum & "::" & errMsg',
|
||||
'end try'
|
||||
]
|
||||
onStatus?.('授权后请保持微信已登录并活动...')
|
||||
onStatus?.('授权后请保持微信登录界面 并点击登录微信...')
|
||||
const { stdout } = await execFileAsync(
|
||||
'/usr/bin/osascript',
|
||||
scriptLines.flatMap((line) => ['-e', line]),
|
||||
@@ -157,4 +162,283 @@ export class KeyServiceMac {
|
||||
return { success: false, error: error instanceof Error ? error.message : String(error) }
|
||||
}
|
||||
}
|
||||
|
||||
async autoGetImageKey(
|
||||
accountPath?: string,
|
||||
onStatus?: (message: string) => void,
|
||||
wxid?: string
|
||||
): Promise<ImageKeyResult> {
|
||||
try {
|
||||
onStatus?.('正在从缓存目录扫描图片密钥...')
|
||||
const codes = this.collectKvcommCodes(accountPath)
|
||||
if (codes.length === 0) {
|
||||
return { success: false, error: '未找到有效的密钥码(kvcomm 缓存为空)' }
|
||||
}
|
||||
|
||||
const wxidCandidates = this.collectWxidCandidates(accountPath, wxid)
|
||||
const accountPathCandidates = this.collectAccountPathCandidates(accountPath)
|
||||
|
||||
for (const candidateAccountPath of accountPathCandidates) {
|
||||
if (!fs.existsSync(candidateAccountPath)) continue
|
||||
const template = this.findTemplateData(candidateAccountPath, 32)
|
||||
if (!template.ciphertext) continue
|
||||
|
||||
const orderedWxids: string[] = []
|
||||
this.pushAccountIdCandidates(orderedWxids, path.basename(candidateAccountPath))
|
||||
for (const candidate of wxidCandidates)
|
||||
this.pushAccountIdCandidates(orderedWxids, candidate)
|
||||
|
||||
onStatus?.(`正在校验候选 wxid(${orderedWxids.length} 个)...`)
|
||||
for (const candidateWxid of orderedWxids) {
|
||||
for (const code of codes) {
|
||||
const { xorKey, aesKey } = this.deriveImageKeys(code, candidateWxid)
|
||||
if (!this.verifyDerivedAesKey(aesKey, template.ciphertext)) continue
|
||||
onStatus?.(`图片密钥获取成功 (wxid: ${candidateWxid})`)
|
||||
return { success: true, xorKey, aesKey, verified: true }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const fallbackWxid = wxidCandidates[0]
|
||||
const fallbackCode = codes[0]
|
||||
const { xorKey, aesKey } = this.deriveImageKeys(fallbackCode, fallbackWxid)
|
||||
onStatus?.(`图片密钥已计算 (wxid: ${fallbackWxid})`)
|
||||
return { success: true, xorKey, aesKey, verified: false }
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : String(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private collectKvcommCodes(accountPath?: string): number[] {
|
||||
const codeSet = new Set<number>()
|
||||
const pattern = /^key_(\d+)_.+\.statistic$/i
|
||||
for (const kvcommDir of this.getKvcommCandidates(accountPath)) {
|
||||
if (!fs.existsSync(kvcommDir)) continue
|
||||
try {
|
||||
for (const file of fs.readdirSync(kvcommDir)) {
|
||||
const match = file.match(pattern)
|
||||
if (!match) continue
|
||||
const code = Number(match[1])
|
||||
if (Number.isFinite(code) && code > 0 && code <= 0xffffffff) codeSet.add(code)
|
||||
}
|
||||
} catch {
|
||||
// Try the next candidate.
|
||||
}
|
||||
}
|
||||
return Array.from(codeSet)
|
||||
}
|
||||
|
||||
private getKvcommCandidates(accountPath?: string): string[] {
|
||||
const home = app.getPath('home')
|
||||
const candidates = new Set<string>([
|
||||
path.join(
|
||||
home,
|
||||
'Library/Containers/com.tencent.xinWeChat/Data/Documents/app_data/net/kvcomm'
|
||||
),
|
||||
path.join(
|
||||
home,
|
||||
'Library/Containers/com.tencent.xinWeChat/Data/Library/Application Support/com.tencent.xinWeChat/xwechat/net/kvcomm'
|
||||
),
|
||||
path.join(
|
||||
home,
|
||||
'Library/Containers/com.tencent.xinWeChat/Data/Library/Application Support/com.tencent.xinWeChat/net/kvcomm'
|
||||
),
|
||||
path.join(home, 'Library/Containers/com.tencent.xinWeChat/Data/Documents/xwechat/net/kvcomm')
|
||||
])
|
||||
|
||||
const normalized = String(accountPath || '')
|
||||
.replace(/\\/g, '/')
|
||||
.replace(/\/+$/, '')
|
||||
const marker = '/xwechat_files'
|
||||
const markerIndex = normalized.indexOf(marker)
|
||||
if (markerIndex >= 0) {
|
||||
candidates.add(`${normalized.slice(0, markerIndex)}/app_data/net/kvcomm`)
|
||||
}
|
||||
|
||||
const newPathMatch = normalized.match(
|
||||
/^(.*\/com\.tencent\.xinWeChat\/(?:\d+\.\d+b\d+\.\d+|\d+\.\d+\.\d+))/
|
||||
)
|
||||
if (newPathMatch) {
|
||||
candidates.add(`${newPathMatch[1]}/net/kvcomm`)
|
||||
candidates.add(`${newPathMatch[1]}/xwechat/net/kvcomm`)
|
||||
}
|
||||
|
||||
return Array.from(candidates)
|
||||
}
|
||||
|
||||
private collectWxidCandidates(accountPath?: string, wxidParam?: string): string[] {
|
||||
const candidates: string[] = []
|
||||
this.pushAccountIdCandidates(candidates, wxidParam)
|
||||
|
||||
const normalized = String(accountPath || '')
|
||||
.replace(/\\/g, '/')
|
||||
.replace(/\/+$/, '')
|
||||
if (normalized) {
|
||||
this.pushAccountIdCandidates(candidates, path.basename(normalized))
|
||||
const root = this.resolveXwechatRootFromPath(normalized)
|
||||
if (root && fs.existsSync(root)) {
|
||||
try {
|
||||
for (const entry of fs.readdirSync(root, { withFileTypes: true })) {
|
||||
if (!entry.isDirectory()) continue
|
||||
const entryPath = path.join(root, entry.name)
|
||||
if (this.isAccountDirPath(entryPath))
|
||||
this.pushAccountIdCandidates(candidates, entry.name)
|
||||
}
|
||||
} catch {
|
||||
// Ignore unreadable directories.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (candidates.length === 0) candidates.push('unknown')
|
||||
return candidates
|
||||
}
|
||||
|
||||
private collectAccountPathCandidates(accountPath?: string): string[] {
|
||||
const candidates: string[] = []
|
||||
const push = (value?: string): void => {
|
||||
const normalized = String(value || '').trim()
|
||||
if (normalized && !candidates.includes(normalized)) candidates.push(normalized)
|
||||
}
|
||||
|
||||
push(accountPath)
|
||||
const root = this.resolveXwechatRootFromPath(accountPath)
|
||||
if (root && fs.existsSync(root)) {
|
||||
try {
|
||||
for (const entry of fs.readdirSync(root, { withFileTypes: true })) {
|
||||
if (!entry.isDirectory()) continue
|
||||
const entryPath = path.join(root, entry.name)
|
||||
if (this.isAccountDirPath(entryPath) && this.isReasonableAccountId(entry.name))
|
||||
push(entryPath)
|
||||
}
|
||||
} catch {
|
||||
// Ignore unreadable directories.
|
||||
}
|
||||
}
|
||||
return candidates
|
||||
}
|
||||
|
||||
private resolveXwechatRootFromPath(accountPath?: string): string | null {
|
||||
const normalized = String(accountPath || '')
|
||||
.replace(/\\/g, '/')
|
||||
.replace(/\/+$/, '')
|
||||
if (!normalized) return null
|
||||
const marker = '/xwechat_files'
|
||||
const markerIndex = normalized.indexOf(marker)
|
||||
if (markerIndex >= 0) return normalized.slice(0, markerIndex + marker.length)
|
||||
const newPathMatch = normalized.match(
|
||||
/^(.*\/com\.tencent\.xinWeChat\/(?:\d+\.\d+b\d+\.\d+|\d+\.\d+\.\d+))(\/|$)/
|
||||
)
|
||||
return newPathMatch ? newPathMatch[1] : null
|
||||
}
|
||||
|
||||
private isAccountDirPath(entryPath: string): boolean {
|
||||
return (
|
||||
fs.existsSync(path.join(entryPath, 'db_storage')) ||
|
||||
fs.existsSync(path.join(entryPath, 'msg')) ||
|
||||
fs.existsSync(path.join(entryPath, 'FileStorage', 'Image')) ||
|
||||
fs.existsSync(path.join(entryPath, 'FileStorage', 'Image2'))
|
||||
)
|
||||
}
|
||||
|
||||
private pushAccountIdCandidates(candidates: string[], value?: string): void {
|
||||
const raw = String(value || '').trim()
|
||||
if (!this.isReasonableAccountId(raw)) return
|
||||
for (const candidate of [raw, this.normalizeAccountId(raw)]) {
|
||||
if (candidate && !candidates.includes(candidate) && this.isReasonableAccountId(candidate)) {
|
||||
candidates.push(candidate)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private normalizeAccountId(value: string): string {
|
||||
const trimmed = String(value || '').trim()
|
||||
if (!trimmed) return ''
|
||||
if (trimmed.toLowerCase().startsWith('wxid_')) {
|
||||
const match = trimmed.match(/^(wxid_[^_]+)/i)
|
||||
return match?.[1] || trimmed
|
||||
}
|
||||
const suffixMatch = trimmed.match(/^(.+)_([a-zA-Z0-9]{4})$/)
|
||||
return suffixMatch ? suffixMatch[1] : trimmed
|
||||
}
|
||||
|
||||
private isReasonableAccountId(value: string): boolean {
|
||||
const lowered = String(value || '')
|
||||
.trim()
|
||||
.toLowerCase()
|
||||
if (!lowered || lowered.includes('/') || lowered.includes('\\')) return false
|
||||
return !['xwechat_files', 'all_users', 'backup', 'wmpf', 'app_data'].includes(lowered)
|
||||
}
|
||||
|
||||
private deriveImageKeys(code: number, wxid: string): { xorKey: number; aesKey: string } {
|
||||
const xorKey = code & 0xff
|
||||
const aesKey = crypto
|
||||
.createHash('md5')
|
||||
.update(`${code}${this.normalizeAccountId(wxid)}`)
|
||||
.digest('hex')
|
||||
.substring(0, 16)
|
||||
return { xorKey, aesKey }
|
||||
}
|
||||
|
||||
private findTemplateData(userDir: string, limit = 32): { ciphertext: Buffer | null } {
|
||||
const magic = Buffer.from([0x07, 0x08, 0x56, 0x32, 0x08, 0x07])
|
||||
const files: string[] = []
|
||||
const collect = (dir: string): void => {
|
||||
if (files.length >= limit) return
|
||||
try {
|
||||
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
||||
if (files.length >= limit) break
|
||||
const full = path.join(dir, entry.name)
|
||||
if (entry.isDirectory()) collect(full)
|
||||
else if (entry.isFile() && entry.name.endsWith('_t.dat')) files.push(full)
|
||||
}
|
||||
} catch {
|
||||
// Ignore unreadable directories.
|
||||
}
|
||||
}
|
||||
collect(userDir)
|
||||
files.sort((a, b) => {
|
||||
try {
|
||||
return fs.statSync(b).mtimeMs - fs.statSync(a).mtimeMs
|
||||
} catch {
|
||||
return 0
|
||||
}
|
||||
})
|
||||
|
||||
for (const file of files) {
|
||||
try {
|
||||
const data = fs.readFileSync(file)
|
||||
if (data.length >= 0x1f && data.subarray(0, 6).equals(magic)) {
|
||||
return { ciphertext: data.subarray(0x0f, 0x1f) }
|
||||
}
|
||||
} catch {
|
||||
// Try the next file.
|
||||
}
|
||||
}
|
||||
return { ciphertext: null }
|
||||
}
|
||||
|
||||
private verifyDerivedAesKey(aesKey: string, ciphertext: Buffer): boolean {
|
||||
try {
|
||||
if (!aesKey || aesKey.length < 16 || ciphertext.length !== 16) return false
|
||||
const decipher = crypto.createDecipheriv(
|
||||
'aes-128-ecb',
|
||||
Buffer.from(aesKey, 'ascii').subarray(0, 16),
|
||||
null
|
||||
)
|
||||
decipher.setAutoPadding(false)
|
||||
const dec = Buffer.concat([decipher.update(ciphertext), decipher.final()])
|
||||
if (dec[0] === 0xff && dec[1] === 0xd8 && dec[2] === 0xff) return true
|
||||
if (dec[0] === 0x89 && dec[1] === 0x50 && dec[2] === 0x4e && dec[3] === 0x47) return true
|
||||
if (dec[0] === 0x52 && dec[1] === 0x49 && dec[2] === 0x46 && dec[3] === 0x46) return true
|
||||
if (dec[0] === 0x77 && dec[1] === 0x78 && dec[2] === 0x67 && dec[3] === 0x66) return true
|
||||
if (dec[0] === 0x47 && dec[1] === 0x49 && dec[2] === 0x46) return true
|
||||
return false
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
import fs from 'fs'
|
||||
import path from 'path'
|
||||
|
||||
function prependPath(values: string[]): void {
|
||||
if (process.platform !== 'win32') return
|
||||
|
||||
const existing = process.env.PATH || ''
|
||||
const next = Array.from(new Set(values.filter(Boolean))).join(path.delimiter)
|
||||
process.env.PATH = next ? `${next}${path.delimiter}${existing}` : existing
|
||||
process.env.Path = process.env.PATH
|
||||
}
|
||||
|
||||
try {
|
||||
const archDir = process.arch === 'arm64' ? 'arm64' : 'x64'
|
||||
const resourceRoots = [
|
||||
path.join(process.cwd(), 'resources'),
|
||||
path.join(process.cwd(), 'resources', 'resources'),
|
||||
path.join(process.resourcesPath || '', 'resources'),
|
||||
process.resourcesPath || ''
|
||||
].filter((value, index, list) => value && list.indexOf(value) === index && fs.existsSync(value))
|
||||
|
||||
const resourcesRoot = resourceRoots[0] || path.join(process.cwd(), 'resources')
|
||||
const dllDirs = resourceRoots.flatMap((root) => [
|
||||
root,
|
||||
path.join(root, 'wcdb', 'win32', archDir),
|
||||
path.join(root, 'wcdb', 'win32', 'x64'),
|
||||
path.join(root, 'key', 'win32', archDir),
|
||||
path.join(root, 'key', 'win32', 'x64'),
|
||||
path.join(root, 'runtime', 'win32')
|
||||
])
|
||||
|
||||
process.env.WCDB_RESOURCES_PATH = process.env.WCDB_RESOURCES_PATH || resourcesRoot
|
||||
process.env.WEFLOW_PROJECT_NAME = process.env.WEFLOW_PROJECT_NAME || 'WeFlow'
|
||||
prependPath(dllDirs.filter((dir) => fs.existsSync(dir)))
|
||||
} catch (error) {
|
||||
console.error('[WechatExplorer] failed to enforce local DLL priority:', error)
|
||||
}
|
||||
@@ -0,0 +1,238 @@
|
||||
import { app, nativeImage } from 'electron'
|
||||
import { promises as fs } from 'fs'
|
||||
import path from 'path'
|
||||
import type {
|
||||
GeneratedReportRecord,
|
||||
DeleteGeneratedReportResult,
|
||||
ReportAssetStatus,
|
||||
ReportHistoryResult,
|
||||
SaveGeneratedReportRequest,
|
||||
SaveGeneratedReportResult
|
||||
} from '../shared/report-history'
|
||||
|
||||
const REPORTS_DIR = 'reports'
|
||||
|
||||
const getReportsRoot = (): string => path.join(app.getPath('userData'), REPORTS_DIR)
|
||||
|
||||
const pad2 = (value: number): string => String(value).padStart(2, '0')
|
||||
|
||||
const safeSegment = (value: string): string =>
|
||||
value
|
||||
.trim()
|
||||
// Strip Windows-reserved filename characters and ASCII control chars.
|
||||
// eslint-disable-next-line no-control-regex
|
||||
.replace(/[<>:"/\\|?*\x00-\x1f]/g, '_')
|
||||
.replace(/\s+/g, '_')
|
||||
.slice(0, 48) || 'report'
|
||||
|
||||
const parseDataUrl = (dataUrl: string): Buffer | null => {
|
||||
const match = /^data:image\/png;base64,(.+)$/i.exec(dataUrl)
|
||||
if (!match) return null
|
||||
return Buffer.from(match[1], 'base64')
|
||||
}
|
||||
|
||||
const exists = async (filePath?: string): Promise<boolean> => {
|
||||
if (!filePath) return false
|
||||
try {
|
||||
const stat = await fs.stat(filePath)
|
||||
return stat.isFile()
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
const fileStatus = async (filePath?: string): Promise<ReportAssetStatus> =>
|
||||
(await exists(filePath)) ? 'ready' : 'missing'
|
||||
|
||||
const readPngAsDataUrl = async (filePath?: string): Promise<string | undefined> => {
|
||||
if (!filePath || !(await exists(filePath))) return undefined
|
||||
const content = await fs.readFile(filePath)
|
||||
return `data:image/png;base64,${content.toString('base64')}`
|
||||
}
|
||||
|
||||
const readPngSize = async (
|
||||
filePath?: string
|
||||
): Promise<{ width: number; height: number } | undefined> => {
|
||||
if (!filePath || !(await exists(filePath))) return undefined
|
||||
const image = nativeImage.createFromPath(filePath)
|
||||
if (image.isEmpty()) return undefined
|
||||
const size = image.getSize()
|
||||
return size.width && size.height ? size : undefined
|
||||
}
|
||||
|
||||
const readFileSize = async (filePath?: string): Promise<number | undefined> => {
|
||||
if (!filePath) return undefined
|
||||
try {
|
||||
const stat = await fs.stat(filePath)
|
||||
return stat.isFile() ? stat.size : undefined
|
||||
} catch {
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
|
||||
const normalizeRecord = async (
|
||||
record: GeneratedReportRecord,
|
||||
jsonPath: string
|
||||
): Promise<GeneratedReportRecord> => {
|
||||
const htmlStatus = await fileStatus(record.htmlPath)
|
||||
const pngStatus = await fileStatus(record.pngPath)
|
||||
return {
|
||||
...record,
|
||||
jsonPath,
|
||||
htmlStatus,
|
||||
pngStatus,
|
||||
generatedImage: await readPngAsDataUrl(record.pngPath),
|
||||
imageSize: await readPngSize(record.pngPath),
|
||||
fileSize: {
|
||||
html: await readFileSize(record.htmlPath),
|
||||
png: await readFileSize(record.pngPath)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const walkJsonFiles = async (directory: string): Promise<string[]> => {
|
||||
try {
|
||||
const entries = await fs.readdir(directory, { withFileTypes: true })
|
||||
const children = await Promise.all(
|
||||
entries.map(async (entry) => {
|
||||
const entryPath = path.join(directory, entry.name)
|
||||
if (entry.isDirectory()) return walkJsonFiles(entryPath)
|
||||
return entry.isFile() && entry.name.endsWith('.json') ? [entryPath] : []
|
||||
})
|
||||
)
|
||||
return children.flat()
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code === 'ENOENT') return []
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
export async function listGeneratedReports(): Promise<ReportHistoryResult> {
|
||||
try {
|
||||
const jsonFiles = await walkJsonFiles(getReportsRoot())
|
||||
const records = await Promise.all(
|
||||
jsonFiles.map(async (jsonPath) => {
|
||||
try {
|
||||
const content = await fs.readFile(jsonPath, 'utf8')
|
||||
return normalizeRecord(JSON.parse(content) as GeneratedReportRecord, jsonPath)
|
||||
} catch (error) {
|
||||
console.warn(`[ReportHistory] skip invalid report record: ${jsonPath}`, error)
|
||||
return null
|
||||
}
|
||||
})
|
||||
)
|
||||
const reports = records.filter((record): record is GeneratedReportRecord => Boolean(record))
|
||||
reports.sort((left, right) => Date.parse(right.generatedAt) - Date.parse(left.generatedAt))
|
||||
return { success: true, reports }
|
||||
} catch (error) {
|
||||
return { success: false, error: error instanceof Error ? error.message : String(error) }
|
||||
}
|
||||
}
|
||||
|
||||
export async function saveGeneratedReport(
|
||||
request: SaveGeneratedReportRequest
|
||||
): Promise<SaveGeneratedReportResult> {
|
||||
try {
|
||||
const generatedAtDate = new Date(request.generatedAt)
|
||||
const timestamp = Number.isFinite(generatedAtDate.getTime()) ? generatedAtDate : new Date()
|
||||
const year = String(timestamp.getFullYear())
|
||||
const month = pad2(timestamp.getMonth() + 1)
|
||||
const directory = path.join(getReportsRoot(), year, month)
|
||||
await fs.mkdir(directory, { recursive: true })
|
||||
|
||||
const id = `report_${timestamp.getTime()}_${Math.random().toString(36).slice(2, 8)}`
|
||||
const baseName = `${id}_${safeSegment(request.contactName)}`
|
||||
const htmlPath = path.join(directory, `${baseName}.html`)
|
||||
const pngPath = path.join(directory, `${baseName}.png`)
|
||||
const jsonPath = path.join(directory, `${baseName}.json`)
|
||||
|
||||
let savedHtmlPath: string | undefined
|
||||
if (request.htmlPath && (await exists(request.htmlPath))) {
|
||||
await fs.copyFile(request.htmlPath, htmlPath)
|
||||
savedHtmlPath = htmlPath
|
||||
}
|
||||
|
||||
let savedPngPath: string | undefined
|
||||
const imageBuffer = request.generatedImage ? parseDataUrl(request.generatedImage) : null
|
||||
if (imageBuffer) {
|
||||
await fs.writeFile(pngPath, imageBuffer)
|
||||
savedPngPath = pngPath
|
||||
} else if (request.pngPath && (await exists(request.pngPath))) {
|
||||
await fs.copyFile(request.pngPath, pngPath)
|
||||
savedPngPath = pngPath
|
||||
}
|
||||
|
||||
const record: GeneratedReportRecord = {
|
||||
id,
|
||||
contactId: request.contactId,
|
||||
contactName: request.contactName,
|
||||
contactAvatar: request.contactAvatar,
|
||||
dateRange: request.dateRange,
|
||||
messageCount: request.messageCount,
|
||||
generatedAt: timestamp.toISOString(),
|
||||
reportDate: `${year}-${month}-${pad2(timestamp.getDate())}`,
|
||||
htmlPath: savedHtmlPath,
|
||||
pngPath: savedPngPath,
|
||||
jsonPath,
|
||||
htmlStatus: savedHtmlPath ? 'ready' : 'missing',
|
||||
pngStatus: savedPngPath ? 'ready' : 'missing',
|
||||
imageSize: await readPngSize(savedPngPath),
|
||||
duration: request.duration,
|
||||
modelName: request.modelName,
|
||||
tokenUsage: request.tokenUsage,
|
||||
fileSize: {
|
||||
html: await readFileSize(savedHtmlPath),
|
||||
png: await readFileSize(savedPngPath)
|
||||
},
|
||||
generationLogs: request.generationLogs
|
||||
}
|
||||
|
||||
await fs.writeFile(jsonPath, JSON.stringify(record, null, 2), 'utf8')
|
||||
return {
|
||||
success: true,
|
||||
record: {
|
||||
...record,
|
||||
generatedImage: savedPngPath ? await readPngAsDataUrl(savedPngPath) : undefined
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
return { success: false, error: error instanceof Error ? error.message : String(error) }
|
||||
}
|
||||
}
|
||||
|
||||
export async function deleteGeneratedReport(
|
||||
reportId: string
|
||||
): Promise<DeleteGeneratedReportResult> {
|
||||
try {
|
||||
const jsonFiles = await walkJsonFiles(getReportsRoot())
|
||||
for (const jsonPath of jsonFiles) {
|
||||
try {
|
||||
const content = await fs.readFile(jsonPath, 'utf8')
|
||||
const record = JSON.parse(content) as GeneratedReportRecord
|
||||
if (record.id !== reportId) continue
|
||||
|
||||
const paths = [record.htmlPath, record.pngPath, jsonPath].filter(
|
||||
(filePath): filePath is string => Boolean(filePath)
|
||||
)
|
||||
await Promise.all(
|
||||
paths.map(async (filePath) => {
|
||||
try {
|
||||
await fs.unlink(filePath)
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error
|
||||
}
|
||||
})
|
||||
)
|
||||
return { success: true, deletedId: reportId }
|
||||
} catch (error) {
|
||||
console.warn(
|
||||
`[ReportHistory] skip invalid report record while deleting: ${jsonPath}`,
|
||||
error
|
||||
)
|
||||
}
|
||||
}
|
||||
return { success: false, error: '未找到要删除的日报记录' }
|
||||
} catch (error) {
|
||||
return { success: false, error: error instanceof Error ? error.message : String(error) }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import { app } from 'electron'
|
||||
import { existsSync } from 'fs'
|
||||
import { dirname, join } from 'path'
|
||||
|
||||
function unique(values: string[]): string[] {
|
||||
return Array.from(new Set(values.filter(Boolean)))
|
||||
}
|
||||
|
||||
export function getResourceRoots(): string[] {
|
||||
const appPath = app.getAppPath()
|
||||
const appPathDir = dirname(appPath)
|
||||
const execDir = dirname(process.execPath)
|
||||
|
||||
return unique([
|
||||
process.env.WECHATEXPLORER_RESOURCES_PATH || '',
|
||||
join(process.cwd(), 'resources'),
|
||||
join(process.cwd(), 'resources', 'resources'),
|
||||
join(process.resourcesPath || '', 'resources'),
|
||||
process.resourcesPath || '',
|
||||
join(appPath, 'resources'),
|
||||
join(appPathDir, 'resources'),
|
||||
appPathDir,
|
||||
join(execDir, 'resources'),
|
||||
join(dirname(execDir), 'Resources', 'resources'),
|
||||
join(dirname(execDir), 'Resources')
|
||||
]).filter((root) => existsSync(root))
|
||||
}
|
||||
|
||||
export function getResourceCandidates(relativePath: string): string[] {
|
||||
return unique(getResourceRoots().map((root) => join(root, relativePath)))
|
||||
}
|
||||
|
||||
export function findResource(relativePath: string): string | null {
|
||||
return getResourceCandidates(relativePath).find((candidate) => existsSync(candidate)) || null
|
||||
}
|
||||
@@ -0,0 +1,668 @@
|
||||
import { app } from 'electron'
|
||||
import fs from 'fs-extra'
|
||||
import path from 'path'
|
||||
import type {
|
||||
AIChatRequestOptions,
|
||||
AIConnectionTestResult,
|
||||
AIProviderConfig,
|
||||
AIProviderListResult,
|
||||
AIProviderSummary,
|
||||
AIRuntimeModelConfig,
|
||||
AIVisionTestRequest,
|
||||
AIVisionTestResult,
|
||||
LegacyAIConfig
|
||||
} from '../../shared/ai-provider'
|
||||
import { AIProviderKeyStore } from '../ai-provider-key-store'
|
||||
|
||||
interface AIProviderMetadataFile {
|
||||
version: 1
|
||||
defaultProviderId?: string
|
||||
providers: Array<Omit<AIProviderSummary, 'hasApiKey' | 'isDefault'>>
|
||||
}
|
||||
|
||||
type AIMessagePart = { type: 'text'; text: string } | { type: 'image'; dataUrl: string }
|
||||
type AIMessage = { role: string; content: string | AIMessagePart[] }
|
||||
type AIRequestResult = {
|
||||
data: string
|
||||
usage?: { input?: number; output?: number; total?: number; estimated?: boolean }
|
||||
}
|
||||
interface OpenAIResponsePayload {
|
||||
error?: { message?: string }
|
||||
choices?: Array<{ message?: { content?: string } }>
|
||||
usage?: { prompt_tokens?: number; completion_tokens?: number; total_tokens?: number }
|
||||
}
|
||||
interface AnthropicResponsePayload {
|
||||
error?: { message?: string }
|
||||
content?: Array<{ type?: string; text?: string }>
|
||||
usage?: { input_tokens?: number; output_tokens?: number }
|
||||
}
|
||||
|
||||
export class AIProviderService {
|
||||
constructor(private readonly keyStore = new AIProviderKeyStore()) {}
|
||||
|
||||
list(): AIProviderListResult {
|
||||
this.ensureEnvironmentMigration()
|
||||
try {
|
||||
const data = this.readMetadata()
|
||||
return {
|
||||
success: true,
|
||||
defaultProviderId: data.defaultProviderId,
|
||||
providers: data.providers.map((provider) =>
|
||||
this.toSummary(provider, data.defaultProviderId)
|
||||
)
|
||||
}
|
||||
} catch {
|
||||
return { success: false, providers: [], error: 'AI Provider 配置无法读取' }
|
||||
}
|
||||
}
|
||||
|
||||
getRuntimeConfig(): AIRuntimeModelConfig {
|
||||
const result = this.list()
|
||||
const provider =
|
||||
result.providers.find((item) => item.id === result.defaultProviderId) || result.providers[0]
|
||||
const model = provider?.models.find((item) => item.id === provider.defaultModel)
|
||||
return {
|
||||
providerId: provider?.id,
|
||||
providerName: provider?.name || '尚未配置',
|
||||
model: provider?.defaultModel || '',
|
||||
modelName: model?.name || provider?.defaultModel || '尚未选择模型',
|
||||
configured: Boolean(
|
||||
provider && provider.models.length && (provider.hasApiKey || !needsApiKey(provider))
|
||||
),
|
||||
status: provider?.status || 'untested',
|
||||
timeoutMs: provider?.advanced.timeoutMs
|
||||
}
|
||||
}
|
||||
|
||||
save(input: AIProviderConfig): AIProviderListResult {
|
||||
const validationError = validateProvider(input)
|
||||
if (validationError) return { success: false, providers: [], error: validationError }
|
||||
const data = this.readMetadata()
|
||||
const existing = data.providers.find((provider) => provider.id === input.id)
|
||||
if (input.apiKey?.trim()) {
|
||||
const saved = this.keyStore.save(input.id, input.apiKey.trim())
|
||||
if (!saved.success) return { success: false, providers: [], error: saved.error }
|
||||
} else if (needsApiKey(input) && !this.keyStore.get(input.id).key) {
|
||||
return { success: false, providers: [], error: '请填写 API Key' }
|
||||
}
|
||||
|
||||
const metadata: Omit<AIProviderSummary, 'hasApiKey' | 'isDefault'> = {
|
||||
id: input.id,
|
||||
name: input.name.trim(),
|
||||
type: input.type,
|
||||
baseUrl: input.baseUrl.trim().replace(/\/+$/, ''),
|
||||
auth: input.auth,
|
||||
models: input.models,
|
||||
defaultModel: input.defaultModel,
|
||||
advanced: input.advanced,
|
||||
status: existing?.status || 'untested',
|
||||
lastTestedAt: existing?.lastTestedAt,
|
||||
lastError: existing?.lastError
|
||||
}
|
||||
const index = data.providers.findIndex((provider) => provider.id === input.id)
|
||||
if (index >= 0) data.providers[index] = metadata
|
||||
else data.providers.push(metadata)
|
||||
if (!data.defaultProviderId) data.defaultProviderId = input.id
|
||||
this.writeMetadata(data)
|
||||
return this.list()
|
||||
}
|
||||
|
||||
delete(providerId: string): AIProviderListResult {
|
||||
const data = this.readMetadata()
|
||||
data.providers = data.providers.filter((provider) => provider.id !== providerId)
|
||||
if (data.defaultProviderId === providerId) data.defaultProviderId = data.providers[0]?.id
|
||||
const cleared = this.keyStore.clear(providerId)
|
||||
if (!cleared.success) return { success: false, providers: [], error: cleared.error }
|
||||
this.writeMetadata(data)
|
||||
return this.list()
|
||||
}
|
||||
|
||||
setDefault(providerId: string): AIProviderListResult {
|
||||
const data = this.readMetadata()
|
||||
if (!data.providers.some((provider) => provider.id === providerId)) {
|
||||
return { success: false, providers: [], error: '供应商不存在' }
|
||||
}
|
||||
data.defaultProviderId = providerId
|
||||
this.writeMetadata(data)
|
||||
return this.list()
|
||||
}
|
||||
|
||||
migrateLegacy(config: LegacyAIConfig): AIProviderListResult {
|
||||
const data = this.readMetadata()
|
||||
if (data.providers.length) return this.list()
|
||||
const provider = deepSeekProvider(config.baseUrl, config.model)
|
||||
if (config.apiKey?.trim()) {
|
||||
const saved = this.keyStore.save(provider.id, config.apiKey.trim())
|
||||
if (!saved.success) return { success: false, providers: [], error: saved.error }
|
||||
}
|
||||
data.providers = [stripRuntimeFields(provider)]
|
||||
data.defaultProviderId = provider.id
|
||||
this.writeMetadata(data)
|
||||
return this.list()
|
||||
}
|
||||
|
||||
async test(providerId: string): Promise<AIConnectionTestResult> {
|
||||
const startedAt = Date.now()
|
||||
try {
|
||||
await this.request([{ role: 'user', content: 'Reply with OK.' }], { providerId }, true)
|
||||
this.updateTestStatus(providerId, 'connected')
|
||||
return { success: true, latencyMs: Date.now() - startedAt }
|
||||
} catch (error) {
|
||||
const message = safeAIError(error)
|
||||
this.updateTestStatus(providerId, 'error', message)
|
||||
return { success: false, error: message, latencyMs: Date.now() - startedAt }
|
||||
}
|
||||
}
|
||||
|
||||
async chat(
|
||||
messages: Array<{ role: string; content: string }>,
|
||||
options?: AIChatRequestOptions
|
||||
): Promise<{
|
||||
success: boolean
|
||||
data?: string
|
||||
usage?: { input?: number; output?: number; total?: number; estimated?: boolean }
|
||||
error?: string
|
||||
}> {
|
||||
try {
|
||||
return { success: true, ...(await this.request(messages, options)) }
|
||||
} catch (error) {
|
||||
return { success: false, error: safeAIError(error) }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 多模态图片理解。
|
||||
* 输入:text + image parts 的 messages,返回 AI 文本响应。
|
||||
* 与 testVision 区别:不校验 prompt,不写入 capability marker(供 ImageInsightService 复用)。
|
||||
*/
|
||||
async analyzeImage(
|
||||
messages: Array<{
|
||||
role: string
|
||||
content: string | Array<{ type: 'text'; text: string } | { type: 'image'; dataUrl: string }>
|
||||
}>,
|
||||
options?: AIChatRequestOptions
|
||||
): Promise<{
|
||||
success: boolean
|
||||
data?: string
|
||||
usage?: { input?: number; output?: number; total?: number; estimated?: boolean }
|
||||
error?: string
|
||||
}> {
|
||||
try {
|
||||
const imagePart = messages
|
||||
.flatMap((message) => (typeof message.content === 'string' ? [] : message.content))
|
||||
.find((part) => part.type === 'image')
|
||||
if (!imagePart || imagePart.type !== 'image') throw new Error('图片识别请求缺少图片数据')
|
||||
const imageError = validateVisionImage(imagePart.dataUrl)
|
||||
if (imageError) throw new Error(imageError)
|
||||
const result = await this.request(messages as AIMessage[], options)
|
||||
return { success: true, ...result }
|
||||
} catch (error) {
|
||||
return { success: false, error: safeAIError(error) }
|
||||
}
|
||||
}
|
||||
|
||||
async testVision(request: AIVisionTestRequest): Promise<AIVisionTestResult> {
|
||||
const startedAt = Date.now()
|
||||
const imageError = validateVisionImage(request.imageDataUrl)
|
||||
if (imageError) return { success: false, code: 'INVALID_IMAGE', error: imageError }
|
||||
if (!request.prompt.trim()) {
|
||||
return { success: false, code: 'INVALID_IMAGE', error: '请填写图片识别提示词' }
|
||||
}
|
||||
try {
|
||||
const resolved = this.resolveProvider(request)
|
||||
const result = await requestProvider(resolved.provider, resolved.key, resolved.model, [
|
||||
{
|
||||
role: 'user',
|
||||
content: [
|
||||
{ type: 'text', text: request.prompt.trim() },
|
||||
{ type: 'image', dataUrl: request.imageDataUrl }
|
||||
]
|
||||
}
|
||||
])
|
||||
if (!result.data.trim()) throw new Error('API 未返回识别内容')
|
||||
this.markVisionCapability(resolved.provider.id, resolved.model)
|
||||
const model = resolved.provider.models.find((item) => item.id === resolved.model)
|
||||
return {
|
||||
success: true,
|
||||
providerName: resolved.provider.name,
|
||||
modelId: resolved.model,
|
||||
modelName: model?.name || resolved.model,
|
||||
latencyMs: Date.now() - startedAt,
|
||||
usage: result.usage,
|
||||
answer: result.data
|
||||
}
|
||||
} catch (error) {
|
||||
const failure = visionFailure(error)
|
||||
return { success: false, ...failure, latencyMs: Date.now() - startedAt }
|
||||
}
|
||||
}
|
||||
|
||||
private async request(
|
||||
messages: AIMessage[],
|
||||
options?: AIChatRequestOptions,
|
||||
testing = false
|
||||
): Promise<{
|
||||
data: string
|
||||
usage?: { input?: number; output?: number; total?: number; estimated?: boolean }
|
||||
}> {
|
||||
if (options?.apiKey) return this.requestLegacy(messages, options)
|
||||
const resolved = this.resolveProvider(options)
|
||||
const provider = options?.timeoutMs
|
||||
? {
|
||||
...resolved.provider,
|
||||
advanced: { ...resolved.provider.advanced, timeoutMs: options.timeoutMs }
|
||||
}
|
||||
: resolved.provider
|
||||
return requestProvider(provider, resolved.key, resolved.model, messages, testing)
|
||||
}
|
||||
|
||||
private resolveProvider(options?: { providerId?: string; modelId?: string }): {
|
||||
provider: AIProviderSummary
|
||||
model: string
|
||||
key: string
|
||||
} {
|
||||
const list = this.list()
|
||||
const provider =
|
||||
list.providers.find((item) => item.id === options?.providerId) ||
|
||||
list.providers.find((item) => item.id === list.defaultProviderId)
|
||||
if (!provider) throw new Error('尚未配置 AI Provider')
|
||||
const model = options?.modelId || provider.defaultModel
|
||||
if (!provider.models.some((item) => item.id === model)) throw new Error('当前模型不存在')
|
||||
const key = this.keyStore.get(provider.id).key || ''
|
||||
if (needsApiKey(provider) && !key) throw new Error('当前供应商尚未配置 API Key')
|
||||
return { provider, model, key }
|
||||
}
|
||||
|
||||
private async requestLegacy(
|
||||
messages: AIMessage[],
|
||||
options: AIChatRequestOptions
|
||||
): Promise<AIRequestResult> {
|
||||
const provider = deepSeekProvider(options.baseURL, options.model)
|
||||
return requestOpenAICompatible(
|
||||
provider,
|
||||
options.apiKey || '',
|
||||
options.model || provider.defaultModel,
|
||||
messages
|
||||
)
|
||||
}
|
||||
|
||||
private updateTestStatus(
|
||||
providerId: string,
|
||||
status: 'connected' | 'error',
|
||||
lastError?: string
|
||||
): void {
|
||||
const data = this.readMetadata()
|
||||
const provider = data.providers.find((item) => item.id === providerId)
|
||||
if (!provider) return
|
||||
provider.status = status
|
||||
provider.lastTestedAt = Date.now()
|
||||
provider.lastError = lastError
|
||||
this.writeMetadata(data)
|
||||
}
|
||||
|
||||
private markVisionCapability(providerId: string, modelId: string): void {
|
||||
this.markCapabilities(providerId, modelId, { vision: true, ocr: true })
|
||||
}
|
||||
|
||||
/**
|
||||
* 标记模型已验证的 capabilities(已存在则跳过)。
|
||||
* OCR 跟随 vision:几乎所有 vision 模型都能 OCR,标记 vision 时同步标记 ocr。
|
||||
*/
|
||||
private markCapabilities(
|
||||
providerId: string,
|
||||
modelId: string,
|
||||
caps: { vision?: boolean; ocr?: boolean }
|
||||
): void {
|
||||
const data = this.readMetadata()
|
||||
const provider = data.providers.find((item) => item.id === providerId)
|
||||
const model = provider?.models.find((item) => item.id === modelId)
|
||||
if (!provider || !model) return
|
||||
// 老配置可能没有 ocr 字段,补默认 false
|
||||
if (typeof model.capabilities.ocr !== 'boolean') model.capabilities.ocr = false
|
||||
let changed = false
|
||||
if (caps.vision === true && !model.capabilities.vision) {
|
||||
model.capabilities.vision = true
|
||||
// vision 开启默认带 ocr(派生能力)
|
||||
if (!model.capabilities.ocr) {
|
||||
model.capabilities.ocr = true
|
||||
}
|
||||
changed = true
|
||||
}
|
||||
if (caps.ocr === true && !model.capabilities.ocr) {
|
||||
model.capabilities.ocr = true
|
||||
changed = true
|
||||
}
|
||||
if (changed) this.writeMetadata(data)
|
||||
}
|
||||
|
||||
private ensureEnvironmentMigration(): void {
|
||||
const data = this.readMetadata()
|
||||
if (data.providers.length) return
|
||||
const apiKey = String(import.meta.env.VITE_DEEPSEEK_API_KEY || '').trim()
|
||||
if (!apiKey) return
|
||||
this.migrateLegacy({
|
||||
apiKey,
|
||||
baseUrl: String(import.meta.env.VITE_AI_BASE_URL || ''),
|
||||
model: String(import.meta.env.VITE_AI_MODEL || '')
|
||||
})
|
||||
}
|
||||
|
||||
private toSummary(
|
||||
provider: Omit<AIProviderSummary, 'hasApiKey' | 'isDefault'>,
|
||||
defaultProviderId?: string
|
||||
): AIProviderSummary {
|
||||
return {
|
||||
...provider,
|
||||
hasApiKey: Boolean(this.keyStore.get(provider.id).key),
|
||||
isDefault: provider.id === defaultProviderId
|
||||
}
|
||||
}
|
||||
|
||||
private readMetadata(): AIProviderMetadataFile {
|
||||
const filePath = this.metadataPath
|
||||
if (!fs.existsSync(filePath)) return { version: 1, providers: [] }
|
||||
const data = fs.readJsonSync(filePath) as AIProviderMetadataFile
|
||||
if (data.version !== 1 || !Array.isArray(data.providers))
|
||||
throw new Error('invalid provider metadata')
|
||||
// 老配置兼容:补 capabilities.ocr 默认值(vision 派生 OCR)
|
||||
for (const provider of data.providers) {
|
||||
for (const model of provider.models) {
|
||||
if (typeof model.capabilities.ocr !== 'boolean') {
|
||||
model.capabilities.ocr = model.capabilities.vision === true
|
||||
}
|
||||
}
|
||||
}
|
||||
return data
|
||||
}
|
||||
|
||||
private writeMetadata(data: AIProviderMetadataFile): void {
|
||||
fs.ensureDirSync(path.dirname(this.metadataPath))
|
||||
fs.writeJsonSync(this.metadataPath, data, { spaces: 2 })
|
||||
}
|
||||
|
||||
private get metadataPath(): string {
|
||||
return path.join(app.getPath('userData'), 'ai-providers.json')
|
||||
}
|
||||
}
|
||||
|
||||
function deepSeekProvider(baseUrl?: string, model?: string): AIProviderSummary {
|
||||
const modelId = model?.trim() || 'deepseek-chat'
|
||||
return {
|
||||
id: 'deepseek',
|
||||
name: 'DeepSeek',
|
||||
type: 'openai-compatible',
|
||||
baseUrl: baseUrl?.trim() || 'https://api.deepseek.com',
|
||||
auth: { type: 'bearer' },
|
||||
models: [
|
||||
{
|
||||
name: modelId === 'deepseek-chat' ? 'DeepSeek Chat' : modelId,
|
||||
id: modelId,
|
||||
capabilities: { chat: true, vision: false, ocr: false, longContext: true }
|
||||
}
|
||||
],
|
||||
defaultModel: modelId,
|
||||
advanced: { timeoutMs: 120_000, temperature: 0.7, maxTokens: 4096, extraHeaders: {} },
|
||||
hasApiKey: false,
|
||||
isDefault: true,
|
||||
status: 'untested'
|
||||
}
|
||||
}
|
||||
|
||||
function stripRuntimeFields(
|
||||
provider: AIProviderSummary
|
||||
): Omit<AIProviderSummary, 'hasApiKey' | 'isDefault'> {
|
||||
return {
|
||||
id: provider.id,
|
||||
name: provider.name,
|
||||
type: provider.type,
|
||||
baseUrl: provider.baseUrl,
|
||||
auth: provider.auth,
|
||||
models: provider.models,
|
||||
defaultModel: provider.defaultModel,
|
||||
advanced: provider.advanced,
|
||||
status: provider.status,
|
||||
lastTestedAt: provider.lastTestedAt,
|
||||
lastError: provider.lastError
|
||||
}
|
||||
}
|
||||
|
||||
function needsApiKey(provider: Pick<AIProviderConfig, 'type' | 'auth'>): boolean {
|
||||
return provider.type !== 'ollama' && provider.auth.type !== 'none'
|
||||
}
|
||||
|
||||
function validateProvider(provider: AIProviderConfig): string | undefined {
|
||||
if (!provider.id.trim() || !/^[a-z0-9][a-z0-9-_]*$/i.test(provider.id))
|
||||
return '供应商 ID 格式不正确'
|
||||
if (!provider.name.trim()) return '供应商名称不能为空'
|
||||
if (!provider.baseUrl.trim()) return 'Base URL 不能为空'
|
||||
if (!provider.models.length) return '请至少添加一个模型'
|
||||
if (provider.models.some((model) => !model.name.trim() || !model.id.trim()))
|
||||
return '模型名称和 ID 不能为空'
|
||||
if (!provider.models.some((model) => model.id === provider.defaultModel))
|
||||
return '默认模型不在模型列表中'
|
||||
if (provider.auth.type === 'custom-header' && !provider.auth.headerName?.trim())
|
||||
return '请填写自定义认证字段'
|
||||
return undefined
|
||||
}
|
||||
|
||||
function buildHeaders(provider: AIProviderSummary, apiKey: string): Record<string, string> {
|
||||
const headers: Record<string, string> = {
|
||||
'content-type': 'application/json',
|
||||
...provider.advanced.extraHeaders
|
||||
}
|
||||
if (!apiKey || provider.auth.type === 'none') return headers
|
||||
if (provider.auth.type === 'bearer') headers.authorization = `Bearer ${apiKey}`
|
||||
else if (provider.auth.type === 'x-api-key') headers['x-api-key'] = apiKey
|
||||
else headers[provider.auth.headerName || 'authorization'] = apiKey
|
||||
return headers
|
||||
}
|
||||
|
||||
function requestProvider(
|
||||
provider: AIProviderSummary,
|
||||
apiKey: string,
|
||||
model: string,
|
||||
messages: AIMessage[],
|
||||
testing = false
|
||||
): Promise<AIRequestResult> {
|
||||
return provider.type === 'anthropic-messages'
|
||||
? requestAnthropic(provider, apiKey, model, messages, testing)
|
||||
: requestOpenAICompatible(provider, apiKey, model, messages, testing)
|
||||
}
|
||||
|
||||
function toOpenAIMessages(messages: AIMessage[]): Array<{ role: string; content: unknown }> {
|
||||
return messages.map((message) => ({
|
||||
role: message.role,
|
||||
content:
|
||||
typeof message.content === 'string'
|
||||
? message.content
|
||||
: message.content.map((part) =>
|
||||
part.type === 'text'
|
||||
? { type: 'text', text: part.text }
|
||||
: { type: 'image_url', image_url: { url: part.dataUrl } }
|
||||
)
|
||||
}))
|
||||
}
|
||||
|
||||
function toAnthropicMessages(messages: AIMessage[]): Array<{ role: string; content: unknown }> {
|
||||
return messages
|
||||
.filter((message) => message.role !== 'system')
|
||||
.map((message) => ({
|
||||
role: message.role,
|
||||
content:
|
||||
typeof message.content === 'string'
|
||||
? message.content
|
||||
: message.content.map((part) => {
|
||||
if (part.type === 'text') return { type: 'text', text: part.text }
|
||||
const image = parseVisionImage(part.dataUrl)
|
||||
return {
|
||||
type: 'image',
|
||||
source: { type: 'base64', media_type: image.mimeType, data: image.base64 }
|
||||
}
|
||||
})
|
||||
}))
|
||||
}
|
||||
|
||||
async function requestOpenAICompatible(
|
||||
provider: AIProviderSummary,
|
||||
apiKey: string,
|
||||
model: string,
|
||||
messages: AIMessage[],
|
||||
testing = false
|
||||
): Promise<AIRequestResult> {
|
||||
const endpoint = provider.baseUrl.endsWith('/chat/completions')
|
||||
? provider.baseUrl
|
||||
: `${provider.baseUrl.replace(/\/+$/, '')}/chat/completions`
|
||||
const response = await fetchWithTimeout(
|
||||
endpoint,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: buildHeaders(provider, apiKey),
|
||||
body: JSON.stringify({
|
||||
model,
|
||||
messages: toOpenAIMessages(messages),
|
||||
temperature: provider.advanced.temperature,
|
||||
max_tokens: testing ? 8 : provider.advanced.maxTokens
|
||||
})
|
||||
},
|
||||
provider.advanced.timeoutMs
|
||||
)
|
||||
const payload = await parseJsonResponse<OpenAIResponsePayload>(response)
|
||||
if (!response.ok) throw new Error(payload.error?.message || `AI 请求失败 (${response.status})`)
|
||||
return {
|
||||
data: String(payload.choices?.[0]?.message?.content || ''),
|
||||
usage: payload.usage
|
||||
? {
|
||||
input: payload.usage.prompt_tokens,
|
||||
output: payload.usage.completion_tokens,
|
||||
total: payload.usage.total_tokens,
|
||||
estimated: false
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
}
|
||||
|
||||
async function requestAnthropic(
|
||||
provider: AIProviderSummary,
|
||||
apiKey: string,
|
||||
model: string,
|
||||
messages: AIMessage[],
|
||||
testing = false
|
||||
): Promise<AIRequestResult> {
|
||||
const system = messages
|
||||
.filter((message) => message.role === 'system')
|
||||
.map((message) =>
|
||||
typeof message.content === 'string'
|
||||
? message.content
|
||||
: message.content
|
||||
.filter((part) => part.type === 'text')
|
||||
.map((part) => (part.type === 'text' ? part.text : ''))
|
||||
.join('\n')
|
||||
)
|
||||
.join('\n\n')
|
||||
const anthropicMessages = toAnthropicMessages(messages)
|
||||
const headers = buildHeaders(provider, apiKey)
|
||||
if (!headers['anthropic-version']) headers['anthropic-version'] = '2023-06-01'
|
||||
const endpoint = provider.baseUrl.endsWith('/messages')
|
||||
? provider.baseUrl
|
||||
: `${provider.baseUrl.replace(/\/+$/, '')}/messages`
|
||||
const response = await fetchWithTimeout(
|
||||
endpoint,
|
||||
{
|
||||
method: 'POST',
|
||||
headers,
|
||||
body: JSON.stringify({
|
||||
model,
|
||||
system: system || undefined,
|
||||
messages: anthropicMessages,
|
||||
temperature: provider.advanced.temperature,
|
||||
max_tokens: testing ? 8 : provider.advanced.maxTokens || 4096
|
||||
})
|
||||
},
|
||||
provider.advanced.timeoutMs
|
||||
)
|
||||
const payload = await parseJsonResponse<AnthropicResponsePayload>(response)
|
||||
if (!response.ok)
|
||||
throw new Error(payload.error?.message || `Anthropic 请求失败 (${response.status})`)
|
||||
return {
|
||||
data: Array.isArray(payload.content)
|
||||
? payload.content
|
||||
.filter((item) => item.type === 'text')
|
||||
.map((item) => item.text || '')
|
||||
.join('\n')
|
||||
: '',
|
||||
usage: payload.usage
|
||||
? {
|
||||
input: payload.usage.input_tokens,
|
||||
output: payload.usage.output_tokens,
|
||||
total: Number(payload.usage.input_tokens || 0) + Number(payload.usage.output_tokens || 0),
|
||||
estimated: false
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
}
|
||||
|
||||
async function fetchWithTimeout(
|
||||
url: string,
|
||||
init: RequestInit,
|
||||
timeoutMs: number
|
||||
): Promise<Response> {
|
||||
const controller = new AbortController()
|
||||
const timer = setTimeout(() => controller.abort(), Math.max(1_000, timeoutMs || 120_000))
|
||||
try {
|
||||
return await fetch(url, { ...init, signal: controller.signal })
|
||||
} finally {
|
||||
clearTimeout(timer)
|
||||
}
|
||||
}
|
||||
|
||||
async function parseJsonResponse<T>(response: Response): Promise<T> {
|
||||
const body = await response.text()
|
||||
try {
|
||||
return JSON.parse(body) as T
|
||||
} catch {
|
||||
const looksLikeHtml = /^\s*(?:<!doctype\s+html|<html\b)/i.test(body)
|
||||
const status = `${response.status}${response.statusText ? ` ${response.statusText}` : ''}`
|
||||
if (looksLikeHtml) {
|
||||
throw new Error(`模型服务返回了网页而不是 JSON(HTTP ${status}),请稍后重试或检查中转服务`)
|
||||
}
|
||||
throw new Error(`模型服务返回格式异常(HTTP ${status})`)
|
||||
}
|
||||
}
|
||||
|
||||
function safeAIError(error: unknown): string {
|
||||
if (error instanceof DOMException && error.name === 'AbortError') return 'AI 请求超时'
|
||||
const message = error instanceof Error ? error.message : String(error)
|
||||
return message.replace(/sk-[a-z0-9_-]+/gi, '***').slice(0, 300)
|
||||
}
|
||||
|
||||
function parseVisionImage(dataUrl: string): { mimeType: string; base64: string; bytes: number } {
|
||||
const match = /^data:(image\/(?:png|jpeg|webp));base64,([a-z0-9+/=]+)$/i.exec(dataUrl)
|
||||
if (!match) throw new Error('图片格式不受支持,请选择 PNG、JPG、JPEG 或 WebP')
|
||||
const bytes = Buffer.byteLength(match[2], 'base64')
|
||||
return { mimeType: match[1].toLowerCase(), base64: match[2], bytes }
|
||||
}
|
||||
|
||||
function validateVisionImage(dataUrl: string): string | undefined {
|
||||
try {
|
||||
const image = parseVisionImage(dataUrl)
|
||||
if (!image.bytes) return '图片内容为空'
|
||||
if (image.bytes > 10 * 1024 * 1024) return '图片不能超过 10 MB'
|
||||
return undefined
|
||||
} catch (error) {
|
||||
return error instanceof Error ? error.message : '图片无法读取'
|
||||
}
|
||||
}
|
||||
|
||||
function visionFailure(error: unknown): {
|
||||
code: 'VISION_UNSUPPORTED' | 'API_ERROR'
|
||||
error: string
|
||||
} {
|
||||
const message = safeAIError(error)
|
||||
const unsupported =
|
||||
/vision|multimodal|image[_ ]url|image input|image.*support|support.*image|图片.*不支持|不支持.*图片/i.test(
|
||||
message
|
||||
)
|
||||
return unsupported
|
||||
? { code: 'VISION_UNSUPPORTED', error: '当前模型不支持图片理解' }
|
||||
: { code: 'API_ERROR', error: message || 'API 返回错误' }
|
||||
}
|
||||
@@ -0,0 +1,246 @@
|
||||
import { app } from 'electron'
|
||||
import crypto from 'crypto'
|
||||
import fs from 'fs-extra'
|
||||
import path from 'path'
|
||||
import type { Contact, Message } from '../../shared/types'
|
||||
|
||||
export interface CachedSelfInfo {
|
||||
wxid: string
|
||||
nickname: string
|
||||
avatar?: string
|
||||
accountRoot: string
|
||||
}
|
||||
|
||||
interface CachedMessageBucket {
|
||||
updatedAt: number
|
||||
startTime?: number
|
||||
endTime?: number
|
||||
items: Message[]
|
||||
}
|
||||
|
||||
interface BootstrapCacheFile {
|
||||
version: 1
|
||||
platform: NodeJS.Platform
|
||||
accountRoot: string
|
||||
updatedAt: number
|
||||
self?: CachedSelfInfo
|
||||
contacts?: Contact[]
|
||||
messages?: Record<string, CachedMessageBucket>
|
||||
}
|
||||
|
||||
const CACHE_VERSION = 1
|
||||
const MAX_MESSAGE_BUCKETS = 24
|
||||
const MAX_MESSAGES_PER_BUCKET = 1200
|
||||
|
||||
function normalizeRoot(accountRoot?: string): string {
|
||||
return String(accountRoot || '').trim()
|
||||
}
|
||||
|
||||
function getCacheFile(accountRoot?: string): string {
|
||||
const normalizedRoot = normalizeRoot(accountRoot) || 'default'
|
||||
const hash = crypto
|
||||
.createHash('sha1')
|
||||
.update(`${process.platform}:${normalizedRoot}`)
|
||||
.digest('hex')
|
||||
.slice(0, 16)
|
||||
return path.join(app.getPath('userData'), 'cache', 'bootstrap', `${process.platform}-${hash}.json`)
|
||||
}
|
||||
|
||||
function readCacheFile(accountRoot?: string): BootstrapCacheFile | null {
|
||||
const normalizedRoot = normalizeRoot(accountRoot)
|
||||
if (!normalizedRoot) return null
|
||||
const file = getCacheFile(normalizedRoot)
|
||||
try {
|
||||
if (!fs.existsSync(file)) return null
|
||||
const raw = fs.readJsonSync(file) as Partial<BootstrapCacheFile>
|
||||
if (raw.version !== CACHE_VERSION || raw.platform !== process.platform) return null
|
||||
if (normalizeRoot(raw.accountRoot) !== normalizedRoot) return null
|
||||
return {
|
||||
version: CACHE_VERSION,
|
||||
platform: process.platform,
|
||||
accountRoot: normalizedRoot,
|
||||
updatedAt: Number(raw.updatedAt) || 0,
|
||||
self: raw.self,
|
||||
contacts: Array.isArray(raw.contacts) ? raw.contacts : [],
|
||||
messages: raw.messages && typeof raw.messages === 'object' ? raw.messages : {}
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('[BootstrapCache] read failed:', error)
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
function writeCacheFile(cache: BootstrapCacheFile): void {
|
||||
try {
|
||||
const file = getCacheFile(cache.accountRoot)
|
||||
fs.ensureDirSync(path.dirname(file))
|
||||
fs.writeJsonSync(file, cache, { spaces: 2 })
|
||||
} catch (error) {
|
||||
console.warn('[BootstrapCache] write failed:', error)
|
||||
}
|
||||
}
|
||||
|
||||
function loadOrCreate(accountRoot?: string): BootstrapCacheFile | null {
|
||||
const normalizedRoot = normalizeRoot(accountRoot)
|
||||
if (!normalizedRoot) return null
|
||||
return (
|
||||
readCacheFile(normalizedRoot) || {
|
||||
version: CACHE_VERSION,
|
||||
platform: process.platform,
|
||||
accountRoot: normalizedRoot,
|
||||
updatedAt: Date.now(),
|
||||
contacts: [],
|
||||
messages: {}
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
function messageBucketKey(userMd5: string, startTime?: number, endTime?: number): string {
|
||||
return `${userMd5}:${startTime ?? ''}:${endTime ?? ''}`
|
||||
}
|
||||
|
||||
function pruneMessageBuckets(messages: Record<string, CachedMessageBucket>): void {
|
||||
const entries = Object.entries(messages)
|
||||
if (entries.length <= MAX_MESSAGE_BUCKETS) return
|
||||
entries
|
||||
.sort((left, right) => (right[1].updatedAt || 0) - (left[1].updatedAt || 0))
|
||||
.slice(MAX_MESSAGE_BUCKETS)
|
||||
.forEach(([key]) => {
|
||||
delete messages[key]
|
||||
})
|
||||
}
|
||||
|
||||
export function getBootstrapCache(accountRoot?: string): {
|
||||
self?: CachedSelfInfo
|
||||
contacts: Contact[]
|
||||
updatedAt: number
|
||||
} | null {
|
||||
const cache = readCacheFile(accountRoot)
|
||||
if (!cache) return null
|
||||
return {
|
||||
self: cache.self,
|
||||
contacts: cache.contacts || [],
|
||||
updatedAt: cache.updatedAt
|
||||
}
|
||||
}
|
||||
|
||||
function isRawContactName(contact: Contact): boolean {
|
||||
const name = String(contact.m_nsNickName || '').trim()
|
||||
const username = String(contact.m_nsUsrName || '').trim()
|
||||
if (!name) return true
|
||||
if (name === username) return true
|
||||
if (name.endsWith('@chatroom')) return true
|
||||
if (name.startsWith('Group_') || name.startsWith('Unknown_')) return true
|
||||
return false
|
||||
}
|
||||
|
||||
export function mergeCachedContactAvatars(accountRoot: string, contacts: Contact[]): Contact[] {
|
||||
const cache = readCacheFile(accountRoot)
|
||||
if (!cache?.contacts?.length) return contacts
|
||||
const avatarByUsername = new Map(
|
||||
cache.contacts
|
||||
.filter((contact) => contact.m_nsUsrName && contact.avatar)
|
||||
.map((contact) => [contact.m_nsUsrName, contact.avatar as string])
|
||||
)
|
||||
const nameByUsername = new Map(
|
||||
cache.contacts
|
||||
.filter((contact) => contact.m_nsUsrName && contact.m_nsNickName && !isRawContactName(contact))
|
||||
.map((contact) => [contact.m_nsUsrName, contact.m_nsNickName])
|
||||
)
|
||||
if (avatarByUsername.size === 0 && nameByUsername.size === 0) return contacts
|
||||
return contacts.map((contact) => ({
|
||||
...contact,
|
||||
avatar:
|
||||
contact.avatar || !avatarByUsername.has(contact.m_nsUsrName)
|
||||
? contact.avatar
|
||||
: avatarByUsername.get(contact.m_nsUsrName),
|
||||
m_nsNickName:
|
||||
!isRawContactName(contact) || !nameByUsername.has(contact.m_nsUsrName)
|
||||
? contact.m_nsNickName
|
||||
: nameByUsername.get(contact.m_nsUsrName) || contact.m_nsNickName
|
||||
}))
|
||||
}
|
||||
|
||||
export function saveBootstrapSelf(accountRoot: string, self: CachedSelfInfo): void {
|
||||
const cache = loadOrCreate(accountRoot)
|
||||
if (!cache) return
|
||||
cache.self = self
|
||||
cache.updatedAt = Date.now()
|
||||
writeCacheFile(cache)
|
||||
}
|
||||
|
||||
export function saveBootstrapContacts(accountRoot: string, contacts: Contact[]): void {
|
||||
const cache = loadOrCreate(accountRoot)
|
||||
if (!cache) return
|
||||
const avatarByUsername = new Map(
|
||||
(cache.contacts || [])
|
||||
.filter((contact) => contact.m_nsUsrName && contact.avatar)
|
||||
.map((contact) => [contact.m_nsUsrName, contact.avatar as string])
|
||||
)
|
||||
const nameByUsername = new Map(
|
||||
(cache.contacts || [])
|
||||
.filter((contact) => contact.m_nsUsrName && contact.m_nsNickName && !isRawContactName(contact))
|
||||
.map((contact) => [contact.m_nsUsrName, contact.m_nsNickName])
|
||||
)
|
||||
cache.contacts = contacts.map((contact) => ({
|
||||
...contact,
|
||||
avatar:
|
||||
contact.avatar || !avatarByUsername.has(contact.m_nsUsrName)
|
||||
? contact.avatar
|
||||
: avatarByUsername.get(contact.m_nsUsrName),
|
||||
m_nsNickName:
|
||||
!isRawContactName(contact) || !nameByUsername.has(contact.m_nsUsrName)
|
||||
? contact.m_nsNickName
|
||||
: nameByUsername.get(contact.m_nsUsrName) || contact.m_nsNickName
|
||||
}))
|
||||
cache.updatedAt = Date.now()
|
||||
writeCacheFile(cache)
|
||||
}
|
||||
|
||||
export function mergeBootstrapAvatars(accountRoot: string, avatars: Record<string, string>): void {
|
||||
const cache = loadOrCreate(accountRoot)
|
||||
if (!cache || !cache.contacts?.length) return
|
||||
let changed = false
|
||||
cache.contacts = cache.contacts.map((contact) => {
|
||||
const avatar = avatars[contact.m_nsUsrName]
|
||||
if (!avatar || contact.avatar === avatar) return contact
|
||||
changed = true
|
||||
return { ...contact, avatar }
|
||||
})
|
||||
if (!changed) return
|
||||
cache.updatedAt = Date.now()
|
||||
writeCacheFile(cache)
|
||||
}
|
||||
|
||||
export function getCachedMessages(
|
||||
accountRoot: string,
|
||||
userMd5: string,
|
||||
startTime?: number,
|
||||
endTime?: number
|
||||
): Message[] {
|
||||
const cache = readCacheFile(accountRoot)
|
||||
const bucket = cache?.messages?.[messageBucketKey(userMd5, startTime, endTime)]
|
||||
return bucket?.items || []
|
||||
}
|
||||
|
||||
export function saveCachedMessages(
|
||||
accountRoot: string,
|
||||
userMd5: string,
|
||||
startTime: number | undefined,
|
||||
endTime: number | undefined,
|
||||
messages: Message[]
|
||||
): void {
|
||||
const cache = loadOrCreate(accountRoot)
|
||||
if (!cache) return
|
||||
const nextMessages = cache.messages || {}
|
||||
nextMessages[messageBucketKey(userMd5, startTime, endTime)] = {
|
||||
updatedAt: Date.now(),
|
||||
startTime,
|
||||
endTime,
|
||||
items: messages.slice(-MAX_MESSAGES_PER_BUCKET)
|
||||
}
|
||||
pruneMessageBuckets(nextMessages)
|
||||
cache.messages = nextMessages
|
||||
cache.updatedAt = Date.now()
|
||||
writeCacheFile(cache)
|
||||
}
|
||||
@@ -4,6 +4,10 @@ import {
|
||||
parseMessageContent,
|
||||
parseStickerMessageFromRow
|
||||
} from '../message-parser'
|
||||
import type {
|
||||
DatabaseKeyValidationCode,
|
||||
DatabaseKeyValidationResult
|
||||
} from '../../shared/database-key'
|
||||
|
||||
export function getCurrentKey(): string {
|
||||
if (!dbRef) return ''
|
||||
@@ -14,6 +18,15 @@ export function getCurrentKey(): string {
|
||||
}
|
||||
}
|
||||
|
||||
export function getCurrentAccountRoot(): string {
|
||||
if (!dbRef) return ''
|
||||
try {
|
||||
return dbRef.getWcdb4Client().getAccountRoot()
|
||||
} catch {
|
||||
return ''
|
||||
}
|
||||
}
|
||||
|
||||
export interface FormattedContact {
|
||||
m_nsUsrName: string
|
||||
m_nsNickName: string
|
||||
@@ -31,6 +44,7 @@ export interface FormattedMessage {
|
||||
isSender: boolean
|
||||
img?: string
|
||||
name?: string
|
||||
senderId?: string
|
||||
contentData?: ReturnType<typeof parseMessageContent>
|
||||
voiceDataUrl?: string
|
||||
voiceDuration?: number
|
||||
@@ -42,7 +56,14 @@ export interface FormattedMessage {
|
||||
export interface GroupSnapshot {
|
||||
roomId: string
|
||||
memberCount: number
|
||||
members: { wxid: string; nickname: string; avatar: string }[]
|
||||
members: {
|
||||
wxid: string
|
||||
nickname: string
|
||||
groupNickname: string
|
||||
wechatNickname: string
|
||||
remark: string
|
||||
avatar: string
|
||||
}[]
|
||||
}
|
||||
|
||||
const MSG_TYPE_DICT: Record<number, string> = {
|
||||
@@ -133,23 +154,36 @@ export function listContacts(filter?: string): FormattedContact[] {
|
||||
return contacts
|
||||
}
|
||||
|
||||
export function getContactAvatars(usernames: string[]): Record<string, string> {
|
||||
if (!dbRef) return {}
|
||||
const normalized = Array.from(
|
||||
new Set((usernames || []).map((username) => String(username || '').trim()).filter(Boolean))
|
||||
)
|
||||
if (normalized.length === 0) return {}
|
||||
return dbRef.getWcdb4Client().getAvatarUrls(normalized)
|
||||
}
|
||||
|
||||
export function listMessages(
|
||||
userMd5: string,
|
||||
startTime?: number,
|
||||
endTime?: number
|
||||
endTime?: number,
|
||||
options?: { limit?: number }
|
||||
): FormattedMessage[] {
|
||||
if (!dbRef) return []
|
||||
|
||||
const startedAt = Date.now()
|
||||
const wcdb4Client = dbRef.getWcdb4Client()
|
||||
const username = wcdb4Client.getUsernameByMd5(userMd5)
|
||||
const rawMessages = dbRef.getUserMessages(userMd5, startTime, endTime)
|
||||
const groupMembers = dbRef.getGroupMembersForChat(userMd5)
|
||||
const myAvatar = dbRef.getMyAvatarUrl()
|
||||
const myGroupNickname = username?.endsWith('@chatroom')
|
||||
? wcdb4Client.getMyGroupNickname(username)
|
||||
: undefined
|
||||
const isGroupChat = Boolean(username?.endsWith('@chatroom'))
|
||||
console.log(
|
||||
`[ChatService] listMessages begin md5=${userMd5} username=${username || ''} start=${startTime || 0} end=${endTime || 0} limit=${options?.limit || 0}`
|
||||
)
|
||||
const rawMessages = dbRef.getUserMessages(userMd5, startTime, endTime, options)
|
||||
console.log(
|
||||
`[ChatService] listMessages native done md5=${userMd5} raw=${rawMessages.length} cost=${Date.now() - startedAt}ms`
|
||||
)
|
||||
|
||||
return rawMessages.map((msg: WechatMessage) => {
|
||||
const formatted = rawMessages.map((msg: WechatMessage) => {
|
||||
const rawMsgType = parseInt(msg.messageType)
|
||||
const msgType = normalizeMsgType(msg.messageType)
|
||||
const createTime = parseInt(msg.msgCreateTime)
|
||||
@@ -160,27 +194,25 @@ export function listMessages(
|
||||
let content = msg.msgContent
|
||||
let img = ''
|
||||
let name = ''
|
||||
let senderId = typeof msg.sender === 'string' ? msg.sender : ''
|
||||
if (isMine) {
|
||||
if (myAvatar) img = myAvatar
|
||||
name = myGroupNickname || (typeof msg.senderNickname === 'string' ? msg.senderNickname : '')
|
||||
name = typeof msg.senderNickname === 'string' ? msg.senderNickname : ''
|
||||
} else {
|
||||
if (typeof msg.senderAvatar === 'string') img = msg.senderAvatar
|
||||
if (typeof msg.senderNickname === 'string') name = msg.senderNickname
|
||||
}
|
||||
if (content && typeof content === 'string') {
|
||||
if (isGroupChat && content && typeof content === 'string') {
|
||||
const colonIndex = content.indexOf(':')
|
||||
if (colonIndex > 0) {
|
||||
const potentialWxid = content.substring(0, colonIndex)
|
||||
if (potentialWxid.startsWith('wxid_')) {
|
||||
const member = dbRef!.getGroupMember(potentialWxid)
|
||||
if (member) img = member.m_nsHeadImgUrl
|
||||
if (groupMembers[potentialWxid]) {
|
||||
name = groupMembers[potentialWxid]
|
||||
content = content.substring(colonIndex + 1)
|
||||
}
|
||||
const potentialSenderId = content.substring(0, colonIndex).trim()
|
||||
if (/^[a-zA-Z0-9_@.-]{3,64}$/.test(potentialSenderId)) {
|
||||
senderId = senderId || potentialSenderId
|
||||
name = name || potentialSenderId
|
||||
content = content.substring(colonIndex + 1).replace(/^\s+/, '')
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!isMine && !name && senderId) name = senderId
|
||||
|
||||
let contentData: ReturnType<typeof parseMessageContent> | undefined
|
||||
let displayType = MSG_TYPE_DICT[msgType] || msg.messageType
|
||||
@@ -218,11 +250,7 @@ export function listMessages(
|
||||
}
|
||||
}
|
||||
|
||||
if (
|
||||
!contentData &&
|
||||
typeof content === 'string' &&
|
||||
/^[0-9a-fA-F]{64,}$/.test(content.trim())
|
||||
) {
|
||||
if (!contentData && typeof content === 'string' && /^[0-9a-fA-F]{64,}$/.test(content.trim())) {
|
||||
const parsed = parseStickerMessageFromRow(msg, content)
|
||||
if (parsed.type === 'sticker') {
|
||||
if (!parsed.url && parsed.md5) {
|
||||
@@ -245,12 +273,18 @@ export function listMessages(
|
||||
content,
|
||||
img,
|
||||
name,
|
||||
senderId,
|
||||
sessionId: username,
|
||||
localId,
|
||||
createTime,
|
||||
contentData
|
||||
}
|
||||
})
|
||||
|
||||
console.log(
|
||||
`[ChatService] listMessages end md5=${userMd5} formatted=${formatted.length} cost=${Date.now() - startedAt}ms`
|
||||
)
|
||||
return formatted
|
||||
}
|
||||
|
||||
export function getGroupSnapshot(userMd5: string): GroupSnapshot | null {
|
||||
@@ -265,6 +299,9 @@ export function getGroupSnapshot(userMd5: string): GroupSnapshot | null {
|
||||
.map((member) => ({
|
||||
wxid: member.m_nsUsrName,
|
||||
nickname: member.nickname || '',
|
||||
groupNickname: member.groupNickname || '',
|
||||
wechatNickname: member.wechatNickname || '',
|
||||
remark: member.remark || '',
|
||||
avatar: member.m_nsHeadImgUrl || ''
|
||||
}))
|
||||
|
||||
@@ -297,8 +334,7 @@ export function resolveMd5(query: string): FormattedContact | null {
|
||||
|
||||
const partial = contacts.find(
|
||||
(c) =>
|
||||
c.m_nsNickName.toLowerCase().includes(lower) ||
|
||||
c.m_nsUsrName.toLowerCase().includes(lower)
|
||||
c.m_nsNickName.toLowerCase().includes(lower) || c.m_nsUsrName.toLowerCase().includes(lower)
|
||||
)
|
||||
return partial || null
|
||||
}
|
||||
@@ -350,32 +386,87 @@ export function getSelfAccountInfo(): SelfAccountInfo | null {
|
||||
}
|
||||
}
|
||||
|
||||
export function testConnection(
|
||||
key: string,
|
||||
accountRoot?: string
|
||||
): { success: boolean; error?: string; accountRoot?: string; wxid?: string } {
|
||||
try {
|
||||
const probeKey = key.replace(/^0x/i, '').trim()
|
||||
if (!probeKey) {
|
||||
return { success: false, error: '密钥不能为空' }
|
||||
}
|
||||
const probe = accountRoot ? new WechatDb(probeKey, accountRoot) : new WechatDb(probeKey)
|
||||
try {
|
||||
probe.close()
|
||||
} catch {
|
||||
// best effort
|
||||
}
|
||||
return {
|
||||
success: true,
|
||||
accountRoot: probe.getWcdb4Client().getAccountRoot(),
|
||||
wxid: (probe.getWcdb4Client().getMyUsernameCandidates?.() ?? [])[0] || ''
|
||||
}
|
||||
} catch (error) {
|
||||
export function testConnection(key: string, accountRoot?: string): DatabaseKeyValidationResult {
|
||||
const probeKey = key.replace(/^0x/i, '').trim()
|
||||
if (!/^[0-9a-f]{64}$/i.test(probeKey)) {
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : String(error)
|
||||
code: 'INVALID_FORMAT',
|
||||
error: '密钥格式不正确'
|
||||
}
|
||||
}
|
||||
|
||||
let probe: WechatDb | null = null
|
||||
let ownsProbe = false
|
||||
try {
|
||||
const current = dbRef
|
||||
const canReuseCurrent =
|
||||
current &&
|
||||
getCurrentKey().replace(/^0x/i, '').trim() === probeKey &&
|
||||
(!accountRoot || getCurrentAccountRoot() === accountRoot)
|
||||
const validationDb = canReuseCurrent
|
||||
? current
|
||||
: accountRoot
|
||||
? new WechatDb(probeKey, accountRoot)
|
||||
: new WechatDb(probeKey)
|
||||
probe = validationDb
|
||||
ownsProbe = validationDb !== current
|
||||
const client = validationDb.getWcdb4Client()
|
||||
const contacts = client.getSessions()
|
||||
const messages = client.getChatTables()
|
||||
if (contacts[0]) client.getMessages(contacts[0].username, undefined, undefined, { limit: 1 })
|
||||
return {
|
||||
success: true,
|
||||
accountRoot: client.getAccountRoot(),
|
||||
wxid: (client.getMyUsernameCandidates?.() ?? [])[0] || '',
|
||||
contacts: { available: true, count: contacts.length },
|
||||
messages: { available: true, count: messages.length }
|
||||
}
|
||||
} catch (error) {
|
||||
const detail = error instanceof Error ? error.message : String(error)
|
||||
const code = mapConnectionError(detail)
|
||||
return {
|
||||
success: false,
|
||||
code,
|
||||
error: DATABASE_KEY_ERROR_MESSAGES[code]
|
||||
}
|
||||
} finally {
|
||||
try {
|
||||
// macOS native shutdown is process-wide. Do not tear down the active reader
|
||||
// when validating a replacement key; the new runtime connection takes over on save.
|
||||
if (ownsProbe && !(process.platform === 'darwin' && dbRef)) probe?.close()
|
||||
} catch {
|
||||
// Validation probes are best-effort closed without exposing native details.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const DATABASE_KEY_ERROR_MESSAGES: Record<DatabaseKeyValidationCode, string> = {
|
||||
INVALID_FORMAT: '密钥格式不正确',
|
||||
DATABASE_OPEN_FAILED: '无法打开数据库',
|
||||
ACCOUNT_MISMATCH: '密钥与当前账号不匹配',
|
||||
ROOT_UNAVAILABLE: '当前数据库目录不可用',
|
||||
DATABASE_FILE_MISSING: '数据库文件缺失',
|
||||
UNKNOWN_VALIDATION_ERROR: '未知验证错误'
|
||||
}
|
||||
|
||||
function mapConnectionError(detail: string): DatabaseKeyValidationCode {
|
||||
const normalized = detail.toLowerCase()
|
||||
if (normalized.includes('-1005') || normalized.includes('不匹配')) return 'ACCOUNT_MISMATCH'
|
||||
if (normalized.includes('session.db') || normalized.includes('数据库文件')) {
|
||||
return 'DATABASE_FILE_MISSING'
|
||||
}
|
||||
if (
|
||||
normalized.includes('数据目录') ||
|
||||
normalized.includes('账号目录') ||
|
||||
normalized.includes('db_storage')
|
||||
) {
|
||||
return 'ROOT_UNAVAILABLE'
|
||||
}
|
||||
if (normalized.includes('wcdb_open_account') || normalized.includes('open')) {
|
||||
return 'DATABASE_OPEN_FAILED'
|
||||
}
|
||||
return 'UNKNOWN_VALIDATION_ERROR'
|
||||
}
|
||||
|
||||
export function reopenWithRoot(accountRoot: string): boolean {
|
||||
|
||||
@@ -0,0 +1,139 @@
|
||||
import { app } from 'electron'
|
||||
import fs from 'fs-extra'
|
||||
import os from 'os'
|
||||
import path from 'path'
|
||||
import type {
|
||||
ImageDecryptionStatus,
|
||||
ImageDecryptionTestResult,
|
||||
ImageKeyConfigResult,
|
||||
ImageResourceCheck,
|
||||
TestImageDecryptionRequest
|
||||
} from '../../shared/image-decryption'
|
||||
import { ImageDecryptService } from '../image-decrypt-service'
|
||||
import * as chat from './chat-service'
|
||||
import { validateImageKeyRequest } from './image-key-config-service'
|
||||
import { isWechatRunning } from './wechat-process-status'
|
||||
|
||||
export async function inspectImageDecryptionStatus(
|
||||
config: ImageKeyConfigResult
|
||||
): Promise<ImageDecryptionStatus> {
|
||||
const accountRoot = chat.getCurrentAccountRoot() || config.resourceRoot
|
||||
const imageDirectoryFound = hasImageDirectory(accountRoot)
|
||||
const stickerCacheFound =
|
||||
fs.existsSync(path.join(accountRoot, 'cache')) ||
|
||||
fs.existsSync(path.join(os.homedir(), 'Documents', 'WechatExplorer', 'Emojis'))
|
||||
const dbConnected = chat.isReady()
|
||||
|
||||
return {
|
||||
configured: config.configured,
|
||||
saved: config.saved,
|
||||
encryptionAvailable: config.encryptionAvailable,
|
||||
source: config.source,
|
||||
accountId: config.accountId,
|
||||
resourceRoot: accountRoot,
|
||||
updatedAt: config.updatedAt,
|
||||
platform: process.platform,
|
||||
autoDetectSupported: process.platform === 'win32' || process.platform === 'darwin',
|
||||
wechatRunning: await isWechatRunning(),
|
||||
accountIdentified: Boolean(chat.getSelfAccountInfo()?.wxid),
|
||||
cacheState: canUseCacheRoot() ? 'normal' : 'unavailable',
|
||||
resources: {
|
||||
imageIndex: check(dbConnected, dbConnected ? '可用' : '数据库尚未连接'),
|
||||
imageDirectory: check(imageDirectoryFound, imageDirectoryFound ? '已找到' : '未找到'),
|
||||
thumbnail: pending(imageDirectoryFound),
|
||||
original: pending(imageDirectoryFound),
|
||||
sticker: stickerCacheFound
|
||||
? check(true, '本地缓存可用')
|
||||
: { state: 'unknown', detail: '独立按需解析' },
|
||||
video: { state: 'unavailable', detail: '当前版本未提供视频媒体解析' }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function testImageDecryption(
|
||||
request: TestImageDecryptionRequest
|
||||
): ImageDecryptionTestResult {
|
||||
const normalized = validateImageKeyRequest(request)
|
||||
if (!normalized.success) return failure('NOT_CONFIGURED', normalized.error)
|
||||
if (!chat.isReady() || !request.userMd5) {
|
||||
return failure('NO_CONVERSATION', '请选择已连接账号中的聊天记录')
|
||||
}
|
||||
|
||||
try {
|
||||
const messages = chat.listMessages(request.userMd5, undefined, undefined, { limit: 300 })
|
||||
const imageMessage = [...messages]
|
||||
.reverse()
|
||||
.find((message) => message.contentData?.type === 'image')
|
||||
if (!imageMessage || imageMessage.contentData?.type !== 'image') {
|
||||
return failure('NO_IMAGE_MESSAGE', '所选聊天最近没有可测试的图片消息')
|
||||
}
|
||||
|
||||
const service = new ImageDecryptService(
|
||||
normalized.xorKey,
|
||||
normalized.aesKey,
|
||||
chat.getChatDb()?.getWcdb4Client()
|
||||
)
|
||||
const image = imageMessage.contentData
|
||||
let filePath = service.findImageFile(image.md5, image.datName, { allowThumbnail: false })
|
||||
if (!filePath)
|
||||
filePath = service.findImageFile(image.md5, image.datName, { allowThumbnail: true })
|
||||
if (!filePath) return failure('FILE_NOT_FOUND', '图片文件不存在')
|
||||
|
||||
const data = service.decryptImageToBase64(filePath)
|
||||
if (!data) {
|
||||
return {
|
||||
...failure('DECRYPT_FAILED', '无法解析媒体文件'),
|
||||
fileFound: true
|
||||
}
|
||||
}
|
||||
const readable = data.startsWith('data:image/')
|
||||
return {
|
||||
success: readable,
|
||||
code: readable ? undefined : 'DECRYPT_FAILED',
|
||||
error: readable ? undefined : '图片解密结果不可读取',
|
||||
fileFound: true,
|
||||
decrypted: true,
|
||||
readable,
|
||||
isThumbnail: service.isThumbnailFile(filePath)
|
||||
}
|
||||
} catch {
|
||||
return failure('UNKNOWN', '图片解析测试未通过')
|
||||
}
|
||||
}
|
||||
|
||||
function hasImageDirectory(accountRoot: string): boolean {
|
||||
if (!accountRoot) return false
|
||||
return [
|
||||
path.join(accountRoot, 'msg', 'attach'),
|
||||
path.join(accountRoot, 'FileStorage', 'Image'),
|
||||
path.join(accountRoot, 'FileStorage', 'Image2'),
|
||||
path.join(accountRoot, 'FileStorage', 'MsgImg')
|
||||
].some((candidate) => fs.existsSync(candidate))
|
||||
}
|
||||
|
||||
function canUseCacheRoot(): boolean {
|
||||
try {
|
||||
const cacheRoot = path.join(app.getPath('userData'), 'cache')
|
||||
fs.ensureDirSync(cacheRoot)
|
||||
return fs.statSync(cacheRoot).isDirectory()
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
function check(available: boolean, detail: string): ImageResourceCheck {
|
||||
return { state: available ? 'available' : 'unavailable', detail }
|
||||
}
|
||||
|
||||
function pending(directoryFound: boolean): ImageResourceCheck {
|
||||
return directoryFound
|
||||
? { state: 'unknown', detail: '通过图片解析测试确认' }
|
||||
: { state: 'unavailable', detail: '图片目录不可用' }
|
||||
}
|
||||
|
||||
function failure(
|
||||
code: NonNullable<ImageDecryptionTestResult['code']>,
|
||||
error: string
|
||||
): ImageDecryptionTestResult {
|
||||
return { success: false, code, error, fileFound: false, decrypted: false, readable: false }
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
// src/main/services/image-insight-prompt.ts
|
||||
// 图片理解 prompt 模板 — 输出严格的 JSON,便于程序化解析
|
||||
|
||||
export const IMAGE_ANALYSIS_SYSTEM_PROMPT = `你是微信群聊的图片分析助手。
|
||||
请根据用户提供的图片和图片前后的聊天上下文,生成对该图片的结构化理解。
|
||||
|
||||
输出要求(严格遵守):
|
||||
1. 必须输出 JSON,不要用 markdown 代码块包裹
|
||||
2. description:1-2 句中文,30-80 字,描述图片核心内容
|
||||
3. ocrText:如果图片含文字(截图、文档、票据等),提取出来;纯风景/表情包可填空字符串
|
||||
4. tags:3-6 个中文关键词标签
|
||||
5. category:screenshot / photo / meme / document / chart / other 之一
|
||||
6. importance:low / medium / high — 根据图片的信息密度和后续讨论热度判断
|
||||
|
||||
禁止:
|
||||
- 不要猜测图片中未明确可见的内容
|
||||
- 不要复述聊天上下文本身(那是 description 之外的事)
|
||||
- 不要输出 markdown 标记`
|
||||
|
||||
export interface ImageAnalysisContext {
|
||||
sender: string
|
||||
sentAt: number
|
||||
contextBefore: string[] // 图片前 1-3 条消息
|
||||
contextAfter: string[] // 图片后 1-3 条消息
|
||||
}
|
||||
|
||||
export function buildImageAnalysisUserText(ctx: ImageAnalysisContext): string {
|
||||
const before = ctx.contextBefore.length
|
||||
? ctx.contextBefore.map((m, i) => ` ${i + 1}. ${m}`).join('\n')
|
||||
: ' (无前文)'
|
||||
const after = ctx.contextAfter.length
|
||||
? ctx.contextAfter.map((m, i) => ` ${i + 1}. ${m}`).join('\n')
|
||||
: ' (无后续讨论)'
|
||||
const time = new Date(ctx.sentAt * 1000).toLocaleString('zh-CN', { hour12: false })
|
||||
|
||||
return `发送者:${ctx.sender}
|
||||
时间:${time}
|
||||
|
||||
图片前的聊天:
|
||||
${before}
|
||||
|
||||
图片后的聊天:
|
||||
${after}
|
||||
|
||||
请输出 JSON(严格遵守 system 要求):
|
||||
{"description":"...","ocrText":"...","tags":["..."],"category":"...","importance":"..."}`
|
||||
}
|
||||
|
||||
/**
|
||||
* 把 AI 文本响应解析成结构化字段。
|
||||
* 容忍:无 markdown 包裹、有 markdown 包裹、尾部有杂质等。
|
||||
*/
|
||||
export function parseImageAnalysisResponse(raw: string): {
|
||||
description: string
|
||||
ocrText: string
|
||||
tags: string[]
|
||||
category: 'screenshot' | 'photo' | 'meme' | 'document' | 'chart' | 'other'
|
||||
importance: 'low' | 'medium' | 'high'
|
||||
} {
|
||||
const text = raw.trim()
|
||||
// 提取 JSON 段
|
||||
const jsonMatch = text.match(/\{[\s\S]*\}/)
|
||||
if (!jsonMatch) {
|
||||
throw new Error('AI 未返回合法 JSON')
|
||||
}
|
||||
let parsed: Record<string, unknown>
|
||||
try {
|
||||
parsed = JSON.parse(jsonMatch[0])
|
||||
} catch {
|
||||
throw new Error('AI 返回的 JSON 无法解析')
|
||||
}
|
||||
|
||||
const description = String(parsed.description || '').trim()
|
||||
if (!description) throw new Error('AI 未返回 description')
|
||||
|
||||
const ocrText = String(parsed.ocrText || '').trim()
|
||||
const tagsRaw = parsed.tags
|
||||
const tags = Array.isArray(tagsRaw)
|
||||
? tagsRaw.map((t) => String(t).trim()).filter(Boolean).slice(0, 8)
|
||||
: []
|
||||
|
||||
const categoryRaw = String(parsed.category || 'other').toLowerCase()
|
||||
const category: 'screenshot' | 'photo' | 'meme' | 'document' | 'chart' | 'other' =
|
||||
['screenshot', 'photo', 'meme', 'document', 'chart'].includes(categoryRaw)
|
||||
? (categoryRaw as 'screenshot' | 'photo' | 'meme' | 'document' | 'chart')
|
||||
: 'other'
|
||||
|
||||
const importanceRaw = String(parsed.importance || 'medium').toLowerCase()
|
||||
const importance: 'low' | 'medium' | 'high' = ['low', 'medium', 'high'].includes(importanceRaw)
|
||||
? (importanceRaw as 'low' | 'medium' | 'high')
|
||||
: 'medium'
|
||||
|
||||
return { description, ocrText, tags, category, importance }
|
||||
}
|
||||
@@ -0,0 +1,279 @@
|
||||
// src/main/services/image-insight-service.ts
|
||||
// WechatExplorer AI 图片理解基础设施
|
||||
//
|
||||
// 设计原则:
|
||||
// 1. base64 不走 IPC,只在 main 内部流转(renderer 只看到 ImageInsight 结构化结果)
|
||||
// 2. 同图(imageHash)走缓存,绝不重复调 AI
|
||||
// 3. 失败不抛,日志记录 + 返回原状(不阻塞日报)
|
||||
// 4. 第一阶段:Top 3 热点图 + 缓存命中即返回,未命中并发调 AI
|
||||
|
||||
import crypto from 'crypto'
|
||||
import { randomUUID } from 'crypto'
|
||||
import { imageInsightsStore } from '../db/image-insights-store'
|
||||
import {
|
||||
buildImageAnalysisUserText,
|
||||
IMAGE_ANALYSIS_SYSTEM_PROMPT,
|
||||
parseImageAnalysisResponse
|
||||
} from './image-insight-prompt'
|
||||
import type {
|
||||
ImageAnalysisRequest,
|
||||
ImageAnalysisResponse,
|
||||
ImageCandidate,
|
||||
ImageCandidateQuery,
|
||||
ImageInsight
|
||||
} from '../../shared/image-insight'
|
||||
|
||||
/**
|
||||
* 单张图片的最小信息(由 renderer 从已加载的 messages 中提取并传入 main)。
|
||||
* 这样可以避免 ImageInsightService 自己重新查询消息,且参数语义清晰。
|
||||
*/
|
||||
export interface ImageCandidateInput {
|
||||
messageId: string
|
||||
md5?: string
|
||||
datName?: string
|
||||
sessionId: string
|
||||
sender: string
|
||||
sentAt: number
|
||||
/** 图片发出后 8 条消息内、不同发言人的回复数(由 renderer 计算) */
|
||||
responseCount: number
|
||||
/** 表情/语音互动条数 */
|
||||
interactionCount: number
|
||||
}
|
||||
|
||||
interface ProviderServiceLike {
|
||||
list(): ProviderSummaryLike
|
||||
analyzeImage(
|
||||
messages: Array<{
|
||||
role: string
|
||||
content: string | Array<{ type: 'text'; text: string } | { type: 'image'; dataUrl: string }>
|
||||
}>,
|
||||
options?: { providerId?: string; modelId?: string }
|
||||
): Promise<{
|
||||
success: boolean
|
||||
data?: string
|
||||
error?: string
|
||||
}>
|
||||
}
|
||||
|
||||
interface DecryptServiceLike {
|
||||
findImageFile(
|
||||
md5?: string,
|
||||
imageDatName?: string,
|
||||
options?: { allowThumbnail?: boolean }
|
||||
): string | null
|
||||
decryptImageToBase64(datPath: string): string | null
|
||||
}
|
||||
|
||||
interface ProviderSummaryLike {
|
||||
providers: Array<{
|
||||
id: string
|
||||
isDefault: boolean
|
||||
defaultModel: string
|
||||
models: Array<{ id: string; capabilities: { vision: boolean; ocr: boolean } }>
|
||||
}>
|
||||
defaultProviderId?: string
|
||||
}
|
||||
|
||||
class ImageInsightService {
|
||||
private providerService: ProviderServiceLike | null = null
|
||||
private decryptService: DecryptServiceLike | null = null
|
||||
/** 最近一次实际使用的默认 AI provider/model,仅用于写入分析元数据 */
|
||||
private runtimeProviderId: string | undefined = undefined
|
||||
private runtimeModelId: string | undefined = undefined
|
||||
|
||||
/** 注入依赖(由 main/index.ts 在 app ready 后调用) */
|
||||
bind(deps: {
|
||||
providerService: ProviderServiceLike & { list(): ProviderSummaryLike }
|
||||
decryptService: DecryptServiceLike
|
||||
}): void {
|
||||
this.providerService = deps.providerService
|
||||
this.decryptService = deps.decryptService
|
||||
console.log(
|
||||
'[ImageInsightService] bind ok, default provider=%s model=%s',
|
||||
this.runtimeProviderId,
|
||||
this.runtimeModelId
|
||||
)
|
||||
// 读取默认 provider/model(后续 analyze 时使用)
|
||||
try {
|
||||
const list = deps.providerService.list()
|
||||
const provider =
|
||||
list.providers.find((p) => p.id === list.defaultProviderId) || list.providers[0]
|
||||
this.runtimeProviderId = provider?.id
|
||||
this.runtimeModelId = provider?.defaultModel
|
||||
console.log(
|
||||
'[ImageInsightService] bind loaded default provider=%s model=%s',
|
||||
this.runtimeProviderId,
|
||||
this.runtimeModelId
|
||||
)
|
||||
} catch (error) {
|
||||
console.warn('[ImageInsightService] bind list failed:', error)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 计算图片缓存 key:imageHash。
|
||||
* 策略:优先微信原始 md5,无 md5 才用 sha256(rawBytes).slice(0, 32)
|
||||
*/
|
||||
private async computeImageHash(
|
||||
md5: string | undefined,
|
||||
datName: string | undefined
|
||||
): Promise<string | null> {
|
||||
if (md5 && md5.trim()) return md5.trim().toLowerCase()
|
||||
if (!this.decryptService) return null
|
||||
const filePath = this.decryptService.findImageFile(undefined, datName, { allowThumbnail: true })
|
||||
if (!filePath) return null
|
||||
// 一次性读盘 + sha256(只在没有 md5 时才付出 IO)
|
||||
try {
|
||||
const fs = await import('fs-extra')
|
||||
const buf = await fs.readFile(filePath)
|
||||
const sha = crypto.createHash('sha256').update(buf).digest('hex').slice(0, 32)
|
||||
return `sha256:${sha}`
|
||||
} catch (error) {
|
||||
console.warn('[ImageInsightService] computeImageHash failed:', error)
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
/** 通过 hash 拿 Insight(只读缓存,无 AI 调用) */
|
||||
getInsight(imageHash: string): ImageInsight | null {
|
||||
return imageInsightsStore.getByHash(imageHash)
|
||||
}
|
||||
|
||||
/**
|
||||
* 主入口:分析一张图片。
|
||||
* 1. 通过 imageHash 查缓存,命中即返回
|
||||
* 2. 未命中:解密图片 → 调 AI → 解析响应 → 落库 → 返回
|
||||
* 3. 任意步骤失败:记录日志,返回 success=false,**不抛**
|
||||
*/
|
||||
async analyze(request: ImageAnalysisRequest): Promise<ImageAnalysisResponse> {
|
||||
try {
|
||||
if (!request.force) {
|
||||
const cached = imageInsightsStore.getByHash(request.imageHash)
|
||||
if (cached) {
|
||||
return { success: true, insight: cached, fromCache: true }
|
||||
}
|
||||
}
|
||||
|
||||
if (!this.providerService) {
|
||||
return { success: false, error: 'AI Provider 未初始化' }
|
||||
}
|
||||
|
||||
const messages = [
|
||||
{
|
||||
role: 'system',
|
||||
content: IMAGE_ANALYSIS_SYSTEM_PROMPT
|
||||
},
|
||||
{
|
||||
role: 'user',
|
||||
content: [
|
||||
{
|
||||
type: 'text' as const,
|
||||
text: buildImageAnalysisUserText({
|
||||
sender: request.sender,
|
||||
sentAt: request.sentAt,
|
||||
contextBefore: [],
|
||||
contextAfter: []
|
||||
})
|
||||
},
|
||||
{ type: 'image' as const, dataUrl: request.imageDataUrl }
|
||||
]
|
||||
}
|
||||
]
|
||||
|
||||
const list = this.providerService.list()
|
||||
const provider =
|
||||
list.providers.find((item) => item.id === list.defaultProviderId) || list.providers[0]
|
||||
this.runtimeProviderId = provider?.id
|
||||
this.runtimeModelId = provider?.defaultModel
|
||||
const result = await this.providerService.analyzeImage(messages, {
|
||||
providerId: this.runtimeProviderId,
|
||||
modelId: this.runtimeModelId
|
||||
})
|
||||
if (!result.success || !result.data) {
|
||||
console.warn('[ImageInsightService] analyze vision failed: %s', result.error || 'no data')
|
||||
return { success: false, error: result.error || 'AI 未返回内容' }
|
||||
}
|
||||
console.log('[ImageInsightService] analyze ok, description=%s', result.data.slice(0, 80))
|
||||
|
||||
const parsed = parseImageAnalysisResponse(result.data)
|
||||
const insight: ImageInsight = {
|
||||
id: randomUUID(),
|
||||
messageId: request.messageId,
|
||||
imageHash: request.imageHash,
|
||||
md5: undefined,
|
||||
datName: undefined,
|
||||
description: parsed.description,
|
||||
ocrText: parsed.ocrText || undefined,
|
||||
tags: parsed.tags,
|
||||
category: parsed.category,
|
||||
importance: parsed.importance,
|
||||
provider: this.runtimeProviderId || '',
|
||||
model: this.runtimeModelId || '',
|
||||
createdAt: Date.now(),
|
||||
updatedAt: Date.now(),
|
||||
sender: request.sender,
|
||||
sentAt: request.sentAt,
|
||||
sessionId: request.sessionId
|
||||
}
|
||||
imageInsightsStore.upsert(insight)
|
||||
return { success: true, insight, fromCache: false }
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : String(error)
|
||||
console.warn('[ImageInsightService] analyze failed:', message)
|
||||
return { success: false, error: message }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 日报入口:从 renderer 传入的图片消息候选中挑 Top N + 命中缓存的 Insight。
|
||||
*
|
||||
* 设计:不自己查 chat-service(参数语义不清),而是由 renderer 从已加载的 messages 中
|
||||
* 提取图片消息 + 计算热度后传入。这样既复用现有数据,又避免 userMd5/sessionId 混淆。
|
||||
*/
|
||||
async listTopHotImages(
|
||||
query: ImageCandidateQuery,
|
||||
inputs: ImageCandidateInput[] = []
|
||||
): Promise<ImageCandidate[]> {
|
||||
const limit = query.limit ?? 3
|
||||
const candidates: ImageCandidate[] = []
|
||||
console.log('[ImageInsightService] listTopHotImages received %d inputs', inputs.length)
|
||||
for (const input of inputs) {
|
||||
const hash = await this.computeImageHash(input.md5, input.datName)
|
||||
if (!hash) {
|
||||
console.log(
|
||||
'[ImageInsightService] skip %s: hash empty (md5=%s datName=%s)',
|
||||
input.messageId,
|
||||
input.md5,
|
||||
input.datName
|
||||
)
|
||||
continue
|
||||
}
|
||||
const heatScore = input.responseCount * 3 + input.interactionCount * 2 + 1
|
||||
const candidate: ImageCandidate = {
|
||||
messageId: input.messageId,
|
||||
imageHash: hash,
|
||||
md5: input.md5,
|
||||
datName: input.datName,
|
||||
sessionId: input.sessionId,
|
||||
sender: input.sender,
|
||||
sentAt: input.sentAt,
|
||||
heatScore
|
||||
}
|
||||
const cached = imageInsightsStore.getByHash(hash)
|
||||
if (cached) candidate.insight = cached
|
||||
candidates.push(candidate)
|
||||
}
|
||||
candidates.sort((a, b) => b.heatScore - a.heatScore)
|
||||
return candidates.slice(0, limit)
|
||||
}
|
||||
|
||||
/**
|
||||
* 列出会话所有 insights(按时间倒序,供未来 UI 复用)
|
||||
*/
|
||||
listBySession(sessionId: string, limit?: number): ImageInsight[] {
|
||||
return imageInsightsStore.listBySession(sessionId, limit)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
export const imageInsightService = new ImageInsightService()
|
||||
@@ -0,0 +1,207 @@
|
||||
import path from 'path'
|
||||
import type { ImageKeyConfigResult, SaveImageKeyRequest } from '../../shared/image-decryption'
|
||||
import { ImageKeyStore } from '../image-key-store'
|
||||
import * as chat from './chat-service'
|
||||
import { loadSettings, saveSettings, type AppSettings } from './settings-store'
|
||||
|
||||
export class ImageKeyConfigService {
|
||||
constructor(private readonly store = new ImageKeyStore()) {}
|
||||
|
||||
getConfig(): ImageKeyConfigResult {
|
||||
const settings = loadSettings()
|
||||
const context = this.getContext(settings)
|
||||
const stored = this.store.get(context.accountId)
|
||||
if (!stored.success) {
|
||||
return {
|
||||
success: false,
|
||||
configured: false,
|
||||
saved: false,
|
||||
encryptionAvailable: stored.encryptionAvailable,
|
||||
source: 'none',
|
||||
accountId: context.accountId,
|
||||
resourceRoot: context.resourceRoot,
|
||||
error: stored.error
|
||||
}
|
||||
}
|
||||
if (stored.entry) {
|
||||
return {
|
||||
success: true,
|
||||
configured: true,
|
||||
saved: true,
|
||||
encryptionAvailable: stored.encryptionAvailable,
|
||||
source: 'secure-storage',
|
||||
accountId: context.accountId,
|
||||
resourceRoot: context.resourceRoot,
|
||||
xorKey: stored.entry.xorKey,
|
||||
aesKey: stored.entry.aesKey,
|
||||
updatedAt: stored.entry.updatedAt
|
||||
}
|
||||
}
|
||||
|
||||
if (settings.imageAesKey.trim()) {
|
||||
const legacy = this.buildResult({
|
||||
source: 'legacy-settings',
|
||||
xorKey: settings.imageXorKey || '0x40',
|
||||
aesKey: settings.imageAesKey,
|
||||
context,
|
||||
encryptionAvailable: stored.encryptionAvailable
|
||||
})
|
||||
if (!stored.encryptionAvailable) return legacy
|
||||
const migrated = this.save({
|
||||
resourceRoot: context.resourceRoot,
|
||||
xorKey: legacy.xorKey || '0x40',
|
||||
aesKey: legacy.aesKey || ''
|
||||
})
|
||||
return migrated.success ? this.getConfig() : legacy
|
||||
}
|
||||
|
||||
const envAesKey = String(import.meta.env.VITE_IMAGE_AES_KEY || '').trim()
|
||||
if (!settings.imageKeyFallbackDisabled && envAesKey) {
|
||||
return this.buildResult({
|
||||
source: 'environment',
|
||||
xorKey: String(import.meta.env.VITE_IMAGE_XOR_KEY || '0x40'),
|
||||
aesKey: envAesKey,
|
||||
context,
|
||||
encryptionAvailable: stored.encryptionAvailable
|
||||
})
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
configured: false,
|
||||
saved: false,
|
||||
encryptionAvailable: stored.encryptionAvailable,
|
||||
source: 'none',
|
||||
accountId: context.accountId,
|
||||
resourceRoot: context.resourceRoot
|
||||
}
|
||||
}
|
||||
|
||||
save(request: SaveImageKeyRequest): ImageKeyConfigResult {
|
||||
const normalized = validateImageKeyRequest(request)
|
||||
if (!normalized.success) return { ...this.getEmptyConfig(), error: normalized.error }
|
||||
const settings = loadSettings()
|
||||
const context = this.getContext(settings)
|
||||
if (!chat.getSelfAccountInfo()?.wxid) {
|
||||
return { ...this.getEmptyConfig(), error: '当前微信账号尚未识别' }
|
||||
}
|
||||
const result = this.store.save(context.accountId, {
|
||||
xorKey: normalized.xorKey,
|
||||
aesKey: normalized.aesKey
|
||||
})
|
||||
if (!result.success || !result.entry) {
|
||||
return { ...this.getEmptyConfig(), error: result.error || '图片密钥保存失败' }
|
||||
}
|
||||
saveSettings({
|
||||
...settings,
|
||||
imageKeyRoot: normalized.resourceRoot,
|
||||
imageXorKey: '',
|
||||
imageAesKey: '',
|
||||
imageKeyFallbackDisabled: false
|
||||
})
|
||||
return {
|
||||
success: true,
|
||||
configured: true,
|
||||
saved: true,
|
||||
encryptionAvailable: true,
|
||||
source: 'secure-storage',
|
||||
accountId: context.accountId,
|
||||
resourceRoot: normalized.resourceRoot,
|
||||
xorKey: result.entry.xorKey,
|
||||
aesKey: result.entry.aesKey,
|
||||
updatedAt: result.entry.updatedAt
|
||||
}
|
||||
}
|
||||
|
||||
clear(): { success: boolean; error?: string } {
|
||||
const settings = loadSettings()
|
||||
const context = this.getContext(settings)
|
||||
const cleared = this.store.clear(context.accountId)
|
||||
if (!cleared.success) return cleared
|
||||
saveSettings({
|
||||
...settings,
|
||||
imageXorKey: '',
|
||||
imageAesKey: '',
|
||||
imageKeyFallbackDisabled: true
|
||||
})
|
||||
return { success: true }
|
||||
}
|
||||
|
||||
getLegacySettingsView(): AppSettings {
|
||||
const settings = loadSettings()
|
||||
const config = this.getConfig()
|
||||
return {
|
||||
...settings,
|
||||
imageXorKey: config.xorKey || '',
|
||||
imageAesKey: config.aesKey || ''
|
||||
}
|
||||
}
|
||||
|
||||
private getContext(settings: AppSettings): { accountId: string; resourceRoot: string } {
|
||||
const self = chat.getSelfAccountInfo()
|
||||
const accountRoot = self?.accountRoot || chat.getCurrentAccountRoot() || settings.dbRoot
|
||||
return {
|
||||
accountId: self?.wxid || path.basename(accountRoot || '') || 'unbound',
|
||||
resourceRoot: settings.imageKeyRoot || accountRoot || settings.dbRoot
|
||||
}
|
||||
}
|
||||
|
||||
private buildResult(input: {
|
||||
source: 'legacy-settings' | 'environment'
|
||||
xorKey: string
|
||||
aesKey: string
|
||||
context: { accountId: string; resourceRoot: string }
|
||||
encryptionAvailable: boolean
|
||||
}): ImageKeyConfigResult {
|
||||
return {
|
||||
success: true,
|
||||
configured: true,
|
||||
saved: false,
|
||||
encryptionAvailable: input.encryptionAvailable,
|
||||
source: input.source,
|
||||
accountId: input.context.accountId,
|
||||
resourceRoot: input.context.resourceRoot,
|
||||
xorKey: normalizeImageXorKey(input.xorKey),
|
||||
aesKey: input.aesKey.trim()
|
||||
}
|
||||
}
|
||||
|
||||
private getEmptyConfig(): ImageKeyConfigResult {
|
||||
const settings = loadSettings()
|
||||
const context = this.getContext(settings)
|
||||
const stored = this.store.get(context.accountId)
|
||||
return {
|
||||
success: false,
|
||||
configured: false,
|
||||
saved: false,
|
||||
encryptionAvailable: stored.encryptionAvailable,
|
||||
source: 'none',
|
||||
accountId: context.accountId,
|
||||
resourceRoot: context.resourceRoot
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function normalizeImageXorKey(value: unknown): string {
|
||||
const raw = String(value ?? '').trim()
|
||||
if (!raw) return '0x40'
|
||||
const parsed = raw.toLowerCase().startsWith('0x')
|
||||
? Number.parseInt(raw.slice(2), 16)
|
||||
: Number.parseInt(raw, 10)
|
||||
if (!Number.isFinite(parsed) || parsed < 0 || parsed > 255) return raw
|
||||
return `0x${parsed.toString(16).toUpperCase().padStart(2, '0')}`
|
||||
}
|
||||
|
||||
export function validateImageKeyRequest(
|
||||
request: SaveImageKeyRequest
|
||||
):
|
||||
| { success: true; resourceRoot: string; xorKey: string; aesKey: string }
|
||||
| { success: false; error: string } {
|
||||
const resourceRoot = request.resourceRoot.trim()
|
||||
const xorKey = normalizeImageXorKey(request.xorKey)
|
||||
const aesKey = request.aesKey.trim()
|
||||
if (!resourceRoot) return { success: false, error: '图片资源目录不能为空' }
|
||||
if (!/^0x[0-9A-F]{2}$/.test(xorKey)) return { success: false, error: 'XOR Key 格式不正确' }
|
||||
if (aesKey.length !== 16) return { success: false, error: 'AES Key 必须为 16 个字符' }
|
||||
return { success: true, resourceRoot, xorKey, aesKey }
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
import http from 'http'
|
||||
import { apiServer } from '../http-server'
|
||||
import {
|
||||
LOCAL_API_ENDPOINTS,
|
||||
type LocalApiEndpointId,
|
||||
type LocalApiTestRequest,
|
||||
type LocalApiTestResponse
|
||||
} from '../../shared/local-api-test'
|
||||
|
||||
const REQUEST_TIMEOUT_MS = 10_000
|
||||
const MAX_BODY_SIZE = 512 * 1024
|
||||
|
||||
function isEndpointId(value: unknown): value is LocalApiEndpointId {
|
||||
return typeof value === 'string' && value in LOCAL_API_ENDPOINTS
|
||||
}
|
||||
|
||||
function requestHost(host: string): string {
|
||||
if (host === '0.0.0.0') return '127.0.0.1'
|
||||
if (host === '::') return '::1'
|
||||
return host
|
||||
}
|
||||
|
||||
function invalidResponse(message: string): LocalApiTestResponse {
|
||||
return {
|
||||
ok: false,
|
||||
method: 'GET',
|
||||
path: '',
|
||||
url: '',
|
||||
durationMs: 0,
|
||||
responseSize: 0,
|
||||
errorCode: 'INVALID_REQUEST',
|
||||
error: message
|
||||
}
|
||||
}
|
||||
|
||||
function parseBody(bodyText: string, contentType?: string): { json?: unknown; bodyText?: string } {
|
||||
if (contentType?.includes('application/json')) {
|
||||
try {
|
||||
return { json: JSON.parse(bodyText) }
|
||||
} catch {
|
||||
// Keep malformed responses readable to the tester.
|
||||
}
|
||||
}
|
||||
return { bodyText }
|
||||
}
|
||||
|
||||
export async function testLocalApiRequest(payload: unknown): Promise<LocalApiTestResponse> {
|
||||
if (!payload || typeof payload !== 'object') return invalidResponse('请求格式无效')
|
||||
const { endpointId, query = {}, body = '' } = payload as Partial<LocalApiTestRequest>
|
||||
if (!isEndpointId(endpointId)) return invalidResponse('不允许访问该 API 端点')
|
||||
if (!query || typeof query !== 'object' || Array.isArray(query))
|
||||
return invalidResponse('查询参数格式无效')
|
||||
if (typeof body !== 'string' || Buffer.byteLength(body) > MAX_BODY_SIZE)
|
||||
return invalidResponse('请求体格式无效')
|
||||
|
||||
const endpoint = LOCAL_API_ENDPOINTS[endpointId]
|
||||
const entries = Object.entries(query)
|
||||
if (
|
||||
entries.some(
|
||||
([key, value]) => !endpoint.queryKeys.includes(key as never) || typeof value !== 'string'
|
||||
)
|
||||
) {
|
||||
return invalidResponse('查询参数不属于当前端点')
|
||||
}
|
||||
|
||||
const service = apiServer.getState()
|
||||
const targetHost = requestHost(service.host)
|
||||
const targetPort = service.port
|
||||
const hostPart = targetHost.includes(':') ? `[${targetHost}]` : targetHost
|
||||
const url = new URL(endpoint.path, `http://${hostPart}:${targetPort}`)
|
||||
entries.forEach(([key, value]) => {
|
||||
if (value.trim()) url.searchParams.set(key, value.trim())
|
||||
})
|
||||
|
||||
if (!service.running) {
|
||||
return {
|
||||
ok: false,
|
||||
method: endpoint.method,
|
||||
path: endpoint.path,
|
||||
url: url.toString(),
|
||||
durationMs: 0,
|
||||
responseSize: 0,
|
||||
errorCode: 'API_NOT_RUNNING',
|
||||
error: '请先启动本地 API 服务'
|
||||
}
|
||||
}
|
||||
|
||||
return new Promise((resolve) => {
|
||||
const startedAt = Date.now()
|
||||
let settled = false
|
||||
const finish = (result: LocalApiTestResponse): void => {
|
||||
if (settled) return
|
||||
settled = true
|
||||
resolve(result)
|
||||
}
|
||||
const request = http.request(
|
||||
url,
|
||||
{
|
||||
method: endpoint.method,
|
||||
headers: endpoint.method === 'POST' ? { 'Content-Type': 'application/json' } : undefined
|
||||
},
|
||||
(response) => {
|
||||
const chunks: Buffer[] = []
|
||||
response.on('data', (chunk: Buffer) => chunks.push(chunk))
|
||||
response.on('end', () => {
|
||||
const bodyText = Buffer.concat(chunks).toString('utf-8')
|
||||
const contentType = Array.isArray(response.headers['content-type'])
|
||||
? response.headers['content-type'][0]
|
||||
: response.headers['content-type']
|
||||
finish({
|
||||
ok: true,
|
||||
method: endpoint.method,
|
||||
path: endpoint.path,
|
||||
url: url.toString(),
|
||||
status: response.statusCode || 0,
|
||||
statusText: response.statusMessage || '',
|
||||
durationMs: Date.now() - startedAt,
|
||||
responseSize: Buffer.byteLength(bodyText),
|
||||
contentType,
|
||||
...parseBody(bodyText, contentType)
|
||||
})
|
||||
})
|
||||
}
|
||||
)
|
||||
request.setTimeout(REQUEST_TIMEOUT_MS, () => {
|
||||
request.destroy(new Error('请求超时'))
|
||||
finish({
|
||||
ok: false,
|
||||
method: endpoint.method,
|
||||
path: endpoint.path,
|
||||
url: url.toString(),
|
||||
durationMs: Date.now() - startedAt,
|
||||
responseSize: 0,
|
||||
errorCode: 'TIMEOUT',
|
||||
error: '请求超时(10 秒)'
|
||||
})
|
||||
})
|
||||
request.on('error', (error: NodeJS.ErrnoException) => {
|
||||
finish({
|
||||
ok: false,
|
||||
method: endpoint.method,
|
||||
path: endpoint.path,
|
||||
url: url.toString(),
|
||||
durationMs: Date.now() - startedAt,
|
||||
responseSize: 0,
|
||||
errorCode: error.code === 'ECONNREFUSED' ? 'CONNECTION_REFUSED' : 'UNKNOWN',
|
||||
error: error.message
|
||||
})
|
||||
})
|
||||
if (endpoint.method === 'POST') request.write(body)
|
||||
request.end()
|
||||
})
|
||||
}
|
||||
@@ -8,16 +8,117 @@ export interface AppSettings {
|
||||
apiEnabled: boolean
|
||||
apiHost: string
|
||||
apiPort: number
|
||||
imageKeyRoot: string
|
||||
imageXorKey: string
|
||||
imageAesKey: string
|
||||
imageKeyFallbackDisabled: boolean
|
||||
}
|
||||
|
||||
function getDefaultDbRoot(): string {
|
||||
const home = os.homedir()
|
||||
const candidates = getDefaultDbRootCandidates(home)
|
||||
return candidates.find((candidate) => isUsableDbRoot(candidate)) || candidates[0]
|
||||
}
|
||||
|
||||
function getDefaultDbRootCandidates(home: string): string[] {
|
||||
if (process.platform !== 'win32') {
|
||||
return [
|
||||
path.join(home, 'Library/Containers/com.tencent.xinWeChat/Data/Documents/xwechat_files')
|
||||
]
|
||||
}
|
||||
|
||||
const candidates = [
|
||||
...getWeflowDbPathCandidates(home),
|
||||
path.join(home, 'Documents', 'WeChat Files'),
|
||||
path.join(home, 'Documents', 'xwechat_files'),
|
||||
path.join(home, 'WeChat Files'),
|
||||
path.join(os.homedir(), 'AppData', 'Roaming', 'Tencent', 'xwechat_files')
|
||||
]
|
||||
|
||||
for (const drive of getWindowsDrives()) {
|
||||
candidates.push(path.join(`${drive}:\\`, 'xwechat_files'))
|
||||
candidates.push(path.join(`${drive}:\\`, 'WeChat Files'))
|
||||
for (const child of listDirectories(`${drive}:\\`)) {
|
||||
candidates.push(path.join(child, 'xwechat_files'))
|
||||
candidates.push(path.join(child, 'WeChat Files'))
|
||||
}
|
||||
}
|
||||
|
||||
return unique(candidates)
|
||||
}
|
||||
|
||||
function getWeflowDbPathCandidates(home: string): string[] {
|
||||
const configPaths = [
|
||||
path.join(home, 'AppData', 'Roaming', 'weflow', 'WeFlow-config.json'),
|
||||
path.join(home, 'AppData', 'Roaming', 'WeFlow', 'WeFlow-config.json')
|
||||
]
|
||||
const candidates: string[] = []
|
||||
for (const configPath of configPaths) {
|
||||
try {
|
||||
const config = fs.readJsonSync(configPath) as { dbPath?: unknown }
|
||||
if (typeof config.dbPath === 'string' && config.dbPath.trim()) {
|
||||
candidates.push(config.dbPath.trim())
|
||||
}
|
||||
} catch {
|
||||
// WeFlow is optional; ignore missing or unreadable config.
|
||||
}
|
||||
}
|
||||
return candidates
|
||||
}
|
||||
|
||||
function getWindowsDrives(): string[] {
|
||||
const drives: string[] = []
|
||||
for (let code = 67; code <= 90; code += 1) {
|
||||
const drive = String.fromCharCode(code)
|
||||
if (fs.existsSync(`${drive}:\\`)) drives.push(drive)
|
||||
}
|
||||
return drives
|
||||
}
|
||||
|
||||
function listDirectories(root: string): string[] {
|
||||
try {
|
||||
return fs
|
||||
.readdirSync(root)
|
||||
.map((name) => path.join(root, name))
|
||||
.filter((candidate) => {
|
||||
try {
|
||||
return fs.statSync(candidate).isDirectory()
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
})
|
||||
} catch {
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
function unique(values: string[]): string[] {
|
||||
return Array.from(new Set(values))
|
||||
}
|
||||
|
||||
function isUsableDbRoot(candidate?: string): boolean {
|
||||
if (!candidate || !fs.existsSync(candidate)) return false
|
||||
if (fs.existsSync(path.join(candidate, 'db_storage'))) return true
|
||||
try {
|
||||
return fs
|
||||
.readdirSync(candidate)
|
||||
.some((name) => fs.existsSync(path.join(candidate, name, 'db_storage')))
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
const defaultDbRoot = getDefaultDbRoot()
|
||||
|
||||
const DEFAULT_SETTINGS: AppSettings = {
|
||||
dbRoot: path.join(
|
||||
os.homedir(),
|
||||
'Library/Containers/com.tencent.xinWeChat/Data/Documents/xwechat_files'
|
||||
),
|
||||
dbRoot: defaultDbRoot,
|
||||
apiEnabled: true,
|
||||
apiHost: '127.0.0.1',
|
||||
apiPort: 6131
|
||||
apiPort: 6131,
|
||||
imageKeyRoot: defaultDbRoot,
|
||||
imageXorKey: '',
|
||||
imageAesKey: '',
|
||||
imageKeyFallbackDisabled: false
|
||||
}
|
||||
|
||||
const SETTINGS_FILE = path.join(
|
||||
@@ -37,6 +138,12 @@ export function loadSettings(): AppSettings {
|
||||
if (fs.existsSync(SETTINGS_FILE)) {
|
||||
const raw = fs.readJsonSync(SETTINGS_FILE) as Partial<AppSettings>
|
||||
cache = { ...DEFAULT_SETTINGS, ...raw }
|
||||
if (process.platform === 'win32' && !isUsableDbRoot(cache.dbRoot)) {
|
||||
cache.dbRoot = getDefaultDbRoot()
|
||||
}
|
||||
if (!cache.imageKeyRoot) {
|
||||
cache.imageKeyRoot = cache.dbRoot
|
||||
}
|
||||
return cache
|
||||
}
|
||||
} catch (error) {
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
import { app, shell } from 'electron'
|
||||
import { existsSync, promises as fs } from 'fs'
|
||||
import { dirname, join } from 'path'
|
||||
|
||||
const SKILL_RELATIVE_PATH = join('skill', 'wechatexplorer-reader', 'SKILL.md')
|
||||
const GITHUB_URL =
|
||||
'https://github.com/Wxw-Gu/WechatExplorer/tree/main/docs/skill/wechatexplorer-reader'
|
||||
|
||||
export interface SkillResourceStatus {
|
||||
available: boolean
|
||||
version?: string
|
||||
filePath?: string
|
||||
directoryPath?: string
|
||||
source: 'development' | 'bundled'
|
||||
githubUrl: string
|
||||
error?: string
|
||||
}
|
||||
|
||||
function getSkillCandidates(): { path: string; source: 'development' | 'bundled' }[] {
|
||||
const developmentPath = join(app.getAppPath(), 'docs', SKILL_RELATIVE_PATH)
|
||||
const bundledPaths = [
|
||||
join(process.resourcesPath, SKILL_RELATIVE_PATH),
|
||||
join(dirname(app.getAppPath()), SKILL_RELATIVE_PATH),
|
||||
join(dirname(process.execPath), 'resources', SKILL_RELATIVE_PATH)
|
||||
]
|
||||
return app.isPackaged
|
||||
? bundledPaths.map((path) => ({ path, source: 'bundled' as const }))
|
||||
: [
|
||||
{ path: developmentPath, source: 'development' as const },
|
||||
...bundledPaths.map((path) => ({ path, source: 'bundled' as const }))
|
||||
]
|
||||
}
|
||||
|
||||
function getStatus(): SkillResourceStatus {
|
||||
const candidates = getSkillCandidates()
|
||||
const resolved = candidates.find((candidate) => existsSync(candidate.path))
|
||||
const filePath = resolved?.path || candidates[0].path
|
||||
const source = resolved?.source || candidates[0].source
|
||||
const directoryPath = dirname(filePath)
|
||||
if (!resolved) {
|
||||
return {
|
||||
available: false,
|
||||
source,
|
||||
githubUrl: GITHUB_URL,
|
||||
error: `未找到 WechatExplorer Reader Skill 文件(已检查:${candidates.map((item) => item.path).join(';')})`
|
||||
}
|
||||
}
|
||||
return {
|
||||
available: true,
|
||||
version: 'v1.0',
|
||||
filePath,
|
||||
directoryPath,
|
||||
source,
|
||||
githubUrl: GITHUB_URL
|
||||
}
|
||||
}
|
||||
|
||||
export const skillResourceService = {
|
||||
getStatus,
|
||||
|
||||
async read(): Promise<{ success: boolean; content?: string; error?: string }> {
|
||||
const status = this.getStatus()
|
||||
if (!status.available || !status.filePath) return { success: false, error: status.error }
|
||||
try {
|
||||
return { success: true, content: await fs.readFile(status.filePath, 'utf-8') }
|
||||
} catch (error) {
|
||||
return { success: false, error: error instanceof Error ? error.message : String(error) }
|
||||
}
|
||||
},
|
||||
|
||||
async reveal(): Promise<{ success: boolean; error?: string }> {
|
||||
const status = this.getStatus()
|
||||
if (!status.available || !status.directoryPath) return { success: false, error: status.error }
|
||||
try {
|
||||
const error = await shell.openPath(status.directoryPath)
|
||||
if (error) return { success: false, error }
|
||||
return { success: true }
|
||||
} catch (error) {
|
||||
return { success: false, error: error instanceof Error ? error.message : String(error) }
|
||||
}
|
||||
},
|
||||
|
||||
async openGithub(): Promise<{ success: boolean; error?: string }> {
|
||||
try {
|
||||
await shell.openExternal(GITHUB_URL)
|
||||
return { success: true }
|
||||
} catch (error) {
|
||||
return { success: false, error: error instanceof Error ? error.message : String(error) }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import { execFile } from 'child_process'
|
||||
import { promisify } from 'util'
|
||||
|
||||
const execFileAsync = promisify(execFile)
|
||||
const WINDOWS_WECHAT_IMAGES = ['Weixin.exe', 'WeChat.exe']
|
||||
|
||||
export async function isWindowsWechatRunning(): Promise<boolean> {
|
||||
if (process.platform !== 'win32') return false
|
||||
|
||||
for (const imageName of WINDOWS_WECHAT_IMAGES) {
|
||||
try {
|
||||
const { stdout } = await execFileAsync(
|
||||
'tasklist',
|
||||
['/FI', `IMAGENAME eq ${imageName}`, '/FO', 'CSV', '/NH'],
|
||||
{ windowsHide: true }
|
||||
)
|
||||
if (stdout.toLowerCase().includes(`"${imageName.toLowerCase()}"`)) return true
|
||||
} catch {
|
||||
// Try the other supported WeChat executable name.
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
export async function isWechatRunning(): Promise<boolean> {
|
||||
if (process.platform === 'win32') return isWindowsWechatRunning()
|
||||
if (process.platform !== 'darwin') return false
|
||||
|
||||
for (const args of [
|
||||
['-x', 'WeChat'],
|
||||
['-f', 'WeChat.app/Contents/MacOS/WeChat']
|
||||
]) {
|
||||
try {
|
||||
const { stdout } = await execFileAsync('/usr/bin/pgrep', args)
|
||||
if (stdout.trim()) return true
|
||||
} catch {
|
||||
// Try the next macOS process lookup strategy.
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import os from 'os'
|
||||
import crypto from 'crypto'
|
||||
import { createRequire } from 'module'
|
||||
import { createConnection, Socket } from 'net'
|
||||
import { getResourceRoots } from './resource-paths'
|
||||
|
||||
export interface Wcdb4Session {
|
||||
username: string
|
||||
@@ -24,9 +25,16 @@ export interface Wcdb4Message {
|
||||
raw: Record<string, unknown>
|
||||
}
|
||||
|
||||
export interface Wcdb4MessageQueryOptions {
|
||||
limit?: number
|
||||
}
|
||||
|
||||
export interface Wcdb4GroupMember {
|
||||
m_nsUsrName: string
|
||||
nickname: string
|
||||
groupNickname: string
|
||||
wechatNickname: string
|
||||
remark: string
|
||||
m_nsHeadImgUrl: string
|
||||
}
|
||||
|
||||
@@ -41,6 +49,85 @@ type KoffiModule = {
|
||||
decode: (ptr: unknown, type: string, length: number) => string
|
||||
}
|
||||
|
||||
// Module-level singleton for WCDB native handle. WCDB's Windows runtime
|
||||
// returns -1006 if wcdb_init is called more than once per process, so we
|
||||
// perform InitProtection + wcdb_init exactly once and cache the resulting
|
||||
// library reference for every Wcdb4Client instance.
|
||||
let wcdbBootstrapLib: KoffiLibrary | null = null
|
||||
|
||||
export function bootstrapWcdbNative(libPath?: string, libDirOverride?: string): KoffiLibrary {
|
||||
if (wcdbBootstrapLib) return wcdbBootstrapLib
|
||||
|
||||
const koffi = nodeRequire('koffi') as KoffiModule
|
||||
const resolvedLibPath = libPath || Wcdb4Client.resolveNativeLibrary()
|
||||
const libDir = libDirOverride || path.dirname(resolvedLibPath)
|
||||
console.log(
|
||||
`[WCDB4] bootstrap koffi.load begin ${resolvedLibPath} cwd=${process.cwd()} resourcesPath=${process.resourcesPath || ''}`
|
||||
)
|
||||
for (const name of process.platform === 'win32'
|
||||
? ['WCDB.dll', 'SDL2.dll']
|
||||
: process.platform === 'darwin'
|
||||
? ['libWCDB.dylib']
|
||||
: []) {
|
||||
const preloadPath = path.join(libDir, name)
|
||||
if (!fs.existsSync(preloadPath)) continue
|
||||
try {
|
||||
koffi.load(preloadPath)
|
||||
console.log(`[WCDB4] bootstrap preload ok ${preloadPath}`)
|
||||
} catch {
|
||||
console.warn(`[WCDB4] bootstrap preload failed ${preloadPath}`)
|
||||
}
|
||||
}
|
||||
const lib = koffi.load(resolvedLibPath)
|
||||
console.log(`[WCDB4] bootstrap koffi.load ok ${resolvedLibPath}`)
|
||||
|
||||
const initProtection = lib.func('int32 InitProtection(const char* resourcePath)') as (
|
||||
resourcePath: string
|
||||
) => number
|
||||
const resourceRoots = Array.from(
|
||||
new Set(
|
||||
[
|
||||
libDir,
|
||||
path.dirname(libDir),
|
||||
process.env.WCDB_RESOURCES_PATH || '',
|
||||
...getResourceRoots()
|
||||
].filter(Boolean)
|
||||
)
|
||||
)
|
||||
let lastCode = -1
|
||||
let initOk = false
|
||||
for (const resourceRoot of resourceRoots) {
|
||||
try {
|
||||
console.log(`[WCDB4] bootstrap InitProtection call ${resourceRoot}`)
|
||||
lastCode = Number(initProtection(resourceRoot))
|
||||
console.log(`[WCDB4] bootstrap InitProtection rc=${lastCode} path=${resourceRoot}`)
|
||||
if (lastCode === 0) {
|
||||
initOk = true
|
||||
console.log(`[WCDB4] bootstrap InitProtection ok path=${resourceRoot}`)
|
||||
break
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn(`[WCDB4] bootstrap InitProtection exception path=${resourceRoot}`, error)
|
||||
}
|
||||
}
|
||||
if (!initOk) {
|
||||
console.warn(
|
||||
`[WCDB4] bootstrap InitProtection 返回 ${lastCode},继续尝试 wcdb_init/open; tried=${resourceRoots.join(' | ')}`
|
||||
)
|
||||
} else {
|
||||
const wcdbInit = lib.func('int32 wcdb_init()') as () => number
|
||||
console.log('[WCDB4] bootstrap wcdb_init begin')
|
||||
const initRc = Number(wcdbInit())
|
||||
console.log(`[WCDB4] bootstrap wcdb_init rc=${initRc}`)
|
||||
if (initRc !== 0) {
|
||||
console.warn(`[WCDB4] bootstrap wcdb_init 返回 ${initRc},继续尝试 wcdb_open_account`)
|
||||
}
|
||||
}
|
||||
|
||||
wcdbBootstrapLib = lib
|
||||
return lib
|
||||
}
|
||||
|
||||
type KoffiLibrary = {
|
||||
func: (signature: string) => (...args: unknown[]) => unknown
|
||||
}
|
||||
@@ -51,10 +138,7 @@ type WcdbHandleOut = [number]
|
||||
const nodeRequire = createRequire(import.meta.url)
|
||||
|
||||
export class Wcdb4Client {
|
||||
static readonly defaultRoot = path.join(
|
||||
os.homedir(),
|
||||
'Library/Containers/com.tencent.xinWeChat/Data/Documents/xwechat_files'
|
||||
)
|
||||
static readonly defaultRoot = Wcdb4Client.findExistingDefaultRoot()
|
||||
|
||||
private readonly key: string
|
||||
private readonly accountRoot: string
|
||||
@@ -63,13 +147,12 @@ export class Wcdb4Client {
|
||||
private readonly sessionDbPath: string
|
||||
private koffi: KoffiModule | null = null
|
||||
private handle: number | null = null
|
||||
private initialized = false
|
||||
private displayNameCache = new Map<string, string>()
|
||||
private avatarCache = new Map<string, string>()
|
||||
private groupNicknameCache = new Map<string, Map<string, string>>()
|
||||
private cachedSessions: Wcdb4Session[] | null = null
|
||||
private cachedChatTables: { name: string; db_number: string }[] | null = null
|
||||
|
||||
private wcdbInit: (() => number) | null = null
|
||||
private wcdbShutdown: (() => number) | null = null
|
||||
private wcdbOpenAccount:
|
||||
| ((sessionDbPath: string, key: string, handleOut: WcdbHandleOut) => number)
|
||||
@@ -86,6 +169,9 @@ export class Wcdb4Client {
|
||||
outJson: WcdbVoidOut
|
||||
) => number)
|
||||
| null = null
|
||||
private wcdbGetMessageTableStats:
|
||||
| ((handle: number, username: string, outJson: WcdbVoidOut) => number)
|
||||
| null = null
|
||||
private wcdbGetDisplayNames:
|
||||
| ((handle: number, usernamesJson: string, outJson: WcdbVoidOut) => number)
|
||||
| null = null
|
||||
@@ -158,11 +244,11 @@ export class Wcdb4Client {
|
||||
}
|
||||
|
||||
static resolveAccountRoot(accountRoot: string): string {
|
||||
const target = (accountRoot || '').trim().replace(/\/+$/, '')
|
||||
const target = (accountRoot || '').trim().replace(/[\\/]+$/, '')
|
||||
if (!target) {
|
||||
throw new Error('微信 4.0 账号目录不能为空')
|
||||
}
|
||||
if (fs.existsSync(path.join(target, 'db_storage'))) {
|
||||
if (Wcdb4Client.hasDbStorage(target)) {
|
||||
return target
|
||||
}
|
||||
if (!fs.existsSync(target)) {
|
||||
@@ -171,17 +257,8 @@ export class Wcdb4Client {
|
||||
const candidates = fs
|
||||
.readdirSync(target)
|
||||
.map((name) => path.join(target, name))
|
||||
.filter((candidate) => {
|
||||
try {
|
||||
return (
|
||||
fs.statSync(candidate).isDirectory() &&
|
||||
fs.existsSync(path.join(candidate, 'db_storage'))
|
||||
)
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
})
|
||||
.sort((a, b) => fs.statSync(b).mtimeMs - fs.statSync(a).mtimeMs)
|
||||
.filter((candidate) => Wcdb4Client.hasDbStorage(candidate))
|
||||
.sort(Wcdb4Client.compareAccountDirs)
|
||||
if (!candidates[0]) {
|
||||
throw new Error(`未找到包含 db_storage 的微信 4.0 账号目录: ${target}`)
|
||||
}
|
||||
@@ -194,24 +271,15 @@ export class Wcdb4Client {
|
||||
throw new Error(`未找到微信 4.0 数据目录: ${root}`)
|
||||
}
|
||||
|
||||
if (fs.existsSync(path.join(root, 'db_storage'))) {
|
||||
if (Wcdb4Client.hasDbStorage(root)) {
|
||||
return root
|
||||
}
|
||||
|
||||
const candidates = fs
|
||||
.readdirSync(root)
|
||||
.map((name) => path.join(root, name))
|
||||
.filter((candidate) => {
|
||||
try {
|
||||
return (
|
||||
fs.statSync(candidate).isDirectory() &&
|
||||
fs.existsSync(path.join(candidate, 'db_storage'))
|
||||
)
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
})
|
||||
.sort((a, b) => fs.statSync(b).mtimeMs - fs.statSync(a).mtimeMs)
|
||||
.filter((candidate) => Wcdb4Client.hasDbStorage(candidate))
|
||||
.sort(Wcdb4Client.compareAccountDirs)
|
||||
|
||||
if (!candidates[0]) {
|
||||
throw new Error(`未找到包含 db_storage 的微信 4.0 账号目录: ${root}`)
|
||||
@@ -220,6 +288,117 @@ export class Wcdb4Client {
|
||||
return candidates[0]
|
||||
}
|
||||
|
||||
private static findExistingDefaultRoot(): string {
|
||||
const roots = Wcdb4Client.getDefaultRootCandidates()
|
||||
return roots.find((root) => Wcdb4Client.isUsableRoot(root)) || roots[0]
|
||||
}
|
||||
|
||||
private static getDefaultRootCandidates(): string[] {
|
||||
const home = os.homedir()
|
||||
if (process.platform === 'win32') {
|
||||
const candidates = [
|
||||
...Wcdb4Client.getWeflowDbPathCandidates(home),
|
||||
path.join(home, 'Documents', 'WeChat Files'),
|
||||
path.join(home, 'Documents', 'xwechat_files'),
|
||||
path.join(home, 'WeChat Files'),
|
||||
path.join(home, 'AppData', 'Roaming', 'Tencent', 'xwechat_files')
|
||||
]
|
||||
for (const drive of Wcdb4Client.getWindowsDrives()) {
|
||||
candidates.push(path.join(`${drive}:\\`, 'xwechat_files'))
|
||||
candidates.push(path.join(`${drive}:\\`, 'WeChat Files'))
|
||||
for (const child of Wcdb4Client.listDirectories(`${drive}:\\`)) {
|
||||
candidates.push(path.join(child, 'xwechat_files'))
|
||||
candidates.push(path.join(child, 'WeChat Files'))
|
||||
}
|
||||
}
|
||||
return Array.from(new Set(candidates))
|
||||
}
|
||||
return [path.join(home, 'Library/Containers/com.tencent.xinWeChat/Data/Documents/xwechat_files')]
|
||||
}
|
||||
|
||||
private static getWeflowDbPathCandidates(home: string): string[] {
|
||||
const configPaths = [
|
||||
path.join(home, 'AppData', 'Roaming', 'weflow', 'WeFlow-config.json'),
|
||||
path.join(home, 'AppData', 'Roaming', 'WeFlow', 'WeFlow-config.json')
|
||||
]
|
||||
const candidates: string[] = []
|
||||
for (const configPath of configPaths) {
|
||||
try {
|
||||
const config = fs.readJsonSync(configPath) as { dbPath?: unknown }
|
||||
if (typeof config.dbPath === 'string' && config.dbPath.trim()) {
|
||||
candidates.push(config.dbPath.trim())
|
||||
}
|
||||
} catch {
|
||||
// WeFlow is optional; ignore missing or unreadable config.
|
||||
}
|
||||
}
|
||||
return candidates
|
||||
}
|
||||
|
||||
private static getWindowsDrives(): string[] {
|
||||
const drives: string[] = []
|
||||
for (let code = 67; code <= 90; code += 1) {
|
||||
const drive = String.fromCharCode(code)
|
||||
if (fs.existsSync(`${drive}:\\`)) drives.push(drive)
|
||||
}
|
||||
return drives
|
||||
}
|
||||
|
||||
private static listDirectories(root: string): string[] {
|
||||
try {
|
||||
return fs
|
||||
.readdirSync(root)
|
||||
.map((name) => path.join(root, name))
|
||||
.filter((candidate) => {
|
||||
try {
|
||||
return fs.statSync(candidate).isDirectory()
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
})
|
||||
} catch {
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
private static hasDbStorage(candidate: string): boolean {
|
||||
try {
|
||||
return fs.statSync(candidate).isDirectory() && fs.existsSync(path.join(candidate, 'db_storage'))
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
private static isUsableRoot(candidate: string): boolean {
|
||||
if (!fs.existsSync(candidate)) return false
|
||||
if (Wcdb4Client.hasDbStorage(candidate)) return true
|
||||
try {
|
||||
return fs
|
||||
.readdirSync(candidate)
|
||||
.some((name) => Wcdb4Client.hasDbStorage(path.join(candidate, name)))
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
private static hasSessionDb(candidate: string): boolean {
|
||||
return (
|
||||
fs.existsSync(path.join(candidate, 'db_storage', 'session', 'session.db')) ||
|
||||
fs.existsSync(path.join(candidate, 'db_storage', 'session.db'))
|
||||
)
|
||||
}
|
||||
|
||||
private static compareAccountDirs(a: string, b: string): number {
|
||||
const aHasSession = Wcdb4Client.hasSessionDb(a)
|
||||
const bHasSession = Wcdb4Client.hasSessionDb(b)
|
||||
if (aHasSession !== bHasSession) return aHasSession ? -1 : 1
|
||||
try {
|
||||
return fs.statSync(b).mtimeMs - fs.statSync(a).mtimeMs
|
||||
} catch {
|
||||
return 0
|
||||
}
|
||||
}
|
||||
|
||||
private static cleanAccountDirName(dirName: string): string {
|
||||
const trimmed = dirName.trim()
|
||||
if (!trimmed) return trimmed
|
||||
@@ -236,24 +415,21 @@ export class Wcdb4Client {
|
||||
|
||||
open(): void {
|
||||
this.loadNativeLibrary()
|
||||
if (!this.wcdbInit || !this.wcdbOpenAccount) {
|
||||
if (!this.wcdbOpenAccount) {
|
||||
throw new Error('WCDB 4.0 native 接口未就绪')
|
||||
}
|
||||
|
||||
if (!this.initialized) {
|
||||
const initResult = this.wcdbInit()
|
||||
if (initResult !== 0) {
|
||||
console.warn(`wcdb_init 返回 ${initResult},继续尝试 wcdb_open_account`)
|
||||
} else {
|
||||
this.initialized = true
|
||||
}
|
||||
}
|
||||
|
||||
let openResult = -1
|
||||
const handleOut: WcdbHandleOut = [0]
|
||||
const openResult = this.wcdbOpenAccount(this.sessionDbPath, this.key, handleOut)
|
||||
openResult = this.wcdbOpenAccount(this.sessionDbPath, this.key, handleOut)
|
||||
|
||||
if (openResult !== 0 || handleOut[0] <= 0) {
|
||||
const hint =
|
||||
openResult === -1005
|
||||
? ';这通常表示密钥与当前账号数据库不匹配,请确认微信已登录目标账号,并重新自动获取密钥'
|
||||
: ''
|
||||
throw new Error(
|
||||
`wcdb_open_account 失败,错误码: ${openResult}; sessionDb=${this.sessionDbPath}; accountRoot=${this.accountRoot}; wxid=${this.wxid}`
|
||||
`wcdb_open_account 失败,错误码: ${openResult}${hint}; sessionDb=${this.sessionDbPath}; accountRoot=${this.accountRoot}; wxid=${this.wxid}; keyLength=${this.key.length}`
|
||||
)
|
||||
}
|
||||
|
||||
@@ -269,16 +445,17 @@ export class Wcdb4Client {
|
||||
|
||||
close(): void {
|
||||
this.stopMonitor()
|
||||
if (!this.initialized || !this.wcdbShutdown) return
|
||||
if (this.handle === null || !this.wcdbShutdown) return
|
||||
|
||||
try {
|
||||
this.wcdbShutdown()
|
||||
} catch {
|
||||
// Mirror WechatExplorer: shutdown is best-effort on app close.
|
||||
if (process.platform !== 'win32') {
|
||||
try {
|
||||
this.wcdbShutdown()
|
||||
} catch {
|
||||
// Shutdown is best-effort on app close.
|
||||
}
|
||||
}
|
||||
|
||||
this.handle = null
|
||||
this.initialized = false
|
||||
this.cachedSessions = null
|
||||
this.displayNameCache.clear()
|
||||
this.avatarCache.clear()
|
||||
@@ -425,36 +602,70 @@ export class Wcdb4Client {
|
||||
if (this.cachedSessions) return this.cachedSessions
|
||||
if (!this.wcdbGetSessions) return []
|
||||
|
||||
const rows = this.callJson<Record<string, unknown>[]>((handle, outJson) =>
|
||||
this.wcdbGetSessions!(handle, outJson)
|
||||
)
|
||||
|
||||
const rows = this.readSessionRows()
|
||||
const sessions = (Array.isArray(rows) ? rows : [])
|
||||
.map((row) => this.normalizeSession(row))
|
||||
.filter((session) => session.username)
|
||||
|
||||
const sessionUsernames = sessions.map((session) => session.username)
|
||||
this.hydrateDisplayNames(sessionUsernames)
|
||||
this.hydrateAvatarUrls(sessionUsernames)
|
||||
this.hydrateDisplayNames(
|
||||
sessions
|
||||
.filter((session) => this.shouldHydrateSessionDisplayName(session))
|
||||
.map((session) => session.username)
|
||||
)
|
||||
this.cachedSessions = sessions.map((session) => ({
|
||||
...session,
|
||||
nickname: this.displayNameCache.get(session.username) || session.nickname || session.username,
|
||||
avatar: this.avatarCache.get(session.username)
|
||||
nickname: this.displayNameCache.get(session.username) || session.nickname || session.username
|
||||
}))
|
||||
|
||||
return this.cachedSessions
|
||||
}
|
||||
|
||||
getChatTables(): { name: string; db_number: string }[] {
|
||||
return this.getSessions().map((session) => ({
|
||||
if (this.cachedChatTables) return this.cachedChatTables
|
||||
const sessions =
|
||||
this.cachedSessions ||
|
||||
this.readSessionRows()
|
||||
.map((row) => this.normalizeSession(row))
|
||||
.filter((session) => session.username)
|
||||
this.cachedChatTables = sessions.map((session) => ({
|
||||
name: `Chat_${this.md5(session.username)}`,
|
||||
db_number: session.username
|
||||
}))
|
||||
return this.cachedChatTables
|
||||
}
|
||||
|
||||
getMessages(username: string, startTime?: number, endTime?: number): Wcdb4Message[] {
|
||||
const cursorMessages = this.getMessagesByCursor(username, startTime, endTime)
|
||||
if (cursorMessages) return cursorMessages
|
||||
getMessages(
|
||||
username: string,
|
||||
startTime?: number,
|
||||
endTime?: number,
|
||||
options: Wcdb4MessageQueryOptions = {}
|
||||
): Wcdb4Message[] {
|
||||
const startedAt = Date.now()
|
||||
const maxRows = this.normalizeMessageLimit(options.limit)
|
||||
console.log(
|
||||
`[WCDB4] getMessages begin username=${username} start=${startTime || 0} end=${endTime || 0} limit=${maxRows || 0}`
|
||||
)
|
||||
try {
|
||||
const cursorMessages = this.getMessagesByCursor(username, startTime, endTime, maxRows)
|
||||
if (cursorMessages) {
|
||||
console.log(
|
||||
`[WCDB4] getMessages cursor ok username=${username} rows=${cursorMessages.length} cost=${Date.now() - startedAt}ms`
|
||||
)
|
||||
return cursorMessages
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn(`[WCDB4] cursor messages failed username=${username}:`, error)
|
||||
}
|
||||
|
||||
if (maxRows) {
|
||||
const tableRows = this.getMessagesByTableScan(username, startTime, endTime, maxRows)
|
||||
if (tableRows.length > 0) {
|
||||
console.log(
|
||||
`[WCDB4] getMessages table scan ok username=${username} rows=${tableRows.length} cost=${Date.now() - startedAt}ms`
|
||||
)
|
||||
return tableRows
|
||||
}
|
||||
}
|
||||
|
||||
if (!this.wcdbGetMessages) return []
|
||||
|
||||
@@ -463,16 +674,101 @@ export class Wcdb4Client {
|
||||
let offset = 0
|
||||
|
||||
while (true) {
|
||||
const rows = this.callJson<Record<string, unknown>[]>((handle, outJson) =>
|
||||
this.wcdbGetMessages!(handle, username, limit, offset, outJson)
|
||||
)
|
||||
let rows: Record<string, unknown>[]
|
||||
try {
|
||||
rows = this.callJson<Record<string, unknown>[]>((handle, outJson) =>
|
||||
this.wcdbGetMessages!(handle, username, limit, offset, outJson)
|
||||
)
|
||||
} catch (error) {
|
||||
console.warn(
|
||||
`[WCDB4] get_messages failed username=${username} offset=${offset}:`,
|
||||
error
|
||||
)
|
||||
break
|
||||
}
|
||||
const batch = Array.isArray(rows) ? rows : []
|
||||
allRows.push(...batch)
|
||||
if (batch.length < limit) break
|
||||
if (maxRows && allRows.length >= maxRows) break
|
||||
offset += limit
|
||||
}
|
||||
|
||||
return this.finalizeMessages(username, allRows, startTime, endTime)
|
||||
if (allRows.length === 0) {
|
||||
const tableRows = this.getMessagesByTableScan(username, startTime, endTime, maxRows)
|
||||
if (tableRows.length > 0) {
|
||||
console.log(
|
||||
`[WCDB4] getMessages table scan ok username=${username} rows=${tableRows.length} cost=${Date.now() - startedAt}ms`
|
||||
)
|
||||
return tableRows
|
||||
}
|
||||
}
|
||||
|
||||
const messages = this.finalizeMessages(username, allRows, startTime, endTime, maxRows)
|
||||
console.log(
|
||||
`[WCDB4] getMessages direct ok username=${username} rows=${messages.length} cost=${Date.now() - startedAt}ms`
|
||||
)
|
||||
return messages
|
||||
}
|
||||
|
||||
private readSessionRows(): Record<string, unknown>[] {
|
||||
if (!this.wcdbGetSessions) return []
|
||||
const rows = this.callJson<Record<string, unknown>[]>((handle, outJson) =>
|
||||
this.wcdbGetSessions!(handle, outJson)
|
||||
)
|
||||
return Array.isArray(rows) ? rows : []
|
||||
}
|
||||
|
||||
private getMessagesByTableScan(
|
||||
username: string,
|
||||
startTime?: number,
|
||||
endTime?: number,
|
||||
limit?: number
|
||||
): Wcdb4Message[] {
|
||||
if (!this.wcdbGetMessageTableStats || !this.wcdbExecQuery) return []
|
||||
|
||||
let tables: { tableName: string; dbPath: string }[] = []
|
||||
try {
|
||||
const rows = this.callJson<Record<string, unknown>[]>((handle, outJson) =>
|
||||
this.wcdbGetMessageTableStats!(handle, username, outJson)
|
||||
)
|
||||
tables = (Array.isArray(rows) ? rows : [])
|
||||
.map((row) => ({
|
||||
tableName: this.pickString(row, ['table_name', 'tableName', 'name']),
|
||||
dbPath: this.pickString(row, ['db_path', 'dbPath', 'path'])
|
||||
}))
|
||||
.filter((row) => row.tableName && row.dbPath)
|
||||
} catch (error) {
|
||||
console.warn(`[WCDB4] message table stats failed username=${username}:`, error)
|
||||
return []
|
||||
}
|
||||
|
||||
const allRows: Record<string, unknown>[] = []
|
||||
const begin = this.normalizeTimestamp(startTime || 0)
|
||||
const end = this.normalizeTimestamp(endTime || 0)
|
||||
const where = [
|
||||
begin > 0 ? `"create_time" >= ${begin}` : '',
|
||||
end > 0 ? `"create_time" <= ${end}` : ''
|
||||
].filter(Boolean)
|
||||
const whereSql = where.length ? ` WHERE ${where.join(' AND ')}` : ''
|
||||
|
||||
for (const table of tables) {
|
||||
try {
|
||||
const order = limit ? 'DESC' : 'ASC'
|
||||
const rowLimit = limit || 5000
|
||||
const sql = `SELECT * FROM ${this.quoteSqlIdentifier(table.tableName)}${whereSql} ORDER BY "create_time" ${order} LIMIT ${rowLimit}`
|
||||
const rows = this.callJson<Record<string, unknown>[]>((handle, outJson) =>
|
||||
this.wcdbExecQuery!(handle, 'message', table.dbPath, sql, outJson)
|
||||
)
|
||||
if (Array.isArray(rows)) allRows.push(...rows)
|
||||
} catch (error) {
|
||||
console.warn(
|
||||
`[WCDB4] message table scan failed username=${username} db=${table.dbPath} table=${table.tableName}:`,
|
||||
error
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
return this.finalizeMessages(username, allRows, startTime, endTime, limit)
|
||||
}
|
||||
|
||||
getMyAvatarUrl(): string | undefined {
|
||||
@@ -487,6 +783,17 @@ export class Wcdb4Client {
|
||||
return undefined
|
||||
}
|
||||
|
||||
getAvatarUrls(usernames: string[]): Record<string, string> {
|
||||
const normalized = this.uniq(usernames)
|
||||
this.hydrateAvatarUrls(normalized)
|
||||
const result: Record<string, string> = {}
|
||||
for (const username of normalized) {
|
||||
const avatar = this.avatarCache.get(username)
|
||||
if (avatar) result[username] = avatar
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
getMyGroupNickname(chatroomId: string): string | undefined {
|
||||
const groupNicknames = this.getGroupNicknames(chatroomId)
|
||||
for (const candidate of this.getMyUsernameCandidates()) {
|
||||
@@ -499,7 +806,8 @@ export class Wcdb4Client {
|
||||
private getMessagesByCursor(
|
||||
username: string,
|
||||
startTime?: number,
|
||||
endTime?: number
|
||||
endTime?: number,
|
||||
limit?: number
|
||||
): Wcdb4Message[] | null {
|
||||
if (
|
||||
!this.wcdbOpenMessageCursor ||
|
||||
@@ -510,15 +818,16 @@ export class Wcdb4Client {
|
||||
}
|
||||
|
||||
const handle = this.ensureHandle()
|
||||
const batchSize = 1000
|
||||
const batchSize = limit ? Math.min(500, limit) : 1000
|
||||
const cursorOut: WcdbHandleOut = [0]
|
||||
const begin = this.normalizeTimestamp(startTime || 0)
|
||||
const end = this.normalizeTimestamp(endTime || 0)
|
||||
const ascending = limit ? 0 : 1
|
||||
const openResult = this.wcdbOpenMessageCursor(
|
||||
handle,
|
||||
username,
|
||||
batchSize,
|
||||
1,
|
||||
ascending,
|
||||
begin,
|
||||
end,
|
||||
cursorOut
|
||||
@@ -546,6 +855,7 @@ export class Wcdb4Client {
|
||||
}
|
||||
|
||||
if (!outHasMore[0]) break
|
||||
if (limit && allRows.length >= limit) break
|
||||
}
|
||||
} finally {
|
||||
try {
|
||||
@@ -555,21 +865,19 @@ export class Wcdb4Client {
|
||||
}
|
||||
}
|
||||
|
||||
return this.finalizeMessages(username, allRows, startTime, endTime)
|
||||
return this.finalizeMessages(username, allRows, startTime, endTime, limit)
|
||||
}
|
||||
|
||||
private finalizeMessages(
|
||||
username: string,
|
||||
rows: Record<string, unknown>[],
|
||||
startTime?: number,
|
||||
endTime?: number
|
||||
endTime?: number,
|
||||
limit?: number
|
||||
): Wcdb4Message[] {
|
||||
const messages = rows.map((row) => this.normalizeMessage(row))
|
||||
const senderIds = messages.map((message) => message.sender || '').filter(Boolean)
|
||||
this.hydrateDisplayNames(senderIds)
|
||||
this.hydrateAvatarUrls(senderIds)
|
||||
|
||||
return messages
|
||||
const sorted = messages
|
||||
.filter((message) => {
|
||||
const createTime = Number(message.msgCreateTime)
|
||||
if (startTime && createTime < startTime) return false
|
||||
@@ -577,6 +885,10 @@ export class Wcdb4Client {
|
||||
return true
|
||||
})
|
||||
.sort((a, b) => Number(a.msgCreateTime) - Number(b.msgCreateTime))
|
||||
|
||||
const visibleMessages = limit && sorted.length > limit ? sorted.slice(-limit) : sorted
|
||||
|
||||
return visibleMessages
|
||||
.map((message) => {
|
||||
if (!message.sender) return message
|
||||
const senderNickname = this.displayNameCache.get(message.sender) || message.senderNickname
|
||||
@@ -598,6 +910,12 @@ export class Wcdb4Client {
|
||||
})
|
||||
}
|
||||
|
||||
private normalizeMessageLimit(limit?: number): number | undefined {
|
||||
const normalized = Number(limit)
|
||||
if (!Number.isFinite(normalized) || normalized <= 0) return undefined
|
||||
return Math.max(1, Math.min(5000, Math.floor(normalized)))
|
||||
}
|
||||
|
||||
getGroupMembers(chatroomId: string): Wcdb4GroupMember[] {
|
||||
if (!this.wcdbGetGroupMembers || !chatroomId) return []
|
||||
|
||||
@@ -615,17 +933,24 @@ export class Wcdb4Client {
|
||||
'member_username',
|
||||
'm_nsUsrName'
|
||||
])
|
||||
const memberNickname = this.pickString(row, [
|
||||
const wechatNickname = this.pickString(row, [
|
||||
'nickname',
|
||||
'nickName',
|
||||
'wechatNickname',
|
||||
'wechat_nickname',
|
||||
'm_nsNickName'
|
||||
])
|
||||
const remark = this.pickString(row, [
|
||||
'remark',
|
||||
'remarkName',
|
||||
'remark_name',
|
||||
'contactRemark',
|
||||
'contact_remark'
|
||||
])
|
||||
const memberNickname = this.pickString(row, [
|
||||
'displayName',
|
||||
'display_name',
|
||||
'groupNickname',
|
||||
'group_nickname',
|
||||
'roomNickname',
|
||||
'room_nickname',
|
||||
'remark',
|
||||
'm_nsNickName'
|
||||
'name'
|
||||
])
|
||||
const avatar = this.pickString(row, [
|
||||
'avatarUrl',
|
||||
@@ -640,7 +965,11 @@ export class Wcdb4Client {
|
||||
|
||||
return {
|
||||
m_nsUsrName: username,
|
||||
nickname: groupNicknames.get(username) || memberNickname,
|
||||
nickname:
|
||||
groupNicknames.get(username) || remark || wechatNickname || memberNickname,
|
||||
groupNickname: groupNicknames.get(username) || '',
|
||||
wechatNickname: wechatNickname || memberNickname,
|
||||
remark,
|
||||
m_nsHeadImgUrl: avatar
|
||||
}
|
||||
})
|
||||
@@ -650,10 +979,18 @@ export class Wcdb4Client {
|
||||
.map((member) => member.m_nsUsrName)
|
||||
.filter(Boolean)
|
||||
this.hydrateDisplayNames(missingDisplayNames)
|
||||
this.hydrateAvatarUrls(
|
||||
members
|
||||
.filter((member) => !member.m_nsHeadImgUrl)
|
||||
.map((member) => member.m_nsUsrName)
|
||||
.filter(Boolean)
|
||||
)
|
||||
return members.map((member) => ({
|
||||
...member,
|
||||
nickname:
|
||||
member.nickname || this.displayNameCache.get(member.m_nsUsrName) || member.m_nsUsrName,
|
||||
wechatNickname:
|
||||
member.wechatNickname || this.displayNameCache.get(member.m_nsUsrName) || '',
|
||||
m_nsHeadImgUrl: member.m_nsHeadImgUrl || this.avatarCache.get(member.m_nsUsrName) || ''
|
||||
}))
|
||||
} catch {
|
||||
@@ -815,19 +1152,49 @@ export class Wcdb4Client {
|
||||
|
||||
const libPath = this.findNativeLibrary()
|
||||
const libDir = path.dirname(libPath)
|
||||
const wcdbCorePath = path.join(libDir, 'libWCDB.dylib')
|
||||
if (fs.existsSync(wcdbCorePath)) {
|
||||
try {
|
||||
koffi.load(wcdbCorePath)
|
||||
} catch {
|
||||
// Some builds resolve this dependency through rpath.
|
||||
console.log(
|
||||
`[WCDB4] loadNativeLibrary platform=${process.platform} arch=${process.arch} libPath=${libPath} cwd=${process.cwd()} resourcesPath=${process.resourcesPath || ''} WCDB_RESOURCES_PATH=${process.env.WCDB_RESOURCES_PATH || ''}`
|
||||
)
|
||||
|
||||
// Reuse the module-level bootstrap if main.ts already performed
|
||||
// InitProtection + wcdb_init; WCDB returns -1006 if wcdb_init is called
|
||||
// twice in the same process.
|
||||
let lib: KoffiLibrary
|
||||
if (wcdbBootstrapLib) {
|
||||
console.log('[WCDB4] reusing bootstrap lib, skip koffi.load and wcdb_init')
|
||||
lib = wcdbBootstrapLib
|
||||
} else {
|
||||
const preloadLibraries =
|
||||
process.platform === 'win32'
|
||||
? ['WCDB.dll', 'SDL2.dll']
|
||||
: process.platform === 'darwin'
|
||||
? ['libWCDB.dylib']
|
||||
: []
|
||||
for (const name of preloadLibraries) {
|
||||
const preloadPath = path.join(libDir, name)
|
||||
if (!fs.existsSync(preloadPath)) continue
|
||||
try {
|
||||
koffi.load(preloadPath)
|
||||
console.log(`[WCDB4] preload ok ${preloadPath}`)
|
||||
} catch {
|
||||
console.warn(`[WCDB4] preload failed ${preloadPath}`)
|
||||
// Some builds resolve dependencies through the platform loader path.
|
||||
}
|
||||
}
|
||||
|
||||
console.log(`[WCDB4] koffi.load begin ${libPath}`)
|
||||
lib = koffi.load(libPath)
|
||||
console.log(`[WCDB4] koffi.load ok ${libPath}`)
|
||||
this.initProtection(lib, libDir)
|
||||
const wcdbInit = lib.func('int32 wcdb_init()') as () => number
|
||||
console.log('[WCDB4] wcdb_init begin')
|
||||
const initResult = wcdbInit()
|
||||
console.log(`[WCDB4] wcdb_init rc=${initResult}`)
|
||||
if (initResult !== 0) {
|
||||
console.warn(`[WCDB4] wcdb_init 返回 ${initResult},继续尝试 wcdb_open_account`)
|
||||
}
|
||||
}
|
||||
|
||||
const lib = koffi.load(libPath)
|
||||
this.initProtection(lib, libDir)
|
||||
|
||||
this.wcdbInit = lib.func('int32 wcdb_init()') as () => number
|
||||
this.wcdbShutdown = lib.func('int32 wcdb_shutdown()') as () => number
|
||||
this.wcdbOpenAccount = lib.func(
|
||||
'int32 wcdb_open_account(const char* path, const char* key, _Out_ int64* handle)'
|
||||
@@ -845,6 +1212,13 @@ export class Wcdb4Client {
|
||||
offset: number,
|
||||
outJson: WcdbVoidOut
|
||||
) => number
|
||||
try {
|
||||
this.wcdbGetMessageTableStats = lib.func(
|
||||
'int32 wcdb_get_message_table_stats(int64 handle, const char* sessionId, _Out_ void** outJson)'
|
||||
) as (handle: number, username: string, outJson: WcdbVoidOut) => number
|
||||
} catch {
|
||||
this.wcdbGetMessageTableStats = null
|
||||
}
|
||||
this.wcdbGetDisplayNames = lib.func(
|
||||
'int32 wcdb_get_display_names(int64 handle, const char* usernamesJson, _Out_ void** outJson)'
|
||||
) as (handle: number, usernamesJson: string, outJson: WcdbVoidOut) => number
|
||||
@@ -973,52 +1347,79 @@ export class Wcdb4Client {
|
||||
) => number
|
||||
|
||||
const resourceRoots = Array.from(
|
||||
new Set([
|
||||
libDir,
|
||||
path.dirname(libDir),
|
||||
process.env.WCDB_RESOURCES_PATH || '',
|
||||
path.join(process.resourcesPath || process.cwd(), 'resources'),
|
||||
process.resourcesPath || process.cwd(),
|
||||
path.join(process.cwd(), 'resources')
|
||||
])
|
||||
new Set(
|
||||
[
|
||||
libDir,
|
||||
path.dirname(libDir),
|
||||
process.env.WCDB_RESOURCES_PATH || '',
|
||||
...getResourceRoots()
|
||||
].filter(Boolean)
|
||||
)
|
||||
)
|
||||
|
||||
let lastCode = -1
|
||||
for (const resourceRoot of resourceRoots) {
|
||||
try {
|
||||
console.log(`[WCDB4] InitProtection call ${resourceRoot}`)
|
||||
lastCode = initProtection(resourceRoot)
|
||||
if (lastCode === 0) return
|
||||
} catch {
|
||||
console.log(`[WCDB4] InitProtection rc=${lastCode} path=${resourceRoot}`)
|
||||
if (lastCode === 0) {
|
||||
console.log(`[WCDB4] InitProtection ok path=${resourceRoot}`)
|
||||
return
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn(`[WCDB4] InitProtection exception path=${resourceRoot}`, error)
|
||||
// Try next candidate.
|
||||
}
|
||||
}
|
||||
|
||||
console.warn(
|
||||
`InitProtection 返回 ${lastCode},继续尝试 wcdb_init/open; tried=${resourceRoots.join(' | ')}`
|
||||
`[WCDB4] InitProtection 返回 ${lastCode},继续尝试 wcdb_init/open; tried=${resourceRoots.join(' | ')}`
|
||||
)
|
||||
}
|
||||
|
||||
private findNativeLibrary(): string {
|
||||
return Wcdb4Client.resolveNativeLibrary()
|
||||
}
|
||||
|
||||
static resolveNativeLibrary(): string {
|
||||
const libName =
|
||||
process.platform === 'darwin'
|
||||
? 'libwcdb_api.dylib'
|
||||
: process.platform === 'linux'
|
||||
? 'libwcdb_api.so'
|
||||
: 'wcdb_api.dll'
|
||||
const platformDir = process.platform === 'darwin' ? 'macos' : process.platform
|
||||
const resourcesPath = process.resourcesPath || process.cwd()
|
||||
const platformDir =
|
||||
process.platform === 'darwin'
|
||||
? 'macos'
|
||||
: process.platform === 'win32'
|
||||
? 'win32'
|
||||
: process.platform
|
||||
const archDir = process.arch === 'arm64' ? 'arm64' : 'x64'
|
||||
const resourceRoots = getResourceRoots()
|
||||
const candidates = [
|
||||
process.env.WCDB_DLL_PATH,
|
||||
path.join(resourcesPath, 'resources', platformDir, libName),
|
||||
path.join(resourcesPath, 'resources', libName),
|
||||
path.join(process.cwd(), 'resources', platformDir, libName),
|
||||
path.join(process.cwd(), 'resources', libName)
|
||||
...resourceRoots.flatMap((root) => [
|
||||
path.join(root, 'wcdb', platformDir, archDir, libName),
|
||||
path.join(root, 'wcdb', platformDir, 'x64', libName),
|
||||
path.join(root, platformDir, libName),
|
||||
path.join(root, libName)
|
||||
])
|
||||
].filter(Boolean) as string[]
|
||||
|
||||
const found = candidates.find((candidate) => fs.existsSync(candidate))
|
||||
if (!found) {
|
||||
throw new Error(`找不到 WCDB native 库: ${candidates.join(', ')}`)
|
||||
}
|
||||
if (process.platform === 'win32') {
|
||||
const runtimeDir = resourceRoots
|
||||
.map((root) => path.join(root, 'runtime', 'win32'))
|
||||
.find((candidate) => fs.existsSync(candidate))
|
||||
const dllDir = path.dirname(found)
|
||||
process.env.PATH = [dllDir, runtimeDir || '', process.env.PATH || '']
|
||||
.filter(Boolean)
|
||||
.join(path.delimiter)
|
||||
}
|
||||
return found
|
||||
}
|
||||
|
||||
@@ -1183,6 +1584,17 @@ export class Wcdb4Client {
|
||||
}
|
||||
}
|
||||
|
||||
private shouldHydrateSessionDisplayName(session: Wcdb4Session): boolean {
|
||||
const username = String(session.username || '').trim()
|
||||
const nickname = String(session.nickname || '').trim()
|
||||
if (!username) return false
|
||||
if (!nickname) return true
|
||||
if (nickname === username) return true
|
||||
if (nickname.endsWith('@chatroom')) return true
|
||||
if (nickname.startsWith('Group_') || nickname.startsWith('Unknown_')) return true
|
||||
return false
|
||||
}
|
||||
|
||||
private hydrateDisplayNames(usernames: string[]): void {
|
||||
if (!this.wcdbGetDisplayNames) return
|
||||
const missing = this.uniq(usernames).filter((username) => !this.displayNameCache.has(username))
|
||||
@@ -1437,4 +1849,8 @@ export class Wcdb4Client {
|
||||
const normalized = input > 1e12 ? Math.floor(input / 1000) : Math.floor(input)
|
||||
return Math.min(Math.max(normalized, 0), 2147483647)
|
||||
}
|
||||
|
||||
private quoteSqlIdentifier(identifier: string): string {
|
||||
return `"${String(identifier || '').replace(/"/g, '""')}"`
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Wcdb4Client } from './wcdb4-client'
|
||||
import { Wcdb4Client, Wcdb4MessageQueryOptions } from './wcdb4-client'
|
||||
|
||||
export interface UserContact {
|
||||
m_nsUsrName: string
|
||||
@@ -34,12 +34,33 @@ export class WechatDb {
|
||||
private wcdb4Client: Wcdb4Client
|
||||
private chatMd5ToUsername = new Map<string, string>()
|
||||
|
||||
constructor(rawKey: string, accountRoot?: string) {
|
||||
static async create(rawKey: string, accountRoot?: string): Promise<WechatDb> {
|
||||
// WCDB native init must run on the Electron main process; worker threads
|
||||
// get -1006 from wcdb_init. Initialize the client synchronously here
|
||||
// (and keep create() async for callers that already await it).
|
||||
return new Promise((resolve, reject) => {
|
||||
try {
|
||||
const client = new Wcdb4Client(rawKey, accountRoot)
|
||||
client.open()
|
||||
resolve(new WechatDb(rawKey, accountRoot, client))
|
||||
} catch (error) {
|
||||
reject(error instanceof Error ? error : new Error(String(error)))
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
constructor(
|
||||
rawKey: string,
|
||||
accountRoot?: string,
|
||||
clientOverride?: Wcdb4Client,
|
||||
initialChatTables?: { name: string; db_number: string }[]
|
||||
) {
|
||||
console.log(`Initializing WechatDb with key length: ${rawKey.trim().length}`)
|
||||
const client = new Wcdb4Client(rawKey, accountRoot)
|
||||
client.open()
|
||||
const client =
|
||||
clientOverride || new Wcdb4Client(rawKey, accountRoot)
|
||||
if (!clientOverride) client.open()
|
||||
this.wcdb4Client = client
|
||||
for (const table of client.getChatTables()) {
|
||||
for (const table of initialChatTables || client.getChatTables()) {
|
||||
if (table.name.startsWith('Chat_')) {
|
||||
this.chatMd5ToUsername.set(table.name.substring(5), table.db_number)
|
||||
}
|
||||
@@ -125,10 +146,15 @@ export class WechatDb {
|
||||
this.wcdb4Client.close()
|
||||
}
|
||||
|
||||
public getUserMessages(userMd5: string, startTime?: number, endTime?: number): WechatMessage[] {
|
||||
public getUserMessages(
|
||||
userMd5: string,
|
||||
startTime?: number,
|
||||
endTime?: number,
|
||||
options?: Wcdb4MessageQueryOptions
|
||||
): WechatMessage[] {
|
||||
const username = this.chatMd5ToUsername.get(userMd5)
|
||||
if (!username) return []
|
||||
return this.wcdb4Client.getMessages(username, startTime, endTime).map((message) => ({
|
||||
return this.wcdb4Client.getMessages(username, startTime, endTime, options).map((message) => ({
|
||||
...message,
|
||||
...message.raw
|
||||
}))
|
||||
|
||||
@@ -1,6 +1,42 @@
|
||||
import { ElectronAPI } from '@electron-toolkit/preload'
|
||||
import { Contact, Message } from '../shared/types'
|
||||
import { GroupReportExportRequest, GroupReportExportResult } from '../shared/group-report'
|
||||
import { LocalApiTestRequest, LocalApiTestResponse } from '../shared/local-api-test'
|
||||
import {
|
||||
DeleteGeneratedReportResult,
|
||||
ReportHistoryResult,
|
||||
SaveGeneratedReportRequest,
|
||||
SaveGeneratedReportResult
|
||||
} from '../shared/report-history'
|
||||
import type {
|
||||
DatabaseKeyEnvironment,
|
||||
DatabaseKeyStorageResult,
|
||||
DatabaseKeyValidationResult
|
||||
} from '../shared/database-key'
|
||||
import type {
|
||||
ImageDecryptionStatus,
|
||||
ImageDecryptionTestResult,
|
||||
ImageKeyConfigResult,
|
||||
SaveImageKeyRequest,
|
||||
TestImageDecryptionRequest
|
||||
} from '../shared/image-decryption'
|
||||
import type {
|
||||
AIChatRequestOptions,
|
||||
AIConnectionTestResult,
|
||||
AIProviderConfig,
|
||||
AIProviderListResult,
|
||||
AIRuntimeModelConfig,
|
||||
AIVisionTestRequest,
|
||||
AIVisionTestResult,
|
||||
LegacyAIConfig
|
||||
} from '../shared/ai-provider'
|
||||
import type {
|
||||
ImageAnalysisRequest,
|
||||
ImageAnalysisResponse,
|
||||
ImageCandidate,
|
||||
ImageCandidateQuery,
|
||||
ImageInsight
|
||||
} from '../shared/image-insight'
|
||||
|
||||
export type ParsedContent =
|
||||
| { type: 'text'; content: string }
|
||||
@@ -37,18 +73,59 @@ declare global {
|
||||
initDb: (
|
||||
key: string
|
||||
) => Promise<boolean | { success: boolean; error?: string; monitoring?: boolean }>
|
||||
getBootstrapCache: () => Promise<{
|
||||
self?: { wxid: string; nickname: string; avatar?: string; accountRoot: string }
|
||||
contacts: Contact[]
|
||||
updatedAt: number
|
||||
} | null>
|
||||
getContacts: (filter?: string) => Promise<Contact[]>
|
||||
getMessages: (userMd5: string, startTime?: number, endTime?: number) => Promise<Message[]>
|
||||
getContactAvatars: (usernames: string[]) => Promise<Record<string, string>>
|
||||
getCachedMessages: (
|
||||
userMd5: string,
|
||||
startTime?: number,
|
||||
endTime?: number
|
||||
) => Promise<Message[]>
|
||||
getMessages: (
|
||||
userMd5: string,
|
||||
startTime?: number,
|
||||
endTime?: number,
|
||||
options?: { limit?: number }
|
||||
) => Promise<Message[]>
|
||||
getGroupSnapshot: (userMd5: string) => Promise<{
|
||||
roomId: string
|
||||
memberCount: number
|
||||
members: { wxid: string; nickname: string; avatar: string }[]
|
||||
members: {
|
||||
wxid: string
|
||||
nickname: string
|
||||
groupNickname: string
|
||||
wechatNickname: string
|
||||
remark: string
|
||||
avatar: string
|
||||
}[]
|
||||
} | null>
|
||||
search: (keyword: string) => Promise<string | null>
|
||||
aiChat: (
|
||||
messages: { role: string; content: string }[],
|
||||
options?: { apiKey?: string; model?: string; baseURL?: string }
|
||||
) => Promise<{ success: boolean; data?: string; error?: string }>
|
||||
options?: AIChatRequestOptions
|
||||
) => Promise<{
|
||||
success: boolean
|
||||
data?: string
|
||||
usage?: {
|
||||
input?: number
|
||||
output?: number
|
||||
total?: number
|
||||
estimated?: boolean
|
||||
}
|
||||
error?: string
|
||||
}>
|
||||
listAIProviders: () => Promise<AIProviderListResult>
|
||||
getAIRuntimeConfig: () => Promise<AIRuntimeModelConfig>
|
||||
saveAIProvider: (provider: AIProviderConfig) => Promise<AIProviderListResult>
|
||||
deleteAIProvider: (providerId: string) => Promise<AIProviderListResult>
|
||||
setDefaultAIProvider: (providerId: string) => Promise<AIProviderListResult>
|
||||
testAIProvider: (providerId: string) => Promise<AIConnectionTestResult>
|
||||
testAIVision: (request: AIVisionTestRequest) => Promise<AIVisionTestResult>
|
||||
migrateLegacyAIConfig: (config: LegacyAIConfig) => Promise<AIProviderListResult>
|
||||
copyImage: (base64String: string) => Promise<{ success: boolean; error?: string }>
|
||||
getVoiceData: (
|
||||
sessionId: string,
|
||||
@@ -60,16 +137,34 @@ declare global {
|
||||
getImage: (
|
||||
imageMd5?: string,
|
||||
imageDatNameOrThumb?: string | boolean,
|
||||
sessionId?: string
|
||||
) => Promise<{ success: boolean; data?: string; error?: string }>
|
||||
sessionId?: string,
|
||||
options?: { force?: boolean }
|
||||
) => Promise<{
|
||||
success: boolean
|
||||
data?: string
|
||||
error?: string
|
||||
isThumb?: boolean
|
||||
filePath?: string
|
||||
}>
|
||||
getSticker: (
|
||||
cdnUrl?: string,
|
||||
md5?: string
|
||||
) => Promise<{ success: boolean; data?: string; error?: string }>
|
||||
exportGroupReport: (request: GroupReportExportRequest) => Promise<GroupReportExportResult>
|
||||
listGeneratedReports: () => Promise<ReportHistoryResult>
|
||||
saveGeneratedReport: (
|
||||
request: SaveGeneratedReportRequest
|
||||
) => Promise<SaveGeneratedReportResult>
|
||||
deleteGeneratedReport: (reportId: string) => Promise<DeleteGeneratedReportResult>
|
||||
revealGroupReport: (filePath: string) => Promise<{ success: boolean; error?: string }>
|
||||
getSavedDbKey: () => Promise<{ success: boolean; key?: string; error?: string }>
|
||||
autoGetDbKey: () => Promise<{
|
||||
getSavedDbKey: () => Promise<DatabaseKeyStorageResult>
|
||||
getDatabaseKeyEnvironment: () => Promise<DatabaseKeyEnvironment>
|
||||
readDatabaseKeyClipboard: () => Promise<{
|
||||
success: boolean
|
||||
value?: string
|
||||
error?: string
|
||||
}>
|
||||
autoGetDbKey: (options?: { save?: boolean }) => Promise<{
|
||||
success: boolean
|
||||
key?: string
|
||||
error?: string
|
||||
@@ -77,31 +172,68 @@ declare global {
|
||||
saved?: boolean
|
||||
warning?: string
|
||||
}>
|
||||
autoGetImageKey: (options?: { save?: boolean }) => Promise<{
|
||||
success: boolean
|
||||
xorKey?: number
|
||||
aesKey?: string
|
||||
verified?: boolean
|
||||
error?: string
|
||||
imageXorKey?: string
|
||||
imageAesKey?: string
|
||||
settings?: {
|
||||
dbRoot: string
|
||||
apiEnabled: boolean
|
||||
apiHost: string
|
||||
apiPort: number
|
||||
imageKeyRoot: string
|
||||
imageXorKey: string
|
||||
imageAesKey: string
|
||||
}
|
||||
}>
|
||||
getImageKeyConfig: () => Promise<ImageKeyConfigResult>
|
||||
getImageDecryptionStatus: () => Promise<ImageDecryptionStatus>
|
||||
saveImageKeyConfig: (request: SaveImageKeyRequest) => Promise<ImageKeyConfigResult>
|
||||
testImageDecryption: (
|
||||
request: TestImageDecryptionRequest
|
||||
) => Promise<ImageDecryptionTestResult>
|
||||
clearImageKeyConfig: () => Promise<{ success: boolean; error?: string }>
|
||||
pasteAndSaveDbKey: () => Promise<{ success: boolean; key?: string; error?: string }>
|
||||
saveDbKey: (key: string) => Promise<{ success: boolean; key?: string; error?: string }>
|
||||
saveDbKey: (key: string) => Promise<DatabaseKeyStorageResult>
|
||||
clearSavedDbKey: () => Promise<{ success: boolean; error?: string }>
|
||||
onWcdbChange: (callback: (payload: { type: string; json: string }) => void) => () => void
|
||||
onDbKeyStatus: (callback: (payload: { message: string }) => void) => () => void
|
||||
onImageKeyStatus: (callback: (payload: { message: string }) => void) => () => void
|
||||
getSettings: () => Promise<{
|
||||
settings: {
|
||||
dbRoot: string
|
||||
apiEnabled: boolean
|
||||
apiHost: string
|
||||
apiPort: number
|
||||
imageKeyRoot: string
|
||||
imageXorKey: string
|
||||
imageAesKey: string
|
||||
}
|
||||
settingsPath: string
|
||||
}>
|
||||
setSettings: (patch: Partial<{
|
||||
dbRoot: string
|
||||
apiEnabled: boolean
|
||||
apiHost: string
|
||||
apiPort: number
|
||||
}>) => Promise<{
|
||||
setSettings: (
|
||||
patch: Partial<{
|
||||
dbRoot: string
|
||||
apiEnabled: boolean
|
||||
apiHost: string
|
||||
apiPort: number
|
||||
imageKeyRoot: string
|
||||
imageXorKey: string
|
||||
imageAesKey: string
|
||||
}>
|
||||
) => Promise<{
|
||||
settings: {
|
||||
dbRoot: string
|
||||
apiEnabled: boolean
|
||||
apiHost: string
|
||||
apiPort: number
|
||||
imageKeyRoot: string
|
||||
imageXorKey: string
|
||||
imageAesKey: string
|
||||
}
|
||||
settingsPath: string
|
||||
}>
|
||||
@@ -112,20 +244,15 @@ declare global {
|
||||
}
|
||||
| { ready: false }
|
||||
>
|
||||
testConnection: (
|
||||
key: string,
|
||||
accountRoot?: string
|
||||
) => Promise<{
|
||||
success: boolean
|
||||
error?: string
|
||||
accountRoot?: string
|
||||
wxid?: string
|
||||
}>
|
||||
testConnection: (key: string, accountRoot?: string) => Promise<DatabaseKeyValidationResult>
|
||||
reopenWithRoot: (accountRoot: string) => Promise<{
|
||||
success: boolean
|
||||
error?: string
|
||||
info?: { wxid: string; nickname: string; avatar?: string; accountRoot: string }
|
||||
}>
|
||||
selectDbRoot: () => Promise<{ canceled: boolean; path?: string }>
|
||||
openAccountRoot: () => Promise<{ success: boolean; error?: string }>
|
||||
disconnectDb: () => Promise<{ success: boolean; error?: string }>
|
||||
apiStatus: () => Promise<{
|
||||
running: boolean
|
||||
host: string
|
||||
@@ -143,6 +270,34 @@ declare global {
|
||||
port: number
|
||||
error?: string
|
||||
}>
|
||||
getReaderSkillStatus: () => Promise<{
|
||||
available: boolean
|
||||
version?: string
|
||||
filePath?: string
|
||||
directoryPath?: string
|
||||
source: 'development' | 'bundled'
|
||||
githubUrl: string
|
||||
error?: string
|
||||
}>
|
||||
readReaderSkill: () => Promise<{ success: boolean; content?: string; error?: string }>
|
||||
revealReaderSkill: () => Promise<{ success: boolean; error?: string }>
|
||||
openReaderSkillGithub: () => Promise<{ success: boolean; error?: string }>
|
||||
testLocalApiRequest: (request: LocalApiTestRequest) => Promise<LocalApiTestResponse>
|
||||
copyText: (text: string) => Promise<{ success: boolean; error?: string }>
|
||||
// ============================================================
|
||||
// AI 图片理解基础设施(ImageInsightService)
|
||||
// ============================================================
|
||||
imageListCandidates: (query: ImageCandidateQuery) => Promise<{
|
||||
success: boolean
|
||||
candidates: ImageCandidate[]
|
||||
error?: string
|
||||
}>
|
||||
imageAnalyze: (request: ImageAnalysisRequest) => Promise<ImageAnalysisResponse>
|
||||
getImageInsight: (imageHash: string) => Promise<{ success: boolean; insight?: ImageInsight }>
|
||||
listImageInsights: (
|
||||
sessionId: string,
|
||||
limit?: number
|
||||
) => Promise<{ success: boolean; insights: ImageInsight[] }>
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,32 +1,79 @@
|
||||
import { contextBridge, ipcRenderer } from 'electron'
|
||||
import { electronAPI } from '@electron-toolkit/preload'
|
||||
import { GroupReportExportRequest } from '../shared/group-report'
|
||||
import type { GroupReportExportRequest } from '../shared/group-report'
|
||||
import type { SaveGeneratedReportRequest } from '../shared/report-history'
|
||||
import type {
|
||||
AIChatRequestOptions,
|
||||
AIProviderConfig,
|
||||
AIVisionTestRequest,
|
||||
LegacyAIConfig
|
||||
} from '../shared/ai-provider'
|
||||
import type {
|
||||
ImageAnalysisRequest,
|
||||
ImageAnalysisResponse,
|
||||
ImageCandidate,
|
||||
ImageCandidateQuery,
|
||||
ImageInsight
|
||||
} from '../shared/image-insight'
|
||||
|
||||
// 渲染器的自定义 API
|
||||
const api = {
|
||||
initDb: (key: string) => ipcRenderer.invoke('db:init', key),
|
||||
getBootstrapCache: () => ipcRenderer.invoke('db:getBootstrapCache'),
|
||||
getContacts: (filter?: string) => ipcRenderer.invoke('db:getContacts', filter),
|
||||
getMessages: (userMd5: string, startTime?: number, endTime?: number) =>
|
||||
ipcRenderer.invoke('db:getMessages', userMd5, startTime, endTime),
|
||||
getContactAvatars: (usernames: string[]) => ipcRenderer.invoke('db:getContactAvatars', usernames),
|
||||
getCachedMessages: (userMd5: string, startTime?: number, endTime?: number) =>
|
||||
ipcRenderer.invoke('db:getCachedMessages', userMd5, startTime, endTime),
|
||||
getMessages: (
|
||||
userMd5: string,
|
||||
startTime?: number,
|
||||
endTime?: number,
|
||||
options?: { limit?: number }
|
||||
) => ipcRenderer.invoke('db:getMessages', userMd5, startTime, endTime, options),
|
||||
getGroupSnapshot: (userMd5: string) => ipcRenderer.invoke('db:getGroupSnapshot', userMd5),
|
||||
search: (keyword: string) => ipcRenderer.invoke('db:search', keyword),
|
||||
aiChat: (
|
||||
messages: { role: string; content: string }[],
|
||||
options?: { apiKey?: string; model?: string; baseURL?: string }
|
||||
) => ipcRenderer.invoke('ai:chat', messages, options),
|
||||
aiChat: (messages: { role: string; content: string }[], options?: AIChatRequestOptions) =>
|
||||
ipcRenderer.invoke('ai:chat', messages, options),
|
||||
listAIProviders: () => ipcRenderer.invoke('ai:listProviders'),
|
||||
getAIRuntimeConfig: () => ipcRenderer.invoke('ai:getRuntimeConfig'),
|
||||
saveAIProvider: (provider: AIProviderConfig) => ipcRenderer.invoke('ai:saveProvider', provider),
|
||||
deleteAIProvider: (providerId: string) => ipcRenderer.invoke('ai:deleteProvider', providerId),
|
||||
setDefaultAIProvider: (providerId: string) =>
|
||||
ipcRenderer.invoke('ai:setDefaultProvider', providerId),
|
||||
testAIProvider: (providerId: string) => ipcRenderer.invoke('ai:testProvider', providerId),
|
||||
testAIVision: (request: AIVisionTestRequest) => ipcRenderer.invoke('ai:testVision', request),
|
||||
migrateLegacyAIConfig: (config: LegacyAIConfig) => ipcRenderer.invoke('ai:migrateLegacy', config),
|
||||
copyImage: (base64String) => ipcRenderer.invoke('copy-image', base64String),
|
||||
getVoiceData: (sessionId: string, localId: number, createTime: number, svrId?: string | number) =>
|
||||
ipcRenderer.invoke('db:getVoiceData', sessionId, localId, createTime, svrId),
|
||||
parseMessage: (content: string, messageType: number) =>
|
||||
ipcRenderer.invoke('db:parseMessage', content, messageType),
|
||||
getImage: (imageMd5?: string, imageDatNameOrThumb?: string | boolean, sessionId?: string) =>
|
||||
ipcRenderer.invoke('db:getImage', imageMd5, imageDatNameOrThumb, sessionId),
|
||||
getImage: (
|
||||
imageMd5?: string,
|
||||
imageDatNameOrThumb?: string | boolean,
|
||||
sessionId?: string,
|
||||
options?: { force?: boolean }
|
||||
) => ipcRenderer.invoke('db:getImage', imageMd5, imageDatNameOrThumb, sessionId, options),
|
||||
getSticker: (cdnUrl?: string, md5?: string) => ipcRenderer.invoke('db:getSticker', cdnUrl, md5),
|
||||
exportGroupReport: (request: GroupReportExportRequest) =>
|
||||
ipcRenderer.invoke('report:export', request),
|
||||
listGeneratedReports: () => ipcRenderer.invoke('report:listGenerated'),
|
||||
saveGeneratedReport: (request: SaveGeneratedReportRequest) =>
|
||||
ipcRenderer.invoke('report:saveGenerated', request),
|
||||
deleteGeneratedReport: (reportId: string) =>
|
||||
ipcRenderer.invoke('report:deleteGenerated', reportId),
|
||||
revealGroupReport: (filePath: string) => ipcRenderer.invoke('report:reveal', filePath),
|
||||
getSavedDbKey: () => ipcRenderer.invoke('key:getSavedDbKey'),
|
||||
autoGetDbKey: () => ipcRenderer.invoke('key:autoGetDbKey'),
|
||||
getDatabaseKeyEnvironment: () => ipcRenderer.invoke('key:getEnvironment'),
|
||||
readDatabaseKeyClipboard: () => ipcRenderer.invoke('key:readClipboardDbKey'),
|
||||
autoGetDbKey: (options?: { save?: boolean }) => ipcRenderer.invoke('key:autoGetDbKey', options),
|
||||
autoGetImageKey: (options?: { save?: boolean }) =>
|
||||
ipcRenderer.invoke('key:autoGetImageKey', options),
|
||||
getImageKeyConfig: () => ipcRenderer.invoke('image:getConfig'),
|
||||
getImageDecryptionStatus: () => ipcRenderer.invoke('image:getStatus'),
|
||||
saveImageKeyConfig: (request) => ipcRenderer.invoke('image:saveConfig', request),
|
||||
testImageDecryption: (request) => ipcRenderer.invoke('image:testConfig', request),
|
||||
clearImageKeyConfig: () => ipcRenderer.invoke('image:clearConfig'),
|
||||
pasteAndSaveDbKey: () => ipcRenderer.invoke('key:pasteAndSaveDbKey'),
|
||||
saveDbKey: (key: string) => ipcRenderer.invoke('key:saveDbKey', key),
|
||||
clearSavedDbKey: () => ipcRenderer.invoke('key:clearSavedDbKey'),
|
||||
@@ -44,16 +91,48 @@ const api = {
|
||||
ipcRenderer.on('key:dbKeyStatus', listener)
|
||||
return () => ipcRenderer.removeListener('key:dbKeyStatus', listener)
|
||||
},
|
||||
onImageKeyStatus: (callback: (payload: { message: string }) => void) => {
|
||||
const listener = (_event: Electron.IpcRendererEvent, payload: { message: string }): void =>
|
||||
callback(payload)
|
||||
ipcRenderer.on('key:imageKeyStatus', listener)
|
||||
return () => ipcRenderer.removeListener('key:imageKeyStatus', listener)
|
||||
},
|
||||
getSettings: () => ipcRenderer.invoke('settings:get'),
|
||||
setSettings: (patch) => ipcRenderer.invoke('settings:set', patch),
|
||||
getSelf: () => ipcRenderer.invoke('settings:getSelf'),
|
||||
testConnection: (key: string, accountRoot?: string) =>
|
||||
ipcRenderer.invoke('db:testConnection', key, accountRoot),
|
||||
reopenWithRoot: (accountRoot: string) => ipcRenderer.invoke('db:reopenWithRoot', accountRoot),
|
||||
selectDbRoot: () => ipcRenderer.invoke('settings:selectDbRoot'),
|
||||
openAccountRoot: () => ipcRenderer.invoke('settings:openAccountRoot'),
|
||||
disconnectDb: () => ipcRenderer.invoke('db:disconnect'),
|
||||
apiStatus: () => ipcRenderer.invoke('api:getStatus'),
|
||||
apiStart: (host?: string, port?: number) => ipcRenderer.invoke('api:start', host, port),
|
||||
apiStop: () => ipcRenderer.invoke('api:stop'),
|
||||
apiToggle: (enabled: boolean) => ipcRenderer.invoke('api:toggle', enabled)
|
||||
apiToggle: (enabled: boolean) => ipcRenderer.invoke('api:toggle', enabled),
|
||||
getReaderSkillStatus: () => ipcRenderer.invoke('api:skillStatus'),
|
||||
readReaderSkill: () => ipcRenderer.invoke('api:readSkill'),
|
||||
revealReaderSkill: () => ipcRenderer.invoke('api:revealSkill'),
|
||||
openReaderSkillGithub: () => ipcRenderer.invoke('api:openSkillGithub'),
|
||||
testLocalApiRequest: (request) => ipcRenderer.invoke('api:testLocalRequest', request),
|
||||
copyText: (text: string) => ipcRenderer.invoke('api:copyText', text),
|
||||
// ============================================================
|
||||
// AI 图片理解基础设施(ImageInsightService)
|
||||
// ============================================================
|
||||
imageListCandidates: (query: ImageCandidateQuery): Promise<{
|
||||
success: boolean
|
||||
candidates: ImageCandidate[]
|
||||
error?: string
|
||||
}> => ipcRenderer.invoke('image:listCandidates', query),
|
||||
imageAnalyze: (request: ImageAnalysisRequest): Promise<ImageAnalysisResponse> =>
|
||||
ipcRenderer.invoke('image:analyze', request),
|
||||
getImageInsight: (imageHash: string): Promise<{ success: boolean; insight?: ImageInsight }> =>
|
||||
ipcRenderer.invoke('image:getInsight', imageHash),
|
||||
listImageInsights: (
|
||||
sessionId: string,
|
||||
limit?: number
|
||||
): Promise<{ success: boolean; insights: ImageInsight[] }> =>
|
||||
ipcRenderer.invoke('image:listInsights', sessionId, limit)
|
||||
}
|
||||
|
||||
if (process.contextIsolated) {
|
||||
|
||||
@@ -2,7 +2,8 @@
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<title>Electron</title>
|
||||
<title>WechatExplorer</title>
|
||||
<link rel="icon" type="image/svg+xml" href="/src/assets/brand-icon.svg" />
|
||||
<!-- https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP -->
|
||||
<meta
|
||||
http-equiv="Content-Security-Policy"
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
<svg width="256" height="256" viewBox="0 0 256 256" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<rect width="256" height="256" rx="48" fill="#022C22" />
|
||||
<rect x="0.5" y="0.5" width="255" height="255" rx="47.5" stroke="#064E3B" />
|
||||
<rect x="128" y="16.2742" width="158" height="158" rx="15" transform="rotate(45 128 16.2742)" stroke="#14B8A6" stroke-opacity="0.3" stroke-width="2" />
|
||||
<rect x="65" y="65" width="126" height="126" rx="11" stroke="#14B8A6" stroke-opacity="0.5" stroke-width="2" />
|
||||
<rect x="104" y="104" width="48" height="48" rx="24" fill="#14B8A6" />
|
||||
<rect x="192" y="48" width="16" height="16" rx="8" fill="#2DD4BF" />
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 656 B |
@@ -1,119 +1,111 @@
|
||||
import React, { useEffect, useRef, useState } from 'react'
|
||||
import React, { useCallback, useEffect, useRef, useState } from 'react'
|
||||
import { Message, Contact } from '../../../shared/types'
|
||||
import { VoicePlayer } from './VoicePlayer'
|
||||
import { RichMessageBubble } from './RichMessageBubble'
|
||||
import { ImageBubble } from './ImageBubble'
|
||||
import {
|
||||
buildGroupReportInput,
|
||||
GROUP_REPORT_SYSTEM_PROMPT,
|
||||
parseGroupDailyReport
|
||||
} from '../utils/group-report'
|
||||
import { ChatHeader } from './chat/ChatHeader'
|
||||
import { ChatStatusBar } from './chat/ChatStatusBar'
|
||||
import { DataTrustBar } from './chat/DataTrustBar'
|
||||
import { EmptyConversationState } from './chat/EmptyConversationState'
|
||||
import { ExportRange } from './chat/ExportMenu'
|
||||
import { MessageList } from './chat/MessageList'
|
||||
|
||||
interface ChatWindowProps {
|
||||
contact: Contact | null
|
||||
messages: Message[]
|
||||
isLoadingMessages?: boolean
|
||||
contentFilter?: string
|
||||
dateRange?: string
|
||||
onContentFilterChange?: (keyword: string) => void
|
||||
onRefresh?: () => void
|
||||
onRefreshData?: () => void
|
||||
onCreateGroupReport?: () => void
|
||||
isAiLoading?: boolean
|
||||
}
|
||||
|
||||
type SummaryDateRange = 'today' | 'yesterday' | '7days'
|
||||
type SummaryMessageType = 'text' | 'image' | 'sticker' | 'video' | 'voice' | 'share' | 'system'
|
||||
const MAX_RENDERED_MESSAGES = 600
|
||||
const DATE_RANGE_LABELS: Record<string, string> = {
|
||||
today: '今天',
|
||||
yesterday: '昨日',
|
||||
'7': '7 天',
|
||||
'30': '30 天',
|
||||
all: '全部'
|
||||
}
|
||||
|
||||
const SUMMARY_DATE_OPTIONS: { value: SummaryDateRange; label: string }[] = [
|
||||
{ value: 'today', label: '今天' },
|
||||
{ value: 'yesterday', label: '昨日' },
|
||||
{ value: '7days', label: '最近 7 天' }
|
||||
]
|
||||
const formatClock = (date: Date): string =>
|
||||
`${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
|
||||
|
||||
const SUMMARY_TYPE_OPTIONS: {
|
||||
value: SummaryMessageType
|
||||
label: string
|
||||
messageTypes: string[]
|
||||
}[] = [
|
||||
{ value: 'text', label: '文本', messageTypes: ['普通文本'] },
|
||||
{ value: 'image', label: '图片', messageTypes: ['图片'] },
|
||||
{ value: 'sticker', label: '表情包', messageTypes: ['表情包'] },
|
||||
{ value: 'video', label: '视频', messageTypes: ['视频'] },
|
||||
{ value: 'voice', label: '语音', messageTypes: ['语音'] },
|
||||
{ value: 'share', label: '分享/引用', messageTypes: ['分享消息', '名片', '位置', '通话'] },
|
||||
{ value: 'system', label: '系统消息', messageTypes: ['系统消息'] }
|
||||
]
|
||||
const formatRangeDate = (date: Date, now: Date): string => {
|
||||
const clock = formatClock(date)
|
||||
if (date.getFullYear() === now.getFullYear()) {
|
||||
return `${date.getMonth() + 1} 月 ${date.getDate()} 日 ${clock}`
|
||||
}
|
||||
return `${date.getFullYear()} 年 ${date.getMonth() + 1} 月 ${date.getDate()} 日 ${clock}`
|
||||
}
|
||||
|
||||
const getSummaryDateRange = (range: SummaryDateRange): { startTime: number; endTime: number } => {
|
||||
const getChatHeaderRangeLabel = (range: string): string => {
|
||||
const now = new Date()
|
||||
const startOfToday = new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime() / 1000
|
||||
const endTime = Math.floor(Date.now() / 1000)
|
||||
if (range === 'yesterday') {
|
||||
return { startTime: startOfToday - 86400, endTime: startOfToday - 1 }
|
||||
const startOfToday = new Date(now.getFullYear(), now.getMonth(), now.getDate())
|
||||
const endOfYesterday = new Date(startOfToday.getTime() - 60_000)
|
||||
|
||||
if (range === 'today') return `今天 00:00—现在`
|
||||
if (range === 'yesterday') return `昨天 00:00—${formatClock(endOfYesterday)}`
|
||||
if (range === '7') {
|
||||
const start = new Date(Date.now() - 7 * 86400000)
|
||||
return `${formatRangeDate(start, now)}—现在`
|
||||
}
|
||||
if (range === '7days') {
|
||||
return { startTime: startOfToday - 6 * 86400, endTime }
|
||||
if (range === '30') {
|
||||
const start = new Date(Date.now() - 30 * 86400000)
|
||||
return `${formatRangeDate(start, now)}—现在`
|
||||
}
|
||||
return { startTime: startOfToday, endTime }
|
||||
if (range === 'all') return '全部记录'
|
||||
return DATE_RANGE_LABELS[range] || '当前范围'
|
||||
}
|
||||
|
||||
const ChatWindow: React.FC<ChatWindowProps> = ({
|
||||
contact,
|
||||
messages,
|
||||
isLoadingMessages,
|
||||
contentFilter,
|
||||
dateRange = 'today',
|
||||
onContentFilterChange,
|
||||
onRefresh,
|
||||
onRefreshData
|
||||
onRefreshData,
|
||||
onCreateGroupReport,
|
||||
isAiLoading = false
|
||||
}) => {
|
||||
const isGroupChat = Boolean(
|
||||
contact?.type === 'group' || contact?.m_nsUsrName?.endsWith('@chatroom')
|
||||
)
|
||||
const messageListRef = useRef<HTMLDivElement>(null)
|
||||
const messagesEndRef = useRef<HTMLDivElement>(null)
|
||||
const [generatedImage, setGeneratedImage] = useState<string | null>(null)
|
||||
const [reportPaths, setReportPaths] = useState<{ htmlPath: string; pngPath: string } | null>(null)
|
||||
const [previewImage, setPreviewImage] = useState<string | null>(null)
|
||||
const [imageScale, setImageScale] = useState(0.75)
|
||||
const [imageRotation, setImageRotation] = useState(0)
|
||||
const [imageOffset, setImageOffset] = useState({ x: 0, y: 0 })
|
||||
const imageViewerStageRef = useRef<HTMLDivElement>(null)
|
||||
const imageDragRef = useRef<{ x: number; y: number; offsetX: number; offsetY: number } | null>(
|
||||
null
|
||||
)
|
||||
const [showAvatar, setShowAvatar] = useState(true)
|
||||
const [isAtLatest, setIsAtLatest] = useState(true)
|
||||
|
||||
// AI Settings
|
||||
const [showSettingsModal, setShowSettingsModal] = useState(false)
|
||||
const [apiKey, setApiKey] = useState(() => localStorage.getItem('ai_api_key') || '')
|
||||
const [baseURL, setBaseURL] = useState(
|
||||
() => localStorage.getItem('ai_base_url') || 'https://api.deepseek.com'
|
||||
)
|
||||
const [model, setModel] = useState(() => localStorage.getItem('ai_model') || 'deepseek-chat')
|
||||
const [summaryDateRange, setSummaryDateRange] = useState<SummaryDateRange>('today')
|
||||
const [summaryMessageTypes, setSummaryMessageTypes] = useState<SummaryMessageType[]>(['text'])
|
||||
|
||||
const handleSaveSettings = (): void => {
|
||||
if (!summaryMessageTypes.length) {
|
||||
alert('请至少选择一种消息类型')
|
||||
return
|
||||
}
|
||||
localStorage.setItem('ai_api_key', apiKey)
|
||||
localStorage.setItem('ai_base_url', baseURL)
|
||||
localStorage.setItem('ai_model', model)
|
||||
setShowSettingsModal(false)
|
||||
AIChat()
|
||||
}
|
||||
|
||||
const toggleSummaryMessageType = (type: SummaryMessageType): void => {
|
||||
setSummaryMessageTypes((current) =>
|
||||
current.includes(type) ? current.filter((item) => item !== type) : [...current, type]
|
||||
)
|
||||
}
|
||||
|
||||
const scrollToBottom = (): void => {
|
||||
const scrollToBottom = useCallback((): void => {
|
||||
messagesEndRef.current?.scrollIntoView({ behavior: 'auto' })
|
||||
}
|
||||
setIsAtLatest(true)
|
||||
}, [])
|
||||
|
||||
const handleMessageListScroll = useCallback((event: React.UIEvent<HTMLDivElement>): void => {
|
||||
const target = event.currentTarget
|
||||
const distanceToBottom = target.scrollHeight - target.scrollTop - target.clientHeight
|
||||
setIsAtLatest(distanceToBottom <= 24)
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
scrollToBottom()
|
||||
}, [messages])
|
||||
const frame = window.requestAnimationFrame(() => scrollToBottom())
|
||||
return () => window.cancelAnimationFrame(frame)
|
||||
}, [messages, scrollToBottom])
|
||||
|
||||
const openImagePreview = (imageUrl: string): void => {
|
||||
setPreviewImage(imageUrl)
|
||||
setImageScale(0.75)
|
||||
setImageScale(1)
|
||||
setImageRotation(0)
|
||||
setImageOffset({ x: 0, y: 0 })
|
||||
}
|
||||
@@ -124,17 +116,18 @@ const ChatWindow: React.FC<ChatWindowProps> = ({
|
||||
}
|
||||
|
||||
const zoomImage = (delta: number): void => {
|
||||
setImageScale((prev) => Math.min(3, Math.max(0.25, Number((prev + delta).toFixed(2)))))
|
||||
setImageScale((prev) => Math.min(8, Math.max(0.1, Number((prev + delta).toFixed(2)))))
|
||||
}
|
||||
|
||||
const resetImageTransform = (): void => {
|
||||
setImageScale(0.75)
|
||||
setImageScale(1)
|
||||
setImageRotation(0)
|
||||
setImageOffset({ x: 0, y: 0 })
|
||||
}
|
||||
|
||||
const handleViewerWheel = (event: React.WheelEvent): void => {
|
||||
event.preventDefault()
|
||||
event.stopPropagation()
|
||||
zoomImage(event.deltaY > 0 ? -0.1 : 0.1)
|
||||
}
|
||||
|
||||
@@ -161,7 +154,25 @@ const ChatWindow: React.FC<ChatWindowProps> = ({
|
||||
imageDragRef.current = null
|
||||
}
|
||||
|
||||
const handleExport = (days: number | 'all'): void => {
|
||||
useEffect(() => {
|
||||
if (!previewImage) return
|
||||
|
||||
const previousOverflow = document.body.style.overflow
|
||||
document.body.style.overflow = 'hidden'
|
||||
|
||||
const stage = imageViewerStageRef.current
|
||||
const preventBackgroundWheel = (event: WheelEvent): void => {
|
||||
event.preventDefault()
|
||||
}
|
||||
stage?.addEventListener('wheel', preventBackgroundWheel, { passive: false })
|
||||
|
||||
return () => {
|
||||
document.body.style.overflow = previousOverflow
|
||||
stage?.removeEventListener('wheel', preventBackgroundWheel)
|
||||
}
|
||||
}, [previewImage])
|
||||
|
||||
const handleExport = (days: ExportRange): void => {
|
||||
if (!messages.length) return
|
||||
|
||||
let filtered = messages
|
||||
@@ -220,60 +231,6 @@ const ChatWindow: React.FC<ChatWindowProps> = ({
|
||||
document.body.removeChild(link)
|
||||
}
|
||||
|
||||
const [isLoading, setIsLoading] = useState(false)
|
||||
|
||||
const AIChat = async (): Promise<void> => {
|
||||
if (!contact) return
|
||||
if (!summaryMessageTypes.length) {
|
||||
alert('请至少选择一种消息类型')
|
||||
return
|
||||
}
|
||||
setIsLoading(true)
|
||||
try {
|
||||
const { startTime, endTime } = getSummaryDateRange(summaryDateRange)
|
||||
const rangeMessages = await window.api.getMessages(contact.md5, startTime, endTime)
|
||||
const allowedTypes = new Set(
|
||||
SUMMARY_TYPE_OPTIONS.filter((option) => summaryMessageTypes.includes(option.value)).flatMap(
|
||||
(option) => option.messageTypes
|
||||
)
|
||||
)
|
||||
const reportMessages = rangeMessages.filter((message) => allowedTypes.has(message.type))
|
||||
if (!reportMessages.length) throw new Error('当前条件下没有可总结的消息')
|
||||
|
||||
const input = buildGroupReportInput(reportMessages, contact, isGroupChat)
|
||||
console.log('🚀 ~ AIChat ~ input:', input)
|
||||
console.log('🚀 ~ AIChat ~ input.prompt:', input.prompt)
|
||||
const result = await window.api.aiChat(
|
||||
[
|
||||
{ role: 'system', content: GROUP_REPORT_SYSTEM_PROMPT },
|
||||
{ role: 'user', content: input.prompt }
|
||||
],
|
||||
{ apiKey, model, baseURL }
|
||||
)
|
||||
|
||||
if (!result.success || !result.data) throw new Error(result.error || 'AI 请求失败')
|
||||
const report = parseGroupDailyReport(result.data, input.topSpeakers, input.activeTimeline)
|
||||
const exported = await window.api.exportGroupReport({ report, metadata: input.metadata })
|
||||
if (!exported.success || !exported.imageDataUrl || !exported.htmlPath || !exported.pngPath) {
|
||||
throw new Error(exported.error || '日报文件生成失败')
|
||||
}
|
||||
setGeneratedImage(exported.imageDataUrl)
|
||||
setReportPaths({ htmlPath: exported.htmlPath, pngPath: exported.pngPath })
|
||||
} catch (error) {
|
||||
console.error('AI Call Failed:', error)
|
||||
alert(`AI 日报生成失败:${error instanceof Error ? error.message : String(error)}`)
|
||||
} finally {
|
||||
setIsLoading(false)
|
||||
}
|
||||
}
|
||||
const handleCopyImage = async (): Promise<void> => {
|
||||
if (!generatedImage) return
|
||||
const result = await window.api.copyImage(generatedImage)
|
||||
if (result.success) {
|
||||
alert('复制成功')
|
||||
}
|
||||
}
|
||||
|
||||
const filteredMessages = React.useMemo(() => {
|
||||
return messages.filter((msg) => {
|
||||
const filterTypes = (import.meta.env.VITE_FILTER_MSG_TYPES || '')
|
||||
@@ -285,194 +242,53 @@ const ChatWindow: React.FC<ChatWindowProps> = ({
|
||||
return typeMatch && contentMatch
|
||||
})
|
||||
}, [messages, contentFilter])
|
||||
const hiddenMessageCount = Math.max(0, filteredMessages.length - MAX_RENDERED_MESSAGES)
|
||||
const renderedMessages = React.useMemo(
|
||||
() => filteredMessages.slice(-MAX_RENDERED_MESSAGES),
|
||||
[filteredMessages]
|
||||
)
|
||||
|
||||
if (!contact) {
|
||||
return (
|
||||
<div className="chat-window">
|
||||
<div className="empty-state">选择一条消息</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
if (!contact) return <EmptyConversationState />
|
||||
|
||||
const dateRangeLabel = getChatHeaderRangeLabel(dateRange)
|
||||
|
||||
return (
|
||||
<div className="chat-window">
|
||||
<div className="chat-header">
|
||||
<h2>{contact.m_nsNickName}</h2>
|
||||
<div className="window-controls"></div>
|
||||
</div>
|
||||
|
||||
<div className="message-list wechat-message-list">
|
||||
{filteredMessages.map((msg) => {
|
||||
const isMine = msg.from === 'assistant'
|
||||
const isSystem = msg.from === 'system' || msg.type === '系统消息'
|
||||
const displayName = isMine
|
||||
? '我'
|
||||
: isGroupChat
|
||||
? msg.name || msg.from
|
||||
: contact.m_nsNickName
|
||||
const avatarSrc = isMine ? msg.img : msg.img || contact.avatar
|
||||
const isVoice = msg.type === '语音'
|
||||
const isImage = msg.type === '图片'
|
||||
const isRichMedia = ['名片', '位置', '分享消息', '通话', '表情包', '系统消息'].includes(
|
||||
msg.type
|
||||
)
|
||||
|
||||
if (isSystem) {
|
||||
return (
|
||||
<div key={msg.id} className="wechat-system-message-row">
|
||||
<div className="wechat-system-message">{msg.content}</div>
|
||||
<div className="wechat-system-message-meta">{msg.datetime}</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div key={msg.id} className={`wechat-message-row ${isMine ? 'mine' : 'other'}`}>
|
||||
{!isMine && showAvatar && (
|
||||
<div className="message-avatar">
|
||||
{avatarSrc ? (
|
||||
<img src={avatarSrc} alt={displayName} referrerPolicy="no-referrer" />
|
||||
) : (
|
||||
(displayName || '?').charAt(0)
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
<div className="message-stack">
|
||||
{!isMine && isGroupChat && <div className="message-sender-name">{displayName}</div>}
|
||||
<div
|
||||
className={`message-bubble ${isVoice ? 'voice-bubble' : ''} ${isImage ? 'image-message-bubble' : ''}`}
|
||||
>
|
||||
{isVoice && msg.sessionId ? (
|
||||
<VoicePlayer
|
||||
sessionId={msg.sessionId}
|
||||
localId={msg.localId || 0}
|
||||
createTime={msg.createTime || 0}
|
||||
/>
|
||||
) : isImage && msg.contentData && msg.contentData.type === 'image' ? (
|
||||
<ImageBubble
|
||||
imageMd5={msg.contentData.md5}
|
||||
imageDatName={msg.contentData.datName}
|
||||
sessionId={msg.sessionId}
|
||||
onImageClick={openImagePreview}
|
||||
/>
|
||||
) : isRichMedia && msg.contentData ? (
|
||||
<RichMessageBubble contentData={msg.contentData} />
|
||||
) : (
|
||||
<div className="message-text">{msg.content}</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="message-meta">
|
||||
<span>{msg.datetime}</span>
|
||||
<span>{msg.type}</span>
|
||||
</div>
|
||||
</div>
|
||||
{isMine && showAvatar && (
|
||||
<div className="message-avatar mine-avatar">
|
||||
{avatarSrc ? <img src={avatarSrc} alt="我" referrerPolicy="no-referrer" /> : '我'}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
<div ref={messagesEndRef} />
|
||||
</div>
|
||||
|
||||
<div className="chat-toolbar">
|
||||
<label
|
||||
style={{ marginRight: '10px', display: 'flex', alignItems: 'center', cursor: 'pointer' }}
|
||||
>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={showAvatar}
|
||||
onChange={(e) => setShowAvatar(e.target.checked)}
|
||||
style={{ marginRight: '5px' }}
|
||||
/>
|
||||
显示头像
|
||||
</label>
|
||||
<button className="toolbar-btn" onClick={onRefresh}>
|
||||
🔄 刷新聊天记录
|
||||
</button>
|
||||
<button className="toolbar-btn" onClick={onRefreshData}>
|
||||
🔄 刷新数据
|
||||
</button>
|
||||
<button className="toolbar-btn" onClick={() => handleExport('all')}>
|
||||
📤 导出全部
|
||||
</button>
|
||||
<button className="toolbar-btn" onClick={() => handleExport(0)}>
|
||||
🕒 导出今日
|
||||
</button>
|
||||
<button className="toolbar-btn" onClick={() => handleExport(1)}>
|
||||
📅 导出昨日
|
||||
</button>
|
||||
<button className="toolbar-btn" onClick={() => handleExport(7)}>
|
||||
📅 导出近7天
|
||||
</button>
|
||||
<button className="toolbar-btn" onClick={() => handleExport(30)}>
|
||||
📅 导出近30天
|
||||
</button>
|
||||
<button className="toolbar-btn" onClick={() => setShowSettingsModal(true)}>
|
||||
🤖 AI总结群聊
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* 加载模态框 */}
|
||||
{isLoading && (
|
||||
<div className="modal-overlay">
|
||||
<div className="modal-content" style={{ textAlign: 'center', minWidth: '200px' }}>
|
||||
<div style={{ fontSize: '40px', marginBottom: '20px' }}>🤖</div>
|
||||
<div style={{ fontSize: '16px', color: '#333' }}>正在生成群聊日报...</div>
|
||||
<div style={{ fontSize: '12px', color: '#999', marginTop: '10px' }}>
|
||||
正在分析记录、处理头像并生成 HTML 和长图
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 图片预览模态框 */}
|
||||
{generatedImage && (
|
||||
<div className="modal-overlay" onClick={() => setGeneratedImage(null)}>
|
||||
<div className="modal-content image-preview-modal" onClick={(e) => e.stopPropagation()}>
|
||||
<div className="report-preview-frame">
|
||||
<div className="report-preview-scroller">
|
||||
<img
|
||||
src={generatedImage}
|
||||
alt="Generated Summary"
|
||||
className="report-preview-image"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="report-preview-actions">
|
||||
<button
|
||||
onClick={handleCopyImage}
|
||||
style={{
|
||||
padding: '8px 15px',
|
||||
cursor: 'pointer',
|
||||
backgroundColor: '#4CAF50',
|
||||
color: 'white',
|
||||
border: 'none',
|
||||
borderRadius: '4px'
|
||||
}}
|
||||
>
|
||||
📋 复制图片
|
||||
</button>
|
||||
{reportPaths && (
|
||||
<button
|
||||
onClick={() => window.api.revealGroupReport(reportPaths.pngPath)}
|
||||
style={{ padding: '5px 10px', cursor: 'pointer' }}
|
||||
>
|
||||
在文件夹中显示
|
||||
</button>
|
||||
)}
|
||||
<button
|
||||
onClick={() => setGeneratedImage(null)}
|
||||
style={{ padding: '5px 10px', cursor: 'pointer' }}
|
||||
>
|
||||
关闭
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<ChatHeader
|
||||
contact={contact}
|
||||
isGroupChat={isGroupChat}
|
||||
dateRangeLabel={dateRangeLabel}
|
||||
loadedCount={messages.length}
|
||||
filteredCount={filteredMessages.length}
|
||||
contentFilter={contentFilter || ''}
|
||||
isAiLoading={isAiLoading}
|
||||
canExport={messages.length > 0}
|
||||
onContentFilterChange={onContentFilterChange || (() => undefined)}
|
||||
onRefresh={onRefresh}
|
||||
onRefreshData={onRefreshData}
|
||||
onExport={handleExport}
|
||||
onOpenAiSettings={onCreateGroupReport || (() => undefined)}
|
||||
/>
|
||||
<DataTrustBar messageCount={messages.length} />
|
||||
<MessageList
|
||||
contact={contact}
|
||||
messages={renderedMessages}
|
||||
hiddenMessageCount={hiddenMessageCount}
|
||||
isLoadingMessages={isLoadingMessages}
|
||||
isGroupChat={isGroupChat}
|
||||
showAvatar={showAvatar}
|
||||
listRef={messageListRef}
|
||||
bottomRef={messagesEndRef}
|
||||
onScroll={handleMessageListScroll}
|
||||
onImageClick={openImagePreview}
|
||||
/>
|
||||
<ChatStatusBar
|
||||
count={renderedMessages.length}
|
||||
showAvatar={showAvatar}
|
||||
isAtLatest={isAtLatest}
|
||||
onShowAvatarChange={setShowAvatar}
|
||||
onJumpToLatest={scrollToBottom}
|
||||
/>
|
||||
|
||||
{previewImage && (
|
||||
<div className="image-viewer-overlay" onClick={closeImagePreview}>
|
||||
@@ -503,6 +319,7 @@ const ChatWindow: React.FC<ChatWindowProps> = ({
|
||||
</button>
|
||||
</div>
|
||||
<div
|
||||
ref={imageViewerStageRef}
|
||||
className="image-viewer-stage"
|
||||
onWheel={handleViewerWheel}
|
||||
onMouseDown={handleViewerMouseDown}
|
||||
@@ -522,100 +339,6 @@ const ChatWindow: React.FC<ChatWindowProps> = ({
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* AI Settings Modal */}
|
||||
{showSettingsModal && (
|
||||
<div className="modal-overlay" onClick={() => setShowSettingsModal(false)}>
|
||||
<div className="modal-content ai-settings-modal" onClick={(e) => e.stopPropagation()}>
|
||||
<h3>AI 设置</h3>
|
||||
<div className="ai-filter-section">
|
||||
<div className="ai-filter-label">时间范围</div>
|
||||
<div className="ai-date-options">
|
||||
{SUMMARY_DATE_OPTIONS.map((option) => (
|
||||
<label
|
||||
key={option.value}
|
||||
className={summaryDateRange === option.value ? 'selected' : ''}
|
||||
>
|
||||
<input
|
||||
type="radio"
|
||||
name="summary-date-range"
|
||||
value={option.value}
|
||||
checked={summaryDateRange === option.value}
|
||||
onChange={() => setSummaryDateRange(option.value)}
|
||||
/>
|
||||
{option.label}
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<div className="ai-filter-section">
|
||||
<div className="ai-filter-label">消息类型</div>
|
||||
<div className="ai-type-options">
|
||||
{SUMMARY_TYPE_OPTIONS.map((option) => (
|
||||
<label key={option.value}>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={summaryMessageTypes.includes(option.value)}
|
||||
onChange={() => toggleSummaryMessageType(option.value)}
|
||||
/>
|
||||
{option.label}
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<div className="form-group" style={{ marginBottom: '15px' }}>
|
||||
<label style={{ display: 'block', marginBottom: '5px' }}>模型服务:</label>
|
||||
<select
|
||||
value={model}
|
||||
onChange={(e) => setModel(e.target.value)}
|
||||
style={{ width: '100%', padding: '8px' }}
|
||||
>
|
||||
<option value="deepseek-chat">DeepSeek Chat</option>
|
||||
<option value="gpt-4o">GPT-4o</option>
|
||||
<option value="gpt-4o-mini">GPT-4o Mini</option>
|
||||
<option value="gpt-4-turbo">GPT-4 Turbo</option>
|
||||
<option value="claude-3-5-sonnet-20240620">Claude 3.5 Sonnet</option>
|
||||
<option value="moonshot-v1-8k">Moonshot V1</option>
|
||||
</select>
|
||||
</div>
|
||||
<div className="form-group" style={{ marginBottom: '15px' }}>
|
||||
<label style={{ display: 'block', marginBottom: '5px' }}>Base URL:</label>
|
||||
<input
|
||||
type="text"
|
||||
value={baseURL}
|
||||
onChange={(e) => setBaseURL(e.target.value)}
|
||||
placeholder="https://api.deepseek.com"
|
||||
style={{ width: '95%', padding: '8px' }}
|
||||
/>
|
||||
</div>
|
||||
<div className="form-group" style={{ marginBottom: '20px' }}>
|
||||
<label style={{ display: 'block', marginBottom: '5px' }}>API Key:</label>
|
||||
<input
|
||||
type="password"
|
||||
value={apiKey}
|
||||
onChange={(e) => setApiKey(e.target.value)}
|
||||
placeholder="Enter your API Key"
|
||||
style={{ width: '95%', padding: '8px' }}
|
||||
/>
|
||||
</div>
|
||||
<div style={{ display: 'flex', justifyContent: 'flex-end', gap: '10px' }}>
|
||||
<button onClick={() => setShowSettingsModal(false)}>取消</button>
|
||||
<button
|
||||
onClick={handleSaveSettings}
|
||||
style={{
|
||||
backgroundColor: '#4CAF50',
|
||||
color: 'white',
|
||||
border: 'none',
|
||||
padding: '8px 15px',
|
||||
borderRadius: '4px'
|
||||
}}
|
||||
>
|
||||
生成总结
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -18,7 +18,9 @@ export function ImageBubble({
|
||||
}: ImageBubbleProps): JSX.Element {
|
||||
const [imageUrl, setImageUrl] = useState<string | null>(null)
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [upgrading, setUpgrading] = useState(false)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [isThumbnail, setIsThumbnail] = useState(false)
|
||||
const containerRef = useRef<HTMLDivElement>(null)
|
||||
|
||||
const loadImage = useCallback(async () => {
|
||||
@@ -31,22 +33,18 @@ export function ImageBubble({
|
||||
setLoading(true)
|
||||
try {
|
||||
const result = await window.api.getImage(imageMd5, imageDatName || isThumb, sessionId)
|
||||
if (result.success && result.data) {
|
||||
// 验证返回的是否是有效的图片 data URL
|
||||
if (result.data.startsWith('data:image/')) {
|
||||
setImageUrl(result.data)
|
||||
setError(null)
|
||||
} else {
|
||||
// 解密后不是有效图片格式,显示未解密
|
||||
setError('未解密')
|
||||
}
|
||||
if (result.success && result.data?.startsWith('data:image/')) {
|
||||
setImageUrl(result.data)
|
||||
setIsThumbnail(Boolean(result.isThumb))
|
||||
setError(null)
|
||||
} else {
|
||||
setError(result.error || '加载图片失败')
|
||||
}
|
||||
} catch {
|
||||
setError('加载图片失败')
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
setLoading(false)
|
||||
}, [imageMd5, imageDatName, sessionId, isThumb, imageUrl, loading])
|
||||
|
||||
useEffect(() => {
|
||||
@@ -71,22 +69,49 @@ export function ImageBubble({
|
||||
|
||||
const handleCopy = async (event: MouseEvent): Promise<void> => {
|
||||
event.stopPropagation()
|
||||
if (imageUrl) {
|
||||
await window.api.copyImage(imageUrl)
|
||||
alert('图片已复制')
|
||||
}
|
||||
if (!imageUrl) return
|
||||
await window.api.copyImage(imageUrl)
|
||||
alert('图片已复制')
|
||||
}
|
||||
|
||||
const handleClick = (): void => {
|
||||
if (imageUrl) {
|
||||
onImageClick?.(imageUrl)
|
||||
const handleClick = async (): Promise<void> => {
|
||||
if (!imageUrl && !error) return
|
||||
if (!imageMd5 && !imageDatName) {
|
||||
if (imageUrl) onImageClick?.(imageUrl)
|
||||
return
|
||||
}
|
||||
|
||||
if (upgrading) {
|
||||
if (imageUrl) onImageClick?.(imageUrl)
|
||||
return
|
||||
}
|
||||
|
||||
setUpgrading(true)
|
||||
try {
|
||||
const result = await window.api.getImage(imageMd5, imageDatName || isThumb, sessionId, {
|
||||
force: true
|
||||
})
|
||||
if (result.success && result.data?.startsWith('data:image/')) {
|
||||
setImageUrl(result.data)
|
||||
setIsThumbnail(Boolean(result.isThumb))
|
||||
setError(null)
|
||||
onImageClick?.(result.data)
|
||||
return
|
||||
}
|
||||
} catch {
|
||||
// Fall back to the already visible image.
|
||||
} finally {
|
||||
setUpgrading(false)
|
||||
}
|
||||
|
||||
if (imageUrl) onImageClick?.(imageUrl)
|
||||
}
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="image-bubble image-loading" onClick={handleClick}>
|
||||
<div className="image-loading-spinner">加载中...</div>
|
||||
<div className="image-loading-skeleton" aria-hidden />
|
||||
<div className="image-quality-badge">加载中</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -94,7 +119,8 @@ export function ImageBubble({
|
||||
if (error) {
|
||||
return (
|
||||
<div className="image-bubble image-error" onClick={loadImage}>
|
||||
<div className="image-error-text">图片未加载</div>
|
||||
<div className="image-error-text">{error || '图片未缓存'}</div>
|
||||
<div className="image-quality-badge">加载失败</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -102,8 +128,8 @@ export function ImageBubble({
|
||||
if (!imageUrl) {
|
||||
return (
|
||||
<div ref={containerRef} className="image-bubble image-placeholder">
|
||||
<div className="image-placeholder-icon">🖼</div>
|
||||
<div className="image-placeholder-text">加载图片中</div>
|
||||
<div className="image-loading-skeleton" aria-hidden />
|
||||
<div className="image-quality-badge">加载中</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -111,9 +137,12 @@ export function ImageBubble({
|
||||
return (
|
||||
<div className="image-bubble image-loaded" onClick={handleClick}>
|
||||
<img src={imageUrl} alt="图片" className="image-content" />
|
||||
{(upgrading || isThumbnail) && (
|
||||
<div className="image-quality-badge">{upgrading ? '正在查找原图' : '缩略图'}</div>
|
||||
)}
|
||||
<div className="image-actions">
|
||||
<button className="image-action-btn" onClick={handleCopy} title="复制图片">
|
||||
📋
|
||||
复制
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { ParsedContent } from '../../../shared/types'
|
||||
import { useEffect, useState } from 'react'
|
||||
import type { JSX, MouseEvent } from 'react'
|
||||
import { renderWechatEmojiText } from '../utils/wechatEmojiText'
|
||||
|
||||
const stickerDataUrlCache = new Map<string, string>()
|
||||
|
||||
@@ -26,7 +27,9 @@ export function RichMessageBubble({ contentData }: RichMessageBubbleProps): JSX.
|
||||
return <SystemBubble data={contentData} />
|
||||
case 'unknown':
|
||||
return (
|
||||
<div className="message-text">{(contentData as { raw?: string }).raw || '[未知消息]'}</div>
|
||||
<div className="message-text">
|
||||
{renderWechatEmojiText((contentData as { raw?: string }).raw || '[未知消息]')}
|
||||
</div>
|
||||
)
|
||||
default:
|
||||
return <div className="message-text">[不支持的消息类型]</div>
|
||||
@@ -51,7 +54,7 @@ function LocationBubble({
|
||||
|
||||
return (
|
||||
<div className="location-message" onClick={hasCoords ? handleClick : undefined}>
|
||||
<div className="location-icon">📍</div>
|
||||
<div className="location-icon">位置</div>
|
||||
<div className="location-info">
|
||||
<div className="location-name">{locationText}</div>
|
||||
{label && poiname && label !== poiname && <div className="location-label">{label}</div>}
|
||||
@@ -123,7 +126,7 @@ function VoipBubble({ data }: { data: Extract<ParsedContent, { type: 'voip' }> }
|
||||
|
||||
return (
|
||||
<div className="voip-message">
|
||||
<span className="voip-icon">{isVideo ? '📹' : '📞'}</span>
|
||||
<span className="voip-icon">{isVideo ? '视频' : '通话'}</span>
|
||||
<span className="voip-status">
|
||||
{status}
|
||||
{duration ? ` ${formatDuration(duration)}` : ''}
|
||||
@@ -207,15 +210,15 @@ function QuoteBubble({ data }: { data: Extract<ParsedContent, { type: 'quote' }>
|
||||
<div className="quote-message">
|
||||
<div className="quoted-message">
|
||||
{quotedSender && <span className="quoted-sender">{quotedSender}</span>}
|
||||
<span className="quoted-text">{quotedText}</span>
|
||||
<span className="quoted-text">{renderWechatEmojiText(quotedText, 18)}</span>
|
||||
</div>
|
||||
{replyText && <div className="quote-reply">{replyText}</div>}
|
||||
{replyText && <div className="quote-reply">{renderWechatEmojiText(replyText)}</div>}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function SystemBubble({ data }: { data: Extract<ParsedContent, { type: 'system' }> }): JSX.Element {
|
||||
return <div className="message-text">{data.content || '[系统消息]'}</div>
|
||||
return <div className="message-text">{renderWechatEmojiText(data.content || '[系统消息]')}</div>
|
||||
}
|
||||
|
||||
function getUrlHost(url?: string): string {
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
// Legacy fallback: SETTINGS-01 moved the default entry to features/settings.
|
||||
// Keep this panel intact until its database-key, image-key, AI and API sections are migrated.
|
||||
import React, { useEffect, useState } from 'react'
|
||||
|
||||
interface SelfInfo {
|
||||
@@ -12,6 +14,9 @@ interface AppSettings {
|
||||
apiEnabled: boolean
|
||||
apiHost: string
|
||||
apiPort: number
|
||||
imageKeyRoot: string
|
||||
imageXorKey: string
|
||||
imageAesKey: string
|
||||
}
|
||||
|
||||
interface ApiState {
|
||||
@@ -21,25 +26,50 @@ interface ApiState {
|
||||
error?: string
|
||||
}
|
||||
|
||||
interface AiModelConfig {
|
||||
apiKey: string
|
||||
baseURL: string
|
||||
model: string
|
||||
}
|
||||
|
||||
interface SettingsPanelProps {
|
||||
open: boolean
|
||||
selfInfo: SelfInfo | null
|
||||
dbReady: boolean
|
||||
dbKey: string
|
||||
aiModelConfig: AiModelConfig
|
||||
onClose: () => void
|
||||
onDbKeyChange: (key: string) => void
|
||||
onAiModelConfigChange: (config: AiModelConfig) => void
|
||||
onSaveAiModelConfig: () => void
|
||||
onDbRootChanged: () => void
|
||||
}
|
||||
|
||||
const AI_MODEL_OPTIONS = [
|
||||
{ value: 'deepseek-chat', label: 'DeepSeek Chat' },
|
||||
{ value: 'gpt-4o', label: 'GPT-4o' },
|
||||
{ value: 'gpt-4o-mini', label: 'GPT-4o Mini' },
|
||||
{ value: 'gpt-4-turbo', label: 'GPT-4 Turbo' },
|
||||
{ value: 'claude-3-5-sonnet-20240620', label: 'Claude 3.5 Sonnet' },
|
||||
{ value: 'moonshot-v1-8k', label: 'Moonshot V1' }
|
||||
]
|
||||
|
||||
export const SettingsPanel: React.FC<SettingsPanelProps> = ({
|
||||
open,
|
||||
selfInfo,
|
||||
dbReady,
|
||||
dbKey,
|
||||
aiModelConfig,
|
||||
onClose,
|
||||
onDbKeyChange,
|
||||
onAiModelConfigChange,
|
||||
onSaveAiModelConfig,
|
||||
onDbRootChanged
|
||||
}) => {
|
||||
const isWindows = window.electron.process.platform === 'win32'
|
||||
const dbRootPlaceholder = isWindows
|
||||
? 'C:\\Users\\你\\Documents\\WeChat Files'
|
||||
: '~/Library/Containers/com.tencent.xinWeChat/Data/Documents/xwechat_files'
|
||||
const [settings, setSettings] = useState<AppSettings | null>(null)
|
||||
const [settingsPath, setSettingsPath] = useState('')
|
||||
const [apiState, setApiState] = useState<ApiState | null>(null)
|
||||
@@ -47,6 +77,10 @@ export const SettingsPanel: React.FC<SettingsPanelProps> = ({
|
||||
{ kind: 'idle' | 'ok' | 'fail'; message: string; wxid?: string; accountRoot?: string }
|
||||
>({ kind: 'idle', message: '' })
|
||||
const [reopenStatus, setReopenStatus] = useState<string>('')
|
||||
const [imageKeyStatus, setImageKeyStatus] = useState<{
|
||||
kind: 'idle' | 'ok' | 'fail'
|
||||
message: string
|
||||
}>({ kind: 'idle', message: '' })
|
||||
const [busy, setBusy] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
@@ -54,6 +88,13 @@ export const SettingsPanel: React.FC<SettingsPanelProps> = ({
|
||||
void refresh()
|
||||
}, [open])
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return
|
||||
return window.api.onImageKeyStatus(({ message }) => {
|
||||
setImageKeyStatus({ kind: 'idle', message })
|
||||
})
|
||||
}, [open])
|
||||
|
||||
async function refresh(): Promise<void> {
|
||||
const [{ settings, settingsPath }, api] = await Promise.all([
|
||||
window.api.getSettings(),
|
||||
@@ -136,6 +177,37 @@ export const SettingsPanel: React.FC<SettingsPanelProps> = ({
|
||||
setBusy(false)
|
||||
}
|
||||
|
||||
async function handleAutoGetImageKey(): Promise<void> {
|
||||
if (!settings) return
|
||||
setBusy(true)
|
||||
setImageKeyStatus({ kind: 'idle', message: '正在扫描微信内存获取图片密钥...' })
|
||||
try {
|
||||
const result = await window.api.autoGetImageKey()
|
||||
if (!result.success || !result.aesKey) {
|
||||
setImageKeyStatus({ kind: 'fail', message: result.error || '图片密钥获取失败' })
|
||||
return
|
||||
}
|
||||
const imageXorKey =
|
||||
result.imageXorKey ||
|
||||
(typeof result.xorKey === 'number'
|
||||
? `0x${result.xorKey.toString(16).toUpperCase().padStart(2, '0')}`
|
||||
: settings.imageXorKey)
|
||||
const imageAesKey = result.imageAesKey || result.aesKey
|
||||
setSettings(result.settings || { ...settings, imageXorKey, imageAesKey })
|
||||
setImageKeyStatus({
|
||||
kind: 'ok',
|
||||
message: result.verified ? '图片密钥已获取并校验通过' : '图片密钥已获取,未完成模板校验'
|
||||
})
|
||||
} catch (error) {
|
||||
setImageKeyStatus({
|
||||
kind: 'fail',
|
||||
message: error instanceof Error ? error.message : String(error)
|
||||
})
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="settings-overlay" onClick={onClose}>
|
||||
<div className="settings-modal" onClick={(e) => e.stopPropagation()}>
|
||||
@@ -208,7 +280,61 @@ export const SettingsPanel: React.FC<SettingsPanelProps> = ({
|
||||
/>
|
||||
</div>
|
||||
<div className="settings-hint">
|
||||
密钥保存在本机 macOS Keychain(safeStorage 加密),不会上传任何服务器。
|
||||
密钥通过系统 safeStorage 加密保存在本机,不会上传任何服务器。
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{/* 图片解密密钥 */}
|
||||
<section className="settings-section">
|
||||
<div className="settings-section-title">图片解密密钥</div>
|
||||
<div className="settings-row">
|
||||
<input
|
||||
type="text"
|
||||
className="settings-input"
|
||||
value={settings?.imageKeyRoot || settings?.dbRoot || ''}
|
||||
onChange={(e) =>
|
||||
setSettings(settings ? { ...settings, imageKeyRoot: e.target.value } : null)
|
||||
}
|
||||
onBlur={(e) => handleSave({ imageKeyRoot: e.target.value })}
|
||||
placeholder={dbRootPlaceholder}
|
||||
spellCheck={false}
|
||||
/>
|
||||
</div>
|
||||
<div className="settings-row">
|
||||
<input
|
||||
type="text"
|
||||
className="settings-input settings-input-quarter"
|
||||
value={settings?.imageXorKey ?? ''}
|
||||
onChange={(e) =>
|
||||
setSettings(settings ? { ...settings, imageXorKey: e.target.value } : null)
|
||||
}
|
||||
onBlur={(e) => handleSave({ imageXorKey: e.target.value })}
|
||||
placeholder="XOR Key,如 0x40"
|
||||
spellCheck={false}
|
||||
/>
|
||||
<input
|
||||
type="text"
|
||||
className="settings-input"
|
||||
value={settings?.imageAesKey ?? ''}
|
||||
onChange={(e) =>
|
||||
setSettings(settings ? { ...settings, imageAesKey: e.target.value } : null)
|
||||
}
|
||||
onBlur={(e) => handleSave({ imageAesKey: e.target.value })}
|
||||
placeholder="AES Key,16 位字符"
|
||||
spellCheck={false}
|
||||
/>
|
||||
<button className="settings-btn" onClick={handleAutoGetImageKey} disabled={busy}>
|
||||
内存扫描图片密钥
|
||||
</button>
|
||||
</div>
|
||||
{imageKeyStatus.message && (
|
||||
<div className={`settings-status ${imageKeyStatus.kind}`}>
|
||||
{imageKeyStatus.kind === 'ok' ? '✓ ' : imageKeyStatus.kind === 'fail' ? '✗ ' : ''}
|
||||
{imageKeyStatus.message}
|
||||
</div>
|
||||
)}
|
||||
<div className="settings-hint">
|
||||
目录默认使用数据库根目录,用于查找图片模板文件。Windows 会直接扫描微信内存,请先在微信中打开 2-3 张图片大图。
|
||||
</div>
|
||||
</section>
|
||||
|
||||
@@ -222,7 +348,7 @@ export const SettingsPanel: React.FC<SettingsPanelProps> = ({
|
||||
value={settings?.dbRoot ?? ''}
|
||||
onChange={(e) => setSettings(settings ? { ...settings, dbRoot: e.target.value } : null)}
|
||||
onBlur={(e) => handleSave({ dbRoot: e.target.value })}
|
||||
placeholder="~/Library/Containers/com.tencent.xinWeChat/Data/Documents/xwechat_files"
|
||||
placeholder={dbRootPlaceholder}
|
||||
spellCheck={false}
|
||||
/>
|
||||
</div>
|
||||
@@ -237,7 +363,57 @@ export const SettingsPanel: React.FC<SettingsPanelProps> = ({
|
||||
{reopenStatus && <span className="settings-status">{reopenStatus}</span>}
|
||||
</div>
|
||||
<div className="settings-hint">
|
||||
指向 xwechat_files 目录,内部包含 db_storage/。修改后需重新初始化才能生效。
|
||||
可填写微信数据总目录或具体账号目录。Windows 通常是 Documents\WeChat Files,macOS 通常是 xwechat_files;程序会自动选择包含 db_storage/session.db 的账号目录。
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="settings-section">
|
||||
<div className="settings-section-title">AI 模型配置</div>
|
||||
<div className="settings-row">
|
||||
<select
|
||||
className="settings-input settings-input-half"
|
||||
value={aiModelConfig.model}
|
||||
onChange={(event) =>
|
||||
onAiModelConfigChange({ ...aiModelConfig, model: event.target.value })
|
||||
}
|
||||
>
|
||||
{AI_MODEL_OPTIONS.map((option) => (
|
||||
<option key={option.value} value={option.value}>
|
||||
{option.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<button className="settings-btn" onClick={onSaveAiModelConfig}>
|
||||
保存 AI 配置
|
||||
</button>
|
||||
</div>
|
||||
<div className="settings-row">
|
||||
<input
|
||||
type="text"
|
||||
className="settings-input"
|
||||
value={aiModelConfig.baseURL}
|
||||
onChange={(event) =>
|
||||
onAiModelConfigChange({ ...aiModelConfig, baseURL: event.target.value })
|
||||
}
|
||||
placeholder="https://api.deepseek.com"
|
||||
spellCheck={false}
|
||||
/>
|
||||
</div>
|
||||
<div className="settings-row">
|
||||
<input
|
||||
type="password"
|
||||
className="settings-input"
|
||||
value={aiModelConfig.apiKey}
|
||||
onChange={(event) =>
|
||||
onAiModelConfigChange({ ...aiModelConfig, apiKey: event.target.value })
|
||||
}
|
||||
placeholder="API Key"
|
||||
spellCheck={false}
|
||||
/>
|
||||
</div>
|
||||
<div className="settings-hint">
|
||||
所选内容会发送至你配置的模型服务进行处理。配置沿用原有本地
|
||||
localStorage 保存方式。
|
||||
</div>
|
||||
</section>
|
||||
|
||||
|
||||
@@ -1,151 +1,6 @@
|
||||
import React, { useState } from 'react'
|
||||
import { Contact } from '../../../shared/types'
|
||||
import React from 'react'
|
||||
import { ConversationSidebar, ConversationSidebarProps } from './conversation/ConversationSidebar'
|
||||
|
||||
interface SelfInfo {
|
||||
wxid: string
|
||||
nickname: string
|
||||
avatar?: string
|
||||
accountRoot: string
|
||||
}
|
||||
|
||||
interface SidebarProps {
|
||||
contacts: Contact[]
|
||||
selectedContact: Contact | null
|
||||
onSelectContact: (contact: Contact) => void
|
||||
onSearch: (keyword: string) => void
|
||||
onContentFilter: (keyword: string) => void
|
||||
width: number
|
||||
dateRange: string
|
||||
onDateRangeChange: (range: string) => void
|
||||
selfInfo: SelfInfo | null
|
||||
dbReady: boolean
|
||||
onOpenSettings: () => void
|
||||
}
|
||||
|
||||
export const Sidebar: React.FC<SidebarProps> = ({
|
||||
contacts,
|
||||
selectedContact,
|
||||
onSelectContact,
|
||||
onSearch,
|
||||
onContentFilter,
|
||||
width,
|
||||
dateRange,
|
||||
onDateRangeChange,
|
||||
selfInfo,
|
||||
dbReady,
|
||||
onOpenSettings
|
||||
}) => {
|
||||
const [searchTerm, setSearchTerm] = useState('')
|
||||
const [contentFilter, setContentFilter] = useState('')
|
||||
const [isGroupsExpanded, setIsGroupsExpanded] = useState(true)
|
||||
const [isContactsExpanded, setIsContactsExpanded] = useState(true)
|
||||
|
||||
const handleSearchChange = (e: React.ChangeEvent<HTMLInputElement>): void => {
|
||||
const term = e.target.value
|
||||
setSearchTerm(term)
|
||||
onSearch(term)
|
||||
}
|
||||
|
||||
const handleContentFilterChange = (e: React.ChangeEvent<HTMLInputElement>): void => {
|
||||
const term = e.target.value
|
||||
setContentFilter(term)
|
||||
onContentFilter(term)
|
||||
}
|
||||
|
||||
const groups = contacts.filter((c) => c.type === 'group')
|
||||
const users = contacts.filter((c) => c.type === 'user')
|
||||
|
||||
const renderContactItem = (contact: Contact): React.ReactElement => (
|
||||
<div
|
||||
key={contact.md5}
|
||||
className={`contact-item ${selectedContact?.md5 === contact.md5 ? 'active' : ''}`}
|
||||
onClick={() => onSelectContact(contact)}
|
||||
>
|
||||
<div className="contact-avatar">
|
||||
{contact.avatar ? (
|
||||
<img src={contact.avatar} alt={contact.m_nsNickName} referrerPolicy="no-referrer" />
|
||||
) : (
|
||||
(contact.m_nsNickName || contact.m_nsUsrName || '?').charAt(0)
|
||||
)}
|
||||
</div>
|
||||
<div className="contact-info">
|
||||
<div className="contact-name">{contact.m_nsNickName}</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
|
||||
return (
|
||||
<div className="sidebar" style={{ width: width }}>
|
||||
<div className="sidebar-header">
|
||||
<input
|
||||
type="text"
|
||||
className="search-input"
|
||||
placeholder="搜索联系人"
|
||||
value={searchTerm}
|
||||
onChange={handleSearchChange}
|
||||
style={{ marginBottom: '8px' }}
|
||||
/>
|
||||
<input
|
||||
type="text"
|
||||
className="search-input"
|
||||
placeholder="过滤消息内容"
|
||||
value={contentFilter}
|
||||
onChange={handleContentFilterChange}
|
||||
/>
|
||||
<div className="date-range-selector">
|
||||
{[
|
||||
{ key: 'today', label: '当天' },
|
||||
{ key: 'yesterday', label: '昨日' },
|
||||
{ key: '7', label: '近7天' },
|
||||
{ key: '30', label: '近30天' },
|
||||
{ key: 'all', label: '所有' }
|
||||
].map((item) => (
|
||||
<button
|
||||
key={item.key}
|
||||
className={`range-btn ${dateRange === item.key ? 'active' : ''}`}
|
||||
onClick={() => onDateRangeChange(item.key)}
|
||||
title={item.label}
|
||||
>
|
||||
{item.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<div className="contact-list">
|
||||
{/* 群聊部分 */}
|
||||
<div className="section-header" onClick={() => setIsGroupsExpanded(!isGroupsExpanded)}>
|
||||
<span className="arrow">{isGroupsExpanded ? '▼' : '▶'}</span> 群聊 ({groups.length})
|
||||
</div>
|
||||
{isGroupsExpanded && groups.map(renderContactItem)}
|
||||
{isGroupsExpanded && groups.length === 0 && <div className="section-empty">暂无群聊</div>}
|
||||
|
||||
{/* 联系人部分 */}
|
||||
<div className="section-header" onClick={() => setIsContactsExpanded(!isContactsExpanded)}>
|
||||
<span className="arrow">{isContactsExpanded ? '▼' : '▶'}</span> 联系人 ({users.length})
|
||||
</div>
|
||||
{isContactsExpanded && users.map(renderContactItem)}
|
||||
{isContactsExpanded && users.length === 0 && (
|
||||
<div className="section-empty">暂无联系人</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="sidebar-footer" onClick={onOpenSettings} title="设置">
|
||||
<div className="sidebar-self-avatar">
|
||||
{selfInfo?.avatar ? (
|
||||
<img src={selfInfo.avatar} alt={selfInfo.nickname} referrerPolicy="no-referrer" />
|
||||
) : (
|
||||
((selfInfo?.nickname || selfInfo?.wxid || '我').charAt(0))
|
||||
)}
|
||||
</div>
|
||||
<div className="sidebar-self-info">
|
||||
<div className="sidebar-self-nickname">
|
||||
{dbReady && selfInfo ? selfInfo.nickname || selfInfo.wxid || '我' : '未连接'}
|
||||
</div>
|
||||
<div className="sidebar-self-wxid">
|
||||
{dbReady && selfInfo ? selfInfo.wxid : '点击设置 →'}
|
||||
</div>
|
||||
</div>
|
||||
<div className="sidebar-self-arrow" aria-hidden>⚙</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
export const Sidebar: React.FC<ConversationSidebarProps> = (props) => (
|
||||
<ConversationSidebar {...props} />
|
||||
)
|
||||
|
||||
@@ -176,7 +176,7 @@ export function VoicePlayer({
|
||||
return (
|
||||
<div className="voice-message voice-error" onClick={handlePlayPause}>
|
||||
<span className="voice-icon">▶</span>
|
||||
<span className="voice-error-text">[语音]</span>
|
||||
<span className="voice-error-text">当前版本暂不支持播放</span>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
import React from 'react'
|
||||
|
||||
interface SelfInfo {
|
||||
wxid: string
|
||||
nickname: string
|
||||
avatar?: string
|
||||
accountRoot: string
|
||||
}
|
||||
|
||||
interface AccountSummaryProps {
|
||||
selfInfo: SelfInfo | null
|
||||
dbReady: boolean
|
||||
compact?: boolean
|
||||
onClick?: () => void
|
||||
}
|
||||
|
||||
export function AccountSummary({
|
||||
selfInfo,
|
||||
dbReady,
|
||||
compact = false,
|
||||
onClick
|
||||
}: AccountSummaryProps): React.ReactElement {
|
||||
const displayName =
|
||||
dbReady && selfInfo ? selfInfo.nickname || selfInfo.wxid || '当前账号' : '未连接'
|
||||
const subtitle = dbReady && selfInfo ? selfInfo.wxid : '打开设置'
|
||||
const statusText = dbReady ? '数据库已连接' : '数据库未连接'
|
||||
const initial = (displayName || '?').charAt(0)
|
||||
const title = `${displayName}\n${subtitle}`
|
||||
const avatar = (
|
||||
<span className="account-summary-avatar">
|
||||
{selfInfo?.avatar ? (
|
||||
<img src={selfInfo.avatar} alt={displayName} referrerPolicy="no-referrer" />
|
||||
) : (
|
||||
initial
|
||||
)}
|
||||
<span className={`account-summary-status ${dbReady ? 'ready' : ''}`} aria-hidden />
|
||||
</span>
|
||||
)
|
||||
|
||||
if (compact) {
|
||||
return (
|
||||
<button type="button" className="account-summary compact" onClick={onClick} title={title}>
|
||||
{avatar}
|
||||
</button>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="account-summary" title={title}>
|
||||
{avatar}
|
||||
<span className="account-summary-text">
|
||||
<span className="account-summary-name">{displayName}</span>
|
||||
<span className="account-summary-meta">{subtitle}</span>
|
||||
<span className="account-summary-state">
|
||||
<span className={`account-summary-state-dot ${dbReady ? 'ready' : ''}`} aria-hidden />
|
||||
{statusText}
|
||||
</span>
|
||||
</span>
|
||||
<button type="button" className="account-summary-settings" onClick={onClick} title="设置">
|
||||
<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
||||
<path d="M12 8.5a3.5 3.5 0 1 0 0 7 3.5 3.5 0 0 0 0-7Z" />
|
||||
<path d="M19.4 15a8.2 8.2 0 0 0 .1-1l2-1.5-2-3.5-2.4 1a7.5 7.5 0 0 0-1.7-1l-.3-2.5h-4l-.4 2.5a7.5 7.5 0 0 0-1.7 1l-2.3-1-2 3.5 2 1.5a8.2 8.2 0 0 0 0 2l-2 1.5 2 3.5 2.3-1a7.5 7.5 0 0 0 1.7 1l.4 2.5h4l.3-2.5a7.5 7.5 0 0 0 1.7-1l2.4 1 2-3.5-2.1-1.5Z" />
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
import React, { useEffect, useRef, useState } from 'react'
|
||||
import { Contact } from '../../../../shared/types'
|
||||
import { ConversationContentSearch } from './ConversationContentSearch'
|
||||
import { ExportMenu, ExportRange } from './ExportMenu'
|
||||
import { AiIcon, MoreIcon, RefreshIcon, SearchIcon } from './icons'
|
||||
|
||||
interface ChatHeaderProps {
|
||||
contact: Contact
|
||||
isGroupChat: boolean
|
||||
dateRangeLabel: string
|
||||
loadedCount: number
|
||||
filteredCount: number
|
||||
contentFilter: string
|
||||
isAiLoading: boolean
|
||||
canExport: boolean
|
||||
onContentFilterChange: (value: string) => void
|
||||
onRefresh?: () => void
|
||||
onRefreshData?: () => void
|
||||
onExport: (range: ExportRange) => void
|
||||
onOpenAiSettings: () => void
|
||||
}
|
||||
|
||||
export function ChatHeader({
|
||||
contact,
|
||||
isGroupChat,
|
||||
dateRangeLabel,
|
||||
loadedCount,
|
||||
filteredCount,
|
||||
contentFilter,
|
||||
isAiLoading,
|
||||
canExport,
|
||||
onContentFilterChange,
|
||||
onRefresh,
|
||||
onRefreshData,
|
||||
onExport,
|
||||
onOpenAiSettings
|
||||
}: ChatHeaderProps): React.ReactElement {
|
||||
const [searchOpen, setSearchOpen] = useState(Boolean(contentFilter))
|
||||
const [moreOpen, setMoreOpen] = useState(false)
|
||||
const moreRef = useRef<HTMLDivElement>(null)
|
||||
const displayName = contact.m_nsNickName || contact.m_nsUsrName || '未命名会话'
|
||||
const typeLabel = isGroupChat ? '群聊' : '联系人'
|
||||
const visibleCount = contentFilter ? filteredCount : loadedCount
|
||||
|
||||
useEffect(() => {
|
||||
if (!moreOpen) return
|
||||
const handlePointerDown = (event: PointerEvent): void => {
|
||||
if (!moreRef.current?.contains(event.target as Node)) setMoreOpen(false)
|
||||
}
|
||||
window.addEventListener('pointerdown', handlePointerDown)
|
||||
return () => window.removeEventListener('pointerdown', handlePointerDown)
|
||||
}, [moreOpen])
|
||||
|
||||
const handleCloseSearch = (): void => {
|
||||
onContentFilterChange('')
|
||||
setSearchOpen(false)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="chat-archive-header">
|
||||
<div className="chat-title-block">
|
||||
<div className="chat-title-avatar">
|
||||
{contact.avatar ? (
|
||||
<img src={contact.avatar} alt={displayName} referrerPolicy="no-referrer" />
|
||||
) : (
|
||||
displayName.charAt(0)
|
||||
)}
|
||||
</div>
|
||||
<div className="chat-title-text">
|
||||
<h2>{displayName}</h2>
|
||||
<div className="chat-title-meta">
|
||||
<span>{typeLabel}</span>
|
||||
<span>{dateRangeLabel}</span>
|
||||
<span>{visibleCount} 条消息</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="chat-header-actions">
|
||||
{searchOpen ? (
|
||||
<ConversationContentSearch
|
||||
value={contentFilter}
|
||||
resultCount={filteredCount}
|
||||
onChange={onContentFilterChange}
|
||||
onClose={handleCloseSearch}
|
||||
/>
|
||||
) : (
|
||||
<button
|
||||
type="button"
|
||||
className="chat-icon-button"
|
||||
onClick={() => setSearchOpen(true)}
|
||||
title="搜索当前聊天"
|
||||
>
|
||||
<SearchIcon />
|
||||
</button>
|
||||
)}
|
||||
<button type="button" className="chat-icon-button" onClick={onRefresh} title="刷新聊天记录">
|
||||
<RefreshIcon />
|
||||
</button>
|
||||
<ExportMenu disabled={!canExport} onExport={onExport} />
|
||||
<div className="chat-menu" ref={moreRef}>
|
||||
<button
|
||||
type="button"
|
||||
className="chat-icon-button"
|
||||
onClick={() => setMoreOpen((current) => !current)}
|
||||
title="更多"
|
||||
>
|
||||
<MoreIcon />
|
||||
</button>
|
||||
{moreOpen && (
|
||||
<div className="chat-dropdown-menu right">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
onRefreshData?.()
|
||||
setMoreOpen(false)
|
||||
}}
|
||||
>
|
||||
刷新数据
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
className="chat-ai-button"
|
||||
onClick={onOpenAiSettings}
|
||||
disabled={isAiLoading}
|
||||
title={isGroupChat ? '生成 AI 日报' : 'AI 日报当前仅支持群聊'}
|
||||
>
|
||||
<AiIcon />
|
||||
<span>{isAiLoading ? '生成中' : '生成 AI 日报'}</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import React from 'react'
|
||||
|
||||
interface ChatStatusBarProps {
|
||||
count: number
|
||||
showAvatar: boolean
|
||||
isAtLatest: boolean
|
||||
onShowAvatarChange: (show: boolean) => void
|
||||
onJumpToLatest: () => void
|
||||
}
|
||||
|
||||
export function ChatStatusBar({
|
||||
count,
|
||||
showAvatar,
|
||||
isAtLatest,
|
||||
onShowAvatarChange,
|
||||
onJumpToLatest
|
||||
}: ChatStatusBarProps): React.ReactElement {
|
||||
const jumpDisabled = isAtLatest || count === 0
|
||||
|
||||
return (
|
||||
<div className="chat-status-bar">
|
||||
<div>已显示当前范围 {count} 条消息</div>
|
||||
<div className="chat-status-actions">
|
||||
<label className="chat-avatar-toggle">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={showAvatar}
|
||||
onChange={(event) => onShowAvatarChange(event.target.checked)}
|
||||
/>
|
||||
<span>显示头像</span>
|
||||
</label>
|
||||
<span className="chat-status-separator" aria-hidden />
|
||||
<button type="button" onClick={onJumpToLatest} disabled={jumpDisabled}>
|
||||
{jumpDisabled ? '已是最新消息' : '跳转到最新消息'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
import React from 'react'
|
||||
import { CloseIcon, SearchIcon } from './icons'
|
||||
|
||||
interface ConversationContentSearchProps {
|
||||
value: string
|
||||
resultCount: number
|
||||
onChange: (value: string) => void
|
||||
onClose: () => void
|
||||
}
|
||||
|
||||
export function ConversationContentSearch({
|
||||
value,
|
||||
resultCount,
|
||||
onChange,
|
||||
onClose
|
||||
}: ConversationContentSearchProps): React.ReactElement {
|
||||
return (
|
||||
<div className="chat-content-search">
|
||||
<span className="chat-content-search-icon">
|
||||
<SearchIcon />
|
||||
</span>
|
||||
<input
|
||||
type="text"
|
||||
value={value}
|
||||
placeholder="搜索当前聊天内容"
|
||||
onChange={(event) => onChange(event.target.value)}
|
||||
autoFocus
|
||||
/>
|
||||
<span className="chat-content-search-count">
|
||||
{value ? `${resultCount} 条结果` : '输入关键词'}
|
||||
</span>
|
||||
<button type="button" className="chat-icon-button" onClick={onClose} title="关闭搜索">
|
||||
<CloseIcon />
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import React from 'react'
|
||||
import { CheckCircleIcon, HomeIcon } from './icons'
|
||||
|
||||
interface DataTrustBarProps {
|
||||
messageCount: number
|
||||
}
|
||||
|
||||
export function DataTrustBar({ messageCount }: DataTrustBarProps): React.ReactElement {
|
||||
return (
|
||||
<div className="data-trust-bar">
|
||||
<div className="data-trust-left">
|
||||
<HomeIcon />
|
||||
<span>聊天记录仅在本机读取</span>
|
||||
</div>
|
||||
<div className="data-trust-right">
|
||||
<span className="data-trust-item">
|
||||
<CheckCircleIcon />
|
||||
数据库已连接
|
||||
</span>
|
||||
<span className="data-trust-dot" aria-hidden />
|
||||
<span>已加载 {messageCount} 条消息</span>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import React from 'react'
|
||||
|
||||
export function EmptyConversationState(): React.ReactElement {
|
||||
return (
|
||||
<div className="chat-window empty">
|
||||
<div className="empty-conversation-state">
|
||||
<h2>选择一条消息</h2>
|
||||
<p>从左侧选择群聊或联系人以浏览历史记录</p>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
import React, { useEffect, useRef, useState } from 'react'
|
||||
import { ArrowDownIcon, ExportIcon } from './icons'
|
||||
|
||||
export type ExportRange = number | 'all'
|
||||
|
||||
interface ExportMenuProps {
|
||||
disabled: boolean
|
||||
onExport: (range: ExportRange) => void
|
||||
}
|
||||
|
||||
const EXPORT_OPTIONS: { label: string; value: ExportRange }[] = [
|
||||
{ label: '导出当前范围', value: 'all' },
|
||||
{ label: '导出今天', value: 0 },
|
||||
{ label: '导出昨日', value: 1 },
|
||||
{ label: '导出近 7 天', value: 7 },
|
||||
{ label: '导出近 30 天', value: 30 },
|
||||
{ label: '导出全部', value: 'all' }
|
||||
]
|
||||
|
||||
export function ExportMenu({ disabled, onExport }: ExportMenuProps): React.ReactElement {
|
||||
const [open, setOpen] = useState(false)
|
||||
const menuRef = useRef<HTMLDivElement>(null)
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return
|
||||
const handlePointerDown = (event: PointerEvent): void => {
|
||||
if (!menuRef.current?.contains(event.target as Node)) setOpen(false)
|
||||
}
|
||||
window.addEventListener('pointerdown', handlePointerDown)
|
||||
return () => window.removeEventListener('pointerdown', handlePointerDown)
|
||||
}, [open])
|
||||
|
||||
return (
|
||||
<div className="chat-menu" ref={menuRef}>
|
||||
<button
|
||||
type="button"
|
||||
className="chat-tool-button"
|
||||
disabled={disabled}
|
||||
onClick={() => setOpen((current) => !current)}
|
||||
title={disabled ? '没有可导出的消息' : '导出聊天记录'}
|
||||
>
|
||||
<ExportIcon />
|
||||
<span>导出</span>
|
||||
<ArrowDownIcon />
|
||||
</button>
|
||||
{open && (
|
||||
<div className="chat-dropdown-menu">
|
||||
{EXPORT_OPTIONS.map((option, index) => (
|
||||
<button
|
||||
key={`${option.label}-${index}`}
|
||||
type="button"
|
||||
onClick={() => {
|
||||
onExport(option.value)
|
||||
setOpen(false)
|
||||
}}
|
||||
>
|
||||
{option.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
import React from 'react'
|
||||
import { Contact, Message } from '../../../../shared/types'
|
||||
import { ImageBubble } from '../ImageBubble'
|
||||
import { RichMessageBubble } from '../RichMessageBubble'
|
||||
import { VoicePlayer } from '../VoicePlayer'
|
||||
import { renderWechatEmojiText } from '../../utils/wechatEmojiText'
|
||||
import { formatMessageTime } from './messageGrouping'
|
||||
|
||||
interface MessageBubbleProps {
|
||||
message: Message
|
||||
contact: Contact
|
||||
isGroupChat: boolean
|
||||
isMine: boolean
|
||||
showAvatarSpace: boolean
|
||||
onImageClick: (imageUrl: string) => void
|
||||
}
|
||||
|
||||
const RICH_MESSAGE_TYPES = ['名片', '位置', '分享消息', '通话', '表情包', '系统消息']
|
||||
|
||||
export function MessageBubble({
|
||||
message,
|
||||
contact,
|
||||
isGroupChat,
|
||||
isMine,
|
||||
showAvatarSpace,
|
||||
onImageClick
|
||||
}: MessageBubbleProps): React.ReactElement {
|
||||
const isVoice = message.type === '语音'
|
||||
const isImage = message.type === '图片'
|
||||
const isRichMedia = RICH_MESSAGE_TYPES.includes(message.type)
|
||||
const hoverTime = formatMessageTime(message)
|
||||
|
||||
return (
|
||||
<div className={`message-bubble-wrap ${showAvatarSpace ? '' : 'is-followup'}`}>
|
||||
<div
|
||||
className={`message-bubble ${isVoice ? 'voice-bubble' : ''} ${
|
||||
isImage ? 'image-message-bubble' : ''
|
||||
}`}
|
||||
>
|
||||
{isVoice && message.sessionId ? (
|
||||
<VoicePlayer
|
||||
sessionId={message.sessionId}
|
||||
localId={message.localId || 0}
|
||||
createTime={message.createTime || 0}
|
||||
/>
|
||||
) : isImage && message.contentData && message.contentData.type === 'image' ? (
|
||||
<ImageBubble
|
||||
imageMd5={message.contentData.md5}
|
||||
imageDatName={message.contentData.datName}
|
||||
sessionId={message.sessionId}
|
||||
onImageClick={onImageClick}
|
||||
/>
|
||||
) : isRichMedia && message.contentData ? (
|
||||
<RichMessageBubble contentData={message.contentData} />
|
||||
) : (
|
||||
<div className="message-text">{renderWechatEmojiText(message.content)}</div>
|
||||
)}
|
||||
</div>
|
||||
<span className="message-hover-time">{hoverTime}</span>
|
||||
{!isGroupChat && !isMine && contact.m_nsNickName && (
|
||||
<span className="message-accessible-sender">{contact.m_nsNickName}</span>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
import React from 'react'
|
||||
import { Contact } from '../../../../shared/types'
|
||||
import { MessageBubble } from './MessageBubble'
|
||||
import { MessageGroupModel } from './messageGrouping'
|
||||
|
||||
interface MessageGroupProps {
|
||||
group: MessageGroupModel
|
||||
contact: Contact
|
||||
isGroupChat: boolean
|
||||
showAvatar: boolean
|
||||
onImageClick: (imageUrl: string) => void
|
||||
}
|
||||
|
||||
export function MessageGroup({
|
||||
group,
|
||||
contact,
|
||||
isGroupChat,
|
||||
showAvatar,
|
||||
onImageClick
|
||||
}: MessageGroupProps): React.ReactElement {
|
||||
const firstMessage = group.messages[0]
|
||||
|
||||
if (group.isSystem) {
|
||||
return (
|
||||
<>
|
||||
{group.timeLabel && <div className="chat-time-separator">{group.timeLabel}</div>}
|
||||
{group.messages.map((message) => (
|
||||
<div key={message.id} className="wechat-system-message-row">
|
||||
<div className="wechat-system-message">{message.content}</div>
|
||||
</div>
|
||||
))}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
const isMine = group.isMine
|
||||
const displayName = isMine
|
||||
? '我'
|
||||
: isGroupChat
|
||||
? firstMessage.name || firstMessage.from
|
||||
: contact.m_nsNickName
|
||||
const avatarSrc = isMine ? firstMessage.img : firstMessage.img || contact.avatar
|
||||
const shouldShowAvatar = showAvatar
|
||||
|
||||
return (
|
||||
<>
|
||||
{group.timeLabel && <div className="chat-time-separator">{group.timeLabel}</div>}
|
||||
<div className={`wechat-message-row ${isMine ? 'mine' : 'other'} grouped`}>
|
||||
{!isMine && shouldShowAvatar && (
|
||||
<div className="message-avatar">
|
||||
{avatarSrc ? (
|
||||
<img src={avatarSrc} alt={displayName} referrerPolicy="no-referrer" />
|
||||
) : (
|
||||
(displayName || '?').charAt(0)
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{!isMine && !shouldShowAvatar && <div className="message-avatar-spacer" aria-hidden />}
|
||||
<div className="message-stack">
|
||||
{!isMine && isGroupChat && shouldShowAvatar && (
|
||||
<div className="message-sender-name">{displayName}</div>
|
||||
)}
|
||||
{group.messages.map((message, index) => (
|
||||
<MessageBubble
|
||||
key={message.id}
|
||||
message={message}
|
||||
contact={contact}
|
||||
isGroupChat={isGroupChat}
|
||||
isMine={isMine}
|
||||
showAvatarSpace={index === 0}
|
||||
onImageClick={onImageClick}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
{isMine && shouldShowAvatar && (
|
||||
<div className="message-avatar mine-avatar">
|
||||
{avatarSrc ? <img src={avatarSrc} alt="我" referrerPolicy="no-referrer" /> : '我'}
|
||||
</div>
|
||||
)}
|
||||
{isMine && !shouldShowAvatar && <div className="message-avatar-spacer" aria-hidden />}
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import React from 'react'
|
||||
import { Contact, Message } from '../../../../shared/types'
|
||||
import { MessageGroup } from './MessageGroup'
|
||||
import { buildMessageGroups } from './messageGrouping'
|
||||
|
||||
interface MessageListProps {
|
||||
contact: Contact
|
||||
messages: Message[]
|
||||
hiddenMessageCount: number
|
||||
isLoadingMessages?: boolean
|
||||
isGroupChat: boolean
|
||||
showAvatar: boolean
|
||||
listRef: React.RefObject<HTMLDivElement | null>
|
||||
bottomRef: React.RefObject<HTMLDivElement | null>
|
||||
onScroll: (event: React.UIEvent<HTMLDivElement>) => void
|
||||
onImageClick: (imageUrl: string) => void
|
||||
}
|
||||
|
||||
export function MessageList({
|
||||
contact,
|
||||
messages,
|
||||
hiddenMessageCount,
|
||||
isLoadingMessages,
|
||||
isGroupChat,
|
||||
showAvatar,
|
||||
listRef,
|
||||
bottomRef,
|
||||
onScroll,
|
||||
onImageClick
|
||||
}: MessageListProps): React.ReactElement {
|
||||
const groups = React.useMemo(() => buildMessageGroups(messages), [messages])
|
||||
|
||||
return (
|
||||
<div className="message-list wechat-message-list" ref={listRef} onScroll={onScroll}>
|
||||
{isLoadingMessages && <div className="message-loading-pill">正在加载聊天记录...</div>}
|
||||
{hiddenMessageCount > 0 && (
|
||||
<div className="wechat-system-message-row">
|
||||
<div className="wechat-system-message">
|
||||
已隐藏较早的 {hiddenMessageCount} 条消息,当前显示最新 {messages.length} 条
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{groups.map((group) => (
|
||||
<MessageGroup
|
||||
key={group.id}
|
||||
group={group}
|
||||
contact={contact}
|
||||
isGroupChat={isGroupChat}
|
||||
showAvatar={showAvatar}
|
||||
onImageClick={onImageClick}
|
||||
/>
|
||||
))}
|
||||
<div ref={bottomRef} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
import React from 'react'
|
||||
|
||||
interface IconProps {
|
||||
className?: string
|
||||
}
|
||||
|
||||
export function SearchIcon({ className }: IconProps): React.ReactElement {
|
||||
return (
|
||||
<svg className={className} viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
||||
<circle cx="11" cy="11" r="6.5" />
|
||||
<path d="m16 16 4 4" />
|
||||
</svg>
|
||||
)
|
||||
}
|
||||
|
||||
export function RefreshIcon({ className }: IconProps): React.ReactElement {
|
||||
return (
|
||||
<svg className={className} viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
||||
<path d="M20 12a8 8 0 0 1-13.7 5.7" />
|
||||
<path d="M4 12A8 8 0 0 1 17.7 6.3" />
|
||||
<path d="M17.5 3.5v3h-3" />
|
||||
<path d="M6.5 20.5v-3h3" />
|
||||
</svg>
|
||||
)
|
||||
}
|
||||
|
||||
export function ExportIcon({ className }: IconProps): React.ReactElement {
|
||||
return (
|
||||
<svg className={className} viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
||||
<path d="M12 3v11" />
|
||||
<path d="m8 10 4 4 4-4" />
|
||||
<path d="M5 17v2a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2v-2" />
|
||||
</svg>
|
||||
)
|
||||
}
|
||||
|
||||
export function MoreIcon({ className }: IconProps): React.ReactElement {
|
||||
return (
|
||||
<svg className={className} viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
||||
<circle cx="5" cy="12" r="1.4" />
|
||||
<circle cx="12" cy="12" r="1.4" />
|
||||
<circle cx="19" cy="12" r="1.4" />
|
||||
</svg>
|
||||
)
|
||||
}
|
||||
|
||||
export function AiIcon({ className }: IconProps): React.ReactElement {
|
||||
return (
|
||||
<svg className={className} viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
||||
<path d="M12 3l1.5 5 5 1.5-5 1.5-1.5 5-1.5-5-5-1.5 5-1.5L12 3Z" />
|
||||
<path d="M18 15l.8 2.4 2.2.6-2.2.7L18 22l-.8-2.3-2.2-.7 2.2-.6L18 15Z" />
|
||||
</svg>
|
||||
)
|
||||
}
|
||||
|
||||
export function CloseIcon({ className }: IconProps): React.ReactElement {
|
||||
return (
|
||||
<svg className={className} viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
||||
<path d="M6 6l12 12" />
|
||||
<path d="M18 6 6 18" />
|
||||
</svg>
|
||||
)
|
||||
}
|
||||
|
||||
export function ArrowDownIcon({ className }: IconProps): React.ReactElement {
|
||||
return (
|
||||
<svg className={className} viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
||||
<path d="m6 9 6 6 6-6" />
|
||||
</svg>
|
||||
)
|
||||
}
|
||||
|
||||
export function CheckCircleIcon({ className }: IconProps): React.ReactElement {
|
||||
return (
|
||||
<svg className={className} viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
||||
<circle cx="12" cy="12" r="8" />
|
||||
<path d="m8.5 12.2 2.2 2.2 4.8-5" />
|
||||
</svg>
|
||||
)
|
||||
}
|
||||
|
||||
export function HomeIcon({ className }: IconProps): React.ReactElement {
|
||||
return (
|
||||
<svg className={className} viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
||||
<path d="M4 11.5 12 5l8 6.5" />
|
||||
<path d="M6.5 10.5V19h11v-8.5" />
|
||||
</svg>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
import { Message } from '../../../../shared/types'
|
||||
|
||||
const GROUP_INTERVAL_SECONDS = 5 * 60
|
||||
const TIME_SEPARATOR_INTERVAL_SECONDS = 10 * 60
|
||||
|
||||
export interface MessageGroupModel {
|
||||
id: string
|
||||
messages: Message[]
|
||||
isSystem: boolean
|
||||
isMine: boolean
|
||||
timeLabel?: string
|
||||
}
|
||||
|
||||
const getMessageTime = (message: Message): number | null => {
|
||||
if (typeof message.createTime === 'number' && message.createTime > 0) return message.createTime
|
||||
const parsed = Date.parse(message.datetime)
|
||||
if (Number.isNaN(parsed)) return null
|
||||
return Math.floor(parsed / 1000)
|
||||
}
|
||||
|
||||
const getSenderKey = (message: Message): string =>
|
||||
String(message.senderId || message.name || message.from || '').trim()
|
||||
|
||||
const formatClock = (date: Date): string =>
|
||||
`${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
|
||||
|
||||
export const isSystemMessage = (message: Message): boolean =>
|
||||
message.from === 'system' || message.type === '系统消息'
|
||||
|
||||
export const isMineMessage = (message: Message): boolean => message.from === 'assistant'
|
||||
|
||||
export const formatMessageTime = (message: Message): string => {
|
||||
const timestamp = getMessageTime(message)
|
||||
if (!timestamp) return message.datetime
|
||||
const date = new Date(timestamp * 1000)
|
||||
const now = new Date()
|
||||
const startOfToday = new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime()
|
||||
const startOfMessageDay = new Date(date.getFullYear(), date.getMonth(), date.getDate()).getTime()
|
||||
const dayDiff = Math.round((startOfToday - startOfMessageDay) / 86400000)
|
||||
const clock = formatClock(date)
|
||||
|
||||
if (dayDiff === 0) return `今天 ${clock}`
|
||||
if (dayDiff === 1) return `昨天 ${clock}`
|
||||
if (date.getFullYear() === now.getFullYear()) {
|
||||
return `${date.getMonth() + 1} 月 ${date.getDate()} 日 ${clock}`
|
||||
}
|
||||
return `${date.getFullYear()} 年 ${date.getMonth() + 1} 月 ${date.getDate()} 日 ${clock}`
|
||||
}
|
||||
|
||||
export const buildMessageGroups = (messages: Message[]): MessageGroupModel[] => {
|
||||
const groups: MessageGroupModel[] = []
|
||||
let previousGroupStartTime: number | null = null
|
||||
|
||||
messages.forEach((message) => {
|
||||
const isSystem = isSystemMessage(message)
|
||||
const isMine = isMineMessage(message)
|
||||
const timestamp = getMessageTime(message)
|
||||
const previousGroup = groups[groups.length - 1]
|
||||
const previousMessage = previousGroup?.messages[previousGroup.messages.length - 1]
|
||||
const previousTimestamp = previousMessage ? getMessageTime(previousMessage) : null
|
||||
const canJoinPrevious =
|
||||
previousGroup &&
|
||||
!isSystem &&
|
||||
!previousGroup.isSystem &&
|
||||
previousGroup.isMine === isMine &&
|
||||
getSenderKey(previousMessage) === getSenderKey(message) &&
|
||||
timestamp !== null &&
|
||||
previousTimestamp !== null &&
|
||||
timestamp - previousTimestamp >= 0 &&
|
||||
timestamp - previousTimestamp <= GROUP_INTERVAL_SECONDS
|
||||
|
||||
if (canJoinPrevious) {
|
||||
previousGroup.messages.push(message)
|
||||
return
|
||||
}
|
||||
|
||||
const needsTimeLabel =
|
||||
timestamp !== null &&
|
||||
(previousGroupStartTime === null ||
|
||||
Math.abs(timestamp - previousGroupStartTime) >= TIME_SEPARATOR_INTERVAL_SECONDS)
|
||||
const group: MessageGroupModel = {
|
||||
id: message.id || `${groups.length}-${message.datetime}`,
|
||||
messages: [message],
|
||||
isSystem,
|
||||
isMine,
|
||||
timeLabel: needsTimeLabel ? formatMessageTime(message) : undefined
|
||||
}
|
||||
groups.push(group)
|
||||
if (timestamp !== null && needsTimeLabel) previousGroupStartTime = timestamp
|
||||
})
|
||||
|
||||
return groups
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
import React from 'react'
|
||||
import { Contact } from '../../../../shared/types'
|
||||
|
||||
interface ConversationItemProps {
|
||||
contact: Contact
|
||||
active: boolean
|
||||
onSelect: (contact: Contact) => void
|
||||
}
|
||||
|
||||
export function ConversationItem({
|
||||
contact,
|
||||
active,
|
||||
onSelect
|
||||
}: ConversationItemProps): React.ReactElement {
|
||||
const nickname = contact.m_nsNickName?.trim()
|
||||
const wxid = contact.m_nsUsrName
|
||||
const displayName = nickname || wxid || '未命名会话'
|
||||
const initial = (displayName || wxid || '?').charAt(0)
|
||||
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
className={`conversation-item ${active ? 'active' : ''}`}
|
||||
onClick={() => onSelect(contact)}
|
||||
title={wxid && wxid !== displayName ? wxid : displayName}
|
||||
>
|
||||
<span className="conversation-item-active-mark" aria-hidden />
|
||||
<span className="conversation-item-avatar">
|
||||
{contact.avatar ? (
|
||||
<img
|
||||
src={contact.avatar}
|
||||
alt={displayName}
|
||||
referrerPolicy="no-referrer"
|
||||
loading="lazy"
|
||||
decoding="async"
|
||||
/>
|
||||
) : (
|
||||
initial
|
||||
)}
|
||||
</span>
|
||||
<span className="conversation-item-body">
|
||||
<span className="conversation-item-name">{displayName}</span>
|
||||
</span>
|
||||
</button>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import React from 'react'
|
||||
|
||||
interface ConversationSearchProps {
|
||||
value: string
|
||||
onChange: (value: string) => void
|
||||
}
|
||||
|
||||
function SearchIcon(): React.ReactElement {
|
||||
return (
|
||||
<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
||||
<circle cx="11" cy="11" r="6.5" />
|
||||
<path d="m16 16 4 4" />
|
||||
</svg>
|
||||
)
|
||||
}
|
||||
|
||||
export function ConversationSearch({
|
||||
value,
|
||||
onChange
|
||||
}: ConversationSearchProps): React.ReactElement {
|
||||
return (
|
||||
<label className="conversation-search">
|
||||
<span className="conversation-search-icon">
|
||||
<SearchIcon />
|
||||
</span>
|
||||
<input
|
||||
type="text"
|
||||
value={value}
|
||||
placeholder="搜索群聊、联系人或 wxid"
|
||||
onChange={(event) => onChange(event.target.value)}
|
||||
/>
|
||||
</label>
|
||||
)
|
||||
}
|
||||