mirror of
https://github.com/hicccc77/WeFlow.git
synced 2026-04-19 07:25:52 +00:00
Merge remote-tracking branch 'upstream/dev' into dev
This commit is contained in:
66
.github/workflows/dev-daily-fixed.yml
vendored
66
.github/workflows/dev-daily-fixed.yml
vendored
@@ -60,7 +60,23 @@ jobs:
|
||||
fi
|
||||
gh release create "$FIXED_DEV_TAG" --repo "$GITHUB_REPOSITORY" --title "Daily Dev Build" --notes "开发版发布页" --prerelease --target "$TARGET_BRANCH"
|
||||
RELEASE_REST_ID="$(gh api "repos/$GITHUB_REPOSITORY/releases/tags/$FIXED_DEV_TAG" --jq '.id')"
|
||||
gh api --method PATCH "repos/$GITHUB_REPOSITORY/releases/$RELEASE_REST_ID" -f draft=false -f prerelease=true >/dev/null
|
||||
RELEASE_ENDPOINT="repos/$GITHUB_REPOSITORY/releases/tags/$FIXED_DEV_TAG"
|
||||
settled="false"
|
||||
for i in 1 2 3 4 5; do
|
||||
gh api --method PATCH "repos/$GITHUB_REPOSITORY/releases/$RELEASE_REST_ID" -F draft=false -F prerelease=true >/dev/null 2>&1 || true
|
||||
DRAFT_STATE="$(gh api "$RELEASE_ENDPOINT" --jq '.draft' 2>/dev/null || echo true)"
|
||||
PRERELEASE_STATE="$(gh api "$RELEASE_ENDPOINT" --jq '.prerelease' 2>/dev/null || echo false)"
|
||||
if [ "$DRAFT_STATE" = "false" ] && [ "$PRERELEASE_STATE" = "true" ]; then
|
||||
settled="true"
|
||||
break
|
||||
fi
|
||||
sleep 2
|
||||
done
|
||||
if [ "$settled" != "true" ]; then
|
||||
echo "Failed to settle release state after create:"
|
||||
gh api "$RELEASE_ENDPOINT" --jq '{draft: .draft, prerelease: .prerelease, url: .html_url}'
|
||||
exit 1
|
||||
fi
|
||||
|
||||
dev-mac-arm64:
|
||||
needs: prepare
|
||||
@@ -81,6 +97,22 @@ jobs:
|
||||
- name: Install Dependencies
|
||||
run: npm install
|
||||
|
||||
- name: Ensure mac key helpers are executable
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
for file in \
|
||||
resources/key/macos/universal/xkey_helper \
|
||||
resources/key/macos/universal/image_scan_helper \
|
||||
resources/key/macos/universal/xkey_helper_macos \
|
||||
resources/key/macos/universal/libwx_key.dylib
|
||||
do
|
||||
if [ -f "$file" ]; then
|
||||
chmod +x "$file"
|
||||
ls -l "$file"
|
||||
fi
|
||||
done
|
||||
|
||||
- name: Set dev version
|
||||
shell: bash
|
||||
run: npm version "${{ needs.prepare.outputs.dev_version }}" --no-git-tag-version --allow-same-version
|
||||
@@ -270,21 +302,25 @@ jobs:
|
||||
- name: Update fixed dev release notes
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
FIXED_DEV_TAG: ${{ env.FIXED_DEV_TAG }}
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
|
||||
TAG="$FIXED_DEV_TAG"
|
||||
TAG="${FIXED_DEV_TAG:-}"
|
||||
if [ -z "$TAG" ]; then
|
||||
echo "FIXED_DEV_TAG is empty, abort."
|
||||
exit 1
|
||||
fi
|
||||
REPO="$GITHUB_REPOSITORY"
|
||||
RELEASE_PAGE="https://github.com/$REPO/releases/tag/$TAG"
|
||||
echo "Using release tag: $TAG"
|
||||
|
||||
if ! gh release view "$TAG" --repo "$REPO" >/dev/null 2>&1; then
|
||||
if ! gh api "repos/$REPO/releases/tags/$TAG" >/dev/null 2>&1; then
|
||||
echo "Release $TAG not found, skip notes update."
|
||||
exit 0
|
||||
fi
|
||||
|
||||
ASSETS_JSON="$(gh release view "$TAG" --repo "$REPO" --json assets)"
|
||||
ASSETS_JSON="$(gh api "repos/$REPO/releases/tags/$TAG")"
|
||||
|
||||
pick_asset() {
|
||||
local pattern="$1"
|
||||
@@ -350,4 +386,22 @@ jobs:
|
||||
}
|
||||
|
||||
update_release_notes
|
||||
gh release view "$TAG" --repo "$REPO" --json isDraft,isPrerelease,url
|
||||
RELEASE_REST_ID="$(gh api "repos/$REPO/releases/tags/$TAG" --jq '.id')"
|
||||
RELEASE_ENDPOINT="repos/$REPO/releases/tags/$TAG"
|
||||
settled="false"
|
||||
for i in 1 2 3 4 5; do
|
||||
gh api --method PATCH "repos/$REPO/releases/$RELEASE_REST_ID" -F draft=false -F prerelease=true >/dev/null 2>&1 || true
|
||||
DRAFT_STATE="$(gh api "$RELEASE_ENDPOINT" --jq '.draft' 2>/dev/null || echo true)"
|
||||
PRERELEASE_STATE="$(gh api "$RELEASE_ENDPOINT" --jq '.prerelease' 2>/dev/null || echo false)"
|
||||
if [ "$DRAFT_STATE" = "false" ] && [ "$PRERELEASE_STATE" = "true" ]; then
|
||||
settled="true"
|
||||
break
|
||||
fi
|
||||
sleep 2
|
||||
done
|
||||
if [ "$settled" != "true" ]; then
|
||||
echo "Failed to settle release state after notes update:"
|
||||
gh api "$RELEASE_ENDPOINT" --jq '{draft: .draft, prerelease: .prerelease, url: .html_url}'
|
||||
exit 1
|
||||
fi
|
||||
gh api "repos/$REPO/releases/tags/$TAG" --jq '{isDraft: .draft, isPrerelease: .prerelease, url: .html_url}'
|
||||
|
||||
65
.github/workflows/preview-nightly-main.yml
vendored
65
.github/workflows/preview-nightly-main.yml
vendored
@@ -86,7 +86,23 @@ jobs:
|
||||
fi
|
||||
gh release create "$FIXED_PREVIEW_TAG" --repo "$GITHUB_REPOSITORY" --title "Preview Nightly Build" --notes "预览版发布页" --prerelease --target "$TARGET_BRANCH"
|
||||
RELEASE_REST_ID="$(gh api "repos/$GITHUB_REPOSITORY/releases/tags/$FIXED_PREVIEW_TAG" --jq '.id')"
|
||||
gh api --method PATCH "repos/$GITHUB_REPOSITORY/releases/$RELEASE_REST_ID" -f draft=false -f prerelease=true >/dev/null
|
||||
RELEASE_ENDPOINT="repos/$GITHUB_REPOSITORY/releases/tags/$FIXED_PREVIEW_TAG"
|
||||
settled="false"
|
||||
for i in 1 2 3 4 5; do
|
||||
gh api --method PATCH "repos/$GITHUB_REPOSITORY/releases/$RELEASE_REST_ID" -F draft=false -F prerelease=true >/dev/null 2>&1 || true
|
||||
DRAFT_STATE="$(gh api "$RELEASE_ENDPOINT" --jq '.draft' 2>/dev/null || echo true)"
|
||||
PRERELEASE_STATE="$(gh api "$RELEASE_ENDPOINT" --jq '.prerelease' 2>/dev/null || echo false)"
|
||||
if [ "$DRAFT_STATE" = "false" ] && [ "$PRERELEASE_STATE" = "true" ]; then
|
||||
settled="true"
|
||||
break
|
||||
fi
|
||||
sleep 2
|
||||
done
|
||||
if [ "$settled" != "true" ]; then
|
||||
echo "Failed to settle release state after create:"
|
||||
gh api "$RELEASE_ENDPOINT" --jq '{draft: .draft, prerelease: .prerelease, url: .html_url}'
|
||||
exit 1
|
||||
fi
|
||||
|
||||
preview-mac-arm64:
|
||||
needs: prepare
|
||||
@@ -108,6 +124,22 @@ jobs:
|
||||
- name: Install Dependencies
|
||||
run: npm install
|
||||
|
||||
- name: Ensure mac key helpers are executable
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
for file in \
|
||||
resources/key/macos/universal/xkey_helper \
|
||||
resources/key/macos/universal/image_scan_helper \
|
||||
resources/key/macos/universal/xkey_helper_macos \
|
||||
resources/key/macos/universal/libwx_key.dylib
|
||||
do
|
||||
if [ -f "$file" ]; then
|
||||
chmod +x "$file"
|
||||
ls -l "$file"
|
||||
fi
|
||||
done
|
||||
|
||||
- name: Set preview version
|
||||
shell: bash
|
||||
run: npm version "${{ needs.prepare.outputs.preview_version }}" --no-git-tag-version --allow-same-version
|
||||
@@ -315,17 +347,22 @@ jobs:
|
||||
run: |
|
||||
set -euo pipefail
|
||||
|
||||
TAG="$FIXED_PREVIEW_TAG"
|
||||
TAG="${FIXED_PREVIEW_TAG:-}"
|
||||
if [ -z "$TAG" ]; then
|
||||
echo "FIXED_PREVIEW_TAG is empty, abort."
|
||||
exit 1
|
||||
fi
|
||||
CURRENT_PREVIEW_VERSION="${{ needs.prepare.outputs.preview_version }}"
|
||||
REPO="$GITHUB_REPOSITORY"
|
||||
RELEASE_PAGE="https://github.com/$REPO/releases/tag/$TAG"
|
||||
echo "Using release tag: $TAG"
|
||||
|
||||
if ! gh release view "$TAG" --repo "$REPO" >/dev/null 2>&1; then
|
||||
if ! gh api "repos/$REPO/releases/tags/$TAG" >/dev/null 2>&1; then
|
||||
echo "Release $TAG not found (possibly all publish jobs failed), skip notes update."
|
||||
exit 0
|
||||
fi
|
||||
|
||||
ASSETS_JSON="$(gh release view "$TAG" --repo "$REPO" --json assets)"
|
||||
ASSETS_JSON="$(gh api "repos/$REPO/releases/tags/$TAG")"
|
||||
|
||||
pick_asset() {
|
||||
local pattern="$1"
|
||||
@@ -392,4 +429,22 @@ jobs:
|
||||
}
|
||||
|
||||
update_release_notes
|
||||
gh release view "$TAG" --repo "$REPO" --json isDraft,isPrerelease,url
|
||||
RELEASE_REST_ID="$(gh api "repos/$REPO/releases/tags/$TAG" --jq '.id')"
|
||||
RELEASE_ENDPOINT="repos/$REPO/releases/tags/$TAG"
|
||||
settled="false"
|
||||
for i in 1 2 3 4 5; do
|
||||
gh api --method PATCH "repos/$REPO/releases/$RELEASE_REST_ID" -F draft=false -F prerelease=true >/dev/null 2>&1 || true
|
||||
DRAFT_STATE="$(gh api "$RELEASE_ENDPOINT" --jq '.draft' 2>/dev/null || echo true)"
|
||||
PRERELEASE_STATE="$(gh api "$RELEASE_ENDPOINT" --jq '.prerelease' 2>/dev/null || echo false)"
|
||||
if [ "$DRAFT_STATE" = "false" ] && [ "$PRERELEASE_STATE" = "true" ]; then
|
||||
settled="true"
|
||||
break
|
||||
fi
|
||||
sleep 2
|
||||
done
|
||||
if [ "$settled" != "true" ]; then
|
||||
echo "Failed to settle release state after notes update:"
|
||||
gh api "$RELEASE_ENDPOINT" --jq '{draft: .draft, prerelease: .prerelease, url: .html_url}'
|
||||
exit 1
|
||||
fi
|
||||
gh api "repos/$REPO/releases/tags/$TAG" --jq '{isDraft: .draft, isPrerelease: .prerelease, url: .html_url}'
|
||||
|
||||
38
.github/workflows/release.yml
vendored
38
.github/workflows/release.yml
vendored
@@ -36,7 +36,7 @@ jobs:
|
||||
run: |
|
||||
VERSION=${GITHUB_REF_NAME#v}
|
||||
echo "Syncing package.json version to $VERSION"
|
||||
npm version $VERSION --no-git-tag-version --allow-same-version
|
||||
node -e "const fs=require('fs');const p=JSON.parse(fs.readFileSync('package.json','utf8'));p.version='$VERSION';fs.writeFileSync('package.json',JSON.stringify(p,null,2)+'\n')"
|
||||
|
||||
- name: Build Frontend & Type Check
|
||||
shell: bash
|
||||
@@ -88,12 +88,17 @@ jobs:
|
||||
- name: Install Dependencies
|
||||
run: npm install
|
||||
|
||||
- name: Ensure linux key helper is executable
|
||||
shell: bash
|
||||
run: |
|
||||
[ -f "resources/key/linux/x64/xkey_helper" ] && chmod +x "resources/key/linux/x64/xkey_helper" || echo "File not found"
|
||||
|
||||
- name: Sync version with tag
|
||||
shell: bash
|
||||
run: |
|
||||
VERSION=${GITHUB_REF_NAME#v}
|
||||
echo "Syncing package.json version to $VERSION"
|
||||
npm version $VERSION --no-git-tag-version --allow-same-version
|
||||
node -e "const fs=require('fs');const p=JSON.parse(fs.readFileSync('package.json','utf8'));p.version='$VERSION';fs.writeFileSync('package.json',JSON.stringify(p,null,2)+'\n')"
|
||||
|
||||
- name: Build Frontend & Type Check
|
||||
shell: bash
|
||||
@@ -115,7 +120,7 @@ jobs:
|
||||
TAG=${GITHUB_REF_NAME}
|
||||
REPO=${{ github.repository }}
|
||||
MINIMUM_VERSION="4.1.7"
|
||||
gh release download "$TAG" --repo "$REPO" --pattern "latest-linux.yml" --output "/tmp/latest-linux.yml" 2>/dev/null
|
||||
gh release download "$TAG" --repo "$REPO" --pattern "latest-linux.yml" --output "/tmp/latest-linux.yml" 2>/dev/null || true
|
||||
if [ -f /tmp/latest-linux.yml ] && ! grep -q 'minimumVersion' /tmp/latest-linux.yml; then
|
||||
echo "minimumVersion: $MINIMUM_VERSION" >> /tmp/latest-linux.yml
|
||||
gh release upload "$TAG" --repo "$REPO" /tmp/latest-linux.yml --clobber
|
||||
@@ -144,7 +149,7 @@ jobs:
|
||||
run: |
|
||||
VERSION=${GITHUB_REF_NAME#v}
|
||||
echo "Syncing package.json version to $VERSION"
|
||||
npm version $VERSION --no-git-tag-version --allow-same-version
|
||||
node -e "const fs=require('fs');const p=JSON.parse(fs.readFileSync('package.json','utf8'));p.version='$VERSION';fs.writeFileSync('package.json',JSON.stringify(p,null,2)+'\n')"
|
||||
|
||||
- name: Build Frontend & Type Check
|
||||
shell: bash
|
||||
@@ -166,7 +171,7 @@ jobs:
|
||||
TAG=${GITHUB_REF_NAME}
|
||||
REPO=${{ github.repository }}
|
||||
MINIMUM_VERSION="4.1.7"
|
||||
gh release download "$TAG" --repo "$REPO" --pattern "latest.yml" --output "/tmp/latest.yml" 2>/dev/null
|
||||
gh release download "$TAG" --repo "$REPO" --pattern "latest.yml" --output "/tmp/latest.yml" 2>/dev/null || true
|
||||
if [ -f /tmp/latest.yml ] && ! grep -q 'minimumVersion' /tmp/latest.yml; then
|
||||
echo "minimumVersion: $MINIMUM_VERSION" >> /tmp/latest.yml
|
||||
gh release upload "$TAG" --repo "$REPO" /tmp/latest.yml --clobber
|
||||
@@ -195,7 +200,7 @@ jobs:
|
||||
run: |
|
||||
VERSION=${GITHUB_REF_NAME#v}
|
||||
echo "Syncing package.json version to $VERSION"
|
||||
npm version $VERSION --no-git-tag-version --allow-same-version
|
||||
node -e "const fs=require('fs');const p=JSON.parse(fs.readFileSync('package.json','utf8'));p.version='$VERSION';fs.writeFileSync('package.json',JSON.stringify(p,null,2)+'\n')"
|
||||
|
||||
- name: Build Frontend & Type Check
|
||||
shell: bash
|
||||
@@ -217,7 +222,7 @@ jobs:
|
||||
TAG=${GITHUB_REF_NAME}
|
||||
REPO=${{ github.repository }}
|
||||
MINIMUM_VERSION="4.1.7"
|
||||
gh release download "$TAG" --repo "$REPO" --pattern "latest-arm64.yml" --output "/tmp/latest-arm64.yml" 2>/dev/null
|
||||
gh release download "$TAG" --repo "$REPO" --pattern "latest-arm64.yml" --output "/tmp/latest-arm64.yml" 2>/dev/null || true
|
||||
if [ -f /tmp/latest-arm64.yml ] && ! grep -q 'minimumVersion' /tmp/latest-arm64.yml; then
|
||||
echo "minimumVersion: $MINIMUM_VERSION" >> /tmp/latest-arm64.yml
|
||||
gh release upload "$TAG" --repo "$REPO" /tmp/latest-arm64.yml --clobber
|
||||
@@ -295,3 +300,22 @@ jobs:
|
||||
EOF
|
||||
|
||||
gh release edit "$TAG" --repo "$REPO" --notes-file release_notes.md
|
||||
|
||||
deploy-aur:
|
||||
runs-on: ubuntu-latest
|
||||
needs: [release-linux]
|
||||
if: startsWith(github.ref, 'refs/tags/v')
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v5
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Publish AUR package
|
||||
uses: KSXGitHub/github-actions-deploy-aur@master
|
||||
with:
|
||||
pkgname: weflow
|
||||
ssh_private_key: ${{ secrets.AUR_SSH_PRIVATE_KEY }}
|
||||
commit_username: H3CoF6
|
||||
commit_email: h3cof6@gmail.com
|
||||
ssh_keyscan_types: ed25519
|
||||
|
||||
51
README.md
51
README.md
@@ -1,34 +1,23 @@
|
||||
# WeFlow
|
||||
|
||||
WeFlow 是一个**完全本地**的微信**实时**聊天记录查看、分析与导出工具。它可以实时获取你的微信聊天记录并将其导出,还可以根据你的聊天记录为你生成独一无二的分析报告
|
||||
|
||||
---
|
||||
WeFlow 是一个**完全本地**的微信**实时**聊天记录查看、分析与导出工具。它可以实时获取你的微信聊天记录并将其导出,还可以根据你的聊天记录为你生成独一无二的分析报告。
|
||||
|
||||
<p align="center">
|
||||
<img src="app.png" alt="WeFlow" width="90%">
|
||||
<img src="app.png" alt="WeFlow 应用预览" width="90%">
|
||||
</p>
|
||||
|
||||
---
|
||||
|
||||
<p align="center">
|
||||
<a href="https://github.com/hicccc77/WeFlow/stargazers">
|
||||
<img src="https://img.shields.io/github/stars/hicccc77/WeFlow?style=flat-square" alt="Stargazers">
|
||||
</a>
|
||||
<a href="https://github.com/hicccc77/WeFlow/network/members">
|
||||
<img src="https://img.shields.io/github/forks/hicccc77/WeFlow?style=flat-square" alt="Forks">
|
||||
</a>
|
||||
<a href="https://github.com/hicccc77/WeFlow/issues">
|
||||
<img src="https://img.shields.io/github/issues/hicccc77/WeFlow?style=flat-square" alt="Issues">
|
||||
</a>
|
||||
<a href="https://github.com/hicccc77/WeFlow/releases">
|
||||
<img src="https://img.shields.io/github/downloads/hicccc77/WeFlow/total?style=flat-square" alt="Downloads" />
|
||||
</a>
|
||||
<a href="https://t.me/weflow_cc">
|
||||
<img src="https://img.shields.io/badge/Telegram%20频道-0088cc?style=flat-square&logo=telegram&logoColor=0088cc&labelColor=white" alt="Telegram">
|
||||
</a>
|
||||
<!-- 第一行修复样式 -->
|
||||
<a href="https://github.com/hicccc77/WeFlow/stargazers"><img src="https://img.shields.io/github/stars/hicccc77/WeFlow?style=flat&label=Stars&labelColor=1F2937&color=2563EB" alt="Stargazers"></a>
|
||||
<a href="https://github.com/hicccc77/WeFlow/network/members"><img src="https://img.shields.io/github/forks/hicccc77/WeFlow?style=flat&label=Forks&labelColor=1F2937&color=7C3AED" alt="Forks"></a>
|
||||
<a href="https://github.com/hicccc77/WeFlow/issues"><img src="https://img.shields.io/github/issues/hicccc77/WeFlow?style=flat&label=Issues&labelColor=1F2937&color=D97706" alt="Issues"></a>
|
||||
<a href="https://github.com/hicccc77/WeFlow/releases"><img src="https://img.shields.io/github/downloads/hicccc77/WeFlow/total?style=flat&label=Downloads&labelColor=1F2937&color=059669" alt="Downloads"></a>
|
||||
<br><br>
|
||||
<!-- 第二行:电报矮一点(22px),排名高一点(32px),使用 vertical-align: middle 居中对齐 -->
|
||||
<a href="https://t.me/weflow_cc"><img src="https://img.shields.io/badge/Telegram-频道-1D9BF0?style=flat&logo=telegram&logoColor=white&labelColor=1F2937&color=1D9BF0" alt="Telegram Channel" style="height: 22px; vertical-align: middle;"></a>
|
||||
<a href="https://www.star-history.com/hicccc77/weflow"><img src="https://api.star-history.com/badge?repo=hicccc77/WeFlow&theme=dark" alt="Star History Rank" style="height: 32px; vertical-align: middle;"></a>
|
||||
</p>
|
||||
|
||||
|
||||
> [!TIP]
|
||||
> 如果导出聊天记录后,想深入分析聊天内容可以试试 [ChatLab](https://chatlab.fun/)
|
||||
|
||||
@@ -47,14 +36,12 @@ WeFlow 是一个**完全本地**的微信**实时**聊天记录查看、分析
|
||||
|
||||
## 支持平台与设备
|
||||
|
||||
|
||||
| 平台 | 设备/架构 | 安装包 |
|
||||
|------|----------|--------|
|
||||
| Windows | Windows10+、x64(amd64) | `.exe` |
|
||||
| macOS | Apple Silicon(M 系列,arm64) | `.dmg` |
|
||||
| Linux | x64 设备(amd64) | `.AppImage`、`.tar.gz` |
|
||||
|
||||
|
||||
## 快速开始
|
||||
|
||||
若你只想使用成品版本,可前往 [Releases](https://github.com/hicccc77/WeFlow/releases) 下载并安装。
|
||||
@@ -93,7 +80,6 @@ WeFlow 提供本地 HTTP API 服务,支持通过接口查询消息数据,可
|
||||
|
||||
完整接口文档:[点击查看](docs/HTTP-API.md)
|
||||
|
||||
|
||||
## 面向开发者
|
||||
|
||||
如果你想从源码构建或为项目贡献代码,请遵循以下步骤:
|
||||
@@ -108,7 +94,6 @@ npm install
|
||||
|
||||
# 3. 运行应用(开发模式)
|
||||
npm run dev
|
||||
|
||||
```
|
||||
|
||||
## 致谢
|
||||
@@ -120,18 +105,16 @@ npm run dev
|
||||
|
||||
如果 WeFlow 确实帮到了你,可以考虑请我们喝杯咖啡:
|
||||
|
||||
|
||||
> TRC20 **Address:** `TZCtAw8CaeARWZBfvjidCnTcfnAtf6nvS6`
|
||||
|
||||
> TRC20 **Address:** `TZCtAw8CaeARWZBfvjidCnTcfnAtf6nvS6`
|
||||
|
||||
## Star History
|
||||
|
||||
<a href="https://www.star-history.com/#hicccc77/WeFlow&type=date&legend=top-left">
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=hicccc77/WeFlow&type=date&theme=dark&legend=top-left" />
|
||||
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=hicccc77/WeFlow&type=date&legend=top-left" />
|
||||
<img alt="Star History Chart" src="https://api.star-history.com/svg?repos=hicccc77/WeFlow&type=date&legend=top-left" />
|
||||
</picture>
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=hicccc77/WeFlow&type=date&theme=dark&legend=top-left" />
|
||||
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=hicccc77/WeFlow&type=date&legend=top-left" />
|
||||
<img alt="Star History Chart" src="https://api.star-history.com/svg?repos=hicccc77/WeFlow&type=date&legend=top-left" />
|
||||
</picture>
|
||||
</a>
|
||||
|
||||
<div align="center">
|
||||
|
||||
168
electron/main.ts
168
electron/main.ts
@@ -950,8 +950,17 @@ function closeSplash() {
|
||||
/**
|
||||
* 创建首次引导窗口
|
||||
*/
|
||||
function createOnboardingWindow() {
|
||||
function createOnboardingWindow(mode: 'default' | 'add-account' = 'default') {
|
||||
const onboardingHash = mode === 'add-account'
|
||||
? '/onboarding-window?mode=add-account'
|
||||
: '/onboarding-window'
|
||||
|
||||
if (onboardingWindow && !onboardingWindow.isDestroyed()) {
|
||||
if (process.env.VITE_DEV_SERVER_URL) {
|
||||
onboardingWindow.loadURL(`${process.env.VITE_DEV_SERVER_URL}#${onboardingHash}`)
|
||||
} else {
|
||||
onboardingWindow.loadFile(join(__dirname, '../dist/index.html'), { hash: onboardingHash })
|
||||
}
|
||||
onboardingWindow.focus()
|
||||
return onboardingWindow
|
||||
}
|
||||
@@ -987,9 +996,9 @@ function createOnboardingWindow() {
|
||||
})
|
||||
|
||||
if (process.env.VITE_DEV_SERVER_URL) {
|
||||
onboardingWindow.loadURL(`${process.env.VITE_DEV_SERVER_URL}#/onboarding-window`)
|
||||
onboardingWindow.loadURL(`${process.env.VITE_DEV_SERVER_URL}#${onboardingHash}`)
|
||||
} else {
|
||||
onboardingWindow.loadFile(join(__dirname, '../dist/index.html'), { hash: '/onboarding-window' })
|
||||
onboardingWindow.loadFile(join(__dirname, '../dist/index.html'), { hash: onboardingHash })
|
||||
}
|
||||
|
||||
onboardingWindow.on('closed', () => {
|
||||
@@ -1635,6 +1644,22 @@ function registerIpcHandlers() {
|
||||
return insightService.triggerTest()
|
||||
})
|
||||
|
||||
ipcMain.handle('insight:generateFootprintInsight', async (_, payload: {
|
||||
rangeLabel: string
|
||||
summary: {
|
||||
private_inbound_people?: number
|
||||
private_replied_people?: number
|
||||
private_outbound_people?: number
|
||||
private_reply_rate?: number
|
||||
mention_count?: number
|
||||
mention_group_count?: number
|
||||
}
|
||||
privateSegments?: Array<{ displayName?: string; session_id?: string; incoming_count?: number; outgoing_count?: number; message_count?: number; replied?: boolean }>
|
||||
mentionGroups?: Array<{ displayName?: string; session_id?: string; count?: number }>
|
||||
}) => {
|
||||
return insightService.generateFootprintInsight(payload)
|
||||
})
|
||||
|
||||
ipcMain.handle('config:clear', async () => {
|
||||
if (isLaunchAtStartupSupported() && getSystemLaunchAtStartup()) {
|
||||
const result = setSystemLaunchAtStartup(false)
|
||||
@@ -2244,6 +2269,39 @@ function registerIpcHandlers() {
|
||||
const defaultValue = key === 'lastSession' ? '' : {}
|
||||
cfg.set(key as any, defaultValue as any)
|
||||
}
|
||||
|
||||
try {
|
||||
const dbPath = String(cfg.get('dbPath') || '').trim()
|
||||
const automationMapRaw = cfg.get('exportAutomationTaskMap') as Record<string, unknown> | undefined
|
||||
if (automationMapRaw && typeof automationMapRaw === 'object') {
|
||||
const nextAutomationMap: Record<string, unknown> = { ...automationMapRaw }
|
||||
let changed = false
|
||||
for (const scopeKey of Object.keys(automationMapRaw)) {
|
||||
const normalizedScopeKey = String(scopeKey || '').trim()
|
||||
if (!normalizedScopeKey) continue
|
||||
const separatorIndex = normalizedScopeKey.lastIndexOf('::')
|
||||
const scopedDbPath = separatorIndex >= 0
|
||||
? normalizedScopeKey.slice(0, separatorIndex)
|
||||
: ''
|
||||
const scopedWxidRaw = separatorIndex >= 0
|
||||
? normalizedScopeKey.slice(separatorIndex + 2)
|
||||
: normalizedScopeKey
|
||||
const scopedWxid = normalizeAccountId(scopedWxidRaw)
|
||||
const wxidMatched = wxidCandidates.includes(scopedWxidRaw) || scopedWxid === normalizedWxid
|
||||
const dbPathMatched = !dbPath || !scopedDbPath || scopedDbPath === dbPath
|
||||
if (!wxidMatched || !dbPathMatched) continue
|
||||
delete nextAutomationMap[scopeKey]
|
||||
changed = true
|
||||
}
|
||||
if (changed) {
|
||||
cfg.set('exportAutomationTaskMap' as any, nextAutomationMap as any)
|
||||
} else if (!Object.keys(automationMapRaw).length) {
|
||||
cfg.set('exportAutomationTaskMap' as any, {} as any)
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
warnings.push(`清理自动化导出任务失败: ${String(error)}`)
|
||||
}
|
||||
}
|
||||
|
||||
if (clearCache) {
|
||||
@@ -2363,6 +2421,21 @@ function registerIpcHandlers() {
|
||||
return chatService.searchMessages(keyword, sessionId, limit, offset, beginTimestamp, endTimestamp)
|
||||
})
|
||||
|
||||
ipcMain.handle('chat:getMyFootprintStats', async (_, beginTimestamp: number, endTimestamp: number, options?: {
|
||||
myWxid?: string
|
||||
privateSessionIds?: string[]
|
||||
groupSessionIds?: string[]
|
||||
mentionLimit?: number
|
||||
privateLimit?: number
|
||||
mentionMode?: 'text_at_me' | string
|
||||
}) => {
|
||||
return chatService.getMyFootprintStats(beginTimestamp, endTimestamp, options)
|
||||
})
|
||||
|
||||
ipcMain.handle('chat:exportMyFootprint', async (_, beginTimestamp: number, endTimestamp: number, format: 'csv' | 'json', filePath: string) => {
|
||||
return chatService.exportMyFootprint(beginTimestamp, endTimestamp, format, filePath)
|
||||
})
|
||||
|
||||
ipcMain.handle('sns:getTimeline', async (_, limit: number, offset: number, usernames?: string[], keyword?: string, startTime?: number, endTime?: number) => {
|
||||
return snsService.getTimeline(limit, offset, usernames, keyword, startTime, endTime)
|
||||
})
|
||||
@@ -2988,12 +3061,13 @@ function registerIpcHandlers() {
|
||||
})
|
||||
|
||||
// 重新打开首次引导窗口,并隐藏主窗口
|
||||
ipcMain.handle('window:openOnboardingWindow', async () => {
|
||||
ipcMain.handle('window:openOnboardingWindow', async (_, options?: { mode?: 'add-account' }) => {
|
||||
shouldShowMain = false
|
||||
if (mainWindow && !mainWindow.isDestroyed()) {
|
||||
mainWindow.hide()
|
||||
}
|
||||
createOnboardingWindow()
|
||||
const mode = options?.mode === 'add-account' ? 'add-account' : 'default'
|
||||
createOnboardingWindow(mode)
|
||||
return true
|
||||
})
|
||||
|
||||
@@ -3455,12 +3529,38 @@ app.whenReady().then(async () => {
|
||||
}
|
||||
|
||||
const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))
|
||||
const withTimeout = <T>(task: () => Promise<T>, timeoutMs: number): Promise<{ timedOut: boolean; value?: T; error?: string }> => {
|
||||
return new Promise((resolve) => {
|
||||
let settled = false
|
||||
const timer = setTimeout(() => {
|
||||
if (settled) return
|
||||
settled = true
|
||||
resolve({ timedOut: true, error: `timeout(${timeoutMs}ms)` })
|
||||
}, timeoutMs)
|
||||
|
||||
task()
|
||||
.then((value) => {
|
||||
if (settled) return
|
||||
settled = true
|
||||
clearTimeout(timer)
|
||||
resolve({ timedOut: false, value })
|
||||
})
|
||||
.catch((error) => {
|
||||
if (settled) return
|
||||
settled = true
|
||||
clearTimeout(timer)
|
||||
resolve({ timedOut: false, error: String(error) })
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
// 初始化配置服务
|
||||
updateSplashProgress(5, '正在加载配置...')
|
||||
configService = new ConfigService()
|
||||
applyAutoUpdateChannel('startup')
|
||||
syncLaunchAtStartupPreference()
|
||||
const onboardingDone = configService.get('onboardingDone') === true
|
||||
shouldShowMain = onboardingDone
|
||||
|
||||
// 将用户主题配置推送给 Splash 窗口
|
||||
if (splashWindow && !splashWindow.isDestroyed()) {
|
||||
@@ -3473,7 +3573,7 @@ app.whenReady().then(async () => {
|
||||
await delay(200)
|
||||
|
||||
// 设置资源路径
|
||||
updateSplashProgress(10, '正在初始化...')
|
||||
updateSplashProgress(12, '正在初始化...')
|
||||
const candidateResources = app.isPackaged
|
||||
? join(process.resourcesPath, 'resources')
|
||||
: join(app.getAppPath(), 'resources')
|
||||
@@ -3483,13 +3583,13 @@ app.whenReady().then(async () => {
|
||||
await delay(200)
|
||||
|
||||
// 初始化数据库服务
|
||||
updateSplashProgress(18, '正在初始化...')
|
||||
updateSplashProgress(20, '正在初始化...')
|
||||
wcdbService.setPaths(resourcesPath, userDataPath)
|
||||
wcdbService.setLogEnabled(configService.get('logEnabled') === true)
|
||||
await delay(200)
|
||||
|
||||
// 注册 IPC 处理器
|
||||
updateSplashProgress(25, '正在初始化...')
|
||||
updateSplashProgress(28, '正在初始化...')
|
||||
registerIpcHandlers()
|
||||
chatService.addDbMonitorListener((type, json) => {
|
||||
messagePushService.handleDbMonitorChange(type, json)
|
||||
@@ -3499,12 +3599,54 @@ app.whenReady().then(async () => {
|
||||
insightService.start()
|
||||
await delay(200)
|
||||
|
||||
// 检查配置状态
|
||||
const onboardingDone = configService.get('onboardingDone')
|
||||
shouldShowMain = onboardingDone === true
|
||||
// 已完成引导时,在 Splash 阶段预热核心数据(联系人、消息库索引等)
|
||||
if (onboardingDone) {
|
||||
updateSplashProgress(34, '正在连接数据库...')
|
||||
const connectWarmup = await withTimeout(() => chatService.connect(), 12000)
|
||||
const connected = !connectWarmup.timedOut && connectWarmup.value?.success === true
|
||||
|
||||
if (!connected) {
|
||||
const reason = connectWarmup.timedOut
|
||||
? connectWarmup.error
|
||||
: (connectWarmup.value?.error || connectWarmup.error || 'unknown')
|
||||
console.warn('[StartupWarmup] 跳过预热,数据库连接失败:', reason)
|
||||
updateSplashProgress(68, '数据库预热已跳过')
|
||||
} else {
|
||||
const preloadUsernames = new Set<string>()
|
||||
|
||||
updateSplashProgress(44, '正在预加载会话...')
|
||||
const sessionsWarmup = await withTimeout(() => chatService.getSessions(), 12000)
|
||||
if (!sessionsWarmup.timedOut && sessionsWarmup.value?.success && Array.isArray(sessionsWarmup.value.sessions)) {
|
||||
for (const session of sessionsWarmup.value.sessions) {
|
||||
const username = String((session as any)?.username || '').trim()
|
||||
if (username) preloadUsernames.add(username)
|
||||
}
|
||||
}
|
||||
|
||||
updateSplashProgress(56, '正在预加载联系人...')
|
||||
const contactsWarmup = await withTimeout(() => chatService.getContacts(), 15000)
|
||||
if (!contactsWarmup.timedOut && contactsWarmup.value?.success && Array.isArray(contactsWarmup.value.contacts)) {
|
||||
for (const contact of contactsWarmup.value.contacts) {
|
||||
const username = String((contact as any)?.username || '').trim()
|
||||
if (username) preloadUsernames.add(username)
|
||||
}
|
||||
}
|
||||
|
||||
updateSplashProgress(63, '正在缓存联系人头像...')
|
||||
const avatarWarmupUsernames = Array.from(preloadUsernames).slice(0, 2000)
|
||||
if (avatarWarmupUsernames.length > 0) {
|
||||
await withTimeout(() => chatService.enrichSessionsContactInfo(avatarWarmupUsernames), 15000)
|
||||
}
|
||||
|
||||
updateSplashProgress(68, '正在初始化消息库索引...')
|
||||
await withTimeout(() => chatService.warmupMessageDbSnapshot(), 10000)
|
||||
}
|
||||
} else {
|
||||
updateSplashProgress(68, '首次启动准备中...')
|
||||
}
|
||||
|
||||
// 创建主窗口(不显示,由启动流程统一控制)
|
||||
updateSplashProgress(30, '正在加载界面...')
|
||||
updateSplashProgress(70, '正在准备主窗口...')
|
||||
mainWindow = createWindow({ autoShow: false })
|
||||
|
||||
let iconName = 'icon.ico';
|
||||
@@ -3576,7 +3718,7 @@ app.whenReady().then(async () => {
|
||||
)
|
||||
|
||||
// 等待主窗口加载完成(真正耗时阶段,进度条末端呼吸光点)
|
||||
updateSplashProgress(30, '正在加载界面...', true)
|
||||
updateSplashProgress(70, '正在准备主窗口...', true)
|
||||
await new Promise<void>((resolve) => {
|
||||
if (mainWindowReady) {
|
||||
resolve()
|
||||
|
||||
@@ -110,7 +110,7 @@ contextBridge.exposeInMainWorld('electronAPI', {
|
||||
ipcRenderer.invoke('window:respondCloseConfirm', action),
|
||||
openAgreementWindow: () => ipcRenderer.invoke('window:openAgreementWindow'),
|
||||
completeOnboarding: () => ipcRenderer.invoke('window:completeOnboarding'),
|
||||
openOnboardingWindow: () => ipcRenderer.invoke('window:openOnboardingWindow'),
|
||||
openOnboardingWindow: (options?: { mode?: 'add-account' }) => ipcRenderer.invoke('window:openOnboardingWindow', options),
|
||||
setTitleBarOverlay: (options: { symbolColor: string }) => ipcRenderer.send('window:setTitleBarOverlay', options),
|
||||
openVideoPlayerWindow: (videoPath: string, videoWidth?: number, videoHeight?: number) =>
|
||||
ipcRenderer.invoke('window:openVideoPlayerWindow', videoPath, videoWidth, videoHeight),
|
||||
@@ -258,6 +258,24 @@ contextBridge.exposeInMainWorld('electronAPI', {
|
||||
ipcRenderer.invoke('chat:getMessage', sessionId, localId),
|
||||
searchMessages: (keyword: string, sessionId?: string, limit?: number, offset?: number, beginTimestamp?: number, endTimestamp?: number) =>
|
||||
ipcRenderer.invoke('chat:searchMessages', keyword, sessionId, limit, offset, beginTimestamp, endTimestamp),
|
||||
getMyFootprintStats: (
|
||||
beginTimestamp: number,
|
||||
endTimestamp: number,
|
||||
options?: {
|
||||
myWxid?: string
|
||||
privateSessionIds?: string[]
|
||||
groupSessionIds?: string[]
|
||||
mentionLimit?: number
|
||||
privateLimit?: number
|
||||
mentionMode?: 'text_at_me' | string
|
||||
}
|
||||
) => ipcRenderer.invoke('chat:getMyFootprintStats', beginTimestamp, endTimestamp, options),
|
||||
exportMyFootprint: (
|
||||
beginTimestamp: number,
|
||||
endTimestamp: number,
|
||||
format: 'csv' | 'json',
|
||||
filePath: string
|
||||
) => ipcRenderer.invoke('chat:exportMyFootprint', beginTimestamp, endTimestamp, format, filePath),
|
||||
onWcdbChange: (callback: (event: any, data: { type: string; json: string }) => void) => {
|
||||
ipcRenderer.on('wcdb-change', callback)
|
||||
return () => ipcRenderer.removeListener('wcdb-change', callback)
|
||||
@@ -508,6 +526,19 @@ contextBridge.exposeInMainWorld('electronAPI', {
|
||||
insight: {
|
||||
testConnection: () => ipcRenderer.invoke('insight:testConnection'),
|
||||
getTodayStats: () => ipcRenderer.invoke('insight:getTodayStats'),
|
||||
triggerTest: () => ipcRenderer.invoke('insight:triggerTest')
|
||||
triggerTest: () => ipcRenderer.invoke('insight:triggerTest'),
|
||||
generateFootprintInsight: (payload: {
|
||||
rangeLabel: string
|
||||
summary: {
|
||||
private_inbound_people?: number
|
||||
private_replied_people?: number
|
||||
private_outbound_people?: number
|
||||
private_reply_rate?: number
|
||||
mention_count?: number
|
||||
mention_group_count?: number
|
||||
}
|
||||
privateSegments?: Array<{ displayName?: string; session_id?: string; incoming_count?: number; outgoing_count?: number; message_count?: number; replied?: boolean }>
|
||||
mentionGroups?: Array<{ displayName?: string; session_id?: string; count?: number }>
|
||||
}) => ipcRenderer.invoke('insight:generateFootprintInsight', payload)
|
||||
}
|
||||
})
|
||||
|
||||
@@ -13,6 +13,7 @@ export interface BizAccount {
|
||||
type: number
|
||||
last_time: number
|
||||
formatted_last_time: string
|
||||
unread_count?: number
|
||||
}
|
||||
|
||||
export interface BizMessage {
|
||||
@@ -104,19 +105,24 @@ export class BizService {
|
||||
if (!root || !accountWxid) return []
|
||||
|
||||
const bizLatestTime: Record<string, number> = {}
|
||||
const bizUnreadCount: Record<string, number> = {}
|
||||
|
||||
try {
|
||||
const sessionsRes = await wcdbService.getSessions()
|
||||
const sessionsRes = await chatService.getSessions()
|
||||
if (sessionsRes.success && sessionsRes.sessions) {
|
||||
for (const session of sessionsRes.sessions) {
|
||||
const uname = session.username || session.strUsrName || session.userName || session.id
|
||||
// 适配日志中发现的字段,注意转为整型数字
|
||||
const timeStr = session.last_timestamp || session.sort_timestamp || session.nTime || session.timestamp || '0'
|
||||
const timeStr = session.lastTimestamp || session.sortTimestamp || session.last_timestamp || session.sort_timestamp || session.nTime || session.timestamp || '0'
|
||||
const time = parseInt(timeStr.toString(), 10)
|
||||
|
||||
if (usernames.includes(uname) && time > 0) {
|
||||
bizLatestTime[uname] = time
|
||||
}
|
||||
if (usernames.includes(uname)) {
|
||||
const unread = Number(session.unreadCount ?? session.unread_count ?? 0)
|
||||
bizUnreadCount[uname] = Number.isFinite(unread) ? Math.max(0, Math.floor(unread)) : 0
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
@@ -152,7 +158,8 @@ export class BizService {
|
||||
avatar: info?.avatarUrl || '',
|
||||
type: 0,
|
||||
last_time: lastTime,
|
||||
formatted_last_time: formatBizTime(lastTime)
|
||||
formatted_last_time: formatBizTime(lastTime),
|
||||
unread_count: bizUnreadCount[uname] || 0
|
||||
}
|
||||
})
|
||||
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -61,6 +61,8 @@ interface ConfigSchema {
|
||||
notificationFilterMode: 'all' | 'whitelist' | 'blacklist'
|
||||
notificationFilterList: string[]
|
||||
messagePushEnabled: boolean
|
||||
messagePushFilterMode: 'all' | 'whitelist' | 'blacklist'
|
||||
messagePushFilterList: string[]
|
||||
httpApiEnabled: boolean
|
||||
httpApiPort: number
|
||||
httpApiHost: string
|
||||
@@ -69,8 +71,12 @@ interface ConfigSchema {
|
||||
quoteLayout: 'quote-top' | 'quote-bottom'
|
||||
wordCloudExcludeWords: string[]
|
||||
exportWriteLayout: 'A' | 'B' | 'C'
|
||||
exportAutomationTaskMap: Record<string, unknown>
|
||||
|
||||
// AI 见解
|
||||
aiModelApiBaseUrl: string
|
||||
aiModelApiKey: string
|
||||
aiModelApiModel: string
|
||||
aiInsightEnabled: boolean
|
||||
aiInsightApiBaseUrl: string
|
||||
aiInsightApiKey: string
|
||||
@@ -93,10 +99,23 @@ interface ConfigSchema {
|
||||
aiInsightTelegramToken: string
|
||||
/** Telegram 接收 Chat ID,逗号分隔,支持多个 */
|
||||
aiInsightTelegramChatIds: string
|
||||
|
||||
// AI 足迹
|
||||
aiFootprintEnabled: boolean
|
||||
aiFootprintSystemPrompt: string
|
||||
/** 是否将 AI 见解调试日志输出到桌面 */
|
||||
aiInsightDebugLogEnabled: boolean
|
||||
}
|
||||
|
||||
// 需要 safeStorage 加密的字段(普通模式)
|
||||
const ENCRYPTED_STRING_KEYS: Set<string> = new Set(['decryptKey', 'imageAesKey', 'authPassword', 'httpApiToken', 'aiInsightApiKey'])
|
||||
const ENCRYPTED_STRING_KEYS: Set<string> = new Set([
|
||||
'decryptKey',
|
||||
'imageAesKey',
|
||||
'authPassword',
|
||||
'httpApiToken',
|
||||
'aiModelApiKey',
|
||||
'aiInsightApiKey'
|
||||
])
|
||||
const ENCRYPTED_BOOL_KEYS: Set<string> = new Set(['authEnabled', 'authUseHello'])
|
||||
const ENCRYPTED_NUMBER_KEYS: Set<string> = new Set(['imageXorKey'])
|
||||
|
||||
@@ -163,10 +182,16 @@ export class ConfigService {
|
||||
httpApiPort: 5031,
|
||||
httpApiHost: '127.0.0.1',
|
||||
messagePushEnabled: false,
|
||||
messagePushFilterMode: 'all',
|
||||
messagePushFilterList: [],
|
||||
windowCloseBehavior: 'ask',
|
||||
quoteLayout: 'quote-top',
|
||||
wordCloudExcludeWords: [],
|
||||
exportWriteLayout: 'A',
|
||||
exportAutomationTaskMap: {},
|
||||
aiModelApiBaseUrl: '',
|
||||
aiModelApiKey: '',
|
||||
aiModelApiModel: 'gpt-4o-mini',
|
||||
aiInsightEnabled: false,
|
||||
aiInsightApiBaseUrl: '',
|
||||
aiInsightApiKey: '',
|
||||
@@ -181,7 +206,10 @@ export class ConfigService {
|
||||
aiInsightSystemPrompt: '',
|
||||
aiInsightTelegramEnabled: false,
|
||||
aiInsightTelegramToken: '',
|
||||
aiInsightTelegramChatIds: ''
|
||||
aiInsightTelegramChatIds: '',
|
||||
aiFootprintEnabled: false,
|
||||
aiFootprintSystemPrompt: '',
|
||||
aiInsightDebugLogEnabled: false
|
||||
}
|
||||
|
||||
const storeOptions: any = {
|
||||
@@ -213,6 +241,7 @@ export class ConfigService {
|
||||
}
|
||||
}
|
||||
this.migrateAuthFields()
|
||||
this.migrateAiConfig()
|
||||
}
|
||||
|
||||
// === 状态查询 ===
|
||||
@@ -270,7 +299,9 @@ export class ConfigService {
|
||||
const inLockMode = this.isLockMode() && this.unlockPassword
|
||||
|
||||
if (ENCRYPTED_BOOL_KEYS.has(key)) {
|
||||
toStore = this.safeEncrypt(String(value)) as ConfigSchema[K]
|
||||
const boolValue = value === true || value === 'true'
|
||||
// `false` 不需要写入 keychain,避免无意义触发 macOS 钥匙串弹窗
|
||||
toStore = (boolValue ? this.safeEncrypt('true') : false) as ConfigSchema[K]
|
||||
} else if (ENCRYPTED_NUMBER_KEYS.has(key)) {
|
||||
if (inLockMode && LOCKABLE_NUMBER_KEYS.has(key)) {
|
||||
toStore = this.lockEncrypt(String(value), this.unlockPassword!) as ConfigSchema[K]
|
||||
@@ -649,7 +680,7 @@ export class ConfigService {
|
||||
|
||||
clearHelloSecret(): void {
|
||||
this.store.set('authHelloSecret', '' as any)
|
||||
this.store.set('authUseHello', this.safeEncrypt('false') as any)
|
||||
this.store.set('authUseHello', false as any)
|
||||
}
|
||||
|
||||
// === 迁移 ===
|
||||
@@ -658,13 +689,18 @@ export class ConfigService {
|
||||
// 将旧版明文 auth 字段迁移为 safeStorage 加密格式
|
||||
// 如果已经是 safe: 或 lock: 前缀则跳过
|
||||
const rawEnabled: any = this.store.get('authEnabled')
|
||||
if (typeof rawEnabled === 'boolean') {
|
||||
this.store.set('authEnabled', this.safeEncrypt(String(rawEnabled)) as any)
|
||||
if (rawEnabled === true || rawEnabled === 'true') {
|
||||
this.store.set('authEnabled', this.safeEncrypt('true') as any)
|
||||
} else if (rawEnabled === false || rawEnabled === 'false') {
|
||||
// 保持 false 为明文布尔,避免冷启动访问 keychain
|
||||
this.store.set('authEnabled', false as any)
|
||||
}
|
||||
|
||||
const rawUseHello: any = this.store.get('authUseHello')
|
||||
if (typeof rawUseHello === 'boolean') {
|
||||
this.store.set('authUseHello', this.safeEncrypt(String(rawUseHello)) as any)
|
||||
if (rawUseHello === true || rawUseHello === 'true') {
|
||||
this.store.set('authUseHello', this.safeEncrypt('true') as any)
|
||||
} else if (rawUseHello === false || rawUseHello === 'false') {
|
||||
this.store.set('authUseHello', false as any)
|
||||
}
|
||||
|
||||
const rawPassword: any = this.store.get('authPassword')
|
||||
@@ -710,6 +746,26 @@ export class ConfigService {
|
||||
}
|
||||
}
|
||||
|
||||
private migrateAiConfig(): void {
|
||||
const sharedBaseUrl = String(this.get('aiModelApiBaseUrl') || '').trim()
|
||||
const sharedApiKey = String(this.get('aiModelApiKey') || '').trim()
|
||||
const sharedModel = String(this.get('aiModelApiModel') || '').trim()
|
||||
|
||||
const legacyBaseUrl = String(this.get('aiInsightApiBaseUrl') || '').trim()
|
||||
const legacyApiKey = String(this.get('aiInsightApiKey') || '').trim()
|
||||
const legacyModel = String(this.get('aiInsightApiModel') || '').trim()
|
||||
|
||||
if (!sharedBaseUrl && legacyBaseUrl) {
|
||||
this.set('aiModelApiBaseUrl', legacyBaseUrl)
|
||||
}
|
||||
if (!sharedApiKey && legacyApiKey) {
|
||||
this.set('aiModelApiKey', legacyApiKey)
|
||||
}
|
||||
if (!sharedModel && legacyModel) {
|
||||
this.set('aiModelApiModel', legacyModel)
|
||||
}
|
||||
}
|
||||
|
||||
// === 验证 ===
|
||||
|
||||
verifyAuthEnabled(): boolean {
|
||||
@@ -729,7 +785,7 @@ export class ConfigService {
|
||||
// === 工具方法 ===
|
||||
|
||||
/**
|
||||
* 获取当前 wxid 对应的图片密钥,优先从 wxidConfigs 中取,找不到则回退到全局<EFBFBD><EFBFBD>置
|
||||
* 获取当前 wxid 对应的图片密钥,优先从 wxidConfigs 中取,找不到则回退到全局配置
|
||||
*/
|
||||
getImageKeysForCurrentWxid(): { xorKey: unknown; aesKey: string } {
|
||||
const wxid = this.get('myWxid')
|
||||
|
||||
@@ -19,7 +19,8 @@ class ExportRecordService {
|
||||
|
||||
private resolveFilePath(): string {
|
||||
if (this.filePath) return this.filePath
|
||||
const userDataPath = app.getPath('userData')
|
||||
const workerUserDataPath = String(process.env.WEFLOW_USER_DATA_PATH || process.env.WEFLOW_CONFIG_CWD || '').trim()
|
||||
const userDataPath = workerUserDataPath || app?.getPath?.('userData') || process.cwd()
|
||||
fs.mkdirSync(userDataPath, { recursive: true })
|
||||
this.filePath = path.join(userDataPath, 'weflow-export-records.json')
|
||||
return this.filePath
|
||||
|
||||
@@ -92,6 +92,7 @@ export interface ExportOptions {
|
||||
dateRange?: { start: number; end: number } | null
|
||||
senderUsername?: string
|
||||
fileNameSuffix?: string
|
||||
fileNamingMode?: 'classic' | 'date-range'
|
||||
exportMedia?: boolean
|
||||
exportAvatars?: boolean
|
||||
exportImages?: boolean
|
||||
@@ -494,6 +495,80 @@ class ExportService {
|
||||
}
|
||||
}
|
||||
|
||||
private sanitizeExportFileNamePart(value: string): string {
|
||||
return String(value || '')
|
||||
.replace(/[<>:"\/\\|?*]/g, '_')
|
||||
.replace(/\.+$/, '')
|
||||
.trim()
|
||||
}
|
||||
|
||||
private normalizeFileNamingMode(value: unknown): 'classic' | 'date-range' {
|
||||
return String(value || '').trim().toLowerCase() === 'date-range' ? 'date-range' : 'classic'
|
||||
}
|
||||
|
||||
private formatDateTokenBySeconds(seconds?: number): string | null {
|
||||
if (!Number.isFinite(seconds) || (seconds || 0) <= 0) return null
|
||||
const date = new Date(Math.floor(Number(seconds)) * 1000)
|
||||
if (Number.isNaN(date.getTime())) return null
|
||||
const y = date.getFullYear()
|
||||
const m = `${date.getMonth() + 1}`.padStart(2, '0')
|
||||
const d = `${date.getDate()}`.padStart(2, '0')
|
||||
return `${y}${m}${d}`
|
||||
}
|
||||
|
||||
private buildDateRangeFileNamePart(dateRange?: { start: number; end: number } | null): string {
|
||||
const start = this.formatDateTokenBySeconds(dateRange?.start)
|
||||
const end = this.formatDateTokenBySeconds(dateRange?.end)
|
||||
if (start && end) {
|
||||
if (start === end) return start
|
||||
return start < end ? `${start}-${end}` : `${end}-${start}`
|
||||
}
|
||||
if (start) return `${start}-至今`
|
||||
if (end) return `截至-${end}`
|
||||
return '全部时间'
|
||||
}
|
||||
|
||||
private buildSessionExportBaseName(
|
||||
sessionId: string,
|
||||
displayName: string,
|
||||
options: ExportOptions
|
||||
): string {
|
||||
const baseName = this.sanitizeExportFileNamePart(displayName || sessionId) || this.sanitizeExportFileNamePart(sessionId) || 'session'
|
||||
const suffix = this.sanitizeExportFileNamePart(options.fileNameSuffix || '')
|
||||
const namingMode = this.normalizeFileNamingMode(options.fileNamingMode)
|
||||
const parts = [baseName]
|
||||
if (suffix) parts.push(suffix)
|
||||
if (namingMode === 'date-range') {
|
||||
parts.push(this.buildDateRangeFileNamePart(options.dateRange))
|
||||
}
|
||||
return this.sanitizeExportFileNamePart(parts.join('_')) || 'session'
|
||||
}
|
||||
|
||||
private async reserveUniqueOutputPath(preferredPath: string, reservedPaths: Set<string>): Promise<string> {
|
||||
const dir = path.dirname(preferredPath)
|
||||
const ext = path.extname(preferredPath)
|
||||
const base = path.basename(preferredPath, ext)
|
||||
|
||||
for (let attempt = 0; attempt < 10000; attempt += 1) {
|
||||
const candidate = attempt === 0
|
||||
? preferredPath
|
||||
: path.join(dir, `${base}_${attempt + 1}${ext}`)
|
||||
|
||||
if (reservedPaths.has(candidate)) continue
|
||||
|
||||
const exists = await this.pathExists(candidate)
|
||||
if (reservedPaths.has(candidate)) continue
|
||||
if (exists) continue
|
||||
|
||||
reservedPaths.add(candidate)
|
||||
return candidate
|
||||
}
|
||||
|
||||
const fallback = path.join(dir, `${base}_${Date.now()}${ext}`)
|
||||
reservedPaths.add(fallback)
|
||||
return fallback
|
||||
}
|
||||
|
||||
private isCloneUnsupportedError(code: string | undefined): boolean {
|
||||
return code === 'ENOTSUP' || code === 'ENOSYS' || code === 'EINVAL' || code === 'EXDEV' || code === 'ENOTTY'
|
||||
}
|
||||
@@ -2044,6 +2119,7 @@ class ExportService {
|
||||
}
|
||||
return title || '[引用消息]'
|
||||
}
|
||||
if (xmlType === '53') return title ? `[接龙] ${title.split(/\r?\n/).map(line => line.trim()).find(Boolean) || title}` : '[接龙]'
|
||||
if (xmlType === '5' || xmlType === '49') return title ? `[链接] ${title}` : '[链接]'
|
||||
|
||||
// 有 title 就返回 title
|
||||
@@ -3145,6 +3221,8 @@ class ExportService {
|
||||
appMsgKind = 'announcement'
|
||||
} else if (xmlType === '57' || hasReferMsg || localType === 244813135921) {
|
||||
appMsgKind = 'quote'
|
||||
} else if (xmlType === '53') {
|
||||
appMsgKind = 'solitaire'
|
||||
} else if (xmlType === '5' || xmlType === '49') {
|
||||
appMsgKind = 'link'
|
||||
} else if (looksLikeAppMsg) {
|
||||
@@ -8911,6 +8989,7 @@ class ExportService {
|
||||
? path.join(outputDir, 'texts')
|
||||
: outputDir
|
||||
const createdTaskDirs = new Set<string>()
|
||||
const reservedOutputPaths = new Set<string>()
|
||||
const ensureTaskDir = async (dirPath: string) => {
|
||||
if (createdTaskDirs.has(dirPath)) return
|
||||
await fs.promises.mkdir(dirPath, { recursive: true })
|
||||
@@ -9159,10 +9238,8 @@ class ExportService {
|
||||
phaseLabel: '准备导出'
|
||||
})
|
||||
|
||||
const sanitizeName = (value: string) => value.replace(/[<>:"\/\\|?*]/g, '_').replace(/\.+$/, '').trim()
|
||||
const baseName = sanitizeName(sessionInfo.displayName || sessionId) || sanitizeName(sessionId) || 'session'
|
||||
const suffix = sanitizeName(effectiveOptions.fileNameSuffix || '')
|
||||
const safeName = suffix ? `${baseName}_${suffix}` : baseName
|
||||
const fileNamingMode = this.normalizeFileNamingMode(effectiveOptions.fileNamingMode)
|
||||
const safeName = this.buildSessionExportBaseName(sessionId, sessionInfo.displayName, effectiveOptions)
|
||||
const sessionNameWithTypePrefix = effectiveOptions.sessionNameWithTypePrefix !== false
|
||||
const sessionTypePrefix = sessionNameWithTypePrefix ? await this.getSessionFilePrefix(sessionId) : ''
|
||||
const fileNameWithPrefix = `${sessionTypePrefix}${safeName}`
|
||||
@@ -9180,13 +9257,13 @@ class ExportService {
|
||||
else if (effectiveOptions.format === 'txt') ext = '.txt'
|
||||
else if (effectiveOptions.format === 'weclone') ext = '.csv'
|
||||
else if (effectiveOptions.format === 'html') ext = '.html'
|
||||
const outputPath = path.join(sessionDir, `${fileNameWithPrefix}${ext}`)
|
||||
const preferredOutputPath = path.join(sessionDir, `${fileNameWithPrefix}${ext}`)
|
||||
const canTrySkipUnchanged = canTrySkipUnchangedTextSessions &&
|
||||
typeof messageCountHint === 'number' &&
|
||||
messageCountHint >= 0 &&
|
||||
typeof latestTimestampHint === 'number' &&
|
||||
latestTimestampHint > 0 &&
|
||||
await this.pathExists(outputPath)
|
||||
await this.pathExists(preferredOutputPath)
|
||||
if (canTrySkipUnchanged) {
|
||||
const latestRecord = exportRecordService.getLatestRecord(sessionId, effectiveOptions.format)
|
||||
const hasNoDataChange = Boolean(
|
||||
@@ -9213,6 +9290,10 @@ class ExportService {
|
||||
}
|
||||
}
|
||||
|
||||
const outputPath = fileNamingMode === 'date-range'
|
||||
? await this.reserveUniqueOutputPath(preferredOutputPath, reservedOutputPaths)
|
||||
: preferredOutputPath
|
||||
|
||||
let result: { success: boolean; error?: string }
|
||||
if (effectiveOptions.format === 'json' || effectiveOptions.format === 'arkme-json') {
|
||||
result = await this.exportSessionToDetailedJson(sessionId, outputPath, effectiveOptions, sessionProgress, control)
|
||||
|
||||
@@ -949,7 +949,7 @@ export class ImageDecryptService {
|
||||
} catch { }
|
||||
}
|
||||
|
||||
// --- 绛栫暐 B: 鏂扮増 Session 鍝堝笇璺緞鐚滄祴 ---
|
||||
// --- 策略 B: 新版 Session 哈希路径猜测 ---
|
||||
try {
|
||||
const entries = await fs.readdir(root, { withFileTypes: true })
|
||||
const sessionDirs = entries
|
||||
@@ -1854,7 +1854,7 @@ export class ImageDecryptService {
|
||||
}
|
||||
|
||||
/**
|
||||
* 浠?wxgf 鏁版嵁涓彁鍙?HEVC NALU 瑁告祦
|
||||
* 从 wxgf 数据中提取 HEVC NALU 裸流
|
||||
*/
|
||||
private extractHevcNalu(buffer: Buffer): Buffer | null {
|
||||
const nalUnits: Buffer[] = []
|
||||
|
||||
@@ -15,8 +15,10 @@
|
||||
|
||||
import https from 'https'
|
||||
import http from 'http'
|
||||
import fs from 'fs'
|
||||
import path from 'path'
|
||||
import { URL } from 'url'
|
||||
import { Notification } from 'electron'
|
||||
import { app, Notification } from 'electron'
|
||||
import { ConfigService } from './config'
|
||||
import { chatService, ChatSession, Message } from './chatService'
|
||||
|
||||
@@ -33,12 +35,17 @@ const SILENCE_SCAN_INITIAL_DELAY_MS = 3 * 60 * 1000
|
||||
|
||||
/** 单次 API 请求超时(毫秒) */
|
||||
const API_TIMEOUT_MS = 45_000
|
||||
const API_MAX_TOKENS = 200
|
||||
const API_TEMPERATURE = 0.7
|
||||
|
||||
/** 沉默天数阈值默认值 */
|
||||
const DEFAULT_SILENCE_DAYS = 3
|
||||
const INSIGHT_CONFIG_KEYS = new Set([
|
||||
'aiInsightEnabled',
|
||||
'aiInsightScanIntervalHours',
|
||||
'aiModelApiBaseUrl',
|
||||
'aiModelApiKey',
|
||||
'aiModelApiModel',
|
||||
'dbPath',
|
||||
'decryptKey',
|
||||
'myWxid'
|
||||
@@ -51,17 +58,82 @@ interface TodayTriggerRecord {
|
||||
timestamps: number[]
|
||||
}
|
||||
|
||||
interface SharedAiModelConfig {
|
||||
apiBaseUrl: string
|
||||
apiKey: string
|
||||
model: string
|
||||
}
|
||||
|
||||
// ─── 日志 ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
type InsightLogLevel = 'INFO' | 'WARN' | 'ERROR'
|
||||
|
||||
let debugLogWriteQueue: Promise<void> = Promise.resolve()
|
||||
|
||||
function formatDebugTimestamp(date: Date = new Date()): string {
|
||||
const year = date.getFullYear()
|
||||
const month = String(date.getMonth() + 1).padStart(2, '0')
|
||||
const day = String(date.getDate()).padStart(2, '0')
|
||||
const hours = String(date.getHours()).padStart(2, '0')
|
||||
const minutes = String(date.getMinutes()).padStart(2, '0')
|
||||
const seconds = String(date.getSeconds()).padStart(2, '0')
|
||||
return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
|
||||
}
|
||||
|
||||
function getInsightDebugLogFilePath(date: Date = new Date()): string {
|
||||
const year = date.getFullYear()
|
||||
const month = String(date.getMonth() + 1).padStart(2, '0')
|
||||
const day = String(date.getDate()).padStart(2, '0')
|
||||
return path.join(app.getPath('desktop'), `weflow-ai-insight-debug-${year}-${month}-${day}.log`)
|
||||
}
|
||||
|
||||
function isInsightDebugLogEnabled(): boolean {
|
||||
try {
|
||||
return ConfigService.getInstance().get('aiInsightDebugLogEnabled') === true
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
function appendInsightDebugText(text: string): void {
|
||||
if (!isInsightDebugLogEnabled()) return
|
||||
|
||||
let logFilePath = ''
|
||||
try {
|
||||
logFilePath = getInsightDebugLogFilePath()
|
||||
} catch {
|
||||
return
|
||||
}
|
||||
|
||||
debugLogWriteQueue = debugLogWriteQueue
|
||||
.then(() => fs.promises.appendFile(logFilePath, text, 'utf8'))
|
||||
.catch(() => undefined)
|
||||
}
|
||||
|
||||
function insightDebugLine(level: InsightLogLevel, message: string): void {
|
||||
appendInsightDebugText(`[${formatDebugTimestamp()}] [${level}] ${message}\n`)
|
||||
}
|
||||
|
||||
function insightDebugSection(level: InsightLogLevel, title: string, payload: unknown): void {
|
||||
const content = typeof payload === 'string'
|
||||
? payload
|
||||
: JSON.stringify(payload, null, 2)
|
||||
|
||||
appendInsightDebugText(
|
||||
`\n========== [${formatDebugTimestamp()}] [${level}] ${title} ==========\n${content}\n========== END ==========\n`
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 仅输出到 console,不落盘到文件。
|
||||
*/
|
||||
function insightLog(level: 'INFO' | 'WARN' | 'ERROR', message: string): void {
|
||||
function insightLog(level: InsightLogLevel, message: string): void {
|
||||
if (level === 'ERROR' || level === 'WARN') {
|
||||
console.warn(`[InsightService] ${message}`)
|
||||
} else {
|
||||
console.log(`[InsightService] ${message}`)
|
||||
}
|
||||
insightDebugLine(level, message)
|
||||
}
|
||||
|
||||
// ─── 工具函数 ─────────────────────────────────────────────────────────────────
|
||||
@@ -118,8 +190,8 @@ function callApi(
|
||||
const body = JSON.stringify({
|
||||
model,
|
||||
messages,
|
||||
max_tokens: 200,
|
||||
temperature: 0.7,
|
||||
max_tokens: API_MAX_TOKENS,
|
||||
temperature: API_TEMPERATURE,
|
||||
stream: false
|
||||
})
|
||||
|
||||
@@ -316,28 +388,46 @@ class InsightService {
|
||||
}
|
||||
|
||||
/**
|
||||
* 测<EFBFBD><EFBFBD><EFBFBD> API 连接,返回 { success, message }。
|
||||
* 测试 API 连接,返回 { success, message }。
|
||||
* 供设置页"测试连接"按钮调用。
|
||||
*/
|
||||
async testConnection(): Promise<{ success: boolean; message: string }> {
|
||||
const apiBaseUrl = this.config.get('aiInsightApiBaseUrl') as string
|
||||
const apiKey = this.config.get('aiInsightApiKey') as string
|
||||
const model = (this.config.get('aiInsightApiModel') as string) || 'gpt-4o-mini'
|
||||
const { apiBaseUrl, apiKey, model } = this.getSharedAiModelConfig()
|
||||
|
||||
if (!apiBaseUrl || !apiKey) {
|
||||
return { success: false, message: '请先填写 API 地址和 API Key' }
|
||||
}
|
||||
|
||||
try {
|
||||
const endpoint = buildApiUrl(apiBaseUrl, '/chat/completions')
|
||||
const requestMessages = [{ role: 'user', content: '请回复"连接成功"四个字。' }]
|
||||
insightDebugSection(
|
||||
'INFO',
|
||||
'AI 测试连接请求',
|
||||
[
|
||||
`Endpoint: ${endpoint}`,
|
||||
`Model: ${model}`,
|
||||
'',
|
||||
'用户提示词:',
|
||||
requestMessages[0].content
|
||||
].join('\n')
|
||||
)
|
||||
|
||||
const result = await callApi(
|
||||
apiBaseUrl,
|
||||
apiKey,
|
||||
model,
|
||||
[{ role: 'user', content: '请回复"连接成功"四个字。' }],
|
||||
requestMessages,
|
||||
15_000
|
||||
)
|
||||
insightDebugSection('INFO', 'AI 测试连接输出原文', result)
|
||||
return { success: true, message: `连接成功,模型回复:${result.slice(0, 50)}` }
|
||||
} catch (e) {
|
||||
insightDebugSection(
|
||||
'ERROR',
|
||||
'AI 测试连接失败',
|
||||
`错误信息:${(e as Error).message}\n\n堆栈:\n${(e as Error).stack || '[无堆栈]'}`
|
||||
)
|
||||
return { success: false, message: `连接失败:${(e as Error).message}` }
|
||||
}
|
||||
}
|
||||
@@ -348,8 +438,7 @@ class InsightService {
|
||||
*/
|
||||
async triggerTest(): Promise<{ success: boolean; message: string }> {
|
||||
insightLog('INFO', '手动触发测试见解...')
|
||||
const apiBaseUrl = this.config.get('aiInsightApiBaseUrl') as string
|
||||
const apiKey = this.config.get('aiInsightApiKey') as string
|
||||
const { apiBaseUrl, apiKey } = this.getSharedAiModelConfig()
|
||||
if (!apiBaseUrl || !apiKey) {
|
||||
return { success: false, message: '请先填写 API 地址和 Key' }
|
||||
}
|
||||
@@ -398,12 +487,223 @@ class InsightService {
|
||||
return result
|
||||
}
|
||||
|
||||
async generateFootprintInsight(params: {
|
||||
rangeLabel: string
|
||||
summary: {
|
||||
private_inbound_people?: number
|
||||
private_replied_people?: number
|
||||
private_outbound_people?: number
|
||||
private_reply_rate?: number
|
||||
mention_count?: number
|
||||
mention_group_count?: number
|
||||
}
|
||||
privateSegments?: Array<{ displayName?: string; session_id?: string; incoming_count?: number; outgoing_count?: number; message_count?: number; replied?: boolean }>
|
||||
mentionGroups?: Array<{ displayName?: string; session_id?: string; count?: number }>
|
||||
}): Promise<{ success: boolean; message: string; insight?: string }> {
|
||||
const enabled = this.config.get('aiFootprintEnabled') === true
|
||||
if (!enabled) {
|
||||
return { success: false, message: '请先在设置中开启「AI 足迹总结」' }
|
||||
}
|
||||
|
||||
const { apiBaseUrl, apiKey, model } = this.getSharedAiModelConfig()
|
||||
if (!apiBaseUrl || !apiKey) {
|
||||
return { success: false, message: '请先填写通用 AI 模型配置(API 地址和 Key)' }
|
||||
}
|
||||
|
||||
const summary = params?.summary || {}
|
||||
const rangeLabel = String(params?.rangeLabel || '').trim() || '当前范围'
|
||||
const privateSegments = Array.isArray(params?.privateSegments) ? params.privateSegments.slice(0, 6) : []
|
||||
const mentionGroups = Array.isArray(params?.mentionGroups) ? params.mentionGroups.slice(0, 6) : []
|
||||
|
||||
const topPrivateText = privateSegments.length > 0
|
||||
? privateSegments
|
||||
.map((item, idx) => {
|
||||
const name = String(item.displayName || item.session_id || `联系人${idx + 1}`).trim()
|
||||
const inbound = Number(item.incoming_count) || 0
|
||||
const outbound = Number(item.outgoing_count) || 0
|
||||
const total = Math.max(Number(item.message_count) || 0, inbound + outbound)
|
||||
return `${idx + 1}. ${name}(收${inbound}/发${outbound}/总${total}${item.replied ? '/已回复' : ''})`
|
||||
})
|
||||
.join('\n')
|
||||
: '无'
|
||||
|
||||
const topMentionText = mentionGroups.length > 0
|
||||
? mentionGroups
|
||||
.map((item, idx) => {
|
||||
const name = String(item.displayName || item.session_id || `群聊${idx + 1}`).trim()
|
||||
const count = Number(item.count) || 0
|
||||
return `${idx + 1}. ${name}(@我 ${count} 次)`
|
||||
})
|
||||
.join('\n')
|
||||
: '无'
|
||||
|
||||
const defaultSystemPrompt = `你是用户的聊天足迹教练,负责基于统计数据给出一段简明复盘。
|
||||
要求:
|
||||
1. 输出 2-3 句,总长度不超过 180 字。
|
||||
2. 必须包含:总体观察 + 一个可执行建议。
|
||||
3. 语气务实,不夸张,不使用 Markdown。`
|
||||
const customPrompt = String(this.config.get('aiFootprintSystemPrompt') || '').trim()
|
||||
const systemPrompt = customPrompt || defaultSystemPrompt
|
||||
|
||||
const userPrompt = `统计范围:${rangeLabel}
|
||||
有聊天的人数:${Number(summary.private_inbound_people) || 0}
|
||||
我有回复的人数:${Number(summary.private_outbound_people) || 0}
|
||||
回复率:${(((Number(summary.private_reply_rate) || 0) * 100)).toFixed(1)}%
|
||||
@我次数:${Number(summary.mention_count) || 0}
|
||||
涉及群聊:${Number(summary.mention_group_count) || 0}
|
||||
|
||||
私聊重点:
|
||||
${topPrivateText}
|
||||
|
||||
群聊@我重点:
|
||||
${topMentionText}
|
||||
|
||||
请给出足迹复盘(2-3句,含建议):`
|
||||
|
||||
try {
|
||||
const result = await callApi(
|
||||
apiBaseUrl,
|
||||
apiKey,
|
||||
model,
|
||||
[
|
||||
{ role: 'system', content: systemPrompt },
|
||||
{ role: 'user', content: userPrompt }
|
||||
],
|
||||
25_000
|
||||
)
|
||||
const insight = result.trim().slice(0, 400)
|
||||
if (!insight) return { success: false, message: '模型返回为空' }
|
||||
return { success: true, message: '生成成功', insight }
|
||||
} catch (error) {
|
||||
return { success: false, message: `生成失败:${(error as Error).message}` }
|
||||
}
|
||||
}
|
||||
|
||||
// ── 私有方法 ────────────────────────────────────────────────────────────────
|
||||
|
||||
private isEnabled(): boolean {
|
||||
return this.config.get('aiInsightEnabled') === true
|
||||
}
|
||||
|
||||
private getSharedAiModelConfig(): SharedAiModelConfig {
|
||||
const apiBaseUrl = String(
|
||||
this.config.get('aiModelApiBaseUrl')
|
||||
|| this.config.get('aiInsightApiBaseUrl')
|
||||
|| ''
|
||||
).trim()
|
||||
const apiKey = String(
|
||||
this.config.get('aiModelApiKey')
|
||||
|| this.config.get('aiInsightApiKey')
|
||||
|| ''
|
||||
).trim()
|
||||
const model = String(
|
||||
this.config.get('aiModelApiModel')
|
||||
|| this.config.get('aiInsightApiModel')
|
||||
|| 'gpt-4o-mini'
|
||||
).trim() || 'gpt-4o-mini'
|
||||
|
||||
return { apiBaseUrl, apiKey, model }
|
||||
}
|
||||
|
||||
private looksLikeWxid(text: string): boolean {
|
||||
const normalized = String(text || '').trim()
|
||||
if (!normalized) return false
|
||||
return /^wxid_[a-z0-9]+$/i.test(normalized)
|
||||
|| /^[a-z0-9_]+@chatroom$/i.test(normalized)
|
||||
}
|
||||
|
||||
private looksLikeXmlPayload(text: string): boolean {
|
||||
const normalized = String(text || '').trim()
|
||||
if (!normalized) return false
|
||||
return /^(<\?xml|<msg\b|<appmsg\b|<img\b|<emoji\b|<voip\b|<sysmsg\b|<\?xml|<msg\b|<appmsg\b)/i.test(normalized)
|
||||
}
|
||||
|
||||
private normalizeInsightText(text: string): string {
|
||||
return String(text || '')
|
||||
.replace(/\r\n/g, '\n')
|
||||
.replace(/\u0000/g, '')
|
||||
.replace(/\n{3,}/g, '\n\n')
|
||||
.trim()
|
||||
}
|
||||
|
||||
private formatInsightMessageTimestamp(createTime: number): string {
|
||||
const ms = createTime > 1_000_000_000_000 ? createTime : createTime * 1000
|
||||
const date = new Date(ms)
|
||||
const year = date.getFullYear()
|
||||
const month = String(date.getMonth() + 1).padStart(2, '0')
|
||||
const day = String(date.getDate()).padStart(2, '0')
|
||||
const hours = String(date.getHours()).padStart(2, '0')
|
||||
const minutes = String(date.getMinutes()).padStart(2, '0')
|
||||
const seconds = String(date.getSeconds()).padStart(2, '0')
|
||||
return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
|
||||
}
|
||||
|
||||
private async resolveInsightSessionDisplayName(sessionId: string, fallbackDisplayName: string): Promise<string> {
|
||||
const fallback = String(fallbackDisplayName || '').trim()
|
||||
if (fallback && !this.looksLikeWxid(fallback)) {
|
||||
return fallback
|
||||
}
|
||||
|
||||
try {
|
||||
const sessions = await this.getSessionsCached()
|
||||
const matched = sessions.find((session) => String(session.username || '').trim() === sessionId)
|
||||
const cachedDisplayName = String(matched?.displayName || '').trim()
|
||||
if (cachedDisplayName && !this.looksLikeWxid(cachedDisplayName)) {
|
||||
return cachedDisplayName
|
||||
}
|
||||
} catch {
|
||||
// ignore display name lookup failures
|
||||
}
|
||||
|
||||
try {
|
||||
const contact = await chatService.getContactAvatar(sessionId)
|
||||
const contactDisplayName = String(contact?.displayName || '').trim()
|
||||
if (contactDisplayName && !this.looksLikeWxid(contactDisplayName)) {
|
||||
return contactDisplayName
|
||||
}
|
||||
} catch {
|
||||
// ignore display name lookup failures
|
||||
}
|
||||
|
||||
return fallback || sessionId
|
||||
}
|
||||
|
||||
private formatInsightMessageContent(message: Message): string {
|
||||
const parsedContent = this.normalizeInsightText(String(message.parsedContent || ''))
|
||||
const quotedPreview = this.normalizeInsightText(String(message.quotedContent || ''))
|
||||
const quotedSender = this.normalizeInsightText(String(message.quotedSender || ''))
|
||||
|
||||
if (quotedPreview) {
|
||||
const cleanQuotedSender = quotedSender && !this.looksLikeWxid(quotedSender) ? quotedSender : ''
|
||||
const quoteLabel = cleanQuotedSender ? `${cleanQuotedSender}:${quotedPreview}` : quotedPreview
|
||||
const replyText = parsedContent && parsedContent !== '[引用消息]' ? parsedContent : ''
|
||||
return replyText ? `${replyText}[引用 ${quoteLabel}]` : `[引用 ${quoteLabel}]`
|
||||
}
|
||||
|
||||
if (parsedContent) {
|
||||
return parsedContent
|
||||
}
|
||||
|
||||
const rawContent = this.normalizeInsightText(String(message.rawContent || ''))
|
||||
if (rawContent && !this.looksLikeXmlPayload(rawContent)) {
|
||||
return rawContent
|
||||
}
|
||||
|
||||
return '[其他消息]'
|
||||
}
|
||||
|
||||
private buildInsightContextSection(messages: Message[], peerDisplayName: string): string {
|
||||
if (!messages.length) return ''
|
||||
|
||||
const lines = messages.map((message) => {
|
||||
const senderName = message.isSend === 1 ? '我' : peerDisplayName
|
||||
const content = this.formatInsightMessageContent(message)
|
||||
return `${this.formatInsightMessageTimestamp(message.createTime)} '${senderName}'\n${content}`
|
||||
})
|
||||
|
||||
return `近期聊天记录(最近 ${lines.length} 条):\n\n${lines.join('\n\n')}`
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断某个会话是否允许触发见解。
|
||||
* 若白名单未启用,则所有私聊会话均允许;
|
||||
@@ -475,7 +775,7 @@ class InsightService {
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取今日全局已触发次数(所有会话合计),用于 prompt 中告知模<EFBFBD><EFBFBD><EFBFBD>全局上下文。
|
||||
* 获取今日全局已触发次数(所有会话合计),用于 prompt 中告知模型全局上下文。
|
||||
*/
|
||||
private getTodayTotalTriggerCount(): number {
|
||||
this.resetIfNewDay()
|
||||
@@ -696,11 +996,10 @@ class InsightService {
|
||||
if (!sessionId) return
|
||||
if (!this.isEnabled()) return
|
||||
|
||||
const apiBaseUrl = this.config.get('aiInsightApiBaseUrl') as string
|
||||
const apiKey = this.config.get('aiInsightApiKey') as string
|
||||
const model = (this.config.get('aiInsightApiModel') as string) || 'gpt-4o-mini'
|
||||
const { apiBaseUrl, apiKey, model } = this.getSharedAiModelConfig()
|
||||
const allowContext = this.config.get('aiInsightAllowContext') as boolean
|
||||
const contextCount = (this.config.get('aiInsightContextCount') as number) || 40
|
||||
const resolvedDisplayName = await this.resolveInsightSessionDisplayName(sessionId, displayName)
|
||||
|
||||
insightLog('INFO', `generateInsightForSession: sessionId=${sessionId}, reason=${triggerReason}, contextCount=${contextCount}, api=${apiBaseUrl ? '已配置' : '未配置'}`)
|
||||
|
||||
@@ -709,7 +1008,7 @@ class InsightService {
|
||||
return
|
||||
}
|
||||
|
||||
// ── 构建 prompt ─────────────<EFBFBD><EFBFBD><EFBFBD>───────────────────────────────<EFBFBD><EFBFBD><EFBFBD>────────────
|
||||
// ── 构建 prompt ────────────────────────────────────────────────────────────
|
||||
|
||||
// 今日触发统计(让模型具备时间与克制感)
|
||||
const sessionTriggerTimes = this.recordTrigger(sessionId)
|
||||
@@ -721,14 +1020,8 @@ class InsightService {
|
||||
const msgsResult = await chatService.getLatestMessages(sessionId, contextCount)
|
||||
if (msgsResult.success && msgsResult.messages && msgsResult.messages.length > 0) {
|
||||
const messages: Message[] = msgsResult.messages
|
||||
const msgLines = messages.map((m) => {
|
||||
const sender = m.isSend === 1 ? '我' : (displayName || sessionId)
|
||||
const content = m.rawContent || m.parsedContent || '[非文字消息]'
|
||||
const time = new Date(Number(m.createTime) * 1000).toLocaleString('zh-CN')
|
||||
return `[${time}] ${sender}:${content}`
|
||||
})
|
||||
contextSection = `\n\n近期对话记录(最近 ${msgLines.length} 条):\n${msgLines.join('\n')}`
|
||||
insightLog('INFO', `已加载 ${msgLines.length} 条上下文消息`)
|
||||
contextSection = this.buildInsightContextSection(messages, resolvedDisplayName)
|
||||
insightLog('INFO', `已加载 ${messages.length} 条上下文消息`)
|
||||
}
|
||||
} catch (e) {
|
||||
insightLog('WARN', `拉取上下文失败: ${(e as Error).message}`)
|
||||
@@ -752,48 +1045,71 @@ class InsightService {
|
||||
// 这样 provider 端(Anthropic/OpenAI)能最大化命中 prompt cache,降低费用
|
||||
const triggerDesc =
|
||||
triggerReason === 'silence'
|
||||
? `你已经 ${silentDays} 天没有和「${displayName}」聊天了。`
|
||||
: `你最近和「${displayName}」有新的聊天动态。`
|
||||
? `你已经 ${silentDays} 天没有和「${resolvedDisplayName}」聊天了。`
|
||||
: `你最近和「${resolvedDisplayName}」有新的聊天动态。`
|
||||
|
||||
const todayStatsDesc =
|
||||
sessionTriggerTimes.length > 1
|
||||
? `今天你已经针对「${displayName}」收到过 ${sessionTriggerTimes.length - 1} 条见解(时间:${sessionTriggerTimes.slice(0, -1).join('、')}),请适当克制。`
|
||||
: `今天你还没有针对「${displayName}」发出过见解。`
|
||||
? `今天你已经针对「${resolvedDisplayName}」收到过 ${sessionTriggerTimes.length - 1} 条见解(时间:${sessionTriggerTimes.slice(0, -1).join('、')}),请适当克制。`
|
||||
: `今天你还没有针对「${resolvedDisplayName}」发出过见解。`
|
||||
|
||||
const globalStatsDesc = `今天全部联系人合计已触发 ${totalTodayTriggers} 条见解。`
|
||||
|
||||
const userPrompt = `触发原因:${triggerDesc}
|
||||
时间统计:${todayStatsDesc} ${globalStatsDesc}${contextSection}
|
||||
|
||||
请给出你的见解(≤80字):`
|
||||
const userPrompt = [
|
||||
`触发原因:${triggerDesc}`,
|
||||
`时间统计:${todayStatsDesc}`,
|
||||
`全局统计:${globalStatsDesc}`,
|
||||
contextSection,
|
||||
'请给出你的见解(≤80字):'
|
||||
].filter(Boolean).join('\n\n')
|
||||
|
||||
const endpoint = buildApiUrl(apiBaseUrl, '/chat/completions')
|
||||
const requestMessages = [
|
||||
{ role: 'system', content: systemPrompt },
|
||||
{ role: 'user', content: userPrompt }
|
||||
]
|
||||
|
||||
insightLog('INFO', `准备调用 API: ${endpoint},模型: ${model}`)
|
||||
insightDebugSection(
|
||||
'INFO',
|
||||
`AI 请求 ${resolvedDisplayName} (${sessionId})`,
|
||||
[
|
||||
`接口地址:${endpoint}`,
|
||||
`模型:${model}`,
|
||||
`触发原因:${triggerReason}`,
|
||||
`上下文开关:${allowContext ? '开启' : '关闭'}`,
|
||||
`上下文条数:${contextCount}`,
|
||||
'',
|
||||
'系统提示词:',
|
||||
systemPrompt,
|
||||
'',
|
||||
'用户提示词:',
|
||||
userPrompt
|
||||
].join('\n')
|
||||
)
|
||||
|
||||
try {
|
||||
const result = await callApi(
|
||||
apiBaseUrl,
|
||||
apiKey,
|
||||
model,
|
||||
[
|
||||
{ role: 'system', content: systemPrompt },
|
||||
{ role: 'user', content: userPrompt }
|
||||
]
|
||||
requestMessages
|
||||
)
|
||||
|
||||
insightLog('INFO', `API 返回原文: ${result.slice(0, 150)}`)
|
||||
insightDebugSection('INFO', `AI 输出原文 ${resolvedDisplayName} (${sessionId})`, result)
|
||||
|
||||
// 模型主动选择跳过
|
||||
if (result.trim().toUpperCase() === 'SKIP' || result.trim().startsWith('SKIP')) {
|
||||
insightLog('INFO', `模型选择跳过 ${displayName}`)
|
||||
insightLog('INFO', `模型选择跳过 ${resolvedDisplayName}`)
|
||||
return
|
||||
}
|
||||
if (!this.isEnabled()) return
|
||||
|
||||
const insight = result.slice(0, 120)
|
||||
const notifTitle = `见解 · ${displayName}`
|
||||
const notifTitle = `见解 · ${resolvedDisplayName}`
|
||||
|
||||
insightLog('INFO', `推送通知 → ${displayName}: ${insight}`)
|
||||
insightLog('INFO', `推送通知 → ${resolvedDisplayName}: ${insight}`)
|
||||
|
||||
// 渠道一:Electron 原生系统通知
|
||||
if (Notification.isSupported()) {
|
||||
@@ -821,9 +1137,14 @@ class InsightService {
|
||||
}
|
||||
}
|
||||
|
||||
insightLog('INFO', `已为 ${displayName} 推送见解`)
|
||||
insightLog('INFO', `已为 ${resolvedDisplayName} 推送见解`)
|
||||
} catch (e) {
|
||||
insightLog('ERROR', `API 调用失败 (${displayName}): ${(e as Error).message}`)
|
||||
insightDebugSection(
|
||||
'ERROR',
|
||||
`AI 请求失败 ${resolvedDisplayName} (${sessionId})`,
|
||||
`错误信息:${(e as Error).message}\n\n堆栈:\n${(e as Error).stack || '[无堆栈]'}`
|
||||
)
|
||||
insightLog('ERROR', `API 调用失败 (${resolvedDisplayName}): ${(e as Error).message}`)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@ import crypto from 'crypto'
|
||||
const execFileAsync = promisify(execFile)
|
||||
|
||||
type DbKeyResult = { success: boolean; key?: string; error?: string; logs?: string[] }
|
||||
type ImageKeyResult = { success: boolean; xorKey?: number; aesKey?: string; error?: string }
|
||||
type ImageKeyResult = { success: boolean; xorKey?: number; aesKey?: string; verified?: boolean; error?: string }
|
||||
|
||||
export class KeyService {
|
||||
private readonly isMac = process.platform === 'darwin'
|
||||
@@ -814,7 +814,7 @@ export class KeyService {
|
||||
if (!this.verifyDerivedAesKey(aesKey, verifyCiphertext)) continue
|
||||
onProgress?.(`密钥获取成功 (wxid: ${candidateWxid}, code: ${code})`)
|
||||
console.log('[ImageKey] 校验命中: wxid=', candidateWxid, 'code=', code)
|
||||
return { success: true, xorKey, aesKey }
|
||||
return { success: true, xorKey, aesKey, verified: true }
|
||||
}
|
||||
}
|
||||
return { success: false, error: '缓存 code 与当前账号 wxid 未匹配,请确认账号目录后重试,或使用内存扫描' }
|
||||
@@ -826,7 +826,7 @@ export class KeyService {
|
||||
const { xorKey, aesKey } = this.deriveImageKeys(fallbackCode, fallbackWxid)
|
||||
onProgress?.(`密钥获取成功 (wxid: ${fallbackWxid}, code: ${fallbackCode})`)
|
||||
console.log('[ImageKey] 回退计算: wxid=', fallbackWxid, 'code=', fallbackCode)
|
||||
return { success: true, xorKey, aesKey }
|
||||
return { success: true, xorKey, aesKey, verified: false }
|
||||
}
|
||||
|
||||
// --- 内存扫描备选方案(融合 Dart+Python 优点)---
|
||||
|
||||
@@ -3,6 +3,7 @@ import { join } from 'path'
|
||||
import { existsSync, readdirSync, statSync, readFileSync } from 'fs'
|
||||
import { execFile, exec, spawn } from 'child_process'
|
||||
import { promisify } from 'util'
|
||||
import crypto from 'crypto'
|
||||
import { createRequire } from 'module';
|
||||
const require = createRequire(import.meta.url);
|
||||
|
||||
@@ -10,7 +11,7 @@ const execFileAsync = promisify(execFile)
|
||||
const execAsync = promisify(exec)
|
||||
|
||||
type DbKeyResult = { success: boolean; key?: string; error?: string; logs?: string[] }
|
||||
type ImageKeyResult = { success: boolean; xorKey?: number; aesKey?: string; error?: string }
|
||||
type ImageKeyResult = { success: boolean; xorKey?: number; aesKey?: string; verified?: boolean; error?: string }
|
||||
|
||||
export class KeyServiceLinux {
|
||||
private sudo: any
|
||||
@@ -98,7 +99,12 @@ export class KeyServiceLinux {
|
||||
'xwechat',
|
||||
'/opt/wechat/wechat',
|
||||
'/usr/bin/wechat',
|
||||
'/opt/apps/com.tencent.wechat/files/wechat'
|
||||
'/usr/local/bin/wechat',
|
||||
'/usr/bin/wechat',
|
||||
'/opt/apps/com.tencent.wechat/files/wechat',
|
||||
'/usr/bin/wechat-bin',
|
||||
'/usr/local/bin/wechat-bin',
|
||||
'com.tencent.wechat'
|
||||
]
|
||||
|
||||
for (const binName of wechatBins) {
|
||||
@@ -152,7 +158,7 @@ export class KeyServiceLinux {
|
||||
}
|
||||
|
||||
if (!pid) {
|
||||
const err = '未能自动启动微信,或获取PID失败,请查看控制台日志或手动启动并登录。'
|
||||
const err = '未能自动启动微信,或获取PID失败,请查看控制台日志或手动启动微信,看到登录窗口后点击确认。'
|
||||
onStatus?.(err, 2)
|
||||
return { success: false, error: err }
|
||||
}
|
||||
@@ -238,7 +244,14 @@ export class KeyServiceLinux {
|
||||
if (account && account.keys && account.keys.length > 0) {
|
||||
onProgress?.(`已找到匹配的图片密钥 (wxid: ${account.wxid})`);
|
||||
const keyObj = account.keys[0]
|
||||
return { success: true, xorKey: keyObj.xorKey, aesKey: keyObj.aesKey }
|
||||
const aesKey = String(keyObj.aesKey || '')
|
||||
const verified = await this.verifyImageKeyByTemplate(accountPath, aesKey)
|
||||
if (verified === true) {
|
||||
onProgress?.('缓存密钥校验成功,已确认可用')
|
||||
} else if (verified === false) {
|
||||
onProgress?.('已从缓存计算密钥,但未通过本地模板校验')
|
||||
}
|
||||
return { success: true, xorKey: keyObj.xorKey, aesKey, verified: verified === true }
|
||||
}
|
||||
return { success: false, error: '未在缓存中找到匹配的图片密钥' }
|
||||
} catch (err: any) {
|
||||
@@ -246,6 +259,35 @@ export class KeyServiceLinux {
|
||||
}
|
||||
}
|
||||
|
||||
private async verifyImageKeyByTemplate(accountPath: string | undefined, aesKey: string): Promise<boolean | null> {
|
||||
const normalizedPath = String(accountPath || '').trim()
|
||||
if (!normalizedPath || !aesKey || aesKey.length < 16 || !existsSync(normalizedPath)) return null
|
||||
try {
|
||||
const template = await this._findTemplateData(normalizedPath, 32)
|
||||
if (!template.ciphertext) return null
|
||||
return this.verifyDerivedAesKey(aesKey, template.ciphertext)
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
private verifyDerivedAesKey(aesKey: string, ciphertext: Buffer): boolean {
|
||||
try {
|
||||
if (!aesKey || aesKey.length < 16 || ciphertext.length !== 16) return false
|
||||
const decipher = crypto.createDecipheriv('aes-128-ecb', Buffer.from(aesKey, 'ascii').subarray(0, 16), null)
|
||||
decipher.setAutoPadding(false)
|
||||
const dec = Buffer.concat([decipher.update(ciphertext), decipher.final()])
|
||||
if (dec[0] === 0xFF && dec[1] === 0xD8 && dec[2] === 0xFF) return true
|
||||
if (dec[0] === 0x89 && dec[1] === 0x50 && dec[2] === 0x4E && dec[3] === 0x47) return true
|
||||
if (dec[0] === 0x52 && dec[1] === 0x49 && dec[2] === 0x46 && dec[3] === 0x46) return true
|
||||
if (dec[0] === 0x77 && dec[1] === 0x78 && dec[2] === 0x67 && dec[3] === 0x66) return true
|
||||
if (dec[0] === 0x47 && dec[1] === 0x49 && dec[2] === 0x46) return true
|
||||
return false
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
public async autoGetImageKeyByMemoryScan(
|
||||
accountPath: string,
|
||||
onProgress?: (msg: string) => void
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
import { app, shell } from 'electron'
|
||||
import { join, basename, dirname } from 'path'
|
||||
import { existsSync, readdirSync, readFileSync, statSync } from 'fs'
|
||||
import { existsSync, readdirSync, readFileSync, statSync, chmodSync } from 'fs'
|
||||
import { execFile, spawn } from 'child_process'
|
||||
import { promisify } from 'util'
|
||||
import crypto from 'crypto'
|
||||
import { homedir } from 'os'
|
||||
|
||||
type DbKeyResult = { success: boolean; key?: string; error?: string; logs?: string[] }
|
||||
type ImageKeyResult = { success: boolean; xorKey?: number; aesKey?: string; error?: string }
|
||||
type ImageKeyResult = { success: boolean; xorKey?: number; aesKey?: string; verified?: boolean; error?: string }
|
||||
const execFileAsync = promisify(execFile)
|
||||
|
||||
export class KeyServiceMac {
|
||||
@@ -403,19 +403,71 @@ export class KeyServiceMac {
|
||||
return `'${String(text).replace(/'/g, `'\\''`)}'`
|
||||
}
|
||||
|
||||
private collectMacKeyArtifactPaths(primaryBinaryPath: string): string[] {
|
||||
const baseDir = dirname(primaryBinaryPath)
|
||||
const names = ['xkey_helper', 'image_scan_helper', 'xkey_helper_macos', 'libwx_key.dylib']
|
||||
const unique: string[] = []
|
||||
for (const name of names) {
|
||||
const full = join(baseDir, name)
|
||||
if (!existsSync(full)) continue
|
||||
if (!unique.includes(full)) unique.push(full)
|
||||
}
|
||||
if (existsSync(primaryBinaryPath) && !unique.includes(primaryBinaryPath)) {
|
||||
unique.unshift(primaryBinaryPath)
|
||||
}
|
||||
return unique
|
||||
}
|
||||
|
||||
private ensureExecutableBitsBestEffort(paths: string[]): void {
|
||||
for (const p of paths) {
|
||||
try {
|
||||
const mode = statSync(p).mode
|
||||
if ((mode & 0o111) !== 0) continue
|
||||
chmodSync(p, mode | 0o111)
|
||||
} catch {
|
||||
// ignore: 可能无权限(例如 /Applications 下 root-owned 的 .app)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async ensureExecutableBitsWithElevation(paths: string[], timeoutMs: number): Promise<void> {
|
||||
const existing = paths.filter(p => existsSync(p))
|
||||
if (existing.length === 0) return
|
||||
|
||||
const quotedPaths = existing.map(p => this.shellSingleQuote(p)).join(' ')
|
||||
const timeoutSec = Math.max(30, Math.ceil(timeoutMs / 1000))
|
||||
const scriptLines = [
|
||||
`set chmodCmd to "/bin/chmod +x ${quotedPaths}"`,
|
||||
`set timeoutSec to ${timeoutSec}`,
|
||||
'with timeout of timeoutSec seconds',
|
||||
'do shell script chmodCmd with administrator privileges',
|
||||
'end timeout'
|
||||
]
|
||||
|
||||
await execFileAsync('/usr/bin/osascript', scriptLines.flatMap(line => ['-e', line]), {
|
||||
timeout: timeoutMs + 10_000
|
||||
})
|
||||
}
|
||||
|
||||
private async getDbKeyByHelperElevated(
|
||||
timeoutMs: number,
|
||||
onStatus?: (message: string, level: number) => void
|
||||
): Promise<string> {
|
||||
const helperPath = this.getHelperPath()
|
||||
const artifactPaths = this.collectMacKeyArtifactPaths(helperPath)
|
||||
this.ensureExecutableBitsBestEffort(artifactPaths)
|
||||
const waitMs = Math.max(timeoutMs, 30_000)
|
||||
const timeoutSec = Math.ceil(waitMs / 1000) + 30
|
||||
const pid = await this.getWeChatPid()
|
||||
const chmodPart = artifactPaths.length > 0
|
||||
? `/bin/chmod +x ${artifactPaths.map(p => this.shellSingleQuote(p)).join(' ')}`
|
||||
: ''
|
||||
const runPart = `${this.shellSingleQuote(helperPath)} ${pid} ${waitMs}`
|
||||
const privilegedCmd = chmodPart ? `${chmodPart} && ${runPart}` : runPart
|
||||
// 用 AppleScript 的 quoted form 组装命令,避免复杂 shell 拼接导致整条失败
|
||||
// 通过 try/on error 回传详细错误,避免只看到 "Command failed"
|
||||
const scriptLines = [
|
||||
`set helperPath to ${JSON.stringify(helperPath)}`,
|
||||
`set cmd to quoted form of helperPath & " ${pid} ${waitMs}"`,
|
||||
`set cmd to ${JSON.stringify(privilegedCmd)}`,
|
||||
`set timeoutSec to ${timeoutSec}`,
|
||||
'try',
|
||||
'with timeout of timeoutSec seconds',
|
||||
@@ -503,7 +555,19 @@ export class KeyServiceMac {
|
||||
if (code === 'HOOK_TARGET_ONLY') {
|
||||
return `已定位到目标函数地址(${detail || ''}),但当前原生 C++ 仅完成定位,尚未完成远程 Hook 回调取 key 流程。`
|
||||
}
|
||||
if (code === 'SCAN_FAILED') return '内存扫描失败'
|
||||
if (code === 'SCAN_FAILED') {
|
||||
const normalizedDetail = (detail || '').trim()
|
||||
if (!normalizedDetail) {
|
||||
return '内存扫描失败:未匹配到可用特征。可能是当前微信版本更新导致,请升级 WeFlow 后重试。'
|
||||
}
|
||||
if (normalizedDetail.includes('Sink pattern not found')) {
|
||||
return '内存扫描失败:未匹配到目标函数特征,可使用微信 4.1.8.100 版本尝试。'
|
||||
}
|
||||
if (normalizedDetail.includes('No suitable module found')) {
|
||||
return '内存扫描失败:未找到可扫描的微信主模块。请确认微信已完整启动并保持前台,再重试。'
|
||||
}
|
||||
return `内存扫描失败:${normalizedDetail}`
|
||||
}
|
||||
return '未知错误'
|
||||
}
|
||||
|
||||
@@ -583,7 +647,7 @@ export class KeyServiceMac {
|
||||
const { xorKey, aesKey } = this.deriveImageKeys(code, candidateWxid)
|
||||
if (!this.verifyDerivedAesKey(aesKey, template.ciphertext)) continue
|
||||
onStatus?.(`密钥获取成功 (wxid: ${candidateWxid}, code: ${code})`)
|
||||
return { success: true, xorKey, aesKey }
|
||||
return { success: true, xorKey, aesKey, verified: true }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -598,7 +662,7 @@ export class KeyServiceMac {
|
||||
const fallbackCode = codes[0]
|
||||
const { xorKey, aesKey } = this.deriveImageKeys(fallbackCode, fallbackWxid)
|
||||
onStatus?.(`密钥获取成功 (wxid: ${fallbackWxid}, code: ${fallbackCode})`)
|
||||
return { success: true, xorKey, aesKey }
|
||||
return { success: true, xorKey, aesKey, verified: false }
|
||||
} catch (e: any) {
|
||||
return { success: false, error: `自动获取图片密钥失败: ${e.message}` }
|
||||
}
|
||||
@@ -751,10 +815,12 @@ export class KeyServiceMac {
|
||||
try {
|
||||
const helperPath = this.getImageScanHelperPath()
|
||||
const ciphertextHex = ciphertext.toString('hex')
|
||||
const artifactPaths = this.collectMacKeyArtifactPaths(helperPath)
|
||||
this.ensureExecutableBitsBestEffort(artifactPaths)
|
||||
|
||||
// 1) 直接运行 helper(有正式签名的 debugger entitlement 时可用)
|
||||
if (!this._needsElevation) {
|
||||
const direct = await this._spawnScanHelper(helperPath, pid, ciphertextHex, false)
|
||||
const direct = await this._spawnScanHelper(helperPath, pid, ciphertextHex, false, artifactPaths)
|
||||
if (direct.key) return direct.key
|
||||
if (direct.permissionError) {
|
||||
console.warn('[KeyServiceMac] task_for_pid 权限不足,切换到 osascript 提权模式')
|
||||
@@ -765,7 +831,12 @@ export class KeyServiceMac {
|
||||
|
||||
// 2) 通过 osascript 以管理员权限运行 helper(SIP 下 ad-hoc 签名无法获取 task_for_pid)
|
||||
if (this._needsElevation) {
|
||||
const elevated = await this._spawnScanHelper(helperPath, pid, ciphertextHex, true)
|
||||
try {
|
||||
await this.ensureExecutableBitsWithElevation(artifactPaths, 45_000)
|
||||
} catch (e: any) {
|
||||
console.warn('[KeyServiceMac] elevated chmod failed before image scan:', e?.message || e)
|
||||
}
|
||||
const elevated = await this._spawnScanHelper(helperPath, pid, ciphertextHex, true, artifactPaths)
|
||||
if (elevated.key) return elevated.key
|
||||
}
|
||||
} catch (e: any) {
|
||||
@@ -868,12 +939,19 @@ export class KeyServiceMac {
|
||||
}
|
||||
|
||||
private _spawnScanHelper(
|
||||
helperPath: string, pid: number, ciphertextHex: string, elevated: boolean
|
||||
helperPath: string,
|
||||
pid: number,
|
||||
ciphertextHex: string,
|
||||
elevated: boolean,
|
||||
artifactPaths: string[] = []
|
||||
): Promise<{ key: string | null; permissionError: boolean }> {
|
||||
return new Promise((resolve, reject) => {
|
||||
let child: ReturnType<typeof spawn>
|
||||
if (elevated) {
|
||||
const shellCmd = `'${helperPath}' ${pid} ${ciphertextHex}`
|
||||
const chmodPart = artifactPaths.length > 0
|
||||
? `/bin/chmod +x ${artifactPaths.map(p => this.shellSingleQuote(p)).join(' ')} && `
|
||||
: ''
|
||||
const shellCmd = `${chmodPart}${this.shellSingleQuote(helperPath)} ${pid} ${ciphertextHex}`
|
||||
child = spawn('/usr/bin/osascript', ['-e', `do shell script ${JSON.stringify(shellCmd)} with administrator privileges`],
|
||||
{ stdio: ['ignore', 'pipe', 'pipe'] })
|
||||
} else {
|
||||
|
||||
@@ -11,6 +11,7 @@ interface SessionBaseline {
|
||||
interface MessagePushPayload {
|
||||
event: 'message.new'
|
||||
sessionId: string
|
||||
sessionType: 'private' | 'group' | 'official' | 'other'
|
||||
messageKey: string
|
||||
avatarUrl?: string
|
||||
sourceName: string
|
||||
@@ -20,6 +21,8 @@ interface MessagePushPayload {
|
||||
|
||||
const PUSH_CONFIG_KEYS = new Set([
|
||||
'messagePushEnabled',
|
||||
'messagePushFilterMode',
|
||||
'messagePushFilterList',
|
||||
'dbPath',
|
||||
'decryptKey',
|
||||
'myWxid'
|
||||
@@ -38,6 +41,7 @@ class MessagePushService {
|
||||
private rerunRequested = false
|
||||
private started = false
|
||||
private baselineReady = false
|
||||
private messageTableScanRequested = false
|
||||
|
||||
constructor() {
|
||||
this.configService = ConfigService.getInstance()
|
||||
@@ -60,12 +64,15 @@ class MessagePushService {
|
||||
payload = null
|
||||
}
|
||||
|
||||
const tableName = String(payload?.table || '').trim().toLowerCase()
|
||||
if (tableName && tableName !== 'session') {
|
||||
const tableName = String(payload?.table || '').trim()
|
||||
if (this.isSessionTableChange(tableName)) {
|
||||
this.scheduleSync()
|
||||
return
|
||||
}
|
||||
|
||||
this.scheduleSync()
|
||||
if (!tableName || this.isMessageTableChange(tableName)) {
|
||||
this.scheduleSync({ scanMessageBackedSessions: true })
|
||||
}
|
||||
}
|
||||
|
||||
async handleConfigChanged(key: string): Promise<void> {
|
||||
@@ -91,6 +98,7 @@ class MessagePushService {
|
||||
this.recentMessageKeys.clear()
|
||||
this.groupNicknameCache.clear()
|
||||
this.baselineReady = false
|
||||
this.messageTableScanRequested = false
|
||||
if (this.debounceTimer) {
|
||||
clearTimeout(this.debounceTimer)
|
||||
this.debounceTimer = null
|
||||
@@ -121,7 +129,11 @@ class MessagePushService {
|
||||
this.baselineReady = true
|
||||
}
|
||||
|
||||
private scheduleSync(): void {
|
||||
private scheduleSync(options: { scanMessageBackedSessions?: boolean } = {}): void {
|
||||
if (options.scanMessageBackedSessions) {
|
||||
this.messageTableScanRequested = true
|
||||
}
|
||||
|
||||
if (this.debounceTimer) {
|
||||
clearTimeout(this.debounceTimer)
|
||||
}
|
||||
@@ -141,6 +153,8 @@ class MessagePushService {
|
||||
this.processing = true
|
||||
try {
|
||||
if (!this.isPushEnabled()) return
|
||||
const scanMessageBackedSessions = this.messageTableScanRequested
|
||||
this.messageTableScanRequested = false
|
||||
|
||||
const connectResult = await chatService.connect()
|
||||
if (!connectResult.success) {
|
||||
@@ -163,27 +177,47 @@ class MessagePushService {
|
||||
const previousBaseline = new Map(this.sessionBaseline)
|
||||
this.setBaseline(sessions)
|
||||
|
||||
const candidates = sessions.filter((session) => this.shouldInspectSession(previousBaseline.get(session.username), session))
|
||||
const candidates = sessions.filter((session) => {
|
||||
const previous = previousBaseline.get(session.username)
|
||||
if (this.shouldInspectSession(previous, session)) {
|
||||
return true
|
||||
}
|
||||
return scanMessageBackedSessions && this.shouldScanMessageBackedSession(previous, session)
|
||||
})
|
||||
for (const session of candidates) {
|
||||
await this.pushSessionMessages(session, previousBaseline.get(session.username))
|
||||
await this.pushSessionMessages(
|
||||
session,
|
||||
previousBaseline.get(session.username) || this.sessionBaseline.get(session.username)
|
||||
)
|
||||
}
|
||||
} finally {
|
||||
this.processing = false
|
||||
if (this.rerunRequested) {
|
||||
this.rerunRequested = false
|
||||
this.scheduleSync()
|
||||
this.scheduleSync({ scanMessageBackedSessions: this.messageTableScanRequested })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private setBaseline(sessions: ChatSession[]): void {
|
||||
const previousBaseline = new Map(this.sessionBaseline)
|
||||
const nextBaseline = new Map<string, SessionBaseline>()
|
||||
const nowSeconds = Math.floor(Date.now() / 1000)
|
||||
this.sessionBaseline.clear()
|
||||
for (const session of sessions) {
|
||||
this.sessionBaseline.set(session.username, {
|
||||
lastTimestamp: Number(session.lastTimestamp || 0),
|
||||
const username = String(session.username || '').trim()
|
||||
if (!username) continue
|
||||
const previous = previousBaseline.get(username)
|
||||
const sessionTimestamp = Number(session.lastTimestamp || 0)
|
||||
const initialTimestamp = sessionTimestamp > 0 ? sessionTimestamp : nowSeconds
|
||||
nextBaseline.set(username, {
|
||||
lastTimestamp: Math.max(sessionTimestamp, Number(previous?.lastTimestamp || 0), previous ? 0 : initialTimestamp),
|
||||
unreadCount: Number(session.unreadCount || 0)
|
||||
})
|
||||
}
|
||||
for (const [username, baseline] of nextBaseline.entries()) {
|
||||
this.sessionBaseline.set(username, baseline)
|
||||
}
|
||||
}
|
||||
|
||||
private shouldInspectSession(previous: SessionBaseline | undefined, session: ChatSession): boolean {
|
||||
@@ -204,16 +238,30 @@ class MessagePushService {
|
||||
return unreadCount > 0 && lastTimestamp > 0
|
||||
}
|
||||
|
||||
if (lastTimestamp <= previous.lastTimestamp) {
|
||||
return lastTimestamp > previous.lastTimestamp || unreadCount > previous.unreadCount
|
||||
}
|
||||
|
||||
private shouldScanMessageBackedSession(previous: SessionBaseline | undefined, session: ChatSession): boolean {
|
||||
const sessionId = String(session.username || '').trim()
|
||||
if (!sessionId || sessionId.toLowerCase().includes('placeholder_foldgroup')) {
|
||||
return false
|
||||
}
|
||||
|
||||
// unread 未增长时,大概率是自己发送、其他设备已读或状态同步,不作为主动推送
|
||||
return unreadCount > previous.unreadCount
|
||||
const summary = String(session.summary || '').trim()
|
||||
if (Number(session.lastMsgType || 0) === 10002 || summary.includes('撤回了一条消息')) {
|
||||
return false
|
||||
}
|
||||
|
||||
const sessionType = this.getSessionType(sessionId, session)
|
||||
if (sessionType === 'private') {
|
||||
return false
|
||||
}
|
||||
|
||||
return Boolean(previous) || Number(session.lastTimestamp || 0) > 0
|
||||
}
|
||||
|
||||
private async pushSessionMessages(session: ChatSession, previous: SessionBaseline | undefined): Promise<void> {
|
||||
const since = Math.max(0, Number(previous?.lastTimestamp || 0) - 1)
|
||||
const since = Math.max(0, Number(previous?.lastTimestamp || 0))
|
||||
const newMessagesResult = await chatService.getNewMessages(session.username, since, 1000)
|
||||
if (!newMessagesResult.success || !newMessagesResult.messages || newMessagesResult.messages.length === 0) {
|
||||
return
|
||||
@@ -224,7 +272,7 @@ class MessagePushService {
|
||||
if (!messageKey) continue
|
||||
if (message.isSend === 1) continue
|
||||
|
||||
if (previous && Number(message.createTime || 0) < Number(previous.lastTimestamp || 0)) {
|
||||
if (previous && Number(message.createTime || 0) <= Number(previous.lastTimestamp || 0)) {
|
||||
continue
|
||||
}
|
||||
|
||||
@@ -234,9 +282,11 @@ class MessagePushService {
|
||||
|
||||
const payload = await this.buildPayload(session, message)
|
||||
if (!payload) continue
|
||||
if (!this.shouldPushPayload(payload)) continue
|
||||
|
||||
httpService.broadcastMessagePush(payload)
|
||||
this.rememberMessageKey(messageKey)
|
||||
this.bumpSessionBaseline(session.username, message)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -246,6 +296,7 @@ class MessagePushService {
|
||||
if (!sessionId || !messageKey) return null
|
||||
|
||||
const isGroup = sessionId.endsWith('@chatroom')
|
||||
const sessionType = this.getSessionType(sessionId, session)
|
||||
const content = this.getMessageDisplayContent(message)
|
||||
|
||||
if (isGroup) {
|
||||
@@ -255,6 +306,7 @@ class MessagePushService {
|
||||
return {
|
||||
event: 'message.new',
|
||||
sessionId,
|
||||
sessionType,
|
||||
messageKey,
|
||||
avatarUrl: session.avatarUrl || groupInfo?.avatarUrl,
|
||||
groupName,
|
||||
@@ -267,6 +319,7 @@ class MessagePushService {
|
||||
return {
|
||||
event: 'message.new',
|
||||
sessionId,
|
||||
sessionType,
|
||||
messageKey,
|
||||
avatarUrl: session.avatarUrl || contactInfo?.avatarUrl,
|
||||
sourceName: session.displayName || contactInfo?.displayName || sessionId,
|
||||
@@ -274,10 +327,84 @@ class MessagePushService {
|
||||
}
|
||||
}
|
||||
|
||||
private getSessionType(sessionId: string, session: ChatSession): MessagePushPayload['sessionType'] {
|
||||
if (sessionId.endsWith('@chatroom')) {
|
||||
return 'group'
|
||||
}
|
||||
if (sessionId.startsWith('gh_') || session.type === 'official') {
|
||||
return 'official'
|
||||
}
|
||||
if (session.type === 'friend') {
|
||||
return 'private'
|
||||
}
|
||||
return 'other'
|
||||
}
|
||||
|
||||
private shouldPushPayload(payload: MessagePushPayload): boolean {
|
||||
const sessionId = String(payload.sessionId || '').trim()
|
||||
const filterMode = this.getMessagePushFilterMode()
|
||||
if (filterMode === 'all') {
|
||||
return true
|
||||
}
|
||||
|
||||
const filterList = this.getMessagePushFilterList()
|
||||
const listed = filterList.has(sessionId)
|
||||
if (filterMode === 'whitelist') {
|
||||
return listed
|
||||
}
|
||||
return !listed
|
||||
}
|
||||
|
||||
private getMessagePushFilterMode(): 'all' | 'whitelist' | 'blacklist' {
|
||||
const value = this.configService.get('messagePushFilterMode')
|
||||
if (value === 'whitelist' || value === 'blacklist') return value
|
||||
return 'all'
|
||||
}
|
||||
|
||||
private getMessagePushFilterList(): Set<string> {
|
||||
const value = this.configService.get('messagePushFilterList')
|
||||
if (!Array.isArray(value)) return new Set()
|
||||
return new Set(value.map((item) => String(item || '').trim()).filter(Boolean))
|
||||
}
|
||||
|
||||
private isSessionTableChange(tableName: string): boolean {
|
||||
return String(tableName || '').trim().toLowerCase() === 'session'
|
||||
}
|
||||
|
||||
private isMessageTableChange(tableName: string): boolean {
|
||||
const normalized = String(tableName || '').trim().toLowerCase()
|
||||
if (!normalized) return false
|
||||
return normalized === 'message' ||
|
||||
normalized === 'msg' ||
|
||||
normalized.startsWith('message_') ||
|
||||
normalized.startsWith('msg_') ||
|
||||
normalized.includes('message')
|
||||
}
|
||||
|
||||
private bumpSessionBaseline(sessionId: string, message: Message): void {
|
||||
const key = String(sessionId || '').trim()
|
||||
if (!key) return
|
||||
|
||||
const createTime = Number(message.createTime || 0)
|
||||
if (!Number.isFinite(createTime) || createTime <= 0) return
|
||||
|
||||
const current = this.sessionBaseline.get(key) || { lastTimestamp: 0, unreadCount: 0 }
|
||||
if (createTime > current.lastTimestamp) {
|
||||
this.sessionBaseline.set(key, {
|
||||
...current,
|
||||
lastTimestamp: createTime
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
private getMessageDisplayContent(message: Message): string | null {
|
||||
const cleanOfficialPrefix = (value: string | null): string | null => {
|
||||
if (!value) return value
|
||||
return value.replace(/^\s*\[视频号\]\s*/u, '').trim() || value
|
||||
}
|
||||
switch (Number(message.localType || 0)) {
|
||||
case 1:
|
||||
return message.rawContent || null
|
||||
return cleanOfficialPrefix(message.rawContent || null)
|
||||
case 3:
|
||||
return '[图片]'
|
||||
case 34:
|
||||
@@ -287,13 +414,13 @@ class MessagePushService {
|
||||
case 47:
|
||||
return '[表情]'
|
||||
case 42:
|
||||
return message.cardNickname || '[名片]'
|
||||
return cleanOfficialPrefix(message.cardNickname || '[名片]')
|
||||
case 48:
|
||||
return '[位置]'
|
||||
case 49:
|
||||
return message.linkTitle || message.fileName || '[消息]'
|
||||
return cleanOfficialPrefix(message.linkTitle || message.fileName || '[消息]')
|
||||
default:
|
||||
return message.parsedContent || message.rawContent || null
|
||||
return cleanOfficialPrefix(message.parsedContent || message.rawContent || null)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -58,6 +58,7 @@ export class WcdbCore {
|
||||
private wcdbGetAnnualReportExtras: any = null
|
||||
private wcdbGetDualReportStats: any = null
|
||||
private wcdbGetGroupStats: any = null
|
||||
private wcdbGetMyFootprintStats: any = null
|
||||
private wcdbGetMessageDates: any = null
|
||||
private wcdbOpenMessageCursor: any = null
|
||||
private wcdbOpenMessageCursorLite: any = null
|
||||
@@ -127,6 +128,8 @@ export class WcdbCore {
|
||||
private logTimer: NodeJS.Timeout | null = null
|
||||
private lastLogTail: string | null = null
|
||||
private lastResolvedLogPath: string | null = null
|
||||
private lastCursorForceReopenAt = 0
|
||||
private readonly cursorForceReopenCooldownMs = 15000
|
||||
|
||||
setPaths(resourcesPath: string, userDataPath: string): void {
|
||||
this.resourcesPath = resourcesPath
|
||||
@@ -923,6 +926,13 @@ export class WcdbCore {
|
||||
this.wcdbGetGroupStats = null
|
||||
}
|
||||
|
||||
// wcdb_status wcdb_get_my_footprint_stats(wcdb_handle handle, const char* options_json, char** out_json)
|
||||
try {
|
||||
this.wcdbGetMyFootprintStats = this.lib.func('int32 wcdb_get_my_footprint_stats(int64 handle, const char* optionsJson, _Out_ void** outJson)')
|
||||
} catch {
|
||||
this.wcdbGetMyFootprintStats = null
|
||||
}
|
||||
|
||||
// wcdb_status wcdb_get_message_dates(wcdb_handle handle, const char* session_id, char** out_json)
|
||||
try {
|
||||
this.wcdbGetMessageDates = this.lib.func('int32 wcdb_get_message_dates(int64 handle, const char* sessionId, _Out_ void** outJson)')
|
||||
@@ -3098,6 +3108,65 @@ export class WcdbCore {
|
||||
}
|
||||
}
|
||||
|
||||
async getMyFootprintStats(options: {
|
||||
beginTimestamp?: number
|
||||
endTimestamp?: number
|
||||
myWxid?: string
|
||||
privateSessionIds?: string[]
|
||||
groupSessionIds?: string[]
|
||||
mentionLimit?: number
|
||||
privateLimit?: number
|
||||
mentionMode?: 'text_at_me' | string
|
||||
}): Promise<{ success: boolean; data?: any; error?: string }> {
|
||||
if (!this.ensureReady()) {
|
||||
return { success: false, error: 'WCDB 未连接' }
|
||||
}
|
||||
if (!this.wcdbGetMyFootprintStats) {
|
||||
return { success: false, error: '接口未就绪' }
|
||||
}
|
||||
|
||||
try {
|
||||
const normalizedPrivateSessions = Array.from(new Set(
|
||||
(options?.privateSessionIds || [])
|
||||
.map((value) => String(value || '').trim())
|
||||
.filter(Boolean)
|
||||
))
|
||||
const normalizedGroupSessions = Array.from(new Set(
|
||||
(options?.groupSessionIds || [])
|
||||
.map((value) => String(value || '').trim())
|
||||
.filter(Boolean)
|
||||
))
|
||||
const mentionLimitRaw = Number(options?.mentionLimit ?? 0)
|
||||
const privateLimitRaw = Number(options?.privateLimit ?? 0)
|
||||
const mentionLimit = Number.isFinite(mentionLimitRaw) && mentionLimitRaw >= 0 ? Math.floor(mentionLimitRaw) : 0
|
||||
const privateLimit = Number.isFinite(privateLimitRaw) && privateLimitRaw >= 0 ? Math.floor(privateLimitRaw) : 0
|
||||
|
||||
const payload = JSON.stringify({
|
||||
begin: this.normalizeTimestamp(options?.beginTimestamp || 0),
|
||||
end: this.normalizeTimestamp(options?.endTimestamp || 0),
|
||||
my_wxid: String(options?.myWxid || '').trim(),
|
||||
private_session_ids: normalizedPrivateSessions,
|
||||
group_session_ids: normalizedGroupSessions,
|
||||
mention_limit: mentionLimit,
|
||||
private_limit: privateLimit,
|
||||
mention_mode: options?.mentionMode || 'text_at_me'
|
||||
})
|
||||
|
||||
const outPtr = [null as any]
|
||||
const result = this.wcdbGetMyFootprintStats(this.handle, payload, outPtr)
|
||||
if (result !== 0 || !outPtr[0]) {
|
||||
return { success: false, error: `获取我的足迹统计失败: ${result}` }
|
||||
}
|
||||
const jsonStr = this.decodeJsonPtr(outPtr[0])
|
||||
if (!jsonStr) {
|
||||
return { success: false, error: '解析我的足迹统计失败' }
|
||||
}
|
||||
return { success: true, data: JSON.parse(jsonStr) || {} }
|
||||
} catch (e) {
|
||||
return { success: false, error: String(e) }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 强制重新打开账号连接(绕过路径缓存),用于微信重装后消息数据库刷新失败时的自动恢复。
|
||||
* 返回重新打开是否成功。
|
||||
@@ -3119,6 +3188,15 @@ export class WcdbCore {
|
||||
return this.open(path, key, wxid)
|
||||
}
|
||||
|
||||
private shouldRetryCursorAfterNoDb(): boolean {
|
||||
const now = Date.now()
|
||||
if (now - this.lastCursorForceReopenAt < this.cursorForceReopenCooldownMs) {
|
||||
return false
|
||||
}
|
||||
this.lastCursorForceReopenAt = now
|
||||
return true
|
||||
}
|
||||
|
||||
async openMessageCursor(sessionId: string, batchSize: number, ascending: boolean, beginTimestamp: number, endTimestamp: number): Promise<{ success: boolean; cursor?: number; error?: string }> {
|
||||
if (!this.ensureReady()) {
|
||||
return { success: false, error: 'WCDB 未连接' }
|
||||
@@ -3136,7 +3214,7 @@ export class WcdbCore {
|
||||
)
|
||||
// result=-3 表示 WCDB_STATUS_NO_MESSAGE_DB:消息数据库缓存为空(常见于微信重装后)
|
||||
// 自动强制重连并重试一次
|
||||
if (result === -3 && outCursor[0] <= 0) {
|
||||
if (result === -3 && outCursor[0] <= 0 && this.shouldRetryCursorAfterNoDb()) {
|
||||
this.writeLog('openMessageCursor: result=-3 (no message db), attempting forceReopen...', true)
|
||||
const reopened = await this.forceReopen()
|
||||
if (reopened && this.handle !== null) {
|
||||
@@ -3156,11 +3234,13 @@ export class WcdbCore {
|
||||
}
|
||||
}
|
||||
if (result !== 0 || outCursor[0] <= 0) {
|
||||
await this.printLogs(true)
|
||||
this.writeLog(
|
||||
`openMessageCursor failed: sessionId=${sessionId} batchSize=${batchSize} ascending=${ascending ? 1 : 0} begin=${beginTimestamp} end=${endTimestamp} result=${result} cursor=${outCursor[0]}`,
|
||||
true
|
||||
)
|
||||
if (result !== -3) {
|
||||
await this.printLogs(true)
|
||||
this.writeLog(
|
||||
`openMessageCursor failed: sessionId=${sessionId} batchSize=${batchSize} ascending=${ascending ? 1 : 0} begin=${beginTimestamp} end=${endTimestamp} result=${result} cursor=${outCursor[0]}`,
|
||||
true
|
||||
)
|
||||
}
|
||||
const hint = result === -3
|
||||
? `创建游标失败: ${result}(消息数据库未找到)。如果你最近重装过微信,请尝试重新指定数据目录后重试`
|
||||
: result === -7
|
||||
@@ -3197,7 +3277,7 @@ export class WcdbCore {
|
||||
|
||||
// result=-3 表示 WCDB_STATUS_NO_MESSAGE_DB:消息数据库缓存为空
|
||||
// 自动强制重连并重试一次
|
||||
if (result === -3 && outCursor[0] <= 0) {
|
||||
if (result === -3 && outCursor[0] <= 0 && this.shouldRetryCursorAfterNoDb()) {
|
||||
this.writeLog('openMessageCursorLite: result=-3 (no message db), attempting forceReopen...', true)
|
||||
const reopened = await this.forceReopen()
|
||||
if (reopened && this.handle !== null) {
|
||||
@@ -3218,11 +3298,13 @@ export class WcdbCore {
|
||||
}
|
||||
|
||||
if (result !== 0 || outCursor[0] <= 0) {
|
||||
await this.printLogs(true)
|
||||
this.writeLog(
|
||||
`openMessageCursorLite failed: sessionId=${sessionId} batchSize=${batchSize} ascending=${ascending ? 1 : 0} begin=${beginTimestamp} end=${endTimestamp} result=${result} cursor=${outCursor[0]}`,
|
||||
true
|
||||
)
|
||||
if (result !== -3) {
|
||||
await this.printLogs(true)
|
||||
this.writeLog(
|
||||
`openMessageCursorLite failed: sessionId=${sessionId} batchSize=${batchSize} ascending=${ascending ? 1 : 0} begin=${beginTimestamp} end=${endTimestamp} result=${result} cursor=${outCursor[0]}`,
|
||||
true
|
||||
)
|
||||
}
|
||||
if (result === -7) {
|
||||
return { success: false, error: 'message schema mismatch:当前账号消息表结构与程序要求不一致' }
|
||||
}
|
||||
|
||||
@@ -448,6 +448,19 @@ export class WcdbService {
|
||||
return this.callWorker('getGroupStats', { chatroomId, beginTimestamp, endTimestamp })
|
||||
}
|
||||
|
||||
async getMyFootprintStats(options: {
|
||||
beginTimestamp?: number
|
||||
endTimestamp?: number
|
||||
myWxid?: string
|
||||
privateSessionIds?: string[]
|
||||
groupSessionIds?: string[]
|
||||
mentionLimit?: number
|
||||
privateLimit?: number
|
||||
mentionMode?: 'text_at_me' | string
|
||||
}): Promise<{ success: boolean; data?: any; error?: string }> {
|
||||
return this.callWorker('getMyFootprintStats', { options })
|
||||
}
|
||||
|
||||
/**
|
||||
* 打开消息游标
|
||||
*/
|
||||
|
||||
@@ -158,6 +158,9 @@ if (parentPort) {
|
||||
case 'getGroupStats':
|
||||
result = await core.getGroupStats(payload.chatroomId, payload.beginTimestamp, payload.endTimestamp)
|
||||
break
|
||||
case 'getMyFootprintStats':
|
||||
result = await core.getMyFootprintStats(payload.options || {})
|
||||
break
|
||||
case 'openMessageCursor':
|
||||
result = await core.openMessageCursor(payload.sessionId, payload.batchSize, payload.ascending, payload.beginTimestamp, payload.endTimestamp)
|
||||
break
|
||||
|
||||
@@ -115,12 +115,14 @@ export async function showNotification(data: any) {
|
||||
// 检查会话过滤
|
||||
const filterMode = config.get("notificationFilterMode") || "all";
|
||||
const filterList = config.get("notificationFilterList") || [];
|
||||
const sessionId = data.sessionId;
|
||||
const sessionId = typeof data.sessionId === "string" ? data.sessionId : "";
|
||||
// 系统通知(如 "WeFlow 准备就绪")不是聊天消息,不应受会话白/黑名单影响
|
||||
const isSystemNotification = sessionId.startsWith("weflow-");
|
||||
|
||||
if (sessionId && filterMode !== "all" && filterList.length > 0) {
|
||||
const isInList = filterList.includes(sessionId);
|
||||
if (!isSystemNotification && filterMode !== "all") {
|
||||
const isInList = sessionId !== "" && filterList.includes(sessionId);
|
||||
if (filterMode === "whitelist" && !isInList) {
|
||||
// 白名单模式:不在列表中则不显示
|
||||
// 白名单模式:不在列表中则不显示(空列表视为全部拦截)
|
||||
return;
|
||||
}
|
||||
if (filterMode === "blacklist" && isInList) {
|
||||
|
||||
32
package.json
32
package.json
@@ -9,7 +9,7 @@
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/hicccc77/WeFlow"
|
||||
"url": "https://github.com/Jasonzhu1207/WeFlow"
|
||||
},
|
||||
"//": "二改不应改变此处的作者与应用信息",
|
||||
"scripts": {
|
||||
@@ -23,7 +23,6 @@
|
||||
"electron:build": "npm run build"
|
||||
},
|
||||
"dependencies": {
|
||||
"@vscode/sudo-prompt": "^9.3.2",
|
||||
"echarts": "^6.0.0",
|
||||
"echarts-for-react": "^3.0.2",
|
||||
"electron-store": "^11.0.2",
|
||||
@@ -42,8 +41,9 @@
|
||||
"react-router-dom": "^7.14.0",
|
||||
"react-virtuoso": "^4.18.1",
|
||||
"remark-gfm": "^4.0.1",
|
||||
"sherpa-onnx-node": "^1.12.35",
|
||||
"sherpa-onnx-node": "^1.10.38",
|
||||
"silk-wasm": "^3.7.1",
|
||||
"sudo-prompt": "^9.2.1",
|
||||
"wechat-emojis": "^1.0.2",
|
||||
"zustand": "^5.0.2"
|
||||
},
|
||||
@@ -54,11 +54,11 @@
|
||||
"@vitejs/plugin-react": "^4.3.4",
|
||||
"electron": "^41.1.1",
|
||||
"electron-builder": "^26.8.1",
|
||||
"sass": "^1.99.0",
|
||||
"sass": "^1.98.0",
|
||||
"sharp": "^0.34.5",
|
||||
"typescript": "^6.0.2",
|
||||
"vite": "^7.3.2",
|
||||
"vite-plugin-electron": "^0.29.1",
|
||||
"vite": "^7.0.0",
|
||||
"vite-plugin-electron": "^0.28.8",
|
||||
"vite-plugin-electron-renderer": "^0.14.6"
|
||||
},
|
||||
"pnpm": {
|
||||
@@ -70,16 +70,14 @@
|
||||
"lodash": ">=4.17.21",
|
||||
"brace-expansion": ">=1.1.11",
|
||||
"picomatch": ">=2.3.1",
|
||||
"ajv": ">=8.18.0",
|
||||
"ajv-keywords@3>ajv": "^6.12.6",
|
||||
"@develar/schema-utils>ajv": "^6.12.6"
|
||||
"ajv": ">=8.18.0"
|
||||
}
|
||||
},
|
||||
"build": {
|
||||
"appId": "com.WeFlow.app",
|
||||
"publish": {
|
||||
"provider": "github",
|
||||
"owner": "hicccc77",
|
||||
"owner": "Jasonzhu1207",
|
||||
"repo": "WeFlow",
|
||||
"releaseType": "release"
|
||||
},
|
||||
@@ -98,7 +96,7 @@
|
||||
"gatekeeperAssess": false,
|
||||
"entitlements": "electron/entitlements.mac.plist",
|
||||
"entitlementsInherit": "electron/entitlements.mac.plist",
|
||||
"icon": "resources/icons/macos/icon.icns"
|
||||
"icon": "resources/icon.icns"
|
||||
},
|
||||
"win": {
|
||||
"target": [
|
||||
@@ -107,19 +105,19 @@
|
||||
"icon": "public/icon.ico",
|
||||
"extraFiles": [
|
||||
{
|
||||
"from": "resources/runtime/win32/msvcp140.dll",
|
||||
"from": "resources/msvcp140.dll",
|
||||
"to": "."
|
||||
},
|
||||
{
|
||||
"from": "resources/runtime/win32/msvcp140_1.dll",
|
||||
"from": "resources/msvcp140_1.dll",
|
||||
"to": "."
|
||||
},
|
||||
{
|
||||
"from": "resources/runtime/win32/vcruntime140.dll",
|
||||
"from": "resources/vcruntime140.dll",
|
||||
"to": "."
|
||||
},
|
||||
{
|
||||
"from": "resources/runtime/win32/vcruntime140_1.dll",
|
||||
"from": "resources/vcruntime140_1.dll",
|
||||
"to": "."
|
||||
}
|
||||
]
|
||||
@@ -135,7 +133,7 @@
|
||||
"synopsis": "WeFlow for Linux",
|
||||
"extraFiles": [
|
||||
{
|
||||
"from": "resources/installer/linux/install.sh",
|
||||
"from": "resources/linux/install.sh",
|
||||
"to": "install.sh"
|
||||
}
|
||||
]
|
||||
@@ -190,7 +188,7 @@
|
||||
"node_modules/sherpa-onnx-*/**/*",
|
||||
"node_modules/ffmpeg-static/**/*"
|
||||
],
|
||||
"icon": "resources/icons/macos/icon.icns"
|
||||
"icon": "resources/icon.icns"
|
||||
},
|
||||
"overrides": {
|
||||
"picomatch": "^4.0.4",
|
||||
|
||||
0
resources/key/linux/x64/xkey_helper_linux
Normal file → Executable file
0
resources/key/linux/x64/xkey_helper_linux
Normal file → Executable file
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -17,6 +17,7 @@ import AgreementPage from './pages/AgreementPage'
|
||||
import GroupAnalyticsPage from './pages/GroupAnalyticsPage'
|
||||
import SettingsPage from './pages/SettingsPage'
|
||||
import ExportPage from './pages/ExportPage'
|
||||
import MyFootprintPage from './pages/MyFootprintPage'
|
||||
import VideoWindow from './pages/VideoWindow'
|
||||
import ImageWindow from './pages/ImageWindow'
|
||||
import SnsPage from './pages/SnsPage'
|
||||
@@ -25,6 +26,7 @@ import ContactsPage from './pages/ContactsPage'
|
||||
import ResourcesPage from './pages/ResourcesPage'
|
||||
import ChatHistoryPage from './pages/ChatHistoryPage'
|
||||
import NotificationWindow from './pages/NotificationWindow'
|
||||
import AccountManagementPage from './pages/AccountManagementPage'
|
||||
|
||||
import { useAppStore } from './stores/appStore'
|
||||
import { themes, useThemeStore, type ThemeId, type ThemeMode } from './stores/themeStore'
|
||||
@@ -677,6 +679,7 @@ function App() {
|
||||
<Routes location={routeLocation}>
|
||||
<Route path="/" element={<HomePage />} />
|
||||
<Route path="/home" element={<HomePage />} />
|
||||
<Route path="/account-management" element={<AccountManagementPage />} />
|
||||
<Route path="/chat" element={<ChatPage />} />
|
||||
|
||||
<Route path="/analytics" element={<ChatAnalyticsHubPage />} />
|
||||
@@ -689,6 +692,7 @@ function App() {
|
||||
<Route path="/annual-report/view" element={<AnnualReportWindow />} />
|
||||
<Route path="/dual-report" element={<DualReportPage />} />
|
||||
<Route path="/dual-report/view" element={<DualReportWindow />} />
|
||||
<Route path="/footprint" element={<MyFootprintPage />} />
|
||||
|
||||
<Route path="/export" element={<div className="export-route-anchor" aria-hidden="true" />} />
|
||||
<Route path="/sns" element={<SnsPage />} />
|
||||
|
||||
@@ -54,10 +54,11 @@
|
||||
position: absolute;
|
||||
top: calc(100% + 8px);
|
||||
right: 0;
|
||||
background: var(--card-bg);
|
||||
background: var(--bg-secondary-solid, var(--bg-primary, var(--card-bg)));
|
||||
border-radius: 16px;
|
||||
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.15);
|
||||
backdrop-filter: blur(20px);
|
||||
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.25);
|
||||
backdrop-filter: none;
|
||||
-webkit-backdrop-filter: none;
|
||||
border: 1px solid var(--border-color);
|
||||
z-index: 1000;
|
||||
display: flex;
|
||||
|
||||
@@ -29,6 +29,20 @@ function DateRangePicker({ startDate, endDate, onStartDateChange, onEndDateChang
|
||||
const [showYearMonthPicker, setShowYearMonthPicker] = useState(false)
|
||||
const containerRef = useRef<HTMLDivElement>(null)
|
||||
|
||||
const [internalStart, setInternalStart] = useState(startDate)
|
||||
const [internalEnd, setInternalEnd] = useState(endDate)
|
||||
|
||||
useEffect(() => {
|
||||
setInternalStart(startDate)
|
||||
setInternalEnd(endDate)
|
||||
}, [startDate, endDate])
|
||||
|
||||
useEffect(() => {
|
||||
if (isOpen) {
|
||||
setSelectingStart(true)
|
||||
}
|
||||
}, [isOpen])
|
||||
|
||||
// 点击外部关闭
|
||||
useEffect(() => {
|
||||
const handleClickOutside = (e: MouseEvent) => {
|
||||
@@ -63,8 +77,10 @@ function DateRangePicker({ startDate, endDate, onStartDateChange, onEndDateChang
|
||||
const end = new Date()
|
||||
const start = new Date()
|
||||
start.setDate(start.getDate() - days)
|
||||
onStartDateChange(start.toISOString().split('T')[0])
|
||||
onEndDateChange(end.toISOString().split('T')[0])
|
||||
const startStr = `${start.getFullYear()}-${String(start.getMonth() + 1).padStart(2, '0')}-${String(start.getDate()).padStart(2, '0')}`
|
||||
const endStr = `${end.getFullYear()}-${String(end.getMonth() + 1).padStart(2, '0')}-${String(end.getDate()).padStart(2, '0')}`
|
||||
onStartDateChange(startStr)
|
||||
onEndDateChange(endStr)
|
||||
}
|
||||
setIsOpen(false)
|
||||
setTimeout(() => onRangeComplete?.(), 0)
|
||||
@@ -89,38 +105,46 @@ function DateRangePicker({ startDate, endDate, onStartDateChange, onEndDateChang
|
||||
const dateStr = `${currentMonth.getFullYear()}-${String(currentMonth.getMonth() + 1).padStart(2, '0')}-${String(day).padStart(2, '0')}`
|
||||
|
||||
if (selectingStart) {
|
||||
onStartDateChange(dateStr)
|
||||
if (endDate && dateStr > endDate) {
|
||||
onEndDateChange('')
|
||||
setInternalStart(dateStr)
|
||||
if (internalEnd && dateStr > internalEnd) {
|
||||
setInternalEnd('')
|
||||
}
|
||||
setSelectingStart(false)
|
||||
} else {
|
||||
if (dateStr < startDate) {
|
||||
onStartDateChange(dateStr)
|
||||
onEndDateChange(startDate)
|
||||
} else {
|
||||
onEndDateChange(dateStr)
|
||||
let finalStart = internalStart
|
||||
let finalEnd = dateStr
|
||||
|
||||
if (dateStr < internalStart) {
|
||||
finalStart = dateStr
|
||||
finalEnd = internalStart
|
||||
}
|
||||
|
||||
setInternalStart(finalStart)
|
||||
setInternalEnd(finalEnd)
|
||||
|
||||
setSelectingStart(true)
|
||||
setIsOpen(false)
|
||||
|
||||
onStartDateChange(finalStart)
|
||||
onEndDateChange(finalEnd)
|
||||
setTimeout(() => onRangeComplete?.(), 0)
|
||||
}
|
||||
}
|
||||
|
||||
const isInRange = (day: number) => {
|
||||
if (!startDate || !endDate) return false
|
||||
if (!internalStart || !internalEnd) return false
|
||||
const dateStr = `${currentMonth.getFullYear()}-${String(currentMonth.getMonth() + 1).padStart(2, '0')}-${String(day).padStart(2, '0')}`
|
||||
return dateStr >= startDate && dateStr <= endDate
|
||||
return dateStr >= internalStart && dateStr <= internalEnd
|
||||
}
|
||||
|
||||
const isStartDate = (day: number) => {
|
||||
const dateStr = `${currentMonth.getFullYear()}-${String(currentMonth.getMonth() + 1).padStart(2, '0')}-${String(day).padStart(2, '0')}`
|
||||
return dateStr === startDate
|
||||
return dateStr === internalStart
|
||||
}
|
||||
|
||||
const isEndDate = (day: number) => {
|
||||
const dateStr = `${currentMonth.getFullYear()}-${String(currentMonth.getMonth() + 1).padStart(2, '0')}-${String(day).padStart(2, '0')}`
|
||||
return dateStr === endDate
|
||||
return dateStr === internalEnd
|
||||
}
|
||||
|
||||
const isToday = (day: number) => {
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 16px;
|
||||
z-index: 2400;
|
||||
z-index: 9200;
|
||||
}
|
||||
|
||||
.export-date-range-dialog {
|
||||
@@ -192,6 +192,149 @@
|
||||
}
|
||||
}
|
||||
|
||||
.export-date-range-time-select {
|
||||
position: relative;
|
||||
width: 100%;
|
||||
|
||||
&.open .export-date-range-time-trigger {
|
||||
border-color: var(--primary);
|
||||
box-shadow: 0 0 0 1px rgba(var(--primary-rgb), 0.18);
|
||||
color: var(--primary);
|
||||
}
|
||||
}
|
||||
|
||||
.export-date-range-time-trigger {
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
border-radius: 8px;
|
||||
border: 1px solid var(--border-color);
|
||||
background: var(--bg-primary);
|
||||
color: var(--text-primary);
|
||||
height: 30px;
|
||||
padding: 0 9px;
|
||||
font-size: 12px;
|
||||
font-family: inherit;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 8px;
|
||||
cursor: pointer;
|
||||
transition: border-color 0.15s ease, box-shadow 0.15s ease, color 0.15s ease;
|
||||
|
||||
&:focus {
|
||||
outline: none;
|
||||
border-color: var(--primary);
|
||||
box-shadow: 0 0 0 1px rgba(var(--primary-rgb), 0.18);
|
||||
}
|
||||
}
|
||||
|
||||
.export-date-range-time-trigger-value {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.export-date-range-time-dropdown {
|
||||
position: absolute;
|
||||
top: calc(100% + 6px);
|
||||
left: 0;
|
||||
right: 0;
|
||||
z-index: 24;
|
||||
border: 1px solid var(--border-color);
|
||||
border-radius: 12px;
|
||||
background: color-mix(in srgb, var(--bg-primary) 88%, var(--bg-secondary));
|
||||
box-shadow: var(--shadow-md);
|
||||
padding: 8px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
backdrop-filter: blur(14px);
|
||||
-webkit-backdrop-filter: blur(14px);
|
||||
}
|
||||
|
||||
.export-date-range-time-dropdown-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 8px;
|
||||
|
||||
span {
|
||||
font-size: 11px;
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
strong {
|
||||
font-size: 13px;
|
||||
color: var(--text-primary);
|
||||
}
|
||||
}
|
||||
|
||||
.export-date-range-time-quick-list {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.export-date-range-time-quick-item,
|
||||
.export-date-range-time-option {
|
||||
border: 1px solid transparent;
|
||||
border-radius: 8px;
|
||||
background: transparent;
|
||||
color: var(--text-primary);
|
||||
cursor: pointer;
|
||||
transition: background 0.15s ease, border-color 0.15s ease, color 0.15s ease;
|
||||
|
||||
&:hover {
|
||||
background: var(--bg-tertiary);
|
||||
}
|
||||
|
||||
&.active {
|
||||
border-color: rgba(var(--primary-rgb), 0.28);
|
||||
background: rgba(var(--primary-rgb), 0.12);
|
||||
color: var(--primary);
|
||||
}
|
||||
}
|
||||
|
||||
.export-date-range-time-quick-item {
|
||||
min-width: 52px;
|
||||
height: 28px;
|
||||
padding: 0 10px;
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
.export-date-range-time-columns {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.export-date-range-time-column {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.export-date-range-time-column-label {
|
||||
font-size: 11px;
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
.export-date-range-time-column-list {
|
||||
max-height: 168px;
|
||||
overflow-y: auto;
|
||||
padding-right: 2px;
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.export-date-range-time-option {
|
||||
min-height: 28px;
|
||||
padding: 0 8px;
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
.export-date-range-calendar-nav {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react'
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { createPortal } from 'react-dom'
|
||||
import { Check, ChevronLeft, ChevronRight, X } from 'lucide-react'
|
||||
import { Check, ChevronDown, ChevronLeft, ChevronRight, X } from 'lucide-react'
|
||||
import {
|
||||
EXPORT_DATE_RANGE_PRESETS,
|
||||
WEEKDAY_SHORT_LABELS,
|
||||
@@ -10,7 +10,6 @@ import {
|
||||
createDateRangeByPreset,
|
||||
createDefaultDateRange,
|
||||
formatCalendarMonthTitle,
|
||||
formatDateInputValue,
|
||||
isSameDay,
|
||||
parseDateInputValue,
|
||||
startOfDay,
|
||||
@@ -37,6 +36,10 @@ interface ExportDateRangeDialogDraft extends ExportDateRangeSelection {
|
||||
panelMonth: Date
|
||||
}
|
||||
|
||||
const HOUR_OPTIONS = Array.from({ length: 24 }, (_, index) => `${index}`.padStart(2, '0'))
|
||||
const MINUTE_OPTIONS = Array.from({ length: 60 }, (_, index) => `${index}`.padStart(2, '0'))
|
||||
const QUICK_TIME_OPTIONS = ['00:00', '08:00', '12:00', '18:00', '23:59']
|
||||
|
||||
const resolveBounds = (minDate?: Date | null, maxDate?: Date | null): { minDate: Date; maxDate: Date } | null => {
|
||||
if (!(minDate instanceof Date) || Number.isNaN(minDate.getTime())) return null
|
||||
if (!(maxDate instanceof Date) || Number.isNaN(maxDate.getTime())) return null
|
||||
@@ -57,16 +60,42 @@ const clampSelectionToBounds = (
|
||||
const bounds = resolveBounds(minDate, maxDate)
|
||||
if (!bounds) return cloneExportDateRangeSelection(value)
|
||||
|
||||
const rawStart = value.useAllTime ? bounds.minDate : startOfDay(value.dateRange.start)
|
||||
const rawEnd = value.useAllTime ? bounds.maxDate : endOfDay(value.dateRange.end)
|
||||
const nextStart = new Date(Math.min(Math.max(rawStart.getTime(), bounds.minDate.getTime()), bounds.maxDate.getTime()))
|
||||
const nextEndCandidate = new Date(Math.min(Math.max(rawEnd.getTime(), bounds.minDate.getTime()), bounds.maxDate.getTime()))
|
||||
const nextEnd = nextEndCandidate.getTime() < nextStart.getTime() ? endOfDay(nextStart) : nextEndCandidate
|
||||
const changed = nextStart.getTime() !== rawStart.getTime() || nextEnd.getTime() !== rawEnd.getTime()
|
||||
// For custom selections, only ensure end >= start, preserve time precision
|
||||
if (value.preset === 'custom' && !value.useAllTime) {
|
||||
const { start, end } = value.dateRange
|
||||
if (end.getTime() < start.getTime()) {
|
||||
return {
|
||||
...value,
|
||||
dateRange: { start, end: start }
|
||||
}
|
||||
}
|
||||
return cloneExportDateRangeSelection(value)
|
||||
}
|
||||
|
||||
// For useAllTime, use bounds directly
|
||||
if (value.useAllTime) {
|
||||
return {
|
||||
preset: value.preset,
|
||||
useAllTime: true,
|
||||
dateRange: {
|
||||
start: bounds.minDate,
|
||||
end: bounds.maxDate
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// For preset selections (not custom), clamp dates to bounds and use default times
|
||||
const nextStart = new Date(Math.min(Math.max(value.dateRange.start.getTime(), bounds.minDate.getTime()), bounds.maxDate.getTime()))
|
||||
const nextEndCandidate = new Date(Math.min(Math.max(value.dateRange.end.getTime(), bounds.minDate.getTime()), bounds.maxDate.getTime()))
|
||||
const nextEnd = nextEndCandidate.getTime() < nextStart.getTime() ? nextStart : nextEndCandidate
|
||||
|
||||
// Set default times: start at 00:00:00, end at 23:59:59
|
||||
nextStart.setHours(0, 0, 0, 0)
|
||||
nextEnd.setHours(23, 59, 59, 999)
|
||||
|
||||
return {
|
||||
preset: value.useAllTime ? value.preset : (changed ? 'custom' : value.preset),
|
||||
useAllTime: value.useAllTime,
|
||||
preset: value.preset,
|
||||
useAllTime: false,
|
||||
dateRange: {
|
||||
start: nextStart,
|
||||
end: nextEnd
|
||||
@@ -95,62 +124,129 @@ export function ExportDateRangeDialog({
|
||||
onClose,
|
||||
onConfirm
|
||||
}: ExportDateRangeDialogProps) {
|
||||
// Helper: Format date only (YYYY-MM-DD) for the date input field
|
||||
const formatDateOnly = (date: Date): string => {
|
||||
const y = date.getFullYear()
|
||||
const m = `${date.getMonth() + 1}`.padStart(2, '0')
|
||||
const d = `${date.getDate()}`.padStart(2, '0')
|
||||
return `${y}-${m}-${d}`
|
||||
}
|
||||
|
||||
// Helper: Format time only (HH:mm) for the time input field
|
||||
const formatTimeOnly = (date: Date): string => {
|
||||
const h = `${date.getHours()}`.padStart(2, '0')
|
||||
const m = `${date.getMinutes()}`.padStart(2, '0')
|
||||
return `${h}:${m}`
|
||||
}
|
||||
|
||||
const [draft, setDraft] = useState<ExportDateRangeDialogDraft>(() => buildDialogDraft(value, minDate, maxDate))
|
||||
const [activeBoundary, setActiveBoundary] = useState<ActiveBoundary>('start')
|
||||
const [dateInput, setDateInput] = useState({
|
||||
start: formatDateInputValue(value.dateRange.start),
|
||||
end: formatDateInputValue(value.dateRange.end)
|
||||
start: formatDateOnly(value.dateRange.start),
|
||||
end: formatDateOnly(value.dateRange.end)
|
||||
})
|
||||
const [dateInputError, setDateInputError] = useState({ start: false, end: false })
|
||||
|
||||
// Default times: start at 00:00, end at 23:59
|
||||
const [timeInput, setTimeInput] = useState({
|
||||
start: '00:00',
|
||||
end: '23:59'
|
||||
})
|
||||
const [openTimeDropdown, setOpenTimeDropdown] = useState<ActiveBoundary | null>(null)
|
||||
const startTimeSelectRef = useRef<HTMLDivElement>(null)
|
||||
const endTimeSelectRef = useRef<HTMLDivElement>(null)
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return
|
||||
const nextDraft = buildDialogDraft(value, minDate, maxDate)
|
||||
setDraft(nextDraft)
|
||||
setActiveBoundary('start')
|
||||
setDateInput({
|
||||
start: formatDateInputValue(nextDraft.dateRange.start),
|
||||
end: formatDateInputValue(nextDraft.dateRange.end)
|
||||
start: formatDateOnly(nextDraft.dateRange.start),
|
||||
end: formatDateOnly(nextDraft.dateRange.end)
|
||||
})
|
||||
// For preset-based selections (not custom), use default times 00:00 and 23:59
|
||||
// For custom selections, preserve the time from value.dateRange
|
||||
if (nextDraft.useAllTime || nextDraft.preset !== 'custom') {
|
||||
setTimeInput({
|
||||
start: '00:00',
|
||||
end: '23:59'
|
||||
})
|
||||
} else {
|
||||
setTimeInput({
|
||||
start: formatTimeOnly(nextDraft.dateRange.start),
|
||||
end: formatTimeOnly(nextDraft.dateRange.end)
|
||||
})
|
||||
}
|
||||
setOpenTimeDropdown(null)
|
||||
setDateInputError({ start: false, end: false })
|
||||
}, [maxDate, minDate, open, value])
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return
|
||||
setDateInput({
|
||||
start: formatDateInputValue(draft.dateRange.start),
|
||||
end: formatDateInputValue(draft.dateRange.end)
|
||||
start: formatDateOnly(draft.dateRange.start),
|
||||
end: formatDateOnly(draft.dateRange.end)
|
||||
})
|
||||
// Don't sync timeInput here - it's controlled by the time picker
|
||||
setDateInputError({ start: false, end: false })
|
||||
}, [draft.dateRange.end.getTime(), draft.dateRange.start.getTime(), open])
|
||||
|
||||
useEffect(() => {
|
||||
if (!openTimeDropdown) return
|
||||
|
||||
const handlePointerDown = (event: MouseEvent) => {
|
||||
const target = event.target as Node
|
||||
const activeContainer = openTimeDropdown === 'start'
|
||||
? startTimeSelectRef.current
|
||||
: endTimeSelectRef.current
|
||||
if (!activeContainer?.contains(target)) {
|
||||
setOpenTimeDropdown(null)
|
||||
}
|
||||
}
|
||||
|
||||
const handleEscape = (event: KeyboardEvent) => {
|
||||
if (event.key === 'Escape') {
|
||||
setOpenTimeDropdown(null)
|
||||
}
|
||||
}
|
||||
|
||||
document.addEventListener('mousedown', handlePointerDown)
|
||||
document.addEventListener('keydown', handleEscape)
|
||||
return () => {
|
||||
document.removeEventListener('mousedown', handlePointerDown)
|
||||
document.removeEventListener('keydown', handleEscape)
|
||||
}
|
||||
}, [openTimeDropdown])
|
||||
|
||||
const bounds = useMemo(() => resolveBounds(minDate, maxDate), [maxDate, minDate])
|
||||
const clampStartDate = useCallback((targetDate: Date) => {
|
||||
const start = startOfDay(targetDate)
|
||||
if (!bounds) return start
|
||||
if (start.getTime() < bounds.minDate.getTime()) return bounds.minDate
|
||||
if (start.getTime() > bounds.maxDate.getTime()) return startOfDay(bounds.maxDate)
|
||||
return start
|
||||
if (!bounds) return targetDate
|
||||
const min = bounds.minDate
|
||||
const max = bounds.maxDate
|
||||
if (targetDate.getTime() < min.getTime()) return min
|
||||
if (targetDate.getTime() > max.getTime()) return max
|
||||
return targetDate
|
||||
}, [bounds])
|
||||
const clampEndDate = useCallback((targetDate: Date) => {
|
||||
const end = endOfDay(targetDate)
|
||||
if (!bounds) return end
|
||||
if (end.getTime() < bounds.minDate.getTime()) return endOfDay(bounds.minDate)
|
||||
if (end.getTime() > bounds.maxDate.getTime()) return bounds.maxDate
|
||||
return end
|
||||
if (!bounds) return targetDate
|
||||
const min = bounds.minDate
|
||||
const max = bounds.maxDate
|
||||
if (targetDate.getTime() < min.getTime()) return min
|
||||
if (targetDate.getTime() > max.getTime()) return max
|
||||
return targetDate
|
||||
}, [bounds])
|
||||
|
||||
const setRangeStart = useCallback((targetDate: Date) => {
|
||||
const start = clampStartDate(targetDate)
|
||||
setDraft(prev => {
|
||||
const nextEnd = prev.dateRange.end < start ? endOfDay(start) : prev.dateRange.end
|
||||
return {
|
||||
...prev,
|
||||
preset: 'custom',
|
||||
useAllTime: false,
|
||||
dateRange: {
|
||||
start,
|
||||
end: nextEnd
|
||||
end: prev.dateRange.end
|
||||
},
|
||||
panelMonth: toMonthStart(start)
|
||||
}
|
||||
@@ -161,14 +257,13 @@ export function ExportDateRangeDialog({
|
||||
const end = clampEndDate(targetDate)
|
||||
setDraft(prev => {
|
||||
const nextStart = prev.useAllTime ? clampStartDate(targetDate) : prev.dateRange.start
|
||||
const nextEnd = end < nextStart ? endOfDay(nextStart) : end
|
||||
return {
|
||||
...prev,
|
||||
preset: 'custom',
|
||||
useAllTime: false,
|
||||
dateRange: {
|
||||
start: nextStart,
|
||||
end: nextEnd
|
||||
end: end
|
||||
},
|
||||
panelMonth: toMonthStart(targetDate)
|
||||
}
|
||||
@@ -180,6 +275,11 @@ export function ExportDateRangeDialog({
|
||||
const previewRange = bounds
|
||||
? { start: bounds.minDate, end: bounds.maxDate }
|
||||
: createDefaultDateRange()
|
||||
setTimeInput({
|
||||
start: '00:00',
|
||||
end: '23:59'
|
||||
})
|
||||
setOpenTimeDropdown(null)
|
||||
setDraft(prev => ({
|
||||
...prev,
|
||||
preset,
|
||||
@@ -196,6 +296,11 @@ export function ExportDateRangeDialog({
|
||||
useAllTime: false,
|
||||
dateRange: createDateRangeByPreset(preset)
|
||||
}, minDate, maxDate).dateRange
|
||||
setTimeInput({
|
||||
start: '00:00',
|
||||
end: '23:59'
|
||||
})
|
||||
setOpenTimeDropdown(null)
|
||||
setDraft(prev => ({
|
||||
...prev,
|
||||
preset,
|
||||
@@ -206,25 +311,149 @@ export function ExportDateRangeDialog({
|
||||
setActiveBoundary('start')
|
||||
}, [bounds, maxDate, minDate])
|
||||
|
||||
const parseTimeValue = (timeStr: string): { hours: number; minutes: number } | null => {
|
||||
const matched = /^(\d{1,2}):(\d{2})$/.exec(timeStr.trim())
|
||||
if (!matched) return null
|
||||
const hours = Number(matched[1])
|
||||
const minutes = Number(matched[2])
|
||||
if (hours < 0 || hours > 23 || minutes < 0 || minutes > 59) return null
|
||||
return { hours, minutes }
|
||||
}
|
||||
|
||||
const updateBoundaryTime = useCallback((boundary: ActiveBoundary, timeStr: string) => {
|
||||
setTimeInput(prev => ({ ...prev, [boundary]: timeStr }))
|
||||
|
||||
const parsedTime = parseTimeValue(timeStr)
|
||||
if (!parsedTime) return
|
||||
|
||||
setDraft(prev => {
|
||||
const dateObj = boundary === 'start' ? prev.dateRange.start : prev.dateRange.end
|
||||
const newDate = new Date(dateObj)
|
||||
newDate.setHours(parsedTime.hours, parsedTime.minutes, 0, 0)
|
||||
return {
|
||||
...prev,
|
||||
preset: 'custom',
|
||||
useAllTime: false,
|
||||
dateRange: {
|
||||
...prev.dateRange,
|
||||
[boundary]: newDate
|
||||
}
|
||||
}
|
||||
})
|
||||
}, [])
|
||||
|
||||
const toggleTimeDropdown = useCallback((boundary: ActiveBoundary) => {
|
||||
setActiveBoundary(boundary)
|
||||
setOpenTimeDropdown(prev => (prev === boundary ? null : boundary))
|
||||
}, [])
|
||||
|
||||
const handleTimeColumnSelect = useCallback((boundary: ActiveBoundary, field: 'hour' | 'minute', value: string) => {
|
||||
const parsedCurrent = parseTimeValue(timeInput[boundary]) ?? {
|
||||
hours: boundary === 'start' ? 0 : 23,
|
||||
minutes: boundary === 'start' ? 0 : 59
|
||||
}
|
||||
const nextHours = field === 'hour' ? Number(value) : parsedCurrent.hours
|
||||
const nextMinutes = field === 'minute' ? Number(value) : parsedCurrent.minutes
|
||||
updateBoundaryTime(boundary, `${`${nextHours}`.padStart(2, '0')}:${`${nextMinutes}`.padStart(2, '0')}`)
|
||||
}, [timeInput, updateBoundaryTime])
|
||||
|
||||
const renderTimeDropdown = (boundary: ActiveBoundary) => {
|
||||
const currentTime = timeInput[boundary]
|
||||
const parsedCurrent = parseTimeValue(currentTime) ?? {
|
||||
hours: boundary === 'start' ? 0 : 23,
|
||||
minutes: boundary === 'start' ? 0 : 59
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="export-date-range-time-dropdown" onClick={(event) => event.stopPropagation()}>
|
||||
<div className="export-date-range-time-dropdown-header">
|
||||
<span>{boundary === 'start' ? '开始时间' : '结束时间'}</span>
|
||||
<strong>{currentTime}</strong>
|
||||
</div>
|
||||
<div className="export-date-range-time-quick-list">
|
||||
{QUICK_TIME_OPTIONS.map(option => (
|
||||
<button
|
||||
key={`${boundary}-${option}`}
|
||||
type="button"
|
||||
className={`export-date-range-time-quick-item ${currentTime === option ? 'active' : ''}`}
|
||||
onClick={() => updateBoundaryTime(boundary, option)}
|
||||
>
|
||||
{option}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<div className="export-date-range-time-columns">
|
||||
<div className="export-date-range-time-column">
|
||||
<span className="export-date-range-time-column-label">小时</span>
|
||||
<div className="export-date-range-time-column-list">
|
||||
{HOUR_OPTIONS.map(option => (
|
||||
<button
|
||||
key={`${boundary}-hour-${option}`}
|
||||
type="button"
|
||||
className={`export-date-range-time-option ${parsedCurrent.hours === Number(option) ? 'active' : ''}`}
|
||||
onClick={() => handleTimeColumnSelect(boundary, 'hour', option)}
|
||||
>
|
||||
{option}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<div className="export-date-range-time-column">
|
||||
<span className="export-date-range-time-column-label">分钟</span>
|
||||
<div className="export-date-range-time-column-list">
|
||||
{MINUTE_OPTIONS.map(option => (
|
||||
<button
|
||||
key={`${boundary}-minute-${option}`}
|
||||
type="button"
|
||||
className={`export-date-range-time-option ${parsedCurrent.minutes === Number(option) ? 'active' : ''}`}
|
||||
onClick={() => handleTimeColumnSelect(boundary, 'minute', option)}
|
||||
>
|
||||
{option}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// Check if date input string contains time (YYYY-MM-DD HH:mm format)
|
||||
const dateInputHasTime = (dateStr: string): boolean => /^\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}$/.test(dateStr.trim())
|
||||
|
||||
const commitStartFromInput = useCallback(() => {
|
||||
const parsed = parseDateInputValue(dateInput.start)
|
||||
if (!parsed) {
|
||||
const parsedDate = parseDateInputValue(dateInput.start)
|
||||
if (!parsedDate) {
|
||||
setDateInputError(prev => ({ ...prev, start: true }))
|
||||
return
|
||||
}
|
||||
// Only apply time picker value if date input doesn't contain time
|
||||
if (!dateInputHasTime(dateInput.start)) {
|
||||
const parsedTime = parseTimeValue(timeInput.start)
|
||||
if (parsedTime) {
|
||||
parsedDate.setHours(parsedTime.hours, parsedTime.minutes, 0, 0)
|
||||
}
|
||||
}
|
||||
setDateInputError(prev => ({ ...prev, start: false }))
|
||||
setRangeStart(parsed)
|
||||
}, [dateInput.start, setRangeStart])
|
||||
setRangeStart(parsedDate)
|
||||
}, [dateInput.start, timeInput.start, setRangeStart])
|
||||
|
||||
const commitEndFromInput = useCallback(() => {
|
||||
const parsed = parseDateInputValue(dateInput.end)
|
||||
if (!parsed) {
|
||||
const parsedDate = parseDateInputValue(dateInput.end)
|
||||
if (!parsedDate) {
|
||||
setDateInputError(prev => ({ ...prev, end: true }))
|
||||
return
|
||||
}
|
||||
// Only apply time picker value if date input doesn't contain time
|
||||
if (!dateInputHasTime(dateInput.end)) {
|
||||
const parsedTime = parseTimeValue(timeInput.end)
|
||||
if (parsedTime) {
|
||||
parsedDate.setHours(parsedTime.hours, parsedTime.minutes, 0, 0)
|
||||
}
|
||||
}
|
||||
setDateInputError(prev => ({ ...prev, end: false }))
|
||||
setRangeEnd(parsed)
|
||||
}, [dateInput.end, setRangeEnd])
|
||||
setRangeEnd(parsedDate)
|
||||
}, [dateInput.end, timeInput.end, setRangeEnd])
|
||||
|
||||
const shiftPanelMonth = useCallback((delta: number) => {
|
||||
setDraft(prev => ({
|
||||
@@ -234,30 +463,50 @@ export function ExportDateRangeDialog({
|
||||
}, [])
|
||||
|
||||
const handleCalendarSelect = useCallback((targetDate: Date) => {
|
||||
// Use time from timeInput state (which is updated by the time picker)
|
||||
const parseTime = (timeStr: string): { hours: number; minutes: number } => {
|
||||
const matched = /^(\d{1,2}):(\d{2})$/.exec(timeStr.trim())
|
||||
if (!matched) return { hours: 0, minutes: 0 }
|
||||
return { hours: Number(matched[1]), minutes: Number(matched[2]) }
|
||||
}
|
||||
|
||||
if (activeBoundary === 'start') {
|
||||
setRangeStart(targetDate)
|
||||
const newStart = new Date(targetDate)
|
||||
const time = parseTime(timeInput.start)
|
||||
newStart.setHours(time.hours, time.minutes, 0, 0)
|
||||
setRangeStart(newStart)
|
||||
setActiveBoundary('end')
|
||||
setOpenTimeDropdown(null)
|
||||
return
|
||||
}
|
||||
|
||||
setDraft(prev => {
|
||||
const start = prev.useAllTime ? startOfDay(targetDate) : prev.dateRange.start
|
||||
const pickedStart = startOfDay(targetDate)
|
||||
const nextStart = pickedStart <= start ? pickedStart : start
|
||||
const nextEnd = pickedStart <= start ? endOfDay(start) : endOfDay(targetDate)
|
||||
return {
|
||||
...prev,
|
||||
preset: 'custom',
|
||||
useAllTime: false,
|
||||
dateRange: {
|
||||
start: nextStart,
|
||||
end: nextEnd
|
||||
},
|
||||
panelMonth: toMonthStart(targetDate)
|
||||
}
|
||||
})
|
||||
const pickedStart = startOfDay(targetDate)
|
||||
const start = draft.useAllTime ? startOfDay(targetDate) : draft.dateRange.start
|
||||
const nextStart = pickedStart <= start ? pickedStart : start
|
||||
|
||||
const newEnd = new Date(targetDate)
|
||||
const time = parseTime(timeInput.end)
|
||||
// If selecting same day or going backwards, use 23:59:59, otherwise use the time from timeInput
|
||||
if (pickedStart <= start) {
|
||||
newEnd.setHours(23, 59, 59, 999)
|
||||
setTimeInput(prev => ({ ...prev, end: '23:59' }))
|
||||
} else {
|
||||
newEnd.setHours(time.hours, time.minutes, 59, 999)
|
||||
}
|
||||
|
||||
setDraft(prev => ({
|
||||
...prev,
|
||||
preset: 'custom',
|
||||
useAllTime: false,
|
||||
dateRange: {
|
||||
start: nextStart,
|
||||
end: newEnd
|
||||
},
|
||||
panelMonth: toMonthStart(targetDate)
|
||||
}))
|
||||
setActiveBoundary('start')
|
||||
}, [activeBoundary, setRangeEnd, setRangeStart])
|
||||
setOpenTimeDropdown(null)
|
||||
}, [activeBoundary, draft.dateRange.start, draft.useAllTime, timeInput.end, timeInput.start, setRangeStart])
|
||||
|
||||
const isRangeModeActive = !draft.useAllTime
|
||||
const modeText = isRangeModeActive
|
||||
@@ -364,6 +613,23 @@ export function ExportDateRangeDialog({
|
||||
}}
|
||||
onBlur={commitStartFromInput}
|
||||
/>
|
||||
<div
|
||||
className={`export-date-range-time-select ${openTimeDropdown === 'start' ? 'open' : ''}`}
|
||||
ref={startTimeSelectRef}
|
||||
onClick={(event) => event.stopPropagation()}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
className="export-date-range-time-trigger"
|
||||
onClick={() => toggleTimeDropdown('start')}
|
||||
aria-haspopup="dialog"
|
||||
aria-expanded={openTimeDropdown === 'start'}
|
||||
>
|
||||
<span className="export-date-range-time-trigger-value">{timeInput.start}</span>
|
||||
<ChevronDown size={14} />
|
||||
</button>
|
||||
{openTimeDropdown === 'start' && renderTimeDropdown('start')}
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
className={`export-date-range-boundary-card ${activeBoundary === 'end' ? 'active' : ''}`}
|
||||
@@ -391,6 +657,23 @@ export function ExportDateRangeDialog({
|
||||
}}
|
||||
onBlur={commitEndFromInput}
|
||||
/>
|
||||
<div
|
||||
className={`export-date-range-time-select ${openTimeDropdown === 'end' ? 'open' : ''}`}
|
||||
ref={endTimeSelectRef}
|
||||
onClick={(event) => event.stopPropagation()}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
className="export-date-range-time-trigger"
|
||||
onClick={() => toggleTimeDropdown('end')}
|
||||
aria-haspopup="dialog"
|
||||
aria-expanded={openTimeDropdown === 'end'}
|
||||
>
|
||||
<span className="export-date-range-time-trigger-value">{timeInput.end}</span>
|
||||
<ChevronDown size={14} />
|
||||
</button>
|
||||
{openTimeDropdown === 'end' && renderTimeDropdown('end')}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -453,7 +736,14 @@ export function ExportDateRangeDialog({
|
||||
<button
|
||||
type="button"
|
||||
className="export-date-range-dialog-btn primary"
|
||||
onClick={() => onConfirm(cloneExportDateRangeSelection(draft))}
|
||||
onClick={() => {
|
||||
// Validate: end time should not be earlier than start time
|
||||
if (draft.dateRange.end.getTime() < draft.dateRange.start.getTime()) {
|
||||
setDateInputError({ start: true, end: true })
|
||||
return
|
||||
}
|
||||
onConfirm(cloneExportDateRangeSelection(draft))
|
||||
}}
|
||||
>
|
||||
确认
|
||||
</button>
|
||||
|
||||
@@ -15,6 +15,7 @@ export interface ExportDefaultsSettingsPatch {
|
||||
format?: string
|
||||
avatars?: boolean
|
||||
dateRange?: ExportDateRangeSelection
|
||||
fileNamingMode?: configService.ExportFileNamingMode
|
||||
media?: configService.ExportDefaultMediaConfig
|
||||
voiceAsText?: boolean
|
||||
excelCompactColumns?: boolean
|
||||
@@ -44,6 +45,11 @@ const exportExcelColumnOptions = [
|
||||
{ value: 'full', label: '完整列', desc: '含发送者昵称/微信ID/备注' }
|
||||
] as const
|
||||
|
||||
const exportFileNamingModeOptions: Array<{ value: configService.ExportFileNamingMode; label: string; desc: string }> = [
|
||||
{ value: 'classic', label: '简洁模式', desc: '示例:私聊_张三(兼容旧版)' },
|
||||
{ value: 'date-range', label: '时间范围模式', desc: '示例:私聊_张三_20250101-20250331(推荐)' }
|
||||
]
|
||||
|
||||
const exportConcurrencyOptions = [1, 2, 3, 4, 5, 6] as const
|
||||
|
||||
const getOptionLabel = (options: ReadonlyArray<{ value: string; label: string }>, value: string) => {
|
||||
@@ -56,12 +62,15 @@ export function ExportDefaultsSettingsForm({
|
||||
layout = 'stacked'
|
||||
}: ExportDefaultsSettingsFormProps) {
|
||||
const [showExportExcelColumnsSelect, setShowExportExcelColumnsSelect] = useState(false)
|
||||
const [showExportFileNamingModeSelect, setShowExportFileNamingModeSelect] = useState(false)
|
||||
const [isExportDateRangeDialogOpen, setIsExportDateRangeDialogOpen] = useState(false)
|
||||
const exportExcelColumnsDropdownRef = useRef<HTMLDivElement>(null)
|
||||
const exportFileNamingModeDropdownRef = useRef<HTMLDivElement>(null)
|
||||
|
||||
const [exportDefaultFormat, setExportDefaultFormat] = useState('excel')
|
||||
const [exportDefaultAvatars, setExportDefaultAvatars] = useState(true)
|
||||
const [exportDefaultDateRange, setExportDefaultDateRange] = useState<ExportDateRangeSelection>(() => createDefaultExportDateRangeSelection())
|
||||
const [exportDefaultFileNamingMode, setExportDefaultFileNamingMode] = useState<configService.ExportFileNamingMode>('classic')
|
||||
const [exportDefaultMedia, setExportDefaultMedia] = useState<configService.ExportDefaultMediaConfig>({
|
||||
images: true,
|
||||
videos: true,
|
||||
@@ -76,10 +85,11 @@ export function ExportDefaultsSettingsForm({
|
||||
useEffect(() => {
|
||||
let cancelled = false
|
||||
void (async () => {
|
||||
const [savedFormat, savedAvatars, savedDateRange, savedMedia, savedVoiceAsText, savedExcelCompactColumns, savedConcurrency] = await Promise.all([
|
||||
const [savedFormat, savedAvatars, savedDateRange, savedFileNamingMode, savedMedia, savedVoiceAsText, savedExcelCompactColumns, savedConcurrency] = await Promise.all([
|
||||
configService.getExportDefaultFormat(),
|
||||
configService.getExportDefaultAvatars(),
|
||||
configService.getExportDefaultDateRange(),
|
||||
configService.getExportDefaultFileNamingMode(),
|
||||
configService.getExportDefaultMedia(),
|
||||
configService.getExportDefaultVoiceAsText(),
|
||||
configService.getExportDefaultExcelCompactColumns(),
|
||||
@@ -91,6 +101,7 @@ export function ExportDefaultsSettingsForm({
|
||||
setExportDefaultFormat(savedFormat || 'excel')
|
||||
setExportDefaultAvatars(savedAvatars ?? true)
|
||||
setExportDefaultDateRange(resolveExportDateRangeConfig(savedDateRange))
|
||||
setExportDefaultFileNamingMode(savedFileNamingMode ?? 'classic')
|
||||
setExportDefaultMedia(savedMedia ?? {
|
||||
images: true,
|
||||
videos: true,
|
||||
@@ -114,15 +125,19 @@ export function ExportDefaultsSettingsForm({
|
||||
if (showExportExcelColumnsSelect && exportExcelColumnsDropdownRef.current && !exportExcelColumnsDropdownRef.current.contains(target)) {
|
||||
setShowExportExcelColumnsSelect(false)
|
||||
}
|
||||
if (showExportFileNamingModeSelect && exportFileNamingModeDropdownRef.current && !exportFileNamingModeDropdownRef.current.contains(target)) {
|
||||
setShowExportFileNamingModeSelect(false)
|
||||
}
|
||||
}
|
||||
|
||||
document.addEventListener('mousedown', handleClickOutside)
|
||||
return () => document.removeEventListener('mousedown', handleClickOutside)
|
||||
}, [showExportExcelColumnsSelect])
|
||||
}, [showExportExcelColumnsSelect, showExportFileNamingModeSelect])
|
||||
|
||||
const exportExcelColumnsValue = exportDefaultExcelCompactColumns ? 'compact' : 'full'
|
||||
const exportDateRangeLabel = useMemo(() => getExportDateRangeLabel(exportDefaultDateRange), [exportDefaultDateRange])
|
||||
const exportExcelColumnsLabel = useMemo(() => getOptionLabel(exportExcelColumnOptions, exportExcelColumnsValue), [exportExcelColumnsValue])
|
||||
const exportFileNamingModeLabel = useMemo(() => getOptionLabel(exportFileNamingModeOptions, exportDefaultFileNamingMode), [exportDefaultFileNamingMode])
|
||||
|
||||
const notify = (text: string, success = true) => {
|
||||
onNotify?.(text, success)
|
||||
@@ -224,6 +239,7 @@ export function ExportDefaultsSettingsForm({
|
||||
className={`settings-time-range-trigger ${isExportDateRangeDialogOpen ? 'open' : ''}`}
|
||||
onClick={() => {
|
||||
setShowExportExcelColumnsSelect(false)
|
||||
setShowExportFileNamingModeSelect(false)
|
||||
setIsExportDateRangeDialogOpen(true)
|
||||
}}
|
||||
>
|
||||
@@ -247,6 +263,50 @@ export function ExportDefaultsSettingsForm({
|
||||
}}
|
||||
/>
|
||||
|
||||
<div className="form-group">
|
||||
<div className="form-copy">
|
||||
<label>导出文件命名方式</label>
|
||||
<span className="form-hint">控制导出文件名是否包含时间范围</span>
|
||||
</div>
|
||||
<div className="form-control">
|
||||
<div className="select-field" ref={exportFileNamingModeDropdownRef}>
|
||||
<button
|
||||
type="button"
|
||||
className={`select-trigger ${showExportFileNamingModeSelect ? 'open' : ''}`}
|
||||
onClick={() => {
|
||||
setShowExportFileNamingModeSelect(!showExportFileNamingModeSelect)
|
||||
setShowExportExcelColumnsSelect(false)
|
||||
setIsExportDateRangeDialogOpen(false)
|
||||
}}
|
||||
>
|
||||
<span className="select-value">{exportFileNamingModeLabel}</span>
|
||||
<ChevronDown size={16} />
|
||||
</button>
|
||||
{showExportFileNamingModeSelect && (
|
||||
<div className="select-dropdown">
|
||||
{exportFileNamingModeOptions.map((option) => (
|
||||
<button
|
||||
key={option.value}
|
||||
type="button"
|
||||
className={`select-option ${exportDefaultFileNamingMode === option.value ? 'active' : ''}`}
|
||||
onClick={async () => {
|
||||
setExportDefaultFileNamingMode(option.value)
|
||||
await configService.setExportDefaultFileNamingMode(option.value)
|
||||
onDefaultsChanged?.({ fileNamingMode: option.value })
|
||||
notify('已更新导出文件命名方式', true)
|
||||
setShowExportFileNamingModeSelect(false)
|
||||
}}
|
||||
>
|
||||
<span className="option-label">{option.label}</span>
|
||||
<span className="option-desc">{option.desc}</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="form-group">
|
||||
<div className="form-copy">
|
||||
<label>Excel 列显示</label>
|
||||
@@ -259,6 +319,7 @@ export function ExportDefaultsSettingsForm({
|
||||
className={`select-trigger ${showExportExcelColumnsSelect ? 'open' : ''}`}
|
||||
onClick={() => {
|
||||
setShowExportExcelColumnsSelect(!showExportExcelColumnsSelect)
|
||||
setShowExportFileNamingModeSelect(false)
|
||||
setIsExportDateRangeDialogOpen(false)
|
||||
}}
|
||||
>
|
||||
|
||||
@@ -275,263 +275,6 @@
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.sidebar-dialog-overlay {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
background: rgba(15, 23, 42, 0.3);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
z-index: 1100;
|
||||
padding: 20px;
|
||||
animation: fadeIn 0.2s ease;
|
||||
}
|
||||
|
||||
@keyframes fadeIn {
|
||||
from {
|
||||
opacity: 0;
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
|
||||
.sidebar-dialog {
|
||||
width: min(420px, 100%);
|
||||
background: var(--bg-secondary);
|
||||
border: 1px solid var(--border-color);
|
||||
border-radius: 16px;
|
||||
box-shadow: 0 18px 40px rgba(15, 23, 42, 0.24);
|
||||
padding: 18px 18px 16px;
|
||||
animation: slideUp 0.25s ease;
|
||||
|
||||
h3 {
|
||||
margin: 0;
|
||||
font-size: 16px;
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
p {
|
||||
margin: 10px 0 0;
|
||||
font-size: 13px;
|
||||
line-height: 1.6;
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes slideUp {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translateY(20px) scale(0.95);
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: translateY(0) scale(1);
|
||||
}
|
||||
}
|
||||
|
||||
.sidebar-wxid-list {
|
||||
margin-top: 14px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
max-height: 300px;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.sidebar-wxid-item {
|
||||
width: 100%;
|
||||
padding: 12px 14px;
|
||||
border: 1px solid var(--border-color);
|
||||
border-radius: 10px;
|
||||
background: var(--bg-secondary);
|
||||
color: var(--text-primary);
|
||||
font-size: 13px;
|
||||
cursor: pointer;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
transition: all 0.2s ease;
|
||||
|
||||
&:hover:not(:disabled) {
|
||||
border-color: rgba(99, 102, 241, 0.32);
|
||||
background: var(--bg-tertiary);
|
||||
}
|
||||
|
||||
&.current {
|
||||
border-color: rgba(99, 102, 241, 0.5);
|
||||
background: var(--bg-tertiary);
|
||||
}
|
||||
|
||||
&:disabled {
|
||||
cursor: not-allowed;
|
||||
opacity: 0.6;
|
||||
}
|
||||
|
||||
.wxid-avatar {
|
||||
width: 40px;
|
||||
height: 40px;
|
||||
border-radius: 10px;
|
||||
overflow: hidden;
|
||||
background: linear-gradient(135deg, var(--primary), var(--primary-hover));
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
flex-shrink: 0;
|
||||
|
||||
img {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: cover;
|
||||
}
|
||||
|
||||
span {
|
||||
color: var(--on-primary);
|
||||
font-size: 16px;
|
||||
font-weight: 600;
|
||||
}
|
||||
}
|
||||
|
||||
.wxid-info {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.wxid-name {
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
color: var(--text-primary);
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.wxid-id {
|
||||
margin-top: 2px;
|
||||
font-size: 12px;
|
||||
color: var(--text-tertiary);
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.current-badge {
|
||||
padding: 4px 10px;
|
||||
border-radius: 6px;
|
||||
background: var(--primary);
|
||||
color: var(--on-primary);
|
||||
font-size: 11px;
|
||||
font-weight: 600;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
}
|
||||
|
||||
.sidebar-dialog-actions {
|
||||
margin-top: 18px;
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
gap: 10px;
|
||||
|
||||
button {
|
||||
border: 1px solid var(--border-color);
|
||||
border-radius: 10px;
|
||||
padding: 8px 14px;
|
||||
font-size: 13px;
|
||||
cursor: pointer;
|
||||
background: var(--bg-secondary);
|
||||
color: var(--text-primary);
|
||||
transition: all 0.2s ease;
|
||||
|
||||
&:hover:not(:disabled) {
|
||||
background: var(--bg-tertiary);
|
||||
}
|
||||
|
||||
&:disabled {
|
||||
cursor: not-allowed;
|
||||
opacity: 0.6;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.sidebar-clear-dialog-overlay {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
background: rgba(15, 23, 42, 0.3);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
z-index: 1100;
|
||||
padding: 20px;
|
||||
animation: fadeIn 0.2s ease;
|
||||
}
|
||||
|
||||
.sidebar-clear-dialog {
|
||||
width: min(460px, 100%);
|
||||
background: var(--bg-secondary);
|
||||
border: 1px solid var(--border-color);
|
||||
border-radius: 16px;
|
||||
box-shadow: 0 18px 40px rgba(15, 23, 42, 0.24);
|
||||
padding: 18px 18px 16px;
|
||||
animation: slideUp 0.25s ease;
|
||||
|
||||
h3 {
|
||||
margin: 0;
|
||||
font-size: 16px;
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
p {
|
||||
margin: 10px 0 0;
|
||||
font-size: 13px;
|
||||
line-height: 1.6;
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
}
|
||||
|
||||
.sidebar-clear-options {
|
||||
margin-top: 14px;
|
||||
display: flex;
|
||||
gap: 14px;
|
||||
flex-wrap: wrap;
|
||||
|
||||
label {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
font-size: 13px;
|
||||
color: var(--text-primary);
|
||||
}
|
||||
}
|
||||
|
||||
.sidebar-clear-actions {
|
||||
margin-top: 18px;
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
gap: 10px;
|
||||
|
||||
button {
|
||||
border: 1px solid var(--border-color);
|
||||
border-radius: 10px;
|
||||
padding: 8px 14px;
|
||||
font-size: 13px;
|
||||
cursor: pointer;
|
||||
background: var(--bg-secondary);
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
button:disabled {
|
||||
cursor: not-allowed;
|
||||
opacity: 0.6;
|
||||
}
|
||||
|
||||
.danger {
|
||||
border-color: #ef4444;
|
||||
background: #ef4444;
|
||||
color: #fff;
|
||||
}
|
||||
}
|
||||
|
||||
// 繁花如梦主题:侧边栏毛玻璃 + 激活项用主品牌色
|
||||
[data-theme="blossom-dream"] .sidebar {
|
||||
background: rgba(255, 255, 255, 0.6);
|
||||
|
||||
@@ -1,12 +1,9 @@
|
||||
import { useState, useEffect, useRef } from 'react'
|
||||
import { NavLink, useLocation, useNavigate } from 'react-router-dom'
|
||||
import { Home, MessageSquare, BarChart3, FileText, Settings, Download, Aperture, UserCircle, Lock, LockOpen, ChevronUp, RefreshCw, FolderClosed } from 'lucide-react'
|
||||
import { Home, MessageSquare, BarChart3, FileText, Settings, Download, Aperture, UserCircle, Lock, LockOpen, ChevronUp, FolderClosed, Footprints, Users } from 'lucide-react'
|
||||
import { useAppStore } from '../stores/appStore'
|
||||
import { useChatStore } from '../stores/chatStore'
|
||||
import { useAnalyticsStore } from '../stores/analyticsStore'
|
||||
import * as configService from '../services/config'
|
||||
import { onExportSessionStatus, requestExportSessionStatus } from '../services/exportBridge'
|
||||
import { UserRound } from 'lucide-react'
|
||||
|
||||
import './Sidebar.scss'
|
||||
|
||||
@@ -19,6 +16,8 @@ interface SidebarUserProfile {
|
||||
|
||||
const SIDEBAR_USER_PROFILE_CACHE_KEY = 'sidebar_user_profile_cache_v1'
|
||||
const ACCOUNT_PROFILES_CACHE_KEY = 'account_profiles_cache_v1'
|
||||
const DEFAULT_DISPLAY_NAME = '微信用户'
|
||||
const DEFAULT_SUBTITLE = '微信账号'
|
||||
|
||||
interface SidebarUserProfileCache extends SidebarUserProfile {
|
||||
updatedAt: number
|
||||
@@ -33,24 +32,16 @@ interface AccountProfilesCache {
|
||||
}
|
||||
}
|
||||
|
||||
interface WxidOption {
|
||||
wxid: string
|
||||
modifiedTime: number
|
||||
nickname?: string
|
||||
displayName?: string
|
||||
avatarUrl?: string
|
||||
}
|
||||
|
||||
const readSidebarUserProfileCache = (): SidebarUserProfile | null => {
|
||||
try {
|
||||
const raw = window.localStorage.getItem(SIDEBAR_USER_PROFILE_CACHE_KEY)
|
||||
if (!raw) return null
|
||||
const parsed = JSON.parse(raw) as SidebarUserProfileCache
|
||||
if (!parsed || typeof parsed !== 'object') return null
|
||||
if (!parsed.wxid || !parsed.displayName) return null
|
||||
if (!parsed.wxid) return null
|
||||
return {
|
||||
wxid: parsed.wxid,
|
||||
displayName: parsed.displayName,
|
||||
displayName: typeof parsed.displayName === 'string' ? parsed.displayName : '',
|
||||
alias: parsed.alias,
|
||||
avatarUrl: parsed.avatarUrl
|
||||
}
|
||||
@@ -60,7 +51,7 @@ const readSidebarUserProfileCache = (): SidebarUserProfile | null => {
|
||||
}
|
||||
|
||||
const writeSidebarUserProfileCache = (profile: SidebarUserProfile): void => {
|
||||
if (!profile.wxid || !profile.displayName) return
|
||||
if (!profile.wxid) return
|
||||
try {
|
||||
const payload: SidebarUserProfileCache = {
|
||||
...profile,
|
||||
@@ -115,17 +106,11 @@ function Sidebar({ collapsed }: SidebarProps) {
|
||||
const [activeExportTaskCount, setActiveExportTaskCount] = useState(0)
|
||||
const [userProfile, setUserProfile] = useState<SidebarUserProfile>({
|
||||
wxid: '',
|
||||
displayName: '未识别用户'
|
||||
displayName: DEFAULT_DISPLAY_NAME
|
||||
})
|
||||
const [isAccountMenuOpen, setIsAccountMenuOpen] = useState(false)
|
||||
const [showSwitchAccountDialog, setShowSwitchAccountDialog] = useState(false)
|
||||
const [wxidOptions, setWxidOptions] = useState<WxidOption[]>([])
|
||||
const [isSwitchingAccount, setIsSwitchingAccount] = useState(false)
|
||||
const accountCardWrapRef = useRef<HTMLDivElement | null>(null)
|
||||
const setLocked = useAppStore(state => state.setLocked)
|
||||
const isDbConnected = useAppStore(state => state.isDbConnected)
|
||||
const resetChatStore = useChatStore(state => state.reset)
|
||||
const clearAnalyticsStoreCache = useAnalyticsStore(state => state.clearCache)
|
||||
|
||||
useEffect(() => {
|
||||
window.electronAPI.auth.verifyEnabled().then(setAuthEnabled)
|
||||
@@ -164,18 +149,20 @@ function Sidebar({ collapsed }: SidebarProps) {
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
let disposed = false
|
||||
let loadSeq = 0
|
||||
|
||||
const loadCurrentUser = async () => {
|
||||
const patchUserProfile = (patch: Partial<SidebarUserProfile>, expectedWxid?: string) => {
|
||||
const seq = ++loadSeq
|
||||
const patchUserProfile = (patch: Partial<SidebarUserProfile>) => {
|
||||
if (disposed || seq !== loadSeq) return
|
||||
setUserProfile(prev => {
|
||||
if (expectedWxid && prev.wxid && prev.wxid !== expectedWxid) {
|
||||
return prev
|
||||
}
|
||||
const next: SidebarUserProfile = {
|
||||
...prev,
|
||||
...patch
|
||||
}
|
||||
if (!next.displayName) {
|
||||
next.displayName = next.wxid || '未识别用户'
|
||||
if (typeof next.displayName !== 'string' || next.displayName.length === 0) {
|
||||
next.displayName = DEFAULT_DISPLAY_NAME
|
||||
}
|
||||
writeSidebarUserProfileCache(next)
|
||||
return next
|
||||
@@ -184,11 +171,33 @@ function Sidebar({ collapsed }: SidebarProps) {
|
||||
|
||||
try {
|
||||
const wxid = await configService.getMyWxid()
|
||||
if (disposed || seq !== loadSeq) return
|
||||
const resolvedWxidRaw = String(wxid || '').trim()
|
||||
const cleanedWxid = normalizeAccountId(resolvedWxidRaw)
|
||||
const resolvedWxid = cleanedWxid || resolvedWxidRaw
|
||||
|
||||
if (!resolvedWxidRaw && !resolvedWxid) return
|
||||
if (!resolvedWxidRaw && !resolvedWxid) {
|
||||
window.localStorage.removeItem(SIDEBAR_USER_PROFILE_CACHE_KEY)
|
||||
patchUserProfile({
|
||||
wxid: '',
|
||||
displayName: DEFAULT_DISPLAY_NAME,
|
||||
alias: undefined,
|
||||
avatarUrl: undefined
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
setUserProfile((prev) => {
|
||||
if (prev.wxid === resolvedWxid) return prev
|
||||
const seeded: SidebarUserProfile = {
|
||||
wxid: resolvedWxid,
|
||||
displayName: DEFAULT_DISPLAY_NAME,
|
||||
alias: undefined,
|
||||
avatarUrl: undefined
|
||||
}
|
||||
writeSidebarUserProfileCache(seeded)
|
||||
return seeded
|
||||
})
|
||||
|
||||
const wxidCandidates = new Set<string>([
|
||||
resolvedWxidRaw.toLowerCase(),
|
||||
@@ -197,14 +206,13 @@ function Sidebar({ collapsed }: SidebarProps) {
|
||||
].filter(Boolean))
|
||||
|
||||
const normalizeName = (value?: string | null): string | undefined => {
|
||||
if (!value) return undefined
|
||||
const trimmed = value.trim()
|
||||
if (!trimmed) return undefined
|
||||
const lowered = trimmed.toLowerCase()
|
||||
if (typeof value !== 'string') return undefined
|
||||
if (value.length === 0) return undefined
|
||||
const lowered = value.trim().toLowerCase()
|
||||
if (lowered === 'self') return undefined
|
||||
if (lowered.startsWith('wxid_')) return undefined
|
||||
if (wxidCandidates.has(lowered)) return undefined
|
||||
return trimmed
|
||||
return value
|
||||
}
|
||||
|
||||
const pickFirstValidName = (...candidates: Array<string | null | undefined>): string | undefined => {
|
||||
@@ -229,18 +237,20 @@ function Sidebar({ collapsed }: SidebarProps) {
|
||||
})(),
|
||||
window.electronAPI.chat.getMyAvatarUrl()
|
||||
])
|
||||
if (disposed || seq !== loadSeq) return
|
||||
|
||||
const myContact = contactResult.status === 'fulfilled' ? contactResult.value : null
|
||||
const displayName = pickFirstValidName(
|
||||
myContact?.remark,
|
||||
myContact?.nickName,
|
||||
myContact?.alias
|
||||
) || resolvedWxid || '未识别用户'
|
||||
) || DEFAULT_DISPLAY_NAME
|
||||
const alias = normalizeName(myContact?.alias)
|
||||
|
||||
patchUserProfile({
|
||||
wxid: resolvedWxid,
|
||||
displayName,
|
||||
alias: myContact?.alias,
|
||||
alias,
|
||||
avatarUrl: avatarResult.status === 'fulfilled' && avatarResult.value.success
|
||||
? avatarResult.value.avatarUrl
|
||||
: undefined
|
||||
@@ -257,118 +267,28 @@ function Sidebar({ collapsed }: SidebarProps) {
|
||||
|
||||
void loadCurrentUser()
|
||||
const onWxidChanged = () => { void loadCurrentUser() }
|
||||
const onWindowFocus = () => { void loadCurrentUser() }
|
||||
const onVisibilityChange = () => {
|
||||
if (document.visibilityState === 'visible') {
|
||||
void loadCurrentUser()
|
||||
}
|
||||
}
|
||||
window.addEventListener('wxid-changed', onWxidChanged as EventListener)
|
||||
return () => window.removeEventListener('wxid-changed', onWxidChanged as EventListener)
|
||||
window.addEventListener('focus', onWindowFocus)
|
||||
document.addEventListener('visibilitychange', onVisibilityChange)
|
||||
return () => {
|
||||
disposed = true
|
||||
loadSeq += 1
|
||||
window.removeEventListener('wxid-changed', onWxidChanged as EventListener)
|
||||
window.removeEventListener('focus', onWindowFocus)
|
||||
document.removeEventListener('visibilitychange', onVisibilityChange)
|
||||
}
|
||||
}, [])
|
||||
|
||||
const getAvatarLetter = (name: string): string => {
|
||||
if (!name) return '?'
|
||||
return [...name][0] || '?'
|
||||
}
|
||||
|
||||
const openSwitchAccountDialog = async () => {
|
||||
setIsAccountMenuOpen(false)
|
||||
if (!isDbConnected) {
|
||||
window.alert('数据库未连接,无法切换账号')
|
||||
return
|
||||
}
|
||||
const dbPath = await configService.getDbPath()
|
||||
if (!dbPath) {
|
||||
window.alert('请先在设置中配置数据库路径')
|
||||
return
|
||||
}
|
||||
try {
|
||||
const wxids = await window.electronAPI.dbPath.scanWxids(dbPath)
|
||||
const accountsCache = readAccountProfilesCache()
|
||||
console.log('[切换账号] 账号缓存:', accountsCache)
|
||||
|
||||
const enrichedWxids = wxids.map((option: WxidOption) => {
|
||||
const normalizedWxid = normalizeAccountId(option.wxid)
|
||||
const cached = accountsCache[option.wxid] || accountsCache[normalizedWxid]
|
||||
|
||||
let displayName = option.nickname || option.wxid
|
||||
let avatarUrl = option.avatarUrl
|
||||
|
||||
if (option.wxid === userProfile.wxid || normalizedWxid === userProfile.wxid) {
|
||||
displayName = userProfile.displayName || displayName
|
||||
avatarUrl = userProfile.avatarUrl || avatarUrl
|
||||
}
|
||||
|
||||
else if (cached) {
|
||||
displayName = cached.displayName || displayName
|
||||
avatarUrl = cached.avatarUrl || avatarUrl
|
||||
}
|
||||
|
||||
return {
|
||||
...option,
|
||||
displayName,
|
||||
avatarUrl
|
||||
}
|
||||
})
|
||||
|
||||
setWxidOptions(enrichedWxids)
|
||||
setShowSwitchAccountDialog(true)
|
||||
} catch (error) {
|
||||
console.error('扫描账号失败:', error)
|
||||
window.alert('扫描账号失败,请稍后重试')
|
||||
}
|
||||
}
|
||||
|
||||
const handleSwitchAccount = async (selectedWxid: string) => {
|
||||
if (!selectedWxid || isSwitchingAccount) return
|
||||
setIsSwitchingAccount(true)
|
||||
try {
|
||||
console.log('[切换账号] 开始切换到:', selectedWxid)
|
||||
const currentWxid = userProfile.wxid
|
||||
if (currentWxid === selectedWxid) {
|
||||
console.log('[切换账号] 已经是当前账号,跳过')
|
||||
setShowSwitchAccountDialog(false)
|
||||
setIsSwitchingAccount(false)
|
||||
return
|
||||
}
|
||||
|
||||
console.log('[切换账号] 设置新 wxid')
|
||||
await configService.setMyWxid(selectedWxid)
|
||||
|
||||
console.log('[切换账号] 获取账号配置')
|
||||
const wxidConfig = await configService.getWxidConfig(selectedWxid)
|
||||
console.log('[切换账号] 配置内容:', wxidConfig)
|
||||
if (wxidConfig?.decryptKey) {
|
||||
console.log('[切换账号] 设置 decryptKey')
|
||||
await configService.setDecryptKey(wxidConfig.decryptKey)
|
||||
}
|
||||
if (typeof wxidConfig?.imageXorKey === 'number') {
|
||||
console.log('[切换账号] 设置 imageXorKey:', wxidConfig.imageXorKey)
|
||||
await configService.setImageXorKey(wxidConfig.imageXorKey)
|
||||
}
|
||||
if (wxidConfig?.imageAesKey) {
|
||||
console.log('[切换账号] 设置 imageAesKey')
|
||||
await configService.setImageAesKey(wxidConfig.imageAesKey)
|
||||
}
|
||||
|
||||
console.log('[切换账号] 检查数据库连接状态')
|
||||
console.log('[切换账号] 数据库连接状态:', isDbConnected)
|
||||
if (isDbConnected) {
|
||||
console.log('[切换账号] 关闭数据库连接')
|
||||
await window.electronAPI.chat.close()
|
||||
}
|
||||
|
||||
console.log('[切换账号] 清除缓存')
|
||||
window.localStorage.removeItem(SIDEBAR_USER_PROFILE_CACHE_KEY)
|
||||
clearAnalyticsStoreCache()
|
||||
resetChatStore()
|
||||
|
||||
console.log('[切换账号] 触发 wxid-changed 事件')
|
||||
window.dispatchEvent(new CustomEvent('wxid-changed', { detail: { wxid: selectedWxid } }))
|
||||
|
||||
console.log('[切换账号] 切换成功')
|
||||
setShowSwitchAccountDialog(false)
|
||||
} catch (error) {
|
||||
console.error('[切换账号] 失败:', error)
|
||||
window.alert('切换账号失败,请稍后重试')
|
||||
} finally {
|
||||
setIsSwitchingAccount(false)
|
||||
}
|
||||
if (!name) return '微'
|
||||
const visible = name.trim()
|
||||
return (visible && [...visible][0]) || '微'
|
||||
}
|
||||
|
||||
const openSettingsFromAccountMenu = () => {
|
||||
@@ -380,6 +300,11 @@ function Sidebar({ collapsed }: SidebarProps) {
|
||||
})
|
||||
}
|
||||
|
||||
const openAccountManagement = () => {
|
||||
setIsAccountMenuOpen(false)
|
||||
navigate('/account-management')
|
||||
}
|
||||
|
||||
const isActive = (path: string) => {
|
||||
return location.pathname === path || location.pathname.startsWith(`${path}/`)
|
||||
}
|
||||
@@ -459,6 +384,16 @@ function Sidebar({ collapsed }: SidebarProps) {
|
||||
<span className="nav-label">年度报告</span>
|
||||
</NavLink>
|
||||
|
||||
{/* 我的足迹 */}
|
||||
<NavLink
|
||||
to="/footprint"
|
||||
className={`nav-item ${isActive('/footprint') ? 'active' : ''}`}
|
||||
title={collapsed ? '我的足迹' : undefined}
|
||||
>
|
||||
<span className="nav-icon"><Footprints size={20} /></span>
|
||||
<span className="nav-label">我的足迹</span>
|
||||
</NavLink>
|
||||
|
||||
{/* 导出 */}
|
||||
<NavLink
|
||||
to="/export"
|
||||
@@ -505,12 +440,12 @@ function Sidebar({ collapsed }: SidebarProps) {
|
||||
<div className={`sidebar-user-menu ${isAccountMenuOpen ? 'open' : ''}`} role="menu" aria-label="账号菜单">
|
||||
<button
|
||||
className="sidebar-user-menu-item"
|
||||
onClick={openSwitchAccountDialog}
|
||||
onClick={openAccountManagement}
|
||||
type="button"
|
||||
role="menuitem"
|
||||
>
|
||||
<RefreshCw size={14} />
|
||||
<span>切换账号</span>
|
||||
<Users size={14} />
|
||||
<span>账号管理</span>
|
||||
</button>
|
||||
<button
|
||||
className="sidebar-user-menu-item"
|
||||
@@ -524,7 +459,7 @@ function Sidebar({ collapsed }: SidebarProps) {
|
||||
</div>
|
||||
<div
|
||||
className={`sidebar-user-card ${isAccountMenuOpen ? 'menu-open' : ''}`}
|
||||
title={collapsed ? `${userProfile.displayName}${(userProfile.alias || userProfile.wxid) ? `\n${userProfile.alias || userProfile.wxid}` : ''}` : undefined}
|
||||
title={collapsed ? `${userProfile.displayName}${(userProfile.alias) ? `\n${userProfile.alias}` : ''}` : undefined}
|
||||
onClick={() => setIsAccountMenuOpen(prev => !prev)}
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
@@ -539,8 +474,8 @@ function Sidebar({ collapsed }: SidebarProps) {
|
||||
{userProfile.avatarUrl ? <img src={userProfile.avatarUrl} alt="" /> : <span>{getAvatarLetter(userProfile.displayName)}</span>}
|
||||
</div>
|
||||
<div className="user-meta">
|
||||
<div className="user-name">{userProfile.displayName}</div>
|
||||
<div className="user-wxid">{userProfile.alias || userProfile.wxid || 'wxid 未识别'}</div>
|
||||
<div className="user-name">{userProfile.displayName || DEFAULT_DISPLAY_NAME}</div>
|
||||
<div className="user-wxid">{userProfile.alias || DEFAULT_SUBTITLE}</div>
|
||||
</div>
|
||||
{!collapsed && (
|
||||
<span className={`user-menu-caret ${isAccountMenuOpen ? 'open' : ''}`}>
|
||||
@@ -551,44 +486,6 @@ function Sidebar({ collapsed }: SidebarProps) {
|
||||
</div>
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
{showSwitchAccountDialog && (
|
||||
<div className="sidebar-dialog-overlay" onClick={() => !isSwitchingAccount && setShowSwitchAccountDialog(false)}>
|
||||
<div className="sidebar-dialog" role="dialog" aria-modal="true" onClick={(event) => event.stopPropagation()}>
|
||||
<h3>切换账号</h3>
|
||||
<p>选择要切换的微信账号</p>
|
||||
<div className="sidebar-wxid-list">
|
||||
{wxidOptions.map((option) => (
|
||||
<button
|
||||
key={option.wxid}
|
||||
className={`sidebar-wxid-item ${userProfile.wxid === option.wxid ? 'current' : ''}`}
|
||||
onClick={() => handleSwitchAccount(option.wxid)}
|
||||
disabled={isSwitchingAccount}
|
||||
type="button"
|
||||
>
|
||||
<div className="wxid-avatar">
|
||||
{option.avatarUrl ? (
|
||||
<img src={option.avatarUrl} alt="" />
|
||||
) : (
|
||||
<div style={{ width: '100%', height: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center', background: 'var(--bg-tertiary)', borderRadius: '6px', color: 'var(--text-tertiary)' }}>
|
||||
<UserRound size={16} />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="wxid-info">
|
||||
<div className="wxid-name">{option.displayName}</div>
|
||||
{option.displayName !== option.wxid && <div className="wxid-id">{option.wxid}</div>}
|
||||
</div>
|
||||
{userProfile.wxid === option.wxid && <span className="current-badge">当前</span>}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<div className="sidebar-dialog-actions">
|
||||
<button type="button" onClick={() => setShowSwitchAccountDialog(false)} disabled={isSwitchingAccount}>取消</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
274
src/pages/AccountManagementPage.scss
Normal file
274
src/pages/AccountManagementPage.scss
Normal file
@@ -0,0 +1,274 @@
|
||||
.account-management-page {
|
||||
padding: 22px 24px;
|
||||
min-height: 100%;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 14px;
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.account-management-header {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
|
||||
h2 {
|
||||
margin: 0;
|
||||
font-size: 22px;
|
||||
font-weight: 700;
|
||||
letter-spacing: -0.01em;
|
||||
}
|
||||
|
||||
p {
|
||||
margin: 6px 0 0;
|
||||
color: var(--text-secondary);
|
||||
font-size: 13px;
|
||||
}
|
||||
}
|
||||
|
||||
.account-management-actions {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.account-management-summary {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(3, minmax(0, 1fr));
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.summary-item {
|
||||
border: 1px solid var(--border-color);
|
||||
border-radius: 12px;
|
||||
background: var(--bg-secondary);
|
||||
padding: 10px 12px;
|
||||
}
|
||||
|
||||
.summary-label {
|
||||
display: block;
|
||||
font-size: 11px;
|
||||
color: var(--text-tertiary);
|
||||
}
|
||||
|
||||
.summary-value {
|
||||
display: block;
|
||||
margin-top: 4px;
|
||||
font-size: 13px;
|
||||
color: var(--text-primary);
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.account-notice {
|
||||
border-radius: 10px;
|
||||
padding: 10px 12px;
|
||||
font-size: 13px;
|
||||
border: 1px solid transparent;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.notice-action {
|
||||
border: 1px solid currentColor;
|
||||
border-radius: 999px;
|
||||
background: transparent;
|
||||
color: inherit;
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
padding: 4px 10px;
|
||||
cursor: pointer;
|
||||
white-space: nowrap;
|
||||
transition: opacity 0.2s ease, background 0.2s ease;
|
||||
|
||||
&:hover:not(:disabled) {
|
||||
background: rgba(255, 255, 255, 0.35);
|
||||
}
|
||||
|
||||
&:disabled {
|
||||
opacity: 0.6;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
}
|
||||
|
||||
.account-notice.success {
|
||||
background: rgba(34, 197, 94, 0.12);
|
||||
color: #15803d;
|
||||
border-color: rgba(34, 197, 94, 0.25);
|
||||
}
|
||||
|
||||
.account-notice.error {
|
||||
background: rgba(239, 68, 68, 0.12);
|
||||
color: #b91c1c;
|
||||
border-color: rgba(239, 68, 68, 0.25);
|
||||
}
|
||||
|
||||
.account-notice.info {
|
||||
background: rgba(59, 130, 246, 0.12);
|
||||
color: #1d4ed8;
|
||||
border-color: rgba(59, 130, 246, 0.25);
|
||||
}
|
||||
|
||||
.account-empty {
|
||||
border: 1px dashed var(--border-color);
|
||||
border-radius: 12px;
|
||||
background: var(--bg-secondary);
|
||||
padding: 18px 14px;
|
||||
color: var(--text-secondary);
|
||||
font-size: 13px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.account-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.account-card {
|
||||
border: 1px solid var(--border-color);
|
||||
border-radius: 14px;
|
||||
background: var(--bg-secondary);
|
||||
padding: 12px;
|
||||
display: flex;
|
||||
gap: 12px;
|
||||
|
||||
&.is-current {
|
||||
border-color: color-mix(in srgb, var(--primary) 60%, var(--border-color));
|
||||
box-shadow: 0 0 0 1px color-mix(in srgb, var(--primary) 25%, transparent);
|
||||
}
|
||||
}
|
||||
|
||||
.account-avatar {
|
||||
width: 42px;
|
||||
height: 42px;
|
||||
border-radius: 10px;
|
||||
overflow: hidden;
|
||||
background: linear-gradient(135deg, var(--primary), var(--primary-hover));
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
flex-shrink: 0;
|
||||
|
||||
img {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: cover;
|
||||
}
|
||||
|
||||
span {
|
||||
color: var(--on-primary);
|
||||
font-weight: 600;
|
||||
font-size: 14px;
|
||||
}
|
||||
}
|
||||
|
||||
.account-main {
|
||||
min-width: 0;
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.account-title-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
flex-wrap: wrap;
|
||||
|
||||
h3 {
|
||||
margin: 0;
|
||||
font-size: 15px;
|
||||
color: var(--text-primary);
|
||||
}
|
||||
}
|
||||
|
||||
.account-badge {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
border-radius: 999px;
|
||||
padding: 1px 8px;
|
||||
font-size: 11px;
|
||||
font-weight: 600;
|
||||
|
||||
&.current {
|
||||
color: #0f766e;
|
||||
background: rgba(20, 184, 166, 0.14);
|
||||
}
|
||||
|
||||
&.ok {
|
||||
color: #166534;
|
||||
background: rgba(34, 197, 94, 0.12);
|
||||
}
|
||||
|
||||
&.warn {
|
||||
color: #b45309;
|
||||
background: rgba(245, 158, 11, 0.15);
|
||||
}
|
||||
}
|
||||
|
||||
.account-meta {
|
||||
margin-top: 3px;
|
||||
font-size: 12px;
|
||||
color: var(--text-tertiary);
|
||||
word-break: break-all;
|
||||
}
|
||||
|
||||
.meta-tip {
|
||||
margin-left: 6px;
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
.account-card-actions {
|
||||
display: inline-flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
align-items: stretch;
|
||||
|
||||
.btn {
|
||||
min-width: 104px;
|
||||
justify-content: center;
|
||||
}
|
||||
}
|
||||
|
||||
.account-management-footer {
|
||||
margin-top: 2px;
|
||||
color: var(--text-tertiary);
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.account-management-page {
|
||||
.btn-danger {
|
||||
background: rgba(239, 68, 68, 0.12);
|
||||
color: #b91c1c;
|
||||
|
||||
&:hover:not(:disabled) {
|
||||
background: rgba(239, 68, 68, 0.2);
|
||||
}
|
||||
}
|
||||
|
||||
.btn:disabled {
|
||||
opacity: 0.55;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 920px) {
|
||||
.account-management-summary {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
|
||||
.account-card {
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.account-card-actions {
|
||||
flex-direction: row;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
}
|
||||
574
src/pages/AccountManagementPage.tsx
Normal file
574
src/pages/AccountManagementPage.tsx
Normal file
@@ -0,0 +1,574 @@
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react'
|
||||
import { RefreshCw, UserPlus, Trash2, ArrowRightLeft, CheckCircle2, Database } from 'lucide-react'
|
||||
import { useAppStore } from '../stores/appStore'
|
||||
import { useChatStore } from '../stores/chatStore'
|
||||
import { useAnalyticsStore } from '../stores/analyticsStore'
|
||||
import * as configService from '../services/config'
|
||||
import './AccountManagementPage.scss'
|
||||
|
||||
interface ScannedWxidOption {
|
||||
wxid: string
|
||||
modifiedTime: number
|
||||
nickname?: string
|
||||
avatarUrl?: string
|
||||
}
|
||||
|
||||
interface ManagedAccountItem {
|
||||
wxid: string
|
||||
normalizedWxid: string
|
||||
displayName: string
|
||||
avatarUrl?: string
|
||||
modifiedTime?: number
|
||||
configUpdatedAt?: number
|
||||
hasConfig: boolean
|
||||
isCurrent: boolean
|
||||
fromScan: boolean
|
||||
}
|
||||
|
||||
type AccountProfileCacheEntry = {
|
||||
displayName?: string
|
||||
avatarUrl?: string
|
||||
updatedAt?: number
|
||||
}
|
||||
|
||||
interface DeleteUndoState {
|
||||
targetWxid: string
|
||||
deletedConfigEntries: Array<[string, configService.WxidConfig]>
|
||||
deletedProfileEntries: Array<[string, AccountProfileCacheEntry]>
|
||||
previousCurrentWxid: string
|
||||
shouldRestoreAsCurrent: boolean
|
||||
previousDbConnected: boolean
|
||||
}
|
||||
|
||||
type NoticeState =
|
||||
| { type: 'success' | 'error' | 'info'; text: string }
|
||||
| null
|
||||
|
||||
const SIDEBAR_USER_PROFILE_CACHE_KEY = 'sidebar_user_profile_cache_v1'
|
||||
const ACCOUNT_PROFILES_CACHE_KEY = 'account_profiles_cache_v1'
|
||||
const hiddenDeletedAccountIds = new Set<string>()
|
||||
const DEFAULT_ACCOUNT_DISPLAY_NAME = '微信用户'
|
||||
|
||||
const normalizeAccountId = (value?: string | null): string => {
|
||||
const trimmed = String(value || '').trim()
|
||||
if (!trimmed) return ''
|
||||
if (trimmed.toLowerCase().startsWith('wxid_')) {
|
||||
const match = trimmed.match(/^(wxid_[^_]+)/i)
|
||||
return match?.[1] || trimmed
|
||||
}
|
||||
const suffixMatch = trimmed.match(/^(.+)_([a-zA-Z0-9]{4})$/)
|
||||
return suffixMatch ? suffixMatch[1] : trimmed
|
||||
}
|
||||
|
||||
const resolveAccountDisplayName = (
|
||||
candidates: Array<unknown>,
|
||||
wxidCandidates: Set<string>
|
||||
): string => {
|
||||
for (const candidate of candidates) {
|
||||
if (typeof candidate !== 'string') continue
|
||||
if (candidate.length === 0) continue
|
||||
const normalized = candidate.trim().toLowerCase()
|
||||
if (normalized.startsWith('wxid_')) continue
|
||||
if (normalized && wxidCandidates.has(normalized)) continue
|
||||
return candidate
|
||||
}
|
||||
return DEFAULT_ACCOUNT_DISPLAY_NAME
|
||||
}
|
||||
|
||||
const resolveAccountAvatarText = (displayName?: string): string => {
|
||||
if (typeof displayName !== 'string' || displayName.length === 0) return '微'
|
||||
const visible = displayName.trim()
|
||||
return (visible && [...visible][0]) || '微'
|
||||
}
|
||||
|
||||
const readAccountProfilesCache = (): Record<string, AccountProfileCacheEntry> => {
|
||||
try {
|
||||
const raw = window.localStorage.getItem(ACCOUNT_PROFILES_CACHE_KEY)
|
||||
if (!raw) return {}
|
||||
const parsed = JSON.parse(raw)
|
||||
return parsed && typeof parsed === 'object' ? parsed as Record<string, AccountProfileCacheEntry> : {}
|
||||
} catch {
|
||||
return {}
|
||||
}
|
||||
}
|
||||
|
||||
function AccountManagementPage() {
|
||||
const isDbConnected = useAppStore(state => state.isDbConnected)
|
||||
const setDbConnected = useAppStore(state => state.setDbConnected)
|
||||
const resetChatStore = useChatStore(state => state.reset)
|
||||
const clearAnalyticsStoreCache = useAnalyticsStore(state => state.clearCache)
|
||||
|
||||
const [dbPath, setDbPath] = useState('')
|
||||
const [currentWxid, setCurrentWxid] = useState('')
|
||||
const [accounts, setAccounts] = useState<ManagedAccountItem[]>([])
|
||||
const [isLoading, setIsLoading] = useState(false)
|
||||
const [workingWxid, setWorkingWxid] = useState('')
|
||||
const [notice, setNotice] = useState<NoticeState>(null)
|
||||
const [deleteUndoState, setDeleteUndoState] = useState<DeleteUndoState | null>(null)
|
||||
|
||||
const loadAccounts = useCallback(async () => {
|
||||
setIsLoading(true)
|
||||
try {
|
||||
const [path, rawCurrentWxid, wxidConfigs] = await Promise.all([
|
||||
configService.getDbPath(),
|
||||
configService.getMyWxid(),
|
||||
configService.getWxidConfigs()
|
||||
])
|
||||
const nextDbPath = String(path || '').trim()
|
||||
const nextCurrentWxid = String(rawCurrentWxid || '').trim()
|
||||
const normalizedCurrent = normalizeAccountId(nextCurrentWxid) || nextCurrentWxid
|
||||
setDbPath(nextDbPath)
|
||||
setCurrentWxid(nextCurrentWxid)
|
||||
|
||||
let scannedWxids: ScannedWxidOption[] = []
|
||||
if (nextDbPath) {
|
||||
try {
|
||||
const scanned = await window.electronAPI.dbPath.scanWxids(nextDbPath)
|
||||
scannedWxids = Array.isArray(scanned) ? scanned as ScannedWxidOption[] : []
|
||||
} catch {
|
||||
scannedWxids = []
|
||||
}
|
||||
}
|
||||
|
||||
const accountProfileCache = readAccountProfilesCache()
|
||||
const configEntries = Object.entries(wxidConfigs || {})
|
||||
const configByNormalized = new Map<string, { key: string; value: configService.WxidConfig }>()
|
||||
for (const [wxid, cfg] of configEntries) {
|
||||
const normalized = normalizeAccountId(wxid) || wxid
|
||||
if (!normalized) continue
|
||||
const previous = configByNormalized.get(normalized)
|
||||
if (!previous || Number(cfg?.updatedAt || 0) > Number(previous.value?.updatedAt || 0)) {
|
||||
configByNormalized.set(normalized, { key: wxid, value: cfg || {} })
|
||||
}
|
||||
}
|
||||
|
||||
const merged = new Map<string, ManagedAccountItem>()
|
||||
for (const scanned of scannedWxids) {
|
||||
const normalized = normalizeAccountId(scanned.wxid) || scanned.wxid
|
||||
if (!normalized) continue
|
||||
const cached = accountProfileCache[scanned.wxid] || accountProfileCache[normalized]
|
||||
const matchedConfig = configByNormalized.get(normalized)
|
||||
const wxidCandidates = new Set<string>([
|
||||
String(scanned.wxid || '').trim().toLowerCase(),
|
||||
String(normalized || '').trim().toLowerCase()
|
||||
].filter(Boolean))
|
||||
const displayName = resolveAccountDisplayName(
|
||||
[scanned.nickname, cached?.displayName],
|
||||
wxidCandidates
|
||||
)
|
||||
merged.set(normalized, {
|
||||
wxid: scanned.wxid,
|
||||
normalizedWxid: normalized,
|
||||
displayName,
|
||||
avatarUrl: scanned.avatarUrl || cached?.avatarUrl,
|
||||
modifiedTime: Number(scanned.modifiedTime || 0),
|
||||
configUpdatedAt: Number(matchedConfig?.value?.updatedAt || 0),
|
||||
hasConfig: Boolean(matchedConfig),
|
||||
isCurrent: normalizedCurrent && normalized === normalizedCurrent,
|
||||
fromScan: true
|
||||
})
|
||||
}
|
||||
|
||||
for (const [normalized, matchedConfig] of configByNormalized.entries()) {
|
||||
if (merged.has(normalized)) continue
|
||||
const wxid = matchedConfig.key
|
||||
const cached = accountProfileCache[wxid] || accountProfileCache[normalized]
|
||||
const wxidCandidates = new Set<string>([
|
||||
String(wxid || '').trim().toLowerCase(),
|
||||
String(normalized || '').trim().toLowerCase()
|
||||
].filter(Boolean))
|
||||
const displayName = resolveAccountDisplayName(
|
||||
[cached?.displayName],
|
||||
wxidCandidates
|
||||
)
|
||||
merged.set(normalized, {
|
||||
wxid,
|
||||
normalizedWxid: normalized,
|
||||
displayName,
|
||||
avatarUrl: cached?.avatarUrl,
|
||||
modifiedTime: 0,
|
||||
configUpdatedAt: Number(matchedConfig.value?.updatedAt || 0),
|
||||
hasConfig: true,
|
||||
isCurrent: normalizedCurrent && normalized === normalizedCurrent,
|
||||
fromScan: false
|
||||
})
|
||||
}
|
||||
|
||||
// 被“删除配置”操作移除的账号,在当前会话中从列表隐藏;
|
||||
// 若后续再次生成配置,则自动恢复展示。
|
||||
for (const [normalized, item] of Array.from(merged.entries())) {
|
||||
if (!hiddenDeletedAccountIds.has(normalized)) continue
|
||||
if (item.hasConfig) {
|
||||
hiddenDeletedAccountIds.delete(normalized)
|
||||
continue
|
||||
}
|
||||
merged.delete(normalized)
|
||||
}
|
||||
|
||||
const nextAccounts = Array.from(merged.values()).sort((a, b) => {
|
||||
if (a.isCurrent && !b.isCurrent) return -1
|
||||
if (!a.isCurrent && b.isCurrent) return 1
|
||||
const scanDiff = Number(b.modifiedTime || 0) - Number(a.modifiedTime || 0)
|
||||
if (scanDiff !== 0) return scanDiff
|
||||
return Number(b.configUpdatedAt || 0) - Number(a.configUpdatedAt || 0)
|
||||
})
|
||||
setAccounts(nextAccounts)
|
||||
} catch (error) {
|
||||
console.error('加载账号列表失败:', error)
|
||||
setNotice({ type: 'error', text: '加载账号列表失败,请稍后重试' })
|
||||
setAccounts([])
|
||||
} finally {
|
||||
setIsLoading(false)
|
||||
}
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
void loadAccounts()
|
||||
const onWxidChanged = () => { void loadAccounts() }
|
||||
const onWindowFocus = () => { void loadAccounts() }
|
||||
const onVisibilityChange = () => {
|
||||
if (document.visibilityState === 'visible') {
|
||||
void loadAccounts()
|
||||
}
|
||||
}
|
||||
window.addEventListener('wxid-changed', onWxidChanged as EventListener)
|
||||
window.addEventListener('focus', onWindowFocus)
|
||||
document.addEventListener('visibilitychange', onVisibilityChange)
|
||||
return () => {
|
||||
window.removeEventListener('wxid-changed', onWxidChanged as EventListener)
|
||||
window.removeEventListener('focus', onWindowFocus)
|
||||
document.removeEventListener('visibilitychange', onVisibilityChange)
|
||||
}
|
||||
}, [loadAccounts])
|
||||
|
||||
const clearRuntimeCacheState = useCallback(async () => {
|
||||
if (isDbConnected) {
|
||||
await window.electronAPI.chat.close()
|
||||
}
|
||||
window.localStorage.removeItem(SIDEBAR_USER_PROFILE_CACHE_KEY)
|
||||
clearAnalyticsStoreCache()
|
||||
resetChatStore()
|
||||
}, [clearAnalyticsStoreCache, isDbConnected, resetChatStore])
|
||||
|
||||
const applyWxidConfig = useCallback(async (wxid: string, wxidConfig: configService.WxidConfig | null) => {
|
||||
await configService.setMyWxid(wxid)
|
||||
await configService.setDecryptKey(wxidConfig?.decryptKey || '')
|
||||
await configService.setImageXorKey(typeof wxidConfig?.imageXorKey === 'number' ? wxidConfig.imageXorKey : 0)
|
||||
await configService.setImageAesKey(wxidConfig?.imageAesKey || '')
|
||||
}, [])
|
||||
|
||||
const handleSwitchAccount = useCallback(async (wxid: string) => {
|
||||
if (!wxid || workingWxid) return
|
||||
const targetNormalized = normalizeAccountId(wxid) || wxid
|
||||
const currentNormalized = normalizeAccountId(currentWxid) || currentWxid
|
||||
if (targetNormalized && currentNormalized && targetNormalized === currentNormalized) return
|
||||
|
||||
setWorkingWxid(wxid)
|
||||
setNotice(null)
|
||||
setDeleteUndoState(null)
|
||||
try {
|
||||
const allConfigs = await configService.getWxidConfigs()
|
||||
const configEntries = Object.entries(allConfigs || {})
|
||||
const matched = configEntries.find(([key]) => {
|
||||
const normalized = normalizeAccountId(key) || key
|
||||
return key === wxid || normalized === targetNormalized
|
||||
})
|
||||
const targetConfig = matched?.[1] || null
|
||||
await applyWxidConfig(wxid, targetConfig)
|
||||
await clearRuntimeCacheState()
|
||||
window.dispatchEvent(new CustomEvent('wxid-changed', { detail: { wxid } }))
|
||||
setNotice({ type: 'success', text: `已切换到账号「${wxid}」` })
|
||||
await loadAccounts()
|
||||
} catch (error) {
|
||||
console.error('切换账号失败:', error)
|
||||
setNotice({ type: 'error', text: '切换账号失败,请稍后重试' })
|
||||
} finally {
|
||||
setWorkingWxid('')
|
||||
}
|
||||
}, [applyWxidConfig, clearRuntimeCacheState, currentWxid, loadAccounts, workingWxid])
|
||||
|
||||
const handleAddAccount = useCallback(async () => {
|
||||
if (workingWxid) return
|
||||
setNotice(null)
|
||||
setDeleteUndoState(null)
|
||||
try {
|
||||
await window.electronAPI.window.openOnboardingWindow({ mode: 'add-account' })
|
||||
await loadAccounts()
|
||||
const latestWxid = String(await configService.getMyWxid() || '').trim()
|
||||
window.dispatchEvent(new CustomEvent('wxid-changed', { detail: { wxid: latestWxid } }))
|
||||
} catch (error) {
|
||||
console.error('打开添加账号引导失败:', error)
|
||||
setNotice({ type: 'error', text: '打开添加账号引导失败,请稍后重试' })
|
||||
}
|
||||
}, [loadAccounts, workingWxid])
|
||||
|
||||
const handleDeleteAccountConfig = useCallback(async (targetWxid: string) => {
|
||||
if (!targetWxid || workingWxid) return
|
||||
|
||||
const normalizedTarget = normalizeAccountId(targetWxid) || targetWxid
|
||||
|
||||
setWorkingWxid(targetWxid)
|
||||
setNotice(null)
|
||||
setDeleteUndoState(null)
|
||||
try {
|
||||
const allConfigs = await configService.getWxidConfigs()
|
||||
const nextConfigs: Record<string, configService.WxidConfig> = { ...allConfigs }
|
||||
const matchedKeys = Object.keys(nextConfigs).filter((key) => {
|
||||
const normalized = normalizeAccountId(key) || key
|
||||
return key === targetWxid || normalized === normalizedTarget
|
||||
})
|
||||
|
||||
if (matchedKeys.length === 0) {
|
||||
setNotice({ type: 'info', text: `账号「${targetWxid}」暂无可删除配置` })
|
||||
return
|
||||
}
|
||||
|
||||
const deletedConfigEntries: Array<[string, configService.WxidConfig]> = matchedKeys.map((key) => [key, nextConfigs[key] || {}])
|
||||
for (const key of matchedKeys) {
|
||||
delete nextConfigs[key]
|
||||
}
|
||||
await configService.setWxidConfigs(nextConfigs)
|
||||
|
||||
const accountProfileCache = readAccountProfilesCache()
|
||||
const deletedProfileEntries: Array<[string, AccountProfileCacheEntry]> = []
|
||||
for (const key of Object.keys(accountProfileCache)) {
|
||||
const normalized = normalizeAccountId(key) || key
|
||||
if (key === targetWxid || normalized === normalizedTarget) {
|
||||
deletedProfileEntries.push([key, accountProfileCache[key]])
|
||||
delete accountProfileCache[key]
|
||||
}
|
||||
}
|
||||
window.localStorage.setItem(ACCOUNT_PROFILES_CACHE_KEY, JSON.stringify(accountProfileCache))
|
||||
|
||||
const currentNormalized = normalizeAccountId(currentWxid) || currentWxid
|
||||
const isDeletingCurrent = Boolean(currentNormalized && currentNormalized === normalizedTarget)
|
||||
const undoPayload: DeleteUndoState = {
|
||||
targetWxid,
|
||||
deletedConfigEntries,
|
||||
deletedProfileEntries,
|
||||
previousCurrentWxid: currentWxid,
|
||||
shouldRestoreAsCurrent: isDeletingCurrent,
|
||||
previousDbConnected: isDbConnected
|
||||
}
|
||||
|
||||
if (isDeletingCurrent) {
|
||||
await clearRuntimeCacheState()
|
||||
|
||||
const remainingEntries = Object.entries(nextConfigs)
|
||||
.filter(([wxid]) => Boolean(String(wxid || '').trim()))
|
||||
.sort((a, b) => Number(b[1]?.updatedAt || 0) - Number(a[1]?.updatedAt || 0))
|
||||
|
||||
if (remainingEntries.length > 0) {
|
||||
const [nextWxid, nextConfig] = remainingEntries[0]
|
||||
await applyWxidConfig(nextWxid, nextConfig || null)
|
||||
window.dispatchEvent(new CustomEvent('wxid-changed', { detail: { wxid: nextWxid } }))
|
||||
hiddenDeletedAccountIds.add(normalizedTarget)
|
||||
setDeleteUndoState(undoPayload)
|
||||
setNotice({ type: 'success', text: `已删除「${targetWxid}」配置,并切换到「${nextWxid}」` })
|
||||
await loadAccounts()
|
||||
return
|
||||
}
|
||||
|
||||
await configService.setMyWxid('')
|
||||
await configService.setDecryptKey('')
|
||||
await configService.setImageXorKey(0)
|
||||
await configService.setImageAesKey('')
|
||||
setDbConnected(false)
|
||||
window.dispatchEvent(new CustomEvent('wxid-changed', { detail: { wxid: '' } }))
|
||||
hiddenDeletedAccountIds.add(normalizedTarget)
|
||||
setDeleteUndoState(undoPayload)
|
||||
setNotice({ type: 'info', text: `已删除「${targetWxid}」配置,当前无可用账号配置,可撤回或添加账号` })
|
||||
await loadAccounts()
|
||||
return
|
||||
}
|
||||
|
||||
hiddenDeletedAccountIds.add(normalizedTarget)
|
||||
setDeleteUndoState(undoPayload)
|
||||
setNotice({ type: 'success', text: `已删除账号「${targetWxid}」配置` })
|
||||
await loadAccounts()
|
||||
} catch (error) {
|
||||
console.error('删除账号配置失败:', error)
|
||||
setNotice({ type: 'error', text: '删除账号配置失败,请稍后重试' })
|
||||
} finally {
|
||||
setWorkingWxid('')
|
||||
}
|
||||
}, [applyWxidConfig, clearRuntimeCacheState, currentWxid, isDbConnected, loadAccounts, setDbConnected, workingWxid])
|
||||
|
||||
const handleUndoDelete = useCallback(async () => {
|
||||
if (!deleteUndoState || workingWxid) return
|
||||
|
||||
setWorkingWxid(`undo:${deleteUndoState.targetWxid}`)
|
||||
setNotice(null)
|
||||
try {
|
||||
const currentConfigs = await configService.getWxidConfigs()
|
||||
const restoredConfigs: Record<string, configService.WxidConfig> = { ...currentConfigs }
|
||||
for (const [key, configValue] of deleteUndoState.deletedConfigEntries) {
|
||||
restoredConfigs[key] = configValue || {}
|
||||
}
|
||||
await configService.setWxidConfigs(restoredConfigs)
|
||||
hiddenDeletedAccountIds.delete(normalizeAccountId(deleteUndoState.targetWxid) || deleteUndoState.targetWxid)
|
||||
|
||||
const accountProfileCache = readAccountProfilesCache()
|
||||
for (const [key, profile] of deleteUndoState.deletedProfileEntries) {
|
||||
accountProfileCache[key] = profile
|
||||
}
|
||||
window.localStorage.setItem(ACCOUNT_PROFILES_CACHE_KEY, JSON.stringify(accountProfileCache))
|
||||
|
||||
if (deleteUndoState.shouldRestoreAsCurrent && deleteUndoState.previousCurrentWxid) {
|
||||
const previousNormalized = normalizeAccountId(deleteUndoState.previousCurrentWxid) || deleteUndoState.previousCurrentWxid
|
||||
const restoreConfigEntry = Object.entries(restoredConfigs)
|
||||
.filter(([key]) => {
|
||||
const normalized = normalizeAccountId(key) || key
|
||||
return key === deleteUndoState.previousCurrentWxid || normalized === previousNormalized
|
||||
})
|
||||
.sort((a, b) => Number(b[1]?.updatedAt || 0) - Number(a[1]?.updatedAt || 0))[0]
|
||||
const restoreConfig = restoreConfigEntry?.[1] || null
|
||||
|
||||
await clearRuntimeCacheState()
|
||||
await applyWxidConfig(deleteUndoState.previousCurrentWxid, restoreConfig)
|
||||
if (deleteUndoState.previousDbConnected) {
|
||||
setDbConnected(true, dbPath || undefined)
|
||||
}
|
||||
window.dispatchEvent(new CustomEvent('wxid-changed', { detail: { wxid: deleteUndoState.previousCurrentWxid } }))
|
||||
}
|
||||
|
||||
setNotice({ type: 'success', text: `已撤回删除,账号「${deleteUndoState.targetWxid}」配置已恢复` })
|
||||
setDeleteUndoState(null)
|
||||
await loadAccounts()
|
||||
} catch (error) {
|
||||
console.error('撤回删除失败:', error)
|
||||
setNotice({ type: 'error', text: '撤回删除失败,请稍后重试' })
|
||||
} finally {
|
||||
setWorkingWxid('')
|
||||
}
|
||||
}, [applyWxidConfig, clearRuntimeCacheState, dbPath, deleteUndoState, loadAccounts, setDbConnected, workingWxid])
|
||||
|
||||
const currentAccountLabel = useMemo(() => {
|
||||
if (!currentWxid) return '未设置'
|
||||
return currentWxid
|
||||
}, [currentWxid])
|
||||
|
||||
const formatTime = (value?: number): string => {
|
||||
const ts = Number(value || 0)
|
||||
if (!ts) return '未知'
|
||||
const date = new Date(ts)
|
||||
if (Number.isNaN(date.getTime())) return '未知'
|
||||
const year = date.getFullYear()
|
||||
const month = String(date.getMonth() + 1).padStart(2, '0')
|
||||
const day = String(date.getDate()).padStart(2, '0')
|
||||
const hour = String(date.getHours()).padStart(2, '0')
|
||||
const minute = String(date.getMinutes()).padStart(2, '0')
|
||||
return `${year}-${month}-${day} ${hour}:${minute}`
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="account-management-page">
|
||||
<header className="account-management-header">
|
||||
<div>
|
||||
<h2>账号管理</h2>
|
||||
<p>统一管理切换账号、添加账号、删除账号配置。</p>
|
||||
</div>
|
||||
<div className="account-management-actions">
|
||||
<button type="button" className="btn btn-secondary" onClick={() => void loadAccounts()} disabled={isLoading || Boolean(workingWxid)}>
|
||||
<RefreshCw size={16} /> {isLoading ? '刷新中...' : '刷新'}
|
||||
</button>
|
||||
<button type="button" className="btn btn-primary" onClick={handleAddAccount} disabled={Boolean(workingWxid)}>
|
||||
<UserPlus size={16} /> 添加账号
|
||||
</button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<section className="account-management-summary">
|
||||
<div className="summary-item">
|
||||
<span className="summary-label">数据库目录</span>
|
||||
<span className="summary-value">{dbPath || '未配置'}</span>
|
||||
</div>
|
||||
<div className="summary-item">
|
||||
<span className="summary-label">当前账号</span>
|
||||
<span className="summary-value">{currentAccountLabel}</span>
|
||||
</div>
|
||||
<div className="summary-item">
|
||||
<span className="summary-label">账号数量</span>
|
||||
<span className="summary-value">{accounts.length}</span>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{notice && (
|
||||
<div className={`account-notice ${notice.type}`}>
|
||||
<span>{notice.text}</span>
|
||||
{deleteUndoState && (notice.type === 'success' || notice.type === 'info') && (
|
||||
<button
|
||||
type="button"
|
||||
className="notice-action"
|
||||
onClick={() => void handleUndoDelete()}
|
||||
disabled={Boolean(workingWxid)}
|
||||
>
|
||||
撤回
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{accounts.length === 0 ? (
|
||||
<div className="account-empty">
|
||||
<Database size={20} />
|
||||
<span>未发现可管理账号,请先添加账号或检查数据库目录。</span>
|
||||
</div>
|
||||
) : (
|
||||
<div className="account-list">
|
||||
{accounts.map((account) => (
|
||||
<article key={account.normalizedWxid} className={`account-card ${account.isCurrent ? 'is-current' : ''}`}>
|
||||
<div className="account-avatar">
|
||||
{account.avatarUrl ? <img src={account.avatarUrl} alt="" /> : <span>{resolveAccountAvatarText(account.displayName)}</span>}
|
||||
</div>
|
||||
<div className="account-main">
|
||||
<div className="account-title-row">
|
||||
<h3>{account.displayName}</h3>
|
||||
{account.isCurrent && (
|
||||
<span className="account-badge current">
|
||||
<CheckCircle2 size={12} /> 当前
|
||||
</span>
|
||||
)}
|
||||
{account.hasConfig ? (
|
||||
<span className="account-badge ok">已保存配置</span>
|
||||
) : (
|
||||
<span className="account-badge warn">未保存配置</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="account-meta">wxid: {account.wxid}</div>
|
||||
<div className="account-meta">
|
||||
最近数据更新时间: {formatTime(account.modifiedTime)} · 配置更新时间: {formatTime(account.configUpdatedAt)}
|
||||
{!account.fromScan && <span className="meta-tip">(仅配置记录)</span>}
|
||||
</div>
|
||||
</div>
|
||||
<div className="account-card-actions">
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-secondary"
|
||||
onClick={() => void handleSwitchAccount(account.wxid)}
|
||||
disabled={Boolean(workingWxid) || account.isCurrent || !account.hasConfig || !account.fromScan}
|
||||
>
|
||||
<ArrowRightLeft size={14} /> {account.isCurrent ? '当前账号' : (!account.hasConfig ? '无配置' : (account.fromScan ? '切换' : '无数据'))}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-danger"
|
||||
onClick={() => void handleDeleteAccountConfig(account.wxid)}
|
||||
disabled={Boolean(workingWxid) || !account.hasConfig}
|
||||
>
|
||||
<Trash2 size={14} /> 删除配置
|
||||
</button>
|
||||
</div>
|
||||
</article>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<footer className="account-management-footer">
|
||||
删除仅影响 WeFlow 本地配置,不会删除微信原始数据文件。
|
||||
</footer>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default AccountManagementPage
|
||||
@@ -11,6 +11,7 @@
|
||||
}
|
||||
|
||||
.biz-account-item {
|
||||
position: relative;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
@@ -46,6 +47,24 @@
|
||||
background-color: var(--bg-tertiary);
|
||||
}
|
||||
|
||||
.biz-unread-badge {
|
||||
position: absolute;
|
||||
top: 8px;
|
||||
left: 52px;
|
||||
min-width: 18px;
|
||||
height: 18px;
|
||||
padding: 0 5px;
|
||||
border-radius: 9px;
|
||||
background: #ff4d4f;
|
||||
color: #fff;
|
||||
font-size: 11px;
|
||||
font-weight: 600;
|
||||
line-height: 18px;
|
||||
text-align: center;
|
||||
border: 2px solid var(--bg-secondary);
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
.biz-info {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import React, { useState, useEffect, useMemo, useRef } from 'react';
|
||||
import React, { useState, useEffect, useMemo, useRef, useCallback } from 'react';
|
||||
import { useThemeStore } from '../stores/themeStore';
|
||||
import { Newspaper, MessageSquareOff } from 'lucide-react';
|
||||
import './BizPage.scss';
|
||||
@@ -10,6 +10,7 @@ export interface BizAccount {
|
||||
type: string;
|
||||
last_time: number;
|
||||
formatted_last_time: string;
|
||||
unread_count?: number;
|
||||
}
|
||||
|
||||
export const BizAccountList: React.FC<{
|
||||
@@ -36,25 +37,42 @@ export const BizAccountList: React.FC<{
|
||||
initWxid().then(_r => { });
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const fetch = async () => {
|
||||
if (!myWxid) {
|
||||
return;
|
||||
}
|
||||
const fetchAccounts = useCallback(async () => {
|
||||
if (!myWxid) {
|
||||
return;
|
||||
}
|
||||
|
||||
setLoading(true);
|
||||
try {
|
||||
const res = await window.electronAPI.biz.listAccounts(myWxid)
|
||||
setAccounts(res || []);
|
||||
} catch (err) {
|
||||
console.error('获取服务号列表失败:', err);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
fetch().then(_r => { } );
|
||||
setLoading(true);
|
||||
try {
|
||||
const res = await window.electronAPI.biz.listAccounts(myWxid)
|
||||
setAccounts(res || []);
|
||||
} catch (err) {
|
||||
console.error('获取服务号列表失败:', err);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [myWxid]);
|
||||
|
||||
useEffect(() => {
|
||||
fetchAccounts().then(_r => { });
|
||||
}, [fetchAccounts]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!window.electronAPI.chat.onWcdbChange) return;
|
||||
const removeListener = window.electronAPI.chat.onWcdbChange((_event: any, data: { json?: string }) => {
|
||||
try {
|
||||
const payload = JSON.parse(data.json || '{}');
|
||||
const tableName = String(payload.table || '').toLowerCase();
|
||||
if (!tableName || tableName === 'session' || tableName.includes('message') || tableName.startsWith('msg_')) {
|
||||
fetchAccounts().then(_r => { });
|
||||
}
|
||||
} catch {
|
||||
fetchAccounts().then(_r => { });
|
||||
}
|
||||
});
|
||||
return () => removeListener();
|
||||
}, [fetchAccounts]);
|
||||
|
||||
|
||||
const filtered = useMemo(() => {
|
||||
let result = accounts;
|
||||
@@ -80,7 +98,12 @@ export const BizAccountList: React.FC<{
|
||||
{filtered.map(item => (
|
||||
<div
|
||||
key={item.username}
|
||||
onClick={() => onSelect(item)}
|
||||
onClick={() => {
|
||||
setAccounts(prev => prev.map(account =>
|
||||
account.username === item.username ? { ...account, unread_count: 0 } : account
|
||||
));
|
||||
onSelect({ ...item, unread_count: 0 });
|
||||
}}
|
||||
className={`biz-account-item ${selectedUsername === item.username ? 'active' : ''} ${item.username === 'gh_3dfda90e39d6' ? 'pay-account' : ''}`}
|
||||
>
|
||||
<img
|
||||
@@ -88,6 +111,9 @@ export const BizAccountList: React.FC<{
|
||||
className="biz-avatar"
|
||||
alt=""
|
||||
/>
|
||||
{(item.unread_count || 0) > 0 && (
|
||||
<span className="biz-unread-badge">{(item.unread_count || 0) > 99 ? '99+' : item.unread_count}</span>
|
||||
)}
|
||||
<div className="biz-info">
|
||||
<div className="biz-info-top">
|
||||
<span className="biz-name">{item.name || item.username}</span>
|
||||
|
||||
@@ -2064,6 +2064,7 @@
|
||||
.message-bubble .bubble-content:has(> .link-message),
|
||||
.message-bubble .bubble-content:has(> .card-message),
|
||||
.message-bubble .bubble-content:has(> .chat-record-message),
|
||||
.message-bubble .bubble-content:has(> .solitaire-message),
|
||||
.message-bubble .bubble-content:has(> .official-message),
|
||||
.message-bubble .bubble-content:has(> .channel-video-card),
|
||||
.message-bubble .bubble-content:has(> .location-message) {
|
||||
@@ -3604,6 +3605,140 @@
|
||||
}
|
||||
}
|
||||
|
||||
// 接龙消息
|
||||
.solitaire-message {
|
||||
width: min(360px, 72vw);
|
||||
max-width: 360px;
|
||||
background: var(--card-inner-bg);
|
||||
border: 1px solid var(--border-color);
|
||||
border-radius: 8px;
|
||||
overflow: hidden;
|
||||
cursor: pointer;
|
||||
box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
|
||||
transition: background 0.2s ease, border-color 0.2s ease, box-shadow 0.2s ease;
|
||||
|
||||
&:hover {
|
||||
background: var(--bg-hover);
|
||||
border-color: var(--primary);
|
||||
}
|
||||
|
||||
.solitaire-header {
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
padding: 12px 14px 10px;
|
||||
border-bottom: 1px solid var(--border-color);
|
||||
}
|
||||
|
||||
.solitaire-icon {
|
||||
width: 30px;
|
||||
height: 30px;
|
||||
border-radius: 8px;
|
||||
background: color-mix(in srgb, var(--primary) 12%, transparent);
|
||||
color: var(--primary);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.solitaire-heading {
|
||||
min-width: 0;
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.solitaire-title {
|
||||
color: var(--text-primary);
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
line-height: 1.45;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.solitaire-meta {
|
||||
margin-top: 2px;
|
||||
color: var(--text-tertiary);
|
||||
font-size: 12px;
|
||||
line-height: 1.4;
|
||||
}
|
||||
|
||||
.solitaire-intro,
|
||||
.solitaire-entry-list {
|
||||
padding: 10px 14px;
|
||||
border-bottom: 1px solid var(--border-color);
|
||||
}
|
||||
|
||||
.solitaire-intro {
|
||||
color: var(--text-secondary);
|
||||
font-size: 12px;
|
||||
line-height: 1.55;
|
||||
}
|
||||
|
||||
.solitaire-intro-line {
|
||||
white-space: pre-wrap;
|
||||
word-break: break-word;
|
||||
}
|
||||
|
||||
.solitaire-entry-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 7px;
|
||||
}
|
||||
|
||||
.solitaire-entry {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
align-items: flex-start;
|
||||
color: var(--text-secondary);
|
||||
font-size: 12px;
|
||||
line-height: 1.45;
|
||||
}
|
||||
|
||||
.solitaire-entry-index {
|
||||
width: 22px;
|
||||
height: 22px;
|
||||
border-radius: 8px;
|
||||
background: var(--bg-tertiary);
|
||||
color: var(--text-tertiary);
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
flex-shrink: 0;
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
.solitaire-entry-text {
|
||||
min-width: 0;
|
||||
flex: 1;
|
||||
word-break: break-word;
|
||||
}
|
||||
|
||||
.solitaire-muted-line {
|
||||
color: var(--text-tertiary);
|
||||
font-size: 12px;
|
||||
line-height: 1.45;
|
||||
}
|
||||
|
||||
.solitaire-footer {
|
||||
padding: 8px 14px 10px;
|
||||
color: var(--text-tertiary);
|
||||
font-size: 12px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.solitaire-chevron {
|
||||
transition: transform 0.2s ease;
|
||||
}
|
||||
|
||||
&.expanded .solitaire-chevron {
|
||||
transform: rotate(180deg);
|
||||
}
|
||||
}
|
||||
|
||||
// 通话消息
|
||||
.call-message {
|
||||
display: flex;
|
||||
|
||||
@@ -46,6 +46,12 @@ interface PendingInSessionSearchPayload {
|
||||
results: Message[]
|
||||
}
|
||||
|
||||
interface PendingFootprintJumpPayload {
|
||||
sessionId: string
|
||||
localId: number
|
||||
createTime: number
|
||||
}
|
||||
|
||||
type GlobalMsgSearchPhase = 'idle' | 'seed' | 'backfill' | 'done'
|
||||
type GlobalMsgSearchResult = Message & { sessionId: string }
|
||||
|
||||
@@ -175,6 +181,51 @@ function buildChatRecordPreviewItems(recordList: ChatRecordItem[], maxVisible =
|
||||
]
|
||||
}
|
||||
|
||||
interface SolitaireEntry {
|
||||
index: string
|
||||
text: string
|
||||
}
|
||||
|
||||
interface SolitaireContent {
|
||||
title: string
|
||||
introLines: string[]
|
||||
entries: SolitaireEntry[]
|
||||
}
|
||||
|
||||
function parseSolitaireContent(rawTitle: string): SolitaireContent {
|
||||
const lines = String(rawTitle || '')
|
||||
.replace(/\r\n/g, '\n')
|
||||
.split('\n')
|
||||
.map(line => line.trim())
|
||||
.filter(Boolean)
|
||||
|
||||
const title = lines[0] || '接龙'
|
||||
const introLines: string[] = []
|
||||
const entries: SolitaireEntry[] = []
|
||||
let hasStartedEntries = false
|
||||
|
||||
for (const line of lines.slice(1)) {
|
||||
const entryMatch = /^(\d+)[..、]\s*(.+)$/.exec(line)
|
||||
if (entryMatch) {
|
||||
hasStartedEntries = true
|
||||
entries.push({
|
||||
index: entryMatch[1],
|
||||
text: entryMatch[2].trim()
|
||||
})
|
||||
continue
|
||||
}
|
||||
|
||||
if (hasStartedEntries && entries.length > 0) {
|
||||
const previous = entries[entries.length - 1]
|
||||
previous.text = `${previous.text} ${line}`.trim()
|
||||
} else {
|
||||
introLines.push(line)
|
||||
}
|
||||
}
|
||||
|
||||
return { title, introLines, entries }
|
||||
}
|
||||
|
||||
function composeGlobalMsgSearchResults(
|
||||
seedMap: Map<string, GlobalMsgSearchResult[]>,
|
||||
authoritativeMap: Map<string, GlobalMsgSearchResult[]>
|
||||
@@ -1052,6 +1103,13 @@ const SessionItem = React.memo(function SessionItem({
|
||||
</div>
|
||||
<div className="session-bottom">
|
||||
<span className="session-summary">{session.summary || '查看公众号历史消息'}</span>
|
||||
<div className="session-badges">
|
||||
{session.unreadCount > 0 && (
|
||||
<span className="unread-badge">
|
||||
{session.unreadCount > 99 ? '99+' : session.unreadCount}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -1363,6 +1421,7 @@ function ChatPage(props: ChatPageProps) {
|
||||
const [globalMsgAuthoritativeSessionCount, setGlobalMsgAuthoritativeSessionCount] = useState(0)
|
||||
const [globalMsgSearchError, setGlobalMsgSearchError] = useState<string | null>(null)
|
||||
const pendingInSessionSearchRef = useRef<PendingInSessionSearchPayload | null>(null)
|
||||
const pendingFootprintJumpRef = useRef<PendingFootprintJumpPayload | null>(null)
|
||||
const pendingGlobalMsgSearchReplayRef = useRef<string | null>(null)
|
||||
const globalMsgPrefixCacheRef = useRef<GlobalMsgPrefixCacheEntry | null>(null)
|
||||
|
||||
@@ -5042,24 +5101,37 @@ function ChatPage(props: ChatPageProps) {
|
||||
return []
|
||||
}
|
||||
|
||||
const officialSessions = sessions.filter(s => s.username.startsWith('gh_'))
|
||||
|
||||
// 检查是否有折叠的群聊
|
||||
const foldedGroups = sessions.filter(s => s.isFolded && !s.username.toLowerCase().includes('placeholder_foldgroup'))
|
||||
const hasFoldedGroups = foldedGroups.length > 0
|
||||
|
||||
let visible = sessions.filter(s => {
|
||||
if (s.isFolded && !s.username.toLowerCase().includes('placeholder_foldgroup')) return false
|
||||
if (s.username.startsWith('gh_')) return false
|
||||
return true
|
||||
})
|
||||
|
||||
const latestOfficial = officialSessions.reduce<ChatSession | null>((latest, current) => {
|
||||
if (!latest) return current
|
||||
const latestTime = latest.sortTimestamp || latest.lastTimestamp
|
||||
const currentTime = current.sortTimestamp || current.lastTimestamp
|
||||
return currentTime > latestTime ? current : latest
|
||||
}, null)
|
||||
const officialUnreadCount = officialSessions.reduce((sum, s) => sum + (s.unreadCount || 0), 0)
|
||||
|
||||
const bizEntry: ChatSession = {
|
||||
username: OFFICIAL_ACCOUNTS_VIRTUAL_ID,
|
||||
displayName: '公众号',
|
||||
summary: '查看公众号历史消息',
|
||||
summary: latestOfficial
|
||||
? `${latestOfficial.displayName || latestOfficial.username}: ${latestOfficial.summary || '查看公众号历史消息'}`
|
||||
: '查看公众号历史消息',
|
||||
type: 0,
|
||||
sortTimestamp: 9999999999, // 放到最前面? 目前还没有严格的对时间进行排序, 后面可以改一下
|
||||
lastTimestamp: 0,
|
||||
lastMsgType: 0,
|
||||
unreadCount: 0,
|
||||
lastTimestamp: latestOfficial?.lastTimestamp || latestOfficial?.sortTimestamp || 0,
|
||||
lastMsgType: latestOfficial?.lastMsgType || 0,
|
||||
unreadCount: officialUnreadCount,
|
||||
isMuted: false,
|
||||
isFolded: false
|
||||
}
|
||||
@@ -5351,18 +5423,89 @@ function ChatPage(props: ChatPageProps) {
|
||||
selectSessionById
|
||||
])
|
||||
|
||||
// 监听URL参数中的sessionId,用于通知点击导航
|
||||
// 监听 URL 参数中的会话/锚点(通知跳转 + 足迹锚点定位)
|
||||
useEffect(() => {
|
||||
if (standaloneSessionWindow) return // standalone模式由上面的useEffect处理
|
||||
const params = new URLSearchParams(location.search)
|
||||
const urlSessionId = params.get('sessionId')
|
||||
const urlSessionId = String(params.get('sessionId') || '').trim()
|
||||
if (!urlSessionId) return
|
||||
if (!isConnected || isConnecting) return
|
||||
if (currentSessionId === urlSessionId) return
|
||||
selectSessionById(urlSessionId)
|
||||
const jumpSource = String(params.get('jumpSource') || '').trim()
|
||||
const jumpLocalId = Number.parseInt(String(params.get('jumpLocalId') || ''), 10)
|
||||
const jumpCreateTime = Number.parseInt(String(params.get('jumpCreateTime') || ''), 10)
|
||||
const hasFootprintAnchor = jumpSource === 'footprint'
|
||||
&& Number.isFinite(jumpLocalId)
|
||||
&& jumpLocalId > 0
|
||||
&& Number.isFinite(jumpCreateTime)
|
||||
&& jumpCreateTime > 0
|
||||
|
||||
if (hasFootprintAnchor) {
|
||||
pendingFootprintJumpRef.current = {
|
||||
sessionId: urlSessionId,
|
||||
localId: jumpLocalId,
|
||||
createTime: jumpCreateTime
|
||||
}
|
||||
if (currentSessionId !== urlSessionId) {
|
||||
selectSessionById(urlSessionId)
|
||||
return
|
||||
}
|
||||
const messageStub: Message = {
|
||||
messageKey: `footprint:${urlSessionId}:${jumpCreateTime}:${jumpLocalId}`,
|
||||
localId: jumpLocalId,
|
||||
serverId: 0,
|
||||
localType: 0,
|
||||
createTime: jumpCreateTime,
|
||||
sortSeq: jumpCreateTime,
|
||||
isSend: null,
|
||||
senderUsername: null,
|
||||
parsedContent: '',
|
||||
rawContent: ''
|
||||
}
|
||||
handleInSessionResultJump(messageStub)
|
||||
pendingFootprintJumpRef.current = null
|
||||
navigate('/chat', { replace: true })
|
||||
return
|
||||
}
|
||||
|
||||
pendingFootprintJumpRef.current = null
|
||||
if (currentSessionId !== urlSessionId) {
|
||||
selectSessionById(urlSessionId)
|
||||
}
|
||||
// 选中后清除URL参数,避免影响后续用户手动切换会话
|
||||
navigate('/chat', { replace: true })
|
||||
}, [standaloneSessionWindow, location.search, isConnected, isConnecting, currentSessionId, selectSessionById, navigate])
|
||||
}, [
|
||||
standaloneSessionWindow,
|
||||
location.search,
|
||||
isConnected,
|
||||
isConnecting,
|
||||
currentSessionId,
|
||||
selectSessionById,
|
||||
handleInSessionResultJump,
|
||||
navigate
|
||||
])
|
||||
|
||||
useEffect(() => {
|
||||
const pending = pendingFootprintJumpRef.current
|
||||
if (!pending) return
|
||||
if (!isConnected || isConnecting) return
|
||||
if (currentSessionId !== pending.sessionId) return
|
||||
|
||||
const messageStub: Message = {
|
||||
messageKey: `footprint:${pending.sessionId}:${pending.createTime}:${pending.localId}`,
|
||||
localId: pending.localId,
|
||||
serverId: 0,
|
||||
localType: 0,
|
||||
createTime: pending.createTime,
|
||||
sortSeq: pending.createTime,
|
||||
isSend: null,
|
||||
senderUsername: null,
|
||||
parsedContent: '',
|
||||
rawContent: ''
|
||||
}
|
||||
handleInSessionResultJump(messageStub)
|
||||
pendingFootprintJumpRef.current = null
|
||||
navigate('/chat', { replace: true })
|
||||
}, [isConnected, isConnecting, currentSessionId, handleInSessionResultJump, navigate])
|
||||
|
||||
useEffect(() => {
|
||||
if (!standaloneSessionWindow || !normalizedInitialSessionId) return
|
||||
@@ -7727,6 +7870,7 @@ function MessageBubble({
|
||||
const [senderName, setSenderName] = useState<string | undefined>(undefined)
|
||||
const [quotedSenderName, setQuotedSenderName] = useState<string | undefined>(undefined)
|
||||
const [quoteLayout, setQuoteLayout] = useState<QuoteLayout>('quote-top')
|
||||
const [solitaireExpanded, setSolitaireExpanded] = useState(false)
|
||||
const senderProfileRequestSeqRef = useRef(0)
|
||||
const [emojiError, setEmojiError] = useState(false)
|
||||
const [emojiLoading, setEmojiLoading] = useState(false)
|
||||
@@ -9335,6 +9479,71 @@ function MessageBubble({
|
||||
)
|
||||
}
|
||||
|
||||
if (xmlType === '53' || message.appMsgKind === 'solitaire') {
|
||||
const solitaireText = message.linkTitle || q('appmsg > title') || q('title') || cleanedParsedContent || '接龙'
|
||||
const solitaire = parseSolitaireContent(solitaireText)
|
||||
const previewEntries = solitaireExpanded ? solitaire.entries : solitaire.entries.slice(0, 3)
|
||||
const hiddenEntryCount = Math.max(0, solitaire.entries.length - previewEntries.length)
|
||||
const introLines = solitaireExpanded ? solitaire.introLines : solitaire.introLines.slice(0, 4)
|
||||
const hasMoreIntro = !solitaireExpanded && solitaire.introLines.length > introLines.length
|
||||
const countText = solitaire.entries.length > 0 ? `${solitaire.entries.length} 人参与` : '接龙消息'
|
||||
|
||||
return (
|
||||
<div
|
||||
className={`solitaire-message${solitaireExpanded ? ' expanded' : ''}`}
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
aria-expanded={solitaireExpanded}
|
||||
onClick={isSelectionMode ? undefined : (e) => {
|
||||
e.stopPropagation()
|
||||
setSolitaireExpanded(value => !value)
|
||||
}}
|
||||
onKeyDown={isSelectionMode ? undefined : (e) => {
|
||||
if (e.key !== 'Enter' && e.key !== ' ') return
|
||||
e.preventDefault()
|
||||
e.stopPropagation()
|
||||
setSolitaireExpanded(value => !value)
|
||||
}}
|
||||
title={solitaireExpanded ? '点击收起接龙' : '点击展开接龙'}
|
||||
>
|
||||
<div className="solitaire-header">
|
||||
<div className="solitaire-icon" aria-hidden="true">
|
||||
<Hash size={18} />
|
||||
</div>
|
||||
<div className="solitaire-heading">
|
||||
<div className="solitaire-title">{solitaire.title}</div>
|
||||
<div className="solitaire-meta">{countText}</div>
|
||||
</div>
|
||||
</div>
|
||||
{introLines.length > 0 && (
|
||||
<div className="solitaire-intro">
|
||||
{introLines.map((line, index) => (
|
||||
<div key={`${line}-${index}`} className="solitaire-intro-line">{line}</div>
|
||||
))}
|
||||
{hasMoreIntro && <div className="solitaire-muted-line">...</div>}
|
||||
</div>
|
||||
)}
|
||||
{previewEntries.length > 0 ? (
|
||||
<div className="solitaire-entry-list">
|
||||
{previewEntries.map(entry => (
|
||||
<div key={`${entry.index}-${entry.text}`} className="solitaire-entry">
|
||||
<span className="solitaire-entry-index">{entry.index}</span>
|
||||
<span className="solitaire-entry-text">{entry.text}</span>
|
||||
</div>
|
||||
))}
|
||||
{hiddenEntryCount > 0 && (
|
||||
<div className="solitaire-muted-line">还有 {hiddenEntryCount} 条...</div>
|
||||
)}
|
||||
</div>
|
||||
) : null}
|
||||
<div className="solitaire-footer">
|
||||
<span>{solitaireExpanded ? '收起接龙' : '展开接龙'}</span>
|
||||
<ChevronDown size={14} className="solitaire-chevron" />
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const title = message.linkTitle || q('title') || cleanedParsedContent || 'Card'
|
||||
const desc = message.appMsgDesc || q('des')
|
||||
const url = message.linkUrl || q('url')
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
825
src/pages/MyFootprintPage.scss
Normal file
825
src/pages/MyFootprintPage.scss
Normal file
@@ -0,0 +1,825 @@
|
||||
.my-footprint-page {
|
||||
--timeline-mention: #f59e0b; /* muted orange */
|
||||
--timeline-private: #3b82f6; /* muted blue */
|
||||
|
||||
min-height: 100%;
|
||||
margin: -24px -24px 0;
|
||||
padding: 32px 40px;
|
||||
background: var(--bg-primary); /* Pure minimal background */
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 24px;
|
||||
overflow-y: auto;
|
||||
overflow-x: hidden;
|
||||
animation: footprintPageEnter 0.4s ease-out;
|
||||
|
||||
.card-surface {
|
||||
/* Removing border and strong shadows, just subtle background if any */
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
.spin {
|
||||
animation: footprintSpin 1s linear infinite;
|
||||
}
|
||||
}
|
||||
|
||||
.footprint-header {
|
||||
position: relative;
|
||||
z-index: 30;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 20px;
|
||||
padding: 10px 0 20px 0;
|
||||
border-bottom: 1px solid color-mix(in srgb, var(--border-color) 40%, transparent);
|
||||
animation: footprintFadeSlideUp 0.3s ease both;
|
||||
}
|
||||
|
||||
.footprint-title-wrap {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
|
||||
h1 {
|
||||
margin: 0;
|
||||
font-size: 26px;
|
||||
font-weight: 600;
|
||||
line-height: 1.3;
|
||||
letter-spacing: -0.3px;
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
p {
|
||||
margin: 0;
|
||||
color: var(--text-tertiary);
|
||||
font-size: 14px;
|
||||
}
|
||||
}
|
||||
|
||||
.footprint-title-badge {
|
||||
display: none; /* Removed for minimal design */
|
||||
}
|
||||
|
||||
.footprint-toolbar {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
.range-preset-group {
|
||||
display: flex;
|
||||
gap: 4px;
|
||||
background: color-mix(in srgb, var(--text-tertiary) 8%, transparent);
|
||||
padding: 4px;
|
||||
border-radius: 8px;
|
||||
}
|
||||
|
||||
.preset-chip {
|
||||
background: transparent;
|
||||
border: none;
|
||||
color: var(--text-secondary);
|
||||
border-radius: 6px;
|
||||
padding: 6px 14px;
|
||||
font-size: 13px;
|
||||
font-weight: 500;
|
||||
cursor: pointer;
|
||||
transition: all 0.2s ease;
|
||||
|
||||
&:hover {
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
&.active {
|
||||
color: var(--text-primary);
|
||||
background: var(--bg-primary);
|
||||
box-shadow: 0 1px 3px rgba(0,0,0,0.05);
|
||||
}
|
||||
}
|
||||
|
||||
.custom-range-row {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
|
||||
span {
|
||||
color: var(--text-tertiary);
|
||||
font-size: 13px;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
input[type="date"] {
|
||||
font-family: inherit;
|
||||
border: 1px solid transparent;
|
||||
background: color-mix(in srgb, var(--text-tertiary) 6%, transparent);
|
||||
color: var(--text-primary);
|
||||
border-radius: 8px;
|
||||
padding: 6px 10px;
|
||||
font-size: 13px;
|
||||
font-weight: 500;
|
||||
transition: all 0.2s ease;
|
||||
cursor: pointer;
|
||||
box-shadow: 0 1px 2px rgba(0,0,0,0.02) inset;
|
||||
|
||||
&:hover {
|
||||
background: color-mix(in srgb, var(--text-tertiary) 12%, transparent);
|
||||
}
|
||||
|
||||
&:focus {
|
||||
outline: none;
|
||||
background: color-mix(in srgb, var(--primary) 4%, transparent);
|
||||
border-color: color-mix(in srgb, var(--primary) 30%, transparent);
|
||||
color: var(--primary);
|
||||
}
|
||||
|
||||
&::-webkit-calendar-picker-indicator {
|
||||
cursor: pointer;
|
||||
opacity: 0.5;
|
||||
transition: all 0.2s ease;
|
||||
padding: 4px;
|
||||
margin-left: 4px;
|
||||
margin-right: -4px;
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
&::-webkit-calendar-picker-indicator:hover {
|
||||
opacity: 0.9;
|
||||
background: color-mix(in srgb, var(--text-tertiary) 12%, transparent);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.toolbar-actions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.search-input {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
border: none;
|
||||
background: color-mix(in srgb, var(--text-tertiary) 8%, transparent);
|
||||
border-radius: 8px;
|
||||
padding: 8px 12px;
|
||||
color: var(--text-tertiary);
|
||||
transition: all 0.2s ease;
|
||||
|
||||
&:focus-within {
|
||||
background: color-mix(in srgb, var(--primary) 8%, transparent);
|
||||
color: var(--primary);
|
||||
}
|
||||
|
||||
input {
|
||||
min-width: 180px;
|
||||
border: none;
|
||||
background: transparent;
|
||||
color: var(--text-primary);
|
||||
font-size: 13px;
|
||||
|
||||
&::placeholder {
|
||||
color: var(--text-tertiary);
|
||||
}
|
||||
&:focus {
|
||||
outline: none;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.action-btn,
|
||||
.jump-btn {
|
||||
border: none;
|
||||
background: color-mix(in srgb, var(--text-tertiary) 8%, transparent);
|
||||
color: var(--text-secondary);
|
||||
border-radius: 8px;
|
||||
padding: 8px 12px;
|
||||
font-size: 13px;
|
||||
font-weight: 500;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
cursor: pointer;
|
||||
transition: all 0.2s ease;
|
||||
|
||||
&:hover {
|
||||
background: color-mix(in srgb, var(--text-tertiary) 15%, transparent);
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
&:disabled {
|
||||
opacity: 0.4;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
}
|
||||
|
||||
.kpi-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(4, minmax(0, 1fr));
|
||||
gap: 20px;
|
||||
padding: 20px 0;
|
||||
border-bottom: 1px solid color-mix(in srgb, var(--border-color) 40%, transparent);
|
||||
}
|
||||
|
||||
.kpi-card {
|
||||
border: none;
|
||||
background: transparent;
|
||||
padding: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: flex-start;
|
||||
gap: 8px;
|
||||
text-align: left;
|
||||
color: var(--text-primary);
|
||||
animation: footprintKpiIn 0.3s ease both;
|
||||
transition: opacity 0.2s ease;
|
||||
cursor: pointer;
|
||||
|
||||
&:hover {
|
||||
opacity: 0.7;
|
||||
}
|
||||
|
||||
strong {
|
||||
font-size: 32px;
|
||||
font-weight: 300;
|
||||
line-height: 1;
|
||||
color: var(--text-primary);
|
||||
letter-spacing: -0.5px;
|
||||
}
|
||||
|
||||
small {
|
||||
color: var(--text-tertiary);
|
||||
font-size: 12px;
|
||||
}
|
||||
}
|
||||
|
||||
.kpi-icon {
|
||||
display: none; /* Minimalistic, hide icon in KPI */
|
||||
}
|
||||
|
||||
.footprint-ai-result {
|
||||
border-radius: 10px;
|
||||
padding: 14px 16px;
|
||||
background: color-mix(in srgb, var(--text-tertiary) 8%, transparent);
|
||||
border: 1px solid color-mix(in srgb, var(--border-color) 40%, transparent);
|
||||
|
||||
.footprint-ai-head {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
gap: 8px;
|
||||
margin-bottom: 8px;
|
||||
|
||||
strong {
|
||||
font-size: 14px;
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
span {
|
||||
font-size: 12px;
|
||||
color: var(--text-tertiary);
|
||||
}
|
||||
}
|
||||
|
||||
p {
|
||||
margin: 0;
|
||||
white-space: pre-wrap;
|
||||
line-height: 1.6;
|
||||
color: var(--text-secondary);
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
&.footprint-ai-result-error {
|
||||
border-color: color-mix(in srgb, #ef4444 50%, transparent);
|
||||
}
|
||||
}
|
||||
|
||||
.kpi-label {
|
||||
font-size: 13px;
|
||||
font-weight: 500;
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
.kpi-diagnostics {
|
||||
cursor: default;
|
||||
&:hover { opacity: 1; }
|
||||
border-left: 1px solid color-mix(in srgb, var(--border-color) 40%, transparent);
|
||||
padding-left: 20px;
|
||||
}
|
||||
|
||||
.footprint-timeline {
|
||||
animation: timelineSwitchFade 0.4s cubic-bezier(0.16, 1, 0.3, 1) both;
|
||||
--timeline-time-col-width: 64px;
|
||||
--timeline-dot-col-width: 20px;
|
||||
--timeline-gap: 24px;
|
||||
|
||||
flex: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 24px;
|
||||
padding: 10px 0;
|
||||
|
||||
&.timeline-time-month_day_clock {
|
||||
--timeline-time-col-width: 86px;
|
||||
}
|
||||
|
||||
&.timeline-time-full_date_clock {
|
||||
--timeline-time-col-width: 124px;
|
||||
}
|
||||
}
|
||||
|
||||
.timeline-head {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
.timeline-head-left h2 {
|
||||
display: none; /* the minimalist approach relies on content, we skip this redundant title */
|
||||
}
|
||||
|
||||
.timeline-head-left p {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.timeline-mode-row {
|
||||
display: flex;
|
||||
gap: 4px;
|
||||
background: color-mix(in srgb, var(--text-tertiary) 6%, transparent);
|
||||
padding: 3px;
|
||||
border-radius: 8px;
|
||||
}
|
||||
|
||||
.timeline-mode-chip {
|
||||
border: none;
|
||||
background: transparent;
|
||||
color: var(--text-secondary);
|
||||
font-size: 13px;
|
||||
font-weight: 500;
|
||||
padding: 6px 12px;
|
||||
border-radius: 6px;
|
||||
cursor: pointer;
|
||||
transition: all 0.2s ease;
|
||||
|
||||
&:hover {
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
&.active {
|
||||
color: var(--text-primary);
|
||||
background: var(--bg-primary);
|
||||
box-shadow: 0 1px 3px rgba(0,0,0,0.04);
|
||||
}
|
||||
}
|
||||
|
||||
.timeline-stream {
|
||||
position: relative;
|
||||
padding-bottom: 40px;
|
||||
|
||||
&::before {
|
||||
content: '';
|
||||
position: absolute;
|
||||
left: calc(var(--timeline-time-col-width) + var(--timeline-gap) + 9px);
|
||||
top: 0;
|
||||
bottom: 0;
|
||||
width: 2px;
|
||||
background: color-mix(in srgb, var(--text-tertiary) 20%, transparent);
|
||||
}
|
||||
}
|
||||
|
||||
.timeline-item {
|
||||
display: grid;
|
||||
grid-template-columns: var(--timeline-time-col-width) var(--timeline-dot-col-width) minmax(0, 1fr);
|
||||
column-gap: var(--timeline-gap);
|
||||
align-items: stretch;
|
||||
margin-bottom: 38px;
|
||||
}
|
||||
|
||||
.timeline-time {
|
||||
font-size: 13px;
|
||||
color: var(--text-tertiary);
|
||||
text-align: right;
|
||||
padding-top: 5px;
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
.timeline-time-private {
|
||||
padding-top: 5px;
|
||||
}
|
||||
|
||||
.timeline-time-range {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: flex-end;
|
||||
justify-content: space-between;
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
.timeline-time-main,
|
||||
.timeline-time-end {
|
||||
color: var(--text-secondary);
|
||||
font-weight: 500;
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
.timeline-time-sep {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.timeline-dot-col {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
padding-top: 9px;
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
.timeline-dot {
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
border-radius: 50%;
|
||||
background: var(--text-tertiary);
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.timeline-dot-mention {
|
||||
background: var(--timeline-mention);
|
||||
}
|
||||
|
||||
.timeline-dot-private {
|
||||
background: var(--timeline-private);
|
||||
}
|
||||
|
||||
.timeline-dot-private-inbound_only {
|
||||
background: var(--timeline-mention);
|
||||
border: none;
|
||||
}
|
||||
|
||||
.timeline-dot-private-outbound_only {
|
||||
background: #22c55e;
|
||||
}
|
||||
|
||||
.timeline-dot-private-both {
|
||||
background: var(--timeline-private);
|
||||
}
|
||||
|
||||
.timeline-dot-start,
|
||||
.timeline-dot-end {
|
||||
background: transparent;
|
||||
border: 1.5px solid var(--text-tertiary);
|
||||
width: 10px;
|
||||
height: 10px;
|
||||
margin-top: -1px;
|
||||
}
|
||||
|
||||
.timeline-dot-range {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
height: 100%;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.timeline-dot-range-line {
|
||||
width: 2px;
|
||||
flex: 1;
|
||||
margin: 4px 0;
|
||||
background: color-mix(in srgb, var(--timeline-private) 30%, transparent);
|
||||
}
|
||||
|
||||
.timeline-dot-range-line-inbound_only {
|
||||
background: color-mix(in srgb, var(--timeline-mention) 55%, transparent);
|
||||
}
|
||||
|
||||
.timeline-dot-range-line-outbound_only {
|
||||
background: #22c55e;
|
||||
}
|
||||
|
||||
.timeline-dot-range-line-both {
|
||||
background: color-mix(in srgb, var(--timeline-private) 55%, transparent);
|
||||
}
|
||||
|
||||
.timeline-content-wrap {
|
||||
padding-top: 2px;
|
||||
padding-bottom: 6px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
justify-content: space-between;
|
||||
min-height: 100%;
|
||||
}
|
||||
|
||||
.timeline-boundary {
|
||||
font-size: 13px;
|
||||
color: var(--text-tertiary);
|
||||
padding: 4px 0;
|
||||
}
|
||||
|
||||
.timeline-card {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
|
||||
/* completely clean out the old card style */
|
||||
border: none;
|
||||
background: transparent;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.timeline-card-head {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.timeline-identity {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.timeline-avatar {
|
||||
width: 28px;
|
||||
height: 28px;
|
||||
border-radius: 50%; /* Modern circle avatars */
|
||||
overflow: hidden;
|
||||
background: color-mix(in srgb, var(--text-tertiary) 10%, transparent);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
color: var(--text-tertiary);
|
||||
|
||||
img {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: cover;
|
||||
}
|
||||
}
|
||||
|
||||
.timeline-avatar-private {
|
||||
color: var(--timeline-private);
|
||||
}
|
||||
|
||||
.timeline-title-group {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.timeline-title {
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.timeline-subtitle {
|
||||
font-size: 13px;
|
||||
color: var(--text-tertiary);
|
||||
}
|
||||
|
||||
.timeline-right-tools {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.timeline-count-badge {
|
||||
font-size: 12px;
|
||||
color: var(--text-tertiary);
|
||||
}
|
||||
|
||||
.timeline-jump-btn {
|
||||
padding: 4px 10px;
|
||||
font-size: 12px;
|
||||
background: transparent;
|
||||
color: var(--text-tertiary);
|
||||
|
||||
&:hover {
|
||||
background: color-mix(in srgb, var(--text-tertiary) 10%, transparent);
|
||||
color: var(--text-primary);
|
||||
}
|
||||
}
|
||||
|
||||
.timeline-message {
|
||||
font-size: 13px;
|
||||
line-height: 1.5;
|
||||
color: var(--text-secondary);
|
||||
padding: 0;
|
||||
margin-top: 4px;
|
||||
background: transparent;
|
||||
border-radius: 0;
|
||||
word-break: break-word;
|
||||
white-space: pre-wrap;
|
||||
}
|
||||
|
||||
.mention-message {
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.private-message {
|
||||
color: var(--text-tertiary);
|
||||
}
|
||||
|
||||
@keyframes timelineSwitchFade {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translateY(12px);
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: translateY(0);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
.mention-token {
|
||||
color: var(--timeline-mention);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.panel-empty-state {
|
||||
text-align: center;
|
||||
padding: 60px 0;
|
||||
color: var(--text-tertiary);
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.footprint-loading {
|
||||
padding: 40px 0;
|
||||
}
|
||||
|
||||
.kpi-skeleton-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(4, minmax(0, 1fr));
|
||||
gap: 20px;
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
.kpi-skeleton-card {
|
||||
height: 60px;
|
||||
border-radius: 8px;
|
||||
background: color-mix(in srgb, var(--text-tertiary) 6%, transparent);
|
||||
}
|
||||
|
||||
.timeline-skeleton-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 20px;
|
||||
}
|
||||
|
||||
.timeline-skeleton-item {
|
||||
height: 80px;
|
||||
border-radius: 8px;
|
||||
background: color-mix(in srgb, var(--text-tertiary) 6%, transparent);
|
||||
}
|
||||
|
||||
.footprint-export-modal-mask {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
z-index: 1200;
|
||||
background: color-mix(in srgb, #000 36%, transparent);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 24px;
|
||||
}
|
||||
|
||||
.footprint-export-modal {
|
||||
width: min(520px, 100%);
|
||||
border-radius: 16px;
|
||||
background: var(--bg-primary);
|
||||
border: 1px solid color-mix(in srgb, var(--border-color) 60%, transparent);
|
||||
box-shadow: 0 18px 60px rgba(0, 0, 0, 0.2);
|
||||
padding: 22px 22px 18px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
animation: footprintFadeSlideUp 0.2s ease both;
|
||||
|
||||
h3 {
|
||||
margin: 0;
|
||||
font-size: 18px;
|
||||
font-weight: 600;
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
p {
|
||||
margin: 0;
|
||||
color: var(--text-secondary);
|
||||
font-size: 14px;
|
||||
line-height: 1.5;
|
||||
}
|
||||
}
|
||||
|
||||
.export-modal-icon {
|
||||
width: 34px;
|
||||
height: 34px;
|
||||
border-radius: 10px;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.export-modal-icon-progress {
|
||||
color: var(--primary);
|
||||
background: color-mix(in srgb, var(--primary) 16%, transparent);
|
||||
}
|
||||
|
||||
.export-modal-icon-success {
|
||||
color: #16a34a;
|
||||
background: color-mix(in srgb, #16a34a 18%, transparent);
|
||||
}
|
||||
|
||||
.export-modal-icon-error {
|
||||
color: #ef4444;
|
||||
background: color-mix(in srgb, #ef4444 18%, transparent);
|
||||
}
|
||||
|
||||
.export-modal-path {
|
||||
display: block;
|
||||
margin-top: 2px;
|
||||
padding: 10px 12px;
|
||||
border-radius: 10px;
|
||||
font-family: inherit;
|
||||
font-weight: 500;
|
||||
font-size: 12px;
|
||||
line-height: 1.4;
|
||||
color: var(--text-tertiary);
|
||||
background: color-mix(in srgb, var(--text-tertiary) 8%, transparent);
|
||||
border: 1px solid color-mix(in srgb, var(--border-color) 40%, transparent);
|
||||
white-space: pre-wrap;
|
||||
word-break: break-all;
|
||||
}
|
||||
|
||||
.export-modal-actions {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
margin-top: 6px;
|
||||
}
|
||||
|
||||
.skeleton-shimmer {
|
||||
position: relative;
|
||||
overflow: hidden;
|
||||
|
||||
&::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
background: linear-gradient(
|
||||
90deg,
|
||||
transparent,
|
||||
color-mix(in srgb, var(--bg-primary) 50%, transparent),
|
||||
transparent
|
||||
);
|
||||
transform: translateX(-100%);
|
||||
animation: footprintShimmer 1.5s infinite;
|
||||
}
|
||||
}
|
||||
|
||||
/* Animations */
|
||||
@keyframes footprintPageEnter {
|
||||
from { opacity: 0; transform: translateY(10px); }
|
||||
to { opacity: 1; transform: translateY(0); }
|
||||
}
|
||||
|
||||
@keyframes footprintFadeSlideUp {
|
||||
from { opacity: 0; transform: translateY(5px); }
|
||||
to { opacity: 1; transform: translateY(0); }
|
||||
}
|
||||
|
||||
@keyframes footprintKpiIn {
|
||||
from { opacity: 0; transform: translateY(8px); }
|
||||
to { opacity: 1; transform: translateY(0); }
|
||||
}
|
||||
|
||||
@keyframes footprintTimelineItemIn {
|
||||
from { opacity: 0; transform: translateY(10px); }
|
||||
to { opacity: 1; transform: translateY(0); }
|
||||
}
|
||||
|
||||
@keyframes footprintSpin {
|
||||
100% { transform: rotate(360deg); }
|
||||
}
|
||||
|
||||
@keyframes footprintShimmer {
|
||||
100% { transform: translateX(100%); }
|
||||
}
|
||||
|
||||
@media (max-width: 1100px) {
|
||||
.kpi-grid,
|
||||
.kpi-skeleton-grid {
|
||||
grid-template-columns: repeat(3, 1fr);
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 800px) {
|
||||
.my-footprint-page {
|
||||
padding: 20px;
|
||||
}
|
||||
.kpi-grid,
|
||||
.kpi-skeleton-grid {
|
||||
grid-template-columns: repeat(2, 1fr);
|
||||
}
|
||||
}
|
||||
983
src/pages/MyFootprintPage.tsx
Normal file
983
src/pages/MyFootprintPage.tsx
Normal file
@@ -0,0 +1,983 @@
|
||||
import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from 'react'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import { AlertCircle, AtSign, CheckCircle2, Download, Loader2, MessageCircle, RefreshCw, Search, Sparkles, Users } from 'lucide-react'
|
||||
import DateRangePicker from '../components/DateRangePicker'
|
||||
import './MyFootprintPage.scss'
|
||||
|
||||
type RangePreset = 'today' | 'yesterday' | 'this_week' | 'last_week' | 'custom'
|
||||
type TimelineMode = 'all' | 'mention' | 'private'
|
||||
type TimelineTimeMode = 'clock' | 'month_day_clock' | 'full_date_clock'
|
||||
type PrivateDotVariant = 'both' | 'inbound_only' | 'outbound_only'
|
||||
type ExportModalStatus = 'idle' | 'progress' | 'success' | 'error'
|
||||
type FootprintAiStatus = 'idle' | 'loading' | 'success' | 'error'
|
||||
|
||||
interface MyFootprintSummary {
|
||||
private_inbound_people: number
|
||||
private_replied_people: number
|
||||
private_outbound_people: number
|
||||
private_reply_rate: number
|
||||
mention_count: number
|
||||
mention_group_count: number
|
||||
}
|
||||
|
||||
interface MyFootprintPrivateSession {
|
||||
session_id: string
|
||||
incoming_count: number
|
||||
outgoing_count: number
|
||||
replied: boolean
|
||||
first_incoming_ts: number
|
||||
first_reply_ts: number
|
||||
latest_ts: number
|
||||
anchor_local_id: number
|
||||
anchor_create_time: number
|
||||
displayName?: string
|
||||
avatarUrl?: string
|
||||
}
|
||||
|
||||
interface MyFootprintPrivateSegment {
|
||||
session_id: string
|
||||
segment_index: number
|
||||
start_ts: number
|
||||
end_ts: number
|
||||
duration_sec: number
|
||||
incoming_count: number
|
||||
outgoing_count: number
|
||||
message_count: number
|
||||
replied: boolean
|
||||
first_incoming_ts: number
|
||||
first_reply_ts: number
|
||||
latest_ts: number
|
||||
anchor_local_id: number
|
||||
anchor_create_time: number
|
||||
displayName?: string
|
||||
avatarUrl?: string
|
||||
}
|
||||
|
||||
interface MyFootprintMention {
|
||||
session_id: string
|
||||
local_id: number
|
||||
create_time: number
|
||||
sender_username: string
|
||||
message_content: string
|
||||
source: string
|
||||
sessionDisplayName?: string
|
||||
senderDisplayName?: string
|
||||
senderAvatarUrl?: string
|
||||
}
|
||||
|
||||
interface MyFootprintMentionGroup {
|
||||
session_id: string
|
||||
count: number
|
||||
latest_ts: number
|
||||
displayName?: string
|
||||
avatarUrl?: string
|
||||
}
|
||||
|
||||
interface MyFootprintDiagnostics {
|
||||
truncated: boolean
|
||||
scanned_dbs: number
|
||||
elapsed_ms: number
|
||||
mention_truncated?: boolean
|
||||
private_truncated?: boolean
|
||||
}
|
||||
|
||||
interface MyFootprintData {
|
||||
summary: MyFootprintSummary
|
||||
private_sessions: MyFootprintPrivateSession[]
|
||||
private_segments: MyFootprintPrivateSegment[]
|
||||
mentions: MyFootprintMention[]
|
||||
mention_groups: MyFootprintMentionGroup[]
|
||||
diagnostics: MyFootprintDiagnostics
|
||||
}
|
||||
|
||||
interface TimelineBoundaryItem {
|
||||
kind: 'boundary'
|
||||
edge: 'start' | 'end'
|
||||
key: string
|
||||
time: number
|
||||
label: string
|
||||
}
|
||||
|
||||
interface TimelineMentionItem {
|
||||
kind: 'mention'
|
||||
key: string
|
||||
time: number
|
||||
sessionId: string
|
||||
localId: number
|
||||
createTime: number
|
||||
groupName: string
|
||||
groupAvatarUrl?: string
|
||||
senderName: string
|
||||
messageContent: string
|
||||
}
|
||||
|
||||
interface TimelinePrivateItem {
|
||||
kind: 'private'
|
||||
key: string
|
||||
time: number
|
||||
endTime: number
|
||||
sessionId: string
|
||||
anchorLocalId: number
|
||||
anchorCreateTime: number
|
||||
displayName: string
|
||||
avatarUrl?: string
|
||||
subtitle: string
|
||||
totalInteractions: number
|
||||
summaryText: string
|
||||
dotVariant: PrivateDotVariant
|
||||
isRange: boolean
|
||||
}
|
||||
|
||||
type TimelineItem = TimelineBoundaryItem | TimelineMentionItem | TimelinePrivateItem
|
||||
|
||||
const EMPTY_DATA: MyFootprintData = {
|
||||
summary: {
|
||||
private_inbound_people: 0,
|
||||
private_replied_people: 0,
|
||||
private_outbound_people: 0,
|
||||
private_reply_rate: 0,
|
||||
mention_count: 0,
|
||||
mention_group_count: 0
|
||||
},
|
||||
private_sessions: [],
|
||||
private_segments: [],
|
||||
mentions: [],
|
||||
mention_groups: [],
|
||||
diagnostics: {
|
||||
truncated: false,
|
||||
scanned_dbs: 0,
|
||||
elapsed_ms: 0,
|
||||
mention_truncated: false,
|
||||
private_truncated: false
|
||||
}
|
||||
}
|
||||
|
||||
function toDayStart(date: Date): Date {
|
||||
const next = new Date(date)
|
||||
next.setHours(0, 0, 0, 0)
|
||||
return next
|
||||
}
|
||||
|
||||
function toDayEnd(date: Date): Date {
|
||||
const next = new Date(date)
|
||||
next.setHours(23, 59, 59, 999)
|
||||
return next
|
||||
}
|
||||
|
||||
function toSeconds(date: Date): number {
|
||||
return Math.floor(date.getTime() / 1000)
|
||||
}
|
||||
|
||||
function toDateInputValue(date: Date): string {
|
||||
const y = date.getFullYear()
|
||||
const m = `${date.getMonth() + 1}`.padStart(2, '0')
|
||||
const d = `${date.getDate()}`.padStart(2, '0')
|
||||
return `${y}-${m}-${d}`
|
||||
}
|
||||
|
||||
function getWeekStart(date: Date): Date {
|
||||
const base = toDayStart(date)
|
||||
const day = base.getDay()
|
||||
const diff = day === 0 ? -6 : 1 - day
|
||||
base.setDate(base.getDate() + diff)
|
||||
return base
|
||||
}
|
||||
|
||||
function formatTimelineMoment(seconds: number, mode: TimelineTimeMode): string {
|
||||
if (!seconds || !Number.isFinite(seconds)) return '--'
|
||||
const date = new Date(seconds * 1000)
|
||||
const yyyy = `${date.getFullYear()}`
|
||||
const mm = `${date.getMonth() + 1}`.padStart(2, '0')
|
||||
const dd = `${date.getDate()}`.padStart(2, '0')
|
||||
const hh = `${date.getHours()}`.padStart(2, '0')
|
||||
const min = `${date.getMinutes()}`.padStart(2, '0')
|
||||
if (mode === 'full_date_clock') {
|
||||
return `${yyyy}-${mm}-${dd} ${hh}:${min}`
|
||||
}
|
||||
if (mode === 'month_day_clock') {
|
||||
return `${mm}-${dd} ${hh}:${min}`
|
||||
}
|
||||
return `${hh}:${min}`
|
||||
}
|
||||
|
||||
function formatPercent(value: number): string {
|
||||
const safe = Number.isFinite(value) ? value : 0
|
||||
return `${(safe * 100).toFixed(1)}%`
|
||||
}
|
||||
|
||||
function decodeHtmlEntities(content: string): string {
|
||||
return String(content || '')
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, "'")
|
||||
}
|
||||
|
||||
function stripGroupSenderPrefix(content: string): string {
|
||||
return String(content || '')
|
||||
.replace(/^[\s]*([a-zA-Z0-9_@-]+):(?!\/\/)(?:\s*(?:\r?\n|<br\s*\/?>)\s*|\s*)/i, '')
|
||||
.replace(/^[a-zA-Z0-9]+@openim:\n?/i, '')
|
||||
}
|
||||
|
||||
function normalizeFootprintMessageContent(content: string): string {
|
||||
const decoded = decodeHtmlEntities(content || '')
|
||||
const stripped = stripGroupSenderPrefix(decoded)
|
||||
return stripped.trim()
|
||||
}
|
||||
|
||||
function renderMentionContent(content: string): ReactNode {
|
||||
const normalized = String(content || '').trim() || '[空消息]'
|
||||
const parts = normalized.split(/(@我|@我)/g)
|
||||
if (parts.length <= 1) return normalized
|
||||
return parts.map((part, index) => {
|
||||
if (part === '@我' || part === '@我') {
|
||||
return (
|
||||
<span key={index} className="mention-token">
|
||||
{part}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
return <span key={index}>{part}</span>
|
||||
})
|
||||
}
|
||||
|
||||
function formatDurationLabel(beginTimestamp: number, endTimestamp: number): string {
|
||||
if (!beginTimestamp || !endTimestamp || endTimestamp <= beginTimestamp) {
|
||||
return '持续不足 1 分钟'
|
||||
}
|
||||
const minutes = Math.max(1, Math.round((endTimestamp - beginTimestamp) / 60))
|
||||
return `持续 ${minutes} 分钟`
|
||||
}
|
||||
|
||||
function resolveRangePresetLabel(preset: RangePreset): string {
|
||||
switch (preset) {
|
||||
case 'today':
|
||||
return '今天'
|
||||
case 'yesterday':
|
||||
return '昨天'
|
||||
case 'this_week':
|
||||
return '本周'
|
||||
case 'last_week':
|
||||
return '上周'
|
||||
default:
|
||||
return '自定义'
|
||||
}
|
||||
}
|
||||
|
||||
function buildRange(preset: RangePreset, customStart: string, customEnd: string): { begin: number; end: number; label: string } {
|
||||
const now = new Date()
|
||||
|
||||
if (preset === 'today') {
|
||||
return {
|
||||
begin: toSeconds(toDayStart(now)),
|
||||
end: toSeconds(now),
|
||||
label: '今天'
|
||||
}
|
||||
}
|
||||
|
||||
if (preset === 'yesterday') {
|
||||
const yesterday = new Date(now)
|
||||
yesterday.setDate(yesterday.getDate() - 1)
|
||||
return {
|
||||
begin: toSeconds(toDayStart(yesterday)),
|
||||
end: toSeconds(toDayEnd(yesterday)),
|
||||
label: '昨天'
|
||||
}
|
||||
}
|
||||
|
||||
if (preset === 'this_week') {
|
||||
const weekStart = getWeekStart(now)
|
||||
const weekEnd = new Date(weekStart)
|
||||
weekEnd.setDate(weekStart.getDate() + 6)
|
||||
return {
|
||||
begin: toSeconds(toDayStart(weekStart)),
|
||||
end: toSeconds(toDayEnd(weekEnd)),
|
||||
label: '本周'
|
||||
}
|
||||
}
|
||||
|
||||
if (preset === 'last_week') {
|
||||
const thisWeekStart = getWeekStart(now)
|
||||
const lastWeekStart = new Date(thisWeekStart)
|
||||
lastWeekStart.setDate(lastWeekStart.getDate() - 7)
|
||||
const lastWeekEnd = new Date(thisWeekStart)
|
||||
lastWeekEnd.setDate(lastWeekEnd.getDate() - 1)
|
||||
return {
|
||||
begin: toSeconds(toDayStart(lastWeekStart)),
|
||||
end: toSeconds(toDayEnd(lastWeekEnd)),
|
||||
label: '上周'
|
||||
}
|
||||
}
|
||||
|
||||
const customStartDate = customStart ? new Date(`${customStart}T00:00:00`) : toDayStart(now)
|
||||
const customEndDate = customEnd ? new Date(`${customEnd}T23:59:59`) : toDayEnd(now)
|
||||
const begin = toSeconds(customStartDate)
|
||||
const end = Math.max(begin, toSeconds(customEndDate))
|
||||
|
||||
return {
|
||||
begin,
|
||||
end,
|
||||
label: `${toDateInputValue(customStartDate)} 至 ${toDateInputValue(customEndDate)}`
|
||||
}
|
||||
}
|
||||
|
||||
function MyFootprintPage() {
|
||||
const navigate = useNavigate()
|
||||
const [preset, setPreset] = useState<RangePreset>('today')
|
||||
const [customStartDate, setCustomStartDate] = useState(() => toDateInputValue(toDayStart(new Date())))
|
||||
const [customEndDate, setCustomEndDate] = useState(() => toDateInputValue(toDayStart(new Date())))
|
||||
const [searchKeyword, setSearchKeyword] = useState('')
|
||||
const [timelineMode, setTimelineMode] = useState<TimelineMode>('all')
|
||||
const [data, setData] = useState<MyFootprintData>(EMPTY_DATA)
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [exporting, setExporting] = useState(false)
|
||||
const [exportModalStatus, setExportModalStatus] = useState<ExportModalStatus>('idle')
|
||||
const [exportModalTitle, setExportModalTitle] = useState('')
|
||||
const [exportModalDescription, setExportModalDescription] = useState('')
|
||||
const [exportModalPath, setExportModalPath] = useState('')
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [footprintAiStatus, setFootprintAiStatus] = useState<FootprintAiStatus>('idle')
|
||||
const [footprintAiText, setFootprintAiText] = useState('')
|
||||
const inflightRangeKeyRef = useRef<string | null>(null)
|
||||
|
||||
const currentRange = useMemo(() => buildRange(preset, customStartDate, customEndDate), [preset, customStartDate, customEndDate])
|
||||
const timelineTimeMode = useMemo<TimelineTimeMode>(() => {
|
||||
const span = Math.max(0, currentRange.end - currentRange.begin)
|
||||
if (span > 365 * 24 * 60 * 60) return 'full_date_clock'
|
||||
if (span > 24 * 60 * 60) return 'month_day_clock'
|
||||
return 'clock'
|
||||
}, [currentRange.begin, currentRange.end])
|
||||
|
||||
const handleJump = useCallback((sessionId: string, localId: number, createTime: number) => {
|
||||
if (!sessionId || !localId || !createTime) return
|
||||
const query = new URLSearchParams({
|
||||
sessionId,
|
||||
jumpLocalId: String(localId),
|
||||
jumpCreateTime: String(createTime),
|
||||
jumpSource: 'footprint'
|
||||
})
|
||||
navigate(`/chat?${query.toString()}`)
|
||||
}, [navigate])
|
||||
|
||||
const loadData = useCallback(async () => {
|
||||
const rangeKey = `${currentRange.begin}-${currentRange.end}`
|
||||
if (inflightRangeKeyRef.current === rangeKey) {
|
||||
return
|
||||
}
|
||||
inflightRangeKeyRef.current = rangeKey
|
||||
setLoading(true)
|
||||
setError(null)
|
||||
try {
|
||||
const result = await window.electronAPI.chat.getMyFootprintStats(currentRange.begin, currentRange.end)
|
||||
if (!result.success || !result.data) {
|
||||
setError(result.error || '读取统计失败')
|
||||
setData(EMPTY_DATA)
|
||||
return
|
||||
}
|
||||
setData({
|
||||
...result.data,
|
||||
private_segments: Array.isArray(result.data.private_segments) ? result.data.private_segments : []
|
||||
})
|
||||
} catch (loadError) {
|
||||
setError(String(loadError))
|
||||
setData(EMPTY_DATA)
|
||||
} finally {
|
||||
setLoading(false)
|
||||
if (inflightRangeKeyRef.current === rangeKey) {
|
||||
inflightRangeKeyRef.current = null
|
||||
}
|
||||
}
|
||||
}, [currentRange.begin, currentRange.end])
|
||||
|
||||
useEffect(() => {
|
||||
void loadData()
|
||||
}, [loadData])
|
||||
|
||||
const keyword = searchKeyword.trim().toLowerCase()
|
||||
|
||||
const privateSessionMetaMap = useMemo(() => {
|
||||
const map = new Map<string, { displayName?: string; avatarUrl?: string }>()
|
||||
for (const item of data.private_sessions) {
|
||||
map.set(item.session_id, {
|
||||
displayName: item.displayName,
|
||||
avatarUrl: item.avatarUrl
|
||||
})
|
||||
}
|
||||
for (const item of data.private_segments) {
|
||||
if (!map.has(item.session_id)) {
|
||||
map.set(item.session_id, {
|
||||
displayName: item.displayName,
|
||||
avatarUrl: item.avatarUrl
|
||||
})
|
||||
}
|
||||
}
|
||||
return map
|
||||
}, [data.private_sessions, data.private_segments])
|
||||
|
||||
const filteredMentions = useMemo(() => {
|
||||
if (!keyword) return data.mentions
|
||||
return data.mentions.filter((item) => {
|
||||
const sessionName = (item.sessionDisplayName || '').toLowerCase()
|
||||
const senderName = (item.senderDisplayName || '').toLowerCase()
|
||||
const sender = item.sender_username.toLowerCase()
|
||||
const content = normalizeFootprintMessageContent(item.message_content).toLowerCase()
|
||||
return sessionName.includes(keyword) || senderName.includes(keyword) || sender.includes(keyword) || content.includes(keyword)
|
||||
})
|
||||
}, [data.mentions, keyword])
|
||||
|
||||
const filteredPrivateSegments = useMemo(() => {
|
||||
const rawSegments = data.private_segments.length > 0
|
||||
? data.private_segments
|
||||
: data.private_sessions.map((item, index) => ({
|
||||
session_id: item.session_id,
|
||||
segment_index: index + 1,
|
||||
start_ts: item.first_incoming_ts > 0
|
||||
? item.first_incoming_ts
|
||||
: item.first_reply_ts > 0
|
||||
? item.first_reply_ts
|
||||
: item.latest_ts,
|
||||
end_ts: item.latest_ts,
|
||||
duration_sec: Math.max(0, item.latest_ts - (item.first_incoming_ts || item.first_reply_ts || item.latest_ts)),
|
||||
incoming_count: item.incoming_count,
|
||||
outgoing_count: item.outgoing_count,
|
||||
message_count: Math.max(0, item.incoming_count + item.outgoing_count),
|
||||
replied: item.replied,
|
||||
first_incoming_ts: item.first_incoming_ts,
|
||||
first_reply_ts: item.first_reply_ts,
|
||||
latest_ts: item.latest_ts,
|
||||
anchor_local_id: item.anchor_local_id,
|
||||
anchor_create_time: item.anchor_create_time,
|
||||
displayName: item.displayName,
|
||||
avatarUrl: item.avatarUrl
|
||||
}))
|
||||
|
||||
if (!keyword) return rawSegments
|
||||
return rawSegments.filter((item) => {
|
||||
const meta = privateSessionMetaMap.get(item.session_id)
|
||||
const name = String(item.displayName || meta?.displayName || '').toLowerCase()
|
||||
const id = item.session_id.toLowerCase()
|
||||
return name.includes(keyword) || id.includes(keyword)
|
||||
})
|
||||
}, [data.private_segments, data.private_sessions, keyword, privateSessionMetaMap])
|
||||
|
||||
const mentionGroupMetaMap = useMemo(() => {
|
||||
const map = new Map<string, { displayName?: string; avatarUrl?: string }>()
|
||||
for (const item of data.mention_groups) {
|
||||
map.set(item.session_id, { displayName: item.displayName, avatarUrl: item.avatarUrl })
|
||||
}
|
||||
for (const item of data.private_sessions) {
|
||||
if (!map.has(item.session_id)) {
|
||||
map.set(item.session_id, { displayName: item.displayName, avatarUrl: item.avatarUrl })
|
||||
}
|
||||
}
|
||||
return map
|
||||
}, [data.mention_groups, data.private_sessions])
|
||||
|
||||
const mentionTimelineItems = useMemo<TimelineMentionItem[]>(() => {
|
||||
return filteredMentions
|
||||
.filter((item) => item.create_time > 0)
|
||||
.map((item) => {
|
||||
const groupMeta = mentionGroupMetaMap.get(item.session_id)
|
||||
return {
|
||||
kind: 'mention' as const,
|
||||
key: `mention:${item.session_id}:${item.local_id}`,
|
||||
time: item.create_time,
|
||||
sessionId: item.session_id,
|
||||
localId: item.local_id,
|
||||
createTime: item.create_time,
|
||||
groupName: item.sessionDisplayName || groupMeta?.displayName || item.session_id,
|
||||
groupAvatarUrl: groupMeta?.avatarUrl,
|
||||
senderName: item.senderDisplayName || item.sender_username || '未知',
|
||||
messageContent: normalizeFootprintMessageContent(item.message_content)
|
||||
}
|
||||
})
|
||||
}, [filteredMentions, mentionGroupMetaMap])
|
||||
|
||||
const privateTimelineItems = useMemo<TimelinePrivateItem[]>(() => {
|
||||
return filteredPrivateSegments
|
||||
.map((item) => {
|
||||
const startTime = item.start_ts > 0
|
||||
? item.start_ts
|
||||
: item.first_incoming_ts > 0
|
||||
? item.first_incoming_ts
|
||||
: item.first_reply_ts > 0
|
||||
? item.first_reply_ts
|
||||
: item.latest_ts
|
||||
|
||||
const endTime = item.end_ts > 0 ? item.end_ts : item.latest_ts
|
||||
const isRange = endTime > startTime + 60
|
||||
const totalInteractions = Math.max(0, item.message_count || (item.incoming_count + item.outgoing_count))
|
||||
const durationLabel = item.duration_sec > 0
|
||||
? `持续 ${Math.max(1, Math.round(item.duration_sec / 60))} 分钟`
|
||||
: formatDurationLabel(startTime, endTime)
|
||||
const subtitle = isRange
|
||||
? `${formatTimelineMoment(startTime, timelineTimeMode)} 至 ${formatTimelineMoment(endTime || startTime, timelineTimeMode)} · ${durationLabel}`
|
||||
: ''
|
||||
const summaryText = `收到 ${item.incoming_count} 条 / 发送 ${item.outgoing_count} 条${item.replied ? ' · 已回复' : ''}`
|
||||
const sessionMeta = privateSessionMetaMap.get(item.session_id)
|
||||
let dotVariant: PrivateDotVariant = 'both'
|
||||
if (item.incoming_count > 0 && item.outgoing_count === 0) {
|
||||
dotVariant = 'inbound_only'
|
||||
} else if (item.incoming_count === 0 && item.outgoing_count > 0) {
|
||||
dotVariant = 'outbound_only'
|
||||
}
|
||||
|
||||
return {
|
||||
kind: 'private' as const,
|
||||
key: `private:${item.session_id}:${item.segment_index}:${item.start_ts}`,
|
||||
time: startTime,
|
||||
endTime,
|
||||
sessionId: item.session_id,
|
||||
anchorLocalId: item.anchor_local_id,
|
||||
anchorCreateTime: item.anchor_create_time,
|
||||
displayName: item.displayName || sessionMeta?.displayName || item.session_id,
|
||||
avatarUrl: item.avatarUrl || sessionMeta?.avatarUrl,
|
||||
subtitle,
|
||||
totalInteractions,
|
||||
summaryText,
|
||||
dotVariant,
|
||||
isRange
|
||||
}
|
||||
})
|
||||
.filter((item) => item.time > 0)
|
||||
}, [filteredPrivateSegments, privateSessionMetaMap, timelineTimeMode])
|
||||
|
||||
const timelineItems = useMemo<TimelineItem[]>(() => {
|
||||
const events: TimelineItem[] = []
|
||||
if (timelineMode !== 'private') {
|
||||
events.push(...mentionTimelineItems)
|
||||
}
|
||||
if (timelineMode !== 'mention') {
|
||||
events.push(...privateTimelineItems)
|
||||
}
|
||||
|
||||
events.sort((a, b) => {
|
||||
if (a.time !== b.time) return a.time - b.time
|
||||
const rankA = a.kind === 'mention' ? 0 : a.kind === 'private' ? 1 : 2
|
||||
const rankB = b.kind === 'mention' ? 0 : b.kind === 'private' ? 1 : 2
|
||||
return rankA - rankB
|
||||
})
|
||||
|
||||
const presetLabel = resolveRangePresetLabel(preset)
|
||||
const startNode: TimelineBoundaryItem = {
|
||||
kind: 'boundary',
|
||||
edge: 'start',
|
||||
key: 'boundary:start',
|
||||
time: currentRange.begin,
|
||||
label: `区域时间开始(${presetLabel})`
|
||||
}
|
||||
|
||||
const endNode: TimelineBoundaryItem = {
|
||||
kind: 'boundary',
|
||||
edge: 'end',
|
||||
key: 'boundary:end',
|
||||
time: currentRange.end,
|
||||
label: `区域时间结束(${preset === 'today' ? '现在' : presetLabel})`
|
||||
}
|
||||
|
||||
return [startNode, ...events, endNode]
|
||||
}, [timelineMode, mentionTimelineItems, privateTimelineItems, currentRange.begin, currentRange.end, preset])
|
||||
|
||||
const timelineEventCount = useMemo(
|
||||
() => timelineItems.filter((item) => item.kind !== 'boundary').length,
|
||||
[timelineItems]
|
||||
)
|
||||
|
||||
const handleExport = useCallback(async (format: 'csv' | 'json') => {
|
||||
try {
|
||||
setExporting(true)
|
||||
setExportModalStatus('progress')
|
||||
setExportModalTitle(`正在准备导出 ${format.toUpperCase()}`)
|
||||
setExportModalDescription('正在准备文件保存信息...')
|
||||
setExportModalPath('')
|
||||
const downloadsPath = await window.electronAPI.app.getDownloadsPath()
|
||||
const separator = downloadsPath && downloadsPath.includes('\\') ? '\\' : '/'
|
||||
const rangeName = currentRange.label.replace(/[\\/:*?"<>|\s]+/g, '_')
|
||||
const suggestedName = `my_footprint_${rangeName}_${Date.now()}.${format}`
|
||||
const defaultPath = downloadsPath ? `${downloadsPath}${separator}${suggestedName}` : suggestedName
|
||||
|
||||
setExportModalDescription('请在弹窗中选择导出路径...')
|
||||
const saveResult = await window.electronAPI.dialog.saveFile({
|
||||
title: format === 'csv' ? '导出我的足迹 CSV' : '导出我的足迹 JSON',
|
||||
defaultPath,
|
||||
filters: format === 'csv'
|
||||
? [{ name: 'CSV', extensions: ['csv'] }]
|
||||
: [{ name: 'JSON', extensions: ['json'] }]
|
||||
})
|
||||
if (saveResult.canceled || !saveResult.filePath) {
|
||||
setExportModalStatus('idle')
|
||||
setExportModalTitle('')
|
||||
setExportModalDescription('')
|
||||
setExportModalPath('')
|
||||
return
|
||||
}
|
||||
|
||||
setExportModalDescription('正在导出数据,请稍候...')
|
||||
setExportModalPath(saveResult.filePath)
|
||||
const exportResult = await window.electronAPI.chat.exportMyFootprint(
|
||||
currentRange.begin,
|
||||
currentRange.end,
|
||||
format,
|
||||
saveResult.filePath
|
||||
)
|
||||
if (!exportResult.success) {
|
||||
setExportModalStatus('error')
|
||||
setExportModalTitle('导出失败')
|
||||
setExportModalDescription(exportResult.error || '未知错误')
|
||||
setExportModalPath(saveResult.filePath)
|
||||
return
|
||||
}
|
||||
setExportModalStatus('success')
|
||||
setExportModalTitle('导出完成')
|
||||
setExportModalDescription(`文件已成功导出为 ${format.toUpperCase()}。`)
|
||||
setExportModalPath(exportResult.filePath || saveResult.filePath)
|
||||
} catch (exportError) {
|
||||
setExportModalStatus('error')
|
||||
setExportModalTitle('导出失败')
|
||||
setExportModalDescription(String(exportError))
|
||||
} finally {
|
||||
setExporting(false)
|
||||
}
|
||||
}, [currentRange.begin, currentRange.end, currentRange.label])
|
||||
|
||||
const handleGenerateAiSummary = useCallback(async () => {
|
||||
setFootprintAiStatus('loading')
|
||||
setFootprintAiText('')
|
||||
try {
|
||||
const privateSegments = (data.private_segments.length > 0 ? data.private_segments : data.private_sessions).slice(0, 12)
|
||||
const result = await window.electronAPI.insight.generateFootprintInsight({
|
||||
rangeLabel: currentRange.label,
|
||||
summary: data.summary,
|
||||
privateSegments: privateSegments.map((item: MyFootprintPrivateSegment | MyFootprintPrivateSession) => ({
|
||||
session_id: item.session_id,
|
||||
displayName: item.displayName,
|
||||
incoming_count: item.incoming_count,
|
||||
outgoing_count: item.outgoing_count,
|
||||
message_count: 'message_count' in item ? item.message_count : item.incoming_count + item.outgoing_count,
|
||||
replied: item.replied
|
||||
})),
|
||||
mentionGroups: data.mention_groups.slice(0, 12).map((item) => ({
|
||||
session_id: item.session_id,
|
||||
displayName: item.displayName,
|
||||
count: item.count
|
||||
}))
|
||||
})
|
||||
if (!result.success || !result.insight) {
|
||||
setFootprintAiStatus('error')
|
||||
setFootprintAiText(result.message || '生成失败')
|
||||
return
|
||||
}
|
||||
setFootprintAiStatus('success')
|
||||
setFootprintAiText(result.insight)
|
||||
} catch (generateError) {
|
||||
setFootprintAiStatus('error')
|
||||
setFootprintAiText(String(generateError))
|
||||
}
|
||||
}, [currentRange.label, data])
|
||||
|
||||
return (
|
||||
<div className="my-footprint-page">
|
||||
<section className="footprint-header">
|
||||
<div className="footprint-title-wrap">
|
||||
<h1>我的微信足迹</h1>
|
||||
<p>范围:{currentRange.label}</p>
|
||||
</div>
|
||||
|
||||
<div className="footprint-toolbar">
|
||||
<div className="range-preset-group">
|
||||
{[
|
||||
{ value: 'today', label: '今天' },
|
||||
{ value: 'yesterday', label: '昨天' },
|
||||
{ value: 'this_week', label: '本周' },
|
||||
{ value: 'last_week', label: '上周' },
|
||||
{ value: 'custom', label: '自定义' }
|
||||
].map((item) => (
|
||||
<button
|
||||
key={item.value}
|
||||
type="button"
|
||||
className={`preset-chip ${preset === item.value ? 'active' : ''}`}
|
||||
onClick={() => setPreset(item.value as RangePreset)}
|
||||
>
|
||||
{item.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{preset === 'custom' && (
|
||||
<div className="custom-range-row">
|
||||
<DateRangePicker
|
||||
startDate={customStartDate}
|
||||
endDate={customEndDate}
|
||||
onStartDateChange={setCustomStartDate}
|
||||
onEndDateChange={setCustomEndDate}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="toolbar-actions">
|
||||
<div className="search-input">
|
||||
<Search size={15} />
|
||||
<input
|
||||
value={searchKeyword}
|
||||
onChange={(event) => setSearchKeyword(event.target.value)}
|
||||
placeholder="搜索联系人/群聊/内容"
|
||||
/>
|
||||
</div>
|
||||
<button type="button" className="action-btn" onClick={() => void loadData()} disabled={loading}>
|
||||
<RefreshCw size={15} className={loading ? 'spin' : ''} />
|
||||
<span>刷新</span>
|
||||
</button>
|
||||
<button type="button" className="action-btn" onClick={() => void handleGenerateAiSummary()} disabled={loading || footprintAiStatus === 'loading'}>
|
||||
{footprintAiStatus === 'loading' ? <Loader2 size={15} className="spin" /> : <Sparkles size={15} />}
|
||||
<span>{footprintAiStatus === 'loading' ? '生成中...' : 'AI 总结'}</span>
|
||||
</button>
|
||||
<button type="button" className="action-btn" onClick={() => void handleExport('csv')} disabled={exporting || loading}>
|
||||
<Download size={15} />
|
||||
<span>导出 CSV</span>
|
||||
</button>
|
||||
<button type="button" className="action-btn" onClick={() => void handleExport('json')} disabled={exporting || loading}>
|
||||
<Download size={15} />
|
||||
<span>导出 JSON</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{loading ? (
|
||||
<section className="footprint-loading" aria-live="polite">
|
||||
<div className="kpi-skeleton-grid">
|
||||
{Array.from({ length: 4 }).map((_, index) => (
|
||||
<div key={index} className="kpi-skeleton-card skeleton-shimmer" />
|
||||
))}
|
||||
</div>
|
||||
<div className="timeline-skeleton-list">
|
||||
{Array.from({ length: 7 }).map((_, index) => (
|
||||
<div key={index} className="timeline-skeleton-item skeleton-shimmer" />
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
) : error ? (
|
||||
<section className="footprint-error" role="alert">
|
||||
<h3>读取我的足迹失败</h3>
|
||||
<p>{error}</p>
|
||||
<button type="button" className="action-btn" onClick={() => void loadData()}>
|
||||
<RefreshCw size={15} />
|
||||
<span>重试</span>
|
||||
</button>
|
||||
</section>
|
||||
) : (
|
||||
<>
|
||||
<section className="kpi-grid">
|
||||
<button type="button" className="kpi-card" onClick={() => setTimelineMode('private')}>
|
||||
<span className="kpi-label">有聊天的人数</span>
|
||||
<strong>{data.summary.private_inbound_people}</strong>
|
||||
<small>回复了其中 {data.summary.private_replied_people} 人</small>
|
||||
</button>
|
||||
<button type="button" className="kpi-card" onClick={() => setTimelineMode('private')}>
|
||||
<span className="kpi-label">我有回复的人数</span>
|
||||
<strong>{data.summary.private_outbound_people}</strong>
|
||||
<small>回复率 {formatPercent(data.summary.private_reply_rate)}</small>
|
||||
</button>
|
||||
<button type="button" className="kpi-card" onClick={() => setTimelineMode('mention')}>
|
||||
<span className="kpi-label">@我次数</span>
|
||||
<strong>{data.summary.mention_count}</strong>
|
||||
<small>可点击查看原消息</small>
|
||||
</button>
|
||||
<button type="button" className="kpi-card" onClick={() => setTimelineMode('mention')}>
|
||||
<span className="kpi-label">涉及群聊</span>
|
||||
<strong>{data.summary.mention_group_count}</strong>
|
||||
<small>按群聚合 @我消息</small>
|
||||
</button>
|
||||
</section>
|
||||
|
||||
{footprintAiStatus !== 'idle' && (
|
||||
<section className={`footprint-ai-result footprint-ai-result-${footprintAiStatus}`}>
|
||||
<div className="footprint-ai-head">
|
||||
<strong>AI 足迹总结</strong>
|
||||
<span>{currentRange.label}</span>
|
||||
</div>
|
||||
<p>{footprintAiText}</p>
|
||||
</section>
|
||||
)}
|
||||
|
||||
<section
|
||||
className={`footprint-timeline timeline-time-${timelineTimeMode}`}
|
||||
key={`${timelineMode}:${currentRange.begin}:${currentRange.end}`}
|
||||
>
|
||||
<div className="timeline-head">
|
||||
<div className="timeline-head-left">
|
||||
<h2>联络时间线</h2>
|
||||
<p>最上方是时间区间开始,最下方是时间区间终点,中间按时间展示群聊 @我 与私聊分段会话节点。</p>
|
||||
</div>
|
||||
<div className="timeline-mode-row">
|
||||
<button
|
||||
type="button"
|
||||
className={`timeline-mode-chip ${timelineMode === 'all' ? 'active' : ''}`}
|
||||
onClick={() => setTimelineMode('all')}
|
||||
>
|
||||
全部 {timelineEventCount}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className={`timeline-mode-chip ${timelineMode === 'mention' ? 'active' : ''}`}
|
||||
onClick={() => setTimelineMode('mention')}
|
||||
>
|
||||
@我群聊 {mentionTimelineItems.length}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className={`timeline-mode-chip ${timelineMode === 'private' ? 'active' : ''}`}
|
||||
onClick={() => setTimelineMode('private')}
|
||||
>
|
||||
私聊 {privateTimelineItems.length}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{timelineEventCount === 0 ? (
|
||||
<div className="panel-empty-state">当前区间暂无联络事件,试试切换日期范围或清空关键词筛选。</div>
|
||||
) : (
|
||||
<div className="timeline-stream">
|
||||
{timelineItems.map((item, index) => (
|
||||
<div
|
||||
key={item.key}
|
||||
className={`timeline-item timeline-item-${item.kind}`}
|
||||
style={{ animationDelay: `${Math.min(index, 12) * 0.04}s` }}
|
||||
>
|
||||
<div className={`timeline-time timeline-time-${item.kind}`}>
|
||||
{item.kind === 'private' ? (
|
||||
<div className="timeline-time-range">
|
||||
<span className="timeline-time-main">{formatTimelineMoment(item.time, timelineTimeMode)}</span>
|
||||
{item.isRange && (
|
||||
<span className="timeline-time-end-wrap">
|
||||
<span className="timeline-time-end">{formatTimelineMoment(item.endTime, timelineTimeMode)}</span>
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
formatTimelineMoment(item.time, timelineTimeMode)
|
||||
)}
|
||||
</div>
|
||||
<div className={`timeline-dot-col timeline-dot-col-${item.kind}`}>
|
||||
{item.kind === 'private' ? (
|
||||
<div className="timeline-dot-range">
|
||||
<div className={`timeline-dot timeline-dot-private timeline-dot-private-start timeline-dot-private-${item.dotVariant}`} />
|
||||
{item.isRange && (
|
||||
<>
|
||||
<div className={`timeline-dot-range-line timeline-dot-range-line-${item.dotVariant}`} />
|
||||
<div className={`timeline-dot timeline-dot-private timeline-dot-private-end timeline-dot-private-${item.dotVariant}`} />
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<div className={`timeline-dot timeline-dot-${item.kind}${item.kind === 'boundary' ? ` timeline-dot-${item.edge}` : ''}`} />
|
||||
)}
|
||||
</div>
|
||||
<div className="timeline-content-wrap">
|
||||
{item.kind === 'boundary' && (
|
||||
<div className={`timeline-boundary timeline-boundary-${item.edge}`}>{item.label}</div>
|
||||
)}
|
||||
|
||||
{item.kind === 'mention' && (
|
||||
<div className="timeline-card timeline-card-mention">
|
||||
<div className="timeline-card-head">
|
||||
<div className="timeline-identity">
|
||||
<div className="timeline-avatar">
|
||||
{item.groupAvatarUrl ? (
|
||||
<img src={item.groupAvatarUrl} alt={item.groupName} />
|
||||
) : (
|
||||
<Users size={16} />
|
||||
)}
|
||||
</div>
|
||||
<div className="timeline-title-group">
|
||||
<div className="timeline-title">{item.groupName}</div>
|
||||
<div className="timeline-subtitle">发送人:{item.senderName}</div>
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
className="jump-btn timeline-jump-btn"
|
||||
onClick={() => handleJump(item.sessionId, item.localId, item.createTime)}
|
||||
>
|
||||
跳转
|
||||
</button>
|
||||
</div>
|
||||
<div className="timeline-message mention-message">{renderMentionContent(item.messageContent)}</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{item.kind === 'private' && (
|
||||
<div className="timeline-card timeline-card-private">
|
||||
<div className="timeline-card-head">
|
||||
<div className="timeline-identity">
|
||||
<div className="timeline-avatar timeline-avatar-private">
|
||||
{item.avatarUrl ? (
|
||||
<img src={item.avatarUrl} alt={item.displayName} />
|
||||
) : (
|
||||
<MessageCircle size={16} />
|
||||
)}
|
||||
</div>
|
||||
<div className="timeline-title-group">
|
||||
<div className="timeline-title">{item.displayName}</div>
|
||||
<div className="timeline-subtitle">{item.subtitle}</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="timeline-right-tools">
|
||||
<span className="timeline-count-badge">共 {item.totalInteractions} 条</span>
|
||||
<button
|
||||
type="button"
|
||||
className="jump-btn timeline-jump-btn"
|
||||
disabled={!item.anchorLocalId || !item.anchorCreateTime}
|
||||
onClick={() => handleJump(item.sessionId, item.anchorLocalId, item.anchorCreateTime)}
|
||||
>
|
||||
跳转
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div className="timeline-message private-message">{item.summaryText}</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
</>
|
||||
)}
|
||||
{exportModalStatus !== 'idle' && (
|
||||
<div className="footprint-export-modal-mask" role="presentation">
|
||||
<div className="footprint-export-modal" role="dialog" aria-modal="true" aria-live="polite">
|
||||
<div className={`export-modal-icon export-modal-icon-${exportModalStatus}`}>
|
||||
{exportModalStatus === 'progress' && <RefreshCw size={20} className="spin" />}
|
||||
{exportModalStatus === 'success' && <CheckCircle2 size={20} />}
|
||||
{exportModalStatus === 'error' && <AlertCircle size={20} />}
|
||||
</div>
|
||||
<h3>{exportModalTitle}</h3>
|
||||
<p>{exportModalDescription}</p>
|
||||
{exportModalPath && <code className="export-modal-path">{exportModalPath}</code>}
|
||||
{exportModalStatus !== 'progress' && (
|
||||
<div className="export-modal-actions">
|
||||
<button
|
||||
type="button"
|
||||
className="action-btn"
|
||||
onClick={() => {
|
||||
setExportModalStatus('idle')
|
||||
setExportModalTitle('')
|
||||
setExportModalDescription('')
|
||||
setExportModalPath('')
|
||||
}}
|
||||
>
|
||||
知道了
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default MyFootprintPage
|
||||
@@ -177,6 +177,66 @@
|
||||
box-shadow: var(--shadow-sm);
|
||||
}
|
||||
}
|
||||
|
||||
.tab-group {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.tab-group-trigger {
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.tab-group-arrow {
|
||||
margin-left: auto;
|
||||
color: var(--text-tertiary);
|
||||
transition: transform 0.2s ease;
|
||||
|
||||
&.expanded {
|
||||
transform: rotate(180deg);
|
||||
}
|
||||
}
|
||||
|
||||
.tab-sublist {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
padding-left: 8px;
|
||||
}
|
||||
|
||||
.tab-sublist-wrap {
|
||||
display: grid;
|
||||
grid-template-rows: 0fr;
|
||||
opacity: 0;
|
||||
transition: grid-template-rows 0.22s ease, opacity 0.18s ease;
|
||||
|
||||
&.expanded {
|
||||
grid-template-rows: 1fr;
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
&.collapsed {
|
||||
pointer-events: none;
|
||||
}
|
||||
}
|
||||
|
||||
.tab-sublist {
|
||||
min-height: 0;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.tab-sub-btn {
|
||||
padding-left: 24px;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.tab-sub-dot {
|
||||
width: 5px;
|
||||
height: 5px;
|
||||
border-radius: 999px;
|
||||
background: color-mix(in srgb, var(--text-tertiary) 70%, transparent);
|
||||
}
|
||||
}
|
||||
|
||||
.settings-body {
|
||||
@@ -199,6 +259,12 @@
|
||||
}
|
||||
}
|
||||
|
||||
.ai-prompt-textarea {
|
||||
font-family: inherit !important;
|
||||
font-size: 14px !important;
|
||||
line-height: 1.6;
|
||||
}
|
||||
|
||||
.tab-content {
|
||||
background: var(--bg-secondary);
|
||||
border: 1px solid var(--border-color);
|
||||
@@ -2283,6 +2349,24 @@
|
||||
border-radius: 10px;
|
||||
}
|
||||
|
||||
.filter-panel-action {
|
||||
flex-shrink: 0;
|
||||
border: 1px solid var(--border-color);
|
||||
border-radius: 6px;
|
||||
background: var(--bg-tertiary);
|
||||
color: var(--text-secondary);
|
||||
padding: 4px 8px;
|
||||
font-size: 12px;
|
||||
cursor: pointer;
|
||||
transition: all 0.16s ease;
|
||||
|
||||
&:hover {
|
||||
color: var(--primary);
|
||||
border-color: color-mix(in srgb, var(--primary) 42%, var(--border-color));
|
||||
background: color-mix(in srgb, var(--primary) 8%, var(--bg-tertiary));
|
||||
}
|
||||
}
|
||||
|
||||
.filter-panel-list {
|
||||
flex: 1;
|
||||
min-height: 200px;
|
||||
@@ -2346,6 +2430,16 @@
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.filter-item-type {
|
||||
flex-shrink: 0;
|
||||
padding: 2px 6px;
|
||||
border-radius: 6px;
|
||||
font-size: 11px;
|
||||
color: var(--text-secondary);
|
||||
background: var(--bg-tertiary);
|
||||
border: 1px solid var(--border-color);
|
||||
}
|
||||
|
||||
.filter-item-action {
|
||||
font-size: 18px;
|
||||
font-weight: 500;
|
||||
@@ -2355,6 +2449,36 @@
|
||||
}
|
||||
}
|
||||
|
||||
.push-filter-type-tabs {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
margin-top: 12px;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
.push-filter-type-tab {
|
||||
border: 1px solid var(--border-color);
|
||||
border-radius: 8px;
|
||||
background: var(--bg-primary);
|
||||
color: var(--text-secondary);
|
||||
padding: 6px 10px;
|
||||
font-size: 13px;
|
||||
cursor: pointer;
|
||||
transition: all 0.16s ease;
|
||||
|
||||
&:hover {
|
||||
color: var(--text-primary);
|
||||
border-color: color-mix(in srgb, var(--primary) 38%, var(--border-color));
|
||||
}
|
||||
|
||||
&.active {
|
||||
color: var(--primary);
|
||||
border-color: color-mix(in srgb, var(--primary) 54%, var(--border-color));
|
||||
background: color-mix(in srgb, var(--primary) 8%, var(--bg-primary));
|
||||
}
|
||||
}
|
||||
|
||||
.filter-panel-empty {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1127,7 +1127,7 @@ export default function SnsPage() {
|
||||
activeContactsCountTaskIdRef.current = null
|
||||
}
|
||||
finishBackgroundTask(taskId, 'completed', {
|
||||
detail: '鑱旂郴浜烘湅鍙嬪湀鏉℃暟琛ョ畻瀹屾垚',
|
||||
detail: '联系人朋友圈条数补算完成',
|
||||
progressText: `${totalTargets}/${totalTargets}`
|
||||
})
|
||||
}
|
||||
|
||||
@@ -304,6 +304,19 @@
|
||||
}
|
||||
}
|
||||
|
||||
.nav-hint {
|
||||
margin-top: 4px;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
width: fit-content;
|
||||
padding: 1px 6px;
|
||||
border-radius: 999px;
|
||||
font-size: 11px;
|
||||
font-weight: 600;
|
||||
color: #0f766e;
|
||||
background: rgba(20, 184, 166, 0.16);
|
||||
}
|
||||
|
||||
|
||||
.sidebar-footer {
|
||||
display: flex;
|
||||
@@ -362,6 +375,16 @@
|
||||
font-size: 15px;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.header-mode-tip {
|
||||
margin: 10px 0 0;
|
||||
padding: 6px 10px;
|
||||
border-radius: 10px;
|
||||
font-size: 12px;
|
||||
color: var(--text-secondary);
|
||||
background: var(--bg-tertiary);
|
||||
border: 1px dashed var(--border-color);
|
||||
}
|
||||
}
|
||||
|
||||
.step-icon-wrapper {
|
||||
@@ -556,6 +579,41 @@
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
.auto-image-key-preview {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
padding: 12px;
|
||||
border: 1px solid var(--border-color);
|
||||
border-radius: 12px;
|
||||
background: var(--bg-tertiary);
|
||||
}
|
||||
|
||||
.auto-image-key-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
|
||||
code {
|
||||
padding: 4px 8px;
|
||||
border-radius: 8px;
|
||||
background: var(--bg-primary);
|
||||
border: 1px solid var(--border-color);
|
||||
font-size: 12px;
|
||||
color: var(--text-primary);
|
||||
max-width: 70%;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
}
|
||||
|
||||
.auto-image-key-label {
|
||||
font-size: 13px;
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
.mt-4 {
|
||||
margin-top: 16px;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useState, useEffect, useRef } from 'react'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import { useLocation, useNavigate } from 'react-router-dom'
|
||||
import { useAppStore } from '../stores/appStore'
|
||||
import { dialog } from '../services/ipc'
|
||||
import * as configService from '../services/config'
|
||||
@@ -15,7 +15,6 @@ const isMac = navigator.userAgent.toLowerCase().includes('mac')
|
||||
const isLinux = navigator.userAgent.toLowerCase().includes('linux')
|
||||
const isWindows = !isMac && !isLinux
|
||||
|
||||
const dbDirName = isMac ? '2.0b4.0.9 目录' : 'xwechat_files 目录'
|
||||
const DB_PATH_CHINESE_ERROR = '路径包含中文字符,迁移至全英文目录后再试'
|
||||
const dbPathPlaceholder = isMac
|
||||
? '例如: ~/Library/Containers/com.tencent.xinWeChat/Data/Library/Application Support/com.tencent.xinWeChat/2.0b4.0.9'
|
||||
@@ -25,12 +24,14 @@ const dbPathPlaceholder = isMac
|
||||
|
||||
const steps = [
|
||||
{ id: 'intro', title: '欢迎', desc: '准备开始你的本地数据探索' },
|
||||
{ id: 'db', title: '数据库目录', desc: `定位 ${dbDirName}` },
|
||||
{ id: 'db', title: '数据库目录', desc: `定位 xwechat_files 目录` },
|
||||
{ id: 'cache', title: '缓存目录', desc: '设置本地缓存存储位置(可选)' },
|
||||
{ id: 'key', title: '解密密钥', desc: '获取密钥与自动识别账号' },
|
||||
{ id: 'image', title: '图片密钥', desc: '获取 XOR 与 AES 密钥' },
|
||||
{ id: 'security', title: '安全防护', desc: '保护你的数据' }
|
||||
]
|
||||
type SetupStepId = typeof steps[number]['id']
|
||||
type ImageKeyResolveSource = 'manual-cache' | 'prefetch-cache' | 'memory-scan'
|
||||
|
||||
interface WelcomePageProps {
|
||||
standalone?: boolean
|
||||
@@ -61,9 +62,44 @@ const isDbKeyReadyMessage = (message: string): boolean => (
|
||||
|| message.includes('已准备就绪,现在登录微信或退出登录后重新登录微信')
|
||||
)
|
||||
|
||||
const pickWxidByAnchorTime = (
|
||||
wxids: Array<{ wxid: string; modifiedTime: number }>,
|
||||
anchorTime?: number
|
||||
): string => {
|
||||
if (!Array.isArray(wxids) || wxids.length === 0) return ''
|
||||
const fallbackWxid = wxids[0]?.wxid || ''
|
||||
if (!anchorTime || !Number.isFinite(anchorTime)) return fallbackWxid
|
||||
|
||||
const valid = wxids.filter(item => Number.isFinite(item.modifiedTime) && item.modifiedTime > 0)
|
||||
if (valid.length === 0) return fallbackWxid
|
||||
|
||||
const anchor = Number(anchorTime)
|
||||
const nearWindowMs = 10 * 60 * 1000
|
||||
|
||||
const near = valid
|
||||
.filter(item => Math.abs(item.modifiedTime - anchor) <= nearWindowMs)
|
||||
.sort((a, b) => {
|
||||
const diffGap = Math.abs(a.modifiedTime - anchor) - Math.abs(b.modifiedTime - anchor)
|
||||
if (diffGap !== 0) return diffGap
|
||||
if (b.modifiedTime !== a.modifiedTime) return b.modifiedTime - a.modifiedTime
|
||||
return a.wxid.localeCompare(b.wxid)
|
||||
})
|
||||
if (near.length > 0) return near[0].wxid
|
||||
|
||||
const closest = valid.sort((a, b) => {
|
||||
const diffGap = Math.abs(a.modifiedTime - anchor) - Math.abs(b.modifiedTime - anchor)
|
||||
if (diffGap !== 0) return diffGap
|
||||
if (b.modifiedTime !== a.modifiedTime) return b.modifiedTime - a.modifiedTime
|
||||
return a.wxid.localeCompare(b.wxid)
|
||||
})
|
||||
return closest[0]?.wxid || fallbackWxid
|
||||
}
|
||||
|
||||
function WelcomePage({ standalone = false }: WelcomePageProps) {
|
||||
const navigate = useNavigate()
|
||||
const location = useLocation()
|
||||
const { isDbConnected, setDbConnected, setLoading } = useAppStore()
|
||||
const isAddAccountMode = standalone && new URLSearchParams(location.search).get('mode') === 'add-account'
|
||||
|
||||
const [stepIndex, setStepIndex] = useState(0)
|
||||
const [dbPath, setDbPath] = useState('')
|
||||
@@ -92,7 +128,11 @@ function WelcomePage({ standalone = false }: WelcomePageProps) {
|
||||
const [imageKeyStatus, setImageKeyStatus] = useState('')
|
||||
const [isManualStartPrompt, setIsManualStartPrompt] = useState(false)
|
||||
const [imageKeyPercent, setImageKeyPercent] = useState<number | null>(null)
|
||||
const [isImageKeyVerified, setIsImageKeyVerified] = useState(false)
|
||||
const [isImageStepAutoCompleted, setIsImageStepAutoCompleted] = useState(false)
|
||||
const [hasReacquiredDbKey, setHasReacquiredDbKey] = useState(!isAddAccountMode)
|
||||
const [showDbKeyConfirm, setShowDbKeyConfirm] = useState(false)
|
||||
const imagePrefetchAttemptRef = useRef<string>('')
|
||||
|
||||
// 安全相关 state
|
||||
const [enableAuth, setEnableAuth] = useState(false)
|
||||
@@ -191,7 +231,79 @@ function WelcomePage({ standalone = false }: WelcomePageProps) {
|
||||
setWxidOptions([])
|
||||
setWxid('')
|
||||
setShowWxidSelect(false)
|
||||
}, [dbPath])
|
||||
setIsImageKeyVerified(false)
|
||||
setIsImageStepAutoCompleted(false)
|
||||
if (isAddAccountMode) {
|
||||
setHasReacquiredDbKey(false)
|
||||
setDecryptKey('')
|
||||
}
|
||||
imagePrefetchAttemptRef.current = ''
|
||||
}, [dbPath, isAddAccountMode])
|
||||
|
||||
useEffect(() => {
|
||||
if (!isAddAccountMode) return
|
||||
let cancelled = false
|
||||
|
||||
const hydrateAddAccountMode = async () => {
|
||||
const keyStepIndex = steps.findIndex(step => step.id === 'key')
|
||||
if (keyStepIndex >= 0) {
|
||||
setStepIndex(keyStepIndex)
|
||||
}
|
||||
|
||||
try {
|
||||
const [
|
||||
savedDbPath,
|
||||
savedCachePath,
|
||||
savedWxid,
|
||||
savedImageXorKey,
|
||||
savedImageAesKey
|
||||
] = await Promise.all([
|
||||
configService.getDbPath(),
|
||||
configService.getCachePath(),
|
||||
configService.getMyWxid(),
|
||||
configService.getImageXorKey(),
|
||||
configService.getImageAesKey()
|
||||
])
|
||||
if (cancelled) return
|
||||
|
||||
setDbPath(savedDbPath || '')
|
||||
setCachePath(savedCachePath || '')
|
||||
setDecryptKey('')
|
||||
setHasReacquiredDbKey(false)
|
||||
if (typeof savedImageXorKey === 'number' && Number.isFinite(savedImageXorKey)) {
|
||||
setImageXorKey(`0x${savedImageXorKey.toString(16).toUpperCase().padStart(2, '0')}`)
|
||||
}
|
||||
setImageAesKey(savedImageAesKey || '')
|
||||
|
||||
if (savedDbPath) {
|
||||
const scannedWxids = await window.electronAPI.dbPath.scanWxids(savedDbPath)
|
||||
if (cancelled) return
|
||||
setWxidOptions(scannedWxids)
|
||||
|
||||
const preferredWxid = String(savedWxid || '').trim()
|
||||
const matched = scannedWxids.find(item => item.wxid === preferredWxid)
|
||||
if (matched) {
|
||||
setWxid(matched.wxid)
|
||||
} else if (preferredWxid) {
|
||||
setWxid(preferredWxid)
|
||||
} else if (scannedWxids.length > 0) {
|
||||
setWxid(scannedWxids[0].wxid)
|
||||
}
|
||||
} else if (savedWxid) {
|
||||
setWxid(savedWxid)
|
||||
}
|
||||
} catch (e) {
|
||||
if (!cancelled) {
|
||||
setError(`加载当前账号配置失败: ${e}`)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void hydrateAddAccountMode()
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [isAddAccountMode])
|
||||
|
||||
useEffect(() => {
|
||||
const handleClickOutside = (event: MouseEvent) => {
|
||||
@@ -206,10 +318,30 @@ function WelcomePage({ standalone = false }: WelcomePageProps) {
|
||||
return () => document.removeEventListener('mousedown', handleClickOutside)
|
||||
}, [showWxidSelect])
|
||||
|
||||
const currentStep = steps[stepIndex]
|
||||
const imageStepIndex = steps.findIndex(step => step.id === 'image')
|
||||
const securityStepIndex = steps.findIndex(step => step.id === 'security')
|
||||
const currentStep = steps[stepIndex] ?? steps[0]
|
||||
const imagePreCompletedAhead = isImageStepAutoCompleted && imageStepIndex >= 0 && stepIndex < imageStepIndex
|
||||
const rootClassName = `welcome-page${isClosing ? ' is-closing' : ''}${standalone ? ' is-standalone' : ''}`
|
||||
const showWindowControls = standalone
|
||||
|
||||
const isStepCompleted = (index: number, stepId: SetupStepId): boolean => {
|
||||
if (index < stepIndex) return true
|
||||
if (stepId === 'image' && isImageStepAutoCompleted) return true
|
||||
if (isAddAccountMode && stepId !== 'key') return true
|
||||
return false
|
||||
}
|
||||
|
||||
const resolveStepDesc = (step: { id: SetupStepId; desc: string }): string => {
|
||||
if (step.id === 'image' && isImageStepAutoCompleted) {
|
||||
return '缓存校验成功,已自动完成'
|
||||
}
|
||||
if (isAddAccountMode && step.id !== 'key') {
|
||||
return '已沿用当前配置'
|
||||
}
|
||||
return step.desc
|
||||
}
|
||||
|
||||
const handleMinimize = () => {
|
||||
window.electronAPI.window.minimize()
|
||||
}
|
||||
@@ -302,7 +434,7 @@ function WelcomePage({ standalone = false }: WelcomePageProps) {
|
||||
}
|
||||
}
|
||||
|
||||
const handleScanWxid = async (silent = false) => {
|
||||
const handleScanWxid = async (silent = false, anchorTime?: number) => {
|
||||
if (!dbPath) {
|
||||
if (!silent) setError('请先选择数据库目录')
|
||||
return
|
||||
@@ -314,8 +446,10 @@ function WelcomePage({ standalone = false }: WelcomePageProps) {
|
||||
const wxids = await window.electronAPI.dbPath.scanWxids(dbPath)
|
||||
setWxidOptions(wxids)
|
||||
if (wxids.length > 0) {
|
||||
// scanWxids 已经按时间排过序了,直接取第一个
|
||||
setWxid(wxids[0].wxid)
|
||||
// 密钥成功后使用成功时刻作为锚点,自动选择最接近该时刻的活跃账号;
|
||||
// 其余场景保持“时间最新”优先。
|
||||
const selectedWxid = pickWxidByAnchorTime(wxids, anchorTime)
|
||||
setWxid(selectedWxid || wxids[0].wxid)
|
||||
if (!silent) setError('')
|
||||
} else {
|
||||
if (!silent) setError('未检测到账号目录,请检查路径')
|
||||
@@ -364,11 +498,22 @@ function WelcomePage({ standalone = false }: WelcomePageProps) {
|
||||
const result = await window.electronAPI.key.autoGetDbKey()
|
||||
if (result.success && result.key) {
|
||||
setDecryptKey(result.key)
|
||||
setHasReacquiredDbKey(true)
|
||||
setDbKeyStatus('密钥获取成功')
|
||||
setError('')
|
||||
await handleScanWxid(true)
|
||||
const keySuccessAt = Date.now()
|
||||
await handleScanWxid(true, keySuccessAt)
|
||||
} else {
|
||||
if (result.error?.includes('未找到微信安装路径') || result.error?.includes('启动微信失败')) {
|
||||
if (isAddAccountMode) {
|
||||
setHasReacquiredDbKey(false)
|
||||
}
|
||||
if (
|
||||
result.error?.includes('未找到微信安装路径') ||
|
||||
result.error?.includes('启动微信失败') ||
|
||||
result.error?.includes('未能自动启动微信') ||
|
||||
result.error?.includes('未找到微信进程') ||
|
||||
result.error?.includes('微信进程未运行')
|
||||
) {
|
||||
setIsManualStartPrompt(true)
|
||||
setDbKeyStatus('需要手动启动微信')
|
||||
} else {
|
||||
@@ -390,25 +535,45 @@ function WelcomePage({ standalone = false }: WelcomePageProps) {
|
||||
handleAutoGetDbKey()
|
||||
}
|
||||
|
||||
const handleAutoGetImageKey = async () => {
|
||||
const handleAutoGetImageKey = async (
|
||||
source: ImageKeyResolveSource = 'manual-cache',
|
||||
options?: { silentError?: boolean }
|
||||
) => {
|
||||
if (isFetchingImageKey) return
|
||||
if (!dbPath) { setError('请先选择数据库目录'); return }
|
||||
setIsFetchingImageKey(true)
|
||||
setError('')
|
||||
if (!options?.silentError) {
|
||||
setError('')
|
||||
}
|
||||
setImageKeyPercent(0)
|
||||
setImageKeyStatus('正在准备获取图片密钥...')
|
||||
setImageKeyStatus(source === 'prefetch-cache' ? '正在预计算图片密钥...' : '正在准备获取图片密钥...')
|
||||
try {
|
||||
const accountPath = wxid ? `${dbPath}/${wxid}` : dbPath
|
||||
const result = await window.electronAPI.key.autoGetImageKey(accountPath, wxid)
|
||||
if (result.success && result.aesKey) {
|
||||
if (typeof result.xorKey === 'number') setImageXorKey(`0x${result.xorKey.toString(16).toUpperCase().padStart(2, '0')}`)
|
||||
setImageAesKey(result.aesKey)
|
||||
setImageKeyStatus('已获取图片密钥')
|
||||
const verified = result.verified === true
|
||||
setIsImageKeyVerified(verified)
|
||||
setIsImageStepAutoCompleted(verified)
|
||||
if (verified) {
|
||||
setImageKeyStatus(source === 'prefetch-cache' ? '图片密钥已预先自动完成(缓存校验通过)' : '图片密钥获取成功(缓存校验通过)')
|
||||
} else {
|
||||
setImageKeyStatus('已自动计算图片密钥(未完成校验)')
|
||||
}
|
||||
} else {
|
||||
setError(result.error || '自动获取图片密钥失败')
|
||||
setIsImageKeyVerified(false)
|
||||
setIsImageStepAutoCompleted(false)
|
||||
if (!options?.silentError) {
|
||||
setError(result.error || '自动获取图片密钥失败')
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
setError(`自动获取图片密钥失败: ${e}`)
|
||||
setIsImageKeyVerified(false)
|
||||
setIsImageStepAutoCompleted(false)
|
||||
if (!options?.silentError) {
|
||||
setError(`自动获取图片密钥失败: ${e}`)
|
||||
}
|
||||
} finally {
|
||||
setIsFetchingImageKey(false)
|
||||
}
|
||||
@@ -427,6 +592,8 @@ function WelcomePage({ standalone = false }: WelcomePageProps) {
|
||||
if (result.success && result.aesKey) {
|
||||
if (typeof result.xorKey === 'number') setImageXorKey(`0x${result.xorKey.toString(16).toUpperCase().padStart(2, '0')}`)
|
||||
setImageAesKey(result.aesKey)
|
||||
setIsImageKeyVerified(false)
|
||||
setIsImageStepAutoCompleted(false)
|
||||
setImageKeyStatus('内存扫描成功,已获取图片密钥')
|
||||
} else {
|
||||
setError(result.error || '内存扫描获取图片密钥失败')
|
||||
@@ -438,7 +605,61 @@ function WelcomePage({ standalone = false }: WelcomePageProps) {
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (!dbPath || !wxid || decryptKey.length !== 64) return
|
||||
const attemptKey = `${dbPath}::${wxid}::${decryptKey}`
|
||||
if (imagePrefetchAttemptRef.current === attemptKey) return
|
||||
imagePrefetchAttemptRef.current = attemptKey
|
||||
void handleAutoGetImageKey('prefetch-cache', { silentError: true })
|
||||
}, [dbPath, wxid, decryptKey])
|
||||
|
||||
const jumpToStep = (stepId: SetupStepId) => {
|
||||
const targetIndex = steps.findIndex(step => step.id === stepId)
|
||||
if (targetIndex >= 0) setStepIndex(targetIndex)
|
||||
}
|
||||
|
||||
const validateDbStepBeforeNext = async (): Promise<string | null> => {
|
||||
if (!dbPath) return '数据库目录步骤未完成:请先选择数据库目录'
|
||||
if (dbPathValidationError) return `数据库目录步骤配置有误:${dbPathValidationError}`
|
||||
try {
|
||||
const wxids = await window.electronAPI.dbPath.scanWxids(dbPath)
|
||||
if (!Array.isArray(wxids) || wxids.length === 0) {
|
||||
return '数据库目录步骤配置有误:当前目录下未找到可用账号数据(缺少 db_storage),请重新选择微信数据目录'
|
||||
}
|
||||
} catch (e) {
|
||||
return `数据库目录步骤配置有误:目录读取失败,请确认该路径可访问(${String(e)})`
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
const findConfigIssueBeforeConnect = async (): Promise<{ stepId: SetupStepId; message: string } | null> => {
|
||||
const dbIssue = await validateDbStepBeforeNext()
|
||||
if (dbIssue) return { stepId: 'db', message: dbIssue }
|
||||
|
||||
let scannedWxids: Array<{ wxid: string }> = []
|
||||
try {
|
||||
scannedWxids = await window.electronAPI.dbPath.scanWxids(dbPath)
|
||||
} catch {
|
||||
scannedWxids = []
|
||||
}
|
||||
|
||||
if (!wxid) {
|
||||
return { stepId: 'key', message: '解密密钥步骤未完成:请先选择微信账号 (wxid)' }
|
||||
}
|
||||
if (!scannedWxids.some(item => item.wxid === wxid)) {
|
||||
return { stepId: 'key', message: `解密密钥步骤配置有误:微信账号「${wxid}」不在当前数据库目录中,请重新选择账号` }
|
||||
}
|
||||
if (!decryptKey || decryptKey.length !== 64) {
|
||||
return { stepId: 'key', message: '解密密钥步骤未完成:请填写 64 位解密密钥' }
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
const canGoNext = () => {
|
||||
if (isAddAccountMode) {
|
||||
if (currentStep.id === 'key') return hasReacquiredDbKey && decryptKey.length === 64 && Boolean(wxid)
|
||||
return true
|
||||
}
|
||||
if (currentStep.id === 'intro') return true
|
||||
if (currentStep.id === 'db') return Boolean(dbPath) && !dbPathValidationError
|
||||
if (currentStep.id === 'cache') return true
|
||||
@@ -453,7 +674,20 @@ function WelcomePage({ standalone = false }: WelcomePageProps) {
|
||||
return false
|
||||
}
|
||||
|
||||
const handleNext = () => {
|
||||
const handleNext = async () => {
|
||||
if (isAddAccountMode) {
|
||||
await handleConnect()
|
||||
return
|
||||
}
|
||||
|
||||
if (currentStep.id === 'db') {
|
||||
const dbStepIssue = await validateDbStepBeforeNext()
|
||||
if (dbStepIssue) {
|
||||
setError(dbStepIssue)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
if (!canGoNext()) {
|
||||
if (currentStep.id === 'db' && !dbPath) setError('请先选择数据库目录')
|
||||
else if (currentStep.id === 'db' && dbPathValidationError) setError(dbPathValidationError)
|
||||
@@ -464,18 +698,31 @@ function WelcomePage({ standalone = false }: WelcomePageProps) {
|
||||
return
|
||||
}
|
||||
setError('')
|
||||
if (currentStep.id === 'key' && isImageStepAutoCompleted && securityStepIndex >= 0) {
|
||||
setStepIndex(securityStepIndex)
|
||||
return
|
||||
}
|
||||
setStepIndex((prev) => Math.min(prev + 1, steps.length - 1))
|
||||
}
|
||||
|
||||
const handleBack = () => {
|
||||
if (isAddAccountMode) return
|
||||
setError('')
|
||||
setStepIndex((prev) => Math.max(prev - 1, 0))
|
||||
}
|
||||
|
||||
const handleConnect = async () => {
|
||||
if (!dbPath) { setError('请先选择数据库目录'); return }
|
||||
if (!wxid) { setError('请填写微信ID'); return }
|
||||
if (!decryptKey || decryptKey.length !== 64) { setError('请填写 64 位解密密钥'); return }
|
||||
if (isAddAccountMode && !hasReacquiredDbKey) {
|
||||
setError('请先在当前流程中自动获取一次数据库密钥')
|
||||
return
|
||||
}
|
||||
|
||||
const configIssue = await findConfigIssueBeforeConnect()
|
||||
if (configIssue) {
|
||||
setError(configIssue.message)
|
||||
jumpToStep(configIssue.stepId)
|
||||
return
|
||||
}
|
||||
|
||||
setIsConnecting(true)
|
||||
setError('')
|
||||
@@ -484,7 +731,19 @@ function WelcomePage({ standalone = false }: WelcomePageProps) {
|
||||
try {
|
||||
const result = await window.electronAPI.wcdb.testConnection(dbPath, decryptKey, wxid)
|
||||
if (!result.success) {
|
||||
setError(result.error || 'WCDB 连接失败')
|
||||
const errorMessage = result.error || 'WCDB 连接失败'
|
||||
if (errorMessage.includes('-3001')) {
|
||||
const fallbackIssue = await findConfigIssueBeforeConnect()
|
||||
if (fallbackIssue) {
|
||||
setError(fallbackIssue.message)
|
||||
jumpToStep(fallbackIssue.stepId)
|
||||
} else {
|
||||
setError(`数据库目录步骤配置有误:${errorMessage}`)
|
||||
jumpToStep('db')
|
||||
}
|
||||
} else {
|
||||
setError(errorMessage)
|
||||
}
|
||||
setLoading(false)
|
||||
return
|
||||
}
|
||||
@@ -637,13 +896,16 @@ function WelcomePage({ standalone = false }: WelcomePageProps) {
|
||||
|
||||
<div className="sidebar-nav">
|
||||
{steps.map((step, index) => (
|
||||
<div key={step.id} className={`nav-item ${index === stepIndex ? 'active' : ''} ${index < stepIndex ? 'completed' : ''}`}>
|
||||
<div key={step.id} className={`nav-item ${index === stepIndex ? 'active' : ''} ${isStepCompleted(index, step.id) ? 'completed' : ''}`}>
|
||||
<div className="nav-indicator">
|
||||
{index < stepIndex ? <CheckCircle2 size={14} /> : <div className="dot" />}
|
||||
{isStepCompleted(index, step.id) ? <CheckCircle2 size={14} /> : <div className="dot" />}
|
||||
</div>
|
||||
<div className="nav-info">
|
||||
<div className="nav-title">{step.title}</div>
|
||||
<div className="nav-desc">{step.desc}</div>
|
||||
<div className="nav-desc">{resolveStepDesc(step)}</div>
|
||||
{step.id === 'image' && imagePreCompletedAhead && (
|
||||
<div className="nav-hint">已预先自动完成</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
@@ -660,6 +922,9 @@ function WelcomePage({ standalone = false }: WelcomePageProps) {
|
||||
<div>
|
||||
<h2>{currentStep.title}</h2>
|
||||
<p className="header-desc">{currentStep.desc}</p>
|
||||
{isAddAccountMode && (
|
||||
<p className="header-mode-tip">添加账号模式:其他步骤已沿用当前配置,只需重新获取数据库密钥。</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -779,9 +1044,9 @@ function WelcomePage({ standalone = false }: WelcomePageProps) {
|
||||
<div className="key-actions">
|
||||
{isManualStartPrompt ? (
|
||||
<div className="manual-prompt">
|
||||
<p>未能自动启动微信,请手动启动并登录</p>
|
||||
<p>未能自动启动微信,请手动启动微信,看到登录窗口后点击下方确认</p>
|
||||
<button className="btn btn-primary" onClick={handleManualConfirm}>
|
||||
我已登录,继续
|
||||
我已看到登录窗口,继续
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
@@ -792,6 +1057,9 @@ function WelcomePage({ standalone = false }: WelcomePageProps) {
|
||||
</div>
|
||||
|
||||
{dbKeyStatus && <div className={`status-message ${isDbKeyReadyMessage(dbKeyStatus) ? 'is-success' : ''}`}>{dbKeyStatus}</div>}
|
||||
{isAddAccountMode && !hasReacquiredDbKey && (
|
||||
<div className="field-hint">添加账号模式下需先自动获取一次数据库密钥,才能完成并返回主窗口。</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -865,19 +1133,19 @@ function WelcomePage({ standalone = false }: WelcomePageProps) {
|
||||
|
||||
{currentStep.id === 'image' && (
|
||||
<div className="form-group">
|
||||
<div className="grid-2">
|
||||
<div>
|
||||
<label className="field-label">图片 XOR 密钥</label>
|
||||
<input type="text" className="field-input" placeholder="0x..." value={imageXorKey} onChange={(e) => setImageXorKey(e.target.value)} />
|
||||
<div className="auto-image-key-preview">
|
||||
<div className="auto-image-key-row">
|
||||
<span className="auto-image-key-label">图片 XOR 密钥</span>
|
||||
<code>{imageXorKey || '等待自动计算'}</code>
|
||||
</div>
|
||||
<div>
|
||||
<label className="field-label">图片 AES 密钥</label>
|
||||
<input type="text" className="field-input" placeholder="16位密钥" value={imageAesKey} onChange={(e) => setImageAesKey(e.target.value)} />
|
||||
<div className="auto-image-key-row">
|
||||
<span className="auto-image-key-label">图片 AES 密钥</span>
|
||||
<code>{imageAesKey || '等待自动计算'}</code>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div style={{ display: 'flex', gap: '8px', marginTop: '16px' }}>
|
||||
<button className="btn btn-primary btn-block" onClick={handleAutoGetImageKey} disabled={isFetchingImageKey} title="从本地缓存快速计算">
|
||||
<button className="btn btn-primary btn-block" onClick={() => handleAutoGetImageKey('manual-cache')} disabled={isFetchingImageKey} title="从本地缓存快速计算">
|
||||
{isFetchingImageKey ? '获取中...' : '缓存计算(推荐)'}
|
||||
</button>
|
||||
<button className="btn btn-secondary btn-block" onClick={handleScanImageKeyFromMemory} disabled={isFetchingImageKey} title="扫描微信进程内存">
|
||||
@@ -889,13 +1157,23 @@ function WelcomePage({ standalone = false }: WelcomePageProps) {
|
||||
<div className="brute-force-progress">
|
||||
<div className="status-header">
|
||||
<span className="status-text">{imageKeyStatus || '正在启动...'}</span>
|
||||
{typeof imageKeyPercent === 'number' && Number.isFinite(imageKeyPercent) && (
|
||||
<span className="status-text">{Math.max(0, Math.min(100, imageKeyPercent)).toFixed(1)}%</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
imageKeyStatus && <div className="status-message" style={{ marginTop: '12px' }}>{imageKeyStatus}</div>
|
||||
)}
|
||||
|
||||
<div className="field-hint" style={{ marginTop: '8px' }}>优先推荐缓存计算方案。若图片无法解密,可使用内存扫描(需微信运行并打开 2-3 张图片大图)</div>
|
||||
<div className="field-hint" style={{ marginTop: '8px' }}>
|
||||
图片密钥已改为自动计算。仅当“缓存计算 + 本地校验通过”时会自动跳过本步骤;若失败可使用内存扫描兜底。
|
||||
</div>
|
||||
{isImageKeyVerified && (
|
||||
<div className="status-message is-success" style={{ marginTop: '8px' }}>
|
||||
当前密钥已通过缓存校验,可安全自动跳过图片密钥步骤。
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
@@ -910,11 +1188,15 @@ function WelcomePage({ standalone = false }: WelcomePageProps) {
|
||||
)}
|
||||
|
||||
<div className="content-actions">
|
||||
<button className="btn btn-ghost" onClick={handleBack} disabled={stepIndex === 0}>
|
||||
<button className="btn btn-ghost" onClick={handleBack} disabled={stepIndex === 0 || isAddAccountMode}>
|
||||
<ArrowLeft size={16} /> 上一步
|
||||
</button>
|
||||
|
||||
{stepIndex < steps.length - 1 ? (
|
||||
{isAddAccountMode ? (
|
||||
<button className="btn btn-primary" onClick={handleConnect} disabled={isConnecting || !canGoNext()}>
|
||||
{isConnecting ? '连接中...' : '完成并返回'} <ArrowRight size={16} />
|
||||
</button>
|
||||
) : stepIndex < steps.length - 1 ? (
|
||||
<button className="btn btn-primary" onClick={handleNext} disabled={!canGoNext()}>
|
||||
下一步 <ArrowRight size={16} />
|
||||
</button>
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
// 配置服务 - 封装 Electron Store
|
||||
import { config } from './ipc'
|
||||
import type { ExportDefaultDateRangeConfig } from '../utils/exportDateRange'
|
||||
import type { ExportAutomationTask } from '../types/exportAutomation'
|
||||
|
||||
// 配置键名
|
||||
export const CONFIG_KEYS = {
|
||||
@@ -30,6 +31,7 @@ export const CONFIG_KEYS = {
|
||||
EXPORT_DEFAULT_FORMAT: 'exportDefaultFormat',
|
||||
EXPORT_DEFAULT_AVATARS: 'exportDefaultAvatars',
|
||||
EXPORT_DEFAULT_DATE_RANGE: 'exportDefaultDateRange',
|
||||
EXPORT_DEFAULT_FILE_NAMING_MODE: 'exportDefaultFileNamingMode',
|
||||
EXPORT_DEFAULT_MEDIA: 'exportDefaultMedia',
|
||||
EXPORT_DEFAULT_VOICE_AS_TEXT: 'exportDefaultVoiceAsText',
|
||||
EXPORT_DEFAULT_EXCEL_COMPACT_COLUMNS: 'exportDefaultExcelCompactColumns',
|
||||
@@ -47,6 +49,7 @@ export const CONFIG_KEYS = {
|
||||
EXPORT_SNS_STATS_CACHE_MAP: 'exportSnsStatsCacheMap',
|
||||
EXPORT_SNS_USER_POST_COUNTS_CACHE_MAP: 'exportSnsUserPostCountsCacheMap',
|
||||
EXPORT_SESSION_MUTUAL_FRIENDS_CACHE_MAP: 'exportSessionMutualFriendsCacheMap',
|
||||
EXPORT_AUTOMATION_TASK_MAP: 'exportAutomationTaskMap',
|
||||
SNS_PAGE_CACHE_MAP: 'snsPageCacheMap',
|
||||
CONTACTS_LOAD_TIMEOUT_MS: 'contactsLoadTimeoutMs',
|
||||
CONTACTS_LIST_CACHE_MAP: 'contactsListCacheMap',
|
||||
@@ -71,6 +74,8 @@ export const CONFIG_KEYS = {
|
||||
HTTP_API_PORT: 'httpApiPort',
|
||||
HTTP_API_HOST: 'httpApiHost',
|
||||
MESSAGE_PUSH_ENABLED: 'messagePushEnabled',
|
||||
MESSAGE_PUSH_FILTER_MODE: 'messagePushFilterMode',
|
||||
MESSAGE_PUSH_FILTER_LIST: 'messagePushFilterList',
|
||||
WINDOW_CLOSE_BEHAVIOR: 'windowCloseBehavior',
|
||||
QUOTE_LAYOUT: 'quoteLayout',
|
||||
|
||||
@@ -82,6 +87,9 @@ export const CONFIG_KEYS = {
|
||||
ANALYTICS_DENY_COUNT: 'analyticsDenyCount',
|
||||
|
||||
// AI 见解
|
||||
AI_MODEL_API_BASE_URL: 'aiModelApiBaseUrl',
|
||||
AI_MODEL_API_KEY: 'aiModelApiKey',
|
||||
AI_MODEL_API_MODEL: 'aiModelApiModel',
|
||||
AI_INSIGHT_ENABLED: 'aiInsightEnabled',
|
||||
AI_INSIGHT_API_BASE_URL: 'aiInsightApiBaseUrl',
|
||||
AI_INSIGHT_API_KEY: 'aiInsightApiKey',
|
||||
@@ -96,7 +104,12 @@ export const CONFIG_KEYS = {
|
||||
AI_INSIGHT_SYSTEM_PROMPT: 'aiInsightSystemPrompt',
|
||||
AI_INSIGHT_TELEGRAM_ENABLED: 'aiInsightTelegramEnabled',
|
||||
AI_INSIGHT_TELEGRAM_TOKEN: 'aiInsightTelegramToken',
|
||||
AI_INSIGHT_TELEGRAM_CHAT_IDS: 'aiInsightTelegramChatIds'
|
||||
AI_INSIGHT_TELEGRAM_CHAT_IDS: 'aiInsightTelegramChatIds',
|
||||
|
||||
// AI 足迹
|
||||
AI_FOOTPRINT_ENABLED: 'aiFootprintEnabled',
|
||||
AI_FOOTPRINT_SYSTEM_PROMPT: 'aiFootprintSystemPrompt',
|
||||
AI_INSIGHT_DEBUG_LOG_ENABLED: 'aiInsightDebugLogEnabled'
|
||||
} as const
|
||||
|
||||
export interface WxidConfig {
|
||||
@@ -114,6 +127,8 @@ export interface ExportDefaultMediaConfig {
|
||||
files: boolean
|
||||
}
|
||||
|
||||
export type ExportFileNamingMode = 'classic' | 'date-range'
|
||||
|
||||
export type WindowCloseBehavior = 'ask' | 'tray' | 'quit'
|
||||
export type QuoteLayout = 'quote-top' | 'quote-bottom'
|
||||
export type UpdateChannel = 'stable' | 'preview' | 'dev'
|
||||
@@ -178,6 +193,10 @@ export async function getWxidConfigs(): Promise<Record<string, WxidConfig>> {
|
||||
return {}
|
||||
}
|
||||
|
||||
export async function setWxidConfigs(configs: Record<string, WxidConfig>): Promise<void> {
|
||||
await config.set(CONFIG_KEYS.WXID_CONFIGS, configs || {})
|
||||
}
|
||||
|
||||
export async function getWxidConfig(wxid: string): Promise<WxidConfig | null> {
|
||||
if (!wxid) return null
|
||||
const configs = await getWxidConfigs()
|
||||
@@ -434,6 +453,18 @@ export async function setExportDefaultDateRange(range: ExportDefaultDateRangeCon
|
||||
await config.set(CONFIG_KEYS.EXPORT_DEFAULT_DATE_RANGE, range)
|
||||
}
|
||||
|
||||
// 获取导出默认文件命名方式
|
||||
export async function getExportDefaultFileNamingMode(): Promise<ExportFileNamingMode | null> {
|
||||
const value = await config.get(CONFIG_KEYS.EXPORT_DEFAULT_FILE_NAMING_MODE)
|
||||
if (value === 'classic' || value === 'date-range') return value
|
||||
return null
|
||||
}
|
||||
|
||||
// 设置导出默认文件命名方式
|
||||
export async function setExportDefaultFileNamingMode(mode: ExportFileNamingMode): Promise<void> {
|
||||
await config.set(CONFIG_KEYS.EXPORT_DEFAULT_FILE_NAMING_MODE, mode)
|
||||
}
|
||||
|
||||
// 获取导出默认媒体设置
|
||||
export async function getExportDefaultMedia(): Promise<ExportDefaultMediaConfig | null> {
|
||||
const value = await config.get(CONFIG_KEYS.EXPORT_DEFAULT_MEDIA)
|
||||
@@ -505,7 +536,7 @@ export async function setExportDefaultTxtColumns(columns: string[]): Promise<voi
|
||||
await config.set(CONFIG_KEYS.EXPORT_DEFAULT_TXT_COLUMNS, columns)
|
||||
}
|
||||
|
||||
// 获取导出默认并发<EFBFBD><EFBFBD>
|
||||
// 获取导出默认并发数
|
||||
export async function getExportDefaultConcurrency(): Promise<number | null> {
|
||||
const value = await config.get(CONFIG_KEYS.EXPORT_DEFAULT_CONCURRENCY)
|
||||
if (typeof value === 'number' && Number.isFinite(value)) return value
|
||||
@@ -636,6 +667,183 @@ export async function setExportLastSnsPostCount(count: number): Promise<void> {
|
||||
await config.set(CONFIG_KEYS.EXPORT_LAST_SNS_POST_COUNT, normalized)
|
||||
}
|
||||
|
||||
export interface ExportAutomationTaskMapItem {
|
||||
updatedAt: number
|
||||
tasks: ExportAutomationTask[]
|
||||
}
|
||||
|
||||
const normalizeAutomationNumeric = (value: unknown, fallback: number): number => {
|
||||
const numeric = Number(value)
|
||||
if (!Number.isFinite(numeric)) return fallback
|
||||
return Math.floor(numeric)
|
||||
}
|
||||
|
||||
const normalizeAutomationTask = (raw: unknown): ExportAutomationTask | null => {
|
||||
if (!raw || typeof raw !== 'object') return null
|
||||
const source = raw as Record<string, unknown>
|
||||
|
||||
const id = String(source.id || '').trim()
|
||||
const name = String(source.name || '').trim()
|
||||
if (!id || !name) return null
|
||||
|
||||
const sessionIds = Array.isArray(source.sessionIds)
|
||||
? Array.from(new Set(source.sessionIds.map((item) => String(item || '').trim()).filter(Boolean)))
|
||||
: []
|
||||
const sessionNames = Array.isArray(source.sessionNames)
|
||||
? source.sessionNames.map((item) => String(item || '').trim()).filter(Boolean)
|
||||
: []
|
||||
if (sessionIds.length === 0) return null
|
||||
|
||||
const scheduleRaw = source.schedule
|
||||
if (!scheduleRaw || typeof scheduleRaw !== 'object') return null
|
||||
const scheduleObj = scheduleRaw as Record<string, unknown>
|
||||
const scheduleType = String(scheduleObj.type || '').trim() as ExportAutomationTask['schedule']['type']
|
||||
let schedule: ExportAutomationTask['schedule'] | null = null
|
||||
if (scheduleType === 'interval') {
|
||||
const rawDays = Math.max(0, normalizeAutomationNumeric(scheduleObj.intervalDays, 0))
|
||||
const rawHours = Math.max(0, normalizeAutomationNumeric(scheduleObj.intervalHours, 0))
|
||||
const totalHours = (rawDays * 24) + rawHours
|
||||
if (totalHours <= 0) return null
|
||||
const intervalDays = Math.floor(totalHours / 24)
|
||||
const intervalHours = totalHours % 24
|
||||
schedule = { type: 'interval', intervalDays, intervalHours }
|
||||
}
|
||||
if (!schedule) return null
|
||||
|
||||
const conditionRaw = source.condition
|
||||
if (!conditionRaw || typeof conditionRaw !== 'object') return null
|
||||
const conditionType = String((conditionRaw as Record<string, unknown>).type || '').trim()
|
||||
if (conditionType !== 'new-message-since-last-success') return null
|
||||
|
||||
const templateRaw = source.template
|
||||
if (!templateRaw || typeof templateRaw !== 'object') return null
|
||||
const template = templateRaw as Record<string, unknown>
|
||||
const scope = String(template.scope || '').trim() as ExportAutomationTask['template']['scope']
|
||||
if (scope !== 'single' && scope !== 'multi' && scope !== 'content') return null
|
||||
const optionTemplate = template.optionTemplate
|
||||
if (!optionTemplate || typeof optionTemplate !== 'object') return null
|
||||
const dateRangeConfig = template.dateRangeConfig
|
||||
const outputDirRaw = String(source.outputDir || '').trim()
|
||||
const runStateRaw = source.runState && typeof source.runState === 'object'
|
||||
? (source.runState as Record<string, unknown>)
|
||||
: null
|
||||
const stopConditionRaw = source.stopCondition && typeof source.stopCondition === 'object'
|
||||
? (source.stopCondition as Record<string, unknown>)
|
||||
: null
|
||||
const rawContentType = String(template.contentType || '').trim()
|
||||
const contentType = (
|
||||
rawContentType === 'text' ||
|
||||
rawContentType === 'voice' ||
|
||||
rawContentType === 'image' ||
|
||||
rawContentType === 'video' ||
|
||||
rawContentType === 'emoji' ||
|
||||
rawContentType === 'file'
|
||||
)
|
||||
? rawContentType
|
||||
: undefined
|
||||
const rawRunStatus = runStateRaw ? String(runStateRaw.lastRunStatus || '').trim() : ''
|
||||
const lastRunStatus = (
|
||||
rawRunStatus === 'idle' ||
|
||||
rawRunStatus === 'queued' ||
|
||||
rawRunStatus === 'running' ||
|
||||
rawRunStatus === 'success' ||
|
||||
rawRunStatus === 'error' ||
|
||||
rawRunStatus === 'skipped'
|
||||
)
|
||||
? rawRunStatus
|
||||
: undefined
|
||||
const endAt = stopConditionRaw ? Math.max(0, normalizeAutomationNumeric(stopConditionRaw.endAt, 0)) : 0
|
||||
const maxRuns = stopConditionRaw ? Math.max(0, normalizeAutomationNumeric(stopConditionRaw.maxRuns, 0)) : 0
|
||||
|
||||
return {
|
||||
id,
|
||||
name,
|
||||
enabled: source.enabled !== false,
|
||||
sessionIds,
|
||||
sessionNames,
|
||||
outputDir: outputDirRaw || undefined,
|
||||
schedule,
|
||||
condition: { type: 'new-message-since-last-success' },
|
||||
stopCondition: (endAt > 0 || maxRuns > 0)
|
||||
? {
|
||||
endAt: endAt > 0 ? endAt : undefined,
|
||||
maxRuns: maxRuns > 0 ? maxRuns : undefined
|
||||
}
|
||||
: undefined,
|
||||
template: {
|
||||
scope,
|
||||
contentType,
|
||||
optionTemplate: optionTemplate as ExportAutomationTask['template']['optionTemplate'],
|
||||
dateRangeConfig: (dateRangeConfig ?? null) as ExportAutomationTask['template']['dateRangeConfig']
|
||||
},
|
||||
runState: runStateRaw
|
||||
? {
|
||||
lastRunStatus,
|
||||
lastTriggeredAt: normalizeAutomationNumeric(runStateRaw.lastTriggeredAt, 0) || undefined,
|
||||
lastStartedAt: normalizeAutomationNumeric(runStateRaw.lastStartedAt, 0) || undefined,
|
||||
lastFinishedAt: normalizeAutomationNumeric(runStateRaw.lastFinishedAt, 0) || undefined,
|
||||
lastSuccessAt: normalizeAutomationNumeric(runStateRaw.lastSuccessAt, 0) || undefined,
|
||||
lastSkipAt: normalizeAutomationNumeric(runStateRaw.lastSkipAt, 0) || undefined,
|
||||
lastSkipReason: String(runStateRaw.lastSkipReason || '').trim() || undefined,
|
||||
lastError: String(runStateRaw.lastError || '').trim() || undefined,
|
||||
lastScheduleKey: String(runStateRaw.lastScheduleKey || '').trim() || undefined,
|
||||
successCount: Math.max(0, normalizeAutomationNumeric(runStateRaw.successCount, 0)) || undefined
|
||||
}
|
||||
: undefined,
|
||||
createdAt: Math.max(0, normalizeAutomationNumeric(source.createdAt, Date.now())),
|
||||
updatedAt: Math.max(0, normalizeAutomationNumeric(source.updatedAt, Date.now()))
|
||||
}
|
||||
}
|
||||
|
||||
export async function getExportAutomationTasks(scopeKey: string): Promise<ExportAutomationTaskMapItem | null> {
|
||||
if (!scopeKey) return null
|
||||
const value = await config.get(CONFIG_KEYS.EXPORT_AUTOMATION_TASK_MAP)
|
||||
if (!value || typeof value !== 'object') return null
|
||||
const rawMap = value as Record<string, unknown>
|
||||
const rawItem = rawMap[scopeKey]
|
||||
if (!rawItem || typeof rawItem !== 'object') return null
|
||||
|
||||
const item = rawItem as Record<string, unknown>
|
||||
const updatedAt = Number(item.updatedAt)
|
||||
const rawTasks = Array.isArray(item.tasks)
|
||||
? item.tasks
|
||||
: (Array.isArray(rawItem) ? rawItem : [])
|
||||
const tasks: ExportAutomationTask[] = []
|
||||
for (const rawTask of rawTasks) {
|
||||
const normalized = normalizeAutomationTask(rawTask)
|
||||
if (normalized) {
|
||||
tasks.push(normalized)
|
||||
}
|
||||
}
|
||||
return {
|
||||
updatedAt: Number.isFinite(updatedAt) ? Math.max(0, Math.floor(updatedAt)) : 0,
|
||||
tasks
|
||||
}
|
||||
}
|
||||
|
||||
export async function setExportAutomationTasks(scopeKey: string, tasks: ExportAutomationTask[]): Promise<void> {
|
||||
if (!scopeKey) return
|
||||
const current = await config.get(CONFIG_KEYS.EXPORT_AUTOMATION_TASK_MAP)
|
||||
const map = current && typeof current === 'object'
|
||||
? { ...(current as Record<string, unknown>) }
|
||||
: {}
|
||||
map[scopeKey] = {
|
||||
updatedAt: Date.now(),
|
||||
tasks: (Array.isArray(tasks) ? tasks : []).map((task) => ({ ...task }))
|
||||
}
|
||||
await config.set(CONFIG_KEYS.EXPORT_AUTOMATION_TASK_MAP, map)
|
||||
}
|
||||
|
||||
export async function clearExportAutomationTasks(scopeKey: string): Promise<void> {
|
||||
if (!scopeKey) return
|
||||
const current = await config.get(CONFIG_KEYS.EXPORT_AUTOMATION_TASK_MAP)
|
||||
if (!current || typeof current !== 'object') return
|
||||
const map = { ...(current as Record<string, unknown>) }
|
||||
if (!(scopeKey in map)) return
|
||||
delete map[scopeKey]
|
||||
await config.set(CONFIG_KEYS.EXPORT_AUTOMATION_TASK_MAP, map)
|
||||
}
|
||||
|
||||
export interface ExportSessionMessageCountCacheItem {
|
||||
updatedAt: number
|
||||
counts: Record<string, number>
|
||||
@@ -1483,6 +1691,29 @@ export async function setMessagePushEnabled(enabled: boolean): Promise<void> {
|
||||
await config.set(CONFIG_KEYS.MESSAGE_PUSH_ENABLED, enabled)
|
||||
}
|
||||
|
||||
export type MessagePushFilterMode = 'all' | 'whitelist' | 'blacklist'
|
||||
export type MessagePushSessionType = 'private' | 'group' | 'official' | 'other'
|
||||
|
||||
export async function getMessagePushFilterMode(): Promise<MessagePushFilterMode> {
|
||||
const value = await config.get(CONFIG_KEYS.MESSAGE_PUSH_FILTER_MODE)
|
||||
if (value === 'whitelist' || value === 'blacklist') return value
|
||||
return 'all'
|
||||
}
|
||||
|
||||
export async function setMessagePushFilterMode(mode: MessagePushFilterMode): Promise<void> {
|
||||
await config.set(CONFIG_KEYS.MESSAGE_PUSH_FILTER_MODE, mode)
|
||||
}
|
||||
|
||||
export async function getMessagePushFilterList(): Promise<string[]> {
|
||||
const value = await config.get(CONFIG_KEYS.MESSAGE_PUSH_FILTER_LIST)
|
||||
return Array.isArray(value) ? value.map(item => String(item || '').trim()).filter(Boolean) : []
|
||||
}
|
||||
|
||||
export async function setMessagePushFilterList(list: string[]): Promise<void> {
|
||||
const normalized = Array.from(new Set((list || []).map(item => String(item || '').trim()).filter(Boolean)))
|
||||
await config.set(CONFIG_KEYS.MESSAGE_PUSH_FILTER_LIST, normalized)
|
||||
}
|
||||
|
||||
export async function getWindowCloseBehavior(): Promise<WindowCloseBehavior> {
|
||||
const value = await config.get(CONFIG_KEYS.WINDOW_CLOSE_BEHAVIOR)
|
||||
if (value === 'tray' || value === 'quit') return value
|
||||
@@ -1571,6 +1802,39 @@ export async function setHttpApiHost(host: string): Promise<void> {
|
||||
|
||||
// ─── AI 见解 ──────────────────────────────────────────────────────────────────
|
||||
|
||||
export async function getAiModelApiBaseUrl(): Promise<string> {
|
||||
const value = await config.get(CONFIG_KEYS.AI_MODEL_API_BASE_URL)
|
||||
if (typeof value === 'string' && value.trim()) return value
|
||||
const legacy = await config.get(CONFIG_KEYS.AI_INSIGHT_API_BASE_URL)
|
||||
return typeof legacy === 'string' ? legacy : ''
|
||||
}
|
||||
|
||||
export async function setAiModelApiBaseUrl(url: string): Promise<void> {
|
||||
await config.set(CONFIG_KEYS.AI_MODEL_API_BASE_URL, url)
|
||||
}
|
||||
|
||||
export async function getAiModelApiKey(): Promise<string> {
|
||||
const value = await config.get(CONFIG_KEYS.AI_MODEL_API_KEY)
|
||||
if (typeof value === 'string' && value.trim()) return value
|
||||
const legacy = await config.get(CONFIG_KEYS.AI_INSIGHT_API_KEY)
|
||||
return typeof legacy === 'string' ? legacy : ''
|
||||
}
|
||||
|
||||
export async function setAiModelApiKey(key: string): Promise<void> {
|
||||
await config.set(CONFIG_KEYS.AI_MODEL_API_KEY, key)
|
||||
}
|
||||
|
||||
export async function getAiModelApiModel(): Promise<string> {
|
||||
const value = await config.get(CONFIG_KEYS.AI_MODEL_API_MODEL)
|
||||
if (typeof value === 'string' && value.trim()) return value.trim()
|
||||
const legacy = await config.get(CONFIG_KEYS.AI_INSIGHT_API_MODEL)
|
||||
return typeof legacy === 'string' && legacy.trim() ? legacy.trim() : 'gpt-4o-mini'
|
||||
}
|
||||
|
||||
export async function setAiModelApiModel(model: string): Promise<void> {
|
||||
await config.set(CONFIG_KEYS.AI_MODEL_API_MODEL, model)
|
||||
}
|
||||
|
||||
export async function getAiInsightEnabled(): Promise<boolean> {
|
||||
const value = await config.get(CONFIG_KEYS.AI_INSIGHT_ENABLED)
|
||||
return value === true
|
||||
@@ -1581,30 +1845,30 @@ export async function setAiInsightEnabled(enabled: boolean): Promise<void> {
|
||||
}
|
||||
|
||||
export async function getAiInsightApiBaseUrl(): Promise<string> {
|
||||
const value = await config.get(CONFIG_KEYS.AI_INSIGHT_API_BASE_URL)
|
||||
return typeof value === 'string' ? value : ''
|
||||
return getAiModelApiBaseUrl()
|
||||
}
|
||||
|
||||
export async function setAiInsightApiBaseUrl(url: string): Promise<void> {
|
||||
await config.set(CONFIG_KEYS.AI_INSIGHT_API_BASE_URL, url)
|
||||
await setAiModelApiBaseUrl(url)
|
||||
}
|
||||
|
||||
export async function getAiInsightApiKey(): Promise<string> {
|
||||
const value = await config.get(CONFIG_KEYS.AI_INSIGHT_API_KEY)
|
||||
return typeof value === 'string' ? value : ''
|
||||
return getAiModelApiKey()
|
||||
}
|
||||
|
||||
export async function setAiInsightApiKey(key: string): Promise<void> {
|
||||
await config.set(CONFIG_KEYS.AI_INSIGHT_API_KEY, key)
|
||||
await setAiModelApiKey(key)
|
||||
}
|
||||
|
||||
export async function getAiInsightApiModel(): Promise<string> {
|
||||
const value = await config.get(CONFIG_KEYS.AI_INSIGHT_API_MODEL)
|
||||
return typeof value === 'string' && value.trim() ? value.trim() : 'gpt-4o-mini'
|
||||
return getAiModelApiModel()
|
||||
}
|
||||
|
||||
export async function setAiInsightApiModel(model: string): Promise<void> {
|
||||
await config.set(CONFIG_KEYS.AI_INSIGHT_API_MODEL, model)
|
||||
await setAiModelApiModel(model)
|
||||
}
|
||||
|
||||
export async function getAiInsightSilenceDays(): Promise<number> {
|
||||
@@ -1705,3 +1969,30 @@ export async function getAiInsightTelegramChatIds(): Promise<string> {
|
||||
export async function setAiInsightTelegramChatIds(chatIds: string): Promise<void> {
|
||||
await config.set(CONFIG_KEYS.AI_INSIGHT_TELEGRAM_CHAT_IDS, chatIds)
|
||||
}
|
||||
|
||||
export async function getAiFootprintEnabled(): Promise<boolean> {
|
||||
const value = await config.get(CONFIG_KEYS.AI_FOOTPRINT_ENABLED)
|
||||
return value === true
|
||||
}
|
||||
|
||||
export async function setAiFootprintEnabled(enabled: boolean): Promise<void> {
|
||||
await config.set(CONFIG_KEYS.AI_FOOTPRINT_ENABLED, enabled)
|
||||
}
|
||||
|
||||
export async function getAiFootprintSystemPrompt(): Promise<string> {
|
||||
const value = await config.get(CONFIG_KEYS.AI_FOOTPRINT_SYSTEM_PROMPT)
|
||||
return typeof value === 'string' ? value : ''
|
||||
}
|
||||
|
||||
export async function setAiFootprintSystemPrompt(prompt: string): Promise<void> {
|
||||
await config.set(CONFIG_KEYS.AI_FOOTPRINT_SYSTEM_PROMPT, prompt)
|
||||
}
|
||||
|
||||
export async function getAiInsightDebugLogEnabled(): Promise<boolean> {
|
||||
const value = await config.get(CONFIG_KEYS.AI_INSIGHT_DEBUG_LOG_ENABLED)
|
||||
return value === true
|
||||
}
|
||||
|
||||
export async function setAiInsightDebugLogEnabled(enabled: boolean): Promise<void> {
|
||||
await config.set(CONFIG_KEYS.AI_INSIGHT_DEBUG_LOG_ENABLED, enabled)
|
||||
}
|
||||
|
||||
112
src/types/electron.d.ts
vendored
112
src/types/electron.d.ts
vendored
@@ -18,7 +18,7 @@ export interface ElectronAPI {
|
||||
respondCloseConfirm: (action: 'tray' | 'quit' | 'cancel') => Promise<boolean>
|
||||
openAgreementWindow: () => Promise<boolean>
|
||||
completeOnboarding: () => Promise<boolean>
|
||||
openOnboardingWindow: () => Promise<boolean>
|
||||
openOnboardingWindow: (options?: { mode?: 'add-account' }) => Promise<boolean>
|
||||
setTitleBarOverlay: (options: { symbolColor: string }) => void
|
||||
openVideoPlayerWindow: (videoPath: string, videoWidth?: number, videoHeight?: number) => Promise<void>
|
||||
resizeToFitVideo: (videoWidth: number, videoHeight: number) => Promise<void>
|
||||
@@ -146,7 +146,7 @@ export interface ElectronAPI {
|
||||
}
|
||||
key: {
|
||||
autoGetDbKey: () => Promise<{ success: boolean; key?: string; error?: string; logs?: string[] }>
|
||||
autoGetImageKey: (manualDir?: string, wxid?: string) => Promise<{ success: boolean; xorKey?: number; aesKey?: string; error?: string }>
|
||||
autoGetImageKey: (manualDir?: string, wxid?: string) => Promise<{ success: boolean; xorKey?: number; aesKey?: string; verified?: boolean; error?: string }>
|
||||
scanImageKeyFromMemory: (userDir: string) => Promise<{ success: boolean; xorKey?: number; aesKey?: string; error?: string }>
|
||||
onDbKeyStatus: (callback: (payload: { message: string; level: number }) => void) => () => void
|
||||
onImageKeyStatus: (callback: (payload: { message: string }) => void) => () => void
|
||||
@@ -393,6 +393,95 @@ export interface ElectronAPI {
|
||||
getVoiceTranscript: (sessionId: string, msgId: string, createTime?: number) => Promise<{ success: boolean; transcript?: string; error?: string }>
|
||||
onVoiceTranscriptPartial: (callback: (payload: { sessionId?: string; msgId: string; createTime?: number; text: string }) => void) => () => void
|
||||
getMessage: (sessionId: string, localId: number) => Promise<{ success: boolean; message?: Message; error?: string }>
|
||||
getMyFootprintStats: (
|
||||
beginTimestamp: number,
|
||||
endTimestamp: number,
|
||||
options?: {
|
||||
myWxid?: string
|
||||
privateSessionIds?: string[]
|
||||
groupSessionIds?: string[]
|
||||
mentionLimit?: number
|
||||
privateLimit?: number
|
||||
mentionMode?: 'text_at_me' | string
|
||||
}
|
||||
) => Promise<{
|
||||
success: boolean
|
||||
data?: {
|
||||
summary: {
|
||||
private_inbound_people: number
|
||||
private_replied_people: number
|
||||
private_outbound_people: number
|
||||
private_reply_rate: number
|
||||
mention_count: number
|
||||
mention_group_count: number
|
||||
}
|
||||
private_sessions: Array<{
|
||||
session_id: string
|
||||
incoming_count: number
|
||||
outgoing_count: number
|
||||
replied: boolean
|
||||
first_incoming_ts: number
|
||||
first_reply_ts: number
|
||||
latest_ts: number
|
||||
anchor_local_id: number
|
||||
anchor_create_time: number
|
||||
displayName?: string
|
||||
avatarUrl?: string
|
||||
}>
|
||||
private_segments: Array<{
|
||||
session_id: string
|
||||
segment_index: number
|
||||
start_ts: number
|
||||
end_ts: number
|
||||
duration_sec: number
|
||||
incoming_count: number
|
||||
outgoing_count: number
|
||||
message_count: number
|
||||
replied: boolean
|
||||
first_incoming_ts: number
|
||||
first_reply_ts: number
|
||||
latest_ts: number
|
||||
anchor_local_id: number
|
||||
anchor_create_time: number
|
||||
displayName?: string
|
||||
avatarUrl?: string
|
||||
}>
|
||||
mentions: Array<{
|
||||
session_id: string
|
||||
local_id: number
|
||||
create_time: number
|
||||
sender_username: string
|
||||
message_content: string
|
||||
source: string
|
||||
sessionDisplayName?: string
|
||||
senderDisplayName?: string
|
||||
senderAvatarUrl?: string
|
||||
}>
|
||||
mention_groups: Array<{
|
||||
session_id: string
|
||||
count: number
|
||||
latest_ts: number
|
||||
displayName?: string
|
||||
avatarUrl?: string
|
||||
}>
|
||||
diagnostics: {
|
||||
truncated: boolean
|
||||
scanned_dbs: number
|
||||
elapsed_ms: number
|
||||
}
|
||||
}
|
||||
error?: string
|
||||
}>
|
||||
exportMyFootprint: (
|
||||
beginTimestamp: number,
|
||||
endTimestamp: number,
|
||||
format: 'csv' | 'json',
|
||||
filePath: string
|
||||
) => Promise<{
|
||||
success: boolean
|
||||
filePath?: string
|
||||
error?: string
|
||||
}>
|
||||
onWcdbChange: (callback: (event: any, data: { type: string; json: string }) => void) => () => void
|
||||
}
|
||||
biz: {
|
||||
@@ -986,6 +1075,24 @@ export interface ElectronAPI {
|
||||
stop: () => Promise<{ success: boolean }>
|
||||
status: () => Promise<{ running: boolean; port: number; mediaExportPath: string }>
|
||||
}
|
||||
insight: {
|
||||
testConnection: () => Promise<{ success: boolean; message: string }>
|
||||
getTodayStats: () => Promise<Array<{ sessionId: string; count: number; times: string[] }>>
|
||||
triggerTest: () => Promise<{ success: boolean; message: string }>
|
||||
generateFootprintInsight: (payload: {
|
||||
rangeLabel: string
|
||||
summary: {
|
||||
private_inbound_people?: number
|
||||
private_replied_people?: number
|
||||
private_outbound_people?: number
|
||||
private_reply_rate?: number
|
||||
mention_count?: number
|
||||
mention_group_count?: number
|
||||
}
|
||||
privateSegments?: Array<{ displayName?: string; session_id?: string; incoming_count?: number; outgoing_count?: number; message_count?: number; replied?: boolean }>
|
||||
mentionGroups?: Array<{ displayName?: string; session_id?: string; count?: number }>
|
||||
}) => Promise<{ success: boolean; message: string; insight?: string }>
|
||||
}
|
||||
}
|
||||
|
||||
export interface ExportOptions {
|
||||
@@ -1005,6 +1112,7 @@ export interface ExportOptions {
|
||||
exportVoiceAsText?: boolean
|
||||
excelCompactColumns?: boolean
|
||||
txtColumns?: string[]
|
||||
fileNamingMode?: 'classic' | 'date-range'
|
||||
sessionLayout?: 'shared' | 'per-session'
|
||||
sessionNameWithTypePrefix?: boolean
|
||||
displayNamePreference?: 'group-nickname' | 'remark' | 'nickname'
|
||||
|
||||
68
src/types/exportAutomation.ts
Normal file
68
src/types/exportAutomation.ts
Normal file
@@ -0,0 +1,68 @@
|
||||
import type { ExportOptions as ElectronExportOptions } from './electron'
|
||||
|
||||
export type ExportAutomationScope = 'single' | 'multi' | 'content'
|
||||
export type ExportAutomationContentType = 'text' | 'voice' | 'image' | 'video' | 'emoji' | 'file'
|
||||
|
||||
export type ExportAutomationSchedule =
|
||||
| {
|
||||
type: 'interval'
|
||||
intervalDays: number
|
||||
intervalHours: number
|
||||
}
|
||||
|
||||
export interface ExportAutomationCondition {
|
||||
type: 'new-message-since-last-success'
|
||||
}
|
||||
|
||||
export interface ExportAutomationDateRangeConfig {
|
||||
version?: 1
|
||||
preset?: string
|
||||
useAllTime?: boolean
|
||||
start?: string | number | Date | null
|
||||
end?: string | number | Date | null
|
||||
relativeMode?: 'last-n-days' | string
|
||||
relativeDays?: number
|
||||
}
|
||||
|
||||
export interface ExportAutomationTemplate {
|
||||
scope: ExportAutomationScope
|
||||
contentType?: ExportAutomationContentType
|
||||
optionTemplate: Omit<ElectronExportOptions, 'dateRange'>
|
||||
dateRangeConfig: ExportAutomationDateRangeConfig | string | null
|
||||
}
|
||||
|
||||
export interface ExportAutomationStopCondition {
|
||||
endAt?: number
|
||||
maxRuns?: number
|
||||
}
|
||||
|
||||
export type ExportAutomationRunStatus = 'idle' | 'queued' | 'running' | 'success' | 'error' | 'skipped'
|
||||
|
||||
export interface ExportAutomationRunState {
|
||||
lastRunStatus?: ExportAutomationRunStatus
|
||||
lastTriggeredAt?: number
|
||||
lastStartedAt?: number
|
||||
lastFinishedAt?: number
|
||||
lastSuccessAt?: number
|
||||
lastSkipAt?: number
|
||||
lastSkipReason?: string
|
||||
lastError?: string
|
||||
lastScheduleKey?: string
|
||||
successCount?: number
|
||||
}
|
||||
|
||||
export interface ExportAutomationTask {
|
||||
id: string
|
||||
name: string
|
||||
enabled: boolean
|
||||
sessionIds: string[]
|
||||
sessionNames: string[]
|
||||
outputDir?: string
|
||||
schedule: ExportAutomationSchedule
|
||||
condition: ExportAutomationCondition
|
||||
stopCondition?: ExportAutomationStopCondition
|
||||
template: ExportAutomationTemplate
|
||||
runState?: ExportAutomationRunState
|
||||
createdAt: number
|
||||
updatedAt: number
|
||||
}
|
||||
@@ -138,19 +138,24 @@ export const formatDateInputValue = (date: Date): string => {
|
||||
const y = date.getFullYear()
|
||||
const m = `${date.getMonth() + 1}`.padStart(2, '0')
|
||||
const d = `${date.getDate()}`.padStart(2, '0')
|
||||
return `${y}-${m}-${d}`
|
||||
const h = `${date.getHours()}`.padStart(2, '0')
|
||||
const min = `${date.getMinutes()}`.padStart(2, '0')
|
||||
return `${y}-${m}-${d} ${h}:${min}`
|
||||
}
|
||||
|
||||
export const parseDateInputValue = (raw: string): Date | null => {
|
||||
const text = String(raw || '').trim()
|
||||
const matched = /^(\d{4})-(\d{2})-(\d{2})$/.exec(text)
|
||||
const matched = /^(\d{4})-(\d{2})-(\d{2})(?:\s+(\d{2}):(\d{2}))?$/.exec(text)
|
||||
if (!matched) return null
|
||||
const year = Number(matched[1])
|
||||
const month = Number(matched[2])
|
||||
const day = Number(matched[3])
|
||||
const hour = matched[4] !== undefined ? Number(matched[4]) : 0
|
||||
const minute = matched[5] !== undefined ? Number(matched[5]) : 0
|
||||
if (!Number.isFinite(year) || !Number.isFinite(month) || !Number.isFinite(day)) return null
|
||||
if (month < 1 || month > 12 || day < 1 || day > 31) return null
|
||||
const parsed = new Date(year, month - 1, day)
|
||||
if (hour < 0 || hour > 23 || minute < 0 || minute > 59) return null
|
||||
const parsed = new Date(year, month - 1, day, hour, minute, 0, 0)
|
||||
if (
|
||||
parsed.getFullYear() !== year ||
|
||||
parsed.getMonth() !== month - 1 ||
|
||||
@@ -291,14 +296,14 @@ export const resolveExportDateRangeConfig = (
|
||||
const parsedStart = parseStoredDate(raw.start)
|
||||
const parsedEnd = parseStoredDate(raw.end)
|
||||
if (parsedStart && parsedEnd) {
|
||||
const start = startOfDay(parsedStart)
|
||||
const end = endOfDay(parsedEnd)
|
||||
const start = parsedStart
|
||||
const end = parsedEnd
|
||||
return {
|
||||
preset: 'custom',
|
||||
useAllTime: false,
|
||||
dateRange: {
|
||||
start,
|
||||
end: end < start ? endOfDay(start) : end
|
||||
end: end < start ? start : end
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user