mirror of
https://wget.la/https://github.com/Wxw-Gu/WechatExplorer
synced 2026-08-19 04:27:00 +08:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
794880d389 | ||
|
|
d0ceeceb68 | ||
|
|
62f729d281 | ||
|
|
0d544275c0 | ||
|
|
a91b4d7a56 | ||
|
|
f9b567fba2 | ||
|
|
1f693aa3d7 | ||
|
|
8e1e166856 | ||
|
|
1275c512c4 | ||
|
|
1abaa57a0c | ||
|
|
d08db46479 | ||
|
|
eaea8d8435 | ||
|
|
1e97953d67 | ||
|
|
597667e005 | ||
|
|
515348b6d8 | ||
|
|
e150605c91 | ||
|
|
556d70eab3 | ||
|
|
d079d45279 |
+1
-1
@@ -8,7 +8,7 @@ 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=
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
node_modules
|
||||
*.tsbuildinfo
|
||||
dist
|
||||
out
|
||||
.env
|
||||
.DS_Store
|
||||
.eslintcache
|
||||
*.log*
|
||||
resources/connectors/wechat/
|
||||
.omc
|
||||
.codex/
|
||||
docs/design/
|
||||
|
||||
@@ -9,7 +9,7 @@ macOS / Windows 微信聊天记录查看,AI 一键生成群聊总结。
|
||||
|
||||
在微信 4.0 数据库解析、解密思路上,项目参考了 [WeFlow](https://github.com/hicccc77/WeFlow) 等开源项目的实现方式;此项目围绕我自己的使用场景做的定制化工具,重点放在本地聊天记录查看、群聊总结和个人工作流集成上。
|
||||
|
||||
> 当前版本:`v2.1.0`。macOS 支持相对稳定;Windows 已初步支持微信 4.0 数据库连接、自动获取密钥和聊天记录查看,仍在持续兼容不同微信版本与本地目录结构。
|
||||
> 当前版本:`v2.1.2`。macOS 支持相对稳定;Windows 已初步支持微信 4.0 数据库连接、自动获取密钥和聊天记录查看,仍在持续兼容不同微信版本与本地目录结构。
|
||||
|
||||
## ✨ 功能特性
|
||||
|
||||
@@ -18,10 +18,13 @@ macOS / Windows 微信聊天记录查看,AI 一键生成群聊总结。
|
||||
- **AI 智能总结**: 支持多模型服务配置(DeepSeek/GPT-4o/Claude/Moonshot),一键总结群聊精华内容,生成话题报告。
|
||||
- **群聊日报生成**: 支持围绕群聊内容生成日报,通常会覆盖以下模块中的部分或全部内容:
|
||||
- **今日讨论热点**: 梳理群内主要话题,支持热度标签。
|
||||
- **一句话速览**: 首屏突出今日核心结论与待跟进事项。
|
||||
- **实用信息与资源**: 提取分享的链接、资源等信息。
|
||||
- **重要消息汇总**: 标记并展示重要消息,带发送者头像。
|
||||
- **有趣对话或金句**: 收录群内的精彩对话。
|
||||
- **问题与解答**: 整理群内的问答内容。
|
||||
- **尚未解决 / 今日剧情线**: 更适合工作群和项目群的回顾与跟进。
|
||||
- **今日群相册 / 语音时长榜 / 临时群友称号**: 让图片、语音和氛围型内容也能参与日报。
|
||||
- **群内数据可视化**: 消息热度条形图、话唠榜 TOP5、活跃时间线。
|
||||
- **词云/关键词**: 可视化展示群聊关键词。
|
||||
- **图片生成**: 将 AI 总结的内容生成精美图片,方便分享。
|
||||
@@ -194,3 +197,9 @@ curl -G "http://127.0.0.1:6131/api/v1/resolve" \
|
||||
- [WechatMessageExplorer](https://github.com/svcvit/WechatMessageExplorer)
|
||||
- [WeFlow](https://github.com/hicccc77/WeFlow)
|
||||
- [chatlog](https://github.com/sjzar/chatlog)
|
||||
|
||||
## 📱 交流与反馈
|
||||
|
||||
<p align="center">
|
||||
<img src="./public/二维码.jpg" alt="WechatExplorer 交流二维码" width="280" />
|
||||
</p>
|
||||
|
||||
@@ -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": "技术交流",
|
||||
|
||||
@@ -16,6 +16,7 @@ extraMetadata:
|
||||
asarUnpack:
|
||||
- resources/**
|
||||
extraResources:
|
||||
# Includes the optional WeChat connector binary for the target platform.
|
||||
- from: resources
|
||||
to: resources
|
||||
filter:
|
||||
|
||||
+27
-8
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "wechatexplorer",
|
||||
"version": "2.1.1",
|
||||
"version": "2.1.4",
|
||||
"description": "macOS / Windows 微信聊天记录查看与 AI 群聊总结助手",
|
||||
"keywords": [
|
||||
"wechat",
|
||||
@@ -25,23 +25,32 @@
|
||||
"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",
|
||||
"dev": "node scripts/ensure-env.cjs && node scripts/build-wechat-connector.cjs && electron-vite dev",
|
||||
"test:wechat-connector": "go -C services/wechat-connector test ./... && go -C services/wechat-connector vet ./...",
|
||||
"build:wechat-connector": "node scripts/build-wechat-connector.cjs",
|
||||
"build:wechat-connector:win": "node scripts/build-wechat-connector.cjs --platform win32 --arch x64,arm64",
|
||||
"build:wechat-connector:mac": "node scripts/build-wechat-connector.cjs --platform darwin --arch x64,arm64",
|
||||
"build:native-services": "npm run build:wechat-connector",
|
||||
"build": "npm run typecheck && npm run build:native-services && electron-vite build",
|
||||
"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",
|
||||
"build:mac:arm64": "electron-vite build && electron-builder --config electron-builder.yml --mac --arm64",
|
||||
"release:mac": "electron-vite build && electron-builder --config electron-builder.yml --mac --x64 --arm64 --publish always",
|
||||
"build:win": "npm run typecheck && npm run build:wechat-connector:win && electron-vite build && electron-builder --config electron-builder.yml --win --x64",
|
||||
"build:mac:x64": "npm run typecheck && node scripts/build-wechat-connector.cjs --platform darwin --arch x64 && electron-vite build && electron-builder --config electron-builder.yml --mac --x64",
|
||||
"build:mac:arm64": "npm run typecheck && node scripts/build-wechat-connector.cjs --platform darwin --arch arm64 && electron-vite build && electron-builder --config electron-builder.yml --mac --arm64",
|
||||
"release": "npm run release:mac && npm run release:win",
|
||||
"release:mac": "npm run typecheck && npm run build:wechat-connector:mac && electron-vite build && electron-builder --config electron-builder.yml --mac --x64 --arm64 --publish always",
|
||||
"release:win": "npm run typecheck && npm run build:wechat-connector:win && electron-vite build && electron-builder --config electron-builder.yml --win --x64 --publish always",
|
||||
"build:linux": "electron-vite build && electron-builder --config electron-builder.yml --linux"
|
||||
},
|
||||
"dependencies": {
|
||||
"@electron-toolkit/preload": "^3.0.2",
|
||||
"@electron-toolkit/utils": "^4.0.0",
|
||||
"@koromix/koffi-win32-x64": "3.1.0",
|
||||
"@tanstack/react-virtual": "^3.14.6",
|
||||
"fs-extra": "^11.3.2",
|
||||
"fzstd": "^0.1.1",
|
||||
"jsonrepair": "^3.15.0",
|
||||
"koffi": "^3.1.0",
|
||||
"openai": "^6.10.0",
|
||||
"silk-wasm": "^3.7.1",
|
||||
@@ -71,6 +80,16 @@
|
||||
"vite": "^7.2.6"
|
||||
},
|
||||
"pnpm": {
|
||||
"supportedArchitectures": {
|
||||
"os": [
|
||||
"current",
|
||||
"win32"
|
||||
],
|
||||
"cpu": [
|
||||
"current",
|
||||
"x64"
|
||||
]
|
||||
},
|
||||
"onlyBuiltDependencies": [
|
||||
"electron",
|
||||
"esbuild"
|
||||
|
||||
Generated
+26
-4
@@ -10,7 +10,9 @@ specifiers:
|
||||
'@electron-toolkit/preload': ^3.0.2
|
||||
'@electron-toolkit/tsconfig': ^2.0.0
|
||||
'@electron-toolkit/utils': ^4.0.0
|
||||
'@koromix/koffi-win32-x64': 3.1.0
|
||||
'@rollup/rollup-darwin-arm64': ^4.62.2
|
||||
'@tanstack/react-virtual': ^3.14.6
|
||||
'@types/fs-extra': ^11.0.4
|
||||
'@types/node': ^22.19.1
|
||||
'@types/react': ^19.2.7
|
||||
@@ -25,6 +27,7 @@ specifiers:
|
||||
eslint-plugin-react-refresh: ^0.4.24
|
||||
fs-extra: ^11.3.2
|
||||
fzstd: ^0.1.1
|
||||
jsonrepair: ^3.15.0
|
||||
koffi: ^3.1.0
|
||||
openai: ^6.10.0
|
||||
prettier: ^3.7.4
|
||||
@@ -38,8 +41,11 @@ specifiers:
|
||||
dependencies:
|
||||
'@electron-toolkit/preload': 3.0.2_electron@43.1.0
|
||||
'@electron-toolkit/utils': 4.0.0_electron@43.1.0
|
||||
'@koromix/koffi-win32-x64': 3.1.0
|
||||
'@tanstack/react-virtual': 3.14.6_bokjwhiew3ov3ffvbmafuwoalq
|
||||
fs-extra: 11.3.2
|
||||
fzstd: 0.1.1
|
||||
jsonrepair: 3.15.0
|
||||
koffi: 3.1.0
|
||||
openai: 6.10.0
|
||||
silk-wasm: 3.7.1
|
||||
@@ -887,7 +893,6 @@ packages:
|
||||
cpu: [x64]
|
||||
os: [win32]
|
||||
dev: false
|
||||
optional: true
|
||||
|
||||
/@malept/cross-spawn-promise/2.0.0:
|
||||
resolution: {integrity: sha512-1DpKU0Z5ThltBwjNySMC14g0CkbyhCaz9FkhxqNsZI6uAPJXFS8cMXlBKo26FJ8ZuW6S9GCMcR9IO5k2X5/9Fg==}
|
||||
@@ -1123,6 +1128,21 @@ packages:
|
||||
defer-to-connect: 2.0.1
|
||||
dev: true
|
||||
|
||||
/@tanstack/react-virtual/3.14.6_bokjwhiew3ov3ffvbmafuwoalq:
|
||||
resolution: {integrity: sha512-4+Uq8m0/gzO4kMCHUEpTtGX1RnONK0C+g88b2ltwPMWUBiaVarBuWKoPJaz7gj1cKCVRAdyu+U8GcKhwCc2beA==}
|
||||
peerDependencies:
|
||||
react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0
|
||||
react-dom: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0
|
||||
dependencies:
|
||||
'@tanstack/virtual-core': 3.17.4
|
||||
react: 19.2.1
|
||||
react-dom: 19.2.1_react@19.2.1
|
||||
dev: false
|
||||
|
||||
/@tanstack/virtual-core/3.17.4:
|
||||
resolution: {integrity: sha512-nGm5KteqxasUdThLc2izl6dHUqLv0LQj7Nuyo5gYalTPf/U8a9ermvsl7reT+6ioBW1l8WfpP/mcU338nLXpqw==}
|
||||
dev: false
|
||||
|
||||
/@tootallnate/once/2.0.0:
|
||||
resolution: {integrity: sha512-XCuKFP5PS55gnMVu3dty8KPatLqUoy/ZYzDzAGCQ8JNFCkLXzmI7vNHCR+XpbZaMWQK/vQubr7PkYq8g470J/A==}
|
||||
engines: {node: '>= 10'}
|
||||
@@ -3413,6 +3433,11 @@ packages:
|
||||
optionalDependencies:
|
||||
graceful-fs: 4.2.11
|
||||
|
||||
/jsonrepair/3.15.0:
|
||||
resolution: {integrity: sha512-wy8OTjwsJwQRnQJkKnMJJ9vcytRdBPAgIF/Hy6+s1dAj42BHMKiyL8JzEieIl3JY7idt8eyHwBWTO8mh/+mtwA==}
|
||||
hasBin: true
|
||||
dev: false
|
||||
|
||||
/jsx-ast-utils/3.3.5:
|
||||
resolution: {integrity: sha512-ZZow9HBI5O6EPgSJLUb8n2NKgmVWTwCvHGwFuJlMjvLFqlGG6pjirPhtdsseaLZjSibD8eegzmYpUZwoIlj2cQ==}
|
||||
engines: {node: '>=4.0'}
|
||||
@@ -4036,7 +4061,6 @@ packages:
|
||||
dependencies:
|
||||
react: 19.2.1
|
||||
scheduler: 0.27.0
|
||||
dev: true
|
||||
|
||||
/react-is/16.13.1:
|
||||
resolution: {integrity: sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==}
|
||||
@@ -4050,7 +4074,6 @@ packages:
|
||||
/react/19.2.1:
|
||||
resolution: {integrity: sha512-DGrYcCWK7tvYMnWh79yrPHt+vdx9tY+1gPZa7nJQtO/p8bLTDaHp4dzwEhQB7pZ4Xe3ok4XKuEPrVuc+wlpkmw==}
|
||||
engines: {node: '>=0.10.0'}
|
||||
dev: true
|
||||
|
||||
/read-binary-file-arch/1.0.6:
|
||||
resolution: {integrity: sha512-BNg9EN3DD3GsDXX7Aa8O4p92sryjkmzYYgmgTAc6CA4uGLEDzFfxOxugu21akOxpcXHiEgsYkC6nPsQvLLLmEg==}
|
||||
@@ -4233,7 +4256,6 @@ packages:
|
||||
|
||||
/scheduler/0.27.0:
|
||||
resolution: {integrity: sha512-eNv+WrVbKu1f3vbYJT/xtiF5syA5HPIMtf9IgY/nKg0sWqzAUEvqY/xm7OcZc/qafLx/iO9FgOmeSAp4v5ti/Q==}
|
||||
dev: true
|
||||
|
||||
/semver/5.7.2:
|
||||
resolution: {integrity: sha512-cBznnQ9KjJqU67B52RMC65CMarK2600WFnbkcaiwWq3xy/5haFJlshgnpjovMVJ+Hff49d8GEn0b87C5pDQ10g==}
|
||||
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 583 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 157 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 152 KiB |
+449
-108
@@ -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,32 +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;
|
||||
}
|
||||
.record-note {
|
||||
color: #485465;
|
||||
font-weight: 650;
|
||||
}
|
||||
.overview {
|
||||
margin-top: 2px;
|
||||
.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;
|
||||
@@ -83,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);
|
||||
@@ -94,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 {
|
||||
@@ -109,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: '';
|
||||
@@ -127,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;
|
||||
@@ -140,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;
|
||||
@@ -165,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;
|
||||
@@ -189,7 +269,6 @@
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 5px;
|
||||
min-width: 0;
|
||||
background: #f6f8fa;
|
||||
border-radius: 999px;
|
||||
padding: 3px 8px 3px 3px;
|
||||
@@ -198,7 +277,6 @@
|
||||
width: 24px;
|
||||
height: 24px;
|
||||
border-radius: 50%;
|
||||
object-fit: cover;
|
||||
}
|
||||
.person-chip b {
|
||||
max-width: 58px;
|
||||
@@ -220,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;
|
||||
@@ -255,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;
|
||||
@@ -269,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;
|
||||
@@ -299,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;
|
||||
@@ -350,6 +576,9 @@
|
||||
padding: 9px 0;
|
||||
border-bottom: 1px solid #eef0f2;
|
||||
}
|
||||
.rank:last-child {
|
||||
border-bottom: none;
|
||||
}
|
||||
.rank img {
|
||||
width: 30px;
|
||||
height: 30px;
|
||||
@@ -402,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,
|
||||
@@ -414,83 +694,144 @@
|
||||
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">
|
||||
<div>{{DATE_RANGE}}</div>
|
||||
<div class="record-note">{{RECORD_NOTE}}</div>
|
||||
<div class="overview">{{OVERVIEW}}</div>
|
||||
</div>
|
||||
<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">
|
||||
数据来源:WechatExplorer · 微信群聊记录<br />
|
||||
数据来源:微信群聊记录<br />
|
||||
生成时间:{{GENERATED_AT}}<br />
|
||||
{{FOOTER_NOTE}}
|
||||
</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>
|
||||
@@ -10,6 +10,23 @@ function setPlistValue(plistPath, key, value) {
|
||||
}
|
||||
|
||||
exports.default = async function afterPack(context) {
|
||||
if (context.electronPlatformName === 'win32') {
|
||||
const koffiNative = path.join(
|
||||
context.appOutDir,
|
||||
'resources',
|
||||
'app.asar.unpacked',
|
||||
'node_modules',
|
||||
'@koromix',
|
||||
'koffi-win32-x64',
|
||||
'win32_x64',
|
||||
'koffi.node'
|
||||
)
|
||||
if (!existsSync(koffiNative)) {
|
||||
throw new Error(`Missing Windows Koffi native module: ${koffiNative}`)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if (context.electronPlatformName !== 'darwin') return
|
||||
|
||||
const productName = context.packager.appInfo.productFilename
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
/* eslint-disable @typescript-eslint/no-require-imports, @typescript-eslint/explicit-function-return-type */
|
||||
const { execFileSync } = require('node:child_process')
|
||||
const fs = require('node:fs')
|
||||
const path = require('node:path')
|
||||
|
||||
const projectRoot = path.resolve(__dirname, '..')
|
||||
const sourceDir = path.join(projectRoot, 'services', 'wechat-connector')
|
||||
const outputRoot = path.join(projectRoot, 'resources', 'connectors', 'wechat')
|
||||
|
||||
function normalizePlatform(value) {
|
||||
if (value === 'win32' || value === 'windows') return 'windows'
|
||||
if (value === 'darwin' || value === 'macos') return 'darwin'
|
||||
if (value === 'linux') return 'linux'
|
||||
throw new Error(`Unsupported connector platform: ${value}`)
|
||||
}
|
||||
|
||||
function normalizeArch(value) {
|
||||
if (value === 'x64' || value === 'amd64') return 'amd64'
|
||||
if (value === 'arm64') return 'arm64'
|
||||
throw new Error(`Unsupported connector architecture: ${value}`)
|
||||
}
|
||||
|
||||
function detectHostArch() {
|
||||
if (process.platform !== 'darwin') return process.arch
|
||||
try {
|
||||
const arm64Supported = execFileSync('sysctl', ['-n', 'hw.optional.arm64'], {
|
||||
encoding: 'utf8'
|
||||
}).trim()
|
||||
return arm64Supported === '1' ? 'arm64' : process.arch
|
||||
} catch {
|
||||
return process.arch
|
||||
}
|
||||
}
|
||||
|
||||
function parseTargets() {
|
||||
const platformArg = process.argv.indexOf('--platform')
|
||||
const archArg = process.argv.indexOf('--arch')
|
||||
const platforms = platformArg >= 0 ? process.argv[platformArg + 1].split(',') : [process.platform]
|
||||
const arches = archArg >= 0 ? process.argv[archArg + 1].split(',') : [detectHostArch()]
|
||||
return platforms.flatMap((platform) =>
|
||||
arches.map((arch) => ({ goos: normalizePlatform(platform), goarch: normalizeArch(arch) }))
|
||||
)
|
||||
}
|
||||
|
||||
if (!fs.existsSync(path.join(sourceDir, 'go.mod'))) {
|
||||
throw new Error(`Repository-local WeChat connector source is missing: ${sourceDir}`)
|
||||
}
|
||||
|
||||
for (const target of parseTargets()) {
|
||||
const directoryName = `${target.goos === 'windows' ? 'win32' : target.goos}-${target.goarch === 'amd64' ? 'x64' : target.goarch}`
|
||||
const outputDir = path.join(outputRoot, directoryName)
|
||||
const outputPath = path.join(
|
||||
outputDir,
|
||||
target.goos === 'windows' ? 'wechat-connector.exe' : 'wechat-connector'
|
||||
)
|
||||
fs.rmSync(outputDir, { recursive: true, force: true })
|
||||
fs.mkdirSync(outputDir, { recursive: true })
|
||||
execFileSync('go', ['build', '-trimpath', '-o', outputPath, '.'], {
|
||||
cwd: sourceDir,
|
||||
env: { ...process.env, GOOS: target.goos, GOARCH: target.goarch, CGO_ENABLED: '0' },
|
||||
stdio: 'inherit'
|
||||
})
|
||||
if (target.goos !== 'windows') fs.chmodSync(outputPath, 0o755)
|
||||
console.log(`[build-wechat-connector] built ${directoryName}: ${outputPath}`)
|
||||
}
|
||||
@@ -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,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 fastclaw-ai
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,25 @@
|
||||
# WechatExplorer WeChat Connector
|
||||
|
||||
This repository-local service provides the minimal WeChat bridge required by WechatExplorer:
|
||||
|
||||
- QR-code login with a single persisted credential
|
||||
- account discovery
|
||||
- inbound long polling and authenticated webhook delivery
|
||||
- local HTTP health and send endpoints
|
||||
- text and local/remote media sending
|
||||
|
||||
The executable is managed by the Electron main process. It is not a general-purpose agent runtime and does not load external AI command-line tools.
|
||||
|
||||
## Commands
|
||||
|
||||
```bash
|
||||
go run . login --json
|
||||
go run . accounts --json
|
||||
go run . start --foreground --api-addr 127.0.0.1:18011 --account-id <account-id>
|
||||
```
|
||||
|
||||
Credential and synchronization state is stored under `~/.wechatexplorer/wechat-connector/accounts`. A successful login is written before the older credential and synchronization state are removed, so an incomplete login cannot destroy the last working credential.
|
||||
|
||||
## Attribution
|
||||
|
||||
Low-level protocol and media transport portions are distributed under the MIT license in [LICENSE](LICENSE). WechatExplorer-specific process management, webhook contract, product UI, and Agent Hub behavior live in the surrounding WechatExplorer project.
|
||||
@@ -0,0 +1,135 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
|
||||
"github.com/Wxw-Gu/WechatExplorer/services/wechat-connector/ilink"
|
||||
"github.com/Wxw-Gu/WechatExplorer/services/wechat-connector/messaging"
|
||||
)
|
||||
|
||||
// Server provides an HTTP API for sending messages.
|
||||
type Server struct {
|
||||
clients []*ilink.Client
|
||||
addr string
|
||||
}
|
||||
|
||||
// NewServer creates an API server.
|
||||
func NewServer(clients []*ilink.Client, addr string) *Server {
|
||||
if addr == "" {
|
||||
addr = "127.0.0.1:18011"
|
||||
}
|
||||
return &Server{clients: clients, addr: addr}
|
||||
}
|
||||
|
||||
// SendRequest is the JSON body for POST /api/send.
|
||||
type SendRequest struct {
|
||||
AccountID string `json:"account_id,omitempty"`
|
||||
To string `json:"to"`
|
||||
Text string `json:"text,omitempty"`
|
||||
MediaURL string `json:"media_url,omitempty"` // image/video/file URL
|
||||
}
|
||||
|
||||
// Run starts the HTTP server. Blocks until ctx is cancelled.
|
||||
func (s *Server) Run(ctx context.Context) error {
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/api/send", s.handleSend)
|
||||
mux.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
fmt.Fprintln(w, "ok")
|
||||
})
|
||||
|
||||
srv := &http.Server{Addr: s.addr, Handler: mux}
|
||||
|
||||
go func() {
|
||||
<-ctx.Done()
|
||||
srv.Shutdown(context.Background())
|
||||
}()
|
||||
|
||||
log.Printf("[api] listening on %s", s.addr)
|
||||
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Server) handleSend(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
http.Error(w, "POST only", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
var req SendRequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
http.Error(w, "invalid JSON: "+err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
if req.To == "" {
|
||||
http.Error(w, `"to" is required`, http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if req.Text == "" && req.MediaURL == "" {
|
||||
http.Error(w, `"text" or "media_url" is required`, http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
if len(s.clients) == 0 {
|
||||
http.Error(w, "no accounts configured", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
|
||||
client := s.clientForAccount(req.AccountID)
|
||||
if client == nil {
|
||||
http.Error(w, "requested account is not available", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
ctx := r.Context()
|
||||
|
||||
// Send text if provided
|
||||
if req.Text != "" {
|
||||
if err := messaging.SendTextReply(ctx, client, req.To, req.Text, "", ""); err != nil {
|
||||
log.Printf("[api] send text failed: %v", err)
|
||||
http.Error(w, "send text failed: "+err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
log.Printf("[api] sent text to %s: %q", req.To, req.Text)
|
||||
|
||||
// Extract and send any markdown images embedded in text
|
||||
for _, imgURL := range messaging.ExtractImageURLs(req.Text) {
|
||||
if err := messaging.SendMediaFromURL(ctx, client, req.To, imgURL, ""); err != nil {
|
||||
log.Printf("[api] send extracted image failed: %v", err)
|
||||
} else {
|
||||
log.Printf("[api] sent extracted image to %s: %s", req.To, imgURL)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Send media if provided
|
||||
if req.MediaURL != "" {
|
||||
if err := messaging.SendMediaFromURL(ctx, client, req.To, req.MediaURL, ""); err != nil {
|
||||
log.Printf("[api] send media failed: %v", err)
|
||||
http.Error(w, "send media failed: "+err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
log.Printf("[api] sent media to %s: %s", req.To, req.MediaURL)
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(map[string]string{"status": "ok"})
|
||||
}
|
||||
|
||||
func (s *Server) clientForAccount(accountID string) *ilink.Client {
|
||||
if accountID == "" {
|
||||
return s.clients[0]
|
||||
}
|
||||
for _, client := range s.clients {
|
||||
if client.BotID() == accountID {
|
||||
return client
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/Wxw-Gu/WechatExplorer/services/wechat-connector/ilink"
|
||||
)
|
||||
|
||||
func TestClientForAccountSelectsMatchingBot(t *testing.T) {
|
||||
oldClient := ilink.NewClient(&ilink.Credentials{ILinkBotID: "bot-old"})
|
||||
newClient := ilink.NewClient(&ilink.Credentials{ILinkBotID: "bot-new"})
|
||||
server := NewServer([]*ilink.Client{oldClient, newClient}, "")
|
||||
|
||||
if got := server.clientForAccount("bot-new"); got != newClient {
|
||||
t.Fatal("clientForAccount did not select the requested account")
|
||||
}
|
||||
if got := server.clientForAccount("missing"); got != nil {
|
||||
t.Fatal("clientForAccount should reject an unknown account")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
module github.com/Wxw-Gu/WechatExplorer/services/wechat-connector
|
||||
|
||||
go 1.23.0
|
||||
|
||||
require (
|
||||
github.com/google/uuid v1.6.0
|
||||
rsc.io/qr v0.2.0
|
||||
)
|
||||
@@ -0,0 +1,4 @@
|
||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
rsc.io/qr v0.2.0 h1:6vBLea5/NRMVTz8V66gipeLycZMl/+UlFmk8DvqQ6WY=
|
||||
rsc.io/qr v0.2.0/go.mod h1:IF+uZjkb9fqyeF/4tlBoynqmQxUoPfWEKh921coOuXs=
|
||||
@@ -0,0 +1,197 @@
|
||||
package ilink
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
qrCodeURL = "https://ilinkai.weixin.qq.com/ilink/bot/get_bot_qrcode?bot_type=3"
|
||||
qrStatusURL = "https://ilinkai.weixin.qq.com/ilink/bot/get_qrcode_status?qrcode="
|
||||
statusWait = "wait"
|
||||
statusScanned = "scaned"
|
||||
statusConfirmed = "confirmed"
|
||||
statusExpired = "expired"
|
||||
)
|
||||
|
||||
// FetchQRCode retrieves a new QR code for login.
|
||||
func FetchQRCode(ctx context.Context) (*QRCodeResponse, error) {
|
||||
c := NewUnauthenticatedClient()
|
||||
var resp QRCodeResponse
|
||||
if err := c.doGet(ctx, qrCodeURL, &resp); err != nil {
|
||||
return nil, fmt.Errorf("fetch QR code: %w", err)
|
||||
}
|
||||
return &resp, nil
|
||||
}
|
||||
|
||||
// PollQRStatus polls for QR code scan status until confirmed or expired.
|
||||
// It calls onStatus for each status change so the caller can display progress.
|
||||
func PollQRStatus(ctx context.Context, qrcode string, onStatus func(status string)) (*Credentials, error) {
|
||||
c := NewUnauthenticatedClient()
|
||||
url := qrStatusURL + qrcode
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
default:
|
||||
}
|
||||
|
||||
pollCtx, cancel := context.WithTimeout(ctx, 40*time.Second)
|
||||
var resp QRStatusResponse
|
||||
err := c.doGet(pollCtx, url, &resp)
|
||||
cancel()
|
||||
|
||||
if err != nil {
|
||||
// Timeout is normal for long-poll, retry
|
||||
if ctx.Err() != nil {
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
if onStatus != nil {
|
||||
onStatus(resp.Status)
|
||||
}
|
||||
|
||||
switch resp.Status {
|
||||
case statusConfirmed:
|
||||
creds := &Credentials{
|
||||
BotToken: resp.BotToken,
|
||||
ILinkBotID: resp.ILinkBotID,
|
||||
BaseURL: resp.BaseURL,
|
||||
ILinkUserID: resp.ILinkUserID,
|
||||
}
|
||||
return creds, nil
|
||||
case statusExpired:
|
||||
return nil, fmt.Errorf("QR code expired")
|
||||
case statusWait, statusScanned:
|
||||
// Continue polling
|
||||
default:
|
||||
// Unknown status, continue
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// AccountsDir returns the directory where account credentials are stored.
|
||||
func AccountsDir() (string, error) {
|
||||
home, err := os.UserHomeDir()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return filepath.Join(home, ".wechatexplorer", "wechat-connector", "accounts"), nil
|
||||
}
|
||||
|
||||
// NormalizeAccountID converts raw bot ID to filesystem-safe format.
|
||||
func NormalizeAccountID(raw string) string {
|
||||
s := raw
|
||||
for _, ch := range []string{"@", ".", ":"} {
|
||||
s = filepath.Clean(s)
|
||||
s = replaceAll(s, ch, "-")
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
func replaceAll(s, old, new string) string {
|
||||
for {
|
||||
i := indexOf(s, old)
|
||||
if i < 0 {
|
||||
return s
|
||||
}
|
||||
s = s[:i] + new + s[i+len(old):]
|
||||
}
|
||||
}
|
||||
|
||||
func indexOf(s, sub string) int {
|
||||
for i := range s {
|
||||
if i+len(sub) <= len(s) && s[i:i+len(sub)] == sub {
|
||||
return i
|
||||
}
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
// SaveCredentials saves the latest credentials and removes older accounts.
|
||||
// The new credential is written first so a failed login never destroys the
|
||||
// previously working credential.
|
||||
func SaveCredentials(creds *Credentials) error {
|
||||
dir, err := AccountsDir()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.MkdirAll(dir, 0o700); err != nil {
|
||||
return fmt.Errorf("create accounts dir: %w", err)
|
||||
}
|
||||
|
||||
id := NormalizeAccountID(creds.ILinkBotID)
|
||||
path := filepath.Join(dir, id+".json")
|
||||
|
||||
data, err := json.MarshalIndent(creds, "", " ")
|
||||
if err != nil {
|
||||
return fmt.Errorf("marshal credentials: %w", err)
|
||||
}
|
||||
|
||||
if err := os.WriteFile(path, data, 0o600); err != nil {
|
||||
return fmt.Errorf("write credentials: %w", err)
|
||||
}
|
||||
|
||||
entries, err := os.ReadDir(dir)
|
||||
if err != nil {
|
||||
return fmt.Errorf("prune old credentials: %w", err)
|
||||
}
|
||||
keepPrefix := id + "."
|
||||
for _, entry := range entries {
|
||||
if entry.IsDir() || strings.HasPrefix(entry.Name(), keepPrefix) {
|
||||
continue
|
||||
}
|
||||
if filepath.Ext(entry.Name()) != ".json" {
|
||||
continue
|
||||
}
|
||||
if err := os.Remove(filepath.Join(dir, entry.Name())); err != nil && !os.IsNotExist(err) {
|
||||
return fmt.Errorf("remove old credential %s: %w", entry.Name(), err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// LoadAllCredentials loads all saved account credentials.
|
||||
func LoadAllCredentials() ([]*Credentials, error) {
|
||||
dir, err := AccountsDir()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
entries, err := os.ReadDir(dir)
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
return nil, nil
|
||||
}
|
||||
return nil, fmt.Errorf("read accounts dir: %w", err)
|
||||
}
|
||||
|
||||
var result []*Credentials
|
||||
for _, e := range entries {
|
||||
if e.IsDir() || filepath.Ext(e.Name()) != ".json" {
|
||||
continue
|
||||
}
|
||||
data, err := os.ReadFile(filepath.Join(dir, e.Name()))
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
var creds Credentials
|
||||
if json.Unmarshal(data, &creds) == nil && creds.BotToken != "" {
|
||||
result = append(result, &creds)
|
||||
}
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// CredentialsPath returns the path for display purposes.
|
||||
func CredentialsPath() (string, error) {
|
||||
return AccountsDir()
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package ilink
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestSaveCredentialsKeepsOnlyLatestAccount(t *testing.T) {
|
||||
t.Setenv("HOME", t.TempDir())
|
||||
old := &Credentials{ILinkBotID: "bot-old@im.bot", BotToken: "old-token"}
|
||||
latest := &Credentials{ILinkBotID: "bot-new@im.bot", BotToken: "new-token"}
|
||||
if err := SaveCredentials(old); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
dir, err := AccountsDir()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(dir, NormalizeAccountID(old.ILinkBotID)+".sync.json"), []byte(`{}`), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := SaveCredentials(latest); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
accounts, err := LoadAllCredentials()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(accounts) != 1 || accounts[0].ILinkBotID != latest.ILinkBotID {
|
||||
t.Fatalf("accounts = %#v", accounts)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(dir, NormalizeAccountID(old.ILinkBotID)+".sync.json")); !os.IsNotExist(err) {
|
||||
t.Fatalf("old sync state still exists: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,218 @@
|
||||
package ilink
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"encoding/binary"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
defaultBaseURL = "https://ilinkai.weixin.qq.com"
|
||||
longPollTimeout = 35 * time.Second
|
||||
sendTimeout = 15 * time.Second
|
||||
)
|
||||
|
||||
// Client is an iLink HTTP API client.
|
||||
type Client struct {
|
||||
baseURL string
|
||||
botToken string
|
||||
botID string
|
||||
httpClient *http.Client
|
||||
wechatUIN string
|
||||
}
|
||||
|
||||
// NewClient creates a new iLink API client.
|
||||
func NewClient(creds *Credentials) *Client {
|
||||
baseURL := creds.BaseURL
|
||||
if baseURL == "" {
|
||||
baseURL = defaultBaseURL
|
||||
}
|
||||
return &Client{
|
||||
baseURL: baseURL,
|
||||
botToken: creds.BotToken,
|
||||
botID: creds.ILinkBotID,
|
||||
httpClient: &http.Client{},
|
||||
wechatUIN: generateWechatUIN(),
|
||||
}
|
||||
}
|
||||
|
||||
// NewUnauthenticatedClient creates a client without credentials for login flow.
|
||||
func NewUnauthenticatedClient() *Client {
|
||||
return &Client{
|
||||
baseURL: defaultBaseURL,
|
||||
httpClient: &http.Client{Timeout: 40 * time.Second},
|
||||
wechatUIN: generateWechatUIN(),
|
||||
}
|
||||
}
|
||||
|
||||
// BotID returns the bot's user ID.
|
||||
func (c *Client) BotID() string {
|
||||
return c.botID
|
||||
}
|
||||
|
||||
// GetUpdates performs a long-poll for new messages.
|
||||
func (c *Client) GetUpdates(ctx context.Context, buf string) (*GetUpdatesResponse, error) {
|
||||
reqBody := GetUpdatesRequest{
|
||||
GetUpdatesBuf: buf,
|
||||
BaseInfo: BaseInfo{ChannelVersion: "1.0.0"},
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(ctx, longPollTimeout+5*time.Second)
|
||||
defer cancel()
|
||||
|
||||
var resp GetUpdatesResponse
|
||||
if err := c.doPost(ctx, "/ilink/bot/getupdates", reqBody, &resp); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &resp, nil
|
||||
}
|
||||
|
||||
// SendMessage sends a message through iLink.
|
||||
func (c *Client) SendMessage(ctx context.Context, msg *SendMessageRequest) (*SendMessageResponse, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, sendTimeout)
|
||||
defer cancel()
|
||||
|
||||
var resp SendMessageResponse
|
||||
if err := c.doPost(ctx, "/ilink/bot/sendmessage", msg, &resp); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &resp, nil
|
||||
}
|
||||
|
||||
// GetConfig fetches bot config for a user (includes typing_ticket).
|
||||
func (c *Client) GetConfig(ctx context.Context, userID, contextToken string) (*GetConfigResponse, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, 10*time.Second)
|
||||
defer cancel()
|
||||
|
||||
req := GetConfigRequest{
|
||||
ILinkUserID: userID,
|
||||
ContextToken: contextToken,
|
||||
BaseInfo: BaseInfo{},
|
||||
}
|
||||
|
||||
var resp GetConfigResponse
|
||||
if err := c.doPost(ctx, "/ilink/bot/getconfig", req, &resp); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &resp, nil
|
||||
}
|
||||
|
||||
// SendTyping sends a typing indicator to a user.
|
||||
func (c *Client) SendTyping(ctx context.Context, userID, typingTicket string, status int) error {
|
||||
ctx, cancel := context.WithTimeout(ctx, 10*time.Second)
|
||||
defer cancel()
|
||||
|
||||
req := SendTypingRequest{
|
||||
ILinkUserID: userID,
|
||||
TypingTicket: typingTicket,
|
||||
Status: status,
|
||||
BaseInfo: BaseInfo{},
|
||||
}
|
||||
|
||||
var resp SendTypingResponse
|
||||
if err := c.doPost(ctx, "/ilink/bot/sendtyping", req, &resp); err != nil {
|
||||
return err
|
||||
}
|
||||
if resp.Ret != 0 {
|
||||
return fmt.Errorf("sendtyping failed: ret=%d errmsg=%s", resp.Ret, resp.ErrMsg)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetUploadURL gets a pre-signed CDN upload URL for media files.
|
||||
func (c *Client) GetUploadURL(ctx context.Context, req *GetUploadURLRequest) (*GetUploadURLResponse, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, sendTimeout)
|
||||
defer cancel()
|
||||
|
||||
var resp GetUploadURLResponse
|
||||
if err := c.doPost(ctx, "/ilink/bot/getuploadurl", req, &resp); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &resp, nil
|
||||
}
|
||||
|
||||
// BaseURL returns the base URL for CDN operations.
|
||||
func (c *Client) BaseURL() string {
|
||||
return c.baseURL
|
||||
}
|
||||
|
||||
func (c *Client) doPost(ctx context.Context, path string, body interface{}, result interface{}) error {
|
||||
data, err := json.Marshal(body)
|
||||
if err != nil {
|
||||
return fmt.Errorf("marshal request: %w", err)
|
||||
}
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.baseURL+path, bytes.NewReader(data))
|
||||
if err != nil {
|
||||
return fmt.Errorf("create request: %w", err)
|
||||
}
|
||||
c.setHeaders(req)
|
||||
|
||||
resp, err := c.httpClient.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
respBody, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return fmt.Errorf("read response: %w", err)
|
||||
}
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return fmt.Errorf("HTTP %d: %s", resp.StatusCode, string(respBody))
|
||||
}
|
||||
|
||||
if err := json.Unmarshal(respBody, result); err != nil {
|
||||
return fmt.Errorf("unmarshal response: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Client) doGet(ctx context.Context, url string, result interface{}) error {
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
|
||||
if err != nil {
|
||||
return fmt.Errorf("create request: %w", err)
|
||||
}
|
||||
|
||||
resp, err := c.httpClient.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
respBody, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return fmt.Errorf("read response: %w", err)
|
||||
}
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return fmt.Errorf("HTTP %d: %s", resp.StatusCode, string(respBody))
|
||||
}
|
||||
|
||||
if err := json.Unmarshal(respBody, result); err != nil {
|
||||
return fmt.Errorf("unmarshal response: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Client) setHeaders(req *http.Request) {
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("AuthorizationType", "ilink_bot_token")
|
||||
req.Header.Set("Authorization", "Bearer "+c.botToken)
|
||||
req.Header.Set("X-WECHAT-UIN", c.wechatUIN)
|
||||
}
|
||||
|
||||
func generateWechatUIN() string {
|
||||
var n uint32
|
||||
_ = binary.Read(rand.Reader, binary.LittleEndian, &n)
|
||||
s := fmt.Sprintf("%d", n)
|
||||
return base64.StdEncoding.EncodeToString([]byte(s))
|
||||
}
|
||||
@@ -0,0 +1,181 @@
|
||||
package ilink
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
maxConsecutiveFailures = 5
|
||||
initialBackoff = 3 * time.Second
|
||||
maxBackoff = 60 * time.Second
|
||||
sessionExpiredBackoff = 5 * time.Second
|
||||
errCodeSessionExpired = -14
|
||||
)
|
||||
|
||||
// MessageHandler is called for each received message.
|
||||
type MessageHandler func(ctx context.Context, client *Client, msg WeixinMessage)
|
||||
|
||||
// Monitor manages the long-poll loop for receiving messages.
|
||||
type Monitor struct {
|
||||
client *Client
|
||||
handler MessageHandler
|
||||
getUpdatesBuf string
|
||||
bufPath string
|
||||
failures int
|
||||
lastActivity time.Time
|
||||
}
|
||||
|
||||
// NewMonitor creates a new long-poll monitor.
|
||||
func NewMonitor(client *Client, handler MessageHandler) (*Monitor, error) {
|
||||
home, err := os.UserHomeDir()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
accountID := NormalizeAccountID(client.BotID())
|
||||
bufPath := filepath.Join(home, ".wechatexplorer", "wechat-connector", "accounts", accountID+".sync.json")
|
||||
|
||||
m := &Monitor{
|
||||
client: client,
|
||||
handler: handler,
|
||||
bufPath: bufPath,
|
||||
lastActivity: time.Now(),
|
||||
}
|
||||
m.loadBuf()
|
||||
return m, nil
|
||||
}
|
||||
|
||||
// Run starts the long-poll loop. It blocks until ctx is cancelled.
|
||||
// Automatically recovers from errors with exponential backoff.
|
||||
func (m *Monitor) Run(ctx context.Context) error {
|
||||
log.Println("[monitor] starting long-poll loop")
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
log.Println("[monitor] shutting down")
|
||||
return ctx.Err()
|
||||
default:
|
||||
}
|
||||
|
||||
resp, err := m.client.GetUpdates(ctx, m.getUpdatesBuf)
|
||||
if err != nil {
|
||||
if ctx.Err() != nil {
|
||||
return ctx.Err()
|
||||
}
|
||||
m.failures++
|
||||
backoff := m.calcBackoff()
|
||||
log.Printf("[monitor] GetUpdates error (%d/%d, backoff=%s): %v",
|
||||
m.failures, maxConsecutiveFailures, backoff, err)
|
||||
if m.failures == maxConsecutiveFailures {
|
||||
log.Printf("[monitor] WARNING: %d consecutive failures; reconnect from WechatExplorer if this persists.", maxConsecutiveFailures)
|
||||
}
|
||||
select {
|
||||
case <-time.After(backoff):
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
// Reset failure counter on any successful response
|
||||
m.failures = 0
|
||||
m.lastActivity = time.Now()
|
||||
|
||||
// Session expired — reset sync buf and reconnect silently
|
||||
if resp.ErrCode == errCodeSessionExpired {
|
||||
if m.getUpdatesBuf != "" {
|
||||
log.Printf("[monitor] session expired, resetting sync buf")
|
||||
m.getUpdatesBuf = ""
|
||||
m.saveBuf()
|
||||
} else {
|
||||
// Sync buf already empty but still getting session expired:
|
||||
// the bot token itself has expired. The user needs to re-login.
|
||||
log.Printf("[monitor] WARNING: WeChat session expired and cannot be auto-recovered; reconnect from WechatExplorer.")
|
||||
}
|
||||
select {
|
||||
case <-time.After(sessionExpiredBackoff):
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
// Other server errors
|
||||
if resp.Ret != 0 && resp.ErrCode != 0 {
|
||||
log.Printf("[monitor] server error: ret=%d errcode=%d errmsg=%s", resp.Ret, resp.ErrCode, resp.ErrMsg)
|
||||
continue
|
||||
}
|
||||
|
||||
// Update buf for next poll
|
||||
if resp.GetUpdatesBuf != "" {
|
||||
m.getUpdatesBuf = resp.GetUpdatesBuf
|
||||
m.saveBuf()
|
||||
}
|
||||
|
||||
// Process messages concurrently — don't block the poll loop
|
||||
for _, msg := range resp.Msgs {
|
||||
go m.handler(ctx, m.client, msg)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// calcBackoff returns an exponential backoff duration capped at maxBackoff.
|
||||
func (m *Monitor) calcBackoff() time.Duration {
|
||||
d := initialBackoff
|
||||
for i := 1; i < m.failures; i++ {
|
||||
d *= 2
|
||||
if d > maxBackoff {
|
||||
return maxBackoff
|
||||
}
|
||||
}
|
||||
return d
|
||||
}
|
||||
|
||||
type syncData struct {
|
||||
GetUpdatesBuf string `json:"get_updates_buf"`
|
||||
}
|
||||
|
||||
func (m *Monitor) loadBuf() {
|
||||
data, err := os.ReadFile(m.bufPath)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
var s syncData
|
||||
if json.Unmarshal(data, &s) == nil && s.GetUpdatesBuf != "" {
|
||||
m.getUpdatesBuf = s.GetUpdatesBuf
|
||||
log.Printf("[monitor] loaded sync buf from %s", m.bufPath)
|
||||
}
|
||||
}
|
||||
|
||||
func (m *Monitor) saveBuf() {
|
||||
dir := filepath.Dir(m.bufPath)
|
||||
if err := os.MkdirAll(dir, 0o700); err != nil {
|
||||
log.Printf("[monitor] failed to create buf dir: %v", err)
|
||||
return
|
||||
}
|
||||
data, _ := json.Marshal(syncData{GetUpdatesBuf: m.getUpdatesBuf})
|
||||
if err := os.WriteFile(m.bufPath, data, 0o600); err != nil {
|
||||
log.Printf("[monitor] failed to save buf: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// FormatMessageSummary returns a short description of a message for logging.
|
||||
func FormatMessageSummary(msg WeixinMessage) string {
|
||||
text := ""
|
||||
for _, item := range msg.ItemList {
|
||||
if item.Type == ItemTypeText && item.TextItem != nil {
|
||||
text = item.TextItem.Text
|
||||
break
|
||||
}
|
||||
}
|
||||
if len(text) > 50 {
|
||||
text = text[:50] + "..."
|
||||
}
|
||||
return fmt.Sprintf("from=%s type=%d state=%d text=%q", msg.FromUserID, msg.MessageType, msg.MessageState, text)
|
||||
}
|
||||
@@ -0,0 +1,219 @@
|
||||
package ilink
|
||||
|
||||
// Message types
|
||||
const (
|
||||
MessageTypeNone = 0
|
||||
MessageTypeUser = 1
|
||||
MessageTypeBot = 2
|
||||
)
|
||||
|
||||
// Message states
|
||||
const (
|
||||
MessageStateNew = 0
|
||||
MessageStateGenerating = 1
|
||||
MessageStateFinish = 2
|
||||
)
|
||||
|
||||
// Item types
|
||||
const (
|
||||
ItemTypeNone = 0
|
||||
ItemTypeText = 1
|
||||
ItemTypeImage = 2
|
||||
ItemTypeVoice = 3
|
||||
ItemTypeFile = 4
|
||||
ItemTypeVideo = 5
|
||||
)
|
||||
|
||||
// QRCodeResponse is the response from get_bot_qrcode.
|
||||
type QRCodeResponse struct {
|
||||
QRCode string `json:"qrcode"`
|
||||
QRCodeImgContent string `json:"qrcode_img_content"`
|
||||
}
|
||||
|
||||
// QRStatusResponse is the response from get_qrcode_status.
|
||||
type QRStatusResponse struct {
|
||||
Status string `json:"status"`
|
||||
BotToken string `json:"bot_token"`
|
||||
ILinkBotID string `json:"ilink_bot_id"`
|
||||
BaseURL string `json:"baseurl"`
|
||||
ILinkUserID string `json:"ilink_user_id"`
|
||||
}
|
||||
|
||||
// Credentials stores login session data.
|
||||
type Credentials struct {
|
||||
BotToken string `json:"bot_token"`
|
||||
ILinkBotID string `json:"ilink_bot_id"`
|
||||
BaseURL string `json:"baseurl"`
|
||||
ILinkUserID string `json:"ilink_user_id"`
|
||||
}
|
||||
|
||||
// BaseInfo is included in request bodies.
|
||||
type BaseInfo struct {
|
||||
ChannelVersion string `json:"channel_version,omitempty"`
|
||||
}
|
||||
|
||||
// GetUpdatesRequest is the body for getupdates.
|
||||
type GetUpdatesRequest struct {
|
||||
GetUpdatesBuf string `json:"get_updates_buf"`
|
||||
BaseInfo BaseInfo `json:"base_info"`
|
||||
}
|
||||
|
||||
// GetUpdatesResponse is the response from getupdates.
|
||||
type GetUpdatesResponse struct {
|
||||
Ret int `json:"ret"`
|
||||
ErrCode int `json:"errcode,omitempty"`
|
||||
ErrMsg string `json:"errmsg,omitempty"`
|
||||
Msgs []WeixinMessage `json:"msgs"`
|
||||
GetUpdatesBuf string `json:"get_updates_buf"`
|
||||
LongPollingTimeoutMs int `json:"longpolling_timeout_ms,omitempty"`
|
||||
}
|
||||
|
||||
// WeixinMessage represents a message from WeChat.
|
||||
type WeixinMessage struct {
|
||||
Seq int `json:"seq,omitempty"`
|
||||
MessageID int64 `json:"message_id,omitempty"`
|
||||
FromUserID string `json:"from_user_id"`
|
||||
ToUserID string `json:"to_user_id"`
|
||||
MessageType int `json:"message_type"`
|
||||
MessageState int `json:"message_state"`
|
||||
ItemList []MessageItem `json:"item_list"`
|
||||
ContextToken string `json:"context_token"`
|
||||
}
|
||||
|
||||
// MessageItem is a single item in a message.
|
||||
type MessageItem struct {
|
||||
Type int `json:"type"`
|
||||
TextItem *TextItem `json:"text_item,omitempty"`
|
||||
ImageItem *ImageItem `json:"image_item,omitempty"`
|
||||
VoiceItem *VoiceItem `json:"voice_item,omitempty"`
|
||||
VideoItem *VideoItem `json:"video_item,omitempty"`
|
||||
FileItem *FileItem `json:"file_item,omitempty"`
|
||||
}
|
||||
|
||||
// CDN media type constants.
|
||||
const (
|
||||
CDNMediaTypeImage = 1
|
||||
CDNMediaTypeVideo = 2
|
||||
CDNMediaTypeFile = 3
|
||||
)
|
||||
|
||||
// GetUploadURLRequest is the body for getuploadurl.
|
||||
type GetUploadURLRequest struct {
|
||||
FileKey string `json:"filekey"`
|
||||
MediaType int `json:"media_type"`
|
||||
ToUserID string `json:"to_user_id"`
|
||||
RawSize int `json:"rawsize"`
|
||||
RawFileMD5 string `json:"rawfilemd5"`
|
||||
FileSize int `json:"filesize"`
|
||||
NoNeedThumb bool `json:"no_need_thumb"`
|
||||
AESKey string `json:"aeskey"`
|
||||
BaseInfo BaseInfo `json:"base_info"`
|
||||
}
|
||||
|
||||
// GetUploadURLResponse is the response from getuploadurl.
|
||||
type GetUploadURLResponse struct {
|
||||
Ret int `json:"ret"`
|
||||
ErrMsg string `json:"errmsg,omitempty"`
|
||||
UploadParam string `json:"upload_param"`
|
||||
UploadFullURL string `json:"upload_full_url,omitempty"`
|
||||
}
|
||||
|
||||
// TextItem holds text content.
|
||||
type TextItem struct {
|
||||
Text string `json:"text"`
|
||||
}
|
||||
|
||||
// MediaInfo holds CDN media reference for uploaded files.
|
||||
type MediaInfo struct {
|
||||
EncryptQueryParam string `json:"encrypt_query_param"`
|
||||
AESKey string `json:"aes_key"` // base64-encoded
|
||||
EncryptType int `json:"encrypt_type"` // 1 = AES-128-ECB
|
||||
}
|
||||
|
||||
// VoiceItem holds voice content.
|
||||
type VoiceItem struct {
|
||||
Media *MediaInfo `json:"media,omitempty"`
|
||||
VoiceSize int `json:"voice_size,omitempty"`
|
||||
EncodeType int `json:"encode_type,omitempty"` // 1=pcm 2=adpcm 3=feature 4=speex 5=amr 6=silk 7=mp3
|
||||
BitsPerSample int `json:"bits_per_sample,omitempty"`
|
||||
SampleRate int `json:"sample_rate,omitempty"` // Hz
|
||||
Playtime int `json:"playtime,omitempty"` // duration in milliseconds
|
||||
Text string `json:"text,omitempty"` // speech-to-text transcription from WeChat
|
||||
}
|
||||
|
||||
// ImageItem holds image content.
|
||||
type ImageItem struct {
|
||||
URL string `json:"url,omitempty"`
|
||||
Media *MediaInfo `json:"media,omitempty"`
|
||||
MidSize int `json:"mid_size,omitempty"` // ciphertext size
|
||||
}
|
||||
|
||||
// VideoItem holds video content.
|
||||
type VideoItem struct {
|
||||
Media *MediaInfo `json:"media,omitempty"`
|
||||
VideoSize int `json:"video_size,omitempty"`
|
||||
}
|
||||
|
||||
// FileItem holds file content.
|
||||
type FileItem struct {
|
||||
Media *MediaInfo `json:"media,omitempty"`
|
||||
FileName string `json:"file_name,omitempty"`
|
||||
Len string `json:"len,omitempty"` // plaintext size as string
|
||||
}
|
||||
|
||||
// SendMessageRequest is the body for sendmessage.
|
||||
type SendMessageRequest struct {
|
||||
Msg SendMsg `json:"msg"`
|
||||
BaseInfo BaseInfo `json:"base_info"`
|
||||
}
|
||||
|
||||
// SendMsg is the message payload for sending.
|
||||
type SendMsg struct {
|
||||
FromUserID string `json:"from_user_id"`
|
||||
ToUserID string `json:"to_user_id"`
|
||||
ClientID string `json:"client_id"`
|
||||
MessageType int `json:"message_type"`
|
||||
MessageState int `json:"message_state"`
|
||||
ItemList []MessageItem `json:"item_list"`
|
||||
ContextToken string `json:"context_token"`
|
||||
}
|
||||
|
||||
// SendMessageResponse is the response from sendmessage.
|
||||
type SendMessageResponse struct {
|
||||
Ret int `json:"ret"`
|
||||
ErrMsg string `json:"errmsg,omitempty"`
|
||||
}
|
||||
|
||||
// Typing status constants.
|
||||
const (
|
||||
TypingStatusTyping = 1
|
||||
TypingStatusCancel = 2
|
||||
)
|
||||
|
||||
// GetConfigRequest is the body for getconfig.
|
||||
type GetConfigRequest struct {
|
||||
ILinkUserID string `json:"ilink_user_id"`
|
||||
ContextToken string `json:"context_token,omitempty"`
|
||||
BaseInfo BaseInfo `json:"base_info"`
|
||||
}
|
||||
|
||||
// GetConfigResponse is the response from getconfig.
|
||||
type GetConfigResponse struct {
|
||||
Ret int `json:"ret"`
|
||||
ErrMsg string `json:"errmsg,omitempty"`
|
||||
TypingTicket string `json:"typing_ticket,omitempty"`
|
||||
}
|
||||
|
||||
// SendTypingRequest is the body for sendtyping.
|
||||
type SendTypingRequest struct {
|
||||
ILinkUserID string `json:"ilink_user_id"`
|
||||
TypingTicket string `json:"typing_ticket"`
|
||||
Status int `json:"status"`
|
||||
BaseInfo BaseInfo `json:"base_info"`
|
||||
}
|
||||
|
||||
// SendTypingResponse is the response from sendtyping.
|
||||
type SendTypingResponse struct {
|
||||
Ret int `json:"ret"`
|
||||
ErrMsg string `json:"errmsg,omitempty"`
|
||||
}
|
||||
@@ -0,0 +1,200 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
"os/signal"
|
||||
"strings"
|
||||
"sync"
|
||||
"syscall"
|
||||
|
||||
"github.com/Wxw-Gu/WechatExplorer/services/wechat-connector/api"
|
||||
"github.com/Wxw-Gu/WechatExplorer/services/wechat-connector/ilink"
|
||||
"github.com/Wxw-Gu/WechatExplorer/services/wechat-connector/messaging"
|
||||
"rsc.io/qr"
|
||||
)
|
||||
|
||||
type loginEvent struct {
|
||||
Status string `json:"status"`
|
||||
QRCodeDataURL string `json:"qr_code_data_url,omitempty"`
|
||||
AccountID string `json:"account_id,omitempty"`
|
||||
WeChatUserID string `json:"wechat_user_id,omitempty"`
|
||||
}
|
||||
|
||||
type accountSummary struct {
|
||||
AccountID string `json:"account_id"`
|
||||
WeChatUserID string `json:"wechat_user_id"`
|
||||
}
|
||||
|
||||
func main() {
|
||||
if len(os.Args) < 2 {
|
||||
fatal(errors.New("expected one of: login, accounts, start"))
|
||||
}
|
||||
var err error
|
||||
switch os.Args[1] {
|
||||
case "login":
|
||||
err = runLogin(os.Args[2:])
|
||||
case "accounts":
|
||||
err = runAccounts(os.Args[2:])
|
||||
case "start":
|
||||
err = runStart(os.Args[2:])
|
||||
default:
|
||||
err = fmt.Errorf("unknown command %q", os.Args[1])
|
||||
}
|
||||
if err != nil {
|
||||
fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func fatal(err error) {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
func signalContext() (context.Context, context.CancelFunc) {
|
||||
return signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
|
||||
}
|
||||
|
||||
func runLogin(args []string) error {
|
||||
flags := flag.NewFlagSet("login", flag.ContinueOnError)
|
||||
jsonOutput := flags.Bool("json", false, "emit JSON Lines events")
|
||||
if err := flags.Parse(args); err != nil {
|
||||
return err
|
||||
}
|
||||
ctx, cancel := signalContext()
|
||||
defer cancel()
|
||||
creds, err := login(ctx, *jsonOutput)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !*jsonOutput {
|
||||
fmt.Printf("WeChat account %s connected.\n", creds.ILinkBotID)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func login(ctx context.Context, jsonOutput bool) (*ilink.Credentials, error) {
|
||||
qrResponse, err := ilink.FetchQRCode(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
code, err := qr.Encode(qrResponse.QRCodeImgContent, qr.L)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("encode QR image: %w", err)
|
||||
}
|
||||
emit := func(event loginEvent) {
|
||||
if jsonOutput {
|
||||
_ = json.NewEncoder(os.Stdout).Encode(event)
|
||||
}
|
||||
}
|
||||
emit(loginEvent{Status: "qrcode", QRCodeDataURL: "data:image/png;base64," + base64.StdEncoding.EncodeToString(code.PNG())})
|
||||
lastStatus := ""
|
||||
creds, err := ilink.PollQRStatus(ctx, qrResponse.QRCode, func(status string) {
|
||||
if status != lastStatus {
|
||||
lastStatus = status
|
||||
emit(loginEvent{Status: status})
|
||||
}
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := ilink.SaveCredentials(creds); err != nil {
|
||||
return nil, fmt.Errorf("save credentials: %w", err)
|
||||
}
|
||||
emit(loginEvent{Status: "active", AccountID: creds.ILinkBotID, WeChatUserID: creds.ILinkUserID})
|
||||
return creds, nil
|
||||
}
|
||||
|
||||
func runAccounts(args []string) error {
|
||||
flags := flag.NewFlagSet("accounts", flag.ContinueOnError)
|
||||
jsonOutput := flags.Bool("json", false, "print JSON")
|
||||
if err := flags.Parse(args); err != nil {
|
||||
return err
|
||||
}
|
||||
accounts, err := ilink.LoadAllCredentials()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
items := make([]accountSummary, 0, len(accounts))
|
||||
for _, account := range accounts {
|
||||
items = append(items, accountSummary{AccountID: account.ILinkBotID, WeChatUserID: account.ILinkUserID})
|
||||
}
|
||||
if *jsonOutput {
|
||||
return json.NewEncoder(os.Stdout).Encode(map[string]any{"accounts": items})
|
||||
}
|
||||
for _, item := range items {
|
||||
fmt.Printf("%s\t%s\n", item.AccountID, item.WeChatUserID)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func runStart(args []string) error {
|
||||
flags := flag.NewFlagSet("start", flag.ContinueOnError)
|
||||
_ = flags.Bool("foreground", false, "kept for host compatibility")
|
||||
apiAddr := flags.String("api-addr", "127.0.0.1:18011", "local send API address")
|
||||
accountID := flags.String("account-id", "", "account to start")
|
||||
if err := flags.Parse(args); err != nil {
|
||||
return err
|
||||
}
|
||||
accounts, err := ilink.LoadAllCredentials()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(accounts) == 0 {
|
||||
return errors.New("no connected WeChat account; scan a QR code first")
|
||||
}
|
||||
selected := accounts[len(accounts)-1]
|
||||
if *accountID != "" {
|
||||
selected = nil
|
||||
for _, account := range accounts {
|
||||
if account.ILinkBotID == *accountID {
|
||||
selected = account
|
||||
break
|
||||
}
|
||||
}
|
||||
if selected == nil {
|
||||
return fmt.Errorf("account %q not found", *accountID)
|
||||
}
|
||||
}
|
||||
|
||||
ctx, cancel := signalContext()
|
||||
defer cancel()
|
||||
client := ilink.NewClient(selected)
|
||||
server := api.NewServer([]*ilink.Client{client}, *apiAddr)
|
||||
webhookURL := strings.TrimSpace(os.Getenv("WECHAT_CONNECTOR_INBOUND_WEBHOOK_URL"))
|
||||
webhook := messaging.NewInboundWebhook(webhookURL, os.Getenv("WECHAT_CONNECTOR_INBOUND_WEBHOOK_TOKEN"))
|
||||
|
||||
monitor, err := ilink.NewMonitor(client, func(messageContext context.Context, source *ilink.Client, message ilink.WeixinMessage) {
|
||||
if webhookURL != "" {
|
||||
webhook.Dispatch(messageContext, source, message)
|
||||
}
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var wait sync.WaitGroup
|
||||
wait.Add(2)
|
||||
go func() {
|
||||
defer wait.Done()
|
||||
if err := server.Run(ctx); err != nil && ctx.Err() == nil {
|
||||
log.Printf("[api] stopped: %v", err)
|
||||
cancel()
|
||||
}
|
||||
}()
|
||||
go func() {
|
||||
defer wait.Done()
|
||||
if err := monitor.Run(ctx); err != nil && ctx.Err() == nil {
|
||||
log.Printf("[monitor] stopped: %v", err)
|
||||
cancel()
|
||||
}
|
||||
}()
|
||||
wait.Wait()
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,232 @@
|
||||
package messaging
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/aes"
|
||||
"crypto/md5"
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/Wxw-Gu/WechatExplorer/services/wechat-connector/ilink"
|
||||
)
|
||||
|
||||
const cdnBaseURL = "https://novac2c.cdn.weixin.qq.com/c2c"
|
||||
|
||||
// UploadedFile holds the result of a CDN upload.
|
||||
type UploadedFile struct {
|
||||
DownloadParam string // encrypted query param for download
|
||||
AESKeyHex string // hex-encoded AES key
|
||||
FileSize int // plaintext size
|
||||
CipherSize int // ciphertext size
|
||||
}
|
||||
|
||||
// UploadFileToCDN encrypts and uploads a file to the WeChat CDN.
|
||||
func UploadFileToCDN(ctx context.Context, client *ilink.Client, data []byte, toUserID string, mediaType int) (*UploadedFile, error) {
|
||||
// Generate random filekey and AES key
|
||||
filekey := make([]byte, 16)
|
||||
aeskey := make([]byte, 16)
|
||||
if _, err := rand.Read(filekey); err != nil {
|
||||
return nil, fmt.Errorf("generate filekey: %w", err)
|
||||
}
|
||||
if _, err := rand.Read(aeskey); err != nil {
|
||||
return nil, fmt.Errorf("generate aeskey: %w", err)
|
||||
}
|
||||
|
||||
filekeyHex := hex.EncodeToString(filekey)
|
||||
aeskeyHex := hex.EncodeToString(aeskey)
|
||||
|
||||
// Calculate MD5 of plaintext
|
||||
hash := md5.Sum(data)
|
||||
rawMD5 := hex.EncodeToString(hash[:])
|
||||
|
||||
// Calculate ciphertext size (PKCS7 padding)
|
||||
cipherSize := aesECBPaddedSize(len(data))
|
||||
|
||||
// Get upload URL from iLink API
|
||||
uploadReq := &ilink.GetUploadURLRequest{
|
||||
FileKey: filekeyHex,
|
||||
MediaType: mediaType,
|
||||
ToUserID: toUserID,
|
||||
RawSize: len(data),
|
||||
RawFileMD5: rawMD5,
|
||||
FileSize: cipherSize,
|
||||
NoNeedThumb: true,
|
||||
AESKey: aeskeyHex,
|
||||
BaseInfo: ilink.BaseInfo{},
|
||||
}
|
||||
|
||||
uploadResp, err := client.GetUploadURL(ctx, uploadReq)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("get upload URL: %w", err)
|
||||
}
|
||||
if uploadResp.Ret != 0 {
|
||||
return nil, fmt.Errorf("get upload URL failed: ret=%d errmsg=%s", uploadResp.Ret, uploadResp.ErrMsg)
|
||||
}
|
||||
|
||||
// Encrypt data with AES-128-ECB
|
||||
encrypted, err := encryptAESECB(data, aeskey)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("encrypt: %w", err)
|
||||
}
|
||||
|
||||
// Upload to CDN: prefer server-provided full URL, fall back to param-based construction
|
||||
cdnURL := strings.TrimSpace(uploadResp.UploadFullURL)
|
||||
if cdnURL == "" {
|
||||
if uploadResp.UploadParam == "" {
|
||||
return nil, fmt.Errorf("getuploadurl returned no upload URL (need upload_full_url or upload_param)")
|
||||
}
|
||||
cdnURL = fmt.Sprintf("%s/upload?encrypted_query_param=%s&filekey=%s",
|
||||
cdnBaseURL, url.QueryEscape(uploadResp.UploadParam), url.QueryEscape(filekeyHex))
|
||||
}
|
||||
|
||||
downloadParam, err := uploadToCDN(ctx, encrypted, cdnURL)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("CDN upload: %w", err)
|
||||
}
|
||||
|
||||
return &UploadedFile{
|
||||
DownloadParam: downloadParam,
|
||||
AESKeyHex: aeskeyHex,
|
||||
FileSize: len(data),
|
||||
CipherSize: cipherSize,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// AESKeyToBase64 converts a hex AES key to base64 format for message items.
|
||||
func AESKeyToBase64(hexKey string) string {
|
||||
return base64.StdEncoding.EncodeToString([]byte(hexKey))
|
||||
}
|
||||
|
||||
// DownloadFileFromCDN downloads and decrypts a file from the WeChat CDN.
|
||||
func DownloadFileFromCDN(ctx context.Context, encryptQueryParam, aesKeyBase64 string) ([]byte, error) {
|
||||
// Decode AES key: base64 -> hex string -> raw bytes
|
||||
aesKeyHexBytes, err := base64.StdEncoding.DecodeString(aesKeyBase64)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("decode AES key base64: %w", err)
|
||||
}
|
||||
aesKey, err := hex.DecodeString(string(aesKeyHexBytes))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("decode AES key hex: %w", err)
|
||||
}
|
||||
|
||||
// Download encrypted data from CDN
|
||||
downloadURL := fmt.Sprintf("%s/download?encrypted_query_param=%s",
|
||||
cdnBaseURL, url.QueryEscape(encryptQueryParam))
|
||||
|
||||
reqCtx, cancel := context.WithTimeout(ctx, 60*time.Second)
|
||||
defer cancel()
|
||||
|
||||
req, err := http.NewRequestWithContext(reqCtx, http.MethodGet, downloadURL, nil)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create download request: %w", err)
|
||||
}
|
||||
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("download from CDN: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
body, _ := io.ReadAll(resp.Body)
|
||||
return nil, fmt.Errorf("CDN download HTTP %d: %s", resp.StatusCode, string(body))
|
||||
}
|
||||
|
||||
encrypted, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read CDN response: %w", err)
|
||||
}
|
||||
|
||||
// Decrypt AES-128-ECB
|
||||
return decryptAESECB(encrypted, aesKey)
|
||||
}
|
||||
|
||||
// decryptAESECB decrypts data encrypted with AES-128-ECB and removes PKCS7 padding.
|
||||
func decryptAESECB(ciphertext, key []byte) ([]byte, error) {
|
||||
block, err := aes.NewCipher(key)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if len(ciphertext)%aes.BlockSize != 0 {
|
||||
return nil, fmt.Errorf("ciphertext is not a multiple of block size")
|
||||
}
|
||||
|
||||
plaintext := make([]byte, len(ciphertext))
|
||||
for i := 0; i < len(ciphertext); i += aes.BlockSize {
|
||||
block.Decrypt(plaintext[i:i+aes.BlockSize], ciphertext[i:i+aes.BlockSize])
|
||||
}
|
||||
|
||||
// Remove PKCS7 padding
|
||||
if len(plaintext) == 0 {
|
||||
return plaintext, nil
|
||||
}
|
||||
padLen := int(plaintext[len(plaintext)-1])
|
||||
if padLen > aes.BlockSize || padLen == 0 {
|
||||
return nil, fmt.Errorf("invalid PKCS7 padding")
|
||||
}
|
||||
return plaintext[:len(plaintext)-padLen], nil
|
||||
}
|
||||
|
||||
func uploadToCDN(ctx context.Context, encrypted []byte, cdnURL string) (string, error) {
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, cdnURL, bytes.NewReader(encrypted))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/octet-stream")
|
||||
|
||||
client := &http.Client{Timeout: 60 * time.Second}
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
body, _ := io.ReadAll(resp.Body)
|
||||
return "", fmt.Errorf("CDN upload HTTP %d: %s", resp.StatusCode, string(body))
|
||||
}
|
||||
|
||||
downloadParam := resp.Header.Get("X-Encrypted-Param")
|
||||
if downloadParam == "" {
|
||||
return "", fmt.Errorf("CDN upload: missing X-Encrypted-Param header")
|
||||
}
|
||||
|
||||
return downloadParam, nil
|
||||
}
|
||||
|
||||
// encryptAESECB encrypts data using AES-128-ECB with PKCS7 padding.
|
||||
func encryptAESECB(plaintext, key []byte) ([]byte, error) {
|
||||
block, err := aes.NewCipher(key)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// PKCS7 padding
|
||||
padLen := aes.BlockSize - (len(plaintext) % aes.BlockSize)
|
||||
padded := make([]byte, len(plaintext)+padLen)
|
||||
copy(padded, plaintext)
|
||||
for i := len(plaintext); i < len(padded); i++ {
|
||||
padded[i] = byte(padLen)
|
||||
}
|
||||
|
||||
// ECB mode: encrypt each block independently
|
||||
encrypted := make([]byte, len(padded))
|
||||
for i := 0; i < len(padded); i += aes.BlockSize {
|
||||
block.Encrypt(encrypted[i:i+aes.BlockSize], padded[i:i+aes.BlockSize])
|
||||
}
|
||||
|
||||
return encrypted, nil
|
||||
}
|
||||
|
||||
func aesECBPaddedSize(plaintextSize int) int {
|
||||
return (plaintextSize/aes.BlockSize + 1) * aes.BlockSize
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
package messaging
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/Wxw-Gu/WechatExplorer/services/wechat-connector/ilink"
|
||||
)
|
||||
|
||||
const (
|
||||
webhookAttempts = 3
|
||||
webhookTimeout = 5 * time.Second
|
||||
)
|
||||
|
||||
type InboundWebhook struct {
|
||||
url string
|
||||
token string
|
||||
client *http.Client
|
||||
}
|
||||
|
||||
type inboundWebhookPayload struct {
|
||||
AccountID string `json:"account_id"`
|
||||
FromUserID string `json:"from_user_id"`
|
||||
MessageID int64 `json:"message_id"`
|
||||
MessageType int `json:"message_type"`
|
||||
Items []inboundWebhookItem `json:"items"`
|
||||
ReceivedAt time.Time `json:"received_at"`
|
||||
}
|
||||
|
||||
type inboundWebhookItem struct {
|
||||
Type int `json:"type"`
|
||||
Text string `json:"text,omitempty"`
|
||||
}
|
||||
|
||||
func NewInboundWebhook(url, token string) *InboundWebhook {
|
||||
return &InboundWebhook{
|
||||
url: strings.TrimSpace(url),
|
||||
token: token,
|
||||
client: &http.Client{Timeout: webhookTimeout},
|
||||
}
|
||||
}
|
||||
|
||||
// Dispatch is intentionally non-blocking so webhook failures never stall iLink polling.
|
||||
func (w *InboundWebhook) Dispatch(ctx context.Context, client *ilink.Client, msg ilink.WeixinMessage) {
|
||||
payload := normalizeInboundMessage(client.BotID(), msg)
|
||||
go func() {
|
||||
if err := w.deliver(ctx, payload); err != nil {
|
||||
log.Printf("[webhook] inbound delivery failed for message %d: %v", msg.MessageID, err)
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
func (w *InboundWebhook) deliver(ctx context.Context, payload inboundWebhookPayload) error {
|
||||
body, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
return fmt.Errorf("encode payload: %w", err)
|
||||
}
|
||||
var lastErr error
|
||||
for attempt := 1; attempt <= webhookAttempts; attempt++ {
|
||||
if attempt > 1 {
|
||||
timer := time.NewTimer(time.Duration(attempt-1) * time.Second)
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
timer.Stop()
|
||||
return ctx.Err()
|
||||
case <-timer.C:
|
||||
}
|
||||
}
|
||||
req, reqErr := http.NewRequestWithContext(ctx, http.MethodPost, w.url, bytes.NewReader(body))
|
||||
if reqErr != nil {
|
||||
return fmt.Errorf("create request: %w", reqErr)
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
if w.token != "" {
|
||||
req.Header.Set("Authorization", "Bearer "+w.token)
|
||||
}
|
||||
resp, doErr := w.client.Do(req)
|
||||
if doErr != nil {
|
||||
lastErr = doErr
|
||||
continue
|
||||
}
|
||||
responseBody, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))
|
||||
resp.Body.Close()
|
||||
if resp.StatusCode >= 200 && resp.StatusCode < 300 {
|
||||
return nil
|
||||
}
|
||||
lastErr = fmt.Errorf("status %s: %s", resp.Status, strings.TrimSpace(string(responseBody)))
|
||||
if resp.StatusCode >= 400 && resp.StatusCode < 500 {
|
||||
break
|
||||
}
|
||||
}
|
||||
return lastErr
|
||||
}
|
||||
|
||||
func normalizeInboundMessage(accountID string, msg ilink.WeixinMessage) inboundWebhookPayload {
|
||||
items := make([]inboundWebhookItem, 0, len(msg.ItemList))
|
||||
for _, item := range msg.ItemList {
|
||||
normalized := inboundWebhookItem{Type: item.Type}
|
||||
if item.TextItem != nil {
|
||||
normalized.Text = item.TextItem.Text
|
||||
} else if item.VoiceItem != nil {
|
||||
normalized.Text = item.VoiceItem.Text
|
||||
}
|
||||
items = append(items, normalized)
|
||||
}
|
||||
return inboundWebhookPayload{
|
||||
AccountID: accountID,
|
||||
FromUserID: msg.FromUserID,
|
||||
MessageID: msg.MessageID,
|
||||
MessageType: msg.MessageType,
|
||||
Items: items,
|
||||
ReceivedAt: time.Now().UTC(),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package messaging
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
|
||||
"github.com/Wxw-Gu/WechatExplorer/services/wechat-connector/ilink"
|
||||
)
|
||||
|
||||
func TestInboundWebhookDeliversNormalizedPayload(t *testing.T) {
|
||||
var got inboundWebhookPayload
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Header.Get("Authorization") != "Bearer secret" {
|
||||
t.Errorf("authorization = %q", r.Header.Get("Authorization"))
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&got); err != nil {
|
||||
t.Errorf("decode: %v", err)
|
||||
}
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
webhook := NewInboundWebhook(server.URL, "secret")
|
||||
err := webhook.deliver(context.Background(), normalizeInboundMessage("bot-new", ilink.WeixinMessage{
|
||||
MessageID: 7, FromUserID: "user-1", MessageType: ilink.MessageTypeUser,
|
||||
ItemList: []ilink.MessageItem{{Type: ilink.ItemTypeText, TextItem: &ilink.TextItem{Text: "最近5条消息"}}},
|
||||
}))
|
||||
if err != nil {
|
||||
t.Fatalf("deliver: %v", err)
|
||||
}
|
||||
if got.AccountID != "bot-new" || got.MessageID != 7 || len(got.Items) != 1 || got.Items[0].Text != "最近5条消息" {
|
||||
t.Fatalf("payload = %#v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInboundWebhookRetriesServerErrors(t *testing.T) {
|
||||
var calls atomic.Int32
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
if calls.Add(1) < 3 {
|
||||
http.Error(w, "temporary", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
webhook := NewInboundWebhook(server.URL, "")
|
||||
if err := webhook.deliver(context.Background(), inboundWebhookPayload{}); err != nil {
|
||||
t.Fatalf("deliver: %v", err)
|
||||
}
|
||||
if calls.Load() != 3 {
|
||||
t.Fatalf("calls = %d, want 3", calls.Load())
|
||||
}
|
||||
}
|
||||
|
||||
func TestInboundWebhookDoesNotRetryClientErrors(t *testing.T) {
|
||||
var calls atomic.Int32
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
calls.Add(1)
|
||||
http.Error(w, "unauthorized", http.StatusUnauthorized)
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
webhook := NewInboundWebhook(server.URL, "")
|
||||
if err := webhook.deliver(context.Background(), inboundWebhookPayload{}); err == nil {
|
||||
t.Fatal("deliver error = nil")
|
||||
}
|
||||
if calls.Load() != 1 {
|
||||
t.Fatalf("calls = %d, want 1", calls.Load())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
package messaging
|
||||
|
||||
import (
|
||||
"regexp"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var (
|
||||
// Code blocks: strip fences, keep code content
|
||||
reCodeBlock = regexp.MustCompile("(?s)```[^\n]*\n?(.*?)```")
|
||||
// Inline code: strip backticks, keep content
|
||||
reInlineCode = regexp.MustCompile("`([^`]+)`")
|
||||
// Images: remove entirely
|
||||
reImage = regexp.MustCompile(`!\[[^\]]*\]\([^)]*\)`)
|
||||
// Links: keep display text only
|
||||
reLink = regexp.MustCompile(`\[([^\]]+)\]\([^)]*\)`)
|
||||
// Table separator rows: remove
|
||||
reTableSep = regexp.MustCompile(`(?m)^\|[\s:|\-]+\|$`)
|
||||
// Table rows: convert pipe-delimited to space-delimited
|
||||
reTableRow = regexp.MustCompile(`(?m)^\|(.+)\|$`)
|
||||
// Headers: remove # prefix
|
||||
reHeader = regexp.MustCompile(`(?m)^#{1,6}\s+`)
|
||||
// Bold: **text** or __text__
|
||||
reBold = regexp.MustCompile(`\*\*(.+?)\*\*|__(.+?)__`)
|
||||
// Italic: *text* or _text_
|
||||
reItalic = regexp.MustCompile(`(?:^|[^*])\*([^*]+)\*(?:[^*]|$)|(?:^|[^_])_([^_]+)_(?:[^_]|$)`)
|
||||
// Strikethrough: ~~text~~
|
||||
reStrike = regexp.MustCompile(`~~(.+?)~~`)
|
||||
// Blockquote: > prefix
|
||||
reBlockquote = regexp.MustCompile(`(?m)^>\s?`)
|
||||
// Horizontal rule
|
||||
reHR = regexp.MustCompile(`(?m)^[-*_]{3,}\s*$`)
|
||||
// Unordered list markers: -, *, +
|
||||
reUL = regexp.MustCompile(`(?m)^(\s*)[-*+]\s+`)
|
||||
)
|
||||
|
||||
// MarkdownToPlainText converts markdown to readable plain text for WeChat.
|
||||
func MarkdownToPlainText(text string) string {
|
||||
result := text
|
||||
|
||||
// Code blocks: strip fences, keep code content
|
||||
result = reCodeBlock.ReplaceAllStringFunc(result, func(match string) string {
|
||||
parts := reCodeBlock.FindStringSubmatch(match)
|
||||
if len(parts) > 1 {
|
||||
return strings.TrimSpace(parts[1])
|
||||
}
|
||||
return match
|
||||
})
|
||||
|
||||
// Images: remove entirely
|
||||
result = reImage.ReplaceAllString(result, "")
|
||||
|
||||
// Links: keep display text only
|
||||
result = reLink.ReplaceAllString(result, "$1")
|
||||
|
||||
// Table separator rows: remove
|
||||
result = reTableSep.ReplaceAllString(result, "")
|
||||
|
||||
// Table rows: pipe-delimited to space-delimited
|
||||
result = reTableRow.ReplaceAllStringFunc(result, func(match string) string {
|
||||
parts := reTableRow.FindStringSubmatch(match)
|
||||
if len(parts) > 1 {
|
||||
cells := strings.Split(parts[1], "|")
|
||||
for i := range cells {
|
||||
cells[i] = strings.TrimSpace(cells[i])
|
||||
}
|
||||
return strings.Join(cells, " ")
|
||||
}
|
||||
return match
|
||||
})
|
||||
|
||||
// Headers: remove # prefix
|
||||
result = reHeader.ReplaceAllString(result, "")
|
||||
|
||||
// Bold
|
||||
result = reBold.ReplaceAllStringFunc(result, func(match string) string {
|
||||
parts := reBold.FindStringSubmatch(match)
|
||||
if parts[1] != "" {
|
||||
return parts[1]
|
||||
}
|
||||
return parts[2]
|
||||
})
|
||||
|
||||
// Strikethrough
|
||||
result = reStrike.ReplaceAllString(result, "$1")
|
||||
|
||||
// Blockquote
|
||||
result = reBlockquote.ReplaceAllString(result, "")
|
||||
|
||||
// Horizontal rule -> empty line
|
||||
result = reHR.ReplaceAllString(result, "")
|
||||
|
||||
// Unordered list: replace markers with "• "
|
||||
result = reUL.ReplaceAllString(result, "${1}• ")
|
||||
|
||||
// Inline code: strip backticks (do after code blocks)
|
||||
result = reInlineCode.ReplaceAllString(result, "$1")
|
||||
|
||||
// Clean up excessive blank lines
|
||||
result = regexp.MustCompile(`\n{3,}`).ReplaceAllString(result, "\n\n")
|
||||
|
||||
return strings.TrimSpace(result)
|
||||
}
|
||||
@@ -0,0 +1,221 @@
|
||||
package messaging
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"mime"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/Wxw-Gu/WechatExplorer/services/wechat-connector/ilink"
|
||||
)
|
||||
|
||||
// reMarkdownImage matches markdown image syntax: 
|
||||
var reMarkdownImage = regexp.MustCompile(`!\[[^\]]*\]\(([^)]+)\)`)
|
||||
|
||||
// ExtractImageURLs extracts image URLs from markdown text.
|
||||
func ExtractImageURLs(text string) []string {
|
||||
matches := reMarkdownImage.FindAllStringSubmatch(text, -1)
|
||||
var urls []string
|
||||
for _, m := range matches {
|
||||
url := strings.TrimSpace(m[1])
|
||||
if strings.HasPrefix(url, "http://") || strings.HasPrefix(url, "https://") {
|
||||
urls = append(urls, url)
|
||||
}
|
||||
}
|
||||
return urls
|
||||
}
|
||||
|
||||
// SendMediaFromURL sends a local file or downloads from a URL and sends it as a media message.
|
||||
func SendMediaFromURL(ctx context.Context, client *ilink.Client, toUserID, mediaURL, contextToken string) error {
|
||||
// Check if it's a local file
|
||||
if _, err := os.Stat(mediaURL); err == nil {
|
||||
return SendMediaFromPath(ctx, client, toUserID, mediaURL, contextToken)
|
||||
}
|
||||
// Must be a valid HTTP URL to download
|
||||
if !strings.HasPrefix(mediaURL, "http://") && !strings.HasPrefix(mediaURL, "https://") {
|
||||
return fmt.Errorf("unsupported media path (not a local file and not an HTTP URL): %s", mediaURL)
|
||||
}
|
||||
data, contentType, err := downloadFile(ctx, mediaURL)
|
||||
if err != nil {
|
||||
return fmt.Errorf("download %s: %w", mediaURL, err)
|
||||
}
|
||||
|
||||
return sendMediaData(ctx, client, toUserID, filenameFromURL(mediaURL), mediaURL, data, contentType, contextToken)
|
||||
}
|
||||
|
||||
// SendMediaFromPath reads a local file and sends it as a media message.
|
||||
func SendMediaFromPath(ctx context.Context, client *ilink.Client, toUserID, path, contextToken string) error {
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return fmt.Errorf("read %s: %w", path, err)
|
||||
}
|
||||
|
||||
return sendMediaData(ctx, client, toUserID, filepath.Base(path), path, data, inferContentType(path), contextToken)
|
||||
}
|
||||
|
||||
func sendMediaData(ctx context.Context, client *ilink.Client, toUserID, fileName, source string, data []byte, contentType, contextToken string) error {
|
||||
if fileName == "" {
|
||||
fileName = "file"
|
||||
}
|
||||
|
||||
cdnMediaType, itemType := classifyMedia(contentType, source)
|
||||
|
||||
log.Printf("[media] uploading %s (%s, %d bytes) for %s", source, contentType, len(data), toUserID)
|
||||
|
||||
uploaded, err := UploadFileToCDN(ctx, client, data, toUserID, cdnMediaType)
|
||||
if err != nil {
|
||||
return fmt.Errorf("upload to CDN: %w", err)
|
||||
}
|
||||
|
||||
media := &ilink.MediaInfo{
|
||||
EncryptQueryParam: uploaded.DownloadParam,
|
||||
AESKey: AESKeyToBase64(uploaded.AESKeyHex),
|
||||
EncryptType: 1,
|
||||
}
|
||||
|
||||
var item ilink.MessageItem
|
||||
switch itemType {
|
||||
case ilink.ItemTypeImage:
|
||||
item = ilink.MessageItem{
|
||||
Type: ilink.ItemTypeImage,
|
||||
ImageItem: &ilink.ImageItem{
|
||||
Media: media,
|
||||
MidSize: uploaded.CipherSize,
|
||||
},
|
||||
}
|
||||
case ilink.ItemTypeVideo:
|
||||
item = ilink.MessageItem{
|
||||
Type: ilink.ItemTypeVideo,
|
||||
VideoItem: &ilink.VideoItem{
|
||||
Media: media,
|
||||
VideoSize: uploaded.CipherSize,
|
||||
},
|
||||
}
|
||||
default:
|
||||
item = ilink.MessageItem{
|
||||
Type: ilink.ItemTypeFile,
|
||||
FileItem: &ilink.FileItem{
|
||||
Media: media,
|
||||
FileName: fileName,
|
||||
Len: fmt.Sprintf("%d", uploaded.FileSize),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
req := &ilink.SendMessageRequest{
|
||||
Msg: ilink.SendMsg{
|
||||
FromUserID: client.BotID(),
|
||||
ToUserID: toUserID,
|
||||
ClientID: NewClientID(),
|
||||
MessageType: ilink.MessageTypeBot,
|
||||
MessageState: ilink.MessageStateFinish,
|
||||
ItemList: []ilink.MessageItem{item},
|
||||
ContextToken: contextToken,
|
||||
},
|
||||
BaseInfo: ilink.BaseInfo{},
|
||||
}
|
||||
|
||||
resp, err := client.SendMessage(ctx, req)
|
||||
if err != nil {
|
||||
return fmt.Errorf("send media message: %w", err)
|
||||
}
|
||||
if resp.Ret != 0 {
|
||||
return fmt.Errorf("send media failed: ret=%d errmsg=%s", resp.Ret, resp.ErrMsg)
|
||||
}
|
||||
|
||||
log.Printf("[media] sent %s to %s from %s", contentType, toUserID, source)
|
||||
return nil
|
||||
}
|
||||
|
||||
func downloadFile(ctx context.Context, url string) ([]byte, string, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, 60*time.Second)
|
||||
defer cancel()
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return nil, "", fmt.Errorf("HTTP %d", resp.StatusCode)
|
||||
}
|
||||
|
||||
data, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
|
||||
contentType := resp.Header.Get("Content-Type")
|
||||
if contentType == "" {
|
||||
contentType = inferContentType(url)
|
||||
}
|
||||
|
||||
return data, contentType, nil
|
||||
}
|
||||
|
||||
func classifyMedia(contentType, url string) (cdnMediaType int, itemType int) {
|
||||
ct := strings.ToLower(contentType)
|
||||
|
||||
if strings.HasPrefix(ct, "image/") || isImageExt(url) {
|
||||
return ilink.CDNMediaTypeImage, ilink.ItemTypeImage
|
||||
}
|
||||
if strings.HasPrefix(ct, "video/") || isVideoExt(url) {
|
||||
return ilink.CDNMediaTypeVideo, ilink.ItemTypeVideo
|
||||
}
|
||||
return ilink.CDNMediaTypeFile, ilink.ItemTypeFile
|
||||
}
|
||||
|
||||
func isImageExt(url string) bool {
|
||||
ext := strings.ToLower(filepath.Ext(stripQuery(url)))
|
||||
switch ext {
|
||||
case ".png", ".jpg", ".jpeg", ".gif", ".webp", ".bmp":
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func isVideoExt(url string) bool {
|
||||
ext := strings.ToLower(filepath.Ext(stripQuery(url)))
|
||||
switch ext {
|
||||
case ".mp4", ".mov", ".webm", ".mkv", ".avi":
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func inferContentType(url string) string {
|
||||
ext := filepath.Ext(stripQuery(url))
|
||||
if ct := mime.TypeByExtension(ext); ct != "" {
|
||||
return ct
|
||||
}
|
||||
return "application/octet-stream"
|
||||
}
|
||||
|
||||
func filenameFromURL(rawURL string) string {
|
||||
u := stripQuery(rawURL)
|
||||
name := filepath.Base(u)
|
||||
if name == "" || name == "." || name == "/" {
|
||||
return "file"
|
||||
}
|
||||
return name
|
||||
}
|
||||
|
||||
func stripQuery(rawURL string) string {
|
||||
if i := strings.IndexByte(rawURL, '?'); i >= 0 {
|
||||
return rawURL[:i]
|
||||
}
|
||||
return rawURL
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package messaging
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestExtractImageURLs(t *testing.T) {
|
||||
text := "check  and "
|
||||
urls := ExtractImageURLs(text)
|
||||
if len(urls) != 2 {
|
||||
t.Fatalf("expected 2 urls, got %d", len(urls))
|
||||
}
|
||||
if urls[0] != "https://example.com/a.png" {
|
||||
t.Errorf("urls[0] = %q", urls[0])
|
||||
}
|
||||
if urls[1] != "https://example.com/b.jpg" {
|
||||
t.Errorf("urls[1] = %q", urls[1])
|
||||
}
|
||||
}
|
||||
|
||||
func TestExtractImageURLs_NoImages(t *testing.T) {
|
||||
urls := ExtractImageURLs("just plain text")
|
||||
if len(urls) != 0 {
|
||||
t.Errorf("expected 0 urls, got %d", len(urls))
|
||||
}
|
||||
}
|
||||
|
||||
func TestExtractImageURLs_RelativeURL(t *testing.T) {
|
||||
text := ""
|
||||
urls := ExtractImageURLs(text)
|
||||
if len(urls) != 0 {
|
||||
t.Errorf("expected 0 urls for relative path, got %d", len(urls))
|
||||
}
|
||||
}
|
||||
|
||||
func TestFilenameFromURL(t *testing.T) {
|
||||
tests := []struct {
|
||||
url string
|
||||
want string
|
||||
}{
|
||||
{"https://example.com/photo.png", "photo.png"},
|
||||
{"https://example.com/path/to/report.pdf", "report.pdf"},
|
||||
{"https://example.com/file", "file"},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
got := filenameFromURL(tt.url)
|
||||
if got != tt.want {
|
||||
t.Errorf("filenameFromURL(%q) = %q, want %q", tt.url, got, tt.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestFilenameFromURL_WithQuery(t *testing.T) {
|
||||
got := filenameFromURL("https://example.com/photo.png?token=abc")
|
||||
if got != "photo.png" {
|
||||
t.Errorf("got %q, want %q", got, "photo.png")
|
||||
}
|
||||
}
|
||||
|
||||
func TestStripQuery(t *testing.T) {
|
||||
tests := []struct {
|
||||
input string
|
||||
want string
|
||||
}{
|
||||
{"https://example.com/a?b=c", "https://example.com/a"},
|
||||
{"https://example.com/a", "https://example.com/a"},
|
||||
{"https://example.com/?x=1&y=2", "https://example.com/"},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
got := stripQuery(tt.input)
|
||||
if got != tt.want {
|
||||
t.Errorf("stripQuery(%q) = %q, want %q", tt.input, got, tt.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
package messaging
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log"
|
||||
|
||||
"github.com/Wxw-Gu/WechatExplorer/services/wechat-connector/ilink"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// NewClientID generates a new unique client ID for message correlation.
|
||||
func NewClientID() string {
|
||||
return uuid.New().String()
|
||||
}
|
||||
|
||||
// SendTypingState sends a typing indicator to a user via the iLink sendtyping API.
|
||||
// It first fetches a typing_ticket via getconfig, then sends the typing status.
|
||||
func SendTypingState(ctx context.Context, client *ilink.Client, userID, contextToken string) error {
|
||||
// Get typing ticket
|
||||
configResp, err := client.GetConfig(ctx, userID, contextToken)
|
||||
if err != nil {
|
||||
return fmt.Errorf("get config for typing: %w", err)
|
||||
}
|
||||
if configResp.TypingTicket == "" {
|
||||
return fmt.Errorf("no typing_ticket returned from getconfig")
|
||||
}
|
||||
|
||||
// Send typing
|
||||
if err := client.SendTyping(ctx, userID, configResp.TypingTicket, ilink.TypingStatusTyping); err != nil {
|
||||
return fmt.Errorf("send typing: %w", err)
|
||||
}
|
||||
|
||||
log.Printf("[sender] sent typing indicator to %s", userID)
|
||||
return nil
|
||||
}
|
||||
|
||||
// SendTextReply sends a text reply to a user through the iLink API.
|
||||
// If clientID is empty, a new one is generated.
|
||||
func SendTextReply(ctx context.Context, client *ilink.Client, toUserID, text, contextToken, clientID string) error {
|
||||
if clientID == "" {
|
||||
clientID = NewClientID()
|
||||
}
|
||||
|
||||
// Convert markdown to plain text for WeChat display
|
||||
plainText := MarkdownToPlainText(text)
|
||||
|
||||
req := &ilink.SendMessageRequest{
|
||||
Msg: ilink.SendMsg{
|
||||
FromUserID: client.BotID(),
|
||||
ToUserID: toUserID,
|
||||
ClientID: clientID,
|
||||
MessageType: ilink.MessageTypeBot,
|
||||
MessageState: ilink.MessageStateFinish,
|
||||
ItemList: []ilink.MessageItem{
|
||||
{
|
||||
Type: ilink.ItemTypeText,
|
||||
TextItem: &ilink.TextItem{
|
||||
Text: plainText,
|
||||
},
|
||||
},
|
||||
},
|
||||
ContextToken: contextToken,
|
||||
},
|
||||
BaseInfo: ilink.BaseInfo{},
|
||||
}
|
||||
|
||||
resp, err := client.SendMessage(ctx, req)
|
||||
if err != nil {
|
||||
return fmt.Errorf("send message: %w", err)
|
||||
}
|
||||
|
||||
if resp.Ret != 0 {
|
||||
return fmt.Errorf("send message failed: ret=%d errmsg=%s", resp.Ret, resp.ErrMsg)
|
||||
}
|
||||
|
||||
log.Printf("[sender] sent reply to %s: %q", toUserID, truncate(text, 50))
|
||||
return nil
|
||||
}
|
||||
|
||||
func truncate(s string, n int) string {
|
||||
if len(s) <= n {
|
||||
return s
|
||||
}
|
||||
return s[:n] + "..."
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
import { app, shell } from 'electron'
|
||||
import fs from 'fs-extra'
|
||||
import path from 'path'
|
||||
import type { AppLogEntry } from '../shared/app-log'
|
||||
|
||||
const MAX_LOG_BYTES = 5 * 1024 * 1024
|
||||
const REDACTED_KEY = /(?:api[-_]?key|authorization|token|secret|password|database[-_]?key)/i
|
||||
|
||||
const sanitize = (value: unknown, depth = 0): unknown => {
|
||||
if (depth > 4) return '[depth-limited]'
|
||||
if (typeof value === 'string') {
|
||||
return value
|
||||
.replace(/\bsk-[a-z0-9_-]{8,}\b/gi, '***')
|
||||
.replace(/\bBearer\s+[a-z0-9._~-]{8,}\b/gi, 'Bearer ***')
|
||||
.slice(0, 2000)
|
||||
}
|
||||
if (Array.isArray(value)) return value.slice(0, 30).map((item) => sanitize(item, depth + 1))
|
||||
if (value && typeof value === 'object') {
|
||||
return Object.fromEntries(
|
||||
Object.entries(value as Record<string, unknown>).map(([key, item]) => [
|
||||
key,
|
||||
REDACTED_KEY.test(key) ? '***' : sanitize(item, depth + 1)
|
||||
])
|
||||
)
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
export class AppLogger {
|
||||
private get logDir(): string {
|
||||
return app.getPath('logs')
|
||||
}
|
||||
|
||||
get logPath(): string {
|
||||
return path.join(this.logDir, 'wechatexplorer.log')
|
||||
}
|
||||
|
||||
private rotateIfNeeded(): void {
|
||||
try {
|
||||
if (!fs.existsSync(this.logPath) || fs.statSync(this.logPath).size < MAX_LOG_BYTES) return
|
||||
const previous = `${this.logPath}.1`
|
||||
if (fs.existsSync(previous)) fs.removeSync(previous)
|
||||
fs.moveSync(this.logPath, previous)
|
||||
} catch {
|
||||
// Logging must never interrupt the application.
|
||||
}
|
||||
}
|
||||
|
||||
write(entry: AppLogEntry): void {
|
||||
try {
|
||||
fs.ensureDirSync(this.logDir)
|
||||
this.rotateIfNeeded()
|
||||
const record = {
|
||||
timestamp: new Date().toISOString(),
|
||||
mode: app.isPackaged ? 'packaged' : 'development',
|
||||
level: entry.level,
|
||||
scope: String(entry.scope || 'app').slice(0, 80),
|
||||
message: String(entry.message || '').slice(0, 500),
|
||||
details: sanitize(entry.details || {})
|
||||
}
|
||||
fs.appendFileSync(this.logPath, `${JSON.stringify(record)}\n`, { encoding: 'utf8' })
|
||||
if (!app.isPackaged) {
|
||||
const method =
|
||||
entry.level === 'error'
|
||||
? console.error
|
||||
: entry.level === 'warn'
|
||||
? console.warn
|
||||
: console.log
|
||||
method(`[${record.scope}] ${record.message}`, record.details)
|
||||
}
|
||||
} catch {
|
||||
// Logging must never interrupt the application.
|
||||
}
|
||||
}
|
||||
|
||||
reveal(): void {
|
||||
fs.ensureDirSync(this.logDir)
|
||||
if (!fs.existsSync(this.logPath)) fs.writeFileSync(this.logPath, '', 'utf8')
|
||||
shell.showItemInFolder(this.logPath)
|
||||
}
|
||||
}
|
||||
|
||||
export const appLogger = new AppLogger()
|
||||
@@ -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 → 跳过(向后兼容)
|
||||
@@ -138,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)
|
||||
@@ -147,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(
|
||||
@@ -168,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(
|
||||
@@ -213,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('')
|
||||
|
||||
@@ -236,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(
|
||||
@@ -244,35 +423,116 @@ 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(`基于 WechatExplorer 加载的 ${metadata.messageCount} 条记录`),
|
||||
OVERVIEW: escapeHtml(report.overview),
|
||||
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
|
||||
}
|
||||
|
||||
@@ -327,7 +587,8 @@ 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()
|
||||
|
||||
+64
-4
@@ -9,6 +9,8 @@ import {
|
||||
} from './services/chat-service'
|
||||
import { exportGroupReport } from './group-report-service'
|
||||
import { GroupReportExportRequest } from '../shared/group-report'
|
||||
import { generateAgentGroupReport } from './services/agent-group-report-service'
|
||||
import { agentHubService } from './services/agent-hub-service'
|
||||
import { safeError, safeLog, safeWarn } from './safe-log'
|
||||
|
||||
export const DEFAULT_HTTP_HOST = '127.0.0.1'
|
||||
@@ -157,7 +159,9 @@ const routes: Record<string, RouteHandler> = {
|
||||
if (keyword) {
|
||||
const lower = keyword.toLowerCase()
|
||||
groups = groups.filter(
|
||||
(c) => c.m_nsNickName.toLowerCase().includes(lower) || c.m_nsUsrName.toLowerCase().includes(lower)
|
||||
(c) =>
|
||||
c.m_nsNickName.toLowerCase().includes(lower) ||
|
||||
c.m_nsUsrName.toLowerCase().includes(lower)
|
||||
)
|
||||
}
|
||||
sendJson(res, 200, { count: groups.length, chatrooms: groups })
|
||||
@@ -236,13 +240,62 @@ const routes: Record<string, RouteHandler> = {
|
||||
try {
|
||||
request = JSON.parse(body) as GroupReportExportRequest
|
||||
} catch (error) {
|
||||
return sendError(res, 400, '请求体 JSON 解析失败', error instanceof Error ? error.message : String(error))
|
||||
return sendError(
|
||||
res,
|
||||
400,
|
||||
'请求体 JSON 解析失败',
|
||||
error instanceof Error ? error.message : String(error)
|
||||
)
|
||||
}
|
||||
if (!request?.report || !request?.metadata) {
|
||||
return sendError(res, 400, '请求体需包含 report 和 metadata 字段')
|
||||
}
|
||||
const result = await exportGroupReport(request)
|
||||
sendJson(res, result.success ? 200 : 500, result)
|
||||
},
|
||||
|
||||
'/api/v1/agent/group-report': async ({ req, res, body }) => {
|
||||
if (req.method !== 'POST') return sendError(res, 405, '需要 POST 请求')
|
||||
if (!isReady()) return sendError(res, 503, 'WechatExplorer 数据库未初始化')
|
||||
let request: { group?: string; range?: 'today' | 'yesterday' | '7days' }
|
||||
try {
|
||||
request = JSON.parse(typeof body === 'string' ? body : '{}')
|
||||
} catch {
|
||||
return sendError(res, 400, '请求体 JSON 解析失败')
|
||||
}
|
||||
const result = await generateAgentGroupReport({
|
||||
group: request.group || '',
|
||||
range: request.range
|
||||
})
|
||||
sendJson(res, result.success ? 200 : 400, result)
|
||||
},
|
||||
|
||||
'/api/v1/agent/status': ({ res }) => {
|
||||
const status = agentHubService.getStatus()
|
||||
sendJson(res, 200, {
|
||||
ok: status.hub === 'online' && status.connector === 'online',
|
||||
hub: status.hub,
|
||||
connector: status.connector,
|
||||
dataApi: status.dataApi,
|
||||
databaseReady: status.databaseReady,
|
||||
accountId: status.accountId
|
||||
})
|
||||
},
|
||||
|
||||
'/api/v1/agent/send': async ({ req, res, body }) => {
|
||||
if (req.method !== 'POST') return sendError(res, 405, '需要 POST 请求')
|
||||
let request: { to?: string; text?: string; media_url?: string }
|
||||
try {
|
||||
request = JSON.parse(typeof body === 'string' ? body : '{}')
|
||||
} catch {
|
||||
return sendError(res, 400, '请求体 JSON 解析失败')
|
||||
}
|
||||
const result = await agentHubService.testSend({
|
||||
to: request.to,
|
||||
text: request.text,
|
||||
mediaUrl: request.media_url
|
||||
})
|
||||
sendJson(res, result.success ? 200 : result.status === 'token_expired' ? 401 : 503, result)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -311,7 +364,11 @@ export interface ApiServerState {
|
||||
}
|
||||
|
||||
let singleton: HttpServerHandle | null = null
|
||||
let singletonState: ApiServerState = { running: false, host: DEFAULT_HTTP_HOST, port: DEFAULT_HTTP_PORT }
|
||||
let singletonState: ApiServerState = {
|
||||
running: false,
|
||||
host: DEFAULT_HTTP_HOST,
|
||||
port: DEFAULT_HTTP_PORT
|
||||
}
|
||||
|
||||
function sleep(ms: number): Promise<void> {
|
||||
return new Promise((resolve) => setTimeout(resolve, ms))
|
||||
@@ -326,7 +383,10 @@ export const apiServer = {
|
||||
return { ...singletonState }
|
||||
},
|
||||
|
||||
async start(host: string = DEFAULT_HTTP_HOST, port: number = DEFAULT_HTTP_PORT): Promise<ApiServerState> {
|
||||
async start(
|
||||
host: string = DEFAULT_HTTP_HOST,
|
||||
port: number = DEFAULT_HTTP_PORT
|
||||
): Promise<ApiServerState> {
|
||||
if (singleton) {
|
||||
return this.getState()
|
||||
}
|
||||
|
||||
@@ -4,6 +4,11 @@ import crypto from 'crypto'
|
||||
import os from 'os'
|
||||
import { Wcdb4Client } from './wcdb4-client'
|
||||
|
||||
const imageDecryptDebugEnabled = process.env['WECHATEXPLORER_DEBUG_IMAGE'] === '1'
|
||||
const imageDecryptLog = (...args: unknown[]): void => {
|
||||
if (imageDecryptDebugEnabled) console.log(...args)
|
||||
}
|
||||
|
||||
export class ImageDecryptService {
|
||||
private readonly defaultV1AesKey = 'cfcd208495d565ef'
|
||||
|
||||
@@ -41,7 +46,7 @@ export class ImageDecryptService {
|
||||
)
|
||||
|
||||
if (!existsSync(accountRoot)) {
|
||||
console.log('[ImageDecrypt] account root not found:', accountRoot)
|
||||
imageDecryptLog('[ImageDecrypt] account root not found:', accountRoot)
|
||||
return null
|
||||
}
|
||||
|
||||
@@ -61,7 +66,7 @@ export class ImageDecryptService {
|
||||
.sort((a, b) => b.mtime - a.mtime)
|
||||
|
||||
if (accounts.length === 0) {
|
||||
console.log('[ImageDecrypt] no accounts found')
|
||||
imageDecryptLog('[ImageDecrypt] no accounts found')
|
||||
return null
|
||||
}
|
||||
|
||||
@@ -83,7 +88,7 @@ export class ImageDecryptService {
|
||||
|
||||
const normalizedMd5 = this.normalizeDatBase(md5 || '')
|
||||
const normalizedDatName = this.normalizeDatBase(imageDatName || '')
|
||||
console.log('[ImageDecrypt] findImageFile:', {
|
||||
imageDecryptLog('[ImageDecrypt] findImageFile:', {
|
||||
md5: normalizedMd5,
|
||||
imageDatName: normalizedDatName,
|
||||
accountDir,
|
||||
@@ -96,7 +101,7 @@ export class ImageDecryptService {
|
||||
if (fullPath && existsSync(fullPath)) {
|
||||
const selected = this.getPreferredDatVariantPath(fullPath, allowThumbnail)
|
||||
if (allowThumbnail || !this.isThumbnailName(basename(selected))) {
|
||||
console.log('[ImageDecrypt] hardlink hit:', selected)
|
||||
imageDecryptLog('[ImageDecrypt] hardlink hit:', selected)
|
||||
return selected
|
||||
}
|
||||
}
|
||||
@@ -105,7 +110,7 @@ export class ImageDecryptService {
|
||||
// 尝试 WechatExplorer 的目录结构: msg/attach/{hash}/{YYYY-MM}/Img/
|
||||
const attachDir = join(accountDir, 'msg', 'attach')
|
||||
if (!existsSync(attachDir)) {
|
||||
console.log('[ImageDecrypt] attach dir not found:', attachDir)
|
||||
imageDecryptLog('[ImageDecrypt] attach dir not found:', attachDir)
|
||||
return this.findImageFileInLegacyDirs(accountDir, normalizedMd5 || normalizedDatName)
|
||||
}
|
||||
|
||||
@@ -120,7 +125,7 @@ export class ImageDecryptService {
|
||||
const legacyHit = this.findImageFileInLegacyDirs(accountDir, searchKeys[0], allowThumbnail)
|
||||
if (legacyHit) return legacyHit
|
||||
|
||||
console.log('[ImageDecrypt] findImageFile miss for:', searchKeys)
|
||||
imageDecryptLog('[ImageDecrypt] findImageFile miss for:', searchKeys)
|
||||
return null
|
||||
}
|
||||
|
||||
@@ -146,7 +151,7 @@ export class ImageDecryptService {
|
||||
]
|
||||
const found = this.getLargestExistingPath(candidates, allowThumbnail)
|
||||
if (found) {
|
||||
console.log('[ImageDecrypt] prefix path hit:', found)
|
||||
imageDecryptLog('[ImageDecrypt] prefix path hit:', found)
|
||||
return found
|
||||
}
|
||||
}
|
||||
@@ -175,14 +180,14 @@ export class ImageDecryptService {
|
||||
allowThumbnail
|
||||
)
|
||||
if (found) {
|
||||
console.log('[ImageDecrypt] found at:', found)
|
||||
imageDecryptLog('[ImageDecrypt] found at:', found)
|
||||
return found
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
console.log('[ImageDecrypt]遍历目录失败:', e)
|
||||
imageDecryptLog('[ImageDecrypt]遍历目录失败:', e)
|
||||
}
|
||||
|
||||
return null
|
||||
@@ -229,7 +234,7 @@ export class ImageDecryptService {
|
||||
const fullPath = join(dir, entry)
|
||||
const stat = statSync(fullPath)
|
||||
if (stat.isFile() && variants.has(entry.toLowerCase())) {
|
||||
console.log('[ImageDecrypt] legacy path hit:', fullPath)
|
||||
imageDecryptLog('[ImageDecrypt] legacy path hit:', fullPath)
|
||||
return fullPath
|
||||
}
|
||||
}
|
||||
@@ -252,13 +257,13 @@ export class ImageDecryptService {
|
||||
*/
|
||||
decryptImage(datPath: string): Buffer | null {
|
||||
if (!existsSync(datPath)) {
|
||||
console.log('[ImageDecrypt] file not found:', datPath)
|
||||
imageDecryptLog('[ImageDecrypt] file not found:', datPath)
|
||||
return null
|
||||
}
|
||||
|
||||
try {
|
||||
const version = this.getDatVersion(datPath)
|
||||
console.log(
|
||||
imageDecryptLog(
|
||||
'[ImageDecrypt] dat version:',
|
||||
version,
|
||||
'file:',
|
||||
@@ -269,25 +274,25 @@ export class ImageDecryptService {
|
||||
|
||||
let decrypted: Buffer
|
||||
if (version === 1) {
|
||||
console.log('[ImageDecrypt] using V1 (default AES key)')
|
||||
imageDecryptLog('[ImageDecrypt] using V1 (default AES key)')
|
||||
const key = Buffer.from(this.defaultV1AesKey, 'ascii')
|
||||
decrypted = this.decryptDatV4(datPath, key)
|
||||
} else if (version === 2) {
|
||||
console.log('[ImageDecrypt] using V2 (user AES key)')
|
||||
imageDecryptLog('[ImageDecrypt] using V2 (user AES key)')
|
||||
if (!this.aesKey) {
|
||||
console.log('[ImageDecrypt] no AES key configured')
|
||||
imageDecryptLog('[ImageDecrypt] no AES key configured')
|
||||
return null
|
||||
}
|
||||
const key = Buffer.from(this.aesKey, 'ascii').slice(0, 16)
|
||||
decrypted = this.decryptDatV4(datPath, key)
|
||||
} else {
|
||||
console.log('[ImageDecrypt] unsupported dat version:', version)
|
||||
imageDecryptLog('[ImageDecrypt] unsupported dat version:', version)
|
||||
return null
|
||||
}
|
||||
|
||||
return decrypted
|
||||
} catch (error) {
|
||||
console.error('[ImageDecrypt] decrypt error:', error)
|
||||
imageDecryptLog('[ImageDecrypt] decrypt error:', error)
|
||||
return null
|
||||
}
|
||||
}
|
||||
@@ -309,7 +314,7 @@ export class ImageDecryptService {
|
||||
const unwrapped = this.unwrapWxgf(decrypted)
|
||||
const ext = this.detectImageExtension(unwrapped)
|
||||
if (!ext) {
|
||||
console.log('[ImageDecrypt] unknown image format')
|
||||
imageDecryptLog('[ImageDecrypt] unknown image format')
|
||||
return null
|
||||
}
|
||||
|
||||
@@ -317,6 +322,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 }
|
||||
}
|
||||
imageDecryptLog('[ImageDecrypt] all variants failed:', this.uniq(candidates))
|
||||
return null
|
||||
}
|
||||
|
||||
/**
|
||||
* 检测 DAT 文件版本
|
||||
*/
|
||||
@@ -485,7 +523,9 @@ export class ImageDecryptService {
|
||||
})
|
||||
.sort((left, right) => right.size - left.size)
|
||||
|
||||
const nonThumb = toSized(paths.filter((candidate) => !this.isThumbnailName(basename(candidate))))
|
||||
const nonThumb = toSized(
|
||||
paths.filter((candidate) => !this.isThumbnailName(basename(candidate)))
|
||||
)
|
||||
if (nonThumb[0]) return nonThumb[0].candidate
|
||||
if (!allowThumbnail) return null
|
||||
|
||||
|
||||
+158
-8
@@ -37,6 +37,14 @@ import type {
|
||||
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'
|
||||
@@ -60,6 +68,9 @@ import {
|
||||
saveCachedMessages
|
||||
} from './services/bootstrap-cache'
|
||||
import { installSafeConsole } from './safe-log'
|
||||
import { agentHubService } from './services/agent-hub-service'
|
||||
import { appLogger } from './app-logger'
|
||||
import type { AppLogEntry } from '../shared/app-log'
|
||||
|
||||
// electron-vite can close the child's stdout/stderr after spawning Electron.
|
||||
// Plain console.error then throws EPIPE on a closed pipe and crashes the IPC
|
||||
@@ -132,6 +143,31 @@ function createWindow(): void {
|
||||
// 鏌愪簺 API 鍙兘鍦ㄦ浜嬩欢鍙戠敓鍚庝娇鐢?
|
||||
app.whenReady().then(async () => {
|
||||
console.log(`WechatExplorer main build: ${BUILD_MARK}`)
|
||||
appLogger.write({
|
||||
level: 'info',
|
||||
scope: 'lifecycle',
|
||||
message: 'WechatExplorer 启动',
|
||||
details: { build: BUILD_MARK, platform: process.platform, version: app.getVersion() }
|
||||
})
|
||||
process.on('uncaughtException', (error) => {
|
||||
appLogger.write({
|
||||
level: 'error',
|
||||
scope: 'main-process',
|
||||
message: error.message,
|
||||
details: { stack: error.stack }
|
||||
})
|
||||
})
|
||||
process.on('unhandledRejection', (reason) => {
|
||||
appLogger.write({
|
||||
level: 'error',
|
||||
scope: 'main-process',
|
||||
message: reason instanceof Error ? reason.message : 'Promise 未处理拒绝',
|
||||
details: {
|
||||
stack: reason instanceof Error ? reason.stack : undefined,
|
||||
reason: reason instanceof Error ? undefined : String(reason)
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
// 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
|
||||
@@ -157,6 +193,9 @@ app.whenReady().then(async () => {
|
||||
|
||||
// IPC test
|
||||
ipcMain.on('ping', () => console.log('pong'))
|
||||
ipcMain.handle('app-log:write', (_, entry: AppLogEntry) => appLogger.write(entry))
|
||||
ipcMain.handle('app-log:getPath', () => appLogger.logPath)
|
||||
ipcMain.handle('app-log:reveal', () => appLogger.reveal())
|
||||
|
||||
ipcMain.handle('db:init', async (_, key: string) => {
|
||||
if (dbInitInFlight) return dbInitInFlight
|
||||
@@ -475,20 +514,108 @@ app.whenReady().then(async () => {
|
||||
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,
|
||||
isThumb: imageDecryptService.isThumbnailFile(filePath),
|
||||
filePath
|
||||
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 模型不存在' }
|
||||
}
|
||||
// Capability metadata is stored per machine. A model verified on macOS
|
||||
// may still be unmarked on Windows, so do not reject before making the
|
||||
// real multimodal request. The provider response remains authoritative.
|
||||
// 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) }
|
||||
}
|
||||
)
|
||||
|
||||
ipcMain.handle('db:getSticker', async (_, cdnUrl?: string, md5?: string) => {
|
||||
if (!stickerService) {
|
||||
stickerService = new StickerService(chat.getChatDb()?.getWcdb4Client())
|
||||
@@ -558,9 +685,10 @@ app.whenReady().then(async () => {
|
||||
return error ? { success: false, error } : { success: true }
|
||||
})
|
||||
|
||||
ipcMain.handle('db:disconnect', () => {
|
||||
if (!chat.isReady()) return { success: false, error: '数据库当前未连接' }
|
||||
chat.setChatDb(null)
|
||||
ipcMain.handle('db:disconnect', (_, options?: { closeNative?: boolean }) => {
|
||||
// 断开操作保持幂等:渲染进程可能已标记断开,或主进程连接已先行失效。
|
||||
// 即使当前未就绪,也应让用户正常返回登录页。
|
||||
if (options?.closeNative !== false && chat.isReady()) chat.setChatDb(null)
|
||||
return { success: true }
|
||||
})
|
||||
|
||||
@@ -602,6 +730,25 @@ app.whenReady().then(async () => {
|
||||
return { success: false, error: error instanceof Error ? error.message : String(error) }
|
||||
}
|
||||
})
|
||||
ipcMain.handle('agent-hub:getStatus', () => agentHubService.getStatus())
|
||||
ipcMain.handle('agent-hub:getLogs', () => agentHubService.getLogs())
|
||||
ipcMain.handle('agent-hub:clearLogs', () => agentHubService.clearLogs())
|
||||
ipcMain.handle('agent-hub:startLogin', () => agentHubService.startLogin())
|
||||
ipcMain.handle('agent-hub:cancelLogin', () => agentHubService.cancelLogin())
|
||||
ipcMain.handle('agent-hub:reconnect', () => agentHubService.reconnect())
|
||||
ipcMain.handle('agent-hub:disconnect', () => agentHubService.disconnect())
|
||||
ipcMain.handle('agent-hub:selectTestImage', async (event) => {
|
||||
const window = BrowserWindow.fromWebContents(event.sender)
|
||||
const result = await dialog.showOpenDialog(window!, {
|
||||
title: '选择要测试发送的图片',
|
||||
properties: ['openFile'],
|
||||
filters: [
|
||||
{ name: '图片', extensions: ['png', 'jpg', 'jpeg', 'gif', 'webp'] },
|
||||
{ name: '所有文件', extensions: ['*'] }
|
||||
]
|
||||
})
|
||||
return result.canceled ? { canceled: true } : { canceled: false, path: result.filePaths[0] }
|
||||
})
|
||||
|
||||
createWindow()
|
||||
|
||||
@@ -611,6 +758,8 @@ app.whenReady().then(async () => {
|
||||
await apiServer.start(settings.apiHost, settings.apiPort)
|
||||
}
|
||||
|
||||
await agentHubService.start(settings)
|
||||
|
||||
if (TRAY_MODE) {
|
||||
app.dock?.hide()
|
||||
setupTray()
|
||||
@@ -634,6 +783,7 @@ app.on('window-all-closed', () => {
|
||||
})
|
||||
|
||||
app.on('before-quit', async () => {
|
||||
agentHubService.stop()
|
||||
chat.setChatDb(null)
|
||||
await apiServer.stop().catch(() => undefined)
|
||||
if (tray) {
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
import type { Contact, Message } from '../../shared/types'
|
||||
import { exportGroupReport } from '../group-report-service'
|
||||
import { getGroupSnapshot, listMessages, resolveMd5 } from './chat-service'
|
||||
import { AIProviderService } from './ai-provider-service'
|
||||
import {
|
||||
buildGroupReportInput,
|
||||
getSummaryDateRange,
|
||||
GROUP_REPORT_JSON_REPAIR_SYSTEM_PROMPT,
|
||||
GROUP_REPORT_SYSTEM_PROMPT,
|
||||
isInternalName,
|
||||
parseGroupDailyReport,
|
||||
type SummaryDateRange
|
||||
} from '../../renderer/src/utils/group-report'
|
||||
|
||||
const aiProvider = new AIProviderService()
|
||||
|
||||
export interface AgentGroupReportRequest {
|
||||
group: string
|
||||
range?: SummaryDateRange
|
||||
}
|
||||
|
||||
export interface AgentGroupReportResult {
|
||||
success: boolean
|
||||
groupName?: string
|
||||
pngPath?: string
|
||||
messageCount?: number
|
||||
error?: string
|
||||
}
|
||||
|
||||
export async function generateAgentGroupReport(
|
||||
request: AgentGroupReportRequest
|
||||
): Promise<AgentGroupReportResult> {
|
||||
const query = String(request.group || '')
|
||||
.trim()
|
||||
.replace(/群聊?$/, '')
|
||||
.trim()
|
||||
if (!query) return { success: false, error: '缺少群聊名称' }
|
||||
const contact = resolveMd5(query)
|
||||
if (!contact) return { success: false, error: `没有找到群聊“${query}”` }
|
||||
if (contact.type !== 'group' && !contact.m_nsUsrName.endsWith('@chatroom')) {
|
||||
return { success: false, error: `“${query}”不是群聊` }
|
||||
}
|
||||
|
||||
const range = request.range === 'yesterday' || request.range === '7days' ? request.range : 'today'
|
||||
const { startTime, endTime } = getSummaryDateRange(range)
|
||||
let messages = listMessages(contact.md5, startTime, endTime) as Message[]
|
||||
if (!messages.length) return { success: false, error: '所选时间范围没有可总结的消息' }
|
||||
|
||||
const snapshot = getGroupSnapshot(contact.md5)
|
||||
if (snapshot) {
|
||||
const members = new Map(
|
||||
snapshot.members.map((member) => [
|
||||
member.wxid,
|
||||
{ name: member.nickname, avatar: member.avatar }
|
||||
])
|
||||
)
|
||||
messages = messages.map((message) => {
|
||||
if (!isInternalName(message.name)) return message
|
||||
const member = members.get(String(message.senderId || message.name || ''))
|
||||
return member?.name
|
||||
? { ...message, name: member.name, img: message.img || member.avatar }
|
||||
: message
|
||||
})
|
||||
}
|
||||
|
||||
const input = await buildGroupReportInput(messages, contact as Contact, true, 'full')
|
||||
const ai = await aiProvider.chat([
|
||||
{ role: 'system', content: GROUP_REPORT_SYSTEM_PROMPT },
|
||||
{ role: 'user', content: input.prompt }
|
||||
])
|
||||
if (!ai.success || !ai.data) return { success: false, error: ai.error || 'AI 总结失败' }
|
||||
const parseReport = (raw: string): ReturnType<typeof parseGroupDailyReport> =>
|
||||
parseGroupDailyReport(
|
||||
raw,
|
||||
input.topSpeakers,
|
||||
input.activeTimeline,
|
||||
input.voiceLeaderboard,
|
||||
input.metadata,
|
||||
input.media
|
||||
)
|
||||
let report: ReturnType<typeof parseGroupDailyReport>
|
||||
try {
|
||||
report = parseReport(ai.data)
|
||||
} catch (parseError) {
|
||||
const repaired = await aiProvider.chat([
|
||||
{ role: 'system', content: GROUP_REPORT_JSON_REPAIR_SYSTEM_PROMPT },
|
||||
{ role: 'user', content: ai.data }
|
||||
])
|
||||
if (!repaired.success || !repaired.data) {
|
||||
const cause = parseError instanceof Error ? parseError.message : String(parseError)
|
||||
return {
|
||||
success: false,
|
||||
error: `${repaired.error || 'AI 修复日报 JSON 失败'}(原始错误:${cause})`
|
||||
}
|
||||
}
|
||||
try {
|
||||
report = parseReport(repaired.data)
|
||||
} catch (repairError) {
|
||||
return {
|
||||
success: false,
|
||||
error: repairError instanceof Error ? repairError.message : String(repairError)
|
||||
}
|
||||
}
|
||||
}
|
||||
const exported = await exportGroupReport({ report, metadata: input.metadata })
|
||||
if (!exported.success || !exported.pngPath) {
|
||||
return { success: false, error: exported.error || '总结图片生成失败' }
|
||||
}
|
||||
return {
|
||||
success: true,
|
||||
groupName: input.metadata.groupName,
|
||||
pngPath: exported.pngPath,
|
||||
messageCount: messages.length
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -69,7 +69,8 @@ export class AIProviderService {
|
||||
configured: Boolean(
|
||||
provider && provider.models.length && (provider.hasApiKey || !needsApiKey(provider))
|
||||
),
|
||||
status: provider?.status || 'untested'
|
||||
status: provider?.status || 'untested',
|
||||
timeoutMs: provider?.advanced.timeoutMs
|
||||
}
|
||||
}
|
||||
|
||||
@@ -169,6 +170,40 @@ export class AIProviderService {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 多模态图片理解。
|
||||
* 输入: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)
|
||||
if (options?.providerId && options.modelId) {
|
||||
this.markCapabilities(options.providerId, options.modelId, { vision: true, ocr: true })
|
||||
}
|
||||
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)
|
||||
@@ -215,7 +250,13 @@ export class AIProviderService {
|
||||
}> {
|
||||
if (options?.apiKey) return this.requestLegacy(messages, options)
|
||||
const resolved = this.resolveProvider(options)
|
||||
return requestProvider(resolved.provider, resolved.key, resolved.model, messages, testing)
|
||||
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 }): {
|
||||
@@ -263,12 +304,38 @@ export class AIProviderService {
|
||||
}
|
||||
|
||||
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 || model.capabilities.vision) return
|
||||
model.capabilities.vision = true
|
||||
this.writeMetadata(data)
|
||||
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 {
|
||||
@@ -300,6 +367,14 @@ export class AIProviderService {
|
||||
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
|
||||
}
|
||||
|
||||
@@ -325,7 +400,7 @@ function deepSeekProvider(baseUrl?: string, model?: string): AIProviderSummary {
|
||||
{
|
||||
name: modelId === 'deepseek-chat' ? 'DeepSeek Chat' : modelId,
|
||||
id: modelId,
|
||||
capabilities: { chat: true, vision: false, longContext: true }
|
||||
capabilities: { chat: true, vision: false, ocr: false, longContext: true }
|
||||
}
|
||||
],
|
||||
defaultModel: modelId,
|
||||
@@ -454,7 +529,7 @@ async function requestOpenAICompatible(
|
||||
},
|
||||
provider.advanced.timeoutMs
|
||||
)
|
||||
const payload = (await response.json()) as OpenAIResponsePayload
|
||||
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 || ''),
|
||||
@@ -508,7 +583,7 @@ async function requestAnthropic(
|
||||
},
|
||||
provider.advanced.timeoutMs
|
||||
)
|
||||
const payload = (await response.json()) as AnthropicResponsePayload
|
||||
const payload = await parseJsonResponse<AnthropicResponsePayload>(response)
|
||||
if (!response.ok)
|
||||
throw new Error(payload.error?.message || `Anthropic 请求失败 (${response.status})`)
|
||||
return {
|
||||
@@ -543,6 +618,20 @@ async function fetchWithTimeout(
|
||||
}
|
||||
}
|
||||
|
||||
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)
|
||||
|
||||
@@ -31,6 +31,10 @@ interface BootstrapCacheFile {
|
||||
const CACHE_VERSION = 1
|
||||
const MAX_MESSAGE_BUCKETS = 24
|
||||
const MAX_MESSAGES_PER_BUCKET = 1200
|
||||
const WRITE_DEBOUNCE_MS = 300
|
||||
const memoryCache = new Map<string, BootstrapCacheFile>()
|
||||
const writeTimers = new Map<string, NodeJS.Timeout>()
|
||||
const writeQueues = new Map<string, Promise<void>>()
|
||||
|
||||
function normalizeRoot(accountRoot?: string): string {
|
||||
return String(accountRoot || '').trim()
|
||||
@@ -43,19 +47,26 @@ function getCacheFile(accountRoot?: string): string {
|
||||
.update(`${process.platform}:${normalizedRoot}`)
|
||||
.digest('hex')
|
||||
.slice(0, 16)
|
||||
return path.join(app.getPath('userData'), 'cache', 'bootstrap', `${process.platform}-${hash}.json`)
|
||||
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)
|
||||
const cached = memoryCache.get(file)
|
||||
if (cached) return cached
|
||||
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 {
|
||||
const result: BootstrapCacheFile = {
|
||||
version: CACHE_VERSION,
|
||||
platform: process.platform,
|
||||
accountRoot: normalizedRoot,
|
||||
@@ -64,6 +75,8 @@ function readCacheFile(accountRoot?: string): BootstrapCacheFile | null {
|
||||
contacts: Array.isArray(raw.contacts) ? raw.contacts : [],
|
||||
messages: raw.messages && typeof raw.messages === 'object' ? raw.messages : {}
|
||||
}
|
||||
memoryCache.set(file, result)
|
||||
return result
|
||||
} catch (error) {
|
||||
console.warn('[BootstrapCache] read failed:', error)
|
||||
return null
|
||||
@@ -71,28 +84,48 @@ function readCacheFile(accountRoot?: string): BootstrapCacheFile | 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)
|
||||
}
|
||||
const file = getCacheFile(cache.accountRoot)
|
||||
memoryCache.set(file, cache)
|
||||
const existingTimer = writeTimers.get(file)
|
||||
if (existingTimer) clearTimeout(existingTimer)
|
||||
writeTimers.set(
|
||||
file,
|
||||
setTimeout(() => {
|
||||
writeTimers.delete(file)
|
||||
const serialized = JSON.stringify(memoryCache.get(file) || cache)
|
||||
const previous = writeQueues.get(file) || Promise.resolve()
|
||||
const next = previous
|
||||
.catch(() => undefined)
|
||||
.then(async () => {
|
||||
await fs.ensureDir(path.dirname(file))
|
||||
await fs.writeFile(file, serialized, 'utf8')
|
||||
})
|
||||
.catch((error) => {
|
||||
console.warn('[BootstrapCache] write failed:', error)
|
||||
})
|
||||
.finally(() => {
|
||||
if (writeQueues.get(file) === next) writeQueues.delete(file)
|
||||
})
|
||||
writeQueues.set(file, next)
|
||||
}, WRITE_DEBOUNCE_MS)
|
||||
)
|
||||
}
|
||||
|
||||
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: {}
|
||||
}
|
||||
)
|
||||
const existing = readCacheFile(normalizedRoot)
|
||||
if (existing) return existing
|
||||
const created: BootstrapCacheFile = {
|
||||
version: CACHE_VERSION,
|
||||
platform: process.platform,
|
||||
accountRoot: normalizedRoot,
|
||||
updatedAt: Date.now(),
|
||||
contacts: [],
|
||||
messages: {}
|
||||
}
|
||||
memoryCache.set(getCacheFile(normalizedRoot), created)
|
||||
return created
|
||||
}
|
||||
|
||||
function messageBucketKey(userMd5: string, startTime?: number, endTime?: number): string {
|
||||
@@ -144,7 +177,9 @@ export function mergeCachedContactAvatars(accountRoot: string, contacts: Contact
|
||||
)
|
||||
const nameByUsername = new Map(
|
||||
cache.contacts
|
||||
.filter((contact) => contact.m_nsUsrName && contact.m_nsNickName && !isRawContactName(contact))
|
||||
.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
|
||||
@@ -179,7 +214,9 @@ export function saveBootstrapContacts(accountRoot: string, contacts: Contact[]):
|
||||
)
|
||||
const nameByUsername = new Map(
|
||||
(cache.contacts || [])
|
||||
.filter((contact) => contact.m_nsUsrName && contact.m_nsNickName && !isRawContactName(contact))
|
||||
.filter(
|
||||
(contact) => contact.m_nsUsrName && contact.m_nsNickName && !isRawContactName(contact)
|
||||
)
|
||||
.map((contact) => [contact.m_nsUsrName, contact.m_nsNickName])
|
||||
)
|
||||
cache.contacts = contacts.map((contact) => ({
|
||||
|
||||
@@ -56,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> = {
|
||||
@@ -292,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 || ''
|
||||
}))
|
||||
|
||||
|
||||
@@ -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()
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
} from '../../shared/local-api-test'
|
||||
|
||||
const REQUEST_TIMEOUT_MS = 10_000
|
||||
const GROUP_REPORT_TIMEOUT_MS = 180_000
|
||||
const MAX_BODY_SIZE = 512 * 1024
|
||||
|
||||
function isEndpointId(value: unknown): value is LocalApiEndpointId {
|
||||
@@ -122,7 +123,9 @@ export async function testLocalApiRequest(payload: unknown): Promise<LocalApiTes
|
||||
})
|
||||
}
|
||||
)
|
||||
request.setTimeout(REQUEST_TIMEOUT_MS, () => {
|
||||
const timeoutMs =
|
||||
endpointId === 'agent-group-report' ? GROUP_REPORT_TIMEOUT_MS : REQUEST_TIMEOUT_MS
|
||||
request.setTimeout(timeoutMs, () => {
|
||||
request.destroy(new Error('请求超时'))
|
||||
finish({
|
||||
ok: false,
|
||||
@@ -132,7 +135,7 @@ export async function testLocalApiRequest(payload: unknown): Promise<LocalApiTes
|
||||
durationMs: Date.now() - startedAt,
|
||||
responseSize: 0,
|
||||
errorCode: 'TIMEOUT',
|
||||
error: '请求超时(10 秒)'
|
||||
error: `请求超时(${Math.round(timeoutMs / 1000)} 秒)`
|
||||
})
|
||||
})
|
||||
request.on('error', (error: NodeJS.ErrnoException) => {
|
||||
|
||||
@@ -2,6 +2,7 @@ import { app } from 'electron'
|
||||
import fs from 'fs-extra'
|
||||
import path from 'path'
|
||||
import os from 'os'
|
||||
import { discoverWindowsDbRoots } from '../windows-db-root-discovery'
|
||||
|
||||
export interface AppSettings {
|
||||
dbRoot: string
|
||||
@@ -12,6 +13,8 @@ export interface AppSettings {
|
||||
imageXorKey: string
|
||||
imageAesKey: string
|
||||
imageKeyFallbackDisabled: boolean
|
||||
autoLogin: boolean
|
||||
autoLoginPreferenceSet: boolean
|
||||
}
|
||||
|
||||
function getDefaultDbRoot(): string {
|
||||
@@ -35,14 +38,7 @@ function getDefaultDbRootCandidates(home: string): string[] {
|
||||
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'))
|
||||
}
|
||||
}
|
||||
candidates.push(...discoverWindowsDbRoots())
|
||||
|
||||
return unique(candidates)
|
||||
}
|
||||
@@ -66,32 +62,6 @@ function getWeflowDbPathCandidates(home: string): string[] {
|
||||
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))
|
||||
}
|
||||
@@ -118,7 +88,13 @@ const DEFAULT_SETTINGS: AppSettings = {
|
||||
imageKeyRoot: defaultDbRoot,
|
||||
imageXorKey: '',
|
||||
imageAesKey: '',
|
||||
imageKeyFallbackDisabled: false
|
||||
imageKeyFallbackDisabled: false,
|
||||
autoLogin: ['1', 'true', 'yes', 'on'].includes(
|
||||
String(import.meta.env.VITE_AUTO_LOGIN || '')
|
||||
.trim()
|
||||
.toLowerCase()
|
||||
),
|
||||
autoLoginPreferenceSet: false
|
||||
}
|
||||
|
||||
const SETTINGS_FILE = path.join(
|
||||
@@ -138,6 +114,12 @@ export function loadSettings(): AppSettings {
|
||||
if (fs.existsSync(SETTINGS_FILE)) {
|
||||
const raw = fs.readJsonSync(SETTINGS_FILE) as Partial<AppSettings>
|
||||
cache = { ...DEFAULT_SETTINGS, ...raw }
|
||||
if (raw.autoLogin === undefined) {
|
||||
const hasSavedDatabaseKey = fs.existsSync(
|
||||
path.join(app.getPath('userData'), 'wechat-db-key.bin')
|
||||
)
|
||||
if (hasSavedDatabaseKey) cache.autoLogin = true
|
||||
}
|
||||
if (process.platform === 'win32' && !isUsableDbRoot(cache.dbRoot)) {
|
||||
cache.dbRoot = getDefaultDbRoot()
|
||||
}
|
||||
|
||||
+26
-42
@@ -1,6 +1,7 @@
|
||||
import fs from 'fs-extra'
|
||||
import path from 'path'
|
||||
import os from 'os'
|
||||
import { discoverWindowsDbRoots } from './windows-db-root-discovery'
|
||||
import crypto from 'crypto'
|
||||
import { createRequire } from 'module'
|
||||
import { createConnection, Socket } from 'net'
|
||||
@@ -32,6 +33,9 @@ export interface Wcdb4MessageQueryOptions {
|
||||
export interface Wcdb4GroupMember {
|
||||
m_nsUsrName: string
|
||||
nickname: string
|
||||
groupNickname: string
|
||||
wechatNickname: string
|
||||
remark: string
|
||||
m_nsHeadImgUrl: string
|
||||
}
|
||||
|
||||
@@ -300,14 +304,7 @@ export class Wcdb4Client {
|
||||
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'))
|
||||
}
|
||||
}
|
||||
candidates.push(...discoverWindowsDbRoots())
|
||||
return Array.from(new Set(candidates))
|
||||
}
|
||||
return [path.join(home, 'Library/Containers/com.tencent.xinWeChat/Data/Documents/xwechat_files')]
|
||||
@@ -332,32 +329,6 @@ export class Wcdb4Client {
|
||||
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'))
|
||||
@@ -930,17 +901,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',
|
||||
@@ -955,7 +933,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
|
||||
}
|
||||
})
|
||||
@@ -975,6 +957,8 @@ export class Wcdb4Client {
|
||||
...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 {
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
import fs from 'fs-extra'
|
||||
import path from 'path'
|
||||
|
||||
const DB_ROOT_NAMES = new Set(['xwechat_files', 'wechat files'])
|
||||
const SKIPPED_DIRECTORY_NAMES = new Set([
|
||||
'$recycle.bin',
|
||||
'system volume information',
|
||||
'windows',
|
||||
'program files',
|
||||
'program files (x86)',
|
||||
'programdata',
|
||||
'recovery'
|
||||
])
|
||||
const MAX_VISITED_DIRECTORIES_PER_DRIVE = 20_000
|
||||
let cachedDiscoveredRoots: string[] | null = null
|
||||
|
||||
function unique(values: string[]): string[] {
|
||||
return Array.from(new Set(values.map((value) => path.normalize(value))))
|
||||
}
|
||||
|
||||
export function getWindowsDrives(): string[] {
|
||||
if (process.platform !== 'win32') return []
|
||||
const drives: string[] = []
|
||||
for (let code = 67; code <= 90; code += 1) {
|
||||
const root = `${String.fromCharCode(code)}:\\`
|
||||
if (fs.existsSync(root)) drives.push(root)
|
||||
}
|
||||
return drives
|
||||
}
|
||||
|
||||
export function scanWindowsDbRoots(driveRoots: string[], maxDepth = 3): string[] {
|
||||
const results: string[] = []
|
||||
|
||||
for (const driveRoot of driveRoots) {
|
||||
const queue: Array<{ directory: string; depth: number }> = [{ directory: driveRoot, depth: 0 }]
|
||||
let visited = 0
|
||||
|
||||
while (queue.length > 0 && visited < MAX_VISITED_DIRECTORIES_PER_DRIVE) {
|
||||
const current = queue.shift()
|
||||
if (!current || current.depth >= maxDepth) continue
|
||||
|
||||
let entries: fs.Dirent[]
|
||||
try {
|
||||
entries = fs.readdirSync(current.directory, { withFileTypes: true })
|
||||
} catch {
|
||||
continue
|
||||
}
|
||||
|
||||
for (const entry of entries) {
|
||||
if (!entry.isDirectory() || entry.isSymbolicLink()) continue
|
||||
const lowered = entry.name.toLowerCase()
|
||||
const fullPath = path.join(current.directory, entry.name)
|
||||
const depth = current.depth + 1
|
||||
visited += 1
|
||||
|
||||
if (DB_ROOT_NAMES.has(lowered)) {
|
||||
results.push(fullPath)
|
||||
continue
|
||||
}
|
||||
if (depth < maxDepth && !SKIPPED_DIRECTORY_NAMES.has(lowered)) {
|
||||
queue.push({ directory: fullPath, depth })
|
||||
}
|
||||
if (visited >= MAX_VISITED_DIRECTORIES_PER_DRIVE) break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return unique(results)
|
||||
}
|
||||
|
||||
export function discoverWindowsDbRoots(): string[] {
|
||||
if (!cachedDiscoveredRoots) {
|
||||
cachedDiscoveredRoots = scanWindowsDbRoots(getWindowsDrives(), 3)
|
||||
}
|
||||
return [...cachedDiscoveredRoots]
|
||||
}
|
||||
Vendored
+55
-2
@@ -30,6 +30,15 @@ import type {
|
||||
AIVisionTestResult,
|
||||
LegacyAIConfig
|
||||
} from '../shared/ai-provider'
|
||||
import type {
|
||||
ImageAnalysisRequest,
|
||||
ImageAnalysisResponse,
|
||||
ImageCandidate,
|
||||
ImageCandidateQuery,
|
||||
ImageInsight
|
||||
} from '../shared/image-insight'
|
||||
import type { AgentHubActionResult, AgentHubLogEntry, AgentHubStatus } from '../shared/agent-hub'
|
||||
import type { AppLogEntry } from '../shared/app-log'
|
||||
|
||||
export type ParsedContent =
|
||||
| { type: 'text'; content: string }
|
||||
@@ -63,6 +72,9 @@ declare global {
|
||||
interface Window {
|
||||
electron: ElectronAPI
|
||||
api: {
|
||||
writeAppLog: (entry: AppLogEntry) => Promise<void>
|
||||
getAppLogPath: () => Promise<string>
|
||||
revealAppLog: () => Promise<void>
|
||||
initDb: (
|
||||
key: string
|
||||
) => Promise<boolean | { success: boolean; error?: string; monitoring?: boolean }>
|
||||
@@ -87,7 +99,14 @@ declare global {
|
||||
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: (
|
||||
@@ -172,6 +191,8 @@ declare global {
|
||||
apiHost: string
|
||||
apiPort: number
|
||||
imageKeyRoot: string
|
||||
autoLogin: boolean
|
||||
autoLoginPreferenceSet: boolean
|
||||
imageXorKey: string
|
||||
imageAesKey: string
|
||||
}
|
||||
@@ -196,6 +217,8 @@ declare global {
|
||||
apiHost: string
|
||||
apiPort: number
|
||||
imageKeyRoot: string
|
||||
autoLogin: boolean
|
||||
autoLoginPreferenceSet: boolean
|
||||
imageXorKey: string
|
||||
imageAesKey: string
|
||||
}
|
||||
@@ -208,6 +231,8 @@ declare global {
|
||||
apiHost: string
|
||||
apiPort: number
|
||||
imageKeyRoot: string
|
||||
autoLogin: boolean
|
||||
autoLoginPreferenceSet: boolean
|
||||
imageXorKey: string
|
||||
imageAesKey: string
|
||||
}>
|
||||
@@ -218,6 +243,8 @@ declare global {
|
||||
apiHost: string
|
||||
apiPort: number
|
||||
imageKeyRoot: string
|
||||
autoLogin: boolean
|
||||
autoLoginPreferenceSet: boolean
|
||||
imageXorKey: string
|
||||
imageAesKey: string
|
||||
}
|
||||
@@ -238,7 +265,9 @@ declare global {
|
||||
}>
|
||||
selectDbRoot: () => Promise<{ canceled: boolean; path?: string }>
|
||||
openAccountRoot: () => Promise<{ success: boolean; error?: string }>
|
||||
disconnectDb: () => Promise<{ success: boolean; error?: string }>
|
||||
disconnectDb: (options?: {
|
||||
closeNative?: boolean
|
||||
}) => Promise<{ success: boolean; error?: string }>
|
||||
apiStatus: () => Promise<{
|
||||
running: boolean
|
||||
host: string
|
||||
@@ -270,6 +299,30 @@ declare global {
|
||||
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[] }>
|
||||
getAgentHubStatus: () => Promise<AgentHubStatus>
|
||||
getAgentHubLogs: () => Promise<AgentHubLogEntry[]>
|
||||
clearAgentHubLogs: () => Promise<void>
|
||||
startAgentHubLogin: () => Promise<AgentHubActionResult>
|
||||
cancelAgentHubLogin: () => Promise<AgentHubActionResult>
|
||||
reconnectAgentHub: () => Promise<AgentHubActionResult>
|
||||
disconnectAgentHub: () => Promise<AgentHubActionResult>
|
||||
selectAgentHubTestImage: () => Promise<{ canceled: boolean; path?: string }>
|
||||
onAgentHubStatus: (callback: (status: AgentHubStatus) => void) => () => void
|
||||
onAgentHubLog: (callback: (entry: AgentHubLogEntry) => void) => () => void
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+54
-2
@@ -8,9 +8,21 @@ import type {
|
||||
AIVisionTestRequest,
|
||||
LegacyAIConfig
|
||||
} from '../shared/ai-provider'
|
||||
import type {
|
||||
ImageAnalysisRequest,
|
||||
ImageAnalysisResponse,
|
||||
ImageCandidate,
|
||||
ImageCandidateQuery,
|
||||
ImageInsight
|
||||
} from '../shared/image-insight'
|
||||
import type { AgentHubLogEntry, AgentHubStatus } from '../shared/agent-hub'
|
||||
import type { AppLogEntry } from '../shared/app-log'
|
||||
|
||||
// 渲染器的自定义 API
|
||||
const api = {
|
||||
writeAppLog: (entry: AppLogEntry) => ipcRenderer.invoke('app-log:write', entry),
|
||||
getAppLogPath: () => ipcRenderer.invoke('app-log:getPath'),
|
||||
revealAppLog: () => ipcRenderer.invoke('app-log:reveal'),
|
||||
initDb: (key: string) => ipcRenderer.invoke('db:init', key),
|
||||
getBootstrapCache: () => ipcRenderer.invoke('db:getBootstrapCache'),
|
||||
getContacts: (filter?: string) => ipcRenderer.invoke('db:getContacts', filter),
|
||||
@@ -98,7 +110,8 @@ const api = {
|
||||
reopenWithRoot: (accountRoot: string) => ipcRenderer.invoke('db:reopenWithRoot', accountRoot),
|
||||
selectDbRoot: () => ipcRenderer.invoke('settings:selectDbRoot'),
|
||||
openAccountRoot: () => ipcRenderer.invoke('settings:openAccountRoot'),
|
||||
disconnectDb: () => ipcRenderer.invoke('db:disconnect'),
|
||||
disconnectDb: (options?: { closeNative?: boolean }) =>
|
||||
ipcRenderer.invoke('db:disconnect', options),
|
||||
apiStatus: () => ipcRenderer.invoke('api:getStatus'),
|
||||
apiStart: (host?: string, port?: number) => ipcRenderer.invoke('api:start', host, port),
|
||||
apiStop: () => ipcRenderer.invoke('api:stop'),
|
||||
@@ -108,7 +121,46 @@ const api = {
|
||||
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)
|
||||
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),
|
||||
getAgentHubStatus: () => ipcRenderer.invoke('agent-hub:getStatus'),
|
||||
getAgentHubLogs: () => ipcRenderer.invoke('agent-hub:getLogs'),
|
||||
clearAgentHubLogs: () => ipcRenderer.invoke('agent-hub:clearLogs'),
|
||||
startAgentHubLogin: () => ipcRenderer.invoke('agent-hub:startLogin'),
|
||||
cancelAgentHubLogin: () => ipcRenderer.invoke('agent-hub:cancelLogin'),
|
||||
reconnectAgentHub: () => ipcRenderer.invoke('agent-hub:reconnect'),
|
||||
disconnectAgentHub: () => ipcRenderer.invoke('agent-hub:disconnect'),
|
||||
selectAgentHubTestImage: () => ipcRenderer.invoke('agent-hub:selectTestImage'),
|
||||
onAgentHubStatus: (callback: (status: AgentHubStatus) => void) => {
|
||||
const listener = (_event: Electron.IpcRendererEvent, status: AgentHubStatus): void =>
|
||||
callback(status)
|
||||
ipcRenderer.on('agent-hub:status', listener)
|
||||
return () => ipcRenderer.removeListener('agent-hub:status', listener)
|
||||
},
|
||||
onAgentHubLog: (callback: (entry: AgentHubLogEntry) => void) => {
|
||||
const listener = (_event: Electron.IpcRendererEvent, entry: AgentHubLogEntry): void =>
|
||||
callback(entry)
|
||||
ipcRenderer.on('agent-hub:log', listener)
|
||||
return () => ipcRenderer.removeListener('agent-hub:log', listener)
|
||||
}
|
||||
}
|
||||
|
||||
if (process.contextIsolated) {
|
||||
|
||||
+114
-110
@@ -4,6 +4,7 @@ import ChatWindow from './components/ChatWindow'
|
||||
import { AppShell } from './components/layout/AppShell'
|
||||
import { ApiWorkspace } from './features/api-center/ApiWorkspace'
|
||||
import { SettingsWorkspace } from './features/settings/SettingsWorkspace'
|
||||
import { AgentHubWorkspace } from './features/agent-hub/AgentHubWorkspace'
|
||||
import type { SettingsCategoryId } from './features/settings/model/types'
|
||||
import type { AIRuntimeModelConfig } from '../../shared/ai-provider'
|
||||
import { AppPage } from './components/layout/navigation'
|
||||
@@ -18,33 +19,14 @@ import type { GeneratedReportRecord, ReportWorkspaceView } from './components/re
|
||||
import { AiModelConfig, useGroupReportGeneration } from './hooks/useGroupReportGeneration'
|
||||
import { SummaryDateRange, SummaryMessageType } from './utils/group-report'
|
||||
import { Contact, Message } from '../../shared/types'
|
||||
import { DatabaseConnectionMode, DatabaseConnectionPage } from './components/DatabaseConnectionPage'
|
||||
|
||||
const SIDEBAR_MIN_WIDTH = 260
|
||||
const SIDEBAR_MAX_WIDTH = 380
|
||||
|
||||
function EyeIcon({ hidden }: { hidden: boolean }): React.ReactElement {
|
||||
return (
|
||||
<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
||||
<path
|
||||
d="M2.5 12s3.5-6 9.5-6 9.5 6 9.5 6-3.5 6-9.5 6-9.5-6-9.5-6Z"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="1.8"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
/>
|
||||
<circle cx="12" cy="12" r="3" fill="none" stroke="currentColor" strokeWidth="1.8" />
|
||||
{hidden && (
|
||||
<path
|
||||
d="M4 4l16 16"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="1.8"
|
||||
strokeLinecap="round"
|
||||
/>
|
||||
)}
|
||||
</svg>
|
||||
)
|
||||
function getDevelopmentDatabaseKey(): string {
|
||||
if (!import.meta.env.DEV) return ''
|
||||
return String(import.meta.env.VITE_DB_KEY || '').trim()
|
||||
}
|
||||
|
||||
interface SelfInfo {
|
||||
@@ -57,12 +39,6 @@ interface SelfInfo {
|
||||
const MAC_KEY_FAQ_URL = 'https://github.com/hicccc77/WeFlow/blob/main/docs/MAC-KEY-FAQ.md'
|
||||
const MESSAGE_MONITOR_DEBOUNCE_MS = 8000
|
||||
const VIEW_MESSAGE_LIMIT = 600
|
||||
const AUTO_LOGIN_ENABLED = ['1', 'true', 'yes', 'on'].includes(
|
||||
String(import.meta.env.VITE_AUTO_LOGIN || '')
|
||||
.trim()
|
||||
.toLowerCase()
|
||||
)
|
||||
|
||||
const getMessageIdentity = (message: Message): string => {
|
||||
if (message.localId) return `local:${message.localId}`
|
||||
if (message.id) return `id:${message.id}`
|
||||
@@ -81,7 +57,14 @@ const areMessagesEquivalent = (left: Message[], right: Message[]): boolean => {
|
||||
type 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
|
||||
}[]
|
||||
}
|
||||
|
||||
type GroupMemberMeta = { nickname: string; avatar: string }
|
||||
@@ -152,7 +135,7 @@ const sortMessagesChronologically = (items: Message[]): Message[] =>
|
||||
function App(): React.ReactElement {
|
||||
const [isAuthenticated, setIsAuthenticated] = useState(false)
|
||||
const [isDatabaseConnected, setIsDatabaseConnected] = useState(false)
|
||||
const [dbKey, setDbKey] = useState(import.meta.env.VITE_DB_KEY || '')
|
||||
const [dbKey, setDbKey] = useState(getDevelopmentDatabaseKey)
|
||||
const [contacts, setContacts] = useState<Contact[]>([])
|
||||
const [selectedContact, setSelectedContact] = useState<Contact | null>(null)
|
||||
const [messages, setMessages] = useState<Message[]>([])
|
||||
@@ -164,7 +147,11 @@ function App(): React.ReactElement {
|
||||
const [dbKeyStatus, setDbKeyStatus] = useState('')
|
||||
const [dbKeyStatusKind, setDbKeyStatusKind] = useState<'normal' | 'success' | 'error'>('normal')
|
||||
const [showDbKey, setShowDbKey] = useState(false)
|
||||
const [dbRootInput, setDbRootInput] = useState('')
|
||||
const [showMacKeyFaq, setShowMacKeyFaq] = useState(false)
|
||||
const [databaseConnectionMode, setDatabaseConnectionMode] = useState<DatabaseConnectionMode>(
|
||||
getDevelopmentDatabaseKey() ? 'manual' : 'automatic'
|
||||
)
|
||||
const [activePage, setActivePage] = useState<AppPage>('archive')
|
||||
const [settingsCategory, setSettingsCategory] = useState<SettingsCategoryId>('account-database')
|
||||
const [reportSourceContact, setReportSourceContact] = useState<Contact | null>(null)
|
||||
@@ -248,18 +235,25 @@ function App(): React.ReactElement {
|
||||
|
||||
const waitForPaint = (): Promise<void> => new Promise((resolve) => window.setTimeout(resolve, 80))
|
||||
|
||||
const refreshSelfInfo = async (): Promise<void> => {
|
||||
try {
|
||||
const result = await window.api.getSelf()
|
||||
if (result.ready) {
|
||||
setSelfInfo(result.info)
|
||||
} else {
|
||||
setSelfInfo(null)
|
||||
const refreshSelfInfo = async (attempts = 1): Promise<SelfInfo | null> => {
|
||||
let lastError: unknown
|
||||
for (let attempt = 0; attempt < Math.max(1, attempts); attempt += 1) {
|
||||
try {
|
||||
const result = await window.api.getSelf()
|
||||
if (result.ready && result.info) {
|
||||
setSelfInfo(result.info)
|
||||
return result.info
|
||||
}
|
||||
} catch (error) {
|
||||
lastError = error
|
||||
}
|
||||
if (attempt + 1 < attempts) {
|
||||
await new Promise((resolve) => window.setTimeout(resolve, 180))
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('[SelfInfo] 加载失败:', error)
|
||||
setSelfInfo(null)
|
||||
}
|
||||
if (lastError) console.warn('[SelfInfo] 加载失败:', lastError)
|
||||
setSelfInfo(null)
|
||||
return null
|
||||
}
|
||||
|
||||
const loadBootstrapCache = async (): Promise<boolean> => {
|
||||
@@ -322,7 +316,7 @@ function App(): React.ReactElement {
|
||||
usernames.length ? 55 : 90
|
||||
)
|
||||
let loadedCount = 0
|
||||
const chunkSize = 8
|
||||
const chunkSize = 32
|
||||
for (let index = 0; index < usernames.length; index += chunkSize) {
|
||||
if (runId !== contactAvatarHydrationRunRef.current) return
|
||||
const chunk = usernames.slice(index, index + chunkSize)
|
||||
@@ -353,7 +347,7 @@ function App(): React.ReactElement {
|
||||
} catch (error) {
|
||||
console.warn('[Contacts] avatar hydrate failed:', error)
|
||||
}
|
||||
await new Promise((resolve) => window.setTimeout(resolve, 150))
|
||||
await new Promise((resolve) => window.setTimeout(resolve, 50))
|
||||
}
|
||||
if (usernames.length) onProgress?.('头像加载完成', 90)
|
||||
}
|
||||
@@ -361,9 +355,15 @@ function App(): React.ReactElement {
|
||||
React.useEffect(() => {
|
||||
let active = true
|
||||
const attemptAutoConnect = async (): Promise<void> => {
|
||||
// 优先级 1: 构建期环境变量 VITE_DB_KEY(本地开发用)
|
||||
const envKey = String(import.meta.env.VITE_DB_KEY || '').trim()
|
||||
// 优先级 2: 上一次保存到 safeStorage 的密钥
|
||||
const settingsResult = await window.api.getSettings()
|
||||
// 预填已保存的微信聊天文件路径
|
||||
if (active && settingsResult.settings.dbRoot) {
|
||||
setDbRootInput(settingsResult.settings.dbRoot)
|
||||
}
|
||||
const autoLoginEnabled = settingsResult.settings.autoLogin
|
||||
// 开发环境允许使用 VITE_DB_KEY;生产安装包只能读取目标电脑自己的 safeStorage。
|
||||
const envKey = getDevelopmentDatabaseKey()
|
||||
// 生产环境以及未配置开发密钥时,读取上一次保存到 safeStorage 的密钥。
|
||||
let savedKey = ''
|
||||
if (!envKey) {
|
||||
const result = await window.api.getSavedDbKey()
|
||||
@@ -371,14 +371,18 @@ function App(): React.ReactElement {
|
||||
}
|
||||
const key = envKey || savedKey
|
||||
if (!key) {
|
||||
if (active) setBootState('login')
|
||||
if (active) {
|
||||
setDatabaseConnectionMode('automatic')
|
||||
setBootState('login')
|
||||
}
|
||||
return
|
||||
}
|
||||
if (active) {
|
||||
setDbKey(key)
|
||||
setDatabaseConnectionMode('manual')
|
||||
setAutoConnectSource(envKey ? 'env' : 'saved')
|
||||
setDbKeyStatus(
|
||||
AUTO_LOGIN_ENABLED
|
||||
autoLoginEnabled
|
||||
? envKey
|
||||
? '检测到环境变量中的密钥,正在自动连接...'
|
||||
: '已加载安全保存的密钥,正在自动连接...'
|
||||
@@ -387,21 +391,24 @@ function App(): React.ReactElement {
|
||||
: '已加载安全保存的密钥,请手动点击 Connect'
|
||||
)
|
||||
setDbKeyStatusKind('normal')
|
||||
setBootState(AUTO_LOGIN_ENABLED ? 'connecting' : 'login')
|
||||
setBootState(autoLoginEnabled ? 'connecting' : 'login')
|
||||
}
|
||||
if (!AUTO_LOGIN_ENABLED) return
|
||||
if (!autoLoginEnabled) return
|
||||
try {
|
||||
const result = await window.api.initDb(key)
|
||||
if (!active) return
|
||||
const success = typeof result === 'boolean' ? result : result.success
|
||||
if (success) {
|
||||
if (!settingsResult.settings.autoLoginPreferenceSet) {
|
||||
void window.api.setSettings({ autoLogin: true })
|
||||
}
|
||||
setIsNativeMonitorActive(typeof result !== 'boolean' && result.monitoring === true)
|
||||
setIsAuthenticated(true)
|
||||
setIsDatabaseConnected(true)
|
||||
setDbKeyStatus('已自动连接')
|
||||
setDbKeyStatusKind('success')
|
||||
await loadContacts()
|
||||
void refreshSelfInfo()
|
||||
await refreshSelfInfo(3)
|
||||
setIsAuthenticated(true)
|
||||
} else {
|
||||
const error = typeof result === 'boolean' ? '' : result.error
|
||||
setDbKeyStatus(`自动连接失败,请重新输入${error ? `: ${error}` : ''}`)
|
||||
@@ -439,6 +446,15 @@ function App(): React.ReactElement {
|
||||
const keyToUse = keyInput || dbKey
|
||||
if (!keyToUse) return
|
||||
setBootState('connecting')
|
||||
// 持久化用户手动指定的微信聊天文件路径,供 db:init 读取 settings.dbRoot
|
||||
const trimmedRoot = dbRootInput.trim()
|
||||
if (trimmedRoot) {
|
||||
try {
|
||||
await window.api.setSettings({ dbRoot: trimmedRoot })
|
||||
} catch {
|
||||
// 忽略保存失败,仍尝试用默认路径连接
|
||||
}
|
||||
}
|
||||
setStartupProgress({
|
||||
title: '正在连接数据库...',
|
||||
subtitle: '正在初始化微信数据',
|
||||
@@ -462,16 +478,24 @@ function App(): React.ReactElement {
|
||||
detail: '正在读取本地缓存',
|
||||
percent: 25
|
||||
})
|
||||
const hasBootstrapCache = await loadBootstrapCache()
|
||||
await loadBootstrapCache()
|
||||
// 持久化手动输入的密钥,供下次启动继续使用
|
||||
void window.api.saveDbKey(keyToUse).catch(() => undefined)
|
||||
void window.api.getSettings().then((current) => {
|
||||
if (!current.settings.autoLoginPreferenceSet) {
|
||||
void window.api.setSettings({ autoLogin: true })
|
||||
}
|
||||
})
|
||||
setStartupProgress({
|
||||
title: '正在加载账号信息...',
|
||||
subtitle: '即将进入 WechatExplorer',
|
||||
detail: '正在读取当前账号信息',
|
||||
percent: 95
|
||||
detail: '正在读取联系人和当前账号',
|
||||
percent: 70
|
||||
})
|
||||
void refreshSelfInfo()
|
||||
// 账号识别依赖联系人数据就绪。返回登录后数据已被清空,如果先查账号,
|
||||
// 会出现“数据库已连接,但账号未连接”的分离状态。手动连接与启动自动连接保持同一顺序。
|
||||
await loadContacts({ waitForAvatars: false })
|
||||
await refreshSelfInfo(3)
|
||||
setStartupProgress({
|
||||
title: '加载完成',
|
||||
subtitle: '正在进入主页面',
|
||||
@@ -483,7 +507,6 @@ function App(): React.ReactElement {
|
||||
setBootState('login')
|
||||
window.setTimeout(() => {
|
||||
setStartupProgress(null)
|
||||
if (!hasBootstrapCache) void loadContacts({ waitForAvatars: false })
|
||||
}, 500)
|
||||
} else {
|
||||
const error = typeof result === 'boolean' ? '' : result.error
|
||||
@@ -588,6 +611,7 @@ function App(): React.ReactElement {
|
||||
throw new Error(result.error || '获取密钥失败')
|
||||
}
|
||||
setDbKey(result.key)
|
||||
setDatabaseConnectionMode('manual')
|
||||
setDbKeyStatus(result.saved ? '密钥已获取并安全保存' : result.warning || '密钥已获取')
|
||||
setDbKeyStatusKind(result.saved ? 'success' : 'normal')
|
||||
} catch (error) {
|
||||
@@ -603,6 +627,7 @@ function App(): React.ReactElement {
|
||||
const result = await window.api.pasteAndSaveDbKey()
|
||||
if (result.success && result.key) {
|
||||
setDbKey(result.key)
|
||||
setDatabaseConnectionMode('manual')
|
||||
setDbKeyStatus('已从剪贴板粘贴并安全保存')
|
||||
setDbKeyStatusKind('success')
|
||||
} else {
|
||||
@@ -620,6 +645,7 @@ function App(): React.ReactElement {
|
||||
return
|
||||
}
|
||||
setDbKey('')
|
||||
setDatabaseConnectionMode('automatic')
|
||||
setDbKeyStatus('已清除保存的密钥')
|
||||
setDbKeyStatusKind('normal')
|
||||
}
|
||||
@@ -628,6 +654,7 @@ function App(): React.ReactElement {
|
||||
setIsAuthenticated(false)
|
||||
setIsDatabaseConnected(false)
|
||||
setBootState('login')
|
||||
setDatabaseConnectionMode(dbKey ? 'manual' : 'automatic')
|
||||
setActivePage('archive')
|
||||
setSettingsCategory('database-key')
|
||||
setSelectedContact(null)
|
||||
@@ -1012,9 +1039,9 @@ function App(): React.ReactElement {
|
||||
}
|
||||
|
||||
const renderPlaceholderPage = (
|
||||
page: Exclude<AppPage, 'archive' | 'report'>
|
||||
page: Exclude<AppPage, 'archive' | 'report' | 'agent-hub'>
|
||||
): React.ReactElement => {
|
||||
const labels: Record<Exclude<AppPage, 'archive' | 'report'>, string> = {
|
||||
const labels: Record<Exclude<AppPage, 'archive' | 'report' | 'agent-hub'>, string> = {
|
||||
search: '检索',
|
||||
export: '导出',
|
||||
api: 'API',
|
||||
@@ -1120,6 +1147,12 @@ function App(): React.ReactElement {
|
||||
onRevealReport={reportGeneration.revealReport}
|
||||
onViewResult={openReportResult}
|
||||
hasReportResult={generatedReports.length > 0}
|
||||
templateId={reportGeneration.templateId}
|
||||
onTemplateIdChange={reportGeneration.setTemplateId}
|
||||
memberNamePreference={reportGeneration.memberNamePreference}
|
||||
onMemberNamePreferenceChange={reportGeneration.setMemberNamePreference}
|
||||
reportTimeoutSeconds={reportGeneration.reportTimeoutSeconds}
|
||||
onReportTimeoutSecondsChange={reportGeneration.setReportTimeoutSeconds}
|
||||
/>
|
||||
<ReportTaskStatusPanel
|
||||
phase={reportGeneration.phase}
|
||||
@@ -1138,6 +1171,8 @@ function App(): React.ReactElement {
|
||||
return renderArchiveWorkspace()
|
||||
case 'report':
|
||||
return renderReportWorkspace()
|
||||
case 'agent-hub':
|
||||
return <AgentHubWorkspace />
|
||||
case 'api':
|
||||
return (
|
||||
<ApiWorkspace
|
||||
@@ -1243,57 +1278,26 @@ function App(): React.ReactElement {
|
||||
|
||||
if (!isAuthenticated) {
|
||||
return (
|
||||
<div className="login-modal">
|
||||
<div className="login-box">
|
||||
<h2>Enter WeChat DB Key</h2>
|
||||
<div className="login-input-wrapper">
|
||||
<input
|
||||
type={showDbKey ? 'text' : 'password'}
|
||||
className="login-input"
|
||||
value={dbKey}
|
||||
onChange={(e) => setDbKey(e.target.value)}
|
||||
placeholder="Key (e.g. 0x...)"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
className="login-input-toggle"
|
||||
onClick={() => setShowDbKey(!showDbKey)}
|
||||
title={showDbKey ? '隐藏密钥' : '显示密钥'}
|
||||
>
|
||||
<EyeIcon hidden={showDbKey} />
|
||||
</button>
|
||||
</div>
|
||||
<button
|
||||
className="login-btn login-btn-secondary"
|
||||
onClick={handleAutoGetDbKey}
|
||||
disabled={isFetchingDbKey}
|
||||
>
|
||||
{isFetchingDbKey ? '正在获取...' : '自动获取密钥'}
|
||||
</button>
|
||||
<button className="login-btn login-btn-secondary" onClick={handlePasteAndSaveDbKey}>
|
||||
粘贴并安全保存
|
||||
</button>
|
||||
<button className="login-btn" onClick={() => handleLogin()}>
|
||||
Connect
|
||||
</button>
|
||||
<button className="login-clear-btn" onClick={handleClearSavedDbKey}>
|
||||
清除已保存密钥
|
||||
</button>
|
||||
{dbKeyStatus && (
|
||||
<div className={`login-key-status ${dbKeyStatusKind}`}>{dbKeyStatus}</div>
|
||||
)}
|
||||
{showMacKeyFaq && (
|
||||
<a
|
||||
className="login-key-help-link"
|
||||
href={MAC_KEY_FAQ_URL}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
>
|
||||
查看 macOS 获取密钥排障指引
|
||||
</a>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<DatabaseConnectionPage
|
||||
platform={window.electron.process.platform}
|
||||
mode={databaseConnectionMode}
|
||||
dbKey={dbKey}
|
||||
dbRoot={dbRootInput}
|
||||
showDbKey={showDbKey}
|
||||
isFetching={isFetchingDbKey}
|
||||
status={dbKeyStatus}
|
||||
statusKind={dbKeyStatusKind}
|
||||
showMacKeyFaq={showMacKeyFaq}
|
||||
macKeyFaqUrl={MAC_KEY_FAQ_URL}
|
||||
onModeChange={setDatabaseConnectionMode}
|
||||
onDbKeyChange={setDbKey}
|
||||
onDbRootChange={setDbRootInput}
|
||||
onToggleDbKey={() => setShowDbKey((visible) => !visible)}
|
||||
onAutoGetKey={handleAutoGetDbKey}
|
||||
onManualConnect={() => handleLogin()}
|
||||
onPasteKey={handlePasteAndSaveDbKey}
|
||||
onClearKey={handleClearSavedDbKey}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
+3549
-247
File diff suppressed because it is too large
Load Diff
@@ -20,7 +20,6 @@ interface ChatWindowProps {
|
||||
isAiLoading?: boolean
|
||||
}
|
||||
|
||||
const MAX_RENDERED_MESSAGES = 600
|
||||
const DATE_RANGE_LABELS: Record<string, string> = {
|
||||
today: '今天',
|
||||
yesterday: '昨日',
|
||||
@@ -242,12 +241,6 @@ 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 <EmptyConversationState />
|
||||
|
||||
const dateRangeLabel = getChatHeaderRangeLabel(dateRange)
|
||||
@@ -272,8 +265,8 @@ const ChatWindow: React.FC<ChatWindowProps> = ({
|
||||
<DataTrustBar messageCount={messages.length} />
|
||||
<MessageList
|
||||
contact={contact}
|
||||
messages={renderedMessages}
|
||||
hiddenMessageCount={hiddenMessageCount}
|
||||
messages={filteredMessages}
|
||||
hiddenMessageCount={0}
|
||||
isLoadingMessages={isLoadingMessages}
|
||||
isGroupChat={isGroupChat}
|
||||
showAvatar={showAvatar}
|
||||
@@ -283,7 +276,7 @@ const ChatWindow: React.FC<ChatWindowProps> = ({
|
||||
onImageClick={openImagePreview}
|
||||
/>
|
||||
<ChatStatusBar
|
||||
count={renderedMessages.length}
|
||||
count={filteredMessages.length}
|
||||
showAvatar={showAvatar}
|
||||
isAtLatest={isAtLatest}
|
||||
onShowAvatarChange={setShowAvatar}
|
||||
|
||||
@@ -0,0 +1,300 @@
|
||||
import React from 'react'
|
||||
|
||||
export type DatabaseConnectionMode = 'automatic' | 'manual'
|
||||
export type DatabaseConnectionStatusKind = 'normal' | 'success' | 'error'
|
||||
|
||||
interface DatabaseConnectionPageProps {
|
||||
platform: string
|
||||
mode: DatabaseConnectionMode
|
||||
dbKey: string
|
||||
dbRoot: string
|
||||
showDbKey: boolean
|
||||
isFetching: boolean
|
||||
status: string
|
||||
statusKind: DatabaseConnectionStatusKind
|
||||
showMacKeyFaq: boolean
|
||||
macKeyFaqUrl: string
|
||||
onModeChange: (mode: DatabaseConnectionMode) => void
|
||||
onDbKeyChange: (value: string) => void
|
||||
onDbRootChange: (value: string) => void
|
||||
onToggleDbKey: () => void
|
||||
onAutoGetKey: () => void
|
||||
onManualConnect: () => void
|
||||
onPasteKey: () => void
|
||||
onClearKey: () => void
|
||||
}
|
||||
|
||||
function LineIcon({
|
||||
name
|
||||
}: {
|
||||
name: 'shield' | 'lock' | 'cloud' | 'info' | 'database'
|
||||
}): React.ReactElement {
|
||||
const paths = {
|
||||
shield: <path d="M12 3 5 6v5c0 4.5 2.8 7.7 7 10 4.2-2.3 7-5.5 7-10V6l-7-3Z" />,
|
||||
lock: <path d="M7 10V8a5 5 0 0 1 10 0v2m-11 0h12v10H6V10Z" />,
|
||||
cloud: (
|
||||
<path d="m4 4 16 16M7.5 16H6a4 4 0 0 1-.5-8A6.5 6.5 0 0 1 17 6.8M18.5 10A4 4 0 0 1 18 18h-7" />
|
||||
),
|
||||
info: <path d="M12 8h.01M11 12h1v4h1M12 3a9 9 0 1 0 0 18 9 9 0 0 0 0-18Z" />,
|
||||
database: (
|
||||
<path d="M5 6c0-1.7 3.1-3 7-3s7 1.3 7 3-3.1 3-7 3-7-1.3-7-3Zm0 0v6c0 1.7 3.1 3 7 3s7-1.3 7-3V6m-14 6v6c0 1.7 3.1 3 7 3s7-1.3 7-3v-6" />
|
||||
)
|
||||
}
|
||||
return (
|
||||
<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
||||
<g
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="1.7"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
>
|
||||
{paths[name]}
|
||||
</g>
|
||||
</svg>
|
||||
)
|
||||
}
|
||||
|
||||
function EyeIcon({ visible }: { visible: boolean }): React.ReactElement {
|
||||
return (
|
||||
<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
||||
<path d="M2.5 12s3.5-6 9.5-6 9.5 6 9.5 6-3.5 6-9.5 6-9.5-6-9.5-6Z" />
|
||||
<circle cx="12" cy="12" r="3" />
|
||||
{!visible && <path d="M4 4l16 16" />}
|
||||
</svg>
|
||||
)
|
||||
}
|
||||
|
||||
function StoragePathHelp(): React.ReactElement {
|
||||
return (
|
||||
<span className="database-login-path-help">
|
||||
<span
|
||||
className="database-login-path-help-icon"
|
||||
tabIndex={0}
|
||||
aria-describedby="storage-path-help"
|
||||
>
|
||||
!
|
||||
</span>
|
||||
<span id="storage-path-help" className="database-login-path-tooltip" role="tooltip">
|
||||
打开微信设置,在缓存管理中复制存储路径,然后粘贴到这里。
|
||||
</span>
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
export function DatabaseConnectionPage({
|
||||
platform,
|
||||
mode,
|
||||
dbKey,
|
||||
dbRoot,
|
||||
showDbKey,
|
||||
isFetching,
|
||||
status,
|
||||
statusKind,
|
||||
showMacKeyFaq,
|
||||
macKeyFaqUrl,
|
||||
onModeChange,
|
||||
onDbKeyChange,
|
||||
onDbRootChange,
|
||||
onToggleDbKey,
|
||||
onAutoGetKey,
|
||||
onManualConnect,
|
||||
onPasteKey,
|
||||
onClearKey
|
||||
}: DatabaseConnectionPageProps): React.ReactElement {
|
||||
const isMac = platform === 'darwin'
|
||||
const defaultPath = isMac
|
||||
? '~/Library/Containers/com.tencent.xinWeChat/Data/Library/Application Support/com.tencent.xinWeChat/'
|
||||
: 'C:\\Users\\...\\WeChat Files\\Msg'
|
||||
const keyIsValid = /^[0-9a-f]{64}$/i.test(dbKey.trim().replace(/^0x/i, ''))
|
||||
|
||||
return (
|
||||
<main className="database-login-page">
|
||||
<section className="database-login-brand" aria-label="WechatExplorer 产品说明">
|
||||
<div className="database-login-brand-content">
|
||||
<div className="database-login-logo" aria-hidden="true">
|
||||
<LineIcon name="database" />
|
||||
</div>
|
||||
<h1>WechatExplorer</h1>
|
||||
<p className="database-login-tagline">你的本地微信聊天档案</p>
|
||||
<p className="database-login-description">
|
||||
连接本机微信数据库,开始检索、整理和分析聊天记录。
|
||||
</p>
|
||||
<div className="database-login-promises">
|
||||
<div>
|
||||
<LineIcon name="shield" />
|
||||
<span>仅限本机</span>
|
||||
</div>
|
||||
<div>
|
||||
<LineIcon name="lock" />
|
||||
<span>加密保存</span>
|
||||
</div>
|
||||
<div>
|
||||
<LineIcon name="cloud" />
|
||||
<span>不会上传</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="database-login-brand-footer">LOCAL-FIRST · PRIVATE · SECURE</div>
|
||||
</section>
|
||||
|
||||
<section className="database-login-workspace" aria-label="数据库连接">
|
||||
<div className="database-login-panel">
|
||||
<div className="database-login-tabs" role="tablist" aria-label="连接方式">
|
||||
<button
|
||||
type="button"
|
||||
role="tab"
|
||||
aria-selected={mode === 'automatic'}
|
||||
className={mode === 'automatic' ? 'active' : ''}
|
||||
onClick={() => onModeChange('automatic')}
|
||||
>
|
||||
自动获取
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
role="tab"
|
||||
aria-selected={mode === 'manual'}
|
||||
className={mode === 'manual' ? 'active' : ''}
|
||||
onClick={() => onModeChange('manual')}
|
||||
>
|
||||
手动输入
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{mode === 'automatic' ? (
|
||||
<div className="database-login-auto" role="tabpanel">
|
||||
<div className={`database-login-state-card ${statusKind}`}>
|
||||
<div className="database-login-state-heading">
|
||||
<span className="database-login-state-icon">
|
||||
<LineIcon name="info" />
|
||||
</span>
|
||||
<div>
|
||||
<strong>
|
||||
{statusKind === 'error' ? '未能获取数据库密钥' : '已准备检测微信数据库'}
|
||||
</strong>
|
||||
<p>
|
||||
{statusKind === 'error'
|
||||
? status
|
||||
: status || '请保持微信客户端正在运行,系统将尝试安全获取数据库密钥。'}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<dl className="database-login-diagnostics">
|
||||
<div>
|
||||
<dt>微信客户端</dt>
|
||||
<dd>{isFetching ? '正在检测' : '等待检测'}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>
|
||||
存储路径
|
||||
<StoragePathHelp />
|
||||
</dt>
|
||||
<dd>
|
||||
<span className="database-login-path-input-wrap">
|
||||
<input
|
||||
type="text"
|
||||
value={dbRoot}
|
||||
onChange={(event) => onDbRootChange(event.target.value)}
|
||||
placeholder={defaultPath}
|
||||
title={dbRoot || defaultPath}
|
||||
aria-label="微信数据存储路径"
|
||||
spellCheck={false}
|
||||
onFocus={(event) => event.currentTarget.select()}
|
||||
/>
|
||||
<span className="database-login-path-value" role="status">
|
||||
{dbRoot || defaultPath}
|
||||
</span>
|
||||
</span>
|
||||
</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>数据库状态</dt>
|
||||
<dd>{statusKind === 'error' ? '无法连接' : '准备连接'}</dd>
|
||||
</div>
|
||||
</dl>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
className="database-login-primary"
|
||||
onClick={onAutoGetKey}
|
||||
disabled={isFetching}
|
||||
>
|
||||
{isFetching
|
||||
? '正在获取密钥…'
|
||||
: statusKind === 'error'
|
||||
? '重新检测'
|
||||
: '自动获取密钥'}
|
||||
</button>
|
||||
{showMacKeyFaq && (
|
||||
<a href={macKeyFaqUrl} target="_blank" rel="noreferrer">
|
||||
查看详情 · 连接帮助
|
||||
</a>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<div className="database-login-manual" role="tabpanel">
|
||||
<div className="database-login-field">
|
||||
<label htmlFor="database-login-key">数据库密钥</label>
|
||||
<div className="database-login-key-input">
|
||||
<input
|
||||
id="database-login-key"
|
||||
type={showDbKey ? 'text' : 'password'}
|
||||
value={dbKey}
|
||||
onChange={(event) => onDbKeyChange(event.target.value)}
|
||||
placeholder="输入或粘贴 64 位数据库密钥"
|
||||
autoComplete="off"
|
||||
spellCheck={false}
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onToggleDbKey}
|
||||
title={showDbKey ? '隐藏密钥' : '显示密钥'}
|
||||
>
|
||||
<EyeIcon visible={showDbKey} />
|
||||
</button>
|
||||
</div>
|
||||
<small>密钥通过系统安全存储加密保存在当前设备。</small>
|
||||
</div>
|
||||
{platform === 'win32' && (
|
||||
<div className="database-login-field">
|
||||
<label htmlFor="database-login-root">
|
||||
微信数据目录
|
||||
<StoragePathHelp />
|
||||
</label>
|
||||
<input
|
||||
id="database-login-root"
|
||||
value={dbRoot}
|
||||
onChange={(event) => onDbRootChange(event.target.value)}
|
||||
placeholder={defaultPath}
|
||||
title={dbRoot || defaultPath}
|
||||
spellCheck={false}
|
||||
onFocus={(event) => event.currentTarget.select()}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
{status && <div className={`database-login-message ${statusKind}`}>{status}</div>}
|
||||
<button
|
||||
type="button"
|
||||
className="database-login-primary"
|
||||
onClick={onManualConnect}
|
||||
disabled={!keyIsValid}
|
||||
>
|
||||
连接数据库
|
||||
</button>
|
||||
<button type="button" className="database-login-secondary" onClick={onPasteKey}>
|
||||
从剪贴板粘贴并安全保存
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="database-login-footer-actions">
|
||||
<button type="button" onClick={onClearKey}>
|
||||
清除已保存密钥
|
||||
</button>
|
||||
<span>WechatExplorer</span>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</main>
|
||||
)
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import React from 'react'
|
||||
import { useVirtualizer } from '@tanstack/react-virtual'
|
||||
import { Contact, Message } from '../../../../shared/types'
|
||||
import { MessageGroup } from './MessageGroup'
|
||||
import { buildMessageGroups } from './messageGrouping'
|
||||
@@ -29,6 +30,16 @@ export function MessageList({
|
||||
onImageClick
|
||||
}: MessageListProps): React.ReactElement {
|
||||
const groups = React.useMemo(() => buildMessageGroups(messages), [messages])
|
||||
// TanStack Virtual intentionally exposes mutable measurement methods.
|
||||
// eslint-disable-next-line react-hooks/incompatible-library
|
||||
const virtualizer = useVirtualizer({
|
||||
count: groups.length,
|
||||
getScrollElement: () => listRef.current,
|
||||
estimateSize: () => 96,
|
||||
getItemKey: (index) => groups[index]?.id || index,
|
||||
overscan: 8
|
||||
})
|
||||
const virtualItems = virtualizer.getVirtualItems()
|
||||
|
||||
return (
|
||||
<div className="message-list wechat-message-list" ref={listRef} onScroll={onScroll}>
|
||||
@@ -40,16 +51,29 @@ export function MessageList({
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{groups.map((group) => (
|
||||
<MessageGroup
|
||||
key={group.id}
|
||||
group={group}
|
||||
contact={contact}
|
||||
isGroupChat={isGroupChat}
|
||||
showAvatar={showAvatar}
|
||||
onImageClick={onImageClick}
|
||||
/>
|
||||
))}
|
||||
<div className="virtual-message-list" style={{ height: `${virtualizer.getTotalSize()}px` }}>
|
||||
{virtualItems.map((virtualItem) => {
|
||||
const group = groups[virtualItem.index]
|
||||
if (!group) return null
|
||||
return (
|
||||
<div
|
||||
key={virtualItem.key}
|
||||
ref={virtualizer.measureElement}
|
||||
data-index={virtualItem.index}
|
||||
className="virtual-message-group"
|
||||
style={{ transform: `translateY(${virtualItem.start}px)` }}
|
||||
>
|
||||
<MessageGroup
|
||||
group={group}
|
||||
contact={contact}
|
||||
isGroupChat={isGroupChat}
|
||||
showAvatar={showAvatar}
|
||||
onImageClick={onImageClick}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
<div ref={bottomRef} />
|
||||
</div>
|
||||
)
|
||||
|
||||
@@ -45,6 +45,16 @@ function NavIcon({ page }: NavIconProps): React.ReactElement {
|
||||
<path d="M5.5 15.5v3h13v-3" />
|
||||
</svg>
|
||||
)
|
||||
case 'agent-hub':
|
||||
return (
|
||||
<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
||||
<rect x="5" y="7" width="14" height="11" rx="3" />
|
||||
<path d="M12 4.5V7" />
|
||||
<circle cx="9.5" cy="12" r="1" />
|
||||
<circle cx="14.5" cy="12" r="1" />
|
||||
<path d="M9.5 15h5" />
|
||||
</svg>
|
||||
)
|
||||
case 'api':
|
||||
return (
|
||||
<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
export type AppPage = 'archive' | 'search' | 'report' | 'export' | 'api' | 'settings'
|
||||
export type AppPage = 'archive' | 'search' | 'report' | 'agent-hub' | 'export' | 'api' | 'settings'
|
||||
|
||||
export interface NavigationItem {
|
||||
id: AppPage
|
||||
@@ -9,6 +9,7 @@ export const PRIMARY_NAV_ITEMS: NavigationItem[] = [
|
||||
{ id: 'archive', label: '档案' },
|
||||
{ id: 'search', label: '检索' },
|
||||
{ id: 'report', label: '日报' },
|
||||
{ id: 'agent-hub', label: 'Agent' },
|
||||
{ id: 'export', label: '导出' },
|
||||
{ id: 'api', label: 'API' },
|
||||
{ id: 'settings', label: '设置' }
|
||||
|
||||
@@ -3,6 +3,7 @@ import { Contact } from '../../../../shared/types'
|
||||
import {
|
||||
AiModelConfig,
|
||||
RangeMessageState,
|
||||
ReportMemberNamePreference,
|
||||
ReportGenerationPhase,
|
||||
ReportPaths
|
||||
} from '../../hooks/useGroupReportGeneration'
|
||||
@@ -11,7 +12,9 @@ import { MessageTypeSelector } from './MessageTypeSelector'
|
||||
import { ModelSummary } from './ModelSummary'
|
||||
import { ReportDensitySelector } from './ReportDensitySelector'
|
||||
import { ReportRangeSelector } from './ReportRangeSelector'
|
||||
import { ReportMemberNameSelector } from './ReportMemberNameSelector'
|
||||
import { ReportSectionSelector } from './ReportSectionSelector'
|
||||
import { ReportTemplateId, ReportTemplateSelector } from './ReportTemplateSelector'
|
||||
|
||||
interface AiReportWorkspaceProps {
|
||||
sourceContact: Contact | null
|
||||
@@ -36,6 +39,12 @@ interface AiReportWorkspaceProps {
|
||||
onRevealReport: () => Promise<{ success: boolean; error?: string }>
|
||||
onViewResult: () => void
|
||||
hasReportResult: boolean
|
||||
templateId: ReportTemplateId
|
||||
onTemplateIdChange: (value: ReportTemplateId) => void
|
||||
memberNamePreference: ReportMemberNamePreference
|
||||
onMemberNamePreferenceChange: (value: ReportMemberNamePreference) => void
|
||||
reportTimeoutSeconds: number
|
||||
onReportTimeoutSecondsChange: (value: number) => void
|
||||
}
|
||||
|
||||
const rangeLabel = (range: SummaryDateRange): string => {
|
||||
@@ -76,7 +85,13 @@ export function AiReportWorkspace({
|
||||
onCopyImage,
|
||||
onRevealReport,
|
||||
onViewResult,
|
||||
hasReportResult
|
||||
hasReportResult,
|
||||
templateId,
|
||||
onTemplateIdChange,
|
||||
memberNamePreference,
|
||||
onMemberNamePreferenceChange,
|
||||
reportTimeoutSeconds,
|
||||
onReportTimeoutSecondsChange
|
||||
}: AiReportWorkspaceProps): React.ReactElement {
|
||||
const [actionStatus, setActionStatus] = useState('')
|
||||
const groupName = sourceContact?.m_nsNickName || sourceContact?.m_nsUsrName || '未选择群聊'
|
||||
@@ -144,7 +159,35 @@ export function AiReportWorkspace({
|
||||
/>
|
||||
<ReportSectionSelector />
|
||||
<ReportDensitySelector />
|
||||
<ReportTemplateSelector
|
||||
value={templateId}
|
||||
onChange={onTemplateIdChange}
|
||||
disabled={configDisabled}
|
||||
/>
|
||||
<ReportMemberNameSelector
|
||||
value={memberNamePreference}
|
||||
onChange={onMemberNamePreferenceChange}
|
||||
disabled={configDisabled}
|
||||
/>
|
||||
<ModelSummary config={modelConfig} onOpenSettings={onOpenModelSettings} />
|
||||
<section className="report-config-section report-timeout-section">
|
||||
<div>
|
||||
<h3>日报生成超时</h3>
|
||||
<p>大群聊和图片识别耗时较长,可单独设置本次日报最多等待时间。</p>
|
||||
</div>
|
||||
<label>
|
||||
<input
|
||||
type="number"
|
||||
min={30}
|
||||
max={1800}
|
||||
step={30}
|
||||
value={reportTimeoutSeconds}
|
||||
disabled={configDisabled}
|
||||
onChange={(event) => onReportTimeoutSecondsChange(Number(event.target.value))}
|
||||
/>
|
||||
<span>秒</span>
|
||||
</label>
|
||||
</section>
|
||||
<section className="report-privacy-note">
|
||||
<h3>隐私说明</h3>
|
||||
<p>微信数据库和聊天记录默认从本机读取。</p>
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
import React from 'react'
|
||||
import { ReportMemberNamePreference } from '../../hooks/useGroupReportGeneration'
|
||||
|
||||
const OPTIONS: {
|
||||
value: ReportMemberNamePreference
|
||||
label: string
|
||||
description: string
|
||||
}[] = [
|
||||
{
|
||||
value: 'groupNickname',
|
||||
label: '群昵称',
|
||||
description: '优先使用成员在当前群设置的昵称。'
|
||||
},
|
||||
{
|
||||
value: 'wechatNickname',
|
||||
label: '微信昵称',
|
||||
description: '优先使用对方公开的微信昵称。'
|
||||
},
|
||||
{
|
||||
value: 'remark',
|
||||
label: '通讯录备注',
|
||||
description: '优先使用你为对方设置的备注。'
|
||||
}
|
||||
]
|
||||
|
||||
export function ReportMemberNameSelector({
|
||||
value,
|
||||
disabled,
|
||||
onChange
|
||||
}: {
|
||||
value: ReportMemberNamePreference
|
||||
disabled?: boolean
|
||||
onChange: (value: ReportMemberNamePreference) => void
|
||||
}): React.ReactElement {
|
||||
return (
|
||||
<section className="report-section">
|
||||
<h3>成员名称</h3>
|
||||
<p className="report-section-desc">选择日报中群成员的显示名称,默认使用群昵称。</p>
|
||||
<div className="report-template-list">
|
||||
{OPTIONS.map((option) => (
|
||||
<label
|
||||
className={`report-template-item ${value === option.value ? 'active' : ''} ${disabled ? 'disabled' : ''}`}
|
||||
key={option.value}
|
||||
>
|
||||
<input
|
||||
type="radio"
|
||||
name="report-member-name"
|
||||
checked={value === option.value}
|
||||
disabled={disabled}
|
||||
onChange={() => onChange(option.value)}
|
||||
/>
|
||||
<div className="report-template-body">
|
||||
<div className="report-template-title">{option.label}</div>
|
||||
<div className="report-template-tagline">{option.description}</div>
|
||||
</div>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import React from 'react'
|
||||
import React, { useEffect, useState } from 'react'
|
||||
import { ReportGenerationPhase } from '../../hooks/useGroupReportGeneration'
|
||||
|
||||
interface ReportTaskStatusPanelProps {
|
||||
@@ -27,6 +27,14 @@ export function ReportTaskStatusPanel({
|
||||
}: ReportTaskStatusPanelProps): React.ReactElement {
|
||||
const activeIndex = phaseIndex(phase)
|
||||
const completedAll = phase === 'success'
|
||||
const [logPath, setLogPath] = useState('')
|
||||
|
||||
useEffect(() => {
|
||||
void window.api
|
||||
.getAppLogPath()
|
||||
.then(setLogPath)
|
||||
.catch(() => undefined)
|
||||
}, [])
|
||||
|
||||
return (
|
||||
<aside className="report-task-panel">
|
||||
@@ -70,6 +78,10 @@ export function ReportTaskStatusPanel({
|
||||
<button type="button" onClick={onRetry}>
|
||||
重试
|
||||
</button>
|
||||
<button type="button" onClick={() => void window.api.revealAppLog()}>
|
||||
打开诊断日志
|
||||
</button>
|
||||
{logPath && <small className="report-task-log-path">{logPath}</small>}
|
||||
</div>
|
||||
)}
|
||||
{phase === 'success' && (
|
||||
|
||||
@@ -0,0 +1,139 @@
|
||||
import React, { useState } from 'react'
|
||||
|
||||
export type ReportTemplateId = 'v1' | 'v2'
|
||||
|
||||
interface TemplateMeta {
|
||||
id: ReportTemplateId
|
||||
label: string
|
||||
tagline: string
|
||||
preview: { title: string; sections: string[] }
|
||||
}
|
||||
|
||||
const TEMPLATES: TemplateMeta[] = [
|
||||
{
|
||||
id: 'v1',
|
||||
label: '模板1 · 经典日报',
|
||||
tagline: '实用信息 / 重要消息 / 金句 / 问答 / 数据可视化',
|
||||
preview: {
|
||||
title: '经典日报',
|
||||
sections: [
|
||||
'今日讨论热点',
|
||||
'AI 识别的图片精选',
|
||||
'实用信息与资源',
|
||||
'重要消息汇总',
|
||||
'有趣对话或金句',
|
||||
'问题与解答',
|
||||
'群内数据可视化',
|
||||
'词云/关键词'
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
id: 'v2',
|
||||
label: '模板2 · 支持图片板块',
|
||||
tagline: '包含热点图片与上下文;需要模型服务商支持图片识别',
|
||||
preview: {
|
||||
title: '支持图片板块',
|
||||
sections: [
|
||||
'今日讨论热点',
|
||||
'重要消息',
|
||||
'待办事项和未解决问题',
|
||||
'今日名场面',
|
||||
'今日群数据',
|
||||
'关键词',
|
||||
'实用信息与资源',
|
||||
'问题与解答',
|
||||
'今日剧情时间线',
|
||||
'群聊反转现场',
|
||||
'AI 识别的图片精选',
|
||||
'今日群相册',
|
||||
'语音之最',
|
||||
'语音时长榜',
|
||||
'今日临时人设',
|
||||
'话题参与链路'
|
||||
]
|
||||
}
|
||||
}
|
||||
]
|
||||
|
||||
interface ReportTemplateSelectorProps {
|
||||
value: ReportTemplateId
|
||||
onChange: (value: ReportTemplateId) => void
|
||||
disabled?: boolean
|
||||
}
|
||||
|
||||
export const ReportTemplateSelector: React.FC<ReportTemplateSelectorProps> = ({
|
||||
value,
|
||||
onChange,
|
||||
disabled
|
||||
}) => {
|
||||
const [previewing, setPreviewing] = useState<TemplateMeta | null>(null)
|
||||
return (
|
||||
<section className="report-section">
|
||||
<h3>日报模板</h3>
|
||||
<p className="report-section-desc">
|
||||
选择日报呈现风格。模板2 支持图片板块,但需要 AI 模型服务商支持图片识别。
|
||||
</p>
|
||||
<div className="report-template-list">
|
||||
{TEMPLATES.map((tpl) => {
|
||||
const active = value === tpl.id
|
||||
return (
|
||||
<div
|
||||
key={tpl.id}
|
||||
className={`report-template-item ${active ? 'active' : ''} ${disabled ? 'disabled' : ''}`}
|
||||
>
|
||||
<label>
|
||||
<input
|
||||
type="radio"
|
||||
name="report-template"
|
||||
value={tpl.id}
|
||||
checked={active}
|
||||
disabled={disabled}
|
||||
onChange={() => onChange(tpl.id)}
|
||||
/>
|
||||
<div className="report-template-body">
|
||||
<div className="report-template-title">{tpl.label}</div>
|
||||
<div className="report-template-tagline">{tpl.tagline}</div>
|
||||
</div>
|
||||
</label>
|
||||
<button
|
||||
type="button"
|
||||
className="report-template-preview-btn"
|
||||
onClick={() => setPreviewing(tpl)}
|
||||
>
|
||||
预览
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
{previewing && (
|
||||
<div className="report-template-preview-mask" onClick={() => setPreviewing(null)}>
|
||||
<div className="report-template-preview-card" onClick={(e) => e.stopPropagation()}>
|
||||
<h4>{previewing.preview.title}</h4>
|
||||
<p className="muted">{previewing.tagline}</p>
|
||||
<div className="report-template-preview-frame">
|
||||
<div className="fake-card fake-hero">
|
||||
<div className="fake-title">群聊日报 · 预览</div>
|
||||
<div className="fake-sub">2026-xx-xx · 基于已加载记录</div>
|
||||
</div>
|
||||
{previewing.preview.sections.map((s) => (
|
||||
<div className="fake-card fake-section" key={s}>
|
||||
<div className="fake-bar" />
|
||||
<div className="fake-section-title">{s}</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
className="report-template-preview-close"
|
||||
onClick={() => setPreviewing(null)}
|
||||
>
|
||||
关闭
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
)
|
||||
}
|
||||
@@ -37,10 +37,7 @@ export function ReportViewer({
|
||||
return () => window.cancelAnimationFrame(frame)
|
||||
}, [report?.id])
|
||||
|
||||
const title = useMemo(
|
||||
() => (report ? `${report.contactName} 群聊日报` : 'AI 日报'),
|
||||
[report]
|
||||
)
|
||||
const title = useMemo(() => (report ? `${report.contactName} 群聊日报` : 'AI 日报'), [report])
|
||||
|
||||
const fitWidth = (): void => {
|
||||
const viewport = viewportRef.current
|
||||
@@ -108,10 +105,16 @@ export function ReportViewer({
|
||||
}}
|
||||
onLoad={(event) => {
|
||||
const image = event.currentTarget
|
||||
setNaturalSize({
|
||||
const nextSize = {
|
||||
width: image.naturalWidth,
|
||||
height: image.naturalHeight
|
||||
})
|
||||
}
|
||||
setNaturalSize(nextSize)
|
||||
const viewport = viewportRef.current
|
||||
if (viewport && nextSize.width > viewport.clientWidth - 48) {
|
||||
const fittedZoom = Math.max(0.25, (viewport.clientWidth - 48) / nextSize.width)
|
||||
setZoom(Number(fittedZoom.toFixed(2)))
|
||||
}
|
||||
}}
|
||||
onError={() => {
|
||||
setImageError('日报图片加载失败')
|
||||
|
||||
@@ -0,0 +1,280 @@
|
||||
import React from 'react'
|
||||
import type {
|
||||
AgentHubLogEntry,
|
||||
AgentHubLogSource,
|
||||
AgentHubStatus,
|
||||
WechatConnectorStatus
|
||||
} from '../../../../shared/agent-hub'
|
||||
|
||||
const STATUS_LABELS: Record<WechatConnectorStatus, string> = {
|
||||
checking: '正在检查',
|
||||
disconnected: '未连接',
|
||||
starting: '正在连接',
|
||||
waiting_scan: '等待扫码',
|
||||
scanned: '已扫码,等待手机确认',
|
||||
online: '在线',
|
||||
error: '连接异常'
|
||||
}
|
||||
|
||||
const LOG_SOURCE_LABELS: Record<AgentHubLogSource, string> = {
|
||||
system: '系统',
|
||||
'agent-hub': 'Agent Hub',
|
||||
'wechat-connector': '微信连接器'
|
||||
}
|
||||
|
||||
export function AgentHubWorkspace(): React.ReactElement {
|
||||
const [status, setStatus] = React.useState<AgentHubStatus>({
|
||||
hub: 'offline',
|
||||
connector: 'checking',
|
||||
updatedAt: Date.now()
|
||||
})
|
||||
const [busy, setBusy] = React.useState(false)
|
||||
const [logs, setLogs] = React.useState<AgentHubLogEntry[]>([])
|
||||
const [logSource, setLogSource] = React.useState<'all' | AgentHubLogSource>('all')
|
||||
const logBodyRef = React.useRef<HTMLDivElement>(null)
|
||||
|
||||
React.useEffect(() => {
|
||||
let mounted = true
|
||||
void window.api.getAgentHubStatus().then((next) => {
|
||||
if (mounted) setStatus(next)
|
||||
})
|
||||
void window.api.getAgentHubLogs().then((entries) => {
|
||||
if (mounted) setLogs(entries)
|
||||
})
|
||||
const unsubscribe = window.api.onAgentHubStatus((next) => {
|
||||
if (mounted) setStatus(next)
|
||||
})
|
||||
const unsubscribeLog = window.api.onAgentHubLog((entry) => {
|
||||
if (mounted) setLogs((current) => [...current.slice(-799), entry])
|
||||
})
|
||||
return () => {
|
||||
mounted = false
|
||||
unsubscribe()
|
||||
unsubscribeLog()
|
||||
}
|
||||
}, [])
|
||||
|
||||
const visibleLogs = logs.filter((entry) => logSource === 'all' || entry.source === logSource)
|
||||
|
||||
React.useEffect(() => {
|
||||
const body = logBodyRef.current
|
||||
if (body) body.scrollTop = body.scrollHeight
|
||||
}, [visibleLogs.length])
|
||||
|
||||
const copyLogs = async (): Promise<void> => {
|
||||
const text = visibleLogs
|
||||
.map(
|
||||
(entry) =>
|
||||
`${new Date(entry.timestamp).toLocaleTimeString()} [${LOG_SOURCE_LABELS[entry.source]}] [${entry.level}] ${entry.message}`
|
||||
)
|
||||
.join('\n')
|
||||
await window.api.copyText(text)
|
||||
}
|
||||
|
||||
const clearLogs = async (): Promise<void> => {
|
||||
await window.api.clearAgentHubLogs()
|
||||
setLogs([])
|
||||
}
|
||||
|
||||
const runAction = async (
|
||||
action: () => Promise<{ status: AgentHubStatus; error?: string }>
|
||||
): Promise<void> => {
|
||||
setBusy(true)
|
||||
try {
|
||||
const result = await action()
|
||||
setStatus(result.status)
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
const isLoginFlow = ['starting', 'waiting_scan', 'scanned'].includes(status.connector)
|
||||
const showQRCode = Boolean(status.qrCodeDataUrl) && status.connector !== 'online'
|
||||
|
||||
return (
|
||||
<div className="agent-hub-workspace">
|
||||
<header className="agent-hub-header">
|
||||
<div>
|
||||
<div className="agent-hub-eyebrow">WechatExplorer</div>
|
||||
<h1>Agent Hub</h1>
|
||||
<p>让微信机器人安全调用聊天数据与 AI 能力。</p>
|
||||
</div>
|
||||
<span className={`agent-hub-runtime ${status.hub}`}>
|
||||
Agent Hub {status.hub === 'online' ? '运行中' : '未运行'}
|
||||
</span>
|
||||
</header>
|
||||
|
||||
<div className="agent-hub-grid">
|
||||
<section className="agent-hub-card agent-hub-login-card">
|
||||
<div className="agent-hub-card-heading">
|
||||
<div>
|
||||
<span className="agent-hub-card-kicker">微信机器人</span>
|
||||
<h2>连接微信</h2>
|
||||
</div>
|
||||
<span className={`agent-hub-status ${status.connector}`}>
|
||||
<i aria-hidden />
|
||||
{STATUS_LABELS[status.connector]}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{showQRCode ? (
|
||||
<div className="agent-hub-qr-panel">
|
||||
<div className="agent-hub-qr-frame">
|
||||
<img src={status.qrCodeDataUrl} alt="微信机器人登录二维码" />
|
||||
</div>
|
||||
<div className="agent-hub-qr-copy">
|
||||
<h3>
|
||||
{status.connector === 'scanned' ? '请在手机上确认登录' : '使用微信扫描二维码'}
|
||||
</h3>
|
||||
<p>二维码仅用于机器人账号登录,不会读取你的微信密码。</p>
|
||||
<button
|
||||
type="button"
|
||||
className="agent-hub-button secondary"
|
||||
disabled={busy}
|
||||
onClick={() => void runAction(() => window.api.cancelAgentHubLogin())}
|
||||
>
|
||||
取消
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
) : status.connector === 'online' ? (
|
||||
<div className="agent-hub-connected">
|
||||
<div className="agent-hub-connected-icon" aria-hidden>
|
||||
✓
|
||||
</div>
|
||||
<div>
|
||||
<h3>微信机器人已连接</h3>
|
||||
<p>{status.accountId || status.wechatUserId || '登录凭据已就绪'}</p>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="agent-hub-empty-login">
|
||||
<div className="agent-hub-phone" aria-hidden>
|
||||
<span />
|
||||
</div>
|
||||
<h3>{status.connector === 'error' ? '连接遇到问题' : '尚未连接微信机器人'}</h3>
|
||||
<p>{status.error || '扫码登录后,即可从微信向 Agent Hub 提问。'}</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="agent-hub-actions">
|
||||
{status.connector === 'online' ? (
|
||||
<>
|
||||
<button
|
||||
type="button"
|
||||
className="agent-hub-button secondary"
|
||||
disabled={busy}
|
||||
onClick={() => void runAction(() => window.api.startAgentHubLogin())}
|
||||
>
|
||||
重新扫码登录
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="agent-hub-button danger"
|
||||
disabled={busy}
|
||||
onClick={() => void runAction(() => window.api.disconnectAgentHub())}
|
||||
>
|
||||
断开连接
|
||||
</button>
|
||||
</>
|
||||
) : !isLoginFlow ? (
|
||||
<button
|
||||
type="button"
|
||||
className="agent-hub-button primary"
|
||||
disabled={busy || status.hub !== 'online'}
|
||||
onClick={() => void runAction(() => window.api.startAgentHubLogin())}
|
||||
>
|
||||
{busy ? '正在获取二维码…' : '扫码登录微信机器人'}
|
||||
</button>
|
||||
) : null}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<aside className="agent-hub-card agent-hub-capability-card">
|
||||
<span className="agent-hub-card-kicker">已启用能力</span>
|
||||
<h2>微信数据助手</h2>
|
||||
<p>机器人通过本机 Agent Hub 调用 WechatExplorer,不向公网暴露数据库。</p>
|
||||
<div className="agent-hub-example">
|
||||
<span>支持自然语言,可以这样问</span>
|
||||
<strong>“最近 5 条消息是谁?”</strong>
|
||||
<strong>“帮我看看最近跟xx聊了些什么”</strong>
|
||||
<strong>“生成产品交流群今天的群聊总结图片”</strong>
|
||||
</div>
|
||||
<ul>
|
||||
<li>
|
||||
<i />
|
||||
本机 HTTP 通信
|
||||
</li>
|
||||
<li>
|
||||
<i />
|
||||
入站请求鉴权
|
||||
</li>
|
||||
<li>
|
||||
<i />
|
||||
消息重复保护
|
||||
</li>
|
||||
<li>
|
||||
<i />
|
||||
使用已配置 AI 理解自然语言
|
||||
</li>
|
||||
<li>
|
||||
<i className={status.dataApi === 'online' ? '' : 'offline'} />
|
||||
本地数据 API:{status.dataApi === 'online' ? '已连接' : '未连接'}
|
||||
</li>
|
||||
<li>
|
||||
<i className={status.databaseReady ? '' : 'offline'} />
|
||||
微信数据库:{status.databaseReady ? '可查询' : '未就绪'}
|
||||
</li>
|
||||
</ul>
|
||||
</aside>
|
||||
</div>
|
||||
|
||||
<section className="agent-hub-card agent-hub-log-card">
|
||||
<div className="agent-hub-log-heading">
|
||||
<div>
|
||||
<span className="agent-hub-card-kicker">故障诊断</span>
|
||||
<h2>运行日志</h2>
|
||||
</div>
|
||||
<div className="agent-hub-log-actions">
|
||||
<select
|
||||
aria-label="筛选日志来源"
|
||||
value={logSource}
|
||||
onChange={(event) => setLogSource(event.target.value as 'all' | AgentHubLogSource)}
|
||||
>
|
||||
<option value="all">全部来源</option>
|
||||
<option value="system">系统</option>
|
||||
<option value="agent-hub">Agent Hub</option>
|
||||
<option value="wechat-connector">微信连接器</option>
|
||||
</select>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void copyLogs()}
|
||||
disabled={visibleLogs.length === 0}
|
||||
>
|
||||
复制日志
|
||||
</button>
|
||||
<button type="button" onClick={() => void clearLogs()}>
|
||||
清空
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div className="agent-hub-log-body" ref={logBodyRef}>
|
||||
{visibleLogs.length === 0 ? (
|
||||
<div className="agent-hub-log-empty">
|
||||
暂无运行日志。收到消息后,这里会显示处理到哪一步。
|
||||
</div>
|
||||
) : (
|
||||
visibleLogs.map((entry) => (
|
||||
<div className={`agent-hub-log-line ${entry.level}`} key={entry.id}>
|
||||
<time>{new Date(entry.timestamp).toLocaleTimeString()}</time>
|
||||
<span className={`source ${entry.source}`}>{LOG_SOURCE_LABELS[entry.source]}</span>
|
||||
<code>{entry.message}</code>
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
<p className="agent-hub-log-note">日志会隐藏 Token 和二维码数据,不记录你的微信密码。</p>
|
||||
</section>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -40,6 +40,17 @@ export function ApiRequestTester({
|
||||
void onCopyCurl(command)
|
||||
}
|
||||
const update = (key: string, value: string): void => onParams({ ...params, [key]: value })
|
||||
const selectTestImage = async (): Promise<void> => {
|
||||
const result = await window.api.selectAgentHubTestImage()
|
||||
if (result.canceled || !result.path) return
|
||||
let payload: Record<string, unknown> = {}
|
||||
try {
|
||||
payload = JSON.parse(body) as Record<string, unknown>
|
||||
} catch {
|
||||
// Replace an invalid draft with a valid send-test request.
|
||||
}
|
||||
onBody(JSON.stringify({ ...payload, media_url: result.path }, null, 2))
|
||||
}
|
||||
return (
|
||||
<section className="api-request-tester" id="api-request-tester">
|
||||
<div className="api-section-heading">
|
||||
@@ -77,6 +88,14 @@ export function ApiRequestTester({
|
||||
/>
|
||||
</label>
|
||||
)}
|
||||
{endpoint.id === 'agent-send' && (
|
||||
<div className="api-upload-test-row">
|
||||
<button type="button" onClick={() => void selectTestImage()}>
|
||||
选择测试图片
|
||||
</button>
|
||||
<span>选择后只会填入本地路径;点击“发送请求”才会真正发送。</span>
|
||||
</div>
|
||||
)}
|
||||
<div className="api-tester-actions">
|
||||
<button type="button" onClick={onClear}>
|
||||
清空
|
||||
|
||||
@@ -1,7 +1,11 @@
|
||||
import { useCallback, useEffect, useReducer } from 'react'
|
||||
import type { Contact } from '../../../../../shared/types'
|
||||
import { findEndpoint } from '../model/apiEndpoints'
|
||||
import { REPORT_REQUEST_PRESET } from '../model/requestPresets'
|
||||
import {
|
||||
AGENT_GROUP_REPORT_PRESET,
|
||||
AGENT_SEND_PRESET,
|
||||
REPORT_REQUEST_PRESET
|
||||
} from '../model/requestPresets'
|
||||
import { type AgentInstallTarget, type SkillInstallSource } from '../model/skillDistribution'
|
||||
import type {
|
||||
ApiResponse,
|
||||
@@ -66,14 +70,23 @@ function reducer(state: State, action: Action): State {
|
||||
switch (action.type) {
|
||||
case 'loaded':
|
||||
return { ...state, settings: action.settings, service: action.service, skill: action.skill }
|
||||
case 'endpoint':
|
||||
case 'endpoint': {
|
||||
const preset =
|
||||
action.endpointId === 'report'
|
||||
? REPORT_REQUEST_PRESET
|
||||
: action.endpointId === 'agent-group-report'
|
||||
? AGENT_GROUP_REPORT_PRESET
|
||||
: action.endpointId === 'agent-send'
|
||||
? AGENT_SEND_PRESET
|
||||
: state.body
|
||||
return {
|
||||
...state,
|
||||
endpointId: action.endpointId,
|
||||
params: action.talker && action.endpointId === 'chatlog' ? { talker: action.talker } : {},
|
||||
body: action.endpointId === 'report' ? state.body || REPORT_REQUEST_PRESET : state.body,
|
||||
body: preset,
|
||||
error: ''
|
||||
}
|
||||
}
|
||||
case 'params':
|
||||
return { ...state, params: action.params }
|
||||
case 'body':
|
||||
|
||||
@@ -62,6 +62,20 @@ export const API_ENDPOINTS: ApiEndpoint[] = [
|
||||
name: '群聊日报导出',
|
||||
description: '通过内置模板导出群聊日报 HTML 与 PNG。',
|
||||
body: true
|
||||
}),
|
||||
endpoint('agent-status', {
|
||||
name: 'Agent Hub 状态',
|
||||
description: '检查 Agent Hub、微信连接器、本地数据 API 和数据库状态。'
|
||||
}),
|
||||
endpoint('agent-group-report', {
|
||||
name: '生成群聊总结图片',
|
||||
description: '读取指定群聊并生成今天、昨天或近 7 天的总结长图。',
|
||||
body: true
|
||||
}),
|
||||
endpoint('agent-send', {
|
||||
name: '微信发送测试',
|
||||
description: '测试文字或本地图片发送,并区分凭证失效、连接器离线和发送成功。',
|
||||
body: true
|
||||
})
|
||||
]
|
||||
|
||||
|
||||
@@ -29,3 +29,15 @@ export const REPORT_REQUEST_PRESET = JSON.stringify(
|
||||
null,
|
||||
2
|
||||
)
|
||||
|
||||
export const AGENT_GROUP_REPORT_PRESET = JSON.stringify(
|
||||
{ group: '技术交流', range: 'today' },
|
||||
null,
|
||||
2
|
||||
)
|
||||
|
||||
export const AGENT_SEND_PRESET = JSON.stringify(
|
||||
{ to: '', text: 'WechatExplorer Agent Hub 发送测试' },
|
||||
null,
|
||||
2
|
||||
)
|
||||
|
||||
@@ -174,13 +174,31 @@ export function AIProviderEditor({
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={model.capabilities.vision}
|
||||
onChange={(event) => {
|
||||
const vision = event.target.checked
|
||||
// OCR 是 vision 的派生能力:勾 vision 时自动带 OCR
|
||||
patchModel(index, {
|
||||
capabilities: {
|
||||
...model.capabilities,
|
||||
vision,
|
||||
ocr: vision ? true : model.capabilities.ocr
|
||||
}
|
||||
})
|
||||
}}
|
||||
/>
|
||||
图片理解
|
||||
</label>
|
||||
<label title="图片文字识别,跟随图片理解能力">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={model.capabilities.ocr}
|
||||
onChange={(event) =>
|
||||
patchModel(index, {
|
||||
capabilities: { ...model.capabilities, vision: event.target.checked }
|
||||
capabilities: { ...model.capabilities, ocr: event.target.checked }
|
||||
})
|
||||
}
|
||||
/>
|
||||
图片理解
|
||||
图片文字识别
|
||||
</label>
|
||||
<label>
|
||||
<input
|
||||
@@ -296,5 +314,5 @@ export function AIProviderEditor({
|
||||
}
|
||||
|
||||
function emptyModel(): AIModelDefinition {
|
||||
return { name: '', id: '', capabilities: { chat: true, vision: false, longContext: false } }
|
||||
return { name: '', id: '', capabilities: { chat: true, vision: false, ocr: false, longContext: false } }
|
||||
}
|
||||
|
||||
@@ -88,7 +88,7 @@ export function createProviderFromPreset(presetId = 'deepseek'): AIProviderConfi
|
||||
{
|
||||
name: preset.model || '默认模型',
|
||||
id: preset.model,
|
||||
capabilities: { chat: true, vision: false, longContext: false }
|
||||
capabilities: { chat: true, vision: false, ocr: false, longContext: false }
|
||||
}
|
||||
],
|
||||
defaultModel: preset.model,
|
||||
|
||||
@@ -191,7 +191,9 @@ export function useDatabaseKeyController({
|
||||
])
|
||||
|
||||
const returnToLogin = useCallback(async (): Promise<void> => {
|
||||
const result = await window.api.disconnectDb()
|
||||
// macOS WCDB 的 close 会关闭进程级原生运行时,返回登录时只退出 UI 连接态。
|
||||
// 用户再次点击连接后由 db:init 复用已验证的本机连接。
|
||||
const result = await window.api.disconnectDb({ closeNative: false })
|
||||
if (!result.success) {
|
||||
onNotice(result.error || '断开数据库连接失败')
|
||||
return
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import { AccountOverview } from '../account-database/AccountOverview'
|
||||
import { ConnectionHealthSection } from '../account-database/ConnectionHealthSection'
|
||||
import { LocalPrivacyNotice } from '../account-database/LocalPrivacyNotice'
|
||||
@@ -25,6 +26,26 @@ export function AccountDatabasePage({
|
||||
onNotice: (message: string) => void
|
||||
}): React.ReactElement {
|
||||
const controller = useAccountDatabaseController({ dbKey, dbReady, selfInfo, onNotice })
|
||||
const [autoLogin, setAutoLogin] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
let active = true
|
||||
void window.api.getSettings().then((result) => {
|
||||
if (active) setAutoLogin(result.settings.autoLogin)
|
||||
})
|
||||
return () => {
|
||||
active = false
|
||||
}
|
||||
}, [])
|
||||
|
||||
const changeAutoLogin = async (checked: boolean): Promise<void> => {
|
||||
const result = await window.api.setSettings({
|
||||
autoLogin: checked,
|
||||
autoLoginPreferenceSet: true
|
||||
})
|
||||
setAutoLogin(result.settings.autoLogin)
|
||||
onNotice(checked ? '已开启启动时自动连接' : '已关闭启动时自动连接')
|
||||
}
|
||||
return (
|
||||
<div className="settings-page">
|
||||
<header className="settings-page-header">
|
||||
@@ -58,6 +79,20 @@ export function AccountDatabasePage({
|
||||
: undefined
|
||||
}
|
||||
/>
|
||||
<h2 className="settings-section-heading">启动行为</h2>
|
||||
<section className="settings-card settings-auto-login-card">
|
||||
<label>
|
||||
<span>
|
||||
<b>启动时自动连接数据库</b>
|
||||
<small>使用安全存储中已保存的数据库密钥;可随时关闭。</small>
|
||||
</span>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={autoLogin}
|
||||
onChange={(event) => void changeAutoLogin(event.target.checked)}
|
||||
/>
|
||||
</label>
|
||||
</section>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -3,6 +3,7 @@ import { Contact, Message } from '../../../shared/types'
|
||||
import {
|
||||
buildGroupReportInput,
|
||||
getSummaryDateRange,
|
||||
GROUP_REPORT_JSON_REPAIR_SYSTEM_PROMPT,
|
||||
GROUP_REPORT_SYSTEM_PROMPT,
|
||||
isInternalName,
|
||||
parseGroupDailyReport,
|
||||
@@ -10,8 +11,10 @@ import {
|
||||
SummaryDateRange,
|
||||
SummaryMessageType
|
||||
} from '../utils/group-report'
|
||||
import { ReportTemplateId } from '../components/reports/ReportTemplateSelector'
|
||||
|
||||
const REPORT_STEP_TIMEOUT_MS = 90_000
|
||||
const REPORT_MODEL_TIMEOUT_BUFFER_MS = 10_000
|
||||
|
||||
export type ReportGenerationPhase =
|
||||
| 'idle'
|
||||
@@ -29,8 +32,11 @@ export interface AiModelConfig {
|
||||
modelName: string
|
||||
configured: boolean
|
||||
status: 'untested' | 'connected' | 'error'
|
||||
timeoutMs?: number
|
||||
}
|
||||
|
||||
export type ReportMemberNamePreference = 'groupNickname' | 'wechatNickname' | 'remark'
|
||||
|
||||
export interface ReportPaths {
|
||||
htmlPath: string
|
||||
pngPath: string
|
||||
@@ -84,10 +90,14 @@ export interface RangeMessageState {
|
||||
error: string
|
||||
}
|
||||
|
||||
const withTimeout = async <T>(promise: Promise<T>, label: string): Promise<T> => {
|
||||
const withTimeout = async <T>(
|
||||
promise: Promise<T>,
|
||||
label: string,
|
||||
timeoutMs = REPORT_STEP_TIMEOUT_MS
|
||||
): Promise<T> => {
|
||||
let timer: number | undefined
|
||||
const timeout = new Promise<never>((_, reject) => {
|
||||
timer = window.setTimeout(() => reject(new Error(`${label} 超时`)), REPORT_STEP_TIMEOUT_MS)
|
||||
timer = window.setTimeout(() => reject(new Error(`${label} 超时`)), timeoutMs)
|
||||
})
|
||||
try {
|
||||
return await Promise.race([promise, timeout])
|
||||
@@ -99,6 +109,31 @@ const withTimeout = async <T>(promise: Promise<T>, label: string): Promise<T> =>
|
||||
const errorMessage = (error: unknown): string =>
|
||||
error instanceof Error ? error.message : String(error)
|
||||
|
||||
const writeReportLog = (
|
||||
level: 'info' | 'warn' | 'error',
|
||||
message: string,
|
||||
details?: Record<string, unknown>
|
||||
): void => {
|
||||
void window.api
|
||||
.writeAppLog({ level, scope: 'group-report', message, details })
|
||||
.catch(() => undefined)
|
||||
}
|
||||
|
||||
const jsonErrorContext = (raw: string, error: unknown): Record<string, unknown> => {
|
||||
const message = errorMessage(error)
|
||||
const position = Number(/\bposition\s+(\d+)/i.exec(message)?.[1])
|
||||
const safePosition = Number.isFinite(position) ? Math.max(0, Math.min(raw.length, position)) : 0
|
||||
return {
|
||||
error: message,
|
||||
outputLength: raw.length,
|
||||
position: Number.isFinite(position) ? position : undefined,
|
||||
context:
|
||||
raw.length && Number.isFinite(position)
|
||||
? raw.slice(Math.max(0, safePosition - 300), Math.min(raw.length, safePosition + 300))
|
||||
: raw.slice(0, 600)
|
||||
}
|
||||
}
|
||||
|
||||
const isGroupContact = (contact: Contact | null): boolean =>
|
||||
Boolean(contact?.type === 'group' || contact?.m_nsUsrName?.endsWith('@chatroom'))
|
||||
|
||||
@@ -127,14 +162,43 @@ const estimateTokenUsage = (
|
||||
}
|
||||
}
|
||||
|
||||
const applyGroupMemberNames = async (contact: Contact, messages: Message[]): Promise<Message[]> => {
|
||||
let memberMap = new Map<string, { nickname: string; avatar: string }>()
|
||||
const mergeTokenUsage = (
|
||||
first: NonNullable<ReportGenerationMetadata['tokenUsage']>,
|
||||
second: NonNullable<ReportGenerationMetadata['tokenUsage']>
|
||||
): NonNullable<ReportGenerationMetadata['tokenUsage']> => ({
|
||||
input: (first.input || 0) + (second.input || 0),
|
||||
output: (first.output || 0) + (second.output || 0),
|
||||
total: (first.total || 0) + (second.total || 0),
|
||||
estimated: Boolean(first.estimated || second.estimated)
|
||||
})
|
||||
|
||||
const applyGroupMemberNames = async (
|
||||
contact: Contact,
|
||||
messages: Message[],
|
||||
preference: ReportMemberNamePreference
|
||||
): Promise<Message[]> => {
|
||||
let memberMap = new Map<
|
||||
string,
|
||||
{
|
||||
nickname: string
|
||||
groupNickname: string
|
||||
wechatNickname: string
|
||||
remark: string
|
||||
avatar: string
|
||||
}
|
||||
>()
|
||||
try {
|
||||
const snapshot = await withTimeout(window.api.getGroupSnapshot(contact.md5), '读取群成员')
|
||||
memberMap = new Map(
|
||||
(snapshot?.members || []).map((member) => [
|
||||
member.wxid,
|
||||
{ nickname: member.nickname || member.wxid, avatar: member.avatar || '' }
|
||||
{
|
||||
nickname: member.nickname || member.wxid,
|
||||
groupNickname: member.groupNickname || '',
|
||||
wechatNickname: member.wechatNickname || '',
|
||||
remark: member.remark || '',
|
||||
avatar: member.avatar || ''
|
||||
}
|
||||
])
|
||||
)
|
||||
} catch (error) {
|
||||
@@ -143,11 +207,22 @@ const applyGroupMemberNames = async (contact: Contact, messages: Message[]): Pro
|
||||
|
||||
if (!memberMap.size) return messages
|
||||
return messages.map((message) => {
|
||||
if (!isInternalName(message.name)) return message
|
||||
const senderId = String(message.senderId || message.name || '')
|
||||
const member = memberMap.get(senderId)
|
||||
if (!member?.nickname || isInternalName(member.nickname)) return message
|
||||
return { ...message, name: member.nickname, img: message.img || member.avatar }
|
||||
if (!member) return message
|
||||
const preferredNames: Record<ReportMemberNamePreference, string[]> = {
|
||||
// Keep the three modes semantically distinct. `member.nickname` may
|
||||
// already be a contact remark, so it must not leak into the first two.
|
||||
groupNickname: [member.groupNickname, member.wechatNickname],
|
||||
wechatNickname: [member.wechatNickname, member.groupNickname],
|
||||
remark: [member.remark, member.groupNickname, member.wechatNickname, member.nickname]
|
||||
}
|
||||
const name = preferredNames[preference].find((value) => value && !isInternalName(value))
|
||||
return {
|
||||
...message,
|
||||
name: name || (preference === 'remark' ? message.name : ''),
|
||||
img: message.img || member.avatar
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -174,6 +249,12 @@ export function useGroupReportGeneration({
|
||||
closeResult: () => void
|
||||
copyImage: () => Promise<{ success: boolean; error?: string }>
|
||||
revealReport: () => Promise<{ success: boolean; error?: string }>
|
||||
templateId: ReportTemplateId
|
||||
setTemplateId: (value: ReportTemplateId) => void
|
||||
memberNamePreference: ReportMemberNamePreference
|
||||
setMemberNamePreference: (value: ReportMemberNamePreference) => void
|
||||
reportTimeoutSeconds: number
|
||||
setReportTimeoutSeconds: (value: number) => void
|
||||
} {
|
||||
const [phase, setPhase] = useState<ReportGenerationPhase>('idle')
|
||||
const [error, setError] = useState('')
|
||||
@@ -181,11 +262,32 @@ export function useGroupReportGeneration({
|
||||
const [rangeState, setRangeState] = useState<RangeMessageState>({ status: 'idle', error: '' })
|
||||
const [generatedImage, setGeneratedImage] = useState<string | null>(null)
|
||||
const [reportPaths, setReportPaths] = useState<ReportPaths | null>(null)
|
||||
const [templateId, setTemplateId] = useState<ReportTemplateId>('v1')
|
||||
const [memberNamePreference, setMemberNamePreferenceState] = useState<ReportMemberNamePreference>(
|
||||
() => {
|
||||
const saved = localStorage.getItem('group_report_member_name_preference')
|
||||
return saved === 'wechatNickname' || saved === 'remark' ? saved : 'groupNickname'
|
||||
}
|
||||
)
|
||||
const [reportTimeoutSeconds, setReportTimeoutSecondsState] = useState<number>(() => {
|
||||
const saved = Number(localStorage.getItem('group_report_timeout_seconds'))
|
||||
return Number.isFinite(saved) && saved >= 30 ? saved : 300
|
||||
})
|
||||
const [generationMetadata, setGenerationMetadata] = useState<ReportGenerationMetadata>({
|
||||
generationLogs: []
|
||||
})
|
||||
const rangeRequestIdRef = useRef(0)
|
||||
|
||||
const setMemberNamePreference = useCallback((value: ReportMemberNamePreference): void => {
|
||||
localStorage.setItem('group_report_member_name_preference', value)
|
||||
setMemberNamePreferenceState(value)
|
||||
}, [])
|
||||
const setReportTimeoutSeconds = useCallback((value: number): void => {
|
||||
const normalized = Math.max(30, Math.min(1800, Math.round(Number(value) || 300)))
|
||||
localStorage.setItem('group_report_timeout_seconds', String(normalized))
|
||||
setReportTimeoutSecondsState(normalized)
|
||||
}, [])
|
||||
|
||||
const isGenerating =
|
||||
phase === 'loadingMessages' ||
|
||||
phase === 'preparingInput' ||
|
||||
@@ -292,6 +394,7 @@ export function useGroupReportGeneration({
|
||||
}
|
||||
|
||||
const startGenerateTime = Date.now()
|
||||
let failedAt = '初始化'
|
||||
const logs: ReportGenerationLog[] = []
|
||||
const pushLog = (log: ReportGenerationLog): void => {
|
||||
logs.push(log)
|
||||
@@ -322,21 +425,40 @@ export function useGroupReportGeneration({
|
||||
modelName: modelConfig.model,
|
||||
generationLogs: []
|
||||
})
|
||||
writeReportLog('info', '开始生成群聊日报', {
|
||||
groupName: sourceContact.m_nsNickName || sourceContact.m_nsUsrName,
|
||||
dateRange: summaryDateRange,
|
||||
selectedMessageTypes: summaryMessageTypes,
|
||||
providerName: modelConfig.providerName,
|
||||
model: modelConfig.model,
|
||||
templateId
|
||||
})
|
||||
|
||||
try {
|
||||
failedAt = '读取聊天记录'
|
||||
const sourceMessages = await trackStep('读取聊天记录', () => loadRangeMessages(true))
|
||||
|
||||
const selectedTypes = selectedMessageTypeSet(summaryMessageTypes)
|
||||
const filteredMessages = sourceMessages.filter((message) => selectedTypes.has(message.type))
|
||||
if (!filteredMessages.length) throw new Error('当前范围没有可总结消息')
|
||||
writeReportLog('info', '聊天记录读取完成', {
|
||||
sourceMessageCount: sourceMessages.length,
|
||||
filteredMessageCount: filteredMessages.length
|
||||
})
|
||||
|
||||
setPhase('preparingInput')
|
||||
failedAt = '整理日报输入'
|
||||
const input = await trackStep('整理输入', async () => {
|
||||
const namedReportMessages = await applyGroupMemberNames(sourceContact, filteredMessages)
|
||||
return buildGroupReportInput(namedReportMessages, sourceContact, true)
|
||||
const namedReportMessages = await applyGroupMemberNames(
|
||||
sourceContact,
|
||||
filteredMessages,
|
||||
memberNamePreference
|
||||
)
|
||||
return buildGroupReportInput(namedReportMessages, sourceContact, true, 'full')
|
||||
})
|
||||
|
||||
setPhase('requestingModel')
|
||||
failedAt = '调用模型生成内容'
|
||||
const aiMessages = [
|
||||
{ role: 'system', content: GROUP_REPORT_SYSTEM_PROMPT },
|
||||
{ role: 'user', content: input.prompt }
|
||||
@@ -345,23 +467,92 @@ export function useGroupReportGeneration({
|
||||
withTimeout(
|
||||
window.api.aiChat(aiMessages, {
|
||||
providerId: modelConfig.providerId,
|
||||
modelId: modelConfig.model
|
||||
modelId: modelConfig.model,
|
||||
timeoutMs: reportTimeoutSeconds * 1000
|
||||
}),
|
||||
'AI 生成日报'
|
||||
'AI 生成日报',
|
||||
reportTimeoutSeconds * 1000 + REPORT_MODEL_TIMEOUT_BUFFER_MS
|
||||
)
|
||||
)
|
||||
if (!result.success || !result.data) throw new Error(result.error || 'AI 请求失败')
|
||||
writeReportLog('info', '模型响应完成', {
|
||||
outputLength: result.data.length,
|
||||
usage: result.usage
|
||||
})
|
||||
|
||||
const tokenUsage =
|
||||
let tokenUsage =
|
||||
result.usage && result.usage.total
|
||||
? result.usage
|
||||
: estimateTokenUsage(aiMessages, result.data)
|
||||
|
||||
const report = parseGroupDailyReport(result.data, input.topSpeakers, input.activeTimeline)
|
||||
let report: ReturnType<typeof parseGroupDailyReport>
|
||||
try {
|
||||
report = parseGroupDailyReport(
|
||||
result.data,
|
||||
input.topSpeakers,
|
||||
input.activeTimeline,
|
||||
input.voiceLeaderboard || [],
|
||||
input.metadata,
|
||||
input.media
|
||||
)
|
||||
} catch (parseError) {
|
||||
writeReportLog('warn', '本地修复日报 JSON 失败,尝试由模型纠正', {
|
||||
...jsonErrorContext(result.data, parseError),
|
||||
retry: 1
|
||||
})
|
||||
const repairMessages = [
|
||||
{
|
||||
role: 'system',
|
||||
content: GROUP_REPORT_JSON_REPAIR_SYSTEM_PROMPT
|
||||
},
|
||||
{ role: 'user', content: result.data }
|
||||
]
|
||||
const repairResult = await trackStep('AI 修复 JSON', () =>
|
||||
withTimeout(
|
||||
window.api.aiChat(repairMessages, {
|
||||
providerId: modelConfig.providerId,
|
||||
modelId: modelConfig.model,
|
||||
timeoutMs: reportTimeoutSeconds * 1000
|
||||
}),
|
||||
'AI 修复日报 JSON',
|
||||
reportTimeoutSeconds * 1000 + REPORT_MODEL_TIMEOUT_BUFFER_MS
|
||||
)
|
||||
)
|
||||
if (!repairResult.success || !repairResult.data) {
|
||||
throw new Error(repairResult.error || 'AI 修复日报 JSON 失败', { cause: parseError })
|
||||
}
|
||||
const repairUsage =
|
||||
repairResult.usage && repairResult.usage.total
|
||||
? repairResult.usage
|
||||
: estimateTokenUsage(repairMessages, repairResult.data)
|
||||
tokenUsage = mergeTokenUsage(tokenUsage, repairUsage)
|
||||
try {
|
||||
report = parseGroupDailyReport(
|
||||
repairResult.data,
|
||||
input.topSpeakers,
|
||||
input.activeTimeline,
|
||||
input.voiceLeaderboard || [],
|
||||
input.metadata,
|
||||
input.media
|
||||
)
|
||||
writeReportLog('info', '模型已纠正日报 JSON', {
|
||||
retry: 1,
|
||||
outputLength: repairResult.data.length
|
||||
})
|
||||
} catch (retryParseError) {
|
||||
writeReportLog(
|
||||
'error',
|
||||
'日报 JSON 重试后仍解析失败',
|
||||
jsonErrorContext(repairResult.data, retryParseError)
|
||||
)
|
||||
throw retryParseError
|
||||
}
|
||||
}
|
||||
|
||||
setPhase('exportingReport')
|
||||
failedAt = '导出 HTML 与 PNG'
|
||||
const exported = await withTimeout(
|
||||
window.api.exportGroupReport({ report, metadata: input.metadata }),
|
||||
window.api.exportGroupReport({ report, metadata: input.metadata, templateId }),
|
||||
'日报图片导出'
|
||||
)
|
||||
if (!exported.success || !exported.imageDataUrl || !exported.htmlPath || !exported.pngPath) {
|
||||
@@ -395,11 +586,32 @@ export function useGroupReportGeneration({
|
||||
generationLogs: [...logs]
|
||||
})
|
||||
setPhase('success')
|
||||
writeReportLog('info', '群聊日报生成成功', {
|
||||
durationMs: Date.now() - startGenerateTime,
|
||||
htmlPath: exported.htmlPath,
|
||||
pngPath: exported.pngPath
|
||||
})
|
||||
} catch (generateError) {
|
||||
setError(errorMessage(generateError))
|
||||
const message = errorMessage(generateError)
|
||||
writeReportLog('error', '群聊日报生成失败', {
|
||||
error: message,
|
||||
failedAt,
|
||||
durationMs: Date.now() - startGenerateTime
|
||||
})
|
||||
setError(message)
|
||||
setPhase('error')
|
||||
}
|
||||
}, [isGenerating, loadRangeMessages, modelConfig, sourceContact, summaryMessageTypes])
|
||||
}, [
|
||||
isGenerating,
|
||||
loadRangeMessages,
|
||||
memberNamePreference,
|
||||
modelConfig,
|
||||
reportTimeoutSeconds,
|
||||
sourceContact,
|
||||
summaryDateRange,
|
||||
summaryMessageTypes,
|
||||
templateId
|
||||
])
|
||||
|
||||
const clearError = useCallback((): void => {
|
||||
setError('')
|
||||
@@ -437,6 +649,12 @@ export function useGroupReportGeneration({
|
||||
clearError,
|
||||
closeResult,
|
||||
copyImage,
|
||||
revealReport
|
||||
revealReport,
|
||||
templateId,
|
||||
setTemplateId,
|
||||
memberNamePreference,
|
||||
setMemberNamePreference,
|
||||
reportTimeoutSeconds,
|
||||
setReportTimeoutSeconds
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,6 +4,37 @@ import App from './App'
|
||||
import './styles/tokens.css'
|
||||
import './assets/main.css'
|
||||
|
||||
window.addEventListener('error', (event) => {
|
||||
void window.api
|
||||
.writeAppLog({
|
||||
level: 'error',
|
||||
scope: 'renderer',
|
||||
message: event.message || 'Renderer 未捕获错误',
|
||||
details: {
|
||||
filename: event.filename,
|
||||
line: event.lineno,
|
||||
column: event.colno,
|
||||
stack: event.error instanceof Error ? event.error.stack : undefined
|
||||
}
|
||||
})
|
||||
.catch(() => undefined)
|
||||
})
|
||||
|
||||
window.addEventListener('unhandledrejection', (event) => {
|
||||
const reason = event.reason
|
||||
void window.api
|
||||
.writeAppLog({
|
||||
level: 'error',
|
||||
scope: 'renderer',
|
||||
message: reason instanceof Error ? reason.message : 'Renderer Promise 未处理拒绝',
|
||||
details: {
|
||||
stack: reason instanceof Error ? reason.stack : undefined,
|
||||
reason: reason instanceof Error ? undefined : String(reason)
|
||||
}
|
||||
})
|
||||
.catch(() => undefined)
|
||||
})
|
||||
|
||||
ReactDOM.createRoot(document.getElementById('root') as HTMLElement).render(
|
||||
<React.StrictMode>
|
||||
<App />
|
||||
|
||||
@@ -0,0 +1,696 @@
|
||||
import { Contact, Message } from '../../../shared/types'
|
||||
import {
|
||||
GroupDailyReport,
|
||||
GroupReportMetadata,
|
||||
ReportFunBadge,
|
||||
ReportMediaGalleryItem,
|
||||
ReportMode,
|
||||
ReportSpeakerRank,
|
||||
ReportVisionGalleryItem,
|
||||
ReportVoiceHighlight,
|
||||
ReportVoiceLeaderboardItem
|
||||
} from '../../../shared/group-report'
|
||||
import type {
|
||||
ImageAnalysisRequest,
|
||||
ImageAnalysisResponse,
|
||||
ImageCandidate,
|
||||
ImageCandidateQuery
|
||||
} from '../../../shared/image-insight'
|
||||
|
||||
interface ReportImageReadResult {
|
||||
success: boolean
|
||||
data?: string
|
||||
error?: string
|
||||
}
|
||||
|
||||
declare const window: {
|
||||
api: {
|
||||
imageListCandidates: (query: ImageCandidateQuery) => Promise<{
|
||||
success: boolean
|
||||
candidates: ImageCandidate[]
|
||||
error?: string
|
||||
}>
|
||||
imageAnalyze: (request: ImageAnalysisRequest) => Promise<ImageAnalysisResponse>
|
||||
getImage: (
|
||||
imageMd5?: string,
|
||||
imageDatNameOrThumb?: string | boolean,
|
||||
sessionId?: string
|
||||
) => Promise<ReportImageReadResult>
|
||||
}
|
||||
}
|
||||
|
||||
export interface GroupReportTranscriptRow {
|
||||
id: string
|
||||
datetime: string
|
||||
timestamp: number
|
||||
sender: string
|
||||
content: string
|
||||
avatar?: string
|
||||
}
|
||||
|
||||
export interface GroupReportFactsSnapshot {
|
||||
metadata: GroupReportMetadata
|
||||
transcriptRows: GroupReportTranscriptRow[]
|
||||
topSpeakers: ReportSpeakerRank[]
|
||||
activeTimeline: string
|
||||
media: GroupDailyReport['media']
|
||||
voiceLeaderboard: ReportVoiceLeaderboardItem[]
|
||||
factsPrompt: string
|
||||
}
|
||||
|
||||
export const isInternalIdentifier = (value: string): boolean =>
|
||||
/@chatroom$/i.test(value) || /^wxid_/i.test(value) || /^[a-z0-9_-]{18,}$/i.test(value)
|
||||
|
||||
export const summarySender = (
|
||||
message: Message,
|
||||
contact: Contact | null,
|
||||
isGroup: boolean
|
||||
): string => {
|
||||
if (message.from === 'assistant') {
|
||||
const ownGroupNickname = message.name?.trim()
|
||||
if (isGroup && ownGroupNickname && !isInternalIdentifier(ownGroupNickname)) {
|
||||
return ownGroupNickname
|
||||
}
|
||||
return '我'
|
||||
}
|
||||
const candidate = isGroup ? message.name : contact?.m_nsNickName
|
||||
if (!candidate || isInternalIdentifier(candidate)) return isGroup ? '未命名群成员' : '对方'
|
||||
return candidate
|
||||
}
|
||||
|
||||
export const summaryContent = (message: Message): string => {
|
||||
const data = message.contentData
|
||||
if (!data) return message.content?.trim() || `[${message.type || '消息'}]`
|
||||
|
||||
switch (data.type) {
|
||||
case 'image':
|
||||
return '[图片]'
|
||||
case 'sticker':
|
||||
return '[表情]'
|
||||
case 'voice':
|
||||
return `[语音${data.duration ? ` ${data.duration}秒` : ''}]`
|
||||
case 'share':
|
||||
return `[分享] ${data.title}${data.des ? `:${data.des}` : ''}`
|
||||
case 'quote': {
|
||||
const reply = data.title || data.content || message.content || '[回复]'
|
||||
const quotedSender =
|
||||
data.quotedSender && !isInternalIdentifier(data.quotedSender) ? data.quotedSender : '群成员'
|
||||
return `${reply}(引用 ${quotedSender}:${data.quotedContent || `[引用${data.quotedType || '消息'}]`})`
|
||||
}
|
||||
case 'location':
|
||||
return `[位置] ${data.poiname || data.label || '位置消息'}`
|
||||
case 'card':
|
||||
return `[名片] ${data.nickname || '微信名片'}`
|
||||
case 'voip':
|
||||
return `[通话] ${data.status}${data.duration ? `,${data.duration}秒` : ''}`
|
||||
case 'system':
|
||||
case 'text':
|
||||
return data.content
|
||||
case 'unknown':
|
||||
return `[${message.type || '未知消息'}]`
|
||||
}
|
||||
|
||||
return `[${message.type || '消息'}]`
|
||||
}
|
||||
|
||||
export const parseTimestamp = (message: Message): number => {
|
||||
const value = new Date(message.datetime).getTime()
|
||||
return Number.isFinite(value) ? value : 0
|
||||
}
|
||||
|
||||
export const localDate = (timestamp: number): string => {
|
||||
const date = new Date(timestamp)
|
||||
const year = date.getFullYear()
|
||||
const month = String(date.getMonth() + 1).padStart(2, '0')
|
||||
const day = String(date.getDate()).padStart(2, '0')
|
||||
return `${year}-${month}-${day}`
|
||||
}
|
||||
|
||||
export const localTime = (timestamp: number): string =>
|
||||
new Date(timestamp).toLocaleTimeString('zh-CN', {
|
||||
hour12: false,
|
||||
hour: '2-digit',
|
||||
minute: '2-digit'
|
||||
})
|
||||
|
||||
export const resolveVoiceDuration = (message: Message): number => {
|
||||
const fromData = message.contentData?.type === 'voice' ? message.contentData.duration : undefined
|
||||
return Math.max(0, Number(fromData ?? message.voiceDuration ?? 0) || 0)
|
||||
}
|
||||
|
||||
const truncate = (value: string, max = 48): string =>
|
||||
value.length > max ? `${value.slice(0, max - 1)}…` : value
|
||||
|
||||
const buildImageContext = (
|
||||
messages: Message[],
|
||||
index: number,
|
||||
contact: Contact | null,
|
||||
isGroup: boolean
|
||||
): {
|
||||
note: string
|
||||
stats: string
|
||||
responseCount: number
|
||||
participantCount: number
|
||||
snippets: string[]
|
||||
} => {
|
||||
const baseTime = parseTimestamp(messages[index])
|
||||
const participants = new Set<string>()
|
||||
const snippets: string[] = []
|
||||
let responseCount = 0
|
||||
|
||||
for (let offset = index + 1; offset < messages.length && offset <= index + 8; offset++) {
|
||||
const candidate = messages[offset]
|
||||
const candidateTime = parseTimestamp(candidate)
|
||||
if (baseTime && candidateTime && candidateTime - baseTime > 20 * 60 * 1000) break
|
||||
if (candidate.type === '系统消息' || candidate.from === 'system') continue
|
||||
|
||||
const sender = summarySender(candidate, contact, isGroup)
|
||||
const sameSender = sender === summarySender(messages[index], contact, isGroup)
|
||||
const content = summaryContent(candidate)
|
||||
if (!sameSender) {
|
||||
responseCount += 1
|
||||
participants.add(sender)
|
||||
}
|
||||
if (
|
||||
snippets.length < 3 &&
|
||||
!content.startsWith('[图片]') &&
|
||||
!content.startsWith('[表情]') &&
|
||||
!content.startsWith('[语音')
|
||||
) {
|
||||
snippets.push(truncate(content, 28))
|
||||
}
|
||||
}
|
||||
|
||||
const note = snippets.length
|
||||
? `图片发出后,群里接着聊到:${snippets.join(' / ')}`
|
||||
: responseCount > 0
|
||||
? '图片发出后引发了一波接续讨论。'
|
||||
: '这张图片更多像是一次轻量分享,没有形成长链路讨论。'
|
||||
|
||||
const statsParts: string[] = []
|
||||
if (responseCount > 0) statsParts.push(`${responseCount} 条后续消息`)
|
||||
if (participants.size > 0) statsParts.push(`${participants.size} 人接话`)
|
||||
if (!statsParts.length) statsParts.push('讨论热度较低')
|
||||
|
||||
return {
|
||||
note,
|
||||
stats: statsParts.join(' · '),
|
||||
responseCount,
|
||||
participantCount: participants.size,
|
||||
snippets
|
||||
}
|
||||
}
|
||||
|
||||
const buildMediaSection = async (
|
||||
messages: Message[],
|
||||
contact: Contact | null,
|
||||
isGroup: boolean,
|
||||
topSpeakersMap: Map<string, number>
|
||||
): Promise<{
|
||||
media: GroupDailyReport['media']
|
||||
voiceLeaderboard: ReportVoiceLeaderboardItem[]
|
||||
warnings: string[]
|
||||
}> => {
|
||||
const warnings: string[] = []
|
||||
const rendererApi = typeof window === 'undefined' ? null : window.api
|
||||
const rawImageCandidates = messages
|
||||
.map((message, index) => {
|
||||
if (message.contentData?.type !== 'image') return null
|
||||
const sender = summarySender(message, contact, isGroup)
|
||||
const context = buildImageContext(messages, index, contact, isGroup)
|
||||
return {
|
||||
sourceMessageIds: [message.id],
|
||||
md5: message.contentData.md5,
|
||||
datName: message.contentData.datName,
|
||||
sessionId: message.sessionId,
|
||||
sender,
|
||||
time: localTime(parseTimestamp(message)),
|
||||
note: context.note,
|
||||
stats: context.stats,
|
||||
replyCount: context.responseCount,
|
||||
participantCount: context.participantCount,
|
||||
score: context.responseCount * 3 + context.participantCount * 2 + 1
|
||||
}
|
||||
})
|
||||
.filter((item): item is NonNullable<typeof item> => Boolean(item))
|
||||
.sort((left, right) => right.score - left.score)
|
||||
.slice(0, 6)
|
||||
|
||||
// ============================================================
|
||||
// AI 图片理解(ImageInsightService 接入)
|
||||
// 通过 main 进程拿 Top 3 热点图 + 已缓存的 Insight;未缓存的并发调 AI
|
||||
// 失败不阻塞:任何错误只记日志,降级到原 gallery
|
||||
// ============================================================
|
||||
let visionGallery: ReportVisionGalleryItem[] = []
|
||||
try {
|
||||
if (!rendererApi) throw new Error('后台模式不读取 Renderer 图片')
|
||||
const sessionId = messages.find((m) => m.sessionId)?.sessionId || (contact?.md5 ?? '')
|
||||
const startTime = messages.length ? parseTimestamp(messages[0]) : 0
|
||||
const endTime = messages.length ? parseTimestamp(messages[messages.length - 1]) : 0
|
||||
|
||||
// 从 renderer 已加载的消息中提取图片候选(复用 buildImageContext 已算的 replyCount)
|
||||
const imageInputs = rawImageCandidates.map((c) => {
|
||||
const srcMsg = messages.find((m) => m.id === c.sourceMessageIds[0]) || messages[0]
|
||||
return {
|
||||
messageId: c.sourceMessageIds[0] || '',
|
||||
md5: c.md5,
|
||||
datName: c.datName,
|
||||
sessionId: c.sessionId || sessionId,
|
||||
sender: c.sender,
|
||||
sentAt: parseTimestamp(srcMsg),
|
||||
responseCount: c.replyCount || 0,
|
||||
interactionCount: c.participantCount || 0
|
||||
}
|
||||
})
|
||||
|
||||
const candidatesResp = await rendererApi.imageListCandidates({
|
||||
sessionId,
|
||||
startTime,
|
||||
endTime,
|
||||
limit: 3,
|
||||
inputs: imageInputs
|
||||
})
|
||||
const candidates = candidatesResp.success ? candidatesResp.candidates : []
|
||||
console.log('[buildMediaSection] imageListCandidates returned', candidates.length, 'candidates')
|
||||
|
||||
// 对每个候选:缓存命中直接用,未命中并发调 imageAnalyze
|
||||
const analyzed = await Promise.all(
|
||||
candidates.map(async (candidate) => {
|
||||
if (candidate.insight) return candidate.insight
|
||||
// 未命中:解密图片拿 base64 → 调 AI
|
||||
try {
|
||||
const img = await rendererApi.getImage(
|
||||
candidate.md5,
|
||||
candidate.datName,
|
||||
candidate.sessionId
|
||||
)
|
||||
if (!img.success || !img.data) {
|
||||
warnings.push(
|
||||
`${candidate.sender} ${localTime(candidate.sentAt)} 的图片读取失败:${img.error || '未知错误'}`
|
||||
)
|
||||
return null
|
||||
}
|
||||
const analyzeResp = await rendererApi.imageAnalyze({
|
||||
imageHash: candidate.imageHash,
|
||||
imageDataUrl: img.data,
|
||||
messageId: candidate.messageId,
|
||||
sender: candidate.sender,
|
||||
sentAt: candidate.sentAt,
|
||||
sessionId: candidate.sessionId,
|
||||
force: false
|
||||
})
|
||||
if (!analyzeResp.success || !analyzeResp.insight) {
|
||||
warnings.push(
|
||||
`${candidate.sender} ${localTime(candidate.sentAt)} 的图片识别失败:${analyzeResp.error || '模型未返回识别结果'}`
|
||||
)
|
||||
return null
|
||||
}
|
||||
return analyzeResp.insight
|
||||
} catch (error) {
|
||||
console.warn('[buildMediaSection] image analyze failed:', error)
|
||||
warnings.push(
|
||||
`${candidate.sender} ${localTime(candidate.sentAt)} 的图片识别异常:${error instanceof Error ? error.message : String(error)}`
|
||||
)
|
||||
return null
|
||||
}
|
||||
})
|
||||
)
|
||||
visionGallery = analyzed
|
||||
.filter((it): it is NonNullable<typeof it> => Boolean(it))
|
||||
.map((it) => ({
|
||||
messageId: it.messageId,
|
||||
imageHash: it.imageHash,
|
||||
sender: it.sender,
|
||||
time: localTime(it.sentAt),
|
||||
description: it.description,
|
||||
ocrText: it.ocrText,
|
||||
tags: it.tags,
|
||||
category: it.category,
|
||||
importance: it.importance,
|
||||
sourceMessageIds: [it.messageId]
|
||||
}))
|
||||
// 为 visionGallery 加载原图 dataUrl(给 main 渲染用,不暴露给 LLM)
|
||||
if (visionGallery.length) {
|
||||
visionGallery = await Promise.all(
|
||||
visionGallery.map(async (item) => {
|
||||
const orig = rawImageCandidates.find((c) => c.sourceMessageIds[0] === item.messageId)
|
||||
if (!orig) return item
|
||||
try {
|
||||
const img = await rendererApi.getImage(orig.md5, orig.datName, orig.sessionId)
|
||||
if (img.success && img.data?.startsWith('data:image/')) {
|
||||
return { ...item, imageUrl: img.data }
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('[buildMediaSection] preload image failed for', item.messageId, error)
|
||||
}
|
||||
return item
|
||||
})
|
||||
)
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('[buildMediaSection] vision flow failed, fallback to empty:', error)
|
||||
warnings.push(`图片识别流程失败:${error instanceof Error ? error.message : String(error)}`)
|
||||
visionGallery = []
|
||||
}
|
||||
|
||||
const imageCandidates = rendererApi
|
||||
? await Promise.all(
|
||||
rawImageCandidates.map(async (item) => {
|
||||
const result = await rendererApi.getImage(item.md5, item.datName, item.sessionId)
|
||||
if (!result.success || !result.data?.startsWith('data:image/')) return null
|
||||
return {
|
||||
sender: item.sender,
|
||||
time: item.time,
|
||||
imageUrl: result.data,
|
||||
note: item.note,
|
||||
stats: item.stats,
|
||||
inferenceLabel: '基于图片后的聊天上下文推断',
|
||||
sourceMessageIds: item.sourceMessageIds,
|
||||
replyCount: item.replyCount,
|
||||
score: item.score
|
||||
}
|
||||
})
|
||||
)
|
||||
: []
|
||||
|
||||
const gallery: ReportMediaGalleryItem[] = imageCandidates
|
||||
.filter((item): item is NonNullable<typeof item> => Boolean(item))
|
||||
.sort((left, right) => right.score - left.score)
|
||||
.slice(0, 4)
|
||||
.map((item) => ({
|
||||
sender: item.sender,
|
||||
time: item.time,
|
||||
imageUrl: item.imageUrl,
|
||||
note: item.note,
|
||||
stats: item.stats,
|
||||
inferenceLabel: item.inferenceLabel,
|
||||
sourceMessageIds: item.sourceMessageIds,
|
||||
replyCount: item.replyCount
|
||||
}))
|
||||
|
||||
const voiceMessages = messages
|
||||
.filter((message) => message.contentData?.type === 'voice')
|
||||
.map((message) => ({
|
||||
sender: summarySender(message, contact, isGroup),
|
||||
duration: resolveVoiceDuration(message),
|
||||
time: localTime(parseTimestamp(message))
|
||||
}))
|
||||
|
||||
const voiceTotals = new Map<string, { count: number; duration: number }>()
|
||||
for (const item of voiceMessages) {
|
||||
const current = voiceTotals.get(item.sender) || { count: 0, duration: 0 }
|
||||
current.count += 1
|
||||
current.duration += item.duration
|
||||
voiceTotals.set(item.sender, current)
|
||||
}
|
||||
|
||||
const voiceLeaderboard: ReportVoiceLeaderboardItem[] = Array.from(voiceTotals.entries())
|
||||
.map(([sender, value]) => ({
|
||||
sender,
|
||||
count: value.count,
|
||||
durationSec: value.duration
|
||||
}))
|
||||
.sort((left, right) => right.durationSec - left.durationSec || right.count - left.count)
|
||||
.slice(0, 5)
|
||||
|
||||
let bestStreak: { sender: string; count: number; duration: number; time: string } | null = null
|
||||
let currentStreak: { sender: string; count: number; duration: number; time: string } | null = null
|
||||
for (const message of messages) {
|
||||
if (message.contentData?.type !== 'voice') {
|
||||
currentStreak = null
|
||||
continue
|
||||
}
|
||||
const sender = summarySender(message, contact, isGroup)
|
||||
const duration = resolveVoiceDuration(message)
|
||||
const time = localTime(parseTimestamp(message))
|
||||
if (currentStreak && currentStreak.sender === sender) {
|
||||
currentStreak.count += 1
|
||||
currentStreak.duration += duration
|
||||
} else {
|
||||
currentStreak = { sender, count: 1, duration, time }
|
||||
}
|
||||
if (!bestStreak || currentStreak.count > bestStreak.count) {
|
||||
bestStreak = { ...currentStreak }
|
||||
}
|
||||
}
|
||||
|
||||
const voiceHighlights: ReportVoiceHighlight[] = []
|
||||
if (voiceLeaderboard[0]) {
|
||||
voiceHighlights.push({
|
||||
title: '语音输出王',
|
||||
sender: voiceLeaderboard[0].sender,
|
||||
note: `共发送 ${voiceLeaderboard[0].count} 条语音,累计 ${voiceLeaderboard[0].durationSec} 秒。`
|
||||
})
|
||||
}
|
||||
if (bestStreak && bestStreak.count >= 2) {
|
||||
voiceHighlights.push({
|
||||
title: '连续发言时刻',
|
||||
sender: bestStreak.sender,
|
||||
note: `${bestStreak.time} 连发 ${bestStreak.count} 条语音,共 ${bestStreak.duration} 秒。`
|
||||
})
|
||||
}
|
||||
|
||||
const funBadges: ReportFunBadge[] = []
|
||||
const topSpeaker = Array.from(topSpeakersMap.entries()).sort(
|
||||
(left, right) => right[1] - left[1]
|
||||
)[0]
|
||||
if (topSpeaker) {
|
||||
funBadges.push({
|
||||
title: '高能输出王',
|
||||
owner: topSpeaker[0],
|
||||
note: `今天一共发了 ${topSpeaker[1]} 条消息。`
|
||||
})
|
||||
}
|
||||
if (gallery[0]) {
|
||||
funBadges.push({
|
||||
title: '图片话题王',
|
||||
owner: gallery[0].sender,
|
||||
note: `${gallery[0].time} 的图片带动了最明显的一轮讨论。`
|
||||
})
|
||||
}
|
||||
if (voiceLeaderboard[0]) {
|
||||
funBadges.push({
|
||||
title: '语音麦霸',
|
||||
owner: voiceLeaderboard[0].sender,
|
||||
note: `语音总时长暂居第一,适合放进“今日声音档案”。`
|
||||
})
|
||||
}
|
||||
|
||||
return {
|
||||
media: {
|
||||
gallery,
|
||||
visionGallery,
|
||||
voiceHighlights: voiceHighlights.slice(0, 2),
|
||||
funBadges: funBadges.slice(0, 3)
|
||||
},
|
||||
voiceLeaderboard,
|
||||
warnings
|
||||
}
|
||||
}
|
||||
|
||||
const collectQuestionCandidates = (
|
||||
messages: Message[],
|
||||
contact: Contact | null,
|
||||
isGroup: boolean
|
||||
): string[] =>
|
||||
messages
|
||||
.map((message) => ({
|
||||
id: message.id,
|
||||
sender: summarySender(message, contact, isGroup),
|
||||
content: summaryContent(message)
|
||||
}))
|
||||
.filter(
|
||||
(item) =>
|
||||
/[??]$/.test(item.content) || item.content.includes('吗') || item.content.includes('怎么')
|
||||
)
|
||||
.slice(-6)
|
||||
.map((item) => `${item.sender}(${item.id}):${truncate(item.content, 32)}`)
|
||||
|
||||
const collectReplyFacts = (
|
||||
messages: Message[],
|
||||
contact: Contact | null,
|
||||
isGroup: boolean
|
||||
): string[] =>
|
||||
messages
|
||||
.filter((message) => message.contentData?.type === 'quote' && message.contentData.quotedSender)
|
||||
.slice(0, 10)
|
||||
.map((message) => {
|
||||
const sender = summarySender(message, contact, isGroup)
|
||||
const quotedSender =
|
||||
message.contentData?.type === 'quote' && message.contentData.quotedSender
|
||||
? message.contentData.quotedSender
|
||||
: '群成员'
|
||||
return `${sender} 回复了 ${quotedSender}`
|
||||
})
|
||||
|
||||
export const buildGroupReportFacts = async (
|
||||
messages: Message[],
|
||||
contact: Contact | null,
|
||||
isGroup: boolean,
|
||||
reportMode: ReportMode
|
||||
): Promise<GroupReportFactsSnapshot> => {
|
||||
const transcriptRows = messages.map((message) => ({
|
||||
id: message.id,
|
||||
datetime: message.datetime,
|
||||
timestamp: parseTimestamp(message),
|
||||
sender: summarySender(message, contact, isGroup),
|
||||
content: summaryContent(message),
|
||||
avatar: message.img
|
||||
}))
|
||||
|
||||
let firstTimestamp = Number.POSITIVE_INFINITY
|
||||
let lastTimestamp = Number.NEGATIVE_INFINITY
|
||||
for (const row of transcriptRows) {
|
||||
if (!Number.isFinite(row.timestamp)) continue
|
||||
firstTimestamp = Math.min(firstTimestamp, row.timestamp)
|
||||
lastTimestamp = Math.max(lastTimestamp, row.timestamp)
|
||||
}
|
||||
if (!Number.isFinite(firstTimestamp)) firstTimestamp = Date.now()
|
||||
if (!Number.isFinite(lastTimestamp)) lastTimestamp = firstTimestamp
|
||||
|
||||
const speakerCounts = new Map<string, number>()
|
||||
const hourCounts = new Map<number, number>()
|
||||
const avatars: Record<string, string | undefined> = {}
|
||||
let imageCount = 0
|
||||
let stickerCount = 0
|
||||
let voiceCount = 0
|
||||
let voiceDurationSec = 0
|
||||
|
||||
for (const message of messages) {
|
||||
const sender = summarySender(message, contact, isGroup)
|
||||
const timestamp = parseTimestamp(message)
|
||||
speakerCounts.set(sender, (speakerCounts.get(sender) || 0) + 1)
|
||||
if (Number.isFinite(timestamp)) {
|
||||
const hour = new Date(timestamp).getHours()
|
||||
hourCounts.set(hour, (hourCounts.get(hour) || 0) + 1)
|
||||
}
|
||||
if (message.img && !avatars[sender]) avatars[sender] = message.img
|
||||
if (message.contentData?.type === 'image') imageCount += 1
|
||||
if (message.contentData?.type === 'sticker') stickerCount += 1
|
||||
if (message.contentData?.type === 'voice') {
|
||||
voiceCount += 1
|
||||
voiceDurationSec += resolveVoiceDuration(message)
|
||||
}
|
||||
}
|
||||
|
||||
const topSpeakers = Array.from(speakerCounts, ([name, count]) => ({ name, count }))
|
||||
.sort((left, right) => right.count - left.count)
|
||||
.slice(0, 5)
|
||||
|
||||
const activeTimeline = Array.from(hourCounts, ([hour, count]) => ({ hour, count }))
|
||||
.sort((left, right) => right.count - left.count)
|
||||
.slice(0, 4)
|
||||
.sort((left, right) => left.hour - right.hour)
|
||||
.map(
|
||||
({ hour, count }) =>
|
||||
`${String(hour).padStart(2, '0')}:00-${String(hour).padStart(2, '0')}:59(${count}条)`
|
||||
)
|
||||
.join('、')
|
||||
|
||||
const startDate = localDate(firstTimestamp)
|
||||
const endDate = localDate(lastTimestamp)
|
||||
const sameDay = startDate === endDate
|
||||
const dateRange = sameDay
|
||||
? `${startDate} ${localTime(firstTimestamp)}-${localTime(lastTimestamp)}`
|
||||
: `${startDate} ${localTime(firstTimestamp)} 至 ${endDate} ${localTime(lastTimestamp)}`
|
||||
const durationMs = Math.max(0, lastTimestamp - firstTimestamp)
|
||||
const durationHours = durationMs / 3600000
|
||||
const timeSpan = (() => {
|
||||
if (sameDay) {
|
||||
if (durationHours < 1) {
|
||||
const minutes = Math.max(1, Math.round(durationMs / 60000))
|
||||
return `${minutes} min`
|
||||
}
|
||||
const hours = Math.max(1, Math.ceil(durationHours))
|
||||
return `${hours} h`
|
||||
}
|
||||
const days = Math.max(1, Math.ceil(durationMs / 86400000))
|
||||
return `${days} d`
|
||||
})()
|
||||
|
||||
const contactName = contact?.m_nsNickName || ''
|
||||
const groupName = contactName && !isInternalIdentifier(contactName) ? contactName : '未命名会话'
|
||||
const metadata: GroupReportMetadata = {
|
||||
groupName,
|
||||
reportDate: sameDay ? startDate : `${startDate}_to_${endDate}`,
|
||||
dateRange,
|
||||
messageCount: transcriptRows.length,
|
||||
activeUsers: speakerCounts.size,
|
||||
imageCount,
|
||||
voiceCount,
|
||||
stickerCount,
|
||||
mediaMessageCount: imageCount + voiceCount + stickerCount,
|
||||
timeSpan,
|
||||
generatedAt: new Date().toLocaleString('zh-CN', { hour12: false }),
|
||||
recordNote: `基于 WechatExplorer 已加载的 ${transcriptRows.length} 条记录`,
|
||||
footerNote: '基于已读取聊天记录生成;图片、表情等未解析内容默认只按类型与上下文参与日报。',
|
||||
heroParticipants: topSpeakers.slice(0, 4).map((speaker) => speaker.name),
|
||||
avatars,
|
||||
reportMode
|
||||
}
|
||||
|
||||
const { media, voiceLeaderboard, warnings } = await buildMediaSection(
|
||||
messages,
|
||||
contact,
|
||||
isGroup,
|
||||
speakerCounts
|
||||
)
|
||||
if (warnings.length) metadata.warnings = [...(metadata.warnings || []), ...warnings]
|
||||
if (imageCount > 0 && !media.visionGallery?.length) {
|
||||
metadata.footerNote = `图片识别未成功:${warnings[0] || '当前模型未返回图片理解结果'}。其余内容基于已读取聊天记录生成。`
|
||||
} else if (media.visionGallery?.length) {
|
||||
metadata.footerNote = `基于已读取聊天记录生成;其中 ${media.visionGallery.length} 张图片已由当前视觉模型识别。`
|
||||
}
|
||||
|
||||
if (
|
||||
transcriptRows.length > 0 &&
|
||||
transcriptRows.every((row) => row.content === '[图片]') &&
|
||||
!media.visionGallery?.length
|
||||
) {
|
||||
throw new Error(
|
||||
warnings[0] || '所选记录只有图片,但当前图片均未能识别,请检查图片解密密钥和模型视觉能力'
|
||||
)
|
||||
}
|
||||
|
||||
const factsPrompt = [
|
||||
`报告模式:${reportMode === 'compact' ? '精简版(30秒可读完)' : '完整版(保留更多上下文)'}`,
|
||||
`消息统计:共 ${transcriptRows.length} 条,活跃成员 ${speakerCounts.size} 人,图片 ${imageCount} 张,表情 ${stickerCount} 条,语音 ${voiceCount} 条(累计 ${voiceDurationSec} 秒)。`,
|
||||
activeTimeline ? `活跃时段:${activeTimeline}` : '',
|
||||
media.gallery.length
|
||||
? `图片观察:${media.gallery.map((item) => `${item.time} ${item.sender} 发图(${item.stats})`).join(';')}`
|
||||
: '',
|
||||
// AI 图片理解结果(由 ImageInsightService 提供,缓存命中或已调用 Vision)
|
||||
(media.visionGallery?.length ?? 0) > 0
|
||||
? `AI 图片识别摘要:${(media.visionGallery || [])
|
||||
.map(
|
||||
(it) =>
|
||||
`[${it.time} ${it.sender}] ${it.description}${it.ocrText ? `(OCR: ${it.ocrText})` : ''}${it.tags.length ? ` [${it.tags.join('/')}]` : ''}`
|
||||
)
|
||||
.join(';')}`
|
||||
: '',
|
||||
voiceLeaderboard.length
|
||||
? `语音榜:${voiceLeaderboard
|
||||
.slice(0, 3)
|
||||
.map((item) => `${item.sender} ${item.count} 条 / ${item.durationSec} 秒`)
|
||||
.join(';')}`
|
||||
: '',
|
||||
collectQuestionCandidates(messages, contact, isGroup).length
|
||||
? `疑似待跟进问题:${collectQuestionCandidates(messages, contact, isGroup).join(';')}`
|
||||
: '',
|
||||
collectReplyFacts(messages, contact, isGroup).length
|
||||
? `回复关系样本:${collectReplyFacts(messages, contact, isGroup).join(';')}`
|
||||
: ''
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join('\n')
|
||||
|
||||
return {
|
||||
metadata,
|
||||
transcriptRows,
|
||||
topSpeakers,
|
||||
activeTimeline,
|
||||
media,
|
||||
voiceLeaderboard,
|
||||
factsPrompt
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,38 @@
|
||||
export type AgentHubRuntimeStatus = 'starting' | 'online' | 'offline' | 'error'
|
||||
export type WechatConnectorStatus =
|
||||
| 'checking'
|
||||
| 'disconnected'
|
||||
| 'starting'
|
||||
| 'waiting_scan'
|
||||
| 'scanned'
|
||||
| 'online'
|
||||
| 'error'
|
||||
|
||||
export interface AgentHubStatus {
|
||||
hub: AgentHubRuntimeStatus
|
||||
connector: WechatConnectorStatus
|
||||
qrCodeDataUrl?: string
|
||||
accountId?: string
|
||||
wechatUserId?: string
|
||||
error?: string
|
||||
updatedAt: number
|
||||
dataApi?: 'checking' | 'online' | 'offline'
|
||||
databaseReady?: boolean
|
||||
}
|
||||
|
||||
export interface AgentHubActionResult {
|
||||
success: boolean
|
||||
status: AgentHubStatus
|
||||
error?: string
|
||||
}
|
||||
|
||||
export type AgentHubLogSource = 'agent-hub' | 'wechat-connector' | 'system'
|
||||
export type AgentHubLogLevel = 'info' | 'warn' | 'error'
|
||||
|
||||
export interface AgentHubLogEntry {
|
||||
id: number
|
||||
timestamp: number
|
||||
source: AgentHubLogSource
|
||||
level: AgentHubLogLevel
|
||||
message: string
|
||||
}
|
||||
@@ -15,6 +15,11 @@ export interface AIProviderAuth {
|
||||
export interface AIModelCapabilities {
|
||||
chat: boolean
|
||||
vision: boolean
|
||||
/**
|
||||
* OCR 是 vision 能力的派生(几乎所有 vision 模型都能 OCR)。
|
||||
* 不作为用户独立配置项,UI 上显示为"图片文字识别"标签。
|
||||
*/
|
||||
ocr: boolean
|
||||
longContext: boolean
|
||||
}
|
||||
|
||||
@@ -66,6 +71,7 @@ export interface AIRuntimeModelConfig {
|
||||
modelName: string
|
||||
configured: boolean
|
||||
status: AIProviderSummary['status']
|
||||
timeoutMs?: number
|
||||
}
|
||||
|
||||
export interface LegacyAIConfig {
|
||||
@@ -77,6 +83,7 @@ export interface LegacyAIConfig {
|
||||
export interface AIChatRequestOptions {
|
||||
providerId?: string
|
||||
modelId?: string
|
||||
timeoutMs?: number
|
||||
// Legacy compatibility only. New callers must use providerId/modelId.
|
||||
apiKey?: string
|
||||
baseURL?: string
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
export type AppLogLevel = 'info' | 'warn' | 'error'
|
||||
|
||||
export interface AppLogEntry {
|
||||
level: AppLogLevel
|
||||
scope: string
|
||||
message: string
|
||||
details?: Record<string, unknown>
|
||||
}
|
||||
+197
-4
@@ -1,4 +1,36 @@
|
||||
export type ReportHeat = '高' | '中' | '低'
|
||||
export type ReportMode = 'compact' | 'full'
|
||||
export type ReportSectionKey =
|
||||
| 'hero'
|
||||
| 'topics'
|
||||
| 'importantMessages'
|
||||
| 'actions'
|
||||
| 'moments'
|
||||
| 'analytics'
|
||||
| 'keywords'
|
||||
| 'resources'
|
||||
| 'qa'
|
||||
| 'storylines'
|
||||
| 'reversals'
|
||||
| 'gallery'
|
||||
| 'vision'
|
||||
| 'voices'
|
||||
| 'badges'
|
||||
| 'chains'
|
||||
|
||||
export interface ReportSectionMeta {
|
||||
enabled: boolean
|
||||
importance: number
|
||||
confidence: number
|
||||
totalCount: number
|
||||
displayedCount: number
|
||||
hiddenCount?: number
|
||||
}
|
||||
|
||||
export interface ReportTopicConclusion {
|
||||
text: string
|
||||
sourceMessageIds?: string[]
|
||||
}
|
||||
|
||||
export interface ReportTopic {
|
||||
title: string
|
||||
@@ -7,13 +39,25 @@ export interface ReportTopic {
|
||||
participants: string[]
|
||||
summary: string
|
||||
conclusion?: string
|
||||
conclusions?: ReportTopicConclusion[]
|
||||
keywords: string[]
|
||||
sourceMessageIds?: string[]
|
||||
image?: {
|
||||
imageUrl?: string
|
||||
note: string
|
||||
sourceMessageIds?: string[]
|
||||
/** AI 图片识别缓存 key(由 visionGallery 提供,main 渲染时按此取 base64) */
|
||||
imageHash?: string
|
||||
/** AI 真实识别的描述(来自 ImageInsight.description) */
|
||||
aiDescription?: string
|
||||
} | null
|
||||
}
|
||||
|
||||
export interface ReportResource {
|
||||
title: string
|
||||
description: string
|
||||
sender?: string
|
||||
sourceMessageIds?: string[]
|
||||
}
|
||||
|
||||
export interface ReportImportantMessage {
|
||||
@@ -21,22 +65,30 @@ export interface ReportImportantMessage {
|
||||
time: string
|
||||
content: string
|
||||
note: string
|
||||
sourceMessageIds?: string[]
|
||||
importance?: number
|
||||
confidence?: number
|
||||
}
|
||||
|
||||
export interface ReportQuoteMessage {
|
||||
sender: string
|
||||
content: string
|
||||
sourceMessageId?: string
|
||||
}
|
||||
|
||||
export interface ReportQuote {
|
||||
messages: ReportQuoteMessage[]
|
||||
note: string
|
||||
sourceMessageIds?: string[]
|
||||
importance?: number
|
||||
confidence?: number
|
||||
}
|
||||
|
||||
export interface ReportQuestionAnswer {
|
||||
question: string
|
||||
answer: string
|
||||
answerer?: string
|
||||
sourceMessageIds?: string[]
|
||||
}
|
||||
|
||||
export interface ReportTopicHeat {
|
||||
@@ -49,19 +101,157 @@ export interface ReportSpeakerRank {
|
||||
count: number
|
||||
}
|
||||
|
||||
export interface ReportHero {
|
||||
headline: string
|
||||
summary: string
|
||||
keyTakeaway?: string
|
||||
pendingNote?: string
|
||||
statusLine?: string
|
||||
}
|
||||
|
||||
export interface ReportMediaGalleryItem {
|
||||
sender: string
|
||||
time: string
|
||||
imageUrl: string
|
||||
note: string
|
||||
stats?: string
|
||||
inferenceLabel?: string
|
||||
sourceMessageIds?: string[]
|
||||
replyCount?: number
|
||||
}
|
||||
|
||||
/**
|
||||
* 图片 AI 理解结果(由 ImageInsightService 提供)。
|
||||
* 与 ReportMediaGalleryItem 不同:本类型不含 imageUrl(由 main 渲染时按需注入),
|
||||
* description 是 AI 真实识别的结果(非基于上下文的推断)。
|
||||
*/
|
||||
export interface ReportVisionGalleryItem {
|
||||
messageId: string
|
||||
imageHash: string
|
||||
sender: string
|
||||
time: string
|
||||
description: string
|
||||
ocrText?: string
|
||||
tags: string[]
|
||||
category: 'screenshot' | 'photo' | 'meme' | 'document' | 'chart' | 'other'
|
||||
importance: 'low' | 'medium' | 'high'
|
||||
sourceMessageIds?: string[]
|
||||
/** 预加载好的 dataURL,render 时直接嵌进 HTML */
|
||||
imageUrl?: string
|
||||
}
|
||||
|
||||
export interface ReportVoiceHighlight {
|
||||
title: string
|
||||
sender: string
|
||||
note: string
|
||||
sourceMessageIds?: string[]
|
||||
}
|
||||
|
||||
export interface ReportVoiceLeaderboardItem {
|
||||
sender: string
|
||||
count: number
|
||||
durationSec: number
|
||||
}
|
||||
|
||||
export interface ReportFunBadge {
|
||||
title: string
|
||||
owner: string
|
||||
note: string
|
||||
}
|
||||
|
||||
export interface ReportTodoItem {
|
||||
task: string
|
||||
owner?: string | null
|
||||
deadline?: string | null
|
||||
topic?: string | null
|
||||
note?: string
|
||||
sourceMessageIds?: string[]
|
||||
importance?: number
|
||||
confidence?: number
|
||||
}
|
||||
|
||||
export interface ReportUnresolvedItem {
|
||||
question: string
|
||||
owner?: string
|
||||
status: '待跟进' | '暂未回答' | '进行中'
|
||||
note: string
|
||||
lastDiscussedAt?: string | null
|
||||
sourceMessageIds?: string[]
|
||||
importance?: number
|
||||
confidence?: number
|
||||
}
|
||||
|
||||
export interface ReportStorylineStage {
|
||||
time: string
|
||||
event: string
|
||||
sourceMessageIds?: string[]
|
||||
}
|
||||
|
||||
export interface ReportStoryline {
|
||||
title: string
|
||||
stages: ReportStorylineStage[]
|
||||
result?: string
|
||||
sourceMessageIds?: string[]
|
||||
}
|
||||
|
||||
export interface ReportReversal {
|
||||
topic: string
|
||||
initialView: string
|
||||
finalView: string
|
||||
note?: string
|
||||
sourceMessageIds?: string[]
|
||||
}
|
||||
|
||||
export interface ReportParticipantChain {
|
||||
topic: string
|
||||
chain: string[]
|
||||
note?: string
|
||||
sourceMessageIds?: string[]
|
||||
}
|
||||
|
||||
export interface ReportSummaryStats {
|
||||
messageCount: number
|
||||
activeUsers: number
|
||||
topicCount: number
|
||||
mediaCount: number
|
||||
imageCount: number
|
||||
voiceCount: number
|
||||
stickerCount: number
|
||||
conclusionCount: number
|
||||
todoCount: number
|
||||
unresolvedCount: number
|
||||
}
|
||||
|
||||
export interface GroupDailyReport {
|
||||
overview: string
|
||||
mode?: ReportMode
|
||||
hero?: ReportHero
|
||||
topics: ReportTopic[]
|
||||
resources: ReportResource[]
|
||||
importantMessages: ReportImportantMessage[]
|
||||
quotes: ReportQuote[]
|
||||
qa: ReportQuestionAnswer[]
|
||||
todos: ReportTodoItem[]
|
||||
unresolved: ReportUnresolvedItem[]
|
||||
storylines: ReportStoryline[]
|
||||
reversals: ReportReversal[]
|
||||
participantChains: ReportParticipantChain[]
|
||||
analytics: {
|
||||
topicHeat: ReportTopicHeat[]
|
||||
activeTimeline: string
|
||||
topSpeakers: ReportSpeakerRank[]
|
||||
voiceLeaderboard: ReportVoiceLeaderboardItem[]
|
||||
}
|
||||
keywords: string[]
|
||||
media: {
|
||||
gallery: ReportMediaGalleryItem[]
|
||||
/** AI 识别的图片(由 ImageInsightService 提供),渲染时由 main 按 imageHash 取原图 */
|
||||
visionGallery?: ReportVisionGalleryItem[]
|
||||
voiceHighlights: ReportVoiceHighlight[]
|
||||
funBadges: ReportFunBadge[]
|
||||
}
|
||||
summaryStats?: ReportSummaryStats
|
||||
sectionMeta?: Partial<Record<ReportSectionKey, ReportSectionMeta>>
|
||||
}
|
||||
|
||||
export interface GroupReportMetadata {
|
||||
@@ -70,24 +260,27 @@ export interface GroupReportMetadata {
|
||||
dateRange: string
|
||||
messageCount: number
|
||||
activeUsers: number
|
||||
imageCount?: number
|
||||
voiceCount?: number
|
||||
stickerCount?: number
|
||||
mediaMessageCount?: number
|
||||
timeSpan: string
|
||||
generatedAt: string
|
||||
recordNote: string
|
||||
footerNote: string
|
||||
heroParticipants: string[]
|
||||
avatars: Record<string, string | undefined>
|
||||
// === 新增(可选,向后兼容) ===
|
||||
/** 群昵称 / wxid / md5,服务端用来反推真头像(从 getGroupSnapshot) */
|
||||
reportMode?: ReportMode
|
||||
talker?: string
|
||||
/** 预留,与 /api/v1/chatlog 的 time 参数同格式 */
|
||||
timeRange?: string
|
||||
/** 服务端写回,告知 client enrich 失败/部分缺失 */
|
||||
warnings?: string[]
|
||||
}
|
||||
|
||||
export interface GroupReportExportRequest {
|
||||
report: GroupDailyReport
|
||||
metadata: GroupReportMetadata
|
||||
/** 模板 ID:'v1' 经典 / 'v2' 当前。缺省或未知值用默认(v2) */
|
||||
templateId?: 'v1' | 'v2'
|
||||
}
|
||||
|
||||
export interface GroupReportExportResult {
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
// src/shared/image-insight.ts
|
||||
// ImageInsight:微信图片的 AI 理解结果持久化数据结构
|
||||
// 与 WechatExplorer 整体 AI 知识平台定位一致 — 图片理解结果可索引、可缓存、可复用。
|
||||
|
||||
export type ImageCategory =
|
||||
| 'screenshot' // 截图
|
||||
| 'photo' // 实拍照片
|
||||
| 'meme' // 表情包
|
||||
| 'document' // 文档/合同/票据
|
||||
| 'chart' // 图表/数据
|
||||
| 'other'
|
||||
|
||||
export type ImageImportance = 'low' | 'medium' | 'high'
|
||||
|
||||
/**
|
||||
* 单张微信图片的 AI 理解结果(持久化到 image-insights.json)
|
||||
*
|
||||
* imageHash 缓存 key 策略:
|
||||
* 优先用微信原始 md5(已存在,不强制计算)
|
||||
* 无 md5 才用 sha256(rawBytes).slice(0, 32)
|
||||
*/
|
||||
export interface ImageInsight {
|
||||
id: string // UUID
|
||||
messageId: string // 微信消息 ID(用于追溯)
|
||||
imageHash: string // 缓存 key:微信 md5 优先,无 md5 才用 sha256
|
||||
md5?: string // 微信图片 md5
|
||||
datName?: string // .dat 文件名
|
||||
|
||||
/** AI 输出 */
|
||||
description: string // 1-2 句中文描述
|
||||
ocrText?: string // OCR 提取的文字(vision 模型一并返回)
|
||||
tags: string[] // 关键词标签
|
||||
category: ImageCategory
|
||||
importance: ImageImportance
|
||||
|
||||
/** 元数据 */
|
||||
provider: string // AI provider ID
|
||||
model: string // AI model ID
|
||||
createdAt: number // 首次分析时间戳
|
||||
updatedAt: number // 最近更新时间
|
||||
|
||||
/** 关联消息信息 */
|
||||
sender: string
|
||||
sentAt: number
|
||||
sessionId: string
|
||||
}
|
||||
|
||||
/**
|
||||
* 图片理解请求(main 进程内部使用)
|
||||
*/
|
||||
export interface ImageAnalysisRequest {
|
||||
/** 必传,缓存 key */
|
||||
imageHash: string
|
||||
/** base64 dataURL,仅 main 内部使用 */
|
||||
imageDataUrl: string
|
||||
messageId: string
|
||||
sender: string
|
||||
sentAt: number
|
||||
sessionId: string
|
||||
/** 强制重新分析(忽略缓存) */
|
||||
force?: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* 图片理解响应
|
||||
*/
|
||||
export interface ImageAnalysisResponse {
|
||||
success: boolean
|
||||
insight?: ImageInsight
|
||||
/** 是否来自缓存 */
|
||||
fromCache?: boolean
|
||||
error?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* 图片候选(日报使用)
|
||||
* 主进程根据消息列表计算热度,返回 Top N + 已缓存的 Insight
|
||||
*/
|
||||
export interface ImageCandidate {
|
||||
messageId: string
|
||||
imageHash: string
|
||||
md5?: string
|
||||
datName?: string
|
||||
sessionId: string
|
||||
sender: string
|
||||
sentAt: number
|
||||
/** 热度分数 */
|
||||
heatScore: number
|
||||
/** 命中缓存时附带 */
|
||||
insight?: ImageInsight
|
||||
}
|
||||
|
||||
export interface ImageCandidateQuery {
|
||||
sessionId: string
|
||||
startTime: number
|
||||
endTime: number
|
||||
/** 取 Top N,默认 3 */
|
||||
limit?: number
|
||||
/** 由 renderer 从已加载消息中提取的图片候选(包含热度信息) */
|
||||
inputs?: Array<{
|
||||
messageId: string
|
||||
md5?: string
|
||||
datName?: string
|
||||
sessionId: string
|
||||
sender: string
|
||||
sentAt: number
|
||||
responseCount: number
|
||||
interactionCount: number
|
||||
}>
|
||||
}
|
||||
@@ -11,7 +11,10 @@ export const LOCAL_API_ENDPOINTS = {
|
||||
},
|
||||
'group-snapshot': { method: 'GET', path: '/api/v1/group_snapshot', queryKeys: ['md5'] },
|
||||
resolve: { method: 'GET', path: '/api/v1/resolve', queryKeys: ['q'] },
|
||||
report: { method: 'POST', path: '/api/v1/report', queryKeys: [] }
|
||||
report: { method: 'POST', path: '/api/v1/report', queryKeys: [] },
|
||||
'agent-status': { method: 'GET', path: '/api/v1/agent/status', queryKeys: [] },
|
||||
'agent-group-report': { method: 'POST', path: '/api/v1/agent/group-report', queryKeys: [] },
|
||||
'agent-send': { method: 'POST', path: '/api/v1/agent/send', queryKeys: [] }
|
||||
} as const
|
||||
|
||||
export type LocalApiEndpointId = keyof typeof LOCAL_API_ENDPOINTS
|
||||
|
||||
Reference in New Issue
Block a user