editer
This commit is contained in:
1 parent
ad987111a3
commit
c9e61f38c5
89 files changed
+11775
-3155
No files matched your search
@@ -0,0 +1,231 @@
|
||||
//! 「用 Thing 打开」的参数解析与事件投递。
|
||||
//!
|
||||
//! # 两条入口,同一份逻辑
|
||||
//!
|
||||
//! 1. **冷启动**:安装器注册的文件关联让 Windows 用 `thing.exe <文件路径>` 启动本应用;
|
||||
//! 资源管理器右键菜单(`HKCU\...\shell\ThingEditor`)同样以参数形式传入文件/文件夹;
|
||||
//! 2. **热启动**:应用已在运行时再次打开,会起第二个进程,由
|
||||
//! `tauri-plugin-single-instance` 把它的命令行参数转交给第一个实例。
|
||||
//!
|
||||
//! 两条路径的输入形态完全一样(都是命令行参数),因此共用 [`open_target_from_args`]。
|
||||
//! 解析成功后统一发事件(文件走 `editor-open-file`、文件夹走 `editor-open-folder`),
|
||||
//! **窗口由前端创建** —— Rust 侧不持有窗口 label 策略。
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Mutex;
|
||||
|
||||
use serde::Serialize;
|
||||
use specta::Type;
|
||||
|
||||
/// 一个待打开目标(文件或文件夹)。
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum OpenTarget {
|
||||
File(PathBuf),
|
||||
/// 文件夹:由编辑器「本地目录」面板承载
|
||||
Folder(PathBuf),
|
||||
}
|
||||
|
||||
impl OpenTarget {
|
||||
pub fn path(&self) -> &Path {
|
||||
match self {
|
||||
Self::File(p) | Self::Folder(p) => p,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn kind(&self) -> &'static str {
|
||||
match self {
|
||||
Self::File(_) => "file",
|
||||
Self::Folder(_) => "folder",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 回传给前端的待打开目标。
|
||||
#[derive(Debug, Clone, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct OpenTargetPayload {
|
||||
/// 绝对路径
|
||||
pub path: String,
|
||||
/// `"file"` | `"folder"`
|
||||
pub kind: String,
|
||||
}
|
||||
|
||||
impl From<&OpenTarget> for OpenTargetPayload {
|
||||
fn from(target: &OpenTarget) -> Self {
|
||||
Self {
|
||||
path: target.path().to_string_lossy().to_string(),
|
||||
kind: target.kind().to_string(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 「启动时命令行指定的目标」缓存。
|
||||
///
|
||||
/// # 为什么需要缓存而不是启动时直接 `emit`
|
||||
///
|
||||
/// 冷启动的顺序是:`setup` 跑完 → 创建主窗口 → WebView 加载前端 → 前端注册监听。
|
||||
/// 在 `setup` 里 `emit` 时前端还没开始监听,事件**直接丢掉**了 —— 表现是
|
||||
/// 「双击 .md 打开了应用,但笔记没打开」。
|
||||
///
|
||||
/// 因此这里把目标存下来,由前端在注册完监听后**主动取一次**
|
||||
/// (`editor_take_pending_file`)。取走即清空,避免下次打开窗口时又被翻出来。
|
||||
static PENDING: std::sync::OnceLock<Mutex<Option<OpenTarget>>> = std::sync::OnceLock::new();
|
||||
|
||||
fn pending_slot() -> &'static Mutex<Option<OpenTarget>> {
|
||||
PENDING.get_or_init(|| Mutex::new(None))
|
||||
}
|
||||
|
||||
/// 记下「启动时想打开的目标」(由 `setup` 调用)。
|
||||
pub fn remember_pending_target(target: OpenTarget) {
|
||||
if let Ok(mut slot) = pending_slot().lock() {
|
||||
*slot = Some(target);
|
||||
}
|
||||
}
|
||||
|
||||
/// 取出并清空待打开目标(由 `editor_take_pending_file` 命令调用)。
|
||||
pub fn take_pending_target() -> Option<OpenTargetPayload> {
|
||||
pending_slot()
|
||||
.lock()
|
||||
.ok()
|
||||
.and_then(|mut slot| slot.take())
|
||||
.map(|target| OpenTargetPayload::from(&target))
|
||||
}
|
||||
|
||||
/// 从一组命令行参数里挑出「看起来是要打开的路径」。
|
||||
///
|
||||
/// 只认「**存在**的路径」,其余一律忽略 —— 宁可漏开一个窗口,也不要因为一个开关
|
||||
/// 参数把主窗口的启动逻辑搞乱。目录优先(右键文件夹的场景)。
|
||||
pub fn open_target_from_args<I: IntoIterator<Item = String>>(args: I) -> Option<OpenTarget> {
|
||||
for arg in args {
|
||||
let trimmed = arg.trim().trim_matches('"');
|
||||
if trimmed.is_empty() || trimmed.starts_with('-') {
|
||||
continue;
|
||||
}
|
||||
let path = PathBuf::from(trimmed);
|
||||
if path.is_dir() {
|
||||
return Some(OpenTarget::Folder(path));
|
||||
}
|
||||
if path.is_file() {
|
||||
return Some(OpenTarget::File(path));
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// 从一组命令行参数里挑出「看起来是笔记文件」的那个路径(仅 `.md`/`.markdown`/`.mdx`)。
|
||||
///
|
||||
/// 实际启动路径用的是 [`open_target_from_args`](接受任意文件与文件夹,以支持资源
|
||||
/// 管理器右键菜单);这个更严格的入口现在**只服务于单测**,故仅测试构建时编译。
|
||||
#[cfg(test)]
|
||||
pub fn note_path_from_args<I: IntoIterator<Item = String>>(args: I) -> Option<PathBuf> {
|
||||
for arg in args {
|
||||
let trimmed = arg.trim().trim_matches('"');
|
||||
if trimmed.is_empty() || trimmed.starts_with('-') {
|
||||
continue;
|
||||
}
|
||||
let lower = trimmed.to_ascii_lowercase();
|
||||
let is_note_ext =
|
||||
lower.ends_with(".md") || lower.ends_with(".markdown") || lower.ends_with(".mdx");
|
||||
if !is_note_ext {
|
||||
continue;
|
||||
}
|
||||
let path = PathBuf::from(trimmed);
|
||||
if path.is_file() {
|
||||
return Some(path);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// 通知前端「要打开这个目标」(窗口由前端创建)。
|
||||
pub fn emit_open_target(app: &tauri::AppHandle, target: &OpenTarget) {
|
||||
use tauri::Emitter;
|
||||
let payload = serde_json::json!({ "path": target.path().to_string_lossy() });
|
||||
let event = match target {
|
||||
OpenTarget::File(_) => crate::constants::events::EDITOR_OPEN_FILE,
|
||||
OpenTarget::Folder(_) => crate::constants::events::EDITOR_OPEN_FOLDER,
|
||||
};
|
||||
if let Err(e) = app.emit(event, payload) {
|
||||
crate::logger::log_warn("editor", &format!("发出打开目标事件失败: {e}"));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn temp_note(name: &str) -> PathBuf {
|
||||
let dir = std::env::temp_dir().join(format!("thing-notes-args-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join(name);
|
||||
std::fs::write(&path, "# x").unwrap();
|
||||
path
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn picks_markdown_path_and_ignores_flags() {
|
||||
let note = temp_note("会议.md");
|
||||
let args = vec![
|
||||
"--some-flag".to_string(),
|
||||
"not-a-file".to_string(),
|
||||
note.to_string_lossy().to_string(),
|
||||
];
|
||||
assert_eq!(note_path_from_args(args), Some(note.clone()));
|
||||
|
||||
let _ = std::fs::remove_file(¬e);
|
||||
let _ = std::fs::remove_dir_all(note.parent().unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn accepts_markdown_and_mdx_too() {
|
||||
let note = temp_note("a.markdown");
|
||||
assert_eq!(
|
||||
note_path_from_args(vec![note.to_string_lossy().to_string()]),
|
||||
Some(note.clone())
|
||||
);
|
||||
let _ = std::fs::remove_file(¬e);
|
||||
let _ = std::fs::remove_dir_all(note.parent().unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ignores_non_markdown_and_missing_files() {
|
||||
// 非笔记扩展名
|
||||
assert_eq!(note_path_from_args(vec!["C:\\a\\b.txt".to_string()]), None);
|
||||
// 不存在的 .md:静默忽略(否则会开一个空窗口)
|
||||
assert_eq!(
|
||||
note_path_from_args(vec!["C:\\definitely\\missing\\x.md".to_string()]),
|
||||
None
|
||||
);
|
||||
// 空参数与开关
|
||||
assert_eq!(
|
||||
note_path_from_args(vec!["".to_string(), "-v".to_string()]),
|
||||
None
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strips_surrounding_quotes() {
|
||||
let note = temp_note("带 空格.md");
|
||||
let quoted = format!("\"{}\"", note.to_string_lossy());
|
||||
assert_eq!(note_path_from_args(vec![quoted]), Some(note.clone()));
|
||||
let _ = std::fs::remove_file(¬e);
|
||||
let _ = std::fs::remove_dir_all(note.parent().unwrap());
|
||||
}
|
||||
|
||||
/// 右键菜单:任意扩展名的文件都要被接受(不只 .md)。
|
||||
#[test]
|
||||
fn open_target_accepts_any_file_and_folder() {
|
||||
let file = temp_note("plain.txt");
|
||||
match open_target_from_args(vec![file.to_string_lossy().to_string()]) {
|
||||
Some(OpenTarget::File(p)) => assert_eq!(p, file),
|
||||
other => panic!("应识别为文件: {other:?}"),
|
||||
}
|
||||
let dir = file.parent().unwrap().to_path_buf();
|
||||
match open_target_from_args(vec![dir.to_string_lossy().to_string()]) {
|
||||
Some(OpenTarget::Folder(p)) => assert_eq!(p, dir),
|
||||
other => panic!("应识别为文件夹: {other:?}"),
|
||||
}
|
||||
let _ = std::fs::remove_file(&file);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,381 @@
|
||||
//! zip 快照备份:整库打包上传 + 远端轮转 + 恢复。
|
||||
//!
|
||||
//! # 为什么「快照」比「双向同步」更该先做
|
||||
//!
|
||||
//! 规划 §3.6 的判断:对「只是要个备份」的用户,一次上传一个完整 zip 比双向同步
|
||||
//! **可靠得多** —— 同步要考虑冲突、删除传播、时钟偏差;快照只有一个动作(上传),
|
||||
//! 失败就是失败,不会在半途产生「一半新一半旧」的库。
|
||||
//!
|
||||
//! 因此本模块与 `webdav/sync.rs` 是两条独立路径,用的是同一个客户端。
|
||||
//!
|
||||
//! # 打包内容
|
||||
//!
|
||||
//! 库内全部 `.md` 与 `assets/` 下的附件,外加一份 `thing-notes-manifest.json`
|
||||
//! (记录快照时间、文件数、格式版本)。**不打包 `.editor/`**:里面是索引与同步基线,
|
||||
//! 属于本机私有数据,跟着快照跑到另一台机器上只会误导那边的基线判断。
|
||||
//!
|
||||
//! # 轮转
|
||||
//!
|
||||
//! 上传后列出远端 `backups/` 下的快照,按**文件名里的时间戳**倒序保留
|
||||
//! [`WebdavSettings::backup_keep`] 份,其余删除。用文件名排序而不是远端 mtime:
|
||||
//! 各家服务端的 mtime 精度与时钟都不一致,而文件名是我们自己写的、单调递增。
|
||||
|
||||
use std::io::Write;
|
||||
use std::path::{Path, PathBuf};
|
||||
use super::webdav::client::WebdavClient;
|
||||
use crate::editor::library;
|
||||
use crate::editor::types::{BackupReport, BackupSnapshot, WebdavSettings};
|
||||
|
||||
/// 远端存放快照的目录(相对远端根)。
|
||||
pub const BACKUP_DIR: &str = "backups";
|
||||
/// 快照文件名前缀。
|
||||
const SNAPSHOT_PREFIX: &str = "thing-notes-";
|
||||
/// 清单文件名(打包进 zip,供恢复时校验)。
|
||||
const MANIFEST_NAME: &str = "thing-notes-manifest.json";
|
||||
|
||||
/// 快照清单。
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct SnapshotManifest {
|
||||
version: u32,
|
||||
created_at: String,
|
||||
files: u32,
|
||||
}
|
||||
|
||||
/// 打包库根为 zip 字节流(不触网,便于单测)。
|
||||
pub fn build_snapshot(root: &Path) -> Result<(Vec<u8>, u32), String> {
|
||||
library::ensure_library(root)?;
|
||||
let cursor = std::io::Cursor::new(Vec::new());
|
||||
let mut writer = zip::ZipWriter::new(cursor);
|
||||
let options: zip::write::FileOptions<'_, ()> = zip::write::FileOptions::default()
|
||||
.compression_method(zip::CompressionMethod::Deflated);
|
||||
|
||||
let mut files = 0u32;
|
||||
for entry in walkdir::WalkDir::new(root)
|
||||
.max_depth(library::MAX_DEPTH)
|
||||
.into_iter()
|
||||
.filter_map(Result::ok)
|
||||
{
|
||||
if !entry.file_type().is_file() {
|
||||
continue;
|
||||
}
|
||||
let rel = library::rel_string(root, entry.path());
|
||||
if rel.is_empty() {
|
||||
continue;
|
||||
}
|
||||
// `.editor/` 是本机私有数据(索引 + 同步基线),不进快照
|
||||
if rel.split('/').any(|part| part.starts_with('.')) {
|
||||
continue;
|
||||
}
|
||||
let bytes = match std::fs::read(entry.path()) {
|
||||
Ok(bytes) => bytes,
|
||||
Err(e) => {
|
||||
crate::logger::log_warn("editor", &format!("快照跳过 {rel}(读取失败: {e})"));
|
||||
continue;
|
||||
}
|
||||
};
|
||||
writer
|
||||
.start_file(rel.clone(), options)
|
||||
.map_err(|e| format!("写入快照条目失败: {e}"))?;
|
||||
writer
|
||||
.write_all(&bytes)
|
||||
.map_err(|e| format!("写入快照内容失败: {e}"))?;
|
||||
files += 1;
|
||||
}
|
||||
|
||||
// 清单最后写:它要记录真实打包到的文件数
|
||||
let manifest = SnapshotManifest {
|
||||
version: 1,
|
||||
created_at: chrono::Local::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true),
|
||||
files,
|
||||
};
|
||||
let manifest_bytes = serde_json::to_vec_pretty(&manifest)
|
||||
.map_err(|e| format!("序列化快照清单失败: {e}"))?;
|
||||
writer
|
||||
.start_file(MANIFEST_NAME, options)
|
||||
.map_err(|e| format!("写入快照清单失败: {e}"))?;
|
||||
writer
|
||||
.write_all(&manifest_bytes)
|
||||
.map_err(|e| format!("写入快照清单内容失败: {e}"))?;
|
||||
|
||||
let cursor = writer.finish().map_err(|e| format!("完成快照打包失败: {e}"))?;
|
||||
Ok((cursor.into_inner(), files))
|
||||
}
|
||||
|
||||
/// 上传一份快照并做轮转。返回备份报告。
|
||||
pub fn upload_snapshot(
|
||||
root: &Path,
|
||||
settings: &WebdavSettings,
|
||||
client: &WebdavClient,
|
||||
) -> Result<BackupReport, String> {
|
||||
let (bytes, files) = build_snapshot(root)?;
|
||||
let name = format!(
|
||||
"{SNAPSHOT_PREFIX}{}.zip",
|
||||
chrono::Local::now().format("%Y%m%d-%H%M%S")
|
||||
);
|
||||
let remote_path = format!("{BACKUP_DIR}/{name}");
|
||||
client.put(&remote_path, bytes.clone())?;
|
||||
|
||||
let pruned = prune_snapshots(client, settings.backup_keep)?;
|
||||
Ok(BackupReport {
|
||||
name,
|
||||
bytes: bytes.len() as u64,
|
||||
files,
|
||||
pruned,
|
||||
})
|
||||
}
|
||||
|
||||
/// 轮转:只保留最新的 `keep` 份。
|
||||
pub fn prune_snapshots(client: &WebdavClient, keep: u32) -> Result<Vec<String>, String> {
|
||||
let keep = keep.max(1) as usize;
|
||||
let mut snapshots = list_snapshots(client)?;
|
||||
if snapshots.len() <= keep {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
// 文件名里的时间戳是 `%Y%m%d-%H%M%S`,字典序即时间序
|
||||
snapshots.sort_by(|a, b| a.name.cmp(&b.name));
|
||||
let outdated = snapshots.len() - keep;
|
||||
let mut pruned = Vec::new();
|
||||
for snapshot in snapshots.into_iter().take(outdated) {
|
||||
if let Err(e) = client.delete(&format!("{BACKUP_DIR}/{}", snapshot.name)) {
|
||||
crate::logger::log_warn("editor", &format!("删除旧快照 {} 失败: {e}", snapshot.name));
|
||||
continue;
|
||||
}
|
||||
pruned.push(snapshot.name);
|
||||
}
|
||||
Ok(pruned)
|
||||
}
|
||||
|
||||
/// 列出远端已有的快照。
|
||||
pub fn list_snapshots(client: &WebdavClient) -> Result<Vec<BackupSnapshot>, String> {
|
||||
let entries = client.list(BACKUP_DIR)?;
|
||||
let Some(entries) = entries else {
|
||||
return Ok(Vec::new());
|
||||
};
|
||||
Ok(entries
|
||||
.into_iter()
|
||||
.filter(|entry| !entry.is_dir)
|
||||
.filter(|entry| {
|
||||
entry
|
||||
.rel_path
|
||||
.rsplit('/')
|
||||
.next()
|
||||
.map(|name| name.starts_with(SNAPSHOT_PREFIX) && name.ends_with(".zip"))
|
||||
.unwrap_or(false)
|
||||
})
|
||||
.map(|entry| BackupSnapshot {
|
||||
name: entry
|
||||
.rel_path
|
||||
.rsplit('/')
|
||||
.next()
|
||||
.unwrap_or_default()
|
||||
.to_string(),
|
||||
size: entry.size,
|
||||
modified: entry.modified,
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// 从快照恢复(**不覆盖已存在的本地文件**)。
|
||||
///
|
||||
/// 保守策略的理由:恢复的典型场景是「换机器」或「误删了几篇」。前者的本地基本是空的,
|
||||
/// 后者的本地有用户最近的工作 —— 覆盖会把「误删之前写的东西」一起冲掉。
|
||||
/// 需要时用户可以先在资源管理器里移走旧库,再恢复。
|
||||
pub fn restore_snapshot(
|
||||
root: &Path,
|
||||
client: &WebdavClient,
|
||||
name: &str,
|
||||
) -> Result<(u32, u32), String> {
|
||||
if name.contains('/') || name.contains('\\') || name.contains("..") {
|
||||
return Err("快照名不合法".to_string());
|
||||
}
|
||||
let bytes = client.get(&format!("{BACKUP_DIR}/{name}"))?;
|
||||
let mut archive = zip::ZipArchive::new(std::io::Cursor::new(bytes))
|
||||
.map_err(|e| format!("读取快照失败: {e}"))?;
|
||||
|
||||
let mut written = 0u32;
|
||||
let mut kept = 0u32;
|
||||
for index in 0..archive.len() {
|
||||
let mut file = archive
|
||||
.by_index(index)
|
||||
.map_err(|e| format!("读取快照条目失败: {e}"))?;
|
||||
let Some(entry_path) = file.enclosed_name().map(|p| p.to_path_buf()) else {
|
||||
// `enclosed_name` 会拒绝 `..` 与绝对路径 —— 恶意快照不能写到库外
|
||||
crate::logger::log_warn("editor", "快照里有越界路径,已跳过");
|
||||
continue;
|
||||
};
|
||||
let rel = entry_path.to_string_lossy().replace('\\', "/");
|
||||
if rel == MANIFEST_NAME || file.is_dir() {
|
||||
continue;
|
||||
}
|
||||
let target = library::safe_join(root, &rel)?;
|
||||
if target.exists() {
|
||||
kept += 1;
|
||||
continue;
|
||||
}
|
||||
if let Some(parent) = target.parent() {
|
||||
std::fs::create_dir_all(parent).map_err(|e| format!("创建目录失败: {e}"))?;
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
std::io::Read::read_to_end(&mut file, &mut out)
|
||||
.map_err(|e| format!("读取快照内容失败: {e}"))?;
|
||||
std::fs::write(&target, out).map_err(|e| format!("写入 {rel} 失败: {e}"))?;
|
||||
written += 1;
|
||||
}
|
||||
Ok((written, kept))
|
||||
}
|
||||
|
||||
/// 一次完整的「同步 + 备份」会话入口(命令层用)。
|
||||
///
|
||||
/// 返回(同步报告, 可选备份报告)。`with_backup` 为真时在同步之后追加一次快照 ——
|
||||
/// 「先同步再备份」的顺序是刻意的:备份应当是**同步之后的一致状态**,
|
||||
/// 而不是把一次半途失败的同步结果定格下来。
|
||||
pub fn sync_then_backup(
|
||||
root: &Path,
|
||||
settings: &WebdavSettings,
|
||||
client: &WebdavClient,
|
||||
app: &tauri::AppHandle,
|
||||
with_backup: bool,
|
||||
) -> Result<(super::webdav::sync::SyncReport, Option<BackupReport>), String> {
|
||||
let (plan, mut state, remote) = super::webdav::sync::build_plan(root, settings, client)?;
|
||||
let runner = super::webdav::sync::SyncRunner::new(client, root, app, plan.actions.len());
|
||||
let report = runner.run(&plan, &mut state, &remote);
|
||||
|
||||
// 只有「没有失败」时才推进基线:失败的一轮如果把基线写下去,
|
||||
// 那些没传成功的文件会被当成「已同步」,下次同步就静默漏掉了
|
||||
if report.failed == 0 {
|
||||
state.last_sync = chrono::Local::now().timestamp_millis().max(0) as u64;
|
||||
if let Err(e) = state.save(root) {
|
||||
crate::logger::log_warn("editor", &format!("保存同步基线失败: {e}"));
|
||||
}
|
||||
} else {
|
||||
crate::logger::log_warn(
|
||||
"editor",
|
||||
&format!("本轮有 {} 条失败,不推进同步基线", report.failed),
|
||||
);
|
||||
// 仍然保存「成功的那些」:SyncState 是按条更新的,未处理的条目保持旧基线,
|
||||
// 于是下一轮会把它们重新算作差异并重试
|
||||
if let Err(e) = state.save(root) {
|
||||
crate::logger::log_warn("editor", &format!("保存同步基线失败: {e}"));
|
||||
}
|
||||
}
|
||||
|
||||
let backup = if with_backup {
|
||||
Some(upload_snapshot(root, settings, client)?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
Ok((report, backup))
|
||||
}
|
||||
|
||||
/// 本地临时快照目录(供「导出快照到本地」与调试用)。
|
||||
///
|
||||
/// 与 [`upload_snapshot`] 共用 [`build_snapshot`],区别只是落盘而不是上传 ——
|
||||
/// 「我要一份备份,但不想连远端」是个很常见的诉求(比如先手动拷到网盘)。
|
||||
pub fn snapshot_to_file(root: &Path, dest: &Path) -> Result<u64, String> {
|
||||
let (bytes, _) = build_snapshot(root)?;
|
||||
if let Some(parent) = dest.parent() {
|
||||
std::fs::create_dir_all(parent).map_err(|e| format!("创建目录失败: {e}"))?;
|
||||
}
|
||||
std::fs::write(dest, &bytes).map_err(|e| format!("写入快照失败: {e}"))?;
|
||||
Ok(bytes.len() as u64)
|
||||
}
|
||||
|
||||
/// 库根的默认快照落点(用户点「导出快照到本地」时用)。
|
||||
pub fn default_snapshot_path(root: &Path) -> PathBuf {
|
||||
root.join(format!(
|
||||
"{SNAPSHOT_PREFIX}{}.zip",
|
||||
chrono::Local::now().format("%Y%m%d-%H%M%S")
|
||||
))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn temp_root(tag: &str) -> PathBuf {
|
||||
let root = std::env::temp_dir().join(format!("thing-notes-backup-{tag}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
std::fs::create_dir_all(root.join("assets")).unwrap();
|
||||
root
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn snapshot_excludes_private_dir() {
|
||||
let root = temp_root("build");
|
||||
std::fs::write(root.join("a.md"), "# A").unwrap();
|
||||
std::fs::create_dir_all(root.join("sub")).unwrap();
|
||||
std::fs::write(root.join("sub/b.md"), "# B").unwrap();
|
||||
std::fs::write(root.join("assets/pic.png"), [1u8, 2, 3]).unwrap();
|
||||
std::fs::create_dir_all(root.join(".editor")).unwrap();
|
||||
std::fs::write(root.join(".editor/editor.db"), "索引不该进快照").unwrap();
|
||||
|
||||
let (bytes, files) = build_snapshot(&root).unwrap();
|
||||
assert_eq!(files, 3, "两篇笔记 + 一个附件");
|
||||
assert!(!bytes.is_empty());
|
||||
|
||||
let mut archive = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
|
||||
let names: Vec<String> = (0..archive.len())
|
||||
.map(|i| archive.by_index(i).unwrap().name().to_string())
|
||||
.collect();
|
||||
assert!(names.contains(&"a.md".to_string()), "{names:?}");
|
||||
assert!(names.contains(&"sub/b.md".to_string()), "{names:?}");
|
||||
assert!(names.contains(&"assets/pic.png".to_string()), "{names:?}");
|
||||
assert!(names.contains(&MANIFEST_NAME.to_string()), "{names:?}");
|
||||
assert!(
|
||||
!names.iter().any(|n| n.starts_with(".editor")),
|
||||
"私有目录不该进快照: {names:?}"
|
||||
);
|
||||
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn restore_does_not_overwrite_existing_files() {
|
||||
let root = temp_root("restore");
|
||||
std::fs::write(root.join("a.md"), "新版").unwrap();
|
||||
std::fs::write(root.join("b.md"), "旧版").unwrap();
|
||||
let (bytes, _) = build_snapshot(&root).unwrap();
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
std::fs::create_dir_all(&root).unwrap();
|
||||
std::fs::write(root.join("a.md"), "本机已有内容").unwrap();
|
||||
|
||||
// 直接走「解包到库根」的那段逻辑(用本地 zip 代替远端下载)
|
||||
let mut archive = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
|
||||
let mut kept = 0u32;
|
||||
for index in 0..archive.len() {
|
||||
let mut file = archive.by_index(index).unwrap();
|
||||
let Some(path) = file.enclosed_name().map(|p| p.to_path_buf()) else {
|
||||
continue;
|
||||
};
|
||||
let rel = path.to_string_lossy().replace('\\', "/");
|
||||
if rel == MANIFEST_NAME || file.is_dir() {
|
||||
continue;
|
||||
}
|
||||
let target = library::safe_join(&root, &rel).unwrap();
|
||||
if target.exists() {
|
||||
kept += 1;
|
||||
continue;
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
std::io::Read::read_to_end(&mut file, &mut out).unwrap();
|
||||
std::fs::write(&target, out).unwrap();
|
||||
}
|
||||
assert_eq!(kept, 1, "已存在的 a.md 应被跳过");
|
||||
assert_eq!(std::fs::read_to_string(root.join("a.md")).unwrap(), "本机已有内容");
|
||||
assert_eq!(std::fs::read_to_string(root.join("b.md")).unwrap(), "旧版");
|
||||
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn snapshot_file_writing() {
|
||||
let root = temp_root("to-file");
|
||||
std::fs::write(root.join("a.md"), "# A").unwrap();
|
||||
let dest = root.join("out.zip");
|
||||
let size = snapshot_to_file(&root, &dest).unwrap();
|
||||
assert!(size > 0);
|
||||
assert!(dest.is_file());
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,977 @@
|
||||
//! 笔记模块 Tauri 命令层。
|
||||
//!
|
||||
//! 所有库操作都经 [`super::library`] 的路径安全校验、所有库外文件操作都经
|
||||
//! [`super::files`] 的授权白名单、所有 WebDAV 操作都经 [`super::webdav`] 的会话层;
|
||||
//! 命令本身只做几件事:解析当前库根 → 调下层 → 标记「本应用刚写过」→ 发事件。
|
||||
//!
|
||||
//! # 为什么每条命令都要先 `retarget`
|
||||
//!
|
||||
//! 索引服务是常驻 worker,它记着「自己挂在哪个库根上」。库根可以在设置里改,
|
||||
//! 而 worker 不知道这件事 —— 若命令层不主动告知,就会出现「侧栏显示新库、
|
||||
//! 搜索却在新库的旧索引里查」这种最难查的错。`retarget` 在库根未变时是两次
|
||||
//! 比较,成本可忽略。
|
||||
//!
|
||||
//! # 网络类命令为什么是异步的
|
||||
//!
|
||||
//! `tests_webdav` / `sync_now` / `backup_now` 会真的发 HTTP 请求(同步一个几百篇的
|
||||
//! 库可能跑几分钟)。Tauri 的同步命令会占住调用线程,因此这几个一律 `async` 并用
|
||||
//! `spawn_blocking` 把阻塞的 reqwest 调用挪到专用线程池 —— 既不卡 UI,也不卡
|
||||
//! Tauri 的命令线程池。
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
use tauri::{AppHandle, Emitter, State};
|
||||
|
||||
use super::backup;
|
||||
use super::export;
|
||||
use super::files;
|
||||
use super::import;
|
||||
use super::index::{
|
||||
NoteBacklinks, NoteIndexStats, NoteSearchHit, NoteSearchPage, NoteSearchQuery,
|
||||
};
|
||||
use super::index_service::{self, IndexService, NoteIndexReport};
|
||||
use super::library;
|
||||
use super::templates::{self, NoteTemplate};
|
||||
use super::types::{
|
||||
BackupReport, BackupSnapshot, ImportReport, LibraryEntry, LibraryInfo, NoteDoc, EditorSettings,
|
||||
SyncProgress,
|
||||
};
|
||||
use super::webdav::{self, WebdavTestResult};
|
||||
use super::EditorManager;
|
||||
use crate::constants::events;
|
||||
|
||||
/// 通知各窗口「库内容已变更」(新建/保存/重命名/删除/切换库根后)。
|
||||
fn emit_library_changed(app: &AppHandle) {
|
||||
if let Err(e) = app.emit(events::EDITOR_LIBRARY_CHANGED, ()) {
|
||||
crate::logger::log_warn("editor", &format!("发出库变更事件失败: {e}"));
|
||||
}
|
||||
}
|
||||
|
||||
/// 通知各窗口「设置已变更」(跨窗口同步,范式同 terminal-settings)。
|
||||
fn emit_settings_changed(app: &AppHandle) {
|
||||
if let Err(e) = app.emit(events::EDITOR_SETTINGS, ()) {
|
||||
crate::logger::log_warn("editor", &format!("发出设置变更事件失败: {e}"));
|
||||
}
|
||||
}
|
||||
|
||||
/// 当前库根(按设置解析),并确保目录存在。
|
||||
fn current_root(state: &EditorManager) -> PathBuf {
|
||||
let settings = state.load_settings();
|
||||
library::resolve_library_root(state.module_dir(), &settings)
|
||||
}
|
||||
|
||||
/// 取索引服务并把它的库根对齐到当前设置。
|
||||
fn indexed<'a>(app: &AppHandle, state: &EditorManager) -> Result<&'a IndexService, String> {
|
||||
let root = current_root(state);
|
||||
let service = index_service::service(app);
|
||||
service.retarget(root)?;
|
||||
Ok(service)
|
||||
}
|
||||
|
||||
/// 组装库状态概览。
|
||||
fn library_info(state: &EditorManager) -> Result<LibraryInfo, String> {
|
||||
let settings = state.load_settings();
|
||||
let root = library::resolve_library_root(state.module_dir(), &settings);
|
||||
library::ensure_library(&root)?;
|
||||
let entries = library::scan(&root)?;
|
||||
Ok(LibraryInfo {
|
||||
root: root.to_string_lossy().to_string(),
|
||||
is_custom: settings
|
||||
.library_root
|
||||
.as_deref()
|
||||
.map(|s| !s.trim().is_empty())
|
||||
.unwrap_or(false),
|
||||
note_count: library::count_notes(&entries),
|
||||
})
|
||||
}
|
||||
|
||||
/// 标记「本应用刚**批量**写过」,随后把库同步进索引。
|
||||
///
|
||||
/// 用于导入 / WebDAV 同步 / 恢复 / 模板导出这类**无法逐路径枚举**的操作:写完之后
|
||||
/// 在抑制窗口内的一切文件事件都当作自己写的。
|
||||
///
|
||||
/// 顺序重要:先标记(抑制窗口从写入那一刻算起),再同步。这里走全库增量同步而不是
|
||||
/// 「只索引这一篇」的快路径:单文件快路径要额外拼一份 wikilink 的 `stems` 映射,
|
||||
/// 而不完整的映射会让 `[[某笔记]]` 解析到错误位置;全量同步靠 (mtime,size) 跳过
|
||||
/// 未变文件,万篇规模也是毫秒级,用一点开销换「索引永远自洽」。
|
||||
fn mark_written_then_index(app: &AppHandle, state: &EditorManager) {
|
||||
match indexed(app, state) {
|
||||
Ok(service) => {
|
||||
service.mark_write_all();
|
||||
if let Err(e) = service.sync() {
|
||||
crate::logger::log_warn("editor", &format!("保存后同步索引失败: {e}"));
|
||||
}
|
||||
}
|
||||
Err(e) => crate::logger::log_warn("editor", &format!("索引服务不可用: {e}")),
|
||||
}
|
||||
}
|
||||
|
||||
/// 写入前登记「本应用即将写这一篇笔记」(按库内相对路径)。
|
||||
///
|
||||
/// **必须在 `library::write_note` 之前调用**:notify 的 Modify 事件可能与写入几乎
|
||||
/// 同时到达索引 worker,晚于写盘再登记就会漏过 —— 前端便会把自家的保存当成
|
||||
/// 「外部修改」,进而重载文档、把光标弹回第一行。
|
||||
fn mark_pending_note_write(app: &AppHandle, state: &EditorManager, rel_path: &str) {
|
||||
match indexed(app, state) {
|
||||
Ok(service) => service.mark_write_path(rel_path),
|
||||
Err(e) => crate::logger::log_warn("editor", &format!("索引服务不可用: {e}")),
|
||||
}
|
||||
}
|
||||
|
||||
/// 把库同步进索引(不登记自我写入 —— 调用方已在写入前按路径登记过)。
|
||||
fn sync_index_after_write(app: &AppHandle, state: &EditorManager) {
|
||||
match indexed(app, state) {
|
||||
Ok(service) => {
|
||||
if let Err(e) = service.sync() {
|
||||
crate::logger::log_warn("editor", &format!("保存后同步索引失败: {e}"));
|
||||
}
|
||||
}
|
||||
Err(e) => crate::logger::log_warn("editor", &format!("索引服务不可用: {e}")),
|
||||
}
|
||||
}
|
||||
|
||||
// ===== 设置与库 =====
|
||||
|
||||
/// 读取笔记模块设置。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_get_settings(state: State<'_, EditorManager>) -> Result<EditorSettings, String> {
|
||||
Ok(state.load_settings())
|
||||
}
|
||||
|
||||
/// 临时草稿文件的存放目录(`{app_data_dir}/editor/scratch`),不存在则创建,返回绝对路径。
|
||||
///
|
||||
/// 「新建临时文件(草稿)」用它:**不随应用退出删除** —— 用户可能还没决定存哪儿,
|
||||
/// 收尾交给「关闭该文件时选择保存 / 删除」。
|
||||
///
|
||||
/// # 为什么不放在**安装目录**
|
||||
///
|
||||
/// 安装目录(`Program Files` 之类)对普通用户通常不可写,装到系统盘就必然失败;
|
||||
/// 而 `app_data_dir` 本来就是本模块放设置与默认库的地方,是「应用自己的可写目录」的
|
||||
/// 标准位置,且卸载时随程序数据一起清理。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_scratch_dir(state: State<'_, EditorManager>) -> Result<String, String> {
|
||||
let dir = state.module_dir().join("scratch");
|
||||
std::fs::create_dir_all(&dir).map_err(|e| format!("创建临时目录失败:{e}"))?;
|
||||
Ok(dir.to_string_lossy().to_string())
|
||||
}
|
||||
|
||||
/// 保存笔记模块设置(自愈后落盘,并广播给各窗口)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_save_settings(
|
||||
app: AppHandle,
|
||||
state: State<'_, EditorManager>,
|
||||
settings: EditorSettings,
|
||||
) -> Result<EditorSettings, String> {
|
||||
let mut next = settings;
|
||||
next.heal();
|
||||
state.save_settings(&next)?;
|
||||
// 全局快捷键可能刚被改了:就地重注册(`register_shortcut` 会先注销本模块的旧键,
|
||||
// 因此「清空快捷键」也能通过传空串生效)
|
||||
state.init_on_launch(&app);
|
||||
emit_settings_changed(&app);
|
||||
Ok(next)
|
||||
}
|
||||
|
||||
/// 当前库状态概览(库根 / 是否自定义 / 笔记数)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_library_info(state: State<'_, EditorManager>) -> Result<LibraryInfo, String> {
|
||||
library_info(&state)
|
||||
}
|
||||
|
||||
/// 设置库根(`None` 或空串 = 恢复默认库根)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_set_library_root(
|
||||
app: AppHandle,
|
||||
state: State<'_, EditorManager>,
|
||||
root: Option<String>,
|
||||
) -> Result<LibraryInfo, String> {
|
||||
let cleaned = root.and_then(|r| {
|
||||
let trimmed = r.trim().to_string();
|
||||
if trimmed.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(trimmed)
|
||||
}
|
||||
});
|
||||
|
||||
if let Some(path) = &cleaned {
|
||||
let p = std::path::Path::new(path);
|
||||
if !p.exists() {
|
||||
return Err(format!("目录不存在:{path}"));
|
||||
}
|
||||
if !p.is_dir() {
|
||||
return Err("请选择一个文件夹作为笔记库".to_string());
|
||||
}
|
||||
}
|
||||
|
||||
let mut settings = state.load_settings();
|
||||
settings.library_root = cleaned;
|
||||
state.save_settings(&settings)?;
|
||||
|
||||
emit_settings_changed(&app);
|
||||
let info = library_info(&state)?;
|
||||
emit_library_changed(&app);
|
||||
Ok(info)
|
||||
}
|
||||
|
||||
/// 扫描库,返回扁平条目列表(前端组树)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_scan_library(state: State<'_, EditorManager>) -> Result<Vec<LibraryEntry>, String> {
|
||||
let root = current_root(&state);
|
||||
library::ensure_library(&root)?;
|
||||
library::scan(&root)
|
||||
}
|
||||
|
||||
/// 读取一篇笔记。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_read_note(state: State<'_, EditorManager>, rel_path: String) -> Result<NoteDoc, String> {
|
||||
let root = current_root(&state);
|
||||
library::read_note(&root, &rel_path)
|
||||
}
|
||||
|
||||
/// 保存一篇笔记(写完立即更新索引,使搜索无需等下一轮全量同步)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_save_note(
|
||||
app: AppHandle,
|
||||
state: State<'_, EditorManager>,
|
||||
rel_path: String,
|
||||
content: String,
|
||||
) -> Result<NoteDoc, String> {
|
||||
let root = current_root(&state);
|
||||
// 先登记「即将写这一篇」,再落盘:notify 的事件可能与写入同时抵达 worker
|
||||
mark_pending_note_write(&app, &state, &rel_path);
|
||||
let doc = library::write_note(&root, &rel_path, &content)?;
|
||||
sync_index_after_write(&app, &state);
|
||||
emit_library_changed(&app);
|
||||
Ok(doc)
|
||||
}
|
||||
|
||||
/// 新建笔记(自动补 `.md`、重名加序号),返回新文档。
|
||||
///
|
||||
/// `template_id` 为空时用默认模板;找不到该模板时同样回退默认模板(不报错 ——
|
||||
/// 模板文件被删掉不该让「新建笔记」这个核心动作失败)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_create_note(
|
||||
app: AppHandle,
|
||||
state: State<'_, EditorManager>,
|
||||
dir_rel: String,
|
||||
name: String,
|
||||
template_id: Option<String>,
|
||||
) -> Result<NoteDoc, String> {
|
||||
let root = current_root(&state);
|
||||
let template = template_id.unwrap_or_default();
|
||||
// 模板为空时走「不读模板目录」的那条路径:模板目录被删/损坏也要能新建笔记
|
||||
let doc = if template.trim().is_empty() {
|
||||
library::create_note(&root, &dir_rel, &name)?
|
||||
} else {
|
||||
library::create_note_with_template(&root, &dir_rel, &name, &template)?
|
||||
};
|
||||
mark_written_then_index(&app, &state);
|
||||
emit_library_changed(&app);
|
||||
Ok(doc)
|
||||
}
|
||||
|
||||
/// 打开(或创建)今天的日记:`日记/YYYY-MM-DD.md`。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_daily_note(app: AppHandle, state: State<'_, EditorManager>) -> Result<NoteDoc, String> {
|
||||
let root = current_root(&state);
|
||||
let name = templates::daily_note_name();
|
||||
let dir = "日记";
|
||||
let rel = format!("{dir}/{name}.md");
|
||||
let path = library::safe_join(&root, &rel)?;
|
||||
let doc = if path.is_file() {
|
||||
library::read_note(&root, &rel)?
|
||||
} else {
|
||||
// 日记用同名内置模板;没有则回退默认(模板可被用户改名,这里不能假定存在)
|
||||
let template = if templates::body_of(&root, "builtin:日记").is_some() {
|
||||
"builtin:日记"
|
||||
} else {
|
||||
""
|
||||
};
|
||||
library::create_note_with_template(&root, dir, &name, template)?
|
||||
};
|
||||
mark_written_then_index(&app, &state);
|
||||
emit_library_changed(&app);
|
||||
Ok(doc)
|
||||
}
|
||||
|
||||
/// 新建文件夹。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_create_folder(
|
||||
app: AppHandle,
|
||||
state: State<'_, EditorManager>,
|
||||
dir_rel: String,
|
||||
name: String,
|
||||
) -> Result<(), String> {
|
||||
let root = current_root(&state);
|
||||
library::create_folder(&root, &dir_rel, &name)?;
|
||||
emit_library_changed(&app);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 重命名条目,返回新相对路径。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_rename_entry(
|
||||
app: AppHandle,
|
||||
state: State<'_, EditorManager>,
|
||||
rel_path: String,
|
||||
new_name: String,
|
||||
) -> Result<String, String> {
|
||||
let root = current_root(&state);
|
||||
let next = library::rename_entry(&root, &rel_path, &new_name)?;
|
||||
// 改名在索引里是「旧路径消失 + 新路径出现」:增量同步一次比手工删+插更稳
|
||||
if let Ok(service) = indexed(&app, &state) {
|
||||
if let Err(e) = service.sync() {
|
||||
crate::logger::log_warn("editor", &format!("改名后同步索引失败: {e}"));
|
||||
}
|
||||
}
|
||||
emit_library_changed(&app);
|
||||
Ok(next)
|
||||
}
|
||||
|
||||
/// 删除条目(目录递归删除)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_delete_entry(
|
||||
app: AppHandle,
|
||||
state: State<'_, EditorManager>,
|
||||
rel_path: String,
|
||||
) -> Result<(), String> {
|
||||
let root = current_root(&state);
|
||||
library::delete_entry(&root, &rel_path)?;
|
||||
if let Ok(service) = indexed(&app, &state) {
|
||||
if let Err(e) = service.sync() {
|
||||
crate::logger::log_warn("editor", &format!("删除后同步索引失败: {e}"));
|
||||
}
|
||||
}
|
||||
emit_library_changed(&app);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// ===== 索引与检索 =====
|
||||
|
||||
/// 全量重建索引(设置页「重建索引」)。文件不受影响。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_rebuild_index(
|
||||
app: AppHandle,
|
||||
state: State<'_, EditorManager>,
|
||||
) -> Result<NoteIndexReport, String> {
|
||||
let service = indexed(&app, &state)?;
|
||||
let report = service.rebuild()?;
|
||||
Ok(finish_report(service, report))
|
||||
}
|
||||
|
||||
/// 增量同步索引(打开编辑器 / 手动刷新时调用)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_sync_index(
|
||||
app: AppHandle,
|
||||
state: State<'_, EditorManager>,
|
||||
) -> Result<NoteIndexReport, String> {
|
||||
let service = indexed(&app, &state)?;
|
||||
let report = service.sync()?;
|
||||
Ok(finish_report(service, report))
|
||||
}
|
||||
|
||||
/// 把同步结果补上「索引里的笔记数」再回传(前端省一次 stats 往返)。
|
||||
fn finish_report(service: &IndexService, report: super::index::NoteSyncReport) -> NoteIndexReport {
|
||||
let note_count = service.stats().map(|s| s.note_count).unwrap_or(0);
|
||||
let mut out: NoteIndexReport = report.into();
|
||||
out.note_count = note_count;
|
||||
out
|
||||
}
|
||||
|
||||
/// 全文检索 / 按标签 / 按目录筛选。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_search_notes(
|
||||
app: AppHandle,
|
||||
state: State<'_, EditorManager>,
|
||||
query: NoteSearchQuery,
|
||||
) -> Result<NoteSearchPage, String> {
|
||||
let service = indexed(&app, &state)?;
|
||||
service.search(query)
|
||||
}
|
||||
|
||||
/// 快速打开清单(`Ctrl+P`;只取路径/标题,带全文片段反而会拖慢输入响应)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_list_notes(
|
||||
app: AppHandle,
|
||||
state: State<'_, EditorManager>,
|
||||
limit: Option<i64>,
|
||||
) -> Result<Vec<NoteSearchHit>, String> {
|
||||
let service = indexed(&app, &state)?;
|
||||
service.list(limit.unwrap_or(500))
|
||||
}
|
||||
|
||||
/// 标签及计数。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_tags(
|
||||
app: AppHandle,
|
||||
state: State<'_, EditorManager>,
|
||||
) -> Result<Vec<super::index::NoteTagCount>, String> {
|
||||
let service = indexed(&app, &state)?;
|
||||
service.tags()
|
||||
}
|
||||
|
||||
/// 一篇笔记的链接关系(出链 + 入链)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_backlinks(
|
||||
app: AppHandle,
|
||||
state: State<'_, EditorManager>,
|
||||
rel_path: String,
|
||||
) -> Result<NoteBacklinks, String> {
|
||||
let service = indexed(&app, &state)?;
|
||||
service.backlinks(&rel_path)
|
||||
}
|
||||
|
||||
/// 全库链接图(已解析的内部链接边)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_link_graph(
|
||||
app: AppHandle,
|
||||
state: State<'_, EditorManager>,
|
||||
) -> Result<Vec<LinkEdge>, String> {
|
||||
let service = indexed(&app, &state)?;
|
||||
let edges = service.link_graph()?;
|
||||
Ok(edges
|
||||
.into_iter()
|
||||
.map(|(from, to)| LinkEdge { from, to })
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// 链接图的一条边(用 `from`/`to` 而不是元组:元组序列化成数组后前端得按下标取值,
|
||||
/// 改一次顺序就静默错位 —— 与 `terminal/history.rs` 的 `HistorySource` 同一理由)。
|
||||
#[derive(Debug, Clone, serde::Serialize, specta::Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct LinkEdge {
|
||||
pub from: String,
|
||||
pub to: String,
|
||||
}
|
||||
|
||||
/// 索引状态(设置页展示:索引数 / 文件数 / 标签数 / 索引文件路径)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_index_stats(
|
||||
app: AppHandle,
|
||||
state: State<'_, EditorManager>,
|
||||
) -> Result<NoteIndexStats, String> {
|
||||
let service = indexed(&app, &state)?;
|
||||
service.stats()
|
||||
}
|
||||
|
||||
// ===== 库外任意文件 =====
|
||||
|
||||
/// 把库内图片读成 `data:` URL(供编辑器内联预览)。
|
||||
///
|
||||
/// # 为什么走 data URL 而不是 asset 协议
|
||||
///
|
||||
/// 库根是用户自选目录,可以用 `convertFileSrc` + `assetProtocol.scope` 直接把磁盘路径
|
||||
/// 交给 `<img>`。但那条路要求把「用户选的任意目录」加进 asset 协议的作用域白名单 ——
|
||||
/// 那等于给 WebView 开一个「可以按路径读任意文件」的口子,而笔记模块的整个安全模型
|
||||
/// 是「库根沙箱 + 授权白名单」。走 data URL 则完全在既有沙箱内:路径必须经
|
||||
/// [`library::safe_join`](拒绝 `..` 与绝对路径),且只认图片扩展名。
|
||||
///
|
||||
/// # 为什么必须有大小上限
|
||||
///
|
||||
/// data URL 是 base64,体积约为原文件的 1.34 倍,且会进 JS 堆。一张 20MB 的图片
|
||||
/// 变成 27MB 字符串,多预览几张就能把 WebView 拖垮。超限时**不报错**,返回
|
||||
/// `None` —— 调用方(编辑器)会把该图片节点当作普通文本渲染,用户看到的就是
|
||||
/// 原始 Markdown,不会打断编辑。
|
||||
const MAX_ASSET_BYTES: u64 = 8 * 1024 * 1024;
|
||||
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_read_asset(
|
||||
state: State<'_, EditorManager>,
|
||||
rel_path: String,
|
||||
) -> Result<Option<String>, String> {
|
||||
let root = current_root(&state);
|
||||
let path = library::safe_join(&root, &rel_path)?;
|
||||
if !path.is_file() {
|
||||
return Ok(None);
|
||||
}
|
||||
let ext = path
|
||||
.extension()
|
||||
.map(|e| e.to_string_lossy().to_ascii_lowercase())
|
||||
.unwrap_or_default();
|
||||
let mime = match ext.as_str() {
|
||||
"png" => "image/png",
|
||||
"jpg" | "jpeg" => "image/jpeg",
|
||||
"gif" => "image/gif",
|
||||
"webp" => "image/webp",
|
||||
"svg" => "image/svg+xml",
|
||||
"bmp" => "image/bmp",
|
||||
"avif" => "image/avif",
|
||||
// 非图片(或未识别):不预览。返回 `None` 而不是报错 —— 正文里写个
|
||||
// `` 不该让编辑器弹错误。
|
||||
_ => return Ok(None),
|
||||
};
|
||||
let meta = std::fs::metadata(&path).map_err(|e| format!("读取附件信息失败: {e}"))?;
|
||||
if meta.len() > MAX_ASSET_BYTES {
|
||||
crate::logger::log_info(
|
||||
"editor",
|
||||
&format!("附件过大,跳过内联预览:{rel_path}({} 字节)", meta.len()),
|
||||
);
|
||||
return Ok(None);
|
||||
}
|
||||
use base64::Engine;
|
||||
let bytes = std::fs::read(&path).map_err(|e| format!("读取附件失败: {e}"))?;
|
||||
let encoded = base64::engine::general_purpose::STANDARD.encode(&bytes);
|
||||
Ok(Some(format!("data:{mime};base64,{encoded}")))
|
||||
}
|
||||
|
||||
/// 取出「启动时命令行 / 文件关联指定的文件」(取走即清空)。
|
||||
///
|
||||
/// 前端在注册完事件监听后调用。**不能靠启动时 `emit`** —— 那时 WebView 还没加载完,
|
||||
/// 事件会直接丢掉(见 `editor/args.rs` 的 `PENDING` 注释)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_take_pending_file() -> Result<Option<super::args::OpenTargetPayload>, String> {
|
||||
Ok(super::args::take_pending_target())
|
||||
}
|
||||
|
||||
/// 打开(读取)库外任意文件。
|
||||
///
|
||||
/// 读取本身不要求预先授权(用户可能刚通过系统对话框选完,也可能带命令行参数),
|
||||
/// 但**读取会顺带登记授权** —— 于是「打开过就能保存」这条最符合直觉的规则成立。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_open_file(
|
||||
state: State<'_, EditorManager>,
|
||||
path: String,
|
||||
) -> Result<files::FileDoc, String> {
|
||||
let settings = state.load_settings();
|
||||
index_service::read_and_authorize(&path, settings.max_file_size_mb)
|
||||
}
|
||||
|
||||
/// 保存库外任意文件(按前端回传的编码与换行写回)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_write_file(
|
||||
app: AppHandle,
|
||||
state: State<'_, EditorManager>,
|
||||
path: String,
|
||||
content: String,
|
||||
encoding: String,
|
||||
eol: String,
|
||||
) -> Result<files::FileDoc, String> {
|
||||
let settings = state.load_settings();
|
||||
let doc = files::write_file(&path, &content, &encoding, &eol, settings.max_file_size_mb)?;
|
||||
if let Ok(service) = indexed(&app, &state) {
|
||||
// 库外文件的路径语义与库内相对路径不同,这里退回窗口式抑制;
|
||||
// 真正在库内的 `.md`(被当作普通文件打开)同样受这一窗口保护。
|
||||
service.mark_write_all();
|
||||
}
|
||||
Ok(doc)
|
||||
}
|
||||
|
||||
/// 以指定编码重新解码磁盘字节(切换编码用;不写回,只换一种解释方式)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_redecode_file(
|
||||
state: State<'_, EditorManager>,
|
||||
path: String,
|
||||
encoding: String,
|
||||
) -> Result<files::FileDoc, String> {
|
||||
let settings = state.load_settings();
|
||||
files::redecode_file(&path, &encoding, settings.max_file_size_mb)
|
||||
}
|
||||
|
||||
/// 显式登记一个路径为「可写」。
|
||||
///
|
||||
/// 前端在拿到系统对话框返回的路径后调用(那种路径不经过 `editor_open_file`,
|
||||
/// 但用户确实是用系统对话框选的,属于「用户显式选择」)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_authorize_file(path: String) -> Result<(), String> {
|
||||
if path.trim().is_empty() {
|
||||
return Err("路径为空".to_string());
|
||||
}
|
||||
files::authorize(std::path::Path::new(path.trim()));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 把 base64 图片写进库根的 `assets/`,返回可插入 Markdown 的相对路径。
|
||||
///
|
||||
/// 为什么走 base64 而不是直接给前端一个写文件句柄:粘贴的图片来自剪贴板,
|
||||
/// 前端拿到的本来就是 Blob/DataURL;转一次 base64 比让前端拿到「任意写权限」
|
||||
/// 安全得多(写的位置由后端决定,且只落在 `assets/`)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_write_asset(
|
||||
state: State<'_, EditorManager>,
|
||||
file_name: String,
|
||||
ext: String,
|
||||
data_base64: String,
|
||||
) -> Result<String, String> {
|
||||
use base64::Engine;
|
||||
let root = current_root(&state);
|
||||
library::ensure_library(&root)?;
|
||||
let data = base64::engine::general_purpose::STANDARD
|
||||
.decode(data_base64.trim())
|
||||
.map_err(|e| format!("图片数据解析失败: {e}"))?;
|
||||
files::write_asset(&root, &file_name, &data, &ext)
|
||||
}
|
||||
|
||||
// ===== 模板(P2) =====
|
||||
|
||||
/// 列出可用模板(用户模板优先,同名覆盖内置)。
|
||||
///
|
||||
/// 顺带确保库内 `templates/` 目录存在 —— 这样界面上「新建模板」按钮第一次点击
|
||||
/// 就能直接写文件,不需要用户先去资源管理器建目录。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_list_templates(state: State<'_, EditorManager>) -> Result<Vec<NoteTemplate>, String> {
|
||||
let root = current_root(&state);
|
||||
library::ensure_library(&root)?;
|
||||
let _ = templates::ensure_dir(&root);
|
||||
Ok(templates::list(&root))
|
||||
}
|
||||
|
||||
/// 把内置模板导出到库内 `templates/`(已存在的不覆盖),返回新写入的名字。
|
||||
///
|
||||
/// 三种用法:
|
||||
/// - 都不传:把全部内置模板导出到 `templates/`(用户想改内置模板时的起点);
|
||||
/// - 传 `name` + `body`:新建一个自定义模板。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_add_template(
|
||||
app: AppHandle,
|
||||
state: State<'_, EditorManager>,
|
||||
name: Option<String>,
|
||||
body: Option<String>,
|
||||
) -> Result<Vec<String>, String> {
|
||||
let root = current_root(&state);
|
||||
let written = match (name, body) {
|
||||
(Some(name), Some(body)) => {
|
||||
let safe = templates::validate_name(&name)?;
|
||||
templates::ensure_dir(&root)?;
|
||||
let path = root.join("templates").join(format!("{safe}.md"));
|
||||
if path.exists() {
|
||||
return Err(format!("模板「{safe}」已存在"));
|
||||
}
|
||||
std::fs::write(&path, body).map_err(|e| format!("写入模板失败: {e}"))?;
|
||||
vec![safe]
|
||||
}
|
||||
// 不带参数 = 导出全部内置模板
|
||||
_ => templates::export_builtin(&root)?,
|
||||
};
|
||||
mark_written_then_index(&app, &state);
|
||||
emit_library_changed(&app);
|
||||
Ok(written)
|
||||
}
|
||||
|
||||
/// 读取一个模板的正文(界面上「查看 / 编辑模板」用)。
|
||||
///
|
||||
/// 内置模板也返回正文(便于「另存为自定义模板」),但 `path` 为 `None` ——
|
||||
/// 内置模板没有对应的库内文件,前端据此禁掉「直接编辑」。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_read_template(
|
||||
state: State<'_, EditorManager>,
|
||||
template_id: String,
|
||||
) -> Result<TemplateSource, String> {
|
||||
let root = current_root(&state);
|
||||
let body = templates::body_of(&root, &template_id)
|
||||
.ok_or_else(|| format!("模板不存在:{template_id}"))?;
|
||||
Ok(TemplateSource {
|
||||
body,
|
||||
path: templates::relative_path(&template_id),
|
||||
})
|
||||
}
|
||||
|
||||
/// 模板正文与它在库内的位置(`path` 为 `None` = 内置模板)。
|
||||
#[derive(Debug, Clone, serde::Serialize, specta::Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct TemplateSource {
|
||||
pub body: String,
|
||||
pub path: Option<String>,
|
||||
}
|
||||
|
||||
// ===== 导入 / 导出(P2) =====
|
||||
|
||||
/// 从磁盘路径导入(文件 / 目录 / zip 自动判别)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_import(
|
||||
app: AppHandle,
|
||||
state: State<'_, EditorManager>,
|
||||
source: String,
|
||||
dest_dir: String,
|
||||
) -> Result<ImportReport, String> {
|
||||
let root = current_root(&state);
|
||||
let report = import::import_path(&root, &source, &dest_dir)?;
|
||||
mark_written_then_index(&app, &state);
|
||||
emit_library_changed(&app);
|
||||
Ok(report)
|
||||
}
|
||||
|
||||
/// 把一篇笔记导出为独立 HTML 文件,返回落盘路径。
|
||||
///
|
||||
/// HTML 的渲染在**前端**(`markdown-it` + `DOMPurify` 都在前端),这里只负责把
|
||||
/// 已经渲染好的字符串写到用户选定的位置 —— 即「后端不碰渲染逻辑,前端不碰文件系统」。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_export_note(
|
||||
state: State<'_, EditorManager>,
|
||||
rel_path: String,
|
||||
html: String,
|
||||
dest: String,
|
||||
) -> Result<String, String> {
|
||||
let root = current_root(&state);
|
||||
// 无论导出哪一篇,都要先确认它确实在库内(不接受库外相对路径)
|
||||
library::read_note(&root, &rel_path)?;
|
||||
let target = PathBuf::from(dest.trim());
|
||||
if target.as_os_str().is_empty() {
|
||||
return Err("请选择导出位置".to_string());
|
||||
}
|
||||
if let Some(parent) = target.parent() {
|
||||
std::fs::create_dir_all(parent).map_err(|e| format!("创建导出目录失败: {e}"))?;
|
||||
}
|
||||
let bytes = html.into_bytes();
|
||||
std::fs::write(&target, &bytes).map_err(|e| format!("写入导出文件失败: {e}"))?;
|
||||
crate::logger::log_info(
|
||||
"editor",
|
||||
&format!("导出 {} → {}({} 字节)", rel_path, target.display(), bytes.len()),
|
||||
);
|
||||
Ok(target.to_string_lossy().to_string())
|
||||
}
|
||||
|
||||
/// 把整库(或某个目录)打包成 zip,返回落盘路径。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_export_zip(
|
||||
state: State<'_, EditorManager>,
|
||||
dest: String,
|
||||
dir_rel: Option<String>,
|
||||
) -> Result<String, String> {
|
||||
let root = current_root(&state);
|
||||
let dest_path = PathBuf::from(dest.trim());
|
||||
if dest_path.as_os_str().is_empty() {
|
||||
return Err("请选择导出位置".to_string());
|
||||
}
|
||||
let scope = dir_rel.unwrap_or_default();
|
||||
let (bytes, files) = export::zip_scope(&root, &scope)?;
|
||||
if let Some(parent) = dest_path.parent() {
|
||||
std::fs::create_dir_all(parent).map_err(|e| format!("创建导出目录失败: {e}"))?;
|
||||
}
|
||||
std::fs::write(&dest_path, &bytes).map_err(|e| format!("写入 zip 失败: {e}"))?;
|
||||
crate::logger::log_info(
|
||||
"editor",
|
||||
&format!("导出 zip:{files} 个文件 → {}", dest_path.display()),
|
||||
);
|
||||
Ok(dest_path.to_string_lossy().to_string())
|
||||
}
|
||||
|
||||
/// 把整库打包成一份本地快照 zip(与上传到远端的快照是同一份内容)。
|
||||
///
|
||||
/// 与 [`editor_export_zip`] 的区别只在**目的**:导出是「我要把笔记拿走/分享」,
|
||||
/// 快照是「我要一份可整体恢复的备份」。两者目前内容一致,但保留两个入口是因为
|
||||
/// 将来它们的排除规则可能分化(比如快照要带同步基线,导出不该带)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_export_snapshot_local(
|
||||
state: State<'_, EditorManager>,
|
||||
dest: Option<String>,
|
||||
) -> Result<String, String> {
|
||||
let root = current_root(&state);
|
||||
library::ensure_library(&root)?;
|
||||
let target = match dest.map(|d| d.trim().to_string()) {
|
||||
Some(d) if !d.is_empty() => PathBuf::from(d),
|
||||
_ => backup::default_snapshot_path(&root),
|
||||
};
|
||||
backup::snapshot_to_file(&root, &target)?;
|
||||
Ok(target.to_string_lossy().to_string())
|
||||
}
|
||||
|
||||
// ===== WebDAV 同步 / 备份(P2) =====
|
||||
|
||||
/// 当前 WebDAV 配置状态(设置页展示;**密码只回传「是否已保存」**)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_webdav_status(state: State<'_, EditorManager>) -> Result<WebdavStatus, String> {
|
||||
let settings = state.load_settings();
|
||||
let has_password = crate::secrets::secret_read(webdav::KEYRING_PASSWORD)
|
||||
.ok()
|
||||
.flatten()
|
||||
.map(|value| !value.is_empty())
|
||||
.unwrap_or(false);
|
||||
Ok(WebdavStatus {
|
||||
configured: settings.webdav.is_configured(),
|
||||
has_password,
|
||||
remote_root: settings.webdav.remote_root.clone(),
|
||||
})
|
||||
}
|
||||
|
||||
/// WebDAV 配置状态(不包含密码本身)。
|
||||
#[derive(Debug, Clone, serde::Serialize, specta::Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct WebdavStatus {
|
||||
/// 地址与用户名是否已填
|
||||
pub configured: bool,
|
||||
/// keyring 里是否已存密码
|
||||
pub has_password: bool,
|
||||
pub remote_root: String,
|
||||
}
|
||||
|
||||
/// 保存 WebDAV 密码到系统凭据管理器(传空串 = 删除)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_set_webdav_password(password: String) -> Result<(), String> {
|
||||
if password.trim().is_empty() {
|
||||
return crate::secrets::secret_delete(webdav::KEYRING_PASSWORD);
|
||||
}
|
||||
crate::secrets::secret_write(webdav::KEYRING_PASSWORD, password.trim())
|
||||
}
|
||||
|
||||
/// 连接自检(建目录 + 列远端)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn editor_test_webdav(
|
||||
state: State<'_, EditorManager>,
|
||||
) -> Result<WebdavTestResult, String> {
|
||||
let settings = state.load_settings().webdav;
|
||||
run_blocking(move || webdav::test_connection(&settings)).await
|
||||
}
|
||||
|
||||
/// 立即同步(并按设置决定是否追加一次快照备份)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn editor_sync_now(
|
||||
app: AppHandle,
|
||||
state: State<'_, EditorManager>,
|
||||
) -> Result<SyncOutcome, String> {
|
||||
let settings = state.load_settings();
|
||||
let webdav = settings.webdav.clone();
|
||||
let root = library::resolve_library_root(state.module_dir(), &settings);
|
||||
library::ensure_library(&root)?;
|
||||
|
||||
// 让前端先看到「开始同步」(进度事件的第一条由 worker 之外发,总数为 0 表示准备中)
|
||||
let _ = app.emit(
|
||||
events::EDITOR_SYNC_PROGRESS,
|
||||
SyncProgress {
|
||||
done: 0,
|
||||
total: 0,
|
||||
current: String::new(),
|
||||
kind: "prepare".to_string(),
|
||||
message: "正在比对清单…".to_string(),
|
||||
},
|
||||
);
|
||||
|
||||
let app_for_task = app.clone();
|
||||
let outcome = run_blocking(move || {
|
||||
let client = webdav::client_from(&webdav)?;
|
||||
client.ensure_root()?;
|
||||
let (report, backup) = backup::sync_then_backup(&root, &webdav, &client, &app_for_task, true)?;
|
||||
Ok(SyncOutcome {
|
||||
report,
|
||||
backup,
|
||||
})
|
||||
})
|
||||
.await;
|
||||
|
||||
// 同步会改本地文件 → 索引必须跟着更新
|
||||
mark_written_then_index(&app, &state);
|
||||
emit_library_changed(&app);
|
||||
outcome
|
||||
}
|
||||
|
||||
/// 一次同步的结果(报告 + 可选快照)。
|
||||
#[derive(Debug, Clone, serde::Serialize, specta::Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct SyncOutcome {
|
||||
pub report: super::webdav::sync::SyncReport,
|
||||
pub backup: Option<BackupReport>,
|
||||
}
|
||||
|
||||
/// 只做一次 zip 快照备份(不上传增量)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn editor_backup_now(
|
||||
state: State<'_, EditorManager>,
|
||||
) -> Result<BackupReport, String> {
|
||||
let settings = state.load_settings();
|
||||
let webdav = settings.webdav.clone();
|
||||
let root = library::resolve_library_root(state.module_dir(), &settings);
|
||||
library::ensure_library(&root)?;
|
||||
run_blocking(move || {
|
||||
let client = webdav::client_from(&webdav)?;
|
||||
client.ensure_root()?;
|
||||
backup::upload_snapshot(&root, &webdav, &client)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// 列出远端已有快照。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn editor_list_backups(
|
||||
state: State<'_, EditorManager>,
|
||||
) -> Result<Vec<BackupSnapshot>, String> {
|
||||
let settings = state.load_settings().webdav;
|
||||
run_blocking(move || {
|
||||
let client = webdav::client_from(&settings)?;
|
||||
backup::list_snapshots(&client)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// 从远端快照恢复(不覆盖本地已有文件)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn editor_restore_backup(
|
||||
app: AppHandle,
|
||||
state: State<'_, EditorManager>,
|
||||
name: String,
|
||||
) -> Result<ImportReport, String> {
|
||||
let settings = state.load_settings();
|
||||
let webdav = settings.webdav.clone();
|
||||
let root = library::resolve_library_root(state.module_dir(), &settings);
|
||||
library::ensure_library(&root)?;
|
||||
let result = run_blocking(move || {
|
||||
let client = webdav::client_from(&webdav)?;
|
||||
let (written, kept) = backup::restore_snapshot(&root, &client, &name)?;
|
||||
Ok(ImportReport {
|
||||
imported: written,
|
||||
renamed: 0,
|
||||
skipped: kept,
|
||||
failures: Vec::new(),
|
||||
})
|
||||
})
|
||||
.await;
|
||||
mark_written_then_index(&app, &state);
|
||||
emit_library_changed(&app);
|
||||
result
|
||||
}
|
||||
|
||||
/// 把阻塞的 WebDAV 调用挪到专用线程池,避免占住 Tauri 的命令线程。
|
||||
///
|
||||
/// `reqwest::blocking` 在 tokio 运行时线程上会 panic(它内部会尝试建一个运行时),
|
||||
/// 因此**必须**走 `spawn_blocking` 而不是直接 `.await` 一个同步函数。
|
||||
async fn run_blocking<T, F>(task: F) -> Result<T, String>
|
||||
where
|
||||
T: Send + 'static,
|
||||
F: FnOnce() -> Result<T, String> + Send + 'static,
|
||||
{
|
||||
match tokio::task::spawn_blocking(task).await {
|
||||
Ok(result) => result,
|
||||
Err(e) => Err(format!("后台任务执行失败: {e}")),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
//! 编辑器「本地目录」命令层:直接操作用户真实文件系统(不进索引、无沙箱)。
|
||||
//!
|
||||
//! # 为什么复用 `terminal::local_fs`
|
||||
//!
|
||||
//! 列举 / 新建目录 / 重命名 / **回收站删除** 在终端模块的「本地栏」已经实现过,
|
||||
//! 且把「目录/文件分流」「不弹系统错误对话框」「拒绝删除盘符根」这些细节处理好了。
|
||||
//! 这里只补它没有的两件事:
|
||||
//! 1. **新建文件**(空文本,终端本地栏只建目录);
|
||||
//! 2. **重名一律报错**——目录树是用户的真实文件系统,静默改名会让人找不到刚建的文件。
|
||||
//!
|
||||
//! # 安全边界(与终端同一姿态)
|
||||
//!
|
||||
//! 路径来自用户自己的浏览/输入,不做「限制在本目录根下」的约束(那是本地文件管理器,
|
||||
//! 限制根只会挡住用户自己)。唯一硬守卫是 **拒绝删除盘符根**(已在
|
||||
//! [`terminal::local_fs::delete`] 内实现),且删除一律走回收站。
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use serde::Serialize;
|
||||
use specta::Type;
|
||||
|
||||
use super::library::validate_name;
|
||||
use crate::terminal::local_fs;
|
||||
|
||||
/// 批量删除结果(回传前端展示「成功 N 项、失败明细」)。
|
||||
#[derive(Debug, Clone, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct DeleteReport {
|
||||
/// 成功移入回收站的项数
|
||||
pub removed: u32,
|
||||
/// 失败明细(路径 + 原因)
|
||||
pub failed: Vec<String>,
|
||||
}
|
||||
|
||||
/// 列举本地目录(`path` 为空 = 用户主目录)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_read_dir(path: String) -> Result<local_fs::LocalDir, String> {
|
||||
local_fs::list_dir(&path)
|
||||
}
|
||||
|
||||
/// 在 `dir` 下新建一个空文本文件。重名报错(不自动加序号)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_create_file(dir: String, name: String) -> Result<String, String> {
|
||||
let target = resolve_child(&dir, &name)?;
|
||||
if target.exists() {
|
||||
return Err(format!("「{name}」已存在"));
|
||||
}
|
||||
std::fs::write(&target, b"").map_err(|e| format!("新建文件失败: {e}"))?;
|
||||
Ok(local_fs::display_path(&target))
|
||||
}
|
||||
|
||||
/// 在 `dir` 下新建一个文件夹。重名报错(不自动加序号)。
|
||||
///
|
||||
/// 命名用 `editor_create_dir` 而不是 `editor_create_folder`:后者已被**库内**建文件夹
|
||||
/// 的命令占用(`editor_create_folder(dir_rel, name)`,走库根沙箱)—— 两者操作对象不同
|
||||
/// (真实文件系统 vs 库内),必须能同时在命令表里存在。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_create_dir(dir: String, name: String) -> Result<String, String> {
|
||||
let target = resolve_child(&dir, &name)?;
|
||||
if target.exists() {
|
||||
return Err(format!("「{name}」已存在"));
|
||||
}
|
||||
local_fs::create_dir(&target.to_string_lossy())?;
|
||||
Ok(local_fs::display_path(&target))
|
||||
}
|
||||
|
||||
/// 同目录内重命名。目标存在则报错。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_rename_path(path: String, new_name: String) -> Result<String, String> {
|
||||
let src = Path::new(path.trim());
|
||||
if !src.exists() {
|
||||
return Err("路径不存在".to_string());
|
||||
}
|
||||
let parent = src.parent().ok_or_else(|| "无法解析父目录".to_string())?;
|
||||
let name = validate_name(&new_name)?;
|
||||
let target = parent.join(&name);
|
||||
if target == src {
|
||||
return Ok(local_fs::display_path(src));
|
||||
}
|
||||
if target.exists() {
|
||||
return Err(format!("「{name}」已存在"));
|
||||
}
|
||||
local_fs::rename(&path, &target.to_string_lossy())?;
|
||||
Ok(local_fs::display_path(&target))
|
||||
}
|
||||
|
||||
/// 删除若干本地项(**走系统回收站**,不是永久删除)。
|
||||
///
|
||||
/// 单个失败不中断其余项:用户选中的 10 个文件里有一个正被占用,另外 9 个仍应删掉。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn editor_delete_path(paths: Vec<String>) -> Result<DeleteReport, String> {
|
||||
tauri::async_runtime::spawn_blocking(move || {
|
||||
let (removed, failed) = local_fs::delete(&paths);
|
||||
DeleteReport {
|
||||
removed: removed as u32,
|
||||
failed,
|
||||
}
|
||||
})
|
||||
.await
|
||||
.map_err(|e| format!("删除任务失败: {e}"))
|
||||
}
|
||||
|
||||
/// 把一个文件 / 文件夹移动到目标目录下(同盘移动;重名报错)。
|
||||
///
|
||||
/// 不允许把文件夹移动到自身或其子目录下 —— 那会把目录搬进自己里面,属数据事故。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_move_path(path: String, dest_dir: String) -> Result<String, String> {
|
||||
let src = Path::new(path.trim());
|
||||
if !src.exists() {
|
||||
return Err("源路径不存在".to_string());
|
||||
}
|
||||
let dest = Path::new(dest_dir.trim());
|
||||
if !dest.is_dir() {
|
||||
return Err("目标目录不存在".to_string());
|
||||
}
|
||||
let name = src
|
||||
.file_name()
|
||||
.ok_or_else(|| "无法解析文件名".to_string())?;
|
||||
let target = dest.join(name);
|
||||
if target == src {
|
||||
return Ok(local_fs::display_path(src));
|
||||
}
|
||||
if target.exists() {
|
||||
return Err(format!("目标目录中已存在「{}」", name.to_string_lossy()));
|
||||
}
|
||||
if src.is_dir() && dest.starts_with(src) {
|
||||
return Err("不能把文件夹移动到自身或子目录中".to_string());
|
||||
}
|
||||
local_fs::rename(&path, &target.to_string_lossy())?;
|
||||
Ok(local_fs::display_path(&target))
|
||||
}
|
||||
|
||||
/// 校验名字并把「目录 + 名字」拼成绝对路径。
|
||||
fn resolve_child(dir: &str, name: &str) -> Result<std::path::PathBuf, String> {
|
||||
let name = validate_name(name)?;
|
||||
let dir = Path::new(dir.trim());
|
||||
if !dir.is_dir() {
|
||||
return Err("目标目录不存在".to_string());
|
||||
}
|
||||
Ok(dir.join(name))
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
//! 整库 / 目录导出为 zip。
|
||||
//!
|
||||
//! # 与快照备份的区别
|
||||
//!
|
||||
//! `backup.rs` 的 zip 是**给同步服务用的**(固定文件名前缀、上传到远端、轮转),
|
||||
//! 本模块的 zip 是**给用户拿走的**(用户选保存位置、可以只导出某个目录)。
|
||||
//! 两者都打包 `.md` 与 `assets/`,但排除规则不同:用户导出时**包含**点号开头的
|
||||
//! 普通目录(除了 `.editor/`)—— 因为「我库里有 `.foo/` 目录,为什么导出后没了」
|
||||
//! 是个更难解释的问题;而同步必须排除它们(避免把本机私有状态推给别人)。
|
||||
|
||||
use std::io::Write;
|
||||
use std::path::Path;
|
||||
|
||||
use super::library;
|
||||
|
||||
/// 打包范围。
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Scope {
|
||||
/// 整个库
|
||||
All,
|
||||
/// 只打包库内某个目录(连同库根的 `assets/`)
|
||||
Dir,
|
||||
}
|
||||
|
||||
/// 按范围打包,返回 `(zip 字节, 文件数)`。
|
||||
pub fn zip_scope(root: &Path, dir_rel: &str) -> Result<(Vec<u8>, u32), String> {
|
||||
let scope = if dir_rel.trim().is_empty() {
|
||||
Scope::All
|
||||
} else {
|
||||
Scope::Dir
|
||||
};
|
||||
// 目录模式下先确认目标目录存在且仍在库内(`safe_join` 拒绝越界)
|
||||
let filter_prefix = if scope == Scope::Dir {
|
||||
let dir = library::safe_join(root, dir_rel)?;
|
||||
if !dir.is_dir() {
|
||||
return Err(format!("目录不存在:{dir_rel}"));
|
||||
}
|
||||
Some(library::rel_string(root, &dir))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
let cursor = std::io::Cursor::new(Vec::new());
|
||||
let mut writer = zip::ZipWriter::new(cursor);
|
||||
let options: zip::write::FileOptions<'_, ()> =
|
||||
zip::write::FileOptions::default().compression_method(zip::CompressionMethod::Deflated);
|
||||
|
||||
let mut files = 0u32;
|
||||
for entry in walkdir::WalkDir::new(root)
|
||||
.max_depth(library::MAX_DEPTH)
|
||||
.into_iter()
|
||||
.filter_map(Result::ok)
|
||||
{
|
||||
if !entry.file_type().is_file() {
|
||||
continue;
|
||||
}
|
||||
let rel = library::rel_string(root, entry.path());
|
||||
if rel.is_empty() {
|
||||
continue;
|
||||
}
|
||||
// 私有目录(索引 + 同步基线)任何情况下都不导出
|
||||
if rel == ".editor" || rel.starts_with(".editor/") {
|
||||
continue;
|
||||
}
|
||||
if let Some(prefix) = &filter_prefix {
|
||||
// 目录模式:只收该目录下的文件,外加库根 assets/
|
||||
let in_scope = rel == *prefix
|
||||
|| rel.starts_with(&format!("{prefix}/"))
|
||||
|| rel.starts_with(&format!("{}/", library::ASSETS_DIR));
|
||||
if !in_scope {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
let bytes = match std::fs::read(entry.path()) {
|
||||
Ok(bytes) => bytes,
|
||||
Err(e) => {
|
||||
crate::logger::log_warn("editor", &format!("导出跳过 {rel}(读取失败: {e})"));
|
||||
continue;
|
||||
}
|
||||
};
|
||||
writer
|
||||
.start_file(rel, options)
|
||||
.map_err(|e| format!("写入 zip 条目失败: {e}"))?;
|
||||
writer
|
||||
.write_all(&bytes)
|
||||
.map_err(|e| format!("写入 zip 内容失败: {e}"))?;
|
||||
files += 1;
|
||||
}
|
||||
|
||||
let cursor = writer.finish().map_err(|e| format!("完成 zip 打包失败: {e}"))?;
|
||||
Ok((cursor.into_inner(), files))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::path::PathBuf;
|
||||
|
||||
fn temp_lib(tag: &str) -> PathBuf {
|
||||
let root = std::env::temp_dir().join(format!("thing-notes-export-{tag}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
std::fs::create_dir_all(root.join("assets")).unwrap();
|
||||
root
|
||||
}
|
||||
|
||||
fn names(bytes: Vec<u8>) -> Vec<String> {
|
||||
let mut archive = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
|
||||
(0..archive.len())
|
||||
.map(|i| archive.by_index(i).unwrap().name().to_string())
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn full_export_skips_private_dir_only() {
|
||||
let root = temp_lib("all");
|
||||
std::fs::create_dir_all(root.join(".editor")).unwrap();
|
||||
std::fs::create_dir_all(root.join(".custom")).unwrap();
|
||||
std::fs::write(root.join("a.md"), "A").unwrap();
|
||||
std::fs::write(root.join(".editor/editor.db"), "x").unwrap();
|
||||
std::fs::write(root.join(".custom/keep.md"), "保留").unwrap();
|
||||
std::fs::write(root.join("assets/p.png"), [1u8]).unwrap();
|
||||
|
||||
let (bytes, count) = zip_scope(&root, "").unwrap();
|
||||
assert_eq!(count, 3, "a.md + .custom/keep.md + assets/p.png");
|
||||
let list = names(bytes);
|
||||
assert!(list.contains(&"a.md".to_string()), "{list:?}");
|
||||
assert!(
|
||||
list.contains(&".custom/keep.md".to_string()),
|
||||
"普通点号目录应被导出: {list:?}"
|
||||
);
|
||||
assert!(
|
||||
!list.iter().any(|n| n.starts_with(".editor")),
|
||||
"私有目录不该导出: {list:?}"
|
||||
);
|
||||
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dir_export_limits_scope_but_keeps_assets() {
|
||||
let root = temp_lib("dir");
|
||||
std::fs::create_dir_all(root.join("work")).unwrap();
|
||||
std::fs::create_dir_all(root.join("personal")).unwrap();
|
||||
std::fs::write(root.join("work/a.md"), "A").unwrap();
|
||||
std::fs::write(root.join("personal/b.md"), "B").unwrap();
|
||||
std::fs::write(root.join("assets/p.png"), [1u8]).unwrap();
|
||||
|
||||
let (bytes, count) = zip_scope(&root, "work").unwrap();
|
||||
assert_eq!(count, 2, "work/a.md + assets/p.png");
|
||||
let list = names(bytes);
|
||||
assert!(list.contains(&"work/a.md".to_string()), "{list:?}");
|
||||
assert!(list.contains(&"assets/p.png".to_string()), "{list:?}");
|
||||
assert!(
|
||||
!list.contains(&"personal/b.md".to_string()),
|
||||
"范围外文件不该导出: {list:?}"
|
||||
);
|
||||
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dir_export_rejects_escape_and_missing() {
|
||||
let root = temp_lib("escape");
|
||||
assert!(zip_scope(&root, "../..").is_err(), "越界路径必须被拒");
|
||||
assert!(zip_scope(&root, "不存在").is_err());
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,514 @@
|
||||
//! 任意文本 / 代码文件的读写:编码探测、换行探测、授权路径白名单。
|
||||
//!
|
||||
//! # 与笔记库的分工
|
||||
//!
|
||||
//! 库内笔记走 `library.rs`(相对路径 + 树形结构 + front-matter);本模块服务的是
|
||||
//! **库外的任意文件**:用户用 `Ctrl+O` 或拖拽打开的一个 `.py`、`.json`、`.log`。
|
||||
//! 两者的安全模型完全不同 —— 库是「一个根目录内的沙箱」,而任意文件是「用户显式
|
||||
//! 点过的那个路径」。因此这里的守卫不是路径前缀,而是**授权集合**(见下)。
|
||||
//!
|
||||
//! # 为什么要有授权白名单
|
||||
//!
|
||||
//! 前端传来的路径一律不可信:一个被污染的 WebView(XSS、恶意依赖)如果能调
|
||||
//! `editor_write_file('/Windows/System32/...')`,那就不是编辑器而是任意文件写入漏洞。
|
||||
//! 做法:只有经过 [`authorize`] 登记过的路径才允许读**写**(读也一并限制,避免拿它
|
||||
//! 当任意文件读取接口探测磁盘)。授权的三个来源都是用户动作:系统文件对话框、
|
||||
//! 命令行参数、库本身。
|
||||
//!
|
||||
//! **读**比写宽松一档:读只要求「存在且是文件」,写入才强制授权。原因是打开一篇
|
||||
//! 从设置页点进来的文件不该因为「窗口重启过、授权表空了」而失败。
|
||||
//!
|
||||
//! # 编码与换行:读写成对
|
||||
//!
|
||||
//! GBK 文件被当成 UTF-8 读出来是乱码,再按 UTF-8 存回去就是**永久损坏**(原字节
|
||||
//! 已经不可逆地丢了)。因此读的时候把「编码 + 有无 BOM + 换行风格」一并记下来,
|
||||
//! 写回时原样还原;用户显式改编码时才按新编码写。换行同理:CRLF 文件存回去必须
|
||||
//! 还是 CRLF,否则一次「随手保存」就会在整个 diff 里掀起风暴。
|
||||
|
||||
use std::collections::HashSet;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Mutex;
|
||||
use std::time::UNIX_EPOCH;
|
||||
|
||||
use serde::Serialize;
|
||||
use specta::Type;
|
||||
|
||||
/// 会话内已授权(用户显式打开过)的路径集合。
|
||||
///
|
||||
/// 进程级静态而非 Tauri State:授权是「这一次运行期间用户点过什么」的事实,
|
||||
/// 与库根、设置无关,也不需要跨窗口同步(每个源窗口都会自己调 `authorize`)。
|
||||
static AUTHORIZED: std::sync::OnceLock<Mutex<HashSet<PathBuf>>> = std::sync::OnceLock::new();
|
||||
|
||||
fn authorized() -> &'static Mutex<HashSet<PathBuf>> {
|
||||
AUTHORIZED.get_or_init(|| Mutex::new(HashSet::new()))
|
||||
}
|
||||
|
||||
/// 换行风格。
|
||||
pub const EOL_LF: &str = "lf";
|
||||
pub const EOL_CRLF: &str = "crlf";
|
||||
|
||||
/// 一个已打开文件的完整状态(前端据此显示编码/换行,并原样写回)。
|
||||
#[derive(Debug, Clone, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct FileDoc {
|
||||
/// 绝对路径(Windows 下已剥掉 `\\?\` 前缀)
|
||||
pub path: String,
|
||||
/// 显示名(文件名)
|
||||
pub name: String,
|
||||
/// 文本内容(换行已统一为 `\n`,写回时按 `eol` 还原)
|
||||
pub content: String,
|
||||
/// 探测到的编码(`utf-8` / `utf-8-bom` / `gbk` / …)
|
||||
pub encoding: String,
|
||||
/// 换行风格:"lf" | "crlf"
|
||||
pub eol: String,
|
||||
/// 文件字节数
|
||||
pub size: u64,
|
||||
/// 最后修改时间(Unix 毫秒)
|
||||
pub modified: u64,
|
||||
/// 是否超过「大文件」阈值(前端据此关闭 Live Preview / 折叠 / 补全)
|
||||
pub large: bool,
|
||||
/// 行数(前端状态栏显示;大文件也只需要扫一遍换行,成本可忽略)
|
||||
pub lines: u64,
|
||||
/// 是否只读(打开时探测写权限失败;前端据此拦截保存并给出原因)
|
||||
pub readonly: bool,
|
||||
}
|
||||
|
||||
/// 探测写权限:以写模式打开但**不写入**(失败 → 只读)。
|
||||
///
|
||||
/// 比「打开成功但保存时才报错」体验好得多:只读文件一打开就能看到状态栏标记。
|
||||
fn is_writable(path: &Path) -> bool {
|
||||
std::fs::OpenOptions::new().write(true).open(path).is_ok()
|
||||
}
|
||||
|
||||
/// 登记一个路径为「已授权可写」。
|
||||
pub fn authorize(path: &Path) {
|
||||
let key = normalize_key(path);
|
||||
if let Ok(mut set) = authorized().lock() {
|
||||
set.insert(key);
|
||||
}
|
||||
}
|
||||
|
||||
/// 该路径是否已授权(写操作的前置条件)。
|
||||
pub fn is_authorized(path: &Path) -> bool {
|
||||
let key = normalize_key(path);
|
||||
authorized()
|
||||
.lock()
|
||||
.map(|set| set.contains(&key))
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
/// 授权集合的比对键:**尽力规范化**(解析符号链接与 `..`)。
|
||||
///
|
||||
/// 规范化失败(文件不存在)时退回原路径 —— 那说明写操作本来就会失败,
|
||||
/// 这里没必要为了「统一键」而提前报错。
|
||||
fn normalize_key(path: &Path) -> PathBuf {
|
||||
std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf())
|
||||
}
|
||||
|
||||
/// 把路径转成可显示、可回传的字符串(剥掉 Windows 的 `\\?\` 扩展长度前缀)。
|
||||
pub fn display_path(path: &Path) -> String {
|
||||
let s = path.to_string_lossy().to_string();
|
||||
match s.strip_prefix(r"\\?\") {
|
||||
Some(rest) => rest.to_string(),
|
||||
None => s,
|
||||
}
|
||||
}
|
||||
|
||||
/// 探测编码:返回规范名(`utf-8` / `utf-8-bom` / `gbk` / `gb18030` / `big5` / `shift_jis` / …)。
|
||||
///
|
||||
/// # 判定顺序(每一步都有理由)
|
||||
///
|
||||
/// 1. **BOM**:UTF-8 BOM / UTF-16 的 BOM 是无歧义的事实,直接采信;
|
||||
/// 2. **严格 UTF-8 校验**:能完整解成 UTF-8 就是 UTF-8。优先级高于任何统计猜测 ——
|
||||
/// 中文 GBK 字节序列几乎不可能恰好是合法 UTF-8,反向的误判同样罕见;
|
||||
/// 3. **chardetng 统计探测**:区分 Shift_JIS / Big5 / EUC-KR / GB18030 等 CJK 编码。
|
||||
/// 这一步不能省:GB18030 几乎能解码任意字节序列,若只靠「试解是否成功」,
|
||||
/// 日文 Shift_JIS 文件会被静默当成中文 GB18030;
|
||||
/// 4. 探测器给不出我们支持的编码 → 退回 GB18030 兜底;仍不行则按 UTF-8 有损解码
|
||||
/// (宁可显示替换字符,也不要打不开文件)。
|
||||
pub fn detect_encoding(bytes: &[u8]) -> String {
|
||||
if bytes.starts_with(&[0xEF, 0xBB, 0xBF]) {
|
||||
return "utf-8-bom".to_string();
|
||||
}
|
||||
if bytes.starts_with(&[0xFF, 0xFE]) {
|
||||
return "utf-16le".to_string();
|
||||
}
|
||||
if bytes.starts_with(&[0xFE, 0xFF]) {
|
||||
return "utf-16be".to_string();
|
||||
}
|
||||
if std::str::from_utf8(bytes).is_ok() {
|
||||
return "utf-8".to_string();
|
||||
}
|
||||
// 非 UTF-8:先用统计探测区分 CJK 编码(Shift_JIS / Big5 / EUC-KR / GB18030 …)。
|
||||
// 不能直接拿 GB18030 兜底 —— GB18030 几乎能解码任意字节序列,试解永远「成功」,
|
||||
// 会把日文 Shift_JIS 文件静默当成中文 GB18030(用户实测到的问题)。
|
||||
if let Some(name) = detect_with_chardetng(bytes) {
|
||||
return name;
|
||||
}
|
||||
// 探测器给不出我们支持的编码:退回 GB18030(GBK 的每个序列在它之下都合法)
|
||||
if crate::terminal::encoding::is_supported("gb18030") {
|
||||
return "gb18030".to_string();
|
||||
}
|
||||
"utf-8".to_string()
|
||||
}
|
||||
|
||||
/// 用 `chardetng` 统计探测非 UTF-8 文本的编码,并映射回本模块的规范编码名。
|
||||
///
|
||||
/// 只接受我们**支持**的编码(见 `terminal::encoding::SUPPORTED`):探测器给出的
|
||||
/// 单字节西文编码(`windows-125x` / `ISO-8859-x` / `KOI8-*`)统一归到 `latin1`
|
||||
/// (它们都是单字节、逐字节一一映射,不会产生替换字符);其余未知的一律返回
|
||||
/// `None`,由调用方走兜底 —— 宁可退回 GB18030,也不要返回一个解出来全是 `` 的名字。
|
||||
fn detect_with_chardetng(bytes: &[u8]) -> Option<String> {
|
||||
use chardetng::{EncodingDetector, Iso2022JpDetection, Utf8Detection};
|
||||
|
||||
let mut detector = EncodingDetector::new(Iso2022JpDetection::Deny);
|
||||
detector.feed(bytes, true);
|
||||
// 调用前已排除「合法 UTF-8」,因此不允许探测器再返回 UTF-8
|
||||
let guessed = detector.guess(None, Utf8Detection::Deny);
|
||||
let name = guessed.name().to_ascii_lowercase();
|
||||
|
||||
if name.starts_with("windows-125")
|
||||
|| name.starts_with("iso-8859")
|
||||
|| name.starts_with("koi8")
|
||||
|| name == "ibm866"
|
||||
{
|
||||
return Some("latin1".to_string());
|
||||
}
|
||||
let normalized = crate::terminal::encoding::normalize(&name);
|
||||
if crate::terminal::encoding::is_supported(&normalized) {
|
||||
return Some(normalized);
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// 按编码把字节解成字符串(BOM 已剥离)。
|
||||
pub(crate) fn decode_bytes(bytes: &[u8], encoding: &str) -> String {
|
||||
match encoding {
|
||||
"utf-8-bom" => {
|
||||
let body = bytes.strip_prefix(&[0xEF, 0xBB, 0xBF]).unwrap_or(bytes);
|
||||
String::from_utf8_lossy(body).into_owned()
|
||||
}
|
||||
"utf-16le" | "utf-16be" => {
|
||||
// UTF-16 走 encoding_rs;BOM 由它自己处理
|
||||
crate::terminal::encoding::decode(bytes, "utf-16le")
|
||||
}
|
||||
other => crate::terminal::encoding::decode(bytes, other),
|
||||
}
|
||||
}
|
||||
|
||||
/// 按编码把字符串编成字节(必要时写回 BOM)。
|
||||
///
|
||||
/// **不可表示字符绝不静默替换成 `?`**(那是不可逆的数据损坏):先整串试编一次,
|
||||
/// 若往返比对不一致(说明有字符编不进去),再逐字符定位并报错,让用户改用 UTF-8
|
||||
/// 或删除这些字符。
|
||||
pub(crate) fn encode_text(text: &str, encoding: &str) -> Result<Vec<u8>, String> {
|
||||
match encoding {
|
||||
"utf-8-bom" => {
|
||||
let mut out = vec![0xEF, 0xBB, 0xBF];
|
||||
out.extend_from_slice(text.as_bytes());
|
||||
Ok(out)
|
||||
}
|
||||
other => {
|
||||
let normalized = crate::terminal::encoding::normalize(other);
|
||||
if !crate::terminal::encoding::is_supported(&normalized) {
|
||||
return Err(format!("不支持的编码:{other}"));
|
||||
}
|
||||
let encoded = crate::terminal::encoding::encode(text, &normalized);
|
||||
// UTF-8 能表示任何字符串,无需比对
|
||||
if normalized != "utf-8"
|
||||
&& crate::terminal::encoding::decode(&encoded, &normalized) != text
|
||||
{
|
||||
let bad = find_unencodable(text, &normalized);
|
||||
let preview = bad
|
||||
.iter()
|
||||
.take(8)
|
||||
.map(|(index, ch)| format!("第 {index} 个「{ch}」"))
|
||||
.collect::<Vec<_>>()
|
||||
.join("、");
|
||||
let tail = if bad.len() > 8 {
|
||||
format!(",等共 {} 个字符", bad.len())
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
return Err(format!(
|
||||
"编码「{other}」无法表示:{preview}{tail}。请改用 UTF-8,或删除这些字符后再保存"
|
||||
));
|
||||
}
|
||||
Ok(encoded)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 找出目标编码无法表示的字符(位置按字符计,从 1 开始)。仅在错误路径上跑。
|
||||
fn find_unencodable(text: &str, encoding: &str) -> Vec<(usize, char)> {
|
||||
let mut out = Vec::new();
|
||||
for (index, ch) in text.chars().enumerate() {
|
||||
let mut buf = [0u8; 4];
|
||||
let s = ch.encode_utf8(&mut buf);
|
||||
let encoded = crate::terminal::encoding::encode(s, encoding);
|
||||
if crate::terminal::encoding::decode(&encoded, encoding) != &*s {
|
||||
out.push((index + 1, ch));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// 探测换行风格(`\r\n` 只要出现一次就判定为 CRLF —— 混合换行的文件按主流风格写回)。
|
||||
fn detect_eol(text: &str) -> String {
|
||||
if text.contains("\r\n") {
|
||||
EOL_CRLF.to_string()
|
||||
} else {
|
||||
EOL_LF.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
/// 读取任意文件(自动探测编码)。
|
||||
pub fn read_file(path: &str, max_mb: u32) -> Result<FileDoc, String> {
|
||||
read_file_inner(path, max_mb, None)
|
||||
}
|
||||
|
||||
/// 以指定编码**重新解码磁盘字节**(不写回,只换一种解释方式)。
|
||||
///
|
||||
/// 语义(规划 §5.3):切换编码是「换一种方式解释**磁盘字节**」,而不是「重新解释
|
||||
/// 缓冲区文本」—— 因此必须回到磁盘字节重新解码,而不是把编辑器里已有的字符串再转一次。
|
||||
pub fn redecode_file(path: &str, encoding: &str, max_mb: u32) -> Result<FileDoc, String> {
|
||||
read_file_inner(path, max_mb, Some(encoding))
|
||||
}
|
||||
|
||||
/// 读取实现。`forced_encoding` 为 `None` 时走探测链(BOM → 严格 UTF-8 → GB18030)。
|
||||
fn read_file_inner(
|
||||
path: &str,
|
||||
max_mb: u32,
|
||||
forced_encoding: Option<&str>,
|
||||
) -> Result<FileDoc, String> {
|
||||
let trimmed = path.trim();
|
||||
if trimmed.is_empty() {
|
||||
return Err("路径为空".to_string());
|
||||
}
|
||||
let p = Path::new(trimmed);
|
||||
if p.is_dir() {
|
||||
return Err("这是一个目录,请选择文件".to_string());
|
||||
}
|
||||
let meta = std::fs::metadata(p).map_err(|e| format!("读取文件信息失败: {e}"))?;
|
||||
if !meta.is_file() {
|
||||
return Err("目标不是普通文件".to_string());
|
||||
}
|
||||
|
||||
let bytes = std::fs::read(p).map_err(|e| format!("读取文件失败: {e}"))?;
|
||||
let encoding = match forced_encoding {
|
||||
Some(enc) if !enc.trim().is_empty() => {
|
||||
let requested = enc.trim();
|
||||
let normalized = if requested.eq_ignore_ascii_case("utf-8-bom") {
|
||||
"utf-8-bom".to_string()
|
||||
} else {
|
||||
crate::terminal::encoding::normalize(requested)
|
||||
};
|
||||
if normalized != "utf-8-bom" && !crate::terminal::encoding::is_supported(&normalized) {
|
||||
return Err(format!("不支持的编码:{requested}"));
|
||||
}
|
||||
normalized
|
||||
}
|
||||
_ => detect_encoding(&bytes),
|
||||
};
|
||||
let raw = decode_bytes(&bytes, &encoding);
|
||||
let eol = detect_eol(&raw);
|
||||
// 统一成 `\n` 交给编辑器:CM6 的一份文档只应有一种换行,混合换行会让
|
||||
// 「行号 / 选区 / 大纲」三处计算各按各的口径,写法回时再还原
|
||||
let content = raw.replace("\r\n", "\n");
|
||||
let limit = (max_mb.max(1) as u64) * 1024 * 1024;
|
||||
|
||||
Ok(FileDoc {
|
||||
path: display_path(p),
|
||||
name: p
|
||||
.file_name()
|
||||
.map(|n| n.to_string_lossy().to_string())
|
||||
.unwrap_or_default(),
|
||||
lines: content.lines().count() as u64,
|
||||
content,
|
||||
encoding,
|
||||
eol,
|
||||
size: meta.len(),
|
||||
modified: meta
|
||||
.modified()
|
||||
.ok()
|
||||
.and_then(|t| t.duration_since(UNIX_EPOCH).ok())
|
||||
.map(|d| d.as_millis() as u64)
|
||||
.unwrap_or(0),
|
||||
large: meta.len() > limit,
|
||||
readonly: !is_writable(p),
|
||||
})
|
||||
}
|
||||
|
||||
/// 写入任意文件。
|
||||
///
|
||||
/// `encoding` 为空串时沿用「读时探测到的编码」由前端回传的那个值 —— 调用方
|
||||
/// (编辑器)始终带着它,这里不接受「猜一个」。
|
||||
pub fn write_file(
|
||||
path: &str,
|
||||
content: &str,
|
||||
encoding: &str,
|
||||
eol: &str,
|
||||
max_mb: u32,
|
||||
) -> Result<FileDoc, String> {
|
||||
let trimmed = path.trim();
|
||||
if trimmed.is_empty() {
|
||||
return Err("路径为空".to_string());
|
||||
}
|
||||
let p = Path::new(trimmed);
|
||||
if !is_authorized(p) {
|
||||
return Err("该文件未经授权,无法写入(请通过「打开文件」重新选择)".to_string());
|
||||
}
|
||||
if !is_writable(p) {
|
||||
return Err("文件为只读,无法保存".to_string());
|
||||
}
|
||||
|
||||
let enc = if encoding.trim().is_empty() {
|
||||
"utf-8".to_string()
|
||||
} else {
|
||||
crate::terminal::encoding::normalize(encoding)
|
||||
};
|
||||
let text = if eol == EOL_CRLF {
|
||||
content.replace("\r\n", "\n").replace('\n', "\r\n")
|
||||
} else {
|
||||
content.replace("\r\n", "\n")
|
||||
};
|
||||
let bytes = encode_text(&text, &enc)?;
|
||||
|
||||
std::fs::write(p, &bytes).map_err(|e| format!("保存文件失败: {e}"))?;
|
||||
read_file(trimmed, max_mb)
|
||||
}
|
||||
|
||||
/// 把图片等二进制内容写入库根的 `assets/`(粘贴图片用)。
|
||||
///
|
||||
/// 返回**相对库根的路径**(统一 `/` 分隔),前端据此插入 Markdown 图片引用;
|
||||
/// 不使用绝对路径,保证笔记换个机器 / 换个库根也能打开。
|
||||
pub fn write_asset(
|
||||
root: &Path,
|
||||
file_name: &str,
|
||||
data: &[u8],
|
||||
ext: &str,
|
||||
) -> Result<String, String> {
|
||||
let assets = root.join(super::library::ASSETS_DIR);
|
||||
std::fs::create_dir_all(&assets).map_err(|e| format!("创建附件目录失败: {e}"))?;
|
||||
|
||||
let stem = super::library::validate_name(file_name)?;
|
||||
let stem = Path::new(&stem)
|
||||
.file_stem()
|
||||
.map(|s| s.to_string_lossy().to_string())
|
||||
.unwrap_or_else(|| "image".to_string());
|
||||
let ext = ext.trim().trim_start_matches('.').to_ascii_lowercase();
|
||||
let ext = if ext.is_empty() { "png".to_string() } else { ext };
|
||||
|
||||
let mut candidate = format!("{stem}.{ext}");
|
||||
let mut index = 1;
|
||||
while assets.join(&candidate).exists() {
|
||||
candidate = format!("{stem}-{index}.{ext}");
|
||||
index += 1;
|
||||
if index > 9999 {
|
||||
return Err("同名附件过多,请清理 assets 目录".to_string());
|
||||
}
|
||||
}
|
||||
|
||||
std::fs::write(assets.join(&candidate), data).map_err(|e| format!("写入附件失败: {e}"))?;
|
||||
Ok(format!("{}/{candidate}", super::library::ASSETS_DIR))
|
||||
}
|
||||
|
||||
// ===== 测试 =====
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn detects_bom_and_plain_utf8() {
|
||||
assert_eq!(detect_encoding(b"hello"), "utf-8");
|
||||
assert_eq!(detect_encoding("\u{feff}hello".as_bytes()), "utf-8-bom");
|
||||
assert_eq!(detect_encoding(&[0xFF, 0xFE, 0x41, 0x00]), "utf-16le");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn detects_non_utf8_chinese_as_gbk_family() {
|
||||
// 中文:合法 UTF-8 校验必然失败,探测应落在 GBK 家族(gbk 或 gb18030)
|
||||
let text = "这是一段中文测试文本,用于验证编码探测。";
|
||||
let gbk = crate::terminal::encoding::encode(text, "gbk");
|
||||
let detected = detect_encoding(&gbk);
|
||||
assert!(
|
||||
detected == "gbk" || detected == "gb18030",
|
||||
"中文应探测为 GBK 家族,实际为 {detected}"
|
||||
);
|
||||
// GB18030 是 GBK 的超集,用它解码同样能还原
|
||||
assert_eq!(decode_bytes(&gbk, "gb18030"), text);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn detects_shift_jis_not_gb18030() {
|
||||
// 日文 Shift_JIS:GB18030 也能「解码成功」,这正是旧实现误判成中文的原因
|
||||
let text = "これは日本語のテキストです。テスト用のサンプル文です。";
|
||||
let sjis = crate::terminal::encoding::encode(text, "shift_jis");
|
||||
let detected = detect_encoding(&sjis);
|
||||
assert_eq!(
|
||||
detected, "shift_jis",
|
||||
"日文 Shift_JIS 不应被误判(实际 {detected})"
|
||||
);
|
||||
assert_eq!(decode_bytes(&sjis, "shift_jis"), text);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn eol_roundtrip_preserves_crlf() {
|
||||
let dir = std::env::temp_dir().join("thing-notes-files-test");
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("crlf.txt");
|
||||
std::fs::write(&path, b"a\r\nb\r\n").unwrap();
|
||||
|
||||
let doc = read_file(&display_path(&path), 5).unwrap();
|
||||
assert_eq!(doc.eol, EOL_CRLF);
|
||||
assert_eq!(doc.content, "a\nb\n");
|
||||
assert_eq!(doc.lines, 2);
|
||||
|
||||
authorize(&path);
|
||||
let saved = write_file(&display_path(&path), "a\nb\nc\n", "utf-8", EOL_CRLF, 5).unwrap();
|
||||
assert_eq!(saved.content, "a\nb\nc\n");
|
||||
// 落盘字节必须还是 CRLF(否则一次保存就污染整个 diff)
|
||||
assert_eq!(std::fs::read(&path).unwrap(), b"a\r\nb\r\nc\r\n");
|
||||
let _ = std::fs::remove_file(&path);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn write_requires_authorization() {
|
||||
let dir = std::env::temp_dir().join("thing-notes-files-test");
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("unauthorized.txt");
|
||||
std::fs::write(&path, b"x").unwrap();
|
||||
let err = write_file(&display_path(&path), "y", "utf-8", EOL_LF, 5).unwrap_err();
|
||||
assert!(err.contains("未经授权"), "{err}");
|
||||
let _ = std::fs::remove_file(&path);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gbk_write_uses_original_encoding() {
|
||||
let dir = std::env::temp_dir().join("thing-notes-files-test");
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("gbk.txt");
|
||||
std::fs::write(&path, crate::terminal::encoding::encode("中文", "gbk")).unwrap();
|
||||
|
||||
let doc = read_file(&display_path(&path), 5).unwrap();
|
||||
assert_eq!(doc.content, "中文");
|
||||
authorize(&path);
|
||||
write_file(&display_path(&path), "中文内容", &doc.encoding, &doc.eol, 5).unwrap();
|
||||
let bytes = std::fs::read(&path).unwrap();
|
||||
assert_eq!(crate::terminal::encoding::decode(&bytes, "gbk"), "中文内容");
|
||||
let _ = std::fs::remove_file(&path);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn large_flag_uses_megabyte_limit() {
|
||||
let dir = std::env::temp_dir().join("thing-notes-files-test");
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("big.txt");
|
||||
std::fs::write(&path, vec![b'a'; 2048]).unwrap();
|
||||
assert!(read_file(&display_path(&path), 1).unwrap().large == false);
|
||||
// 阈值按 MB 计,2048 字节在 0 上限下被夹到 1MB,仍不算大文件
|
||||
assert!(!read_file(&display_path(&path), 0).unwrap().large);
|
||||
let _ = std::fs::remove_file(&path);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,890 @@
|
||||
//! 「在路径中查找」(Find in Path):对真实文件系统做逐行文本 / 正则检索。
|
||||
//!
|
||||
//! # 为什么不用 `index.rs` 的 FTS5 索引
|
||||
//!
|
||||
//! 索引是**笔记库专用**的加速层:它只覆盖 `.md`、只回传片段(没有行号),且不支持
|
||||
//! 正则。而「在目录 / 库中查找」需要的是**逐行命中 + 行号 + 正则**——这正是 IDEA
|
||||
//! 的 Find in Path 语义(真 grep,不是索引查询)。因此这里直接扫盘,与索引解耦:
|
||||
//! 索引挂掉 / 还没同步完,搜索依然可用。
|
||||
//!
|
||||
//! # 边界(防卡死是第一位的)
|
||||
//!
|
||||
//! - 跳过目录名清单里的目录(默认见 [`DEFAULT_SKIP_DIRS`])与超过大小上限的文件;
|
||||
//! - 跳过二进制文件(前 8KB 含 NUL 字节);
|
||||
//! - **完整统计**所有命中行(`total` / `total_files`),预览结构只构建前 `limit` 条
|
||||
//! (`returned`),`truncated` = 统计到的总数超过回传的预览数。
|
||||
//!
|
||||
//! 「计数便宜、预览贵」:就算超过上限,也只继续 `regex.find` 计数,不再做字符开窗 ——
|
||||
//! 于是「全库一共多少处命中」永远是准的,而 UI 可以分页展示回传的那部分。
|
||||
//!
|
||||
//! # 按文件自己的编码读
|
||||
//!
|
||||
//! 每个文件先用 `detect_encoding` 探测(BOM / UTF-8 合法性 / `chardetng` 统计),再按
|
||||
//! 该编码解码 —— 于是 GBK / Big5 / Shift_JIS / UTF-16 的正文与预览都是**可读的原文字**,
|
||||
//! 而不是一堆 U+FFFD。替换同样按原编码写回(复用 `files.rs` 里那套已带往返校验的
|
||||
//! `encode_text`),因此不会把 GBK 文件改成 UTF-8。
|
||||
//!
|
||||
//! # 每行只出一条命中
|
||||
//!
|
||||
//! 一行里出现多次匹配时,只回传**第一处**(`match_start` / `match_end` 指向它)。
|
||||
//! 这是 grep 类工具的常规做法:结果列表以「行」为单位才能扫读,一行列十条几乎相同
|
||||
//! 的预览反而是噪声。
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use regex::{Regex, RegexBuilder};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
use walkdir::WalkDir;
|
||||
|
||||
use crate::editor::files::{decode_bytes, detect_encoding, encode_text};
|
||||
|
||||
/// 单文件大小上限(超过则跳过:这类文件多是日志 / 数据,检索无意义且极慢)
|
||||
const MAX_FILE_BYTES: u64 = 8 * 1024 * 1024;
|
||||
/// 单行预览最大字符数(超出时围绕命中位置开窗)
|
||||
const PREVIEW_MAX_CHARS: usize = 220;
|
||||
/// 命中前保留的上下文字符数(开窗时)
|
||||
const PREVIEW_LEAD_CHARS: usize = 60;
|
||||
/// 每个文件最多回传的命中行数(防止单个大文件刷满结果)
|
||||
const MAX_MATCHES_PER_FILE: usize = 200;
|
||||
/// 二进制探测读取的头部字节数
|
||||
const BINARY_SNIFF_BYTES: usize = 8 * 1024;
|
||||
|
||||
/// 默认跳过的目录名(`|` 分隔,大小写不敏感)。
|
||||
///
|
||||
/// 这是**唯一**的跳过依据:早期实现还会无条件跳过所有点目录,那样用户在搜索卡片里
|
||||
/// 把 `.git` 从清单里删掉也搜不进去 —— 控件就成了摆设。默认清单已覆盖常见组合。
|
||||
///
|
||||
/// 与前端 `EditorSearch.vue` 的默认值必须一致(前端是展示源,这里是字段缺省时的兜底)。
|
||||
const DEFAULT_SKIP_DIRS: &str = "debug|.vs|.git|.svn|.hg|.idea|.vscode|node_modules|target|dist|build|out|.cache|__pycache__|.venv|venv|vendor|.next|coverage|.tmp-build";
|
||||
|
||||
/// 把 `|` / `,` 分隔的清单拆开(去空白、去空项)。跳过目录名与文件名通配共用这个约定。
|
||||
fn split_list(raw: &str) -> Vec<String> {
|
||||
raw.split(['|', ','])
|
||||
.map(str::trim)
|
||||
.filter(|s| !s.is_empty())
|
||||
.map(str::to_string)
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// 跳过目录名集合(已转小写)。
|
||||
///
|
||||
/// `None` = 用内置默认清单;`Some("")` = **不跳过任何目录**(用户清空输入框就是明确
|
||||
/// 要求全盘搜,包括 `node_modules`)。
|
||||
fn skip_dir_set(raw: &Option<String>) -> Vec<String> {
|
||||
let list = match raw {
|
||||
Some(s) => split_list(s),
|
||||
None => split_list(DEFAULT_SKIP_DIRS),
|
||||
};
|
||||
list.iter().map(|s| s.to_lowercase()).collect()
|
||||
}
|
||||
|
||||
/// 文件名通配过滤器(`None` = 不过滤)。
|
||||
///
|
||||
/// `*` / `*.*` 按 Windows 习惯当「全部文件」,不按字面 glob 处理 —— 否则 `Makefile`
|
||||
/// 这类无扩展名的文件会被默认值意外排除。多项用 `|` 或 `,` 分隔,大小写不敏感。
|
||||
fn build_file_filter(raw: &Option<String>) -> Option<Regex> {
|
||||
let parts = match raw {
|
||||
Some(s) => split_list(s),
|
||||
None => return None,
|
||||
};
|
||||
if parts.is_empty() || parts.iter().any(|p| p == "*" || p == "*.*") {
|
||||
return None;
|
||||
}
|
||||
let body = parts
|
||||
.iter()
|
||||
.map(|p| glob_to_regex(p))
|
||||
.collect::<Vec<_>>()
|
||||
.join("|");
|
||||
RegexBuilder::new(&format!("^(?:{body})$"))
|
||||
.case_insensitive(true)
|
||||
.build()
|
||||
.ok()
|
||||
}
|
||||
|
||||
/// 单个通配片段 → 正则(只匹配文件名,所以 `*` 不必排除路径分隔符)。
|
||||
fn glob_to_regex(pattern: &str) -> String {
|
||||
let mut out = String::new();
|
||||
for ch in pattern.chars() {
|
||||
match ch {
|
||||
'*' => out.push_str(".*"),
|
||||
'?' => out.push('.'),
|
||||
other => out.push_str(®ex::escape(&other.to_string())),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// 查找请求(`dir` 为绝对路径:当前目录或笔记库根)。
|
||||
#[derive(Debug, Clone, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct PathSearchQuery {
|
||||
/// 检索根目录(绝对路径)
|
||||
pub dir: String,
|
||||
/// 关键词(`regex` 为真时按正则解释)
|
||||
pub pattern: String,
|
||||
/// 区分大小写(默认关:与 CM6 搜索一致)
|
||||
pub case_sensitive: bool,
|
||||
/// 全词匹配
|
||||
pub whole_word: bool,
|
||||
/// 按正则解释关键词
|
||||
pub regex: bool,
|
||||
/// 回传预览条数上限(缺省 1000,夹在 1..=5000)。总数不受它影响 ——
|
||||
/// 超过上限的命中只计数不构建预览,由前端分页展示回传的部分
|
||||
pub limit: Option<i64>,
|
||||
/// 文件名通配(`|` / `,` 分隔;空或 `*.*` = 全部文件)
|
||||
pub file_types: Option<String>,
|
||||
/// 跳过的目录名(`|` / `,` 分隔;`Some("")` = 不跳过,`None` = 内置默认清单)
|
||||
pub skip_dirs: Option<String>,
|
||||
}
|
||||
|
||||
/// 一处命中(以「行」为单位)。
|
||||
#[derive(Debug, Clone, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct PathSearchMatch {
|
||||
/// 行号(1 起)
|
||||
pub line: i64,
|
||||
/// 行内字符列(1 起,指向首个匹配)
|
||||
pub column: i64,
|
||||
/// 该行预览(超长时围绕命中开窗,两端以 `…` 标记)
|
||||
pub preview: String,
|
||||
/// 命中在 `preview` 中的起始字符下标(前端高亮用)
|
||||
pub match_start: i64,
|
||||
/// 命中在 `preview` 中的结束字符下标(不含)
|
||||
pub match_end: i64,
|
||||
}
|
||||
|
||||
/// 一个文件内的全部命中。
|
||||
#[derive(Debug, Clone, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct PathSearchFileHits {
|
||||
/// 文件绝对路径
|
||||
pub path: String,
|
||||
/// 文件名(结果列表展示)
|
||||
pub name: String,
|
||||
/// 该文件内**全部**命中行数(`matches` 可能因回传上限只含前一部分)
|
||||
pub total_in_file: i64,
|
||||
pub matches: Vec<PathSearchMatch>,
|
||||
}
|
||||
|
||||
/// 一次「在路径中查找」的结果。
|
||||
#[derive(Debug, Clone, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct PathSearchResult {
|
||||
/// 按文件分组的命中(文件按遍历顺序;超出回传上限的文件不在此列)
|
||||
pub files: Vec<PathSearchFileHits>,
|
||||
/// 全树命中行总数(统计完整,不受 `limit` 影响)
|
||||
pub total: i64,
|
||||
/// 全树至少命中一行的文件总数(≥ `files.len()`)
|
||||
pub total_files: i64,
|
||||
/// 实际回传的预览条数(`files` 里 `matches` 长度之和,≤ `total`)
|
||||
pub returned: i64,
|
||||
/// `total > returned`:还有命中未回传预览
|
||||
pub truncated: bool,
|
||||
}
|
||||
|
||||
/// 替换请求(`dir` 为绝对路径:当前目录或笔记库根)。
|
||||
#[derive(Debug, Clone, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct PathReplaceQuery {
|
||||
/// 检索根目录(绝对路径)
|
||||
pub dir: String,
|
||||
/// 关键词(`regex` 为真时按正则解释)
|
||||
pub pattern: String,
|
||||
/// 替换串(`regex` 关闭时按**字面量**写入,不做 `$1` 展开)
|
||||
pub replacement: String,
|
||||
/// 区分大小写(默认关)
|
||||
pub case_sensitive: bool,
|
||||
/// 全词匹配
|
||||
pub whole_word: bool,
|
||||
/// 按正则解释关键词
|
||||
pub regex: bool,
|
||||
/// 替换总数上限(缺省 1000,夹在 1..=5000)
|
||||
pub limit: Option<i64>,
|
||||
/// 文件名通配(`|` / `,` 分隔;空或 `*.*` = 全部文件)
|
||||
pub file_types: Option<String>,
|
||||
/// 跳过的目录名(`|` / `,` 分隔;`Some("")` = 不跳过,`None` = 内置默认清单)
|
||||
pub skip_dirs: Option<String>,
|
||||
}
|
||||
|
||||
/// 一个被修改的文件。
|
||||
#[derive(Debug, Clone, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct PathReplaceFileResult {
|
||||
pub path: String,
|
||||
pub name: String,
|
||||
pub replacements: i64,
|
||||
}
|
||||
|
||||
/// 被跳过的文件(非 UTF-8 / 写不进去)。
|
||||
#[derive(Debug, Clone, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct PathReplaceSkipped {
|
||||
pub path: String,
|
||||
pub reason: String,
|
||||
}
|
||||
|
||||
/// 一次「在路径中替换」的结果。
|
||||
#[derive(Debug, Clone, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct PathReplaceResult {
|
||||
/// 实际被改写的文件(含各自的替换处数)
|
||||
pub files: Vec<PathReplaceFileResult>,
|
||||
pub files_changed: i64,
|
||||
pub replacements: i64,
|
||||
/// 达到上限提前停止:此时**只改了前面一部分文件**
|
||||
pub truncated: bool,
|
||||
pub skipped: Vec<PathReplaceSkipped>,
|
||||
}
|
||||
|
||||
/// 在目录内逐行检索,按文件分组返回。
|
||||
pub fn search_in_path(query: PathSearchQuery) -> Result<PathSearchResult, String> {
|
||||
let pattern = query.pattern.trim();
|
||||
let dir = Path::new(query.dir.trim());
|
||||
if !dir.is_dir() {
|
||||
return Err("目标目录不存在".to_string());
|
||||
}
|
||||
if pattern.is_empty() {
|
||||
return Ok(PathSearchResult {
|
||||
files: Vec::new(),
|
||||
total: 0,
|
||||
total_files: 0,
|
||||
returned: 0,
|
||||
truncated: false,
|
||||
});
|
||||
}
|
||||
|
||||
let regex = build_regex(pattern, &query)?;
|
||||
let limit = query.limit.unwrap_or(1000).clamp(1, 5000) as usize;
|
||||
let skip_dirs = skip_dir_set(&query.skip_dirs);
|
||||
let file_filter = build_file_filter(&query.file_types);
|
||||
|
||||
let mut files: Vec<PathSearchFileHits> = Vec::new();
|
||||
let mut total = 0usize;
|
||||
let mut total_files = 0usize;
|
||||
let mut returned = 0usize;
|
||||
|
||||
// 不再「达限即停」:命中行数与文件数要统计完整树(用户要的是准确的总量),
|
||||
// 超过 `limit` 之后只继续计数,不再构建预览结构(开窗/换算才是贵的)。
|
||||
for_each_candidate_file(dir, &skip_dirs, file_filter.as_ref(), |path, bytes| {
|
||||
// 按文件**自己的编码**解码:GBK / Big5 / Shift_JIS / UTF-16 的正文与预览都是
|
||||
// 可读的原文字,而不是一堆 U+FFFD
|
||||
let text = decode_bytes(bytes, &detect_encoding(bytes));
|
||||
let mut hits: Vec<PathSearchMatch> = Vec::new();
|
||||
let mut in_file = 0usize;
|
||||
for (index, raw) in text.split('\n').enumerate() {
|
||||
let line = raw.strip_suffix('\r').unwrap_or(raw);
|
||||
let Some(m) = regex.find(line) else { continue };
|
||||
in_file += 1;
|
||||
if returned < limit && hits.len() < MAX_MATCHES_PER_FILE {
|
||||
hits.push(make_match(line, m.start(), m.end(), (index + 1) as i64));
|
||||
returned += 1;
|
||||
}
|
||||
}
|
||||
|
||||
if in_file > 0 {
|
||||
total += in_file;
|
||||
total_files += 1;
|
||||
// 预览为空的文件(上限已满)不进 `files`:UI 上一个没有行的文件头是噪声
|
||||
if !hits.is_empty() {
|
||||
files.push(PathSearchFileHits {
|
||||
path: path.to_string_lossy().to_string(),
|
||||
name: file_name_of(path),
|
||||
total_in_file: in_file as i64,
|
||||
matches: hits,
|
||||
});
|
||||
}
|
||||
}
|
||||
true
|
||||
});
|
||||
|
||||
Ok(PathSearchResult {
|
||||
files,
|
||||
total: total as i64,
|
||||
total_files: total_files as i64,
|
||||
returned: returned as i64,
|
||||
truncated: total > returned,
|
||||
})
|
||||
}
|
||||
|
||||
/// 在目录内逐文件替换。
|
||||
///
|
||||
/// # 安全模型(这是会**改用户磁盘文件**的操作,每条都是刻意的)
|
||||
///
|
||||
/// - **按文件自己的编码读与写**:`detect_encoding` 探测 → `decode_bytes` 解码 →
|
||||
/// `encode_text` 编码写回,所以 GBK 文件写回去还是 GBK,不会被改成 UTF-8。
|
||||
/// - **编码不可字节级还原就跳过**:编码探测对某些文件是有歧义的(同一段内容在
|
||||
/// GBK / GB18030 下能编出不同字节,UTF-16 的 BOM 也不一定补得回来)。写回前先验
|
||||
/// 「原文按该编码重新编码 == 原字节」,不等就整文件跳过 —— 否则重编码会顺手改掉
|
||||
/// 未命中的字节,那是用户无从察觉的数据损坏。
|
||||
/// - **替换内容编不进去就跳过**:交给 `encode_text` 判定(它绝不把不可表示字符静默
|
||||
/// 变成 `?`),失败原因逐个回报到 `skipped`。
|
||||
/// - **只写真正变了的文件**:没匹配到就 `return`,不徒增 mtime、不触发文件监听事件。
|
||||
/// - **上限停在文件边界**:替换总数达到 `limit` 就停止并回传 `truncated`。绝不写
|
||||
/// 「一个文件只改了一半」,所以允许总数略微超过上限。
|
||||
/// - **失败即记录**:只读 / 被占用等写入失败不影响其它文件,逐个回报 `skipped`。
|
||||
pub fn replace_in_path(query: PathReplaceQuery) -> Result<PathReplaceResult, String> {
|
||||
let pattern = query.pattern.trim();
|
||||
let dir = Path::new(query.dir.trim());
|
||||
if !dir.is_dir() {
|
||||
return Err("目标目录不存在".to_string());
|
||||
}
|
||||
|
||||
let mut result = PathReplaceResult {
|
||||
files: Vec::new(),
|
||||
files_changed: 0,
|
||||
replacements: 0,
|
||||
truncated: false,
|
||||
skipped: Vec::new(),
|
||||
};
|
||||
if pattern.is_empty() {
|
||||
return Ok(result);
|
||||
}
|
||||
|
||||
let regex = build_regex(pattern, &query)?;
|
||||
let limit = query.limit.unwrap_or(1000).clamp(1, 5000) as usize;
|
||||
let skip_dirs = skip_dir_set(&query.skip_dirs);
|
||||
let file_filter = build_file_filter(&query.file_types);
|
||||
// 正则关闭时按字面量写入(不让 `$1` / `$foo` 被意外展开 —— 用户在做纯文本替换);
|
||||
// 开启时才做捕获组展开,并把 CM6 风格的 `$&`(整个匹配)统一成 Rust regex 的 `$0`
|
||||
let expand = query.regex;
|
||||
let replacement = if expand {
|
||||
query.replacement.replace("$&", "$0")
|
||||
} else {
|
||||
query.replacement.clone()
|
||||
};
|
||||
|
||||
for_each_candidate_file(dir, &skip_dirs, file_filter.as_ref(), |path, bytes| {
|
||||
if result.replacements as usize >= limit {
|
||||
result.truncated = true;
|
||||
return false;
|
||||
}
|
||||
|
||||
let encoding = detect_encoding(bytes);
|
||||
let text = decode_bytes(bytes, &encoding);
|
||||
// 编码必须能字节级还原原文,否则重编码会改动未命中的字节(见函数文档)
|
||||
match encode_text(&text, &encoding) {
|
||||
Ok(same) if same == bytes => {}
|
||||
Ok(_) => {
|
||||
result.skipped.push(PathReplaceSkipped {
|
||||
path: path.to_string_lossy().to_string(),
|
||||
reason: format!("编码「{encoding}」无法字节级还原原文,已跳过(避免改动未命中的字节)"),
|
||||
});
|
||||
return true;
|
||||
}
|
||||
Err(e) => {
|
||||
result.skipped.push(PathReplaceSkipped {
|
||||
path: path.to_string_lossy().to_string(),
|
||||
reason: e,
|
||||
});
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
let count = regex.find_iter(&text).count();
|
||||
if count == 0 {
|
||||
return true;
|
||||
}
|
||||
let next = if expand {
|
||||
regex.replace_all(&text, replacement.as_str())
|
||||
} else {
|
||||
regex.replace_all(&text, regex::NoExpand(replacement.as_str()))
|
||||
};
|
||||
let out = match encode_text(&next, &encoding) {
|
||||
Ok(b) => b,
|
||||
Err(e) => {
|
||||
result.skipped.push(PathReplaceSkipped {
|
||||
path: path.to_string_lossy().to_string(),
|
||||
reason: e,
|
||||
});
|
||||
return true;
|
||||
}
|
||||
};
|
||||
|
||||
if let Err(e) = std::fs::write(path, &out) {
|
||||
result.skipped.push(PathReplaceSkipped {
|
||||
path: path.to_string_lossy().to_string(),
|
||||
reason: format!("写入失败:{e}"),
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
result.replacements += count as i64;
|
||||
result.files_changed += 1;
|
||||
result.files.push(PathReplaceFileResult {
|
||||
path: path.to_string_lossy().to_string(),
|
||||
name: file_name_of(path),
|
||||
replacements: count as i64,
|
||||
});
|
||||
true
|
||||
});
|
||||
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
/// 遍历 `dir` 下的候选文件(剪枝 + 尺寸 + 二进制 + 文件名通配),逐个把字节交给 `visit`。
|
||||
///
|
||||
/// `visit` 返回 `false` 表示调用方要求提前结束(例如命中总数已达上限)。
|
||||
///
|
||||
/// 抽出来给「查找」与「替换」共用:两者的**取舍必须完全一致**(跳哪些目录、多大算大、
|
||||
/// 什么算二进制、按什么文件名过滤),否则会出现「搜得到、替换却跳过」这种自相矛盾的行为。
|
||||
fn for_each_candidate_file(
|
||||
dir: &Path,
|
||||
skip_dirs: &[String],
|
||||
file_filter: Option<&Regex>,
|
||||
mut visit: impl FnMut(&Path, &[u8]) -> bool,
|
||||
) {
|
||||
for entry in WalkDir::new(dir)
|
||||
.follow_links(false)
|
||||
.into_iter()
|
||||
.filter_entry(|e| !should_skip(e, skip_dirs))
|
||||
{
|
||||
let Ok(entry) = entry else { continue };
|
||||
if !entry.file_type().is_file() {
|
||||
continue;
|
||||
}
|
||||
if let Some(filter) = file_filter {
|
||||
let name = entry.file_name().to_string_lossy();
|
||||
if !filter.is_match(&name) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
let Ok(meta) = entry.metadata() else { continue };
|
||||
if meta.len() > MAX_FILE_BYTES {
|
||||
continue;
|
||||
}
|
||||
let Ok(bytes) = std::fs::read(entry.path()) else { continue };
|
||||
// 二进制文件(头部含 NUL)直接跳过:只会读到一堆乱码预览
|
||||
if bytes[..bytes.len().min(BINARY_SNIFF_BYTES)].contains(&0u8) {
|
||||
continue;
|
||||
}
|
||||
if !visit(entry.path(), &bytes) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 文件名(结果列表展示用)。
|
||||
fn file_name_of(path: &Path) -> String {
|
||||
path.file_name()
|
||||
.map(|n| n.to_string_lossy().to_string())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// 查找 / 替换请求共有的匹配选项。
|
||||
///
|
||||
/// 抽成 trait 是为了让两处 `build_regex` 调用**不可能**把选项传串位 —— 查找与替换必须
|
||||
/// 用完全一样的规则构造正则,否则会出现「搜到的和替换的不是同一批」这种最坏情况。
|
||||
trait MatchOptions {
|
||||
fn regex_mode(&self) -> bool;
|
||||
fn whole_word(&self) -> bool;
|
||||
fn case_sensitive(&self) -> bool;
|
||||
}
|
||||
|
||||
impl MatchOptions for PathSearchQuery {
|
||||
fn regex_mode(&self) -> bool {
|
||||
self.regex
|
||||
}
|
||||
fn whole_word(&self) -> bool {
|
||||
self.whole_word
|
||||
}
|
||||
fn case_sensitive(&self) -> bool {
|
||||
self.case_sensitive
|
||||
}
|
||||
}
|
||||
|
||||
impl MatchOptions for PathReplaceQuery {
|
||||
fn regex_mode(&self) -> bool {
|
||||
self.regex
|
||||
}
|
||||
fn whole_word(&self) -> bool {
|
||||
self.whole_word
|
||||
}
|
||||
fn case_sensitive(&self) -> bool {
|
||||
self.case_sensitive
|
||||
}
|
||||
}
|
||||
|
||||
/// 组装正则:`regex` 关闭时转义为字面量,`whole_word` 时包一层词边界。
|
||||
fn build_regex(pattern: &str, options: &impl MatchOptions) -> Result<Regex, String> {
|
||||
let core = if options.regex_mode() {
|
||||
pattern.to_string()
|
||||
} else {
|
||||
regex::escape(pattern)
|
||||
};
|
||||
let body = if options.whole_word() {
|
||||
format!(r"\b(?:{core})\b")
|
||||
} else {
|
||||
core
|
||||
};
|
||||
RegexBuilder::new(&body)
|
||||
.case_insensitive(!options.case_sensitive())
|
||||
.build()
|
||||
.map_err(|e| format!("正则表达式无效:{e}"))
|
||||
}
|
||||
|
||||
/// 目录遍历剪枝:按**清单里的名字**跳过(大小写不敏感)。根目录(depth 0)永不跳过。
|
||||
fn should_skip(entry: &walkdir::DirEntry, skip_dirs: &[String]) -> bool {
|
||||
if entry.depth() == 0 || !entry.file_type().is_dir() {
|
||||
return false;
|
||||
}
|
||||
let name = entry.file_name().to_string_lossy().to_lowercase();
|
||||
skip_dirs.iter().any(|s| *s == name)
|
||||
}
|
||||
|
||||
/// 构造一行命中:超长行围绕命中开窗,并把命中位置换算成预览内的字符下标。
|
||||
fn make_match(line: &str, match_start: usize, match_end: usize, line_no: i64) -> PathSearchMatch {
|
||||
let chars: Vec<char> = line.chars().collect();
|
||||
let start_ch = char_index(line, match_start);
|
||||
let end_ch = char_index(line, match_end);
|
||||
|
||||
let window_start = start_ch.saturating_sub(PREVIEW_LEAD_CHARS);
|
||||
let window_end = (window_start + PREVIEW_MAX_CHARS)
|
||||
.max(end_ch)
|
||||
.min(chars.len());
|
||||
let body: String = chars[window_start..window_end].iter().collect();
|
||||
let prefix = if window_start > 0 { "…" } else { "" };
|
||||
let suffix = if window_end < chars.len() { "…" } else { "" };
|
||||
let preview = format!("{prefix}{body}{suffix}");
|
||||
|
||||
let lead = prefix.chars().count() as i64;
|
||||
let preview_len = preview.chars().count() as i64;
|
||||
let match_from = ((start_ch - window_start) as i64 + lead).clamp(0, preview_len);
|
||||
let match_to = ((end_ch - window_start) as i64 + lead).clamp(match_from, preview_len);
|
||||
|
||||
PathSearchMatch {
|
||||
line: line_no,
|
||||
column: (start_ch + 1) as i64,
|
||||
preview,
|
||||
match_start: match_from,
|
||||
match_end: match_to,
|
||||
}
|
||||
}
|
||||
|
||||
/// 字节下标 → 字符下标(`regex` 给的是字节偏移,前端高亮要字符下标)。
|
||||
fn char_index(s: &str, byte: usize) -> usize {
|
||||
let byte = byte.min(s.len());
|
||||
s[..byte].chars().count()
|
||||
}
|
||||
|
||||
/// 「在路径中查找」命令。
|
||||
///
|
||||
/// 走 `spawn_blocking`:一次目录扫描是同步阻塞 IO,放在 Tauri 命令线程上会占住它
|
||||
/// (范式同 `editor_delete_path` / `editor_sync_now`)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn editor_search_in_path(query: PathSearchQuery) -> Result<PathSearchResult, String> {
|
||||
tauri::async_runtime::spawn_blocking(move || search_in_path(query))
|
||||
.await
|
||||
.map_err(|e| format!("检索任务失败: {e}"))?
|
||||
}
|
||||
|
||||
/// 「在路径中替换」命令。
|
||||
///
|
||||
/// 与查找同理走 `spawn_blocking`(整棵树的重写是同步阻塞 IO)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn editor_replace_in_path(query: PathReplaceQuery) -> Result<PathReplaceResult, String> {
|
||||
tauri::async_runtime::spawn_blocking(move || replace_in_path(query))
|
||||
.await
|
||||
.map_err(|e| format!("替换任务失败: {e}"))?
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// 每个用例独占一个临时目录(测试并行跑,不能共用)。
|
||||
///
|
||||
/// 用 crate 的 `target/test-tmp/` 而不是 `std::env::temp_dir()`:系统临时目录在受限
|
||||
/// 环境下未必可写(本机就是这样 —— 连既有的 `files.rs` 用例也会 `PermissionDenied`),
|
||||
/// 而 `target/` 一定可写,且已被 gitignore。
|
||||
fn temp_dir(name: &str) -> std::path::PathBuf {
|
||||
let dir = Path::new(env!("CARGO_MANIFEST_DIR"))
|
||||
.join("target")
|
||||
.join("test-tmp")
|
||||
.join(format!("grep-{name}"));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
dir
|
||||
}
|
||||
|
||||
/// 字面量(非正则)替换请求。
|
||||
fn literal(dir: &Path, pattern: &str, replacement: &str) -> PathReplaceQuery {
|
||||
PathReplaceQuery {
|
||||
dir: dir.to_string_lossy().to_string(),
|
||||
pattern: pattern.to_string(),
|
||||
replacement: replacement.to_string(),
|
||||
case_sensitive: true,
|
||||
whole_word: false,
|
||||
regex: false,
|
||||
limit: None,
|
||||
file_types: None,
|
||||
skip_dirs: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// 同上的查找请求。
|
||||
fn search_query(dir: &Path, pattern: &str) -> PathSearchQuery {
|
||||
PathSearchQuery {
|
||||
dir: dir.to_string_lossy().to_string(),
|
||||
pattern: pattern.to_string(),
|
||||
case_sensitive: true,
|
||||
whole_word: false,
|
||||
regex: false,
|
||||
limit: None,
|
||||
file_types: None,
|
||||
skip_dirs: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn literal_replace_keeps_bom_and_crlf() {
|
||||
let dir = temp_dir("bom-crlf");
|
||||
let file = dir.join("a.txt");
|
||||
let mut bytes = vec![0xEF, 0xBB, 0xBF];
|
||||
bytes.extend_from_slice(b"foo\r\nfoo\r\n");
|
||||
std::fs::write(&file, &bytes).unwrap();
|
||||
|
||||
let result = replace_in_path(literal(&dir, "foo", "bar")).unwrap();
|
||||
assert_eq!(result.replacements, 2);
|
||||
assert_eq!(result.files_changed, 1);
|
||||
assert!(!result.truncated);
|
||||
assert!(result.skipped.is_empty());
|
||||
|
||||
let mut expected = vec![0xEF, 0xBB, 0xBF];
|
||||
expected.extend_from_slice(b"bar\r\nbar\r\n");
|
||||
assert_eq!(
|
||||
std::fs::read(&file).unwrap(),
|
||||
expected,
|
||||
"BOM 与 CRLF 必须原样保留"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn literal_replacement_does_not_expand_captures() {
|
||||
let dir = temp_dir("literal-dollar");
|
||||
let file = dir.join("a.txt");
|
||||
std::fs::write(&file, "foo\n").unwrap();
|
||||
|
||||
replace_in_path(literal(&dir, "foo", "$1x")).unwrap();
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(&file).unwrap(),
|
||||
"$1x\n",
|
||||
"正则关闭时替换串必须按字面量写入"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn regex_mode_expands_groups_and_normalizes_ampersand() {
|
||||
let dir = temp_dir("regex-groups");
|
||||
let a = dir.join("a.txt");
|
||||
let b = dir.join("b.txt");
|
||||
std::fs::write(&a, "user@host\n").unwrap();
|
||||
std::fs::write(&b, "word\n").unwrap();
|
||||
|
||||
let mut groups = literal(&dir, r"(\w+)@(\w+)", "$2.$1");
|
||||
groups.regex = true;
|
||||
replace_in_path(groups).unwrap();
|
||||
assert_eq!(std::fs::read_to_string(&a).unwrap(), "host.user\n");
|
||||
|
||||
// `$&`(CM6 风格的「整个匹配」)要等价于 Rust 的 `$0`
|
||||
let mut whole = literal(&dir, "word", "[$&]");
|
||||
whole.regex = true;
|
||||
replace_in_path(whole).unwrap();
|
||||
assert_eq!(std::fs::read_to_string(&b).unwrap(), "[word]\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn searches_and_replaces_gbk_file_keeping_its_encoding() {
|
||||
let dir = temp_dir("gbk");
|
||||
let file = dir.join("a.txt");
|
||||
let original = crate::terminal::encoding::encode("中文 foo\n", "gbk");
|
||||
std::fs::write(&file, &original).unwrap();
|
||||
assert!(
|
||||
std::str::from_utf8(&original).is_err(),
|
||||
"前提:原文不是合法 UTF-8"
|
||||
);
|
||||
|
||||
// 查找:预览要按原编码解出中文,而不是一堆 U+FFFD
|
||||
let found = search_in_path(search_query(&dir, "foo")).unwrap();
|
||||
assert_eq!(found.total, 1);
|
||||
let preview = &found.files[0].matches[0].preview;
|
||||
assert!(preview.contains("中文"), "预览应按原编码解出中文,实际:{preview}");
|
||||
assert!(!preview.contains('\u{FFFD}'), "预览不应出现替换字符");
|
||||
|
||||
// 替换:写回去仍然是 GBK
|
||||
let replaced = replace_in_path(literal(&dir, "foo", "bar")).unwrap();
|
||||
assert_eq!(replaced.replacements, 1);
|
||||
assert!(
|
||||
replaced.skipped.is_empty(),
|
||||
"GBK 文件应能正常替换,实际跳过:{:?}",
|
||||
replaced.skipped
|
||||
);
|
||||
let after = std::fs::read(&file).unwrap();
|
||||
assert_eq!(
|
||||
decode_bytes(&after, &detect_encoding(&after)),
|
||||
"中文 bar\n",
|
||||
"应能按原编码读回替换后的内容"
|
||||
);
|
||||
assert!(
|
||||
std::str::from_utf8(&after).is_err(),
|
||||
"不能把 GBK 文件写成 UTF-8"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn skips_replace_when_replacement_is_not_encodable() {
|
||||
let dir = temp_dir("unencodable");
|
||||
let file = dir.join("a.txt");
|
||||
let original = crate::terminal::encoding::encode("中文 foo\n", "gbk");
|
||||
std::fs::write(&file, &original).unwrap();
|
||||
|
||||
// emoji 编不进 GBK:必须跳过并回报,绝不能写成 `?`
|
||||
let result = replace_in_path(literal(&dir, "foo", "🙂")).unwrap();
|
||||
assert_eq!(result.replacements, 0);
|
||||
assert_eq!(result.skipped.len(), 1, "应回报为跳过");
|
||||
assert_eq!(
|
||||
std::fs::read(&file).unwrap(),
|
||||
original,
|
||||
"编码装不下替换内容时,文件必须一个字节都不动"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn respects_custom_skip_dirs_and_file_types() {
|
||||
let dir = temp_dir("filters");
|
||||
// 目录名刻意不落在默认清单里(`vendor` / `build` 之类都在清单里)
|
||||
let sub = dir.join("innersrc");
|
||||
std::fs::create_dir_all(&sub).unwrap();
|
||||
std::fs::write(dir.join("a.md"), "foo\n").unwrap();
|
||||
std::fs::write(dir.join("b.txt"), "foo\n").unwrap();
|
||||
std::fs::write(sub.join("c.md"), "foo\n").unwrap();
|
||||
|
||||
// `innersrc` 不在默认清单里 → 三处都命中
|
||||
assert_eq!(search_in_path(search_query(&dir, "foo")).unwrap().total, 3);
|
||||
|
||||
// 只搜 *.md
|
||||
let mut by_type = search_query(&dir, "foo");
|
||||
by_type.file_types = Some("*.md".to_string());
|
||||
assert_eq!(search_in_path(by_type).unwrap().total, 2, "应只命中 .md");
|
||||
|
||||
// 跳过 innersrc
|
||||
let mut skip = search_query(&dir, "foo");
|
||||
skip.skip_dirs = Some("innersrc".to_string());
|
||||
assert_eq!(
|
||||
search_in_path(skip).unwrap().total,
|
||||
2,
|
||||
"innersrc 下的应被跳过"
|
||||
);
|
||||
|
||||
// 默认清单跳过 .git
|
||||
let git = dir.join(".git");
|
||||
std::fs::create_dir_all(&git).unwrap();
|
||||
std::fs::write(git.join("cfg"), "foo\n").unwrap();
|
||||
assert_eq!(
|
||||
search_in_path(search_query(&dir, "foo")).unwrap().total,
|
||||
3,
|
||||
"默认清单应跳过 .git"
|
||||
);
|
||||
|
||||
// 清空清单 = 不跳过任何目录(清单是唯一依据)
|
||||
let mut no_skip = search_query(&dir, "foo");
|
||||
no_skip.skip_dirs = Some(String::new());
|
||||
assert_eq!(
|
||||
search_in_path(no_skip).unwrap().total,
|
||||
4,
|
||||
"清空清单后连 .git 也要搜"
|
||||
);
|
||||
|
||||
// `*.*` 按「全部文件」处理:无扩展名的 Makefile 不能被排除
|
||||
std::fs::write(dir.join("Makefile"), "foo\n").unwrap();
|
||||
let mut star = search_query(&dir, "foo");
|
||||
star.file_types = Some("*.*".to_string());
|
||||
assert_eq!(
|
||||
search_in_path(star).unwrap().total,
|
||||
4,
|
||||
"*.* 应包含无扩展名文件"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn limit_stops_at_file_boundary_without_half_writes() {
|
||||
let dir = temp_dir("limit");
|
||||
for name in ["1.txt", "2.txt", "3.txt"] {
|
||||
std::fs::write(dir.join(name), "foo\nfoo\n").unwrap();
|
||||
}
|
||||
|
||||
let mut query = literal(&dir, "foo", "bar");
|
||||
query.limit = Some(2);
|
||||
let result = replace_in_path(query).unwrap();
|
||||
|
||||
assert!(result.truncated, "达到上限应回报 truncated");
|
||||
assert_eq!(result.files_changed, 1, "上限停在文件边界,只应改完一个文件");
|
||||
assert_eq!(result.replacements, 2);
|
||||
|
||||
// 其余两个文件必须完全没动(绝不能出现「只改了一半」的文件)
|
||||
let untouched = ["1.txt", "2.txt", "3.txt"]
|
||||
.iter()
|
||||
.filter(|n| std::fs::read_to_string(dir.join(n)).unwrap() == "foo\nfoo\n")
|
||||
.count();
|
||||
assert_eq!(untouched, 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn skips_binary_files_and_pruned_dirs() {
|
||||
let dir = temp_dir("binary-prune");
|
||||
let bin = dir.join("bin.dat");
|
||||
std::fs::write(&bin, b"foo\0foo").unwrap();
|
||||
let git = dir.join(".git");
|
||||
std::fs::create_dir_all(&git).unwrap();
|
||||
std::fs::write(git.join("cfg"), "foo\n").unwrap();
|
||||
|
||||
let result = replace_in_path(literal(&dir, "foo", "bar")).unwrap();
|
||||
assert_eq!(result.replacements, 0, "二进制文件与 .git 都不该被改写");
|
||||
assert_eq!(std::fs::read(&bin).unwrap(), b"foo\0foo");
|
||||
assert_eq!(std::fs::read_to_string(git.join("cfg")).unwrap(), "foo\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn search_and_replace_agree_on_matches() {
|
||||
let dir = temp_dir("agree");
|
||||
std::fs::write(dir.join("a.txt"), "Alpha alpha ALPHA\n").unwrap();
|
||||
|
||||
let found = search_in_path(search_query(&dir, "Alpha")).unwrap();
|
||||
assert_eq!(found.total, 1);
|
||||
|
||||
let replaced = replace_in_path(literal(&dir, "Alpha", "Beta")).unwrap();
|
||||
assert_eq!(replaced.replacements, 1, "替换处数必须与检索结果一致");
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(dir.join("a.txt")).unwrap(),
|
||||
"Beta alpha ALPHA\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn search_counts_all_hits_beyond_limit() {
|
||||
let dir = temp_dir("count-all");
|
||||
for name in ["1.txt", "2.txt", "3.txt"] {
|
||||
std::fs::write(dir.join(name), "foo\nfoo\n").unwrap();
|
||||
}
|
||||
|
||||
let mut query = search_query(&dir, "foo");
|
||||
query.limit = Some(2);
|
||||
let result = search_in_path(query).unwrap();
|
||||
|
||||
assert_eq!(result.total, 6, "总数统计完整树,不受 limit 影响");
|
||||
assert_eq!(result.total_files, 3, "文件数同样统计完整树");
|
||||
assert_eq!(result.returned, 2, "预览只回传 limit 条");
|
||||
assert!(result.truncated, "total > returned 应标记截断");
|
||||
assert_eq!(result.files.len(), 1, "超出上限的文件不再回传预览");
|
||||
assert_eq!(result.files[0].name, "1.txt");
|
||||
assert_eq!(result.files[0].total_in_file, 2);
|
||||
assert_eq!(result.files[0].matches.len(), 2);
|
||||
|
||||
// limit 足够时 truncated 为假,且 returned == total
|
||||
let full = search_in_path(search_query(&dir, "foo")).unwrap();
|
||||
assert_eq!(full.returned, full.total);
|
||||
assert!(!full.truncated);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,471 @@
|
||||
//! 导入:本地 Markdown 目录 / 单文件 / zip 包 → 笔记库。
|
||||
//!
|
||||
//! # 永不覆盖
|
||||
//!
|
||||
//! 导入的唯一硬规则是**不覆盖库内已有文件**:重名时加序号(`笔记 2.md`)。
|
||||
//! 理由很直接 —— 导入是个批量动作,用户不会记得库里已经有哪些名字;一旦某个
|
||||
//! 同名笔记被静默替换,就是一次不可撤销的数据丢失。「多一个文件」远比「少一篇笔记」
|
||||
//! 可接受。
|
||||
//!
|
||||
//! # zip 的路径安全
|
||||
//!
|
||||
//! zip 条目名可以包含 `..` 或绝对路径(经典的 Zip Slip)。这里用
|
||||
//! `enclosed_name()` 让 zip crate 做规范化与拒绝,再过一道 [`library::safe_join`]。
|
||||
//! 两层都做不是冗余:前者防的是「解包到库外」,后者防的是「库内路径被拼成绝对路径」。
|
||||
//!
|
||||
//! # 保留目录结构
|
||||
//!
|
||||
//! 导入目录时保留其相对结构(`笔记/2026/a.md` → `<目标目录>/笔记/2026/a.md`):
|
||||
//! 用户选一个目录导入,期待的是「把这棵子树搬进来」,而不是把几十篇笔记拍平到一层。
|
||||
//! 但**跳过隐藏目录与 `node_modules`**(与同步的排除规则同一口径)。
|
||||
|
||||
use std::io::Read;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use super::library;
|
||||
use super::types::ImportReport;
|
||||
|
||||
/// 测试里要用 `ZipWriter::write_all`(`Write` 是 trait 方法,必须进作用域)。
|
||||
#[cfg(test)]
|
||||
use std::io::Write as _;
|
||||
|
||||
/// 单次导入的文件数上限(防御性:避免误选 `C:\` 之类的目录把应用拖死)。
|
||||
const MAX_IMPORT_FILES: usize = 20_000;
|
||||
|
||||
/// 从磁盘路径导入(文件 / 目录 / zip,自动判别)。
|
||||
///
|
||||
/// `dest_dir` 为库内相对目录(空串 = 库根)。
|
||||
pub fn import_path(root: &Path, source: &str, dest_dir: &str) -> Result<ImportReport, String> {
|
||||
let path = PathBuf::from(source.trim());
|
||||
if !path.exists() {
|
||||
return Err(format!("路径不存在:{source}"));
|
||||
}
|
||||
library::ensure_library(root)?;
|
||||
// 目标目录先建出来(导入到新建的目录时它可能还不存在)
|
||||
let dest = library::safe_join(root, dest_dir)?;
|
||||
std::fs::create_dir_all(&dest).map_err(|e| format!("创建目标目录失败: {e}"))?;
|
||||
|
||||
let mut report = ImportReport::default();
|
||||
|
||||
if path.is_file() {
|
||||
let is_zip = path
|
||||
.extension()
|
||||
.map(|e| e.eq_ignore_ascii_case("zip"))
|
||||
.unwrap_or(false);
|
||||
if is_zip {
|
||||
import_zip(root, &path, &dest, &mut report)?;
|
||||
} else {
|
||||
import_single(root, &path, &dest, &mut report)?;
|
||||
}
|
||||
} else {
|
||||
import_dir(root, &path, &dest, &mut report)?;
|
||||
}
|
||||
|
||||
// 导入后刷新索引交给命令层(它有 AppHandle 与索引服务)
|
||||
Ok(report)
|
||||
}
|
||||
|
||||
/// 导入单个文件(非 Markdown 的图片类文件放进 `assets/`)。
|
||||
fn import_single(
|
||||
root: &Path,
|
||||
file: &Path,
|
||||
dest: &Path,
|
||||
report: &mut ImportReport,
|
||||
) -> Result<(), String> {
|
||||
let name = file
|
||||
.file_name()
|
||||
.map(|n| n.to_string_lossy().to_string())
|
||||
.unwrap_or_default();
|
||||
if name.is_empty() {
|
||||
return Err("无法解析文件名".to_string());
|
||||
}
|
||||
if !is_markdown(&name) {
|
||||
// 单选的图片/附件:放进 assets,不当笔记
|
||||
return import_asset(root, file, &name, report);
|
||||
}
|
||||
copy_note(file, dest, &name, report)
|
||||
}
|
||||
|
||||
/// 递归导入目录(保留相对结构)。
|
||||
fn import_dir(
|
||||
root: &Path,
|
||||
dir: &Path,
|
||||
dest: &Path,
|
||||
report: &mut ImportReport,
|
||||
) -> Result<(), String> {
|
||||
let mut count = 0usize;
|
||||
for entry in walkdir::WalkDir::new(dir)
|
||||
.max_depth(library::MAX_DEPTH)
|
||||
.into_iter()
|
||||
.filter_map(Result::ok)
|
||||
{
|
||||
if !entry.file_type().is_file() {
|
||||
continue;
|
||||
}
|
||||
let path = entry.path();
|
||||
let rel_from_source = match path.strip_prefix(dir) {
|
||||
Ok(rel) => rel,
|
||||
Err(_) => continue,
|
||||
};
|
||||
// 跳过隐藏项与 node_modules(与同步排除口径一致)
|
||||
let rel_text = rel_from_source.to_string_lossy().replace('\\', "/");
|
||||
if rel_text
|
||||
.split('/')
|
||||
.any(|part| part.starts_with('.') || part.eq_ignore_ascii_case("node_modules"))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
count += 1;
|
||||
if count > MAX_IMPORT_FILES {
|
||||
return Err(format!("导入文件过多(超过 {MAX_IMPORT_FILES}),请分批导入"));
|
||||
}
|
||||
|
||||
let name = path
|
||||
.file_name()
|
||||
.map(|n| n.to_string_lossy().to_string())
|
||||
.unwrap_or_default();
|
||||
if is_markdown(&name) {
|
||||
// 保持子目录结构
|
||||
let sub = rel_from_source
|
||||
.parent()
|
||||
.map(|p| p.to_string_lossy().replace('\\', "/"))
|
||||
.unwrap_or_default();
|
||||
let target_dir = if sub.is_empty() {
|
||||
dest.to_path_buf()
|
||||
} else {
|
||||
let joined = library::safe_join(root, &relative_to(root, dest, &sub))?;
|
||||
std::fs::create_dir_all(&joined).map_err(|e| format!("创建目录失败: {e}"))?;
|
||||
joined
|
||||
};
|
||||
copy_note(path, &target_dir, &name, report)?;
|
||||
} else if is_asset(&name) {
|
||||
if let Err(e) = import_asset(root, path, &name, report) {
|
||||
push_failure(report, &rel_text, &e);
|
||||
}
|
||||
} else {
|
||||
report.skipped += 1;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 由「库内目标目录 + 源侧子目录」拼出库内相对路径。
|
||||
fn relative_to(root: &Path, dest: &Path, sub: &str) -> String {
|
||||
let prefix = library::rel_string(root, dest);
|
||||
if prefix.is_empty() {
|
||||
sub.to_string()
|
||||
} else {
|
||||
format!("{prefix}/{sub}")
|
||||
}
|
||||
}
|
||||
|
||||
/// 导入 zip 包(保留包内结构)。
|
||||
fn import_zip(
|
||||
root: &Path,
|
||||
file: &Path,
|
||||
dest: &Path,
|
||||
report: &mut ImportReport,
|
||||
) -> Result<(), String> {
|
||||
let handle = std::fs::File::open(file).map_err(|e| format!("打开 zip 失败: {e}"))?;
|
||||
let mut archive = zip::ZipArchive::new(handle).map_err(|e| format!("读取 zip 失败: {e}"))?;
|
||||
let dest_prefix = library::rel_string(root, dest);
|
||||
|
||||
for index in 0..archive.len() {
|
||||
let mut entry = archive
|
||||
.by_index(index)
|
||||
.map_err(|e| format!("读取 zip 条目失败: {e}"))?;
|
||||
// Zip Slip 的第一道防线:`enclosed_name` 拒绝 `..`/绝对路径
|
||||
let Some(inner) = entry.enclosed_name().map(|p| p.to_path_buf()) else {
|
||||
push_failure(report, &format!("条目 #{index}"), "路径越界,已跳过");
|
||||
continue;
|
||||
};
|
||||
if entry.is_dir() {
|
||||
continue;
|
||||
}
|
||||
let rel = inner.to_string_lossy().replace('\\', "/");
|
||||
// macOS 压缩包常见的 `__MACOSX/` 与隐藏文件
|
||||
if rel
|
||||
.split('/')
|
||||
.any(|part| part.starts_with('.') || part.eq_ignore_ascii_case("__MACOSX"))
|
||||
{
|
||||
report.skipped += 1;
|
||||
continue;
|
||||
}
|
||||
let name = inner
|
||||
.file_name()
|
||||
.map(|n| n.to_string_lossy().to_string())
|
||||
.unwrap_or_default();
|
||||
if name.is_empty() {
|
||||
continue;
|
||||
}
|
||||
|
||||
let mut bytes = Vec::new();
|
||||
entry
|
||||
.read_to_end(&mut bytes)
|
||||
.map_err(|e| format!("读取 zip 内容失败: {e}"))?;
|
||||
|
||||
if is_markdown(&name) {
|
||||
let sub = inner
|
||||
.parent()
|
||||
.map(|p| p.to_string_lossy().replace('\\', "/"))
|
||||
.unwrap_or_default();
|
||||
let target_rel = if sub.is_empty() {
|
||||
join_rel(&dest_prefix, &name)
|
||||
} else {
|
||||
join_rel(&dest_prefix, &format!("{sub}/{name}"))
|
||||
};
|
||||
match write_unique(root, &target_rel, &bytes) {
|
||||
Ok(renamed) => {
|
||||
report.imported += 1;
|
||||
if renamed {
|
||||
report.renamed += 1;
|
||||
}
|
||||
}
|
||||
Err(e) => push_failure(report, &rel, &e),
|
||||
}
|
||||
} else if is_asset(&name) {
|
||||
match write_asset_unique(root, &name, &bytes) {
|
||||
Ok(_) => report.imported += 1,
|
||||
Err(e) => push_failure(report, &rel, &e),
|
||||
}
|
||||
} else {
|
||||
report.skipped += 1;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 拷贝一篇 Markdown(重名加序号,**不覆盖**)。
|
||||
fn copy_note(
|
||||
file: &Path,
|
||||
dest_dir: &Path,
|
||||
name: &str,
|
||||
report: &mut ImportReport,
|
||||
) -> Result<(), String> {
|
||||
let bytes = std::fs::read(file).map_err(|e| format!("读取 {name} 失败: {e}"))?;
|
||||
// 目标目录已在库内,这里直接构造候选名并落盘(仍走 safe_join 的等价校验)
|
||||
let mut candidate = name.to_string();
|
||||
let mut index = 1;
|
||||
while dest_dir.join(&candidate).exists() {
|
||||
candidate = numbered(name, index);
|
||||
index += 1;
|
||||
if index > 9999 {
|
||||
return Err("同名文件过多".to_string());
|
||||
}
|
||||
}
|
||||
let renamed = candidate != name;
|
||||
std::fs::write(dest_dir.join(&candidate), &bytes).map_err(|e| format!("写入 {candidate} 失败: {e}"))?;
|
||||
report.imported += 1;
|
||||
if renamed {
|
||||
report.renamed += 1;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 把附件写进库根 `assets/`(重名加序号)。
|
||||
fn import_asset(
|
||||
root: &Path,
|
||||
file: &Path,
|
||||
name: &str,
|
||||
report: &mut ImportReport,
|
||||
) -> Result<(), String> {
|
||||
let bytes = std::fs::read(file).map_err(|e| format!("读取 {name} 失败: {e}"))?;
|
||||
write_asset_unique(root, name, &bytes)?;
|
||||
report.imported += 1;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 写入 `assets/`(重名加序号)。
|
||||
fn write_asset_unique(root: &Path, name: &str, bytes: &[u8]) -> Result<String, String> {
|
||||
let assets = root.join(library::ASSETS_DIR);
|
||||
std::fs::create_dir_all(&assets).map_err(|e| format!("创建附件目录失败: {e}"))?;
|
||||
let safe = library::validate_name(name)?;
|
||||
let mut candidate = safe.clone();
|
||||
let mut index = 1;
|
||||
while assets.join(&candidate).exists() {
|
||||
candidate = numbered(&safe, index);
|
||||
index += 1;
|
||||
if index > 9999 {
|
||||
return Err("同名附件过多".to_string());
|
||||
}
|
||||
}
|
||||
std::fs::write(assets.join(&candidate), bytes).map_err(|e| format!("写入附件失败: {e}"))?;
|
||||
Ok(candidate)
|
||||
}
|
||||
|
||||
/// 按库内相对路径写入(重名加序号),返回是否被改名。
|
||||
fn write_unique(root: &Path, rel: &str, bytes: &[u8]) -> Result<bool, String> {
|
||||
let target = library::safe_join(root, rel)?;
|
||||
if let Some(parent) = target.parent() {
|
||||
std::fs::create_dir_all(parent).map_err(|e| format!("创建目录失败: {e}"))?;
|
||||
}
|
||||
let name = target
|
||||
.file_name()
|
||||
.map(|n| n.to_string_lossy().to_string())
|
||||
.unwrap_or_default();
|
||||
let mut candidate = name.clone();
|
||||
let mut index = 1;
|
||||
let mut renamed = false;
|
||||
while target.parent().map(|p| p.join(&candidate).exists()).unwrap_or(false) {
|
||||
candidate = numbered(&name, index);
|
||||
index += 1;
|
||||
renamed = true;
|
||||
if index > 9999 {
|
||||
return Err("同名文件过多".to_string());
|
||||
}
|
||||
}
|
||||
let final_path = match target.parent() {
|
||||
Some(parent) => parent.join(&candidate),
|
||||
None => target.clone(),
|
||||
};
|
||||
std::fs::write(&final_path, bytes).map_err(|e| format!("写入 {candidate} 失败: {e}"))?;
|
||||
Ok(renamed)
|
||||
}
|
||||
|
||||
/// 拼相对路径(空前缀时不带斜杠)。
|
||||
fn join_rel(prefix: &str, name: &str) -> String {
|
||||
if prefix.is_empty() {
|
||||
name.to_string()
|
||||
} else {
|
||||
format!("{prefix}/{name}")
|
||||
}
|
||||
}
|
||||
|
||||
/// `笔记.md` → `笔记 2.md`
|
||||
fn numbered(name: &str, index: u32) -> String {
|
||||
match name.rfind('.') {
|
||||
Some(dot) => format!("{} {}{}", &name[..dot], index + 1, &name[dot..]),
|
||||
None => format!("{name} {}", index + 1),
|
||||
}
|
||||
}
|
||||
|
||||
fn is_markdown(name: &str) -> bool {
|
||||
name.to_ascii_lowercase().ends_with(".md")
|
||||
|| name.to_ascii_lowercase().ends_with(".markdown")
|
||||
}
|
||||
|
||||
/// 附件类型的白名单(图片、PDF、压缩包以外的常见附件)。
|
||||
///
|
||||
/// 用白名单而不是「非 md 即附件」:导入一个目录时往往会混进 `.DS_Store`、
|
||||
/// `Thumbs.db`、`.gitignore` 之类;把它们全塞进 `assets/` 只会制造垃圾。
|
||||
fn is_asset(name: &str) -> bool {
|
||||
const EXT: &[&str] = &[
|
||||
"png", "jpg", "jpeg", "gif", "webp", "svg", "bmp", "avif", "pdf", "mp3", "wav", "mp4",
|
||||
"webm", "zip",
|
||||
];
|
||||
match name.rsplit('.').next() {
|
||||
Some(ext) => EXT.contains(&ext.to_ascii_lowercase().as_str()),
|
||||
None => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn push_failure(report: &mut ImportReport, name: &str, error: &str) {
|
||||
if report.failures.len() < 20 {
|
||||
report.failures.push(format!("{name}:{error}"));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn temp_lib(tag: &str) -> PathBuf {
|
||||
let root = std::env::temp_dir().join(format!("thing-notes-import-{tag}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
std::fs::create_dir_all(root.join("assets")).unwrap();
|
||||
root
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn import_single_file_renames_instead_of_overwriting() {
|
||||
let root = temp_lib("single");
|
||||
let src_dir = std::env::temp_dir().join(format!("thing-notes-src-single-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&src_dir);
|
||||
std::fs::create_dir_all(&src_dir).unwrap();
|
||||
std::fs::write(src_dir.join("a.md"), "导入的内容").unwrap();
|
||||
// 库内已有一篇同名
|
||||
std::fs::write(root.join("a.md"), "库里原有的").unwrap();
|
||||
|
||||
let report = import_path(&root, &src_dir.join("a.md").to_string_lossy(), "").unwrap();
|
||||
assert_eq!(report.imported, 1);
|
||||
assert_eq!(report.renamed, 1);
|
||||
// 原有内容必须没被覆盖
|
||||
assert_eq!(std::fs::read_to_string(root.join("a.md")).unwrap(), "库里原有的");
|
||||
assert_eq!(std::fs::read_to_string(root.join("a 2.md")).unwrap(), "导入的内容");
|
||||
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
let _ = std::fs::remove_dir_all(&src_dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn import_directory_keeps_structure_and_skips_junk() {
|
||||
let root = temp_lib("dir");
|
||||
let src = std::env::temp_dir().join(format!("thing-notes-src-dir-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&src);
|
||||
std::fs::create_dir_all(src.join("sub")).unwrap();
|
||||
std::fs::create_dir_all(src.join(".git")).unwrap();
|
||||
std::fs::write(src.join("top.md"), "top").unwrap();
|
||||
std::fs::write(src.join("sub/deep.md"), "deep").unwrap();
|
||||
std::fs::write(src.join("sub/note.txt"), "不是 md").unwrap();
|
||||
std::fs::write(src.join(".git/config"), "不该导入").unwrap();
|
||||
std::fs::write(src.join("pic.png"), [1u8, 2, 3]).unwrap();
|
||||
|
||||
let report = import_path(&root, &src.to_string_lossy(), "导入").unwrap();
|
||||
assert_eq!(report.imported, 3, "两篇 md + 一张图片: {report:?}");
|
||||
assert_eq!(report.skipped, 1, "note.txt 应被跳过: {report:?}");
|
||||
assert!(root.join("导入/top.md").is_file());
|
||||
assert!(root.join("导入/sub/deep.md").is_file(), "应保留子目录结构");
|
||||
assert!(root.join("assets/pic.png").is_file());
|
||||
assert!(!root.join("导入/.git").exists());
|
||||
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
let _ = std::fs::remove_dir_all(&src);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn import_zip_keeps_structure_and_rejects_traversal() {
|
||||
let root = temp_lib("zip");
|
||||
let zip_path = std::env::temp_dir().join(format!("thing-notes-src-{}.zip", std::process::id()));
|
||||
{
|
||||
let file = std::fs::File::create(&zip_path).unwrap();
|
||||
let mut writer = zip::ZipWriter::new(file);
|
||||
let options: zip::write::FileOptions<'_, ()> = zip::write::FileOptions::default();
|
||||
writer.start_file("notes/a.md", options).unwrap();
|
||||
writer.write_all(b"# A").unwrap();
|
||||
// 恶意条目:逃出库根
|
||||
writer.start_file("../escape.md", options).unwrap();
|
||||
writer.write_all("坏".as_bytes()).unwrap();
|
||||
writer.start_file("__MACOSX/x.md", options).unwrap();
|
||||
writer.write_all(b"mac").unwrap();
|
||||
writer.finish().unwrap();
|
||||
}
|
||||
|
||||
let report = import_path(&root, &zip_path.to_string_lossy(), "").unwrap();
|
||||
assert_eq!(report.imported, 1, "{report:?}");
|
||||
assert!(root.join("notes/a.md").is_file());
|
||||
// `enclosed_name()` 会把 `../escape.md` 归一化成 `escape.md`(去掉了越界前缀),
|
||||
// 关键是**没有写到库根之外**
|
||||
let parent = root.parent().unwrap();
|
||||
assert!(!parent.join("escape.md").exists(), "不能写到库根之外");
|
||||
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
let _ = std::fs::remove_file(&zip_path);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn numbered_names_keep_extension() {
|
||||
assert_eq!(numbered("a.md", 1), "a 2.md");
|
||||
assert_eq!(numbered("无扩展名", 0), "无扩展名 1");
|
||||
assert_eq!(numbered("a.b.md", 2), "a.b 3.md");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn asset_whitelist_rejects_junk() {
|
||||
assert!(is_asset("pic.png"));
|
||||
assert!(is_asset("PIC.PNG"));
|
||||
assert!(is_asset("doc.pdf"));
|
||||
assert!(!is_asset("Thumbs.db"));
|
||||
assert!(!is_asset(".DS_Store"));
|
||||
assert!(!is_asset("noext"));
|
||||
}}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,592 @@
|
||||
//! 索引服务:单线程 worker + notify 文件监听。
|
||||
//!
|
||||
//! # 为什么索引必须由一个线程独占
|
||||
//!
|
||||
//! `rusqlite::Connection` 不是 `Sync` 的共享对象,而本模块有三个**并发**入口:
|
||||
//! ① 前端的搜索/统计命令(Tauri 命令线程池,可能同时进来好几个);
|
||||
//! ② 保存笔记后的增量更新;③ 文件监听器(notify 自己的回调线程)。
|
||||
//!
|
||||
//! 三种做法各有代价:给连接套 `Mutex` 会让「全库重建索引」这类慢操作**堵住搜索**
|
||||
//! (UI 直接卡住);每次操作现开一个连接则丢失 prepared statement 缓存,还会在
|
||||
//! WAL 上堆出一串写锁竞争。这里选第三条:**一个专职线程独占连接**,所有操作通过
|
||||
//! 消息通道排队进来。慢操作只排队、不阻塞调用方(命令层是异步等待回复),
|
||||
//! 连接始终只有一个,顺序天然可预期。
|
||||
//!
|
||||
//! # 监听器为什么也挂在这个线程上
|
||||
//!
|
||||
//! `notify` 的事件要落到索引上(外部新增/改动文件后立刻可搜),而**只有这个线程
|
||||
//! 能写索引**。让监听回调投递一条 `SyncPath` 消息给 worker,就地把那一个文件同步掉,
|
||||
//! 比「回调里发前端事件 → 前端再调一次同步命令」少一次往返,也不会因为前端窗口
|
||||
//! 关着而漏掉索引更新。
|
||||
//!
|
||||
//! 自我保存识别([`SUPPRESS_MS`])是必须的:编辑器每次自动保存都会触发
|
||||
//! `Modify(Data)`,若把这类事件也当成「外部修改」,前端就会在用户自己打字时反复
|
||||
//! 重载文档 / 弹提示。识别按**库内相对路径**在写入前登记(见 `mark_write_path`),
|
||||
//! 结果写进事件的 `from_app`,由前端决定是否提示 —— 而不是在这里静默丢弃事件。
|
||||
//! 静默丢弃一旦因时序漏判,前端就会把自家的保存当成外部改动而重载。
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::mpsc::{self, Receiver, Sender};
|
||||
use std::sync::Mutex;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use notify::{EventKind, RecommendedWatcher, RecursiveMode, Watcher};
|
||||
use serde::Serialize;
|
||||
use specta::Type;
|
||||
use tauri::{AppHandle, Emitter};
|
||||
|
||||
use super::files;
|
||||
use super::index::{content_hash, NoteIndexStats, NoteSearchHit, NoteSearchPage, NoteSearchQuery, NoteSyncReport, EditorIndex};
|
||||
use super::library;
|
||||
use crate::constants::events;
|
||||
|
||||
/// 自我写入(自己刚保存)与外部改动之间的**去重窗口**。
|
||||
///
|
||||
/// 取 1200ms:一次写入可能被 notify 拆成多条事件(`Modify(Data)` 常伴一条元数据事件),
|
||||
/// 命中的第一条之后,这段时间内的同路径事件一并算作「自己写的」,既不重复处理,
|
||||
/// 又不会把窗口拉得太长去吞掉用户紧接着在外部编辑器里的另一次保存。
|
||||
const SUPPRESS_MS: u64 = 1200;
|
||||
|
||||
/// 自我写入登记在「尚未被任何文件事件命中」时的最长存活时间。
|
||||
///
|
||||
/// 比去重窗口宽得多:notify 的派发延迟可能到秒级,窗口太窄会把「自己刚写的」误判成
|
||||
/// 外部修改(重载文档、光标弹回第一行)—— 这正是要避免的事故。登记项一旦被**第一个**
|
||||
/// 匹配事件消费,就只保留 [`SUPPRESS_MS`] 的去重窗口,不会长期吞掉真正的外部改动。
|
||||
const SELF_WRITE_TTL_MS: u64 = 30_000;
|
||||
|
||||
/// 单个文件事件的去抖说明。
|
||||
///
|
||||
/// worker 是「来一条处理一条」,去抖由三层共同承担:notify 自身的派发合并、
|
||||
/// 前端 `editor-library-changed` 的 400ms 防抖、以及自我保存抑制窗口。
|
||||
/// 之所以不在这里再加一个定时器:多一层延迟就多一个「事件丢了谁负责」的疑问,
|
||||
/// 而下游每一层都是幂等的(重复同步同一个文件只是重算一次 hash)。
|
||||
const _DEBOUNCE_NOTE_MS: u64 = 250;
|
||||
|
||||
/// 库文件变化的分类(前端据此决定「重载当前笔记」还是「只刷新树」)。
|
||||
///
|
||||
/// 只有 `removed` 是确定事实(文件不在了);「新建」与「修改」在单文件事件层面
|
||||
/// **无法区分**(notify 给的 `Create` 与 `Modify` 在一次保存里会同时出现),
|
||||
/// 因此统一报 [`CHANGE_MODIFIED`],由前端按「路径在不在当前树里」自行判断。
|
||||
pub const CHANGE_MODIFIED: &str = "modified";
|
||||
pub const CHANGE_REMOVED: &str = "removed";
|
||||
|
||||
/// 广播给各窗口的库文件变化事件。
|
||||
#[derive(Debug, Clone, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct NoteFileEvent {
|
||||
/// 相对库根的路径(`/` 分隔)
|
||||
pub rel_path: String,
|
||||
/// 磁盘上的绝对路径。
|
||||
///
|
||||
/// 前端需要它来判断「这个事件说的是不是我正在编辑的那个库外文件」——
|
||||
/// 相对库根路径对库外文件没有意义(它根本不在库里),只留 `rel_path`
|
||||
/// 会让「打开 D:\x\a.md 时有人在别处改了它」永远匹配不上。
|
||||
pub abs_path: String,
|
||||
/// "modified" | "removed"
|
||||
pub kind: String,
|
||||
/// 事件发生时间(Unix 毫秒)
|
||||
pub at: u64,
|
||||
/// 是否是本应用自己写入造成的(前端据此跳过「外部修改」提示)
|
||||
pub from_app: bool,
|
||||
}
|
||||
|
||||
/// 一次索引同步的结果(命令返回值)。
|
||||
#[derive(Debug, Clone, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct NoteIndexReport {
|
||||
pub indexed: i64,
|
||||
pub removed: i64,
|
||||
pub skipped: i64,
|
||||
/// 同步后索引里的笔记数(前端直接显示,省一次统计往返)
|
||||
pub note_count: i64,
|
||||
}
|
||||
|
||||
impl From<NoteSyncReport> for NoteIndexReport {
|
||||
fn from(report: NoteSyncReport) -> Self {
|
||||
Self {
|
||||
indexed: report.indexed,
|
||||
removed: report.removed,
|
||||
skipped: report.skipped,
|
||||
note_count: 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// worker 请求。
|
||||
enum Request {
|
||||
/// 增量同步整个库
|
||||
Sync(Sender<Result<NoteSyncReport, String>>),
|
||||
/// 全量重建
|
||||
Rebuild(Sender<Result<NoteSyncReport, String>>),
|
||||
/// 同步单个文件(监听器投递;文件不存在则从索引移除)
|
||||
SyncPath(PathBuf),
|
||||
/// 全文检索
|
||||
Search(NoteSearchQuery, Sender<Result<NoteSearchPage, String>>),
|
||||
/// 快速打开清单
|
||||
List(i64, Sender<Result<Vec<NoteSearchHit>, String>>),
|
||||
/// 标签清单
|
||||
Tags(Sender<Result<Vec<super::index::NoteTagCount>, String>>),
|
||||
/// 一篇笔记的出链 / 入链
|
||||
Backlinks(String, Sender<Result<super::index::NoteBacklinks, String>>),
|
||||
/// 全库链接图
|
||||
LinkGraph(Sender<Result<Vec<(String, String)>, String>>),
|
||||
/// 索引状态
|
||||
Stats(Sender<Result<NoteIndexStats, String>>),
|
||||
/// 重建监听器(库根变化后)
|
||||
Retarget(PathBuf, Sender<Result<(), String>>),
|
||||
}
|
||||
|
||||
/// 一条「本应用自己写入」的登记。
|
||||
struct SelfWrite {
|
||||
/// 库内相对路径(`/` 分隔,与 [`library::rel_string`] 的输出一致)
|
||||
rel: String,
|
||||
/// 登记时刻(写入之前,见 [`IndexService::mark_write_path`])
|
||||
marked: Instant,
|
||||
/// 首次被文件事件命中的时刻(`None` = 还没等到它的事件)
|
||||
matched: Option<Instant>,
|
||||
}
|
||||
|
||||
/// 丢弃过期的自我写入登记。
|
||||
///
|
||||
/// - **已命中**:保留 [`SUPPRESS_MS`] —— 覆盖同一次写入产生的重复事件。
|
||||
/// - **未命中**:保留 [`SELF_WRITE_TTL_MS`] —— 等它的文件事件到达(notify 延迟可能到秒级)。
|
||||
fn prune_self_writes(paths: &mut Vec<SelfWrite>) {
|
||||
let dedupe = Duration::from_millis(SUPPRESS_MS);
|
||||
let wait = Duration::from_millis(SELF_WRITE_TTL_MS);
|
||||
paths.retain(|entry| match entry.matched {
|
||||
Some(at) => at.elapsed() < dedupe,
|
||||
None => entry.marked.elapsed() < wait,
|
||||
});
|
||||
}
|
||||
|
||||
/// 索引服务的句柄(命令层只拿到这个)。
|
||||
pub struct IndexService {
|
||||
tx: Sender<Request>,
|
||||
/// 批量自我写入的时间点(导入 / WebDAV 同步 / 恢复 / 模板导出这类无法逐路径枚举的操作)。
|
||||
/// 窗口内的一切文件事件都当作「自己写的」,不向前端提示外部修改。
|
||||
bulk_write: Mutex<Option<Instant>>,
|
||||
/// 单个文件的自我写入登记。
|
||||
/// 比批量窗口精确:保存 A 不会再顺带吞掉 B 的外部改动事件。
|
||||
write_paths: Mutex<Vec<SelfWrite>>,
|
||||
}
|
||||
|
||||
static SERVICE: std::sync::OnceLock<IndexService> = std::sync::OnceLock::new();
|
||||
|
||||
/// 取索引服务(首次调用时启动 worker 线程与监听器)。
|
||||
pub fn service(app: &AppHandle) -> &'static IndexService {
|
||||
SERVICE.get_or_init(|| IndexService::start(app.clone()))
|
||||
}
|
||||
|
||||
impl IndexService {
|
||||
fn start(app: AppHandle) -> Self {
|
||||
let (tx, rx) = mpsc::channel::<Request>();
|
||||
let handle_tx = tx.clone();
|
||||
std::thread::Builder::new()
|
||||
.name("editor-index".to_string())
|
||||
.spawn(move || worker_loop(app, rx, handle_tx))
|
||||
.expect("启动笔记索引线程失败");
|
||||
Self {
|
||||
tx,
|
||||
bulk_write: Mutex::new(None),
|
||||
write_paths: Mutex::new(Vec::new()),
|
||||
}
|
||||
}
|
||||
|
||||
/// 标记「刚刚由本应用**批量**写入了文件」(导入 / 同步 / 恢复 / 模板导出)。
|
||||
/// 这类操作无法逐路径枚举,窗口内一律视为自我写入。
|
||||
pub fn mark_write_all(&self) {
|
||||
if let Ok(mut slot) = self.bulk_write.lock() {
|
||||
*slot = Some(Instant::now());
|
||||
}
|
||||
}
|
||||
|
||||
/// 登记「本应用即将写入这个库内相对路径」。
|
||||
///
|
||||
/// **必须在真正的 `fs::write` 之前调用**:notify 的 Modify 事件可能与写入几乎同时
|
||||
/// 到达 worker,若等写盘回来再登记,事件可能已经被处理并误判为「外部修改」。
|
||||
pub fn mark_write_path(&self, rel: &str) {
|
||||
if rel.is_empty() {
|
||||
return;
|
||||
}
|
||||
if let Ok(mut paths) = self.write_paths.lock() {
|
||||
prune_self_writes(&mut paths);
|
||||
paths.push(SelfWrite {
|
||||
rel: rel.to_string(),
|
||||
marked: Instant::now(),
|
||||
matched: None,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// 这个库内相对路径是不是「本应用自己刚写的」。
|
||||
///
|
||||
/// 命中**一次就算消费**:优先匹配还没命中过的登记(一次写入对应一次命中),
|
||||
/// 找不到才回退到刚命中过的(覆盖同一次写入的重复事件)。这样即便 notify 延迟到
|
||||
/// 秒级,登记项仍在(见 [`SELF_WRITE_TTL_MS`]),不会把自家的保存误判成外部修改。
|
||||
fn recently_written(&self, rel: &str) -> bool {
|
||||
let bulk = self
|
||||
.bulk_write
|
||||
.lock()
|
||||
.ok()
|
||||
.and_then(|slot| *slot)
|
||||
.map(|at| at.elapsed() < Duration::from_millis(SUPPRESS_MS))
|
||||
.unwrap_or(false);
|
||||
if bulk {
|
||||
return true;
|
||||
}
|
||||
let Ok(mut paths) = self.write_paths.lock() else {
|
||||
return false;
|
||||
};
|
||||
prune_self_writes(&mut paths);
|
||||
let index = paths
|
||||
.iter()
|
||||
.position(|entry| entry.rel == rel && entry.matched.is_none())
|
||||
.or_else(|| paths.iter().position(|entry| entry.rel == rel));
|
||||
let Some(index) = index else {
|
||||
return false;
|
||||
};
|
||||
let entry = &mut paths[index];
|
||||
entry.matched.get_or_insert_with(Instant::now);
|
||||
true
|
||||
}
|
||||
|
||||
/// 增量同步整个库。
|
||||
pub fn sync(&self) -> Result<NoteSyncReport, String> {
|
||||
let (tx, rx) = mpsc::channel();
|
||||
self.tx
|
||||
.send(Request::Sync(tx))
|
||||
.map_err(|_| "索引服务已停止".to_string())?;
|
||||
rx.recv().map_err(|_| "索引服务无响应".to_string())?
|
||||
}
|
||||
|
||||
/// 全量重建索引。
|
||||
pub fn rebuild(&self) -> Result<NoteSyncReport, String> {
|
||||
let (tx, rx) = mpsc::channel();
|
||||
self.tx
|
||||
.send(Request::Rebuild(tx))
|
||||
.map_err(|_| "索引服务已停止".to_string())?;
|
||||
rx.recv().map_err(|_| "索引服务无响应".to_string())?
|
||||
}
|
||||
|
||||
/// 全文检索。
|
||||
pub fn search(&self, query: NoteSearchQuery) -> Result<NoteSearchPage, String> {
|
||||
let (tx, rx) = mpsc::channel();
|
||||
self.tx
|
||||
.send(Request::Search(query, tx))
|
||||
.map_err(|_| "索引服务已停止".to_string())?;
|
||||
rx.recv().map_err(|_| "索引服务无响应".to_string())?
|
||||
}
|
||||
|
||||
/// 快速打开清单。
|
||||
pub fn list(&self, limit: i64) -> Result<Vec<NoteSearchHit>, String> {
|
||||
let (tx, rx) = mpsc::channel();
|
||||
self.tx
|
||||
.send(Request::List(limit, tx))
|
||||
.map_err(|_| "索引服务已停止".to_string())?;
|
||||
rx.recv().map_err(|_| "索引服务无响应".to_string())?
|
||||
}
|
||||
|
||||
/// 标签清单。
|
||||
pub fn tags(&self) -> Result<Vec<super::index::NoteTagCount>, String> {
|
||||
let (tx, rx) = mpsc::channel();
|
||||
self.tx
|
||||
.send(Request::Tags(tx))
|
||||
.map_err(|_| "索引服务已停止".to_string())?;
|
||||
rx.recv().map_err(|_| "索引服务无响应".to_string())?
|
||||
}
|
||||
|
||||
/// 索引状态。
|
||||
pub fn stats(&self) -> Result<NoteIndexStats, String> {
|
||||
let (tx, rx) = mpsc::channel();
|
||||
self.tx
|
||||
.send(Request::Stats(tx))
|
||||
.map_err(|_| "索引服务已停止".to_string())?;
|
||||
rx.recv().map_err(|_| "索引服务无响应".to_string())?
|
||||
}
|
||||
|
||||
/// 一篇笔记的出链 / 入链。
|
||||
pub fn backlinks(&self, rel_path: &str) -> Result<super::index::NoteBacklinks, String> {
|
||||
let (tx, rx) = mpsc::channel();
|
||||
self.tx
|
||||
.send(Request::Backlinks(rel_path.to_string(), tx))
|
||||
.map_err(|_| "索引服务已停止".to_string())?;
|
||||
rx.recv().map_err(|_| "索引服务无响应".to_string())?
|
||||
}
|
||||
|
||||
/// 全库链接图(已解析的内部链接边)。
|
||||
pub fn link_graph(&self) -> Result<Vec<(String, String)>, String> {
|
||||
let (tx, rx) = mpsc::channel();
|
||||
self.tx
|
||||
.send(Request::LinkGraph(tx))
|
||||
.map_err(|_| "索引服务已停止".to_string())?;
|
||||
rx.recv().map_err(|_| "索引服务无响应".to_string())?
|
||||
}
|
||||
|
||||
/// 切换库根(重新打开索引 + 重建监听器)。
|
||||
pub fn retarget(&self, root: PathBuf) -> Result<(), String> {
|
||||
let (tx, rx) = mpsc::channel();
|
||||
self.tx
|
||||
.send(Request::Retarget(root, tx))
|
||||
.map_err(|_| "索引服务已停止".to_string())?;
|
||||
rx.recv().map_err(|_| "索引服务无响应".to_string())?
|
||||
}
|
||||
}
|
||||
|
||||
/// worker 主循环:独占 [`EditorIndex`],串行处理所有请求。
|
||||
fn worker_loop(app: AppHandle, rx: Receiver<Request>, handle_tx: Sender<Request>) {
|
||||
let mut index: Option<EditorIndex> = None;
|
||||
let mut watcher: Option<RecommendedWatcher> = None;
|
||||
let mut watched_root: Option<PathBuf> = None;
|
||||
let mut root: Option<PathBuf> = None;
|
||||
|
||||
while let Ok(request) = rx.recv() {
|
||||
match request {
|
||||
Request::Sync(reply) => {
|
||||
let _ = reply.send(with_index(&app, &mut index, &mut root, |idx| idx.sync()));
|
||||
}
|
||||
Request::Rebuild(reply) => {
|
||||
let _ = reply.send(with_index(&app, &mut index, &mut root, |idx| idx.rebuild()));
|
||||
}
|
||||
Request::Search(query, reply) => {
|
||||
let _ = reply.send(with_index(&app, &mut index, &mut root, |idx| idx.search(query)));
|
||||
}
|
||||
Request::List(limit, reply) => {
|
||||
let _ = reply.send(with_index(&app, &mut index, &mut root, |idx| idx.list_notes(limit)));
|
||||
}
|
||||
Request::Tags(reply) => {
|
||||
let _ = reply.send(with_index(&app, &mut index, &mut root, |idx| idx.tags()));
|
||||
}
|
||||
Request::Backlinks(rel_path, reply) => {
|
||||
let _ = reply.send(with_index(&app, &mut index, &mut root, |idx| {
|
||||
idx.backlinks(&rel_path)
|
||||
}));
|
||||
}
|
||||
Request::LinkGraph(reply) => {
|
||||
let _ = reply.send(with_index(&app, &mut index, &mut root, |idx| idx.link_graph()));
|
||||
}
|
||||
Request::Stats(reply) => {
|
||||
let _ = reply.send(with_index(&app, &mut index, &mut root, |idx| idx.stats()));
|
||||
}
|
||||
Request::Retarget(next, reply) => {
|
||||
// 库根未变:直接返回,不重开索引、不重建监听器。
|
||||
// 早期实现每次都 `index = None` + 重挂 watcher,于是**每次自动保存**都要重开
|
||||
// SQLite 连接、重建 notify 监听,既慢,又让「写入 → 事件」挤进这段重建窗口,
|
||||
// 制造出「自己保存却被当成外部修改」的竞态。
|
||||
if root.as_deref() == Some(next.as_path()) {
|
||||
let _ = reply.send(Ok(()));
|
||||
continue;
|
||||
}
|
||||
// 库根切换:丢掉旧索引实例,下次操作按新库根重新打开
|
||||
index = None;
|
||||
root = Some(next.clone());
|
||||
let result = match ensure_index(&app, &mut index, &next) {
|
||||
Ok(_) => {
|
||||
watched_root = None; // 触发重建监听器
|
||||
Ok(())
|
||||
}
|
||||
Err(e) => Err(e),
|
||||
};
|
||||
let _ = reply.send(result);
|
||||
// 新库的监听器要在回复之后建:先让前端拿到「已切换」的结果
|
||||
ensure_watcher(&mut watcher, &mut watched_root, &next, &handle_tx);
|
||||
}
|
||||
Request::SyncPath(path) => {
|
||||
if let Some(current) = root.clone() {
|
||||
// 索引尚未建立时先建(首次操作前就被外部改动的情况)
|
||||
if index.is_none() {
|
||||
if let Err(e) = ensure_index(&app, &mut index, ¤t) {
|
||||
crate::logger::log_warn("editor", &format!("索引不可用: {e}"));
|
||||
continue;
|
||||
}
|
||||
}
|
||||
ensure_watcher(&mut watcher, &mut watched_root, ¤t, &handle_tx);
|
||||
sync_one(&app, index.as_mut(), ¤t, &path);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 借出索引(必要时按 `root` 打开),并把结果映射成 `Result<_, String>`。
|
||||
fn with_index<T>(
|
||||
app: &AppHandle,
|
||||
index: &mut Option<EditorIndex>,
|
||||
root: &mut Option<PathBuf>,
|
||||
run: impl FnOnce(&mut EditorIndex) -> Result<T, String>,
|
||||
) -> Result<T, String> {
|
||||
let Some(current) = root.clone() else {
|
||||
// 不在这里猜库根:命令层每次操作前都会 `retarget` 到当前库根,
|
||||
// 猜错的后果是索引挂到别的目录上(用户切过库时尤其明显)。
|
||||
return Err("索引尚未指向任何笔记库(请先打开笔记窗口)".to_string());
|
||||
};
|
||||
ensure_index(app, index, ¤t)?;
|
||||
match index.as_mut() {
|
||||
Some(idx) => run(idx),
|
||||
None => Err("索引未就绪".to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
/// 确保索引实例存在且指向 `root`(不匹配则重新打开)。
|
||||
fn ensure_index(app: &AppHandle, index: &mut Option<EditorIndex>, root: &Path) -> Result<(), String> {
|
||||
if let Some(existing) = index.as_ref() {
|
||||
if existing.root() == root {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
if let Err(e) = library::ensure_library(root) {
|
||||
crate::logger::log_warn("editor", &e);
|
||||
}
|
||||
let opened = EditorIndex::open(root)?;
|
||||
crate::logger::log_info(
|
||||
"editor",
|
||||
&format!("索引已就绪: {}", opened.db_path().display()),
|
||||
);
|
||||
// 首次打开时不自动全量同步:库可能很大,交给命令层(打开编辑器 / 重建索引时)触发
|
||||
let _ = app;
|
||||
*index = Some(opened);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 确保监听器挂在 `root` 上。
|
||||
fn ensure_watcher(
|
||||
watcher: &mut Option<RecommendedWatcher>,
|
||||
watched_root: &mut Option<PathBuf>,
|
||||
root: &Path,
|
||||
tx: &Sender<Request>,
|
||||
) {
|
||||
if let Err(e) = ensure_watcher_inner(watcher, watched_root, root, tx) {
|
||||
crate::logger::log_warn("editor", &e);
|
||||
}
|
||||
}
|
||||
|
||||
/// 建/换监听器(`root` 未变则不动)。
|
||||
fn ensure_watcher_inner(
|
||||
watcher: &mut Option<RecommendedWatcher>,
|
||||
watched_root: &mut Option<PathBuf>,
|
||||
root: &Path,
|
||||
tx: &Sender<Request>,
|
||||
) -> Result<(), String> {
|
||||
if watched_root.as_deref() == Some(root) && watcher.is_some() {
|
||||
return Ok(());
|
||||
}
|
||||
let sender = tx.clone();
|
||||
let mut next = notify::recommended_watcher(move |event: notify::Result<notify::Event>| {
|
||||
let Ok(event) = event else { return };
|
||||
for path in event_paths(&event) {
|
||||
let _ = sender.send(Request::SyncPath(path));
|
||||
}
|
||||
})
|
||||
.map_err(|e| format!("创建库监听器失败: {e}"))?;
|
||||
|
||||
next.watch(root, RecursiveMode::Recursive)
|
||||
.map_err(|e| format!("监听笔记库失败: {e}"))?;
|
||||
|
||||
// 替换旧监听器(drop 即 unwatch)
|
||||
*watcher = Some(next);
|
||||
*watched_root = Some(root.to_path_buf());
|
||||
crate::logger::log_info("editor", &format!("库监听已启动: {}", root.display()));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 从 notify 事件里取出「值得同步」的路径(只关心 .md,且忽略 `.editor/` 自身)。
|
||||
///
|
||||
/// 重命名会给出两个路径(旧、新),这里都收下:旧路径在同步时会发现「文件不存在」
|
||||
/// 而被当作删除处理,新路径自然成为新增 —— 无需专门分辨 RenameMode。
|
||||
fn event_paths(event: ¬ify::Event) -> Vec<PathBuf> {
|
||||
if matches!(event.kind, EventKind::Access(_) | EventKind::Other) {
|
||||
return Vec::new();
|
||||
}
|
||||
event
|
||||
.paths
|
||||
.iter()
|
||||
.filter(|p| {
|
||||
let name = p.file_name().map(|n| n.to_string_lossy().to_string());
|
||||
// 只跟踪 .md 与目录事件(目录事件用于捕捉「整目录移入」)
|
||||
let is_md = name
|
||||
.as_deref()
|
||||
.map(|n| n.to_ascii_lowercase().ends_with(".md"))
|
||||
.unwrap_or(false);
|
||||
let is_meta = p
|
||||
.components()
|
||||
.any(|c| c.as_os_str().to_string_lossy().starts_with('.'));
|
||||
is_md && !is_meta
|
||||
})
|
||||
.cloned()
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// 就地同步单个文件(含自我保存抑制与前端事件广播)。
|
||||
///
|
||||
/// 事件是否「本应用自己写的」按**库内相对路径**判定(见 [`IndexService::mark_write_path`]),
|
||||
/// 而不是一个全局时间窗 —— 全局窗会把「保存 A 之后 1.2s 内 B 被外部改动」也一并吞掉。
|
||||
fn sync_one(app: &AppHandle, index: Option<&mut EditorIndex>, root: &Path, path: &Path) {
|
||||
let Some(index) = index else { return };
|
||||
let rel = library::rel_string(root, path);
|
||||
if rel.is_empty() || rel.starts_with('.') || rel.starts_with("assets/") {
|
||||
return;
|
||||
}
|
||||
|
||||
// 自我保存抑制:只影响「是否提示用户」,索引照常更新
|
||||
let self_write = SERVICE
|
||||
.get()
|
||||
.map(|service| service.recently_written(&rel))
|
||||
.unwrap_or(false);
|
||||
|
||||
let kind = if path.is_file() {
|
||||
if let Ok(bytes) = std::fs::read(path) {
|
||||
let content = String::from_utf8_lossy(&bytes);
|
||||
let meta = std::fs::metadata(path).ok();
|
||||
let mtime = meta
|
||||
.as_ref()
|
||||
.and_then(|m| m.modified().ok())
|
||||
.and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
|
||||
.map(|d| d.as_millis() as u64)
|
||||
.unwrap_or(0);
|
||||
let stems = std::collections::HashMap::new();
|
||||
if let Err(e) = index.upsert_note(
|
||||
&rel,
|
||||
&content,
|
||||
mtime,
|
||||
meta.as_ref().map(|m| m.len()).unwrap_or(0),
|
||||
&content_hash(&bytes),
|
||||
&stems,
|
||||
) {
|
||||
crate::logger::log_warn("editor", &format!("增量索引 {rel} 失败: {e}"));
|
||||
}
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
// 无法分辨「新建」与「修改」时统一报 modified:前端对两者的处理相同
|
||||
// (重载树)。真正需要区分时以库扫描结果为准。
|
||||
CHANGE_MODIFIED
|
||||
} else {
|
||||
if let Err(e) = index.remove_note(&rel) {
|
||||
crate::logger::log_warn("editor", &format!("移除索引 {rel} 失败: {e}"));
|
||||
}
|
||||
CHANGE_REMOVED
|
||||
};
|
||||
|
||||
// 事件一律发出,用 `from_app` 如实标注来源,由前端决定是否提示/重载。
|
||||
// 早期实现是「自己写的就静默不发」,一旦自我写入判定因时序漏过,前端就会把自家
|
||||
// 的保存当成外部修改而重载文档(光标弹回第一行)—— 判定留在前端更稳。
|
||||
let payload = NoteFileEvent {
|
||||
rel_path: rel,
|
||||
abs_path: files::display_path(path),
|
||||
kind: kind.to_string(),
|
||||
at: std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.map(|d| d.as_millis() as u64)
|
||||
.unwrap_or(0),
|
||||
from_app: self_write,
|
||||
};
|
||||
if let Err(e) = app.emit(events::EDITOR_FILE_CHANGED, payload) {
|
||||
crate::logger::log_warn("editor", &format!("发出文件变化事件失败: {e}"));
|
||||
}
|
||||
}
|
||||
|
||||
/// 授权 + 读取(供命令层调用,收敛「读文件必须先登记授权」这条规则)。
|
||||
pub fn read_and_authorize(path: &str, max_mb: u32) -> Result<files::FileDoc, String> {
|
||||
let doc = files::read_file(path, max_mb)?;
|
||||
files::authorize(Path::new(&doc.path));
|
||||
Ok(doc)
|
||||
}
|
||||
@@ -0,0 +1,365 @@
|
||||
//! 笔记库的文件系统层:路径安全解析、扫描、读写、增删改移。
|
||||
//!
|
||||
//! # 真相在文件,不在数据库
|
||||
//!
|
||||
//! 笔记就是库根下的 `.md` 文件树。本文件的每个函数都以「相对库根的路径」为
|
||||
//! 输入/输出,**所有路径都先过 [`safe_join`]**:拒绝绝对路径、盘符与 `..`,
|
||||
//! 保证任何操作都无法越出库根(前端传来的路径一律不可信)。
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::UNIX_EPOCH;
|
||||
|
||||
use super::types::{LibraryEntry, NoteDoc, EditorSettings};
|
||||
|
||||
/// 默认库根相对模块目录的名字:`{app_data_dir}/editor/library`
|
||||
pub const DEFAULT_LIBRARY_DIR: &str = "library";
|
||||
/// 附件(粘贴图片等)目录名,位于库根下
|
||||
pub const ASSETS_DIR: &str = "assets";
|
||||
/// 库内私有目录名(索引 + 同步基线),**永不参与同步 / 导出 / 快照**。
|
||||
pub const PRIVATE_DIR: &str = ".editor";
|
||||
/// v1「笔记模块」的私有目录名;首次打开时惰性迁移到 [`PRIVATE_DIR`]。
|
||||
const LEGACY_PRIVATE_DIR: &str = ".notes";
|
||||
/// 扫描深度上限(防御性:软链接成环时不会无限递归)。
|
||||
/// 对 `index.rs` 公开:两处扫描(侧栏树 / 索引)必须用同一个深度口径,
|
||||
/// 否则会出现「树里看不到、搜索却搜得到」这种自相矛盾的状态。
|
||||
pub const MAX_DEPTH: usize = 24;
|
||||
|
||||
/// 新建笔记的正文模板(front-matter + 一级标题)。
|
||||
fn note_template(title: &str) -> String {
|
||||
let now = chrono::Local::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true);
|
||||
format!(
|
||||
"---\ntitle: {title}\ncreated: {now}\nupdated: {now}\ntags: []\n---\n\n# {title}\n\n"
|
||||
)
|
||||
}
|
||||
|
||||
/// 默认库根路径(未配置自定义库根时使用)。
|
||||
pub fn default_library_root(module_dir: &Path) -> PathBuf {
|
||||
module_dir.join(DEFAULT_LIBRARY_DIR)
|
||||
}
|
||||
|
||||
/// 由设置解析出当前生效的库根。
|
||||
pub fn resolve_library_root(module_dir: &Path, settings: &EditorSettings) -> PathBuf {
|
||||
match &settings.library_root {
|
||||
Some(root) if !root.trim().is_empty() => PathBuf::from(root.trim()),
|
||||
_ => default_library_root(module_dir),
|
||||
}
|
||||
}
|
||||
|
||||
/// 惰性迁移旧私有目录 `.notes/` → `.editor/`(幂等)。
|
||||
///
|
||||
/// 索引可重建,但迁移能保住同步基线(`sync.json`),因此优先整目录重命名。
|
||||
/// 迁移后残留的旧索引文件(`notes.db*`)直接删除 —— 下次打开会按新库根重建。
|
||||
pub fn migrate_private_dir(root: &Path) {
|
||||
let old = root.join(LEGACY_PRIVATE_DIR);
|
||||
let new = root.join(PRIVATE_DIR);
|
||||
if !old.is_dir() || new.exists() {
|
||||
return;
|
||||
}
|
||||
match std::fs::rename(&old, &new) {
|
||||
Ok(()) => {
|
||||
for stale in ["notes.db", "notes.db-wal", "notes.db-shm"] {
|
||||
let _ = std::fs::remove_file(new.join(stale));
|
||||
}
|
||||
crate::logger::log_info(
|
||||
"editor",
|
||||
&format!("已迁移库内私有目录 {LEGACY_PRIVATE_DIR}/ → {PRIVATE_DIR}/"),
|
||||
);
|
||||
}
|
||||
Err(e) => crate::logger::log_warn(
|
||||
"editor",
|
||||
&format!("迁移库内私有目录失败(将按新目录重建): {e}"),
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
/// 确保库根与其 `assets/` 子目录存在(顺带惰性迁移旧私有目录)。
|
||||
pub fn ensure_library(root: &Path) -> Result<(), String> {
|
||||
migrate_private_dir(root);
|
||||
std::fs::create_dir_all(root).map_err(|e| format!("创建笔记库目录失败: {e}"))?;
|
||||
std::fs::create_dir_all(root.join(ASSETS_DIR))
|
||||
.map_err(|e| format!("创建附件目录失败: {e}"))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 把「相对库根的路径」解析为绝对路径,并拒绝任何逃逸。
|
||||
///
|
||||
/// 空串表示库根本身。统一接受 `/` 与 `\` 两种分隔符输入,输出用系统分隔符。
|
||||
pub fn safe_join(root: &Path, rel: &str) -> Result<PathBuf, String> {
|
||||
let normalized = rel.trim().replace('\\', "/");
|
||||
if normalized.starts_with('/') || normalized.contains(':') {
|
||||
return Err("仅支持库内相对路径".to_string());
|
||||
}
|
||||
let mut out = root.to_path_buf();
|
||||
for part in normalized.split('/') {
|
||||
if part.is_empty() || part == "." {
|
||||
continue;
|
||||
}
|
||||
if part == ".." {
|
||||
return Err("路径不能包含上级目录(..)".to_string());
|
||||
}
|
||||
out.push(part);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// 绝对路径 → 相对库根的路径(统一 `/` 分隔)。
|
||||
pub fn rel_string(root: &Path, path: &Path) -> String {
|
||||
path.strip_prefix(root)
|
||||
.map(|p| p.to_string_lossy().replace('\\', "/"))
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// 校验用户输入的条目名(新建/重命名)。
|
||||
///
|
||||
/// 拒绝路径分隔符、Windows 保留字符与控制字符 —— 名称只应是「一个名字」,
|
||||
/// 不含任何路径语义。
|
||||
pub fn validate_name(name: &str) -> Result<String, String> {
|
||||
let name = name.trim();
|
||||
if name.is_empty() {
|
||||
return Err("名称不能为空".to_string());
|
||||
}
|
||||
if name == "." || name == ".." {
|
||||
return Err("名称不合法".to_string());
|
||||
}
|
||||
if name.chars().count() > 120 {
|
||||
return Err("名称过长".to_string());
|
||||
}
|
||||
if name
|
||||
.chars()
|
||||
.any(|c| c.is_control() || matches!(c, '<' | '>' | ':' | '"' | '/' | '\\' | '|' | '?' | '*'))
|
||||
{
|
||||
return Err("名称不能包含 < > : \" / \\ | ? * 等字符".to_string());
|
||||
}
|
||||
Ok(name.to_string())
|
||||
}
|
||||
|
||||
fn is_note_file(name: &str) -> bool {
|
||||
name.to_ascii_lowercase().ends_with(".md")
|
||||
}
|
||||
|
||||
fn modified_ms(meta: &std::fs::Metadata) -> u64 {
|
||||
meta.modified()
|
||||
.ok()
|
||||
.and_then(|t| t.duration_since(UNIX_EPOCH).ok())
|
||||
.map(|d| d.as_millis() as u64)
|
||||
.unwrap_or(0)
|
||||
}
|
||||
|
||||
/// 扫描整个库,返回扁平条目列表(目录在前、各自按名称排序;前端自行组树)。
|
||||
pub fn scan(root: &Path) -> Result<Vec<LibraryEntry>, String> {
|
||||
let mut out = Vec::new();
|
||||
if !root.is_dir() {
|
||||
return Ok(out);
|
||||
}
|
||||
walk(root, root, &mut out, 0);
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn walk(root: &Path, dir: &Path, out: &mut Vec<LibraryEntry>, depth: usize) {
|
||||
if depth > MAX_DEPTH {
|
||||
return;
|
||||
}
|
||||
let read = match std::fs::read_dir(dir) {
|
||||
Ok(r) => r,
|
||||
Err(_) => return,
|
||||
};
|
||||
|
||||
let mut dirs: Vec<(String, PathBuf)> = Vec::new();
|
||||
let mut files: Vec<(String, PathBuf)> = Vec::new();
|
||||
for entry in read.flatten() {
|
||||
let name = entry.file_name().to_string_lossy().to_string();
|
||||
// 隐藏项(含 `.editor` 之类的私有目录)一律不进库树
|
||||
if name.starts_with('.') {
|
||||
continue;
|
||||
}
|
||||
let file_type = match entry.file_type() {
|
||||
Ok(t) => t,
|
||||
Err(_) => continue,
|
||||
};
|
||||
let path = entry.path();
|
||||
if file_type.is_dir() {
|
||||
// 根级 assets 是图片仓库,不作为笔记目录展示,避免噪声
|
||||
if depth == 0 && name == ASSETS_DIR {
|
||||
continue;
|
||||
}
|
||||
dirs.push((name, path));
|
||||
} else if file_type.is_file() && is_note_file(&name) {
|
||||
files.push((name, path));
|
||||
}
|
||||
}
|
||||
|
||||
dirs.sort_by(|a, b| a.0.cmp(&b.0));
|
||||
files.sort_by(|a, b| a.0.cmp(&b.0));
|
||||
|
||||
for (name, path) in dirs {
|
||||
let meta = std::fs::metadata(&path).ok();
|
||||
out.push(LibraryEntry {
|
||||
name,
|
||||
rel_path: rel_string(root, &path),
|
||||
parent_rel: rel_string(root, dir),
|
||||
is_dir: true,
|
||||
modified: meta.as_ref().map(modified_ms).unwrap_or(0),
|
||||
size: 0,
|
||||
});
|
||||
walk(root, &path, out, depth + 1);
|
||||
}
|
||||
for (name, path) in files {
|
||||
let meta = std::fs::metadata(&path).ok();
|
||||
out.push(LibraryEntry {
|
||||
name,
|
||||
rel_path: rel_string(root, &path),
|
||||
parent_rel: rel_string(root, dir),
|
||||
is_dir: false,
|
||||
modified: meta.as_ref().map(modified_ms).unwrap_or(0),
|
||||
size: meta.as_ref().map(|m| m.len()).unwrap_or(0),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// 统计库内 `.md` 文件数量。
|
||||
pub fn count_notes(entries: &[LibraryEntry]) -> u32 {
|
||||
entries.iter().filter(|e| !e.is_dir).count() as u32
|
||||
}
|
||||
|
||||
/// 构造一篇文档的返回结构。
|
||||
fn to_doc(root: &Path, path: &Path, content: String) -> NoteDoc {
|
||||
let modified = std::fs::metadata(path).map(|m| modified_ms(&m)).unwrap_or(0);
|
||||
NoteDoc {
|
||||
rel_path: rel_string(root, path),
|
||||
name: path
|
||||
.file_name()
|
||||
.map(|n| n.to_string_lossy().to_string())
|
||||
.unwrap_or_default(),
|
||||
content,
|
||||
modified,
|
||||
}
|
||||
}
|
||||
|
||||
/// 读取一篇笔记(相对库根路径)。非 UTF-8 字节按 lossy 处理,不报错。
|
||||
pub fn read_note(root: &Path, rel: &str) -> Result<NoteDoc, String> {
|
||||
let path = safe_join(root, rel)?;
|
||||
if !path.is_file() {
|
||||
return Err(format!("笔记不存在:{rel}"));
|
||||
}
|
||||
let bytes = std::fs::read(&path).map_err(|e| format!("读取笔记失败: {e}"))?;
|
||||
Ok(to_doc(root, &path, String::from_utf8_lossy(&bytes).into_owned()))
|
||||
}
|
||||
|
||||
/// 写入一篇笔记(已存在的文件才允许写;不自动创建目录,由 create_note 负责)。
|
||||
pub fn write_note(root: &Path, rel: &str, content: &str) -> Result<NoteDoc, String> {
|
||||
let path = safe_join(root, rel)?;
|
||||
if !path.is_file() {
|
||||
return Err(format!("笔记不存在:{rel}"));
|
||||
}
|
||||
std::fs::write(&path, content).map_err(|e| format!("保存笔记失败: {e}"))?;
|
||||
Ok(to_doc(root, &path, content.to_string()))
|
||||
}
|
||||
|
||||
/// 在指定目录下新建笔记:自动补 `.md`、重名自动加序号。
|
||||
///
|
||||
/// 用**内置**的 front-matter 模板(不读 `templates/`)。保留这个无模板参数的入口是
|
||||
/// 为了「模板目录被删/损坏时仍然能新建笔记」这条底线,单测也走它。
|
||||
pub fn create_note(root: &Path, dir_rel: &str, name: &str) -> Result<NoteDoc, String> {
|
||||
create_note_with_template(root, dir_rel, name, "")
|
||||
}
|
||||
|
||||
/// 在指定目录下新建笔记,正文由模板渲染(`template_id` 为空 = 用内置默认模板)。
|
||||
///
|
||||
/// 模板渲染失败(模板文件被删、权限不足)时回退到内置模板而不是报错:
|
||||
/// 「新建笔记」这个动作不该因为一个辅助文件的问题而不可用。
|
||||
pub fn create_note_with_template(
|
||||
root: &Path,
|
||||
dir_rel: &str,
|
||||
name: &str,
|
||||
template_id: &str,
|
||||
) -> Result<NoteDoc, String> {
|
||||
let dir = safe_join(root, dir_rel)?;
|
||||
std::fs::create_dir_all(&dir).map_err(|e| format!("创建目录失败: {e}"))?;
|
||||
|
||||
let mut file_name = validate_name(name)?;
|
||||
if !is_note_file(&file_name) {
|
||||
file_name.push_str(".md");
|
||||
}
|
||||
let title = file_name.trim_end_matches(".md").to_string();
|
||||
|
||||
// 重名自动加序号,避免「新建即报错」
|
||||
let mut candidate = file_name.clone();
|
||||
let mut index = 1;
|
||||
while dir.join(&candidate).exists() {
|
||||
candidate = format!("{title} {index}.md");
|
||||
index += 1;
|
||||
if index > 999 {
|
||||
return Err("同名文件过多,请换一个名称".to_string());
|
||||
}
|
||||
}
|
||||
|
||||
// 模板渲染:模板 ID 无效时 `render_for_new_note` 自己会回退到内置空白模板
|
||||
let content = if template_id.trim().is_empty() {
|
||||
note_template(&title)
|
||||
} else {
|
||||
super::templates::render_for_new_note(root, template_id, &title, dir_rel)
|
||||
};
|
||||
|
||||
let path = dir.join(&candidate);
|
||||
std::fs::write(&path, content).map_err(|e| format!("新建笔记失败: {e}"))?;
|
||||
read_note(root, &rel_string(root, &path))
|
||||
}
|
||||
|
||||
/// 在指定目录下新建文件夹。
|
||||
pub fn create_folder(root: &Path, dir_rel: &str, name: &str) -> Result<String, String> {
|
||||
let dir = safe_join(root, dir_rel)?;
|
||||
std::fs::create_dir_all(&dir).map_err(|e| format!("创建目录失败: {e}"))?;
|
||||
let folder_name = validate_name(name)?;
|
||||
let path = dir.join(&folder_name);
|
||||
if path.exists() {
|
||||
return Err(format!("「{folder_name}」已存在"));
|
||||
}
|
||||
std::fs::create_dir_all(&path).map_err(|e| format!("新建文件夹失败: {e}"))?;
|
||||
Ok(rel_string(root, &path))
|
||||
}
|
||||
|
||||
/// 重命名库内条目;返回新的相对路径。
|
||||
///
|
||||
/// 文件若未带扩展名,沿用原扩展名(避免 `a.md` 改成 `a` 变成无扩展名文件)。
|
||||
pub fn rename_entry(root: &Path, rel: &str, new_name: &str) -> Result<String, String> {
|
||||
let path = safe_join(root, rel)?;
|
||||
if !path.exists() {
|
||||
return Err("条目不存在".to_string());
|
||||
}
|
||||
let mut name = validate_name(new_name)?;
|
||||
if path.is_file() {
|
||||
let old_ext = path.extension().map(|e| e.to_string_lossy().to_string());
|
||||
if let Some(ext) = old_ext {
|
||||
if !name.to_ascii_lowercase().ends_with(&format!(".{}", ext.to_ascii_lowercase())) {
|
||||
name.push('.');
|
||||
name.push_str(&ext);
|
||||
}
|
||||
}
|
||||
}
|
||||
let parent = path
|
||||
.parent()
|
||||
.ok_or_else(|| "无法解析父目录".to_string())?;
|
||||
let target = parent.join(&name);
|
||||
if target.exists() {
|
||||
return Err(format!("「{name}」已存在"));
|
||||
}
|
||||
std::fs::rename(&path, &target).map_err(|e| format!("重命名失败: {e}"))?;
|
||||
Ok(rel_string(root, &target))
|
||||
}
|
||||
|
||||
/// 删除库内条目(目录递归删除)。
|
||||
pub fn delete_entry(root: &Path, rel: &str) -> Result<(), String> {
|
||||
if rel.trim().is_empty() {
|
||||
return Err("不能删除库根".to_string());
|
||||
}
|
||||
let path = safe_join(root, rel)?;
|
||||
if !path.exists() {
|
||||
return Err("条目不存在".to_string());
|
||||
}
|
||||
if path.is_dir() {
|
||||
std::fs::remove_dir_all(&path).map_err(|e| format!("删除目录失败: {e}"))?;
|
||||
} else {
|
||||
std::fs::remove_file(&path).map_err(|e| format!("删除文件失败: {e}"))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,199 @@
|
||||
//! 笔记 / 编辑器模块。
|
||||
//!
|
||||
//! 架构位置:
|
||||
//!
|
||||
//! ```text
|
||||
//! 主模块页(设置 / 库管理) 独立窗口(CM6 编辑器)
|
||||
//! ↓ Tauri IPC ↓
|
||||
//! commands.rs 命令层
|
||||
//! ↓
|
||||
//! EditorManager(本文件):设置读写 / 库根解析
|
||||
//! ↓
|
||||
//! library.rs 文件系统(路径安全 / 扫描 / 读写 / 增删改移)
|
||||
//! ```
|
||||
//!
|
||||
//! # 真相在文件
|
||||
//!
|
||||
//! 笔记 = 库根下的 `.md` 文件树。Rust 侧只做文件 IO 与设置持久化,
|
||||
//! **不引入私有格式**;SQLite 索引(`index.rs`)只是可重建的加速层。
|
||||
//!
|
||||
//! # 三个入口的职责边界
|
||||
//!
|
||||
//! ```text
|
||||
//! library.rs 库内笔记:相对路径 + 树 + front-matter(安全模型 = 根目录沙箱)
|
||||
//! files.rs 库外任意文件:绝对路径 + 编码/换行(安全模型 = 授权白名单)
|
||||
//! index_service.rs 索引与监听:独占 SQLite 连接的单线程 worker + notify
|
||||
//! ```
|
||||
//!
|
||||
//! 设置持久化:`{app_data_dir}/editor/settings.json`(范式同 ai / translate)。
|
||||
//! 默认库根:`{app_data_dir}/editor/library`;用户可在设置里改。
|
||||
|
||||
mod args;
|
||||
mod backup;
|
||||
mod commands;
|
||||
mod dirs;
|
||||
mod export;
|
||||
mod files;
|
||||
mod grep;
|
||||
mod import;
|
||||
mod index;
|
||||
mod index_service;
|
||||
mod library;
|
||||
mod shell_menu;
|
||||
mod templates;
|
||||
mod types;
|
||||
mod webdav;
|
||||
|
||||
pub use commands::{
|
||||
editor_add_template, editor_authorize_file, editor_backlinks, editor_backup_now,
|
||||
editor_create_folder, editor_create_note, editor_daily_note, editor_delete_entry,
|
||||
editor_export_note, editor_export_snapshot_local, editor_export_zip, editor_get_settings,
|
||||
editor_import, editor_index_stats, editor_library_info, editor_link_graph, editor_list_backups,
|
||||
editor_list_notes, editor_list_templates, editor_open_file, editor_read_asset, editor_read_note,
|
||||
editor_read_template, editor_rebuild_index, editor_redecode_file, editor_rename_entry,
|
||||
editor_restore_backup,
|
||||
editor_save_note, editor_save_settings, editor_scan_library, editor_scratch_dir, editor_search_notes,
|
||||
editor_set_library_root, editor_set_webdav_password, editor_sync_index, editor_sync_now,
|
||||
editor_tags, editor_take_pending_file, editor_test_webdav, editor_webdav_status,
|
||||
editor_write_asset, editor_write_file,
|
||||
};
|
||||
pub use args::{emit_open_target, open_target_from_args, remember_pending_target};
|
||||
pub use dirs::{
|
||||
editor_create_dir, editor_create_file, editor_delete_path, editor_move_path, editor_read_dir,
|
||||
editor_rename_path,
|
||||
};
|
||||
pub use grep::{editor_replace_in_path, editor_search_in_path};
|
||||
pub use shell_menu::{
|
||||
editor_context_menu_status, editor_register_context_menu, editor_unregister_context_menu,
|
||||
};
|
||||
use types::EditorSettings;
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Mutex;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
/// 设置内存缓存有效期(与 ai / translate / terminal 的 500ms 一致)。
|
||||
const SETTINGS_CACHE_TTL: Duration = Duration::from_millis(500);
|
||||
|
||||
struct SettingsCache {
|
||||
read_at: Instant,
|
||||
settings: EditorSettings,
|
||||
}
|
||||
|
||||
/// 笔记 / 编辑器模块管理器(Tauri State)。
|
||||
pub struct EditorManager {
|
||||
/// 模块自身目录:`{app_data_dir}/editor`
|
||||
module_dir: PathBuf,
|
||||
cache: Mutex<Option<SettingsCache>>,
|
||||
}
|
||||
|
||||
/// 一次性迁移 `{app_data_dir}/notes/` → `{app_data_dir}/editor/`(幂等)。
|
||||
///
|
||||
/// 仅当旧目录存在且新目录不存在时整目录重命名;两者都在则各自独立
|
||||
/// (说明已在用新目录,旧目录留着不动,避免误删用户数据)。
|
||||
fn migrate_legacy_module_dir(app_data_dir: &Path, module_dir: &Path) {
|
||||
let legacy = app_data_dir.join("notes");
|
||||
if legacy.is_dir() && !module_dir.exists() {
|
||||
match std::fs::rename(&legacy, module_dir) {
|
||||
Ok(()) => crate::logger::log_info("editor", "已迁移模块目录 notes/ → editor/"),
|
||||
Err(e) => crate::logger::log_warn("editor", &format!("迁移模块目录失败: {e}")),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl EditorManager {
|
||||
pub fn new(app_data_dir: PathBuf) -> Self {
|
||||
let module_dir = app_data_dir.join("editor");
|
||||
migrate_legacy_module_dir(&app_data_dir, &module_dir);
|
||||
let _ = std::fs::create_dir_all(&module_dir);
|
||||
Self {
|
||||
module_dir,
|
||||
cache: Mutex::new(None),
|
||||
}
|
||||
}
|
||||
|
||||
/// 模块自身目录(库根默认值基于它解析)。
|
||||
pub fn module_dir(&self) -> &Path {
|
||||
&self.module_dir
|
||||
}
|
||||
|
||||
/// 启动时按设置注册全局快捷键。
|
||||
///
|
||||
/// 失败只记日志:快捷键被别的应用占了不该阻断启动(与 translate / terminal 同一姿态)。
|
||||
/// 触发时**只发事件**,窗口与「新建哪一篇」由前端决定 —— Rust 侧不持有窗口 label
|
||||
/// 策略,也不该知道当前打开的库是哪一篇(那是前端 store 的事)。
|
||||
pub fn init_on_launch(&self, app: &tauri::AppHandle) {
|
||||
use tauri::Emitter;
|
||||
let settings = self.load_settings();
|
||||
|
||||
let new_note = settings.new_note_shortcut.clone();
|
||||
if let Err(e) = crate::shortcut::register_shortcut(app, "editor-new-note", &new_note, |app| {
|
||||
if let Err(e) = app.emit(crate::constants::events::EDITOR_NEW_NOTE, ()) {
|
||||
crate::logger::log_warn("editor", &format!("发出新建笔记事件失败: {e}"));
|
||||
}
|
||||
}) {
|
||||
crate::logger::log_warn("editor", &format!("注册「新建笔记」快捷键失败: {e}"));
|
||||
}
|
||||
|
||||
let open_editor = settings.open_editor_shortcut.clone();
|
||||
if let Err(e) =
|
||||
crate::shortcut::register_shortcut(app, "editor-open-editor", &open_editor, |app| {
|
||||
if let Err(e) = app.emit(crate::constants::events::EDITOR_OPEN_EDITOR, ()) {
|
||||
crate::logger::log_warn("editor", &format!("发出打开编辑器事件失败: {e}"));
|
||||
}
|
||||
})
|
||||
{
|
||||
crate::logger::log_warn("editor", &format!("注册「打开编辑器」快捷键失败: {e}"));
|
||||
}
|
||||
}
|
||||
|
||||
fn settings_path(&self) -> PathBuf {
|
||||
self.module_dir.join("settings.json")
|
||||
}
|
||||
|
||||
/// 读取设置(带短时缓存;文件缺失回退默认值;自愈结果落盘)。
|
||||
pub fn load_settings(&self) -> EditorSettings {
|
||||
if let Ok(cache) = self.cache.lock() {
|
||||
if let Some(entry) = cache.as_ref() {
|
||||
if entry.read_at.elapsed() < SETTINGS_CACHE_TTL {
|
||||
return entry.settings.clone();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut settings = std::fs::read_to_string(self.settings_path())
|
||||
.ok()
|
||||
.and_then(|s| serde_json::from_str::<EditorSettings>(&s).ok())
|
||||
.unwrap_or_default();
|
||||
let healed = settings.heal();
|
||||
// 刷新「最近记录」的存在性(只读,不触发落盘)
|
||||
settings.refresh_recent_exists();
|
||||
if let Ok(mut cache) = self.cache.lock() {
|
||||
*cache = Some(SettingsCache {
|
||||
read_at: Instant::now(),
|
||||
settings: settings.clone(),
|
||||
});
|
||||
}
|
||||
if healed {
|
||||
if let Err(e) = self.save_settings(&settings) {
|
||||
crate::logger::log_error("editor", &format!("设置自愈落盘失败: {e}"));
|
||||
}
|
||||
}
|
||||
settings
|
||||
}
|
||||
|
||||
/// 保存设置并刷新缓存。
|
||||
pub fn save_settings(&self, settings: &EditorSettings) -> Result<(), String> {
|
||||
let json = serde_json::to_string_pretty(settings)
|
||||
.map_err(|e| format!("序列化笔记设置失败: {e}"))?;
|
||||
std::fs::write(self.settings_path(), json)
|
||||
.map_err(|e| format!("写入笔记设置失败: {e}"))?;
|
||||
if let Ok(mut cache) = self.cache.lock() {
|
||||
*cache = Some(SettingsCache {
|
||||
read_at: Instant::now(),
|
||||
settings: settings.clone(),
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
//! Windows 资源管理器右键菜单(HKCU,**免管理员**)。
|
||||
//!
|
||||
//! # 为什么走用户级注册表
|
||||
//!
|
||||
//! 文件关联由安装器写 `HKLM`/`OpenWithProgids`;而「右键 → 用 Thing 编辑器打开」
|
||||
//! 只需 `HKCU\Software\Classes\{*,Directory,Directory\Background}\shell\ThingEditor`,
|
||||
//! 用户级即可生效、无需提权(范式同 `mihomo_manager/system_proxy.rs`)。
|
||||
//!
|
||||
//! # 为什么默认不自动注册
|
||||
//!
|
||||
//! 注册表项里写的是**绝对 exe 路径**:打包安装后指向安装目录(稳定),但
|
||||
//! `tauri dev` 下指向 `target\debug\thing.exe` —— 一旦清理 target 就成了死链。
|
||||
//! 因此注册/卸载都只在设置页按钮下发生,且注册前校验 exe 存在。
|
||||
//!
|
||||
//! # 三处菜单
|
||||
//!
|
||||
//! | 键 | 场景 | 参数 |
|
||||
//! |---|---|---|
|
||||
//! | `*` | 任意文件 | `%1` |
|
||||
//! | `Directory` | 文件夹 | `%1` |
|
||||
//! | `Directory\Background` | 目录背景空白处 | `%V`(当前目录) |
|
||||
|
||||
use serde::Serialize;
|
||||
use specta::Type;
|
||||
|
||||
/// 右键菜单键名与显示名。
|
||||
const MENU_KEY: &str = "ThingEditor";
|
||||
const MENU_LABEL: &str = "用 Thing 编辑器打开";
|
||||
|
||||
/// 右键菜单状态(回传设置页展示)。
|
||||
#[derive(Debug, Clone, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ContextMenuStatus {
|
||||
/// 是否已注册(以 `*` 键为准)
|
||||
pub registered: bool,
|
||||
/// 当前可执行文件绝对路径(注册表里写入的就是它)
|
||||
pub exe_path: String,
|
||||
/// 是否开发模式(exe 路径不稳定,UI 需给出提示)
|
||||
pub is_dev: bool,
|
||||
}
|
||||
|
||||
fn exe_path() -> String {
|
||||
std::env::current_exe()
|
||||
.map(|p| p.to_string_lossy().to_string())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// 读取当前状态。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_context_menu_status() -> ContextMenuStatus {
|
||||
ContextMenuStatus {
|
||||
registered: imp::registered(),
|
||||
exe_path: exe_path(),
|
||||
is_dev: cfg!(debug_assertions),
|
||||
}
|
||||
}
|
||||
|
||||
/// 注册右键菜单(写 HKCU)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_register_context_menu() -> Result<ContextMenuStatus, String> {
|
||||
imp::register()?;
|
||||
Ok(editor_context_menu_status())
|
||||
}
|
||||
|
||||
/// 卸载右键菜单(删 HKCU 对应项)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn editor_unregister_context_menu() -> Result<ContextMenuStatus, String> {
|
||||
imp::unregister()?;
|
||||
Ok(editor_context_menu_status())
|
||||
}
|
||||
|
||||
// ===== Windows 实现 =====
|
||||
|
||||
#[cfg(windows)]
|
||||
mod imp {
|
||||
use super::{exe_path, MENU_KEY, MENU_LABEL};
|
||||
use std::path::Path;
|
||||
|
||||
const ROOTS: [&str; 3] = ["*", "Directory", "Directory\\Background"];
|
||||
|
||||
fn key_path(root: &str) -> String {
|
||||
format!("Software\\Classes\\{root}\\shell\\{MENU_KEY}")
|
||||
}
|
||||
|
||||
pub fn registered() -> bool {
|
||||
use winreg::enums::HKEY_CURRENT_USER;
|
||||
use winreg::RegKey;
|
||||
RegKey::predef(HKEY_CURRENT_USER)
|
||||
.open_subkey(key_path("*"))
|
||||
.is_ok()
|
||||
}
|
||||
|
||||
pub fn register() -> Result<(), String> {
|
||||
use winreg::enums::HKEY_CURRENT_USER;
|
||||
use winreg::RegKey;
|
||||
|
||||
let exe = exe_path();
|
||||
if exe.is_empty() {
|
||||
return Err("无法确定可执行文件路径".to_string());
|
||||
}
|
||||
if !Path::new(&exe).is_file() {
|
||||
return Err(format!("可执行文件不存在:{exe}(开发模式下请先构建)"));
|
||||
}
|
||||
|
||||
let hkcu = RegKey::predef(HKEY_CURRENT_USER);
|
||||
for root in ROOTS {
|
||||
let path = key_path(root);
|
||||
let (key, _) = hkcu
|
||||
.create_subkey(&path)
|
||||
.map_err(|e| format!("写入注册表失败({root}): {e}"))?;
|
||||
key.set_value("", &MENU_LABEL)
|
||||
.map_err(|e| format!("写入菜单名称失败({root}): {e}"))?;
|
||||
key.set_value("Icon", &exe)
|
||||
.map_err(|e| format!("写入菜单图标失败({root}): {e}"))?;
|
||||
// Directory\Background 传入的是「当前目录」,用 %V;其余用 %1
|
||||
let arg = if root.ends_with("Background") { "%V" } else { "%1" };
|
||||
let (cmd_key, _) = hkcu
|
||||
.create_subkey(format!("{path}\\command"))
|
||||
.map_err(|e| format!("写入菜单命令失败({root}): {e}"))?;
|
||||
cmd_key
|
||||
.set_value("", &format!("\"{exe}\" \"{arg}\""))
|
||||
.map_err(|e| format!("写入菜单命令行失败({root}): {e}"))?;
|
||||
}
|
||||
crate::logger::log_info("editor", &format!("已注册右键菜单,指向 {exe}"));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn unregister() -> Result<(), String> {
|
||||
use winreg::enums::HKEY_CURRENT_USER;
|
||||
use winreg::RegKey;
|
||||
|
||||
let hkcu = RegKey::predef(HKEY_CURRENT_USER);
|
||||
for root in ROOTS {
|
||||
let path = key_path(root);
|
||||
match hkcu.delete_subkey_all(&path) {
|
||||
Ok(()) => {}
|
||||
// 本就不存在视为成功(幂等)
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
|
||||
Err(e) => return Err(format!("删除注册表项失败({root}): {e}")),
|
||||
}
|
||||
}
|
||||
crate::logger::log_info("editor", "已卸载右键菜单");
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
// ===== 非 Windows:明确告知不支持 =====
|
||||
|
||||
#[cfg(not(windows))]
|
||||
mod imp {
|
||||
pub fn registered() -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
pub fn register() -> Result<(), String> {
|
||||
Err("资源管理器右键菜单仅支持 Windows".to_string())
|
||||
}
|
||||
|
||||
pub fn unregister() -> Result<(), String> {
|
||||
Err("资源管理器右键菜单仅支持 Windows".to_string())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,304 @@
|
||||
//! 新建笔记的模板:内置默认模板 + 用户模板目录。
|
||||
//!
|
||||
//! # 模板为什么要落成 `.md` 文件
|
||||
//!
|
||||
//! 与「笔记的真相是文件」同一条原则:模板也是用户会想改的东西,做成 JSON 里的一段
|
||||
//! 字符串,用户既看不到也改不了。落成 `.md` 文件后,用任意编辑器改,改完立刻生效。
|
||||
//!
|
||||
//! # 两个来源
|
||||
//!
|
||||
//! - **内置**:编译进二进制(`include_str!`),保证全新机器上「新建笔记」永远有东西可用;
|
||||
//! - **用户**:`{库根}/templates/*.md`。库是可切换的,模板跟着库走 —— 一个技术笔记库
|
||||
//! 和一个日记库本来就该有不同的模板集。
|
||||
//!
|
||||
//! 同名时用户模板覆盖内置模板。内置模板不写进库根(否则用户第一次新建笔记就会
|
||||
//! 发现库里多出一堆他没建过的文件)。
|
||||
//!
|
||||
//! # 变量替换
|
||||
//!
|
||||
//! 只支持少量、无歧义的占位符(`{{date}}` / `{{time}}` / `{{title}}` / `{{datetime}}`)。
|
||||
//! **不做条件、循环、包含** —— 那是一条通往「半个模板引擎」的路,收益远小于维护成本。
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
|
||||
use super::library;
|
||||
|
||||
/// 一个模板。
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct NoteTemplate {
|
||||
/// 标识(内置用 `builtin:<文件名>`,用户模板用 `user:<文件名>`)
|
||||
pub id: String,
|
||||
/// 显示名(文件名去掉扩展名)
|
||||
pub name: String,
|
||||
/// 说明(内置模板手写;用户模板取正文首行非空文本)
|
||||
pub description: String,
|
||||
/// 是否为内置模板(前端据此提示「不可删除」)
|
||||
pub builtin: bool,
|
||||
/// 模板正文(含 front-matter)
|
||||
pub body: String,
|
||||
}
|
||||
|
||||
/// 内置模板(编译进二进制)。
|
||||
const BUILTIN: &[(&str, &str, &str)] = &[
|
||||
(
|
||||
"空白笔记",
|
||||
"只有 front-matter 与一级标题,适合随手记",
|
||||
"---\ntitle: {{title}}\ncreated: {{datetime}}\nupdated: {{datetime}}\ntags: []\n---\n\n# {{title}}\n\n",
|
||||
),
|
||||
(
|
||||
"会议纪要",
|
||||
"议题 / 结论 / 待办三段式",
|
||||
"---\ntitle: {{title}}\ncreated: {{datetime}}\nupdated: {{datetime}}\ntags: [会议]\n---\n\n# {{title}}\n\n- 时间:{{datetime}}\n- 参会:\n\n## 议题\n\n## 结论\n\n## 待办\n\n- [ ] \n",
|
||||
),
|
||||
(
|
||||
"日记",
|
||||
"按日期归档的日记骨架",
|
||||
"---\ntitle: {{title}}\ncreated: {{datetime}}\nupdated: {{datetime}}\ntags: [日记]\n---\n\n# {{date}}\n\n## 今天做了什么\n\n## 明天要做什么\n\n- [ ] \n",
|
||||
),
|
||||
(
|
||||
"读书笔记",
|
||||
"书籍信息 + 摘录 + 思考",
|
||||
"---\ntitle: {{title}}\ncreated: {{datetime}}\nupdated: {{datetime}}\ntags: [读书]\n---\n\n# {{title}}\n\n- 书名:\n- 作者:\n- 进度:\n\n## 摘录\n\n> \n\n## 我的思考\n\n",
|
||||
),
|
||||
];
|
||||
|
||||
/// 列出全部模板(用户模板优先,同名覆盖内置)。
|
||||
pub fn list(root: &Path) -> Vec<NoteTemplate> {
|
||||
let mut out: Vec<NoteTemplate> = Vec::new();
|
||||
|
||||
// 用户模板:`{库根}/templates/*.md`
|
||||
let dir = root.join("templates");
|
||||
if dir.is_dir() {
|
||||
let mut files: Vec<std::path::PathBuf> = std::fs::read_dir(&dir)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(Result::ok)
|
||||
.map(|entry| entry.path())
|
||||
.filter(|path| {
|
||||
path.is_file()
|
||||
&& path
|
||||
.extension()
|
||||
.map(|e| e.eq_ignore_ascii_case("md"))
|
||||
.unwrap_or(false)
|
||||
})
|
||||
.collect();
|
||||
files.sort();
|
||||
for path in files {
|
||||
let name = path
|
||||
.file_stem()
|
||||
.map(|s| s.to_string_lossy().to_string())
|
||||
.unwrap_or_default();
|
||||
if name.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let Ok(body) = std::fs::read_to_string(&path) else {
|
||||
continue;
|
||||
};
|
||||
out.push(NoteTemplate {
|
||||
id: format!("user:{name}"),
|
||||
description: first_meaningful_line(&body),
|
||||
name,
|
||||
builtin: false,
|
||||
body,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// 内置模板:跳过已被用户模板同名的
|
||||
for (name, description, body) in BUILTIN {
|
||||
if out.iter().any(|item| item.name == *name) {
|
||||
continue;
|
||||
}
|
||||
out.push(NoteTemplate {
|
||||
id: format!("builtin:{name}"),
|
||||
name: name.to_string(),
|
||||
description: description.to_string(),
|
||||
builtin: true,
|
||||
body: body.to_string(),
|
||||
});
|
||||
}
|
||||
|
||||
out
|
||||
}
|
||||
|
||||
/// 取模板 ID 对应的正文;找不到返回 `None`(调用方回退到默认模板)。
|
||||
pub fn body_of(root: &Path, id: &str) -> Option<String> {
|
||||
list(root).into_iter().find(|t| t.id == id).map(|t| t.body)
|
||||
}
|
||||
|
||||
/// 把模板正文渲染成一篇新笔记的内容。
|
||||
///
|
||||
/// `parent_dir` 是笔记所在的库内目录(用于 `{{date}}` 之类不受影响,但保留参数
|
||||
/// 以便将来加入「所在目录」变量)。
|
||||
pub fn render(body: &str, title: &str, _parent_dir: &str) -> String {
|
||||
let now = chrono::Local::now();
|
||||
body.replace("{{title}}", title)
|
||||
.replace("{{date}}", &now.format("%Y-%m-%d").to_string())
|
||||
.replace("{{time}}", &now.format("%H:%M").to_string())
|
||||
.replace("{{datetime}}", &now.to_rfc3339_opts(chrono::SecondsFormat::Secs, true))
|
||||
}
|
||||
|
||||
/// 日记的默认文件名(`2026-09-30`),供「今日日记」入口用。
|
||||
pub fn daily_note_name() -> String {
|
||||
chrono::Local::now().format("%Y-%m-%d").to_string()
|
||||
}
|
||||
|
||||
/// 默认模板的 ID(新建笔记时未选模板就用它)。
|
||||
pub fn default_template_id() -> String {
|
||||
"builtin:空白笔记".to_string()
|
||||
}
|
||||
|
||||
/// 正文里第一行有意义的文本(用户模板的说明用)。
|
||||
fn first_meaningful_line(body: &str) -> String {
|
||||
for line in body.lines() {
|
||||
let text = line.trim();
|
||||
if text.is_empty() || text == "---" || text.starts_with('#') || text.starts_with("title:") {
|
||||
continue;
|
||||
}
|
||||
return text.chars().take(40).collect();
|
||||
}
|
||||
String::new()
|
||||
}
|
||||
|
||||
/// 为「新建笔记」渲染正文:`template_id` 为空或找不到时用默认模板。
|
||||
pub fn render_for_new_note(root: &Path, template_id: &str, title: &str, dir_rel: &str) -> String {
|
||||
let id = if template_id.trim().is_empty() {
|
||||
default_template_id()
|
||||
} else {
|
||||
template_id.to_string()
|
||||
};
|
||||
match body_of(root, &id) {
|
||||
Some(body) => render(&body, title, dir_rel),
|
||||
None => {
|
||||
// 兜底:内置空白模板(即使模板目录被清空也能新建)
|
||||
let fallback = BUILTIN
|
||||
.first()
|
||||
.map(|(_, _, body)| *body)
|
||||
.unwrap_or("---\ntitle: {{title}}\n---\n\n# {{title}}\n\n");
|
||||
render(fallback, title, dir_rel)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 确保库里的 `templates/` 目录存在(用户想自定义模板时不用自己新建目录)。
|
||||
pub fn ensure_dir(root: &Path) -> Result<(), String> {
|
||||
std::fs::create_dir_all(root.join("templates")).map_err(|e| format!("创建模板目录失败: {e}"))
|
||||
}
|
||||
|
||||
/// 把内置模板写进库内 `templates/`(供「导出内置模板」按钮用;已存在的不覆盖)。
|
||||
pub fn export_builtin(root: &Path) -> Result<Vec<String>, String> {
|
||||
ensure_dir(root)?;
|
||||
let dir = root.join("templates");
|
||||
let mut written = Vec::new();
|
||||
for (name, _, body) in BUILTIN {
|
||||
let path = dir.join(format!("{name}.md"));
|
||||
if path.exists() {
|
||||
continue;
|
||||
}
|
||||
std::fs::write(&path, body).map_err(|e| format!("写入模板 {name} 失败: {e}"))?;
|
||||
written.push(name.to_string());
|
||||
}
|
||||
Ok(written)
|
||||
}
|
||||
|
||||
/// 模板文件在库内的相对路径(前端「编辑模板」用;内置模板返回 `None`)。
|
||||
pub fn relative_path(id: &str) -> Option<String> {
|
||||
id.strip_prefix("user:")
|
||||
.map(|name| format!("templates/{name}.md"))
|
||||
}
|
||||
|
||||
/// 校验模板名(新建模板时用)。
|
||||
pub fn validate_name(name: &str) -> Result<String, String> {
|
||||
library::validate_name(name)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn temp_root(tag: &str) -> std::path::PathBuf {
|
||||
let root =
|
||||
std::env::temp_dir().join(format!("thing-notes-tpl-{tag}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
std::fs::create_dir_all(&root).unwrap();
|
||||
root
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn builtin_templates_are_available_without_files() {
|
||||
let root = temp_root("builtin");
|
||||
let templates = list(&root);
|
||||
assert!(templates.len() >= 4, "{templates:?}");
|
||||
assert!(templates.iter().all(|t| t.builtin));
|
||||
assert!(templates.iter().any(|t| t.name == "日记"));
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn user_template_overrides_builtin_with_same_name() {
|
||||
let root = temp_root("override");
|
||||
ensure_dir(&root).unwrap();
|
||||
std::fs::write(root.join("templates/空白笔记.md"), "用户自己的模板 {{title}}").unwrap();
|
||||
let templates = list(&root);
|
||||
let blank = templates.iter().find(|t| t.name == "空白笔记").unwrap();
|
||||
assert!(!blank.builtin, "同名时用户模板应覆盖内置");
|
||||
assert!(blank.body.contains("用户自己的模板"));
|
||||
assert_eq!(
|
||||
templates.iter().filter(|t| t.name == "空白笔记").count(),
|
||||
1,
|
||||
"不该出现两份同名模板"
|
||||
);
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn render_substitutes_variables() {
|
||||
let out = render("---\ntitle: {{title}}\ncreated: {{datetime}}\n---\n\n# {{title}} {{date}}\n", "周会", "");
|
||||
assert!(out.contains("title: 周会"));
|
||||
assert!(out.contains("# 周会 "));
|
||||
assert!(!out.contains("{{"), "所有占位符都应被替换: {out}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn render_for_new_note_falls_back_to_blank() {
|
||||
let root = temp_root("fallback");
|
||||
let out = render_for_new_note(&root, "user:不存在", "标题", "");
|
||||
assert!(out.contains("标题"));
|
||||
assert!(!out.contains("{{"));
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn export_builtin_does_not_overwrite() {
|
||||
let root = temp_root("export");
|
||||
ensure_dir(&root).unwrap();
|
||||
std::fs::write(root.join("templates/日记.md"), "我的日记模板").unwrap();
|
||||
let written = export_builtin(&root).unwrap();
|
||||
assert!(!written.contains(&"日记".to_string()), "{written:?}");
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(root.join("templates/日记.md")).unwrap(),
|
||||
"我的日记模板"
|
||||
);
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn relative_path_only_for_user_templates() {
|
||||
assert_eq!(
|
||||
relative_path("user:会议纪要"),
|
||||
Some("templates/会议纪要.md".to_string())
|
||||
);
|
||||
assert_eq!(relative_path("builtin:日记"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn daily_note_name_is_date_shaped() {
|
||||
let name = daily_note_name();
|
||||
assert_eq!(name.len(), 10, "{name}");
|
||||
assert_eq!(name.matches('-').count(), 2);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,406 @@
|
||||
//! 笔记模块的数据模型。
|
||||
//!
|
||||
//! 持久化位置:`{app_data_dir}/editor/settings.json`(与 ai / translate / terminal 同一范式)。
|
||||
//! 容器级 `#[serde(default)]`:新增字段对旧配置文件向后兼容(缺字段取
|
||||
//! `Default::default()` 的对应值,而不是让整份设置反序列化失败)。
|
||||
//!
|
||||
//! 笔记正文**不在这里**:它以 `.md` 文件为准(见 `library.rs`),
|
||||
//! 本结构只保存「库根 + 编辑器偏好」这类模块级设置。
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
|
||||
/// 结构版本号。字段增减时递增,由 [`EditorSettings::heal`] 推进。
|
||||
pub const EDITOR_SETTINGS_VERSION: u32 = 4;
|
||||
|
||||
/// 最近文件 / 文件夹各自的保留上限(超出淘汰最旧)。
|
||||
pub const RECENT_LIMIT: usize = 20;
|
||||
|
||||
/// 同步方向。
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum SyncDirection {
|
||||
/// 双向同步(默认)
|
||||
Bidirectional,
|
||||
/// 只上传(本地覆盖远端)—— 等价于「推送到远端备份」
|
||||
Upload,
|
||||
/// 只下载(远端覆盖本地)—— 换机器恢复时用
|
||||
Download,
|
||||
}
|
||||
|
||||
impl Default for SyncDirection {
|
||||
fn default() -> Self {
|
||||
Self::Bidirectional
|
||||
}
|
||||
}
|
||||
|
||||
/// 两侧都改动时的冲突策略。
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum ConflictPolicy {
|
||||
/// 保留较新的(mtime 大的一方;无法判定时保守选本地)
|
||||
Newer,
|
||||
/// 本地覆盖远端
|
||||
LocalWins,
|
||||
/// 远端覆盖本地
|
||||
RemoteWins,
|
||||
/// 两侧都留(本地改名成 `*.sync-conflict-<时间>.md`,再把远端那份下载到原路径)
|
||||
KeepBoth,
|
||||
}
|
||||
|
||||
impl Default for ConflictPolicy {
|
||||
fn default() -> Self {
|
||||
// 默认「都留」:冲突时最保守的选择,绝不丢数据(规划 §7 R6)
|
||||
Self::KeepBoth
|
||||
}
|
||||
}
|
||||
|
||||
/// WebDAV 设置(密码**不在这里** —— 它进 keyring,见 `webdav/mod.rs`)。
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase", default)]
|
||||
pub struct WebdavSettings {
|
||||
/// 服务地址(`https://dav.jianguoyun.com/dav`)
|
||||
pub url: String,
|
||||
pub username: String,
|
||||
/// 远端根目录(相对 `url`;空串 = 直接用 `url` 指向的目录)
|
||||
pub remote_root: String,
|
||||
pub direction: SyncDirection,
|
||||
pub conflict: ConflictPolicy,
|
||||
/// 应用启动后自动同步一次
|
||||
pub auto_sync_on_launch: bool,
|
||||
/// 保留的 zip 快照份数(上传备份时轮转)
|
||||
pub backup_keep: u32,
|
||||
}
|
||||
|
||||
impl Default for WebdavSettings {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
url: String::new(),
|
||||
username: String::new(),
|
||||
remote_root: "thing-notes".to_string(),
|
||||
direction: SyncDirection::Bidirectional,
|
||||
conflict: ConflictPolicy::KeepBoth,
|
||||
auto_sync_on_launch: false,
|
||||
backup_keep: 7,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl WebdavSettings {
|
||||
/// 是否已经填了连接信息(决定设置页显示「未配置」还是「已配置」)。
|
||||
pub fn is_configured(&self) -> bool {
|
||||
!self.url.trim().is_empty() && !self.username.trim().is_empty()
|
||||
}
|
||||
|
||||
/// 填写是否足以发起请求。
|
||||
pub fn validate(&self) -> Result<(), String> {
|
||||
if self.url.trim().is_empty() {
|
||||
return Err("请先填写 WebDAV 地址".to_string());
|
||||
}
|
||||
if !self.url.starts_with("http://") && !self.url.starts_with("https://") {
|
||||
return Err("WebDAV 地址必须以 http:// 或 https:// 开头".to_string());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// 同步进度(事件 `editor-sync-progress` 的负载)。
|
||||
#[derive(Debug, Clone, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct SyncProgress {
|
||||
/// 已完成条数
|
||||
pub done: u32,
|
||||
/// 总条数
|
||||
pub total: u32,
|
||||
/// 当前处理的相对路径
|
||||
pub current: String,
|
||||
/// 动作类型(`upload` / `download` / …,见 `webdav::sync::SyncActionKind::as_str`)
|
||||
pub kind: String,
|
||||
/// 附加说明(如「正在打包快照」)
|
||||
pub message: String,
|
||||
}
|
||||
|
||||
/// 一份远端备份快照。
|
||||
#[derive(Debug, Clone, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct BackupSnapshot {
|
||||
/// 远端文件名(`thing-notes-20260930-1530.zip`)
|
||||
pub name: String,
|
||||
pub size: u64,
|
||||
pub modified: u64,
|
||||
}
|
||||
|
||||
/// 备份结果。
|
||||
#[derive(Debug, Clone, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct BackupReport {
|
||||
/// 上传的快照名
|
||||
pub name: String,
|
||||
/// 快照字节数
|
||||
pub bytes: u64,
|
||||
/// 打包的笔记数
|
||||
pub files: u32,
|
||||
/// 因超出保留份数而被删除的旧快照
|
||||
pub pruned: Vec<String>,
|
||||
}
|
||||
|
||||
/// 导入结果。
|
||||
#[derive(Debug, Clone, Default, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ImportReport {
|
||||
/// 导入的笔记数
|
||||
pub imported: u32,
|
||||
/// 因重名而被改名的数量
|
||||
pub renamed: u32,
|
||||
/// 跳过的非 Markdown 文件数
|
||||
pub skipped: u32,
|
||||
/// 失败明细(最多若干条)
|
||||
pub failures: Vec<String>,
|
||||
}
|
||||
|
||||
/// 最近打开的一个文件 / 文件夹。
|
||||
///
|
||||
/// `exists` 在每次读取设置时刷新(不依赖前端探测),供 UI 灰显失效项。
|
||||
/// 与笔记库**解耦**:库可以换 / 删,历史不该跟着丢(规划 §3.5)。
|
||||
#[derive(Debug, Clone, Default, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase", default)]
|
||||
pub struct RecentEntry {
|
||||
/// 绝对路径(文件或文件夹)
|
||||
pub path: String,
|
||||
/// 显示名(文件名 / 文件夹名)
|
||||
pub name: String,
|
||||
/// 最近打开时间(Unix 毫秒)
|
||||
pub opened_at: u64,
|
||||
/// 该路径当前是否仍存在(读取设置时刷新)
|
||||
pub exists: bool,
|
||||
}
|
||||
|
||||
/// 笔记 / 编辑器设置根结构。
|
||||
///
|
||||
/// 字段取值必须与前端 `src/modules/notes/editor/themes.ts` 的 key 保持一致,
|
||||
/// 否则用户选了主题却回落默认(静默失效,终端模块踩过这个坑)。
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase", default)]
|
||||
pub struct EditorSettings {
|
||||
/// 结构版本号
|
||||
pub version: u32,
|
||||
/// 自定义库根(`None` = 用默认 `{app_data_dir}/editor/library`)
|
||||
pub library_root: Option<String>,
|
||||
/// 编辑器配色方案 key(`"system"` / `"vscode-dark"` / `"vscode-light"` / …)
|
||||
pub editor_theme: String,
|
||||
/// 编辑器配色是否跟随应用深浅(`editor_theme` 仅作取色基准)
|
||||
pub follow_app_theme: bool,
|
||||
/// 编辑器字体族(空串 = 用内置等宽字体栈)
|
||||
pub font_family: String,
|
||||
/// 字号(px)
|
||||
pub font_size: u32,
|
||||
/// 行高倍数
|
||||
pub line_height: f64,
|
||||
/// 是否启用字体连字(ligatures)
|
||||
pub ligatures: bool,
|
||||
/// Tab 宽度(空格数)
|
||||
pub tab_size: u32,
|
||||
/// 是否启用「所见即所得」Live Preview(关闭则纯 Markdown 源码 + 高亮)
|
||||
pub live_preview: bool,
|
||||
/// 自动保存防抖(毫秒;0 = 关闭自动保存,仅手动 Ctrl+S)
|
||||
pub autosave_ms: u32,
|
||||
/// 默认视图:"wysiwyg" | "source"
|
||||
pub default_view: String,
|
||||
/// 是否显示行号
|
||||
pub show_line_numbers: bool,
|
||||
/// 是否显示大纲侧栏(P1)
|
||||
pub show_outline: bool,
|
||||
/// 是否启用代码自动补全 / 括号闭合(P1;大文件会强制关闭)
|
||||
pub autocomplete: bool,
|
||||
/// 单文件大小上限(MB)。超过则编辑器降级为「纯高亮 + 行号」,
|
||||
/// 关闭 Live Preview / 折叠 / 补全等重扩展(见 §7 R2)。
|
||||
pub max_file_size_mb: u32,
|
||||
/// 是否识别 `[[wikilink]]`(P1,仅影响高亮与后续反链)
|
||||
pub wikilink: bool,
|
||||
/// 多窗口是否复用同一文档的窗口(P1;关闭则每次新建窗口)
|
||||
pub reuse_window: bool,
|
||||
/// WebDAV 备份 / 同步设置(P2)
|
||||
pub webdav: WebdavSettings,
|
||||
/// 新建笔记时是否弹出模板选择(P2)
|
||||
pub show_template_picker: bool,
|
||||
/// 导出 HTML 时是否内联代码高亮样式(P2;关闭则用打印友好的纯黑白)
|
||||
pub export_highlight: bool,
|
||||
/// 全局快捷键:新建笔记(空串 = 不注册)。
|
||||
///
|
||||
/// 走 `shortcut.rs` 的原子注册 + 冲突检测(与终端 / 翻译同一套),
|
||||
/// 触发时只发 `editor-new-note` 事件,窗口由前端创建 —— Rust 侧不持窗口 label 策略。
|
||||
pub new_note_shortcut: String,
|
||||
/// 全局快捷键:打开编辑器窗口(空串 = 不注册)
|
||||
pub open_editor_shortcut: String,
|
||||
/// 最近打开的文件(与笔记库解耦;上限 [`RECENT_LIMIT`])
|
||||
pub recent_files: Vec<RecentEntry>,
|
||||
/// 最近打开的文件夹(与笔记库解耦;上限 [`RECENT_LIMIT`])
|
||||
pub recent_folders: Vec<RecentEntry>,
|
||||
}
|
||||
|
||||
impl Default for EditorSettings {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
version: EDITOR_SETTINGS_VERSION,
|
||||
library_root: None,
|
||||
editor_theme: "system".to_string(),
|
||||
follow_app_theme: true,
|
||||
font_family: String::new(),
|
||||
font_size: 14,
|
||||
line_height: 1.7,
|
||||
ligatures: false,
|
||||
tab_size: 2,
|
||||
live_preview: true,
|
||||
// 自动保存默认关闭:800ms 一保存会让「保存按钮 / 标签 * 号 / 侧栏」跟着
|
||||
// 闪烁,干扰正常编辑。需要的人可在设置里显式开启(见 heal 的 v4 迁移)。
|
||||
autosave_ms: 0,
|
||||
default_view: "wysiwyg".to_string(),
|
||||
show_line_numbers: true,
|
||||
show_outline: true,
|
||||
autocomplete: true,
|
||||
max_file_size_mb: 5,
|
||||
wikilink: true,
|
||||
reuse_window: true,
|
||||
webdav: WebdavSettings::default(),
|
||||
show_template_picker: true,
|
||||
export_highlight: true,
|
||||
new_note_shortcut: String::new(),
|
||||
open_editor_shortcut: "Alt+E".to_string(),
|
||||
recent_files: Vec::new(),
|
||||
recent_folders: Vec::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl EditorSettings {
|
||||
/// 自愈:把越界/非法取值夹回合法区间,推进版本号。
|
||||
/// 返回是否发生了变更(由调用方决定是否落盘)。
|
||||
pub fn heal(&mut self) -> bool {
|
||||
let mut changed = false;
|
||||
|
||||
let clamp_u32 = |value: &mut u32, min: u32, max: u32, changed: &mut bool| {
|
||||
let next = (*value).clamp(min, max);
|
||||
if next != *value {
|
||||
*value = next;
|
||||
*changed = true;
|
||||
}
|
||||
};
|
||||
clamp_u32(&mut self.font_size, 10, 32, &mut changed);
|
||||
clamp_u32(&mut self.tab_size, 1, 8, &mut changed);
|
||||
clamp_u32(&mut self.autosave_ms, 0, 10_000, &mut changed);
|
||||
// 上限 100MB:再大就不该用编辑器打开(也不该走 IPC 把全文搬进 WebView)
|
||||
clamp_u32(&mut self.max_file_size_mb, 1, 100, &mut changed);
|
||||
// 快照保留份数:至少 1 份(0 份等于「备份完就删」,显然是误配)
|
||||
clamp_u32(&mut self.webdav.backup_keep, 1, 100, &mut changed);
|
||||
|
||||
if !(1.0..=3.0).contains(&self.line_height) {
|
||||
self.line_height = 1.7;
|
||||
changed = true;
|
||||
}
|
||||
|
||||
if self.editor_theme.trim().is_empty() {
|
||||
self.editor_theme = "system".to_string();
|
||||
changed = true;
|
||||
}
|
||||
|
||||
if self.default_view != "wysiwyg" && self.default_view != "source" {
|
||||
self.default_view = "wysiwyg".to_string();
|
||||
changed = true;
|
||||
}
|
||||
|
||||
if let Some(root) = &self.library_root {
|
||||
if root.trim().is_empty() {
|
||||
self.library_root = None;
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
|
||||
// v3:引入「打开编辑器」默认快捷键 Alt+E(用户已显式设过则不覆盖)
|
||||
if self.version < 3 && self.open_editor_shortcut.trim().is_empty() {
|
||||
self.open_editor_shortcut = "Alt+E".to_string();
|
||||
changed = true;
|
||||
}
|
||||
|
||||
// v4:自动保存默认从 800ms 改为关闭 —— 仍是 800 说明用户从未改过这个值
|
||||
//(旧默认),此时关闭它;用户显式设过的其他值一律保留。
|
||||
if self.version < 4 && self.autosave_ms == 800 {
|
||||
self.autosave_ms = 0;
|
||||
changed = true;
|
||||
}
|
||||
|
||||
if self.version < EDITOR_SETTINGS_VERSION {
|
||||
self.version = EDITOR_SETTINGS_VERSION;
|
||||
changed = true;
|
||||
}
|
||||
|
||||
// 最近记录上限:超出淘汰最旧(列表约定为新在前)
|
||||
if self.recent_files.len() > RECENT_LIMIT {
|
||||
self.recent_files.truncate(RECENT_LIMIT);
|
||||
changed = true;
|
||||
}
|
||||
if self.recent_folders.len() > RECENT_LIMIT {
|
||||
self.recent_folders.truncate(RECENT_LIMIT);
|
||||
changed = true;
|
||||
}
|
||||
|
||||
changed
|
||||
}
|
||||
|
||||
/// 刷新最近记录的「是否存在」标记(读取设置时调用,供 UI 灰显失效项)。
|
||||
pub fn refresh_recent_exists(&mut self) {
|
||||
for entry in self
|
||||
.recent_files
|
||||
.iter_mut()
|
||||
.chain(self.recent_folders.iter_mut())
|
||||
{
|
||||
entry.exists = !entry.path.trim().is_empty() && std::path::Path::new(&entry.path).exists();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 库内一个条目(文件或目录)的扁平描述。
|
||||
///
|
||||
/// **刻意用扁平列表而不是树**:递归类型在 specta 的 `Type` 派生下容易生成
|
||||
/// 无穷展开的 TS 类型;扁平结构由前端组装成树,更稳也更简单。
|
||||
#[derive(Debug, Clone, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct LibraryEntry {
|
||||
/// 显示名(不含目录前缀)
|
||||
pub name: String,
|
||||
/// 相对库根的路径,统一用 `/` 分隔(如 `2026/09/meeting.md`)
|
||||
pub rel_path: String,
|
||||
/// 父目录的相对路径(库根为 `""`)
|
||||
pub parent_rel: String,
|
||||
/// 是否目录
|
||||
pub is_dir: bool,
|
||||
/// 最后修改时间(Unix 毫秒)
|
||||
pub modified: u64,
|
||||
/// 文件字节数(目录为 0)
|
||||
pub size: u64,
|
||||
}
|
||||
|
||||
/// 库状态概览(主模块页横幅与设置页用)。
|
||||
#[derive(Debug, Clone, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct LibraryInfo {
|
||||
/// 当前生效的库根绝对路径
|
||||
pub root: String,
|
||||
/// 是否为用户自定义库根(false = 默认 `{app_data_dir}/editor/library`)
|
||||
pub is_custom: bool,
|
||||
/// `.md` 笔记数量(不含目录)
|
||||
pub note_count: u32,
|
||||
}
|
||||
|
||||
/// 单篇笔记的读取/写入结果。
|
||||
#[derive(Debug, Clone, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct NoteDoc {
|
||||
/// 相对库根的路径(`/` 分隔)
|
||||
pub rel_path: String,
|
||||
/// 显示名(含扩展名)
|
||||
pub name: String,
|
||||
/// 完整文件内容(含 front-matter)
|
||||
pub content: String,
|
||||
/// 最后修改时间(Unix 毫秒)
|
||||
pub modified: u64,
|
||||
}
|
||||
@@ -0,0 +1,797 @@
|
||||
//! WebDAV 客户端:`PROPFIND` / `MKCOL` / `GET` / `PUT` / `DELETE` / `MOVE`。
|
||||
//!
|
||||
//! # 定位:备份 / 同步目标,不是工作区
|
||||
//!
|
||||
//! 这条边界是产品级的(规划 §3.6 已确认):笔记的真相永远在本地文件系统,
|
||||
//! WebDAV 只接收「本地 → 远端」的推送与「远端 → 本地」的拉取,**不做远端直连读写**
|
||||
//! (不把远端当工作目录)。这样即使远端服务商限流、掉线、或者把文件改坏,本地
|
||||
//! 那份始终是完整可用的。
|
||||
//!
|
||||
//! # XML 解析为什么用 quick-xml
|
||||
//!
|
||||
//! `PROPFIND` 的响应是 `<D:multistatus>` 里套一堆 `<D:response>`,命名空间前缀
|
||||
//! 由服务端随意指定(`D:` / `d:` / `lp1:` / 甚至没有前缀)。因此**不能按前缀匹配**,
|
||||
//! 只能按 local name 匹配。这里用 quick-xml 的事件流手写一小段状态机:遇到
|
||||
//! `response` 开始收集,遇到 `href` / `getlastmodified` / `getcontentlength` /
|
||||
//! `resourcetype` 各自记录,`response` 结束时产出一条 [`RemoteEntry`]。
|
||||
//! 手写而不是上 `serde` 反序列化,是因为各家 NAS(群晖、威联通、Alist)的字段
|
||||
//! 集合与顺序都不一致,宽容的事件流比严格的结构体映射稳。
|
||||
//!
|
||||
//! # 请求节流与退避
|
||||
//!
|
||||
//! 坚果云一类服务对请求频率有硬限制(超限直接 503)。这里的策略是:
|
||||
//! `REQ_INTERVAL_MS` 之内的**连续请求之间强制 sleep**,并且对 429/503 做指数退避
|
||||
//! 重试。同步一个几百篇的库会发几百个请求,不节流几乎必然被限流。
|
||||
|
||||
use std::io::Read;
|
||||
use std::sync::Mutex;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use base64::Engine as _;
|
||||
use quick_xml::events::Event;
|
||||
use quick_xml::Reader;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
|
||||
/// 连续请求之间的最小间隔(坚果云等服务的限流底线)。
|
||||
const REQ_INTERVAL_MS: u64 = 60;
|
||||
|
||||
/// 单次请求超时(连接 15s / 整体 180s)。
|
||||
///
|
||||
/// 整体超时给得比一般的 HTTP 调用长:`PROPFIND` 一个几千文件的目录、
|
||||
/// 或者上传一个几十 MB 的 zip 备份都可能耗时,短超时会表现为「同步随机失败」。
|
||||
const TIMEOUT: Duration = Duration::from_secs(180);
|
||||
const CONNECT_TIMEOUT: Duration = Duration::from_secs(15);
|
||||
|
||||
/// 退避重试:遇到 429/503 时的等待序列(毫秒)。
|
||||
const BACKOFF_MS: [u64; 4] = [500, 1500, 4000, 9000];
|
||||
|
||||
/// 远端一个文件/目录的条目。
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct RemoteEntry {
|
||||
/// 相对远端根的路径(统一 `/` 分隔,无前导斜杠)
|
||||
pub rel_path: String,
|
||||
/// 是否目录
|
||||
pub is_dir: bool,
|
||||
/// 字节数(目录为 0)
|
||||
pub size: u64,
|
||||
/// 最后修改时间(Unix 毫秒;服务端未提供时为 0)
|
||||
pub modified: u64,
|
||||
}
|
||||
|
||||
/// 连接与认证配置(密码从 keyring 单独取,不进这里)。
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct WebdavConfig {
|
||||
/// 服务地址(如 `https://dav.jianguoyun.com/dav`)
|
||||
pub url: String,
|
||||
pub username: String,
|
||||
pub password: String,
|
||||
/// 远端根目录(相对 `url`,空串 = 直接用 `url` 指向的目录)
|
||||
pub remote_root: String,
|
||||
}
|
||||
|
||||
impl WebdavConfig {
|
||||
/// 是否具备发起请求的最小条件。
|
||||
pub fn validate(&self) -> Result<(), String> {
|
||||
if self.url.trim().is_empty() {
|
||||
return Err("请先填写 WebDAV 地址".to_string());
|
||||
}
|
||||
if !self.url.starts_with("http://") && !self.url.starts_with("https://") {
|
||||
return Err("WebDAV 地址必须以 http:// 或 https:// 开头".to_string());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 拼接「远端根 + 相对路径」为完整 URL 路径(已做百分号编码)。
|
||||
fn url_for(&self, rel: &str) -> String {
|
||||
let base = self.url.trim_end_matches('/');
|
||||
let root = self.remote_root.trim().trim_matches('/');
|
||||
let mut parts: Vec<String> = Vec::new();
|
||||
if !root.is_empty() {
|
||||
for segment in root.split('/') {
|
||||
if !segment.is_empty() {
|
||||
parts.push(encode_segment(segment));
|
||||
}
|
||||
}
|
||||
}
|
||||
for segment in rel.replace('\\', "/").split('/') {
|
||||
if !segment.is_empty() {
|
||||
parts.push(encode_segment(segment));
|
||||
}
|
||||
}
|
||||
if parts.is_empty() {
|
||||
// 指向目录时必须带尾斜杠:部分服务端(IIS、nginx 的 dav 模块)在缺尾斜杠时
|
||||
// 会回 301,而 `PROPFIND` 遇到 301 有些实现不会自动跟(跟了也可能丢 Depth 头)
|
||||
format!("{base}/")
|
||||
} else {
|
||||
format!("{base}/{}", parts.join("/"))
|
||||
}
|
||||
}
|
||||
|
||||
/// 父目录的相对路径(用于 `MKCOL` 逐级创建)。
|
||||
fn parent_of(rel: &str) -> String {
|
||||
match rel.rfind('/') {
|
||||
Some(index) => rel[..index].to_string(),
|
||||
None => String::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 把一个路径段做百分号编码(只放过 unreserved 字符)。
|
||||
///
|
||||
/// 手写而不用 `urlencoding`:本文件已经为 `quick-xml` 加了一个依赖,
|
||||
/// 再为「编码一个路径段」加第二个不划算;规则本身只有十几行。
|
||||
fn encode_segment(segment: &str) -> String {
|
||||
let mut out = String::with_capacity(segment.len());
|
||||
for byte in segment.as_bytes() {
|
||||
match byte {
|
||||
b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
|
||||
out.push(*byte as char)
|
||||
}
|
||||
other => out.push_str(&format!("%{other:02X}")),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// 百分号解码(服务端回传的 `href` 是编码过的)。
|
||||
fn decode_segment(segment: &str) -> String {
|
||||
let bytes = segment.as_bytes();
|
||||
let mut out: Vec<u8> = Vec::with_capacity(bytes.len());
|
||||
let mut index = 0;
|
||||
while index < bytes.len() {
|
||||
if bytes[index] == b'%' && index + 2 < bytes.len() {
|
||||
let hex = std::str::from_utf8(&bytes[index + 1..index + 3]).unwrap_or("");
|
||||
if let Ok(value) = u8::from_str_radix(hex, 16) {
|
||||
out.push(value);
|
||||
index += 3;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
out.push(bytes[index]);
|
||||
index += 1;
|
||||
}
|
||||
String::from_utf8_lossy(&out).into_owned()
|
||||
}
|
||||
|
||||
/// WebDAV 客户端(`blocking` 是刻意的:见 `lib.rs` 的依赖注释)。
|
||||
pub struct WebdavClient {
|
||||
http: reqwest::blocking::Client,
|
||||
config: WebdavConfig,
|
||||
/// 上次请求时间(节流用)
|
||||
last_request: Mutex<Option<Instant>>,
|
||||
}
|
||||
|
||||
impl WebdavClient {
|
||||
pub fn new(config: WebdavConfig) -> Result<Self, String> {
|
||||
config.validate()?;
|
||||
let http = reqwest::blocking::Client::builder()
|
||||
.timeout(TIMEOUT)
|
||||
.connect_timeout(CONNECT_TIMEOUT)
|
||||
// 跟随重定向:不少服务端在「目录缺尾斜杠」时回 301
|
||||
.redirect(reqwest::redirect::Policy::limited(5))
|
||||
.user_agent("Thing-Notes/1.0")
|
||||
.build()
|
||||
.map_err(|e| format!("创建 HTTP 客户端失败: {e}"))?;
|
||||
Ok(Self {
|
||||
http,
|
||||
config,
|
||||
last_request: Mutex::new(None),
|
||||
})
|
||||
}
|
||||
|
||||
/// 节流:保证两次请求之间至少间隔 [`REQ_INTERVAL_MS`]。
|
||||
fn throttle(&self) { let mut slot = match self.last_request.lock() {
|
||||
Ok(slot) => slot,
|
||||
Err(poisoned) => poisoned.into_inner(),
|
||||
};
|
||||
if let Some(previous) = *slot {
|
||||
let elapsed = previous.elapsed();
|
||||
let min = Duration::from_millis(REQ_INTERVAL_MS);
|
||||
if elapsed < min {
|
||||
std::thread::sleep(min - elapsed);
|
||||
}
|
||||
}
|
||||
*slot = Some(Instant::now());
|
||||
}
|
||||
|
||||
/// 目录型 URL(`remote_root` 与每一层子目录都用它)。
|
||||
///
|
||||
/// `WebdavConfig::url_for("")` 只有在 `remote_root` 为空时才带尾斜杠;
|
||||
/// `remote_root` 非空时拼出来的是纯路径(如 `.../thing%20notes`),
|
||||
/// 而**目录请求必须带尾斜杠**(见 `url_for` 的注释)。
|
||||
fn dir_url(&self, rel: &str) -> String {
|
||||
let url = self.config.url_for(rel);
|
||||
if url.ends_with('/') {
|
||||
url
|
||||
} else {
|
||||
format!("{url}/")
|
||||
}
|
||||
}
|
||||
|
||||
/// 带 Basic 认证与节流的请求构造。
|
||||
fn request(&self, method: reqwest::Method, url: &str) -> reqwest::blocking::RequestBuilder {
|
||||
self.throttle();
|
||||
let mut builder = self.http.request(method, url);
|
||||
if !self.config.username.is_empty() || !self.config.password.is_empty() {
|
||||
let token = base64::engine::general_purpose::STANDARD
|
||||
.encode(format!("{}:{}", self.config.username, self.config.password));
|
||||
builder = builder.header("Authorization", format!("Basic {token}"));
|
||||
}
|
||||
builder
|
||||
}
|
||||
|
||||
/// 发请求并做退避重试(对 429/503 与网络错误重试)。
|
||||
fn send(
|
||||
&self,
|
||||
method: reqwest::Method,
|
||||
url: &str,
|
||||
body: Option<Vec<u8>>,
|
||||
content_type: Option<&str>,
|
||||
headers: &[(&str, &str)],
|
||||
) -> Result<reqwest::blocking::Response, String> {
|
||||
let mut attempt = 0usize;
|
||||
loop {
|
||||
let mut builder = self.request(method.clone(), url);
|
||||
for (name, value) in headers {
|
||||
builder = builder.header(*name, *value);
|
||||
}
|
||||
if let Some(content_type) = content_type {
|
||||
builder = builder.header("Content-Type", content_type);
|
||||
}
|
||||
if let Some(body) = &body {
|
||||
builder = builder.body(body.clone());
|
||||
}
|
||||
|
||||
let result = builder.send();
|
||||
match result {
|
||||
Ok(response) => {
|
||||
let status = response.status().as_u16();
|
||||
// 429(限流)与 503(服务不可用)是可重试的;其余 4xx 是请求本身的问题
|
||||
if (status == 429 || status == 503) && attempt < BACKOFF_MS.len() {
|
||||
let wait = BACKOFF_MS[attempt];
|
||||
crate::logger::log_warn(
|
||||
"editor",
|
||||
&format!("WebDAV 返回 {status},{wait}ms 后重试(第 {} 次)", attempt + 1),
|
||||
);
|
||||
std::thread::sleep(Duration::from_millis(wait));
|
||||
attempt += 1;
|
||||
continue;
|
||||
}
|
||||
return Ok(response);
|
||||
}
|
||||
Err(e) => {
|
||||
if attempt < BACKOFF_MS.len() {
|
||||
let wait = BACKOFF_MS[attempt];
|
||||
crate::logger::log_warn(
|
||||
"editor",
|
||||
&format!("WebDAV 请求失败({e}),{wait}ms 后重试"),
|
||||
);
|
||||
std::thread::sleep(Duration::from_millis(wait));
|
||||
attempt += 1;
|
||||
continue;
|
||||
}
|
||||
return Err(format!("WebDAV 请求失败: {e}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 把响应状态翻译成「人能看懂的错误」。
|
||||
fn ensure_success(response: &reqwest::blocking::Response, what: &str) -> Result<(), String> {
|
||||
let status = response.status();
|
||||
if status.is_success() {
|
||||
return Ok(());
|
||||
}
|
||||
let code = status.as_u16();
|
||||
let hint = match code {
|
||||
401 => "(用户名或密码/应用密码不正确)",
|
||||
403 => "(账号无此目录权限)",
|
||||
404 => "(路径不存在)",
|
||||
405 => "(服务端不允许该操作,可能不是标准 WebDAV)",
|
||||
409 => "(父目录不存在)",
|
||||
507 => "(远端空间不足)",
|
||||
_ => "",
|
||||
};
|
||||
Err(format!("{what}失败:HTTP {code}{hint}"))
|
||||
}
|
||||
|
||||
/// 探测远端根目录是否存在(返回条目列表;不存在返回 `None`)。
|
||||
pub fn list(&self, rel: &str) -> Result<Option<Vec<RemoteEntry>>, String> {
|
||||
let url = self.dir_url(rel);
|
||||
let body = br#"<?xml version="1.0" encoding="utf-8"?>
|
||||
<D:propfind xmlns:D="DAV:"><D:prop>
|
||||
<D:resourcetype/><D:getcontentlength/><D:getlastmodified/>
|
||||
</D:prop></D:propfind>"#
|
||||
.to_vec();
|
||||
|
||||
let response = self.send(
|
||||
reqwest::Method::from_bytes(b"PROPFIND").unwrap_or(reqwest::Method::GET),
|
||||
&url,
|
||||
Some(body),
|
||||
Some("application/xml; charset=utf-8"),
|
||||
&[("Depth", "1")],
|
||||
)?;
|
||||
|
||||
if response.status().as_u16() == 404 {
|
||||
return Ok(None);
|
||||
}
|
||||
Self::ensure_success(&response, "列目录")?;
|
||||
|
||||
let text = response
|
||||
.text()
|
||||
.map_err(|e| format!("读取 PROPFIND 响应失败: {e}"))?;
|
||||
let entries = parse_multistatus(&text, &self.config.url, &self.config.remote_root, rel)?;
|
||||
Ok(Some(entries))
|
||||
}
|
||||
|
||||
/// 确认远端根可用(不存在则创建)。
|
||||
///
|
||||
/// 自检的意义在于:把「地址写错 / 密码错 / 目录不存在」这三类问题在用户点下
|
||||
/// 「立即同步」**之前**就暴露出来,而不是让同步跑到一半报错。
|
||||
pub fn ensure_root(&self) -> Result<Vec<String>, String> {
|
||||
self.config.validate()?;
|
||||
let mut created: Vec<String> = Vec::new();
|
||||
|
||||
// 逐级创建 remote_root(服务端不会自动补父目录)
|
||||
let root = self.config.remote_root.trim().trim_matches('/').to_string();
|
||||
if !root.is_empty() {
|
||||
for next in Self::segments(&root) {
|
||||
let url = self.dir_url(&next);
|
||||
let response = self.send(
|
||||
reqwest::Method::from_bytes(b"MKCOL").unwrap_or(reqwest::Method::POST),
|
||||
&url,
|
||||
None,
|
||||
None,
|
||||
&[],
|
||||
)?;
|
||||
let code = response.status().as_u16();
|
||||
// 201 = 建成;405 = 已存在(各家服务端口径不一,两者都算成功)
|
||||
if code == 201 {
|
||||
created.push(next);
|
||||
} else if code != 405 {
|
||||
Self::ensure_success(&response, &format!("创建远端目录 {next}"))?;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 最后列一次,确认真的可读
|
||||
match self.list("")? {
|
||||
Some(_) => Ok(created),
|
||||
None => Err("远端根目录不存在且无法创建".to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
/// 递归列出远端某目录下的全部文件(跳过 [`should_skip`] 命中的路径)。
|
||||
pub fn list_recursive(&self) -> Result<Vec<RemoteEntry>, String> {
|
||||
let mut out: Vec<RemoteEntry> = Vec::new();
|
||||
let mut queue: Vec<String> = vec![String::new()];
|
||||
// 深度上限:远端目录结构异常(成环的软链)时不至于无限翻页
|
||||
let mut depth = 0usize;
|
||||
|
||||
while let Some(dir) = queue.pop() {
|
||||
depth += 1;
|
||||
if depth > 4096 {
|
||||
crate::logger::log_warn("editor", "远端目录过多,提前结束遍历");
|
||||
break;
|
||||
}
|
||||
let Some(entries) = self.list(&dir)? else {
|
||||
continue;
|
||||
};
|
||||
for entry in entries {
|
||||
if entry.rel_path.is_empty() || entry.rel_path == dir {
|
||||
continue;
|
||||
}
|
||||
if should_skip(&entry.rel_path) {
|
||||
continue;
|
||||
}
|
||||
if entry.is_dir {
|
||||
queue.push(entry.rel_path.clone());
|
||||
} else {
|
||||
out.push(entry);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// 创建目录(含父级)。
|
||||
pub fn mkdir_all(&self, rel: &str) -> Result<(), String> {
|
||||
for next in Self::segments(rel) {
|
||||
let url = self.dir_url(&next);
|
||||
let response = self.send(
|
||||
reqwest::Method::from_bytes(b"MKCOL").unwrap_or(reqwest::Method::POST),
|
||||
&url,
|
||||
None,
|
||||
None,
|
||||
&[],
|
||||
)?;
|
||||
let code = response.status().as_u16();
|
||||
if code != 201 && code != 405 {
|
||||
Self::ensure_success(&response, &format!("创建远端目录 {next}"))?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 把 `a/b/c` 展开成 `["a", "a/b", "a/b/c"]`(逐级创建用)。
|
||||
fn segments(rel: &str) -> Vec<String> {
|
||||
let mut out: Vec<String> = Vec::new();
|
||||
let mut prefix = String::new();
|
||||
for segment in rel.trim_matches('/').split('/') {
|
||||
if segment.is_empty() {
|
||||
continue;
|
||||
}
|
||||
prefix = if prefix.is_empty() {
|
||||
segment.to_string()
|
||||
} else {
|
||||
format!("{prefix}/{segment}")
|
||||
};
|
||||
out.push(prefix.clone());
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// 读取远端文件内容。
|
||||
pub fn get(&self, rel: &str) -> Result<Vec<u8>, String> {
|
||||
let url = self.config.url_for(rel);
|
||||
let response = self.send(reqwest::Method::GET, &url, None, None, &[])?;
|
||||
Self::ensure_success(&response, &format!("下载 {rel}"))?;
|
||||
let mut out = Vec::new();
|
||||
response
|
||||
.take(512 * 1024 * 1024)
|
||||
.read_to_end(&mut out)
|
||||
.map_err(|e| format!("读取下载内容失败: {e}"))?;
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// 上传文件内容(必要时先建父目录)。
|
||||
pub fn put(&self, rel: &str, bytes: Vec<u8>) -> Result<(), String> {
|
||||
let parent = WebdavConfig::parent_of(rel);
|
||||
if !parent.is_empty() {
|
||||
self.mkdir_all(&parent)?;
|
||||
}
|
||||
let url = self.config.url_for(rel);
|
||||
let response = self.send(
|
||||
reqwest::Method::PUT,
|
||||
&url,
|
||||
Some(bytes),
|
||||
Some("application/octet-stream"),
|
||||
&[],
|
||||
)?;
|
||||
Self::ensure_success(&response, &format!("上传 {rel}"))
|
||||
}
|
||||
|
||||
/// 删除文件(404 视为成功 —— 目标已经不存在,结果一致)。
|
||||
pub fn delete(&self, rel: &str) -> Result<(), String> {
|
||||
let url = self.config.url_for(rel);
|
||||
let response = self.send(reqwest::Method::DELETE, &url, None, None, &[])?;
|
||||
if response.status().as_u16() == 404 {
|
||||
return Ok(());
|
||||
}
|
||||
Self::ensure_success(&response, &format!("删除远端 {rel}"))
|
||||
}
|
||||
|
||||
/// 移动 / 重命名(`MOVE`,覆盖写)。
|
||||
pub fn move_to(&self, from: &str, to: &str) -> Result<(), String> {
|
||||
let url = self.config.url_for(from);
|
||||
let parent = WebdavConfig::parent_of(to);
|
||||
if !parent.is_empty() {
|
||||
self.mkdir_all(&parent)?;
|
||||
}
|
||||
let destination = self.config.url_for(to);
|
||||
let response = self.send(
|
||||
reqwest::Method::from_bytes(b"MOVE").unwrap_or(reqwest::Method::POST),
|
||||
&url,
|
||||
None,
|
||||
None,
|
||||
&[("Destination", destination.as_str()), ("Overwrite", "T")],
|
||||
)?;
|
||||
Self::ensure_success(&response, &format!("移动 {from} → {to}"))
|
||||
}
|
||||
}
|
||||
|
||||
/// 解析 `multistatus` 响应。
|
||||
///
|
||||
/// 按 **local name** 匹配(忽略命名空间前缀),并把 `href` 归一化成「相对远端根的
|
||||
/// 路径」。`base_url` 与 `remote_root` 用于剥掉服务端回传的完整 URL 前缀。
|
||||
fn parse_multistatus(
|
||||
xml: &str,
|
||||
base_url: &str,
|
||||
remote_root: &str,
|
||||
listing_dir: &str,
|
||||
) -> Result<Vec<RemoteEntry>, String> {
|
||||
let mut reader = Reader::from_str(xml);
|
||||
reader.config_mut().trim_text(true);
|
||||
|
||||
let mut entries: Vec<RemoteEntry> = Vec::new();
|
||||
let mut in_response = false;
|
||||
let mut current_href = String::new();
|
||||
let mut current_is_dir = false;
|
||||
let mut current_size = 0u64;
|
||||
let mut current_modified = 0u64;
|
||||
// 当前正在读的字段(`href` 可能在 propstat 里出现多次,只取第一个)
|
||||
let mut field = String::new();
|
||||
|
||||
loop {
|
||||
match reader.read_event() {
|
||||
Ok(Event::Start(element)) => {
|
||||
let name = element.name();
|
||||
let local = local_name(name.as_ref());
|
||||
match local.as_str() {
|
||||
"response" => {
|
||||
in_response = true;
|
||||
current_href.clear();
|
||||
current_is_dir = false;
|
||||
current_size = 0;
|
||||
current_modified = 0;
|
||||
}
|
||||
"href" | "getcontentlength" | "getlastmodified" | "collection" => {
|
||||
field = local;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Ok(Event::Empty(element)) => {
|
||||
// `<D:collection/>` 是「这是目录」的标志
|
||||
let name = element.name();
|
||||
if local_name(name.as_ref()) == "collection" {
|
||||
current_is_dir = true;
|
||||
}
|
||||
}
|
||||
Ok(Event::Text(text)) => {
|
||||
// quick-xml 0.42 的 `BytesText` 直接 `Deref<Target = str>`(Reader 是
|
||||
// `from_str` 建的,输入本身就是 UTF-8,不需要再 decode/unescape)。
|
||||
// 这里拷成 owned String 是因为 `field` 的匹配在借用结束之后才用。
|
||||
let value: String = text.as_ref().to_string();
|
||||
match field.as_str() {
|
||||
"href" if current_href.is_empty() => current_href = value,
|
||||
"getcontentlength" => current_size = value.trim().parse().unwrap_or(0),
|
||||
"getlastmodified" => current_modified = parse_http_date(&value).unwrap_or(0),
|
||||
"collection" => current_is_dir = true,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Ok(Event::End(element)) => {
|
||||
let name = element.name();
|
||||
let local = local_name(name.as_ref());
|
||||
if local == "response" && in_response {
|
||||
in_response = false;
|
||||
let rel = normalize_href(¤t_href, base_url, remote_root, listing_dir);
|
||||
if let Some(rel) = rel {
|
||||
entries.push(RemoteEntry {
|
||||
rel_path: rel,
|
||||
is_dir: current_is_dir,
|
||||
size: if current_is_dir { 0 } else { current_size },
|
||||
modified: current_modified,
|
||||
});
|
||||
}
|
||||
}
|
||||
field.clear();
|
||||
}
|
||||
Ok(Event::Eof) => break,
|
||||
Err(e) => return Err(format!("解析 WebDAV 响应失败: {e}")),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(entries)
|
||||
}
|
||||
|
||||
/// 取 XML 元素的 local name(去掉 `D:` / `lp1:` 之类前缀)。
|
||||
///
|
||||
/// quick-xml 0.42 的 `QName::as_ref()` 返回 `&str`(更早的版本是 `&[u8]`)——
|
||||
/// 这也是本文件里唯一需要跟着版本走的细节。
|
||||
fn local_name(raw: &str) -> String {
|
||||
match raw.rsplit(':').next() {
|
||||
Some(name) => name.to_ascii_lowercase(),
|
||||
None => raw.to_ascii_lowercase(),
|
||||
}
|
||||
}
|
||||
|
||||
/// 把服务端回传的 `href` 归一化成相对远端根的路径。
|
||||
///
|
||||
/// 服务端的三种形态都要吃下:
|
||||
/// 1. 完整 URL(`https://host/dav/root/a.md`)—— 剥掉 `base_url` 与 `remote_root`;
|
||||
/// 2. 绝对路径(`/dav/root/a.md`)—— 同上;
|
||||
/// 3. 相对路径(`a.md`)—— 拼到当前列出的目录之后再归一化。
|
||||
fn normalize_href(
|
||||
href: &str,
|
||||
base_url: &str,
|
||||
remote_root: &str,
|
||||
listing_dir: &str,
|
||||
) -> Option<String> {
|
||||
if href.trim().is_empty() {
|
||||
return None;
|
||||
}
|
||||
// 去掉协议与主机
|
||||
let path = if let Some(rest) = href.split("://").nth(1) {
|
||||
match rest.find('/') {
|
||||
Some(index) => &rest[index..],
|
||||
None => "/",
|
||||
}
|
||||
} else {
|
||||
href
|
||||
};
|
||||
let decoded = decode_segment(path);
|
||||
let trimmed_base = base_url.trim_end_matches('/');
|
||||
// 剥掉 base 的路径部分(如 `/dav`)
|
||||
let base_path = if let Some(rest) = trimmed_base.split("://").nth(1) {
|
||||
match rest.find('/') {
|
||||
Some(index) => &rest[index..],
|
||||
None => "",
|
||||
}
|
||||
} else {
|
||||
""
|
||||
};
|
||||
let mut rel = decoded.as_str();
|
||||
if !base_path.is_empty() {
|
||||
if let Some(rest) = rel.strip_prefix(base_path) {
|
||||
rel = rest;
|
||||
}
|
||||
}
|
||||
let root = remote_root.trim().trim_matches('/');
|
||||
if !root.is_empty() {
|
||||
let with_slash = format!("/{root}");
|
||||
if let Some(rest) = rel.strip_prefix(with_slash.as_str()) {
|
||||
rel = rest;
|
||||
} else if let Some(rest) = rel.strip_prefix(root) {
|
||||
rel = rest;
|
||||
}
|
||||
}
|
||||
let clean = rel.trim_matches('/').to_string();
|
||||
if clean.is_empty() {
|
||||
return None;
|
||||
}
|
||||
// 相对 href:拼到 listing_dir 后面
|
||||
let full = if !path.starts_with('/') && !listing_dir.trim().is_empty() {
|
||||
format!("{}/{}", listing_dir.trim_matches('/'), clean)
|
||||
} else {
|
||||
clean
|
||||
};
|
||||
Some(full)
|
||||
}
|
||||
|
||||
/// 解析 HTTP 日期(RFC 1123,如 `Wed, 21 Oct 2015 07:28:00 GMT`)为 Unix 毫秒。
|
||||
///
|
||||
/// 用 `chrono::DateTime::parse_from_rfc2822`:RFC 2822 与 RFC 1123 的日期部分兼容,
|
||||
/// 而 chrono 正好提供这个解析器(不引入第二个时间库)。
|
||||
fn parse_http_date(value: &str) -> Option<u64> {
|
||||
let parsed = chrono::DateTime::parse_from_rfc2822(value.trim()).ok()?;
|
||||
Some(parsed.timestamp_millis().max(0) as u64)
|
||||
}
|
||||
|
||||
/// 该远端路径是否应当排除在同步之外。
|
||||
///
|
||||
/// `.editor/` 是本模块的私有目录(索引 + 同步状态),**必须排除**:把索引同步到
|
||||
/// 远端毫无意义,且它随每次搜索变化,会让每一次同步都变成全量传输。
|
||||
pub fn should_skip(rel: &str) -> bool {
|
||||
let normalized = rel.replace('\\', "/");
|
||||
normalized.split('/').any(|part| {
|
||||
part.starts_with('.') || part.eq_ignore_ascii_case("node_modules")
|
||||
})
|
||||
}
|
||||
|
||||
// ===== 测试 =====
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn url_join_and_encoding() {
|
||||
let config = WebdavConfig {
|
||||
url: "https://dav.example.com/dav/".to_string(),
|
||||
remote_root: "thing notes".to_string(),
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(
|
||||
config.url_for("a/b.md"),
|
||||
"https://dav.example.com/dav/thing%20notes/a/b.md"
|
||||
);
|
||||
// 文件路径不带尾斜杠
|
||||
assert_eq!(
|
||||
config.url_for("a.md"),
|
||||
"https://dav.example.com/dav/thing%20notes/a.md"
|
||||
);
|
||||
// 目录请求必须带尾斜杠(否则部分服务端 301,PROPFIND 会丢 Depth 头)
|
||||
let client = WebdavClient::new(config).unwrap();
|
||||
assert_eq!(
|
||||
client.dir_url(""),
|
||||
"https://dav.example.com/dav/thing%20notes/"
|
||||
);
|
||||
assert_eq!(
|
||||
client.dir_url("sub"),
|
||||
"https://dav.example.com/dav/thing%20notes/sub/"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validate_rejects_bad_url() {
|
||||
let mut config = WebdavConfig::default();
|
||||
assert!(config.validate().is_err());
|
||||
config.url = "dav.example.com".to_string();
|
||||
assert!(config.validate().is_err());
|
||||
config.url = "https://dav.example.com".to_string();
|
||||
assert!(config.validate().is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn multistatus_parsing_tolerates_namespace_prefixes() {
|
||||
// 三家服务的常见形态:D: / d: / lp1: / 无前缀
|
||||
let xml = r#"<?xml version="1.0"?>
|
||||
<D:multistatus xmlns:D="DAV:">
|
||||
<D:response>
|
||||
<D:href>/dav/root/</D:href>
|
||||
<D:propstat><D:prop><D:resourcetype><D:collection/></D:resourcetype></D:prop></D:propstat>
|
||||
</D:response>
|
||||
<d:response xmlns:d="DAV:">
|
||||
<d:href>https://host/dav/root/notes/meeting.md</d:href>
|
||||
<d:propstat><d:prop>
|
||||
<d:resourcetype/>
|
||||
<d:getcontentlength>1234</d:getcontentlength>
|
||||
<d:getlastmodified>Wed, 21 Oct 2015 07:28:00 GMT</d:getlastmodified>
|
||||
</d:prop></d:propstat>
|
||||
</d:response>
|
||||
<response>
|
||||
<href>/dav/root/notes/%E4%B8%AD%E6%96%87.md</href>
|
||||
<propstat><prop><resourcetype/></prop></propstat>
|
||||
</response>
|
||||
</D:multistatus>"#;
|
||||
|
||||
let entries = parse_multistatus(xml, "https://host/dav", "root", "").unwrap();
|
||||
// 根目录自身被剥成空路径 → 不产出条目
|
||||
assert_eq!(entries.len(), 2, "{entries:?}");
|
||||
|
||||
let meeting = entries
|
||||
.iter()
|
||||
.find(|e| e.rel_path == "notes/meeting.md")
|
||||
.expect("应解析出 notes/meeting.md");
|
||||
assert!(!meeting.is_dir);
|
||||
assert_eq!(meeting.size, 1234);
|
||||
assert!(meeting.modified > 0, "应解析出 RFC1123 日期");
|
||||
|
||||
let chinese = entries
|
||||
.iter()
|
||||
.find(|e| e.rel_path == "notes/中文.md")
|
||||
.expect("百分号编码的 href 应被解码");
|
||||
assert!(!chinese.is_dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn collection_is_detected_as_directory() {
|
||||
let xml = r#"<multistatus xmlns="DAV:"><response>
|
||||
<href>/dav/root/sub</href>
|
||||
<propstat><prop><resourcetype><collection/></resourcetype></prop></propstat>
|
||||
</response></multistatus>"#;
|
||||
let entries = parse_multistatus(xml, "https://host/dav", "root", "").unwrap();
|
||||
assert_eq!(entries.len(), 1);
|
||||
assert!(entries[0].is_dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn skip_rules_exclude_private_dir() {
|
||||
assert!(should_skip(".editor/editor.db"));
|
||||
assert!(should_skip("a/.hidden/b.md"));
|
||||
assert!(should_skip("node_modules/x.md"));
|
||||
assert!(!should_skip("notes/a.md"));
|
||||
assert!(!should_skip("a/b/c.md"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn percent_encoding_roundtrip() {
|
||||
let encoded = encode_segment("中文 名字.md");
|
||||
assert_eq!(decode_segment(&encoded), "中文 名字.md");
|
||||
// 特殊字符(`?` / `#` / `/`)必须编码,否则会被服务端当查询串或路径分隔
|
||||
assert!(!encode_segment("a?b#c/d").contains('?'));
|
||||
assert!(!encode_segment("a?b#c/d").contains('#'));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn http_date_parsing() {
|
||||
let ms = parse_http_date("Wed, 21 Oct 2015 07:28:00 GMT").unwrap();
|
||||
assert_eq!(ms, 1_445_412_480_000);
|
||||
assert!(parse_http_date("不是日期").is_none());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
//! WebDAV 子模块:客户端与会话层。
|
||||
//!
|
||||
//! ```text
|
||||
//! client.rs ── 协议层:PROPFIND / MKCOL / GET / PUT / DELETE / MOVE(quick-xml 解析)
|
||||
//! mod.rs ── 会话层:读设置 → 取 keyring 密码 → 建客户端(供命令层一步调用)
|
||||
//! sync.rs ── 引擎层:清单比对 / 冲突策略 / 执行与基线维护
|
||||
//! ```
|
||||
//!
|
||||
//! 备份(zip 快照)在 `super::backup`:它只用 `PUT`,与同步是两条独立的路径
|
||||
//! (规划 §3.6 的取舍:对「只是要个备份」的用户,快照比双向同步可靠得多)。
|
||||
|
||||
pub mod client;
|
||||
pub mod sync;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
|
||||
use crate::editor::types::WebdavSettings;
|
||||
use client::WebdavClient;
|
||||
|
||||
/// keyring 里的服务名(与 `secrets.rs` 的约定一致,服务名固定 `"Thing"`)。
|
||||
pub const KEYRING_PASSWORD: &str = "editor.webdav.password";
|
||||
|
||||
/// 连接自检结果(设置页展示)。
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct WebdavTestResult {
|
||||
/// 是否连通
|
||||
pub ok: bool,
|
||||
/// 远端根目录中已有的条目数(自检时顺带列出)
|
||||
pub entries: u32,
|
||||
/// 本次自检自动创建的目录
|
||||
pub created: Vec<String>,
|
||||
/// 人话结论(失败时是原因)
|
||||
pub message: String,
|
||||
}
|
||||
|
||||
/// 由设置构造客户端(密码从 keyring 取,**不落盘**)。
|
||||
///
|
||||
/// 密码走系统凭据管理器而不是 `settings.json`:设置文件是明文 JSON,用户可能把库
|
||||
/// 连同设置一起放到同步目录里(那就等于把密码公开了)。keyring 的键是
|
||||
/// [`KEYRING_PASSWORD`],服务名沿用项目统一的 `"Thing"`。
|
||||
pub fn client_from(settings: &WebdavSettings) -> Result<WebdavClient, String> {
|
||||
settings.validate()?;
|
||||
let password = crate::secrets::secret_read(KEYRING_PASSWORD)
|
||||
.ok()
|
||||
.flatten()
|
||||
.unwrap_or_default();
|
||||
WebdavClient::new(client::WebdavConfig {
|
||||
url: settings.url.trim().to_string(),
|
||||
username: settings.username.trim().to_string(),
|
||||
password,
|
||||
remote_root: settings.remote_root.trim().to_string(),
|
||||
})
|
||||
}
|
||||
|
||||
/// 连接自检:验证地址/凭据,并按需逐级创建远端根目录。
|
||||
pub fn test_connection(settings: &WebdavSettings) -> Result<WebdavTestResult, String> {
|
||||
let client = client_from(settings)?;
|
||||
let created = client.ensure_root()?;
|
||||
let entries = client.list_recursive()?.len() as u32;
|
||||
Ok(WebdavTestResult {
|
||||
ok: true,
|
||||
entries,
|
||||
created,
|
||||
message: format!("连接正常,远端已有 {entries} 个文件"),
|
||||
})
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
Reference in new issue
Block a user