Datasets:
DOI:
License:
Upload 58 files
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- XPostArchiver-clean-upload-20260711-225630/.cargo/config.toml +9 -0
- XPostArchiver-clean-upload-20260711-225630/.gitignore +23 -0
- XPostArchiver-clean-upload-20260711-225630/CHANGELOG.md +56 -0
- XPostArchiver-clean-upload-20260711-225630/Cargo.lock +0 -0
- XPostArchiver-clean-upload-20260711-225630/Cargo.toml +39 -0
- XPostArchiver-clean-upload-20260711-225630/DECISIONS.md +30 -0
- XPostArchiver-clean-upload-20260711-225630/PUBLIC_SAFETY_NOTES.md +8 -0
- XPostArchiver-clean-upload-20260711-225630/README.md +30 -0
- XPostArchiver-clean-upload-20260711-225630/UPLOAD_MANIFEST.md +29 -0
- XPostArchiver-clean-upload-20260711-225630/VERSION_HISTORY.md +31 -0
- XPostArchiver-clean-upload-20260711-225630/build.rs +4 -0
- XPostArchiver-clean-upload-20260711-225630/docs/01-需求规格说明.md +38 -0
- XPostArchiver-clean-upload-20260711-225630/docs/02-技术架构.md +33 -0
- XPostArchiver-clean-upload-20260711-225630/docs/03-数据库设计.md +52 -0
- XPostArchiver-clean-upload-20260711-225630/docs/04-界面与交互设计.md +30 -0
- XPostArchiver-clean-upload-20260711-225630/docs/05-X接口与权限说明.md +26 -0
- XPostArchiver-clean-upload-20260711-225630/docs/06-安装与数据目录设计.md +28 -0
- XPostArchiver-clean-upload-20260711-225630/docs/07-测试方案.md +45 -0
- XPostArchiver-clean-upload-20260711-225630/docs/08-打包发布方案.md +28 -0
- XPostArchiver-clean-upload-20260711-225630/docs/09-隐私与安全说明.md +22 -0
- XPostArchiver-clean-upload-20260711-225630/docs/10-开发阶段计划.md +21 -0
- XPostArchiver-clean-upload-20260711-225630/docs/11-后期优化路线.md +155 -0
- XPostArchiver-clean-upload-20260711-225630/migrations/0001_initial.sql +142 -0
- XPostArchiver-clean-upload-20260711-225630/migrations/README.md +4 -0
- XPostArchiver-clean-upload-20260711-225630/src/api/mod.rs +2 -0
- XPostArchiver-clean-upload-20260711-225630/src/app.rs +824 -0
- XPostArchiver-clean-upload-20260711-225630/src/config/mod.rs +3 -0
- XPostArchiver-clean-upload-20260711-225630/src/config/paths.rs +13 -0
- XPostArchiver-clean-upload-20260711-225630/src/config/settings.rs +105 -0
- XPostArchiver-clean-upload-20260711-225630/src/database/connection.rs +34 -0
- XPostArchiver-clean-upload-20260711-225630/src/database/maintenance.rs +64 -0
- XPostArchiver-clean-upload-20260711-225630/src/database/migrations.rs +9 -0
- XPostArchiver-clean-upload-20260711-225630/src/database/mod.rs +4 -0
- XPostArchiver-clean-upload-20260711-225630/src/domain/mod.rs +2 -0
- XPostArchiver-clean-upload-20260711-225630/src/error.rs +27 -0
- XPostArchiver-clean-upload-20260711-225630/src/exporters/mod.rs +2 -0
- XPostArchiver-clean-upload-20260711-225630/src/lib.rs +8 -0
- XPostArchiver-clean-upload-20260711-225630/src/logging/mod.rs +37 -0
- XPostArchiver-clean-upload-20260711-225630/src/logging/rotation.rs +34 -0
- XPostArchiver-clean-upload-20260711-225630/src/main.rs +13 -0
- XPostArchiver-clean-upload-20260711-225630/src/security/mod.rs +2 -0
- XPostArchiver-clean-upload-20260711-225630/src/services/account_service.rs +137 -0
- XPostArchiver-clean-upload-20260711-225630/src/services/archive_export_service.rs +167 -0
- XPostArchiver-clean-upload-20260711-225630/src/services/crawl_task_service.rs +199 -0
- XPostArchiver-clean-upload-20260711-225630/src/services/credential_service.rs +69 -0
- XPostArchiver-clean-upload-20260711-225630/src/services/database_service.rs +110 -0
- XPostArchiver-clean-upload-20260711-225630/src/services/media_download_service.rs +324 -0
- XPostArchiver-clean-upload-20260711-225630/src/services/mod.rs +10 -0
- XPostArchiver-clean-upload-20260711-225630/src/services/path_service.rs +44 -0
- XPostArchiver-clean-upload-20260711-225630/src/services/post_fetch_service.rs +649 -0
XPostArchiver-clean-upload-20260711-225630/.cargo/config.toml
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[source.crates-io]
|
| 2 |
+
replace-with = "rsproxy-sparse"
|
| 3 |
+
|
| 4 |
+
[source.rsproxy-sparse]
|
| 5 |
+
registry = "sparse+https://rsproxy.cn/index/"
|
| 6 |
+
|
| 7 |
+
[net]
|
| 8 |
+
git-fetch-with-cli = true
|
| 9 |
+
|
XPostArchiver-clean-upload-20260711-225630/.gitignore
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/target/
|
| 2 |
+
/build/
|
| 3 |
+
/dist/
|
| 4 |
+
/backups/
|
| 5 |
+
|
| 6 |
+
*.db
|
| 7 |
+
*.sqlite
|
| 8 |
+
*.sqlite3
|
| 9 |
+
*.db-wal
|
| 10 |
+
*.db-shm
|
| 11 |
+
|
| 12 |
+
*.log
|
| 13 |
+
*.tmp
|
| 14 |
+
*.part
|
| 15 |
+
|
| 16 |
+
.env
|
| 17 |
+
.env.*
|
| 18 |
+
secrets.*
|
| 19 |
+
credentials.*
|
| 20 |
+
|
| 21 |
+
.DS_Store
|
| 22 |
+
Thumbs.db
|
| 23 |
+
|
XPostArchiver-clean-upload-20260711-225630/CHANGELOG.md
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# 变更记录
|
| 2 |
+
|
| 3 |
+
## [未发布]
|
| 4 |
+
|
| 5 |
+
### 新增
|
| 6 |
+
|
| 7 |
+
- 初始化 Rust + Slint + Cargo 项目。
|
| 8 |
+
- 配置 RsProxy Cargo 镜像。
|
| 9 |
+
- 添加最小 Slint 中文窗口。
|
| 10 |
+
- 添加 Tokio 后台运行时骨架。
|
| 11 |
+
- 添加统一错误类型和脱敏日志骨架。
|
| 12 |
+
- 添加 SQLx 初始迁移草案。
|
| 13 |
+
- 添加数据库新建/打开服务与非敏感设置保存。
|
| 14 |
+
- 添加媒体、导出、日志、备份和临时下载目录选择与保存。
|
| 15 |
+
- 添加数据库和数据目录位于系统盘时的非阻断提醒。
|
| 16 |
+
- 添加数据库完整性检查和手动备份入口。
|
| 17 |
+
- 将主界面整理为数据库、归档内容、准备采集三步配置流程。
|
| 18 |
+
- 添加保存媒体文件/只保存文本选项,并兼容旧配置文件。
|
| 19 |
+
- 添加 X API Bearer Token 的系统密钥库保存、状态显示和清除入口。
|
| 20 |
+
- 添加 X API Bearer Token 联网校验与 mock 测试。
|
| 21 |
+
- 添加公开账号查询入口,并将账号基础信息保存到数据库。
|
| 22 |
+
- 添加采集任务创建入口,并将任务记录写入数据库。
|
| 23 |
+
- 添加一页公开帖子拉取入口,基于任务 ID 调用官方 X API 拉取少量公开帖子。
|
| 24 |
+
- 将公开帖子基础字段保存/更新到 posts 表,并更新采集任务计数。
|
| 25 |
+
- 添加分页游标保存和断点续采骨架,下一页拉取会从 crawl_checkpoints 继续。
|
| 26 |
+
- 添加 X API 媒体元数据解析,并保存 media 与 post_media 关联。
|
| 27 |
+
- 添加媒体文件下载骨架,将待保存媒体下载到归档内容目录并更新下载状态。
|
| 28 |
+
- 添加自动连续采集 3 页骨架,并在每页之间保守等待。
|
| 29 |
+
- 将自动连续采集改为后台线程执行,避免采集期间阻塞主界面。
|
| 30 |
+
- 添加自动连续采集页数上限与每页等待秒数输入;页数上限为 0 时持续采集到末页或手动停止。
|
| 31 |
+
- 添加自动采集停止入口,并在停止后将任务状态写回数据库。
|
| 32 |
+
- 添加最近采集任务列表查询与刷新入口。
|
| 33 |
+
- 为主窗口添加最小尺寸约束,改善自由缩放体验。
|
| 34 |
+
- 创建任务或刷新任务列表后自动填入最新任务 ID。
|
| 35 |
+
- 将 Bearer Token 输入框改为密码遮罩输入。
|
| 36 |
+
- 将采集任务状态在界面中显示为中文,并显示失败原因。
|
| 37 |
+
- X API 拉取失败时写回任务失败状态、错误次数和错误信息。
|
| 38 |
+
- 添加按任务 ID 预览已保存帖子的入口。
|
| 39 |
+
- 添加将任务帖子导出为 Markdown 文本索引的入口。
|
| 40 |
+
- 添加失败媒体重试下载入口。
|
| 41 |
+
- 自动采集运行中阻止重复启动第二个自动采集任务。
|
| 42 |
+
- 添加后期优化路线文档。
|
| 43 |
+
- 添加维护接手文档,方便后续 AI 或开发者阅读维护。
|
| 44 |
+
- 为主界面添加滚动区域,避免功能区超出窗口后无法访问。
|
| 45 |
+
- 添加数据库迁移集成测试。
|
| 46 |
+
- 通过 `cargo fmt --all -- --check`、`cargo check`、`cargo clippy --all-targets --all-features -- -D warnings` 和 `cargo test --all`。
|
| 47 |
+
- 实际运行 `cargo run` 并启动最小 Slint 窗口。
|
| 48 |
+
- 将项目文档从旧技术路线修订为 Rust 技术路线。
|
| 49 |
+
|
| 50 |
+
### 环境
|
| 51 |
+
|
| 52 |
+
- Rust:1.97.0
|
| 53 |
+
- Cargo:1.97.0
|
| 54 |
+
- MSVC Build Tools:Visual Studio Build Tools 2022,17.14.35
|
| 55 |
+
- Windows SDK:10.0.26100.0
|
| 56 |
+
|
XPostArchiver-clean-upload-20260711-225630/Cargo.lock
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
XPostArchiver-clean-upload-20260711-225630/Cargo.toml
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[package]
|
| 2 |
+
name = "xpost-archiver"
|
| 3 |
+
version = "0.1.0"
|
| 4 |
+
edition = "2024"
|
| 5 |
+
build = "build.rs"
|
| 6 |
+
|
| 7 |
+
[dependencies]
|
| 8 |
+
slint = "1.13"
|
| 9 |
+
tokio = { version = "1.47", features = ["rt-multi-thread", "macros", "sync", "time", "fs"] }
|
| 10 |
+
tokio-util = { version = "0.7", features = ["rt"] }
|
| 11 |
+
reqwest = { version = "0.12", default-features = false, features = ["json", "stream", "rustls-tls"] }
|
| 12 |
+
serde = { version = "1.0", features = ["derive"] }
|
| 13 |
+
serde_json = "1.0"
|
| 14 |
+
sqlx = { version = "0.8", default-features = false, features = ["runtime-tokio-rustls", "sqlite", "migrate", "macros", "chrono", "json"] }
|
| 15 |
+
rfd = "0.15"
|
| 16 |
+
keyring = "3.6"
|
| 17 |
+
tracing = "0.1"
|
| 18 |
+
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
|
| 19 |
+
tracing-appender = "0.2"
|
| 20 |
+
thiserror = "2.0"
|
| 21 |
+
anyhow = "1.0"
|
| 22 |
+
chrono = { version = "0.4", features = ["serde"] }
|
| 23 |
+
url = "2.5"
|
| 24 |
+
uuid = { version = "1.18", features = ["v4", "serde"] }
|
| 25 |
+
rust_xlsxwriter = "0.90"
|
| 26 |
+
csv = "1.3"
|
| 27 |
+
sha2 = "0.10"
|
| 28 |
+
directories = "6.0"
|
| 29 |
+
bytes = "1.10"
|
| 30 |
+
futures-util = "0.3"
|
| 31 |
+
|
| 32 |
+
[build-dependencies]
|
| 33 |
+
slint-build = "1.13"
|
| 34 |
+
|
| 35 |
+
[dev-dependencies]
|
| 36 |
+
tempfile = "3.21"
|
| 37 |
+
wiremock = "0.6"
|
| 38 |
+
pretty_assertions = "1.4"
|
| 39 |
+
|
XPostArchiver-clean-upload-20260711-225630/DECISIONS.md
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# 技术决策记录
|
| 2 |
+
|
| 3 |
+
## ADR-001:纯 Rust 桌面架构
|
| 4 |
+
|
| 5 |
+
项目采用 Rust stable、Edition 2024、Slint、Tokio、reqwest、SQLx、SQLite、keyring、tracing 和 Inno Setup。不得引入 Python、JavaScript、TypeScript、Node.js、Electron、Tauri、WebView、Docker、云数据库或浏览器自动化。
|
| 6 |
+
|
| 7 |
+
## ADR-002:Slint 作为桌面界面
|
| 8 |
+
|
| 9 |
+
Slint 提供纯 Rust 桌面 UI,避免网页前端栈。界面运行在主线程;后台任务通过消息通道或 Slint 安全事件循环返回结果,不从后台线程直接修改控件。
|
| 10 |
+
|
| 11 |
+
## ADR-003:SQLx 运行时查询与迁移
|
| 12 |
+
|
| 13 |
+
使用 SQLite + SQLx migrations。第一版优先使用运行时 SQL,避免构建期依赖用户数据库或 SQLx 离线元数据。迁移前必须备份用户数据库。
|
| 14 |
+
|
| 15 |
+
## ADR-004:仅使用官方允许的 X API
|
| 16 |
+
|
| 17 |
+
不模拟登录,不收集账号密码或 Cookie,不绕过验证码、保护账号、付费权限、访问控制和频率限制。“尽可能完整”仅指 API 当前实际可访问并返回的范围。
|
| 18 |
+
|
| 19 |
+
## ADR-005:严格分离开发、安装和数据目录
|
| 20 |
+
|
| 21 |
+
正式程序不得依赖开发路径。安装目录仅放程序文件;数据库、媒体、导出、日志和备份由用户分别选择。配置只保存路径和非敏感偏好,凭据由 keyring 保存。
|
| 22 |
+
|
| 23 |
+
## ADR-006:数据语义
|
| 24 |
+
|
| 25 |
+
所有 X ID 按字符串保存;内部时间统一使用 UTC;接口未提供的数值使用 NULL,不用 0 冒充未知。原始 JSON 用于兼容和审计,但默认日志不记录完整响应。
|
| 26 |
+
|
| 27 |
+
## ADR-007:后台任务和受控写入
|
| 28 |
+
|
| 29 |
+
Tokio 运行在后台工作线程。网络、分页、导出和媒体下载不阻塞 Slint 主线程;SQLite 使用受控写入队列或单写者策略,防止大量任务无序写入。
|
| 30 |
+
|
XPostArchiver-clean-upload-20260711-225630/PUBLIC_SAFETY_NOTES.md
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Public Safety Notes
|
| 2 |
+
|
| 3 |
+
This project is designed to use the official X API only. It does not include credentials, cookies, databases, local archives, logs, or media files.
|
| 4 |
+
|
| 5 |
+
Bearer Tokens are expected to be stored by the running app in the operating system keyring, not in this source package.
|
| 6 |
+
|
| 7 |
+
Do not upload your own generated databases, archived media, logs, or keyring exports.
|
| 8 |
+
|
XPostArchiver-clean-upload-20260711-225630/README.md
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# X公开帖子归档器
|
| 2 |
+
|
| 3 |
+
内部英文标识:`XPostArchiver`。
|
| 4 |
+
|
| 5 |
+
这是纯本地 Windows 桌面软件项目,采用 Rust + Slint。软件计划通过 X 官方允许的 API,在当前权限、额度和平台可访问范围内尽可能归档公开帖子。
|
| 6 |
+
|
| 7 |
+
> 本软件会在当前X API权限、账户额度和平台可访问范围内,尽可能完整地获取公开内容。实际可获取数量和时间范围由X平台返回结果决定。
|
| 8 |
+
|
| 9 |
+
## 技术路线
|
| 10 |
+
|
| 11 |
+
- Rust stable,Edition 2024
|
| 12 |
+
- Slint 桌面界面
|
| 13 |
+
- Tokio 后台运行时
|
| 14 |
+
- reqwest + rustls 网络请求
|
| 15 |
+
- SQLx + SQLite + SQLx migrations
|
| 16 |
+
- keyring 保存 Windows 凭据
|
| 17 |
+
- tracing 日志
|
| 18 |
+
- rust_xlsxwriter、csv、serde_json 导出
|
| 19 |
+
- Inno Setup 安装程序
|
| 20 |
+
|
| 21 |
+
## 目录边界
|
| 22 |
+
|
| 23 |
+
- 开发源码目录:`<project-directory>`,仅供开发,不得写死到正式程序。
|
| 24 |
+
- 安装目录:由最终用户在安装时选择。
|
| 25 |
+
- 数据目录:数据库、媒体、导出、日志和备份分别由用户选择,禁止默认混入开发目录或安装目录。
|
| 26 |
+
|
| 27 |
+
## 当前状态
|
| 28 |
+
|
| 29 |
+
第零阶段进行中。Rust 工具链、Cargo、MSVC Build Tools 和 Windows SDK 已安装;最小 Slint 窗口和基础架构正在验收。
|
| 30 |
+
|
XPostArchiver-clean-upload-20260711-225630/UPLOAD_MANIFEST.md
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Clean Upload Package Manifest
|
| 2 |
+
|
| 3 |
+
This package is intended for uploading to Hugging Face or another public code hosting platform.
|
| 4 |
+
|
| 5 |
+
Included:
|
| 6 |
+
|
| 7 |
+
- Rust source code under `src/`
|
| 8 |
+
- Slint UI under `ui/`
|
| 9 |
+
- SQLite migrations under `migrations/`
|
| 10 |
+
- Tests under `tests/`
|
| 11 |
+
- Public documentation under `docs/`
|
| 12 |
+
- Cargo project files
|
| 13 |
+
- Public changelog and version history
|
| 14 |
+
|
| 15 |
+
Excluded:
|
| 16 |
+
|
| 17 |
+
- `.git/`
|
| 18 |
+
- `target/`
|
| 19 |
+
- `backups/`
|
| 20 |
+
- local release staging folders
|
| 21 |
+
- local database files
|
| 22 |
+
- logs
|
| 23 |
+
- media archives
|
| 24 |
+
- system keyring credentials
|
| 25 |
+
- local environment reports
|
| 26 |
+
- machine-specific project state/inventory files
|
| 27 |
+
|
| 28 |
+
Before public release, review README and docs once more for wording and platform policy fit.
|
| 29 |
+
|
XPostArchiver-clean-upload-20260711-225630/VERSION_HISTORY.md
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Version History
|
| 2 |
+
|
| 3 |
+
This file is generated for the clean upload package. It keeps commit hashes and public commit messages only. The `.git` directory is intentionally not included, so local author identity and repository metadata are not packaged.
|
| 4 |
+
|
| 5 |
+
- `c87d83e` chore: initialize Rust and Slint application architecture
|
| 6 |
+
- `9d0fe80` feat: add database selection and migration foundation
|
| 7 |
+
- `9a060a2` feat: add configurable data directories
|
| 8 |
+
- `465a24c` feat: warn for system drive data paths
|
| 9 |
+
- `e565f9e` feat: add database maintenance actions
|
| 10 |
+
- `97b3c98` feat: add first-run configuration flow
|
| 11 |
+
- `dcd036c` feat: add local X API credential storage
|
| 12 |
+
- `2f2365f` feat: validate X API bearer token
|
| 13 |
+
- `90c0a0b` feat: add public account lookup
|
| 14 |
+
- `977b16d` feat: add crawl task creation skeleton
|
| 15 |
+
- `222e9fb` feat: fetch first page of public posts
|
| 16 |
+
- `39c8fc4` feat: continue public post pagination
|
| 17 |
+
- `eb2e698` feat: store public post media metadata
|
| 18 |
+
- `78f25df` feat: download archived media files
|
| 19 |
+
- `8f6ad1b` feat: add automatic paged crawl skeleton
|
| 20 |
+
- `485e471` feat: run automatic crawl in background
|
| 21 |
+
- `19031e1` feat: add automatic crawl stop and limits
|
| 22 |
+
- `7e2b770` feat: persist stopped crawl status
|
| 23 |
+
- `1a7ce21` feat: show recent crawl tasks
|
| 24 |
+
- `392a4c8` feat: improve resizable window constraints
|
| 25 |
+
- `f4bc9f6` feat: autofill selected crawl task id
|
| 26 |
+
- `e8e4fca` feat: mask bearer token input
|
| 27 |
+
- `39c3741` feat: show crawl status labels and errors
|
| 28 |
+
- `d46776e` feat: preview and export archived posts
|
| 29 |
+
- `c1676f0` feat: retry failed media and guard auto crawl
|
| 30 |
+
- `57275ed` docs: add maintenance and optimization notes
|
| 31 |
+
|
XPostArchiver-clean-upload-20260711-225630/build.rs
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
fn main() {
|
| 2 |
+
slint_build::compile("ui/app-window.slint").expect("failed to compile Slint UI");
|
| 3 |
+
}
|
| 4 |
+
|
XPostArchiver-clean-upload-20260711-225630/docs/01-需求规格说明.md
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# 需求规格说明
|
| 2 |
+
|
| 3 |
+
## 软件目标
|
| 4 |
+
|
| 5 |
+
用户输入 `@username`、用户名或 X 账号主页链接,经确认后通过 X 官方允许的 API 创建任务,把接口实际返回的公开帖子保存到用户选择的 SQLite 数据库,并在本地浏览、筛选和导出。
|
| 6 |
+
|
| 7 |
+
## 支持范围
|
| 8 |
+
|
| 9 |
+
- 查询并确认公开账号。
|
| 10 |
+
- 保存原创、回复、转发、引用及其原始引用关系。
|
| 11 |
+
- 保存接口返回的正文、长文信息、互动指标和媒体元数据。
|
| 12 |
+
- 分页、去重、断点续传、增量更新、暂停、继续和停止。
|
| 13 |
+
- 可选媒体下载及失败重试。
|
| 14 |
+
- 本地搜索、筛选和排序。
|
| 15 |
+
- 导出 Excel、CSV、JSON、JSON Lines、Markdown 和 TXT。
|
| 16 |
+
|
| 17 |
+
## 不能保证
|
| 18 |
+
|
| 19 |
+
软件不保证获得已删除、受保护、无权访问、被平台隐藏、超出 API 权限或额度、接口没有返回的帖子和媒体,也不保证取得账号创建以来绝对完整的历史内容。
|
| 20 |
+
|
| 21 |
+
界面统一显示:
|
| 22 |
+
|
| 23 |
+
> 本软件会在当前X API权限、账户额度和平台可访问范围内,尽可能完整地获取公开内容。实际可获取数量和时间范围由X平台返回结果决定。
|
| 24 |
+
|
| 25 |
+
## 核心约束
|
| 26 |
+
|
| 27 |
+
- 用户确认目标账号后才能采集。
|
| 28 |
+
- 不绕过登录、验证码、付费、访问控制和频率限制。
|
| 29 |
+
- 不要求 X 账号密码,不窃取 Cookie。
|
| 30 |
+
- X ID 必须按字符串保存;时间内部统一为 UTC。
|
| 31 |
+
- 未返回字段使用空值,并区分明确为 0、未提供、权限不足和解析失败。
|
| 32 |
+
- 数据库路径失效时不得自动建立替代空库。
|
| 33 |
+
- 正式程序不得依赖开发目录。
|
| 34 |
+
|
| 35 |
+
## 验收原则
|
| 36 |
+
|
| 37 |
+
每阶段必须运行相关测试并实际启动检查。测试失败、环境缺失或未实际运行时,不得宣称阶段完成或软件正常运行。
|
| 38 |
+
|
XPostArchiver-clean-upload-20260711-225630/docs/02-技术架构.md
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# 技术架构
|
| 2 |
+
|
| 3 |
+
## 技术栈
|
| 4 |
+
|
| 5 |
+
项目使用 Rust stable、Edition 2024、Slint、Tokio、reqwest + rustls、serde、SQLx + SQLite + SQLx migrations、rfd、keyring、tracing、thiserror、anyhow、chrono、url、uuid、rust_xlsxwriter、csv、sha2、directories、Inno Setup。
|
| 6 |
+
|
| 7 |
+
## 模块分层
|
| 8 |
+
|
| 9 |
+
- `ui`:Slint 界面文件。
|
| 10 |
+
- `ui_bridge`:Rust 与 Slint 的回调、模型和通知桥接。
|
| 11 |
+
- `api`:官方 X API 客户端、认证、账号、帖子、分页、限流、响应和错误分类。
|
| 12 |
+
- `database`:SQLx 连接、迁移、仓储、账号、帖子、任务、断点和媒体访问。
|
| 13 |
+
- `domain`:账号、帖子、媒体、采集任务和断点领域模型。
|
| 14 |
+
- `tasks`:Tokio 运行时、命令、事件、采集工作者、单一数据库写入任务、媒体工作者和取消控制。
|
| 15 |
+
- `services`:账号、采集、媒体、数据库和导出应用服务。
|
| 16 |
+
- `exporters`:Excel、CSV、JSON、Markdown、TXT。
|
| 17 |
+
- `config`:非敏感设置和路径。
|
| 18 |
+
- `security`:Windows 凭据保存和脱敏。
|
| 19 |
+
- `logging`:tracing 日志和轮转。
|
| 20 |
+
- `utils`:文件名、时间、URL 和磁盘工具。
|
| 21 |
+
|
| 22 |
+
## 线程与异步
|
| 23 |
+
|
| 24 |
+
Slint 界面运行在主线程。Tokio 后台运行时处理 HTTP、分页、媒体下载、导出和数据库写入命令。后台任务不得直接修改 Slint 控件;必须通过消息通道或 Slint 安全事件循环返回结果。
|
| 25 |
+
|
| 26 |
+
## 数据库并发
|
| 27 |
+
|
| 28 |
+
使用 SQLx 连接用户选择的 SQLite 文件。采用多个受控读取连接和单一数据库写入任务。每页帖子在事务中保存,提交成功后才更新断点。
|
| 29 |
+
|
| 30 |
+
## 禁止方案
|
| 31 |
+
|
| 32 |
+
不得引入覆盖指令禁止的跨语言脚本栈、网页前端栈、浏览器壳、浏览器自动化、远程服务器、云数据库或容器化方案。
|
| 33 |
+
|
XPostArchiver-clean-upload-20260711-225630/docs/03-数据库设计.md
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# 数据库设计
|
| 2 |
+
|
| 3 |
+
## 原则
|
| 4 |
+
|
| 5 |
+
数据库由用户新建或选择。使用 SQLite、SQLx 和 SQLx migrations。迁移前创建备份,失败时保留原数据库。X ID 使用 TEXT,时间统一存 UTC,未知指标使用 NULL,API 凭据绝不入库。
|
| 6 |
+
|
| 7 |
+
## 迁移
|
| 8 |
+
|
| 9 |
+
迁移文件保存在 `migrations`。构建软件时不得要求用户数据库存在。第一版优先使用 SQLx 运行时查询接口,不依赖构建期数据库连接或离线查询元数据。
|
| 10 |
+
|
| 11 |
+
## 数据表
|
| 12 |
+
|
| 13 |
+
### app_metadata
|
| 14 |
+
|
| 15 |
+
保存数据库创建时间、结构版本、应用版本、最后打开时间等非敏感数据库级信息。
|
| 16 |
+
|
| 17 |
+
### accounts
|
| 18 |
+
|
| 19 |
+
保存 `x_user_id`(唯一)、用户名、显示名、简介、头像、X 创建时间、protected、verified、粉丝/关注/帖子数量、首次和最后发现时间、raw_json。
|
| 20 |
+
|
| 21 |
+
### posts
|
| 22 |
+
|
| 23 |
+
保存 `x_post_id`(唯一)、作者账号 ID/用户名/显示名、正文、发布时间、原始链接、语言、conversation_id、回复对象、帖子分类、长文标记、可空互动指标、媒体标志、首次和最后采集时间、数据来源、来源任务及 raw_json。
|
| 24 |
+
|
| 25 |
+
### post_references
|
| 26 |
+
|
| 27 |
+
保存 source_post_id、reference_type 和 target_x_post_id。类型包括 `replied_to`、`quoted`、`reposted`,允许一条帖子存在多种关系。
|
| 28 |
+
|
| 29 |
+
### media 与 post_media
|
| 30 |
+
|
| 31 |
+
媒体表保存 media_key、类型、原始/预览 URL、相对媒体根目录路径、MIME、文件大小、宽高、时长、下载状态、时间、校验和、错误及 raw_json;关联表保存帖子、媒体和显示顺序。
|
| 32 |
+
|
| 33 |
+
### crawl_jobs
|
| 34 |
+
|
| 35 |
+
保存目标、任务模式、日期、数量上限、类型开关、媒体开关、状态、时间和统计。状态至少包括 pending、running、pausing、paused、completed、completed_with_warnings、failed、cancelled、rate_limited、quota_exhausted。
|
| 36 |
+
|
| 37 |
+
### crawl_checkpoints
|
| 38 |
+
|
| 39 |
+
保存任务、分页令牌、最早/最新帖子 ID 和时间、成功页数、最后成功请求时间和更新时间。
|
| 40 |
+
|
| 41 |
+
### fetch_errors
|
| 42 |
+
|
| 43 |
+
保存任务、阶段、脱敏请求标识、错误类别、HTTP 状态、消息、是否可重试、重试次数、创建和解决时间。
|
| 44 |
+
|
| 45 |
+
## 去重、分页和事务
|
| 46 |
+
|
| 47 |
+
以 `x_post_id` 唯一约束和 upsert 双重去重。重复返回时更新接口实际提供的字段,不用缺失字段覆盖已有有效值。每页数据成功提交后才更新断点;失败回滚本页,不破坏此前页面。
|
| 48 |
+
|
| 49 |
+
## 打开、检查和迁移
|
| 50 |
+
|
| 51 |
+
检查 SQLite 文件头、读写权限、完整性、迁移版本和必要数据表。迁移前复制备份;失败则关闭连接并保留原库。不得覆盖同名数据库或在旧路径失效时创建替代空库。
|
| 52 |
+
|
XPostArchiver-clean-upload-20260711-225630/docs/04-界面与交互设计.md
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# 界面与交互设计
|
| 2 |
+
|
| 3 |
+
## 首次启动向导
|
| 4 |
+
|
| 5 |
+
1. 欢迎页说明 API 权限、额度和可访问范围限制。
|
| 6 |
+
2. 新建数据库、打开已有数据库或退出。无有效数据库时禁止采集。
|
| 7 |
+
3. 选择媒体目录,或暂不下载媒体。
|
| 8 |
+
4. 分别设置导出、日志、临时和备份目录。
|
| 9 |
+
5. 设置 Bearer Token 等必要凭据,提供保存、测试、删除和状态显示,不完整展示已保存密钥。
|
| 10 |
+
6. 汇总数据库、各目录、API 状态、写权限和磁盘空间。
|
| 11 |
+
|
| 12 |
+
新建数据库自动补 `.db`,同名文件存在时不得覆盖。打开已有库需要检查 SQLite 有效性、读写权限、结构版本、必要表和完整性;迁移先备份,失败恢复。
|
| 13 |
+
|
| 14 |
+
## 页面
|
| 15 |
+
|
| 16 |
+
- 首页/新建任务:账号输入、查询、预览、范围、日期、数量、类型、媒体选项、当前数据库和 API 状态。
|
| 17 |
+
- 任务管理:状态、页数、接收/新增/更新/重复、媒体数量、当前日期和最近错误;支持开始、暂停、继续、停止、重试、报告和日志。总量未知时不显示虚假百分比。
|
| 18 |
+
- 帖子数据库:账号、关键词、日期、类型、媒体和互动指标筛选;分页列表、详情和多种排序。
|
| 19 |
+
- 数据库管理:新建、打开、切换、备份、检查、统计、迁移和打开文件夹。
|
| 20 |
+
- 导出:当前筛选、账号、任务、日期范围或勾选项。
|
| 21 |
+
- 设置:API、数据库、媒体、导出、日志、备份、网络重试、界面、隐私和关于。
|
| 22 |
+
|
| 23 |
+
## 账号输入
|
| 24 |
+
|
| 25 |
+
去除首尾空格和开头 `@`;解析 x.com / www.x.com 主页链接并去掉查询参数和多余斜杠;拒绝帖子链接及明显无效用户名。查询只显示预览,用户点击确认后才创建任务。
|
| 26 |
+
|
| 27 |
+
## 路径失效
|
| 28 |
+
|
| 29 |
+
上次数据库不可访问时,提示用户连接对应磁盘或重新选择文件;不自动建空库、不改用系统盘、不删除路径记录,也不武断声称数据丢失。
|
| 30 |
+
|
XPostArchiver-clean-upload-20260711-225630/docs/05-X接口与权限说明.md
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# X接口与权限说明
|
| 2 |
+
|
| 3 |
+
## 官方接口
|
| 4 |
+
|
| 5 |
+
软件只使用 X 官方当前允许的 API 和用户自行申请的凭据。第一版至少支持 Bearer Token。具体 endpoint、字段、分页令牌、历史范围和价格在实现时必须依据当时官方文档核验,不能把易变化的套餐能力写成永久承诺。
|
| 6 |
+
|
| 7 |
+
## 权限、额度和费用
|
| 8 |
+
|
| 9 |
+
不同 API 产品和账号层级可能具有不同额度、历史范围、字段和媒体 URL 权限,并可能收费。401 通常表示认证失败;403 可能是权限、保护状态或产品限制;404 表示不存在或不可见;429 表示频率限制;额度耗尽时必须停止请求并报告。
|
| 10 |
+
|
| 11 |
+
## 可获取边界
|
| 12 |
+
|
| 13 |
+
软件不保证取得已删除、受保护、隐藏、超历史范围、超额度、无权限或接口未返回的数据和媒体源文件。“尽可能完整”只是沿当前接口分页获取实际可访问的公开内容。
|
| 14 |
+
|
| 15 |
+
当权限不足时显示:
|
| 16 |
+
|
| 17 |
+
> 当前接口权限无法继续获取更早的数据。本次任务已经保存所有实际返回的内容,但不能据此保证账号历史内容绝对完整。
|
| 18 |
+
|
| 19 |
+
## 合规要求
|
| 20 |
+
|
| 21 |
+
不绕过登录、验证码、付费、保护账号、访问控制和频率限制;不轮换账号或密钥规避限制;不使用浏览器自动化;不索取账号密码;不窃取 Cookie。
|
| 22 |
+
|
| 23 |
+
## 错误与重试
|
| 24 |
+
|
| 25 |
+
只重试可能恢复的错误,使用有限指数退避并尊重 Retry-After 等限流信息。401、403 不无限重试。任务报告应说明分页末尾、日期/数量停止、限流、额度、权限及仍可能缺失的内容。
|
| 26 |
+
|
XPostArchiver-clean-upload-20260711-225630/docs/06-安装与数据目录设计.md
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# 安装与数据目录设计
|
| 2 |
+
|
| 3 |
+
## 三类目录
|
| 4 |
+
|
| 5 |
+
- 开发目录固定为 `<project-directory>`,只保存源码、测试、脚本、文档和构建结果;正式程序不得依赖或写死该路径。
|
| 6 |
+
- 安装目录由用户在安装程序中选择,只保存 EXE、DLL、Qt 资源、图标、必要资源和卸载程序。
|
| 7 |
+
- 数据目录由用户分别选择数据库、媒体、导出、日志、临时下载和备份位置,不默认写入开发目录或安装目录。
|
| 8 |
+
|
| 9 |
+
## 配置与凭据
|
| 10 |
+
|
| 11 |
+
使用 platformdirs 对应的 Windows 用户配置目录保存上次数据库路径、媒体/导出/日志/备份目录、界面设置和非敏感偏好。API 凭据使用 Windows 凭据管理能力和 keyring,不得写入配置文件、SQLite 或日志。
|
| 12 |
+
|
| 13 |
+
## 路径兼容
|
| 14 |
+
|
| 15 |
+
使用 pathlib 与 Qt 路径 API,支持中文、空格、不同盘符、外接硬盘和较长目录名。媒体记录保存相对于媒体根目录的路径,并允许用户移动后重新绑定。磁盘断开时保留原设置,禁止自动转到系统盘或创建空库。
|
| 16 |
+
|
| 17 |
+
## 系统盘提醒
|
| 18 |
+
|
| 19 |
+
安装时和首次选择数据库或媒体目录时检测 Windows 系统盘。若选择系统盘,建议改用空间充足的非系统盘,但允许继续;数据位置提醒可选择不再提示,避免反复弹窗。推荐安装目录不得是开发目录。
|
| 20 |
+
|
| 21 |
+
## 卸载和升级
|
| 22 |
+
|
| 23 |
+
卸载默认只删除程序文件,并明确说明不会删除用户数据库、媒体、导出和备份;可以让用户选择删除小型设置,但不得默认删除数据。升级保留路径、凭据和媒体;数据库结构升级前先备份,失败恢复。
|
| 24 |
+
|
| 25 |
+
## 便携版
|
| 26 |
+
|
| 27 |
+
便携版仍允许选择独立数据库和媒体目录,不把“便携”解释为所有数据必须放在程序目录。
|
| 28 |
+
|
XPostArchiver-clean-upload-20260711-225630/docs/07-测试方案.md
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# 测试方案
|
| 2 |
+
|
| 3 |
+
## 基础命令
|
| 4 |
+
|
| 5 |
+
每个阶段至少执行:
|
| 6 |
+
|
| 7 |
+
```powershell
|
| 8 |
+
cargo fmt --all -- --check
|
| 9 |
+
cargo clippy --all-targets --all-features -- -D warnings
|
| 10 |
+
cargo test --all
|
| 11 |
+
cargo check
|
| 12 |
+
```
|
| 13 |
+
|
| 14 |
+
完成可运行阶段后还必须执行:
|
| 15 |
+
|
| 16 |
+
```powershell
|
| 17 |
+
cargo run
|
| 18 |
+
```
|
| 19 |
+
|
| 20 |
+
发布前执行:
|
| 21 |
+
|
| 22 |
+
```powershell
|
| 23 |
+
cargo build --release
|
| 24 |
+
```
|
| 25 |
+
|
| 26 |
+
## 单元测试
|
| 27 |
+
|
| 28 |
+
覆盖用户名规范化、X 主页链接解析和帖子链接拒绝、帖子分类、ID 去重、UTC/本地时间转换、路径处理、Windows 文件名清理、分页断点、API 错误分类、敏感信息脱敏、各导出格式和数据库迁移。
|
| 29 |
+
|
| 30 |
+
## 数据库测试
|
| 31 |
+
|
| 32 |
+
覆盖新建、打开、拒绝无效库、重复帖子 upsert、字段更新、断点恢复、迁移前备份、迁移失败回滚、未知值与 0 区分、长 ID 字符串保存。
|
| 33 |
+
|
| 34 |
+
## 界面测试
|
| 35 |
+
|
| 36 |
+
覆盖首次向导、无数据库时禁止采集、API 失败中文提示、开始/暂停/恢复/停止、切换数据库、导出筛选结果、路径失效提示和主线程响应性。每阶段必须实际检查 Slint 窗口能打开、移动和关闭。
|
| 37 |
+
|
| 38 |
+
## 模拟 API 测试
|
| 39 |
+
|
| 40 |
+
使用 wiremock 模拟正常分页、空结果、无下一页、401、403、404、429、5xx、额度不足、超时、字段缺失、重复帖子和媒体失败。自动测试不得大量调用真实 X API,不使用真实密钥。
|
| 41 |
+
|
| 42 |
+
## 发布验收
|
| 43 |
+
|
| 44 |
+
在无 Rust 开发环境的 Windows 10/11 上测试 release 程序;验证中文和空格路径、不同盘符、安装、卸载、升级、数据库备份恢复、磁盘断开和数据保留。
|
| 45 |
+
|
XPostArchiver-clean-upload-20260711-225630/docs/08-打包发布方案.md
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# 打包发布方案
|
| 2 |
+
|
| 3 |
+
## Release 构建
|
| 4 |
+
|
| 5 |
+
开发阶段使用 `cargo run`。发布构建使用:
|
| 6 |
+
|
| 7 |
+
```powershell
|
| 8 |
+
cargo build --release
|
| 9 |
+
```
|
| 10 |
+
|
| 11 |
+
生成的可执行文件通常位于 `target\release\xpost-archiver.exe`。最终发布文件复制到 `dist`。不得要求最终用户安装 Rust、Cargo 或开发工具链。
|
| 12 |
+
|
| 13 |
+
## 资源
|
| 14 |
+
|
| 15 |
+
打包时包含 EXE、必要动态库、Slint 运行资源、图标和软件内部只读资源。数据库、媒体、导出和备份不得默认写入安装目录。
|
| 16 |
+
|
| 17 |
+
## Inno Setup
|
| 18 |
+
|
| 19 |
+
安装器允许用户选择安装位置,显示目标磁盘剩余空间和快捷方式选项。若安装到系统盘,只提醒并提供返回修改或继续安装,不强制阻止。
|
| 20 |
+
|
| 21 |
+
## 卸载和升级
|
| 22 |
+
|
| 23 |
+
卸载默认保留数据库、媒体、导出和备份,只删除程序文件;小型设置可由用户选择删除。升级保留路径、凭据和用户数据,数据库迁移前创建备份,并显示版本变化。
|
| 24 |
+
|
| 25 |
+
## 发布检查
|
| 26 |
+
|
| 27 |
+
执行全量 Cargo 测试、安全与隐私检查、安装/卸载/升级测试、备份恢复和无开发环境启动测试。最终输出安装版 EXE、便携版 ZIP、`SHA256SUMS.txt` 和发布说明。
|
| 28 |
+
|
XPostArchiver-clean-upload-20260711-225630/docs/09-隐私与安全说明.md
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# 隐私与安全说明
|
| 2 |
+
|
| 3 |
+
## 数据最小化
|
| 4 |
+
|
| 5 |
+
软件第一版纯本地运行,不主动上传用户数据库、媒体、导出或诊断信息。默认日志不记录完整帖子正文和完整 API 响应。
|
| 6 |
+
|
| 7 |
+
## 凭据
|
| 8 |
+
|
| 9 |
+
Bearer Token、API Secret 等仅由 keyring 保存;界面只显示状态或掩码。禁止将密钥写入源码、Git、SQLite、日志、错误弹窗、诊断报告、导出文件和测试。复制诊断信息时清理 Authorization、token、secret、cookie 等敏感字段。
|
| 10 |
+
|
| 11 |
+
## 文件安全
|
| 12 |
+
|
| 13 |
+
新建数据库不得覆盖同名文件;迁移前备份,失败恢复。媒体使用临时扩展名下载,成功后原子重命名,可校验文件大小和 SHA-256。磁盘断开时安全停止,不删除原路径或已有数据。
|
| 14 |
+
|
| 15 |
+
## 平台边界
|
| 16 |
+
|
| 17 |
+
不索取 X 密码、不窃取 Cookie、不绕过验证码、登录、保护账号、付费权限、访问控制和频率限制,不轮换密钥,不以高并发轰炸接口,不使用来源不明的代理或免登录库。
|
| 18 |
+
|
| 19 |
+
## 日志与诊断
|
| 20 |
+
|
| 21 |
+
日志按日期或大小轮转,可设置保留天数。诊断报告只包含软件版本、Windows 版本、打包版本、数据库结构版本、错误类别、脱敏请求信息和任务状态,不包含凭据和不必要的完整个人数据。
|
| 22 |
+
|
XPostArchiver-clean-upload-20260711-225630/docs/10-开发阶段计划.md
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# 开发阶段计划
|
| 2 |
+
|
| 3 |
+
## 阶段
|
| 4 |
+
|
| 5 |
+
0. Rust 项目初始化:检查 Rust 环境、Cargo 项目、Slint、Tokio、基础依赖、统一错误、脱敏日志、SQLx 迁移草案、文档修订、Cargo 验收和实际窗口运行。
|
| 6 |
+
1. 数据库与首次启动向导:用户选择数据库、新建/打开 SQLite、SQLx 迁移、备份、路径设置、配置文件和无效路径提示。
|
| 7 |
+
2. X API 凭据和账号查询:Windows 凭据管理、Bearer Token 测试、用户名规范化、账号查询、账号确认和 API 错误分类。
|
| 8 |
+
3. 保存一页帖子:获取帖子、解析、保存数据库、唯一去重、本地列表和详情查看。
|
| 9 |
+
4. 分页和断点续传:自动分页、任务状态机、数据库检查点、暂停、继续、停止和软件重启恢复。
|
| 10 |
+
5. 搜索和筛选:关键词搜索、日期筛选、帖子类型筛选、排序、本地分页和大数据量列表优化。
|
| 11 |
+
6. 媒体下载:流式下载、临时文件、重试、校验、目录重新绑定和下载失败记录。
|
| 12 |
+
7. 导出:Excel、CSV、JSON、JSON Lines、Markdown、TXT。
|
| 13 |
+
8. Release 构建:release 编译、Windows 图标、版本资源、独立电脑测试和运行依赖检查。
|
| 14 |
+
9. 安装程序:Inno Setup、自定义安装目录、系统盘提醒、快捷方式、卸载、升级保留配置和用户数据保留。
|
| 15 |
+
|
| 16 |
+
## 每次工作顺序
|
| 17 |
+
|
| 18 |
+
读取 `PROJECT_STATE.md`;检查 Git 状态;检查当前可运行版本;只处理一个阶段;做最少必要修改;运行 Cargo 验收;实际启动;更新状态和变更记录;建立提交。
|
| 19 |
+
|
| 20 |
+
不得因局部错误推倒重写,也不得未经备份使用 `git reset --hard`、`git clean -fd`、清空目录、覆盖数据库等危险操作。
|
| 21 |
+
|
XPostArchiver-clean-upload-20260711-225630/docs/11-后期优化路线.md
ADDED
|
@@ -0,0 +1,155 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# 后期优化路线
|
| 2 |
+
|
| 3 |
+
本文记录暂缓但值得后续继续做的优化。当前软件已经具备本地配置、官方 X API 凭据保存、公开账号查询、采集任务、分页采集、媒体下载、失败写回、归档预览和 Markdown 导出能力。后续优化优先围绕减少手动操作、增强长期运行稳定性和提升导出可用性。
|
| 4 |
+
|
| 5 |
+
## 一、任务操作体验
|
| 6 |
+
|
| 7 |
+
### 1. 真正可点击任务列表
|
| 8 |
+
|
| 9 |
+
当前任务列表是文本展示,并会自动把最新任务 ID 填入输入框。后续可改成可选择列表:
|
| 10 |
+
|
| 11 |
+
- 点击某个任务后自动设置为当前任务。
|
| 12 |
+
- 当前任务用于拉取下一页、自动采集、预览、导出和媒体下载。
|
| 13 |
+
- 任务行显示账号、中文状态、页数、保存数量、失败原因。
|
| 14 |
+
- 失败任务可突出显示,但不要用吓人的警告样式。
|
| 15 |
+
|
| 16 |
+
实现建议:
|
| 17 |
+
|
| 18 |
+
- 优先保持数据库结构不变。
|
| 19 |
+
- 如果 Slint 标准控件不方便做表格,先做简单列表加“选择第 N 个任务”也可以。
|
| 20 |
+
- 不要为了这个功能引入 WebView、Electron、Tauri 或前端框架。
|
| 21 |
+
|
| 22 |
+
### 2. 任务详情区
|
| 23 |
+
|
| 24 |
+
点击任务后显示更清楚的任务详情:
|
| 25 |
+
|
| 26 |
+
- 任务 ID
|
| 27 |
+
- 目标账号
|
| 28 |
+
- 当前状态
|
| 29 |
+
- 已采集页数
|
| 30 |
+
- 收到/保存/更新/重复帖子数量
|
| 31 |
+
- 最近错误
|
| 32 |
+
- 下一页游标是否存在
|
| 33 |
+
- 创建、开始、暂停、完成时间
|
| 34 |
+
|
| 35 |
+
## 二、采集任务长期运行
|
| 36 |
+
|
| 37 |
+
### 1. 暂停和恢复
|
| 38 |
+
|
| 39 |
+
当前有“停止自动采集”,并会写回 `stopped`。后续可以把“停止”细分为:
|
| 40 |
+
|
| 41 |
+
- 暂停:保留分页游标,状态写为 `paused` 或继续使用 `stopped` 但 UI 显示为“已暂停”。
|
| 42 |
+
- 恢复:从 `crawl_checkpoints.pagination_token` 继续采集。
|
| 43 |
+
|
| 44 |
+
注意:如果要新增状态值,必须同步更新 UI 中文状态映射和测试。
|
| 45 |
+
|
| 46 |
+
### 2. 更清楚的运行保护
|
| 47 |
+
|
| 48 |
+
当前已阻止自动采集运行中重复启动第二个自动采集。后续可继续增强:
|
| 49 |
+
|
| 50 |
+
- 切换数据库前检查是否有运行任务。
|
| 51 |
+
- 关闭窗口前提示是否仍有后台采集。
|
| 52 |
+
- 记录自动采集开始和结束日志。
|
| 53 |
+
- 长时间无进度时显示“仍在运行”而不是让用户以为卡住。
|
| 54 |
+
|
| 55 |
+
### 3. 速率限制处理
|
| 56 |
+
|
| 57 |
+
官方 X API 可能返回 429。后续可做:
|
| 58 |
+
|
| 59 |
+
- 识别 429 并显示“达到 X API 频率限制”。
|
| 60 |
+
- 如果响应头包含重置时间,显示大概可继续时间。
|
| 61 |
+
- 不绕过、不并发冲击、不伪造登录状态。
|
| 62 |
+
|
| 63 |
+
## 三、媒体下载
|
| 64 |
+
|
| 65 |
+
### 1. 重试策略细化
|
| 66 |
+
|
| 67 |
+
当前已有“重试失败媒体”入口,会把 `metadata_only` 和 `failed` 状态的媒体纳入下载。后续可继续:
|
| 68 |
+
|
| 69 |
+
- 区分临时失败和永久失败。
|
| 70 |
+
- 记录每个媒体的重试次数。
|
| 71 |
+
- 对 404 或无 URL 的媒体减少重复重试。
|
| 72 |
+
- 显示最近失败媒体列表。
|
| 73 |
+
|
| 74 |
+
如需增加字段,优先新增迁移,不要直接修改历史迁移文件。
|
| 75 |
+
|
| 76 |
+
### 2. 文件校验
|
| 77 |
+
|
| 78 |
+
后续可补:
|
| 79 |
+
|
| 80 |
+
- 下载后记录文件大小。
|
| 81 |
+
- 可选 checksum。
|
| 82 |
+
- 本地文件丢失时重新下载。
|
| 83 |
+
|
| 84 |
+
## 四、归档查看和导出
|
| 85 |
+
|
| 86 |
+
### 1. 导出格式扩展
|
| 87 |
+
|
| 88 |
+
当前支持按任务导出 Markdown 文本索引。后续可扩展:
|
| 89 |
+
|
| 90 |
+
- CSV
|
| 91 |
+
- JSON
|
| 92 |
+
- XLSX
|
| 93 |
+
- 带媒体相对路径的 Markdown
|
| 94 |
+
- 按账号导出
|
| 95 |
+
- 按时间范围导出
|
| 96 |
+
|
| 97 |
+
导出仍应写入用户选择的导出目录,不要默认写入开发目录或 C 盘。
|
| 98 |
+
|
| 99 |
+
### 2. 归档搜索
|
| 100 |
+
|
| 101 |
+
后续可做简单本地搜索:
|
| 102 |
+
|
| 103 |
+
- 按账号
|
| 104 |
+
- 按关键词
|
| 105 |
+
- 按任务
|
| 106 |
+
- 按是否含媒体
|
| 107 |
+
- 按采集时间或 X 发布时间
|
| 108 |
+
|
| 109 |
+
第一版建议直接使用 SQLite 查询,不引入额外搜索引擎。
|
| 110 |
+
|
| 111 |
+
## 五、数据库维护
|
| 112 |
+
|
| 113 |
+
### 1. 恢复备份
|
| 114 |
+
|
| 115 |
+
当前已有检查和备份入口。后续可以加恢复功能:
|
| 116 |
+
|
| 117 |
+
- 恢复前必须再次备份当前数据库。
|
| 118 |
+
- 恢复时不能有运行中的采集任务。
|
| 119 |
+
- 恢复后重新检查数据库完整性。
|
| 120 |
+
|
| 121 |
+
### 2. 数据统计页
|
| 122 |
+
|
| 123 |
+
可以显示:
|
| 124 |
+
|
| 125 |
+
- 总账号数
|
| 126 |
+
- 总任务数
|
| 127 |
+
- 总帖子数
|
| 128 |
+
- 总媒体数
|
| 129 |
+
- 已下载媒体数
|
| 130 |
+
- 失败媒体数
|
| 131 |
+
- 数据库文件大小
|
| 132 |
+
|
| 133 |
+
## 六、打包和安装
|
| 134 |
+
|
| 135 |
+
后续正式发版前需要:
|
| 136 |
+
|
| 137 |
+
- 更新 README 当前状态。
|
| 138 |
+
- 检查安装程序是否不写死开发目录。
|
| 139 |
+
- 确认配置目录、日志目录、数据库目录可由用户选择。
|
| 140 |
+
- 在干净机器或新用户环境测试启动。
|
| 141 |
+
|
| 142 |
+
## 七、优先级建议
|
| 143 |
+
|
| 144 |
+
建议顺序:
|
| 145 |
+
|
| 146 |
+
1. 真正可点击任务列表。
|
| 147 |
+
2. 任务详情区。
|
| 148 |
+
3. 导出 CSV/JSON。
|
| 149 |
+
4. 暂停/恢复语义优化。
|
| 150 |
+
5. 数据库恢复 UI。
|
| 151 |
+
6. 速率限制友好提示。
|
| 152 |
+
7. 归档搜索。
|
| 153 |
+
|
| 154 |
+
每个优化继续保持小步提交:实现、严格验收、窗口确认、更新文档、提交。
|
| 155 |
+
|
XPostArchiver-clean-upload-20260711-225630/migrations/0001_initial.sql
ADDED
|
@@ -0,0 +1,142 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
CREATE TABLE IF NOT EXISTS app_metadata (
|
| 2 |
+
key TEXT PRIMARY KEY NOT NULL,
|
| 3 |
+
value TEXT NOT NULL,
|
| 4 |
+
updated_at TEXT NOT NULL
|
| 5 |
+
);
|
| 6 |
+
|
| 7 |
+
CREATE TABLE IF NOT EXISTS accounts (
|
| 8 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 9 |
+
x_user_id TEXT NOT NULL UNIQUE,
|
| 10 |
+
username TEXT NOT NULL,
|
| 11 |
+
display_name TEXT,
|
| 12 |
+
description TEXT,
|
| 13 |
+
profile_image_url TEXT,
|
| 14 |
+
created_at_x TEXT,
|
| 15 |
+
protected INTEGER,
|
| 16 |
+
verified INTEGER,
|
| 17 |
+
followers_count INTEGER,
|
| 18 |
+
following_count INTEGER,
|
| 19 |
+
post_count INTEGER,
|
| 20 |
+
first_seen_at TEXT NOT NULL,
|
| 21 |
+
last_seen_at TEXT NOT NULL,
|
| 22 |
+
raw_json TEXT
|
| 23 |
+
);
|
| 24 |
+
|
| 25 |
+
CREATE TABLE IF NOT EXISTS posts (
|
| 26 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 27 |
+
x_post_id TEXT NOT NULL UNIQUE,
|
| 28 |
+
author_x_user_id TEXT NOT NULL,
|
| 29 |
+
author_username TEXT,
|
| 30 |
+
author_display_name TEXT,
|
| 31 |
+
text TEXT,
|
| 32 |
+
created_at_x TEXT,
|
| 33 |
+
original_url TEXT,
|
| 34 |
+
language TEXT,
|
| 35 |
+
conversation_id TEXT,
|
| 36 |
+
in_reply_to_user_id TEXT,
|
| 37 |
+
in_reply_to_post_id TEXT,
|
| 38 |
+
quote_target_post_id TEXT,
|
| 39 |
+
repost_source_post_id TEXT,
|
| 40 |
+
post_type TEXT,
|
| 41 |
+
possibly_long_text INTEGER,
|
| 42 |
+
like_count INTEGER,
|
| 43 |
+
reply_count INTEGER,
|
| 44 |
+
repost_count INTEGER,
|
| 45 |
+
quote_count INTEGER,
|
| 46 |
+
bookmark_count INTEGER,
|
| 47 |
+
view_count INTEGER,
|
| 48 |
+
has_media INTEGER NOT NULL DEFAULT 0,
|
| 49 |
+
first_fetched_at TEXT NOT NULL,
|
| 50 |
+
last_fetched_at TEXT NOT NULL,
|
| 51 |
+
source_job_id TEXT,
|
| 52 |
+
raw_json TEXT,
|
| 53 |
+
data_source TEXT
|
| 54 |
+
);
|
| 55 |
+
|
| 56 |
+
CREATE TABLE IF NOT EXISTS post_references (
|
| 57 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 58 |
+
source_post_id TEXT NOT NULL,
|
| 59 |
+
reference_type TEXT NOT NULL,
|
| 60 |
+
target_x_post_id TEXT NOT NULL,
|
| 61 |
+
UNIQUE(source_post_id, reference_type, target_x_post_id)
|
| 62 |
+
);
|
| 63 |
+
|
| 64 |
+
CREATE TABLE IF NOT EXISTS media (
|
| 65 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 66 |
+
media_key TEXT NOT NULL UNIQUE,
|
| 67 |
+
media_type TEXT NOT NULL,
|
| 68 |
+
original_url TEXT,
|
| 69 |
+
preview_url TEXT,
|
| 70 |
+
local_relative_path TEXT,
|
| 71 |
+
mime_type TEXT,
|
| 72 |
+
file_size INTEGER,
|
| 73 |
+
width INTEGER,
|
| 74 |
+
height INTEGER,
|
| 75 |
+
duration_ms INTEGER,
|
| 76 |
+
download_status TEXT NOT NULL,
|
| 77 |
+
downloaded_at TEXT,
|
| 78 |
+
checksum TEXT,
|
| 79 |
+
last_error TEXT,
|
| 80 |
+
raw_json TEXT
|
| 81 |
+
);
|
| 82 |
+
|
| 83 |
+
CREATE TABLE IF NOT EXISTS post_media (
|
| 84 |
+
post_id TEXT NOT NULL,
|
| 85 |
+
media_key TEXT NOT NULL,
|
| 86 |
+
display_order INTEGER NOT NULL,
|
| 87 |
+
PRIMARY KEY (post_id, media_key)
|
| 88 |
+
);
|
| 89 |
+
|
| 90 |
+
CREATE TABLE IF NOT EXISTS crawl_jobs (
|
| 91 |
+
id TEXT PRIMARY KEY NOT NULL,
|
| 92 |
+
target_x_user_id TEXT,
|
| 93 |
+
target_username TEXT NOT NULL,
|
| 94 |
+
task_mode TEXT NOT NULL,
|
| 95 |
+
date_start TEXT,
|
| 96 |
+
date_end TEXT,
|
| 97 |
+
maximum_posts INTEGER,
|
| 98 |
+
include_original INTEGER NOT NULL,
|
| 99 |
+
include_replies INTEGER NOT NULL,
|
| 100 |
+
include_reposts INTEGER NOT NULL,
|
| 101 |
+
include_quotes INTEGER NOT NULL,
|
| 102 |
+
download_media INTEGER NOT NULL,
|
| 103 |
+
status TEXT NOT NULL,
|
| 104 |
+
created_at TEXT NOT NULL,
|
| 105 |
+
started_at TEXT,
|
| 106 |
+
paused_at TEXT,
|
| 107 |
+
finished_at TEXT,
|
| 108 |
+
pages_fetched INTEGER NOT NULL DEFAULT 0,
|
| 109 |
+
posts_received INTEGER NOT NULL DEFAULT 0,
|
| 110 |
+
posts_inserted INTEGER NOT NULL DEFAULT 0,
|
| 111 |
+
posts_updated INTEGER NOT NULL DEFAULT 0,
|
| 112 |
+
posts_duplicated INTEGER NOT NULL DEFAULT 0,
|
| 113 |
+
media_downloaded INTEGER NOT NULL DEFAULT 0,
|
| 114 |
+
error_count INTEGER NOT NULL DEFAULT 0,
|
| 115 |
+
last_error TEXT
|
| 116 |
+
);
|
| 117 |
+
|
| 118 |
+
CREATE TABLE IF NOT EXISTS crawl_checkpoints (
|
| 119 |
+
job_id TEXT PRIMARY KEY NOT NULL,
|
| 120 |
+
pagination_token TEXT,
|
| 121 |
+
oldest_post_id TEXT,
|
| 122 |
+
oldest_post_time TEXT,
|
| 123 |
+
newest_post_id TEXT,
|
| 124 |
+
newest_post_time TEXT,
|
| 125 |
+
last_successful_page INTEGER NOT NULL DEFAULT 0,
|
| 126 |
+
updated_at TEXT NOT NULL
|
| 127 |
+
);
|
| 128 |
+
|
| 129 |
+
CREATE TABLE IF NOT EXISTS fetch_errors (
|
| 130 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 131 |
+
job_id TEXT,
|
| 132 |
+
stage TEXT NOT NULL,
|
| 133 |
+
request_identifier TEXT,
|
| 134 |
+
error_category TEXT NOT NULL,
|
| 135 |
+
http_status INTEGER,
|
| 136 |
+
message TEXT NOT NULL,
|
| 137 |
+
retryable INTEGER NOT NULL,
|
| 138 |
+
retry_count INTEGER NOT NULL DEFAULT 0,
|
| 139 |
+
created_at TEXT NOT NULL,
|
| 140 |
+
resolved_at TEXT
|
| 141 |
+
);
|
| 142 |
+
|
XPostArchiver-clean-upload-20260711-225630/migrations/README.md
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SQLx Migrations
|
| 2 |
+
|
| 3 |
+
数据库迁移文件必须随源码提交。程序打开用户选择的 SQLite 数据库时运行迁移;迁移前必须先备份用户数据库。
|
| 4 |
+
|
XPostArchiver-clean-upload-20260711-225630/src/api/mod.rs
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
|
XPostArchiver-clean-upload-20260711-225630/src/app.rs
ADDED
|
@@ -0,0 +1,824 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
use std::cell::RefCell;
|
| 2 |
+
use std::path::Path;
|
| 3 |
+
use std::rc::Rc;
|
| 4 |
+
use std::sync::{
|
| 5 |
+
Arc,
|
| 6 |
+
atomic::{AtomicBool, Ordering},
|
| 7 |
+
};
|
| 8 |
+
use std::thread;
|
| 9 |
+
use std::time::Duration;
|
| 10 |
+
|
| 11 |
+
use crate::config::settings::{AppSettings, ConfigPathKind};
|
| 12 |
+
use crate::logging::rotation::redact_secret;
|
| 13 |
+
use crate::logging::{LoggingGuard, init_logging};
|
| 14 |
+
use crate::services::account_service::lookup_account;
|
| 15 |
+
use crate::services::archive_export_service::{
|
| 16 |
+
export_posts_for_job_markdown, preview_posts_for_job,
|
| 17 |
+
};
|
| 18 |
+
use crate::services::crawl_task_service::{create_crawl_task, list_recent_crawl_tasks};
|
| 19 |
+
use crate::services::credential_service::{
|
| 20 |
+
bearer_token_status, clear_bearer_token, read_bearer_token, save_bearer_token,
|
| 21 |
+
};
|
| 22 |
+
use crate::services::database_service::{
|
| 23 |
+
backup_current_database, check_current_database, choose_existing_database, create_database,
|
| 24 |
+
};
|
| 25 |
+
use crate::services::media_download_service::{download_pending_media, retry_failed_media};
|
| 26 |
+
use crate::services::path_service::choose_config_directory;
|
| 27 |
+
use crate::services::post_fetch_service::{
|
| 28 |
+
auto_fetch_pages_for_task_owned_async, fetch_one_page_for_task,
|
| 29 |
+
};
|
| 30 |
+
use crate::services::x_api_service::validate_bearer_token;
|
| 31 |
+
use crate::tasks::runtime::BackgroundRuntime;
|
| 32 |
+
|
| 33 |
+
slint::include_modules!();
|
| 34 |
+
|
| 35 |
+
pub struct App {
|
| 36 |
+
_logging: LoggingGuard,
|
| 37 |
+
runtime: Rc<BackgroundRuntime>,
|
| 38 |
+
settings: Rc<RefCell<AppSettings>>,
|
| 39 |
+
}
|
| 40 |
+
|
| 41 |
+
impl App {
|
| 42 |
+
pub fn bootstrap() -> anyhow::Result<Self> {
|
| 43 |
+
let logging = init_logging()?;
|
| 44 |
+
tracing::info!(
|
| 45 |
+
module = "app",
|
| 46 |
+
"{}",
|
| 47 |
+
redact_secret("starting XPostArchiver")
|
| 48 |
+
);
|
| 49 |
+
let runtime = Rc::new(BackgroundRuntime::new()?);
|
| 50 |
+
let settings = Rc::new(RefCell::new(AppSettings::load()?));
|
| 51 |
+
Ok(Self {
|
| 52 |
+
_logging: logging,
|
| 53 |
+
runtime,
|
| 54 |
+
settings,
|
| 55 |
+
})
|
| 56 |
+
}
|
| 57 |
+
|
| 58 |
+
pub fn run(self) -> anyhow::Result<()> {
|
| 59 |
+
let _shutdown_token = self.runtime.cancellation_token();
|
| 60 |
+
let window = AppWindow::new()?;
|
| 61 |
+
load_saved_settings(&window, &self.settings.borrow());
|
| 62 |
+
register_database_callbacks(&window, Rc::clone(&self.runtime), Rc::clone(&self.settings));
|
| 63 |
+
register_path_callbacks(&window, Rc::clone(&self.settings));
|
| 64 |
+
register_media_mode_callbacks(&window, Rc::clone(&self.settings));
|
| 65 |
+
register_credential_callbacks(&window, Rc::clone(&self.runtime));
|
| 66 |
+
register_account_callbacks(&window, Rc::clone(&self.runtime), Rc::clone(&self.settings));
|
| 67 |
+
register_crawl_task_callbacks(&window, Rc::clone(&self.runtime), Rc::clone(&self.settings));
|
| 68 |
+
|
| 69 |
+
window.run()?;
|
| 70 |
+
tracing::info!(module = "app", "application closed");
|
| 71 |
+
Ok(())
|
| 72 |
+
}
|
| 73 |
+
}
|
| 74 |
+
|
| 75 |
+
fn load_saved_settings(window: &AppWindow, settings: &AppSettings) {
|
| 76 |
+
if let Some(path) = settings.last_database_path.as_ref() {
|
| 77 |
+
window.set_database_path(display_path(path).into());
|
| 78 |
+
if path.exists() {
|
| 79 |
+
window.set_status_message("已加载上次数据库路径。".into());
|
| 80 |
+
window.set_database_ready(true);
|
| 81 |
+
} else {
|
| 82 |
+
window.set_status_message(
|
| 83 |
+
"上次使用的数据库当前无法访问。请连接对应磁盘,或重新选择数据库文件。".into(),
|
| 84 |
+
);
|
| 85 |
+
window.set_database_ready(false);
|
| 86 |
+
}
|
| 87 |
+
}
|
| 88 |
+
|
| 89 |
+
set_optional_path(
|
| 90 |
+
window,
|
| 91 |
+
ConfigPathKind::MediaRoot,
|
| 92 |
+
settings.get_path(ConfigPathKind::MediaRoot),
|
| 93 |
+
);
|
| 94 |
+
set_optional_path(
|
| 95 |
+
window,
|
| 96 |
+
ConfigPathKind::ExportDir,
|
| 97 |
+
settings.get_path(ConfigPathKind::ExportDir),
|
| 98 |
+
);
|
| 99 |
+
set_optional_path(
|
| 100 |
+
window,
|
| 101 |
+
ConfigPathKind::LogDir,
|
| 102 |
+
settings.get_path(ConfigPathKind::LogDir),
|
| 103 |
+
);
|
| 104 |
+
set_optional_path(
|
| 105 |
+
window,
|
| 106 |
+
ConfigPathKind::BackupDir,
|
| 107 |
+
settings.get_path(ConfigPathKind::BackupDir),
|
| 108 |
+
);
|
| 109 |
+
set_optional_path(
|
| 110 |
+
window,
|
| 111 |
+
ConfigPathKind::TempDir,
|
| 112 |
+
settings.get_path(ConfigPathKind::TempDir),
|
| 113 |
+
);
|
| 114 |
+
window.set_save_media_files(settings.save_media_files);
|
| 115 |
+
set_credential_status(window);
|
| 116 |
+
}
|
| 117 |
+
|
| 118 |
+
fn register_database_callbacks(
|
| 119 |
+
window: &AppWindow,
|
| 120 |
+
runtime: Rc<BackgroundRuntime>,
|
| 121 |
+
settings: Rc<RefCell<AppSettings>>,
|
| 122 |
+
) {
|
| 123 |
+
{
|
| 124 |
+
let weak_window = window.as_weak();
|
| 125 |
+
let runtime = Rc::clone(&runtime);
|
| 126 |
+
let settings = Rc::clone(&settings);
|
| 127 |
+
window.on_create_database(move || {
|
| 128 |
+
let Some(window) = weak_window.upgrade() else {
|
| 129 |
+
return;
|
| 130 |
+
};
|
| 131 |
+
match create_database(&runtime, &mut settings.borrow_mut()) {
|
| 132 |
+
Ok(Some(result)) => {
|
| 133 |
+
window.set_database_path(display_path(&result.path).into());
|
| 134 |
+
window.set_status_message(result.message.into());
|
| 135 |
+
window.set_database_ready(true);
|
| 136 |
+
}
|
| 137 |
+
Ok(None) => {
|
| 138 |
+
window.set_status_message("已取消新建数据库。".into());
|
| 139 |
+
}
|
| 140 |
+
Err(error) => {
|
| 141 |
+
window.set_status_message(format!("新建数据库失败:{error}").into());
|
| 142 |
+
window.set_database_ready(false);
|
| 143 |
+
}
|
| 144 |
+
}
|
| 145 |
+
});
|
| 146 |
+
}
|
| 147 |
+
|
| 148 |
+
{
|
| 149 |
+
let weak_window = window.as_weak();
|
| 150 |
+
let runtime = Rc::clone(&runtime);
|
| 151 |
+
let settings = Rc::clone(&settings);
|
| 152 |
+
window.on_open_database(move || {
|
| 153 |
+
let Some(window) = weak_window.upgrade() else {
|
| 154 |
+
return;
|
| 155 |
+
};
|
| 156 |
+
match choose_existing_database(&runtime, &mut settings.borrow_mut()) {
|
| 157 |
+
Ok(Some(result)) => {
|
| 158 |
+
window.set_database_path(display_path(&result.path).into());
|
| 159 |
+
window.set_status_message(result.message.into());
|
| 160 |
+
window.set_database_ready(true);
|
| 161 |
+
}
|
| 162 |
+
Ok(None) => {
|
| 163 |
+
window.set_status_message("已取消打开数据库。".into());
|
| 164 |
+
}
|
| 165 |
+
Err(error) => {
|
| 166 |
+
window.set_status_message(format!("打开数据库失败:{error}").into());
|
| 167 |
+
window.set_database_ready(false);
|
| 168 |
+
}
|
| 169 |
+
}
|
| 170 |
+
});
|
| 171 |
+
}
|
| 172 |
+
|
| 173 |
+
{
|
| 174 |
+
let weak_window = window.as_weak();
|
| 175 |
+
let runtime = Rc::clone(&runtime);
|
| 176 |
+
let settings = Rc::clone(&settings);
|
| 177 |
+
window.on_check_database(move || {
|
| 178 |
+
let Some(window) = weak_window.upgrade() else {
|
| 179 |
+
return;
|
| 180 |
+
};
|
| 181 |
+
match check_current_database(&runtime, &settings.borrow()) {
|
| 182 |
+
Ok(result) => {
|
| 183 |
+
window.set_status_message(result.message.into());
|
| 184 |
+
}
|
| 185 |
+
Err(error) => {
|
| 186 |
+
window.set_status_message(format!("检查数据库失败:{error}").into());
|
| 187 |
+
}
|
| 188 |
+
}
|
| 189 |
+
});
|
| 190 |
+
}
|
| 191 |
+
|
| 192 |
+
{
|
| 193 |
+
let weak_window = window.as_weak();
|
| 194 |
+
let settings = Rc::clone(&settings);
|
| 195 |
+
window.on_backup_database(move || {
|
| 196 |
+
let Some(window) = weak_window.upgrade() else {
|
| 197 |
+
return;
|
| 198 |
+
};
|
| 199 |
+
match backup_current_database(&settings.borrow()) {
|
| 200 |
+
Ok(result) => {
|
| 201 |
+
window.set_status_message(result.message.into());
|
| 202 |
+
}
|
| 203 |
+
Err(error) => {
|
| 204 |
+
window.set_status_message(format!("备份数据库失败:{error}").into());
|
| 205 |
+
}
|
| 206 |
+
}
|
| 207 |
+
});
|
| 208 |
+
}
|
| 209 |
+
}
|
| 210 |
+
|
| 211 |
+
fn register_path_callbacks(window: &AppWindow, settings: Rc<RefCell<AppSettings>>) {
|
| 212 |
+
register_one_path_callback(window, Rc::clone(&settings), ConfigPathKind::MediaRoot);
|
| 213 |
+
register_one_path_callback(window, Rc::clone(&settings), ConfigPathKind::ExportDir);
|
| 214 |
+
register_one_path_callback(window, Rc::clone(&settings), ConfigPathKind::LogDir);
|
| 215 |
+
register_one_path_callback(window, Rc::clone(&settings), ConfigPathKind::BackupDir);
|
| 216 |
+
register_one_path_callback(window, settings, ConfigPathKind::TempDir);
|
| 217 |
+
}
|
| 218 |
+
|
| 219 |
+
fn register_one_path_callback(
|
| 220 |
+
window: &AppWindow,
|
| 221 |
+
settings: Rc<RefCell<AppSettings>>,
|
| 222 |
+
kind: ConfigPathKind,
|
| 223 |
+
) {
|
| 224 |
+
let weak_window = window.as_weak();
|
| 225 |
+
let callback = move || {
|
| 226 |
+
let Some(window) = weak_window.upgrade() else {
|
| 227 |
+
return;
|
| 228 |
+
};
|
| 229 |
+
match choose_config_directory(kind, &mut settings.borrow_mut()) {
|
| 230 |
+
Ok(Some(result)) => {
|
| 231 |
+
set_optional_path(&window, result.kind, Some(&result.path));
|
| 232 |
+
window.set_status_message(result.message.into());
|
| 233 |
+
}
|
| 234 |
+
Ok(None) => {
|
| 235 |
+
window.set_status_message(format!("已取消设置{}。", kind.label()).into());
|
| 236 |
+
}
|
| 237 |
+
Err(error) => {
|
| 238 |
+
window.set_status_message(format!("设置{}失败:{error}", kind.label()).into());
|
| 239 |
+
}
|
| 240 |
+
}
|
| 241 |
+
};
|
| 242 |
+
|
| 243 |
+
match kind {
|
| 244 |
+
ConfigPathKind::MediaRoot => window.on_choose_media_root(callback),
|
| 245 |
+
ConfigPathKind::ExportDir => window.on_choose_export_dir(callback),
|
| 246 |
+
ConfigPathKind::LogDir => window.on_choose_log_dir(callback),
|
| 247 |
+
ConfigPathKind::BackupDir => window.on_choose_backup_dir(callback),
|
| 248 |
+
ConfigPathKind::TempDir => window.on_choose_temp_dir(callback),
|
| 249 |
+
}
|
| 250 |
+
}
|
| 251 |
+
|
| 252 |
+
fn register_account_callbacks(
|
| 253 |
+
window: &AppWindow,
|
| 254 |
+
runtime: Rc<BackgroundRuntime>,
|
| 255 |
+
settings: Rc<RefCell<AppSettings>>,
|
| 256 |
+
) {
|
| 257 |
+
let weak_window = window.as_weak();
|
| 258 |
+
window.on_lookup_account(move |username| {
|
| 259 |
+
let Some(window) = weak_window.upgrade() else {
|
| 260 |
+
return;
|
| 261 |
+
};
|
| 262 |
+
let Some(database_path) = settings.borrow().last_database_path.clone() else {
|
| 263 |
+
window.set_account_status("请先选择或新建数据库。".into());
|
| 264 |
+
return;
|
| 265 |
+
};
|
| 266 |
+
match lookup_account(&runtime, &database_path, username.as_str()) {
|
| 267 |
+
Ok(result) => {
|
| 268 |
+
let display_name = result
|
| 269 |
+
.display_name
|
| 270 |
+
.unwrap_or_else(|| "未提供显示名".to_owned());
|
| 271 |
+
window.set_account_status(
|
| 272 |
+
format!(
|
| 273 |
+
"{} 显示名:{} 用户名:@{}",
|
| 274 |
+
result.message, display_name, result.username
|
| 275 |
+
)
|
| 276 |
+
.into(),
|
| 277 |
+
);
|
| 278 |
+
}
|
| 279 |
+
Err(error) => {
|
| 280 |
+
window.set_account_status(format!("查询账号失败:{error}").into());
|
| 281 |
+
}
|
| 282 |
+
}
|
| 283 |
+
});
|
| 284 |
+
}
|
| 285 |
+
|
| 286 |
+
fn register_crawl_task_callbacks(
|
| 287 |
+
window: &AppWindow,
|
| 288 |
+
runtime: Rc<BackgroundRuntime>,
|
| 289 |
+
settings: Rc<RefCell<AppSettings>>,
|
| 290 |
+
) {
|
| 291 |
+
let auto_stop_signal: Rc<RefCell<Option<Arc<AtomicBool>>>> = Rc::new(RefCell::new(None));
|
| 292 |
+
let auto_running = Arc::new(AtomicBool::new(false));
|
| 293 |
+
|
| 294 |
+
let weak_window = window.as_weak();
|
| 295 |
+
let create_runtime = Rc::clone(&runtime);
|
| 296 |
+
let create_settings = Rc::clone(&settings);
|
| 297 |
+
window.on_create_crawl_task(move |username| {
|
| 298 |
+
let Some(window) = weak_window.upgrade() else {
|
| 299 |
+
return;
|
| 300 |
+
};
|
| 301 |
+
let settings_ref = create_settings.borrow();
|
| 302 |
+
let Some(database_path) = settings_ref.last_database_path.as_ref() else {
|
| 303 |
+
window.set_crawl_task_status("请先选择或新建数据库。".into());
|
| 304 |
+
return;
|
| 305 |
+
};
|
| 306 |
+
match create_runtime.block_on(create_crawl_task(
|
| 307 |
+
database_path,
|
| 308 |
+
username.as_str(),
|
| 309 |
+
&settings_ref,
|
| 310 |
+
)) {
|
| 311 |
+
Ok(Ok(result)) => {
|
| 312 |
+
window.set_selected_job_id(result.job_id.clone().into());
|
| 313 |
+
window.set_crawl_task_status(
|
| 314 |
+
format!("{} 任务ID:{}", result.message, result.job_id).into(),
|
| 315 |
+
);
|
| 316 |
+
}
|
| 317 |
+
Ok(Err(error)) | Err(error) => {
|
| 318 |
+
window.set_crawl_task_status(format!("创建采集任务失败:{error}").into());
|
| 319 |
+
}
|
| 320 |
+
}
|
| 321 |
+
});
|
| 322 |
+
|
| 323 |
+
let weak_window = window.as_weak();
|
| 324 |
+
let list_runtime = Rc::clone(&runtime);
|
| 325 |
+
let list_settings = Rc::clone(&settings);
|
| 326 |
+
window.on_refresh_crawl_tasks(move || {
|
| 327 |
+
let Some(window) = weak_window.upgrade() else {
|
| 328 |
+
return;
|
| 329 |
+
};
|
| 330 |
+
let settings_ref = list_settings.borrow();
|
| 331 |
+
let Some(database_path) = settings_ref.last_database_path.as_ref() else {
|
| 332 |
+
window.set_crawl_task_list("请先选择或新建数据库。".into());
|
| 333 |
+
return;
|
| 334 |
+
};
|
| 335 |
+
match list_runtime.block_on(list_recent_crawl_tasks(database_path, 8)) {
|
| 336 |
+
Ok(Ok(tasks)) => {
|
| 337 |
+
if tasks.is_empty() {
|
| 338 |
+
window.set_crawl_task_list("当前数据库还没有采集任务。".into());
|
| 339 |
+
} else {
|
| 340 |
+
if let Some(first_task) = tasks.first() {
|
| 341 |
+
window.set_selected_job_id(first_task.job_id.clone().into());
|
| 342 |
+
}
|
| 343 |
+
let lines = tasks
|
| 344 |
+
.iter()
|
| 345 |
+
.map(|task| {
|
| 346 |
+
let error_suffix = task
|
| 347 |
+
.last_error
|
| 348 |
+
.as_ref()
|
| 349 |
+
.map(|error| format!(" 错误:{}", error))
|
| 350 |
+
.unwrap_or_default();
|
| 351 |
+
format!(
|
| 352 |
+
"{} @{} 状态:{} 页:{} 收到:{} 保存:{} 创建:{}{}",
|
| 353 |
+
task.job_id,
|
| 354 |
+
task.username,
|
| 355 |
+
crawl_status_label(&task.status),
|
| 356 |
+
task.pages_fetched,
|
| 357 |
+
task.posts_received,
|
| 358 |
+
task.posts_inserted,
|
| 359 |
+
task.created_at,
|
| 360 |
+
error_suffix
|
| 361 |
+
)
|
| 362 |
+
})
|
| 363 |
+
.collect::<Vec<_>>()
|
| 364 |
+
.join("\n");
|
| 365 |
+
window.set_crawl_task_list(lines.into());
|
| 366 |
+
}
|
| 367 |
+
}
|
| 368 |
+
Ok(Err(error)) | Err(error) => {
|
| 369 |
+
window.set_crawl_task_list(format!("刷新任务列表失败:{error}").into());
|
| 370 |
+
}
|
| 371 |
+
}
|
| 372 |
+
});
|
| 373 |
+
|
| 374 |
+
let weak_window = window.as_weak();
|
| 375 |
+
let fetch_runtime = Rc::clone(&runtime);
|
| 376 |
+
let fetch_settings = Rc::clone(&settings);
|
| 377 |
+
window.on_fetch_one_page(move |job_id| {
|
| 378 |
+
let Some(window) = weak_window.upgrade() else {
|
| 379 |
+
return;
|
| 380 |
+
};
|
| 381 |
+
let settings_ref = fetch_settings.borrow();
|
| 382 |
+
let Some(database_path) = settings_ref.last_database_path.as_ref() else {
|
| 383 |
+
window.set_fetch_status("请先选择或新建数据库。".into());
|
| 384 |
+
return;
|
| 385 |
+
};
|
| 386 |
+
match fetch_one_page_for_task(&fetch_runtime, database_path, job_id.as_str()) {
|
| 387 |
+
Ok(result) => window.set_fetch_status(
|
| 388 |
+
format!(
|
| 389 |
+
"{} 收到:{} 保存:{} 媒体:{} 状态:{}",
|
| 390 |
+
result.message,
|
| 391 |
+
result.received,
|
| 392 |
+
result.saved,
|
| 393 |
+
result.media_saved,
|
| 394 |
+
if result.has_next_page {
|
| 395 |
+
"可继续"
|
| 396 |
+
} else {
|
| 397 |
+
"已完成"
|
| 398 |
+
}
|
| 399 |
+
)
|
| 400 |
+
.into(),
|
| 401 |
+
),
|
| 402 |
+
Err(error) => window.set_fetch_status(format!("拉取帖子失败:{error}").into()),
|
| 403 |
+
}
|
| 404 |
+
});
|
| 405 |
+
|
| 406 |
+
let weak_window = window.as_weak();
|
| 407 |
+
let auto_settings = Rc::clone(&settings);
|
| 408 |
+
let auto_stop_signal_for_start = Rc::clone(&auto_stop_signal);
|
| 409 |
+
let auto_running_for_start = Arc::clone(&auto_running);
|
| 410 |
+
window.on_auto_fetch_pages(move |job_id, page_limit, delay_seconds| {
|
| 411 |
+
let Some(window) = weak_window.upgrade() else {
|
| 412 |
+
return;
|
| 413 |
+
};
|
| 414 |
+
let settings_ref = auto_settings.borrow();
|
| 415 |
+
let Some(database_path) = settings_ref.last_database_path.as_ref().cloned() else {
|
| 416 |
+
window.set_auto_crawl_status("请先选择或新建数据库。".into());
|
| 417 |
+
return;
|
| 418 |
+
};
|
| 419 |
+
let token = match read_bearer_token() {
|
| 420 |
+
Ok(Some(token)) => token,
|
| 421 |
+
Ok(None) => {
|
| 422 |
+
window.set_auto_crawl_status("请先保存 X API Bearer Token。".into());
|
| 423 |
+
return;
|
| 424 |
+
}
|
| 425 |
+
Err(error) => {
|
| 426 |
+
window.set_auto_crawl_status(format!("读取系统密钥库失败:{error}").into());
|
| 427 |
+
return;
|
| 428 |
+
}
|
| 429 |
+
};
|
| 430 |
+
let page_limit = match page_limit.trim().parse::<usize>() {
|
| 431 |
+
Ok(value) => value,
|
| 432 |
+
Err(_) => {
|
| 433 |
+
window
|
| 434 |
+
.set_auto_crawl_status("页数上限请输入数字;0 表示直到末页或手动停止。".into());
|
| 435 |
+
return;
|
| 436 |
+
}
|
| 437 |
+
};
|
| 438 |
+
let delay_seconds = match delay_seconds.trim().parse::<u64>() {
|
| 439 |
+
Ok(value) => value,
|
| 440 |
+
Err(_) => {
|
| 441 |
+
window.set_auto_crawl_status("每页等待秒数请输入数字。".into());
|
| 442 |
+
return;
|
| 443 |
+
}
|
| 444 |
+
};
|
| 445 |
+
let job_id = job_id.to_string();
|
| 446 |
+
if job_id.trim().is_empty() {
|
| 447 |
+
window.set_auto_crawl_status("请先填写任务 ID。".into());
|
| 448 |
+
return;
|
| 449 |
+
}
|
| 450 |
+
if auto_running_for_start.swap(true, Ordering::Relaxed) {
|
| 451 |
+
window.set_auto_crawl_status("已有自动采集正在运行,请先停止或等待完成。".into());
|
| 452 |
+
return;
|
| 453 |
+
}
|
| 454 |
+
let completion_window = weak_window.clone();
|
| 455 |
+
let running_signal = Arc::clone(&auto_running_for_start);
|
| 456 |
+
let stop_requested = Arc::new(AtomicBool::new(false));
|
| 457 |
+
*auto_stop_signal_for_start.borrow_mut() = Some(Arc::clone(&stop_requested));
|
| 458 |
+
window.set_auto_crawl_status(
|
| 459 |
+
format!(
|
| 460 |
+
"自动采集已在后台启动;页数上限:{};每页等待:{} 秒。",
|
| 461 |
+
if page_limit == 0 {
|
| 462 |
+
"直到末页或手动停止".to_owned()
|
| 463 |
+
} else {
|
| 464 |
+
page_limit.to_string()
|
| 465 |
+
},
|
| 466 |
+
delay_seconds
|
| 467 |
+
)
|
| 468 |
+
.into(),
|
| 469 |
+
);
|
| 470 |
+
thread::spawn(move || {
|
| 471 |
+
let result = tokio::runtime::Builder::new_current_thread()
|
| 472 |
+
.enable_all()
|
| 473 |
+
.build()
|
| 474 |
+
.map_err(anyhow::Error::from)
|
| 475 |
+
.and_then(|runtime| {
|
| 476 |
+
runtime.block_on(auto_fetch_pages_for_task_owned_async(
|
| 477 |
+
database_path,
|
| 478 |
+
job_id,
|
| 479 |
+
token,
|
| 480 |
+
page_limit,
|
| 481 |
+
Duration::from_secs(delay_seconds),
|
| 482 |
+
stop_requested,
|
| 483 |
+
))
|
| 484 |
+
});
|
| 485 |
+
let message = match result {
|
| 486 |
+
Ok(result) => format!(
|
| 487 |
+
"{} 页数:{} 收到:{} 保存:{} 媒体:{} 状态:{}",
|
| 488 |
+
result.message,
|
| 489 |
+
result.pages_fetched,
|
| 490 |
+
result.posts_received,
|
| 491 |
+
result.posts_saved,
|
| 492 |
+
result.media_saved,
|
| 493 |
+
if result.stopped_by_request {
|
| 494 |
+
"已停止"
|
| 495 |
+
} else if result.stopped_because_complete {
|
| 496 |
+
"已完成"
|
| 497 |
+
} else {
|
| 498 |
+
"可继续"
|
| 499 |
+
}
|
| 500 |
+
),
|
| 501 |
+
Err(error) => format!("自动采集失败:{error}"),
|
| 502 |
+
};
|
| 503 |
+
running_signal.store(false, Ordering::Relaxed);
|
| 504 |
+
let _ = slint::invoke_from_event_loop(move || {
|
| 505 |
+
if let Some(window) = completion_window.upgrade() {
|
| 506 |
+
window.set_auto_crawl_status(message.into());
|
| 507 |
+
}
|
| 508 |
+
});
|
| 509 |
+
});
|
| 510 |
+
});
|
| 511 |
+
|
| 512 |
+
let weak_window = window.as_weak();
|
| 513 |
+
let auto_stop_signal_for_stop = Rc::clone(&auto_stop_signal);
|
| 514 |
+
window.on_stop_auto_crawl(move || {
|
| 515 |
+
let Some(window) = weak_window.upgrade() else {
|
| 516 |
+
return;
|
| 517 |
+
};
|
| 518 |
+
if let Some(stop_requested) = auto_stop_signal_for_stop.borrow().as_ref() {
|
| 519 |
+
stop_requested.store(true, Ordering::Relaxed);
|
| 520 |
+
window.set_auto_crawl_status("已请求停止自动采集;当前页完成后会停下。".into());
|
| 521 |
+
} else {
|
| 522 |
+
window.set_auto_crawl_status("当前没有正在运行的自动采集。".into());
|
| 523 |
+
}
|
| 524 |
+
});
|
| 525 |
+
|
| 526 |
+
let weak_window = window.as_weak();
|
| 527 |
+
let preview_runtime = Rc::clone(&runtime);
|
| 528 |
+
let preview_settings = Rc::clone(&settings);
|
| 529 |
+
window.on_preview_archive(move |job_id| {
|
| 530 |
+
let Some(window) = weak_window.upgrade() else {
|
| 531 |
+
return;
|
| 532 |
+
};
|
| 533 |
+
let settings_ref = preview_settings.borrow();
|
| 534 |
+
let Some(database_path) = settings_ref.last_database_path.as_ref() else {
|
| 535 |
+
window.set_archive_preview("请先选择或新建数据库。".into());
|
| 536 |
+
return;
|
| 537 |
+
};
|
| 538 |
+
match preview_runtime.block_on(preview_posts_for_job(database_path, job_id.as_str(), 5)) {
|
| 539 |
+
Ok(Ok(result)) => {
|
| 540 |
+
if result.posts.is_empty() {
|
| 541 |
+
window.set_archive_preview("这个任务还没有已保存帖子。".into());
|
| 542 |
+
} else {
|
| 543 |
+
let lines = result
|
| 544 |
+
.posts
|
| 545 |
+
.iter()
|
| 546 |
+
.map(|post| {
|
| 547 |
+
format!(
|
| 548 |
+
"{} @{} {}\n{}",
|
| 549 |
+
post.x_post_id,
|
| 550 |
+
post.author_username.as_deref().unwrap_or("未知账号"),
|
| 551 |
+
post.created_at_x.as_deref().unwrap_or("未知时间"),
|
| 552 |
+
post.text.as_deref().unwrap_or("")
|
| 553 |
+
)
|
| 554 |
+
})
|
| 555 |
+
.collect::<Vec<_>>()
|
| 556 |
+
.join("\n---\n");
|
| 557 |
+
window.set_archive_preview(format!("{}\n{}", result.message, lines).into());
|
| 558 |
+
}
|
| 559 |
+
}
|
| 560 |
+
Ok(Err(error)) | Err(error) => {
|
| 561 |
+
window.set_archive_preview(format!("预览归档失败:{error}").into());
|
| 562 |
+
}
|
| 563 |
+
}
|
| 564 |
+
});
|
| 565 |
+
|
| 566 |
+
let weak_window = window.as_weak();
|
| 567 |
+
let export_runtime = Rc::clone(&runtime);
|
| 568 |
+
let export_settings = Rc::clone(&settings);
|
| 569 |
+
window.on_export_archive(move |job_id| {
|
| 570 |
+
let Some(window) = weak_window.upgrade() else {
|
| 571 |
+
return;
|
| 572 |
+
};
|
| 573 |
+
let settings_ref = export_settings.borrow();
|
| 574 |
+
let Some(database_path) = settings_ref.last_database_path.as_ref() else {
|
| 575 |
+
window.set_archive_preview("请先选择或新建数据库。".into());
|
| 576 |
+
return;
|
| 577 |
+
};
|
| 578 |
+
let Some(export_dir) = settings_ref.export_dir.as_ref() else {
|
| 579 |
+
window.set_archive_preview("请先选择导出目录。".into());
|
| 580 |
+
return;
|
| 581 |
+
};
|
| 582 |
+
match export_runtime.block_on(export_posts_for_job_markdown(
|
| 583 |
+
database_path,
|
| 584 |
+
export_dir,
|
| 585 |
+
job_id.as_str(),
|
| 586 |
+
)) {
|
| 587 |
+
Ok(Ok(result)) => window.set_archive_preview(
|
| 588 |
+
format!(
|
| 589 |
+
"{} 文件:{} 帖子数:{}",
|
| 590 |
+
result.message,
|
| 591 |
+
result.path.display(),
|
| 592 |
+
result.post_count
|
| 593 |
+
)
|
| 594 |
+
.into(),
|
| 595 |
+
),
|
| 596 |
+
Ok(Err(error)) | Err(error) => {
|
| 597 |
+
window.set_archive_preview(format!("导出归档失败:{error}").into());
|
| 598 |
+
}
|
| 599 |
+
}
|
| 600 |
+
});
|
| 601 |
+
|
| 602 |
+
let weak_window = window.as_weak();
|
| 603 |
+
let download_runtime = Rc::clone(&runtime);
|
| 604 |
+
let download_settings = Rc::clone(&settings);
|
| 605 |
+
window.on_download_media(move || {
|
| 606 |
+
let Some(window) = weak_window.upgrade() else {
|
| 607 |
+
return;
|
| 608 |
+
};
|
| 609 |
+
let settings_ref = download_settings.borrow();
|
| 610 |
+
let Some(database_path) = settings_ref.last_database_path.as_ref() else {
|
| 611 |
+
window.set_media_download_status("请先选择或新建数据库。".into());
|
| 612 |
+
return;
|
| 613 |
+
};
|
| 614 |
+
let Some(archive_root) = settings_ref.media_root.as_ref() else {
|
| 615 |
+
window.set_media_download_status("请先选择归档内容目录。".into());
|
| 616 |
+
return;
|
| 617 |
+
};
|
| 618 |
+
if !settings_ref.save_media_files {
|
| 619 |
+
window.set_media_download_status("当前设置为只保存文本,已跳过媒体文件下载。".into());
|
| 620 |
+
return;
|
| 621 |
+
}
|
| 622 |
+
match download_pending_media(&download_runtime, database_path, archive_root, 20) {
|
| 623 |
+
Ok(result) => window.set_media_download_status(
|
| 624 |
+
format!(
|
| 625 |
+
"{} 尝试:{} 成功:{} 跳过:{} 失败:{}",
|
| 626 |
+
result.message,
|
| 627 |
+
result.attempted,
|
| 628 |
+
result.downloaded,
|
| 629 |
+
result.skipped,
|
| 630 |
+
result.failed
|
| 631 |
+
)
|
| 632 |
+
.into(),
|
| 633 |
+
),
|
| 634 |
+
Err(error) => window.set_media_download_status(format!("下载媒体失败:{error}").into()),
|
| 635 |
+
}
|
| 636 |
+
});
|
| 637 |
+
|
| 638 |
+
let weak_window = window.as_weak();
|
| 639 |
+
let retry_runtime = Rc::clone(&runtime);
|
| 640 |
+
let retry_settings = Rc::clone(&settings);
|
| 641 |
+
window.on_retry_failed_media(move || {
|
| 642 |
+
let Some(window) = weak_window.upgrade() else {
|
| 643 |
+
return;
|
| 644 |
+
};
|
| 645 |
+
let settings_ref = retry_settings.borrow();
|
| 646 |
+
let Some(database_path) = settings_ref.last_database_path.as_ref() else {
|
| 647 |
+
window.set_media_download_status("请先选择或新建数据库。".into());
|
| 648 |
+
return;
|
| 649 |
+
};
|
| 650 |
+
let Some(archive_root) = settings_ref.media_root.as_ref() else {
|
| 651 |
+
window.set_media_download_status("请先选择归档内容目录。".into());
|
| 652 |
+
return;
|
| 653 |
+
};
|
| 654 |
+
if !settings_ref.save_media_files {
|
| 655 |
+
window.set_media_download_status("当前设置为只保存文本,已跳过媒体文件下载。".into());
|
| 656 |
+
return;
|
| 657 |
+
}
|
| 658 |
+
match retry_failed_media(&retry_runtime, database_path, archive_root, 20) {
|
| 659 |
+
Ok(result) => window.set_media_download_status(
|
| 660 |
+
format!(
|
| 661 |
+
"{} 尝试:{} 成功:{} 跳过:{} 失败:{}",
|
| 662 |
+
result.message,
|
| 663 |
+
result.attempted,
|
| 664 |
+
result.downloaded,
|
| 665 |
+
result.skipped,
|
| 666 |
+
result.failed
|
| 667 |
+
)
|
| 668 |
+
.into(),
|
| 669 |
+
),
|
| 670 |
+
Err(error) => {
|
| 671 |
+
window.set_media_download_status(format!("重试失败媒体失败:{error}").into());
|
| 672 |
+
}
|
| 673 |
+
}
|
| 674 |
+
});
|
| 675 |
+
}
|
| 676 |
+
|
| 677 |
+
fn register_credential_callbacks(window: &AppWindow, runtime: Rc<BackgroundRuntime>) {
|
| 678 |
+
{
|
| 679 |
+
let weak_window = window.as_weak();
|
| 680 |
+
window.on_save_bearer_token(move |token| {
|
| 681 |
+
let Some(window) = weak_window.upgrade() else {
|
| 682 |
+
return;
|
| 683 |
+
};
|
| 684 |
+
match save_bearer_token(token.as_str()) {
|
| 685 |
+
Ok(status) => apply_credential_status(&window, status),
|
| 686 |
+
Err(error) => {
|
| 687 |
+
window.set_credentials_ready(false);
|
| 688 |
+
window.set_credential_status(format!("保存凭据失败:{error}").into());
|
| 689 |
+
}
|
| 690 |
+
}
|
| 691 |
+
});
|
| 692 |
+
}
|
| 693 |
+
|
| 694 |
+
{
|
| 695 |
+
let weak_window = window.as_weak();
|
| 696 |
+
let runtime = Rc::clone(&runtime);
|
| 697 |
+
window.on_validate_bearer_token(move || {
|
| 698 |
+
let Some(window) = weak_window.upgrade() else {
|
| 699 |
+
return;
|
| 700 |
+
};
|
| 701 |
+
match read_bearer_token() {
|
| 702 |
+
Ok(Some(token)) => match runtime.block_on(validate_bearer_token(&token)) {
|
| 703 |
+
Ok(Ok(result)) => {
|
| 704 |
+
window.set_credentials_ready(result.valid);
|
| 705 |
+
window.set_credential_status(result.message.into());
|
| 706 |
+
}
|
| 707 |
+
Ok(Err(error)) | Err(error) => {
|
| 708 |
+
window.set_credentials_ready(false);
|
| 709 |
+
window.set_credential_status(format!("检查凭据失败:{error}").into());
|
| 710 |
+
}
|
| 711 |
+
},
|
| 712 |
+
Ok(None) => {
|
| 713 |
+
window.set_credentials_ready(false);
|
| 714 |
+
window.set_credential_status("请先保存 X API Bearer Token。".into());
|
| 715 |
+
}
|
| 716 |
+
Err(error) => {
|
| 717 |
+
window.set_credentials_ready(false);
|
| 718 |
+
window.set_credential_status(format!("读取系统密钥库失败:{error}").into());
|
| 719 |
+
}
|
| 720 |
+
}
|
| 721 |
+
});
|
| 722 |
+
}
|
| 723 |
+
|
| 724 |
+
{
|
| 725 |
+
let weak_window = window.as_weak();
|
| 726 |
+
window.on_clear_bearer_token(move || {
|
| 727 |
+
let Some(window) = weak_window.upgrade() else {
|
| 728 |
+
return;
|
| 729 |
+
};
|
| 730 |
+
match clear_bearer_token() {
|
| 731 |
+
Ok(status) => apply_credential_status(&window, status),
|
| 732 |
+
Err(error) => {
|
| 733 |
+
window.set_credentials_ready(false);
|
| 734 |
+
window.set_credential_status(format!("清除凭据失败:{error}").into());
|
| 735 |
+
}
|
| 736 |
+
}
|
| 737 |
+
});
|
| 738 |
+
}
|
| 739 |
+
}
|
| 740 |
+
|
| 741 |
+
fn set_credential_status(window: &AppWindow) {
|
| 742 |
+
apply_credential_status(window, bearer_token_status());
|
| 743 |
+
}
|
| 744 |
+
|
| 745 |
+
fn apply_credential_status(
|
| 746 |
+
window: &AppWindow,
|
| 747 |
+
status: crate::services::credential_service::CredentialStatus,
|
| 748 |
+
) {
|
| 749 |
+
window.set_credentials_ready(status.configured);
|
| 750 |
+
window.set_credential_status(status.message.into());
|
| 751 |
+
}
|
| 752 |
+
|
| 753 |
+
fn register_media_mode_callbacks(window: &AppWindow, settings: Rc<RefCell<AppSettings>>) {
|
| 754 |
+
{
|
| 755 |
+
let weak_window = window.as_weak();
|
| 756 |
+
let settings = Rc::clone(&settings);
|
| 757 |
+
window.on_enable_media_files(move || {
|
| 758 |
+
let Some(window) = weak_window.upgrade() else {
|
| 759 |
+
return;
|
| 760 |
+
};
|
| 761 |
+
let mut settings = settings.borrow_mut();
|
| 762 |
+
settings.save_media_files = true;
|
| 763 |
+
match settings.save() {
|
| 764 |
+
Ok(()) => {
|
| 765 |
+
window.set_save_media_files(true);
|
| 766 |
+
window.set_status_message("已设置为保存文本和媒体文件。".into());
|
| 767 |
+
}
|
| 768 |
+
Err(error) => {
|
| 769 |
+
window.set_status_message(format!("保存媒体设置失败:{error}").into());
|
| 770 |
+
}
|
| 771 |
+
}
|
| 772 |
+
});
|
| 773 |
+
}
|
| 774 |
+
|
| 775 |
+
{
|
| 776 |
+
let weak_window = window.as_weak();
|
| 777 |
+
window.on_disable_media_files(move || {
|
| 778 |
+
let Some(window) = weak_window.upgrade() else {
|
| 779 |
+
return;
|
| 780 |
+
};
|
| 781 |
+
let mut settings = settings.borrow_mut();
|
| 782 |
+
settings.save_media_files = false;
|
| 783 |
+
match settings.save() {
|
| 784 |
+
Ok(()) => {
|
| 785 |
+
window.set_save_media_files(false);
|
| 786 |
+
window.set_status_message("已设置为只保存文本和媒体链接信息。".into());
|
| 787 |
+
}
|
| 788 |
+
Err(error) => {
|
| 789 |
+
window.set_status_message(format!("保存媒体设置失败:{error}").into());
|
| 790 |
+
}
|
| 791 |
+
}
|
| 792 |
+
});
|
| 793 |
+
}
|
| 794 |
+
}
|
| 795 |
+
|
| 796 |
+
fn set_optional_path(window: &AppWindow, kind: ConfigPathKind, path: Option<&Path>) {
|
| 797 |
+
let value = path
|
| 798 |
+
.map(display_path)
|
| 799 |
+
.unwrap_or_else(|| "未设置".to_owned());
|
| 800 |
+
match kind {
|
| 801 |
+
ConfigPathKind::MediaRoot => window.set_media_root(value.into()),
|
| 802 |
+
ConfigPathKind::ExportDir => window.set_export_dir(value.into()),
|
| 803 |
+
ConfigPathKind::LogDir => window.set_log_dir(value.into()),
|
| 804 |
+
ConfigPathKind::BackupDir => window.set_backup_dir(value.into()),
|
| 805 |
+
ConfigPathKind::TempDir => window.set_temp_dir(value.into()),
|
| 806 |
+
}
|
| 807 |
+
}
|
| 808 |
+
|
| 809 |
+
fn crawl_status_label(status: &str) -> &'static str {
|
| 810 |
+
match status {
|
| 811 |
+
"created" => "已创建",
|
| 812 |
+
"running" => "正在采集",
|
| 813 |
+
"page_fetched" => "可继续",
|
| 814 |
+
"completed" => "已完成",
|
| 815 |
+
"stopped" => "已停止",
|
| 816 |
+
"failed" => "失败",
|
| 817 |
+
_ => "未知",
|
| 818 |
+
}
|
| 819 |
+
}
|
| 820 |
+
|
| 821 |
+
fn display_path(path: &Path) -> String {
|
| 822 |
+
path.display().to_string()
|
| 823 |
+
}
|
| 824 |
+
|
XPostArchiver-clean-upload-20260711-225630/src/config/mod.rs
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
pub mod paths;
|
| 2 |
+
pub mod settings;
|
| 3 |
+
|
XPostArchiver-clean-upload-20260711-225630/src/config/paths.rs
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
use std::path::PathBuf;
|
| 2 |
+
|
| 3 |
+
use directories::ProjectDirs;
|
| 4 |
+
|
| 5 |
+
pub fn project_dirs() -> anyhow::Result<ProjectDirs> {
|
| 6 |
+
ProjectDirs::from("cn", "XPostArchiver", "XPostArchiver")
|
| 7 |
+
.ok_or_else(|| anyhow::anyhow!("无法取得用户配置目录"))
|
| 8 |
+
}
|
| 9 |
+
|
| 10 |
+
pub fn config_file_path() -> anyhow::Result<PathBuf> {
|
| 11 |
+
Ok(project_dirs()?.config_dir().join("settings.json"))
|
| 12 |
+
}
|
| 13 |
+
|
XPostArchiver-clean-upload-20260711-225630/src/config/settings.rs
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
use std::path::{Path, PathBuf};
|
| 2 |
+
|
| 3 |
+
use serde::{Deserialize, Serialize};
|
| 4 |
+
|
| 5 |
+
use crate::config::paths::config_file_path;
|
| 6 |
+
|
| 7 |
+
#[derive(Debug, Clone, Serialize, Deserialize)]
|
| 8 |
+
pub struct AppSettings {
|
| 9 |
+
pub last_database_path: Option<PathBuf>,
|
| 10 |
+
pub media_root: Option<PathBuf>,
|
| 11 |
+
pub export_dir: Option<PathBuf>,
|
| 12 |
+
pub log_dir: Option<PathBuf>,
|
| 13 |
+
pub backup_dir: Option<PathBuf>,
|
| 14 |
+
pub temp_dir: Option<PathBuf>,
|
| 15 |
+
#[serde(default = "default_save_media_files")]
|
| 16 |
+
pub save_media_files: bool,
|
| 17 |
+
pub system_drive_warning_acknowledged: bool,
|
| 18 |
+
}
|
| 19 |
+
|
| 20 |
+
fn default_save_media_files() -> bool {
|
| 21 |
+
true
|
| 22 |
+
}
|
| 23 |
+
|
| 24 |
+
impl Default for AppSettings {
|
| 25 |
+
fn default() -> Self {
|
| 26 |
+
Self {
|
| 27 |
+
last_database_path: None,
|
| 28 |
+
media_root: None,
|
| 29 |
+
export_dir: None,
|
| 30 |
+
log_dir: None,
|
| 31 |
+
backup_dir: None,
|
| 32 |
+
temp_dir: None,
|
| 33 |
+
save_media_files: true,
|
| 34 |
+
system_drive_warning_acknowledged: false,
|
| 35 |
+
}
|
| 36 |
+
}
|
| 37 |
+
}
|
| 38 |
+
|
| 39 |
+
impl AppSettings {
|
| 40 |
+
pub fn load() -> anyhow::Result<Self> {
|
| 41 |
+
let path = config_file_path()?;
|
| 42 |
+
if !path.exists() {
|
| 43 |
+
return Ok(Self::default());
|
| 44 |
+
}
|
| 45 |
+
let text = std::fs::read_to_string(path)?;
|
| 46 |
+
Ok(serde_json::from_str(&text)?)
|
| 47 |
+
}
|
| 48 |
+
|
| 49 |
+
pub fn save(&self) -> anyhow::Result<()> {
|
| 50 |
+
let path = config_file_path()?;
|
| 51 |
+
if let Some(parent) = path.parent() {
|
| 52 |
+
std::fs::create_dir_all(parent)?;
|
| 53 |
+
}
|
| 54 |
+
let text = serde_json::to_string_pretty(self)?;
|
| 55 |
+
std::fs::write(path, text)?;
|
| 56 |
+
Ok(())
|
| 57 |
+
}
|
| 58 |
+
|
| 59 |
+
pub fn set_database_path(&mut self, path: impl AsRef<Path>) {
|
| 60 |
+
self.last_database_path = Some(path.as_ref().to_path_buf());
|
| 61 |
+
}
|
| 62 |
+
|
| 63 |
+
pub fn set_path(&mut self, kind: ConfigPathKind, path: impl AsRef<Path>) {
|
| 64 |
+
let path = Some(path.as_ref().to_path_buf());
|
| 65 |
+
match kind {
|
| 66 |
+
ConfigPathKind::MediaRoot => self.media_root = path,
|
| 67 |
+
ConfigPathKind::ExportDir => self.export_dir = path,
|
| 68 |
+
ConfigPathKind::LogDir => self.log_dir = path,
|
| 69 |
+
ConfigPathKind::BackupDir => self.backup_dir = path,
|
| 70 |
+
ConfigPathKind::TempDir => self.temp_dir = path,
|
| 71 |
+
}
|
| 72 |
+
}
|
| 73 |
+
|
| 74 |
+
pub fn get_path(&self, kind: ConfigPathKind) -> Option<&Path> {
|
| 75 |
+
match kind {
|
| 76 |
+
ConfigPathKind::MediaRoot => self.media_root.as_deref(),
|
| 77 |
+
ConfigPathKind::ExportDir => self.export_dir.as_deref(),
|
| 78 |
+
ConfigPathKind::LogDir => self.log_dir.as_deref(),
|
| 79 |
+
ConfigPathKind::BackupDir => self.backup_dir.as_deref(),
|
| 80 |
+
ConfigPathKind::TempDir => self.temp_dir.as_deref(),
|
| 81 |
+
}
|
| 82 |
+
}
|
| 83 |
+
}
|
| 84 |
+
|
| 85 |
+
#[derive(Debug, Clone, Copy)]
|
| 86 |
+
pub enum ConfigPathKind {
|
| 87 |
+
MediaRoot,
|
| 88 |
+
ExportDir,
|
| 89 |
+
LogDir,
|
| 90 |
+
BackupDir,
|
| 91 |
+
TempDir,
|
| 92 |
+
}
|
| 93 |
+
|
| 94 |
+
impl ConfigPathKind {
|
| 95 |
+
pub fn label(self) -> &'static str {
|
| 96 |
+
match self {
|
| 97 |
+
Self::MediaRoot => "归档内容目录",
|
| 98 |
+
Self::ExportDir => "导出目录",
|
| 99 |
+
Self::LogDir => "日志目录",
|
| 100 |
+
Self::BackupDir => "备份目录",
|
| 101 |
+
Self::TempDir => "临时下载目录",
|
| 102 |
+
}
|
| 103 |
+
}
|
| 104 |
+
}
|
| 105 |
+
|
XPostArchiver-clean-upload-20260711-225630/src/database/connection.rs
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
use std::path::Path;
|
| 2 |
+
|
| 3 |
+
use sqlx::{Connection, SqliteConnection, sqlite::SqliteConnectOptions};
|
| 4 |
+
|
| 5 |
+
use crate::database::migrations::run_migrations;
|
| 6 |
+
|
| 7 |
+
pub async fn open_or_create_database(path: &Path) -> anyhow::Result<()> {
|
| 8 |
+
if let Some(parent) = path.parent() {
|
| 9 |
+
std::fs::create_dir_all(parent)?;
|
| 10 |
+
}
|
| 11 |
+
|
| 12 |
+
let options = SqliteConnectOptions::new()
|
| 13 |
+
.filename(path)
|
| 14 |
+
.create_if_missing(true);
|
| 15 |
+
let mut connection = SqliteConnection::connect_with(&options).await?;
|
| 16 |
+
run_migrations(&mut connection).await?;
|
| 17 |
+
connection.close().await?;
|
| 18 |
+
Ok(())
|
| 19 |
+
}
|
| 20 |
+
|
| 21 |
+
pub async fn open_existing_database(path: &Path) -> anyhow::Result<()> {
|
| 22 |
+
if !path.exists() {
|
| 23 |
+
anyhow::bail!("数据库文件不存在:{}", path.display());
|
| 24 |
+
}
|
| 25 |
+
|
| 26 |
+
let options = SqliteConnectOptions::new()
|
| 27 |
+
.filename(path)
|
| 28 |
+
.create_if_missing(false);
|
| 29 |
+
let mut connection = SqliteConnection::connect_with(&options).await?;
|
| 30 |
+
run_migrations(&mut connection).await?;
|
| 31 |
+
connection.close().await?;
|
| 32 |
+
Ok(())
|
| 33 |
+
}
|
| 34 |
+
|
XPostArchiver-clean-upload-20260711-225630/src/database/maintenance.rs
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
use std::path::{Path, PathBuf};
|
| 2 |
+
|
| 3 |
+
use chrono::Local;
|
| 4 |
+
use sqlx::{Connection, SqliteConnection, sqlite::SqliteConnectOptions};
|
| 5 |
+
|
| 6 |
+
#[derive(Debug, Clone)]
|
| 7 |
+
pub struct DatabaseBackupResult {
|
| 8 |
+
pub path: PathBuf,
|
| 9 |
+
}
|
| 10 |
+
|
| 11 |
+
pub async fn check_database_integrity(path: &Path) -> anyhow::Result<String> {
|
| 12 |
+
if !path.exists() {
|
| 13 |
+
anyhow::bail!("数据库文件不存在:{}", path.display());
|
| 14 |
+
}
|
| 15 |
+
|
| 16 |
+
let options = SqliteConnectOptions::new()
|
| 17 |
+
.filename(path)
|
| 18 |
+
.read_only(true)
|
| 19 |
+
.create_if_missing(false);
|
| 20 |
+
let mut connection = SqliteConnection::connect_with(&options).await?;
|
| 21 |
+
let result: String = sqlx::query_scalar("PRAGMA integrity_check;")
|
| 22 |
+
.fetch_one(&mut connection)
|
| 23 |
+
.await?;
|
| 24 |
+
connection.close().await?;
|
| 25 |
+
|
| 26 |
+
if result == "ok" {
|
| 27 |
+
Ok("数据库完整性检查通过。".to_owned())
|
| 28 |
+
} else {
|
| 29 |
+
anyhow::bail!("数据库完整性检查异常:{result}");
|
| 30 |
+
}
|
| 31 |
+
}
|
| 32 |
+
|
| 33 |
+
pub fn backup_database(
|
| 34 |
+
database_path: &Path,
|
| 35 |
+
backup_dir: &Path,
|
| 36 |
+
) -> anyhow::Result<DatabaseBackupResult> {
|
| 37 |
+
if !database_path.exists() {
|
| 38 |
+
anyhow::bail!("数据库文件不存在:{}", database_path.display());
|
| 39 |
+
}
|
| 40 |
+
|
| 41 |
+
std::fs::create_dir_all(backup_dir)?;
|
| 42 |
+
if !backup_dir.is_dir() {
|
| 43 |
+
anyhow::bail!("备份位置不是目录:{}", backup_dir.display());
|
| 44 |
+
}
|
| 45 |
+
|
| 46 |
+
let stem = database_path
|
| 47 |
+
.file_stem()
|
| 48 |
+
.and_then(|name| name.to_str())
|
| 49 |
+
.unwrap_or("X公开帖子归档");
|
| 50 |
+
let extension = database_path
|
| 51 |
+
.extension()
|
| 52 |
+
.and_then(|name| name.to_str())
|
| 53 |
+
.unwrap_or("db");
|
| 54 |
+
let timestamp = Local::now().format("%Y%m%d-%H%M%S");
|
| 55 |
+
let backup_path = backup_dir.join(format!("{stem}-{timestamp}.{extension}"));
|
| 56 |
+
|
| 57 |
+
if backup_path.exists() {
|
| 58 |
+
anyhow::bail!("备份文件已存在,请稍后重试:{}", backup_path.display());
|
| 59 |
+
}
|
| 60 |
+
|
| 61 |
+
std::fs::copy(database_path, &backup_path)?;
|
| 62 |
+
Ok(DatabaseBackupResult { path: backup_path })
|
| 63 |
+
}
|
| 64 |
+
|
XPostArchiver-clean-upload-20260711-225630/src/database/migrations.rs
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
use sqlx::{SqliteConnection, migrate::Migrator};
|
| 2 |
+
|
| 3 |
+
static MIGRATOR: Migrator = sqlx::migrate!("./migrations");
|
| 4 |
+
|
| 5 |
+
pub async fn run_migrations(connection: &mut SqliteConnection) -> anyhow::Result<()> {
|
| 6 |
+
MIGRATOR.run(connection).await?;
|
| 7 |
+
Ok(())
|
| 8 |
+
}
|
| 9 |
+
|
XPostArchiver-clean-upload-20260711-225630/src/database/mod.rs
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
pub mod connection;
|
| 2 |
+
pub mod maintenance;
|
| 3 |
+
pub mod migrations;
|
| 4 |
+
|
XPostArchiver-clean-upload-20260711-225630/src/domain/mod.rs
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
|
XPostArchiver-clean-upload-20260711-225630/src/error.rs
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
use std::path::PathBuf;
|
| 2 |
+
|
| 3 |
+
use thiserror::Error;
|
| 4 |
+
|
| 5 |
+
#[allow(dead_code)]
|
| 6 |
+
#[derive(Debug, Error)]
|
| 7 |
+
pub enum AppError {
|
| 8 |
+
#[error("API请求失败:{0}")]
|
| 9 |
+
Api(String),
|
| 10 |
+
#[error("数据库错误:{0}")]
|
| 11 |
+
Database(String),
|
| 12 |
+
#[error("凭据错误:{0}")]
|
| 13 |
+
Credential(String),
|
| 14 |
+
#[error("导出失败:{0}")]
|
| 15 |
+
Export(String),
|
| 16 |
+
#[error("媒体处理失败:{0}")]
|
| 17 |
+
Media(String),
|
| 18 |
+
#[error("配置错误:{0}")]
|
| 19 |
+
Configuration(String),
|
| 20 |
+
#[error("任务错误:{0}")]
|
| 21 |
+
Task(String),
|
| 22 |
+
#[error("路径不可用:{path}")]
|
| 23 |
+
PathUnavailable { path: PathBuf },
|
| 24 |
+
#[error("操作已取消")]
|
| 25 |
+
Cancelled,
|
| 26 |
+
}
|
| 27 |
+
|
XPostArchiver-clean-upload-20260711-225630/src/exporters/mod.rs
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
|
XPostArchiver-clean-upload-20260711-225630/src/lib.rs
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
pub mod config;
|
| 2 |
+
pub mod database;
|
| 3 |
+
pub mod error;
|
| 4 |
+
pub mod logging;
|
| 5 |
+
pub mod services;
|
| 6 |
+
pub mod tasks;
|
| 7 |
+
pub mod utils;
|
| 8 |
+
|
XPostArchiver-clean-upload-20260711-225630/src/logging/mod.rs
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
pub mod rotation;
|
| 2 |
+
|
| 3 |
+
use std::path::PathBuf;
|
| 4 |
+
|
| 5 |
+
use directories::ProjectDirs;
|
| 6 |
+
use tracing_subscriber::{EnvFilter, Layer, layer::SubscriberExt, util::SubscriberInitExt};
|
| 7 |
+
|
| 8 |
+
pub struct LoggingGuard {
|
| 9 |
+
_file_guard: tracing_appender::non_blocking::WorkerGuard,
|
| 10 |
+
}
|
| 11 |
+
|
| 12 |
+
pub fn init_logging() -> anyhow::Result<LoggingGuard> {
|
| 13 |
+
let log_dir = default_log_dir()?;
|
| 14 |
+
std::fs::create_dir_all(&log_dir)?;
|
| 15 |
+
|
| 16 |
+
let file_appender = tracing_appender::rolling::daily(&log_dir, "xpost-archiver.log");
|
| 17 |
+
let (file_writer, file_guard) = tracing_appender::non_blocking(file_appender);
|
| 18 |
+
|
| 19 |
+
let filter = EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("info"));
|
| 20 |
+
let file_layer = tracing_subscriber::fmt::layer()
|
| 21 |
+
.with_ansi(false)
|
| 22 |
+
.with_writer(file_writer)
|
| 23 |
+
.with_filter(filter);
|
| 24 |
+
|
| 25 |
+
tracing_subscriber::registry().with(file_layer).try_init()?;
|
| 26 |
+
|
| 27 |
+
Ok(LoggingGuard {
|
| 28 |
+
_file_guard: file_guard,
|
| 29 |
+
})
|
| 30 |
+
}
|
| 31 |
+
|
| 32 |
+
fn default_log_dir() -> anyhow::Result<PathBuf> {
|
| 33 |
+
let dirs = ProjectDirs::from("cn", "XPostArchiver", "XPostArchiver")
|
| 34 |
+
.ok_or_else(|| anyhow::anyhow!("无法取得用户配置目录"))?;
|
| 35 |
+
Ok(dirs.data_local_dir().join("logs"))
|
| 36 |
+
}
|
| 37 |
+
|
XPostArchiver-clean-upload-20260711-225630/src/logging/rotation.rs
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
pub fn redact_secret(input: &str) -> String {
|
| 2 |
+
let mut output = input.to_owned();
|
| 3 |
+
for marker in [
|
| 4 |
+
"Bearer ",
|
| 5 |
+
"token=",
|
| 6 |
+
"api_key=",
|
| 7 |
+
"api_secret=",
|
| 8 |
+
"Authorization:",
|
| 9 |
+
] {
|
| 10 |
+
if let Some(index) = output
|
| 11 |
+
.to_ascii_lowercase()
|
| 12 |
+
.find(&marker.to_ascii_lowercase())
|
| 13 |
+
{
|
| 14 |
+
let end = output[index..]
|
| 15 |
+
.find(['\n', '\r', '&'])
|
| 16 |
+
.map(|offset| index + offset)
|
| 17 |
+
.unwrap_or(output.len());
|
| 18 |
+
output.replace_range(index..end, "[REDACTED]");
|
| 19 |
+
}
|
| 20 |
+
}
|
| 21 |
+
output
|
| 22 |
+
}
|
| 23 |
+
|
| 24 |
+
#[cfg(test)]
|
| 25 |
+
mod tests {
|
| 26 |
+
use super::redact_secret;
|
| 27 |
+
|
| 28 |
+
#[test]
|
| 29 |
+
fn redacts_bearer_token() {
|
| 30 |
+
let text = "Authorization: Bearer abcdefghijklmnopqrstuvwxyz";
|
| 31 |
+
assert!(!redact_secret(text).contains("abcdefghijklmnopqrstuvwxyz"));
|
| 32 |
+
}
|
| 33 |
+
}
|
| 34 |
+
|
XPostArchiver-clean-upload-20260711-225630/src/main.rs
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
mod app;
|
| 2 |
+
mod config;
|
| 3 |
+
mod database;
|
| 4 |
+
mod error;
|
| 5 |
+
mod logging;
|
| 6 |
+
mod services;
|
| 7 |
+
mod tasks;
|
| 8 |
+
mod utils;
|
| 9 |
+
|
| 10 |
+
fn main() -> anyhow::Result<()> {
|
| 11 |
+
app::App::bootstrap()?.run()
|
| 12 |
+
}
|
| 13 |
+
|
XPostArchiver-clean-upload-20260711-225630/src/security/mod.rs
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
|
XPostArchiver-clean-upload-20260711-225630/src/services/account_service.rs
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
use chrono::Utc;
|
| 2 |
+
use sqlx::{Connection, SqliteConnection, sqlite::SqliteConnectOptions};
|
| 3 |
+
|
| 4 |
+
use crate::database::migrations::run_migrations;
|
| 5 |
+
use crate::services::credential_service::read_bearer_token;
|
| 6 |
+
use crate::services::x_api_service::{XAccountProfile, lookup_public_account};
|
| 7 |
+
use crate::tasks::runtime::BackgroundRuntime;
|
| 8 |
+
|
| 9 |
+
#[derive(Debug, Clone)]
|
| 10 |
+
pub struct AccountLookupResult {
|
| 11 |
+
pub username: String,
|
| 12 |
+
pub display_name: Option<String>,
|
| 13 |
+
pub message: String,
|
| 14 |
+
}
|
| 15 |
+
|
| 16 |
+
pub fn lookup_account(
|
| 17 |
+
runtime: &BackgroundRuntime,
|
| 18 |
+
database_path: &std::path::Path,
|
| 19 |
+
username: &str,
|
| 20 |
+
) -> anyhow::Result<AccountLookupResult> {
|
| 21 |
+
let token =
|
| 22 |
+
read_bearer_token()?.ok_or_else(|| anyhow::anyhow!("请先保存 X API Bearer Token。"))?;
|
| 23 |
+
let profile = runtime.block_on(lookup_public_account(&token, username))??;
|
| 24 |
+
runtime.block_on(save_account_profile(database_path, &profile))??;
|
| 25 |
+
|
| 26 |
+
Ok(AccountLookupResult {
|
| 27 |
+
username: profile.username.clone(),
|
| 28 |
+
display_name: profile.name.clone(),
|
| 29 |
+
message: format!("已查询并保存公开账号:@{}。", profile.username),
|
| 30 |
+
})
|
| 31 |
+
}
|
| 32 |
+
|
| 33 |
+
pub async fn save_account_profile(
|
| 34 |
+
database_path: &std::path::Path,
|
| 35 |
+
profile: &XAccountProfile,
|
| 36 |
+
) -> anyhow::Result<()> {
|
| 37 |
+
let options = SqliteConnectOptions::new()
|
| 38 |
+
.filename(database_path)
|
| 39 |
+
.create_if_missing(false);
|
| 40 |
+
let mut connection = SqliteConnection::connect_with(&options).await?;
|
| 41 |
+
run_migrations(&mut connection).await?;
|
| 42 |
+
|
| 43 |
+
let now = Utc::now().to_rfc3339();
|
| 44 |
+
let metrics = profile.public_metrics.as_ref();
|
| 45 |
+
sqlx::query(
|
| 46 |
+
r#"
|
| 47 |
+
INSERT INTO accounts (
|
| 48 |
+
x_user_id, username, display_name, description, profile_image_url, created_at_x,
|
| 49 |
+
protected, verified, followers_count, following_count, post_count,
|
| 50 |
+
first_seen_at, last_seen_at, raw_json
|
| 51 |
+
)
|
| 52 |
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
| 53 |
+
ON CONFLICT(x_user_id) DO UPDATE SET
|
| 54 |
+
username = excluded.username,
|
| 55 |
+
display_name = excluded.display_name,
|
| 56 |
+
description = excluded.description,
|
| 57 |
+
profile_image_url = excluded.profile_image_url,
|
| 58 |
+
created_at_x = excluded.created_at_x,
|
| 59 |
+
protected = excluded.protected,
|
| 60 |
+
verified = excluded.verified,
|
| 61 |
+
followers_count = excluded.followers_count,
|
| 62 |
+
following_count = excluded.following_count,
|
| 63 |
+
post_count = excluded.post_count,
|
| 64 |
+
last_seen_at = excluded.last_seen_at,
|
| 65 |
+
raw_json = excluded.raw_json
|
| 66 |
+
"#,
|
| 67 |
+
)
|
| 68 |
+
.bind(&profile.id)
|
| 69 |
+
.bind(&profile.username)
|
| 70 |
+
.bind(&profile.name)
|
| 71 |
+
.bind(&profile.description)
|
| 72 |
+
.bind(&profile.profile_image_url)
|
| 73 |
+
.bind(&profile.created_at)
|
| 74 |
+
.bind(profile.protected.map(bool_to_i64))
|
| 75 |
+
.bind(profile.verified.map(bool_to_i64))
|
| 76 |
+
.bind(metrics.and_then(|value| value.followers_count))
|
| 77 |
+
.bind(metrics.and_then(|value| value.following_count))
|
| 78 |
+
.bind(metrics.and_then(|value| value.tweet_count))
|
| 79 |
+
.bind(&now)
|
| 80 |
+
.bind(&now)
|
| 81 |
+
.bind(serde_json::to_string(&profile.raw_json)?)
|
| 82 |
+
.execute(&mut connection)
|
| 83 |
+
.await?;
|
| 84 |
+
|
| 85 |
+
connection.close().await?;
|
| 86 |
+
Ok(())
|
| 87 |
+
}
|
| 88 |
+
|
| 89 |
+
fn bool_to_i64(value: bool) -> i64 {
|
| 90 |
+
if value { 1 } else { 0 }
|
| 91 |
+
}
|
| 92 |
+
|
| 93 |
+
#[cfg(test)]
|
| 94 |
+
mod tests {
|
| 95 |
+
use tempfile::tempdir;
|
| 96 |
+
|
| 97 |
+
use super::save_account_profile;
|
| 98 |
+
use crate::database::connection::open_or_create_database;
|
| 99 |
+
use crate::services::x_api_service::{XAccountProfile, XAccountPublicMetrics};
|
| 100 |
+
|
| 101 |
+
#[tokio::test]
|
| 102 |
+
async fn saves_account_profile() -> anyhow::Result<()> {
|
| 103 |
+
let temp_dir = tempdir()?;
|
| 104 |
+
let database_path = temp_dir.path().join("archive.db");
|
| 105 |
+
open_or_create_database(&database_path).await?;
|
| 106 |
+
|
| 107 |
+
let profile = XAccountProfile {
|
| 108 |
+
id: "123".to_owned(),
|
| 109 |
+
username: "alice".to_owned(),
|
| 110 |
+
name: Some("Alice".to_owned()),
|
| 111 |
+
description: Some("public".to_owned()),
|
| 112 |
+
profile_image_url: None,
|
| 113 |
+
created_at: None,
|
| 114 |
+
protected: Some(false),
|
| 115 |
+
verified: Some(true),
|
| 116 |
+
public_metrics: Some(XAccountPublicMetrics {
|
| 117 |
+
followers_count: Some(10),
|
| 118 |
+
following_count: Some(2),
|
| 119 |
+
tweet_count: Some(30),
|
| 120 |
+
}),
|
| 121 |
+
raw_json: serde_json::json!({"data":{"id":"123"}}),
|
| 122 |
+
};
|
| 123 |
+
|
| 124 |
+
save_account_profile(&database_path, &profile).await?;
|
| 125 |
+
|
| 126 |
+
let pool =
|
| 127 |
+
sqlx::SqlitePool::connect(&format!("sqlite://{}", database_path.display())).await?;
|
| 128 |
+
let username: String =
|
| 129 |
+
sqlx::query_scalar("SELECT username FROM accounts WHERE x_user_id = '123'")
|
| 130 |
+
.fetch_one(&pool)
|
| 131 |
+
.await?;
|
| 132 |
+
|
| 133 |
+
assert_eq!(username, "alice");
|
| 134 |
+
Ok(())
|
| 135 |
+
}
|
| 136 |
+
}
|
| 137 |
+
|
XPostArchiver-clean-upload-20260711-225630/src/services/archive_export_service.rs
ADDED
|
@@ -0,0 +1,167 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
use chrono::Utc;
|
| 2 |
+
use sqlx::{Connection, SqliteConnection, sqlite::SqliteConnectOptions};
|
| 3 |
+
use std::path::{Path, PathBuf};
|
| 4 |
+
|
| 5 |
+
use crate::database::migrations::run_migrations;
|
| 6 |
+
|
| 7 |
+
#[derive(Debug, Clone)]
|
| 8 |
+
pub struct ArchivedPostSummary {
|
| 9 |
+
pub x_post_id: String,
|
| 10 |
+
pub author_username: Option<String>,
|
| 11 |
+
pub text: Option<String>,
|
| 12 |
+
pub created_at_x: Option<String>,
|
| 13 |
+
pub original_url: Option<String>,
|
| 14 |
+
}
|
| 15 |
+
|
| 16 |
+
#[derive(Debug, Clone)]
|
| 17 |
+
pub struct ArchivePreviewResult {
|
| 18 |
+
pub posts: Vec<ArchivedPostSummary>,
|
| 19 |
+
pub message: String,
|
| 20 |
+
}
|
| 21 |
+
|
| 22 |
+
#[derive(Debug, Clone)]
|
| 23 |
+
pub struct ArchiveExportResult {
|
| 24 |
+
pub path: PathBuf,
|
| 25 |
+
pub post_count: usize,
|
| 26 |
+
pub message: String,
|
| 27 |
+
}
|
| 28 |
+
|
| 29 |
+
pub async fn preview_posts_for_job(
|
| 30 |
+
database_path: &Path,
|
| 31 |
+
job_id: &str,
|
| 32 |
+
limit: i64,
|
| 33 |
+
) -> anyhow::Result<ArchivePreviewResult> {
|
| 34 |
+
let posts = load_posts_for_job(database_path, job_id, limit.clamp(1, 50)).await?;
|
| 35 |
+
Ok(ArchivePreviewResult {
|
| 36 |
+
message: format!("已读取 {} 条已保存帖子。", posts.len()),
|
| 37 |
+
posts,
|
| 38 |
+
})
|
| 39 |
+
}
|
| 40 |
+
|
| 41 |
+
pub async fn export_posts_for_job_markdown(
|
| 42 |
+
database_path: &Path,
|
| 43 |
+
export_dir: &Path,
|
| 44 |
+
job_id: &str,
|
| 45 |
+
) -> anyhow::Result<ArchiveExportResult> {
|
| 46 |
+
let posts = load_posts_for_job(database_path, job_id, 500).await?;
|
| 47 |
+
std::fs::create_dir_all(export_dir)?;
|
| 48 |
+
let safe_job_id = job_id
|
| 49 |
+
.trim()
|
| 50 |
+
.replace(|ch: char| !ch.is_ascii_alphanumeric() && ch != '-', "_");
|
| 51 |
+
let path = export_dir.join(format!(
|
| 52 |
+
"x-posts-{}-{}.md",
|
| 53 |
+
safe_job_id,
|
| 54 |
+
Utc::now().format("%Y%m%d-%H%M%S")
|
| 55 |
+
));
|
| 56 |
+
std::fs::write(&path, render_markdown(job_id, &posts))?;
|
| 57 |
+
Ok(ArchiveExportResult {
|
| 58 |
+
path,
|
| 59 |
+
post_count: posts.len(),
|
| 60 |
+
message: format!("已导出 {} 条帖子。", posts.len()),
|
| 61 |
+
})
|
| 62 |
+
}
|
| 63 |
+
|
| 64 |
+
async fn load_posts_for_job(
|
| 65 |
+
database_path: &Path,
|
| 66 |
+
job_id: &str,
|
| 67 |
+
limit: i64,
|
| 68 |
+
) -> anyhow::Result<Vec<ArchivedPostSummary>> {
|
| 69 |
+
let options = SqliteConnectOptions::new()
|
| 70 |
+
.filename(database_path)
|
| 71 |
+
.create_if_missing(false);
|
| 72 |
+
let mut connection = SqliteConnection::connect_with(&options).await?;
|
| 73 |
+
run_migrations(&mut connection).await?;
|
| 74 |
+
let rows = sqlx::query_as::<
|
| 75 |
+
_,
|
| 76 |
+
(
|
| 77 |
+
String,
|
| 78 |
+
Option<String>,
|
| 79 |
+
Option<String>,
|
| 80 |
+
Option<String>,
|
| 81 |
+
Option<String>,
|
| 82 |
+
),
|
| 83 |
+
>(
|
| 84 |
+
r#"
|
| 85 |
+
SELECT x_post_id, author_username, text, created_at_x, original_url
|
| 86 |
+
FROM posts
|
| 87 |
+
WHERE source_job_id = ?
|
| 88 |
+
ORDER BY COALESCE(created_at_x, first_fetched_at) DESC
|
| 89 |
+
LIMIT ?
|
| 90 |
+
"#,
|
| 91 |
+
)
|
| 92 |
+
.bind(job_id.trim())
|
| 93 |
+
.bind(limit)
|
| 94 |
+
.fetch_all(&mut connection)
|
| 95 |
+
.await?;
|
| 96 |
+
connection.close().await?;
|
| 97 |
+
Ok(rows
|
| 98 |
+
.into_iter()
|
| 99 |
+
.map(
|
| 100 |
+
|(x_post_id, author_username, text, created_at_x, original_url)| ArchivedPostSummary {
|
| 101 |
+
x_post_id,
|
| 102 |
+
author_username,
|
| 103 |
+
text,
|
| 104 |
+
created_at_x,
|
| 105 |
+
original_url,
|
| 106 |
+
},
|
| 107 |
+
)
|
| 108 |
+
.collect())
|
| 109 |
+
}
|
| 110 |
+
|
| 111 |
+
fn render_markdown(job_id: &str, posts: &[ArchivedPostSummary]) -> String {
|
| 112 |
+
let mut text = format!(
|
| 113 |
+
"# X 帖子归档\n\n任务 ID:`{}`\n\n共 {} 条帖子。\n\n",
|
| 114 |
+
job_id,
|
| 115 |
+
posts.len()
|
| 116 |
+
);
|
| 117 |
+
for post in posts {
|
| 118 |
+
text.push_str(&format!("## {}\n\n", post.x_post_id));
|
| 119 |
+
if let Some(author) = &post.author_username {
|
| 120 |
+
text.push_str(&format!("账号:@{}\n\n", author));
|
| 121 |
+
}
|
| 122 |
+
if let Some(created_at) = &post.created_at_x {
|
| 123 |
+
text.push_str(&format!("时间:{}\n\n", created_at));
|
| 124 |
+
}
|
| 125 |
+
if let Some(body) = &post.text {
|
| 126 |
+
text.push_str(body);
|
| 127 |
+
text.push_str("\n\n");
|
| 128 |
+
}
|
| 129 |
+
if let Some(url) = &post.original_url {
|
| 130 |
+
text.push_str(&format!("原始链接:{}\n\n", url));
|
| 131 |
+
}
|
| 132 |
+
text.push_str("---\n\n");
|
| 133 |
+
}
|
| 134 |
+
text
|
| 135 |
+
}
|
| 136 |
+
|
| 137 |
+
#[cfg(test)]
|
| 138 |
+
mod tests {
|
| 139 |
+
use tempfile::tempdir;
|
| 140 |
+
|
| 141 |
+
use super::{export_posts_for_job_markdown, preview_posts_for_job};
|
| 142 |
+
use crate::database::connection::open_or_create_database;
|
| 143 |
+
|
| 144 |
+
#[tokio::test]
|
| 145 |
+
async fn previews_and_exports_posts_for_job() -> anyhow::Result<()> {
|
| 146 |
+
let temp_dir = tempdir()?;
|
| 147 |
+
let database_path = temp_dir.path().join("archive.db");
|
| 148 |
+
open_or_create_database(&database_path).await?;
|
| 149 |
+
let pool =
|
| 150 |
+
sqlx::SqlitePool::connect(&format!("sqlite://{}", database_path.display())).await?;
|
| 151 |
+
sqlx::query(
|
| 152 |
+
"INSERT INTO posts (x_post_id, author_x_user_id, author_username, text, created_at_x, original_url, first_fetched_at, last_fetched_at, source_job_id) VALUES ('post-1', '123', 'alice', 'hello', '2026-07-11T00:00:00Z', 'https://x.com/alice/status/post-1', 'now', 'now', 'job-1')",
|
| 153 |
+
)
|
| 154 |
+
.execute(&pool)
|
| 155 |
+
.await?;
|
| 156 |
+
|
| 157 |
+
let preview = preview_posts_for_job(&database_path, "job-1", 10).await?;
|
| 158 |
+
assert_eq!(preview.posts.len(), 1);
|
| 159 |
+
let export =
|
| 160 |
+
export_posts_for_job_markdown(&database_path, temp_dir.path(), "job-1").await?;
|
| 161 |
+
let exported = std::fs::read_to_string(export.path)?;
|
| 162 |
+
assert!(exported.contains("hello"));
|
| 163 |
+
assert_eq!(export.post_count, 1);
|
| 164 |
+
Ok(())
|
| 165 |
+
}
|
| 166 |
+
}
|
| 167 |
+
|
XPostArchiver-clean-upload-20260711-225630/src/services/crawl_task_service.rs
ADDED
|
@@ -0,0 +1,199 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
use chrono::Utc;
|
| 2 |
+
use sqlx::{Connection, SqliteConnection, sqlite::SqliteConnectOptions};
|
| 3 |
+
use uuid::Uuid;
|
| 4 |
+
|
| 5 |
+
use crate::config::settings::AppSettings;
|
| 6 |
+
use crate::database::migrations::run_migrations;
|
| 7 |
+
|
| 8 |
+
#[derive(Debug, Clone)]
|
| 9 |
+
pub struct CrawlTaskResult {
|
| 10 |
+
pub job_id: String,
|
| 11 |
+
pub message: String,
|
| 12 |
+
}
|
| 13 |
+
|
| 14 |
+
#[derive(Debug, Clone)]
|
| 15 |
+
pub struct CrawlTaskSummary {
|
| 16 |
+
pub job_id: String,
|
| 17 |
+
pub username: String,
|
| 18 |
+
pub status: String,
|
| 19 |
+
pub pages_fetched: i64,
|
| 20 |
+
pub posts_received: i64,
|
| 21 |
+
pub posts_inserted: i64,
|
| 22 |
+
pub last_error: Option<String>,
|
| 23 |
+
pub created_at: String,
|
| 24 |
+
}
|
| 25 |
+
|
| 26 |
+
pub async fn create_crawl_task(
|
| 27 |
+
database_path: &std::path::Path,
|
| 28 |
+
username: &str,
|
| 29 |
+
settings: &AppSettings,
|
| 30 |
+
) -> anyhow::Result<CrawlTaskResult> {
|
| 31 |
+
let username = username.trim().trim_start_matches('@');
|
| 32 |
+
if username.is_empty() {
|
| 33 |
+
anyhow::bail!("用户名不能为空。")
|
| 34 |
+
}
|
| 35 |
+
|
| 36 |
+
let options = SqliteConnectOptions::new()
|
| 37 |
+
.filename(database_path)
|
| 38 |
+
.create_if_missing(false);
|
| 39 |
+
let mut connection = SqliteConnection::connect_with(&options).await?;
|
| 40 |
+
run_migrations(&mut connection).await?;
|
| 41 |
+
|
| 42 |
+
let account_exists: Option<String> = sqlx::query_scalar(
|
| 43 |
+
"SELECT x_user_id FROM accounts WHERE lower(username) = lower(?) LIMIT 1",
|
| 44 |
+
)
|
| 45 |
+
.bind(username)
|
| 46 |
+
.fetch_optional(&mut connection)
|
| 47 |
+
.await?;
|
| 48 |
+
|
| 49 |
+
let Some(target_x_user_id) = account_exists else {
|
| 50 |
+
anyhow::bail!("请先查询并保存公开账号:@{}。", username)
|
| 51 |
+
};
|
| 52 |
+
|
| 53 |
+
let job_id = Uuid::new_v4().to_string();
|
| 54 |
+
let now = Utc::now().to_rfc3339();
|
| 55 |
+
sqlx::query(
|
| 56 |
+
r#"
|
| 57 |
+
INSERT INTO crawl_jobs (
|
| 58 |
+
id, target_x_user_id, target_username, task_mode,
|
| 59 |
+
include_original, include_replies, include_reposts, include_quotes,
|
| 60 |
+
download_media, status, created_at
|
| 61 |
+
)
|
| 62 |
+
VALUES (?, ?, ?, 'timeline', 1, 1, 0, 1, ?, 'created', ?)
|
| 63 |
+
"#,
|
| 64 |
+
)
|
| 65 |
+
.bind(&job_id)
|
| 66 |
+
.bind(&target_x_user_id)
|
| 67 |
+
.bind(username)
|
| 68 |
+
.bind(if settings.save_media_files {
|
| 69 |
+
1_i64
|
| 70 |
+
} else {
|
| 71 |
+
0_i64
|
| 72 |
+
})
|
| 73 |
+
.bind(&now)
|
| 74 |
+
.execute(&mut connection)
|
| 75 |
+
.await?;
|
| 76 |
+
|
| 77 |
+
connection.close().await?;
|
| 78 |
+
Ok(CrawlTaskResult {
|
| 79 |
+
job_id,
|
| 80 |
+
message: format!(
|
| 81 |
+
"已创建采集任务:@{}。当前只建立任务,不拉取帖子。",
|
| 82 |
+
username
|
| 83 |
+
),
|
| 84 |
+
})
|
| 85 |
+
}
|
| 86 |
+
|
| 87 |
+
pub async fn list_recent_crawl_tasks(
|
| 88 |
+
database_path: &std::path::Path,
|
| 89 |
+
limit: i64,
|
| 90 |
+
) -> anyhow::Result<Vec<CrawlTaskSummary>> {
|
| 91 |
+
let options = SqliteConnectOptions::new()
|
| 92 |
+
.filename(database_path)
|
| 93 |
+
.create_if_missing(false);
|
| 94 |
+
let mut connection = SqliteConnection::connect_with(&options).await?;
|
| 95 |
+
run_migrations(&mut connection).await?;
|
| 96 |
+
|
| 97 |
+
let rows = sqlx::query_as::<_, (String, String, String, i64, i64, i64, Option<String>, String)>(
|
| 98 |
+
r#"
|
| 99 |
+
SELECT id, target_username, status, pages_fetched, posts_received, posts_inserted, last_error, created_at
|
| 100 |
+
FROM crawl_jobs
|
| 101 |
+
ORDER BY created_at DESC
|
| 102 |
+
LIMIT ?
|
| 103 |
+
"#,
|
| 104 |
+
)
|
| 105 |
+
.bind(limit.clamp(1, 50))
|
| 106 |
+
.fetch_all(&mut connection)
|
| 107 |
+
.await?;
|
| 108 |
+
|
| 109 |
+
connection.close().await?;
|
| 110 |
+
Ok(rows
|
| 111 |
+
.into_iter()
|
| 112 |
+
.map(
|
| 113 |
+
|(
|
| 114 |
+
job_id,
|
| 115 |
+
username,
|
| 116 |
+
status,
|
| 117 |
+
pages_fetched,
|
| 118 |
+
posts_received,
|
| 119 |
+
posts_inserted,
|
| 120 |
+
last_error,
|
| 121 |
+
created_at,
|
| 122 |
+
)| CrawlTaskSummary {
|
| 123 |
+
job_id,
|
| 124 |
+
username,
|
| 125 |
+
status,
|
| 126 |
+
pages_fetched,
|
| 127 |
+
posts_received,
|
| 128 |
+
posts_inserted,
|
| 129 |
+
last_error,
|
| 130 |
+
created_at,
|
| 131 |
+
},
|
| 132 |
+
)
|
| 133 |
+
.collect())
|
| 134 |
+
}
|
| 135 |
+
|
| 136 |
+
#[cfg(test)]
|
| 137 |
+
mod tests {
|
| 138 |
+
use tempfile::tempdir;
|
| 139 |
+
|
| 140 |
+
use super::{create_crawl_task, list_recent_crawl_tasks};
|
| 141 |
+
use crate::config::settings::AppSettings;
|
| 142 |
+
use crate::database::connection::open_or_create_database;
|
| 143 |
+
use crate::services::account_service::save_account_profile;
|
| 144 |
+
use crate::services::x_api_service::XAccountProfile;
|
| 145 |
+
|
| 146 |
+
#[tokio::test]
|
| 147 |
+
async fn creates_crawl_task_for_saved_account() -> anyhow::Result<()> {
|
| 148 |
+
let temp_dir = tempdir()?;
|
| 149 |
+
let database_path = temp_dir.path().join("archive.db");
|
| 150 |
+
open_or_create_database(&database_path).await?;
|
| 151 |
+
save_account_profile(&database_path, &test_profile()).await?;
|
| 152 |
+
|
| 153 |
+
let result = create_crawl_task(&database_path, "alice", &AppSettings::default()).await?;
|
| 154 |
+
|
| 155 |
+
assert!(result.message.contains("已创建采集任务"));
|
| 156 |
+
let pool =
|
| 157 |
+
sqlx::SqlitePool::connect(&format!("sqlite://{}", database_path.display())).await?;
|
| 158 |
+
let status: String = sqlx::query_scalar("SELECT status FROM crawl_jobs WHERE id = ?")
|
| 159 |
+
.bind(result.job_id)
|
| 160 |
+
.fetch_one(&pool)
|
| 161 |
+
.await?;
|
| 162 |
+
assert_eq!(status, "created");
|
| 163 |
+
Ok(())
|
| 164 |
+
}
|
| 165 |
+
|
| 166 |
+
#[tokio::test]
|
| 167 |
+
async fn lists_recent_crawl_tasks() -> anyhow::Result<()> {
|
| 168 |
+
let temp_dir = tempdir()?;
|
| 169 |
+
let database_path = temp_dir.path().join("archive.db");
|
| 170 |
+
open_or_create_database(&database_path).await?;
|
| 171 |
+
save_account_profile(&database_path, &test_profile()).await?;
|
| 172 |
+
let created = create_crawl_task(&database_path, "alice", &AppSettings::default()).await?;
|
| 173 |
+
|
| 174 |
+
let tasks = list_recent_crawl_tasks(&database_path, 10).await?;
|
| 175 |
+
|
| 176 |
+
assert_eq!(tasks.len(), 1);
|
| 177 |
+
assert_eq!(tasks[0].job_id, created.job_id);
|
| 178 |
+
assert_eq!(tasks[0].username, "alice");
|
| 179 |
+
assert_eq!(tasks[0].status, "created");
|
| 180 |
+
assert_eq!(tasks[0].pages_fetched, 0);
|
| 181 |
+
Ok(())
|
| 182 |
+
}
|
| 183 |
+
|
| 184 |
+
fn test_profile() -> XAccountProfile {
|
| 185 |
+
XAccountProfile {
|
| 186 |
+
id: "123".to_owned(),
|
| 187 |
+
username: "alice".to_owned(),
|
| 188 |
+
name: Some("Alice".to_owned()),
|
| 189 |
+
description: None,
|
| 190 |
+
profile_image_url: None,
|
| 191 |
+
created_at: None,
|
| 192 |
+
protected: Some(false),
|
| 193 |
+
verified: None,
|
| 194 |
+
public_metrics: None,
|
| 195 |
+
raw_json: serde_json::json!({"data":{"id":"123"}}),
|
| 196 |
+
}
|
| 197 |
+
}
|
| 198 |
+
}
|
| 199 |
+
|
XPostArchiver-clean-upload-20260711-225630/src/services/credential_service.rs
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
use keyring::Entry;
|
| 2 |
+
|
| 3 |
+
const SERVICE_NAME: &str = "XPostArchiver";
|
| 4 |
+
const BEARER_TOKEN_ACCOUNT: &str = "x-api-bearer-token";
|
| 5 |
+
|
| 6 |
+
#[derive(Debug, Clone)]
|
| 7 |
+
pub struct CredentialStatus {
|
| 8 |
+
pub configured: bool,
|
| 9 |
+
pub message: String,
|
| 10 |
+
}
|
| 11 |
+
|
| 12 |
+
pub fn save_bearer_token(token: &str) -> anyhow::Result<CredentialStatus> {
|
| 13 |
+
let token = token.trim();
|
| 14 |
+
if token.is_empty() {
|
| 15 |
+
anyhow::bail!("Bearer Token 不能为空。")
|
| 16 |
+
}
|
| 17 |
+
|
| 18 |
+
let entry = bearer_token_entry()?;
|
| 19 |
+
entry.set_password(token)?;
|
| 20 |
+
Ok(CredentialStatus {
|
| 21 |
+
configured: true,
|
| 22 |
+
message: "X API Bearer Token 已保存到系统密钥库。".to_owned(),
|
| 23 |
+
})
|
| 24 |
+
}
|
| 25 |
+
|
| 26 |
+
pub fn clear_bearer_token() -> anyhow::Result<CredentialStatus> {
|
| 27 |
+
let entry = bearer_token_entry()?;
|
| 28 |
+
match entry.delete_credential() {
|
| 29 |
+
Ok(()) => {}
|
| 30 |
+
Err(keyring::Error::NoEntry) => {}
|
| 31 |
+
Err(error) => return Err(error.into()),
|
| 32 |
+
}
|
| 33 |
+
|
| 34 |
+
Ok(CredentialStatus {
|
| 35 |
+
configured: false,
|
| 36 |
+
message: "X API Bearer Token 已清除。".to_owned(),
|
| 37 |
+
})
|
| 38 |
+
}
|
| 39 |
+
|
| 40 |
+
pub fn bearer_token_status() -> CredentialStatus {
|
| 41 |
+
match read_bearer_token() {
|
| 42 |
+
Ok(Some(_)) => CredentialStatus {
|
| 43 |
+
configured: true,
|
| 44 |
+
message: "已配置 X API Bearer Token。".to_owned(),
|
| 45 |
+
},
|
| 46 |
+
Ok(None) => CredentialStatus {
|
| 47 |
+
configured: false,
|
| 48 |
+
message: "尚未配置 X API Bearer Token。".to_owned(),
|
| 49 |
+
},
|
| 50 |
+
Err(error) => CredentialStatus {
|
| 51 |
+
configured: false,
|
| 52 |
+
message: format!("读取系统密钥库失败:{error}"),
|
| 53 |
+
},
|
| 54 |
+
}
|
| 55 |
+
}
|
| 56 |
+
|
| 57 |
+
pub fn read_bearer_token() -> anyhow::Result<Option<String>> {
|
| 58 |
+
let entry = bearer_token_entry()?;
|
| 59 |
+
match entry.get_password() {
|
| 60 |
+
Ok(token) => Ok(Some(token)),
|
| 61 |
+
Err(keyring::Error::NoEntry) => Ok(None),
|
| 62 |
+
Err(error) => Err(error.into()),
|
| 63 |
+
}
|
| 64 |
+
}
|
| 65 |
+
|
| 66 |
+
fn bearer_token_entry() -> anyhow::Result<Entry> {
|
| 67 |
+
Ok(Entry::new(SERVICE_NAME, BEARER_TOKEN_ACCOUNT)?)
|
| 68 |
+
}
|
| 69 |
+
|
XPostArchiver-clean-upload-20260711-225630/src/services/database_service.rs
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
use std::path::{Path, PathBuf};
|
| 2 |
+
|
| 3 |
+
use rfd::FileDialog;
|
| 4 |
+
|
| 5 |
+
use crate::config::settings::AppSettings;
|
| 6 |
+
use crate::database::connection::{open_existing_database, open_or_create_database};
|
| 7 |
+
use crate::database::maintenance::{backup_database, check_database_integrity};
|
| 8 |
+
use crate::tasks::runtime::BackgroundRuntime;
|
| 9 |
+
use crate::utils::disk::system_drive_warning;
|
| 10 |
+
|
| 11 |
+
#[derive(Debug, Clone)]
|
| 12 |
+
pub struct DatabaseSelectionResult {
|
| 13 |
+
pub path: PathBuf,
|
| 14 |
+
pub message: String,
|
| 15 |
+
}
|
| 16 |
+
|
| 17 |
+
#[derive(Debug, Clone)]
|
| 18 |
+
pub struct DatabaseMaintenanceResult {
|
| 19 |
+
pub message: String,
|
| 20 |
+
}
|
| 21 |
+
|
| 22 |
+
pub fn choose_existing_database(
|
| 23 |
+
runtime: &BackgroundRuntime,
|
| 24 |
+
settings: &mut AppSettings,
|
| 25 |
+
) -> anyhow::Result<Option<DatabaseSelectionResult>> {
|
| 26 |
+
let Some(path) = FileDialog::new()
|
| 27 |
+
.add_filter("SQLite 数据库", &["db", "sqlite", "sqlite3"])
|
| 28 |
+
.pick_file()
|
| 29 |
+
else {
|
| 30 |
+
return Ok(None);
|
| 31 |
+
};
|
| 32 |
+
|
| 33 |
+
runtime.block_on(open_existing_database(&path))??;
|
| 34 |
+
settings.set_database_path(&path);
|
| 35 |
+
settings.save()?;
|
| 36 |
+
Ok(Some(DatabaseSelectionResult {
|
| 37 |
+
message: message_with_warning("已打开数据库", &path),
|
| 38 |
+
path,
|
| 39 |
+
}))
|
| 40 |
+
}
|
| 41 |
+
|
| 42 |
+
pub fn create_database(
|
| 43 |
+
runtime: &BackgroundRuntime,
|
| 44 |
+
settings: &mut AppSettings,
|
| 45 |
+
) -> anyhow::Result<Option<DatabaseSelectionResult>> {
|
| 46 |
+
let Some(mut path) = FileDialog::new()
|
| 47 |
+
.add_filter("SQLite 数据库", &["db"])
|
| 48 |
+
.set_file_name("X公开帖子归档.db")
|
| 49 |
+
.save_file()
|
| 50 |
+
else {
|
| 51 |
+
return Ok(None);
|
| 52 |
+
};
|
| 53 |
+
|
| 54 |
+
if path.extension().is_none() {
|
| 55 |
+
path.set_extension("db");
|
| 56 |
+
}
|
| 57 |
+
|
| 58 |
+
if path.exists() {
|
| 59 |
+
anyhow::bail!(
|
| 60 |
+
"文件已存在,请选择打开已有数据库或更换文件名:{}",
|
| 61 |
+
path.display()
|
| 62 |
+
);
|
| 63 |
+
}
|
| 64 |
+
|
| 65 |
+
runtime.block_on(open_or_create_database(&path))??;
|
| 66 |
+
|
| 67 |
+
settings.set_database_path(&path);
|
| 68 |
+
settings.save()?;
|
| 69 |
+
Ok(Some(DatabaseSelectionResult {
|
| 70 |
+
message: message_with_warning("已创建数据库", &path),
|
| 71 |
+
path,
|
| 72 |
+
}))
|
| 73 |
+
}
|
| 74 |
+
|
| 75 |
+
pub fn check_current_database(
|
| 76 |
+
runtime: &BackgroundRuntime,
|
| 77 |
+
settings: &AppSettings,
|
| 78 |
+
) -> anyhow::Result<DatabaseMaintenanceResult> {
|
| 79 |
+
let database_path = settings
|
| 80 |
+
.last_database_path
|
| 81 |
+
.as_deref()
|
| 82 |
+
.ok_or_else(|| anyhow::anyhow!("请先选择或新建数据库。"))?;
|
| 83 |
+
let message = runtime.block_on(check_database_integrity(database_path))??;
|
| 84 |
+
Ok(DatabaseMaintenanceResult { message })
|
| 85 |
+
}
|
| 86 |
+
|
| 87 |
+
pub fn backup_current_database(
|
| 88 |
+
settings: &AppSettings,
|
| 89 |
+
) -> anyhow::Result<DatabaseMaintenanceResult> {
|
| 90 |
+
let database_path = settings
|
| 91 |
+
.last_database_path
|
| 92 |
+
.as_deref()
|
| 93 |
+
.ok_or_else(|| anyhow::anyhow!("请先选择或新建数据库。"))?;
|
| 94 |
+
let backup_dir = settings
|
| 95 |
+
.backup_dir
|
| 96 |
+
.as_deref()
|
| 97 |
+
.ok_or_else(|| anyhow::anyhow!("请先设置备份目录。"))?;
|
| 98 |
+
let result = backup_database(database_path, backup_dir)?;
|
| 99 |
+
Ok(DatabaseMaintenanceResult {
|
| 100 |
+
message: format!("数据库已备份到:{}", result.path.display()),
|
| 101 |
+
})
|
| 102 |
+
}
|
| 103 |
+
|
| 104 |
+
fn message_with_warning(action: &str, path: &Path) -> String {
|
| 105 |
+
match system_drive_warning(path) {
|
| 106 |
+
Some(warning) => format!("{action}。{warning}"),
|
| 107 |
+
None => action.to_owned(),
|
| 108 |
+
}
|
| 109 |
+
}
|
| 110 |
+
|
XPostArchiver-clean-upload-20260711-225630/src/services/media_download_service.rs
ADDED
|
@@ -0,0 +1,324 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
use std::path::{Path, PathBuf};
|
| 2 |
+
|
| 3 |
+
use chrono::Utc;
|
| 4 |
+
use sqlx::{Connection, SqliteConnection, sqlite::SqliteConnectOptions};
|
| 5 |
+
|
| 6 |
+
use crate::database::migrations::run_migrations;
|
| 7 |
+
use crate::tasks::runtime::BackgroundRuntime;
|
| 8 |
+
|
| 9 |
+
#[derive(Debug, Clone)]
|
| 10 |
+
pub struct MediaDownloadResult {
|
| 11 |
+
pub attempted: usize,
|
| 12 |
+
pub downloaded: usize,
|
| 13 |
+
pub skipped: usize,
|
| 14 |
+
pub failed: usize,
|
| 15 |
+
pub message: String,
|
| 16 |
+
}
|
| 17 |
+
|
| 18 |
+
#[derive(Debug)]
|
| 19 |
+
struct PendingMedia {
|
| 20 |
+
media_key: String,
|
| 21 |
+
media_type: String,
|
| 22 |
+
original_url: Option<String>,
|
| 23 |
+
preview_url: Option<String>,
|
| 24 |
+
}
|
| 25 |
+
|
| 26 |
+
pub fn download_pending_media(
|
| 27 |
+
runtime: &BackgroundRuntime,
|
| 28 |
+
database_path: &Path,
|
| 29 |
+
media_root: &Path,
|
| 30 |
+
max_items: usize,
|
| 31 |
+
) -> anyhow::Result<MediaDownloadResult> {
|
| 32 |
+
runtime.block_on(download_pending_media_async(
|
| 33 |
+
database_path,
|
| 34 |
+
media_root,
|
| 35 |
+
max_items,
|
| 36 |
+
))?
|
| 37 |
+
}
|
| 38 |
+
|
| 39 |
+
pub fn retry_failed_media(
|
| 40 |
+
runtime: &BackgroundRuntime,
|
| 41 |
+
database_path: &Path,
|
| 42 |
+
media_root: &Path,
|
| 43 |
+
max_items: usize,
|
| 44 |
+
) -> anyhow::Result<MediaDownloadResult> {
|
| 45 |
+
runtime.block_on(download_media_async(
|
| 46 |
+
database_path,
|
| 47 |
+
media_root,
|
| 48 |
+
max_items,
|
| 49 |
+
true,
|
| 50 |
+
))?
|
| 51 |
+
}
|
| 52 |
+
|
| 53 |
+
pub async fn download_pending_media_async(
|
| 54 |
+
database_path: &Path,
|
| 55 |
+
media_root: &Path,
|
| 56 |
+
max_items: usize,
|
| 57 |
+
) -> anyhow::Result<MediaDownloadResult> {
|
| 58 |
+
download_media_async(database_path, media_root, max_items, false).await
|
| 59 |
+
}
|
| 60 |
+
|
| 61 |
+
async fn download_media_async(
|
| 62 |
+
database_path: &Path,
|
| 63 |
+
media_root: &Path,
|
| 64 |
+
max_items: usize,
|
| 65 |
+
include_failed: bool,
|
| 66 |
+
) -> anyhow::Result<MediaDownloadResult> {
|
| 67 |
+
if max_items == 0 {
|
| 68 |
+
anyhow::bail!("下载数量必须大于 0。")
|
| 69 |
+
}
|
| 70 |
+
std::fs::create_dir_all(media_root)?;
|
| 71 |
+
|
| 72 |
+
let options = SqliteConnectOptions::new()
|
| 73 |
+
.filename(database_path)
|
| 74 |
+
.create_if_missing(false);
|
| 75 |
+
let mut connection = SqliteConnection::connect_with(&options).await?;
|
| 76 |
+
run_migrations(&mut connection).await?;
|
| 77 |
+
|
| 78 |
+
let status_filter = if include_failed {
|
| 79 |
+
"download_status IN ('metadata_only', 'failed')"
|
| 80 |
+
} else {
|
| 81 |
+
"download_status = 'metadata_only'"
|
| 82 |
+
};
|
| 83 |
+
let pending_query = format!(
|
| 84 |
+
"SELECT media_key, media_type, original_url, preview_url FROM media WHERE {status_filter} LIMIT ?"
|
| 85 |
+
);
|
| 86 |
+
let pending_rows: Vec<(String, String, Option<String>, Option<String>)> =
|
| 87 |
+
sqlx::query_as(&pending_query)
|
| 88 |
+
.bind(max_items as i64)
|
| 89 |
+
.fetch_all(&mut connection)
|
| 90 |
+
.await?;
|
| 91 |
+
let pending: Vec<PendingMedia> = pending_rows
|
| 92 |
+
.into_iter()
|
| 93 |
+
.map(
|
| 94 |
+
|(media_key, media_type, original_url, preview_url)| PendingMedia {
|
| 95 |
+
media_key,
|
| 96 |
+
media_type,
|
| 97 |
+
original_url,
|
| 98 |
+
preview_url,
|
| 99 |
+
},
|
| 100 |
+
)
|
| 101 |
+
.collect();
|
| 102 |
+
|
| 103 |
+
let client = reqwest::Client::new();
|
| 104 |
+
let mut downloaded = 0_usize;
|
| 105 |
+
let mut skipped = 0_usize;
|
| 106 |
+
let mut failed = 0_usize;
|
| 107 |
+
|
| 108 |
+
for item in &pending {
|
| 109 |
+
let Some(url) = item.original_url.as_ref().or(item.preview_url.as_ref()) else {
|
| 110 |
+
mark_media_failed(&mut connection, &item.media_key, "没有可下载的媒体 URL。").await?;
|
| 111 |
+
skipped += 1;
|
| 112 |
+
continue;
|
| 113 |
+
};
|
| 114 |
+
|
| 115 |
+
match download_one_media(&client, media_root, item, url).await {
|
| 116 |
+
Ok(relative_path) => {
|
| 117 |
+
mark_media_downloaded(&mut connection, &item.media_key, &relative_path).await?;
|
| 118 |
+
downloaded += 1;
|
| 119 |
+
}
|
| 120 |
+
Err(error) => {
|
| 121 |
+
mark_media_failed(&mut connection, &item.media_key, &error.to_string()).await?;
|
| 122 |
+
failed += 1;
|
| 123 |
+
}
|
| 124 |
+
}
|
| 125 |
+
}
|
| 126 |
+
|
| 127 |
+
connection.close().await?;
|
| 128 |
+
Ok(MediaDownloadResult {
|
| 129 |
+
attempted: pending.len(),
|
| 130 |
+
downloaded,
|
| 131 |
+
skipped,
|
| 132 |
+
failed,
|
| 133 |
+
message: format!(
|
| 134 |
+
"媒体下载完成:尝试 {} 个,成功 {} 个,跳过 {} 个,失败 {} 个。",
|
| 135 |
+
pending.len(),
|
| 136 |
+
downloaded,
|
| 137 |
+
skipped,
|
| 138 |
+
failed
|
| 139 |
+
),
|
| 140 |
+
})
|
| 141 |
+
}
|
| 142 |
+
|
| 143 |
+
async fn download_one_media(
|
| 144 |
+
client: &reqwest::Client,
|
| 145 |
+
media_root: &Path,
|
| 146 |
+
item: &PendingMedia,
|
| 147 |
+
url: &str,
|
| 148 |
+
) -> anyhow::Result<String> {
|
| 149 |
+
let response = client.get(url).send().await?;
|
| 150 |
+
if !response.status().is_success() {
|
| 151 |
+
anyhow::bail!("媒体下载返回状态:{}。", response.status().as_u16())
|
| 152 |
+
}
|
| 153 |
+
let content_type = response
|
| 154 |
+
.headers()
|
| 155 |
+
.get(reqwest::header::CONTENT_TYPE)
|
| 156 |
+
.and_then(|value| value.to_str().ok())
|
| 157 |
+
.map(str::to_owned);
|
| 158 |
+
let bytes = response.bytes().await?;
|
| 159 |
+
if bytes.is_empty() {
|
| 160 |
+
anyhow::bail!("媒体响应为空。")
|
| 161 |
+
}
|
| 162 |
+
|
| 163 |
+
let extension = extension_for(url, content_type.as_deref(), &item.media_type);
|
| 164 |
+
let relative_path = PathBuf::from("media").join(format!("{}.{}", item.media_key, extension));
|
| 165 |
+
let absolute_path = media_root.join(&relative_path);
|
| 166 |
+
if let Some(parent) = absolute_path.parent() {
|
| 167 |
+
std::fs::create_dir_all(parent)?;
|
| 168 |
+
}
|
| 169 |
+
std::fs::write(&absolute_path, &bytes)?;
|
| 170 |
+
Ok(relative_path.to_string_lossy().replace('\\', "/"))
|
| 171 |
+
}
|
| 172 |
+
|
| 173 |
+
fn extension_for(url: &str, content_type: Option<&str>, media_type: &str) -> &'static str {
|
| 174 |
+
if let Some(content_type) = content_type {
|
| 175 |
+
if content_type.contains("png") {
|
| 176 |
+
return "png";
|
| 177 |
+
}
|
| 178 |
+
if content_type.contains("webp") {
|
| 179 |
+
return "webp";
|
| 180 |
+
}
|
| 181 |
+
if content_type.contains("gif") {
|
| 182 |
+
return "gif";
|
| 183 |
+
}
|
| 184 |
+
if content_type.contains("mp4") {
|
| 185 |
+
return "mp4";
|
| 186 |
+
}
|
| 187 |
+
if content_type.contains("jpeg") || content_type.contains("jpg") {
|
| 188 |
+
return "jpg";
|
| 189 |
+
}
|
| 190 |
+
}
|
| 191 |
+
let lower_url = url.to_ascii_lowercase();
|
| 192 |
+
for extension in ["png", "webp", "gif", "mp4", "jpg", "jpeg"] {
|
| 193 |
+
if lower_url.contains(&format!(".{extension}")) {
|
| 194 |
+
return if extension == "jpeg" {
|
| 195 |
+
"jpg"
|
| 196 |
+
} else {
|
| 197 |
+
extension
|
| 198 |
+
};
|
| 199 |
+
}
|
| 200 |
+
}
|
| 201 |
+
match media_type {
|
| 202 |
+
"video" | "animated_gif" => "mp4",
|
| 203 |
+
_ => "jpg",
|
| 204 |
+
}
|
| 205 |
+
}
|
| 206 |
+
|
| 207 |
+
async fn mark_media_downloaded(
|
| 208 |
+
connection: &mut SqliteConnection,
|
| 209 |
+
media_key: &str,
|
| 210 |
+
relative_path: &str,
|
| 211 |
+
) -> anyhow::Result<()> {
|
| 212 |
+
sqlx::query(
|
| 213 |
+
"UPDATE media SET download_status = 'downloaded', local_relative_path = ?, downloaded_at = ?, last_error = NULL WHERE media_key = ?",
|
| 214 |
+
)
|
| 215 |
+
.bind(relative_path)
|
| 216 |
+
.bind(Utc::now().to_rfc3339())
|
| 217 |
+
.bind(media_key)
|
| 218 |
+
.execute(connection)
|
| 219 |
+
.await?;
|
| 220 |
+
Ok(())
|
| 221 |
+
}
|
| 222 |
+
|
| 223 |
+
async fn mark_media_failed(
|
| 224 |
+
connection: &mut SqliteConnection,
|
| 225 |
+
media_key: &str,
|
| 226 |
+
error: &str,
|
| 227 |
+
) -> anyhow::Result<()> {
|
| 228 |
+
sqlx::query("UPDATE media SET download_status = 'failed', last_error = ? WHERE media_key = ?")
|
| 229 |
+
.bind(error)
|
| 230 |
+
.bind(media_key)
|
| 231 |
+
.execute(connection)
|
| 232 |
+
.await?;
|
| 233 |
+
Ok(())
|
| 234 |
+
}
|
| 235 |
+
|
| 236 |
+
#[cfg(test)]
|
| 237 |
+
mod tests {
|
| 238 |
+
use tempfile::tempdir;
|
| 239 |
+
use wiremock::matchers::{method, path};
|
| 240 |
+
use wiremock::{Mock, MockServer, ResponseTemplate};
|
| 241 |
+
|
| 242 |
+
use super::{download_media_async, download_pending_media_async};
|
| 243 |
+
use crate::database::connection::open_or_create_database;
|
| 244 |
+
|
| 245 |
+
#[tokio::test]
|
| 246 |
+
async fn downloads_pending_media_file() -> anyhow::Result<()> {
|
| 247 |
+
let server = MockServer::start().await;
|
| 248 |
+
Mock::given(method("GET"))
|
| 249 |
+
.and(path("/image.jpg"))
|
| 250 |
+
.respond_with(
|
| 251 |
+
ResponseTemplate::new(200)
|
| 252 |
+
.insert_header("content-type", "image/jpeg")
|
| 253 |
+
.set_body_bytes(vec![1_u8, 2, 3]),
|
| 254 |
+
)
|
| 255 |
+
.mount(&server)
|
| 256 |
+
.await;
|
| 257 |
+
|
| 258 |
+
let temp_dir = tempdir()?;
|
| 259 |
+
let database_path = temp_dir.path().join("archive.db");
|
| 260 |
+
let media_root = temp_dir.path().join("archive");
|
| 261 |
+
open_or_create_database(&database_path).await?;
|
| 262 |
+
let pool =
|
| 263 |
+
sqlx::SqlitePool::connect(&format!("sqlite://{}", database_path.display())).await?;
|
| 264 |
+
sqlx::query(
|
| 265 |
+
"INSERT INTO media (media_key, media_type, original_url, download_status) VALUES ('media-1', 'photo', ?, 'metadata_only')",
|
| 266 |
+
)
|
| 267 |
+
.bind(format!("{}/image.jpg", server.uri()))
|
| 268 |
+
.execute(&pool)
|
| 269 |
+
.await?;
|
| 270 |
+
|
| 271 |
+
let result = download_pending_media_async(&database_path, &media_root, 10).await?;
|
| 272 |
+
|
| 273 |
+
assert_eq!(result.attempted, 1);
|
| 274 |
+
assert_eq!(result.downloaded, 1);
|
| 275 |
+
let relative_path: String =
|
| 276 |
+
sqlx::query_scalar("SELECT local_relative_path FROM media WHERE media_key = 'media-1'")
|
| 277 |
+
.fetch_one(&pool)
|
| 278 |
+
.await?;
|
| 279 |
+
assert_eq!(relative_path, "media/media-1.jpg");
|
| 280 |
+
assert!(media_root.join(relative_path).exists());
|
| 281 |
+
Ok(())
|
| 282 |
+
}
|
| 283 |
+
|
| 284 |
+
#[tokio::test]
|
| 285 |
+
async fn retries_failed_media_file() -> anyhow::Result<()> {
|
| 286 |
+
let server = MockServer::start().await;
|
| 287 |
+
Mock::given(method("GET"))
|
| 288 |
+
.and(path("/image.jpg"))
|
| 289 |
+
.respond_with(
|
| 290 |
+
ResponseTemplate::new(200)
|
| 291 |
+
.insert_header("content-type", "image/jpeg")
|
| 292 |
+
.set_body_bytes(vec![4_u8, 5, 6]),
|
| 293 |
+
)
|
| 294 |
+
.mount(&server)
|
| 295 |
+
.await;
|
| 296 |
+
|
| 297 |
+
let temp_dir = tempdir()?;
|
| 298 |
+
let database_path = temp_dir.path().join("archive.db");
|
| 299 |
+
let media_root = temp_dir.path().join("archive");
|
| 300 |
+
open_or_create_database(&database_path).await?;
|
| 301 |
+
let pool =
|
| 302 |
+
sqlx::SqlitePool::connect(&format!("sqlite://{}", database_path.display())).await?;
|
| 303 |
+
sqlx::query(
|
| 304 |
+
"INSERT INTO media (media_key, media_type, original_url, download_status, last_error) VALUES ('media-retry', 'photo', ?, 'failed', 'old error')",
|
| 305 |
+
)
|
| 306 |
+
.bind(format!("{}/image.jpg", server.uri()))
|
| 307 |
+
.execute(&pool)
|
| 308 |
+
.await?;
|
| 309 |
+
|
| 310 |
+
let result = download_media_async(&database_path, &media_root, 10, true).await?;
|
| 311 |
+
|
| 312 |
+
assert_eq!(result.attempted, 1);
|
| 313 |
+
assert_eq!(result.downloaded, 1);
|
| 314 |
+
let (status, last_error): (String, Option<String>) = sqlx::query_as(
|
| 315 |
+
"SELECT download_status, last_error FROM media WHERE media_key = 'media-retry'",
|
| 316 |
+
)
|
| 317 |
+
.fetch_one(&pool)
|
| 318 |
+
.await?;
|
| 319 |
+
assert_eq!(status, "downloaded");
|
| 320 |
+
assert_eq!(last_error, None);
|
| 321 |
+
Ok(())
|
| 322 |
+
}
|
| 323 |
+
}
|
| 324 |
+
|
XPostArchiver-clean-upload-20260711-225630/src/services/mod.rs
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
pub mod account_service;
|
| 2 |
+
pub mod archive_export_service;
|
| 3 |
+
pub mod crawl_task_service;
|
| 4 |
+
pub mod credential_service;
|
| 5 |
+
pub mod database_service;
|
| 6 |
+
pub mod media_download_service;
|
| 7 |
+
pub mod path_service;
|
| 8 |
+
pub mod post_fetch_service;
|
| 9 |
+
pub mod x_api_service;
|
| 10 |
+
|
XPostArchiver-clean-upload-20260711-225630/src/services/path_service.rs
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
use std::path::{Path, PathBuf};
|
| 2 |
+
|
| 3 |
+
use rfd::FileDialog;
|
| 4 |
+
|
| 5 |
+
use crate::config::settings::{AppSettings, ConfigPathKind};
|
| 6 |
+
use crate::utils::disk::system_drive_warning;
|
| 7 |
+
|
| 8 |
+
#[derive(Debug, Clone)]
|
| 9 |
+
pub struct PathSelectionResult {
|
| 10 |
+
pub kind: ConfigPathKind,
|
| 11 |
+
pub path: PathBuf,
|
| 12 |
+
pub message: String,
|
| 13 |
+
}
|
| 14 |
+
|
| 15 |
+
pub fn choose_config_directory(
|
| 16 |
+
kind: ConfigPathKind,
|
| 17 |
+
settings: &mut AppSettings,
|
| 18 |
+
) -> anyhow::Result<Option<PathSelectionResult>> {
|
| 19 |
+
let Some(path) = FileDialog::new().set_title(kind.label()).pick_folder() else {
|
| 20 |
+
return Ok(None);
|
| 21 |
+
};
|
| 22 |
+
|
| 23 |
+
if !path.exists() {
|
| 24 |
+
anyhow::bail!("目录不存在:{}", path.display());
|
| 25 |
+
}
|
| 26 |
+
|
| 27 |
+
settings.set_path(kind, &path);
|
| 28 |
+
settings.save()?;
|
| 29 |
+
|
| 30 |
+
Ok(Some(PathSelectionResult {
|
| 31 |
+
kind,
|
| 32 |
+
message: message_with_warning(kind, &path),
|
| 33 |
+
path,
|
| 34 |
+
}))
|
| 35 |
+
}
|
| 36 |
+
|
| 37 |
+
fn message_with_warning(kind: ConfigPathKind, path: &Path) -> String {
|
| 38 |
+
let action = format!("已设置{}", kind.label());
|
| 39 |
+
match system_drive_warning(path) {
|
| 40 |
+
Some(warning) => format!("{action}。{warning}"),
|
| 41 |
+
None => action,
|
| 42 |
+
}
|
| 43 |
+
}
|
| 44 |
+
|
XPostArchiver-clean-upload-20260711-225630/src/services/post_fetch_service.rs
ADDED
|
@@ -0,0 +1,649 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
use chrono::Utc;
|
| 2 |
+
use sqlx::{Connection, SqliteConnection, sqlite::SqliteConnectOptions};
|
| 3 |
+
use std::sync::{
|
| 4 |
+
Arc,
|
| 5 |
+
atomic::{AtomicBool, Ordering},
|
| 6 |
+
};
|
| 7 |
+
use std::time::Duration;
|
| 8 |
+
|
| 9 |
+
use crate::database::migrations::run_migrations;
|
| 10 |
+
use crate::services::credential_service::read_bearer_token;
|
| 11 |
+
use crate::services::x_api_service::{XMedia, XPost, fetch_user_posts_page};
|
| 12 |
+
use crate::tasks::runtime::BackgroundRuntime;
|
| 13 |
+
|
| 14 |
+
#[derive(Debug, Clone)]
|
| 15 |
+
pub struct PostFetchResult {
|
| 16 |
+
pub received: usize,
|
| 17 |
+
pub saved: usize,
|
| 18 |
+
pub media_saved: usize,
|
| 19 |
+
pub has_next_page: bool,
|
| 20 |
+
pub message: String,
|
| 21 |
+
}
|
| 22 |
+
|
| 23 |
+
#[derive(Debug, Clone)]
|
| 24 |
+
pub struct AutoCrawlResult {
|
| 25 |
+
pub pages_fetched: usize,
|
| 26 |
+
pub posts_received: usize,
|
| 27 |
+
pub posts_saved: usize,
|
| 28 |
+
pub media_saved: usize,
|
| 29 |
+
pub stopped_because_complete: bool,
|
| 30 |
+
pub stopped_by_request: bool,
|
| 31 |
+
pub message: String,
|
| 32 |
+
}
|
| 33 |
+
|
| 34 |
+
pub fn fetch_one_page_for_task(
|
| 35 |
+
runtime: &BackgroundRuntime,
|
| 36 |
+
database_path: &std::path::Path,
|
| 37 |
+
job_id: &str,
|
| 38 |
+
) -> anyhow::Result<PostFetchResult> {
|
| 39 |
+
let token =
|
| 40 |
+
read_bearer_token()?.ok_or_else(|| anyhow::anyhow!("请先保存 X API Bearer Token。"))?;
|
| 41 |
+
runtime.block_on(fetch_one_page_for_task_async(database_path, job_id, &token))?
|
| 42 |
+
}
|
| 43 |
+
|
| 44 |
+
pub async fn auto_fetch_pages_for_task_owned_async(
|
| 45 |
+
database_path: std::path::PathBuf,
|
| 46 |
+
job_id: String,
|
| 47 |
+
token: String,
|
| 48 |
+
max_pages: usize,
|
| 49 |
+
delay_between_pages: Duration,
|
| 50 |
+
stop_requested: Arc<AtomicBool>,
|
| 51 |
+
) -> anyhow::Result<AutoCrawlResult> {
|
| 52 |
+
auto_fetch_pages_for_task_async(
|
| 53 |
+
&database_path,
|
| 54 |
+
&job_id,
|
| 55 |
+
&token,
|
| 56 |
+
max_pages,
|
| 57 |
+
delay_between_pages,
|
| 58 |
+
&stop_requested,
|
| 59 |
+
)
|
| 60 |
+
.await
|
| 61 |
+
}
|
| 62 |
+
|
| 63 |
+
pub async fn auto_fetch_pages_for_task_async(
|
| 64 |
+
database_path: &std::path::Path,
|
| 65 |
+
job_id: &str,
|
| 66 |
+
token: &str,
|
| 67 |
+
max_pages: usize,
|
| 68 |
+
delay_between_pages: Duration,
|
| 69 |
+
stop_requested: &AtomicBool,
|
| 70 |
+
) -> anyhow::Result<AutoCrawlResult> {
|
| 71 |
+
let mut pages_fetched = 0_usize;
|
| 72 |
+
let mut posts_received = 0_usize;
|
| 73 |
+
let mut posts_saved = 0_usize;
|
| 74 |
+
let mut media_saved = 0_usize;
|
| 75 |
+
let mut stopped_because_complete = false;
|
| 76 |
+
let mut stopped_by_request = false;
|
| 77 |
+
|
| 78 |
+
while max_pages == 0 || pages_fetched < max_pages {
|
| 79 |
+
if stop_requested.load(Ordering::Relaxed) {
|
| 80 |
+
stopped_by_request = true;
|
| 81 |
+
break;
|
| 82 |
+
}
|
| 83 |
+
let page = match fetch_one_page_for_task_async(database_path, job_id, token).await {
|
| 84 |
+
Ok(page) => page,
|
| 85 |
+
Err(error) => {
|
| 86 |
+
mark_job_failed(database_path, job_id, &error.to_string()).await?;
|
| 87 |
+
return Err(error);
|
| 88 |
+
}
|
| 89 |
+
};
|
| 90 |
+
pages_fetched += 1;
|
| 91 |
+
posts_received += page.received;
|
| 92 |
+
posts_saved += page.saved;
|
| 93 |
+
media_saved += page.media_saved;
|
| 94 |
+
if !page.has_next_page {
|
| 95 |
+
stopped_because_complete = true;
|
| 96 |
+
break;
|
| 97 |
+
}
|
| 98 |
+
if (max_pages == 0 || pages_fetched < max_pages) && !delay_between_pages.is_zero() {
|
| 99 |
+
tokio::time::sleep(delay_between_pages).await;
|
| 100 |
+
}
|
| 101 |
+
if stop_requested.load(Ordering::Relaxed) {
|
| 102 |
+
stopped_by_request = true;
|
| 103 |
+
mark_job_stopped(database_path, job_id).await?;
|
| 104 |
+
break;
|
| 105 |
+
}
|
| 106 |
+
}
|
| 107 |
+
|
| 108 |
+
if stopped_by_request && pages_fetched == 0 {
|
| 109 |
+
mark_job_stopped(database_path, job_id).await?;
|
| 110 |
+
}
|
| 111 |
+
|
| 112 |
+
Ok(AutoCrawlResult {
|
| 113 |
+
pages_fetched,
|
| 114 |
+
posts_received,
|
| 115 |
+
posts_saved,
|
| 116 |
+
media_saved,
|
| 117 |
+
stopped_because_complete,
|
| 118 |
+
stopped_by_request,
|
| 119 |
+
message: format!(
|
| 120 |
+
"自动采集结束:拉取 {} 页,收到 {} 条,保存 {} 条,记录媒体 {} 个。{}",
|
| 121 |
+
pages_fetched,
|
| 122 |
+
posts_received,
|
| 123 |
+
posts_saved,
|
| 124 |
+
media_saved,
|
| 125 |
+
if stopped_by_request {
|
| 126 |
+
"已按停止请求结束。"
|
| 127 |
+
} else if stopped_because_complete {
|
| 128 |
+
"任务已到末页。"
|
| 129 |
+
} else {
|
| 130 |
+
"已达到本次页数上限。"
|
| 131 |
+
}
|
| 132 |
+
),
|
| 133 |
+
})
|
| 134 |
+
}
|
| 135 |
+
|
| 136 |
+
async fn mark_job_stopped(database_path: &std::path::Path, job_id: &str) -> anyhow::Result<()> {
|
| 137 |
+
let options = SqliteConnectOptions::new()
|
| 138 |
+
.filename(database_path)
|
| 139 |
+
.create_if_missing(false);
|
| 140 |
+
let mut connection = SqliteConnection::connect_with(&options).await?;
|
| 141 |
+
sqlx::query(
|
| 142 |
+
"UPDATE crawl_jobs SET status = 'stopped', finished_at = ?, paused_at = ? WHERE id = ?",
|
| 143 |
+
)
|
| 144 |
+
.bind(Utc::now().to_rfc3339())
|
| 145 |
+
.bind(Utc::now().to_rfc3339())
|
| 146 |
+
.bind(job_id.trim())
|
| 147 |
+
.execute(&mut connection)
|
| 148 |
+
.await?;
|
| 149 |
+
Ok(())
|
| 150 |
+
}
|
| 151 |
+
|
| 152 |
+
async fn mark_job_failed(
|
| 153 |
+
database_path: &std::path::Path,
|
| 154 |
+
job_id: &str,
|
| 155 |
+
error: &str,
|
| 156 |
+
) -> anyhow::Result<()> {
|
| 157 |
+
let options = SqliteConnectOptions::new()
|
| 158 |
+
.filename(database_path)
|
| 159 |
+
.create_if_missing(false);
|
| 160 |
+
let mut connection = SqliteConnection::connect_with(&options).await?;
|
| 161 |
+
sqlx::query(
|
| 162 |
+
"UPDATE crawl_jobs SET status = 'failed', finished_at = ?, error_count = error_count + 1, last_error = ? WHERE id = ?",
|
| 163 |
+
)
|
| 164 |
+
.bind(Utc::now().to_rfc3339())
|
| 165 |
+
.bind(error.chars().take(1000).collect::<String>())
|
| 166 |
+
.bind(job_id.trim())
|
| 167 |
+
.execute(&mut connection)
|
| 168 |
+
.await?;
|
| 169 |
+
Ok(())
|
| 170 |
+
}
|
| 171 |
+
|
| 172 |
+
pub async fn fetch_one_page_for_task_async(
|
| 173 |
+
database_path: &std::path::Path,
|
| 174 |
+
job_id: &str,
|
| 175 |
+
token: &str,
|
| 176 |
+
) -> anyhow::Result<PostFetchResult> {
|
| 177 |
+
let options = SqliteConnectOptions::new()
|
| 178 |
+
.filename(database_path)
|
| 179 |
+
.create_if_missing(false);
|
| 180 |
+
let mut connection = SqliteConnection::connect_with(&options).await?;
|
| 181 |
+
run_migrations(&mut connection).await?;
|
| 182 |
+
|
| 183 |
+
let job: Option<(String, String)> = sqlx::query_as(
|
| 184 |
+
"SELECT target_x_user_id, target_username FROM crawl_jobs WHERE id = ? LIMIT 1",
|
| 185 |
+
)
|
| 186 |
+
.bind(job_id.trim())
|
| 187 |
+
.fetch_optional(&mut connection)
|
| 188 |
+
.await?;
|
| 189 |
+
let Some((target_x_user_id, target_username)) = job else {
|
| 190 |
+
anyhow::bail!("未找到采集任务:{}。", job_id)
|
| 191 |
+
};
|
| 192 |
+
|
| 193 |
+
sqlx::query("UPDATE crawl_jobs SET status = 'running', started_at = COALESCE(started_at, ?) WHERE id = ?")
|
| 194 |
+
.bind(Utc::now().to_rfc3339())
|
| 195 |
+
.bind(job_id)
|
| 196 |
+
.execute(&mut connection)
|
| 197 |
+
.await?;
|
| 198 |
+
|
| 199 |
+
let pagination_token: Option<String> = sqlx::query_scalar(
|
| 200 |
+
"SELECT pagination_token FROM crawl_checkpoints WHERE job_id = ? LIMIT 1",
|
| 201 |
+
)
|
| 202 |
+
.bind(job_id.trim())
|
| 203 |
+
.fetch_optional(&mut connection)
|
| 204 |
+
.await?;
|
| 205 |
+
let page = match fetch_user_posts_page(
|
| 206 |
+
token,
|
| 207 |
+
&target_x_user_id,
|
| 208 |
+
10,
|
| 209 |
+
pagination_token.as_deref(),
|
| 210 |
+
)
|
| 211 |
+
.await
|
| 212 |
+
{
|
| 213 |
+
Ok(page) => page,
|
| 214 |
+
Err(error) => {
|
| 215 |
+
let now = Utc::now().to_rfc3339();
|
| 216 |
+
sqlx::query(
|
| 217 |
+
"UPDATE crawl_jobs SET status = 'failed', finished_at = ?, error_count = error_count + 1, last_error = ? WHERE id = ?",
|
| 218 |
+
)
|
| 219 |
+
.bind(&now)
|
| 220 |
+
.bind(error.to_string().chars().take(1000).collect::<String>())
|
| 221 |
+
.bind(job_id.trim())
|
| 222 |
+
.execute(&mut connection)
|
| 223 |
+
.await?;
|
| 224 |
+
return Err(error);
|
| 225 |
+
}
|
| 226 |
+
};
|
| 227 |
+
let posts = page.posts;
|
| 228 |
+
let media = page.media;
|
| 229 |
+
let received = posts.len();
|
| 230 |
+
let mut media_saved = 0_usize;
|
| 231 |
+
for item in &media {
|
| 232 |
+
save_media(&mut connection, item).await?;
|
| 233 |
+
media_saved += 1;
|
| 234 |
+
}
|
| 235 |
+
let mut saved = 0_usize;
|
| 236 |
+
for post in &posts {
|
| 237 |
+
save_post(
|
| 238 |
+
&mut connection,
|
| 239 |
+
post,
|
| 240 |
+
&target_x_user_id,
|
| 241 |
+
&target_username,
|
| 242 |
+
job_id,
|
| 243 |
+
)
|
| 244 |
+
.await?;
|
| 245 |
+
saved += 1;
|
| 246 |
+
}
|
| 247 |
+
|
| 248 |
+
let has_next_page = page.next_token.is_some();
|
| 249 |
+
let next_status = if has_next_page {
|
| 250 |
+
"page_fetched"
|
| 251 |
+
} else {
|
| 252 |
+
"completed"
|
| 253 |
+
};
|
| 254 |
+
let checkpoint_updated_at = Utc::now().to_rfc3339();
|
| 255 |
+
sqlx::query(
|
| 256 |
+
"INSERT INTO crawl_checkpoints (job_id, pagination_token, last_successful_page, updated_at) VALUES (?, ?, 1, ?) ON CONFLICT(job_id) DO UPDATE SET pagination_token = excluded.pagination_token, last_successful_page = crawl_checkpoints.last_successful_page + 1, updated_at = excluded.updated_at",
|
| 257 |
+
)
|
| 258 |
+
.bind(job_id)
|
| 259 |
+
.bind(&page.next_token)
|
| 260 |
+
.bind(&checkpoint_updated_at)
|
| 261 |
+
.execute(&mut connection)
|
| 262 |
+
.await?;
|
| 263 |
+
|
| 264 |
+
sqlx::query(
|
| 265 |
+
"UPDATE crawl_jobs SET status = ?, finished_at = ?, pages_fetched = pages_fetched + 1, posts_received = posts_received + ?, posts_inserted = posts_inserted + ? WHERE id = ?",
|
| 266 |
+
)
|
| 267 |
+
.bind(next_status)
|
| 268 |
+
.bind(Utc::now().to_rfc3339())
|
| 269 |
+
.bind(received as i64)
|
| 270 |
+
.bind(saved as i64)
|
| 271 |
+
.bind(job_id)
|
| 272 |
+
.execute(&mut connection)
|
| 273 |
+
.await?;
|
| 274 |
+
|
| 275 |
+
connection.close().await?;
|
| 276 |
+
Ok(PostFetchResult {
|
| 277 |
+
received,
|
| 278 |
+
saved,
|
| 279 |
+
media_saved,
|
| 280 |
+
has_next_page,
|
| 281 |
+
message: format!(
|
| 282 |
+
"已拉取下一页公开帖子:收到 {} 条,保存 {} 条,记录媒体 {} 个。{}",
|
| 283 |
+
received,
|
| 284 |
+
saved,
|
| 285 |
+
media_saved,
|
| 286 |
+
if has_next_page {
|
| 287 |
+
"还有下一页。"
|
| 288 |
+
} else {
|
| 289 |
+
"已经没有下一页。"
|
| 290 |
+
}
|
| 291 |
+
),
|
| 292 |
+
})
|
| 293 |
+
}
|
| 294 |
+
|
| 295 |
+
async fn save_post(
|
| 296 |
+
connection: &mut SqliteConnection,
|
| 297 |
+
post: &XPost,
|
| 298 |
+
author_x_user_id: &str,
|
| 299 |
+
author_username: &str,
|
| 300 |
+
job_id: &str,
|
| 301 |
+
) -> anyhow::Result<()> {
|
| 302 |
+
let now = Utc::now().to_rfc3339();
|
| 303 |
+
let original_url = format!("https://x.com/{}/status/{}", author_username, post.id);
|
| 304 |
+
sqlx::query(
|
| 305 |
+
r#"
|
| 306 |
+
INSERT INTO posts (
|
| 307 |
+
x_post_id, author_x_user_id, author_username, text, created_at_x,
|
| 308 |
+
original_url, conversation_id, like_count, reply_count, repost_count, quote_count,
|
| 309 |
+
first_fetched_at, last_fetched_at, source_job_id, raw_json, data_source
|
| 310 |
+
)
|
| 311 |
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'x_api')
|
| 312 |
+
ON CONFLICT(x_post_id) DO UPDATE SET
|
| 313 |
+
text = excluded.text,
|
| 314 |
+
created_at_x = excluded.created_at_x,
|
| 315 |
+
original_url = excluded.original_url,
|
| 316 |
+
conversation_id = excluded.conversation_id,
|
| 317 |
+
like_count = excluded.like_count,
|
| 318 |
+
reply_count = excluded.reply_count,
|
| 319 |
+
repost_count = excluded.repost_count,
|
| 320 |
+
quote_count = excluded.quote_count,
|
| 321 |
+
last_fetched_at = excluded.last_fetched_at,
|
| 322 |
+
source_job_id = excluded.source_job_id,
|
| 323 |
+
raw_json = excluded.raw_json,
|
| 324 |
+
data_source = excluded.data_source
|
| 325 |
+
"#,
|
| 326 |
+
)
|
| 327 |
+
.bind(&post.id)
|
| 328 |
+
.bind(author_x_user_id)
|
| 329 |
+
.bind(author_username)
|
| 330 |
+
.bind(&post.text)
|
| 331 |
+
.bind(&post.created_at)
|
| 332 |
+
.bind(original_url)
|
| 333 |
+
.bind(&post.conversation_id)
|
| 334 |
+
.bind(
|
| 335 |
+
post.public_metrics
|
| 336 |
+
.as_ref()
|
| 337 |
+
.and_then(|value| value.like_count),
|
| 338 |
+
)
|
| 339 |
+
.bind(
|
| 340 |
+
post.public_metrics
|
| 341 |
+
.as_ref()
|
| 342 |
+
.and_then(|value| value.reply_count),
|
| 343 |
+
)
|
| 344 |
+
.bind(
|
| 345 |
+
post.public_metrics
|
| 346 |
+
.as_ref()
|
| 347 |
+
.and_then(|value| value.retweet_count),
|
| 348 |
+
)
|
| 349 |
+
.bind(
|
| 350 |
+
post.public_metrics
|
| 351 |
+
.as_ref()
|
| 352 |
+
.and_then(|value| value.quote_count),
|
| 353 |
+
)
|
| 354 |
+
.bind(&now)
|
| 355 |
+
.bind(&now)
|
| 356 |
+
.bind(job_id)
|
| 357 |
+
.bind(serde_json::to_string(&post.raw_json)?)
|
| 358 |
+
.execute(&mut *connection)
|
| 359 |
+
.await?;
|
| 360 |
+
|
| 361 |
+
for (index, media_key) in post.media_keys.iter().enumerate() {
|
| 362 |
+
sqlx::query(
|
| 363 |
+
"INSERT OR REPLACE INTO post_media (post_id, media_key, display_order) VALUES (?, ?, ?)",
|
| 364 |
+
)
|
| 365 |
+
.bind(&post.id)
|
| 366 |
+
.bind(media_key)
|
| 367 |
+
.bind(index as i64)
|
| 368 |
+
.execute(&mut *connection)
|
| 369 |
+
.await?;
|
| 370 |
+
}
|
| 371 |
+
Ok(())
|
| 372 |
+
}
|
| 373 |
+
|
| 374 |
+
async fn save_media(connection: &mut SqliteConnection, media: &XMedia) -> anyhow::Result<()> {
|
| 375 |
+
sqlx::query(
|
| 376 |
+
r#"
|
| 377 |
+
INSERT INTO media (
|
| 378 |
+
media_key, media_type, original_url, preview_url, width, height, duration_ms,
|
| 379 |
+
download_status, raw_json
|
| 380 |
+
)
|
| 381 |
+
VALUES (?, ?, ?, ?, ?, ?, ?, 'metadata_only', ?)
|
| 382 |
+
ON CONFLICT(media_key) DO UPDATE SET
|
| 383 |
+
media_type = excluded.media_type,
|
| 384 |
+
original_url = excluded.original_url,
|
| 385 |
+
preview_url = excluded.preview_url,
|
| 386 |
+
width = excluded.width,
|
| 387 |
+
height = excluded.height,
|
| 388 |
+
duration_ms = excluded.duration_ms,
|
| 389 |
+
raw_json = excluded.raw_json
|
| 390 |
+
"#,
|
| 391 |
+
)
|
| 392 |
+
.bind(&media.media_key)
|
| 393 |
+
.bind(&media.media_type)
|
| 394 |
+
.bind(&media.url)
|
| 395 |
+
.bind(&media.preview_image_url)
|
| 396 |
+
.bind(media.width)
|
| 397 |
+
.bind(media.height)
|
| 398 |
+
.bind(media.duration_ms)
|
| 399 |
+
.bind(serde_json::to_string(&media.raw_json)?)
|
| 400 |
+
.execute(connection)
|
| 401 |
+
.await?;
|
| 402 |
+
Ok(())
|
| 403 |
+
}
|
| 404 |
+
|
| 405 |
+
#[cfg(test)]
|
| 406 |
+
mod tests {
|
| 407 |
+
use sqlx::{Connection, SqliteConnection};
|
| 408 |
+
use std::sync::atomic::AtomicBool;
|
| 409 |
+
use std::time::Duration;
|
| 410 |
+
use tempfile::tempdir;
|
| 411 |
+
use wiremock::matchers::{header, method, path, query_param};
|
| 412 |
+
use wiremock::{Mock, MockServer, ResponseTemplate};
|
| 413 |
+
|
| 414 |
+
use super::{auto_fetch_pages_for_task_async, fetch_one_page_for_task_async};
|
| 415 |
+
use crate::config::settings::AppSettings;
|
| 416 |
+
use crate::database::connection::open_or_create_database;
|
| 417 |
+
use crate::services::account_service::save_account_profile;
|
| 418 |
+
use crate::services::crawl_task_service::create_crawl_task;
|
| 419 |
+
use crate::services::x_api_service::{XAccountProfile, set_scoped_test_base_url};
|
| 420 |
+
|
| 421 |
+
#[tokio::test]
|
| 422 |
+
async fn fetches_and_saves_one_page() -> anyhow::Result<()> {
|
| 423 |
+
let server = MockServer::start().await;
|
| 424 |
+
let _base_url_guard = set_scoped_test_base_url(server.uri());
|
| 425 |
+
Mock::given(method("GET"))
|
| 426 |
+
.and(path("/2/users/123/tweets"))
|
| 427 |
+
.and(query_param("max_results", "10"))
|
| 428 |
+
.and(header("authorization", "Bearer test-token"))
|
| 429 |
+
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
|
| 430 |
+
"data": [
|
| 431 |
+
{ "id": "post-1", "text": "hello", "created_at": "2026-07-11T00:00:00Z", "public_metrics": { "like_count": 1, "reply_count": 2, "retweet_count": 3, "quote_count": 4 }, "attachments": { "media_keys": ["media-1"] } }
|
| 432 |
+
],
|
| 433 |
+
"includes": {
|
| 434 |
+
"media": [
|
| 435 |
+
{ "media_key": "media-1", "type": "photo", "url": "https://example.com/image.jpg", "width": 640, "height": 480 }
|
| 436 |
+
]
|
| 437 |
+
},
|
| 438 |
+
"meta": { "next_token": "next-page" }
|
| 439 |
+
})))
|
| 440 |
+
.up_to_n_times(1)
|
| 441 |
+
.mount(&server)
|
| 442 |
+
.await;
|
| 443 |
+
Mock::given(method("GET"))
|
| 444 |
+
.and(path("/2/users/123/tweets"))
|
| 445 |
+
.and(query_param("max_results", "10"))
|
| 446 |
+
.and(query_param("pagination_token", "next-page"))
|
| 447 |
+
.and(header("authorization", "Bearer test-token"))
|
| 448 |
+
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
|
| 449 |
+
"data": [
|
| 450 |
+
{ "id": "post-2", "text": "world", "created_at": "2026-07-11T00:01:00Z" }
|
| 451 |
+
],
|
| 452 |
+
"meta": { "result_count": 1 }
|
| 453 |
+
})))
|
| 454 |
+
.mount(&server)
|
| 455 |
+
.await;
|
| 456 |
+
|
| 457 |
+
let temp_dir = tempdir()?;
|
| 458 |
+
let database_path = temp_dir.path().join("archive.db");
|
| 459 |
+
open_or_create_database(&database_path).await?;
|
| 460 |
+
save_account_profile(&database_path, &test_profile()).await?;
|
| 461 |
+
let job = create_crawl_task(&database_path, "alice", &AppSettings::default()).await?;
|
| 462 |
+
|
| 463 |
+
let result =
|
| 464 |
+
fetch_one_page_for_task_async(&database_path, &job.job_id, "test-token").await?;
|
| 465 |
+
|
| 466 |
+
assert_eq!(result.received, 1);
|
| 467 |
+
assert_eq!(result.saved, 1);
|
| 468 |
+
assert_eq!(result.media_saved, 1);
|
| 469 |
+
assert!(result.has_next_page);
|
| 470 |
+
let pool =
|
| 471 |
+
sqlx::SqlitePool::connect(&format!("sqlite://{}", database_path.display())).await?;
|
| 472 |
+
let text: String = sqlx::query_scalar("SELECT text FROM posts WHERE x_post_id = 'post-1'")
|
| 473 |
+
.fetch_one(&pool)
|
| 474 |
+
.await?;
|
| 475 |
+
assert_eq!(text, "hello");
|
| 476 |
+
let media_type: String =
|
| 477 |
+
sqlx::query_scalar("SELECT media_type FROM media WHERE media_key = 'media-1'")
|
| 478 |
+
.fetch_one(&pool)
|
| 479 |
+
.await?;
|
| 480 |
+
assert_eq!(media_type, "photo");
|
| 481 |
+
let linked_media: String =
|
| 482 |
+
sqlx::query_scalar("SELECT media_key FROM post_media WHERE post_id = 'post-1'")
|
| 483 |
+
.fetch_one(&pool)
|
| 484 |
+
.await?;
|
| 485 |
+
assert_eq!(linked_media, "media-1");
|
| 486 |
+
let checkpoint: String =
|
| 487 |
+
sqlx::query_scalar("SELECT pagination_token FROM crawl_checkpoints WHERE job_id = ?")
|
| 488 |
+
.bind(&job.job_id)
|
| 489 |
+
.fetch_one(&pool)
|
| 490 |
+
.await?;
|
| 491 |
+
assert_eq!(checkpoint, "next-page");
|
| 492 |
+
|
| 493 |
+
let second_result =
|
| 494 |
+
fetch_one_page_for_task_async(&database_path, &job.job_id, "test-token").await?;
|
| 495 |
+
assert_eq!(second_result.received, 1);
|
| 496 |
+
assert_eq!(second_result.saved, 1);
|
| 497 |
+
assert_eq!(second_result.media_saved, 0);
|
| 498 |
+
assert!(!second_result.has_next_page);
|
| 499 |
+
let second_text: String =
|
| 500 |
+
sqlx::query_scalar("SELECT text FROM posts WHERE x_post_id = 'post-2'")
|
| 501 |
+
.fetch_one(&pool)
|
| 502 |
+
.await?;
|
| 503 |
+
assert_eq!(second_text, "world");
|
| 504 |
+
let checkpoint_after_second: Option<String> =
|
| 505 |
+
sqlx::query_scalar("SELECT pagination_token FROM crawl_checkpoints WHERE job_id = ?")
|
| 506 |
+
.bind(&job.job_id)
|
| 507 |
+
.fetch_one(&pool)
|
| 508 |
+
.await?;
|
| 509 |
+
assert_eq!(checkpoint_after_second, None);
|
| 510 |
+
Ok(())
|
| 511 |
+
}
|
| 512 |
+
|
| 513 |
+
#[tokio::test]
|
| 514 |
+
async fn marks_job_failed_when_post_fetch_fails() -> anyhow::Result<()> {
|
| 515 |
+
let server = MockServer::start().await;
|
| 516 |
+
let _base_url_guard = set_scoped_test_base_url(server.uri());
|
| 517 |
+
Mock::given(method("GET"))
|
| 518 |
+
.and(path("/2/users/123/tweets"))
|
| 519 |
+
.and(query_param("max_results", "10"))
|
| 520 |
+
.and(header("authorization", "Bearer test-token"))
|
| 521 |
+
.respond_with(ResponseTemplate::new(500).set_body_string("server error"))
|
| 522 |
+
.mount(&server)
|
| 523 |
+
.await;
|
| 524 |
+
|
| 525 |
+
let temp_dir = tempdir()?;
|
| 526 |
+
let database_path = temp_dir.path().join("archive.db");
|
| 527 |
+
open_or_create_database(&database_path).await?;
|
| 528 |
+
save_account_profile(&database_path, &test_profile()).await?;
|
| 529 |
+
let job = create_crawl_task(&database_path, "alice", &AppSettings::default()).await?;
|
| 530 |
+
|
| 531 |
+
let result = fetch_one_page_for_task_async(&database_path, &job.job_id, "test-token").await;
|
| 532 |
+
|
| 533 |
+
assert!(result.is_err());
|
| 534 |
+
let pool =
|
| 535 |
+
sqlx::SqlitePool::connect(&format!("sqlite://{}", database_path.display())).await?;
|
| 536 |
+
let (status, error_count, last_error): (String, i64, Option<String>) =
|
| 537 |
+
sqlx::query_as("SELECT status, error_count, last_error FROM crawl_jobs WHERE id = ?")
|
| 538 |
+
.bind(&job.job_id)
|
| 539 |
+
.fetch_one(&pool)
|
| 540 |
+
.await?;
|
| 541 |
+
assert_eq!(status, "failed");
|
| 542 |
+
assert_eq!(error_count, 1);
|
| 543 |
+
assert!(
|
| 544 |
+
last_error
|
| 545 |
+
.unwrap_or_default()
|
| 546 |
+
.contains("X API 返回异常状态")
|
| 547 |
+
);
|
| 548 |
+
Ok(())
|
| 549 |
+
}
|
| 550 |
+
|
| 551 |
+
#[tokio::test]
|
| 552 |
+
async fn auto_fetches_until_last_page() -> anyhow::Result<()> {
|
| 553 |
+
let server = MockServer::start().await;
|
| 554 |
+
let _base_url_guard = set_scoped_test_base_url(server.uri());
|
| 555 |
+
Mock::given(method("GET"))
|
| 556 |
+
.and(path("/2/users/123/tweets"))
|
| 557 |
+
.and(query_param("max_results", "10"))
|
| 558 |
+
.and(header("authorization", "Bearer test-token"))
|
| 559 |
+
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
|
| 560 |
+
"data": [{ "id": "post-a", "text": "first" }],
|
| 561 |
+
"meta": { "next_token": "next-page" }
|
| 562 |
+
})))
|
| 563 |
+
.up_to_n_times(1)
|
| 564 |
+
.mount(&server)
|
| 565 |
+
.await;
|
| 566 |
+
Mock::given(method("GET"))
|
| 567 |
+
.and(path("/2/users/123/tweets"))
|
| 568 |
+
.and(query_param("max_results", "10"))
|
| 569 |
+
.and(query_param("pagination_token", "next-page"))
|
| 570 |
+
.and(header("authorization", "Bearer test-token"))
|
| 571 |
+
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
|
| 572 |
+
"data": [{ "id": "post-b", "text": "second" }],
|
| 573 |
+
"meta": { "result_count": 1 }
|
| 574 |
+
})))
|
| 575 |
+
.mount(&server)
|
| 576 |
+
.await;
|
| 577 |
+
|
| 578 |
+
let temp_dir = tempdir()?;
|
| 579 |
+
let database_path = temp_dir.path().join("archive.db");
|
| 580 |
+
open_or_create_database(&database_path).await?;
|
| 581 |
+
save_account_profile(&database_path, &test_profile()).await?;
|
| 582 |
+
let job = create_crawl_task(&database_path, "alice", &AppSettings::default()).await?;
|
| 583 |
+
|
| 584 |
+
let stop_requested = AtomicBool::new(false);
|
| 585 |
+
let result = auto_fetch_pages_for_task_async(
|
| 586 |
+
&database_path,
|
| 587 |
+
&job.job_id,
|
| 588 |
+
"test-token",
|
| 589 |
+
3,
|
| 590 |
+
Duration::ZERO,
|
| 591 |
+
&stop_requested,
|
| 592 |
+
)
|
| 593 |
+
.await?;
|
| 594 |
+
|
| 595 |
+
assert_eq!(result.pages_fetched, 2);
|
| 596 |
+
assert_eq!(result.posts_received, 2);
|
| 597 |
+
assert!(result.stopped_because_complete);
|
| 598 |
+
assert!(!result.stopped_by_request);
|
| 599 |
+
Ok(())
|
| 600 |
+
}
|
| 601 |
+
|
| 602 |
+
#[tokio::test]
|
| 603 |
+
async fn auto_fetch_respects_stop_request_before_next_page() -> anyhow::Result<()> {
|
| 604 |
+
let temp_dir = tempdir()?;
|
| 605 |
+
let database_path = temp_dir.path().join("archive.db");
|
| 606 |
+
open_or_create_database(&database_path).await?;
|
| 607 |
+
save_account_profile(&database_path, &test_profile()).await?;
|
| 608 |
+
let job = create_crawl_task(&database_path, "alice", &AppSettings::default()).await?;
|
| 609 |
+
|
| 610 |
+
let stop_requested = AtomicBool::new(true);
|
| 611 |
+
let result = auto_fetch_pages_for_task_async(
|
| 612 |
+
&database_path,
|
| 613 |
+
&job.job_id,
|
| 614 |
+
"test-token",
|
| 615 |
+
3,
|
| 616 |
+
Duration::ZERO,
|
| 617 |
+
&stop_requested,
|
| 618 |
+
)
|
| 619 |
+
.await?;
|
| 620 |
+
|
| 621 |
+
let status: String = sqlx::query_scalar("SELECT status FROM crawl_jobs WHERE id = ?")
|
| 622 |
+
.bind(&job.job_id)
|
| 623 |
+
.fetch_one(&mut SqliteConnection::connect(&database_path.to_string_lossy()).await?)
|
| 624 |
+
.await?;
|
| 625 |
+
|
| 626 |
+
assert_eq!(result.pages_fetched, 0);
|
| 627 |
+
assert_eq!(result.posts_received, 0);
|
| 628 |
+
assert!(result.stopped_by_request);
|
| 629 |
+
assert!(!result.stopped_because_complete);
|
| 630 |
+
assert_eq!(status, "stopped");
|
| 631 |
+
Ok(())
|
| 632 |
+
}
|
| 633 |
+
|
| 634 |
+
fn test_profile() -> XAccountProfile {
|
| 635 |
+
XAccountProfile {
|
| 636 |
+
id: "123".to_owned(),
|
| 637 |
+
username: "alice".to_owned(),
|
| 638 |
+
name: Some("Alice".to_owned()),
|
| 639 |
+
description: None,
|
| 640 |
+
profile_image_url: None,
|
| 641 |
+
created_at: None,
|
| 642 |
+
protected: Some(false),
|
| 643 |
+
verified: None,
|
| 644 |
+
public_metrics: None,
|
| 645 |
+
raw_json: serde_json::json!({"data":{"id":"123"}}),
|
| 646 |
+
}
|
| 647 |
+
}
|
| 648 |
+
}
|
| 649 |
+
|